source stringlengths 3 92 | c stringlengths 26 2.25M |
|---|---|
GB_unaryop__ainv_uint64_uint64.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__ainv_uint64_uint64
// op(A') function: GB_tran__ainv_uint64_uint64
// C type: uint64_t
// A type: uint64_t
// cast: uint64_t cij = (uint64_t) aij
// unaryop: cij = -aij
#define GB_ATYPE \
uint64_t
#define GB_CTYPE \
uint64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = -x ;
// casting
#define GB_CASTING(z, x) \
uint64_t z = (uint64_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_AINV || GxB_NO_UINT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__ainv_uint64_uint64
(
uint64_t *restrict Cx,
const uint64_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__ainv_uint64_uint64
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t **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
|
bin_class_metric.h | /**
* Copyright (c) 2015 by Contributors
*/
#ifndef DIFACTO_LOSS_BIN_CLASS_METRIC_H_
#define DIFACTO_LOSS_BIN_CLASS_METRIC_H_
#include <algorithm>
#include <vector>
#include "difacto/base.h"
#include "dmlc/logging.h"
#include "dmlc/omp.h"
#include "difacto/sarray.h"
namespace difacto {
/**
* \brief binary classificatoin metrics
* all metrics are not divided by num_examples
*/
class BinClassMetric {
public:
/**
* \brief constructor
*
* @param label label vector
* @param predict predict vector
* @param n length
* @param nthreads num threads
*/
BinClassMetric(const dmlc::real_t* const label,
const real_t* const predict,
size_t n, int nthreads = DEFAULT_NTHREADS)
: label_(label), predict_(predict), size_(n), nt_(nthreads) { }
~BinClassMetric() { }
real_t AUC() {
size_t n = size_;
struct Entry { dmlc::real_t label; real_t predict; };
std::vector<Entry> buff(n);
for (size_t i = 0; i < n; ++i) {
buff[i].label = label_[i];
buff[i].predict = predict_[i];
}
std::sort(buff.data(), buff.data()+n, [](const Entry& a, const Entry&b) {
return a.predict < b.predict; });
real_t area = 0, cum_tp = 0;
for (size_t i = 0; i < n; ++i) {
if (buff[i].label > 0) {
cum_tp += 1;
} else {
area += cum_tp;
}
}
if (cum_tp == 0 || cum_tp == n) return 1;
area /= cum_tp * (n - cum_tp);
return (area < 0.5 ? 1 - area : area) * n;
}
real_t Accuracy(real_t threshold) {
real_t correct = 0;
size_t n = size_;
#pragma omp parallel for reduction(+:correct) num_threads(nt_)
for (size_t i = 0; i < n; ++i) {
if ((label_[i] > 0 && predict_[i] > threshold) ||
(label_[i] <= 0 && predict_[i] <= threshold))
correct += 1;
}
return correct > 0.5 * n ? correct : n - correct;
}
real_t LogLoss() {
real_t loss = 0;
size_t n = size_;
#pragma omp parallel for reduction(+:loss) num_threads(nt_)
for (size_t i = 0; i < n; ++i) {
real_t y = label_[i] > 0;
real_t p = 1 / (1 + exp(- predict_[i]));
p = p < 1e-10 ? 1e-10 : p;
loss += y * log(p) + (1 - y) * log(1 - p);
}
return - loss;
}
real_t LogitObjv() {
real_t objv = 0;
#pragma omp parallel for reduction(+:objv) num_threads(nt_)
for (size_t i = 0; i < size_; ++i) {
real_t y = label_[i] > 0 ? 1 : -1;
objv += log(1 + exp(- y * predict_[i]));
}
return objv;
}
private:
dmlc::real_t const* label_;
real_t const* predict_;
size_t size_;
int nt_;
};
} // namespace difacto
#endif // DIFACTO_LOSS_BIN_CLASS_METRIC_H_
|
mxEvaluatePostFunc1d.c | #include "../../@SWEAbstract1d/private/mxSWE1d.h"
#include "mex.h"
#ifdef _OPENMP
#include <omp.h>
#endif
#define NRHS 4
#define NLHS 1
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
/* check input & output */
if (nrhs != NRHS) {
mexPrintf("Matlab:%s:InvalidNumberInput,\n", __FILE__);
mexPrintf("%d inputs required.\n", NRHS);
}
if (nlhs != NLHS) {
mexPrintf("Matlab:%s:InvalidNumberOutput,\n", __FILE__);
mexPrintf("%d inputs required.\n", NLHS);
}
/* get inputs */
double hcrit = mxGetScalar(prhs[0]);
double *fphys = mxGetPr(prhs[1]);
double *hc = mxGetPr(prhs[2]);
double *qxc = mxGetPr(prhs[3]);
/* get dimensions */
const mwSize *dims = mxGetDimensions(prhs[1]);
const size_t Np = dims[0];
const size_t K = dims[1];
const size_t ndimOut = 3;
const mwSize dimOut[3] = {Np, K, NVAR};
plhs[0] = mxCreateNumericArray(ndimOut, dimOut, mxDOUBLE_CLASS, mxREAL);
double *h = fphys;
double *qx = fphys + K * Np;
double *h_pos = mxGetPr(plhs[0]);
double *qx_pos = h_pos + K * Np;
const double ksi = 0.0;
// cell area and scalar averages
#ifdef _OPENMP
#pragma omp parallel for num_threads(DG_THREADS)
#endif
for (int k = 0; k < K; k++) {
double hmean = hc[k];
double qxmean = qxc[k];
if (hmean <= ksi) {
for (int n = 0; n < Np; n++) {
size_t sk = k * Np + n;
h[sk] = 0;
qx[sk] = 0;
}
continue;
}
double hmin = h[k * Np];
for (int n = 0; n < Np; n++) {
hmin = min(hmin, h[k * Np + n]);
}
double theta;
if (hmin < hmean) {
theta = min((hmean - ksi) / (hmean - hmin), 1.0);
} else {
theta = 0.0;
}
for (int n = 0; n < Np; n++) {
size_t sk = k * Np + n;
h_pos[sk] = theta * (h[sk] - hmean) + hmean;
qx_pos[sk] = theta * (qx[sk] - qxmean) + qxmean;
if (h_pos[sk] < hcrit) { // dry nodes
qx_pos[sk] = 0.0;
}
}
}
return;
} |
GB_binop__iseq_uint8.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__iseq_uint8)
// A.*B function (eWiseMult): GB (_AemultB_08__iseq_uint8)
// A.*B function (eWiseMult): GB (_AemultB_02__iseq_uint8)
// A.*B function (eWiseMult): GB (_AemultB_04__iseq_uint8)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__iseq_uint8)
// A*D function (colscale): GB (_AxD__iseq_uint8)
// D*A function (rowscale): GB (_DxB__iseq_uint8)
// C+=B function (dense accum): GB (_Cdense_accumB__iseq_uint8)
// C+=b function (dense accum): GB (_Cdense_accumb__iseq_uint8)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__iseq_uint8)
// C=scalar+B GB (_bind1st__iseq_uint8)
// C=scalar+B' GB (_bind1st_tran__iseq_uint8)
// C=A+scalar GB (_bind2nd__iseq_uint8)
// C=A'+scalar GB (_bind2nd_tran__iseq_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_ISEQ || GxB_NO_UINT8 || GxB_NO_ISEQ_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__iseq_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__iseq_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__iseq_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__iseq_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__iseq_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__iseq_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__iseq_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__iseq_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__iseq_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__iseq_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__iseq_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__iseq_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__iseq_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__iseq_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
|
hyperquicksort.c | //hyper quick sort
#include <math.h>
#include <omp.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <signal.h>
#include <unistd.h>
int cmpfunc (const void * a, const void * b){
return *(int*)a >= *(int*)b ? 1 : -1;
}
int* readArrayValues(char* filename, int *n){
int *A;
FILE *file = fopen(filename,"r");
if (file == NULL) {
fprintf(stderr, "Error while opening file\n");
exit(EXIT_FAILURE);
}
fscanf(file,"%d",n);
A = (int*) malloc(sizeof(int)* *n);
for(int i = 0; i < *n; i++){
fscanf(file,"%d",&A[i]);
}
fclose(file);
return A;
}
void writeArrayValues(char* filename, int n, int* arr){
FILE *file = fopen(filename,"w");
if (file == NULL) {
fprintf(stderr, "Error while opening file\n");
exit(EXIT_FAILURE);
}
fprintf(file,"%d \n", n);
for(int i = 0 ; i < n; i++)
fprintf(file,"%d \n",arr[i]);
for(int i = 1 ; i < n; i++)
if(arr[i-1] > arr[i])
printf("ERROR: %d\n",i);
fclose(file);
return;
}
int findMedianIndex(int size, int *arr){
return arr[size/2];
}
int roundUp(int numToRound, int multiple)
{
int ans = log(numToRound) / log(2);
return pow(2, ans);
}
int findPivot(int median, int n, int **arr, int threadRank){
//can be optimized by doubling technique later
int pivot = 0;
while(pivot < n && arr[threadRank][pivot] < median)
pivot++;
return pivot;
}
int main(int argc, char* argv[]){
if(argc != 4){
fprintf(stderr, "incorrect arguments, use as :\n");
fprintf(stderr, "./a.out <inputfile.txt> <outputfile.txt> <num_threads>\n");
exit(EXIT_FAILURE);
}
int n, *A;
A = readArrayValues(argv[1], &n);
int nthreads = roundUp(atoi(argv[3]), 2);
int *pivots, *sizes;
pivots = (int*) malloc(sizeof(int) * nthreads);
sizes = (int*) malloc(sizeof(int) * nthreads);
memset(sizes, 0, sizeof(int) * nthreads);
memset(pivots, 0, sizeof(int) * nthreads);
//shared array accross processes
int **arr;
arr = (int **) malloc(nthreads * sizeof(int*));
for(int i = 0 ; i < nthreads ; i++){
arr[i] = (int *)malloc(n * sizeof(int));
for(int j = 0 ; j < n ; j++){
arr[i][j] = INT_MAX;
}
}
for(int i = 0 ; i < n ; i++){
arr[i%nthreads][i/nthreads] = A[i];
sizes[i%nthreads]++;
}
int logT = round(log(nthreads) / log(2));
#pragma omp parallel default (none) num_threads (nthreads) shared (arr, sizes, pivots, n, nthreads, logT)
{
int threadRank = omp_get_thread_num();
int sz = nthreads;
qsort(arr[threadRank], sizes[threadRank], sizeof(int), cmpfunc);
#pragma omp barrier
for(int iter = 0 ; iter < logT ; iter++){
int medianBroadcasterThreadRank = pow(2, iter) * threadRank/nthreads;
medianBroadcasterThreadRank *= sz;
int median = arr[medianBroadcasterThreadRank][sizes[medianBroadcasterThreadRank] / 2];
int pairThreadRank = (threadRank - medianBroadcasterThreadRank+(sz>>1))%sz + medianBroadcasterThreadRank;
int* pairThreadArr = (int*)malloc(sizes[pairThreadRank] * sizeof(int));
int merge_buf[n];
pivots[threadRank] = findPivot(median, sizes[threadRank], arr, threadRank);
int sizeOfPairThread = sizes[pairThreadRank];
// memcpy(pairThreadArr, arr[pairThreadRank], sizes[pairThreadRank]*sizeof(int));
for(int i = 0 ; i < sizeOfPairThread ; i++){
pairThreadArr[i] = arr[pairThreadRank][i];
}
//wait for all threads to compute the pivot and store in the shared pivots array
#pragma omp barrier
int pivotOfPairThread = pivots[pairThreadRank];
int i,j = 0,k = 0, i_end, j_end;
if((threadRank - medianBroadcasterThreadRank) >= (sz>>1)){
i = pivots[threadRank], i_end = sizes[threadRank];
sizes[threadRank] = sizes[threadRank] - pivots[threadRank] + sizeOfPairThread - pivotOfPairThread ;
j_end = sizeOfPairThread;
j = pivotOfPairThread;
}
else{
j_end = pivotOfPairThread;
i = 0, i_end = pivots[threadRank];
sizes[threadRank] = pivots[threadRank] + j_end;
}
while(i < i_end && j < j_end){
if(arr[threadRank][i] < pairThreadArr[j])
merge_buf[k++] = arr[threadRank][i++];
else
merge_buf[k++] = pairThreadArr[j++];
}
while(i < i_end)
merge_buf[k++] = arr[threadRank][i++];
while(j < j_end)
merge_buf[k++] = pairThreadArr[j++];
// memcpy(arr[threadRank], merge_buf, sizes[threadRank]*sizeof(int));
for(int i = 0 ; i < sizes[threadRank] ; i++){
arr[threadRank][i] = merge_buf[i];
}
sz /= 2;
#pragma omp barrier
}
}
int k = 0;
for(int i = 0 ; i < nthreads ; i++){
for(int j = 0 ; j < sizes[i] ; j++){
A[k++] = arr[i][j];
}
}
writeArrayValues(argv[2], n, A);
return 0;
} |
3d25pt.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-2, 3D 25 point stencil
* 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)
#ifndef min
#define min(x,y) ((x) < (y)? (x) : (y))
#endif
/* 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, 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]);
double ****A = (double ****) malloc(sizeof(double***)*2);
double ***roc2 = (double ***) malloc(sizeof(double**));
A[0] = (double ***) malloc(sizeof(double**)*Nz);
A[1] = (double ***) malloc(sizeof(double**)*Nz);
roc2 = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[0][i] = (double**) malloc(sizeof(double*)*Ny);
A[1][i] = (double**) malloc(sizeof(double*)*Ny);
roc2[i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[0][i][j] = (double*) malloc(sizeof(double)*Nx);
A[1][i][j] = (double*) malloc(sizeof(double)*Nx);
roc2[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] = 8;
tile_size[1] = 8;
tile_size[2] = 4;
tile_size[3] = 128;
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);
roc2[i][j][k] = 2.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
const double coef0 = -0.28472;
const double coef1 = 0.16000;
const double coef2 = -0.02000;
const double coef3 = 0.00254;
const double coef4 = -0.00018;
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 >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) {
for (t1=-1;t1<=Nt-1;t1++) {
lbp=ceild(t1+1,2);
ubp=min(floord(4*Nt+Nz-9,8),floord(4*t1+Nz-2,8));
#pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8)
for (t2=lbp;t2<=ubp;t2++) {
for (t3=max(max(1,ceild(8*t2-Nz+9,4)),t1+1);t3<=min(floord(4*Nt+Ny-9,4),floord(4*t1+Ny-1,4));t3++) {
for (t4=max(max(ceild(t1-30,32),ceild(8*t2-Nz-115,128)),ceild(4*t3-Ny-115,128));t4<=min(min(floord(4*Nt+Nx-9,128),floord(4*t1+Nx-1,128)),floord(4*t3+Nx-9,128));t4++) {
for (t5=max(max(max(max(0,ceild(8*t2-Nz+5,4)),ceild(4*t3-Ny+5,4)),ceild(128*t4-Nx+5,4)),t1);t5<=min(min(min(Nt-1,t1+1),t3-1),32*t4+30);t5++) {
for (t6=max(max(8*t2,4*t5+4),-8*t1+8*t2+8*t5-7);t6<=min(min(8*t2+7,-8*t1+8*t2+8*t5),4*t5+Nz-5);t6++) {
for (t7=4*t3;t7<=min(4*t3+3,4*t5+Ny-5);t7++) {
lbv=max(128*t4,4*t5+4);
ubv=min(128*t4+127,4*t5+Nx-5);
#pragma ivdep
#pragma vector always
for (t8=lbv;t8<=ubv;t8++) {
A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((2.0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) - A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (roc2[ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (((((coef0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef1 * (((((A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef2 * (((((A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef3 * (((((A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef4 * (((((A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])))));;
}
}
}
}
}
}
}
}
}
/* 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(4, "constant")
#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(roc2[i][j]);
}
free(A[0][i]);
free(A[1][i]);
free(roc2[i]);
}
free(A[0]);
free(A[1]);
free(roc2);
return 0;
}
|
data.h | /*!
* Copyright (c) 2015 by Contributors
* \file data.h
* \brief The input data structure of xgboost.
* \author Tianqi Chen
*/
#ifndef XGBOOST_DATA_H_
#define XGBOOST_DATA_H_
#include <dmlc/base.h>
#include <dmlc/data.h>
#include <dmlc/serializer.h>
#include <xgboost/base.h>
#include <xgboost/span.h>
#include <xgboost/host_device_vector.h>
#include <memory>
#include <numeric>
#include <algorithm>
#include <string>
#include <utility>
#include <vector>
namespace xgboost {
// forward declare dmatrix.
class DMatrix;
/*! \brief data type accepted by xgboost interface */
enum class DataType : uint8_t {
kFloat32 = 1,
kDouble = 2,
kUInt32 = 3,
kUInt64 = 4,
kStr = 5
};
enum class FeatureType : uint8_t {
kNumerical,
kCategorical
};
/*!
* \brief Meta information about dataset, always sit in memory.
*/
class MetaInfo {
public:
/*! \brief number of data fields in MetaInfo */
static constexpr uint64_t kNumField = 11;
/*! \brief number of rows in the data */
uint64_t num_row_{0}; // NOLINT
/*! \brief number of columns in the data */
uint64_t num_col_{0}; // NOLINT
/*! \brief number of nonzero entries in the data */
uint64_t num_nonzero_{0}; // NOLINT
/*! \brief label of each instance */
HostDeviceVector<bst_float> labels_; // NOLINT
/*!
* \brief the index of begin and end of a group
* needed when the learning task is ranking.
*/
std::vector<bst_group_t> group_ptr_; // NOLINT
/*! \brief weights of each instance, optional */
HostDeviceVector<bst_float> weights_; // NOLINT
/*!
* \brief initialized margins,
* if specified, xgboost will start from this init margin
* can be used to specify initial prediction to boost from.
*/
HostDeviceVector<bst_float> base_margin_; // NOLINT
/*!
* \brief lower bound of the label, to be used for survival analysis (censored regression)
*/
HostDeviceVector<bst_float> labels_lower_bound_; // NOLINT
/*!
* \brief upper bound of the label, to be used for survival analysis (censored regression)
*/
HostDeviceVector<bst_float> labels_upper_bound_; // NOLINT
/*!
* \brief Name of type for each feature provided by users. Eg. "int"/"float"/"i"/"q"
*/
std::vector<std::string> feature_type_names;
/*!
* \brief Name for each feature.
*/
std::vector<std::string> feature_names;
/*
* \brief Type of each feature. Automatically set when feature_type_names is specifed.
*/
HostDeviceVector<FeatureType> feature_types;
/*
* \brief Weight of each feature, used to define the probability of each feature being
* selected when using column sampling.
*/
HostDeviceVector<float> feature_weigths;
/*! \brief default constructor */
MetaInfo() = default;
MetaInfo(MetaInfo&& that) = default;
MetaInfo& operator=(MetaInfo&& that) = default;
MetaInfo& operator=(MetaInfo const& that) = delete;
/*!
* \brief Validate all metainfo.
*/
void Validate(int32_t device) const;
MetaInfo Slice(common::Span<int32_t const> ridxs) const;
/*!
* \brief Get weight of each instances.
* \param i Instance index.
* \return The weight.
*/
inline bst_float GetWeight(size_t i) const {
return weights_.Size() != 0 ? weights_.HostVector()[i] : 1.0f;
}
/*! \brief get sorted indexes (argsort) of labels by absolute value (used by cox loss) */
inline const std::vector<size_t>& LabelAbsSort() const {
if (label_order_cache_.size() == labels_.Size()) {
return label_order_cache_;
}
label_order_cache_.resize(labels_.Size());
std::iota(label_order_cache_.begin(), label_order_cache_.end(), 0);
const auto& l = labels_.HostVector();
XGBOOST_PARALLEL_SORT(label_order_cache_.begin(), label_order_cache_.end(),
[&l](size_t i1, size_t i2) {return std::abs(l[i1]) < std::abs(l[i2]);});
return label_order_cache_;
}
/*! \brief clear all the information */
void Clear();
/*!
* \brief Load the Meta info from binary stream.
* \param fi The input stream
*/
void LoadBinary(dmlc::Stream* fi);
/*!
* \brief Save the Meta info to binary stream
* \param fo The output stream.
*/
void SaveBinary(dmlc::Stream* fo) const;
/*!
* \brief Set information in the meta info.
* \param key The key of the information.
* \param dptr The data pointer of the source array.
* \param dtype The type of the source data.
* \param num Number of elements in the source array.
*/
void SetInfo(const char* key, const void* dptr, DataType dtype, size_t num);
/*!
* \brief Set information in the meta info with array interface.
* \param key The key of the information.
* \param interface_str String representation of json format array interface.
*
* [ column_0, column_1, ... column_n ]
*
* Right now only 1 column is permitted.
*/
void SetInfo(const char* key, std::string const& interface_str);
void GetInfo(char const* key, bst_ulong* out_len, DataType dtype,
const void** out_dptr) const;
void SetFeatureInfo(const char *key, const char **info, const bst_ulong size);
void GetFeatureInfo(const char *field, std::vector<std::string>* out_str_vecs) const;
/*
* \brief Extend with other MetaInfo.
*
* \param that The other MetaInfo object.
*
* \param accumulate_rows Whether rows need to be accumulated in this function. If
* client code knows number of rows in advance, set this parameter to false.
*/
void Extend(MetaInfo const& that, bool accumulate_rows);
private:
/*! \brief argsort of labels */
mutable std::vector<size_t> label_order_cache_;
};
/*! \brief Element from a sparse vector */
struct Entry {
/*! \brief feature index */
bst_feature_t index;
/*! \brief feature value */
bst_float fvalue;
/*! \brief default constructor */
Entry() = default;
/*!
* \brief constructor with index and value
* \param index The feature or row index.
* \param fvalue The feature value.
*/
XGBOOST_DEVICE Entry(bst_feature_t index, bst_float fvalue) : index(index), fvalue(fvalue) {}
/*! \brief reversely compare feature values */
inline static bool CmpValue(const Entry& a, const Entry& b) {
return a.fvalue < b.fvalue;
}
inline bool operator==(const Entry& other) const {
return (this->index == other.index && this->fvalue == other.fvalue);
}
};
/*!
* \brief Parameters for constructing batches.
*/
struct BatchParam {
/*! \brief The GPU device to use. */
int gpu_id;
/*! \brief Maximum number of bins per feature for histograms. */
int max_bin{0};
/*! \brief Page size for external memory mode. */
size_t gpu_page_size;
BatchParam() = default;
BatchParam(int32_t device, int32_t max_bin, size_t gpu_page_size = 0)
: gpu_id{device}, max_bin{max_bin}, gpu_page_size{gpu_page_size} {}
inline bool operator!=(const BatchParam& other) const {
return gpu_id != other.gpu_id || max_bin != other.max_bin ||
gpu_page_size != other.gpu_page_size;
}
};
struct HostSparsePageView {
using Inst = common::Span<Entry const>;
common::Span<bst_row_t const> offset;
common::Span<Entry const> data;
Inst operator[](size_t i) const {
auto size = *(offset.data() + i + 1) - *(offset.data() + i);
return {data.data() + *(offset.data() + i),
static_cast<Inst::index_type>(size)};
}
size_t Size() const { return offset.size() == 0 ? 0 : offset.size() - 1; }
};
/*!
* \brief In-memory storage unit of sparse batch, stored in CSR format.
*/
class SparsePage {
public:
// Offset for each row.
HostDeviceVector<bst_row_t> offset;
/*! \brief the data of the segments */
HostDeviceVector<Entry> data;
size_t base_rowid {0};
/*! \brief an instance of sparse vector in the batch */
using Inst = common::Span<Entry const>;
/*! \brief get i-th row from the batch */
inline Inst operator[](size_t i) const {
const auto& data_vec = data.HostVector();
const auto& offset_vec = offset.HostVector();
size_t size = offset_vec[i + 1] - offset_vec[i];
return {data_vec.data() + offset_vec[i],
static_cast<Inst::index_type>(size)};
}
HostSparsePageView GetView() const {
return {offset.ConstHostSpan(), data.ConstHostSpan()};
}
/*! \brief constructor */
SparsePage() {
this->Clear();
}
/*! \return Number of instances in the page. */
inline size_t Size() const {
return offset.Size() == 0 ? 0 : offset.Size() - 1;
}
/*! \return estimation of memory cost of this page */
inline size_t MemCostBytes() const {
return offset.Size() * sizeof(size_t) + data.Size() * sizeof(Entry);
}
/*! \brief clear the page */
inline void Clear() {
base_rowid = 0;
auto& offset_vec = offset.HostVector();
offset_vec.clear();
offset_vec.push_back(0);
data.HostVector().clear();
}
/*! \brief Set the base row id for this page. */
inline void SetBaseRowId(size_t row_id) {
base_rowid = row_id;
}
SparsePage GetTranspose(int num_columns) const;
void SortRows() {
auto ncol = static_cast<bst_omp_uint>(this->Size());
#pragma omp parallel for default(none) shared(ncol) schedule(dynamic, 1)
for (bst_omp_uint i = 0; i < ncol; ++i) {
if (this->offset.HostVector()[i] < this->offset.HostVector()[i + 1]) {
std::sort(
this->data.HostVector().begin() + this->offset.HostVector()[i],
this->data.HostVector().begin() + this->offset.HostVector()[i + 1],
Entry::CmpValue);
}
}
}
/**
* \brief Pushes external data batch onto this page
*
* \tparam AdapterBatchT
* \param batch
* \param missing
* \param nthread
*
* \return The maximum number of columns encountered in this input batch. Useful when pushing many adapter batches to work out the total number of columns.
*/
template <typename AdapterBatchT>
uint64_t Push(const AdapterBatchT& batch, float missing, int nthread);
/*!
* \brief Push a sparse page
* \param batch the row page
*/
void Push(const SparsePage &batch);
/*!
* \brief Push a SparsePage stored in CSC format
* \param batch The row batch to be pushed
*/
void PushCSC(const SparsePage& batch);
};
class CSCPage: public SparsePage {
public:
CSCPage() : SparsePage() {}
explicit CSCPage(SparsePage page) : SparsePage(std::move(page)) {}
};
class SortedCSCPage : public SparsePage {
public:
SortedCSCPage() : SparsePage() {}
explicit SortedCSCPage(SparsePage page) : SparsePage(std::move(page)) {}
};
class EllpackPageImpl;
/*!
* \brief A page stored in ELLPACK format.
*
* This class uses the PImpl idiom (https://en.cppreference.com/w/cpp/language/pimpl) to avoid
* including CUDA-specific implementation details in the header.
*/
class EllpackPage {
public:
/*!
* \brief Default constructor.
*
* This is used in the external memory case. An empty ELLPACK page is constructed with its content
* set later by the reader.
*/
EllpackPage();
/*!
* \brief Constructor from an existing DMatrix.
*
* This is used in the in-memory case. The ELLPACK page is constructed from an existing DMatrix
* in CSR format.
*/
explicit EllpackPage(DMatrix* dmat, const BatchParam& param);
/*! \brief Destructor. */
~EllpackPage();
EllpackPage(EllpackPage&& that);
/*! \return Number of instances in the page. */
size_t Size() const;
/*! \brief Set the base row id for this page. */
void SetBaseRowId(size_t row_id);
const EllpackPageImpl* Impl() const { return impl_.get(); }
EllpackPageImpl* Impl() { return impl_.get(); }
private:
std::unique_ptr<EllpackPageImpl> impl_;
};
template<typename T>
class BatchIteratorImpl {
public:
virtual ~BatchIteratorImpl() = default;
virtual T& operator*() = 0;
virtual const T& operator*() const = 0;
virtual void operator++() = 0;
virtual bool AtEnd() const = 0;
};
template<typename T>
class BatchIterator {
public:
using iterator_category = std::forward_iterator_tag; // NOLINT
explicit BatchIterator(BatchIteratorImpl<T>* impl) { impl_.reset(impl); }
void operator++() {
CHECK(impl_ != nullptr);
++(*impl_);
}
T& operator*() {
CHECK(impl_ != nullptr);
return *(*impl_);
}
const T& operator*() const {
CHECK(impl_ != nullptr);
return *(*impl_);
}
bool operator!=(const BatchIterator&) const {
CHECK(impl_ != nullptr);
return !impl_->AtEnd();
}
bool AtEnd() const {
CHECK(impl_ != nullptr);
return impl_->AtEnd();
}
private:
std::shared_ptr<BatchIteratorImpl<T>> impl_;
};
template<typename T>
class BatchSet {
public:
explicit BatchSet(BatchIterator<T> begin_iter) : begin_iter_(std::move(begin_iter)) {}
BatchIterator<T> begin() { return begin_iter_; } // NOLINT
BatchIterator<T> end() { return BatchIterator<T>(nullptr); } // NOLINT
private:
BatchIterator<T> begin_iter_;
};
struct XGBAPIThreadLocalEntry;
/*!
* \brief Internal data structured used by XGBoost during training.
*/
class DMatrix {
public:
/*! \brief default constructor */
DMatrix() = default;
/*! \brief meta information of the dataset */
virtual MetaInfo& Info() = 0;
virtual void SetInfo(const char *key, const void *dptr, DataType dtype,
size_t num) {
this->Info().SetInfo(key, dptr, dtype, num);
}
virtual void SetInfo(const char* key, std::string const& interface_str) {
this->Info().SetInfo(key, interface_str);
}
/*! \brief meta information of the dataset */
virtual const MetaInfo& Info() const = 0;
/*! \brief Get thread local memory for returning data from DMatrix. */
XGBAPIThreadLocalEntry& GetThreadLocal() const;
/**
* \brief Gets batches. Use range based for loop over BatchSet to access individual batches.
*/
template<typename T>
BatchSet<T> GetBatches(const BatchParam& param = {});
template <typename T>
bool PageExists() const;
// the following are column meta data, should be able to answer them fast.
/*! \return Whether the data columns single column block. */
virtual bool SingleColBlock() const = 0;
/*! \brief virtual destructor */
virtual ~DMatrix();
/*! \brief Whether the matrix is dense. */
bool IsDense() const {
return Info().num_nonzero_ == Info().num_row_ * Info().num_col_;
}
/*!
* \brief Load DMatrix from URI.
* \param uri The URI of input.
* \param silent Whether print information during loading.
* \param load_row_split Flag to read in part of rows, divided among the workers in distributed mode.
* \param file_format The format type of the file, used for dmlc::Parser::Create.
* By default "auto" will be able to load in both local binary file.
* \param page_size Page size for external memory.
* \return The created DMatrix.
*/
static DMatrix* Load(const std::string& uri,
bool silent,
bool load_row_split,
const std::string& file_format = "auto",
size_t page_size = kPageSize);
/**
* \brief Creates a new DMatrix from an external data adapter.
*
* \tparam AdapterT Type of the adapter.
* \param [in,out] adapter View onto an external data.
* \param missing Values to count as missing.
* \param nthread Number of threads for construction.
* \param cache_prefix (Optional) The cache prefix for external memory.
* \param page_size (Optional) Size of the page.
*
* \return a Created DMatrix.
*/
template <typename AdapterT>
static DMatrix* Create(AdapterT* adapter, float missing, int nthread,
const std::string& cache_prefix = "",
size_t page_size = kPageSize);
/**
* \brief Create a new Quantile based DMatrix used for histogram based algorithm.
*
* \tparam DataIterHandle External iterator type, defined in C API.
* \tparam DMatrixHandle DMatrix handle, defined in C API.
* \tparam DataIterResetCallback Callback for reset, prototype defined in C API.
* \tparam XGDMatrixCallbackNext Callback for next, prototype defined in C API.
*
* \param iter External data iterator
* \param proxy A hanlde to ProxyDMatrix
* \param reset Callback for reset
* \param next Callback for next
* \param missing Value that should be treated as missing.
* \param nthread number of threads used for initialization.
* \param max_bin Maximum number of bins.
*
* \return A created quantile based DMatrix.
*/
template <typename DataIterHandle, typename DMatrixHandle,
typename DataIterResetCallback, typename XGDMatrixCallbackNext>
static DMatrix *Create(DataIterHandle iter, DMatrixHandle proxy,
DataIterResetCallback *reset,
XGDMatrixCallbackNext *next, float missing,
int nthread,
int max_bin);
virtual DMatrix *Slice(common::Span<int32_t const> ridxs) = 0;
/*! \brief page size 32 MB */
static const size_t kPageSize = 32UL << 20UL;
protected:
virtual BatchSet<SparsePage> GetRowBatches() = 0;
virtual BatchSet<CSCPage> GetColumnBatches() = 0;
virtual BatchSet<SortedCSCPage> GetSortedColumnBatches() = 0;
virtual BatchSet<EllpackPage> GetEllpackBatches(const BatchParam& param) = 0;
virtual bool EllpackExists() const = 0;
virtual bool SparsePageExists() const = 0;
};
template<>
inline BatchSet<SparsePage> DMatrix::GetBatches(const BatchParam&) {
return GetRowBatches();
}
template<>
inline bool DMatrix::PageExists<EllpackPage>() const {
return this->EllpackExists();
}
template<>
inline bool DMatrix::PageExists<SparsePage>() const {
return this->SparsePageExists();
}
template<>
inline BatchSet<CSCPage> DMatrix::GetBatches(const BatchParam&) {
return GetColumnBatches();
}
template<>
inline BatchSet<SortedCSCPage> DMatrix::GetBatches(const BatchParam&) {
return GetSortedColumnBatches();
}
template<>
inline BatchSet<EllpackPage> DMatrix::GetBatches(const BatchParam& param) {
return GetEllpackBatches(param);
}
} // namespace xgboost
namespace dmlc {
DMLC_DECLARE_TRAITS(is_pod, xgboost::Entry, true);
namespace serializer {
template <>
struct Handler<xgboost::Entry> {
inline static void Write(Stream* strm, const xgboost::Entry& data) {
strm->Write(data.index);
strm->Write(data.fvalue);
}
inline static bool Read(Stream* strm, xgboost::Entry* data) {
return strm->Read(&data->index) && strm->Read(&data->fvalue);
}
};
} // namespace serializer
} // namespace dmlc
#endif // XGBOOST_DATA_H_
|
myblas.h | #include<omp.h>
#include<math.h>
// y = alpha * x + y
void axpy(size_t N, double alpha, const double* x, double* y){
#pragma omp parallel for
for(size_t i=0; i<N; i++){
y[i] = alpha * x[i] + y[i];
}
}
// z = alpha * x + y
void axpyz(size_t N, double alpha, const double* x, const double* y, double* z){
#pragma omp parallel for
for(size_t i=0; i<N; i++){
z[i] = alpha * x[i] + y[i];
}
}
// x = x + alpha * y
void xpay(size_t N, double alpha, double* x, const double* y){
#pragma omp parallel for
for(size_t i=0; i<N; i++){
x[i] = x[i] + alpha * y[i];
}
}
// x = alpha * x
void scal(size_t N, double alpha, double* x){
#pragma omp parallel for
for(size_t i=0; i<N; i++){
x[i] = alpha * x[i];
}
}
// inner product
double dot(size_t N, const double* x, const double* y){
double ans=0;
#pragma omp parallel for reduction(+:ans)
for(size_t i=0; i<N; i++){
ans += x[i] * y[i];
}
return ans;
}
// 2nrm
double nrm2(size_t N, const double* x){
return sqrt(dot(N, x, x));
}
// copy (y=x)
void copy(size_t N, const double* x, double* y){
#pragma omp parallel for
for(size_t i=0; i<N; i++){
y[i] = x[i];
}
}
// matvec:y=Ax
void matvec(int N,
const int* row_ptr, const int* col_ind, const double* val,
const double* x, double* y)
{
#pragma omp parallel for
for(size_t i = 0; i < N; i++){
y[i] = 0;
for(size_t j = row_ptr[i]; j < row_ptr[i+1]; j++){
y[i] += x[col_ind[j]] * val[j];
}
}
}
|
DigitalToAnalog.h | // --------------------------------------------------------------------------
// Binary Brain -- binary neural net framework
//
// Copyright (C) 2018-2019 by Ryuji Fuchikami
// https://github.com/ryuz
// ryuji.fuchikami@nifty.com
// --------------------------------------------------------------------------
#pragma once
#include <random>
#include "bb/Model.h"
namespace bb {
/**
* @brief バイナリ変調したデータを積算して実数に戻す
* @details バイナリ変調したデータを積算して実数に戻す
* 出力に対して入力は frame_mux_size 倍のフレーム数を必要とする
* BinaryToReal と組み合わせて使う想定
*
* @tparam BinType バイナリ型 (x)
* @tparam RealType 実数型 (y, dy, dx)
*/
template <typename BinType = float, typename RealType = float>
class DigitalToAnalog : public Model
{
using _super = Model;
public:
static inline std::string ModelName(void) { return "DigitalToAnalog"; }
static inline std::string ObjectName(void){ return ModelName() + "_" + DataType<BinType>::Name() + "_" + DataType<RealType>::Name(); }
std::string GetModelName(void) const override { return ModelName(); }
std::string GetObjectName(void) const override { return ObjectName(); }
protected:
bool m_host_only = false;
indices_t m_input_shape;
indices_t m_output_shape;
index_t m_digit_size = 0;
public:
struct create_t
{
indices_t output_shape;
index_t digit_size = 0;
};
protected:
DigitalToAnalog(create_t const &create)
{
m_output_shape = create.output_shape;
m_digit_size = create.digit_size;
}
/**
* @brief コマンド処理
* @detail コマンド処理
* @param args コマンド
*/
void CommandProc(std::vector<std::string> args)
{
// HostOnlyモード設定
if (args.size() == 2 && args[0] == "host_only")
{
m_host_only = EvalBool(args[1]);
}
}
public:
~DigitalToAnalog() {}
static std::shared_ptr<DigitalToAnalog> Create(create_t const &create)
{
return std::shared_ptr<DigitalToAnalog>(new DigitalToAnalog(create));
}
static std::shared_ptr<DigitalToAnalog> Create(index_t output_node, index_t digit_size=0)
{
create_t create;
create.output_shape = indices_t({output_node});
create.digit_size = digit_size;
return Create(create);
}
static std::shared_ptr<DigitalToAnalog> Create(indices_t output_shape, index_t digit_size=0)
{
create_t create;
create.output_shape = output_shape;
create.digit_size = digit_size;
return Create(create);
}
static std::shared_ptr<DigitalToAnalog> Create(void)
{
return Create(create_t());
}
#ifdef BB_PYBIND11
static std::shared_ptr<DigitalToAnalog> CreatePy(indices_t output_shape, index_t digit_size=0)
{
create_t create;
create.output_shape = output_shape;
create.digit_size = digit_size;
return Create(create);
}
#endif
/**
* @brief 入力のshape設定
* @detail 入力のshape設定
* @param shape 新しいshape
* @return なし
*/
indices_t SetInputShape(indices_t shape) override
{
// 設定済みなら何もしない
if ( shape == this->GetInputShape() ) {
return this->GetOutputShape();
}
// 形状設定
m_input_shape = shape;
// 桁数指定があるなら従う
if ( m_digit_size > 0 ) {
m_output_shape = shape;
BB_ASSERT(m_output_shape[0] % m_digit_size == 0);
m_output_shape[0] /= m_digit_size;
}
// 整数倍の縮退のみ許容
BB_ASSERT(CalcShapeSize(m_input_shape) >= CalcShapeSize(m_output_shape));
BB_ASSERT(CalcShapeSize(m_input_shape) % CalcShapeSize(m_output_shape) == 0);
return m_output_shape;
}
/**
* @brief 入力形状取得
* @detail 入力形状を取得する
* @return 入力形状を返す
*/
indices_t GetInputShape(void) const override
{
return m_input_shape;
}
/**
* @brief 出力形状取得
* @detail 出力形状を取得する
* @return 出力形状を返す
*/
indices_t GetOutputShape(void) const override
{
return m_output_shape;
}
FrameBuffer Forward(FrameBuffer x_buf, bool train = true) override
{
BB_ASSERT(x_buf.GetType() == DataType<BinType>::type);
// SetInputShpaeされていなければ初回に設定
if (x_buf.GetShape() != m_input_shape) {
SetInputShape(x_buf.GetShape());
}
// 戻り値の型を設定
FrameBuffer y_buf(x_buf.GetFrameSize(), m_output_shape, DataType<RealType>::type);
{
// 汎用版
auto x_ptr = x_buf.LockConst<BinType>();
auto y_ptr = y_buf.Lock<RealType>(true);
index_t input_node_size = GetInputNodeSize();
index_t output_node_size = GetOutputNodeSize();
index_t frame_size = y_buf.GetFrameSize();
index_t mux_size = input_node_size / output_node_size;
#pragma omp parallel for
for (index_t output_node = 0; output_node < output_node_size; ++output_node) {
for (index_t frame = 0; frame < frame_size; ++frame) {
RealType sum = 0;
RealType weight = (RealType)0.5;
for (index_t i = 0; i < mux_size; ++i) {
sum += (RealType)x_ptr.Get(frame, output_node_size * i + output_node) * weight;
weight *= (RealType)0.5;
}
y_ptr.Set(frame, output_node, sum);
}
}
return y_buf;
}
}
FrameBuffer Backward(FrameBuffer dy_buf) override
{
if (dy_buf.Empty()) {
return FrameBuffer();
}
BB_ASSERT(dy_buf.GetType() == DataType<RealType>::type);
// 戻り値の型を設定
FrameBuffer dx_buf(dy_buf.GetFrameSize(), m_input_shape, DataType<RealType>::type);
{
// 汎用版
index_t input_node_size = GetInputNodeSize();
index_t output_node_size = GetOutputNodeSize();
index_t frame_size = dy_buf.GetFrameSize();
index_t mux_size = input_node_size / output_node_size;
auto dy_ptr = dy_buf.LockConst<RealType>();
auto dx_ptr = dx_buf.Lock<RealType>();
#pragma omp parallel for
for (index_t output_node = 0; output_node < output_node_size; ++output_node) {
for (index_t frame = 0; frame < frame_size; ++frame) {
RealType dy = dy_ptr.Get(frame, output_node);
RealType weight = (RealType)0.5;
for (index_t i = 0; i < mux_size; i++) {
dx_ptr.Set(frame, output_node_size * i + output_node, dy * weight);
weight *= (RealType)0.5;
}
}
}
return dx_buf;
}
}
// シリアライズ
protected:
void DumpObjectData(std::ostream &os) const override
{
// バージョン
std::int64_t ver = 1;
bb::SaveValue(os, ver);
// 親クラス
_super::DumpObjectData(os);
// メンバ
bb::SaveValue(os, m_host_only);
bb::SaveValue(os, m_input_shape);
bb::SaveValue(os, m_output_shape);
bb::SaveValue(os, m_digit_size);
}
void LoadObjectData(std::istream &is) override
{
// バージョン
std::int64_t ver;
bb::LoadValue(is, ver);
BB_ASSERT(ver == 1);
// 親クラス
_super::LoadObjectData(is);
// メンバ
bb::LoadValue(is, m_host_only);
bb::LoadValue(is, m_input_shape);
bb::LoadValue(is, m_output_shape);
bb::LoadValue(is, m_digit_size);
}
};
}
// end of file
|
firstPrivateArray.c | /*
Array typed firstprivate variables:
element-by-element copy.
Contributed by Pranav Tendulkar
pranav@ics.forth.gr
4/12/2010
*/
int array[100];
int main()
{
array[10] = 10;
#pragma omp parallel firstprivate(array)
{
int i;
for(i=0;i<100;i++)
array[i] += i;
}
return 0;
}
|
3d7pt.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
* 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, 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]);
double ****A = (double ****) malloc(sizeof(double***)*2);
A[0] = (double ***) malloc(sizeof(double**)*Nz);
A[1] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[0][i] = (double**) malloc(sizeof(double*)*Ny);
A[1][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[0][i][j] = (double*) malloc(sizeof(double)*Nx);
A[1][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] = 16;
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;
const double alpha = 0.0876;
const double beta = 0.0765;
// 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);
}
}
}
#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,2);t1++) {
lbp=max(ceild(t1,2),ceild(4*t1-Nt+3,4));
ubp=min(floord(Nt+Nz-4,4),floord(2*t1+Nz-1,4));
#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(t1-7,8)),ceild(4*t2-Nz-12,16));t3<=min(min(min(floord(4*t2+Ny,16),floord(Nt+Ny-4,16)),floord(2*t1+Ny+1,16)),floord(4*t1-4*t2+Nz+Ny-1,16));t3++) {
for (t4=max(max(max(0,ceild(t1-127,128)),ceild(4*t2-Nz-252,256)),ceild(16*t3-Ny-252,256));t4<=min(min(min(min(floord(4*t2+Nx,256),floord(Nt+Nx-4,256)),floord(2*t1+Nx+1,256)),floord(16*t3+Nx+12,256)),floord(4*t1-4*t2+Nz+Nx-1,256));t4++) {
for (t5=max(max(max(max(max(0,2*t1),4*t1-4*t2+1),4*t2-Nz+2),16*t3-Ny+2),256*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,2*t1+3),4*t2+2),16*t3+14),256*t4+254),4*t1-4*t2+Nz+1);t5++) {
for (t6=max(max(4*t2,t5+1),-4*t1+4*t2+2*t5-3);t6<=min(min(4*t2+3,-4*t1+4*t2+2*t5),t5+Nz-2);t6++) {
for (t7=max(16*t3,t5+1);t7<=min(16*t3+15,t5+Ny-2);t7++) {
lbv=max(256*t4,t5+1);
ubv=min(256*t4+255,t5+Nx-2);
#pragma ivdep
#pragma vector always
for (t8=lbv;t8<=ubv;t8++) {
A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = ((alpha * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (beta * (((((A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)] + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1]) + A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-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, "constant")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays (Causing performance degradation
/* 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]);
*/
return 0;
}
|
untied_task.c | // RUN: %libomp-compile-and-run | %sort-threads | FileCheck %s
// REQUIRES: ompt
#define TEST_NEED_PRINT_FRAME_FROM_OUTLINED_FN
#include "callback.h"
#include <omp.h>
int main()
{
int condition=0;
omp_set_nested(0);
print_frame(0);
#pragma omp parallel num_threads(2)
{
print_frame_from_outlined_fn(1);
print_ids(0);
print_ids(1);
print_frame(0);
#pragma omp master
{
print_ids(0);
#pragma omp task untied shared(condition)
{
OMPT_SIGNAL(condition);
print_frame(1);
print_ids(0);
print_ids(1);
print_ids(2);
#pragma omp task if(0)
{
print_ids(0);
print_ids(1);
print_ids(2);
}
print_ids(0);
print_ids(1);
print_ids(2);
}
OMPT_WAIT(condition,1);
print_ids(0);
}
#pragma omp barrier
print_ids(0);
}
// Check if libomp supports the callbacks for this test.
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_task_create'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_task_schedule'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_parallel_begin'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_parallel_end'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_implicit_task'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_mutex_acquire'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_mutex_acquired'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_mutex_released'
// CHECK: {{^}}0: NULL_POINTER=[[NULL:.*$]]
// make sure initial data pointers are null
// CHECK-NOT: 0: new_task_data initially not null
// CHECK: {{^}}[[MASTER_ID:[0-9]+]]: __builtin_frame_address(0)=[[MAIN_REENTER:0x[0-f]+]]
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_parallel_begin: parent_task_id=[[PARENT_TASK_ID:[0-9]+]], parent_task_frame.exit=[[NULL]], parent_task_frame.reenter=0x{{[0-f]+}}, parallel_id=[[PARALLEL_ID:[0-9]+]], requested_team_size=2, codeptr_ra=0x{{[0-f]+}}, invoker=[[PARALLEL_INVOKER:[0-9]+]]
// nested parallel masters
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_begin: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID:[0-9]+]]
// CHECK: {{^}}[[MASTER_ID]]: __builtin_frame_address({{.}})=[[EXIT:0x[0-f]+]]
// CHECK: {{^}}[[MASTER_ID]]: task level 0: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]], exit_frame=[[EXIT]], reenter_frame=[[NULL]]
// CHECK: {{^}}[[MASTER_ID]]: task level 1: parallel_id=[[IMPLICIT_PARALLEL_ID:[0-9]+]], task_id=[[PARENT_TASK_ID]], exit_frame=[[NULL]], reenter_frame=0x{{[0-f]+}}
// CHECK: {{^}}[[MASTER_ID]]: __builtin_frame_address(0)=[[REENTER:0x[0-f]+]]
// CHECK: {{^}}[[MASTER_ID]]: task level 0: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]], exit_frame=[[EXIT]], reenter_frame=[[NULL]]
// <- ompt_event_task_create would be expected here
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_task_create: parent_task_id=[[IMPLICIT_TASK_ID]], parent_task_frame.exit=[[EXIT]], parent_task_frame.reenter=0x{{[0-f]+}}, new_task_id=[[TASK_ID:[0-9]+]], codeptr_ra=[[TASK_FUNCTION:0x[0-f]+]]
// CHECK: {{^}}[[MASTER_ID]]: task level 0: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]], exit_frame=[[EXIT]], reenter_frame=[[NULL]]
// explicit barrier after master
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_barrier_begin: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]]
// CHECK: {{^}}[[MASTER_ID]]: task level 0: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]], exit_frame=[[EXIT]], reenter_frame=0x{{[0-f]+}}
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_barrier_end: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]]
// implicit barrier parallel
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_barrier_begin: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]]
// CHECK: {{^}}[[MASTER_ID]]: task level 0: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]], exit_frame=[[NULL]], reenter_frame=[[NULL]]
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_barrier_end: parallel_id={{[0-9]+}}, task_id=[[IMPLICIT_TASK_ID]]
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_end: parallel_id={{[0-9]+}}, task_id=[[IMPLICIT_TASK_ID]]
// CHECK: {{^}}[[THREAD_ID:[0-9]+]]: ompt_event_implicit_task_begin: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID:[0-9]+]]
// CHECK: {{^}}[[THREAD_ID]]: __builtin_frame_address({{.}})=[[EXIT:0x[0-f]+]]
// CHECK: {{^}}[[THREAD_ID]]: task level 0: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]], exit_frame=[[EXIT]], reenter_frame=[[NULL]]
// CHECK: {{^}}[[THREAD_ID]]: task level 1: parallel_id=[[IMPLICIT_PARALLEL_ID]], task_id=[[PARENT_TASK_ID]], exit_frame=[[NULL]], reenter_frame=0x{{[0-f]+}}
// CHECK: {{^}}[[THREAD_ID]]: __builtin_frame_address(0)=[[REENTER:0x[0-f]+]]
// CHECK: {{^}}[[THREAD_ID]]: ompt_event_barrier_begin: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]]
// CHECK: {{^}}[[THREAD_ID]]: task level 0: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]], exit_frame=[[EXIT]], reenter_frame=0x{{[0-f]+}}
// this is expected to come earlier and at MASTER:
// CHECK: {{^}}[[THREAD_ID]]: ompt_event_task_schedule: first_task_id=[[IMPLICIT_TASK_ID]], second_task_id=[[TASK_ID]]
// CHECK: {{^}}[[THREAD_ID]]: __builtin_frame_address(1)=[[TASK_EXIT:0x[0-f]+]]
// CHECK: {{^}}[[THREAD_ID]]: task level 0: parallel_id=[[PARALLEL_ID]], task_id=[[TASK_ID]], exit_frame=[[TASK_EXIT]], reenter_frame=[[NULL]]
// CHECK: {{^}}[[THREAD_ID]]: task level 1: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]], exit_frame=[[EXIT]], reenter_frame=0x{{[0-f]+}}
// CHECK: {{^}}[[THREAD_ID]]: task level 2: parallel_id=[[IMPLICIT_PARALLEL_ID]], task_id=[[PARENT_TASK_ID]], exit_frame=[[NULL]], reenter_frame=0x{{[0-f]+}}
// CHECK: {{^}}[[THREAD_ID]]: ompt_event_task_schedule: first_task_id=[[TASK_ID]], second_task_id=[[IMPLICIT_TASK_ID]]
// CHECK: {{^}}[[THREAD_ID]]: ompt_event_task_end: task_id=[[TASK_ID]]
// CHECK: {{^}}[[THREAD_ID]]: ompt_event_barrier_end: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]]
// CHECK: {{^}}[[THREAD_ID]]: ompt_event_barrier_begin: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]]
// CHECK: {{^}}[[THREAD_ID]]: task level 0: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]], exit_frame=[[NULL]], reenter_frame=[[NULL]]
// CHECK: {{^}}[[THREAD_ID]]: ompt_event_barrier_end: parallel_id={{[0-9]+}}, task_id=[[IMPLICIT_TASK_ID]]
// CHECK: {{^}}[[THREAD_ID]]: ompt_event_implicit_task_end: parallel_id={{[0-9]+}}, task_id=[[IMPLICIT_TASK_ID]]
return 0;
}
|
decomp.h | /*!
/* Software SPAMS v2.2 - Copyright 2009-2011 Julien Mairal
*
* This file is part of SPAMS.
*
* SPAMS 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 of the License, or
* (at your option) any later version.
*
* SPAMS 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
* along with SPAMS. If not, see <http://www.gnu.org/licenses/>.
*
*
* \file
* toolbox decomp
*
* by Julien Mairal
* julien.mairal@inria.fr
*
* File decomp.h
* \brief Contains sparse decomposition algorithms
* It requires the toolbox linalg */
#ifndef DECOMP_H
#define DECOMP_H
#include <utils.h>
/* **************************
* Greedy Forward Selection
* **************************/
/// Forward Selection (or Orthogonal matching pursuit)
/// Address the problem of:
/// \forall i, \min_{\alpha_i} ||X_i-D\alpha_i||_2^2
/// s.t. ||\alphai||_0 <= L or
/// \forall i, \min_{\alpha_i} ||\alpha_i||_0
/// s.t. ||\X_i-D\alpha_i||_2^2 <= epsilon
/// This function is
/// * based on Cholesky decompositions
/// * parallel
/// * optimized for a large number of signals (precompute the Gramm matrix
template <typename T>
void omp(const Matrix<T>& X, const Matrix<T>& D, SpMatrix<T>& spalpha,
const int *L, const T* eps, const T* lambda, const bool vecL = false,
const bool vecEps = false, const bool Lambda=false, const int numThreads=-1,
Matrix<T>* path = NULL);
template <typename T>
void omp_mask(const Matrix<T>& X, const Matrix<T>& D, SpMatrix<T>& spalpha, const Matrix<bool>& mask,
const int *L, const T* eps, const T* lambda, const bool vecL = false,
const bool vecEps = false, const bool Lambda=false, const int numThreads=-1,
Matrix<T>* path = NULL);
/// Auxiliary function of omp
template <typename T>
void coreORMP(Vector<T>& scores, Vector<T>& norm, Vector<T>& tmp,
Matrix<T>& Un, Matrix<T>& Undn, Matrix<T>& Unds, Matrix<T>& Gs,
Vector<T>& Rdn, const AbstractMatrix<T>& G, Vector<int>& ind,
Vector<T>& RUn, T& normX, const T* eps, const int* L, const T* lambda,
T* path = NULL);
/// Auxiliary function of omp
template <typename T>
void coreORMPB(Vector<T>& RtD, const AbstractMatrix<T>& G, Vector<int>& ind,
Vector<T>& coeffs, T& normX, const int L, const T eps, const T lambda = 0);
/* **************
* LARS - Lasso
* **************/
/// Defines different types of problem,
/// - constraint on the l1 norm of the coefficients
/// - constraint on the reconstruction error
/// - l1-sparsity penalty
enum constraint_type { L1COEFFS, L2ERROR, PENALTY, SPARSITY, L2ERROR2, PENALTY2};
/// Implementation of LARS-Lasso for solving
/// \forall i, \min_{\alpha_i} ||X_i-D\alpha_i||_2^2
/// s.t. ||\alphai||_1 <= constraint or
/// \forall i, \min_{\alpha_i} ||\alpha_i||_1
/// s.t. ||\X_i-D\alpha_i||_2^2 <= constraint or
/// \forall i, \min_{\alpha_i} constraint*||\alpha_i||_1 + ...
/// ... ||\X_i-D\alpha_i||_2^2 <= T
/// Optionally, the solution might be positive (boolean pos), and a
/// Least-Square can be solved as a post-processing step.
/// L is a maximum number of coefficients.
/// This function is
/// * efficient (Cholesky-based)
/// * parallel
/// * optimized for a big number of signals (precompute the Gramm matrix
template <typename T>
void lasso(const Matrix<T>& X, const Matrix<T>& D,
SpMatrix<T>& spalpha,
int L, const T constraint, const T lambda2 = 0, constraint_type mode = PENALTY,
const bool pos = false, const bool ols = false, const int numThreads=-1,
Matrix<T>* path = NULL, const int length_path=-1);
template <typename T>
void lasso(const Data<T>& X, const AbstractMatrix<T>& G, const AbstractMatrix<T>& DtX,
SpMatrix<T>& spalpha,
int L, const T constraint, constraint_type mode = PENALTY,
const bool pos = false, const bool ols = false, const int numThreads=-1,
Matrix<T>* path = NULL, const int length_path=-1);
/// second implementation using matrix inversion lemma
template <typename T>
void lasso2(const Matrix<T>& X, const Matrix<T>& D, SpMatrix<T>& spalpha,
int L, const T constraint,const T lambda2=0, constraint_type mode = PENALTY, const bool pos = false,
const int numThreads = -1, Matrix<T>* path = NULL, const int length_path=-1);
template <typename T>
void lasso2(const Data<T>& X, const AbstractMatrix<T>& G, const AbstractMatrix<T>& DtX,
SpMatrix<T>& spalpha,
int L, const T constraint, constraint_type mode = PENALTY, const bool pos = false,
const int numThreads = -1, Matrix<T>* path = NULL, const int length_path=-1);
/// second implementation using matrix inversion lemma
template <typename T>
void lasso_mask(const Matrix<T>& X, const Matrix<T>& D, SpMatrix<T>& spalpha, const Matrix<bool>& mask,
int L, const T constraint,const T lambda2=0, constraint_type mode = PENALTY, const bool pos = false,
const int numThreads = -1);
/// second implementation using matrix inversion lemma
template <typename T>
void lassoReweighted(const Matrix<T>& X, const Matrix<T>& D, SpMatrix<T>& spalpha,
int L, const T constraint, constraint_type mode, const bool pos,
const T sigma,
const int numThreads = -1);
/// Auxiliary function for lasso
template <typename T>
void coreLARS(Vector<T>& Rdn, Vector<T>& Xdn, Vector<T>& A,
Vector<T>& u, Vector<T>& sig,
Vector<T>& av, Vector<T>& RUn, Matrix<T>& Un,
Matrix<T>& Unds, Matrix<T>& Gs,
Matrix<T>& Gsa, Matrix<T>& workT, Matrix<T>& R,
const AbstractMatrix<T>& G,T& normX,
Vector<int>& ind,Vector<T>& coeffs,const T constraint,
const bool ols = false,
const bool pos =false,
constraint_type mode = L1COEFFS,
T* path = NULL, int length_path=-1);
template <typename T>
void coreLARS2(Vector<T>& DtR, const AbstractMatrix<T>& G,
Matrix<T>& Gs,
Matrix<T>& Ga,
Matrix<T>& invGs,
Vector<T>& u,
Vector<T>& coeffs,
Vector<int>& ind,
Matrix<T>& work,
T& normX,
const constraint_type mode,
const T constraint, const bool pos = false,
T* pr_path = NULL, int length_path = -1);
template <typename T>
void coreLARS2W(Vector<T>& DtR, AbstractMatrix<T>& G,
Matrix<T>& Gs,
Matrix<T>& Ga,
Matrix<T>& invGs,
Vector<T>& u,
Vector<T>& coeffs,
const Vector<T>& weights,
Vector<int>& ind,
Matrix<T>& work,
T& normX,
const constraint_type mode,
const T constraint, const bool pos = false);
/// Auxiliary functoni for coreLARS (Cholesky downdate)
template <typename T>
void downDateLasso(int& j,int& minBasis,T& normX,const bool ols,
const bool pos, Vector<T>& Rdn, int* ind,
T* coeffs, Vector<T>& sig, Vector<T>& av,
Vector<T>& Xdn, Vector<T>& RUn,Matrix<T>& Unm, Matrix<T>& Gsm,
Matrix<T>& Gsam, Matrix<T>& Undsm, Matrix<T>& Rm);
/* ************************
* Iterative thresholding
* ************************/
/// Implementation of IST for solving
/// \forall i, \min_{\alpha_i} ||\alpha_i||_1
/// s.t. ||\X_i-D\alpha_i||_2^2 <= constraint or
/// \forall i, \min_{\alpha_i} constraint*||\alpha_i||_1 + ...
/// ... ||\X_i-D\alpha_i||_2^2 <= T
template <typename T>
void ist(const Matrix<T>& X, const Matrix<T>& D,
SpMatrix<T>& spalpha, T lambda, constraint_type mode,
const int itermax=500,
const T tol = 0.5, const int numThreads = -1);
template <typename T>
void ist(const Matrix<T>& X, const Matrix<T>& D,
Matrix<T>& spalpha, T lambda, constraint_type mode,
const int itermax=500,
const T tol = 0.5, const int numThreads=-1);
/// coreIST
template <typename T>
void coreIST(const AbstractMatrix<T>& G, Vector<T>& DtR, Vector<T>& coeffs,
const T thrs, const int itermax = 500,
const T tol = 0.5);
/// coreIST constrained
template <typename T>
void coreISTconstrained(const AbstractMatrix<T>& G, Vector<T>& DtR, Vector<T>& coeffs,
const T normX2,
const T thrs, const int itermax = 500,
const T tol = 0.5);
/// ist for group Lasso
template <typename T>
void ist_groupLasso(const Matrix<T>* XT, const Matrix<T>& D,
Matrix<T>* alphaT, const int Ngroups,
const T lambda, const constraint_type mode,
const int itermax = 500,
const T tol = 0.5, const int numThreads = -1);
/// Auxiliary function for ist_groupLasso
template <typename T>
void coreGroupIST(const Matrix<T>& G, Matrix<T>& RtD,
Matrix<T>& alphat,
const T thrs,
const int itermax=500,
const T tol = 0.5);
/// Auxiliary function for ist_groupLasso
template <typename T>
void coreGroupISTConstrained(const Matrix<T>& G, Matrix<T>& RtD,
Matrix<T>& alphat, const T normR,
const T eps,
const int itermax=500,
const T tol = 0.5);
/// auxiliary function for ist_groupLasso
template <typename T>
T computeError(const T normX2,const Vector<T>& norms,
const Matrix<T>& G,const Matrix<T>& RtD,const Matrix<T>& alphat);
/// auxiliary function for ist_groupLasso
template <typename T>
T computeError(const T normX2,
const Matrix<T>& G,const Vector<T>& DtR,const Vector<T>& coeffs,
SpVector<T>& coeffs_tmp);
/* ******************
* Simultaneous OMP
* *****************/
template <typename T>
void somp(const Matrix<T>* X, const Matrix<T>& D, SpMatrix<T>* spalpha,
const int Ngroups, const int L, const T* pr_eps, const bool adapt=false,
const int numThreads=-1);
template <typename T>
void somp(const Matrix<T>* X, const Matrix<T>& D, SpMatrix<T>* spalpha,
const int Ngroups, const int L, const T eps, const int numThreads=-1);
template <typename T>
void coreSOMP(const Matrix<T>& X, const Matrix<T>& D, const Matrix<T>& G,
Matrix<T>& vM,
Vector<int>& rv, const int L, const T eps);
/* *********************
* Implementation of OMP
* *********************/
/// Forward Selection (or Orthogonal matching pursuit)
/// Address the problem of:
/// \forall i, \min_{\alpha_i} ||X_i-D\alpha_i||_2^2
/// s.t. ||\alphai||_0 <= L or
/// \forall i, \min_{\alpha_i} ||\alpha_i||_0
/// s.t. ||\X_i-D\alpha_i||_2^2 <= epsilon
/// This function is
/// * efficient (Cholesky-based)
/// * parallel
/// * optimized for a big number of signals (precompute the Gramm matrix
template <typename T>
void omp(const Matrix<T>& X, const Matrix<T>& D, SpMatrix<T>& spalpha,
const int* pL, const T* peps, const T* pLambda,
const bool vecL, const bool vecEps,
const bool vecLambda, const int numThreads, Matrix<T>* path) {
int L;
if (!vecL) {
L=*pL;
} else {
Vector<int> vL(const_cast<int*>(pL),X.n());
L=vL.maxval();
}
spalpha.clear();
if (L <= 0) return;
const int M = X.n();
const int K = D.n();
L = MIN(X.m(),MIN(L,K));
Matrix<T> vM(L,M);
Matrix<int> rM(L,M);
ProdMatrix<T> G(D, K < 25000 && M > 10);
int NUM_THREADS=init_omp(numThreads);
Vector<T>* scoresT=new Vector<T>[NUM_THREADS];
Vector<T>* normT=new Vector<T>[NUM_THREADS];
Vector<T>* tmpT=new Vector<T>[NUM_THREADS];
Vector<T>* RdnT=new Vector<T>[NUM_THREADS];
Matrix<T>* UnT=new Matrix<T>[NUM_THREADS];
Matrix<T>* UndnT=new Matrix<T>[NUM_THREADS];
Matrix<T>* UndsT=new Matrix<T>[NUM_THREADS];
Matrix<T>* GsT=new Matrix<T>[NUM_THREADS];
for (int i = 0; i<NUM_THREADS; ++i) {
scoresT[i].resize(K);
normT[i].resize(K);
tmpT[i].resize(K);
RdnT[i].resize(K);
UnT[i].resize(L,L);
UnT[i].setZeros();
UndnT[i].resize(K,L);
UndsT[i].resize(L,L);
GsT[i].resize(K,L);
}
int i;
#pragma omp parallel for private(i)
for (i = 0; i< M; ++i) {
#ifdef _OPENMP
int numT=omp_get_thread_num();
#else
int numT=0;
#endif
Vector<T> Xi;
X.refCol(i,Xi);
T normX = Xi.nrm2sq();
Vector<int> ind;
rM.refCol(i,ind);
ind.set(-1);
Vector<T> RUn;
vM.refCol(i,RUn);
Vector<T>& Rdn=RdnT[numT];
D.multTrans(Xi,Rdn);
coreORMP(scoresT[numT],normT[numT],tmpT[numT],UnT[numT],UndnT[numT],UndsT[numT],
GsT[numT],Rdn,G,ind,RUn, normX, vecEps ? peps+i : peps,
vecL ? pL+i : pL, vecLambda ? pLambda+i : pLambda,
path && i==0 ? path->rawX() : NULL);
}
delete[](scoresT);
delete[](normT);
delete[](tmpT);
delete[](RdnT);
delete[](UnT);
delete[](UndnT);
delete[](UndsT);
delete[](GsT);
/// convert the sparse matrix into a proper format
spalpha.convert(vM,rM,K);
};
template <typename T>
void omp_mask(const Matrix<T>& X, const Matrix<T>& D, SpMatrix<T>& spalpha, const Matrix<bool>& mask,
const int *pL, const T* peps, const T* pLambda, const bool vecL,
const bool vecEps, const bool vecLambda, const int numThreads,
Matrix<T>* path) {
int L;
if (!vecL) {
L=*pL;
} else {
Vector<int> vL(const_cast<int*>(pL),X.n());
L=vL.maxval();
}
spalpha.clear();
if (L <= 0) return;
const int M = X.n();
const int K = D.n();
L = MIN(X.m(),MIN(L,K));
Matrix<T> vM(L,M);
Matrix<int> rM(L,M);
ProdMatrix<T> G(D, K < 25000 && M > 10);
int NUM_THREADS=init_omp(numThreads);
Vector<T>* scoresT=new Vector<T>[NUM_THREADS];
Vector<T>* normT=new Vector<T>[NUM_THREADS];
Vector<T>* tmpT=new Vector<T>[NUM_THREADS];
Vector<T>* RdnT=new Vector<T>[NUM_THREADS];
Matrix<T>* UnT=new Matrix<T>[NUM_THREADS];
Matrix<T>* UndnT=new Matrix<T>[NUM_THREADS];
Matrix<T>* UndsT=new Matrix<T>[NUM_THREADS];
Matrix<T>* GsT=new Matrix<T>[NUM_THREADS];
ProdMatrix<T>* GT=new ProdMatrix<T>[NUM_THREADS];
Matrix<T>* DmaskT=new Matrix<T>[NUM_THREADS];
Vector<T>* XmaskT=new Vector<T>[NUM_THREADS];
for (int i = 0; i<NUM_THREADS; ++i) {
DmaskT[i].resize(D.m(),D.n());
XmaskT[i].resize(X.m());
scoresT[i].resize(K);
normT[i].resize(K);
tmpT[i].resize(K);
RdnT[i].resize(K);
UnT[i].resize(L,L);
UnT[i].setZeros();
UndnT[i].resize(K,L);
UndsT[i].resize(L,L);
GsT[i].resize(K,L);
}
int i;
#pragma omp parallel for private(i)
for (i = 0; i< M; ++i) {
#ifdef _OPENMP
int numT=omp_get_thread_num();
#else
int numT=0;
#endif
Vector<T> Xi;
X.refCol(i,Xi);
Vector<int> ind;
rM.refCol(i,ind);
ind.set(-1);
Vector<T> RUn;
vM.refCol(i,RUn);
Vector<bool> maski;
mask.refCol(i,maski);
Vector<T>& Rdn=RdnT[numT];
if (maski.allfalse()) continue;
if (maski.alltrue()) {
D.multTrans(Xi,Rdn);
T normX = Xi.nrm2sq();
coreORMP(scoresT[numT],normT[numT],tmpT[numT],UnT[numT],UndnT[numT],UndsT[numT],
GsT[numT],Rdn,G,ind,RUn, normX, vecEps ? peps+i : peps,
vecL ? pL+i : pL, vecLambda ? pLambda+i : pLambda,
path && i==0 ? path->rawX() : NULL);
} else {
D.copyMask(DmaskT[numT],maski);
Xi.copyMask(XmaskT[numT],maski);
T normX = XmaskT[numT].nrm2sq();
DmaskT[numT].multTrans(XmaskT[numT],Rdn);
GT[numT].setMatrices(DmaskT[numT],false);
GT[numT].addDiag(T(1e-10));
T eps_mask= (vecEps ? *(peps+i) : *peps)*XmaskT[numT].n()/Xi.n();
coreORMP(scoresT[numT],normT[numT],tmpT[numT],
UnT[numT],UndnT[numT],UndsT[numT],
GsT[numT],Rdn,GT[numT],ind,RUn,
normX, &eps_mask, vecL ? pL+i : pL,
vecLambda ? pLambda+i : pLambda,
path && i==0 ? path->rawX() : NULL);
DmaskT[numT].setm(D.m());
DmaskT[numT].setn(D.n());
XmaskT[numT].setn(X.m());
}
}
delete[](GT);
delete[](XmaskT);
delete[](DmaskT);
delete[](scoresT);
delete[](normT);
delete[](tmpT);
delete[](RdnT);
delete[](UnT);
delete[](UndnT);
delete[](UndsT);
delete[](GsT);
/// convert the sparse matrix into a proper format
spalpha.convert(vM,rM,K);
};
/// Auxiliary function of omp
template <typename T>
void coreORMPB(Vector<T>& RtD, const AbstractMatrix<T>& G, Vector<int>& ind,
Vector<T>& coeffs, T& normX, const int L, const T eps, const T lambda) {
const int K = G.n();
Vector<T> scores(K);
Vector<T> norm(K);
Vector<T> tmp(K);
Matrix<T> Un(L,L);
Matrix<T> Undn(K,L);
Matrix<T> Unds(L,L);
Matrix<T> Gs(K,L);
ind.set(-1);
coreORMP(scores,norm,tmp,Un,Undn,Unds,Gs,RtD,G,ind,coeffs,normX,&eps,&L,&lambda);
};
/// Auxiliary function of omp
template <typename T>
void coreORMP(Vector<T>& scores, Vector<T>& norm, Vector<T>& tmp, Matrix<T>& Un,
Matrix<T>& Undn, Matrix<T>& Unds, Matrix<T>& Gs, Vector<T>& Rdn,
const AbstractMatrix<T>& G,
Vector<int>& ind, Vector<T>& RUn,
T& normX, const T* peps, const int* pL, const T* plambda,
T* path) {
const T eps = abs<T>(*peps);
const int L = MIN(*pL,Gs.n());
const T lambda=*plambda;
if ((normX <= eps) || L == 0) return;
const int K = scores.n();
scores.copy(Rdn);
norm.set(T(1.0));
Un.setZeros();
// permit unsafe low level access
T* const prUn = Un.rawX();
T* const prUnds = Unds.rawX();
T* const prUndn = Undn.rawX();
T* const prGs = Gs.rawX();
T* const prRUn= RUn.rawX();
if (path)
memset(path,0,K*L*sizeof(T));
int j;
for (j = 0; j<L; ++j) {
const int currentInd=scores.fmax();
if (norm[currentInd] < 1e-8) {
ind[j]=-1;
break;
}
const T invNorm=T(1.0)/sqrt(norm[currentInd]);
const T RU=Rdn[currentInd]*invNorm;
const T delta = RU*RU;
if (delta < 2*lambda) {
break;
}
RUn[j]=RU;
normX -= delta;
ind[j]=currentInd;
//for (int k = 0; k<j; ++k) prUn[j*L+k]=0.0;
//prUn[j*L+j]=T(1.0);
// for (int k = 0; k<j; ++k) prUnds[k*L+j]=prUndn[k*K+currentInd];
// MGS algorithm, Update Un
// int iter = norm[currentInd] < 0.5 ? 2 : 1;
//int iter=1;
// for (int k = 0; k<iter; ++k) {
/// for (int l = 0; l<j; ++l) {
// T scal=-cblas_dot<T>(j+1-l,prUn+j*L+l,1,prUnds+l*L+l,1);
// T scal = -prUnds[l*L+j];
// cblas_axpy<T>(l+1,scal,prUn+l*L,1,prUn+j*L,1);
// }
// }
prUn[j*L+j]=-T(1.0);
cblas_copy<T>(j,prUndn+currentInd,K,prUn+j*L,1);
cblas_trmv<T>(CblasColMajor,CblasUpper,CblasNoTrans,CblasNonUnit,j,prUn,L,prUn+j*L,1);
cblas_scal<T>(j+1,-invNorm,prUn+j*L,1);
if (j == L-1 || (normX <= eps)) {
++j;
break;
}
if (path) {
T* last_path=path+(L-1)*K;
cblas_copy<T>(j+1,prRUn,1,last_path,1);
cblas_trmv<T>(CblasColMajor,CblasUpper,CblasNoTrans,CblasNonUnit,
j+1,prUn,L,last_path,1);
for (int k = 0; k<=j; ++k) {
path[j*K+ind[k]]=last_path[k];
}
}
// update the variables Gs, Undn, Unds, Rdn, norm, scores
Vector<T> Gsj;
Gs.refCol(j,Gsj);
G.copyCol(currentInd,Gsj);
cblas_gemv<T>(CblasColMajor,CblasNoTrans,K,j+1,T(1.0),prGs,K,prUn+j*L,1,
T(0.0),prUndn+j*K,1);
// prUnds[j*L+j] = prUndn[j*K+currentInd];
Vector<T> Undnj;
Undn.refCol(j,Undnj);
Rdn.add(Undnj,-RUn[j]);
tmp.sqr(Undnj);
norm.sub(tmp);
scores.sqr(Rdn);
scores.div(norm);
for (int k = 0; k<=j; ++k) scores[ind[k]]=T();
}
// compute the final coefficients
cblas_trmv<T>(CblasColMajor,CblasUpper,CblasNoTrans,CblasNonUnit,
j,prUn,L,prRUn,1);
if (path) {
memset(path+(L-1)*K,0,L*sizeof(T));
for (int k = 0; k<j; ++k) {
path[(j-1)*K+ind[k]]=prRUn[k];
}
}
};
/* **************
* LARS - Lasso
* **************/
/// Implementation of LARS-Lasso for solving
/// \forall i, \min_{\alpha_i} ||X_i-D\alpha_i||_2^2
/// s.t. ||\alphai||_1 <= constraint or
/// \forall i, \min_{\alpha_i} ||\alpha_i||_1
/// s.t. ||\X_i-D\alpha_i||_2^2 <= constraint or
/// \forall i, \min_{\alpha_i} constraint*||\alpha_i||_1 + ...
/// ... ||\X_i-D\alpha_i||_2^2 <= T
/// Optionally, the solution might be positive (boolean pos), and a
/// Least-Square can be solved as a post-processing step.
/// L is a maximum number of coefficients.
/// This function is
/// * efficient (Cholesky-based)
/// * parallel
/// * optimized for a big number of signals (precompute the Gramm matrix
template <typename T>
void lasso(const Matrix<T>& X, const Matrix<T>& D, SpMatrix<T>& spalpha,
int L, const T lambda, const T lambda2, constraint_type mode,
const bool pos, const bool ols, const int numThreads,
Matrix<T>* path, const int length_path) {
ProdMatrix<T> G(D, X.n() > 10 && D.n() < 50000);
G.addDiag(MAX(lambda2,1e-10));
ProdMatrix<T> DtX(D,X,false);
lasso(X,G,DtX,spalpha,L,lambda,mode,pos,ols,numThreads,path,length_path);
}
template <typename T>
void lasso(const Data<T>& X, const AbstractMatrix<T>& G,
const AbstractMatrix<T>& DtX, SpMatrix<T>& spalpha,
int L, const T lambda, constraint_type mode,
const bool pos, const bool ols, const int numThreads,
Matrix<T>* path, const int length_path) {
spalpha.clear();
const int M = X.n();
const int K = G.n();
Matrix<T> vM;
Matrix<int> rM;
vM.resize(L,M);
rM.resize(L,M);
if (L <= 0) return;
if (path) path->setZeros();
int NUM_THREADS=init_omp(numThreads);
//ProdMatrix<T> G(D, K < 25000 && M > 10);
Vector<T>* RdnT=new Vector<T>[NUM_THREADS];
Vector<T>* XdnT =new Vector<T>[NUM_THREADS];
Vector<T>* AT=new Vector<T>[NUM_THREADS];
Vector<T>* uT=new Vector<T>[NUM_THREADS];
Vector<T>* sigT=new Vector<T>[NUM_THREADS];
Vector<T>* avT=new Vector<T>[NUM_THREADS];
Vector<T>* RUnT = new Vector<T>[NUM_THREADS];
Matrix<T>* UnT=new Matrix<T>[NUM_THREADS];
Matrix<T>* RT=new Matrix<T>[NUM_THREADS];
Matrix<T>* UndsT=new Matrix<T>[NUM_THREADS];
Matrix<T>* GsT=new Matrix<T>[NUM_THREADS];
Matrix<T>* GsaT=new Matrix<T>[NUM_THREADS];
Matrix<T>* workT=new Matrix<T>[NUM_THREADS];
for (int i = 0; i<NUM_THREADS; ++i) {
RdnT[i].resize(K);
if (ols) XdnT[i].resize(K);
AT[i].resize(K);
uT[i].resize(L);
sigT[i].resize(L);
avT[i].resize(L);
if (ols) RUnT[i].resize(L);
UnT[i].resize(L,L);
UnT[i].setZeros();
UndsT[i].resize(L,L);
UndsT[i].setZeros();
GsT[i].resize(K,L);
GsaT[i].resize(L,L);
workT[i].resize(K,2);
RT[i].resize(L,L);
}
Vector<T> norms;
X.norm_2sq_cols(norms);
int i;
#pragma omp parallel for private(i)
for (i = 0; i< M; ++i) {
#ifdef _OPENMP
int numT=omp_get_thread_num();
#else
int numT=0;
#endif
T normX = norms[i];
Vector<int> ind;
rM.refCol(i,ind);
Vector<T> coeffs;
vM.refCol(i,coeffs);
coeffs.setZeros();
Vector<T>& Rdn=RdnT[numT];
DtX.copyCol(i,Rdn);
coreLARS(Rdn,XdnT[numT], AT[numT], uT[numT], sigT[numT], avT[numT],
RUnT[numT], UnT[numT], UndsT[numT], GsT[numT], GsaT[numT],
workT[numT],RT[numT],G,normX, ind,coeffs,lambda,ols,pos,
mode,path && i==0 ? path->rawX() : NULL, length_path);
}
delete[](RdnT);
delete[](XdnT);
delete[](AT);
delete[](uT);
delete[](sigT);
delete[](avT);
delete[](RUnT);
delete[](UnT);
delete[](RT);
delete[](UndsT);
delete[](GsT);
delete[](GsaT);
delete[](workT);
/// convert the sparse matrix into a proper format
spalpha.convert(vM,rM,K);
};
/// Auxiliary function for lasso
template <typename T>
void coreLARS(Vector<T>& Rdnv, Vector<T>& Xdnv, Vector<T>& Av,
Vector<T>& uv, Vector<T>& sigv, Vector<T>& avv, Vector<T>& RUnv,
Matrix<T>& Unm, Matrix<T>& Undsm, Matrix<T>& Gsm,
Matrix<T>& Gsam, Matrix<T>& workm, Matrix<T>& Rm,
const AbstractMatrix<T>& Gm,T& normX,
Vector<int>& indv,Vector<T>& coeffsv,const T constraint,
const bool ols,const bool pos, constraint_type mode,
T* path, int length_path) {
if (mode == L2ERROR && normX < constraint) return;
const int LL = Gsm.n();
const int K = Gsm.m();
const int L = MIN(LL,K);
if (length_path <= 1) length_path=4*L;
// permit unsafe fast low level access
T* const Rdn = Rdnv.rawX();
T* const Xdn = Xdnv.rawX();
T* const A = Av.rawX();
T* const u = uv.rawX();
T* const sig = sigv.rawX();
T* const av = avv.rawX();
T* const RUn = RUnv.rawX();
T* const Un = Unm.rawX();
T* const Unds = Undsm.rawX();
T* const Gs = Gsm.rawX();
T* const Gsa = Gsam.rawX();
T* const work = workm.rawX();
//T* const G = Gm.rawX();
T* const R = Rm.rawX();
int* ind = indv.rawX();
T* coeffs = coeffsv.rawX();
coeffsv.setZeros();
indv.set(-1);
if (ols) Xdnv.copy(Rdnv);
int currentInd= pos ? Rdnv.max() : Rdnv.fmax();
bool newAtom=true;
T Cmax;
int iter=1;
T thrs = 0.0;
int* const ind_orig = ind;
T* const coeffs_orig = coeffs;
int j;
for (j = 0; j<L; ++j) {
if (newAtom) {
ind[j]=currentInd;
if (pos) {
Cmax = Rdn[currentInd];
sig[j]=1.0;
} else {
Cmax = abs<T>(Rdn[currentInd]);
sig[j] = SIGN(Rdn[currentInd]);
}
for (int k = 0; k<=j; ++k) Un[j*L+k]=0.0;
Un[j*L+j]=1.0;
Gm.extract_rawCol(currentInd,Gs+K*j);
for (int k = 0; k<j; ++k) Gs[K*j+ind[k]] *= sig[k];
if (sig[j] < 0) {
Rdn[currentInd]=-Rdn[currentInd];
if (ols) Xdn[currentInd]=-Xdn[currentInd];
cblas_scal<T>(K,sig[j],Gs+K*j,1);
cblas_scal<T>(j+1,sig[j],Gs+currentInd,K);
}
cblas_copy<T>(j+1,Gs+currentInd,K,Gsa+j*L,1);
for (int k = 0; k<j; ++k) Gsa[k*L+j]=Gsa[j*L+k];
// <d_j,d_i>
cblas_copy<T>(j,Gsa+j*L,1,Unds+j,L);
// <U_j final,d_i>
cblas_trmv<T>(CblasColMajor,CblasUpper,CblasTrans,CblasNonUnit,
j+1,Un,L,Unds+j,L);
// norm2
T norm2=Gsa[j*L+j];
for (int k = 0; k<j; ++k) norm2 -= Unds[k*L+j]*Unds[k*L+j];
if (norm2 < 1e-15) {
ind[j]=-1;
// cerr << "bad exit" << endl;
break;
}
// int iter2 = norm2 < 0.5 ? 2 : 1;
// for(int k = 0; k<iter2; ++k) {
// for (int l = 0; l<j; ++l) {
// T scal=-cblas_dot<T>(j+1-l,Un+j*L+l,1,Unds+l*L+l,1);
// cblas_axpy<T>(l+1,scal,Un+l*L,1,Un+j*L,1);
// }
// }
Un[j*L+j]=-T(1.0);
cblas_copy<T>(j,Unds+j,L,Un+j*L,1);
cblas_trmv<T>(CblasColMajor,CblasUpper,CblasNoTrans,CblasNonUnit,j,Un,L,Un+j*L,1);
/// Un is the orthogonalized vectors in the D basis
T invNorm=1.0/sqrt(norm2);
cblas_scal<T>(j+1,-invNorm,Un+j*L,1);
Unds[j*L+j]=cblas_dot<T>(j+1,Un+j*L,1,Gsa+j*L,1);
}
for (int k = 0; k<=j; ++k) u[k]=T(1.0);
cblas_trmv<T>(CblasColMajor,CblasUpper,CblasTrans,CblasNonUnit,
j+1,Un,L,u,1);
T a = T(1.0)/cblas_nrm2<T>(j+1,u,1);
cblas_trmv<T>(CblasColMajor,CblasUpper,CblasNoTrans,CblasNonUnit,
j+1,Un,L,u,1);
cblas_scal<T>(j+1,a,u,1);
cblas_gemv<T>(CblasColMajor,CblasNoTrans,K,j+1,T(1.0),Gs,K,u,1,T(0.0),A,1);
T potentNorm=0.0;
if (!ols) {
for (int k = 0; k<=j; ++k) potentNorm += Rdn[ind[k]]*u[k];
}
if (pos) {
for (int k = 0; k<K; ++k) {
T diff = a-A[k];
work[k]= diff <= 0 ? INFINITY : (Cmax-Rdn[k])/diff;
}
for (int k = 0; k<=j; ++k) {
work[ind[k]]=INFINITY;
}
for (int k = 0; k<K; ++k)
if (work[k] <=0) work[k]=INFINITY;
currentInd =cblas_iamin<T>(K,work,1);
} else {
memset(work,0,2*K*sizeof(T));
for (int k = 0; k<=j; ++k) {
const int index=2*ind[k];
work[index]=INFINITY;
work[index+1]=INFINITY;
}
for (int k = 0; k<K; ++k) {
const int index=2*k;
if (!work[index]) {
const T diff1=a-A[k];
work[index]= diff1 <= 0 ? INFINITY : (Cmax-Rdn[k])/diff1;
const T diff2=a+A[k];
work[index+1]=diff2 <= 0 ? INFINITY : (Cmax+Rdn[k])/diff2;
}
}
currentInd =cblas_iamin<T>(2*K,work,1);
}
T gamma=work[currentInd];
T gammaMin=0;
int minBasis=0;
//if (j == L-1) gamma=potentNorm;
if (mode == PENALTY) {
gamma=MIN(gamma,(Cmax-constraint)/a);
}
// if (j > 0) {
vDiv<T>(j+1,coeffs,u,work);
cblas_scal<T>(j+1,-T(1.0),work,1);
/// voir pour petites valeurs
for (int k=0; k<=j; ++k)
if (coeffs[k]==0 || work[k] <=0) work[k]=INFINITY;
minBasis=cblas_iamin<T>(j+1,work,1);
gammaMin=work[minBasis];
if (gammaMin < gamma) gamma=gammaMin;
// }
if (mode == L1COEFFS) {
T Tu = 0.0;
for (int k = 0; k<=j; ++k) Tu += u[k];
if (Tu > EPSILON)
gamma= MIN(gamma,(constraint-thrs)/Tu);
thrs+=gamma*Tu;
}
// compute the norm of the residdual
if (ols == 0) {
const T t = gamma*gamma - 2*gamma*potentNorm;
if (t > 0 || isnan(t) || isinf(t)) {
// cerr << "bad bad exit" << endl;
// cerr << t << endl;
ind[j]=-1;
break;
}
normX += t;
} else {
// plan the last orthogonal projection
if (newAtom) {
RUn[j]=0.0;
for (int k = 0; k<=j; ++k) RUn[j] += Xdn[ind[k]]*
Un[j*L+k];
normX -= RUn[j]*RUn[j];
}
}
// Update the coefficients
cblas_axpy<T>(j+1,gamma,u,1,coeffs,1);
if (pos) {
for (int k = 0; k<j+1; ++k)
if (coeffs[k] < 0) coeffs[k]=0;
}
cblas_axpy<T>(K,-gamma,A,1,Rdn,1);
if (!pos) currentInd/= 2;
if (path) {
for (int k = 0; k<=j; ++k)
path[iter*K+ind[k]]=coeffs[k]*sig[k];
}
if (gamma == gammaMin) {
downDateLasso<T>(j,minBasis,normX,ols,pos,Rdnv,ind,coeffs,sigv,
avv,Xdnv, RUnv, Unm, Gsm, Gsam,Undsm,Rm);
newAtom=false;
Cmax=abs<T>(Rdn[ind[0]]);
--j;
} else {
newAtom=true;
}
++iter;
if (mode == PENALTY) {
thrs=abs<T>(Rdn[ind[0]]);
}
if ((j == L-1) ||
(mode == PENALTY && (thrs - constraint < 1e-15)) ||
(mode == L1COEFFS && (thrs - constraint > -1e-15)) ||
(newAtom && mode == L2ERROR && (normX - constraint < 1e-15)) ||
(normX < 1e-15) ||
(iter >= length_path)) {
// cerr << "exit" << endl;
// PRINT_F(thrs)
// PRINT_F(constraint)
// PRINT_F(normX)
break;
}
}
if (ols) {
cblas_copy<T>(j+1,RUn,1,coeffs,1);
cblas_trmv<T>(CblasColMajor,CblasUpper,CblasNoTrans,CblasNonUnit,
j+1,Un,L,coeffs,1);
}
vMul<T>(j+1,coeffs,sig,coeffs);
};
/// Auxiliary functoni for coreLARS (Cholesky downdate)
template <typename T>
inline void downDateLasso(int& j,int& minBasis,T& normX,const bool ols,
const bool pos,
Vector<T>& Rdnv, int* ind,
T* coeffs, Vector<T>& sigv, Vector<T>& avv,
Vector<T>& Xdnv, Vector<T>& RUnv,Matrix<T>& Unm, Matrix<T>& Gsm,
Matrix<T>& Gsam, Matrix<T>& Undsm, Matrix<T>& Rm) {
int k,l;
const int L = Gsm.n();
const int K = Gsm.m();
T* const Rdn = Rdnv.rawX();
T* const Xdn = Xdnv.rawX();
T* const sig = sigv.rawX();
T* const av = avv.rawX();
T* const RUn = RUnv.rawX();
T* const Un = Unm.rawX();
T* const Unds = Undsm.rawX();
T* const Gs = Gsm.rawX();
T* const Gsa = Gsam.rawX();
T* const R = Rm.rawX();
int indB=ind[minBasis];
if (!pos && sig[minBasis] < 0) {
// Update Rdn
Rdn[indB]=-Rdn[indB];
if (ols) Xdn[indB]=-Xdn[indB];
}
int num=j-minBasis;
for (int k = 0; k<num*num;++k) R[k]=0.0;
for (int k = 0; k<num; ++k) R[k*num+k]=1.0;
// Update Un
for (int k = minBasis+1; k<=j; ++k) {
T a = -Un[k*L+minBasis]/Un[minBasis*L+minBasis];
av[k-minBasis-1] = a;
cblas_axpy<T>(minBasis,a,Un+minBasis*L,1,Un+k*L,1);
}
for (int k = minBasis+1; k<=j; ++k) {
cblas_copy<T>(minBasis,Un+k*L,1,Un+(k-1)*L,1);
cblas_copy<T>(num,Un+k*L+minBasis+1,1,Un+(k-1)*L+minBasis,1);
}
T alpha=1.0;
T alphab,gamma,lambda;
for (int k = 0; k<num; ++k) {
alphab=alpha+av[k]*av[k];
R[k*num+k]=sqrt(alphab/alpha);
gamma=av[k]*R[k*num+k]/alphab;
alpha=alphab;
cblas_copy<T>(num-k-1,av+k+1,1,R+k*num+k+1,1);
cblas_scal<T>(num-k-1,gamma,R+k*num+k+1,1);
}
if (num > 0) {
trtri<T>(low,nonUnit,num,R,num);
cblas_trmm<T>(CblasColMajor,CblasRight,CblasLower,CblasTrans,CblasNonUnit,
j,num,T(1.0),R,num,Un+minBasis*L,L);
}
// Update Unds
for (int k = minBasis+1; k<=j; ++k)
cblas_axpy<T>(j-minBasis,av[k-minBasis-1],Unds+minBasis*L+minBasis+1,1,
Unds+k*L+minBasis+1,1);
for (int k = 0; k<minBasis; ++k)
for (int l = minBasis+1; l<=j; ++l)
Unds[k*L+l-1]=Unds[k*L+l];
for (int k = minBasis+1; k<=j; ++k)
cblas_copy<T>(j-minBasis,Unds+k*L+minBasis+1,1,Unds+(k-1)*L+minBasis,1);
if (num > 0)
cblas_trmm<T>(CblasColMajor,CblasRight,CblasLower,CblasTrans,CblasNonUnit,
j-minBasis,num,T(1.0),R,num,Unds+minBasis*L+minBasis,L);
for (int k = minBasis+1; k<=j; ++k)
for (int l = 0; l<k; ++l) Unds[k*L+l]=0.0;
// Update Gs
for (int k = minBasis+1; k<=j; ++k) {
cblas_copy<T>(K,Gs+k*K,1,Gs+(k-1)*K,1);
}
if (!pos && sig[minBasis] < T(0.0)) cblas_scal<T>(j,T(-1.0),Gs+indB,K);
// Update Gsa
for (int k = minBasis+1; k<=j; ++k) {
cblas_copy<T>(minBasis,Gsa+k*L,1,Gsa+(k-1)*L,1);
cblas_copy<T>(j-minBasis,Gsa+k*L+minBasis+1,1,Gsa+(k-1)*L+minBasis,1);
}
for (int k = 0; k<minBasis; ++k) {
for (int l = minBasis+1; l<=j; ++l) Gsa[k*L+l-1]=Gsa[k*L+l];
}
// Update sig
for (int k = minBasis+1; k<=j && !pos; ++k) sig[k-1]=sig[k];
// Update ind
for (int k = minBasis+1; k<=j; ++k) ind[k-1]=ind[k];
ind[j]=-1;
for (int k = minBasis+1; k<=j; ++k) coeffs[k-1]=coeffs[k];
coeffs[j]=0.0;
if (ols) {
// Update RUn and normX
for (int k = minBasis; k<=j; ++k)
normX += RUn[k]*RUn[k];
for (int k = minBasis; k<j; ++k) {
RUn[k]=0.0;
for (int l = 0; l<=k; ++l) RUn[k] += Xdn[ind[l]]*
Un[k*L+l];
normX -= RUn[k]*RUn[k];
}
}
// Update j
--j;
}
/// second implementation using matrix inversion lemma
template <typename T>
void lassoReweighted(const Matrix<T>& X, const Matrix<T>& D, SpMatrix<T>& spalpha,
int L, const T constraint, constraint_type mode, const bool pos,
const T sigma,
const int numThreads) {
spalpha.clear();
const int M = X.n();
const int K = D.n();
Matrix<T> vM;
Matrix<int> rM;
vM.resize(L,M);
rM.resize(L,M);
const int iterR = 30;
if (L <= 0) return;
int NUM_THREADS=init_omp(numThreads);
//ProdMatrix<T> G(D, K < 25000 && M > 10);
ProdMatrix<T> G(D, K < 50000);
//Matrix<T> G;
//D.XtX(G);
G.addDiag(1e-10);
Vector<T>* DtRT=new Vector<T>[NUM_THREADS];
Vector<T>* DtRRT=new Vector<T>[NUM_THREADS];
Vector<T>* uT=new Vector<T>[NUM_THREADS];
Vector<T>* weightsT=new Vector<T>[NUM_THREADS];
Vector<int>* inddT=new Vector<int>[NUM_THREADS];
Matrix<T>* GsT=new Matrix<T>[NUM_THREADS];
Matrix<T>* GaT=new Matrix<T>[NUM_THREADS];
Matrix<T>* invGsT=new Matrix<T>[NUM_THREADS];
Matrix<T>* workT=new Matrix<T>[NUM_THREADS];
Matrix<T>* GT=new Matrix<T>[NUM_THREADS];
for (int i = 0; i<NUM_THREADS; ++i) {
DtRT[i].resize(K);
DtRRT[i].resize(K);
uT[i].resize(K);
weightsT[i].resize(K);
GT[i].resize(K,K);
inddT[i].resize(K);
GsT[i].resize(L,L);
invGsT[i].resize(L,L);
GaT[i].resize(K,L);
workT[i].resize(K,3);
workT[i].setZeros();
}
int i;
#pragma omp parallel for private(i)
for (i = 0; i< M; ++i) {
#ifdef _OPENMP
int numT=omp_get_thread_num();
#else
int numT=0;
#endif
Vector<T> Xi;
X.refCol(i,Xi);
T normXo = Xi.nrm2sq();
T normX = normXo;
Vector<int> ind;
rM.refCol(i,ind);
Vector<T> coeffs;
vM.refCol(i,coeffs);
Vector<T>& DtR=DtRT[numT];
Vector<T>& DtRR = DtRRT[numT];
D.multTrans(Xi,DtR);
DtRR.copy(DtR);
coreLARS2(DtRR,G,GsT[numT],GaT[numT],invGsT[numT],uT[numT],coeffs,
ind,workT[numT],normX,mode,constraint,pos);
//Matrix<T>& GG = GT[numT];
Vector<T>& weights = weightsT[numT];
//Vector<int>& indd = inddT[numT];
for (int j = 0; j<iterR; ++j) {
const T sig = sigma*pow(0.7,iterR-1-j);
weights.set(sig);
for (int k = 0; k<K; ++k) {
if (ind[k] != -1) {
weights[ind[k]] = MAX(1e-4,sig*exp(-sig*abs<T>(coeffs[k])));
} else {
break;
}
}
DtRR.copy(DtR);
normX=normXo;
coreLARS2W(DtRR,G,GsT[numT],GaT[numT],invGsT[numT],uT[numT],coeffs,weights,
ind,workT[numT],normX,mode,constraint,pos);
}
}
delete[](DtRT);
delete[](DtRRT);
delete[](inddT);
delete[](uT);
delete[](weightsT);
delete[](GsT);
delete[](GT);
delete[](GaT);
delete[](invGsT);
delete[](workT);
/// convert the sparse matrix into a proper format
spalpha.convert(vM,rM,K);
}
template <typename T>
void lassoWeight(const Matrix<T>& X, const Matrix<T>& D, const Matrix<T>& weights,
SpMatrix<T>& spalpha,
int L, const T constraint, constraint_type mode, const bool pos,
const int numThreads) {
spalpha.clear();
const int M = X.n();
const int K = D.n();
Matrix<T> vM;
Matrix<int> rM;
vM.resize(L,M);
rM.resize(L,M);
if (L <= 0) return;
int NUM_THREADS=init_omp(numThreads);
//ProdMatrix<T> G(D, K < 25000 && M > 10);
ProdMatrix<T> G(D, K < 50000);
//Matrix<T> G;
//D.XtX(G);
G.addDiag(1e-10);
Vector<T>* DtRT=new Vector<T>[NUM_THREADS];
Vector<T>* uT=new Vector<T>[NUM_THREADS];
Matrix<T>* GsT=new Matrix<T>[NUM_THREADS];
Matrix<T>* GaT=new Matrix<T>[NUM_THREADS];
Matrix<T>* invGsT=new Matrix<T>[NUM_THREADS];
Matrix<T>* workT=new Matrix<T>[NUM_THREADS];
for (int i = 0; i<NUM_THREADS; ++i) {
DtRT[i].resize(K);
uT[i].resize(K);
uT[i].setZeros();
GsT[i].resize(L,L);
invGsT[i].resize(L,L);
GaT[i].resize(K,L);
workT[i].resize(K,3);
workT[i].setZeros();
}
int i;
#pragma omp parallel for private(i)
for (i = 0; i< M; ++i) {
#ifdef _OPENMP
int numT=omp_get_thread_num();
#else
int numT=0;
#endif
Vector<T> Xi;
X.refCol(i,Xi);
T normX = Xi.nrm2sq();
Vector<int> ind;
rM.refCol(i,ind);
Vector<T> coeffs;
vM.refCol(i,coeffs);
Vector<T>& DtR=DtRT[numT];
D.multTrans(Xi,DtR);
Vector<T> we;
weights.refCol(i,we);
coreLARS2W(DtR,G,GsT[numT],GaT[numT],invGsT[numT],uT[numT],coeffs,we,
ind,workT[numT],normX,mode,constraint,pos);
}
delete[](DtRT);
delete[](uT);
delete[](GsT);
delete[](GaT);
delete[](invGsT);
delete[](workT);
/// convert the sparse matrix into a proper format
spalpha.convert(vM,rM,K);
};
template <typename T>
void lassoWeightPreComputed(const Matrix<T>& X, const Matrix<T>& G, const Matrix<T>& DtR, const Matrix<T>& weights,
SpMatrix<T>& spalpha,
int L, const T constraint, constraint_type mode, const bool pos,
const int numThreads) {
spalpha.clear();
const int M = X.n();
const int K = G.n();
Matrix<T> vM;
Matrix<int> rM;
vM.resize(L,M);
rM.resize(L,M);
if (L <= 0) return;
int NUM_THREADS=init_omp(numThreads);
Vector<T>* DtRT=new Vector<T>[NUM_THREADS];
Vector<T>* uT=new Vector<T>[NUM_THREADS];
Matrix<T>* GsT=new Matrix<T>[NUM_THREADS];
Matrix<T>* GaT=new Matrix<T>[NUM_THREADS];
Matrix<T>* invGsT=new Matrix<T>[NUM_THREADS];
Matrix<T>* workT=new Matrix<T>[NUM_THREADS];
for (int i = 0; i<NUM_THREADS; ++i) {
DtRT[i].resize(K);
uT[i].resize(K);
uT[i].setZeros();
GsT[i].resize(L,L);
invGsT[i].resize(L,L);
GaT[i].resize(K,L);
workT[i].resize(K,3);
workT[i].setZeros();
}
int i;
#pragma omp parallel for private(i)
for (i = 0; i< M; ++i) {
#ifdef _OPENMP
int numT=omp_get_thread_num();
#else
int numT=0;
#endif
Vector<T> Xi;
X.refCol(i,Xi);
T normX = Xi.nrm2sq();
Vector<int> ind;
rM.refCol(i,ind);
Vector<T> coeffs;
vM.refCol(i,coeffs);
Vector<T>& DtRi=DtRT[numT];
DtR.copyCol(i,DtRi);
Vector<T> we;
weights.refCol(i,we);
coreLARS2W(DtRi,G,GsT[numT],GaT[numT],invGsT[numT],uT[numT],coeffs,we,
ind,workT[numT],normX,mode,constraint,pos);
}
delete[](DtRT);
delete[](uT);
delete[](GsT);
delete[](GaT);
delete[](invGsT);
delete[](workT);
/// convert the sparse matrix into a proper format
spalpha.convert(vM,rM,K);
};
/// second implementation using matrix inversion lemma
template <typename T>
void lasso_mask(const Matrix<T>& X, const Matrix<T>& D, SpMatrix<T>& spalpha, const Matrix<bool>& mask,
int L, const T constraint,const T lambda2, constraint_type mode, const bool pos,
const int numThreads) {
spalpha.clear();
const int M = X.n();
const int K = D.n();
Matrix<T> vM;
Matrix<int> rM;
vM.resize(L,M);
rM.resize(L,M);
if (L <= 0) return;
int NUM_THREADS=init_omp(numThreads);
ProdMatrix<T> G(D,K < 25000 && M > 10);
G.addDiag(MAX(lambda2,1e-10));
Vector<T>* DtRT=new Vector<T>[NUM_THREADS];
Vector<T>* uT=new Vector<T>[NUM_THREADS];
Vector<T>* XmaskT=new Vector<T>[NUM_THREADS];
Matrix<T>* GsT=new Matrix<T>[NUM_THREADS];
ProdMatrix<T>* GT=new ProdMatrix<T>[NUM_THREADS];
Matrix<T>* DmaskT=new Matrix<T>[NUM_THREADS];
Matrix<T>* GaT=new Matrix<T>[NUM_THREADS];
Matrix<T>* invGsT=new Matrix<T>[NUM_THREADS];
Matrix<T>* workT=new Matrix<T>[NUM_THREADS];
for (int i = 0; i<NUM_THREADS; ++i) {
DmaskT[i].resize(D.m(),D.n());
DtRT[i].resize(K);
uT[i].resize(K);
XmaskT[i].resize(X.m());
uT[i].setZeros();
GsT[i].resize(L,L);
invGsT[i].resize(L,L);
GaT[i].resize(K,L);
workT[i].resize(K,3);
workT[i].setZeros();
}
int i;
#pragma omp parallel for private(i)
for (i = 0; i< M; ++i) {
#ifdef _OPENMP
int numT=omp_get_thread_num();
#else
int numT=0;
#endif
Vector<T> Xi;
X.refCol(i,Xi);
Vector<bool> maski;
mask.refCol(i,maski);
Vector<int> ind;
rM.refCol(i,ind);
Vector<T> coeffs;
vM.refCol(i,coeffs);
Vector<T>& DtR=DtRT[numT];
if (maski.allfalse()) continue;
if (maski.alltrue()) {
T normX = Xi.nrm2sq();
D.multTrans(Xi,DtR);
coreLARS2(DtR,G,GsT[numT],GaT[numT],invGsT[numT],uT[numT],coeffs,
ind,workT[numT],normX,mode,constraint,pos);
} else {
D.copyMask(DmaskT[numT],maski);
Xi.copyMask(XmaskT[numT],maski);
T constraint_mask = mode == PENALTY || mode == L2ERROR ? constraint*XmaskT[numT].n()/Xi.n() : constraint;
T normX = XmaskT[numT].nrm2sq();
DmaskT[numT].multTrans(XmaskT[numT],DtR);
GT[numT].setMatrices(DmaskT[numT],false);
GT[numT].addDiag(MAX(lambda2,T(1e-10)));
coreLARS2(DtR,GT[numT],
GsT[numT],GaT[numT],invGsT[numT],uT[numT],coeffs,
ind,workT[numT],normX,mode,constraint_mask,pos);
DmaskT[numT].setm(D.m());
DmaskT[numT].setn(D.n());
XmaskT[numT].setn(X.m());
}
}
delete[](GT);
delete[](XmaskT);
delete[](DmaskT);
delete[](DtRT);
delete[](uT);
delete[](GsT);
delete[](GaT);
delete[](invGsT);
delete[](workT);
/// convert the sparse matrix into a proper format
spalpha.convert(vM,rM,K);
};
template <typename T>
void lasso2(const Matrix<T>& X, const Matrix<T>& D, SpMatrix<T>& spalpha,
int L, const T constraint, const T lambda2, constraint_type mode, const bool pos,
const int numThreads, Matrix<T>* path, int length_path) {
ProdMatrix<T> G(D,X.n() > 10 && D.n() < 50000);
ProdMatrix<T> DtX(D,X,false);
G.addDiag(MAX(lambda2,1e-10));
lasso2(X,G,DtX,spalpha,L,constraint,mode,pos,numThreads,path, length_path);
}
template <typename T>
void lasso2(const Data<T>& X, const AbstractMatrix<T>& G, const AbstractMatrix<T>& DtX,
SpMatrix<T>& spalpha,
int L, const T constraint, constraint_type mode, const bool pos,
const int numThreads, Matrix<T>* path, int length_path) {
spalpha.clear();
const int M = X.n();
const int K = G.n();
Matrix<T> vM;
Matrix<int> rM;
vM.resize(L,M);
rM.resize(L,M);
if (L <= 0) return;
if (path) path->setZeros();
int NUM_THREADS=init_omp(numThreads);
Vector<T>* DtRT=new Vector<T>[NUM_THREADS];
Vector<T>* uT=new Vector<T>[NUM_THREADS];
Matrix<T>* GsT=new Matrix<T>[NUM_THREADS];
Matrix<T>* GaT=new Matrix<T>[NUM_THREADS];
Matrix<T>* invGsT=new Matrix<T>[NUM_THREADS];
Matrix<T>* workT=new Matrix<T>[NUM_THREADS];
for (int i = 0; i<NUM_THREADS; ++i) {
DtRT[i].resize(K);
uT[i].resize(K);
uT[i].setZeros();
GsT[i].resize(L,L);
invGsT[i].resize(L,L);
GaT[i].resize(K,L);
workT[i].resize(K,3);
workT[i].setZeros();
}
int i;
Vector<T> norms;
X.norm_2sq_cols(norms);
#pragma omp parallel for private(i)
for (i = 0; i< M; ++i) {
#ifdef _OPENMP
int numT=omp_get_thread_num();
#else
int numT=0;
#endif
// Vector<T> Xi;
// X.refCol(i,Xi);
// T normX = Xi.nrm2sq();
T normX = norms[i];
Vector<int> ind;
rM.refCol(i,ind);
Vector<T> coeffs;
vM.refCol(i,coeffs);
Vector<T>& DtR=DtRT[numT];
DtX.copyCol(i,DtR);
//D.multTrans(Xi,DtR);
coreLARS2(DtR,G,GsT[numT],GaT[numT],invGsT[numT],
uT[numT],coeffs,
ind,workT[numT],normX,mode,constraint,pos,
path && i==0 ? path->rawX() : NULL,length_path);
}
delete[](DtRT);
delete[](uT);
delete[](GsT);
delete[](GaT);
delete[](invGsT);
delete[](workT);
/// convert the sparse matrix into a proper format
spalpha.convert(vM,rM,K);
};
/// Auxiliary function for lasso
template <typename T>
void coreLARS2(Vector<T>& DtR, const AbstractMatrix<T>& G,
Matrix<T>& Gs,
Matrix<T>& Ga,
Matrix<T>& invGs,
Vector<T>& u,
Vector<T>& coeffs,
Vector<int>& ind,
Matrix<T>& work,
T& normX,
const constraint_type mode,
const T constraint,
const bool pos,
T* path, int length_path) {
const int LL = Gs.n();
const int K = G.n();
const int L = MIN(LL,K);
if (length_path <= 1) length_path=4*L;
coeffs.setZeros();
ind.set(-1);
T* const pr_Gs = Gs.rawX();
T* const pr_invGs = invGs.rawX();
T* const pr_Ga = Ga.rawX();
T* const pr_work = work.rawX();
T* const pr_u = u.rawX();
T* const pr_DtR = DtR.rawX();
T* const pr_coeffs = coeffs.rawX();
int* const pr_ind = ind.rawX();
// Find the most correlated element
int currentInd = pos ? DtR.max() : DtR.fmax();
if (mode == PENALTY && abs(DtR[currentInd]) < constraint) return;
if (mode == L2ERROR && normX < constraint) return;
bool newAtom=true;
int i;
int iter=0;
T thrs = 0;
for (i = 0; i<L; ++i) {
++iter;
if (newAtom) {
pr_ind[i]=currentInd;
// cerr << "Add " << currentInd << endl;
G.extract_rawCol(pr_ind[i],pr_Ga+i*K);
for (int j = 0; j<=i; ++j)
pr_Gs[i*LL+j]=pr_Ga[i*K+pr_ind[j]];
// Update inverse of Gs
if (i == 0) {
pr_invGs[0]=T(1.0)/pr_Gs[0];
} else {
cblas_symv<T>(CblasColMajor,CblasUpper,i,T(1.0),
pr_invGs,LL,pr_Gs+i*LL,1,T(0.0),pr_u,1);
const T schur =
T(1.0)/(pr_Gs[i*LL+i]-cblas_dot<T>(i,pr_u,1,pr_Gs+i*LL,1));
pr_invGs[i*LL+i]=schur;
cblas_copy<T>(i,pr_u,1,pr_invGs+i*LL,1);
cblas_scal<T>(i,-schur,pr_invGs+i*LL,1);
cblas_syr<T>(CblasColMajor,CblasUpper,i,schur,pr_u,1,
pr_invGs,LL);
}
}
// Compute the path direction
for (int j = 0; j<=i; ++j)
pr_work[j]= pr_DtR[pr_ind[j]] > 0 ? T(1.0) : T(-1.0);
cblas_symv<T>(CblasColMajor,CblasUpper,i+1,T(1.0),pr_invGs,LL,
pr_work,1,T(0.0),pr_u,1);
// Compute the step on the path
T step_max = INFINITY;
int first_zero = -1;
for (int j = 0; j<=i; ++j) {
T ratio = -pr_coeffs[j]/pr_u[j];
if (ratio > 0 && ratio <= step_max) {
step_max=ratio;
first_zero=j;
}
}
// PRINT_F(step_max)
T current_correlation = abs<T>(pr_DtR[pr_ind[0]]);
cblas_gemv<T>(CblasColMajor,CblasNoTrans,K,i+1,T(1.0),pr_Ga,
K,pr_u,1,T(0.0),pr_work+2*K,1);
cblas_copy<T>(K,pr_work+2*K,1,pr_work+K,1);
cblas_copy<T>(K,pr_work+2*K,1,pr_work,1);
for (int j = 0; j<=i; ++j) {
pr_work[pr_ind[j]]=INFINITY;
pr_work[pr_ind[j]+K]=INFINITY;
}
for (int j = 0; j<K; ++j) {
pr_work[j] = ((pr_work[j] < INFINITY) && (pr_work[j] > T(-1.0))) ? (pr_DtR[j]+current_correlation)/(T(1.0)+pr_work[j]) : INFINITY;
}
// work.print("work");
for (int j = 0; j<K; ++j) {
pr_work[j+K] = ((pr_work[j+K] < INFINITY) && (pr_work[j+K] < T(1.0))) ? (current_correlation-pr_DtR[j])/(T(1.0)-pr_work[j+K]) : INFINITY;
}
// work.print("work");
if (pos) {
for (int j = 0; j<K; ++j) {
pr_work[j]=INFINITY;
}
}
// work.print("work");
// coeffs.print("coeffs");
int index = cblas_iamin<T>(2*K,pr_work,1);
T step = pr_work[index];
// Choose next element
currentInd = index % K;
// compute the coefficients of the polynome representing normX^2
T coeff1 = 0;
for (int j = 0; j<=i; ++j)
coeff1 += pr_DtR[pr_ind[j]] > 0 ? pr_u[j] : -pr_u[j];
T coeff2 = 0;
for (int j = 0; j<=i; ++j)
coeff2 += pr_DtR[pr_ind[j]]*pr_u[j];
T coeff3 = normX-constraint;
T step_max2;
if (mode == PENALTY) {
step_max2 = current_correlation-constraint;
} else if (mode == L2ERROR) {
/// L2ERROR
const T delta = coeff2*coeff2-coeff1*coeff3;
step_max2 = delta < 0 ? INFINITY : (coeff2-sqrt(delta))/coeff1;
step_max2 = MIN(current_correlation,step_max2);
} else {
/// L1COEFFS
step_max2 = coeff1 < 0 ? INFINITY : (constraint-thrs)/coeff1;
step_max2 = MIN(current_correlation,step_max2);
}
step = MIN(MIN(step,step_max2),step_max);
if (step == INFINITY) break; // stop the path
// Update coefficients
cblas_axpy<T>(i+1,step,pr_u,1,pr_coeffs,1);
if (pos) {
for (int j = 0; j<i+1; ++j)
if (pr_coeffs[j] < 0) pr_coeffs[j]=0;
}
// Update correlations
cblas_axpy<T>(K,-step,pr_work+2*K,1,pr_DtR,1);
// Update normX
normX += coeff1*step*step-2*coeff2*step;
// Update norm1
thrs += step*coeff1;
if (path) {
for (int k = 0; k<=i; ++k)
path[iter*K+ind[k]]=pr_coeffs[k];
}
// Choose next action
if (step == step_max) {
// cerr << "Remove " << pr_ind[first_zero] << endl;
/// Downdate, remove first_zero
/// Downdate Ga, Gs, invGs, ind, coeffs
for (int j = first_zero; j<i; ++j) {
cblas_copy<T>(K,pr_Ga+(j+1)*K,1,pr_Ga+j*K,1);
pr_ind[j]=pr_ind[j+1];
pr_coeffs[j]=pr_coeffs[j+1];
}
pr_ind[i]=-1;
pr_coeffs[i]=0;
for (int j = first_zero; j<i; ++j) {
cblas_copy<T>(first_zero,pr_Gs+(j+1)*LL,1,pr_Gs+j*LL,1);
cblas_copy<T>(i-first_zero,pr_Gs+(j+1)*LL+first_zero+1,1,
pr_Gs+j*LL+first_zero,1);
}
const T schur = pr_invGs[first_zero*LL+first_zero];
cblas_copy<T>(first_zero,pr_invGs+first_zero*LL,1,pr_u,1);
cblas_copy<T>(i-first_zero,pr_invGs+(first_zero+1)*LL+first_zero,LL,
pr_u+first_zero,1);
for (int j = first_zero; j<i; ++j) {
cblas_copy<T>(first_zero,pr_invGs+(j+1)*LL,1,pr_invGs+j*LL,1);
cblas_copy<T>(i-first_zero,pr_invGs+(j+1)*LL+first_zero+1,1,
pr_invGs+j*LL+first_zero,1);
}
cblas_syr<T>(CblasColMajor,CblasUpper,i,T(-1.0)/schur,
pr_u,1,pr_invGs,LL);
newAtom=false;
i=i-2;
} else {
newAtom=true;
}
if ((iter >= length_path-1) || abs(step) < 1e-15 ||
step == step_max2 || (normX < 1e-15) ||
(i == (L-1)) ||
(mode == L2ERROR && normX - constraint < 1e-15) ||
(mode == L1COEFFS && (constraint-thrs < 1e-15))) {
break;
}
}
}
/// Auxiliary function for lasso
template <typename T>
void coreLARS2W(Vector<T>& DtR, AbstractMatrix<T>& G,
Matrix<T>& Gs,
Matrix<T>& Ga,
Matrix<T>& invGs,
Vector<T>& u,
Vector<T>& coeffs,
const Vector<T>& weights,
Vector<int>& ind,
Matrix<T>& work,
T& normX,
const constraint_type mode,
const T constraint,
const bool pos) {
const int LL = Gs.n();
const int K = G.n();
const int L = MIN(LL,K);
coeffs.setZeros();
ind.set(-1);
T* const pr_Gs = Gs.rawX();
T* const pr_invGs = invGs.rawX();
T* const pr_Ga = Ga.rawX();
// T* const pr_G = G.rawX();
T* const pr_work = work.rawX();
T* const pr_u = u.rawX();
T* const pr_DtR = DtR.rawX();
T* const pr_coeffs = coeffs.rawX();
T* const pr_weights = weights.rawX();
int* const pr_ind = ind.rawX();
DtR.div(weights);
// Find the most correlated element
int currentInd = pos ? DtR.max() : DtR.fmax();
if (mode == PENALTY && abs(DtR[currentInd]) < constraint) return;
if (mode == L2ERROR && normX < constraint) return;
bool newAtom=true;
int i;
int iter=0;
T thrs = 0;
for (i = 0; i<L; ++i) {
++iter;
if (newAtom) {
pr_ind[i]=currentInd;
// Update upper part of Gs and Ga
G.extract_rawCol(pr_ind[i],pr_Ga+i*K);
for (int j = 0; j<=i; ++j)
pr_Gs[i*LL+j]=pr_Ga[i*K+pr_ind[j]];
// Update inverse of Gs
if (i == 0) {
pr_invGs[0]=T(1.0)/pr_Gs[0];
} else {
cblas_symv<T>(CblasColMajor,CblasUpper,i,T(1.0),
pr_invGs,LL,pr_Gs+i*LL,1,T(0.0),pr_u,1);
const T schur =
T(1.0)/(pr_Gs[i*LL+i]-cblas_dot<T>(i,pr_u,1,pr_Gs+i*LL,1));
pr_invGs[i*LL+i]=schur;
cblas_copy<T>(i,pr_u,1,pr_invGs+i*LL,1);
cblas_scal<T>(i,-schur,pr_invGs+i*LL,1);
cblas_syr<T>(CblasColMajor,CblasUpper,i,schur,pr_u,1,
pr_invGs,LL);
}
}
// Compute the path direction
for (int j = 0; j<=i; ++j)
pr_work[j]= pr_DtR[pr_ind[j]] > 0 ? weights[pr_ind[j]] : -weights[pr_ind[j]];
cblas_symv<T>(CblasColMajor,CblasUpper,i+1,T(1.0),pr_invGs,LL,
pr_work,1,T(0.0),pr_u,1);
// Compute the step on the path
T step_max = INFINITY;
int first_zero = -1;
for (int j = 0; j<=i; ++j) {
T ratio = -pr_coeffs[j]/pr_u[j];
if (ratio > 0 && ratio <= step_max) {
step_max=ratio;
first_zero=j;
}
}
T current_correlation = abs<T>(pr_DtR[pr_ind[0]]);
cblas_gemv<T>(CblasColMajor,CblasNoTrans,K,i+1,T(1.0),pr_Ga,
K,pr_u,1,T(0.0),pr_work+2*K,1);
vDiv<T>(K,pr_work+2*K,pr_weights,pr_work+2*K);
cblas_copy<T>(K,pr_work+2*K,1,pr_work+K,1);
cblas_copy<T>(K,pr_work+2*K,1,pr_work,1);
for (int j = 0; j<=i; ++j) {
pr_work[pr_ind[j]]=INFINITY;
pr_work[pr_ind[j]+K]=INFINITY;
}
for (int j = 0; j<K; ++j) {
pr_work[j] = ((pr_work[j] < INFINITY) && (pr_work[j] > T(-1.0))) ? (pr_DtR[j]+current_correlation)/(T(1.0)+pr_work[j]) : INFINITY;
}
for (int j = 0; j<K; ++j) {
pr_work[j+K] = ((pr_work[j+K] < INFINITY) && (pr_work[j+K] < T(1.0))) ? (current_correlation-pr_DtR[j])/(T(1.0)-pr_work[j+K]) : INFINITY;
}
if (pos) {
for (int j = 0; j<K; ++j) {
pr_work[j]=INFINITY;
}
}
int index = cblas_iamin<T>(2*K,pr_work,1);
T step = pr_work[index];
// Choose next element
currentInd = index % K;
// compute the coefficients of the polynome representing normX^2
T coeff1 = 0;
for (int j = 0; j<=i; ++j)
coeff1 += pr_DtR[pr_ind[j]] > 0 ? pr_weights[pr_ind[j]]*pr_u[j] :
-pr_weights[pr_ind[j]]*pr_u[j];
T coeff2 = 0;
for (int j = 0; j<=i; ++j)
coeff2 += pr_DtR[pr_ind[j]]*pr_u[j]*pr_weights[pr_ind[j]];
T coeff3 = normX-constraint;
T step_max2;
if (mode == PENALTY) {
step_max2 = current_correlation-constraint;
} else if (mode == L2ERROR) {
/// L2ERROR
const T delta = coeff2*coeff2-coeff1*coeff3;
step_max2 = delta < 0 ? INFINITY : (coeff2-sqrt(delta))/coeff1;
} else {
/// L1COEFFS
step_max2 = coeff1 < 0 ? INFINITY : (constraint-thrs)/coeff1;
}
step = MIN(MIN(step,step_max2),step_max);
if (step == INFINITY) break; // stop the path
// Update coefficients
cblas_axpy<T>(i+1,step,pr_u,1,pr_coeffs,1);
// Update correlations
cblas_axpy<T>(K,-step,pr_work+2*K,1,pr_DtR,1);
// Update normX
normX += coeff1*step*step-2*coeff2*step;
// Update norm1
thrs += step*coeff1;
if (step == step_max) {
/// Downdate, remove first_zero
/// Downdate Ga, Gs, invGs, ind, coeffs
for (int j = first_zero; j<i; ++j) {
cblas_copy<T>(K,pr_Ga+(j+1)*K,1,pr_Ga+j*K,1);
pr_ind[j]=pr_ind[j+1];
pr_coeffs[j]=pr_coeffs[j+1];
}
pr_ind[i]=-1;
pr_coeffs[i]=0;
for (int j = first_zero; j<i; ++j) {
cblas_copy<T>(first_zero,pr_Gs+(j+1)*LL,1,pr_Gs+j*LL,1);
cblas_copy<T>(i-first_zero,pr_Gs+(j+1)*LL+first_zero+1,1,
pr_Gs+j*LL+first_zero,1);
}
const T schur = pr_invGs[first_zero*LL+first_zero];
cblas_copy<T>(first_zero,pr_invGs+first_zero*LL,1,pr_u,1);
cblas_copy<T>(i-first_zero,pr_invGs+(first_zero+1)*LL+first_zero,LL,
pr_u+first_zero,1);
for (int j = first_zero; j<i; ++j) {
cblas_copy<T>(first_zero,pr_invGs+(j+1)*LL,1,pr_invGs+j*LL,1);
cblas_copy<T>(i-first_zero,pr_invGs+(j+1)*LL+first_zero+1,1,
pr_invGs+j*LL+first_zero,1);
}
cblas_syr<T>(CblasColMajor,CblasUpper,i,T(-1.0)/schur,
pr_u,1,pr_invGs,LL);
newAtom=false;
i=i-2;
} else {
newAtom=true;
}
// Choose next action
if (iter > 4*L || abs(step) < 1e-10 ||
step == step_max2 || (normX < 1e-10) ||
(i == (L-1)) ||
(mode == L2ERROR && normX - constraint < 1e-10) ||
(mode == L1COEFFS && (constraint-thrs < 1e-10))) {
break;
}
}
}
/* ************************
* Iterative thresholding
* ************************/
/// Implementation of IST for solving
/// \forall i, \min_{\alpha_i} ||\alpha_i||_1
/// s.t. ||\X_i-D\alpha_i||_2^2 <= constraint or
/// \forall i, \min_{\alpha_i} constraint*||\alpha_i||_1 + ...
/// ... ||\X_i-D\alpha_i||_2^2 <= lambda
template <typename T>
void ist(const Matrix<T>& X, const Matrix<T>& D,
SpMatrix<T>& spalpha, T lambda, constraint_type mode,
const int itermax,
const T tol,
const int numThreads) {
Matrix<T> alpha;
spalpha.toFull(alpha);
spalpha.clear();
ist(X,D,alpha,lambda,mode,itermax,tol,numThreads);
alpha.toSparse(spalpha);
}
template <typename T>
void ist(const Matrix<T>& X, const Matrix<T>& D,
Matrix<T>& alpha, T lambda, constraint_type mode,
const int itermax,
const T tol, const int numThreads) {
if (mode == L1COEFFS) {
std::cerr << "Mode not implemented" << std::endl;
return;
}
int K=D.n();
int M=X.n();
alpha.resize(K,M);
if (!D.isNormalized()) {
cerr << "Current implementation of IST does not support non-normalized dictionaries" << endl;
return;
}
/// compute the Gram Matrix G=D'D
//CachedProdMatrix<T> G(D, K < 20000 && M*K/10 > K);
//ProdMatrix<T> G(D, K < 20000 && M*K/10 > K);
Matrix<T> G;
D.XtX(G);
// for (int i = 0; i<K; ++i) G[i*K+i] += 1e-6;
G.addDiag(1e-12);
ProdMatrix<T> DtX(D,X,false);
int NUM_THREADS=init_omp(numThreads);
Vector<T>* DtRT= new Vector<T>[NUM_THREADS];
SpVector<T>* spAlphaT= new SpVector<T>[NUM_THREADS];
for (int i = 0; i<NUM_THREADS; ++i) {
DtRT[i].resize(K);
spAlphaT[i].resize(K);
};
int i;
#pragma omp parallel for private(i)
for (i = 0; i< M; ++i) {
#ifdef _OPENMP
int numT=omp_get_thread_num();
#else
int numT=0;
#endif
Vector<T> coeffs;
alpha.refCol(i,coeffs);
Vector<T>& DtR=DtRT[numT];
SpVector<T>& spAlpha=spAlphaT[numT];
T norm1 = coeffs.asum();
// Compute DtR
DtX.copyCol(i,DtR);
Vector<T> Xi;
X.refCol(i,Xi);
T normX2 = Xi.nrm2sq();
if (norm1 > EPSILON) {
coeffs.toSparse(spAlpha);
G.mult(spAlpha,DtR,-1.0,1.0);
}
if (mode == PENALTY) {
coreIST(G,DtR,coeffs,lambda,itermax,tol);
} else {
coreISTconstrained(G,DtR,coeffs,normX2,lambda,itermax,tol);
}
}
delete[](DtRT);
delete[](spAlphaT);
}
template <typename T>
inline void coreIST(const AbstractMatrix<T>& G, Vector<T>& DtRv, Vector<T>& coeffsv,
const T thrs, const int itermax,
const T tol) {
const int K = G.n();
T* const coeffs = coeffsv.rawX();
T* const DtR = DtRv.rawX();
// T* const prG = G.rawX();
const T lambda_init=thrs;
T maxDtR = DtRv.fmaxval();
T norm1=coeffsv.asum();
T lambda=lambda_init;
vAdd(K,DtR,coeffs,DtR);
for (int iter=0; iter < itermax; ++iter) {
for (int j = 0; j <K; ++j) {
if (DtR[j] > lambda) {
T diff=coeffs[j];
coeffs[j]=DtR[j]-lambda;
diff-=coeffs[j];
DtR[j]-=diff;
G.add_rawCol(j,DtR,diff);
//cblas_axpy(K,diff,prG+j*K,1,DtR,1);
} else if (DtR[j] < -lambda) {
T diff=coeffs[j];
coeffs[j]=DtR[j]+lambda;
diff-=coeffs[j];
DtR[j]-=diff;
G.add_rawCol(j,DtR,diff);
//cblas_axpy(K,diff,prG+j*K,1,DtR,1);
} else if (coeffs[j]) {
T diff=coeffs[j];
coeffs[j]=T();
DtR[j]-=diff;
G.add_rawCol(j,DtR,diff);
//cblas_axpy(K,diff,prG+j*K,1,DtR,1);
}
}
if (iter % 5 == 1) {
vSub(K,DtR,coeffs,DtR);
maxDtR = DtRv.fmaxval();
norm1 =T();
T DtRa = T();
for (int j = 0; j<K; ++j) {
if (coeffs[j]) {
norm1 += abs(coeffs[j]);
DtRa += DtR[j]*coeffs[j];
}
}
vAdd(K,DtR,coeffs,DtR);
const T kappa = -DtRa+norm1*maxDtR;
if (abs(lambda - maxDtR) < tol && kappa <= tol)
break;
}
}
}
/// coreIST constrained
template <typename T>
void coreISTconstrained(const AbstractMatrix<T>& G, Vector<T>& DtRv, Vector<T>&
coeffsv, const T normX2, const T eps, const int itermax, const T tol) {
const int K = G.n();
T* const coeffs = coeffsv.rawX();
T* const DtR = DtRv.rawX();
// T* const prG = G.rawX();
T err = normX2;
T norm1 = coeffsv.asum();
if (!norm1 && err <= eps) return;
T current_tol = 10.0*tol;
T maxDtR = DtRv.fmaxval();
T lambda = maxDtR;
T lambdasq= lambda*lambda;
if (!norm1) {
lambdasq *= eps/err;
lambda=sqrt(lambdasq);
}
Vector<int> indices(K);
indices.set(-1);
int* const pr_indices=indices.rawX();
int count;
for (int iter=0; iter < itermax; ++iter) {
count=0;
T old_err = err;
for (int j = 0; j <K; ++j) {
// Soft-thresholding
T old_coeff = coeffs[j];
T diff = DtR[j]+old_coeff;
if (diff > lambda) {
coeffs[j] = diff - lambda;
err+=lambdasq-DtR[j]*DtR[j];
pr_indices[count++]=j;
} else if (diff < - lambda) {
coeffs[j] = diff + lambda;
err+=lambdasq-DtR[j]*DtR[j];
pr_indices[count++]=j;
} else {
coeffs[j]=T();
if (old_coeff) {
err+=diff*diff-DtR[j]*DtR[j];
}
}
// Update DtR
diff = old_coeff-coeffs[j];
if (diff) {
G.add_rawCol(j,DtR,diff);
//cblas_axpy<T>(K,old_coeff-coeffs[j],prG+j*K,1,DtR,1);
}
}
maxDtR = DtRv.fmaxval();
norm1 =T();
T DtRa = T();
for (int j = 0; j<count; ++j) {
const int ind = pr_indices[j];
norm1 += abs(coeffs[ind]);
DtRa += DtR[ind]*coeffs[ind];
}
if (norm1-DtRa/maxDtR <= current_tol) {
const bool change = ((old_err > eps) && err < eps+current_tol) ||
(old_err < eps && err > eps-current_tol);
if (change) {
if (current_tol == tol) {
break;
} else {
current_tol = MAX(current_tol*0.5,tol);
}
}
lambdasq *= eps/err;
lambda=sqrt(lambdasq);
}
}
};
/// ist for group Lasso
template <typename T>
void ist_groupLasso(const Matrix<T>* XT, const Matrix<T>& D,
Matrix<T>* alphaT, const int Ngroups,
const T lambda, const constraint_type mode,
const int itermax,
const T tol, const int numThreads) {
int K=D.n();
int n = D.m();
if (!D.isNormalized()) {
cerr << "Current implementation of block coordinate descent does not support non-normalized dictionaries" << endl;
return;
}
if (mode == L1COEFFS) {
std::cerr << "Mode not implemented" << std::endl;
return;
}
/// compute the Gram Matrix G=D'D
Matrix<T> G;
D.XtX(G);
int NUM_THREADS=init_omp(numThreads);
Matrix<T>* RtDT = new Matrix<T>[NUM_THREADS];
Matrix<T>* alphatT = new Matrix<T>[NUM_THREADS];
int i;
#pragma omp parallel for private(i)
for (i = 0; i< Ngroups; ++i) {
#ifdef _OPENMP
int numT=omp_get_thread_num();
#else
int numT=0;
#endif
const Matrix<T>& X = XT[i];
int M = X.n();
Matrix<T>& alphat = alphatT[numT];
alphaT[i].transpose(alphat);
Matrix<T>& RtD = RtDT[numT];
X.mult(D,RtD,true,false);
Vector<T> col, col2;
T norm1 = alphat.asum();
T normX2;
if (!norm1) {
Vector<T> DtR_mean(K);
Vector<T> coeffs_mean(K);
coeffs_mean.setZeros();
RtD.meanRow(DtR_mean);
coeffs_mean.setZeros();
if (mode == PENALTY) {
coreIST(G,DtR_mean,coeffs_mean,lambda/T(2.0),itermax,tol);
} else {
Vector<T> meanVec(n);
X.meanCol(meanVec);
normX2=meanVec.nrm2sq();
coreISTconstrained(G,DtR_mean,coeffs_mean,normX2,
lambda,itermax,tol);
SpVector<T> spalpha(K);
normX2-=computeError(normX2,G,DtR_mean,coeffs_mean,spalpha);
normX2=X.normFsq()-M*normX2;
}
alphat.fillRow(coeffs_mean);
}
if (M > 1) {
for (int j = 0; j<K; ++j) {
alphat.refCol(j,col);
const T nrm=col.nrm2sq();
if (nrm) {
G.refCol(j,col2);
RtD.rank1Update(col,col2,T(-1.0));
}
}
if (mode == PENALTY) {
coreGroupIST(G,RtD,alphat,sqr<T>(M)*lambda/T(2.0),itermax,sqr<T>(M)*tol);
} else {
coreGroupISTConstrained(G,RtD,alphat,normX2,M*lambda,itermax,sqr<T>(M)*tol);
}
}
alphat.transpose(alphaT[i]);
}
delete[](RtDT);
delete[](alphatT);
};
template <typename T>
void coreGroupIST(const Matrix<T>& G, Matrix<T>& RtDm,
Matrix<T>& coeffsm,
const T thrs,
const int itermax,
const T tol) {
const int K = G.n();
const int M = RtDm.m();
T* const prG = G.rawX();
T* const RtD = RtDm.rawX();
T* const coeffs = coeffsm.rawX();
const T lambda_init=thrs;
T lambda=lambda_init;
Vector<T> old_coeffv(M);
T* const old_coeff = old_coeffv.rawX();
Vector<T> normsv(K);
T* const norms = normsv.rawX();
coeffsm.norm_2_cols(normsv);
Vector<T> normRtDv(K);
Vector<int> activatev(K);
activatev.set(3);
int* const activate=activatev.rawX();
for (int iter=0; iter < itermax; ++iter) {
for (int j = 0; j <K; ++j) {
if (activate[j] >= 0) {
if (norms[j]) {
cblas_copy(M,coeffs+j*M,1,old_coeff,1);
vAdd(M,coeffs+j*M,RtD+j*M,coeffs+j*M);
const T nrm = cblas_nrm2(M,coeffs+j*M,1);
if (nrm > lambda) {
norms[j]=nrm-lambda;
cblas_scal(M,norms[j]/nrm,coeffs+j*M,1);
vSub(M,old_coeff,coeffs+j*M,old_coeff);
cblas_ger(CblasColMajor,M,K,T(1.0),old_coeff,1,prG+j*K,1,RtD,M);
activate[j]=5;
} else {
memset(coeffs+j*M,0,M*sizeof(T));
norms[j]=T();
cblas_ger(CblasColMajor,M,K,T(1.0),old_coeff,1,prG+j*K,1,RtD,M);
--activate[j];
}
} else {
cblas_copy(M,RtD+j*M,1,old_coeff,1);
const T nrm = cblas_nrm2(M,old_coeff,1);
if (nrm > lambda) {
norms[j]=nrm-lambda;
cblas_copy(M,old_coeff,1,coeffs+j*M,1);
cblas_scal(M,norms[j]/nrm,coeffs+j*M,1);
cblas_ger(CblasColMajor,M,K,T(-1.0),coeffs+j*M,1,prG+j*K,1,RtD,M);
activate[j]=5;
} else {
activate[j] = (activate[j] == 0) ? -10 : activate[j]-1;
}
}
} else {
++activate[j];
}
}
if (iter % 5 == 4) {
T norm1=normsv.asum();
RtDm.norm_2sq_cols(normRtDv);
T maxDtR = sqr(normRtDv.maxval());
T DtRa=T();
for (int j = 0; j<K; ++j) {
if (norms[j]) {
DtRa += cblas_dot(M,coeffs+j*M,1,RtD+j*M,1);
}
}
if ((maxDtR - lambda) < (tol*maxDtR/norm1) && norm1-DtRa/maxDtR < tol) break;
}
}
};
/// Auxiliary function for ist_groupLasso
template <typename T>
void coreGroupISTConstrained(const Matrix<T>& G, Matrix<T>& RtDm,
Matrix<T>& coeffsm, const T normR,
const T eps,
const int itermax,
const T tol) {
const int K = G.n();
const int M = RtDm.m();
T* const prG = G.rawX();
T* const RtD = RtDm.rawX();
T* const coeffs = coeffsm.rawX();
T err = normR;
Vector<T> old_coeffv(M);
T* const old_coeff = old_coeffv.rawX();
Vector<T> normsv(K);
T* const norms = normsv.rawX();
coeffsm.norm_2_cols(normsv);
Vector<T> normRtDv(K);
RtDm.norm_2sq_cols(normRtDv);
Vector<int> activatev(K);
activatev.set(3);
int* const activate=activatev.rawX();
T norm1 = normsv.sum();
if (!norm1 && err <= eps) return;
T current_tol = 10.0*tol;
T maxDtR = sqr(normRtDv.maxval());
T lambda = maxDtR;
T lambdasq= lambda*lambda;
if (!norm1) {
lambdasq *= eps/err;
lambda=sqrt(lambdasq);
}
for (int iter=0; iter < itermax; ++iter) {
T old_err = err;
for (int j = 0; j <K; ++j) {
if (activate[j] >= 0) {
if (norms[j]) {
cblas_copy(M,coeffs+j*M,1,old_coeff,1);
vAdd(M,coeffs+j*M,RtD+j*M,coeffs+j*M);
const T nrm = cblas_nrm2(M,coeffs+j*M,1);
if (nrm > lambda) {
norms[j]=nrm-lambda;
cblas_scal(M,norms[j]/nrm,coeffs+j*M,1);
vSub(M,old_coeff,coeffs+j*M,old_coeff);
err += cblas_dot(M,old_coeff,1,old_coeff,1)
+2*cblas_dot(M,old_coeff,1,RtD+j*M,1);
cblas_ger(CblasColMajor,M,K,T(1.0),old_coeff,1,prG+j*K,1,RtD,M);
activate[j]=3;
} else {
memset(coeffs+j*M,0,M*sizeof(T));
norms[j]=T();
err += cblas_dot(M,old_coeff,1,old_coeff,1)
+2*cblas_dot(M,old_coeff,1,RtD+j*M,1);
cblas_ger(CblasColMajor,M,K,T(1.0),old_coeff,1,prG+j*K,1,RtD,M);
--activate[j];
}
} else {
cblas_copy(M,RtD+j*M,1,old_coeff,1);
const T nrm = cblas_nrm2(M,old_coeff,1);
if (nrm > lambda) {
norms[j]=nrm-lambda;
cblas_copy(M,old_coeff,1,coeffs+j*M,1);
cblas_scal(M,norms[j]/nrm,coeffs+j*M,1);
err += cblas_dot(M,coeffs+j*M,1,coeffs+j*M,1)
-2*cblas_dot(M,coeffs+j*M,1,RtD+j*M,1);
cblas_ger(CblasColMajor,M,K,T(-1.0),coeffs+j*M,1,prG+j*K,1,RtD,M);
activate[j]=3;
} else {
activate[j] = (activate[j] == 0) ? -3 : activate[j]-1;
}
}
} else {
++activate[j];
}
}
norm1 = normsv.sum();
RtDm.norm_2sq_cols(normRtDv);
maxDtR = sqr(normRtDv.maxval());
T DtRa=T();
for (int j = 0; j<K; ++j) {
if (norms[j]) {
DtRa += cblas_dot(M,coeffs+j*M,1,RtD+j*M,1);
}
}
if (norm1-DtRa/maxDtR <= current_tol) {
const T tol_bis=current_tol*maxDtR;
const bool change = ((old_err > eps) && err < eps+tol_bis) ||
(old_err < eps && err > eps-tol_bis);
if (change) {
if (current_tol == tol) {
break;
} else {
current_tol = MAX(current_tol*0.5,tol);
}
}
lambdasq *= eps/err;
lambda=sqrt(lambdasq);
}
}
};
/// auxiliary function for ist_groupLasso
template <typename T>
T computeError(const T normX2,const Vector<T>& norms,
const Matrix<T>& G,const Matrix<T>& RtD,const Matrix<T>& alphat) {
T err2 = normX2;
Vector<T> col,col2;
for (int j = 0; j<G.n(); ++j) {
if (norms[j] > EPSILON) {
alphat.refCol(j,col);
RtD.refCol(j,col2);
err2 -= 2*col.dot(col2);
T add = 0.0;
for (int k = 0; k<j; ++k) {
if (norms[k] > EPSILON) {
alphat.refCol(k,col2);
add -= G(j,k)*col.dot(col2);
}
}
add += add - G(j,j)*col.nrm2sq();
err2 += add;
}
}
return err2;
}
/// auxiliary function for
template <typename T>
T computeError(const T normX2,
const Matrix<T>& G,const Vector<T>& DtR,const Vector<T>& coeffs,
SpVector<T>& spAlpha) {
coeffs.toSparse(spAlpha);
return normX2 -G.quad(spAlpha)-2*DtR.dot(spAlpha);
};
/* ******************
* Simultaneous OMP
* *****************/
template <typename T>
void somp(const Matrix<T>* X, const Matrix<T>& D, SpMatrix<T>* spalpha,
const int Ngroups, const int L, const T eps,const int numThreads) {
somp(X,D,spalpha,Ngroups,L,&eps,false,numThreads);
}
template <typename T>
void somp(const Matrix<T>* XT, const Matrix<T>& D, SpMatrix<T>* spalphaT,
const int Ngroups, const int LL, const T* eps, const bool adapt,
const int numThreads) {
if (LL <= 0) return;
const int K = D.n();
const int L = MIN(D.m(),MIN(LL,K));
if (!D.isNormalized()) {
cerr << "Current implementation of OMP does not support non-normalized dictionaries" << endl;
return;
}
/// compute the Gram Matrix G=D'D
Matrix<T> G;
D.XtX(G);
int NUM_THREADS=init_omp(numThreads);
int i;
#pragma omp parallel for private(i)
for (i = 0; i< Ngroups; ++i) {
const Matrix<T>& X = XT[i];
const int M = X.n();
SpMatrix<T>& spalpha = spalphaT[i];
spalpha.clear();
Vector<int> rv;
Matrix<T> vM;
T thrs = adapt ? eps[i] : M*(*eps);
coreSOMP(X,D,G,vM,rv,L,thrs);
spalpha.convert2(vM,rv,K);
}
}
template <typename T>
void coreSOMP(const Matrix<T>& X, const Matrix<T>& D, const Matrix<T>& G,
Matrix<T>& v,
Vector<int>& r, const int L, const T eps) {
const int K = G.n();
const int n = D.m();
const int M = X.n();
const bool big_mode = M*K*(n+L) > 2*(M*n*n+K*n*(n+L));
r.resize(L);
r.set(-1);
v.resize(0,X.n());
if (M == 1) {
Vector<T> scores(K);
Vector<T> norm(K);
Vector<T> tmp(K);
Matrix<T> Un(L,L);
Un.setZeros();
Matrix<T> Undn(K,L);
Matrix<T> Unds(L,L);
Matrix<T> Gs(K,L);
Vector<T> Rdn(K);
Vector<T> Xt(X.rawX(),n);
D.multTrans(Xt,Rdn);
Vector<T> RUn(L);
T normX = Xt.nrm2sq();
T lambda=0;
coreORMP(scores,norm,tmp,Un,Undn,Unds,Gs,Rdn,G,r,RUn,normX,&eps,&L,&lambda);
int count=0;
for (int i = 0; i<L; ++i) {
if (r[i] == -1) break;
++count;
}
v.resize(count,X.n());
Vector<T> v1(v.rawX(),count);
Vector<T> v2(RUn.rawX(),count);
v1.copy(v2);
return;
}
Matrix<T> XXtD;
Matrix<T> XtD;
T E;
if (big_mode) {
Matrix<T> XXt;
X.XXt(XXt);
E = XXt.trace();
if (E < eps) return;
XXt.mult(D,XXtD);
} else {
E=X.normFsq();
if (E < eps) return;
X.mult(D,XtD,true);
}
Matrix<T> A(K,L);
A.setZeros();
Matrix<T> B(L,K);
B.setZeros();
Matrix<T> S(L,L);
S.setZeros();
Matrix<T> Fs(K,L);
Fs.setZeros();
Matrix<T> Gs(K,L);
Gs.setZeros();
Matrix<T> As(L,L);
As.setZeros();
Vector<T> tmp(K);
Vector<T> e(K);
G.diag(e);
Vector<T> f(K);
if (big_mode) {
for (int i = 0; i<K; ++i) {
Vector<T> di;
D.refCol(i,di);
Vector<T> di2;
XXtD.refCol(i,di2);
f[i]=di.dot(di2);
}
} else {
XtD.norm_2sq_cols(f);
}
Vector<T> c(L);
c.setZeros();
Vector<T> scores(K);
/// permit unsafe fast low level accesses
T* const prAs = As.rawX();
T* const prA = A.rawX();
T* const prS = S.rawX();
T* const prGs = Gs.rawX();
T* const prFs = Fs.rawX();
T* const prB = B.rawX();
T* const pr_c = c.rawX();
T* const pr_tmp = tmp.rawX();
int j;
for (j = 0; j<L; ++j) {
scores.copy(f);
scores.div(e);
for (int k = 0; k<j; ++k) scores[r[k]]=-1.0;
const int currentInd = scores.max();
const T invNorm=T(1.0)/sqrt(e[currentInd]);
if (invNorm > 1e3) {
j=j-1;
break;
}
r[j]=currentInd;
E -= scores[currentInd];
for (int k = 0; k<j; ++k) prS[j*L+k]=T();
prS[j*L+j]=T(1.0);
for (int k = 0; k<j; ++k) prAs[k*L+j]=prA[k*K+currentInd];
/// Cholesky update with partial reorthogonalization
int iter = invNorm > 1.41 ? 2 : 1;
for (int k = 0; k<iter; ++k) {
for (int l = 0; l<j; ++l) {
T scal = -cblas_dot<T>(j-l+1,prAs+l*L+l,1,prS+j*L+l,1);
cblas_axpy<T>(l+1,scal,prS+l*L,1,prS+j*L,1);
}
}
cblas_scal<T>(j+1,invNorm,prS+j*L,1);
if (j == L-1 || E <= eps) {
++j;
break;
}
/// Update e,f,scores,A,B,As,Bs,Fs,Gs,S,c
/// Gs,S,A,As, e, Fs, B,c
Vector<T> Gsj;
Gs.refCol(j,Gsj);
G.copyCol(currentInd,Gsj);
cblas_gemv<T>(CblasColMajor,CblasNoTrans,K,j+1,T(1.0),prGs,K,prS+j*L,1,
T(0.0),prA+j*K,1);
prAs[j*L+j]=prA[j*K+currentInd];
Vector<T> Aj;
A.refCol(j,Aj);
tmp.sqr(Aj);
e.sub(tmp);
Vector<T> Fsj;
Fs.refCol(j,Fsj);
if (big_mode) {
Vector<T> di;
D.refCol(currentInd,di);
XXtD.multTrans(di,Fsj);
} else {
Vector<T> di;
XtD.refCol(currentInd,di);
XtD.multTrans(di,Fsj);
}
cblas_gemv<T>(CblasColMajor,CblasNoTrans,K,j+1,T(1.0),prFs,K,prS+j*L,1,
T(0.0),prB+j,L);
for (int k = 0; k<j;++k) pr_c[k]=T();
for (int k = 0; k<=j;++k)
cblas_axpy<T>(j,prS[j*L+k],prB+r[k]*L,1,pr_c,1);
f.add(tmp,f[currentInd]*invNorm*invNorm);
if (j > 0) {
cblas_gemv<T>(CblasColMajor,CblasNoTrans,K,j,T(1.0),prA,K,pr_c,1,
T(0.0),pr_tmp,1);
} else {
tmp.setZeros();
}
cblas_axpy<T>(K,T(-1.0),prB+j,L,pr_tmp,1);
tmp.mult(tmp,Aj);
f.add(tmp,T(2.0));
}
A.clear();
B.clear();
Fs.clear();
Gs.clear();
As.clear();
if (j == 0) return;
Matrix<T> SSt;
S.upperTriXXt(SSt,j);
Matrix<T> Dg(n,j);
for (int i = 0; i<j;++i) {
Vector<T> Dgi;
Dg.refCol(i,Dgi);
D.copyCol(r[i],Dgi);
}
Matrix<T> SStDt;
SSt.mult(Dg,SStDt,false,true);
SStDt.mult(X,v);
};
#endif // DECOMP_H
|
core_math.h | // == mojo ====================================================================
//
// Copyright (c) gnawice@gnawice.com. All rights reserved.
// See LICENSE in root folder
//
// 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.
//
// ============================================================================
// core_math.h: defines matrix class and math functions
// ==================================================================== mojo ==
#pragma once
#include <math.h>
#include <string.h>
#include <string>
#include <cstdlib>
#include <random>
#include <algorithm>
#include <immintrin.h>
namespace mojo
{
enum pad_type { zero = 0, edge = 1, median_edge = 2 };
inline float dot(const float *x1, const float *x2, const int size)
{
switch (size)
{
case 1: return x1[0] * x2[0];
case 2: return x1[0] * x2[0] + x1[1] * x2[1];
case 3: return x1[0] * x2[0] + x1[1] * x2[1] + x1[2] * x2[2];
case 4: return x1[0] * x2[0] + x1[1] * x2[1] + x1[2] * x2[2] + x1[3] * x2[3];
case 5: return x1[0] * x2[0] + x1[1] * x2[1] + x1[2] * x2[2] + x1[3] * x2[3] + x1[4] * x2[4];
default:
float v = 0;
for (int i = 0; i < size; i++) v += x1[i] * x2[i];
return v;
};
}
inline float unwrap_2d_dot(const float *x1, const float *x2, const int size, int stride1, int stride2)
{
float v = 0;
for (int j = 0; j < size; j++)
v += dot(&x1[stride1*j], &x2[stride2*j], size);
return v;
}
// second item is rotated 180 (this is a convolution)
inline float dot_rot180(const float *x1, const float *x2, const int size)
{
switch (size)
{
case 1: return x1[0] * x2[0];
case 2: return x1[0] * x2[1] + x1[1] * x2[0];
case 3: return x1[0] * x2[2] + x1[1] * x2[1] + x1[2] * x2[0];
case 4: return x1[0] * x2[3] + x1[1] * x2[2] + x1[2] * x2[1] + x1[3] * x2[0];
case 5: return x1[0] * x2[4] + x1[1] * x2[3] + x1[2] * x2[2] + x1[3] * x2[1] + x1[4] * x2[0];
default:
float v = 0;
for (int i = 0; i < size; i++) v += x1[i] * x2[size - i - 1];
return v;
};
}
inline float unwrap_2d_dot_rot180(const float *x1, const float *x2, const int size, int stride1, int stride2)
{
float v = 0;
for (int j = 0; j < size; j++)
{
v += dot_rot180(&x1[stride1*j], &x2[stride2*(size - j - 1)], size);
}
return v;
}
inline void unwrap_aligned_NxN(const int N, float *aligned_out, const float *in, const int in_size, const int stride = 1)
{
const int node_size = (in_size - N) / stride + 1;
int c1 = 0;
int off = 0;
const int inc_off = N * N * 8;
for (int j = 0; j < node_size; j += 1) // intput h
{
for (int i = 0; i < node_size; i += 1) // intput w
{
const float *tn = in + j * in_size + i;
if (N == 5)
{
for (int k = 0; k < 5; k++)
{
aligned_out[c1 + 0 + k * 40 + off] = tn[0 + 0 + in_size * k];
aligned_out[c1 + 8 + k * 40 + off] = tn[0 + 1 + in_size * k];
aligned_out[c1 + 16 + k * 40 + off] = tn[0 + 2 + in_size * k];
aligned_out[c1 + 24 + k * 40 + off] = tn[0 + 3 + in_size * k];
aligned_out[c1 + 32 + k * 40 + off] = tn[0 + 4 + in_size * k];
}
}
else if (N == 3)
{
aligned_out[c1 + off] = tn[0];
aligned_out[c1 + 8 + off] = tn[0 + 1];
aligned_out[c1 + 16 + off] = tn[0 + 2];
aligned_out[c1 + 24 + off] = tn[0 + in_size];
aligned_out[c1 + 32 + off] = tn[0 + 1 + in_size];
aligned_out[c1 + 40 + off] = tn[0 + 2 + in_size];
aligned_out[c1 + 48 + off] = tn[0 + 2 * in_size];
aligned_out[c1 + 56 + off] = tn[0 + 1 + 2 * in_size];
aligned_out[c1 + 64 + off] = tn[0 + 2 + 2 * in_size];
}
else
{
int cnt = 0;
for (int k = 0; k < N; k++)
{
for (int m = 0; m < N; m++)
{
aligned_out[c1 + cnt * 8 + off] = tn[0 + m + in_size * k];
cnt++;
}
}
}
off++;
if (off > 7) { off = 0; c1 += inc_off; }
}
}
}
inline void dotsum_unwrapped_NxN(const int N, const float *im, const float *filter_ptr, float *out, const int outsize)
{
const int NN = N * N;
for (int j = 0; j < outsize; j += 8)
{
float *c = out + j;
for (int i = 0; i < NN; i++)
{
const float f = filter_ptr[i];
c[0] += im[0] * f; c[1] += im[1] * f; c[2] += im[2] * f; c[3] += im[3] * f; c[4] += im[4] * f; c[5] += im[5] * f; c[6] += im[6] * f; c[7] += im[7] * f;
im += 8;
}
}
}
#ifdef MOJO_AVX
inline void dotsum_unwrapped_2x2(const float *_img, const float *filter_ptr, float *out, const int outsize)
{
_mm256_zeroupper();
const __m256 f0 = _mm256_broadcast_ss(&filter_ptr[0]); const __m256 f1 = _mm256_broadcast_ss(&filter_ptr[1]);
const __m256 f2 = _mm256_broadcast_ss(&filter_ptr[2]); const __m256 f3 = _mm256_broadcast_ss(&filter_ptr[3]);
for (int j = 0; j < outsize; j += 8)
{
__m256 a, c0, c1;
// multiply filter
a = _mm256_load_ps(_img); c0 = _mm256_mul_ps(a, f0);
a = _mm256_load_ps(_img + 8); c1 = _mm256_mul_ps(a, f1); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 16); c1 = _mm256_mul_ps(a, f2); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 24); c1 = _mm256_mul_ps(a, f3); c0 = _mm256_add_ps(c0, c1);
// add result to output
a = _mm256_load_ps(out + j);
c0 = _mm256_add_ps(c0, a);
_mm256_stream_ps(out + j, c0);
_img += 32;
}
_mm256_zeroupper();
}
inline void dotsum_unwrapped_3x3(const float *_img, const float *filter_ptr, float *out, const int outsize)
{
_mm256_zeroupper();
const __m256 f0 = _mm256_broadcast_ss(&filter_ptr[0]); const __m256 f1 = _mm256_broadcast_ss(&filter_ptr[1]);
const __m256 f2 = _mm256_broadcast_ss(&filter_ptr[2]); const __m256 f3 = _mm256_broadcast_ss(&filter_ptr[3]);
const __m256 f4 = _mm256_broadcast_ss(&filter_ptr[4]); const __m256 f5 = _mm256_broadcast_ss(&filter_ptr[5]);
const __m256 f6 = _mm256_broadcast_ss(&filter_ptr[6]); const __m256 f7 = _mm256_broadcast_ss(&filter_ptr[7]);
const __m256 f8 = _mm256_broadcast_ss(&filter_ptr[8]);
for (int j = 0; j < outsize; j += 8)//stride) // intput w
{
__m256 a, c0, c1;
// multiply filter
a = _mm256_load_ps(_img); c0 = _mm256_mul_ps(a, f0);
a = _mm256_load_ps(_img + 8); c1 = _mm256_mul_ps(a, f1); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 16); c1 = _mm256_mul_ps(a, f2); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 24); c1 = _mm256_mul_ps(a, f3); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 32); c1 = _mm256_mul_ps(a, f4); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 40); c1 = _mm256_mul_ps(a, f5); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 48); c1 = _mm256_mul_ps(a, f6); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 56); c1 = _mm256_mul_ps(a, f7); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 64); c1 = _mm256_mul_ps(a, f8); c0 = _mm256_add_ps(c0, c1);
// add result to output
a = _mm256_load_ps(out + j);
c0 = _mm256_add_ps(c0, a);
_mm256_stream_ps(out + j, c0);
_img += 72;
}
_mm256_zeroupper();
}
inline void dotsum_unwrapped_4x4(const float *_img, const float *filter_ptr, float *out, const int outsize)
{
_mm256_zeroupper();
const __m256 f0 = _mm256_broadcast_ss(&filter_ptr[0]); const __m256 f1 = _mm256_broadcast_ss(&filter_ptr[1]);
const __m256 f2 = _mm256_broadcast_ss(&filter_ptr[2]); const __m256 f3 = _mm256_broadcast_ss(&filter_ptr[3]);
const __m256 f4 = _mm256_broadcast_ss(&filter_ptr[4]); const __m256 f5 = _mm256_broadcast_ss(&filter_ptr[5]);
const __m256 f6 = _mm256_broadcast_ss(&filter_ptr[6]); const __m256 f7 = _mm256_broadcast_ss(&filter_ptr[7]);
const __m256 f8 = _mm256_broadcast_ss(&filter_ptr[8]); const __m256 f9 = _mm256_broadcast_ss(&filter_ptr[9]);
const __m256 f10 = _mm256_broadcast_ss(&filter_ptr[10]); const __m256 f11 = _mm256_broadcast_ss(&filter_ptr[11]);
const __m256 f12 = _mm256_broadcast_ss(&filter_ptr[12]); const __m256 f13 = _mm256_broadcast_ss(&filter_ptr[13]);
const __m256 f14 = _mm256_broadcast_ss(&filter_ptr[14]); const __m256 f15 = _mm256_broadcast_ss(&filter_ptr[15]);
for (int j = 0; j < outsize; j += 8)//stride) // intput w
{
__m256 a, c0, c1;
// multiply filter
a = _mm256_load_ps(_img); c0 = _mm256_mul_ps(a, f0);
a = _mm256_load_ps(_img + 8); c1 = _mm256_mul_ps(a, f1); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 16); c1 = _mm256_mul_ps(a, f2); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 24); c1 = _mm256_mul_ps(a, f3); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 32); c1 = _mm256_mul_ps(a, f4); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 40); c1 = _mm256_mul_ps(a, f5); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 48); c1 = _mm256_mul_ps(a, f6); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 56); c1 = _mm256_mul_ps(a, f7); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 64); c1 = _mm256_mul_ps(a, f8); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 72); c1 = _mm256_mul_ps(a, f9); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 80); c1 = _mm256_mul_ps(a, f10); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 88); c1 = _mm256_mul_ps(a, f11); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 96); c1 = _mm256_mul_ps(a, f12); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 104); c1 = _mm256_mul_ps(a, f13); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 112); c1 = _mm256_mul_ps(a, f14); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 120); c1 = _mm256_mul_ps(a, f15); c0 = _mm256_add_ps(c0, c1);
// add result to output
a = _mm256_load_ps(out + j);
c0 = _mm256_add_ps(c0, a);
_mm256_stream_ps(out + j, c0);
_img += 128;
}
_mm256_zeroupper();
}
inline void dotsum_unwrapped_5x5(const float *_img, const float *filter_ptr, float *out, const int outsize)
{
_mm256_zeroupper();
const __m256 f0 = _mm256_broadcast_ss(&filter_ptr[0]); const __m256 f1 = _mm256_broadcast_ss(&filter_ptr[1]);
const __m256 f2 = _mm256_broadcast_ss(&filter_ptr[2]); const __m256 f3 = _mm256_broadcast_ss(&filter_ptr[3]);
const __m256 f4 = _mm256_broadcast_ss(&filter_ptr[4]); const __m256 f5 = _mm256_broadcast_ss(&filter_ptr[5]);
const __m256 f6 = _mm256_broadcast_ss(&filter_ptr[6]); const __m256 f7 = _mm256_broadcast_ss(&filter_ptr[7]);
const __m256 f8 = _mm256_broadcast_ss(&filter_ptr[8]); const __m256 f9 = _mm256_broadcast_ss(&filter_ptr[9]);
const __m256 f10 = _mm256_broadcast_ss(&filter_ptr[10]); const __m256 f11 = _mm256_broadcast_ss(&filter_ptr[11]);
const __m256 f12 = _mm256_broadcast_ss(&filter_ptr[12]); const __m256 f13 = _mm256_broadcast_ss(&filter_ptr[13]);
const __m256 f14 = _mm256_broadcast_ss(&filter_ptr[14]); const __m256 f15 = _mm256_broadcast_ss(&filter_ptr[15]);
const __m256 f16 = _mm256_broadcast_ss(&filter_ptr[16]); const __m256 f17 = _mm256_broadcast_ss(&filter_ptr[17]);
const __m256 f18 = _mm256_broadcast_ss(&filter_ptr[18]); const __m256 f19 = _mm256_broadcast_ss(&filter_ptr[19]);
const __m256 f20 = _mm256_broadcast_ss(&filter_ptr[20]); const __m256 f21 = _mm256_broadcast_ss(&filter_ptr[21]);
const __m256 f22 = _mm256_broadcast_ss(&filter_ptr[22]); const __m256 f23 = _mm256_broadcast_ss(&filter_ptr[23]);
const __m256 f24 = _mm256_broadcast_ss(&filter_ptr[24]);
for (int j = 0; j < outsize; j += 8)
{
__m256 a, c0, c1;
a = _mm256_load_ps(_img); c0 = _mm256_mul_ps(a, f0);
a = _mm256_load_ps(_img + 8); c1 = _mm256_mul_ps(a, f1); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 16); c1 = _mm256_mul_ps(a, f2); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 24); c1 = _mm256_mul_ps(a, f3); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 32); c1 = _mm256_mul_ps(a, f4); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 40); c1 = _mm256_mul_ps(a, f5); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 48); c1 = _mm256_mul_ps(a, f6); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 56); c1 = _mm256_mul_ps(a, f7); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 64); c1 = _mm256_mul_ps(a, f8); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 72); c1 = _mm256_mul_ps(a, f9); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 80); c1 = _mm256_mul_ps(a, f10); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 88); c1 = _mm256_mul_ps(a, f11); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 96); c1 = _mm256_mul_ps(a, f12); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 104); c1 = _mm256_mul_ps(a, f13); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 112); c1 = _mm256_mul_ps(a, f14); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 120); c1 = _mm256_mul_ps(a, f15); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 128); c1 = _mm256_mul_ps(a, f16); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 136); c1 = _mm256_mul_ps(a, f17); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 144); c1 = _mm256_mul_ps(a, f18); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 152); c1 = _mm256_mul_ps(a, f19); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 160); c1 = _mm256_mul_ps(a, f20); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 168); c1 = _mm256_mul_ps(a, f21); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 176); c1 = _mm256_mul_ps(a, f22); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 184); c1 = _mm256_mul_ps(a, f23); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(_img + 192); c1 = _mm256_mul_ps(a, f24); c0 = _mm256_add_ps(c0, c1);
a = _mm256_load_ps(out + j);
c0 = _mm256_add_ps(c0, a);
_mm256_stream_ps(out + j, c0);
_img += 200;
}
_mm256_zeroupper();
}
inline void dotsum_unwrapped_7x7(const float *_img, const float *filter_ptr, float *out, const int outsize)
{
_mm256_zeroupper();
__m256 f[49];//=new __m256(s);
for (int i = 0; i < 49; i++) f[i] = _mm256_broadcast_ss(&filter_ptr[i]);
for (int j = 0; j < outsize; j += 8)
{
__m256 a, c0, c1;
a = _mm256_load_ps(_img);
c0 = _mm256_mul_ps(a, f[0]);
for (int i = 1; i < 49; i++)
{
a = _mm256_load_ps(_img + 8 * i); c1 = _mm256_mul_ps(a, f[i]); c0 = _mm256_add_ps(c0, c1);
}
a = _mm256_load_ps(out + j);
c0 = _mm256_add_ps(c0, a);
_mm256_stream_ps(out + j, c0);
_img += 49 * 8;
}
_mm256_zeroupper();
//delete [] f;
}
#else // no AVX
inline void dotsum_unwrapped_2x2(const float *_img, const float *filter_ptr, float *out, const int outsize)
{
dotsum_unwrapped_NxN(2, _img, filter_ptr, out, outsize);
}
inline void dotsum_unwrapped_3x3(const float *_img, const float *filter_ptr, float *out, const int outsize)
{
dotsum_unwrapped_NxN(3, _img, filter_ptr, out, outsize);
}
inline void dotsum_unwrapped_4x4(const float *_img, const float *filter_ptr, float *out, const int outsize)
{
dotsum_unwrapped_NxN(4, _img, filter_ptr, out, outsize);
}
inline void dotsum_unwrapped_5x5(const float *_img, const float *filter_ptr, float *out, const int outsize)
{
dotsum_unwrapped_NxN(5, _img, filter_ptr, out, outsize);
}
inline void dotsum_unwrapped_7x7(const float *_img, const float *filter_ptr, float *out, const int outsize)
{
dotsum_unwrapped_NxN(7, _img, filter_ptr, out, outsize);
}
#endif
// matrix class ---------------------------------------------------
// should use opencv if available
//
class matrix
{
int _size;
int _capacity;
float *_x_mem;
void delete_x() { delete[] _x_mem; x = NULL; _x_mem = NULL; }
// 4 extra for alignment and 4 for 3 padding for SSE
//float *new_x(const int size) { _x_mem = new float[size + 4+3]; x = (float *)(((uintptr_t)_x_mem + 16) & ~(uintptr_t)0x0F); return x; }
// avx mem aligment
float *new_x(const int size) { _x_mem = new float[size + 8 + 7]; x = (float *)(((uintptr_t)_x_mem + 32) & ~(uintptr_t)0x1F); return x; }
public:
std::string _name;
int cols, rows, chans;
int chan_stride;
int chan_aligned;
float *x;
// size must be divisible by 8 for AVX
virtual int calc_chan_stride(int w, int h)
{
if (chan_aligned)
{
int s = w * h;
const int remainder = s % 8;
if (remainder > 0) s += 8 - remainder;
return s;
}
else return w * h;
}
matrix() : cols(0), rows(0), chans(0), _size(0), _capacity(0), chan_stride(0), x(NULL), chan_aligned(0)/*, empty_chan(NULL)*/ {}
matrix(int _w, int _h, int _c = 1, const float *data = NULL, int align_chan = 0) : cols(_w), rows(_h), chans(_c)
{
chan_aligned = align_chan;
chan_stride = calc_chan_stride(cols, rows);
_size = chan_stride * chans; _capacity = _size; x = new_x(_size);
if (data != NULL) memcpy(x, data, _size * sizeof(float));
}
// copy constructor - deep copy
matrix(const matrix &m) : cols(m.cols), rows(m.rows), chan_aligned(m.chan_aligned), chans(m.chans), chan_stride(m.chan_stride), _size(m._size), _capacity(m._size) { x = new_x(_size); memcpy(x, m.x, sizeof(float)*_size); /*empty_chan = new unsigned char[chans]; memcpy(empty_chan, m.empty_chan, chans);*/ } // { v=m.v; x=(float*)v.data();}
// copy and pad constructor
matrix(const matrix &m, int pad_cols, int pad_rows, mojo::pad_type padding = mojo::zero, int threads = 1) : cols(m.cols), rows(m.rows), chans(m.chans), chan_aligned(m.chan_aligned), chan_stride(m.chan_stride), _size(m._size), _capacity(m._size)
{
x = new_x(_size); memcpy(x, m.x, sizeof(float)*_size);
*this = pad(pad_cols, pad_rows, padding, threads);
}
~matrix() { if (x) delete_x(); }
matrix get_chans(int start_channel, int num_chans = 1) const
{
return matrix(cols, rows, num_chans, &x[start_channel*chan_stride]);
}
// if edge_pad==0, then the padded area is just 0.
// if edge_pad==1 it fills with edge pixel colors
// if edge_pad==2 it fills with median edge pixel color
matrix pad(int dx, int dy, mojo::pad_type edge_pad = mojo::zero, int threads = 1) const
{
return pad(dx, dy, dx, dy, edge_pad, threads);
}
matrix pad(int dx, int dy, int dx_right, int dy_bottom, mojo::pad_type edge_pad = mojo::zero, int threads = 1) const
{
matrix v(cols + dx + dx_right, rows + dy + dy_bottom, chans);//,NULL,this->chan_aligned);
v.fill(0);
//float *new_x = new float[chans*w*h];
#pragma omp parallel for num_threads(threads)
for (int k = 0; k < chans; k++)
{
const int v_chan_offset = k * v.chan_stride;
const int chan_offset = k * chan_stride;
// find median color of perimeter
float median = 0.f;
if (edge_pad == mojo::median_edge)
{
int perimeter = 2 * (cols + rows - 2);
std::vector<float> d(perimeter);
for (int i = 0; i < cols; i++)
{
d[i] = x[i + chan_offset]; d[i + cols] = x[i + cols * (rows - 1) + chan_offset];
}
for (int i = 1; i < (rows - 1); i++)
{
d[i + cols * 2] = x[cols*i + chan_offset];
// file from back so i dont need to cal index
d[perimeter - i] = x[cols - 1 + cols * i + chan_offset];
}
std::nth_element(d.begin(), d.begin() + perimeter / 2, d.end());
median = d[perimeter / 2];
//for (int i = 0; i < v.rows*v.cols; i++) v.x[v_chan_offset + i] = solid_fill;
}
for (int j = 0; j < rows; j++)
{
memcpy(&v.x[dx + (j + dy)*v.cols + v_chan_offset], &x[j*cols + chan_offset], sizeof(float)*cols);
if (edge_pad == mojo::edge)
{
// do left/right side
for (int i = 0; i < dx; i++) v.x[i + (j + dy)*v.cols + v_chan_offset] = x[0 + j * cols + chan_offset];
for (int i = 0; i < dx_right; i++) v.x[i + dx + cols + (j + dy)*v.cols + v_chan_offset] = x[(cols - 1) + j * cols + chan_offset];
}
else if (edge_pad == mojo::median_edge)
{
for (int i = 0; i < dx; i++) v.x[i + (j + dy)*v.cols + v_chan_offset] = median;
for (int i = 0; i < dx_right; i++) v.x[i + dx + cols + (j + dy)*v.cols + v_chan_offset] = median;
}
}
// top bottom pad
if (edge_pad == mojo::edge)
{
for (int j = 0; j < dy; j++) memcpy(&v.x[(j)*v.cols + v_chan_offset], &v.x[(dy)*v.cols + v_chan_offset], sizeof(float)*v.cols);
for (int j = 0; j < dy_bottom; j++) memcpy(&v.x[(j + dy + rows)*v.cols + v_chan_offset], &v.x[(rows - 1 + dy)*v.cols + v_chan_offset], sizeof(float)*v.cols);
}
if (edge_pad == mojo::median_edge)
{
for (int j = 0; j < dy; j++)
for (int i = 0; i < v.cols; i++)
v.x[i + j * v.cols + v_chan_offset] = median;
for (int j = 0; j < dy_bottom; j++)
for (int i = 0; i < v.cols; i++)
v.x[i + (j + dy + rows)*v.cols + v_chan_offset] = median;
}
}
return v;
}
matrix crop(int dx, int dy, int w, int h, int threads = 1) const
{
matrix v(w, h, chans);
#pragma omp parallel for num_threads(threads)
for (int k = 0; k < chans; k++)
{
for (int j = 0; j < h; j++)
{
memcpy(&v.x[j*w + k * v.chan_stride], &x[dx + (j + dy)*cols + k * chan_stride], sizeof(float)*w);
}
}
return v;
}
mojo::matrix shift(int dx, int dy, mojo::pad_type edge_pad = mojo::zero)
{
int orig_cols = cols;
int orig_rows = rows;
int off_x = abs(dx);
int off_y = abs(dy);
mojo::matrix shifted = pad(off_x, off_y, edge_pad);
return shifted.crop(off_x - dx, off_y - dy, orig_cols, orig_rows);
}
mojo::matrix flip_cols()
{
mojo::matrix v(cols, rows, chans);
for (int k = 0; k < chans; k++)
for (int j = 0; j < rows; j++)
for (int i = 0; i < cols; i++)
v.x[i + j * cols + k * chan_stride] = x[(cols - i - 1) + j * cols + k * chan_stride];
return v;
}
mojo::matrix flip_rows()
{
mojo::matrix v(cols, rows, chans);
for (int k = 0; k < chans; k++)
for (int j = 0; j < rows; j++)
memcpy(&v.x[(rows - 1 - j)*cols + k * chan_stride], &x[j*cols + k * chan_stride], cols * sizeof(float));
return v;
}
void clip(float min, float max)
{
int s = chan_stride * chans;
for (int i = 0; i < s; i++)
{
if (x[i] < min) x[i] = min;
if (x[i] > max) x[i] = max;
}
}
void min_max(float *min, float *max, int *min_i = NULL, int *max_i = NULL)
{
int s = rows * cols;
int mini = 0;
int maxi = 0;
for (int c = 0; c < chans; c++)
{
const int t = chan_stride * c;
for (int i = t; i < t + s; i++)
{
if (x[i] < x[mini]) mini = i;
if (x[i] > x[maxi]) maxi = i;
}
}
*min = x[mini];
*max = x[maxi];
if (min_i) *min_i = mini;
if (max_i) *max_i = maxi;
}
float mean()
{
const int s = rows * cols;
int cnt = 0;// channel*s;
float average = 0;
for (int c = 0; c < chans; c++)
{
const int t = chan_stride * c;
for (int i = 0; i < s; i++)
average += x[i + t];
}
average = average / (float)(s*chans);
return average;
}
float remove_mean(int channel)
{
int s = rows * cols;
int offset = channel * chan_stride;
float average = 0;
for (int i = 0; i < s; i++) average += x[i + offset];
average = average / (float)s;
for (int i = 0; i < s; i++) x[i + offset] -= average;
return average;
}
float remove_mean()
{
float m = mean();
int s = chan_stride * chans;
//int offset = channel*s;
for (int i = 0; i < s; i++) x[i] -= m;
return m;
}
void fill(float val) {
for (int i = 0; i < _size; i++) x[i] = val;
}
void fill_random_uniform(float range)
{
std::mt19937 gen(0);
std::uniform_real_distribution<float> dst(-range, range);
for (int i = 0; i < _size; i++) x[i] = dst(gen);
}
void fill_random_normal(float std)
{
std::mt19937 gen(0);
std::normal_distribution<float> dst(0, std);
for (int i = 0; i < _size; i++) x[i] = dst(gen);
}
// deep copy
inline matrix& operator =(const matrix &m)
{
resize(m.cols, m.rows, m.chans, m.chan_aligned);
memcpy(x, m.x, sizeof(float)*_size);
// memcpy(empty_chan, m.empty_chan, chans);
return *this;
}
int size() const { return _size; }
void resize(int _w, int _h, int _c, int align_chans = 0) {
chan_aligned = align_chans;
int new_stride = calc_chan_stride(_w, _h);
int s = new_stride * _c;
if (s > _capacity)
{
if (_capacity > 0) delete_x(); _size = s; _capacity = _size; x = new_x(_size);
}
cols = _w; rows = _h; chans = _c; _size = s; chan_stride = new_stride;
}
// dot vector to 2d mat
inline matrix dot_1dx2d(const matrix &m_2d) const
{
mojo::matrix v(m_2d.rows, 1, 1);
for (int j = 0; j < m_2d.rows; j++) v.x[j] = dot(x, &m_2d.x[j*m_2d.cols], _size);
return v;
}
// +=
inline matrix& operator+=(const matrix &m2) {
for (int i = 0; i < _size; i++) x[i] += m2.x[i];
return *this;
}
// -=
inline matrix& operator-=(const matrix &m2) {
for (int i = 0; i < _size; i++) x[i] -= m2.x[i];
return *this;
}
#ifndef MOJO_AVX
// *= float
inline matrix operator *=(const float v) {
for (int i = 0; i < _size; i++) x[i] = x[i] * v;
return *this;
}
#else
inline matrix operator *=(const float v) {
__m128 b;
b = _mm_set_ps(v, v, v, v);
for (int j = 0; j < _size; j += 4)
_mm_store_ps(x + j, _mm_mul_ps(_mm_load_ps(x + j), b));
return *this;
}
#endif
// *= matrix
inline matrix operator *=(const matrix &v) {
for (int i = 0; i < _size; i++) x[i] = x[i] * v.x[i];
return *this;
}
inline matrix operator *(const matrix &v) {
matrix T(cols, rows, chans);
for (int i = 0; i < _size; i++) T.x[i] = x[i] * v.x[i];
return T;
}
// * float
inline matrix operator *(const float v) {
matrix T(cols, rows, chans);
for (int i = 0; i < _size; i++) T.x[i] = x[i] * v;
return T;
}
// + float
inline matrix operator +(const float v) {
matrix T(cols, rows, chans);
for (int i = 0; i < _size; i++) T.x[i] = x[i] + v;
return T;
}
// +
inline matrix operator +(matrix m2)
{
matrix T(cols, rows, chans);
for (int i = 0; i < _size; i++) T.x[i] = x[i] + m2.x[i];
return T;
}
};
}// namespace
|
3d7pt.c | /*
* Order-1, 3D 7 point stencil
* 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, 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]);
double ****A = (double ****) malloc(sizeof(double***)*2);
A[0] = (double ***) malloc(sizeof(double**)*Nz);
A[1] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[0][i] = (double**) malloc(sizeof(double*)*Ny);
A[1][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[0][i][j] = (double*) malloc(sizeof(double)*Nx);
A[1][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] = 32;
tile_size[1] = 32;
tile_size[2] = 4;
tile_size[3] = 32;
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;
const double alpha = 0.0876;
const double beta = 0.0765;
// 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);
}
}
}
#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-1; t++) {
for (i = 1; i < Nz-1; i++) {
for (j = 1; j < Ny-1; j++) {
for (k = 1; k < Nx-1; k++) {
A[(t+1)%2][i][j][k] = alpha * (A[t%2][i][j][k])
+ beta * (A[t%2][i - 1][j][k] + A[t%2][i][j - 1][k] + A[t%2][i][j][k - 1] +
A[t%2][i + 1][j][k] + A[t%2][i][j + 1][k] + A[t%2][i][j][k + 1]);
}
}
}
}
#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(1, "constant")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays (Causing performance degradation
/* 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]);
*/
return 0;
}
|
multind.c | /* Copyright 2013-2015 The Regents of the University of California.
* Copyright 2016-2018. Martin Uecker.
* Copyright 2017. Intel Corporation.
* All rights reserved. Use of this source code is governed by
* a BSD-style license which can be found in the LICENSE file.
*
* Authors:
* 2012-2018 Martin Uecker <martin.uecker@med.uni-goettingen.de>
* 2013 Frank Ong <frankong@berkeley.edu>
* 2017 Michael J. Anderson <michael.j.anderson@intel.com>
*
* Generic operations on multi-dimensional arrays. Most functions
* come in two flavours:
*
* 1. A basic version which takes the number of dimensions, an array
* of long integers specifing the size of each dimension, the pointers
* to the data, and the size of each element and other required parameters.
* The data is assumed to be stored in column-major format.
*
* 2. An extended version which takes an array of long integers which
* specifies the strides for each argument.
*
* All functions should work on CPU and GPU and md_copy can be used
* to copy between CPU and GPU.
*
*/
#define _GNU_SOURCE
#include <string.h>
#include <assert.h>
#include <stdbool.h>
#include <alloca.h>
#include <strings.h>
#include "misc/misc.h"
#include "misc/types.h"
#include "misc/debug.h"
#include "misc/nested.h"
#include "num/optimize.h"
#ifdef USE_CUDA
#include "num/gpuops.h"
#endif
#include "multind.h"
/**
* Generic functions which loops over all dimensions of a set of
* multi-dimensional arrays and calls a given function for each position.
*/
void md_nary(unsigned int C, unsigned int D, const long dim[D], const long* str[C], void* ptr[C], md_nary_fun_t fun)
{
if (0 == D) {
fun(ptr);
return;
}
for (long i = 0; i < dim[D - 1]; i++) {
void* moving_ptr[C];
for (unsigned int j = 0; j < C; j++)
moving_ptr[j] = ptr[j] + i * str[j][D - 1];
md_nary(C, D - 1, dim, str, moving_ptr, fun);
}
}
/**
* Generic functions which loops over all dimensions of a set of
* multi-dimensional arrays and calls a given function for each position.
* This functions tries to parallelize over the dimensions indicated
* with flags.
*/
void md_parallel_nary(unsigned int C, unsigned int D, const long dim[D], unsigned long flags, const long* str[C], void* ptr[C], md_nary_fun_t fun)
{
if (0 == flags) {
md_nary(C, D, dim, str, ptr, fun);
return;
}
long dimc[D];
md_select_dims(D, ~flags, dimc, dim);
// Collect all parallel dimensions
int nparallel = 0;
int parallel_b[D];
long parallel_dim[D];
long total_iterations = 1L;
while (0 != flags) {
int b = ffsl(flags & -flags) - 1;
assert(MD_IS_SET(flags, b));
flags = MD_CLEAR(flags, b);
debug_printf(DP_DEBUG4, "Parallelize: %d\n", dim[b]);
parallel_b[nparallel] = b;
parallel_dim[nparallel] = dim[b];
total_iterations *= parallel_dim[nparallel];
nparallel++;
}
#pragma omp parallel for
for (long i = 0; i < total_iterations; i++) {
// Recover place in parallel iteration space
long iter_i[D];
long ii = i;
for (int p = nparallel - 1; p >= 0; p--) {
iter_i[p] = ii % parallel_dim[p];
ii /= parallel_dim[p];
}
void* moving_ptr[C];
for (unsigned int j = 0; j < C; j++) {
moving_ptr[j] = ptr[j];
for(int p = 0; p < nparallel; p++)
moving_ptr[j] += iter_i[p] * str[j][parallel_b[p]];
}
md_nary(C, D, dimc, str, moving_ptr, fun);
}
}
static void md_parallel_loop_r(unsigned int D, unsigned int N, const long dim[static N], unsigned int flags, const long pos[static N], md_loop_fun_t fun)
{
if (0 == D) {
fun(pos);
return;
}
D--;
// we need to make a copy because firstprivate needs to see
// an array instead of a pointer
long pos_copy[N];
for (unsigned int i = 0; i < N; i++)
pos_copy[i] = pos[i];
#pragma omp parallel for firstprivate(pos_copy) if ((1 < dim[D]) && (flags & (1 << D)))
for (int i = 0; i < dim[D]; i++) {
pos_copy[D] = i;
md_parallel_loop_r(D, N, dim, flags, pos_copy, fun);
}
}
/**
* Generic function which loops over all dimensions and calls a given
* function passing the current indices as argument.
*
* Runs fun(data, position) for all position in dim
*
*/
void md_parallel_loop(unsigned int D, const long dim[static D], unsigned long flags, md_loop_fun_t fun)
{
long pos[D];
md_parallel_loop_r(D, D, dim, flags, pos, fun);
}
static void md_loop_r(unsigned int D, const long dim[D], long pos[D], md_loop_fun_t fun)
{
if (0 == D) {
fun(pos);
return;
}
D--;
for (pos[D] = 0; pos[D] < dim[D]; pos[D]++)
md_loop_r(D, dim, pos, fun);
}
/**
* Generic function which loops over all dimensions and calls a given
* function passing the current indices as argument.
*
* Runs fun( position ) for all position in dim
*
*/
void md_loop(unsigned int D, const long dim[D], md_loop_fun_t fun)
{
long pos[D];
md_loop_r(D, dim, pos, fun);
}
/**
* Computes the next position. Returns true until last index.
*/
bool md_next(unsigned int D, const long dims[D], unsigned long flags, long pos[D])
{
if (0 == D--)
return false;
if (md_next(D, dims, flags, pos))
return true;
if (MD_IS_SET(flags, D)) {
assert((0 <= pos[D]) && (pos[D] < dims[D]));
if (++pos[D] < dims[D])
return true;
pos[D] = 0;
}
return false;
}
/**
* Returns offset for position in a multidimensional array
*
* return pos[0]*strides[0] + ... + pos[D-1]*strides[D-1]
*
* @param D number of dimensions
* @param dim dimensions array
*/
long md_calc_offset(unsigned int D, const long strides[D], const long position[D])
{
long pos = 0;
for (unsigned int i = 0; i < D; i++)
pos += strides[i] * position[i];
return pos;
}
static long md_calc_size_r(unsigned int D, const long dim[D], size_t size)
{
if (0 == D)
return size;
return md_calc_size_r(D - 1, dim, size * dim[D - 1]);
}
/**
* Returns the number of elements
*
* return dim[0]*dim[1]*...*dim[D-1]
*
* @param D number of dimensions
* @param dim dimensions array
*/
long md_calc_size(unsigned int D, const long dim[D])
{
return md_calc_size_r(D, dim, 1);
}
/**
* Computes the number of smallest dimensions which are stored
* contineously, i.e. can be accessed as a block of memory.
*
*/
unsigned int md_calc_blockdim(unsigned int D, const long dim[D], const long str[D], size_t size)
{
long dist = size;
unsigned int i = 0;
for (i = 0; i < D; i++) {
if (!((str[i] == dist) || (dim[i] == 1)))
break;
dist *= dim[i];
}
return i;
}
/**
* Copy dimensions specified by flags and set remaining dimensions to 1
*
* odims = [ 1 idims[1] idims[2] 1 1 idims[5] ]
*
* @param D number of dimensions
* @param flags bitmask specifying which dimensions to copy
* @param odims output dimensions
* @param idims input dimensions
*/
void md_select_dims(unsigned int D, unsigned long flags, long odims[D], const long idims[D])
{
md_copy_dims(D, odims, idims);
for (unsigned int i = 0; i < D; i++)
if (!MD_IS_SET(flags, i))
odims[i] = 1;
}
/**
* Copy dimensions
*
* odims[i] = idims[i]
*/
void md_copy_dims(unsigned int D, long odims[D], const long idims[D])
{
memcpy(odims, idims, D * sizeof(long));
}
/**
* Copy strides
*
* ostrs[i] = istrs[i]
*/
void md_copy_strides(unsigned int D, long ostrs[D], const long istrs[D])
{
memcpy(ostrs, istrs, D * sizeof(long));
}
/**
* Set all dimensions to value
*
* dims[i] = val
*/
void md_set_dims(unsigned int D, long dims[D], long val)
{
for (unsigned int i = 0; i < D; i++)
dims[i] = val;
}
/**
* returns whether or not @param pos is a valid index of an array of dimension @param dims
*/
bool md_is_index(unsigned int D, const long pos[D], const long dims[D])
{
if (D == 0)
return true;
return ((pos[0] >= 0) && (pos[0] < dims[0]) && md_is_index(D - 1, pos + 1, dims + 1));
}
/**
* return whether some other dimensions are >1
*/
bool md_check_dimensions(unsigned int N, const long dims[N], unsigned int flags)
{
long d[N];
md_select_dims(N, ~flags, d, dims);
return (1 != md_calc_size(N, d));
}
/*
* compute non-trivial (> 1) dims
*/
unsigned long md_nontriv_dims(unsigned int D, const long dims[D])
{
unsigned long flags = 0;
for (unsigned int i = 0; i < D; i++)
if (dims[i] > 1)
flags = MD_SET(flags, i);
return flags;
}
/*
* compute non-trivial (!= 0) strides
*/
unsigned long md_nontriv_strides(unsigned int D, const long strs[D])
{
unsigned long flags = 0;
for (unsigned int i = 0; i < D; i++)
if (strs[i] != 0)
flags = MD_SET(flags, i);
return flags;
}
/**
* Set all dimensions to one
*
* dims[i] = 1
*/
void md_singleton_dims(unsigned int D, long dims[D])
{
for (unsigned int i = 0; i < D; i++)
dims[i] = 1;
}
/**
* Set all strides to one
*
* dims[i] = 1
*/
void md_singleton_strides(unsigned int D, long strs[D])
{
for (unsigned int i = 0; i < D; i++)
strs[i] = 0;
}
/**
* Check dimensions for compatibility. Dimensions must be equal or
* where indicated by a set bit in flags one must be equal to one
* in atleast one of the arguments.
*/
bool md_check_compat(unsigned int D, unsigned long flags, const long dim1[D], const long dim2[D])
{
if (0 == D)
return true;
D--;
if ((dim1[D] == dim2[D]) || (MD_IS_SET(flags, D) && ((1 == dim1[D]) || (1 == dim2[D]))))
return md_check_compat(D, flags, dim1, dim2);
return false;
}
void md_merge_dims(unsigned int N, long out_dims[N], const long dims1[N], const long dims2[N])
{
assert(md_check_compat(N, ~0, dims1, dims2));
for (unsigned int i = 0; i < N; i++)
out_dims[i] = (1 == dims1[i]) ? dims2[i] : dims1[i];
}
/**
* dim1 must be bounded by dim2 where a bit is set
*/
bool md_check_bounds(unsigned int D, unsigned long flags, const long dim1[D], const long dim2[D])
{
if (0 == D--)
return true;
if (!MD_IS_SET(flags, D) || (dim1[D] <= dim2[D]))
return md_check_bounds(D, flags, dim1, dim2);
return false;
}
/**
* Set the output's flagged dimensions to the minimum of the two input dimensions
*
* odims = [ MIN(idims1[0],idims2[0] ... MIN(idims1[D-1],idims2[D-1]) ]
*
* @param D number of dimensions
* @param flags bitmask specifying which dimensions to minimize
* @param odims output dimensions
* @param idims1 input 1 dimensions
* @param idims2 input 2 dimensions
*/
void md_min_dims(unsigned int D, unsigned long flags, long odims[D], const long idims1[D], const long idims2[D])
{
for (unsigned int i = 0; i < D; i++)
if (MD_IS_SET(flags, i))
odims[i] = MIN(idims1[i], idims2[i]);
}
/**
* Set the output's flagged dimensions to the maximum of the two input dimensions
*
* odims = [ MAX(idims1[0],idims2[0] ... MAX(idims1[D-1],idims2[D-1]) ]
*
* @param D number of dimensions
* @param flags bitmask specifying which dimensions to maximize
* @param odims output dimensions
* @param idims1 input 1 dimensions
* @param idims2 input 2 dimensions
*/
void md_max_dims(unsigned int D, unsigned long flags, long odims[D], const long idims1[D], const long idims2[D])
{
for (unsigned int i = 0; i < D; i++)
if (MD_IS_SET(flags, i))
odims[i] = MAX(idims1[i], idims2[i]);
}
/**
* Zero out array (with strides)
*
* ptr[i] = 0
*/
void md_clear2(unsigned int D, const long dim[D], const long str[D], void* ptr, size_t size)
{
const long (*nstr[1])[D] = { (const long (*)[D])str };
#ifdef USE_CUDA
bool use_gpu = cuda_ondevice(ptr);
#endif
unsigned long flags = 0;
for (unsigned int i = 0; i < D; i++)
if (0 == str[i])
flags |= MD_BIT(i);
long dim2[D];
md_select_dims(D, ~flags, dim2, dim);
NESTED(void, nary_clear, (struct nary_opt_data_s* opt_data, void* ptr[]))
{
size_t size2 = size * opt_data->size;
#ifdef USE_CUDA
if (use_gpu) {
cuda_clear(size2, ptr[0]);
return;
}
#endif
memset(ptr[0], 0, size2);
};
optimized_nop(1, MD_BIT(0), D, dim2, nstr, (void*[1]){ ptr }, (size_t[1]){ size }, nary_clear);
}
/**
* Calculate strides in column-major format
* (smallest index is sequential)
*
* @param D number of dimensions
* @param array of calculates strides
* @param dim array of dimensions
* @param size of a single element
*/
long* md_calc_strides(unsigned int D, long str[D], const long dim[D], size_t size)
{
long old = size;
for (unsigned int i = 0; i < D; i++) {
str[i] = (1 == dim[i]) ? 0 : old;
old *= dim[i];
}
return str;
}
/**
* Zero out array (without strides)
*
* ptr[i] = 0
*
* @param D number of dimensions
* @param dim dimensions array
* @param ptr pointer to data to clear
* @param size sizeof()
*/
void md_clear(unsigned int D, const long dim[D], void* ptr, size_t size)
{
md_clear2(D, dim, MD_STRIDES(D, dim, size), ptr, size);
}
/**
* Copy array (with strides)
*
* optr[i] = iptr[i]
*/
void md_copy2(unsigned int D, const long dim[D], const long ostr[D], void* optr, const long istr[D], const void* iptr, size_t size)
{
#if 0
// this is for a fun comparison between our copy engine and FFTW
extern void fft2(unsigned int D, const long dim[D], unsigned int flags,
const long ostr[D], void* optr, const long istr[D], const void* iptr);
if (sizeof(complex float) == size)
fft2(D, dim, 0, ostr, optr, istr, iptr);
#endif
#ifdef USE_CUDA
bool use_gpu = cuda_ondevice(optr) || cuda_ondevice(iptr);
#if 1
long tostr[D];
long tistr[D];
long tdims[D];
md_copy_strides(D, tostr, ostr);
md_copy_strides(D, tistr, istr);
md_copy_dims(D, tdims, dim);
long (*nstr2[2])[D] = { &tostr, &tistr };
int ND = optimize_dims(2, D, tdims, nstr2);
size_t sizes[2] = { size, size };
int skip = min_blockdim(2, ND, tdims, nstr2, sizes);
if (use_gpu && (ND - skip > 0)) {
void* nptr[2] = { optr, (void*)iptr };
long sizes[2] = { md_calc_size(skip, tdims) * size, tdims[skip] };
long ostr2 = (*nstr2[0])[skip];
long istr2 = (*nstr2[1])[skip];
skip++;
const long* nstr[2] = { *nstr2[0] + skip, *nstr2[1] + skip };
long* sizesp = sizes; // because of clang
NESTED(void, nary_strided_copy, (void* ptr[]))
{
// printf("CUDA 2D copy %ld %ld %ld %ld %ld %ld\n", data->sizes[0], data->sizes[1], data->ostr, data->istr, (long)ptr[0], (long)ptr[1]);
cuda_memcpy_strided(sizesp, ostr2, ptr[0], istr2, ptr[1]);
};
md_nary(2, ND - skip, tdims + skip , nstr, nptr, nary_strided_copy);
return;
}
#endif
#endif
const long (*nstr[2])[D] = { (const long (*)[D])ostr, (const long (*)[D])istr };
NESTED(void, nary_copy, (struct nary_opt_data_s* opt_data, void* ptr[]))
{
size_t size2 = size * opt_data->size;
#ifdef USE_CUDA
if (use_gpu) {
cuda_memcpy(size2, ptr[0], ptr[1]);
return;
}
#endif
memcpy(ptr[0], ptr[1], size2);
};
optimized_nop(2, MD_BIT(0), D, dim, nstr, (void*[2]){ optr, (void*)iptr }, (size_t[2]){ size, size }, nary_copy);
}
/**
* Copy array (without strides)
*
* optr[i] = iptr[i]
*/
void md_copy(unsigned int D, const long dim[D], void* optr, const void* iptr, size_t size)
{
long str[D];
md_calc_strides(D, str, dim, size);
md_copy2(D, dim, str, optr, str, iptr, size);
}
#ifdef USE_CUDA
// copied from flpmath.c
static void* gpu_constant(const void* vp, size_t size)
{
return md_gpu_move(1, (long[1]){ 1 }, vp, size);
}
#endif
/**
* Fill array with value pointed by pointer (with strides)
*
* ptr[i] = iptr[0]
*/
void md_fill2(unsigned int D, const long dim[D], const long str[D], void* ptr, const void* iptr, size_t size)
{
#ifdef USE_CUDA
if (cuda_ondevice(ptr) && (!cuda_ondevice(iptr))) {
void* giptr = gpu_constant(iptr, size);
md_fill2(D, dim, str, ptr, giptr, size);
md_free(giptr);
return;
}
#endif
long istr[D];
md_singleton_strides(D, istr);
md_copy2(D, dim, str, ptr, istr, iptr, size);
}
/**
* Fill array with value pointed by pointer (without strides)
*
* ptr[i] = iptr[0]
*/
void md_fill(unsigned int D, const long dim[D], void* ptr, const void* iptr, size_t size)
{
md_fill2(D, dim, MD_STRIDES(D, dim, size), ptr, iptr, size);
}
/**
* Swap values between a number of arrays (with strides)
*/
void md_circular_swap2(unsigned int M, unsigned int D, const long dims[D], const long* strs[M], void* ptr[M], size_t size)
{
size_t sizes[M];
for (unsigned int i = 0; i < M; i++)
sizes[i] = size;
const long (*nstrs[M])[D];
for (unsigned int i = 0; i < M; i++)
nstrs[i] = (const long (*)[D])strs[i];
NESTED(void, nary_swap, (struct nary_opt_data_s* opt_data, void* ptr[]))
{
size_t size2 = size * opt_data->size;
char* tmp = (size2 < 32) ? alloca(size2) : xmalloc(size2);
#ifdef USE_CUDA
assert(!cuda_ondevice(ptr[0]));
assert(!cuda_ondevice(ptr[1]));
#endif
memcpy(tmp, ptr[0], size2);
for (unsigned int i = 0; i < M - 1; i++)
memcpy(ptr[i], ptr[i + 1], size2);
memcpy(ptr[M - 1], tmp, size2);
if (size2 >= 32)
xfree(tmp);
};
optimized_nop(M, (1 << M) - 1, D, dims, nstrs, ptr, sizes, nary_swap);
}
/**
* Swap values between a number of arrays
*/
void md_circular_swap(unsigned M, unsigned int D, const long dims[D], void* ptr[M], size_t size)
{
long strs[M][D];
md_calc_strides(D, strs[0], dims, size);
const long* strp[M];
strp[0] = strs[0];
for (unsigned int i = 1; i < M; i++) {
md_copy_strides(D, strs[i], strs[0]);
strp[i] = strs[i];
}
md_circular_swap2(M, D, dims, strp, ptr, size);
}
/**
* Swap values between two arrays (with strides)
*
* iptr[i] = optr[i] and optr[i] = iptr[i]
*/
void md_swap2(unsigned int D, const long dim[D], const long ostr[D], void* optr, const long istr[D], void* iptr, size_t size)
{
md_circular_swap2(2, D, dim, (const long*[2]){ ostr, istr }, (void*[2]){ optr, iptr }, size);
}
/**
* Swap values between two arrays (without strides)
*
* iptr[i] = optr[i] and optr[i] = iptr[i]
*/
void md_swap(unsigned int D, const long dim[D], void* optr, void* iptr, size_t size)
{
long str[D];
md_calc_strides(D, str, dim, size);
md_swap2(D, dim, str, optr, str, iptr, size);
}
/**
* Move a block from an array to another array (with strides)
*
*/
void md_move_block2(unsigned int D, const long dim[D], const long opos[D], const long odim[D], const long ostr[D], void* optr, const long ipos[D], const long idim[D], const long istr[D], const void* iptr, size_t size)
{
for (unsigned int i = 0; i < D; i++) {
assert(dim[i] <= odim[i]);
assert(dim[i] <= idim[i]);
assert((0 <= opos[i]) && (opos[i] <= odim[i] - dim[i]));
assert((0 <= ipos[i]) && (ipos[i] <= idim[i] - dim[i]));
}
long ioff = md_calc_offset(D, istr, ipos);
long ooff = md_calc_offset(D, ostr, opos);
md_copy2(D, dim, ostr, optr + ooff, istr, iptr + ioff, size);
}
/**
* Move a block from an array to another array (without strides)
*
*/
void md_move_block(unsigned int D, const long dim[D], const long opos[D], const long odim[D], void* optr, const long ipos[D], const long idim[D], const void* iptr, size_t size)
{
md_move_block2(D, dim,
opos, odim, MD_STRIDES(D, odim, size), optr,
ipos, idim, MD_STRIDES(D, idim, size), iptr, size);
}
/**
* Copy a block from an array to another array (with strides)
*
* Block dimensions are min(idim , odim)
*
* if idim[d] > odim[d], then optr[i] = iptr[pos + i] for 0 <= i < odim[d]
*
* if idim[d] < odim[d], then optr[pos + i] = iptr[i] for 0 <= i < idim[d]
*
*/
void md_copy_block2(unsigned int D, const long pos[D], const long odim[D], const long ostr[D], void* optr, const long idim[D], const long istr[D], const void* iptr, size_t size)
{
long dim[D];
long ipos[D];
long opos[D];
for (unsigned int i = 0; i < D; i++) {
assert((idim[i] != odim[i]) || (0 == pos[i]));
dim[i] = MIN(odim[i], idim[i]);
ipos[i] = 0;
opos[i] = 0;
if (idim[i] != dim[i])
ipos[i] = pos[i];
if (odim[i] != dim[i])
opos[i] = pos[i];
}
md_move_block2(D, dim, opos, odim, ostr, optr, ipos, idim, istr, iptr, size);
}
/**
* Copy a block from an array to another array (without strides)
*
* Block dimensions are min(idim , odim)
*
* if idim[d] > odim[d], then optr[i] = iptr[pos + i] for 0 <= i < odim[d]
*
* if idim[d] < odim[d], then optr[pos + i] = iptr[i] for 0 <= i < idim[d]
*
*/
void md_copy_block(unsigned int D, const long pos[D], const long odim[D], void* optr, const long idim[D], const void* iptr, size_t size)
{
md_copy_block2(D, pos,
odim, MD_STRIDES(D, odim, size), optr,
idim, MD_STRIDES(D, idim, size), iptr, size);
}
/**
* Resize an array by zero-padding or by truncation at the end.
*
* optr = [iptr 0 0 0 0]
*
*/
void md_resize(unsigned int D, const long odim[D], void* optr, const long idim[D], const void* iptr, size_t size)
{
long pos[D];
memset(pos, 0, D * sizeof(long));
md_clear(D, odim, optr, size);
md_copy_block(D, pos, odim, optr, idim, iptr, size);
}
/**
* Resize an array by zero-padding or by truncation at both ends symmetrically.
*
* optr = [0 0 iptr 0 0]
*
*/
void md_resize_center(unsigned int D, const long odim[D], void* optr, const long idim[D], const void* iptr, size_t size)
{
// the definition of the center position corresponds
// to the one used in the FFT.
long pos[D];
for (unsigned int i = 0; i < D; i++)
pos[i] = labs((odim[i] / 2) - (idim[i] / 2));
md_clear(D, odim, optr, size);
md_copy_block(D, pos, odim, optr, idim, iptr, size);
}
/**
* Extract slice from array specified by flags (with strides)
*
* optr = iptr(pos[0], :, pos[2], :, :)
*
*/
void md_slice2(unsigned int D, unsigned long flags, const long pos[D], const long dim[D], const long ostr[D], void* optr, const long istr[D], const void* iptr, size_t size)
{
long odim[D];
md_select_dims(D, ~flags, odim, dim);
md_copy_block2(D, pos, odim, ostr, optr, dim, istr, iptr, size);
}
/**
* Extract slice from array specified by flags (with strides)
*
* optr = iptr(pos[0], :, pos[2], :, :)
*
*/
void md_slice(unsigned int D, unsigned long flags, const long pos[D], const long dim[D], void* optr, const void* iptr, size_t size)
{
long odim[D];
md_select_dims(D, ~flags, odim, dim);
md_slice2(D, flags, pos, dim,
MD_STRIDES(D, odim, size), optr,
MD_STRIDES(D, dim, size), iptr, size);
}
/**
* Permute array (with strides)
*
* optr[order[i]] = iptr[i]
*
*/
void md_permute2(unsigned int D, const unsigned int order[D], const long odims[D], const long ostr[D], void* optr, const long idims[D], const long istr[D], const void* iptr, size_t size)
{
unsigned int flags = 0;
long ostr2[D];
for (unsigned int i = 0; i < D; i++) {
assert(order[i] < D);
assert(odims[i] == idims[order[i]]);
flags = MD_SET(flags, order[i]);
ostr2[order[i]] = ostr[i];
}
assert(MD_BIT(D) == flags + 1);
md_copy2(D, idims, ostr2, optr, istr, iptr, size);
}
/**
* Permute array (without strides)
*
* optr[order[i]] = iptr[i]
*
*/
void md_permute(unsigned int D, const unsigned int order[D], const long odims[D], void* optr, const long idims[D], const void* iptr, size_t size)
{
md_permute2(D, order,
odims, MD_STRIDES(D, odims, size), optr,
idims, MD_STRIDES(D, idims, size), iptr, size);
}
/**
* Permute dimensions
*
*
*/
void md_permute_dims(unsigned int D, const unsigned int order[D], long odims[D], const long idims[D])
{
for (unsigned int i = 0; i < D; i++)
odims[i] = idims[order[i]];
}
static void md_transpose_order(unsigned int D, unsigned int order[D], unsigned int dim1, unsigned int dim2)
{
assert(dim1 < D);
assert(dim2 < D);
for (unsigned int i = 0; i < D; i++)
order[i] = i;
order[dim1] = dim2;
order[dim2] = dim1;
}
/**
* Transpose dimensions
*
*
*/
void md_transpose_dims(unsigned int D, unsigned int dim1, unsigned int dim2, long odims[D], const long idims[D])
{
unsigned int order[D];
md_transpose_order(D, order, dim1, dim2);
md_permute_dims(D, order, odims, idims);
}
/**
* Tranpose array (with strides)
*
* optr[dim2] = iptr[dim1]
*
* optr[dim1] = iptr[dim2]
*
*/
void md_transpose2(unsigned int D, unsigned int dim1, unsigned int dim2, const long odims[D], const long ostr[D], void* optr, const long idims[D], const long istr[D], const void* iptr, size_t size)
{
for (unsigned int i = 0; i < D; i++)
if ((i != dim1) && (i != dim2))
assert(odims[i] == idims[i]);
assert(odims[dim1] == idims[dim2]);
assert(odims[dim2] == idims[dim1]);
unsigned int order[D];
md_transpose_order(D, order, dim1, dim2);
md_permute2(D, order, odims, ostr, optr, idims, istr, iptr, size);
}
/**
* Tranpose array (without strides)
*
* optr[dim2] = iptr[dim1]
*
* optr[dim1] = iptr[dim2]
*
*/
void md_transpose(unsigned int D, unsigned int dim1, unsigned int dim2, const long odims[D], void* optr, const long idims[D], const void* iptr, size_t size)
{
md_transpose2(D, dim1, dim2,
odims, MD_STRIDES(D, odims, size), optr,
idims, MD_STRIDES(D, idims, size), iptr, size);
}
static void md_flip_inpl2(unsigned int D, const long dims[D], unsigned long flags, const long str[D], void* ptr, size_t size);
/**
* Swap input and output while flipping selected dimensions
* at the same time.
*/
void md_swap_flip2(unsigned int D, const long dims[D], unsigned long flags, const long ostr[D], void* optr, const long istr[D], void* iptr, size_t size)
{
#if 1
int i;
for (i = D - 1; i >= 0; i--)
if ((1 != dims[i]) && MD_IS_SET(flags, i))
break;
if (-1 == i) {
md_swap2(D, dims, ostr, optr, istr, iptr, size);
return;
}
assert(1 < dims[i]);
assert(ostr[i] != 0);
assert(istr[i] != 0);
long dims2[D];
md_copy_dims(D, dims2, dims);
dims2[i] = dims[i] / 2;
long off = (dims[i] + 1) / 2;
assert(dims2[i] + off == dims[i]);
md_swap_flip2(D, dims2, flags, ostr, optr, istr, iptr + off * istr[i], size);
md_swap_flip2(D, dims2, flags, ostr, optr + off * ostr[i], istr, iptr, size);
// odd, swap center plane
// (we should split in three similar sized chunks instead)
dims2[i] = 1;
if (1 == dims[i] % 2)
md_swap_flip2(D, dims2, flags, ostr, optr + (off - 1) * ostr[i], istr, iptr + (off - 1) * istr[i], size);
#else
// simpler, but more swaps
md_swap2(D, dims, ostr, optr, istr, iptr, size);
md_flip_inpl2(D, dims, flags, ostr, optr, size);
md_flip_inpl2(D, dims, flags, istr, iptr, size);
#endif
}
/**
* Swap input and output while flipping selected dimensions
* at the same time.
*/
void md_swap_flip(unsigned int D, const long dims[D], unsigned long flags, void* optr, void* iptr, size_t size)
{
long strs[D];
md_calc_strides(D, strs, dims, size);
md_swap_flip2(D, dims, flags, strs, optr, strs, iptr, size);
}
static void md_flip_inpl2(unsigned int D, const long dims[D], unsigned long flags, const long str[D], void* ptr, size_t size)
{
int i;
for (i = D - 1; i >= 0; i--)
if ((1 != dims[i]) && MD_IS_SET(flags, i))
break;
if (-1 == i)
return;
assert(1 < dims[i]);
assert(str[i] != 0);
long dims2[D];
md_copy_dims(D, dims2, dims);
dims2[i] = dims[i] / 2;
long off = str[i] * (0 + (dims[i] + 1) / 2);
md_swap_flip2(D, dims2, flags, str, ptr, str, ptr + off, size);
}
/**
* Flip array (with strides)
*
* optr[dims[D] - 1 - i] = iptr[i]
*
*/
void md_flip2(unsigned int D, const long dims[D], unsigned long flags, const long ostr[D], void* optr, const long istr[D], const void* iptr, size_t size)
{
if (optr == iptr) {
assert(ostr == istr);
md_flip_inpl2(D, dims, flags, ostr, optr, size);
return;
}
long off = 0;
long ostr2[D];
for (unsigned int i = 0; i < D; i++) {
ostr2[i] = ostr[i];
if (MD_IS_SET(flags, i)) {
ostr2[i] = -ostr[i];
off += (dims[i] - 1) * ostr[i];
}
}
md_copy2(D, dims, ostr2, optr + off, istr, iptr, size);
}
/**
* Flip array (without strides)
*
* optr[dims[D] - 1 - i] = iptr[i]
*
*/
void md_flip(unsigned int D, const long dims[D], unsigned long flags, void* optr, const void* iptr, size_t size)
{
long str[D];
md_calc_strides(D, str, dims, size);
md_flip2(D, dims, flags, str, optr, str, iptr, size);
}
bool md_compare2(unsigned int D, const long dims[D], const long str1[D], const void* src1,
const long str2[D], const void* src2, size_t size)
{
__block bool eq = true;
const long (*nstr[2])[D] = { (const long (*)[D])str1, (const long (*)[D])str2 };
NESTED(void, nary_cmp, (struct nary_opt_data_s* opt_data, void* ptrs[]))
{
size_t size2 = size * opt_data->size;
bool eq2 = (0 == memcmp(ptrs[0], ptrs[1], size2));
#pragma omp critical
eq &= eq2;
};
optimized_nop(2, 0u, D, dims, nstr, (void*[2]){ (void*)src1, (void*)src2 }, (size_t[2]){ size, size }, nary_cmp);
return eq;
}
bool md_compare(unsigned int D, const long dims[D], const void* src1, const void* src2, size_t size)
{
long str[D];
md_calc_strides(D, str, dims, size);
return md_compare2(D, dims, str, src1, str, src2, size);
}
static void md_septrafo_r(unsigned int D, unsigned int R, long dimensions[D], unsigned long flags, const long strides[D], void* ptr, md_trafo_fun_t fun)
{
if (0 == R--)
return;
md_septrafo_r(D, R, dimensions, flags, strides, ptr, fun);
if (MD_IS_SET(flags, R)) {
void* nptr[1] = { ptr };
const long* nstrides[1] = { strides };
long dimsR = dimensions[R];
long strsR = strides[R]; // because of clang
dimensions[R] = 1; // we made a copy in md_septrafo2
NESTED(void, nary_septrafo, (void* ptr[]))
{
fun(dimsR, strsR, ptr[0]);
};
//md_nary_parallel(1, D, dimensions, nstrides, nptr, &data, nary_septrafo);
md_nary(1, D, dimensions, nstrides, nptr, nary_septrafo);
dimensions[R] = dimsR;
}
}
/**
* Apply a separable transformation along selected dimensions.
*
*/
void md_septrafo2(unsigned int D, const long dimensions[D], unsigned long flags, const long strides[D], void* ptr, md_trafo_fun_t fun)
{
long dimcopy[D];
md_copy_dims(D, dimcopy, dimensions);
md_septrafo_r(D, D, dimcopy, flags, strides, ptr, fun);
}
/**
* Apply a separable transformation along selected dimensions.
*
*/
void md_septrafo(unsigned int D, const long dims[D], unsigned long flags, void* ptr, size_t size, md_trafo_fun_t fun)
{
md_septrafo2(D, dims, flags, MD_STRIDES(D, dims, size), ptr, fun);
}
/**
* Copy diagonals from array specified by flags (with strides)
*
* dst(i, i, :, i, :) = src(i, i, :, i, :)
*
*/
void md_copy_diag2(unsigned int D, const long dims[D], unsigned long flags, const long str1[D], void* dst, const long str2[D], const void* src, size_t size)
{
long stride1 = 0;
long stride2 = 0;
long count = -1;
for (unsigned int i = 0; i < D; i++) {
if (MD_IS_SET(flags, i)) {
if (count < 0)
count = dims[i];
assert(dims[i] == count);
stride1 += str1[i];
stride2 += str2[i];
}
}
long xdims[D];
md_select_dims(D, ~flags, xdims, dims);
for (long i = 0; i < count; i++)
md_copy2(D, xdims, str1, dst + i * stride1, str2, src + i * stride2, size);
}
/**
* Copy diagonals from array specified by flags (without strides)
*
* dst(i ,i ,: ,i , :) = src(i ,i ,: ,i ,:)
*
*/
void md_copy_diag(unsigned int D, const long dims[D], unsigned long flags, void* dst, const void* src, size_t size)
{
long str[D];
md_calc_strides(D, str, dims, size);
md_copy_diag2(D, dims, flags, str, dst, str, src, size);
}
/**
* Fill diagonals specified by flags with value (without strides)
*
* dst(i, i, :, i, :) = src[0]
*
*/
void md_fill_diag(unsigned int D, const long dims[D], unsigned long flags, void* dst, const void* src, size_t size)
{
long str2[D];
md_singleton_strides(D, str2);
md_copy_diag2(D, dims, flags, MD_STRIDES(D, dims, size), dst, str2, src, size);
}
static void md_circ_shift_inpl2(unsigned int D, const long dims[D], const long center[D], const long strs[D], void* dst, size_t size)
{
#if 0
long dims1[D];
long dims2[D];
md_copy_dims(D, dims1, dims);
md_copy_dims(D, dims2, dims);
unsigned int i;
for (i = 0; i < D; i++) {
if (0 != center[i]) {
dims1[i] = center[i];
dims2[i] = dims[i] - center[i];
break;
}
}
if (i == D)
return;
long off = strs[i] * center[i];
// cool but slow, instead we want to have a chain of swaps
md_flip2(D, dims, MD_BIT(i), strs, dst, strs, dst, size);
md_flip2(D, dims1, MD_BIT(i), strs, dst, strs, dst, size);
md_flip2(D, dims2, MD_BIT(i), strs, dst + off, strs, dst + off, size);
// also not efficient, we want to merge the chain of swaps
long center2[D];
md_copy_dims(D, center2, center);
center2[i] = 0;
md_circ_shift_inpl2(D, dims, center2, strs, dst, size);
#else
// use tmp for now
unsigned int i;
for (i = 0; i < D; i++)
if (0 != center[i])
break;
if (i == D)
return;
long tmp_strs[D];
md_calc_strides(D, tmp_strs, dims, size);
void* tmp = md_alloc_sameplace(D, dims, size, dst);
md_copy2(D, dims, tmp_strs, tmp, strs, dst, size);
md_circ_shift2(D, dims, center, strs, dst, tmp_strs, tmp, size);
md_free(tmp);
#endif
}
/**
* Circularly shift array (with strides)
*
* dst[mod(i + center)] = src[i]
*
*/
void md_circ_shift2(unsigned int D, const long dimensions[D], const long center[D], const long str1[D], void* dst, const long str2[D], const void* src, size_t size)
{
long pos[D];
for (unsigned int i = 0; i < D; i++) { // FIXME: it would be better to calc modulo
pos[i] = center[i];
while (pos[i] < 0)
pos[i] += dimensions[i];
}
unsigned int i = 0; // FIXME :maybe we shoud search the other way?
while ((i < D) && (0 == pos[i]))
i++;
if (D == i) {
md_copy2(D, dimensions, str1, dst, str2, src, size);
return;
}
if (dst == src) {
assert(str1 == str2);
md_circ_shift_inpl2(D, dimensions, pos, str1, dst, size);
return;
}
long shift = pos[i];
assert(shift != 0);
long dim1[D];
long dim2[D];
md_copy_dims(D, dim1, dimensions);
md_copy_dims(D, dim2, dimensions);
dim1[i] = shift;
dim2[i] = dimensions[i] - shift;
assert((dim1[i] >= 0) && (dim2[i] >= 0));
pos[i] = 0;
//printf("%d: %ld %ld %d\n", i, dim1[i], dim2[i], sizeof(dimensions));
md_circ_shift2(D, dim1, pos, str1, dst, str2, src + dim2[i] * str2[i], size);
md_circ_shift2(D, dim2, pos, str1, dst + dim1[i] * str1[i], str2, src, size);
}
/**
* Circularly shift array (without strides)
*
* dst[mod(i + center)] = src[i]
*
*/
void md_circ_shift(unsigned int D, const long dimensions[D], const long center[D], void* dst, const void* src, size_t size)
{
long strides[D];
md_calc_strides(D, strides, dimensions, size);
md_circ_shift2(D, dimensions, center, strides, dst, strides, src, size);
}
/**
* Circularly extend array (with strides)
*
*/
void md_circ_ext2(unsigned int D, const long dims1[D], const long strs1[D], void* dst, const long dims2[D], const long strs2[D], const void* src, size_t size)
{
long ext[D];
for (unsigned int i = 0; i < D; i++) {
ext[i] = dims1[i] - dims2[i];
assert(ext[i] >= 0);
assert(ext[i] <= dims2[i]);
}
unsigned int i = 0; // FIXME :maybe we shoud search the other way?
while ((i < D) && (0 == ext[i]))
i++;
if (D == i) {
md_copy2(D, dims1, strs1, dst, strs2, src, size);
return;
}
long dims1_crop[D];
long dims2_crop[D];
long ext_dims[D];
md_copy_dims(D, dims1_crop, dims1);
md_copy_dims(D, dims2_crop, dims2);
md_copy_dims(D, ext_dims, dims1);
dims1_crop[i] = dims2[i];
dims2_crop[i] = ext[i];
ext_dims[i] = ext[i];
ext[i] = 0;
//printf("%d: %ld %ld %d\n", i, dim1[i], dim2[i], sizeof(dimensions));
md_circ_ext2(D, dims1_crop, strs1, dst, dims2, strs2, src, size);
md_circ_ext2(D, ext_dims, strs1, dst + dims2[i] * strs1[i], dims2_crop, strs2, src, size);
}
/**
* Circularly extend array (without strides)
*
*/
void md_circ_ext(unsigned int D, const long dims1[D], void* dst, const long dims2[D], const void* src, size_t size)
{
md_circ_ext2(D, dims1, MD_STRIDES(D, dims1, size), dst,
dims2, MD_STRIDES(D, dims2, size), src, size);
}
/**
* Periodically extend array (with strides)
*
*/
void md_periodic2(unsigned int D, const long dims1[D], const long strs1[D], void* dst, const long dims2[D], const long strs2[D], const void* src, size_t size)
{
long dims1B[2 * D];
long strs1B[2 * D];
long strs2B[2 * D];
for (unsigned int i = 0; i < D; i++) {
assert(0 == dims1[i] % dims2[i]);
// blocks
dims1B[2 * i + 0] = dims2[i];
strs1B[2 * i + 0] = strs1[i];
strs2B[2 * i + 0] = strs2[i];
// periodic copies
dims1B[2 * i + 0] = dims1[i] / dims2[i];
strs1B[2 * i + 0] = strs1[i] * dims2[i];
strs2B[2 * i + 0] = 0;
}
md_copy2(D, dims1B, strs1B, dst, strs2B, src, size);
}
/**
* Periodically extend array (without strides)
*
*/
void md_periodic(unsigned int D, const long dims1[D], void* dst, const long dims2[D], const void* src, size_t size)
{
md_periodic2(D, dims1, MD_STRIDES(D, dims1, size), dst,
dims2, MD_STRIDES(D, dims2, size), src, size);
}
/**
* Allocate CPU memory
*
* return pointer to CPU memory
*/
void* md_alloc(unsigned int D, const long dimensions[D], size_t size)
{
return xmalloc(md_calc_size(D, dimensions) * size);
}
/**
* Allocate CPU memory and clear
*
* return pointer to CPU memory
*/
void* md_calloc(unsigned int D, const long dimensions[D], size_t size)
{
void* ptr = md_alloc(D, dimensions, size);
md_clear(D, dimensions, ptr, size);
return ptr;
}
#ifdef USE_CUDA
/**
* Allocate GPU memory
*
* return pointer to GPU memory
*/
void* md_alloc_gpu(unsigned int D, const long dimensions[D], size_t size)
{
return cuda_malloc(md_calc_size(D, dimensions) * size);
}
/**
* Allocate GPU memory and copy from CPU pointer
*
* return pointer to GPU memory
*/
void* md_gpu_move(unsigned int D, const long dims[D], const void* ptr, size_t size)
{
if (NULL == ptr)
return NULL;
void* gpu_ptr = md_alloc_gpu(D, dims, size);
md_copy(D, dims, gpu_ptr, ptr, size);
return gpu_ptr;
}
#endif
/**
* Allocate memory on the same device (CPU/GPU) place as ptr
*
* return pointer to CPU memory if ptr is in CPU or to GPU memory if ptr is in GPU
*/
void* md_alloc_sameplace(unsigned int D, const long dimensions[D], size_t size, const void* ptr)
{
#ifdef USE_CUDA
return (cuda_ondevice(ptr) ? md_alloc_gpu : md_alloc)(D, dimensions, size);
#else
assert(0 != ptr);
return md_alloc(D, dimensions, size);
#endif
}
/**
* Free CPU/GPU memory
*
*/
void md_free(const void* ptr)
{
#ifdef USE_CUDA
if (cuda_ondevice(ptr))
cuda_free((void*)ptr);
else
#endif
xfree(ptr);
}
|
nvector_openmpdev.c | /* -----------------------------------------------------------------
* Programmer(s): David J. Gardner and Shelby Lockhart @ LLNL
* -----------------------------------------------------------------
* Acknowledgements: This NVECTOR module is based on the NVECTOR
* Serial module by Scott D. Cohen, Alan C.
* Hindmarsh, Radu Serban, and Aaron Collier
* @ LLNL
* -----------------------------------------------------------------
* SUNDIALS Copyright Start
* Copyright (c) 2002-2022, Lawrence Livermore National Security
* and Southern Methodist University.
* All rights reserved.
*
* See the top-level LICENSE and NOTICE files for details.
*
* SPDX-License-Identifier: BSD-3-Clause
* SUNDIALS Copyright End
* -----------------------------------------------------------------
* This is the implementation file for an OpenMP DEV implementation
* of the NVECTOR module.
* -----------------------------------------------------------------*/
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <nvector/nvector_openmpdev.h>
#include <sundials/sundials_math.h>
#define ZERO RCONST(0.0)
#define HALF RCONST(0.5)
#define ONE RCONST(1.0)
#define ONEPT5 RCONST(1.5)
/* Private functions for special cases of vector operations */
static void VCopy_OpenMPDEV(N_Vector x, N_Vector z); /* z=x */
static void VSum_OpenMPDEV(N_Vector x, N_Vector y, N_Vector z); /* z=x+y */
static void VDiff_OpenMPDEV(N_Vector x, N_Vector y, N_Vector z); /* z=x-y */
static void VNeg_OpenMPDEV(N_Vector x, N_Vector z); /* z=-x */
static void VScaleSum_OpenMPDEV(realtype c, N_Vector x, N_Vector y, N_Vector z); /* z=c(x+y) */
static void VScaleDiff_OpenMPDEV(realtype c, N_Vector x, N_Vector y, N_Vector z); /* z=c(x-y) */
static void VLin1_OpenMPDEV(realtype a, N_Vector x, N_Vector y, N_Vector z); /* z=ax+y */
static void VLin2_OpenMPDEV(realtype a, N_Vector x, N_Vector y, N_Vector z); /* z=ax-y */
static void Vaxpy_OpenMPDEV(realtype a, N_Vector x, N_Vector y); /* y <- ax+y */
static void VScaleBy_OpenMPDEV(realtype a, N_Vector x); /* x <- ax */
/* Private functions for special cases of vector array operations */
static int VSumVectorArray_OpenMPDEV(int nvec, N_Vector* X, N_Vector* Y, N_Vector* Z); /* Z=X+Y */
static int VDiffVectorArray_OpenMPDEV(int nvec, N_Vector* X, N_Vector* Y, N_Vector* Z); /* Z=X-Y */
static int VScaleSumVectorArray_OpenMPDEV(int nvec, realtype c, N_Vector* X, N_Vector* Y, N_Vector* Z); /* Z=c(X+Y) */
static int VScaleDiffVectorArray_OpenMPDEV(int nvec, realtype c, N_Vector* X, N_Vector* Y, N_Vector* Z); /* Z=c(X-Y) */
static int VLin1VectorArray_OpenMPDEV(int nvec, realtype a, N_Vector* X, N_Vector* Y, N_Vector* Z); /* Z=aX+Y */
static int VLin2VectorArray_OpenMPDEV(int nvec, realtype a, N_Vector* X, N_Vector* Y, N_Vector* Z); /* Z=aX-Y */
static int VaxpyVectorArray_OpenMPDEV(int nvec, realtype a, N_Vector* X, N_Vector* Y); /* Y <- aX+Y */
/*
* -----------------------------------------------------------------
* exported functions
* -----------------------------------------------------------------
*/
/* ----------------------------------------------------------------
* Returns vector type ID. Used to identify vector implementation
* from abstract N_Vector interface.
*/
N_Vector_ID N_VGetVectorID_OpenMPDEV(N_Vector v)
{
return SUNDIALS_NVEC_OPENMPDEV;
}
/* ----------------------------------------------------------------------------
* Function to create a new empty vector
*/
N_Vector N_VNewEmpty_OpenMPDEV(sunindextype length, SUNContext sunctx)
{
N_Vector v;
N_VectorContent_OpenMPDEV content;
/* Create an empty vector object */
v = NULL;
v = N_VNewEmpty(sunctx);
if (v == NULL) return(NULL);
/* Attach operations */
/* constructors, destructors, and utility operations */
v->ops->nvgetvectorid = N_VGetVectorID_OpenMPDEV;
v->ops->nvclone = N_VClone_OpenMPDEV;
v->ops->nvcloneempty = N_VCloneEmpty_OpenMPDEV;
v->ops->nvdestroy = N_VDestroy_OpenMPDEV;
v->ops->nvspace = N_VSpace_OpenMPDEV;
v->ops->nvgetlength = N_VGetLength_OpenMPDEV;
v->ops->nvgetarraypointer = N_VGetHostArrayPointer_OpenMPDEV;
v->ops->nvgetdevicearraypointer = N_VGetDeviceArrayPointer_OpenMPDEV;
v->ops->nvprint = N_VPrint_OpenMPDEV;
v->ops->nvprintfile = N_VPrintFile_OpenMPDEV;
/* standard vector operations */
v->ops->nvlinearsum = N_VLinearSum_OpenMPDEV;
v->ops->nvconst = N_VConst_OpenMPDEV;
v->ops->nvprod = N_VProd_OpenMPDEV;
v->ops->nvdiv = N_VDiv_OpenMPDEV;
v->ops->nvscale = N_VScale_OpenMPDEV;
v->ops->nvabs = N_VAbs_OpenMPDEV;
v->ops->nvinv = N_VInv_OpenMPDEV;
v->ops->nvaddconst = N_VAddConst_OpenMPDEV;
v->ops->nvdotprod = N_VDotProd_OpenMPDEV;
v->ops->nvmaxnorm = N_VMaxNorm_OpenMPDEV;
v->ops->nvwrmsnormmask = N_VWrmsNormMask_OpenMPDEV;
v->ops->nvwrmsnorm = N_VWrmsNorm_OpenMPDEV;
v->ops->nvmin = N_VMin_OpenMPDEV;
v->ops->nvwl2norm = N_VWL2Norm_OpenMPDEV;
v->ops->nvl1norm = N_VL1Norm_OpenMPDEV;
v->ops->nvcompare = N_VCompare_OpenMPDEV;
v->ops->nvinvtest = N_VInvTest_OpenMPDEV;
v->ops->nvconstrmask = N_VConstrMask_OpenMPDEV;
v->ops->nvminquotient = N_VMinQuotient_OpenMPDEV;
/* fused and vector array operations are disabled (NULL) by default */
/* local reduction operations */
v->ops->nvdotprodlocal = N_VDotProd_OpenMPDEV;
v->ops->nvmaxnormlocal = N_VMaxNorm_OpenMPDEV;
v->ops->nvminlocal = N_VMin_OpenMPDEV;
v->ops->nvl1normlocal = N_VL1Norm_OpenMPDEV;
v->ops->nvinvtestlocal = N_VInvTest_OpenMPDEV;
v->ops->nvconstrmasklocal = N_VConstrMask_OpenMPDEV;
v->ops->nvminquotientlocal = N_VMinQuotient_OpenMPDEV;
v->ops->nvwsqrsumlocal = N_VWSqrSumLocal_OpenMPDEV;
v->ops->nvwsqrsummasklocal = N_VWSqrSumMaskLocal_OpenMPDEV;
/* single buffer reduction operations */
v->ops->nvdotprodmultilocal = N_VDotProdMulti_OpenMPDEV;
/* Create content */
content = NULL;
content = (N_VectorContent_OpenMPDEV) malloc(sizeof *content);
if (content == NULL) { N_VDestroy(v); return(NULL); }
/* Attach content */
v->content = content;
/* Initialize content */
content->length = length;
content->own_data = SUNFALSE;
content->host_data = NULL;
content->dev_data = NULL;
return(v);
}
/* ----------------------------------------------------------------------------
* Function to create a new vector
*/
N_Vector N_VNew_OpenMPDEV(sunindextype length)
{
N_Vector v;
realtype *data;
realtype *dev_data;
int dev;
v = NULL;
v = N_VNewEmpty_OpenMPDEV(length);
if (v == NULL) return(NULL);
/* Create data */
if (length > 0) {
/* Update ownership */
NV_OWN_DATA_OMPDEV(v) = SUNTRUE;
/* Allocate memory on host */
data = NULL;
data = (realtype *) malloc(length * sizeof(realtype));
if (data == NULL) { N_VDestroy(v); return(NULL); }
/* Allocate memory on device */
dev = omp_get_default_device();
dev_data = omp_target_alloc(length * sizeof(realtype), dev);
if (dev_data == NULL) { N_VDestroy(v); return(NULL); }
/* Attach data */
NV_DATA_HOST_OMPDEV(v) = data;
NV_DATA_DEV_OMPDEV(v) = dev_data;
}
return(v);
}
/* ----------------------------------------------------------------------------
* Function to create a vector with user data component
*/
N_Vector N_VMake_OpenMPDEV(sunindextype length, realtype *h_vdata,
realtype *d_vdata)
{
N_Vector v;
int dev, host;
if (h_vdata == NULL || d_vdata == NULL) return(NULL);
v = NULL;
v = N_VNewEmpty_OpenMPDEV(length);
if (v == NULL) return(NULL);
if (length > 0) {
/* Get device and host identifiers */
dev = omp_get_default_device();
host = omp_get_initial_device();
/* Attach data */
NV_OWN_DATA_OMPDEV(v) = SUNFALSE;
NV_DATA_HOST_OMPDEV(v) = h_vdata;
NV_DATA_DEV_OMPDEV(v) = d_vdata;
}
return(v);
}
/* ----------------------------------------------------------------------------
* Function to create an array of new vectors.
*/
N_Vector *N_VCloneVectorArray_OpenMPDEV(int count, N_Vector w)
{
return(N_VCloneVectorArray(count, w));
}
/* ----------------------------------------------------------------------------
* Function to create an array of new vectors with NULL data array.
*/
N_Vector *N_VCloneVectorArrayEmpty_OpenMPDEV(int count, N_Vector w)
{
return(N_VCloneEmptyVectorArray(count, w));
}
/* ----------------------------------------------------------------------------
* Function to free an array created with N_VCloneVectorArray_OpenMPDEV
*/
void N_VDestroyVectorArray_OpenMPDEV(N_Vector *vs, int count)
{
N_VDestroyVectorArray(vs, count);
return;
}
/* ----------------------------------------------------------------------------
* Function to return number of vector elements
*/
sunindextype N_VGetLength_OpenMPDEV(N_Vector v)
{
return NV_LENGTH_OMPDEV(v);
}
/* ----------------------------------------------------------------------------
* Function to return a pointer to the data array on the host.
*/
realtype *N_VGetHostArrayPointer_OpenMPDEV(N_Vector v)
{
return((realtype *) NV_DATA_HOST_OMPDEV(v));
}
/* ----------------------------------------------------------------------------
* Function to return a pointer to the data array on the device.
*/
realtype *N_VGetDeviceArrayPointer_OpenMPDEV(N_Vector v)
{
return((realtype *) NV_DATA_DEV_OMPDEV(v));
}
/* ----------------------------------------------------------------------------
* Function to print a vector to stdout
*/
void N_VPrint_OpenMPDEV(N_Vector x)
{
N_VPrintFile_OpenMPDEV(x, stdout);
}
/* ----------------------------------------------------------------------------
* Function to print a vector to outfile
*/
void N_VPrintFile_OpenMPDEV(N_Vector x, FILE *outfile)
{
sunindextype i, N;
realtype *xd;
xd = NULL;
N = NV_LENGTH_OMPDEV(x);
xd = NV_DATA_HOST_OMPDEV(x);
for (i = 0; i < N; i++) {
#if defined(SUNDIALS_EXTENDED_PRECISION)
fprintf(outfile, "%11.8Lg\n", xd[i]);
#elif defined(SUNDIALS_DOUBLE_PRECISION)
fprintf(outfile, "%11.8g\n", xd[i]);
#else
fprintf(outfile, "%11.8g\n", xd[i]);
#endif
}
fprintf(outfile, "\n");
return;
}
/* ----------------------------------------------------------------------------
* Function to copy host array into device array
*/
void N_VCopyToDevice_OpenMPDEV(N_Vector x)
{
int dev, host;
sunindextype length;
realtype *host_ptr;
realtype *dev_ptr;
/* Get array information */
length = NV_LENGTH_OMPDEV(x);
host_ptr = NV_DATA_HOST_OMPDEV(x);
dev_ptr = NV_DATA_DEV_OMPDEV(x);
/* Get device and host identifiers */
dev = omp_get_default_device();
host = omp_get_initial_device();
/* Copy array from host to device */
omp_target_memcpy(dev_ptr, host_ptr, sizeof(realtype) * length, 0, 0, dev, host);
return;
}
/* ----------------------------------------------------------------------------
* Function to copy device array into host array
*/
void N_VCopyFromDevice_OpenMPDEV(N_Vector x)
{
int dev, host;
sunindextype length;
realtype *host_ptr;
realtype *dev_ptr;
/* Get array information */
length = NV_LENGTH_OMPDEV(x);
host_ptr = NV_DATA_HOST_OMPDEV(x);
dev_ptr = NV_DATA_DEV_OMPDEV(x);
/* Get device and host identifiers */
dev = omp_get_default_device();
host = omp_get_initial_device();
/* Copy array from device to host */
omp_target_memcpy(host_ptr, dev_ptr, sizeof(realtype) * length, 0, 0, host, dev);
return;
}
/*
* -----------------------------------------------------------------
* implementation of vector operations
* -----------------------------------------------------------------
*/
/* ----------------------------------------------------------------------------
* Create new vector from existing vector without attaching data
*/
N_Vector N_VCloneEmpty_OpenMPDEV(N_Vector w)
{
N_Vector v;
N_VectorContent_OpenMPDEV content;
if (w == NULL) return(NULL);
/* Create vector */
v = NULL;
v = N_VNewEmpty(w->sunctx);
if (v == NULL) return(NULL);
/* Attach operations */
if (N_VCopyOps(w, v)) { N_VDestroy(v); return(NULL); }
/* Create content */
content = NULL;
content = (N_VectorContent_OpenMPDEV) malloc(sizeof *content);
if (content == NULL) { N_VDestroy(v); return(NULL); }
/* Attach content */
v->content = content;
/* Initialize content */
content->length = NV_LENGTH_OMPDEV(w);
content->own_data = SUNFALSE;
content->host_data = NULL;
content->dev_data = NULL;
return(v);
}
/* ----------------------------------------------------------------------------
* Create new vector from existing vector and attach data
*/
N_Vector N_VClone_OpenMPDEV(N_Vector w)
{
N_Vector v;
realtype *data;
realtype *dev_data;
sunindextype length;
int dev;
v = NULL;
v = N_VCloneEmpty_OpenMPDEV(w);
if (v == NULL) return(NULL);
length = NV_LENGTH_OMPDEV(w);
/* Create data */
if (length > 0) {
/* Update ownership flag */
NV_OWN_DATA_OMPDEV(v) = SUNTRUE;
/* Allocate memory on host */
data = NULL;
data = (realtype *) malloc(length * sizeof(realtype));
if (data == NULL) { N_VDestroy(v); return(NULL); }
/* Allocate memory on device */
dev = omp_get_default_device();
dev_data = omp_target_alloc(length * sizeof(realtype), dev);
if (dev_data == NULL) { N_VDestroy(v); return(NULL); }
/* Attach data */
NV_DATA_HOST_OMPDEV(v)= data;
NV_DATA_DEV_OMPDEV(v) = dev_data;
}
return(v);
}
/* ----------------------------------------------------------------------------
* Destroy vector and free vector memory
*/
void N_VDestroy_OpenMPDEV(N_Vector v)
{
int dev;
if (v == NULL) return;
/* free content */
if (v->content != NULL) {
/* free data arrays if they are owned by the vector */
if (NV_OWN_DATA_OMPDEV(v)) {
if (NV_DATA_HOST_OMPDEV(v) != NULL) {
free(NV_DATA_HOST_OMPDEV(v));
NV_DATA_HOST_OMPDEV(v) = NULL;
}
if (NV_DATA_DEV_OMPDEV(v) != NULL) {
dev = omp_get_default_device();
omp_target_free(NV_DATA_DEV_OMPDEV(v), dev);
NV_DATA_DEV_OMPDEV(v) = NULL;
}
}
free(v->content);
v->content = NULL;
}
/* free ops and vector */
if (v->ops != NULL) { free(v->ops); v->ops = NULL; }
free(v); v = NULL;
return;
}
/* ----------------------------------------------------------------------------
* Get storage requirement for N_Vector
*/
void N_VSpace_OpenMPDEV(N_Vector v, sunindextype *lrw, sunindextype *liw)
{
*lrw = NV_LENGTH_OMPDEV(v);
*liw = 1;
return;
}
/* ----------------------------------------------------------------------------
* Compute linear combination z[i] = a*x[i]+b*y[i]
*/
void N_VLinearSum_OpenMPDEV(realtype a, N_Vector x, realtype b, N_Vector y, N_Vector z)
{
sunindextype i, N;
realtype c, *xd_dev, *yd_dev, *zd_dev;
N_Vector v1, v2;
booleantype test;
int dev;
xd_dev = yd_dev = zd_dev = NULL;
if ((b == ONE) && (z == y)) { /* BLAS usage: axpy y <- ax+y */
Vaxpy_OpenMPDEV(a,x,y);
return;
}
if ((a == ONE) && (z == x)) { /* BLAS usage: axpy x <- by+x */
Vaxpy_OpenMPDEV(b,y,x);
return;
}
/* Case: a == b == 1.0 */
if ((a == ONE) && (b == ONE)) {
VSum_OpenMPDEV(x, y, z);
return;
}
/* Cases: (1) a == 1.0, b = -1.0, (2) a == -1.0, b == 1.0 */
if ((test = ((a == ONE) && (b == -ONE))) || ((a == -ONE) && (b == ONE))) {
v1 = test ? y : x;
v2 = test ? x : y;
VDiff_OpenMPDEV(v2, v1, z);
return;
}
/* Cases: (1) a == 1.0, b == other or 0.0, (2) a == other or 0.0, b == 1.0 */
/* if a or b is 0.0, then user should have called N_VScale */
if ((test = (a == ONE)) || (b == ONE)) {
c = test ? b : a;
v1 = test ? y : x;
v2 = test ? x : y;
VLin1_OpenMPDEV(c, v1, v2, z);
return;
}
/* Cases: (1) a == -1.0, b != 1.0, (2) a != 1.0, b == -1.0 */
if ((test = (a == -ONE)) || (b == -ONE)) {
c = test ? b : a;
v1 = test ? y : x;
v2 = test ? x : y;
VLin2_OpenMPDEV(c, v1, v2, z);
return;
}
/* Case: a == b */
/* catches case both a and b are 0.0 - user should have called N_VConst */
if (a == b) {
VScaleSum_OpenMPDEV(a, x, y, z);
return;
}
/* Case: a == -b */
if (a == -b) {
VScaleDiff_OpenMPDEV(a, x, y, z);
return;
}
/* Do all cases not handled above:
(1) a == other, b == 0.0 - user should have called N_VScale
(2) a == 0.0, b == other - user should have called N_VScale
(3) a,b == other, a !=b, a != -b */
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
yd_dev = NV_DATA_DEV_OMPDEV(y);
zd_dev = NV_DATA_DEV_OMPDEV(z);
/* get default device identifier */
dev = omp_get_default_device();
#pragma omp target is_device_ptr(xd_dev, yd_dev, zd_dev) device(dev)
#pragma omp teams distribute parallel for schedule(static, 1)
for (i = 0; i < N; i++)
zd_dev[i] = (a*xd_dev[i])+(b*yd_dev[i]);
return;
}
/* ----------------------------------------------------------------------------
* Assigns constant value to all vector elements, z[i] = c
*/
void N_VConst_OpenMPDEV(realtype c, N_Vector z)
{
sunindextype i, N;
realtype *zd_dev;
int dev;
zd_dev = NULL;
N = NV_LENGTH_OMPDEV(z);
zd_dev = NV_DATA_DEV_OMPDEV(z);
/* get default device identifier */
dev = omp_get_default_device();
#pragma omp target is_device_ptr(zd_dev) device(dev)
#pragma omp teams distribute parallel for schedule(static, 1)
for (i = 0; i < N; i++) zd_dev[i] = c;
return;
}
/* ----------------------------------------------------------------------------
* Compute componentwise product z[i] = x[i]*y[i]
*/
void N_VProd_OpenMPDEV(N_Vector x, N_Vector y, N_Vector z)
{
sunindextype i, N;
realtype *xd_dev, *yd_dev, *zd_dev;
int dev;
xd_dev = yd_dev = zd_dev = NULL;
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
yd_dev = NV_DATA_DEV_OMPDEV(y);
zd_dev = NV_DATA_DEV_OMPDEV(z);
/* get default device identifier */
dev = omp_get_default_device();
#pragma omp target is_device_ptr(xd_dev, yd_dev, zd_dev) device(dev)
#pragma omp teams distribute parallel for schedule(static, 1)
for (i = 0; i < N; i++)
zd_dev[i] = xd_dev[i]*yd_dev[i];
return;
}
/* ----------------------------------------------------------------------------
* Compute componentwise division z[i] = x[i]/y[i]
*/
void N_VDiv_OpenMPDEV(N_Vector x, N_Vector y, N_Vector z)
{
sunindextype i, N;
realtype *xd_dev, *yd_dev, *zd_dev;
int dev;
xd_dev = yd_dev = zd_dev = NULL;
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
yd_dev = NV_DATA_DEV_OMPDEV(y);
zd_dev = NV_DATA_DEV_OMPDEV(z);
/* get default device identifier */
dev = omp_get_default_device();
#pragma omp target is_device_ptr(xd_dev, yd_dev, zd_dev) device(dev)
#pragma omp teams distribute parallel for schedule(static, 1)
for (i = 0; i < N; i++)
zd_dev[i] = xd_dev[i]/yd_dev[i];
return;
}
/* ----------------------------------------------------------------------------
* Compute scaler multiplication z[i] = c*x[i]
*/
void N_VScale_OpenMPDEV(realtype c, N_Vector x, N_Vector z)
{
sunindextype i, N;
realtype *xd_dev, *zd_dev;
int dev;
xd_dev = zd_dev = NULL;
if (z == x) { /* BLAS usage: scale x <- cx */
VScaleBy_OpenMPDEV(c, x);
return;
}
if (c == ONE) {
VCopy_OpenMPDEV(x, z);
} else if (c == -ONE) {
VNeg_OpenMPDEV(x, z);
} else {
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
zd_dev = NV_DATA_DEV_OMPDEV(z);
/* get default device identifier */
dev = omp_get_default_device();
#pragma omp target is_device_ptr(xd_dev, zd_dev) device(dev)
#pragma omp teams distribute parallel for schedule(static, 1)
for (i = 0; i < N; i++)
zd_dev[i] = c*xd_dev[i];
}
return;
}
/* ----------------------------------------------------------------------------
* Compute absolute value of vector components z[i] = SUNRabs(x[i])
*/
void N_VAbs_OpenMPDEV(N_Vector x, N_Vector z)
{
sunindextype i, N;
realtype *xd_dev, *zd_dev;
int dev;
xd_dev = zd_dev = NULL;
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
zd_dev = NV_DATA_DEV_OMPDEV(z);
/* get default device identifier */
dev = omp_get_default_device();
#pragma omp target is_device_ptr(xd_dev, zd_dev) device(dev)
#pragma omp teams distribute parallel for schedule(static, 1)
for (i = 0; i < N; i++)
zd_dev[i] = SUNRabs(xd_dev[i]);
return;
}
/* ----------------------------------------------------------------------------
* Compute componentwise inverse z[i] = 1 / x[i]
*/
void N_VInv_OpenMPDEV(N_Vector x, N_Vector z)
{
sunindextype i, N;
realtype *xd_dev, *zd_dev;
int dev;
xd_dev = zd_dev = NULL;
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
zd_dev = NV_DATA_DEV_OMPDEV(z);
/* get default device identifier */
dev = omp_get_default_device();
#pragma omp target is_device_ptr(xd_dev, zd_dev) device(dev)
#pragma omp teams distribute parallel for schedule(static, 1)
for (i = 0; i < N; i++)
zd_dev[i] = ONE/xd_dev[i];
return;
}
/* ----------------------------------------------------------------------------
* Compute componentwise addition of a scaler to a vector z[i] = x[i] + b
*/
void N_VAddConst_OpenMPDEV(N_Vector x, realtype b, N_Vector z)
{
sunindextype i, N;
realtype *xd_dev, *zd_dev;
int dev;
xd_dev = zd_dev = NULL;
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
zd_dev = NV_DATA_DEV_OMPDEV(z);
/* get default device identifier */
dev = omp_get_default_device();
#pragma omp target is_device_ptr(xd_dev, zd_dev) device(dev)
#pragma omp teams distribute parallel for schedule(static, 1)
for (i = 0; i < N; i++)
zd_dev[i] = xd_dev[i]+b;
return;
}
/* ----------------------------------------------------------------------------
* Computes the dot product of two vectors, a = sum(x[i]*y[i])
*/
realtype N_VDotProd_OpenMPDEV(N_Vector x, N_Vector y)
{
sunindextype i, N;
realtype sum, *xd_dev, *yd_dev;
int dev;
xd_dev = yd_dev = NULL;
sum = ZERO;
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
yd_dev = NV_DATA_DEV_OMPDEV(y);
/* get default device identifier */
dev = omp_get_default_device();
#pragma omp target map(tofrom:sum) is_device_ptr(xd_dev, yd_dev) device(dev)
#pragma omp teams distribute parallel for reduction(+:sum) schedule(static, 1)
for (i = 0; i < N; i++) {
sum += xd_dev[i]*yd_dev[i];
}
return(sum);
}
/* ----------------------------------------------------------------------------
* Computes max norm of a vector
*/
realtype N_VMaxNorm_OpenMPDEV(N_Vector x)
{
sunindextype i, N;
realtype max, *xd_dev;
int dev;
max = ZERO;
xd_dev = NULL;
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
/* get default device identifier */
dev = omp_get_default_device();
#pragma omp target map(tofrom:max) is_device_ptr(xd_dev) device(dev)
#pragma omp teams distribute parallel for reduction(max:max) schedule(static, 1)
for (i = 0; i < N; i++) {
max = SUNMAX(SUNRabs(xd_dev[i]), max);
}
return(max);
}
/* ----------------------------------------------------------------------------
* Computes weighted root mean square norm of a vector
*/
realtype N_VWrmsNorm_OpenMPDEV(N_Vector x, N_Vector w)
{
return(SUNRsqrt(N_VWSqrSumLocal_OpenMPDEV(x, w)/(NV_LENGTH_OMPDEV(x))));
}
/* ----------------------------------------------------------------------------
* Computes weighted root mean square norm of a masked vector
*/
realtype N_VWrmsNormMask_OpenMPDEV(N_Vector x, N_Vector w, N_Vector id)
{
return(SUNRsqrt(N_VWSqrSumMaskLocal_OpenMPDEV(x, w, id) / (NV_LENGTH_OMPDEV(x))));
}
/* ----------------------------------------------------------------------------
* Computes weighted square sum of a vector
*/
realtype N_VWSqrSumLocal_OpenMPDEV(N_Vector x, N_Vector w)
{
sunindextype i, N;
realtype sum, *xd_dev, *wd_dev;
int dev;
sum = ZERO;
xd_dev = wd_dev = NULL;
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
wd_dev = NV_DATA_DEV_OMPDEV(w);
/* get default device identifier */
dev = omp_get_default_device();
#pragma omp target map(tofrom:sum) is_device_ptr(xd_dev, wd_dev) device(dev)
#pragma omp teams distribute parallel for reduction(+:sum) schedule(static, 1)
for (i = 0; i < N; i++) {
sum += SUNSQR(xd_dev[i]*wd_dev[i]);
}
return(sum);
}
/* ----------------------------------------------------------------------------
* Computes weighted square sum of a masked vector
*/
realtype N_VWSqrSumMaskLocal_OpenMPDEV(N_Vector x, N_Vector w, N_Vector id)
{
sunindextype i, N;
realtype sum, *xd_dev, *wd_dev, *idd_dev;
int dev;
sum = ZERO;
xd_dev = wd_dev = idd_dev = NULL;
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
wd_dev = NV_DATA_DEV_OMPDEV(w);
idd_dev = NV_DATA_DEV_OMPDEV(id);
/* get default device identifier */
dev = omp_get_default_device();
#pragma omp target map(tofrom:sum) is_device_ptr(xd_dev, wd_dev, idd_dev) device(dev)
#pragma omp teams distribute parallel for reduction(+:sum) schedule(static, 1)
for (i = 0; i < N; i++) {
if (idd_dev[i] > ZERO) {
sum += SUNSQR(xd_dev[i]*wd_dev[i]);
}
}
return(sum);
}
/* ----------------------------------------------------------------------------
* Finds the minimun component of a vector
*/
realtype N_VMin_OpenMPDEV(N_Vector x)
{
sunindextype i, N;
realtype min, *xd_dev;
int dev;
xd_dev = NULL;
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
/* get default device identifier */
dev = omp_get_default_device();
#pragma omp target map(from:min) is_device_ptr(xd_dev) device(dev)
#pragma omp teams num_teams(1)
{
min = xd_dev[0];
#pragma omp distribute parallel for reduction(min:min) schedule(static, 1)
for (i = 1; i < N; i++) {
min = SUNMIN(xd_dev[i], min);
}
}
return(min);
}
/* ----------------------------------------------------------------------------
* Computes weighted L2 norm of a vector
*/
realtype N_VWL2Norm_OpenMPDEV(N_Vector x, N_Vector w)
{
sunindextype i, N;
realtype sum, *xd_dev, *wd_dev;
int dev;
sum = ZERO;
xd_dev = wd_dev = NULL;
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
wd_dev = NV_DATA_DEV_OMPDEV(w);
/* get default device identifier */
dev = omp_get_default_device();
#pragma omp target map(tofrom:sum) is_device_ptr(xd_dev, wd_dev) device(dev)
#pragma omp teams distribute parallel for reduction(+:sum) schedule(static, 1)
for (i = 0; i < N; i++) {
sum += SUNSQR(xd_dev[i]*wd_dev[i]);
}
return(SUNRsqrt(sum));
}
/* ----------------------------------------------------------------------------
* Computes L1 norm of a vector
*/
realtype N_VL1Norm_OpenMPDEV(N_Vector x)
{
sunindextype i, N;
realtype sum, *xd_dev;
int dev;
sum = ZERO;
xd_dev = NULL;
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
/* get default device identifier */
dev = omp_get_default_device();
#pragma omp target map(tofrom:sum) is_device_ptr(xd_dev) device(dev)
#pragma omp teams distribute parallel for reduction(+:sum) schedule(static, 1)
for (i = 0; i<N; i++)
sum += SUNRabs(xd_dev[i]);
return(sum);
}
/* ----------------------------------------------------------------------------
* Compare vector component values to a scaler
*/
void N_VCompare_OpenMPDEV(realtype c, N_Vector x, N_Vector z)
{
sunindextype i, N;
realtype *xd_dev, *zd_dev;
int dev;
xd_dev = zd_dev = NULL;
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
zd_dev = NV_DATA_DEV_OMPDEV(z);
/* get default device identifier */
dev = omp_get_default_device();
#pragma omp target is_device_ptr(xd_dev, zd_dev) device(dev)
#pragma omp teams distribute parallel for schedule(static, 1)
for (i = 0; i < N; i++)
zd_dev[i] = (SUNRabs(xd_dev[i]) >= c) ? ONE : ZERO;
return;
}
/* ----------------------------------------------------------------------------
* Compute componentwise inverse z[i] = ONE/x[i] and checks if x[i] == ZERO
*/
booleantype N_VInvTest_OpenMPDEV(N_Vector x, N_Vector z)
{
sunindextype i, N;
realtype *xd_dev, *zd_dev, val;
int dev;
xd_dev = zd_dev = NULL;
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
zd_dev = NV_DATA_DEV_OMPDEV(z);
/* get default device identifier */
dev = omp_get_default_device();
val = ZERO;
#pragma omp target map(tofrom:val) is_device_ptr(xd_dev, zd_dev) device(dev)
#pragma omp teams distribute parallel for reduction(max:val) schedule(static, 1)
for (i = 0; i < N; i++) {
if (xd_dev[i] == ZERO)
val = ONE;
else
zd_dev[i] = ONE/xd_dev[i];
}
if (val > ZERO)
return (SUNFALSE);
else
return (SUNTRUE);
}
/* ----------------------------------------------------------------------------
* Compute constraint mask of a vector
*/
booleantype N_VConstrMask_OpenMPDEV(N_Vector c, N_Vector x, N_Vector m)
{
sunindextype i, N;
realtype temp;
realtype *cd_dev, *xd_dev, *md_dev;
int dev;
cd_dev = xd_dev = md_dev = NULL;
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
cd_dev = NV_DATA_DEV_OMPDEV(c);
md_dev = NV_DATA_DEV_OMPDEV(m);
/* get default device identifier */
dev = omp_get_default_device();
temp = ONE;
#pragma omp target map(tofrom:temp) is_device_ptr(xd_dev, cd_dev, md_dev) device(dev)
#pragma omp teams distribute parallel for reduction(min:temp) schedule(static, 1)
for (i = 0; i < N; i++) {
md_dev[i] = ZERO;
if (cd_dev[i] == ZERO) continue;
if (cd_dev[i] > ONEPT5 || cd_dev[i] < -ONEPT5) {
if ( xd_dev[i]*cd_dev[i] <= ZERO) { temp = ZERO; md_dev[i] = ONE; }
continue;
}
if ( cd_dev[i] > HALF || cd_dev[i] < -HALF) {
if (xd_dev[i]*cd_dev[i] < ZERO ) { temp = ZERO; md_dev[i] = ONE; }
}
}
if (temp == ONE) return (SUNTRUE);
else return(SUNFALSE);
}
/* ----------------------------------------------------------------------------
* Compute minimum componentwise quotient
*/
realtype N_VMinQuotient_OpenMPDEV(N_Vector num, N_Vector denom)
{
sunindextype i, N;
realtype *nd_dev, *dd_dev, min;
int dev;
nd_dev = dd_dev = NULL;
N = NV_LENGTH_OMPDEV(num);
nd_dev = NV_DATA_DEV_OMPDEV(num);
dd_dev = NV_DATA_DEV_OMPDEV(denom);
/* get default device identifier */
dev = omp_get_default_device();
min = BIG_REAL;
#pragma omp target map(tofrom:min) is_device_ptr(nd_dev, dd_dev) device(dev)
#pragma omp teams distribute parallel for reduction(min:min) schedule(static, 1)
for (i = 0; i < N; i++)
if (dd_dev[i] != ZERO) min = SUNMIN(nd_dev[i]/dd_dev[i], min);
return(min);
}
/*
* -----------------------------------------------------------------
* fused vector operations
* -----------------------------------------------------------------
*/
int N_VLinearCombination_OpenMPDEV(int nvec, realtype* c, N_Vector* X, N_Vector z)
{
int i, dev;
realtype to_add; /* temporary variable to hold sum being added in atomic operation */
sunindextype j, N;
realtype* zd_dev=NULL;
realtype* xd_dev=NULL;
realtype** xd_dev_ptrs=NULL;
/* invalid number of vectors */
if (nvec < 1) return(-1);
/* should have called N_VScale */
if (nvec == 1) {
N_VScale_OpenMPDEV(c[0], X[0], z);
return(0);
}
/* should have called N_VLinearSum */
if (nvec == 2) {
N_VLinearSum_OpenMPDEV(c[0], X[0], c[1], X[1], z);
return(0);
}
/* get vector length and data array */
N = NV_LENGTH_OMPDEV(z);
zd_dev = NV_DATA_DEV_OMPDEV(z);
/* get default device identifier */
dev = omp_get_default_device();
/* Allocate and store X dev pointers to copy to device */
xd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
for (i=0; i<nvec; i++)
xd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(X[i]);
/*
* X[0] += c[i]*X[i], i = 1,...,nvec-1
*/
if ((X[0] == z) && (c[0] == ONE)) {
#pragma omp target map(to:N,nvec,c[:nvec],xd_dev_ptrs[:nvec]) \
is_device_ptr(xd_dev,zd_dev) device(dev)
#pragma omp teams distribute
{
for (i=1; i<nvec; i++) {
xd_dev = xd_dev_ptrs[i];
#pragma omp parallel for schedule(static, 1)
for (j=0; j<N; j++) {
to_add = c[i] * xd_dev[j];
#pragma omp atomic
zd_dev[j] += to_add;
}
}
}
free(xd_dev_ptrs);
return(0);
}
/*
* X[0] = c[0] * X[0] + sum{ c[i] * X[i] }, i = 1,...,nvec-1
*/
if (X[0] == z) {
#pragma omp target map(to:N,nvec,c[:nvec],xd_dev_ptrs[:nvec]) \
is_device_ptr(xd_dev,zd_dev)
{
#pragma omp teams distribute parallel for schedule(static,1)
for (j=0; j<N; j++)
zd_dev[j] *= c[0];
}
#pragma omp target map(to:N,nvec,c[:nvec],xd_dev_ptrs[:nvec]) \
is_device_ptr(xd_dev,zd_dev)
#pragma omp teams distribute
{
for (i=1; i<nvec; i++) {
xd_dev = xd_dev_ptrs[i];
#pragma omp parallel for schedule(static, 1)
for (j=0; j<N; j++) {
to_add = c[i] * xd_dev[j];
#pragma omp atomic
zd_dev[j] += to_add;
}
}
}
free(xd_dev_ptrs);
return(0);
}
/*
* z = sum{ c[i] * X[i] }, i = 0,...,nvec-1
*/
xd_dev = NV_DATA_DEV_OMPDEV(X[0]);
#pragma omp target map(to:N,c[:nvec]) \
is_device_ptr(xd_dev, zd_dev) device(dev)
{
#pragma omp teams distribute parallel for schedule(static, 1)
for (j=0; j<N; j++) {
zd_dev[j] = c[0] * xd_dev[j];
}
}
#pragma omp target map(to:N,nvec,c[:nvec],xd_dev_ptrs[:nvec]) \
is_device_ptr(xd_dev, zd_dev) device(dev)
#pragma omp teams distribute
{
for (i=1; i<nvec; i++) {
xd_dev = xd_dev_ptrs[i];
#pragma omp parallel for schedule(static, 1)
for (j=0; j<N; j++) {
to_add = c[i] * xd_dev[j];
#pragma omp atomic
zd_dev[j] += to_add;
}
}
}
free(xd_dev_ptrs);
return(0);
}
int N_VScaleAddMulti_OpenMPDEV(int nvec, realtype* a, N_Vector x, N_Vector* Y, N_Vector* Z)
{
int i, dev;
sunindextype j, N;
realtype* xd_dev=NULL;
realtype* yd_dev=NULL;
realtype* zd_dev=NULL;
realtype** yd_dev_ptrs=NULL;
realtype** zd_dev_ptrs=NULL;
/* invalid number of vectors */
if (nvec < 1) return(-1);
/* should have called N_VLinearSum */
if (nvec == 1) {
N_VLinearSum_OpenMPDEV(a[0], x, ONE, Y[0], Z[0]);
return(0);
}
/* get vector length and data array */
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
/* get default device identifier */
dev = omp_get_default_device();
/* Allocate and store dev pointers to copy to device */
yd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
for (i=0; i<nvec; i++)
yd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(Y[i]);
/*
* Y[i][j] += a[i] * x[j]
*/
if (Y == Z) {
#pragma omp target map(to:N,nvec,a[:nvec],yd_dev_ptrs[:nvec]) \
is_device_ptr(xd_dev, yd_dev) device(dev)
#pragma omp teams distribute
{
for (i=0; i<nvec; i++) {
yd_dev = yd_dev_ptrs[i];
#pragma omp parallel for schedule(static, 1)
for (j=0; j<N; j++)
yd_dev[j] += a[i] * xd_dev[j];
}
}
free(yd_dev_ptrs);
return(0);
}
/* Allocate and store dev pointers to copy to device */
zd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
for (i=0; i<nvec; i++)
zd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(Z[i]);
/*
* Z[i][j] = Y[i][j] + a[i] * x[j]
*/
#pragma omp target map(to:N,nvec,a[:nvec],yd_dev_ptrs[:nvec],zd_dev_ptrs[:nvec]) \
is_device_ptr(xd_dev, yd_dev, zd_dev) device(dev)
#pragma omp teams distribute
{
for (i=0; i<nvec; i++) {
yd_dev = yd_dev_ptrs[i];
zd_dev = zd_dev_ptrs[i];
#pragma omp parallel for schedule(static, 1)
for (j=0; j<N; j++)
zd_dev[j] = a[i] * xd_dev[j] + yd_dev[j];
}
}
free(yd_dev_ptrs);
free(zd_dev_ptrs);
return(0);
}
int N_VDotProdMulti_OpenMPDEV(int nvec, N_Vector x, N_Vector* Y, realtype* dotprods)
{
int i, dev;
sunindextype j, N;
realtype sum;
realtype* xd_dev=NULL;
realtype* yd_dev=NULL;
realtype** yd_dev_ptrs=NULL;
/* invalid number of vectors */
if (nvec < 1) return(-1);
/* should have called N_VDotProd */
if (nvec == 1) {
dotprods[0] = N_VDotProd_OpenMPDEV(x, Y[0]);
return(0);
}
/* get vector length and data array */
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
/* get default device identifier */
dev = omp_get_default_device();
/* initialize dot products */
for (i=0; i<nvec; i++) {
dotprods[i] = ZERO;
}
/* Allocate and store dev pointers to copy to device */
yd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
for (i=0; i<nvec; i++)
yd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(Y[i]);
/* compute multiple dot products */
#pragma omp target map(to:N,nvec,yd_dev_ptrs[:nvec]) map(tofrom:dotprods[:nvec]) \
is_device_ptr(xd_dev,yd_dev) device(dev)
#pragma omp teams distribute
for (i=0; i<nvec; i++) {
yd_dev = yd_dev_ptrs[i];
sum = ZERO;
#pragma omp parallel for reduction(+:sum) schedule(static, 1)
for (j=0; j<N; j++)
sum += xd_dev[j] * yd_dev[j];
dotprods[i] += sum;
}
free(yd_dev_ptrs);
return(0);
}
/*
* -----------------------------------------------------------------
* vector array operations
* -----------------------------------------------------------------
*/
int N_VLinearSumVectorArray_OpenMPDEV(int nvec,
realtype a, N_Vector* X,
realtype b, N_Vector* Y,
N_Vector* Z)
{
int i, dev;
sunindextype j, N;
N_Vector* V1;
N_Vector* V2;
booleantype test;
realtype c;
realtype* xd_dev=NULL;
realtype* yd_dev=NULL;
realtype* zd_dev=NULL;
realtype** xd_dev_ptrs=NULL;
realtype** yd_dev_ptrs=NULL;
realtype** zd_dev_ptrs=NULL;
/* invalid number of vectors */
if (nvec < 1) return(-1);
/* should have called N_VLinearSum */
if (nvec == 1) {
N_VLinearSum_OpenMPDEV(a, X[0], b, Y[0], Z[0]);
return(0);
}
/* BLAS usage: axpy y <- ax+y */
if ((b == ONE) && (Z == Y))
return(VaxpyVectorArray_OpenMPDEV(nvec, a, X, Y));
/* BLAS usage: axpy x <- by+x */
if ((a == ONE) && (Z == X))
return(VaxpyVectorArray_OpenMPDEV(nvec, b, Y, X));
/* Case: a == b == 1.0 */
if ((a == ONE) && (b == ONE))
return(VSumVectorArray_OpenMPDEV(nvec, X, Y, Z));
/* Cases: */
/* (1) a == 1.0, b = -1.0, */
/* (2) a == -1.0, b == 1.0 */
if ((test = ((a == ONE) && (b == -ONE))) || ((a == -ONE) && (b == ONE))) {
V1 = test ? Y : X;
V2 = test ? X : Y;
return(VDiffVectorArray_OpenMPDEV(nvec, V2, V1, Z));
}
/* Cases: */
/* (1) a == 1.0, b == other or 0.0, */
/* (2) a == other or 0.0, b == 1.0 */
/* if a or b is 0.0, then user should have called N_VScale */
if ((test = (a == ONE)) || (b == ONE)) {
c = test ? b : a;
V1 = test ? Y : X;
V2 = test ? X : Y;
return(VLin1VectorArray_OpenMPDEV(nvec, c, V1, V2, Z));
}
/* Cases: */
/* (1) a == -1.0, b != 1.0, */
/* (2) a != 1.0, b == -1.0 */
if ((test = (a == -ONE)) || (b == -ONE)) {
c = test ? b : a;
V1 = test ? Y : X;
V2 = test ? X : Y;
return(VLin2VectorArray_OpenMPDEV(nvec, c, V1, V2, Z));
}
/* Case: a == b */
/* catches case both a and b are 0.0 - user should have called N_VConst */
if (a == b)
return(VScaleSumVectorArray_OpenMPDEV(nvec, a, X, Y, Z));
/* Case: a == -b */
if (a == -b)
return(VScaleDiffVectorArray_OpenMPDEV(nvec, a, X, Y, Z));
/* Do all cases not handled above: */
/* (1) a == other, b == 0.0 - user should have called N_VScale */
/* (2) a == 0.0, b == other - user should have called N_VScale */
/* (3) a,b == other, a !=b, a != -b */
/* get vector length */
N = NV_LENGTH_OMPDEV(Z[0]);
/* get default device identifier */
dev = omp_get_default_device();
/* Allocate and store dev pointers to copy to device */
xd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
yd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
zd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
for (i=0; i<nvec; i++)
xd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(X[i]);
for (i=0; i<nvec; i++)
yd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(Y[i]);
for (i=0; i<nvec; i++)
zd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(Z[i]);
/* compute linear sum for each vector pair in vector arrays */
#pragma omp target map(to:N,nvec,a,b,xd_dev_ptrs[:nvec], yd_dev_ptrs[:nvec],zd_dev_ptrs[:nvec]) \
is_device_ptr(xd_dev, yd_dev, zd_dev) device(dev)
#pragma omp teams distribute
{
for (i=0; i<nvec; i++) {
xd_dev = xd_dev_ptrs[i];
yd_dev = yd_dev_ptrs[i];
zd_dev = zd_dev_ptrs[i];
#pragma omp parallel for schedule(static, 1)
for (j=0; j<N; j++)
zd_dev[j] = a * xd_dev[j] + b * yd_dev[j];
}
}
free(xd_dev_ptrs);
free(yd_dev_ptrs);
free(zd_dev_ptrs);
return(0);
}
int N_VScaleVectorArray_OpenMPDEV(int nvec, realtype* c, N_Vector* X, N_Vector* Z)
{
int i, dev;
sunindextype j, N;
realtype* xd_dev=NULL;
realtype* zd_dev=NULL;
realtype** xd_dev_ptrs=NULL;
realtype** zd_dev_ptrs=NULL;
/* invalid number of vectors */
if (nvec < 1) return(-1);
/* should have called N_VScale */
if (nvec == 1) {
N_VScale_OpenMPDEV(c[0], X[0], Z[0]);
return(0);
}
/* get vector length */
N = NV_LENGTH_OMPDEV(Z[0]);
/* get default device identifier */
dev = omp_get_default_device();
/* Allocate and store dev pointers to copy to device */
xd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
for (i=0; i<nvec; i++) {
xd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(X[i]);
}
/*
* X[i] *= c[i]
*/
if (X == Z) {
#pragma omp target map(to:N,nvec,c[:nvec],xd_dev_ptrs[:nvec]) \
is_device_ptr(xd_dev) device(dev)
#pragma omp teams distribute
{
for (i=0; i<nvec; i++) {
xd_dev = xd_dev_ptrs[i];
#pragma omp parallel for schedule(static, 1)
for (j=0; j<N; j++)
xd_dev[j] *= c[i];
}
}
free(xd_dev_ptrs);
return(0);
}
/* Allocate and store dev pointers to copy to device */
zd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
for (i=0; i<nvec; i++)
zd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(Z[i]);
/*
* Z[i] = c[i] * X[i]
*/
#pragma omp target map(to:N,nvec,c[:nvec],xd_dev_ptrs[:nvec],zd_dev_ptrs[:nvec]) \
is_device_ptr(xd_dev, zd_dev) device(dev)
#pragma omp teams distribute
{
for (i=0; i<nvec; i++) {
xd_dev = xd_dev_ptrs[i];
zd_dev = zd_dev_ptrs[i];
#pragma omp parallel for schedule(static, 1)
for (j=0; j<N; j++)
zd_dev[j] = c[i] * xd_dev[j];
}
}
free(xd_dev_ptrs);
free(zd_dev_ptrs);
return(0);
}
int N_VConstVectorArray_OpenMPDEV(int nvec, realtype c, N_Vector* Z)
{
int i, dev;
sunindextype j, N;
realtype* zd_dev=NULL;
realtype** zd_dev_ptrs=NULL;
/* invalid number of vectors */
if (nvec < 1) return(-1);
/* should have called N_VConst */
if (nvec == 1) {
N_VConst_OpenMPDEV(c, Z[0]);
return(0);
}
/* get vector length */
N = NV_LENGTH_OMPDEV(Z[0]);
/* get device */
dev = omp_get_default_device();
/* Allocate and store dev pointers to copy to device */
zd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
for (i=0; i<nvec; i++)
zd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(Z[i]);
/* set each vector in the vector array to a constant */
#pragma omp target map(to:N,nvec,zd_dev_ptrs[:nvec]) \
is_device_ptr(zd_dev) device(dev)
#pragma omp teams distribute
{
for (i=0; i<nvec; i++) {
zd_dev = zd_dev_ptrs[i];
#pragma omp parallel for schedule(static, 1)
for (j=0; j<N; j++)
zd_dev[j] = c;
}
}
free(zd_dev_ptrs);
return(0);
}
int N_VWrmsNormVectorArray_OpenMPDEV(int nvec, N_Vector* X, N_Vector* W, realtype* nrm)
{
int i, dev;
sunindextype j, N;
realtype sum;
realtype* wd_dev=NULL;
realtype* xd_dev=NULL;
realtype** wd_dev_ptrs=NULL;
realtype** xd_dev_ptrs=NULL;
/* invalid number of vectors */
if (nvec < 1) return(-1);
/* should have called N_VWrmsNorm */
if (nvec == 1) {
nrm[0] = N_VWrmsNorm_OpenMPDEV(X[0], W[0]);
return(0);
}
/* get vector length */
N = NV_LENGTH_OMPDEV(X[0]);
/* get default device identifier */
dev = omp_get_default_device();
/* initialize norms */
for (i=0; i<nvec; i++)
nrm[i] = ZERO;
/* Allocate and store dev pointers to copy to device */
wd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
xd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
for (i=0; i<nvec; i++)
wd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(W[i]);
for (i=0; i<nvec; i++)
xd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(X[i]);
/* compute the WRMS norm for each vector in the vector array */
#pragma omp target map(to:N,nvec,xd_dev_ptrs[:nvec],wd_dev_ptrs[:nvec]) map(tofrom:nrm[:nvec]) \
is_device_ptr(xd_dev, wd_dev) device(dev)
#pragma omp teams distribute
{
for (i=0; i<nvec; i++) {
xd_dev = xd_dev_ptrs[i];
wd_dev = wd_dev_ptrs[i];
sum = ZERO;
#pragma omp parallel for reduction(+:sum) schedule(static, 1)
{
for (j=0; j<N; j++)
sum += SUNSQR(xd_dev[j] * wd_dev[j]);
}
nrm[i] = SUNRsqrt(sum/N);
}
}
free(wd_dev_ptrs);
free(xd_dev_ptrs);
return(0);
}
int N_VWrmsNormMaskVectorArray_OpenMPDEV(int nvec, N_Vector* X, N_Vector* W,
N_Vector id, realtype* nrm)
{
int i, dev;
sunindextype j, N;
realtype sum;
realtype* wd_dev=NULL;
realtype* xd_dev=NULL;
realtype* idd_dev=NULL;
realtype** wd_dev_ptrs=NULL;
realtype** xd_dev_ptrs=NULL;
/* invalid number of vectors */
if (nvec < 1) return(-1);
/* should have called N_VWrmsNorm */
if (nvec == 1) {
nrm[0] = N_VWrmsNormMask_OpenMPDEV(X[0], W[0], id);
return(0);
}
/* get vector length and mask data array */
N = NV_LENGTH_OMPDEV(X[0]);
idd_dev = NV_DATA_DEV_OMPDEV(id);
/* get default device identifier */
dev = omp_get_default_device();
/* initialize norms */
for (i=0; i<nvec; i++)
nrm[i] = ZERO;
/* Allocate and store dev pointers to copy to device */
xd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
wd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
for (i=0; i<nvec; i++)
xd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(X[i]);
for (i=0; i<nvec; i++)
wd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(W[i]);
/* compute the WRMS norm for each vector in the vector array */
#pragma omp target map(to:N,nvec,xd_dev_ptrs[:nvec],wd_dev_ptrs[:nvec]) map(tofrom:nrm[:nvec]) \
is_device_ptr(idd_dev,xd_dev,wd_dev) device(dev)
#pragma omp teams distribute
{
for (i=0; i<nvec; i++) {
xd_dev = xd_dev_ptrs[i];
wd_dev = wd_dev_ptrs[i];
sum = ZERO;
#pragma omp parallel for reduction(+:sum) schedule(static, 1)
{
for (j=0; j<N; j++) {
if (idd_dev[j] > ZERO)
sum += SUNSQR(xd_dev[j] * wd_dev[j]);
}
}
nrm[i] = SUNRsqrt(sum/N);
}
}
free(xd_dev_ptrs);
free(wd_dev_ptrs);
return(0);
}
int N_VScaleAddMultiVectorArray_OpenMPDEV(int nvec, int nsum, realtype* a,
N_Vector* X, N_Vector** Y, N_Vector** Z)
{
int i, j, dev;
sunindextype k, N;
realtype* xd_dev=NULL;
realtype* yd_dev=NULL;
realtype* zd_dev=NULL;
realtype** xd_dev_ptrs=NULL;
realtype** yd_dev_ptrs=NULL;
realtype** zd_dev_ptrs=NULL;
int retval;
N_Vector* YY;
N_Vector* ZZ;
/* invalid number of vectors */
if (nvec < 1) return(-1);
if (nsum < 1) return(-1);
/* ---------------------------
* Special cases for nvec == 1
* --------------------------- */
if (nvec == 1) {
/* should have called N_VLinearSum */
if (nsum == 1) {
N_VLinearSum_OpenMPDEV(a[0], X[0], ONE, Y[0][0], Z[0][0]);
return(0);
}
/* should have called N_VScaleAddMulti */
YY = (N_Vector *) malloc(nsum * sizeof(N_Vector));
ZZ = (N_Vector *) malloc(nsum * sizeof(N_Vector));
for (j=0; j<nsum; j++) {
YY[j] = Y[j][0];
ZZ[j] = Z[j][0];
}
retval = N_VScaleAddMulti_OpenMPDEV(nsum, a, X[0], YY, ZZ);
free(YY);
free(ZZ);
return(retval);
}
/* --------------------------
* Special cases for nvec > 1
* -------------------------- */
/* should have called N_VLinearSumVectorArray */
if (nsum == 1) {
retval = N_VLinearSumVectorArray_OpenMPDEV(nvec, a[0], X, ONE, Y[0], Z[0]);
return(retval);
}
/* ----------------------------
* Compute multiple linear sums
* ---------------------------- */
/* get vector length */
N = NV_LENGTH_OMPDEV(X[0]);
/* get default device identifier */
dev = omp_get_default_device();
/* Allocate and store dev pointers to copy to device */
xd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
yd_dev_ptrs = (realtype**) malloc(nvec * nsum * sizeof(realtype*));
for (i=0; i<nvec; i++)
xd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(X[i]);
for (i=0; i<nvec; i++) {
for (j=0; j<nsum; j++)
yd_dev_ptrs[i * nsum + j] = NV_DATA_DEV_OMPDEV(Y[j][i]);
}
/*
* Y[i][j] += a[i] * x[j]
*/
if (Y == Z) {
#pragma omp target map(to:N,nvec,nsum,a[:nsum],xd_dev_ptrs[:nvec],yd_dev_ptrs[:nvec*nsum]) \
is_device_ptr(xd_dev, yd_dev) device(dev)
#pragma omp teams distribute
{
for (i=0; i<nvec; i++) {
xd_dev = xd_dev_ptrs[i];
for (j=0; j<nsum; j++) {
yd_dev = yd_dev_ptrs[i*nsum+j];
#pragma omp parallel for schedule(static, 1)
for (k=0; k<N; k++)
yd_dev[k] += a[j] * xd_dev[k];
}
}
}
free(xd_dev_ptrs);
free(yd_dev_ptrs);
return(0);
}
/* Allocate and store dev pointers to copy to device */
zd_dev_ptrs = (realtype**) malloc(nvec * nsum * sizeof(realtype*));
for (i=0; i<nvec; i++) {
for (j=0; j<nsum; j++)
zd_dev_ptrs[i * nsum + j] = NV_DATA_DEV_OMPDEV(Z[j][i]);
}
/*
* Z[i][j] = Y[i][j] + a[i] * x[j]
*/
#pragma omp target map(to:N,nvec,nsum,a[:nsum],xd_dev_ptrs[:nvec],yd_dev_ptrs[:nvec*nsum],zd_dev_ptrs[:nvec*nsum]) \
is_device_ptr(xd_dev, yd_dev, zd_dev) device(dev)
#pragma omp teams distribute
{
for (i=0; i<nvec; i++) {
xd_dev = xd_dev_ptrs[i];
for (j=0; j<nsum; j++) {
yd_dev = yd_dev_ptrs[i*nsum+j];
zd_dev = zd_dev_ptrs[i*nsum+j];
#pragma omp parallel for schedule(static, 1)
for (k=0; k<N; k++)
zd_dev[k] = a[j] * xd_dev[k] + yd_dev[k];
}
}
}
free(xd_dev_ptrs);
free(yd_dev_ptrs);
free(zd_dev_ptrs);
return(0);
}
int N_VLinearCombinationVectorArray_OpenMPDEV(int nvec, int nsum,
realtype* c,
N_Vector** X,
N_Vector* Z)
{
int i; /* vector arrays index in summation [0,nsum) */
int j; /* vector index in vector array [0,nvec) */
sunindextype k; /* element index in vector [0,N) */
sunindextype N;
realtype* zd_dev=NULL;
realtype* xd_dev=NULL;
realtype** zd_dev_ptrs=NULL;
realtype** xd_dev_ptrs=NULL;
int dev;
realtype* ctmp;
N_Vector* Y;
/* invalid number of vectors */
if (nvec < 1) return(-1);
if (nsum < 1) return(-1);
/* ---------------------------
* Special cases for nvec == 1
* --------------------------- */
if (nvec == 1) {
/* should have called N_VScale */
if (nsum == 1) {
N_VScale_OpenMPDEV(c[0], X[0][0], Z[0]);
return(0);
}
/* should have called N_VLinearSum */
if (nsum == 2) {
N_VLinearSum_OpenMPDEV(c[0], X[0][0], c[1], X[1][0], Z[0]);
return(0);
}
/* should have called N_VLinearCombination */
Y = (N_Vector *) malloc(nsum * sizeof(N_Vector));
for (i=0; i<nsum; i++) {
Y[i] = X[i][0];
}
N_VLinearCombination_OpenMPDEV(nsum, c, Y, Z[0]);
free(Y);
return(0);
}
/* --------------------------
* Special cases for nvec > 1
* -------------------------- */
/* should have called N_VScaleVectorArray */
if (nsum == 1) {
ctmp = (realtype*) malloc(nvec * sizeof(realtype));
for (j=0; j<nvec; j++) {
ctmp[j] = c[0];
}
N_VScaleVectorArray_OpenMPDEV(nvec, ctmp, X[0], Z);
free(ctmp);
return(0);
}
/* should have called N_VLinearSumVectorArray */
if (nsum == 2) {
N_VLinearSumVectorArray_OpenMPDEV(nvec, c[0], X[0], c[1], X[1], Z);
return(0);
}
/* --------------------------
* Compute linear combination
* -------------------------- */
/* get vector length */
N = NV_LENGTH_OMPDEV(Z[0]);
/* get default device identifier */
dev = omp_get_default_device();
/* Allocate and store dev pointers to copy to device */
zd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
xd_dev_ptrs = (realtype**) malloc(nvec * nsum * sizeof(realtype*));
for (j=0; j<nvec; j++)
zd_dev_ptrs[j] = NV_DATA_DEV_OMPDEV(Z[j]);
for (j=0; j<nvec; j++) {
for (i=0; i<nsum; i++)
xd_dev_ptrs[j * nsum + i] = NV_DATA_DEV_OMPDEV(X[i][j]);
}
/*
* X[0][j] += c[i]*X[i][j], i = 1,...,nvec-1
*/
if ((X[0] == Z) && (c[0] == ONE)) {
#pragma omp target map(to:N,nvec,c[:nsum],xd_dev_ptrs[:nvec*nsum],zd_dev_ptrs[:nvec]) \
is_device_ptr(xd_dev, zd_dev) device(dev)
#pragma omp teams distribute
{
for (j=0; j<nvec; j++) {
zd_dev = zd_dev_ptrs[j];
for (i=1; i<nsum; i++) {
xd_dev = xd_dev_ptrs[j*nsum+i];
#pragma omp parallel for schedule(static, 1)
for (k=0; k<N; k++)
zd_dev[k] += c[i] * xd_dev[k];
}
}
}
free(xd_dev_ptrs);
free(zd_dev_ptrs);
return(0);
}
/*
* X[0][j] = c[0] * X[0][j] + sum{ c[i] * X[i][j] }, i = 1,...,nvec-1
*/
if (X[0] == Z) {
#pragma omp target map(to:N,nvec,c[:nsum],xd_dev_ptrs[:nvec*nsum],zd_dev_ptrs[:nvec]) \
is_device_ptr(zd_dev) device(dev)
#pragma omp teams distribute
{
for (j=0; j<nvec; j++) {
zd_dev = zd_dev_ptrs[j];
#pragma omp parallel for schedule(static, 1)
for (k=0; k<N; k++)
zd_dev[k] *= c[0];
for (i=1; i<nsum; i++) {
xd_dev = xd_dev_ptrs[j*nsum+i];
#pragma omp parallel for schedule(static, 1)
for (k=0; k<N; k++)
zd_dev[k] += c[i] * xd_dev[k];
}
}
}
free(xd_dev_ptrs);
free(zd_dev_ptrs);
return(0);
}
/*
* Z[j] = sum{ c[i] * X[i][j] }, i = 0,...,nvec-1
*/
#pragma omp target map(to:N,nvec,c[:nsum],xd_dev_ptrs[:nvec*nsum],zd_dev_ptrs[:nvec]) \
is_device_ptr(zd_dev) device(dev)
#pragma omp teams distribute
{
for (j=0; j<nvec; j++) {
/* scale first vector in the sum into the output vector */
xd_dev = xd_dev_ptrs[j*nsum];
zd_dev = zd_dev_ptrs[j];
#pragma omp parallel for schedule(static, 1)
for (k=0; k<N; k++)
zd_dev[k] = c[0] * xd_dev[k];
/* scale and sum remaining vectors into the output vector */
for (i=1; i<nsum; i++) {
xd_dev = xd_dev_ptrs[j*nsum+i];
#pragma omp parallel for schedule(static, 1)
for (k=0; k<N; k++)
zd_dev[k] += c[i] * xd_dev[k];
}
}
}
free(xd_dev_ptrs);
free(zd_dev_ptrs);
return(0);
}
/*
* -----------------------------------------------------------------
* private functions
* -----------------------------------------------------------------
*/
/* ----------------------------------------------------------------------------
* Copy vector components into a second vector
*/
static void VCopy_OpenMPDEV(N_Vector x, N_Vector z)
{
sunindextype i, N;
realtype *xd_dev, *zd_dev;
int dev;
xd_dev = zd_dev = NULL;
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
zd_dev = NV_DATA_DEV_OMPDEV(z);
/* get default device identifier */
dev = omp_get_default_device();
#pragma omp target is_device_ptr(xd_dev, zd_dev) device(dev)
#pragma omp teams distribute parallel for schedule(static, 1)
for (i = 0; i < N; i++)
zd_dev[i] = xd_dev[i];
return;
}
/* ----------------------------------------------------------------------------
* Compute vector sum
*/
static void VSum_OpenMPDEV(N_Vector x, N_Vector y, N_Vector z)
{
sunindextype i, N;
realtype *xd_dev, *yd_dev, *zd_dev;
int dev;
xd_dev = yd_dev = zd_dev = NULL;
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
yd_dev = NV_DATA_DEV_OMPDEV(y);
zd_dev = NV_DATA_DEV_OMPDEV(z);
/* get default device identifier */
dev = omp_get_default_device();
#pragma omp target is_device_ptr(xd_dev, yd_dev, zd_dev) device(dev)
#pragma omp teams distribute parallel for schedule(static, 1)
for (i = 0; i < N; i++)
zd_dev[i] = xd_dev[i]+yd_dev[i];
return;
}
/* ----------------------------------------------------------------------------
* Compute vector difference
*/
static void VDiff_OpenMPDEV(N_Vector x, N_Vector y, N_Vector z)
{
sunindextype i, N;
realtype *xd_dev, *yd_dev, *zd_dev;
int dev;
xd_dev = yd_dev = zd_dev = NULL;
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
yd_dev = NV_DATA_DEV_OMPDEV(y);
zd_dev = NV_DATA_DEV_OMPDEV(z);
/* get default device identifier */
dev = omp_get_default_device();
#pragma omp target is_device_ptr(xd_dev, yd_dev, zd_dev) device(dev)
#pragma omp teams distribute parallel for schedule(static, 1)
for (i = 0; i < N; i++)
zd_dev[i] = xd_dev[i]-yd_dev[i];
return;
}
/* ----------------------------------------------------------------------------
* Compute the negative of a vector
*/
static void VNeg_OpenMPDEV(N_Vector x, N_Vector z)
{
sunindextype i, N;
realtype *xd_dev, *zd_dev;
int dev;
xd_dev = zd_dev = NULL;
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
zd_dev = NV_DATA_DEV_OMPDEV(z);
/* get default device identifier */
dev = omp_get_default_device();
#pragma omp target is_device_ptr(xd_dev, zd_dev) device(dev)
#pragma omp teams distribute parallel for schedule(static, 1)
for (i = 0; i < N; i++)
zd_dev[i] = -xd_dev[i];
return;
}
/* ----------------------------------------------------------------------------
* Compute scaled vector sum
*/
static void VScaleSum_OpenMPDEV(realtype c, N_Vector x, N_Vector y, N_Vector z)
{
sunindextype i, N;
realtype *xd_dev, *yd_dev, *zd_dev;
int dev;
xd_dev = yd_dev = zd_dev = NULL;
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
yd_dev = NV_DATA_DEV_OMPDEV(y);
zd_dev = NV_DATA_DEV_OMPDEV(z);
/* get default device identifier */
dev = omp_get_default_device();
#pragma omp target is_device_ptr(xd_dev, yd_dev, zd_dev) device(dev)
#pragma omp teams distribute parallel for schedule(static, 1)
for (i = 0; i < N; i++)
zd_dev[i] = c*(xd_dev[i]+yd_dev[i]);
return;
}
/* ----------------------------------------------------------------------------
* Compute scaled vector difference
*/
static void VScaleDiff_OpenMPDEV(realtype c, N_Vector x, N_Vector y, N_Vector z)
{
sunindextype i, N;
realtype *xd_dev, *yd_dev, *zd_dev;
int dev;
xd_dev = yd_dev = zd_dev = NULL;
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
yd_dev = NV_DATA_DEV_OMPDEV(y);
zd_dev = NV_DATA_DEV_OMPDEV(z);
/* get default device identifier */
dev = omp_get_default_device();
#pragma omp target is_device_ptr(xd_dev, yd_dev, zd_dev) device(dev)
#pragma omp teams distribute parallel for schedule(static, 1)
for (i = 0; i < N; i++)
zd_dev[i] = c*(xd_dev[i]-yd_dev[i]);
return;
}
/* ----------------------------------------------------------------------------
* Compute vector sum z[i] = a*x[i]+y[i]
*/
static void VLin1_OpenMPDEV(realtype a, N_Vector x, N_Vector y, N_Vector z)
{
sunindextype i, N;
realtype *xd_dev, *yd_dev, *zd_dev;
int dev;
xd_dev = yd_dev = zd_dev = NULL;
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
yd_dev = NV_DATA_DEV_OMPDEV(y);
zd_dev = NV_DATA_DEV_OMPDEV(z);
/* get default device identifier */
dev = omp_get_default_device();
#pragma omp target is_device_ptr(xd_dev, yd_dev, zd_dev) device(dev)
#pragma omp teams distribute parallel for schedule(static, 1)
for (i = 0; i < N; i++)
zd_dev[i] = (a*xd_dev[i])+yd_dev[i];
return;
}
/* ----------------------------------------------------------------------------
* Compute vector difference z[i] = a*x[i]-y[i]
*/
static void VLin2_OpenMPDEV(realtype a, N_Vector x, N_Vector y, N_Vector z)
{
sunindextype i, N;
realtype *xd_dev, *yd_dev, *zd_dev;
int dev;
xd_dev = yd_dev = zd_dev = NULL;
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
yd_dev = NV_DATA_DEV_OMPDEV(y);
zd_dev = NV_DATA_DEV_OMPDEV(z);
/* get default device identifier */
dev = omp_get_default_device();
#pragma omp target is_device_ptr(xd_dev, yd_dev, zd_dev) device(dev)
#pragma omp teams distribute parallel for schedule(static, 1)
for (i = 0; i < N; i++)
zd_dev[i] = (a*xd_dev[i])-yd_dev[i];
return;
}
/* ----------------------------------------------------------------------------
* Compute special cases of linear sum
*/
static void Vaxpy_OpenMPDEV(realtype a, N_Vector x, N_Vector y)
{
sunindextype i, N;
realtype *xd_dev, *yd_dev;
int dev;
xd_dev = yd_dev = NULL;
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
yd_dev = NV_DATA_DEV_OMPDEV(y);
/* get default device identifier */
dev = omp_get_default_device();
if (a == ONE) {
#pragma omp target is_device_ptr(xd_dev, yd_dev) device(dev)
#pragma omp teams distribute parallel for schedule(static, 1)
for (i = 0; i < N; i++)
yd_dev[i] += xd_dev[i];
return;
}
if (a == -ONE) {
#pragma omp target is_device_ptr(xd_dev, yd_dev) device(dev)
#pragma omp teams distribute parallel for schedule(static, 1)
for (i = 0; i < N; i++)
yd_dev[i] -= xd_dev[i];
return;
}
#pragma omp target is_device_ptr(xd_dev, yd_dev) device(dev)
#pragma omp teams distribute parallel for schedule(static, 1)
for (i = 0; i < N; i++)
yd_dev[i] += a*xd_dev[i];
return;
}
/* ----------------------------------------------------------------------------
* Compute scaled vector x[i] = a*x[i]
*/
static void VScaleBy_OpenMPDEV(realtype a, N_Vector x)
{
sunindextype i, N;
realtype *xd_dev;
int dev;
xd_dev = NULL;
N = NV_LENGTH_OMPDEV(x);
xd_dev = NV_DATA_DEV_OMPDEV(x);
/* get default device identifier */
dev = omp_get_default_device();
#pragma omp target is_device_ptr(xd_dev) device(dev)
#pragma omp teams distribute parallel for schedule(static, 1)
for (i = 0; i < N; i++)
xd_dev[i] *= a;
return;
}
/*
* -----------------------------------------------------------------
* private functions for special cases of vector array operations
* -----------------------------------------------------------------
*/
static int VSumVectorArray_OpenMPDEV(int nvec, N_Vector* X, N_Vector* Y, N_Vector* Z)
{
int i, dev;
sunindextype j, N;
realtype* xd_dev=NULL;
realtype* yd_dev=NULL;
realtype* zd_dev=NULL;
realtype** xd_dev_ptrs=NULL;
realtype** yd_dev_ptrs=NULL;
realtype** zd_dev_ptrs=NULL;
N = NV_LENGTH_OMPDEV(X[0]);
/* get default device identifier */
dev = omp_get_default_device();
/* Allocate and store dev pointers to copy to device */
xd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
yd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
zd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
for (i=0; i<nvec; i++)
xd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(X[i]);
for (i=0; i<nvec; i++)
yd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(Y[i]);
for (i=0; i<nvec; i++)
zd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(Z[i]);
#pragma omp target map(to:N,xd_dev_ptrs[:nvec],yd_dev_ptrs[:nvec],zd_dev_ptrs[:nvec]) \
is_device_ptr(xd_dev, yd_dev, zd_dev) device(dev)
#pragma omp teams distribute
{
for (i=0; i<nvec; i++) {
xd_dev = xd_dev_ptrs[i];
yd_dev = yd_dev_ptrs[i];
zd_dev = zd_dev_ptrs[i];
#pragma omp parallel for schedule(static, 1)
for (j=0; j<N; j++)
zd_dev[j] = xd_dev[j] + yd_dev[j];
}
}
free(xd_dev_ptrs);
free(yd_dev_ptrs);
free(zd_dev_ptrs);
return(0);
}
static int VDiffVectorArray_OpenMPDEV(int nvec, N_Vector* X, N_Vector* Y, N_Vector* Z)
{
int i, dev;
sunindextype j, N;
realtype* xd_dev=NULL;
realtype* yd_dev=NULL;
realtype* zd_dev=NULL;
realtype** xd_dev_ptrs=NULL;
realtype** yd_dev_ptrs=NULL;
realtype** zd_dev_ptrs=NULL;
N = NV_LENGTH_OMPDEV(X[0]);
/* get default device identifier */
dev = omp_get_default_device();
/* Allocate and store dev pointers to copy to device */
xd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
yd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
zd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
for (i=0; i<nvec; i++)
xd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(X[i]);
for (i=0; i<nvec; i++)
yd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(Y[i]);
for (i=0; i<nvec; i++)
zd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(Z[i]);
#pragma omp target map(to:N,xd_dev_ptrs[:nvec],yd_dev_ptrs[:nvec],zd_dev_ptrs[:nvec]) \
is_device_ptr(xd_dev,yd_dev,zd_dev) device(dev)
#pragma omp teams distribute
{
for (i=0; i<nvec; i++) {
xd_dev = xd_dev_ptrs[i];
yd_dev = yd_dev_ptrs[i];
zd_dev = zd_dev_ptrs[i];
#pragma omp parallel for schedule(static, 1)
for (j=0; j<N; j++)
zd_dev[j] = xd_dev[j] - yd_dev[j];
}
}
free(xd_dev_ptrs);
free(yd_dev_ptrs);
free(zd_dev_ptrs);
return(0);
}
static int VScaleSumVectorArray_OpenMPDEV(int nvec, realtype c, N_Vector* X, N_Vector* Y, N_Vector* Z)
{
int i, dev;
sunindextype j, N;
realtype* xd_dev=NULL;
realtype* yd_dev=NULL;
realtype* zd_dev=NULL;
realtype** xd_dev_ptrs=NULL;
realtype** yd_dev_ptrs=NULL;
realtype** zd_dev_ptrs=NULL;
N = NV_LENGTH_OMPDEV(X[0]);
/* get default device identifier */
dev = omp_get_default_device();
/* Allocate and store dev pointers to copy to device */
xd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
yd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
zd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
for (i=0; i<nvec; i++)
xd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(X[i]);
for (i=0; i<nvec; i++)
yd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(Y[i]);
for (i=0; i<nvec; i++)
zd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(Z[i]);
#pragma omp target map(to:N,xd_dev_ptrs[:nvec],yd_dev_ptrs[:nvec],zd_dev_ptrs[:nvec]) \
is_device_ptr(xd_dev,yd_dev,zd_dev) device(dev)
#pragma omp teams distribute
{
for (i=0; i<nvec; i++) {
xd_dev = xd_dev_ptrs[i];
yd_dev = yd_dev_ptrs[i];
zd_dev = zd_dev_ptrs[i];
#pragma omp parallel for schedule(static, 1)
for (j=0; j<N; j++)
zd_dev[j] = c * (xd_dev[j] + yd_dev[j]);
}
}
free(xd_dev_ptrs);
free(yd_dev_ptrs);
free(zd_dev_ptrs);
return(0);
}
static int VScaleDiffVectorArray_OpenMPDEV(int nvec, realtype c, N_Vector* X, N_Vector* Y, N_Vector* Z)
{
int i, dev;
sunindextype j, N;
realtype* xd_dev=NULL;
realtype* yd_dev=NULL;
realtype* zd_dev=NULL;
realtype** xd_dev_ptrs=NULL;
realtype** yd_dev_ptrs=NULL;
realtype** zd_dev_ptrs=NULL;
N = NV_LENGTH_OMPDEV(X[0]);
/* get default device identifier */
dev = omp_get_default_device();
/* Allocate and store dev ointer to copy to device */
xd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
yd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
zd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
for (i=0; i<nvec; i++)
xd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(X[i]);
for (i=0; i<nvec; i++)
yd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(Y[i]);
for (i=0; i<nvec; i++)
zd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(Z[i]);
#pragma omp target map(to:N,xd_dev_ptrs[:nvec],yd_dev_ptrs[:nvec],zd_dev_ptrs[:nvec]) \
is_device_ptr(xd_dev,yd_dev,zd_dev) device(dev)
#pragma omp teams distribute
{
for (i=0; i<nvec; i++) {
xd_dev = xd_dev_ptrs[i];
yd_dev = yd_dev_ptrs[i];
zd_dev = zd_dev_ptrs[i];
#pragma omp parallel for schedule(static, 1)
for (j=0; j<N; j++)
zd_dev[j] = c * (xd_dev[j] - yd_dev[j]);
}
}
free(xd_dev_ptrs);
free(yd_dev_ptrs);
free(zd_dev_ptrs);
return(0);
}
static int VLin1VectorArray_OpenMPDEV(int nvec, realtype a, N_Vector* X, N_Vector* Y, N_Vector* Z)
{
int i, dev;
sunindextype j, N;
realtype* xd_dev=NULL;
realtype* yd_dev=NULL;
realtype* zd_dev=NULL;
realtype** xd_dev_ptrs=NULL;
realtype** yd_dev_ptrs=NULL;
realtype** zd_dev_ptrs=NULL;
N = NV_LENGTH_OMPDEV(X[0]);
/* get default device identifier */
dev = omp_get_default_device();
/* Allocate and store dev pointers to copy to device */
xd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
yd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
zd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
for (i=0; i<nvec; i++)
xd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(X[i]);
for (i=0; i<nvec; i++)
yd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(Y[i]);
for (i=0; i<nvec; i++)
zd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(Z[i]);
#pragma omp target map(to:N,xd_dev_ptrs[:nvec],yd_dev_ptrs[:nvec],zd_dev_ptrs[:nvec]) \
is_device_ptr(xd_dev,yd_dev,zd_dev) device(dev)
#pragma omp teams distribute
{
for (i=0; i<nvec; i++) {
xd_dev = xd_dev_ptrs[i];
yd_dev = yd_dev_ptrs[i];
zd_dev = zd_dev_ptrs[i];
#pragma omp parallel for schedule(static, 1)
for (j=0; j<N; j++)
zd_dev[j] = (a * xd_dev[j]) + yd_dev[j];
}
}
free(xd_dev_ptrs);
free(yd_dev_ptrs);
free(zd_dev_ptrs);
return(0);
}
static int VLin2VectorArray_OpenMPDEV(int nvec, realtype a, N_Vector* X, N_Vector* Y, N_Vector* Z)
{
int i, dev;
sunindextype j, N;
realtype* xd_dev=NULL;
realtype* yd_dev=NULL;
realtype* zd_dev=NULL;
realtype** xd_dev_ptrs=NULL;
realtype** yd_dev_ptrs=NULL;
realtype** zd_dev_ptrs=NULL;
N = NV_LENGTH_OMPDEV(X[0]);
/* get default device identifier */
dev = omp_get_default_device();
/* Allocate and store dev pointers to copy to device */
xd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
yd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
zd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
for (i=0; i<nvec; i++)
xd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(X[i]);
for (i=0; i<nvec; i++)
yd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(Y[i]);
for (i=0; i<nvec; i++)
zd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(Z[i]);
#pragma omp target map(to:N,xd_dev_ptrs[:nvec],yd_dev_ptrs[:nvec],zd_dev_ptrs[:nvec]) \
is_device_ptr(xd_dev,yd_dev,zd_dev) device(dev)
#pragma omp teams distribute
{
for (i=0; i<nvec; i++) {
xd_dev = xd_dev_ptrs[i];
yd_dev = yd_dev_ptrs[i];
zd_dev = zd_dev_ptrs[i];
#pragma omp parallel for schedule(static, 1)
for (j=0; j<N; j++)
zd_dev[j] = (a * xd_dev[j]) - yd_dev[j];
}
}
free(xd_dev_ptrs);
free(yd_dev_ptrs);
free(zd_dev_ptrs);
return(0);
}
static int VaxpyVectorArray_OpenMPDEV(int nvec, realtype a, N_Vector* X, N_Vector* Y)
{
int i, dev;
sunindextype j, N;
realtype* xd_dev=NULL;
realtype* yd_dev=NULL;
realtype** xd_dev_ptrs=NULL;
realtype** yd_dev_ptrs=NULL;
N = NV_LENGTH_OMPDEV(X[0]);
/* get default device identifier */
dev = omp_get_default_device();
/* Allocate and store dev pointers to copy to device */
xd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
yd_dev_ptrs = (realtype**) malloc(nvec * sizeof(realtype*));
for (i=0; i<nvec; i++)
xd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(X[i]);
for (i=0; i<nvec; i++)
yd_dev_ptrs[i] = NV_DATA_DEV_OMPDEV(Y[i]);
if (a == ONE) {
#pragma omp target map(to:N,xd_dev_ptrs[:nvec],yd_dev_ptrs[:nvec]) \
is_device_ptr(xd_dev,yd_dev) device(dev)
#pragma omp teams distribute
{
for (i=0; i<nvec; i++) {
xd_dev = xd_dev_ptrs[i];
yd_dev = yd_dev_ptrs[i];
#pragma omp parallel for schedule(static, 1)
for (j=0; j<N; j++)
yd_dev[j] += xd_dev[j];
}
}
free(xd_dev_ptrs);
free(yd_dev_ptrs);
return(0);
}
if (a == -ONE) {
#pragma omp target map(to:N,xd_dev_ptrs[:nvec],yd_dev_ptrs[:nvec]) \
is_device_ptr(xd_dev,yd_dev) device(dev)
#pragma omp teams distribute
{
for (i=0; i<nvec; i++) {
xd_dev = xd_dev_ptrs[i];
yd_dev = yd_dev_ptrs[i];
#pragma omp parallel for schedule(static, 1)
for (j=0; j<N; j++)
yd_dev[j] -= xd_dev[j];
}
}
free(xd_dev_ptrs);
free(yd_dev_ptrs);
return(0);
}
#pragma omp target map(to:N,xd_dev_ptrs[:nvec],yd_dev_ptrs[:nvec]) \
is_device_ptr(xd_dev,yd_dev) device(dev)
#pragma omp teams distribute
{
for (i=0; i<nvec; i++) {
xd_dev = xd_dev_ptrs[i];
yd_dev = yd_dev_ptrs[i];
#pragma omp parallel for schedule(static, 1)
for (j=0; j<N; j++)
yd_dev[j] += a * xd_dev[j];
}
}
free(xd_dev_ptrs);
free(yd_dev_ptrs);
return(0);
}
/*
* -----------------------------------------------------------------
* Enable / Disable fused and vector array operations
* -----------------------------------------------------------------
*/
int N_VEnableFusedOps_OpenMPDEV(N_Vector v, booleantype tf)
{
/* check that vector is non-NULL */
if (v == NULL) return(-1);
/* check that ops structure is non-NULL */
if (v->ops == NULL) return(-1);
if (tf) {
/* enable all fused vector operations */
v->ops->nvlinearcombination = N_VLinearCombination_OpenMPDEV;
v->ops->nvscaleaddmulti = N_VScaleAddMulti_OpenMPDEV;
v->ops->nvdotprodmulti = N_VDotProdMulti_OpenMPDEV;
/* enable all vector array operations */
v->ops->nvlinearsumvectorarray = N_VLinearSumVectorArray_OpenMPDEV;
v->ops->nvscalevectorarray = N_VScaleVectorArray_OpenMPDEV;
v->ops->nvconstvectorarray = N_VConstVectorArray_OpenMPDEV;
v->ops->nvwrmsnormvectorarray = N_VWrmsNormVectorArray_OpenMPDEV;
v->ops->nvwrmsnormmaskvectorarray = N_VWrmsNormMaskVectorArray_OpenMPDEV;
v->ops->nvscaleaddmultivectorarray = N_VScaleAddMultiVectorArray_OpenMPDEV;
v->ops->nvlinearcombinationvectorarray = N_VLinearCombinationVectorArray_OpenMPDEV;
/* enable single buffer reduction operations */
v->ops->nvdotprodmultilocal = N_VDotProdMultiLocal_OpenMPDEV;
} else {
/* disable all fused vector operations */
v->ops->nvlinearcombination = NULL;
v->ops->nvscaleaddmulti = NULL;
v->ops->nvdotprodmulti = NULL;
/* disable all vector array operations */
v->ops->nvlinearsumvectorarray = NULL;
v->ops->nvscalevectorarray = NULL;
v->ops->nvconstvectorarray = NULL;
v->ops->nvwrmsnormvectorarray = NULL;
v->ops->nvwrmsnormmaskvectorarray = NULL;
v->ops->nvscaleaddmultivectorarray = NULL;
v->ops->nvlinearcombinationvectorarray = NULL;
/* disable single buffer reduction operations */
v->ops->nvdotprodmultilocal = NULL;
}
/* return success */
return(0);
}
int N_VEnableLinearCombination_OpenMPDEV(N_Vector v, booleantype tf)
{
/* check that vector is non-NULL */
if (v == NULL) return(-1);
/* check that ops structure is non-NULL */
if (v->ops == NULL) return(-1);
/* enable/disable operation */
if (tf)
v->ops->nvlinearcombination = N_VLinearCombination_OpenMPDEV;
else
v->ops->nvlinearcombination = NULL;
/* return success */
return(0);
}
int N_VEnableScaleAddMulti_OpenMPDEV(N_Vector v, booleantype tf)
{
/* check that vector is non-NULL */
if (v == NULL) return(-1);
/* check that ops structure is non-NULL */
if (v->ops == NULL) return(-1);
/* enable/disable operation */
if (tf)
v->ops->nvscaleaddmulti = N_VScaleAddMulti_OpenMPDEV;
else
v->ops->nvscaleaddmulti = NULL;
/* return success */
return(0);
}
int N_VEnableDotProdMulti_OpenMPDEV(N_Vector v, booleantype tf)
{
/* check that vector is non-NULL */
if (v == NULL) return(-1);
/* check that ops structure is non-NULL */
if (v->ops == NULL) return(-1);
/* enable/disable operation */
if (tf) {
v->ops->nvdotprodmulti = N_VDotProdMulti_OpenMPDEV;
v->ops->nvdotprodmultilocal = N_VDotProdMulti_OpenMPDEV;
} else {
v->ops->nvdotprodmulti = NULL;
v->ops->nvdotprodmultilocal = NULL;
}
/* return success */
return(0);
}
int N_VEnableLinearSumVectorArray_OpenMPDEV(N_Vector v, booleantype tf)
{
/* check that vector is non-NULL */
if (v == NULL) return(-1);
/* check that ops structure is non-NULL */
if (v->ops == NULL) return(-1);
/* enable/disable operation */
if (tf)
v->ops->nvlinearsumvectorarray = N_VLinearSumVectorArray_OpenMPDEV;
else
v->ops->nvlinearsumvectorarray = NULL;
/* return success */
return(0);
}
int N_VEnableScaleVectorArray_OpenMPDEV(N_Vector v, booleantype tf)
{
/* check that vector is non-NULL */
if (v == NULL) return(-1);
/* check that ops structure is non-NULL */
if (v->ops == NULL) return(-1);
/* enable/disable operation */
if (tf)
v->ops->nvscalevectorarray = N_VScaleVectorArray_OpenMPDEV;
else
v->ops->nvscalevectorarray = NULL;
/* return success */
return(0);
}
int N_VEnableConstVectorArray_OpenMPDEV(N_Vector v, booleantype tf)
{
/* check that vector is non-NULL */
if (v == NULL) return(-1);
/* check that ops structure is non-NULL */
if (v->ops == NULL) return(-1);
/* enable/disable operation */
if (tf)
v->ops->nvconstvectorarray = N_VConstVectorArray_OpenMPDEV;
else
v->ops->nvconstvectorarray = NULL;
/* return success */
return(0);
}
int N_VEnableWrmsNormVectorArray_OpenMPDEV(N_Vector v, booleantype tf)
{
/* check that vector is non-NULL */
if (v == NULL) return(-1);
/* check that ops structure is non-NULL */
if (v->ops == NULL) return(-1);
/* enable/disable operation */
if (tf)
v->ops->nvwrmsnormvectorarray = N_VWrmsNormVectorArray_OpenMPDEV;
else
v->ops->nvwrmsnormvectorarray = NULL;
/* return success */
return(0);
}
int N_VEnableWrmsNormMaskVectorArray_OpenMPDEV(N_Vector v, booleantype tf)
{
/* check that vector is non-NULL */
if (v == NULL) return(-1);
/* check that ops structure is non-NULL */
if (v->ops == NULL) return(-1);
/* enable/disable operation */
if (tf)
v->ops->nvwrmsnormmaskvectorarray = N_VWrmsNormMaskVectorArray_OpenMPDEV;
else
v->ops->nvwrmsnormmaskvectorarray = NULL;
/* return success */
return(0);
}
int N_VEnableScaleAddMultiVectorArray_OpenMPDEV(N_Vector v, booleantype tf)
{
/* check that vector is non-NULL */
if (v == NULL) return(-1);
/* check that ops structure is non-NULL */
if (v->ops == NULL) return(-1);
/* enable/disable operation */
if (tf)
v->ops->nvscaleaddmultivectorarray = N_VScaleAddMultiVectorArray_OpenMPDEV;
else
v->ops->nvscaleaddmultivectorarray = NULL;
/* return success */
return(0);
}
int N_VEnableLinearCombinationVectorArray_OpenMPDEV(N_Vector v, booleantype tf)
{
/* check that vector is non-NULL */
if (v == NULL) return(-1);
/* check that ops structure is non-NULL */
if (v->ops == NULL) return(-1);
/* enable/disable operation */
if (tf)
v->ops->nvlinearcombinationvectorarray = N_VLinearCombinationVectorArray_OpenMPDEV;
else
v->ops->nvlinearcombinationvectorarray = NULL;
/* return success */
return(0);
}
|
pfx_fmt_plug.c | /* pfx cracker patch for JtR. Hacked together during June of 2012 by
* Dhiru Kholia <dhiru.kholia at gmail.com>.
*
* This software is Copyright (c) 2021, Dhiru Kholia <dhiru.kholia at gmail.com>,
* and it is hereby released to the general public under the following terms:
* Redistribution and use in source and binary forms, with or without modification,
* are permitted.
*
* Generating pfx files:
*
* keytool -genkeypair -alias my_certificate -keystore my_keystore.pfx -storepass
* my_password -validity 365 -keyalg RSA -keysize 2048 -storetype pkcs12 */
#include "arch.h"
#if !AC_BUILT || HAVE_BIO_NEW
#if FMT_EXTERNS_H
extern struct fmt_main fmt_pfx;
#elif FMT_REGISTERS_H
john_register_one(&fmt_pfx);
#else
#include <openssl/opensslv.h>
#include <openssl/crypto.h>
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/crypto.h>
#include <openssl/pkcs12.h>
#include <openssl/ssl.h>
#undef MEM_FREE
#include "options.h"
#ifdef _OPENMP
#include <omp.h>
#ifndef OMP_SCALE
#define OMP_SCALE 2 // tuned on core i7
#endif
//#define OMP_SCALE 32 // tuned on K8-dual HT (20% faster)
#endif
#include <string.h>
#include "common.h"
#include "formats.h"
#include "params.h"
#include "misc.h"
#include "memory.h"
#include "dyna_salt.h"
#include "memdbg.h"
#define FORMAT_LABEL "PFX"
#define FORMAT_NAME "PKCS12 (.pfx, .p12)"
#define ALGORITHM_NAME "32/" ARCH_BITS_STR
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH -1001
#define PLAINTEXT_LENGTH 32
#define BINARY_SIZE 0
#define SALT_SIZE sizeof(struct custom_salt*)
#define BINARY_ALIGN 1
#define SALT_ALIGN sizeof(struct custom_salt*)
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
static char (*saved_key)[PLAINTEXT_LENGTH + 1];
static int any_cracked, *cracked;
static size_t cracked_size;
// this will almost certainly have to be a dyna salt, with raw salt internal
// into hash, and with PKCS12 structure in 'off-limits' land. OR replace
// oSSL code with native code.
static struct custom_salt {
dyna_salt dsalt;
PKCS12 pfx;
int len;
int hash_len;
char orig_hash[1]; // needed for salt. Otherwise the 'only' thing we had was the len value
} *cur_salt;
static struct fmt_tests pfx_tests[] = {
{"$pfx$*2136*3080020103308006092a864886f70d010701a0802480048207ff3080308006092a864886f70d010701a0802480048203283082032430820320060b2a864886f70d010c0a0102a08202ad308202a93023060a2a864886f70d010c0103301504104b93bf4f13111410dfcf885201edb561020101048202800f288d8419204192f2bf3da2d819984b0223dc9a4c5e00b023004b800e0b250e3fc76dc85d30a2c5b24f8a9a91131530e8c9b0c7702bc45048e799bebec05984f8dbc5f4193a396d6d7cc4e3fbc8001c6a661e434bbdcf3995e0d9191f35a629fb60e6a3e959457cd8eb67c20238448aa54f17ab691da76679388b6b2232a87c3c91f02859103810c36ec43be9ebd571309805bd9d0bf484b91403dc83de02e9af92c611a254ef1f1022058e9bacf9838a6f6e842fbc90adb55f132668ca4fcd4997873aa5901e8e29df1f01a37afd3964eaa2c7ebeb49c51daab12a7c81298d698c625ee9f15d617d77f29292b86c0b31815c94e3d3b569fc7ef64fdd0c83970e339266fdab76f3e9ddd75a086d3f8fe54e52d7ad34bdb34778e755705c87846ba489578fd187ef40e869935444dc2b9b83b769ddf3a40e481e1e2d33946fa77072cd0151e40e6e55b9c949996e501a591a8b34c8cfb38c669cc90e3ac805ef275b0d9a3d123d649b01f7e296f5bdb229ab62e71008b5c4434e98c50d5d575eae862fbe02ac8ae9003eb8353569110618098830b939db2c9992bef8b8d236c7f0dc59de3f65618ef5e313f9c8eae9d701e44baffc9b909fedd3d4b7283d41bac86121d140ef6877b2db1c168cf05507e1c2c6457405621e34c6fb316429fab6773c7336f32edcb72108de6b339c63124d0f491c87420b0511ad3efcfcdf421e9154381eb164716988dd511eb936423503a5e83a68b87892df1c4d4cfebffa0e856bf70a768ccf34770a6e4bb4d1c7d894a09949af40a458698df7e94335d718ff23cb040e7fc85d62086bfc74bc27d29aee4b0a7d8df41070efa9e165b57ca610b7b49afd688e5160d7b0888a99b04d1397f0b68217f677b78526ea7eacbafc3160303906092a864886f70d010914312c1e2a0043006500720074006900660069006300610064006f00200069006d0070006f0072007400610064006f302306092a864886f70d01091531160414478a62a291a103023605dfdec512ed2b65f57108000000000000308006092a864886f70d010706a0803080020100308006092a864886f70d0107013023060a2a864886f70d010c010630150410af99ed8b3a334491f93aeef557445292020101a08004820458853f6b251cbc854fa17ab64a8b1bf2692f54d1309c7fdfdf6e2a6a0e158851d09b665858f938c8ec79dd2d5754d44c2a25bb5d8ae078d20576418899adfe6cb5caeeaae18ea27e808c55cb9e2da0b9847991259fb0ffdaddb3d6e4ba5f9a93d7c0c1226c1b4620023c373c4ad006b80358b959099a3fe71668d4a36abda19659156b61dac0dc3e534ca40521f675b7b347db333a5ea41d06ffc5ab1dc29499b19825a2fa468b062c0a34893dd2fb2c623ef79802b7ab052d2a243431c01d483c8a524c6fcf0b3c929abd755d4291648302e8b8dab16864dcd16c4d35b464a510c39b1dd14c699ef8197515ce40d77404b223a05593a694bea4508926acd3b7bdacf3bfbb4a82e9a9046649bba3de4670ac8d67354ddbab948d16752be9e5f993fd9b9441b6277bf1a3badd4e92de126a8e40f507d67652710ceedd44bcd01a9b8a214b32c8943472c08d3e6fb051ca42d93ceb67e0056e8348bba31a84377121c7ea44bbda7dc02ce0738fb72636788bb4daa5007d2cb3f5709d8dfb4300e39a56d20282f65c834ba91a38672457d3d6b380918c783b37b42cf86ec5bfacead722f794fa597fa7f98a4ddd686898ad9a5e62301171bc7606fb48e0d10f52025f9aaf16ffc91c5a566a5df15c2fc65cee342a3a9e9e8d970b86771c0d5a540f19625bbd9985c561266da78a46b6cd31bf50735e87926ea702eb890c74b22f40837636bed76ce3fb233ee7bd51a0b90c75d9ae7c4fde52c4edf9a0e3943a09c965f7aa27cdbcd1828efc8e6bcbf1d5f9d896793e07991492fe007782d67cb9e9e963ca31efdd77ab94e6590c0fba5e5cf9bf1e8705b27fbc3e5a55cd38c7fd4728e8e3395e2b55962939cb43ba489984f832af201a1856c61561b77097f683733ca5f01ae51f21cdd2777eeba95ce7d0b7c92e16308fe2db0aca5299b904a8d6804de50e3ba19210267660ebb6e9e4fcf9edc574002250ea2ff1b6c3b6eaad6cbc8761b21b04db3bda3ae07e2de3c771239667fb86c55add6d93e3e84f37c0e90f81d2c4917b3014d04c046366ed4048c357f03f6a17bb14872d6965c58b15c22a3179aa1e38e0e0257ff52ab5fb0229c692ac5db11e21aed65ff698038d4c62d171d90f1b31232e5bc5185fc57c75543a0713e906792642164f74b2d840a112a41498030baf2975fd468eef5b36fd3663b05b985613fe0ef553882b7d599c3ddc4f8d47d4862ff6833918fdf506d30b51b730c4e7bbb3c3757d3dc3bf6ac6b604d496bf5e149d0b0d87f8dc0ca91eec77a707d9df278f4d932c42def034db887e0138fa1a42fb72f022864418c088954cfd10276bfa6c8d7380b8136053945e742be0f8c1cdf6be8b75ccaf28c5faf389f685ddefb37af74e1e8199ce72ea079de3ab04eaf78543103045f1b3b1632e1dd983ddd4508b9e8a32ede7b38170c84abdb33aa11067bfa5a3d595521130af3c3f6fb57cc0f5523a4ac3c6aa17fdcbbe8bf7a3356a1d726282c975c93575724865b5cd8ec6809fed65ae01284ccf200a33b0087162a94b78ad8f9551728c7df2789702054e4a62c30408a740e3557ac8a0b700000000000000000000000000000000000030353021300906052b0e03021a0500041475552f348f6570c4d5d17867ac9cfaef14d7c1df0410545367d2571128f17aec366b395a944d0000", "usr0052"},
{"$pfx$*2604*30820a28020103308209e206092a864886f70d010701a08209d3048209cf308209cb3082057806092a864886f70d010701a082056904820565308205613082055d060b2a864886f70d010c0a0102a08204fa308204f63028060a2a864886f70d010c0103301a0414e9a49f4190a3084e02ceba2f049303750f6646da02020400048204c8cd40bb89c287b9fe70a88825e33a648c76aa1b35d93131d445e48943ee50ff8a0aee6a0483a289fbacf21290a8553e3414ea6bd6b305407d709bbaf915a99430c998d9ba68e71f4036d42feb386061d645433390658df91bd4e9750a39f9288f7cf8001e2adc8e4d7480f1a5e2d63799df20d9eb956f86b33330ec2c206b1ae47cf54d9cf2cdd970664c251e64cc725456e2c14506cfd7d9ff1d2894a50093fff4f29d5967a0f788ed707ade93cb3ad7e87d96dad844d2037f4d5e863ec5170c0f1d4514d752a266cd4db49b63c5d86646e54a68187ddc99b00499286f79e2e7c54e30d3a1b1f035d7113180d072c7218d399f8b5427dc2d6fcb42518bd6bb97f74c97ea2358ef39fb176397fe7729cd5c3a474423f0a0e74a91c77bb27b24f82463081fed53bdf216840b2c60482846010b654e2c74db4abfb07936e0cc9d0d133ac7a4baa03091de25f6eea70d85fe9376349731ecc03fe437175101fd6698929f43a94835c6453b68335f478cfa1fab1ddf0236570ca5a07cebf1aa3c36d7804654a5eac8328377abba3b81627fcac7f1dbdb56ba1f0f861af9967c5d245459a81891fb5dd833f0bca633eb616cf10397b295d857c63501e85fb9f11f1fd3dd80baac425ecf0efa012817ca9b23e06575a3942613fad67b4bda4fabfd29bd1897b0623d6d47ec000bd656f5b7c78b9a4808ac022524b17a8df676b86dc29b6d008d09cb1148110bd07464c071504d7dae5803602247da1e4cd5d490771322d7eb568d0ad0293f4d2626ac0f60f568a92eccd097f6d5247e043b7cdb52ddfef0516e7053fb42b7d1b16564f1c862c1bf45436290a5dab1f0e90b24bdd4433ce0cbcc7b0eafc445dcc6fe8a52e606d3977ce6d9e44f037ea8dbf36bce63a877aaafde13b1bb5005856d315f30fd4feaf26ef8eeef899802aa2442364c147b074c64878a696a1f2cadd9bacb187b62c239c16f163d6c44e157dd8daa4610142eb40dadbc3405c4ade7d127db20bc4384bd1d4c2a2a5dc907aa0468c2485654bceeee3d4011d74e6e85ed88811ccf1cd6b3d5540c5709b8e14fb9e610b552502343ec739e8c9c6d6459062f76275de1fa1b24ed8a9924ea9176dfb89520b7fbec9e9968bd0320afc513e560966b524a82ef5a206f1823742e820bbbe6dca6b0a33c8f04208376bfd01f049f666c735b1efe2550a8601b1839bf045c56a9772a3e25235d2fb61f9007713ff57ae47f6335a44e6730bdaaebe833996aaaa78138ddb7d8719570a429debb8183fbd07f71a037335ec5b1d40c62f7163b85dc71d8db536c9092f155429b65ea81f8ff3c7892ebf881c107ea2c167df47d044ae7ed3fb5328d673753450c82d7049dfeaf1dde821a0ee0d6676a1656584cdbd4532f8d2493ea4794d88acacb147f19ca15777a67fe5031991ebc45ea43e87574f9d2f52de0722d6cc7f5b7a378a461148f1f7c5ee8bc7c7ae4fe80b4eed13b35d16906a084120c645812db0bd70e419c004512f284ab7635f17ee2ecc728aef2cda256b86fb4cc9d3e21736249735962d6ccd307a67fdbdb0815184f116eb1747de19449c6fb9410cb669fa2a3f2ab5ca16c3cca918555b583f61f2126aa0895ccdac7a5604ca1e84a76c15c508d620bb9037e5e5acf97e94438a059bc771d84dc1f63fd3f4780274a2f0a03f9b09a0cf4638e0c317f6ebb24f9062fe8c7023d4c06f3c67c9ac2008e8da33150302b06092a864886f70d010914311e1e1c006d0079005f00630065007200740069006600690063006100740065302106092a864886f70d0109153114041254696d6520313334303937373036353139303082044b06092a864886f70d010706a082043c308204380201003082043106092a864886f70d0107013028060a2a864886f70d010c0106301a04147d79e2d2b2986ea4d929b3ba8b956739a393b00802020400808203f82c0ebc2a236e5ffc4dff9e02344449f642fdf3b16da9b2e56d5a5e35f323b23b8ff915fbaf2ff70705465170ccd259a70bb1cde9f76e593f9a7a0d4764806dad2fa5c3b1ee2711e9dbbcaa874f8985f1b6c2ca1d55c919cf9e88aababe7826107cdb937e7cca57809b20a6351504ab688327e4df957a3c167772cf66aed6a2007ead81896465d4931efe7c3291a49761f1428c766fd82e1736218e90d9f8592475d164d9a79f3424cb6a543f7040d3f0dba6996d496f4f603b7d59527e5c9c89b3f96c55fa73b72385629cbd606cf9f88833db66bb1519dee62a0cd4989d93457fa1162b594b86bc7134c9aa530fe10d62b914f1818395f82d5224c3bc793a04b0ab41dc98694535f5bfbf2aa943d6c794f407e02248be842c55789091d1cc28bbfdf86bc1346142b057558ce1e64e38f8b2d7d68d539150f3de23f43d59637ae678f3687e69b52fdf46f54c32b84a658a2a69fb16da7ebb45ea84c9e38d6cedfc1227b86a6ea3094d0908d588213834192849fa5c25b2460bb22fdd9d9e317efaca646ea582ecb50f6a466f55ae38573afe904eadf42b6c596c8740dbf92cbd38c347624f3399ac2d20d0727f897f38417901dfdaa798631af8992fcad5d708882576036531d2deb867fe46d63921dc50b8c73fbc59586a861d7ae47c2a5ff892e9dffc6d8e6e8161506819ebc020cfb7bc4c1708832d53f8cc864012ab8379a1323e23b0edb5ffe48a942411cef6197f5545ae6822a3096db972f96d4d200ba600a1e95595d4532e7a9861b233f71ff37ea3c19143c87dd6d4a3f3186a7693dc11067c7b4c967984d4bbbf9d88acacb1ff3ba4536ea265a0503865d86af408748fe8191119cd7b570b5352f190265d5d468e911ba0020b526d3892119fda21243568cfa638251c9044c91a88d2f8a05dd0d90088b0b79ac2a2ca263aa108160a7f6943ce709a02743afb6e4ec9a7f7535635f839c2baf938418accec3d5c1ad2bbcec69ab337155bd0bb1b45c7e16e32f251d4da7796f013d6d502581853da6ab9736382115141886c14512fb5ca22e3e9e20366257579eb4225a6a3716457b9b1c0df63cb71a34b888de021f3520d62e96675ea8767e23d55b50e9aa40babafe398f5482c83f8caa57d7ed3486ce7dedace7158067194892defe38af28c1695cd6f14a1ddae959541fab3b59e72c17d2a67d980c749ef00b1f61ece68d81c79b4ec4f4d9eeaad43895a0dc9d86f4d7fe114f01189b3db72ee92963d4403c3aca8bf6d60ef7ee7fcd8102b3247048b4d517cd0ab76a0f8d68d33733934cb35a8e40d7de70c4f166c453fda74553069c51dd33f6f513bb9ef0a983187fc7d896c668590577a4e269688cc7b9fbd1f3fe77d3f431cf002043c43e1cae82b22018931f1337ee276d49c19163a866ef10a64ac5b013db1cb1c303d3021300906052b0e03021a05000414501f5cd8e454e44b6925715c4d2605a8d4ce70d00414456a2344e138862de7ad2e0b274952ef566e2b6302020400", "my_password"},
{"$pfx$*1702*308206a20201033082066806092a864886f70d010701a082065904820655308206513082032f06092a864886f70d010706a08203203082031c0201003082031506092a864886f70d010701301c060a2a864886f70d010c0103300e04086c933ea5111fd24602020800808202e83c56ad18c45e54aaca4d170750cfbfb3059d6cf161e49d379eab15e722216cb479eee8da7b6e6ffc89e01fbf30f4eb5e1b88ca146c166c700a68473d25a0979344cc60d1e58230a12d24b8be6e9174d3afecdf111cd7d96527831ac9c8f4bf3817cda021f34b61899f2a75fe511e8dedfb70367fa9902d2d3e500f853cc5a99ec8672a44713d24ae49382a20db6349bc48b23ad8d4be3aa31ba7e6d720590b5e4f6b0b5d84b7789ae9da7a80bfa3c27e507fc87e7bc943cff967db6b76f904ac52c1db5cfe9915fa3493cd42b8db6deae62bc01593e34bc8598f27a24cdfd242701ff72d997f959f3a933ab5a2762df33849c116715b78cb0d83267aff913619cbbdf003e13318e4b188a8a4f851b9f59ae2c71ab215c565f7872e5d54c06f92d6f59eaf19d95f9b4526d52d289cd17bc0c2079f9f13c20a70a566773d90ca6d888386d909b6362cb79e15cf547dceab1fe793c577b70f72463969f7b416fb5a6228053363558df18588b53406343ab320a1bbf1757b67ef8e3075f44dee4521f4a461d37ea894c940bc87f9bd33276f2843ff5922fd8e61d22a8619ad23154880fd7d957c0f151458fc4f686d96695a823b08c1795daaf79e41118a3c57ee065a693853a9c4b2004440662f51d63bb9973dc4bb8c541d424416c57d01a825be4d31dab7c7f4b2b738e4bbfdda1e3d3b95e026dadee4dfe155c0f4a24991693f679b452516bc19eab7cf7eb41b476358583d46630e8cda55974b8fcbe25b93e91e73f584a913149137c1c20d13f38826d8dba9bcf5504b8cee77e20a19d6fb050e9213b8aeb11c26a871c600701aea352ba2dcea15d8010d25034f64aa488b580b8282d226f8203bba6aa424b0a25bcceb9c7c718b6c276022d988ca063d2e88350d68903f95aa3265b44d909c07fa9477a5dfcfe3b5ed49b789d6e1c13aca012630343021dbc0c0f17dae6688eae495b76d21be49ced2c2e98e1068d8725d8a581958fb2530871dff1b3f910ae8beb3bc07bfb4b1d2d73fc5d440dc9bcd32ba656c32e357051bef3082031a06092a864886f70d010701a082030b0482030730820303308202ff060b2a864886f70d010c0a0102a08202a6308202a2301c060a2a864886f70d010c0103300e0408749558ace83617660202080004820280ef790b9cd427ec99a350a6e3afb1727cf3dd859d5377897805a7093e1ca42ab8cccc6c52d2b86d61ed55b5bd743fb2a4ec556b438933a9d97a55e5ad1fb3f9967e550be3d708feb5c7287e31afed165a4a91bd5a80292a1e061f97a8c11339963843348badf3fd898e89fd92bda5ad0195d8d4f75e7bce9f0518eeb85365860cd32ad5cea0958efef02bfb74aec0af0765729dae079f5eb08b099d3b06a9b9c6cd6f1e1e4170208ebec3c61ae3421e90cef0f2b5cd2187e43cc4ceecf4aec06340f886efb94f517e578d13659392246a69505de3914b719fba74709ef0f03f010429f899dbddab950f6e58462b2fe2663986a5e0c8ff235e89bca3bb6e41fcd602a0277a83822ac1a14101c83fd1cafdc45c1980ecf54ef092deb2fea736b428158e0847256fc1211f94ea8075145be5a5fb26206e125d55f45500844f1a83f063d0be19b60427dadbd89109bb9ee31a1ac79c863204e8e80c044b8b6bc45c756c26be514e4270a293faf4608065a27b4a51253cb9f831614d5c7f25ec1d4e36063e68e4e405c1f4deb98a786c57a376609441f2dcbe6393487b884624570f6cbb02b53f58ea4acb0faedd2931293dc87664a0c589322480686f6613ffb794c3b3b1872cd7a418712a35666b53bd8383f2e7aa6e8a9e20dd3d46cc3aaaaf17841732dde708ba5611ebcc8777fb3f7b65f2cf95992fdf4f5a17ddf01f3ebe5fb6c9cd58cb74553865cbec3c9d391dcc3e96e654faf7be7fdc8d5fb5dff98799e740147d2ca4b6df47560a4a20bd8f30cf5b495f4e919c9efad3aa59491a3e2ba4e53606e2016ce13e8271e70ccd5b57eec99a8604caf5997e648f3eb541769267f9cdf76aa84917ebd8a1f60a973ed22cca9fa0d3589bb77dafed82ea4f8cd19d3146301f06092a864886f70d01091431121e10006f00700065006e00770061006c006c302306092a864886f70d01091531160414a38a6be4b090be5e29259879b75e0e482f4a4dd830313021300906052b0e03021a05000414a790274918578289d80aa9fd0d526923f7b8f4d40408e861d3357729c35f02020800", "openwall"},
{NULL}
};
struct pkcs12_list {
struct pkcs12_list *next;
PKCS12 *p12;
};
static struct pkcs12_list *pList;
struct fmt_main fmt_pfx;
static void init(struct fmt_main *self)
{
/* OpenSSL init, cleanup part is left to OS */
SSL_load_error_strings();
SSL_library_init();
OpenSSL_add_all_algorithms();
#if defined(_OPENMP) && OPENSSL_VERSION_NUMBER >= 0x10000000
if (SSLeay() < 0x10000000) {
fprintf(stderr, "Warning: compiled against OpenSSL 1.0+, "
"but running with an older version -\n"
"disabling OpenMP for pfx because of thread-safety issues "
"of older OpenSSL\n");
fmt_pfx.params.min_keys_per_crypt =
fmt_pfx.params.max_keys_per_crypt = 1;
fmt_pfx.params.flags &= ~FMT_OMP;
}
else {
int omp_t = 1;
omp_t = omp_get_max_threads();
self->params.min_keys_per_crypt *= omp_t;
omp_t *= OMP_SCALE;
self->params.max_keys_per_crypt *= omp_t;
}
#endif
saved_key = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*saved_key));
any_cracked = 0;
cracked_size = sizeof(*cracked) * self->params.max_keys_per_crypt;
cracked = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*cracked));
}
static void done(void)
{
MEM_FREE(cracked);
MEM_FREE(saved_key);
while (pList) {
struct pkcs12_list *p = pList;
PKCS12_free(pList->p12);
pList = pList->next;
MEM_FREE(p);
}
}
static int valid(char *ciphertext, struct fmt_main *self)
{
char *ctcopy, *p, *keeptr, *decoded = NULL;
PKCS12 *p12 = NULL;
BIO *bp = NULL;
int len, i;
if (strncmp(ciphertext, "$pfx$*", 6))
return 0;
ctcopy = strdup(ciphertext);
keeptr = ctcopy;
ctcopy += 6;
if ((p = strtokm(ctcopy, "*")) == NULL) /* length */
goto err;
if (!isdec(p))
goto err;
len = atoi(p);
if ((p = strtokm(NULL, "*")) == NULL) /* data */
goto err;
if (!ishexlc(p))
goto err;
if(strlen(p) != len * 2)
goto err;
decoded = (char *) mem_alloc(len + 1);
for (i = 0; i < len; i++)
decoded[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 +
atoi16[ARCH_INDEX(p[i * 2 + 1])];
decoded[len] = 0;
bp = BIO_new(BIO_s_mem());
if (!bp)
goto err;
BIO_write(bp, decoded, len);
if(!(p12 = d2i_PKCS12_bio(bp, NULL)))
goto err;
PKCS12_free(p12);
if (bp) BIO_free(bp);
MEM_FREE(decoded);
MEM_FREE(keeptr);
return 1;
err:
if (bp) BIO_free(bp);
MEM_FREE(decoded);
MEM_FREE(keeptr);
return 0;
}
static void *get_salt(char *ciphertext)
{
struct custom_salt *psalt;
static unsigned char *ptr;
char *decoded_data;
int i;
char *ctcopy = strdup(ciphertext);
char *keeptr = ctcopy;
char *p;
PKCS12 *p12 = NULL;
BIO *bp;
if (!ptr) ptr = mem_alloc_tiny(sizeof(struct custom_salt*),sizeof(struct custom_salt*));
psalt = (struct custom_salt*)mem_calloc(1, sizeof(struct custom_salt) + strlen(ciphertext) + 1);
strcpy(psalt->orig_hash, ciphertext);
psalt->hash_len = strlen(ciphertext);
ctcopy += 6; /* skip over "$pfx$*" */
p = strtokm(ctcopy, "*");
psalt->len = atoi(p);
decoded_data = (char *) mem_alloc(psalt->len + 1);
p = strtokm(NULL, "*");
for (i = 0; i < psalt->len; i++)
decoded_data[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 +
atoi16[ARCH_INDEX(p[i * 2 + 1])];
decoded_data[psalt->len] = 0;
/* load decoded data into OpenSSL structures */
bp = BIO_new(BIO_s_mem());
if (!bp) {
fprintf(stderr, "OpenSSL BIO allocation failure\n");
error();
}
BIO_write(bp, decoded_data, psalt->len);
if(!(p12 = d2i_PKCS12_bio(bp, NULL))) {
perror("Unable to create PKCS12 object from bio\n");
error();
}
/* save custom_salt information */
memcpy(&(psalt->pfx), p12, sizeof(PKCS12));
/* we can NOT release memory here, or the function will not work */
//PKCS12_free(p12);
if (!pList) {
pList = mem_calloc(sizeof(*pList), sizeof(pList));
pList->p12 = p12;
} else {
struct pkcs12_list *p = mem_calloc(sizeof(*pList), sizeof(pList));
p->next = pList;
pList = p;
pList->p12 = p12;
}
BIO_free(bp);
MEM_FREE(decoded_data);
MEM_FREE(keeptr);
psalt->dsalt.salt_alloc_needs_free = 1; // we used mem_calloc, so JtR CAN free our pointer when done with them.
// set the JtR core linkage stuff for this dyna_salt
psalt->dsalt.salt_cmp_offset = SALT_CMP_OFF(struct custom_salt, len);
psalt->dsalt.salt_cmp_size = SALT_CMP_SIZE(struct custom_salt, len, orig_hash, psalt->hash_len);
memcpy(ptr, &psalt, sizeof(struct custom_salt*));
return (void*)ptr;
}
static void set_salt(void *salt)
{
cur_salt = *(struct custom_salt **) salt;
}
static void pfx_set_key(char *key, int index)
{
int len = strlen(key);
if (len > PLAINTEXT_LENGTH)
len = PLAINTEXT_LENGTH;
memcpy(saved_key[index], key, len);
saved_key[index][len] = 0;
}
static char *get_key(int index)
{
return saved_key[index];
}
static int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
int index = 0;
if (any_cracked) {
memset(cracked, 0, cracked_size);
any_cracked = 0;
}
#if defined(_OPENMP) && OPENSSL_VERSION_NUMBER >= 0x10000000
#pragma omp parallel for
for (index = 0; index < count; index++)
#endif
{
if(PKCS12_verify_mac(&cur_salt->pfx, saved_key[index], -1)) {
cracked[index] = 1;
#ifdef _OPENMP
#pragma omp atomic
#endif
any_cracked |= 1;
}
}
return count;
}
static int cmp_all(void *binary, int count)
{
return any_cracked;
}
static int cmp_one(void *binary, int index)
{
return cracked[index];
}
static int cmp_exact(char *source, int index)
{
return cracked[index];
}
struct fmt_main fmt_pfx = {
{
FORMAT_LABEL,
FORMAT_NAME,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
#if defined(_OPENMP) && OPENSSL_VERSION_NUMBER >= 0x10000000
FMT_OMP |
#endif
FMT_CASE | FMT_8_BIT | FMT_DYNA_SALT,
{ NULL },
pfx_tests
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid,
fmt_default_split,
fmt_default_binary,
get_salt,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash
},
fmt_default_dyna_salt_hash,
NULL,
set_salt,
pfx_set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
fmt_default_get_hash
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
#endif /* HAVE_BIO_NEW */
|
expected_output.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
//---------------------------------------------------------------------
// program MG
//---------------------------------------------------------------------
//----------
// Class S:
//----------
//----------
// Class W:
//----------
//----------
// Class A:
//----------
//----------
// Class B:
//----------
//----------
// Class C:
//----------
//----------
// Class D:
//----------
//----------
// Class E:
//----------
struct anon_NAS_MG_c_132 {
double real;
double imag;
};
typedef struct anon_NAS_MG_c_132 dcomplex;
// actual dimension including ghost cells for communications
// size of rhs array
// size of residual array
// maximum number of levels
//---------------------------------------------------------------------
/*common /mg3/*/
int nx[9];
int ny[9];
int nz[9];
/*common /ClassType/*/
char Class;
/*common /my_debug/*/
int debug_vec[8];
/*common /fap/*/
int m1[9];
int m2[9];
int m3[9];
int ir[9];
int lt;
int lb;
//---------------------------------------------------------------------
// Set at m=1024, can handle cases up to 1024^3 case
//---------------------------------------------------------------------
/*common /timers/*/
//-------------------------------------------------------------------------c
// These arrays are in common because they are quite large
// and probably shouldn't be allocated on the stack. They
// are always passed as subroutine args.
//-------------------------------------------------------------------------c
/*commcon /noautom/*/
double u[2530976];
double v[2530976];
double r[2530976];
/*common /grid/*/
int is1;
int is2;
int is3;
int ie1;
int ie2;
int ie3;
void setup(int *n1, int *n2, int *n3);
void mg3P(double u[], double v[], double r[], double a[4], double c[4], int n1, int n2, int n3);
void psinv(void *or, void *ou, int n1, int n2, int n3, double c[4], int k);
void resid(void *ou, void *ov, void *or, int n1, int n2, int n3, double a[4], int k);
void rprj3(void *or, int m1k, int m2k, int m3k, void *os, int m1j, int m2j, int m3j, int k);
void interp(void *oz, int mm1, int mm2, int mm3, void *ou, int n1, int n2, int n3, int k);
void norm2u3(void *or, int n1, int n2, int n3, double *rnm2, double *rnmu, int nx, int ny, int nz);
void rep_nrm(void *u, int n1, int n2, int n3, char *title, int kk);
void comm3(void *ou, int n1, int n2, int n3, int kk);
void zran3(void *oz, int n1, int n2, int n3, int nx, int ny, int k);
void showall(void *oz, int n1, int n2, int n3);
double power(double a, int n);
void bubble(double ten[][2], int j1[][2], int j2[][2], int j3[][2], int m, int ind);
void zero3(void *oz, int n1, int n2, int n3);
double randlc(double *x, double a);
void vranlc(int n, double *x, double a, double y[]);
void print_results(char *name, char class, int n1, int n2, int n3, int niter, double t, double mops, char *optype, int verified);
double start[64];
double elapsed[64];
double elapsed_time();
void timer_clear(int n);
void timer_start(int n);
void timer_stop(int n);
double timer_read(int n);
void wtime(double *t);
int main() {
//-------------------------------------------------------------------------c
// k is the current level. It is passed down through subroutine args
// and is NOT global. it is the current iteration
//-------------------------------------------------------------------------c
int k, it;
double t, tinit, mflops;
double a[4];
double c[4];
double rnm2, rnmu, old2, oldu, epsilon;
int n1, n2, n3, nit;
double nn, verify_value, err;
int verified;
int i;
char *t_names[10];
double tmax;
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(i = 0; i < 10; i++) {
timer_clear(i);
}
timer_start(0);
printf("\n\n NAS Parallel Benchmarks (NPB3.3-SER-C) - MG Benchmark\n\n");
printf(" No input file. Using compiled defaults \n");
lt = 7;
nit = 4;
nx[lt] = 128;
ny[lt] = 128;
nz[lt] = 128;
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(i = 0; i <= 7; i++) {
debug_vec[i] = 0;
}
if((nx[lt] != ny[lt]) || (nx[lt] != nz[lt])) {
Class = 'U';
}
else if(nx[lt] == 32 && nit == 4) {
Class = 'S';
}
else if(nx[lt] == 128 && nit == 4) {
Class = 'W';
}
else if(nx[lt] == 256 && nit == 4) {
Class = 'A';
}
else if(nx[lt] == 256 && nit == 20) {
Class = 'B';
}
else if(nx[lt] == 512 && nit == 20) {
Class = 'C';
}
else if(nx[lt] == 1024 && nit == 50) {
Class = 'D';
}
else if(nx[lt] == 2048 && nit == 50) {
Class = 'E';
}
else {
Class = 'U';
}
//---------------------------------------------------------------------
// Use these for debug info:
//---------------------------------------------------------------------
// debug_vec(0) = 1 !=> report all norms
// debug_vec(1) = 1 !=> some setup information
// debug_vec(1) = 2 !=> more setup information
// debug_vec(2) = k => at level k or below, show result of resid
// debug_vec(3) = k => at level k or below, show result of psinv
// debug_vec(4) = k => at level k or below, show result of rprj
// debug_vec(5) = k => at level k or below, show result of interp
// debug_vec(6) = 1 => (unused)
// debug_vec(7) = 1 => (unused)
//---------------------------------------------------------------------
a[0] = -8.0 / 3.0;
a[1] = 0.0;
a[2] = 1.0 / 6.0;
a[3] = 1.0 / 12.0;
if(Class == 'A' || Class == 'S' || Class == 'W') {
//---------------------------------------------------------------------
// Coefficients for the S(a) smoother
//---------------------------------------------------------------------
c[0] = -3.0 / 8.0;
c[1] = +1.0 / 32.0;
c[2] = -1.0 / 64.0;
c[3] = 0.0;
}
else {
//---------------------------------------------------------------------
// Coefficients for the S(b) smoother
//---------------------------------------------------------------------
c[0] = -3.0 / 17.0;
c[1] = +1.0 / 33.0;
c[2] = -1.0 / 61.0;
c[3] = 0.0;
}
lb = 1;
k = lt;
setup(&n1, &n2, &n3);
zero3(u, n1, n2, n3);
zran3(v, n1, n2, n3, nx[lt], ny[lt], k);
norm2u3(v, n1, n2, n3, &rnm2, &rnmu, nx[lt], ny[lt], nz[lt]);
printf(" Size: %4dx%4dx%4d (class %c)\n", nx[lt], ny[lt], nz[lt], Class);
printf(" Iterations: %3d\n", nit);
printf("\n");
resid(u, v, r, n1, n2, n3, a, k);
norm2u3(r, n1, n2, n3, &rnm2, &rnmu, nx[lt], ny[lt], nz[lt]);
old2 = rnm2;
oldu = rnmu;
//---------------------------------------------------------------------
// One iteration for startup
//---------------------------------------------------------------------
mg3P(u, v, r, a, c, n1, n2, n3);
resid(u, v, r, n1, n2, n3, a, k);
setup(&n1, &n2, &n3);
zero3(u, n1, n2, n3);
zran3(v, n1, n2, n3, nx[lt], ny[lt], k);
timer_stop(0);
tinit = timer_read(0);
printf(" Initialization time: %15.3f seconds\n\n", tinit);
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(i = 1; i < 10; i++) {
timer_clear(i);
}
timer_start(1);
resid(u, v, r, n1, n2, n3, a, k);
norm2u3(r, n1, n2, n3, &rnm2, &rnmu, nx[lt], ny[lt], nz[lt]);
old2 = rnm2;
oldu = rnmu;
/*************** Clava msgError **************
Variables Access as passed arguments Can not be traced inside of function calls :
printf#283{printf(" iter %3d\n", it)}
mg3P#285{mg3P(u, v, r, a, c, n1, n2, n3)}
resid#286{resid(u, v, r, n1, n2, n3, a, k)}
****************************************/
for(it = 1; it <= nit; it++) {
if((it == 1) || (it == nit) || ((it % 5) == 0)) {
printf(" iter %3d\n", it);
}
mg3P(u, v, r, a, c, n1, n2, n3);
resid(u, v, r, n1, n2, n3, a, k);
}
norm2u3(r, n1, n2, n3, &rnm2, &rnmu, nx[lt], ny[lt], nz[lt]);
timer_stop(1);
t = timer_read(1);
verified = 0;
verify_value = 0.0;
printf("\n Benchmark completed\n");
epsilon = 1.0e-8;
if(Class != 'U') {
if(Class == 'S') {
verify_value = 0.5307707005734e-04;
}
else if(Class == 'W') {
verify_value = 0.6467329375339e-05;
}
else if(Class == 'A') {
verify_value = 0.2433365309069e-05;
}
else if(Class == 'B') {
verify_value = 0.1800564401355e-05;
}
else if(Class == 'C') {
verify_value = 0.5706732285740e-06;
}
else if(Class == 'D') {
verify_value = 0.1583275060440e-09;
}
else if(Class == 'E') {
verify_value = 0.8157592357404e-10;
}
err = fabs(rnm2 - verify_value) / verify_value;
// err = fabs( rnm2 - verify_value );
if(err <= epsilon) {
verified = 1;
printf(" VERIFICATION SUCCESSFUL\n");
printf(" L2 Norm is %20.13E\n", rnm2);
printf(" Error is %20.13E\n", err);
}
else {
verified = 0;
printf(" VERIFICATION FAILED\n");
printf(" L2 Norm is %20.13E\n", rnm2);
printf(" The correct L2 Norm is %20.13E\n", verify_value);
}
}
else {
verified = 0;
printf(" Problem size unknown\n");
printf(" NO VERIFICATION PERFORMED\n");
printf(" L2 Norm is %20.13E\n", rnm2);
}
nn = 1.0 * nx[lt] * ny[lt] * nz[lt];
if(t != 0.0) {
mflops = 58.0 * nit * nn * 1.0e-6 / t;
}
else {
mflops = 0.0;
}
print_results("MG", Class, nx[lt], ny[lt], nz[lt], nit, t, mflops, " floating point", verified);
int exitValue = verified ? 0 : 1;
return exitValue;
}
void setup(int *n1, int *n2, int *n3) {
int k, j;
int ax;
int mi[9][3];
int ng[9][3];
ng[lt][0] = nx[lt];
ng[lt][1] = ny[lt];
ng[lt][2] = nz[lt];
/*************** Clava msgError **************
unsolved dependency for arrayAccess ng use : RW
****************************************/
for(k = lt - 1; k >= 1; k--) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(ax = 0; ax < 3; ax++) {
ng[k][ax] = ng[k + 1][ax] / 2;
}
}
#pragma omp parallel for default(shared) private(k) firstprivate(lt, ng)
for(k = lt; k >= 1; k--) {
nx[k] = ng[k][0];
ny[k] = ng[k][1];
nz[k] = ng[k][2];
}
#pragma omp parallel for default(shared) private(k, ax) firstprivate(lt, ng)
for(k = lt; k >= 1; k--) {
/*************** Clava msgError **************
Loop Iteration number is too low
****************************************/
for(ax = 0; ax < 3; ax++) {
mi[k][ax] = 2 + ng[k][ax];
}
m1[k] = mi[k][0];
m2[k] = mi[k][1];
m3[k] = mi[k][2];
}
k = lt;
is1 = 2 + ng[k][0] - ng[lt][0];
ie1 = 1 + ng[k][0];
*n1 = 3 + ie1 - is1;
is2 = 2 + ng[k][1] - ng[lt][1];
ie2 = 1 + ng[k][1];
*n2 = 3 + ie2 - is2;
is3 = 2 + ng[k][2] - ng[lt][2];
ie3 = 1 + ng[k][2];
*n3 = 3 + ie3 - is3;
ir[lt] = 0;
/*************** Clava msgError **************
unsolved dependency for arrayAccess ir use : RW
****************************************/
for(j = lt - 1; j >= 1; j--) {
ir[j] = ir[j + 1] + 1 * m1[j + 1] * m2[j + 1] * m3[j + 1];
}
if(debug_vec[1] >= 1) {
printf(" in setup, \n");
printf(" k lt nx ny nz n1 n2 n3 is1 is2 is3 ie1 ie2 ie3\n");
printf("%4d%4d%4d%4d%4d%4d%4d%4d%4d%4d%4d%4d%4d%4d\n", k, lt, ng[k][0], ng[k][1], ng[k][2], *n1, *n2, *n3, is1, is2, is3, ie1, ie2, ie3);
}
}
//---------------------------------------------------------------------
// multigrid V-cycle routine
//---------------------------------------------------------------------
void mg3P(double u[], double v[], double r[], double a[4], double c[4], int n1, int n2, int n3) {
int j, k;
//---------------------------------------------------------------------
// down cycle.
// restrict the residual from the find grid to the coarse
//---------------------------------------------------------------------
/*************** Clava msgError **************
Variables Access as passed arguments Can not be traced inside of function calls :
rprj3#435{rprj3(&r[ir[k]], m1[k], m2[k], m3[k], &r[ir[k - 1]], m1[k - 1], m2[k - 1], m3[k - 1], k)}
****************************************/
for(k = lt; k >= lb + 1; k--) {
j = k - 1;
rprj3(&r[ir[k]], m1[k], m2[k], m3[k], &r[ir[j]], m1[j], m2[j], m3[j], k);
}
k = lb;
//---------------------------------------------------------------------
// compute an approximate solution on the coarsest grid
//---------------------------------------------------------------------
zero3(&u[ir[k]], m1[k], m2[k], m3[k]);
psinv(&r[ir[k]], &u[ir[k]], m1[k], m2[k], m3[k], c, k);
/*************** Clava msgError **************
Variables Access as passed arguments Can not be traced inside of function calls :
interp#451{interp(&u[ir[k - 1]], m1[k - 1], m2[k - 1], m3[k - 1], &u[ir[k]], m1[k], m2[k], m3[k], k)}
resid#455{resid(&u[ir[k]], &r[ir[k]], &r[ir[k]], m1[k], m2[k], m3[k], a, k)}
psinv#459{psinv(&r[ir[k]], &u[ir[k]], m1[k], m2[k], m3[k], c, k)}
****************************************/
for(k = lb + 1; k <= lt - 1; k++) {
j = k - 1;
//---------------------------------------------------------------------
// prolongate from level k-1 to k
//---------------------------------------------------------------------
zero3(&u[ir[k]], m1[k], m2[k], m3[k]);
interp(&u[ir[j]], m1[j], m2[j], m3[j], &u[ir[k]], m1[k], m2[k], m3[k], k);
//---------------------------------------------------------------------
// compute residual for level k
//---------------------------------------------------------------------
resid(&u[ir[k]], &r[ir[k]], &r[ir[k]], m1[k], m2[k], m3[k], a, k);
//---------------------------------------------------------------------
// apply smoother
//---------------------------------------------------------------------
psinv(&r[ir[k]], &u[ir[k]], m1[k], m2[k], m3[k], c, k);
}
j = lt - 1;
k = lt;
interp(&u[ir[j]], m1[j], m2[j], m3[j], u, n1, n2, n3, k);
resid(u, v, r, n1, n2, n3, a, k);
psinv(r, u, n1, n2, n3, c, k);
}
//---------------------------------------------------------------------
// psinv applies an approximate inverse as smoother: u = u + Cr
//
// This implementation costs 15A + 4M per result, where
// A and M denote the costs of Addition and Multiplication.
// Presuming coefficient c(3) is zero (the NPB assumes this,
// but it is thus not a general case), 2A + 1M may be eliminated,
// resulting in 13A + 3M.
// Note that this vectorizes, and is also fine for cache
// based machines.
//---------------------------------------------------------------------
void psinv(void *or, void *ou, int n1, int n2, int n3, double c[4], int k) {
double (*r)[n2][n1] = (double (*)[n2][n1]) or;
double (*u)[n2][n1] = (double (*)[n2][n1]) ou;
int i3, i2, i1;
double r1[131];
double r2[131];
#pragma omp parallel for default(shared) private(i3, i2, i1) firstprivate(n3, n2, n1, r, c, r1, r2)
for(i3 = 1; i3 < n3 - 1; i3++) {
// #pragma omp parallel for default(shared) private(i2, i1) firstprivate(n2, n1, i3, r, c, r1, r2)
for(i2 = 1; i2 < n2 - 1; i2++) {
// #pragma omp parallel for default(shared) private(i1) firstprivate(n1, i2, i3, r)
for(i1 = 0; i1 < n1; i1++) {
r1[i1] = r[i3][i2 - 1][i1] + r[i3][i2 + 1][i1] + r[i3 - 1][i2][i1] + r[i3 + 1][i2][i1];
r2[i1] = r[i3 - 1][i2 - 1][i1] + r[i3 - 1][i2 + 1][i1] + r[i3 + 1][i2 - 1][i1] + r[i3 + 1][i2 + 1][i1];
}
// #pragma omp parallel for default(shared) private(i1) firstprivate(n1, i3, i2, r, r1, r2, c)
for(i1 = 1; i1 < n1 - 1; i1++) {
u[i3][i2][i1] = u[i3][i2][i1] + c[0] * r[i3][i2][i1] + c[1] * (r[i3][i2][i1 - 1] + r[i3][i2][i1 + 1] + r1[i1]) + c[2] * (r2[i1] + r1[i1 - 1] + r1[i1 + 1]);
//--------------------------------------------------------------------
// Assume c[3] = 0 (Enable line below if c[3] not= 0)
//--------------------------------------------------------------------
// + c[3] * ( r2[i1-1] + r2[i1+1] )
//--------------------------------------------------------------------
}
}
}
//---------------------------------------------------------------------
// exchange boundary points
//---------------------------------------------------------------------
comm3(u, n1, n2, n3, k);
if(debug_vec[0] >= 1) {
rep_nrm(u, n1, n2, n3, " psinv", k);
}
if(debug_vec[3] >= k) {
showall(u, n1, n2, n3);
}
}
//---------------------------------------------------------------------
// resid computes the residual: r = v - Au
//
// This implementation costs 15A + 4M per result, where
// A and M denote the costs of Addition (or Subtraction) and
// Multiplication, respectively.
// Presuming coefficient a(1) is zero (the NPB assumes this,
// but it is thus not a general case), 3A + 1M may be eliminated,
// resulting in 12A + 3M.
// Note that this vectorizes, and is also fine for cache
// based machines.
//---------------------------------------------------------------------
void resid(void *ou, void *ov, void *or, int n1, int n2, int n3, double a[4], int k) {
double (*u)[n2][n1] = (double (*)[n2][n1]) ou;
double (*v)[n2][n1] = (double (*)[n2][n1]) ov;
double (*r)[n2][n1] = (double (*)[n2][n1]) or;
int i3, i2, i1;
double u1[131];
double u2[131];
#pragma omp parallel for default(shared) private(i3, i2, i1) firstprivate(n3, n2, n1, u, a, v, u1, u2)
for(i3 = 1; i3 < n3 - 1; i3++) {
// #pragma omp parallel for default(shared) private(i2, i1) firstprivate(n2, n1, i3, u, a, v, u1, u2)
for(i2 = 1; i2 < n2 - 1; i2++) {
// #pragma omp parallel for default(shared) private(i1) firstprivate(n1, i2, i3, u)
for(i1 = 0; i1 < n1; i1++) {
u1[i1] = u[i3][i2 - 1][i1] + u[i3][i2 + 1][i1] + u[i3 - 1][i2][i1] + u[i3 + 1][i2][i1];
u2[i1] = u[i3 - 1][i2 - 1][i1] + u[i3 - 1][i2 + 1][i1] + u[i3 + 1][i2 - 1][i1] + u[i3 + 1][i2 + 1][i1];
}
// #pragma omp parallel for default(shared) private(i1) firstprivate(n1, i3, i2, u2, u1, a, u, v)
for(i1 = 1; i1 < n1 - 1; i1++) {
r[i3][i2][i1] = v[i3][i2][i1] - a[0] * u[i3][i2][i1] - a[2] * (u2[i1] + u1[i1 - 1] + u1[i1 + 1]) - a[3] * (u2[i1 - 1] + u2[i1 + 1]);
//-------------------------------------------------------------------
// Assume a[1] = 0 (Enable 2 lines below if a[1] not= 0)
//-------------------------------------------------------------------
// - a[1] * ( u[i3][i2][i1-1] + u[i3][i2][i1+1]
// + u1[i1] )
//-------------------------------------------------------------------
}
}
}
//---------------------------------------------------------------------
// exchange boundary data
//---------------------------------------------------------------------
comm3(r, n1, n2, n3, k);
if(debug_vec[0] >= 1) {
rep_nrm(r, n1, n2, n3, " resid", k);
}
if(debug_vec[2] >= k) {
showall(r, n1, n2, n3);
}
}
//---------------------------------------------------------------------
// rprj3 projects onto the next coarser grid,
// using a trilinear Finite Element projection: s = r' = P r
//
// This implementation costs 20A + 4M per result, where
// A and M denote the costs of Addition and Multiplication.
// Note that this vectorizes, and is also fine for cache
// based machines.
//---------------------------------------------------------------------
void rprj3(void *or, int m1k, int m2k, int m3k, void *os, int m1j, int m2j, int m3j, int k) {
double (*r)[m2k][m1k] = (double (*)[m2k][m1k]) or;
double (*s)[m2j][m1j] = (double (*)[m2j][m1j]) os;
int j3, j2, j1, i3, i2, i1, d1, d2, d3, j;
double x1[131];
double y1[131];
double x2;
double y2;
if(m1k == 3) {
d1 = 2;
}
else {
d1 = 1;
}
if(m2k == 3) {
d2 = 2;
}
else {
d2 = 1;
}
if(m3k == 3) {
d3 = 2;
}
else {
d3 = 1;
}
#pragma omp parallel for default(shared) private(j3, j2, j1, i3, i2, i1, y2, x2) firstprivate(m3j, d3, m2j, d2, m1j, d1, r, x1, y1)
for(j3 = 1; j3 < m3j - 1; j3++) {
i3 = 2 * j3 - d3;
// #pragma omp parallel for default(shared) private(j2, j1, i2, i1, y2, x2) firstprivate(m2j, d2, m1j, d1, i3, j3, d3, r, x1, y1)
for(j2 = 1; j2 < m2j - 1; j2++) {
i2 = 2 * j2 - d2;
// #pragma omp parallel for default(shared) private(j1, i1) firstprivate(m1j, d1, j2, i3, d2, i2, j3, d3, r)
for(j1 = 1; j1 < m1j; j1++) {
i1 = 2 * j1 - d1;
x1[i1] = r[i3 + 1][i2][i1] + r[i3 + 1][i2 + 2][i1] + r[i3][i2 + 1][i1] + r[i3 + 2][i2 + 1][i1];
y1[i1] = r[i3][i2][i1] + r[i3 + 2][i2][i1] + r[i3][i2 + 2][i1] + r[i3 + 2][i2 + 2][i1];
}
// #pragma omp parallel for default(shared) private(j1, i1, y2, x2) firstprivate(m1j, d1, j3, j2, d3, d2, i3, i2, r, x1, y1)
for(j1 = 1; j1 < m1j - 1; j1++) {
i1 = 2 * j1 - d1;
y2 = r[i3][i2][i1 + 1] + r[i3 + 2][i2][i1 + 1] + r[i3][i2 + 2][i1 + 1] + r[i3 + 2][i2 + 2][i1 + 1];
x2 = r[i3 + 1][i2][i1 + 1] + r[i3 + 1][i2 + 2][i1 + 1] + r[i3][i2 + 1][i1 + 1] + r[i3 + 2][i2 + 1][i1 + 1];
s[j3][j2][j1] = 0.5 * r[i3 + 1][i2 + 1][i1 + 1] + 0.25 * (r[i3 + 1][i2 + 1][i1] + r[i3 + 1][i2 + 1][i1 + 2] + x2) + 0.125 * (x1[i1] + x1[i1 + 2] + y2) + 0.0625 * (y1[i1] + y1[i1 + 2]);
}
}
}
j = k - 1;
comm3(s, m1j, m2j, m3j, j);
if(debug_vec[0] >= 1) {
rep_nrm(s, m1j, m2j, m3j, " rprj3", k - 1);
}
if(debug_vec[4] >= k) {
showall(s, m1j, m2j, m3j);
}
}
//---------------------------------------------------------------------
// interp adds the trilinear interpolation of the correction
// from the coarser grid to the current approximation: u = u + Qu'
//
// Observe that this implementation costs 16A + 4M, where
// A and M denote the costs of Addition and Multiplication.
// Note that this vectorizes, and is also fine for cache
// based machines. Vector machines may get slightly better
// performance however, with 8 separate "do i1" loops, rather than 4.
//---------------------------------------------------------------------
void interp(void *oz, int mm1, int mm2, int mm3, void *ou, int n1, int n2, int n3, int k) {
double (*z)[mm2][mm1] = (double (*)[mm2][mm1]) oz;
double (*u)[n2][n1] = (double (*)[n2][n1]) ou;
int i3, i2, i1, d1, d2, d3, t1, t2, t3;
// note that m = 1037 in globals.h but for this only need to be
// 535 to handle up to 1024^3
// integer m
// parameter( m=535 )
double z1[131];
double z2[131];
double z3[131];
if(n1 != 3 && n2 != 3 && n3 != 3) {
#pragma omp parallel for default(shared) private(i3, i2, i1) firstprivate(mm3, mm2, mm1, z, z1, z2, z3)
for(i3 = 0; i3 < mm3 - 1; i3++) {
// #pragma omp parallel for default(shared) private(i2, i1) firstprivate(mm2, mm1, i3, z, z1, z2, z3)
for(i2 = 0; i2 < mm2 - 1; i2++) {
// #pragma omp parallel for default(shared) private(i1) firstprivate(mm1, i2, i3, z)
for(i1 = 0; i1 < mm1; i1++) {
z1[i1] = z[i3][i2 + 1][i1] + z[i3][i2][i1];
z2[i1] = z[i3 + 1][i2][i1] + z[i3][i2][i1];
z3[i1] = z[i3 + 1][i2 + 1][i1] + z[i3 + 1][i2][i1] + z1[i1];
}
// #pragma omp parallel for default(shared) private(i1) firstprivate(mm1, i3, i2, z)
for(i1 = 0; i1 < mm1 - 1; i1++) {
u[2 * i3][2 * i2][2 * i1] = u[2 * i3][2 * i2][2 * i1] + z[i3][i2][i1];
u[2 * i3][2 * i2][2 * i1 + 1] = u[2 * i3][2 * i2][2 * i1 + 1] + 0.5 * (z[i3][i2][i1 + 1] + z[i3][i2][i1]);
}
// #pragma omp parallel for default(shared) private(i1) firstprivate(mm1, i2, i3, z1)
for(i1 = 0; i1 < mm1 - 1; i1++) {
u[2 * i3][2 * i2 + 1][2 * i1] = u[2 * i3][2 * i2 + 1][2 * i1] + 0.5 * z1[i1];
u[2 * i3][2 * i2 + 1][2 * i1 + 1] = u[2 * i3][2 * i2 + 1][2 * i1 + 1] + 0.25 * (z1[i1] + z1[i1 + 1]);
}
// #pragma omp parallel for default(shared) private(i1) firstprivate(mm1, i3, i2, z2)
for(i1 = 0; i1 < mm1 - 1; i1++) {
u[2 * i3 + 1][2 * i2][2 * i1] = u[2 * i3 + 1][2 * i2][2 * i1] + 0.5 * z2[i1];
u[2 * i3 + 1][2 * i2][2 * i1 + 1] = u[2 * i3 + 1][2 * i2][2 * i1 + 1] + 0.25 * (z2[i1] + z2[i1 + 1]);
}
// #pragma omp parallel for default(shared) private(i1) firstprivate(mm1, i3, i2, z3)
for(i1 = 0; i1 < mm1 - 1; i1++) {
u[2 * i3 + 1][2 * i2 + 1][2 * i1] = u[2 * i3 + 1][2 * i2 + 1][2 * i1] + 0.25 * z3[i1];
u[2 * i3 + 1][2 * i2 + 1][2 * i1 + 1] = u[2 * i3 + 1][2 * i2 + 1][2 * i1 + 1] + 0.125 * (z3[i1] + z3[i1 + 1]);
}
}
}
}
else {
if(n1 == 3) {
d1 = 2;
t1 = 1;
}
else {
d1 = 1;
t1 = 0;
}
if(n2 == 3) {
d2 = 2;
t2 = 1;
}
else {
d2 = 1;
t2 = 0;
}
if(n3 == 3) {
d3 = 2;
t3 = 1;
}
else {
d3 = 1;
t3 = 0;
}
#pragma omp parallel for default(shared) private(i3, i2, i1) firstprivate(d3, mm3, d2, mm2, d1, mm1, t1, t2, z)
for(i3 = d3; i3 <= mm3 - 1; i3++) {
// #pragma omp parallel for default(shared) private(i2, i1) firstprivate(d2, mm2, d1, mm1, i3, d3, t1, z)
for(i2 = d2; i2 <= mm2 - 1; i2++) {
// #pragma omp parallel for default(shared) private(i1) firstprivate(d1, mm1, i3, i2, d3, d2, z)
for(i1 = d1; i1 <= mm1 - 1; i1++) {
u[2 * i3 - d3 - 1][2 * i2 - d2 - 1][2 * i1 - d1 - 1] = u[2 * i3 - d3 - 1][2 * i2 - d2 - 1][2 * i1 - d1 - 1] + z[i3 - 1][i2 - 1][i1 - 1];
}
// #pragma omp parallel for default(shared) private(i1) firstprivate(mm1, i3, i2, d3, d2, t1, z)
for(i1 = 1; i1 <= mm1 - 1; i1++) {
u[2 * i3 - d3 - 1][2 * i2 - d2 - 1][2 * i1 - t1 - 1] = u[2 * i3 - d3 - 1][2 * i2 - d2 - 1][2 * i1 - t1 - 1] + 0.5 * (z[i3 - 1][i2 - 1][i1] + z[i3 - 1][i2 - 1][i1 - 1]);
}
}
// #pragma omp parallel for default(shared) private(i2, i1) firstprivate(mm2, d1, mm1, i3, d3, t2, t1, z)
for(i2 = 1; i2 <= mm2 - 1; i2++) {
// #pragma omp parallel for default(shared) private(i1) firstprivate(d1, mm1, i3, i2, d3, t2, z)
for(i1 = d1; i1 <= mm1 - 1; i1++) {
u[2 * i3 - d3 - 1][2 * i2 - t2 - 1][2 * i1 - d1 - 1] = u[2 * i3 - d3 - 1][2 * i2 - t2 - 1][2 * i1 - d1 - 1] + 0.5 * (z[i3 - 1][i2][i1 - 1] + z[i3 - 1][i2 - 1][i1 - 1]);
}
// #pragma omp parallel for default(shared) private(i1) firstprivate(mm1, i3, i2, d3, t2, t1, z)
for(i1 = 1; i1 <= mm1 - 1; i1++) {
u[2 * i3 - d3 - 1][2 * i2 - t2 - 1][2 * i1 - t1 - 1] = u[2 * i3 - d3 - 1][2 * i2 - t2 - 1][2 * i1 - t1 - 1] + 0.25 * (z[i3 - 1][i2][i1] + z[i3 - 1][i2 - 1][i1] + z[i3 - 1][i2][i1 - 1] + z[i3 - 1][i2 - 1][i1 - 1]);
}
}
}
#pragma omp parallel for default(shared) private(i3, i2, i1) firstprivate(mm3, d2, mm2, d1, mm1, t3, t1, t2, z)
for(i3 = 1; i3 <= mm3 - 1; i3++) {
// #pragma omp parallel for default(shared) private(i2, i1) firstprivate(d2, mm2, d1, mm1, i3, t3, t1, z)
for(i2 = d2; i2 <= mm2 - 1; i2++) {
// #pragma omp parallel for default(shared) private(i1) firstprivate(d1, mm1, i2, i3, t3, d2, z)
for(i1 = d1; i1 <= mm1 - 1; i1++) {
u[2 * i3 - t3 - 1][2 * i2 - d2 - 1][2 * i1 - d1 - 1] = u[2 * i3 - t3 - 1][2 * i2 - d2 - 1][2 * i1 - d1 - 1] + 0.5 * (z[i3][i2 - 1][i1 - 1] + z[i3 - 1][i2 - 1][i1 - 1]);
}
// #pragma omp parallel for default(shared) private(i1) firstprivate(mm1, i2, i3, t3, d2, t1, z)
for(i1 = 1; i1 <= mm1 - 1; i1++) {
u[2 * i3 - t3 - 1][2 * i2 - d2 - 1][2 * i1 - t1 - 1] = u[2 * i3 - t3 - 1][2 * i2 - d2 - 1][2 * i1 - t1 - 1] + 0.25 * (z[i3][i2 - 1][i1] + z[i3][i2 - 1][i1 - 1] + z[i3 - 1][i2 - 1][i1] + z[i3 - 1][i2 - 1][i1 - 1]);
}
}
// #pragma omp parallel for default(shared) private(i2, i1) firstprivate(mm2, d1, mm1, i3, t3, t2, t1, z)
for(i2 = 1; i2 <= mm2 - 1; i2++) {
// #pragma omp parallel for default(shared) private(i1) firstprivate(d1, mm1, i2, i3, t3, t2, z)
for(i1 = d1; i1 <= mm1 - 1; i1++) {
u[2 * i3 - t3 - 1][2 * i2 - t2 - 1][2 * i1 - d1 - 1] = u[2 * i3 - t3 - 1][2 * i2 - t2 - 1][2 * i1 - d1 - 1] + 0.25 * (z[i3][i2][i1 - 1] + z[i3][i2 - 1][i1 - 1] + z[i3 - 1][i2][i1 - 1] + z[i3 - 1][i2 - 1][i1 - 1]);
}
// #pragma omp parallel for default(shared) private(i1) firstprivate(mm1, i2, i3, t3, t2, t1, z)
for(i1 = 1; i1 <= mm1 - 1; i1++) {
u[2 * i3 - t3 - 1][2 * i2 - t2 - 1][2 * i1 - t1 - 1] = u[2 * i3 - t3 - 1][2 * i2 - t2 - 1][2 * i1 - t1 - 1] + 0.125 * (z[i3][i2][i1] + z[i3][i2 - 1][i1] + z[i3][i2][i1 - 1] + z[i3][i2 - 1][i1 - 1] + z[i3 - 1][i2][i1] + z[i3 - 1][i2 - 1][i1] + z[i3 - 1][i2][i1 - 1] + z[i3 - 1][i2 - 1][i1 - 1]);
}
}
}
}
if(debug_vec[0] >= 1) {
rep_nrm(z, mm1, mm2, mm3, "z: inter", k - 1);
rep_nrm(u, n1, n2, n3, "u: inter", k);
}
if(debug_vec[5] >= k) {
showall(z, mm1, mm2, mm3);
showall(u, n1, n2, n3);
}
}
//---------------------------------------------------------------------
// norm2u3 evaluates approximations to the L2 norm and the
// uniform (or L-infinity or Chebyshev) norm, under the
// assumption that the boundaries are periodic or zero. Add the
// boundaries in with half weight (quarter weight on the edges
// and eighth weight at the corners) for inhomogeneous boundaries.
//---------------------------------------------------------------------
void norm2u3(void *or, int n1, int n2, int n3, double *rnm2, double *rnmu, int nx, int ny, int nz) {
double (*r)[n2][n1] = (double (*)[n2][n1]) or;
double s, a;
int i3, i2, i1;
double dn;
dn = 1.0 * nx * ny * nz;
s = 0.0;
*rnmu = 0.0;
/*************** Clava msgError **************
Variable rnmu could not be categorized into any OpenMP Variable Scopeuse : RW
****************************************/
for(i3 = 1; i3 < n3 - 1; i3++) {
/*************** Clava msgError **************
Variable rnmu could not be categorized into any OpenMP Variable Scopeuse : RW
****************************************/
for(i2 = 1; i2 < n2 - 1; i2++) {
/*************** Clava msgError **************
Variable rnmu could not be categorized into any OpenMP Variable Scopeuse : RW
****************************************/
for(i1 = 1; i1 < n1 - 1; i1++) {
s = s + pow(r[i3][i2][i1], 2.0);
a = fabs(r[i3][i2][i1]);
if(a > *rnmu) *rnmu = a;
}
}
}
*rnm2 = sqrt(s / dn);
}
//---------------------------------------------------------------------
// report on norm
//---------------------------------------------------------------------
void rep_nrm(void *u, int n1, int n2, int n3, char *title, int kk) {
double rnm2, rnmu;
norm2u3(u, n1, n2, n3, &rnm2, &rnmu, nx[kk], ny[kk], nz[kk]);
printf(" Level%2d in %8s: norms =%21.14E%21.14E\n", kk, title, rnm2, rnmu);
}
//---------------------------------------------------------------------
// comm3 organizes the communication on all borders
//---------------------------------------------------------------------
void comm3(void *ou, int n1, int n2, int n3, int kk) {
double (*u)[n2][n1] = (double (*)[n2][n1]) ou;
int i1, i2, i3;
#pragma omp parallel for default(shared) private(i3, i2) firstprivate(n3, n2, n1)
for(i3 = 1; i3 < n3 - 1; i3++) {
// #pragma omp parallel for default(shared) private(i2) firstprivate(n2, n1, i3)
for(i2 = 1; i2 < n2 - 1; i2++) {
u[i3][i2][0] = u[i3][i2][n1 - 2];
u[i3][i2][n1 - 1] = u[i3][i2][1];
}
}
#pragma omp parallel for default(shared) private(i3, i1) firstprivate(n3, n1, n2)
for(i3 = 1; i3 < n3 - 1; i3++) {
// #pragma omp parallel for default(shared) private(i1) firstprivate(n1, n2, i3)
for(i1 = 0; i1 < n1; i1++) {
u[i3][0][i1] = u[i3][n2 - 2][i1];
u[i3][n2 - 1][i1] = u[i3][1][i1];
}
}
#pragma omp parallel for default(shared) private(i2, i1) firstprivate(n2, n1, n3)
for(i2 = 0; i2 < n2; i2++) {
// #pragma omp parallel for default(shared) private(i1) firstprivate(n1, n3, i2)
for(i1 = 0; i1 < n1; i1++) {
u[0][i2][i1] = u[n3 - 2][i2][i1];
u[n3 - 1][i2][i1] = u[1][i2][i1];
}
}
}
//---------------------------------------------------------------------
// zran3 loads +1 at ten randomly chosen points,
// loads -1 at a different ten random points,
// and zero elsewhere.
//---------------------------------------------------------------------
void zran3(void *oz, int n1, int n2, int n3, int nx, int ny, int k) {
double (*z)[n2][n1] = (double (*)[n2][n1]) oz;
int i0, m0, m1;
int i1, i2, i3, d1, e1, e2, e3;
double xx, x0, x1, a1, a2, ai;
int const mm = 10;
double const a = pow(5.0, 13.0);
double const x = 314159265.0;
double ten[mm][2];
double best;
int i;
int j1[mm][2];
int j2[mm][2];
int j3[mm][2];
int jg[4][mm][2];
double rdummy;
a1 = power(a, nx);
a2 = power(a, nx * ny);
zero3(z, n1, n2, n3);
i = is1 - 2 + nx * (is2 - 2 + ny * (is3 - 2));
ai = power(a, i);
d1 = ie1 - is1 + 1;
e1 = ie1 - is1 + 2;
e2 = ie2 - is2 + 2;
e3 = ie3 - is3 + 2;
x0 = x;
rdummy = randlc(&x0, ai);
/*************** Clava msgError **************
Variables Access as passed arguments Can not be traced inside of function calls :
vranlc#931{vranlc(d1, &xx, a, &(z[i3][i2][1]))}
****************************************/
for(i3 = 1; i3 < e3; i3++) {
x1 = x0;
/*************** Clava msgError **************
Variables Access as passed arguments Can not be traced inside of function calls :
vranlc#931{vranlc(d1, &xx, a, &(z[i3][i2][1]))}
****************************************/
for(i2 = 1; i2 < e2; i2++) {
xx = x1;
vranlc(d1, &xx, a, &(z[i3][i2][1]));
rdummy = randlc(&x1, a1);
}
rdummy = randlc(&x0, a2);
}
//---------------------------------------------------------------------
// comm3(z,n1,n2,n3);
// showall(z,n1,n2,n3);
//---------------------------------------------------------------------
//---------------------------------------------------------------------
// each processor looks for twenty candidates
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(i) firstprivate(mm)
for(i = 0; i < mm; i++) {
ten[i][1] = 0.0;
j1[i][1] = 0;
j2[i][1] = 0;
j3[i][1] = 0;
ten[i][0] = 1.0;
j1[i][0] = 0;
j2[i][0] = 0;
j3[i][0] = 0;
}
/*************** Clava msgError **************
Variables Access as passed arguments Can not be traced inside of function calls :
bubble#1011{bubble(ten, j1, j2, j3, mm, 1)}
bubble#1018{bubble(ten, j1, j2, j3, mm, 0)}
****************************************/
for(i3 = 1; i3 < n3 - 1; i3++) {
/*************** Clava msgError **************
Variables Access as passed arguments Can not be traced inside of function calls :
bubble#1011{bubble(ten, j1, j2, j3, mm, 1)}
bubble#1018{bubble(ten, j1, j2, j3, mm, 0)}
****************************************/
for(i2 = 1; i2 < n2 - 1; i2++) {
/*************** Clava msgError **************
Variables Access as passed arguments Can not be traced inside of function calls :
bubble#1011{bubble(ten, j1, j2, j3, mm, 1)}
bubble#1018{bubble(ten, j1, j2, j3, mm, 0)}
****************************************/
for(i1 = 1; i1 < n1 - 1; i1++) {
if(z[i3][i2][i1] > ten[0][1]) {
ten[0][1] = z[i3][i2][i1];
j1[0][1] = i1;
j2[0][1] = i2;
j3[0][1] = i3;
bubble(ten, j1, j2, j3, mm, 1);
}
if(z[i3][i2][i1] < ten[0][0]) {
ten[0][0] = z[i3][i2][i1];
j1[0][0] = i1;
j2[0][0] = i2;
j3[0][0] = i3;
bubble(ten, j1, j2, j3, mm, 0);
}
}
}
}
//---------------------------------------------------------------------
// Now which of these are globally best?
//---------------------------------------------------------------------
i1 = mm - 1;
i0 = mm - 1;
/*************** Clava msgError **************
Variable i1 could not be categorized into any OpenMP Variable Scopeuse : RW
Variable i0 could not be categorized into any OpenMP Variable Scopeuse : RW
****************************************/
for(i = mm - 1; i >= 0; i--) {
best = 0.0;
if(best < ten[i1][1]) {
jg[0][i][1] = 0;
jg[1][i][1] = is1 - 2 + j1[i1][1];
jg[2][i][1] = is2 - 2 + j2[i1][1];
jg[3][i][1] = is3 - 2 + j3[i1][1];
i1 = i1 - 1;
}
else {
jg[0][i][1] = 0;
jg[1][i][1] = 0;
jg[2][i][1] = 0;
jg[3][i][1] = 0;
}
best = 1.0;
if(best > ten[i0][0]) {
jg[0][i][0] = 0;
jg[1][i][0] = is1 - 2 + j1[i0][0];
jg[2][i][0] = is2 - 2 + j2[i0][0];
jg[3][i][0] = is3 - 2 + j3[i0][0];
i0 = i0 - 1;
}
else {
jg[0][i][0] = 0;
jg[1][i][0] = 0;
jg[2][i][0] = 0;
jg[3][i][0] = 0;
}
}
// m1 = i1+1;
// m0 = i0+1;
m1 = 0;
m0 = 0;
/*
int cnt = 0;
printf(" \n");
printf(" negative charges at\n");
for (i = 0; i < mm; i++) {
printf(" (%3d,%3d,%3d)", jg[1][i][0], jg[2][i][0], jg[3][i][0]);
if (++cnt % 5 == 0) printf("\n");
}
cnt = 0;
printf(" positive charges at\n");
for (i = 0; i < mm; i++) {
printf(" (%3d,%3d,%3d)", jg[1][i][1], jg[2][i][1], jg[3][i][1]);
if (++cnt % 5 == 0) printf("\n");
}
cnt = 0;
printf(" small random numbers were\n");
for (i = mm-1; i >= 0; i--) {
printf(" %15.8E", ten[i][0]);
if (++cnt % 5 == 0) printf("\n");
}
cnt = 0;
printf(" and they were found on processor number\n");
for (i = mm-1; i >= 0; i--) {
printf(" %4d", jg[0][i][0]);
if (++cnt % 10 == 0) printf("\n");
}
cnt = 0;
printf(" large random numbers were\n");
for (i = mm-1; i >= 0; i--) {
printf(" %15.8E", ten[i][1]);
if (++cnt % 5 == 0) printf("\n");
}
cnt = 0;
printf(" and they were found on processor number\n");
for (i = mm-1; i >= 0; i--) {
printf(" %4d", jg[0][i][1]);
if (++cnt % 10 == 0) printf("\n");
}
*/
#pragma omp parallel for default(shared) private(i3, i2, i1) firstprivate(n3, n2, n1)
for(i3 = 0; i3 < n3; i3++) {
// #pragma omp parallel for default(shared) private(i2, i1) firstprivate(n2, n1, i3)
for(i2 = 0; i2 < n2; i2++) {
// #pragma omp parallel for default(shared) private(i1) firstprivate(n1, i3, i2)
for(i1 = 0; i1 < n1; i1++) {
z[i3][i2][i1] = 0.0;
}
}
}
/*************** Clava msgError **************
Array access z[jg[3][i][0]][jg[2][i][0]][jg[1][i][0]] which is used for writing has subscript of arrayType jg[3][i][0]
****************************************/
for(i = mm - 1; i >= m0; i--) {
z[jg[3][i][0]][jg[2][i][0]][jg[1][i][0]] = -1.0;
}
/*************** Clava msgError **************
Array access z[jg[3][i][1]][jg[2][i][1]][jg[1][i][1]] which is used for writing has subscript of arrayType jg[3][i][1]
****************************************/
for(i = mm - 1; i >= m1; i--) {
z[jg[3][i][1]][jg[2][i][1]][jg[1][i][1]] = +1.0;
}
comm3(z, n1, n2, n3, k);
//---------------------------------------------------------------------
// showall(z,n1,n2,n3);
//---------------------------------------------------------------------
}
void showall(void *oz, int n1, int n2, int n3) {
double (*z)[n2][n1] = (double (*)[n2][n1]) oz;
int i1, i2, i3;
int m1, m2, m3;
m1 = ((n1) < (18) ? (n1) : (18));
m2 = ((n2) < (14) ? (n2) : (14));
m3 = ((n3) < (18) ? (n3) : (18));
printf(" \n");
/*************** Clava msgError **************
Variables Access as passed arguments Can not be traced inside of function calls :
printf#1154{printf("%6.3f", z[i3][i2][i1])}
printf#1156{printf("\n")}
printf#1158{printf(" - - - - - - - \n")}
****************************************/
for(i3 = 0; i3 < m3; i3++) {
/*************** Clava msgError **************
Variables Access as passed arguments Can not be traced inside of function calls :
printf#1154{printf("%6.3f", z[i3][i2][i1])}
printf#1156{printf("\n")}
****************************************/
for(i1 = 0; i1 < m1; i1++) {
/*************** Clava msgError **************
Variables Access as passed arguments Can not be traced inside of function calls :
printf#1154{printf("%6.3f", z[i3][i2][i1])}
****************************************/
for(i2 = 0; i2 < m2; i2++) {
printf("%6.3f", z[i3][i2][i1]);
}
printf("\n");
}
printf(" - - - - - - - \n");
}
printf(" \n");
}
//---------------------------------------------------------------------
// power raises an integer, disguised as a double
// precision real, to an integer power
//---------------------------------------------------------------------
double power(double a, int n) {
double aj;
int nj;
double rdummy;
double power;
power = 1.0;
nj = n;
aj = a;
while(nj != 0) {
if((nj % 2) == 1) rdummy = randlc(&power, aj);
rdummy = randlc(&aj, aj);
nj = nj / 2;
}
return power;
}
//---------------------------------------------------------------------
// bubble does a bubble sort in direction dir
//---------------------------------------------------------------------
void bubble(double ten[][2], int j1[][2], int j2[][2], int j3[][2], int m, int ind) {
double temp;
int i, j_temp;
if(ind == 1) {
/*************** Clava msgError **************
Loop contains Invalid Statement -> ReturnStmt#1212
****************************************/
for(i = 0; i < m - 1; i++) {
if(ten[i][ind] > ten[i + 1][ind]) {
temp = ten[i + 1][ind];
ten[i + 1][ind] = ten[i][ind];
ten[i][ind] = temp;
j_temp = j1[i + 1][ind];
j1[i + 1][ind] = j1[i][ind];
j1[i][ind] = j_temp;
j_temp = j2[i + 1][ind];
j2[i + 1][ind] = j2[i][ind];
j2[i][ind] = j_temp;
j_temp = j3[i + 1][ind];
j3[i + 1][ind] = j3[i][ind];
j3[i][ind] = j_temp;
}
else {
return;
}
}
}
else {
/*************** Clava msgError **************
Loop contains Invalid Statement -> ReturnStmt#1236
****************************************/
for(i = 0; i < m - 1; i++) {
if(ten[i][ind] < ten[i + 1][ind]) {
temp = ten[i + 1][ind];
ten[i + 1][ind] = ten[i][ind];
ten[i][ind] = temp;
j_temp = j1[i + 1][ind];
j1[i + 1][ind] = j1[i][ind];
j1[i][ind] = j_temp;
j_temp = j2[i + 1][ind];
j2[i + 1][ind] = j2[i][ind];
j2[i][ind] = j_temp;
j_temp = j3[i + 1][ind];
j3[i + 1][ind] = j3[i][ind];
j3[i][ind] = j_temp;
}
else {
return;
}
}
}
}
void zero3(void *oz, int n1, int n2, int n3) {
double (*z)[n2][n1] = (double (*)[n2][n1]) oz;
int i1, i2, i3;
#pragma omp parallel for default(shared) private(i3, i2, i1) firstprivate(n3, n2, n1)
for(i3 = 0; i3 < n3; i3++) {
// #pragma omp parallel for default(shared) private(i2, i1) firstprivate(n2, n1, i3)
for(i2 = 0; i2 < n2; i2++) {
// #pragma omp parallel for default(shared) private(i1) firstprivate(n1, i3, i2)
for(i1 = 0; i1 < n1; i1++) {
z[i3][i2][i1] = 0.0;
}
}
}
}
double randlc(double *x, double a) {
//--------------------------------------------------------------------
//
// This routine returns a uniform pseudorandom double precision number in the
// range (0, 1) by using the linear congruential generator
//
// x_{k+1} = a x_k (mod 2^46)
//
// where 0 < x_k < 2^46 and 0 < a < 2^46. This scheme generates 2^44 numbers
// before repeating. The argument A is the same as 'a' in the above formula,
// and X is the same as x_0. A and X must be odd double precision integers
// in the range (1, 2^46). The returned value RANDLC is normalized to be
// between 0 and 1, i.e. RANDLC = 2^(-46) * x_1. X is updated to contain
// the new seed x_1, so that subsequent calls to RANDLC using the same
// arguments will generate a continuous sequence.
//
// This routine should produce the same results on any computer with at least
// 48 mantissa bits in double precision floating point data. On 64 bit
// systems, double precision should be disabled.
//
// David H. Bailey October 26, 1990
//
//--------------------------------------------------------------------
// r23 = pow(0.5, 23.0);
//// pow(0.5, 23.0) = 1.1920928955078125e-07
// r46 = r23 * r23;
// t23 = pow(2.0, 23.0);
//// pow(2.0, 23.0) = 8.388608e+06
// t46 = t23 * t23;
double const r23 = 1.1920928955078125e-07;
double const r46 = r23 * r23;
double const t23 = 8.388608e+06;
double const t46 = t23 * t23;
double t1, t2, t3, t4, a1, a2, x1, x2, z;
double r;
//--------------------------------------------------------------------
// Break A into two parts such that A = 2^23 * A1 + A2.
//--------------------------------------------------------------------
t1 = r23 * a;
a1 = (int) t1;
a2 = a - t23 * a1;
//--------------------------------------------------------------------
// Break X into two parts such that X = 2^23 * X1 + X2, compute
// Z = A1 * X2 + A2 * X1 (mod 2^23), and then
// X = 2^23 * Z + A2 * X2 (mod 2^46).
//--------------------------------------------------------------------
t1 = r23 * (*x);
x1 = (int) t1;
x2 = *x - t23 * x1;
t1 = a1 * x2 + a2 * x1;
t2 = (int) (r23 * t1);
z = t1 - t23 * t2;
t3 = t23 * z + a2 * x2;
t4 = (int) (r46 * t3);
*x = t3 - t46 * t4;
r = r46 * (*x);
return r;
}
void vranlc(int n, double *x, double a, double y[]) {
//--------------------------------------------------------------------
//
// This routine generates N uniform pseudorandom double precision numbers in
// the range (0, 1) by using the linear congruential generator
//
// x_{k+1} = a x_k (mod 2^46)
//
// where 0 < x_k < 2^46 and 0 < a < 2^46. This scheme generates 2^44 numbers
// before repeating. The argument A is the same as 'a' in the above formula,
// and X is the same as x_0. A and X must be odd double precision integers
// in the range (1, 2^46). The N results are placed in Y and are normalized
// to be between 0 and 1. X is updated to contain the new seed, so that
// subsequent calls to VRANLC using the same arguments will generate a
// continuous sequence. If N is zero, only initialization is performed, and
// the variables X, A and Y are ignored.
//
// This routine is the standard version designed for scalar or RISC systems.
// However, it should produce the same results on any single processor
// computer with at least 48 mantissa bits in double precision floating point
// data. On 64 bit systems, double precision should be disabled.
//
//--------------------------------------------------------------------
// r23 = pow(0.5, 23.0);
//// pow(0.5, 23.0) = 1.1920928955078125e-07
// r46 = r23 * r23;
// t23 = pow(2.0, 23.0);
//// pow(2.0, 23.0) = 8.388608e+06
// t46 = t23 * t23;
double const r23 = 1.1920928955078125e-07;
double const r46 = r23 * r23;
double const t23 = 8.388608e+06;
double const t46 = t23 * t23;
double t1, t2, t3, t4, a1, a2, x1, x2, z;
int i;
//--------------------------------------------------------------------
// Break A into two parts such that A = 2^23 * A1 + A2.
//--------------------------------------------------------------------
t1 = r23 * a;
a1 = (int) t1;
a2 = a - t23 * a1;
//--------------------------------------------------------------------
// Generate N results. This loop is not vectorizable.
//--------------------------------------------------------------------
/*************** Clava msgError **************
Variable x could not be categorized into any OpenMP Variable Scopeuse : RWR
****************************************/
for(i = 0; i < n; i++) {
//--------------------------------------------------------------------
// Break X into two parts such that X = 2^23 * X1 + X2, compute
// Z = A1 * X2 + A2 * X1 (mod 2^23), and then
// X = 2^23 * Z + A2 * X2 (mod 2^46).
//--------------------------------------------------------------------
t1 = r23 * (*x);
x1 = (int) t1;
x2 = *x - t23 * x1;
t1 = a1 * x2 + a2 * x1;
t2 = (int) (r23 * t1);
z = t1 - t23 * t2;
t3 = t23 * z + a2 * x2;
t4 = (int) (r46 * t3);
*x = t3 - t46 * t4;
y[i] = r46 * (*x);
}
return;
}
void print_results(char *name, char class, int n1, int n2, int n3, int niter, double t, double mops, char *optype, int verified) {
char size[16];
int j;
printf("\n\n %s Benchmark Completed.\n", name);
printf(" Class = %12c\n", class);
// If this is not a grid-based problem (EP, FT, CG), then
// we only print n1, which contains some measure of the
// problem size. In that case, n2 and n3 are both zero.
// Otherwise, we print the grid size n1xn2xn3
if((n2 == 0) && (n3 == 0)) {
if((name[0] == 'E') && (name[1] == 'P')) {
sprintf(size, "%15.0lf", pow(2.0, n1));
j = 14;
if(size[j] == '.') {
size[j] = ' ';
j--;
}
size[j + 1] = '\0';
printf(" Size = %15s\n", size);
}
else {
printf(" Size = %12d\n", n1);
}
}
else {
printf(" Size = %4dx%4dx%4d\n", n1, n2, n3);
}
printf(" Iterations = %12d\n", niter);
printf(" Time in seconds = %12.2lf\n", t);
printf(" Mop/s total = %15.2lf\n", mops);
printf(" Operation type = %24s\n", optype);
if(verified) printf(" Verification = %12s\n", "SUCCESSFUL");
else printf(" Verification = %12s\n", "UNSUCCESSFUL");
}
void wtime(double *t) {
static int sec = -1;
struct timeval tv;
gettimeofday(&tv, (void *) 0);
if(sec < 0) sec = tv.tv_sec;
*t = (tv.tv_sec - sec) + 1.0e-6 * tv.tv_usec;
}
/*****************************************************************/
/****** E L A P S E D _ T I M E ******/
/*****************************************************************/
double elapsed_time() {
double t;
wtime(&t);
return (t);
}
/*****************************************************************/
/****** T I M E R _ C L E A R ******/
/*****************************************************************/
void timer_clear(int n) {
elapsed[n] = 0.0;
}
/*****************************************************************/
/****** T I M E R _ S T A R T ******/
/*****************************************************************/
void timer_start(int n) {
start[n] = elapsed_time();
}
/*****************************************************************/
/****** T I M E R _ S T O P ******/
/*****************************************************************/
void timer_stop(int n) {
double t, now;
now = elapsed_time();
t = now - start[n];
elapsed[n] += t;
}
/*****************************************************************/
/****** T I M E R _ R E A D ******/
/*****************************************************************/
double timer_read(int n) {
return (elapsed[n]);
}
|
is.c | /*--------------------------------------------------------------------
NAS Parallel Benchmarks 2.3 OpenMP C versions - IS
This benchmark is an OpenMP C version of the NPB IS code.
The OpenMP C versions are developed by RWCP and derived from the serial
Fortran versions in "NPB 2.3-serial" developed by NAS.
Permission to use, copy, distribute and modify this software for any
purpose with or without fee is hereby granted.
This software is provided "as is" without express or implied warranty.
Send comments on the OpenMP C versions to pdp-openmp@rwcp.or.jp
Information on OpenMP activities at RWCP is available at:
http://pdplab.trc.rwcp.or.jp/pdperf/Omni/
Information on NAS Parallel Benchmarks 2.3 is available at:
http://www.nas.nasa.gov/NAS/NPB/
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
Author: M. Yarrow
OpenMP C version: S. Satoh
--------------------------------------------------------------------*/
#include "npbparams.h"
#include <stdlib.h>
#include <stdio.h>
#if defined(_OPENMP)
#include <omp.h>
#endif /* _OPENMP */
/*****************************************************************/
/* For serial IS, buckets are not really req'd to solve NPB1 IS */
/* spec, but their use on some machines improves performance, on */
/* other machines the use of buckets compromises performance, */
/* probably because it is extra computation which is not req'd. */
/* (Note: Mechanism not understood, probably cache related) */
/* Example: SP2-66MhzWN: 50% speedup with buckets */
/* Example: SGI Indy5000: 50% slowdown with buckets */
/* Example: SGI O2000: 400% slowdown with buckets (Wow!) */
/*****************************************************************/
/* #define USE_BUCKETS */
/* buckets are not used in the OpenMP C version */
/******************/
/* default values */
/******************/
#ifndef CLASS
#define CLASS 'S'
#endif
/*************/
/* CLASS S */
/*************/
#if CLASS == 'S'
#define TOTAL_KEYS_LOG_2 16
#define MAX_KEY_LOG_2 11
#define NUM_BUCKETS_LOG_2 9
#endif
/*************/
/* CLASS W */
/*************/
#if CLASS == 'W'
#define TOTAL_KEYS_LOG_2 20
#define MAX_KEY_LOG_2 16
#define NUM_BUCKETS_LOG_2 10
#endif
/*************/
/* CLASS A */
/*************/
#if CLASS == 'A'
#define TOTAL_KEYS_LOG_2 23
#define MAX_KEY_LOG_2 19
#define NUM_BUCKETS_LOG_2 10
#endif
/*************/
/* CLASS B */
/*************/
#if CLASS == 'B'
#define TOTAL_KEYS_LOG_2 25
#define MAX_KEY_LOG_2 21
#define NUM_BUCKETS_LOG_2 10
#endif
/*************/
/* CLASS C */
/*************/
#if CLASS == 'C'
#define TOTAL_KEYS_LOG_2 27
#define MAX_KEY_LOG_2 23
#define NUM_BUCKETS_LOG_2 10
#endif
#define TOTAL_KEYS (1 << TOTAL_KEYS_LOG_2)
#define MAX_KEY (1 << MAX_KEY_LOG_2)
#define NUM_BUCKETS (1 << NUM_BUCKETS_LOG_2)
#define NUM_KEYS TOTAL_KEYS
#define SIZE_OF_BUFFERS NUM_KEYS
#define MAX_ITERATIONS 10
#define TEST_ARRAY_SIZE 5
/*************************************/
/* Typedef: if necessary, change the */
/* size of int here by changing the */
/* int type to, say, long */
/*************************************/
typedef int INT_TYPE;
/********************/
/* Some global info */
/********************/
INT_TYPE *key_buff_ptr_global; /* used by full_verify to get */
/* copies of rank info */
int passed_verification;
/************************************/
/* These are the three main arrays. */
/* See SIZE_OF_BUFFERS def above */
/************************************/
INT_TYPE key_array[SIZE_OF_BUFFERS],
key_buff1[SIZE_OF_BUFFERS],
key_buff2[SIZE_OF_BUFFERS],
partial_verify_vals[TEST_ARRAY_SIZE];
#ifdef USE_BUCKETS
INT_TYPE bucket_size[NUM_BUCKETS],
bucket_ptrs[NUM_BUCKETS];
#endif
/**********************/
/* Partial verif info */
/**********************/
INT_TYPE test_index_array[TEST_ARRAY_SIZE],
test_rank_array[TEST_ARRAY_SIZE],
S_test_index_array[TEST_ARRAY_SIZE] =
{48427,17148,23627,62548,4431},
S_test_rank_array[TEST_ARRAY_SIZE] =
{0,18,346,64917,65463},
W_test_index_array[TEST_ARRAY_SIZE] =
{357773,934767,875723,898999,404505},
W_test_rank_array[TEST_ARRAY_SIZE] =
{1249,11698,1039987,1043896,1048018},
A_test_index_array[TEST_ARRAY_SIZE] =
{2112377,662041,5336171,3642833,4250760},
A_test_rank_array[TEST_ARRAY_SIZE] =
{104,17523,123928,8288932,8388264},
B_test_index_array[TEST_ARRAY_SIZE] =
{41869,812306,5102857,18232239,26860214},
B_test_rank_array[TEST_ARRAY_SIZE] =
{33422937,10244,59149,33135281,99},
C_test_index_array[TEST_ARRAY_SIZE] =
{44172927,72999161,74326391,129606274,21736814},
C_test_rank_array[TEST_ARRAY_SIZE] =
{61147,882988,266290,133997595,133525895};
/***********************/
/* function prototypes */
/***********************/
double randlc( double *X, double *A );
void full_verify( void );
/*
* FUNCTION RANDLC (X, A)
*
* This routine returns a uniform pseudorandom double precision number in the
* range (0, 1) by using the linear congruential generator
*
* x_{k+1} = a x_k (mod 2^46)
*
* where 0 < x_k < 2^46 and 0 < a < 2^46. This scheme generates 2^44 numbers
* before repeating. The argument A is the same as 'a' in the above formula,
* and X is the same as x_0. A and X must be odd double precision integers
* in the range (1, 2^46). The returned value RANDLC is normalized to be
* between 0 and 1, i.e. RANDLC = 2^(-46) * x_1. X is updated to contain
* the new seed x_1, so that subsequent calls to RANDLC using the same
* arguments will generate a continuous sequence.
*
* This routine should produce the same results on any computer with at least
* 48 mantissa bits in double precision floating point data. On Cray systems,
* double precision should be disabled.
*
* David H. Bailey October 26, 1990
*
* IMPLICIT DOUBLE PRECISION (A-H, O-Z)
* SAVE KS, R23, R46, T23, T46
* DATA KS/0/
*
* If this is the first call to RANDLC, compute R23 = 2 ^ -23, R46 = 2 ^ -46,
* T23 = 2 ^ 23, and T46 = 2 ^ 46. These are computed in loops, rather than
* by merely using the ** operator, in order to insure that the results are
* exact on all systems. This code assumes that 0.5D0 is represented exactly.
*/
/*****************************************************************/
/************* R A N D L C ************/
/************* ************/
/************* portable random number generator ************/
/*****************************************************************/
double randlc(X, A)
double *X;
double *A;
{
static int KS=0;
static double R23, R46, T23, T46;
double T1, T2, T3, T4;
double A1;
double A2;
double X1;
double X2;
double Z;
int i, j;
if (KS == 0)
{
R23 = 1.0;
R46 = 1.0;
T23 = 1.0;
T46 = 1.0;
for (i=1; i<=23; i++)
{
R23 = 0.50 * R23;
T23 = 2.0 * T23;
}
for (i=1; i<=46; i++)
{
R46 = 0.50 * R46;
T46 = 2.0 * T46;
}
KS = 1;
}
/* Break A into two parts such that A = 2^23 * A1 + A2 and set X = N. */
T1 = R23 * *A;
j = T1;
A1 = j;
A2 = *A - T23 * A1;
/* Break X into two parts such that X = 2^23 * X1 + X2, compute
Z = A1 * X2 + A2 * X1 (mod 2^23), and then
X = 2^23 * Z + A2 * X2 (mod 2^46). */
T1 = R23 * *X;
j = T1;
X1 = j;
X2 = *X - T23 * X1;
T1 = A1 * X2 + A2 * X1;
j = R23 * T1;
T2 = j;
Z = T1 - T23 * T2;
T3 = T23 * Z + A2 * X2;
j = R46 * T3;
T4 = j;
*X = T3 - T46 * T4;
return(R46 * *X);
}
/*****************************************************************/
/************* C R E A T E _ S E Q ************/
/*****************************************************************/
void create_seq( double seed, double a )
{
double x;
int i, j, k;
k = MAX_KEY/4;
for (i=0; i<NUM_KEYS; i++)
{
x = randlc(&seed, &a);
x += randlc(&seed, &a);
x += randlc(&seed, &a);
x += randlc(&seed, &a);
key_array[i] = k*x;
}
}
/*****************************************************************/
/************* F U L L _ V E R I F Y ************/
/*****************************************************************/
void full_verify()
{
INT_TYPE i, j;
INT_TYPE k;
INT_TYPE m, unique_keys;
/* Now, finally, sort the keys: */
for( i=0; i<NUM_KEYS; i++ )
key_array[--key_buff_ptr_global[key_buff2[i]]] = key_buff2[i];
/* Confirm keys correctly sorted: count incorrectly sorted keys, if any */
j = 0;
#pragma omp parallel for private(i ) reduction(+:j)
for( i=1; i<NUM_KEYS; i++ )
if( key_array[i-1] > key_array[i] )
j++;
if( j != 0 )
{
printf( "Full_verify: number of keys out of sort: %d\n",
j );
}
else
passed_verification++;
}
/*****************************************************************/
/************* R A N K ****************/
/*****************************************************************/
void rank( int iteration )
{
INT_TYPE i, j, k;
INT_TYPE l, m;
INT_TYPE shift = MAX_KEY_LOG_2 - NUM_BUCKETS_LOG_2;
INT_TYPE key;
INT_TYPE min_key_val, max_key_val;
INT_TYPE prv_buff1[MAX_KEY];
{
key_array[iteration] = iteration;
key_array[iteration+MAX_ITERATIONS] = MAX_KEY - iteration;
/* Determine where the partial verify test keys are, load into */
/* top of array bucket_size */
#pragma omp parallel for private(i )
for( i=0; i<TEST_ARRAY_SIZE; i++ )
partial_verify_vals[i] = key_array[test_index_array[i]];
/* Clear the work array */
for( i=0; i<MAX_KEY; i++ )
key_buff1[i] = 0;
}
for (i=0; i<MAX_KEY; i++)
prv_buff1[i] = 0;
/* Copy keys into work array; keys in key_array will be reused each iter. */
for( i=0; i<NUM_KEYS; i++ ) {
key_buff2[i] = key_array[i];
/* Ranking of all keys occurs in this section: */
/* In this section, the keys themselves are used as their
own indexes to determine how many of each there are: their
individual population */
prv_buff1[key_buff2[i]]++; /* Now they have individual key */
}
/* population */
for( i=0; i<MAX_KEY-1; i++ )
prv_buff1[i+1] += prv_buff1[i];
{
#pragma omp parallel for private(i )
for( i=0; i<MAX_KEY; i++ )
key_buff1[i] += prv_buff1[i];
}
/* To obtain ranks of each key, successively add the individual key
population, not forgetting to add m, the total of lesser keys,
to the first key population */
{
/* This is the partial verify test section */
/* Observe that test_rank_array vals are */
/* shifted differently for different cases */
for( i=0; i<TEST_ARRAY_SIZE; i++ )
{
k = partial_verify_vals[i]; /* test vals were put here */
if( 0 <= k && k <= NUM_KEYS-1 )
switch( CLASS )
{
case 'S':
if( i <= 2 )
{
if( key_buff1[k-1] != test_rank_array[i]+iteration )
{
printf( "Failed partial verification: "
"iteration %d, test key %d\n",
iteration, i );
}
else
passed_verification++;
}
else
{
if( key_buff1[k-1] != test_rank_array[i]-iteration )
{
printf( "Failed partial verification: "
"iteration %d, test key %d\n",
iteration, i );
}
else
passed_verification++;
}
break;
case 'W':
if( i < 2 )
{
if( key_buff1[k-1] !=
test_rank_array[i]+(iteration-2) )
{
printf( "Failed partial verification: "
"iteration %d, test key %d\n",
iteration, i );
}
else
passed_verification++;
}
else
{
if( key_buff1[k-1] != test_rank_array[i]-iteration )
{
printf( "Failed partial verification: "
"iteration %d, test key %d\n",
iteration, i );
}
else
passed_verification++;
}
break;
case 'A':
if( i <= 2 )
{
if( key_buff1[k-1] !=
test_rank_array[i]+(iteration-1) )
{
printf( "Failed partial verification: "
"iteration %d, test key %d\n",
iteration, i );
}
else
passed_verification++;
}
else
{
if( key_buff1[k-1] !=
test_rank_array[i]-(iteration-1) )
{
printf( "Failed partial verification: "
"iteration %d, test key %d\n",
iteration, i );
}
else
passed_verification++;
}
break;
case 'B':
if( i == 1 || i == 2 || i == 4 )
{
if( key_buff1[k-1] != test_rank_array[i]+iteration )
{
printf( "Failed partial verification: "
"iteration %d, test key %d\n",
iteration, i );
}
else
passed_verification++;
}
else
{
if( key_buff1[k-1] != test_rank_array[i]-iteration )
{
printf( "Failed partial verification: "
"iteration %d, test key %d\n",
iteration, i );
}
else
passed_verification++;
}
break;
case 'C':
if( i <= 2 )
{
if( key_buff1[k-1] != test_rank_array[i]+iteration )
{
printf( "Failed partial verification: "
"iteration %d, test key %d\n",
iteration, i );
}
else
passed_verification++;
}
else
{
if( key_buff1[k-1] != test_rank_array[i]-iteration )
{
printf( "Failed partial verification: "
"iteration %d, test key %d\n",
iteration, i );
}
else
passed_verification++;
}
break;
}
}
/* Make copies of rank info for use by full_verify: these variables
in rank are local; making them global slows down the code, probably
since they cannot be made register by compiler */
if( iteration == MAX_ITERATIONS )
key_buff_ptr_global = key_buff1;
} /* end master */
}
/*****************************************************************/
/************* M A I N ****************/
/*****************************************************************/
main( argc, argv )
int argc;
char **argv;
{
int i, iteration, itemp;
int nthreads = 1;
double timecounter, maxtime;
/* Initialize the verification arrays if a valid class */
#pragma omp parallel for private(i )
for( i=0; i<TEST_ARRAY_SIZE; i++ )
switch( CLASS )
{
case 'S':
test_index_array[i] = S_test_index_array[i];
test_rank_array[i] = S_test_rank_array[i];
break;
case 'A':
test_index_array[i] = A_test_index_array[i];
test_rank_array[i] = A_test_rank_array[i];
break;
case 'W':
test_index_array[i] = W_test_index_array[i];
test_rank_array[i] = W_test_rank_array[i];
break;
case 'B':
test_index_array[i] = B_test_index_array[i];
test_rank_array[i] = B_test_rank_array[i];
break;
case 'C':
test_index_array[i] = C_test_index_array[i];
test_rank_array[i] = C_test_rank_array[i];
break;
};
/* Printout initial NPB info */
printf( "\n\n NAS Parallel Benchmarks 2.3 OpenMP C version"
" - IS Benchmark\n\n" );
printf( " Size: %d (class %c)\n", TOTAL_KEYS, CLASS );
printf( " Iterations: %d\n", MAX_ITERATIONS );
/* Initialize timer */
timer_clear( 0 );
/* Generate random number sequence and subsequent keys on all procs */
create_seq( 314159265.00, /* Random number gen seed */
1220703125.00 ); /* Random number gen mult */
/* Do one interation for free (i.e., untimed) to guarantee initialization of
all data and code pages and respective tables */
rank( 1 );
/* Start verification counter */
passed_verification = 0;
if( CLASS != 'S' ) printf( "\n iteration\n" );
/* Start timer */
timer_start( 0 );
/* This is the main iteration */
for( iteration=1; iteration<=MAX_ITERATIONS; iteration++ )
{
if( CLASS != 'S' ) printf( " %d\n", iteration );
rank( iteration );
#if defined(_OPENMP)
nthreads = omp_get_num_threads();
#endif /* _OPENMP */
}
/* End of timing, obtain maximum time of all processors */
timer_stop( 0 );
timecounter = timer_read( 0 );
/* This tests that keys are in sequence: sorting of last ranked key seq
occurs here, but is an untimed operation */
full_verify();
/* The final printout */
if( passed_verification != 5*MAX_ITERATIONS + 1 )
passed_verification = 0;
c_print_results( "IS",
CLASS,
TOTAL_KEYS,
0,
0,
MAX_ITERATIONS,
nthreads,
timecounter,
((double) (MAX_ITERATIONS*TOTAL_KEYS))
/timecounter/1000000.,
"keys ranked",
passed_verification,
NPBVERSION,
COMPILETIME,
CC,
CLINK,
C_LIB,
C_INC,
CFLAGS,
CLINKFLAGS,
"randlc");
/**************************/
} /* E N D P R O G R A M */
/**************************/
|
reduce.h | #ifndef __REDUCE_H__
#define __REDUCE_H__
#include <vector>
#include <iostream>
#include <functional>
template <typename T, typename Op>
T reduceHelper(std::vector<T>& vec, Op op)
{
auto size = vec.size();
auto stepLen = size / 2 + size % 2;
if (size == 1)
{
return vec[0];
}
#pragma omp parallel for
for (auto i = 0; i < (size / 2); i++)
{
vec[i] = op(vec[i], vec[i + stepLen]);
}
vec.resize(stepLen);
reduceHelper(vec, op);
}
template <typename T, typename Op>
void reduce(std::vector<T>& vec, T& result, Op op)
{
if (vec.size() == 0)
{
std::cout << "The vector size is 0, nothing to do.\n";
}
else if (vec.size() == 1)
{
result = vec[0];
}
else
{
std::vector<T> tmp = vec;
result = reduceHelper(tmp, op);
}
return;
}
#endif /* __REDUCE_H__ */
|
a5.c | #include "omp.h"
void axpy(int N, float *Y, float *X, float a) {
int i;
#pragma omp target update nowait to(X)
#pragma omp parallel for
for (i = 0; i < N; ++i)
Y[i] += a * X[i];
}
|
TSDFVoxelGridImpl.h | // ----------------------------------------------------------------------------
// - Open3D: www.open3d.org -
// ----------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2018-2021 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.
// ----------------------------------------------------------------------------
#include <atomic>
#include <cmath>
#include "open3d/core/Dispatch.h"
#include "open3d/core/Dtype.h"
#include "open3d/core/MemoryManager.h"
#include "open3d/core/SizeVector.h"
#include "open3d/core/Tensor.h"
#include "open3d/t/geometry/Utility.h"
#include "open3d/t/geometry/kernel/GeometryIndexer.h"
#include "open3d/t/geometry/kernel/GeometryMacros.h"
#include "open3d/t/geometry/kernel/TSDFVoxel.h"
#include "open3d/t/geometry/kernel/TSDFVoxelGrid.h"
#include "open3d/utility/Logging.h"
#include "open3d/utility/Timer.h"
namespace open3d {
namespace t {
namespace geometry {
namespace kernel {
namespace tsdf {
#if defined(__CUDACC__)
void IntegrateCUDA
#else
void IntegrateCPU
#endif
(const core::Tensor& depth,
const core::Tensor& color,
const core::Tensor& indices,
const core::Tensor& block_keys,
core::Tensor& block_values,
// Transforms
const core::Tensor& intrinsics,
const core::Tensor& extrinsics,
// Parameters
int64_t resolution,
float voxel_size,
float sdf_trunc,
float depth_scale,
float depth_max) {
// Parameters
int64_t resolution3 = resolution * resolution * resolution;
// Shape / transform indexers, no data involved
NDArrayIndexer voxel_indexer({resolution, resolution, resolution});
TransformIndexer transform_indexer(intrinsics, extrinsics, voxel_size);
// Real data indexer
NDArrayIndexer depth_indexer(depth, 2);
NDArrayIndexer block_keys_indexer(block_keys, 1);
NDArrayIndexer voxel_block_buffer_indexer(block_values, 4);
// Optional color integration
NDArrayIndexer color_indexer;
bool integrate_color = false;
if (color.NumElements() != 0) {
color_indexer = NDArrayIndexer(color, 2);
integrate_color = true;
}
// Plain arrays that does not require indexers
const int* indices_ptr = indices.GetDataPtr<int>();
int64_t n = indices.GetLength() * resolution3;
#if defined(__CUDACC__)
namespace launcher = core::kernel::cuda_launcher;
#else
namespace launcher = core::kernel::cpu_launcher;
#endif
DISPATCH_BYTESIZE_TO_VOXEL(
voxel_block_buffer_indexer.ElementByteSize(), [&]() {
launcher::ParallelFor(n, [=] OPEN3D_DEVICE(
int64_t workload_idx) {
// Natural index (0, N) -> (block_idx, voxel_idx)
int block_idx = indices_ptr[workload_idx / resolution3];
int voxel_idx = workload_idx % resolution3;
/// Coordinate transform
// block_idx -> (x_block, y_block, z_block)
int* block_key_ptr =
block_keys_indexer.GetDataPtr<int>(block_idx);
int64_t xb = static_cast<int64_t>(block_key_ptr[0]);
int64_t yb = static_cast<int64_t>(block_key_ptr[1]);
int64_t zb = static_cast<int64_t>(block_key_ptr[2]);
// voxel_idx -> (x_voxel, y_voxel, z_voxel)
int64_t xv, yv, zv;
voxel_indexer.WorkloadToCoord(voxel_idx, &xv, &yv, &zv);
// coordinate in world (in voxel)
int64_t x = (xb * resolution + xv);
int64_t y = (yb * resolution + yv);
int64_t z = (zb * resolution + zv);
// coordinate in camera (in voxel -> in meter)
float xc, yc, zc, u, v;
transform_indexer.RigidTransform(
static_cast<float>(x), static_cast<float>(y),
static_cast<float>(z), &xc, &yc, &zc);
// coordinate in image (in pixel)
transform_indexer.Project(xc, yc, zc, &u, &v);
if (!depth_indexer.InBoundary(u, v)) {
return;
}
// Associate image workload and compute SDF and TSDF.
float depth = *depth_indexer.GetDataPtr<float>(
static_cast<int64_t>(u),
static_cast<int64_t>(v)) /
depth_scale;
float sdf = (depth - zc);
if (depth <= 0 || depth > depth_max || zc <= 0 ||
sdf < -sdf_trunc) {
return;
}
sdf = sdf < sdf_trunc ? sdf : sdf_trunc;
sdf /= sdf_trunc;
// Associate voxel workload and update TSDF/Weights
voxel_t* voxel_ptr =
voxel_block_buffer_indexer.GetDataPtr<voxel_t>(
xv, yv, zv, block_idx);
if (integrate_color) {
float* color_ptr = color_indexer.GetDataPtr<float>(
static_cast<int64_t>(u),
static_cast<int64_t>(v));
voxel_ptr->Integrate(sdf, color_ptr[0], color_ptr[1],
color_ptr[2]);
} else {
voxel_ptr->Integrate(sdf);
}
});
});
#if defined(__CUDACC__)
OPEN3D_CUDA_CHECK(cudaDeviceSynchronize());
#endif
}
#if defined(__CUDACC__)
void ExtractSurfacePointsCUDA
#else
void ExtractSurfacePointsCPU
#endif
(const core::Tensor& indices,
const core::Tensor& nb_indices,
const core::Tensor& nb_masks,
const core::Tensor& block_keys,
const core::Tensor& block_values,
core::Tensor& points,
utility::optional<std::reference_wrapper<core::Tensor>> normals,
utility::optional<std::reference_wrapper<core::Tensor>> colors,
int64_t resolution,
float voxel_size,
float weight_threshold,
int& valid_size) {
// Parameters
int64_t resolution3 = resolution * resolution * resolution;
// Shape / transform indexers, no data involved
NDArrayIndexer voxel_indexer({resolution, resolution, resolution});
// Real data indexer
NDArrayIndexer voxel_block_buffer_indexer(block_values, 4);
NDArrayIndexer block_keys_indexer(block_keys, 1);
NDArrayIndexer nb_block_masks_indexer(nb_masks, 2);
NDArrayIndexer nb_block_indices_indexer(nb_indices, 2);
// Plain arrays that does not require indexers
const int64_t* indices_ptr = indices.GetDataPtr<int64_t>();
int64_t n_blocks = indices.GetLength();
int64_t n = n_blocks * resolution3;
// Output
#if defined(__CUDACC__)
core::Tensor count(std::vector<int>{0}, {1}, core::Int32,
block_values.GetDevice());
int* count_ptr = count.GetDataPtr<int>();
#else
std::atomic<int> count_atomic(0);
std::atomic<int>* count_ptr = &count_atomic;
#endif
#if defined(__CUDACC__)
namespace launcher = core::kernel::cuda_launcher;
#else
namespace launcher = core::kernel::cpu_launcher;
#endif
if (valid_size < 0) {
utility::LogWarning(
"No estimated max point cloud size provided, using a 2-pass "
"estimation. Surface extraction could be slow.");
// This pass determines valid number of points.
DISPATCH_BYTESIZE_TO_VOXEL(
voxel_block_buffer_indexer.ElementByteSize(), [&]() {
launcher::ParallelFor(n, [=] OPEN3D_DEVICE(
int64_t workload_idx) {
auto GetVoxelAt =
[&] OPEN3D_DEVICE(
int xo, int yo, int zo,
int curr_block_idx) -> voxel_t* {
return DeviceGetVoxelAt<voxel_t>(
xo, yo, zo, curr_block_idx,
static_cast<int>(resolution),
nb_block_masks_indexer,
nb_block_indices_indexer,
voxel_block_buffer_indexer);
};
// Natural index (0, N) -> (block_idx,
// voxel_idx)
int64_t workload_block_idx = workload_idx / resolution3;
int64_t block_idx = indices_ptr[workload_block_idx];
int64_t voxel_idx = workload_idx % resolution3;
// voxel_idx -> (x_voxel, y_voxel, z_voxel)
int64_t xv, yv, zv;
voxel_indexer.WorkloadToCoord(voxel_idx, &xv, &yv, &zv);
voxel_t* voxel_ptr =
voxel_block_buffer_indexer.GetDataPtr<voxel_t>(
xv, yv, zv, block_idx);
float tsdf_o = voxel_ptr->GetTSDF();
float weight_o = voxel_ptr->GetWeight();
if (weight_o <= weight_threshold) return;
// Enumerate x-y-z directions
for (int i = 0; i < 3; ++i) {
voxel_t* ptr = GetVoxelAt(
static_cast<int>(xv) + (i == 0),
static_cast<int>(yv) + (i == 1),
static_cast<int>(zv) + (i == 2),
static_cast<int>(workload_block_idx));
if (ptr == nullptr) continue;
float tsdf_i = ptr->GetTSDF();
float weight_i = ptr->GetWeight();
if (weight_i > weight_threshold &&
tsdf_i * tsdf_o < 0) {
OPEN3D_ATOMIC_ADD(count_ptr, 1);
}
}
});
});
#if defined(__CUDACC__)
valid_size = count[0].Item<int>();
count[0] = 0;
#else
valid_size = (*count_ptr).load();
(*count_ptr) = 0;
#endif
}
int max_count = valid_size;
if (points.GetLength() == 0) {
points = core::Tensor({max_count, 3}, core::Float32,
block_values.GetDevice());
}
NDArrayIndexer point_indexer(points, 1);
// Normals
bool extract_normal = false;
NDArrayIndexer normal_indexer;
if (normals.has_value()) {
extract_normal = true;
if (normals.value().get().GetLength() == 0) {
normals.value().get() = core::Tensor({max_count, 3}, core::Float32,
block_values.GetDevice());
}
normal_indexer = NDArrayIndexer(normals.value().get(), 1);
}
// This pass extracts exact surface points.
DISPATCH_BYTESIZE_TO_VOXEL(
voxel_block_buffer_indexer.ElementByteSize(), [&]() {
// Colors
bool extract_color = false;
NDArrayIndexer color_indexer;
if (voxel_t::HasColor() && colors.has_value()) {
extract_color = true;
if (colors.value().get().GetLength() == 0) {
colors.value().get() =
core::Tensor({max_count, 3}, core::Float32,
block_values.GetDevice());
}
color_indexer = NDArrayIndexer(colors.value().get(), 1);
}
launcher::ParallelFor(n, [=] OPEN3D_DEVICE(
int64_t workload_idx) {
auto GetVoxelAt = [&] OPEN3D_DEVICE(
int xo, int yo, int zo,
int curr_block_idx) -> voxel_t* {
return DeviceGetVoxelAt<voxel_t>(
xo, yo, zo, curr_block_idx,
static_cast<int>(resolution),
nb_block_masks_indexer,
nb_block_indices_indexer,
voxel_block_buffer_indexer);
};
auto GetNormalAt = [&] OPEN3D_DEVICE(int xo, int yo, int zo,
int curr_block_idx,
float* n) {
return DeviceGetNormalAt<voxel_t>(
xo, yo, zo, curr_block_idx, n,
static_cast<int>(resolution), voxel_size,
nb_block_masks_indexer,
nb_block_indices_indexer,
voxel_block_buffer_indexer);
};
// Natural index (0, N) -> (block_idx, voxel_idx)
int64_t workload_block_idx = workload_idx / resolution3;
int64_t block_idx = indices_ptr[workload_block_idx];
int64_t voxel_idx = workload_idx % resolution3;
/// Coordinate transform
// block_idx -> (x_block, y_block, z_block)
int* block_key_ptr =
block_keys_indexer.GetDataPtr<int>(block_idx);
int64_t xb = static_cast<int64_t>(block_key_ptr[0]);
int64_t yb = static_cast<int64_t>(block_key_ptr[1]);
int64_t zb = static_cast<int64_t>(block_key_ptr[2]);
// voxel_idx -> (x_voxel, y_voxel, z_voxel)
int64_t xv, yv, zv;
voxel_indexer.WorkloadToCoord(voxel_idx, &xv, &yv, &zv);
voxel_t* voxel_ptr =
voxel_block_buffer_indexer.GetDataPtr<voxel_t>(
xv, yv, zv, block_idx);
float tsdf_o = voxel_ptr->GetTSDF();
float weight_o = voxel_ptr->GetWeight();
if (weight_o <= weight_threshold) return;
int64_t x = xb * resolution + xv;
int64_t y = yb * resolution + yv;
int64_t z = zb * resolution + zv;
float no[3] = {0}, ni[3] = {0};
if (extract_normal) {
GetNormalAt(static_cast<int>(xv), static_cast<int>(yv),
static_cast<int>(zv),
static_cast<int>(workload_block_idx), no);
}
// Enumerate x-y-z axis
for (int i = 0; i < 3; ++i) {
voxel_t* ptr = GetVoxelAt(
static_cast<int>(xv) + (i == 0),
static_cast<int>(yv) + (i == 1),
static_cast<int>(zv) + (i == 2),
static_cast<int>(workload_block_idx));
if (ptr == nullptr) continue;
float tsdf_i = ptr->GetTSDF();
float weight_i = ptr->GetWeight();
if (weight_i > weight_threshold &&
tsdf_i * tsdf_o < 0) {
float ratio = (0 - tsdf_o) / (tsdf_i - tsdf_o);
int idx = OPEN3D_ATOMIC_ADD(count_ptr, 1);
if (idx >= valid_size) {
printf("Point cloud size larger than "
"estimated, please increase the "
"estimation!\n");
return;
}
float* point_ptr =
point_indexer.GetDataPtr<float>(idx);
point_ptr[0] =
voxel_size * (x + ratio * int(i == 0));
point_ptr[1] =
voxel_size * (y + ratio * int(i == 1));
point_ptr[2] =
voxel_size * (z + ratio * int(i == 2));
if (extract_color) {
float* color_ptr =
color_indexer.GetDataPtr<float>(idx);
float r_o = voxel_ptr->GetR();
float g_o = voxel_ptr->GetG();
float b_o = voxel_ptr->GetB();
float r_i = ptr->GetR();
float g_i = ptr->GetG();
float b_i = ptr->GetB();
color_ptr[0] =
((1 - ratio) * r_o + ratio * r_i) /
255.0f;
color_ptr[1] =
((1 - ratio) * g_o + ratio * g_i) /
255.0f;
color_ptr[2] =
((1 - ratio) * b_o + ratio * b_i) /
255.0f;
}
if (extract_normal) {
GetNormalAt(
static_cast<int>(xv) + (i == 0),
static_cast<int>(yv) + (i == 1),
static_cast<int>(zv) + (i == 2),
static_cast<int>(workload_block_idx),
ni);
float* normal_ptr =
normal_indexer.GetDataPtr<float>(idx);
float nx = (1 - ratio) * no[0] + ratio * ni[0];
float ny = (1 - ratio) * no[1] + ratio * ni[1];
float nz = (1 - ratio) * no[2] + ratio * ni[2];
float norm = static_cast<float>(
sqrt(nx * nx + ny * ny + nz * nz) +
1e-5);
normal_ptr[0] = nx / norm;
normal_ptr[1] = ny / norm;
normal_ptr[2] = nz / norm;
}
}
}
});
});
#if defined(__CUDACC__)
int total_count = count.Item<int>();
#else
int total_count = (*count_ptr).load();
#endif
utility::LogDebug("{} vertices extracted", total_count);
valid_size = total_count;
#if defined(BUILD_CUDA_MODULE) && defined(__CUDACC__)
OPEN3D_CUDA_CHECK(cudaDeviceSynchronize());
#endif
}
#if defined(__CUDACC__)
void ExtractSurfaceMeshCUDA
#else
void ExtractSurfaceMeshCPU
#endif
(const core::Tensor& indices,
const core::Tensor& inv_indices,
const core::Tensor& nb_indices,
const core::Tensor& nb_masks,
const core::Tensor& block_keys,
const core::Tensor& block_values,
core::Tensor& vertices,
core::Tensor& triangles,
utility::optional<std::reference_wrapper<core::Tensor>> normals,
utility::optional<std::reference_wrapper<core::Tensor>> colors,
int64_t resolution,
float voxel_size,
float weight_threshold,
int& vertex_count) {
int64_t resolution3 = resolution * resolution * resolution;
// Shape / transform indexers, no data involved
NDArrayIndexer voxel_indexer({resolution, resolution, resolution});
int n_blocks = static_cast<int>(indices.GetLength());
// TODO(wei): profile performance by replacing the table to a hashmap.
// Voxel-wise mesh info. 4 channels correspond to:
// 3 edges' corresponding vertex index + 1 table index.
core::Tensor mesh_structure;
try {
mesh_structure = core::Tensor::Zeros(
{n_blocks, resolution, resolution, resolution, 4}, core::Int32,
block_keys.GetDevice());
} catch (const std::runtime_error&) {
utility::LogError(
"[MeshExtractionKernel] Unable to allocate assistance mesh "
"structure for Marching "
"Cubes with {} active voxel blocks. Please consider using a "
"larger voxel size (currently {}) for TSDF "
"integration, or using tsdf_volume.cpu() to perform mesh "
"extraction on CPU.",
n_blocks, voxel_size);
}
// Real data indexer
NDArrayIndexer voxel_block_buffer_indexer(block_values, 4);
NDArrayIndexer mesh_structure_indexer(mesh_structure, 4);
NDArrayIndexer nb_block_masks_indexer(nb_masks, 2);
NDArrayIndexer nb_block_indices_indexer(nb_indices, 2);
// Plain arrays that does not require indexers
const int64_t* indices_ptr = indices.GetDataPtr<int64_t>();
const int64_t* inv_indices_ptr = inv_indices.GetDataPtr<int64_t>();
int64_t n = n_blocks * resolution3;
#if defined(__CUDACC__)
namespace launcher = core::kernel::cuda_launcher;
#else
namespace launcher = core::kernel::cpu_launcher;
#endif
int64_t voxel_bytesize = voxel_block_buffer_indexer.ElementByteSize();
// Pass 0: analyze mesh structure, set up one-on-one correspondences
// from edges to vertices.
DISPATCH_BYTESIZE_TO_VOXEL(voxel_bytesize, [&]() {
launcher::ParallelFor(n, [=] OPEN3D_DEVICE(int64_t widx) {
auto GetVoxelAt = [&] OPEN3D_DEVICE(
int xo, int yo, int zo,
int curr_block_idx) -> voxel_t* {
return DeviceGetVoxelAt<voxel_t>(
xo, yo, zo, curr_block_idx,
static_cast<int>(resolution), nb_block_masks_indexer,
nb_block_indices_indexer, voxel_block_buffer_indexer);
};
// Natural index (0, N) -> (block_idx, voxel_idx)
int64_t workload_block_idx = widx / resolution3;
int64_t voxel_idx = widx % resolution3;
// voxel_idx -> (x_voxel, y_voxel, z_voxel)
int64_t xv, yv, zv;
voxel_indexer.WorkloadToCoord(voxel_idx, &xv, &yv, &zv);
// Check per-vertex sign in the cube to determine cube
// type
int table_idx = 0;
for (int i = 0; i < 8; ++i) {
voxel_t* voxel_ptr_i =
GetVoxelAt(static_cast<int>(xv) + vtx_shifts[i][0],
static_cast<int>(yv) + vtx_shifts[i][1],
static_cast<int>(zv) + vtx_shifts[i][2],
static_cast<int>(workload_block_idx));
if (voxel_ptr_i == nullptr) return;
float tsdf_i = voxel_ptr_i->GetTSDF();
float weight_i = voxel_ptr_i->GetWeight();
if (weight_i <= weight_threshold) return;
table_idx |= ((tsdf_i < 0) ? (1 << i) : 0);
}
int* mesh_struct_ptr = mesh_structure_indexer.GetDataPtr<int>(
xv, yv, zv, workload_block_idx);
mesh_struct_ptr[3] = table_idx;
if (table_idx == 0 || table_idx == 255) return;
// Check per-edge sign determine the cube type
int edges_with_vertices = edge_table[table_idx];
for (int i = 0; i < 12; ++i) {
if (edges_with_vertices & (1 << i)) {
int64_t xv_i = xv + edge_shifts[i][0];
int64_t yv_i = yv + edge_shifts[i][1];
int64_t zv_i = zv + edge_shifts[i][2];
int edge_i = edge_shifts[i][3];
int dxb = static_cast<int>(xv_i / resolution);
int dyb = static_cast<int>(yv_i / resolution);
int dzb = static_cast<int>(zv_i / resolution);
int nb_idx = (dxb + 1) + (dyb + 1) * 3 + (dzb + 1) * 9;
int64_t block_idx_i =
*nb_block_indices_indexer.GetDataPtr<int64_t>(
workload_block_idx, nb_idx);
int* mesh_ptr_i = mesh_structure_indexer.GetDataPtr<int>(
xv_i - dxb * resolution, yv_i - dyb * resolution,
zv_i - dzb * resolution,
inv_indices_ptr[block_idx_i]);
// Non-atomic write, but we are safe
mesh_ptr_i[edge_i] = -1;
}
}
});
});
// Pass 1: determine valid number of vertices (if not preset)
#if defined(__CUDACC__)
core::Tensor count(std::vector<int>{0}, {}, core::Int32,
block_values.GetDevice());
int* count_ptr = count.GetDataPtr<int>();
#else
std::atomic<int> count_atomic(0);
std::atomic<int>* count_ptr = &count_atomic;
#endif
if (vertex_count < 0) {
launcher::ParallelFor(n, [=] OPEN3D_DEVICE(int64_t widx) {
// Natural index (0, N) -> (block_idx, voxel_idx)
int64_t workload_block_idx = widx / resolution3;
int64_t voxel_idx = widx % resolution3;
// voxel_idx -> (x_voxel, y_voxel, z_voxel)
int64_t xv, yv, zv;
voxel_indexer.WorkloadToCoord(voxel_idx, &xv, &yv, &zv);
// Obtain voxel's mesh struct ptr
int* mesh_struct_ptr = mesh_structure_indexer.GetDataPtr<int>(
xv, yv, zv, workload_block_idx);
// Early quit -- no allocated vertex to compute
if (mesh_struct_ptr[0] != -1 && mesh_struct_ptr[1] != -1 &&
mesh_struct_ptr[2] != -1) {
return;
}
// Enumerate 3 edges in the voxel
for (int e = 0; e < 3; ++e) {
int vertex_idx = mesh_struct_ptr[e];
if (vertex_idx != -1) continue;
OPEN3D_ATOMIC_ADD(count_ptr, 1);
}
});
#if defined(__CUDACC__)
vertex_count = count.Item<int>();
#else
vertex_count = (*count_ptr).load();
#endif
}
utility::LogDebug("Total vertex count = {}", vertex_count);
vertices = core::Tensor({vertex_count, 3}, core::Float32,
block_values.GetDevice());
bool extract_normal = false;
NDArrayIndexer normal_indexer;
if (normals.has_value()) {
extract_normal = true;
normals.value().get() = core::Tensor({vertex_count, 3}, core::Float32,
block_values.GetDevice());
normal_indexer = NDArrayIndexer(normals.value().get(), 1);
}
NDArrayIndexer block_keys_indexer(block_keys, 1);
NDArrayIndexer vertex_indexer(vertices, 1);
#if defined(__CUDACC__)
count = core::Tensor(std::vector<int>{0}, {}, core::Int32,
block_values.GetDevice());
count_ptr = count.GetDataPtr<int>();
#else
(*count_ptr) = 0;
#endif
// Pass 2: extract vertices.
DISPATCH_BYTESIZE_TO_VOXEL(voxel_bytesize, [&]() {
bool extract_color = false;
NDArrayIndexer color_indexer;
if (voxel_t::HasColor() && colors.has_value()) {
extract_color = true;
colors.value().get() = core::Tensor(
{vertex_count, 3}, core::Float32, block_values.GetDevice());
color_indexer = NDArrayIndexer(colors.value().get(), 1);
}
launcher::ParallelFor(n, [=] OPEN3D_DEVICE(int64_t widx) {
auto GetVoxelAt = [&] OPEN3D_DEVICE(
int xo, int yo, int zo,
int curr_block_idx) -> voxel_t* {
return DeviceGetVoxelAt<voxel_t>(
xo, yo, zo, curr_block_idx,
static_cast<int>(resolution), nb_block_masks_indexer,
nb_block_indices_indexer, voxel_block_buffer_indexer);
};
auto GetNormalAt = [&] OPEN3D_DEVICE(int xo, int yo, int zo,
int curr_block_idx, float* n) {
return DeviceGetNormalAt<voxel_t>(
xo, yo, zo, curr_block_idx, n,
static_cast<int>(resolution), voxel_size,
nb_block_masks_indexer, nb_block_indices_indexer,
voxel_block_buffer_indexer);
};
// Natural index (0, N) -> (block_idx, voxel_idx)
int64_t workload_block_idx = widx / resolution3;
int64_t block_idx = indices_ptr[workload_block_idx];
int64_t voxel_idx = widx % resolution3;
// block_idx -> (x_block, y_block, z_block)
int* block_key_ptr = block_keys_indexer.GetDataPtr<int>(block_idx);
int64_t xb = static_cast<int64_t>(block_key_ptr[0]);
int64_t yb = static_cast<int64_t>(block_key_ptr[1]);
int64_t zb = static_cast<int64_t>(block_key_ptr[2]);
// voxel_idx -> (x_voxel, y_voxel, z_voxel)
int64_t xv, yv, zv;
voxel_indexer.WorkloadToCoord(voxel_idx, &xv, &yv, &zv);
// global coordinate (in voxels)
int64_t x = xb * resolution + xv;
int64_t y = yb * resolution + yv;
int64_t z = zb * resolution + zv;
// Obtain voxel's mesh struct ptr
int* mesh_struct_ptr = mesh_structure_indexer.GetDataPtr<int>(
xv, yv, zv, workload_block_idx);
// Early quit -- no allocated vertex to compute
if (mesh_struct_ptr[0] != -1 && mesh_struct_ptr[1] != -1 &&
mesh_struct_ptr[2] != -1) {
return;
}
// Obtain voxel ptr
voxel_t* voxel_ptr = voxel_block_buffer_indexer.GetDataPtr<voxel_t>(
xv, yv, zv, block_idx);
float tsdf_o = voxel_ptr->GetTSDF();
float no[3] = {0}, ne[3] = {0};
if (extract_normal) {
GetNormalAt(static_cast<int>(xv), static_cast<int>(yv),
static_cast<int>(zv),
static_cast<int>(workload_block_idx), no);
}
// Enumerate 3 edges in the voxel
for (int e = 0; e < 3; ++e) {
int vertex_idx = mesh_struct_ptr[e];
if (vertex_idx != -1) continue;
voxel_t* voxel_ptr_e =
GetVoxelAt(static_cast<int>(xv) + (e == 0),
static_cast<int>(yv) + (e == 1),
static_cast<int>(zv) + (e == 2),
static_cast<int>(workload_block_idx));
OPEN3D_ASSERT(voxel_ptr_e != nullptr &&
"Internal error: GetVoxelAt returns nullptr.");
float tsdf_e = voxel_ptr_e->GetTSDF();
float ratio = (0 - tsdf_o) / (tsdf_e - tsdf_o);
int idx = OPEN3D_ATOMIC_ADD(count_ptr, 1);
mesh_struct_ptr[e] = idx;
float ratio_x = ratio * int(e == 0);
float ratio_y = ratio * int(e == 1);
float ratio_z = ratio * int(e == 2);
float* vertex_ptr = vertex_indexer.GetDataPtr<float>(idx);
vertex_ptr[0] = voxel_size * (x + ratio_x);
vertex_ptr[1] = voxel_size * (y + ratio_y);
vertex_ptr[2] = voxel_size * (z + ratio_z);
if (extract_normal) {
float* normal_ptr = normal_indexer.GetDataPtr<float>(idx);
GetNormalAt(static_cast<int>(xv) + (e == 0),
static_cast<int>(yv) + (e == 1),
static_cast<int>(zv) + (e == 2),
static_cast<int>(workload_block_idx), ne);
float nx = (1 - ratio) * no[0] + ratio * ne[0];
float ny = (1 - ratio) * no[1] + ratio * ne[1];
float nz = (1 - ratio) * no[2] + ratio * ne[2];
float norm = static_cast<float>(
sqrt(nx * nx + ny * ny + nz * nz) + 1e-5);
normal_ptr[0] = nx / norm;
normal_ptr[1] = ny / norm;
normal_ptr[2] = nz / norm;
}
if (extract_color) {
float* color_ptr = color_indexer.GetDataPtr<float>(idx);
float r_o = voxel_ptr->GetR();
float g_o = voxel_ptr->GetG();
float b_o = voxel_ptr->GetB();
float r_e = voxel_ptr_e->GetR();
float g_e = voxel_ptr_e->GetG();
float b_e = voxel_ptr_e->GetB();
color_ptr[0] = ((1 - ratio) * r_o + ratio * r_e) / 255.0f;
color_ptr[1] = ((1 - ratio) * g_o + ratio * g_e) / 255.0f;
color_ptr[2] = ((1 - ratio) * b_o + ratio * b_e) / 255.0f;
}
}
});
});
// Pass 3: connect vertices and form triangles.
int triangle_count = vertex_count * 3;
triangles = core::Tensor({triangle_count, 3}, core::Int64,
block_values.GetDevice());
NDArrayIndexer triangle_indexer(triangles, 1);
#if defined(__CUDACC__)
count = core::Tensor(std::vector<int>{0}, {}, core::Int32,
block_values.GetDevice());
count_ptr = count.GetDataPtr<int>();
#else
(*count_ptr) = 0;
#endif
launcher::ParallelFor(n, [=] OPEN3D_DEVICE(int64_t widx) {
// Natural index (0, N) -> (block_idx, voxel_idx)
int64_t workload_block_idx = widx / resolution3;
int64_t voxel_idx = widx % resolution3;
// voxel_idx -> (x_voxel, y_voxel, z_voxel)
int64_t xv, yv, zv;
voxel_indexer.WorkloadToCoord(voxel_idx, &xv, &yv, &zv);
// Obtain voxel's mesh struct ptr
int* mesh_struct_ptr = mesh_structure_indexer.GetDataPtr<int>(
xv, yv, zv, workload_block_idx);
int table_idx = mesh_struct_ptr[3];
if (tri_count[table_idx] == 0) return;
for (size_t tri = 0; tri < 16; tri += 3) {
if (tri_table[table_idx][tri] == -1) return;
int tri_idx = OPEN3D_ATOMIC_ADD(count_ptr, 1);
for (size_t vertex = 0; vertex < 3; ++vertex) {
int edge = tri_table[table_idx][tri + vertex];
int64_t xv_i = xv + edge_shifts[edge][0];
int64_t yv_i = yv + edge_shifts[edge][1];
int64_t zv_i = zv + edge_shifts[edge][2];
int64_t edge_i = edge_shifts[edge][3];
int dxb = static_cast<int>(xv_i / resolution);
int dyb = static_cast<int>(yv_i / resolution);
int dzb = static_cast<int>(zv_i / resolution);
int nb_idx = (dxb + 1) + (dyb + 1) * 3 + (dzb + 1) * 9;
int64_t block_idx_i =
*nb_block_indices_indexer.GetDataPtr<int64_t>(
workload_block_idx, nb_idx);
int* mesh_struct_ptr_i = mesh_structure_indexer.GetDataPtr<int>(
xv_i - dxb * resolution, yv_i - dyb * resolution,
zv_i - dzb * resolution, inv_indices_ptr[block_idx_i]);
int64_t* triangle_ptr =
triangle_indexer.GetDataPtr<int64_t>(tri_idx);
triangle_ptr[2 - vertex] = mesh_struct_ptr_i[edge_i];
}
}
});
#if defined(__CUDACC__)
triangle_count = count.Item<int>();
#else
triangle_count = (*count_ptr).load();
#endif
utility::LogInfo("Total triangle count = {}", triangle_count);
triangles = triangles.Slice(0, 0, triangle_count);
}
#if defined(__CUDACC__)
void EstimateRangeCUDA
#else
void EstimateRangeCPU
#endif
(const core::Tensor& block_keys,
core::Tensor& range_minmax_map,
const core::Tensor& intrinsics,
const core::Tensor& extrinsics,
int h,
int w,
int down_factor,
int64_t block_resolution,
float voxel_size,
float depth_min,
float depth_max) {
// TODO(wei): reserve it in a reusable buffer
// Every 2 channels: (min, max)
int h_down = h / down_factor;
int w_down = w / down_factor;
range_minmax_map = core::Tensor({h_down, w_down, 2}, core::Float32,
block_keys.GetDevice());
NDArrayIndexer range_map_indexer(range_minmax_map, 2);
// Every 6 channels: (v_min, u_min, v_max, u_max, z_min, z_max)
const int fragment_size = 16;
const int frag_buffer_size = 65535;
// TODO(wei): explicit buffer
core::Tensor fragment_buffer = core::Tensor(
{frag_buffer_size, 6}, core::Float32, block_keys.GetDevice());
NDArrayIndexer frag_buffer_indexer(fragment_buffer, 1);
NDArrayIndexer block_keys_indexer(block_keys, 1);
TransformIndexer w2c_transform_indexer(intrinsics, extrinsics);
#if defined(__CUDACC__)
core::Tensor count(std::vector<int>{0}, {1}, core::Int32,
block_keys.GetDevice());
int* count_ptr = count.GetDataPtr<int>();
#else
std::atomic<int> count_atomic(0);
std::atomic<int>* count_ptr = &count_atomic;
#endif
#if defined(__CUDACC__)
namespace launcher = core::kernel::cuda_launcher;
#else
namespace launcher = core::kernel::cpu_launcher;
using std::max;
using std::min;
#endif
// Pass 0: iterate over blocks, fill-in an rendering fragment array
launcher::ParallelFor(
block_keys.GetLength(), [=] OPEN3D_DEVICE(int64_t workload_idx) {
int* key = block_keys_indexer.GetDataPtr<int>(workload_idx);
int u_min = w_down - 1, v_min = h_down - 1, u_max = 0,
v_max = 0;
float z_min = depth_max, z_max = depth_min;
float xc, yc, zc, u, v;
// Project 8 corners to low-res image and form a rectangle
for (int i = 0; i < 8; ++i) {
float xw = (key[0] + ((i & 1) > 0)) * block_resolution *
voxel_size;
float yw = (key[1] + ((i & 2) > 0)) * block_resolution *
voxel_size;
float zw = (key[2] + ((i & 4) > 0)) * block_resolution *
voxel_size;
w2c_transform_indexer.RigidTransform(xw, yw, zw, &xc, &yc,
&zc);
if (zc <= 0) continue;
// Project to the down sampled image buffer
w2c_transform_indexer.Project(xc, yc, zc, &u, &v);
u /= down_factor;
v /= down_factor;
v_min = min(static_cast<int>(floorf(v)), v_min);
v_max = max(static_cast<int>(ceilf(v)), v_max);
u_min = min(static_cast<int>(floorf(u)), u_min);
u_max = max(static_cast<int>(ceilf(u)), u_max);
z_min = min(z_min, zc);
z_max = max(z_max, zc);
}
v_min = max(0, v_min);
v_max = min(h_down - 1, v_max);
u_min = max(0, u_min);
u_max = min(w_down - 1, u_max);
if (v_min >= v_max || u_min >= u_max || z_min >= z_max) return;
// Divide the rectangle into small 16x16 fragments
int frag_v_count =
ceilf(float(v_max - v_min + 1) / float(fragment_size));
int frag_u_count =
ceilf(float(u_max - u_min + 1) / float(fragment_size));
int frag_count = frag_v_count * frag_u_count;
int frag_count_start = OPEN3D_ATOMIC_ADD(count_ptr, 1);
int frag_count_end = frag_count_start + frag_count;
if (frag_count_end >= frag_buffer_size) {
printf("Fragment count exceeding buffer size, abort!\n");
}
int offset = 0;
for (int frag_v = 0; frag_v < frag_v_count; ++frag_v) {
for (int frag_u = 0; frag_u < frag_u_count;
++frag_u, ++offset) {
float* frag_ptr = frag_buffer_indexer.GetDataPtr<float>(
frag_count_start + offset);
// zmin, zmax
frag_ptr[0] = z_min;
frag_ptr[1] = z_max;
// vmin, umin
frag_ptr[2] = v_min + frag_v * fragment_size;
frag_ptr[3] = u_min + frag_u * fragment_size;
// vmax, umax
frag_ptr[4] = min(frag_ptr[2] + fragment_size - 1,
static_cast<float>(v_max));
frag_ptr[5] = min(frag_ptr[3] + fragment_size - 1,
static_cast<float>(u_max));
}
}
});
#if defined(__CUDACC__)
int frag_count = count[0].Item<int>();
#else
int frag_count = (*count_ptr).load();
#endif
// Pass 0.5: Fill in range map to prepare for atomic min/max
launcher::ParallelFor(
h_down * w_down, [=] OPEN3D_DEVICE(int64_t workload_idx) {
int v = workload_idx / w_down;
int u = workload_idx % w_down;
float* range_ptr = range_map_indexer.GetDataPtr<float>(u, v);
range_ptr[0] = depth_max;
range_ptr[1] = depth_min;
});
// Pass 1: iterate over rendering fragment array, fill-in range
launcher::ParallelFor(
frag_count * fragment_size * fragment_size,
[=] OPEN3D_DEVICE(int64_t workload_idx) {
int frag_idx = workload_idx / (fragment_size * fragment_size);
int local_idx = workload_idx % (fragment_size * fragment_size);
int dv = local_idx / fragment_size;
int du = local_idx % fragment_size;
float* frag_ptr =
frag_buffer_indexer.GetDataPtr<float>(frag_idx);
int v_min = static_cast<int>(frag_ptr[2]);
int u_min = static_cast<int>(frag_ptr[3]);
int v_max = static_cast<int>(frag_ptr[4]);
int u_max = static_cast<int>(frag_ptr[5]);
int v = v_min + dv;
int u = u_min + du;
if (v > v_max || u > u_max) return;
float z_min = frag_ptr[0];
float z_max = frag_ptr[1];
float* range_ptr = range_map_indexer.GetDataPtr<float>(u, v);
#ifdef __CUDACC__
atomicMinf(&(range_ptr[0]), z_min);
atomicMaxf(&(range_ptr[1]), z_max);
#else
#pragma omp critical(EstimateRangeCPU)
{
range_ptr[0] = min(z_min, range_ptr[0]);
range_ptr[1] = max(z_max, range_ptr[1]);
}
#endif
});
#if defined(__CUDACC__)
OPEN3D_CUDA_CHECK(cudaDeviceSynchronize());
#endif
}
struct BlockCache {
int x;
int y;
int z;
int block_idx;
inline int OPEN3D_DEVICE Check(int xin, int yin, int zin) {
return (xin == x && yin == y && zin == z) ? block_idx : -1;
}
inline void OPEN3D_DEVICE Update(int xin,
int yin,
int zin,
int block_idx_in) {
x = xin;
y = yin;
z = zin;
block_idx = block_idx_in;
}
};
#if defined(__CUDACC__)
void RayCastCUDA
#else
void RayCastCPU
#endif
(std::shared_ptr<core::DeviceHashmap>& hashmap,
const core::Tensor& block_values,
const core::Tensor& range_map,
core::Tensor& vertex_map,
core::Tensor& depth_map,
core::Tensor& color_map,
core::Tensor& normal_map,
const core::Tensor& intrinsics,
const core::Tensor& extrinsics,
int h,
int w,
int64_t block_resolution,
float voxel_size,
float sdf_trunc,
float depth_scale,
float depth_min,
float depth_max,
float weight_threshold) {
using Key = core::Block<int, 3>;
using Hash = core::BlockHash<int, 3>;
#if defined(BUILD_CUDA_MODULE) && defined(__CUDACC__)
auto cuda_hashmap =
std::dynamic_pointer_cast<core::StdGPUHashmap<Key, Hash>>(hashmap);
if (cuda_hashmap == nullptr) {
utility::LogError(
"Unsupported backend: CUDA raycasting only supports STDGPU.");
}
auto hashmap_impl = cuda_hashmap->GetImpl();
#else
auto cpu_hashmap =
std::dynamic_pointer_cast<core::TBBHashmap<Key, Hash>>(hashmap);
auto hashmap_impl = *cpu_hashmap->GetImpl();
#endif
NDArrayIndexer voxel_block_buffer_indexer(block_values, 4);
NDArrayIndexer range_map_indexer(range_map, 2);
NDArrayIndexer vertex_map_indexer;
NDArrayIndexer depth_map_indexer;
NDArrayIndexer color_map_indexer;
NDArrayIndexer normal_map_indexer;
bool enable_vertex = (vertex_map.GetLength() != 0);
bool enable_depth = (depth_map.GetLength() != 0);
bool enable_color = (color_map.GetLength() != 0);
bool enable_normal = (normal_map.GetLength() != 0);
if (!enable_vertex && !enable_depth && !enable_color && !enable_normal) {
utility::LogWarning("No output specified for ray casting, exit.");
return;
}
if (enable_vertex) {
vertex_map_indexer = NDArrayIndexer(vertex_map, 2);
}
if (enable_depth) {
depth_map_indexer = NDArrayIndexer(depth_map, 2);
}
if (enable_color) {
color_map_indexer = NDArrayIndexer(color_map, 2);
}
if (enable_normal) {
normal_map_indexer = NDArrayIndexer(normal_map, 2);
}
TransformIndexer c2w_transform_indexer(
intrinsics, t::geometry::InverseTransformation(extrinsics));
TransformIndexer w2c_transform_indexer(intrinsics, extrinsics);
int64_t rows = h;
int64_t cols = w;
float block_size = voxel_size * block_resolution;
#if defined(__CUDACC__)
namespace launcher = core::kernel::cuda_launcher;
#else
namespace launcher = core::kernel::cpu_launcher;
using std::max;
#endif
DISPATCH_BYTESIZE_TO_VOXEL(
voxel_block_buffer_indexer.ElementByteSize(), [&]() {
launcher::ParallelFor(rows * cols, [=] OPEN3D_DEVICE(
int64_t workload_idx) {
auto GetVoxelAtP = [&] OPEN3D_DEVICE(
int x_b, int y_b, int z_b,
int x_v, int y_v, int z_v,
core::addr_t block_addr,
BlockCache& cache) -> voxel_t* {
int x_vn = (x_v + block_resolution) % block_resolution;
int y_vn = (y_v + block_resolution) % block_resolution;
int z_vn = (z_v + block_resolution) % block_resolution;
int dx_b = Sign(x_v - x_vn);
int dy_b = Sign(y_v - y_vn);
int dz_b = Sign(z_v - z_vn);
if (dx_b == 0 && dy_b == 0 && dz_b == 0) {
return voxel_block_buffer_indexer
.GetDataPtr<voxel_t>(x_v, y_v, z_v,
block_addr);
} else {
Key key;
key.Set(0, x_b + dx_b);
key.Set(1, y_b + dy_b);
key.Set(2, z_b + dz_b);
int block_addr = cache.Check(key.Get(0), key.Get(1),
key.Get(2));
if (block_addr < 0) {
auto iter = hashmap_impl.find(key);
if (iter == hashmap_impl.end()) return nullptr;
block_addr = iter->second;
cache.Update(key.Get(0), key.Get(1), key.Get(2),
block_addr);
}
return voxel_block_buffer_indexer
.GetDataPtr<voxel_t>(x_vn, y_vn, z_vn,
block_addr);
}
};
auto GetVoxelAtT = [&] OPEN3D_DEVICE(
float x_o, float y_o, float z_o,
float x_d, float y_d, float z_d,
float t,
BlockCache& cache) -> voxel_t* {
float x_g = x_o + t * x_d;
float y_g = y_o + t * y_d;
float z_g = z_o + t * z_d;
// Block coordinate and look up
int x_b = static_cast<int>(floorf(x_g / block_size));
int y_b = static_cast<int>(floorf(y_g / block_size));
int z_b = static_cast<int>(floorf(z_g / block_size));
Key key;
key.Set(0, x_b);
key.Set(1, y_b);
key.Set(2, z_b);
int block_addr = cache.Check(x_b, y_b, z_b);
if (block_addr < 0) {
auto iter = hashmap_impl.find(key);
if (iter == hashmap_impl.end()) return nullptr;
block_addr = iter->second;
cache.Update(x_b, y_b, z_b, block_addr);
}
// Voxel coordinate and look up
int x_v = int((x_g - x_b * block_size) / voxel_size);
int y_v = int((y_g - y_b * block_size) / voxel_size);
int z_v = int((z_g - z_b * block_size) / voxel_size);
return voxel_block_buffer_indexer.GetDataPtr<voxel_t>(
x_v, y_v, z_v, block_addr);
};
int64_t y = workload_idx / cols;
int64_t x = workload_idx % cols;
float *depth_ptr = nullptr, *vertex_ptr = nullptr,
*normal_ptr = nullptr, *color_ptr = nullptr;
if (enable_depth) {
depth_ptr = depth_map_indexer.GetDataPtr<float>(x, y);
*depth_ptr = 0;
}
if (enable_vertex) {
vertex_ptr = vertex_map_indexer.GetDataPtr<float>(x, y);
vertex_ptr[0] = 0;
vertex_ptr[1] = 0;
vertex_ptr[2] = 0;
}
if (enable_color) {
color_ptr = color_map_indexer.GetDataPtr<float>(x, y);
color_ptr[0] = 0;
color_ptr[1] = 0;
color_ptr[2] = 0;
}
if (enable_normal) {
normal_ptr = normal_map_indexer.GetDataPtr<float>(x, y);
normal_ptr[0] = 0;
normal_ptr[1] = 0;
normal_ptr[2] = 0;
}
const float* range =
range_map_indexer.GetDataPtr<float>(x / 8, y / 8);
float t = range[0];
const float t_max = range[1];
if (t >= t_max) return;
// Coordinates in camera and global
float x_c = 0, y_c = 0, z_c = 0;
float x_g = 0, y_g = 0, z_g = 0;
float x_o = 0, y_o = 0, z_o = 0;
// Iterative ray intersection check
float t_prev = t;
float tsdf_prev = -1.0f;
float tsdf = 1.0;
float w = 0.0;
// Camera origin
c2w_transform_indexer.RigidTransform(0, 0, 0, &x_o, &y_o,
&z_o);
// Direction
c2w_transform_indexer.Unproject(static_cast<float>(x),
static_cast<float>(y), 1.0f,
&x_c, &y_c, &z_c);
c2w_transform_indexer.RigidTransform(x_c, y_c, z_c, &x_g,
&y_g, &z_g);
float x_d = (x_g - x_o);
float y_d = (y_g - y_o);
float z_d = (z_g - z_o);
BlockCache cache{0, 0, 0, -1};
bool surface_found = false;
while (t < t_max) {
voxel_t* voxel_ptr = GetVoxelAtT(x_o, y_o, z_o, x_d,
y_d, z_d, t, cache);
if (!voxel_ptr) {
t_prev = t;
t += block_size;
} else {
tsdf_prev = tsdf;
tsdf = voxel_ptr->GetTSDF();
w = voxel_ptr->GetWeight();
if (tsdf_prev > 0 && w >= weight_threshold &&
tsdf <= 0) {
surface_found = true;
break;
}
t_prev = t;
float delta = tsdf * sdf_trunc;
t += delta < voxel_size ? voxel_size : delta;
}
}
if (surface_found) {
float t_intersect = (t * tsdf_prev - t_prev * tsdf) /
(tsdf_prev - tsdf);
x_g = x_o + t_intersect * x_d;
y_g = y_o + t_intersect * y_d;
z_g = z_o + t_intersect * z_d;
// Trivial vertex assignment
if (enable_depth) {
*depth_ptr = t_intersect * depth_scale;
}
if (enable_vertex) {
w2c_transform_indexer.RigidTransform(
x_g, y_g, z_g, vertex_ptr + 0,
vertex_ptr + 1, vertex_ptr + 2);
}
// Trilinear interpolation
// TODO(wei): simplify the flow by splitting the
// functions given what is enabled
if (enable_color || enable_normal) {
int x_b =
static_cast<int>(floorf(x_g / block_size));
int y_b =
static_cast<int>(floorf(y_g / block_size));
int z_b =
static_cast<int>(floorf(z_g / block_size));
float x_v = (x_g - float(x_b) * block_size) /
voxel_size;
float y_v = (y_g - float(y_b) * block_size) /
voxel_size;
float z_v = (z_g - float(z_b) * block_size) /
voxel_size;
Key key;
key.Set(0, x_b);
key.Set(1, y_b);
key.Set(2, z_b);
int block_addr = cache.Check(x_b, y_b, z_b);
if (block_addr < 0) {
auto iter = hashmap_impl.find(key);
if (iter == hashmap_impl.end()) return;
block_addr = iter->second;
cache.Update(x_b, y_b, z_b, block_addr);
}
int x_v_floor = static_cast<int>(floorf(x_v));
int y_v_floor = static_cast<int>(floorf(y_v));
int z_v_floor = static_cast<int>(floorf(z_v));
float ratio_x = x_v - float(x_v_floor);
float ratio_y = y_v - float(y_v_floor);
float ratio_z = z_v - float(z_v_floor);
float sum_weight_color = 0.0;
float sum_weight_normal = 0.0;
for (int k = 0; k < 8; ++k) {
int dx_v = (k & 1) > 0 ? 1 : 0;
int dy_v = (k & 2) > 0 ? 1 : 0;
int dz_v = (k & 4) > 0 ? 1 : 0;
float ratio = (dx_v * (ratio_x) +
(1 - dx_v) * (1 - ratio_x)) *
(dy_v * (ratio_y) +
(1 - dy_v) * (1 - ratio_y)) *
(dz_v * (ratio_z) +
(1 - dz_v) * (1 - ratio_z));
voxel_t* voxel_ptr_k = GetVoxelAtP(
x_b, y_b, z_b, x_v_floor + dx_v,
y_v_floor + dy_v, z_v_floor + dz_v,
block_addr, cache);
if (enable_color && voxel_ptr_k &&
voxel_ptr_k->GetWeight() > 0) {
sum_weight_color += ratio;
color_ptr[0] += ratio * voxel_ptr_k->GetR();
color_ptr[1] += ratio * voxel_ptr_k->GetG();
color_ptr[2] += ratio * voxel_ptr_k->GetB();
}
if (enable_normal) {
for (int dim = 0; dim < 3; ++dim) {
voxel_t* voxel_ptr_k_plus = GetVoxelAtP(
x_b, y_b, z_b,
x_v_floor + dx_v + (dim == 0),
y_v_floor + dy_v + (dim == 1),
z_v_floor + dz_v + (dim == 2),
block_addr, cache);
voxel_t* voxel_ptr_k_minus =
GetVoxelAtP(x_b, y_b, z_b,
x_v_floor + dx_v -
(dim == 0),
y_v_floor + dy_v -
(dim == 1),
z_v_floor + dz_v -
(dim == 2),
block_addr, cache);
bool valid = false;
if (voxel_ptr_k_plus &&
voxel_ptr_k_plus->GetWeight() > 0) {
normal_ptr[dim] +=
ratio *
voxel_ptr_k_plus
->GetTSDF() /
(2 * voxel_size);
valid = true;
}
if (voxel_ptr_k_minus &&
voxel_ptr_k_minus->GetWeight() >
0) {
normal_ptr[dim] -=
ratio *
voxel_ptr_k_minus
->GetTSDF() /
(2 * voxel_size);
valid = true;
}
sum_weight_normal += valid ? ratio : 0;
}
} // if (enable_normal)
} // loop over 8 neighbors
if (enable_color && sum_weight_color > 0) {
sum_weight_color *= 255.0;
color_ptr[0] /= sum_weight_color;
color_ptr[1] /= sum_weight_color;
color_ptr[2] /= sum_weight_color;
}
if (enable_normal && sum_weight_normal > 0) {
normal_ptr[0] /= sum_weight_normal;
normal_ptr[1] /= sum_weight_normal;
normal_ptr[2] /= sum_weight_normal;
float norm =
sqrt(normal_ptr[0] * normal_ptr[0] +
normal_ptr[1] * normal_ptr[1] +
normal_ptr[2] * normal_ptr[2]);
w2c_transform_indexer.Rotate(
normal_ptr[0] / norm,
normal_ptr[1] / norm,
normal_ptr[2] / norm, normal_ptr + 0,
normal_ptr + 1, normal_ptr + 2);
}
} // if (color or normal)
} // if (tsdf < 0)
});
});
#if defined(__CUDACC__)
OPEN3D_CUDA_CHECK(cudaDeviceSynchronize());
#endif
}
} // namespace tsdf
} // namespace kernel
} // namespace geometry
} // namespace t
} // namespace open3d
|
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] = 8;
tile_size[1] = 8;
tile_size[2] = 32;
tile_size[3] = 128;
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,4);t1++) {
lbp=max(ceild(t1,2),ceild(8*t1-Nt+3,8));
ubp=min(floord(Nt+Nz-4,8),floord(4*t1+Nz+1,8));
#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(t1-7,8)),ceild(8*t2-Nz-28,32));t3<=min(min(min(floord(Nt+Ny-4,32),floord(4*t1+Ny+5,32)),floord(8*t2+Ny+4,32)),floord(8*t1-8*t2+Nz+Ny+3,32));t3++) {
for (t4=max(max(max(0,ceild(t1-31,32)),ceild(8*t2-Nz-124,128)),ceild(32*t3-Ny-124,128));t4<=min(min(min(min(floord(Nt+Nx-4,128),floord(4*t1+Nx+5,128)),floord(8*t2+Nx+4,128)),floord(32*t3+Nx+28,128)),floord(8*t1-8*t2+Nz+Nx+3,128));t4++) {
for (t5=max(max(max(max(max(0,4*t1),8*t1-8*t2+1),8*t2-Nz+2),32*t3-Ny+2),128*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,4*t1+7),8*t2+6),32*t3+30),128*t4+126),8*t1-8*t2+Nz+5);t5++) {
for (t6=max(max(8*t2,t5+1),-8*t1+8*t2+2*t5-7);t6<=min(min(8*t2+7,-8*t1+8*t2+2*t5),t5+Nz-2);t6++) {
for (t7=max(32*t3,t5+1);t7<=min(32*t3+31,t5+Ny-2);t7++) {
lbv=max(128*t4,t5+1);
ubv=min(128*t4+127,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;
}
|
seidel.pluto.par.l2tile.c | #include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <math.h>
double A[N][N+13];
void init_arrays()
{
int i, j;
for (i=0; i<N; i++)
for (j=0; j<N; j++)
A[i][j] = i*i+j*j;
}
double rtclock()
{
struct timezone tzp;
struct timeval tp;
int stat;
gettimeofday (&tp, &tzp);
return (tp.tv_sec + tp.tv_usec*1.0e-6);
}
int main()
{
init_arrays();
double annot_t_start=0, annot_t_end=0, annot_t_total=0;
int annot_i;
for (annot_i=0; annot_i<REPS; annot_i++)
{
annot_t_start = rtclock();
#include <math.h>
#include <assert.h>
#include <omp.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))
int c1, c2, c3, c4, c5, c6, c7, c8, c9;
register int lb, ub, lb1, ub1, lb2, ub2;
register int lbv, ubv;
if (N >= 3) {
for (c1=-1;c1<=floord(2*T+N-4,256);c1++) {
lb1=max(max(ceild(256*c1-T+1,256),ceild(128*c1-127,256)),0);
ub1=min(min(floord(256*c1+255,256),floord(256*c1+N+253,512)),floord(T+N-3,256));
#pragma omp parallel for shared(c1,lb1,ub1) private(c2,c3,c4,c5,c6,c7,c8,c9)
for (c2=lb1; c2<=ub1; c2++) {
for (c3=max(max(max(max(0,ceild(512*c2-N-252,256)),ceild(512*c1-512*c2-253,256)),ceild(128*c2-127,128)),ceild(128*c1-127,128));c3<=min(min(min(min(floord(T+N-3,128),floord(256*c1-256*c2+N+253,128)),floord(256*c1+N+508,256)),floord(256*c2+T+N+252,256)),floord(512*c2+N+507,256));c3++) {
for (c4=max(max(max(max(0,ceild(128*c3-N-29,32)),8*c1-8*c2),ceild(256*c2-N-29,32)),ceild(-256*c2+256*c3-N-284,32));c4<=min(min(min(min(8*c1-8*c2+7,floord(T-1,32)),floord(128*c2+127,16)),floord(-128*c2+128*c3+127,16)),floord(256*c3+253,64));c4++) {
for (c5=max(max(max(max(max(0,8*c2),ceild(256*c3-N-59,64)),ceild(256*c3-32*c4-N-60,32)),ceild(256*c3-T-N-28,32)),ceild(16*c4-15,16));c5<=min(min(min(min(min(8*c2+7,floord(256*c3+N+252,64)),floord(128*c3+127,16)),floord(128*c3-16*c4+127,16)),floord(T+N-3,32)),floord(32*c4+N+29,32));c5++) {
for (c6=max(max(max(max(max(8*c3,ceild(16*c4+16*c5-15,16)),ceild(64*c5-N-28,32)),ceild(16*c5-15,16)),ceild(64*c4-29,32)),0);c6<=min(min(min(min(min(floord(T+N-3,16),floord(32*c5+T+N+28,32)),floord(64*c5+N+59,32)),floord(32*c4+N+29,16)),8*c3+7),floord(32*c4+32*c5+N+60,32));c6++) {
for (c7=max(max(max(max(0,32*c4),32*c5-N+2),16*c6-N+2),-32*c5+32*c6-N-29);c7<=min(min(min(min(T-1,-32*c5+32*c6+30),floord(32*c6+29,2)),32*c4+31),32*c5+30);c7++) {
/*@ begin Loop(
transform Unroll(ufactor=4)
for (c8=max(max(c7+1,32*c5),32*c6-c7-N+2);c8<=min(min(c7+N-2,32*c6-c7+30),32*c5+31);c8++) {
transform UnrollJam(ufactor=4)
for (c9=max(c7+c8+1,32*c6);c9<=min(c7+c8+N-2,32*c6+31);c9++) {
A[-c7+c8][-c7-c8+c9]=(A[1+-c7+c8][1+-c7-c8+c9]+A[1+-c7+c8][-c7-c8+c9]+A[1+-c7+c8][-c7-c8+c9-1]+A[-c7+c8][1+-c7-c8+c9]+A[-c7+c8][-c7-c8+c9]+A[-c7+c8][-c7-c8+c9-1]+A[-c7+c8-1][1+-c7-c8+c9]+A[-c7+c8-1][-c7-c8+c9]+A[-c7+c8-1][-c7-c8+c9-1])/9;
}
}
) @*/ {
for (c8=max(max(c7+1,32*c5),32*c6-c7-N+2); c8<=min(min(c7+N-2,32*c6-c7+30),32*c5+31)-3; c8=c8+4) {
{
for (c9=max(c7+c8+1,32*c6); c9<=min(c7+c8+N-2,32*c6+31)-3; c9=c9+4) {
A[-c7+c8][-c7+c9-c8]=0.111111111111*(A[-c7+c8+1][-c7+c9-c8+1]+A[-c7+c8+1][-c7+c9-c8]+A[-c7+c8+1][-c7+c9-c8-1]+A[-c7+c8][-c7+c9-c8+1]+A[-c7+c8][-c7+c9-c8]+A[-c7+c8][-c7+c9-c8-1]+A[-c7+c8-1][-c7+c9-c8+1]+A[-c7+c8-1][-c7+c9-c8]+A[-c7+c8-1][-c7+c9-c8-1]);
A[-c7+c8][-c7+c9-c8+1]=0.111111111111*(A[-c7+c8+1][-c7+c9-c8+2]+A[-c7+c8+1][-c7+c9-c8+1]+A[-c7+c8+1][-c7+c9-c8]+A[-c7+c8][-c7+c9-c8+2]+A[-c7+c8][-c7+c9-c8+1]+A[-c7+c8][-c7+c9-c8]+A[-c7+c8-1][-c7+c9-c8+2]+A[-c7+c8-1][-c7+c9-c8+1]+A[-c7+c8-1][-c7+c9-c8]);
A[-c7+c8][-c7+c9-c8+2]=0.111111111111*(A[-c7+c8+1][-c7+c9-c8+3]+A[-c7+c8+1][-c7+c9-c8+2]+A[-c7+c8+1][-c7+c9-c8+1]+A[-c7+c8][-c7+c9-c8+3]+A[-c7+c8][-c7+c9-c8+2]+A[-c7+c8][-c7+c9-c8+1]+A[-c7+c8-1][-c7+c9-c8+3]+A[-c7+c8-1][-c7+c9-c8+2]+A[-c7+c8-1][-c7+c9-c8+1]);
A[-c7+c8][-c7+c9-c8+3]=0.111111111111*(A[-c7+c8+1][-c7+c9-c8+4]+A[-c7+c8+1][-c7+c9-c8+3]+A[-c7+c8+1][-c7+c9-c8+2]+A[-c7+c8][-c7+c9-c8+4]+A[-c7+c8][-c7+c9-c8+3]+A[-c7+c8][-c7+c9-c8+2]+A[-c7+c8-1][-c7+c9-c8+4]+A[-c7+c8-1][-c7+c9-c8+3]+A[-c7+c8-1][-c7+c9-c8+2]);
}
for (; c9<=min(c7+c8+N-2,32*c6+31); c9=c9+1) {
A[-c7+c8][-c7+c9-c8]=0.111111111111*(A[-c7+c8+1][-c7+c9-c8+1]+A[-c7+c8+1][-c7+c9-c8]+A[-c7+c8+1][-c7+c9-c8-1]+A[-c7+c8][-c7+c9-c8+1]+A[-c7+c8][-c7+c9-c8]+A[-c7+c8][-c7+c9-c8-1]+A[-c7+c8-1][-c7+c9-c8+1]+A[-c7+c8-1][-c7+c9-c8]+A[-c7+c8-1][-c7+c9-c8-1]);
}
}
{
for (c9=max(c7+c8+2,32*c6); c9<=min(c7+c8+N-1,32*c6+31)-3; c9=c9+4) {
A[-c7+c8+1][-c7+c9-c8-1]=0.111111111111*(A[-c7+c8+2][-c7+c9-c8]+A[-c7+c8+2][-c7+c9-c8-1]+A[-c7+c8+2][-c7+c9-c8-2]+A[-c7+c8+1][-c7+c9-c8]+A[-c7+c8+1][-c7+c9-c8-1]+A[-c7+c8+1][-c7+c9-c8-2]+A[-c7+c8][-c7+c9-c8]+A[-c7+c8][-c7+c9-c8-1]+A[-c7+c8][-c7+c9-c8-2]);
A[-c7+c8+1][-c7+c9-c8]=0.111111111111*(A[-c7+c8+2][-c7+c9-c8+1]+A[-c7+c8+2][-c7+c9-c8]+A[-c7+c8+2][-c7+c9-c8-1]+A[-c7+c8+1][-c7+c9-c8+1]+A[-c7+c8+1][-c7+c9-c8]+A[-c7+c8+1][-c7+c9-c8-1]+A[-c7+c8][-c7+c9-c8+1]+A[-c7+c8][-c7+c9-c8]+A[-c7+c8][-c7+c9-c8-1]);
A[-c7+c8+1][-c7+c9-c8+1]=0.111111111111*(A[-c7+c8+2][-c7+c9-c8+2]+A[-c7+c8+2][-c7+c9-c8+1]+A[-c7+c8+2][-c7+c9-c8]+A[-c7+c8+1][-c7+c9-c8+2]+A[-c7+c8+1][-c7+c9-c8+1]+A[-c7+c8+1][-c7+c9-c8]+A[-c7+c8][-c7+c9-c8+2]+A[-c7+c8][-c7+c9-c8+1]+A[-c7+c8][-c7+c9-c8]);
A[-c7+c8+1][-c7+c9-c8+2]=0.111111111111*(A[-c7+c8+2][-c7+c9-c8+3]+A[-c7+c8+2][-c7+c9-c8+2]+A[-c7+c8+2][-c7+c9-c8+1]+A[-c7+c8+1][-c7+c9-c8+3]+A[-c7+c8+1][-c7+c9-c8+2]+A[-c7+c8+1][-c7+c9-c8+1]+A[-c7+c8][-c7+c9-c8+3]+A[-c7+c8][-c7+c9-c8+2]+A[-c7+c8][-c7+c9-c8+1]);
}
for (; c9<=min(c7+c8+N-1,32*c6+31); c9=c9+1) {
A[-c7+c8+1][-c7+c9-c8-1]=0.111111111111*(A[-c7+c8+2][-c7+c9-c8]+A[-c7+c8+2][-c7+c9-c8-1]+A[-c7+c8+2][-c7+c9-c8-2]+A[-c7+c8+1][-c7+c9-c8]+A[-c7+c8+1][-c7+c9-c8-1]+A[-c7+c8+1][-c7+c9-c8-2]+A[-c7+c8][-c7+c9-c8]+A[-c7+c8][-c7+c9-c8-1]+A[-c7+c8][-c7+c9-c8-2]);
}
}
{
for (c9=max(c7+c8+3,32*c6); c9<=min(c7+c8+N,32*c6+31)-3; c9=c9+4) {
A[-c7+c8+2][-c7+c9-c8-2]=0.111111111111*(A[-c7+c8+3][-c7+c9-c8-1]+A[-c7+c8+3][-c7+c9-c8-2]+A[-c7+c8+3][-c7+c9-c8-3]+A[-c7+c8+2][-c7+c9-c8-1]+A[-c7+c8+2][-c7+c9-c8-2]+A[-c7+c8+2][-c7+c9-c8-3]+A[-c7+c8+1][-c7+c9-c8-1]+A[-c7+c8+1][-c7+c9-c8-2]+A[-c7+c8+1][-c7+c9-c8-3]);
A[-c7+c8+2][-c7+c9-c8-1]=0.111111111111*(A[-c7+c8+3][-c7+c9-c8]+A[-c7+c8+3][-c7+c9-c8-1]+A[-c7+c8+3][-c7+c9-c8-2]+A[-c7+c8+2][-c7+c9-c8]+A[-c7+c8+2][-c7+c9-c8-1]+A[-c7+c8+2][-c7+c9-c8-2]+A[-c7+c8+1][-c7+c9-c8]+A[-c7+c8+1][-c7+c9-c8-1]+A[-c7+c8+1][-c7+c9-c8-2]);
A[-c7+c8+2][-c7+c9-c8]=0.111111111111*(A[-c7+c8+3][-c7+c9-c8+1]+A[-c7+c8+3][-c7+c9-c8]+A[-c7+c8+3][-c7+c9-c8-1]+A[-c7+c8+2][-c7+c9-c8+1]+A[-c7+c8+2][-c7+c9-c8]+A[-c7+c8+2][-c7+c9-c8-1]+A[-c7+c8+1][-c7+c9-c8+1]+A[-c7+c8+1][-c7+c9-c8]+A[-c7+c8+1][-c7+c9-c8-1]);
A[-c7+c8+2][-c7+c9-c8+1]=0.111111111111*(A[-c7+c8+3][-c7+c9-c8+2]+A[-c7+c8+3][-c7+c9-c8+1]+A[-c7+c8+3][-c7+c9-c8]+A[-c7+c8+2][-c7+c9-c8+2]+A[-c7+c8+2][-c7+c9-c8+1]+A[-c7+c8+2][-c7+c9-c8]+A[-c7+c8+1][-c7+c9-c8+2]+A[-c7+c8+1][-c7+c9-c8+1]+A[-c7+c8+1][-c7+c9-c8]);
}
for (; c9<=min(c7+c8+N,32*c6+31); c9=c9+1) {
A[-c7+c8+2][-c7+c9-c8-2]=0.111111111111*(A[-c7+c8+3][-c7+c9-c8-1]+A[-c7+c8+3][-c7+c9-c8-2]+A[-c7+c8+3][-c7+c9-c8-3]+A[-c7+c8+2][-c7+c9-c8-1]+A[-c7+c8+2][-c7+c9-c8-2]+A[-c7+c8+2][-c7+c9-c8-3]+A[-c7+c8+1][-c7+c9-c8-1]+A[-c7+c8+1][-c7+c9-c8-2]+A[-c7+c8+1][-c7+c9-c8-3]);
}
}
{
for (c9=max(c7+c8+4,32*c6); c9<=min(c7+c8+N+1,32*c6+31)-3; c9=c9+4) {
A[-c7+c8+3][-c7+c9-c8-3]=0.111111111111*(A[-c7+c8+4][-c7+c9-c8-2]+A[-c7+c8+4][-c7+c9-c8-3]+A[-c7+c8+4][-c7+c9-c8-4]+A[-c7+c8+3][-c7+c9-c8-2]+A[-c7+c8+3][-c7+c9-c8-3]+A[-c7+c8+3][-c7+c9-c8-4]+A[-c7+c8+2][-c7+c9-c8-2]+A[-c7+c8+2][-c7+c9-c8-3]+A[-c7+c8+2][-c7+c9-c8-4]);
A[-c7+c8+3][-c7+c9-c8-2]=0.111111111111*(A[-c7+c8+4][-c7+c9-c8-1]+A[-c7+c8+4][-c7+c9-c8-2]+A[-c7+c8+4][-c7+c9-c8-3]+A[-c7+c8+3][-c7+c9-c8-1]+A[-c7+c8+3][-c7+c9-c8-2]+A[-c7+c8+3][-c7+c9-c8-3]+A[-c7+c8+2][-c7+c9-c8-1]+A[-c7+c8+2][-c7+c9-c8-2]+A[-c7+c8+2][-c7+c9-c8-3]);
A[-c7+c8+3][-c7+c9-c8-1]=0.111111111111*(A[-c7+c8+4][-c7+c9-c8]+A[-c7+c8+4][-c7+c9-c8-1]+A[-c7+c8+4][-c7+c9-c8-2]+A[-c7+c8+3][-c7+c9-c8]+A[-c7+c8+3][-c7+c9-c8-1]+A[-c7+c8+3][-c7+c9-c8-2]+A[-c7+c8+2][-c7+c9-c8]+A[-c7+c8+2][-c7+c9-c8-1]+A[-c7+c8+2][-c7+c9-c8-2]);
A[-c7+c8+3][-c7+c9-c8]=0.111111111111*(A[-c7+c8+4][-c7+c9-c8+1]+A[-c7+c8+4][-c7+c9-c8]+A[-c7+c8+4][-c7+c9-c8-1]+A[-c7+c8+3][-c7+c9-c8+1]+A[-c7+c8+3][-c7+c9-c8]+A[-c7+c8+3][-c7+c9-c8-1]+A[-c7+c8+2][-c7+c9-c8+1]+A[-c7+c8+2][-c7+c9-c8]+A[-c7+c8+2][-c7+c9-c8-1]);
}
for (; c9<=min(c7+c8+N+1,32*c6+31); c9=c9+1) {
A[-c7+c8+3][-c7+c9-c8-3]=0.111111111111*(A[-c7+c8+4][-c7+c9-c8-2]+A[-c7+c8+4][-c7+c9-c8-3]+A[-c7+c8+4][-c7+c9-c8-4]+A[-c7+c8+3][-c7+c9-c8-2]+A[-c7+c8+3][-c7+c9-c8-3]+A[-c7+c8+3][-c7+c9-c8-4]+A[-c7+c8+2][-c7+c9-c8-2]+A[-c7+c8+2][-c7+c9-c8-3]+A[-c7+c8+2][-c7+c9-c8-4]);
}
}
}
for (; c8<=min(min(c7+N-2,32*c6-c7+30),32*c5+31); c8=c8+1) {
{
for (c9=max(c7+c8+1,32*c6); c9<=min(c7+c8+N-2,32*c6+31)-3; c9=c9+4) {
A[-c7+c8][-c7+c9-c8]=0.111111111111*(A[-c7+c8+1][-c7+c9-c8+1]+A[-c7+c8+1][-c7+c9-c8]+A[-c7+c8+1][-c7+c9-c8-1]+A[-c7+c8][-c7+c9-c8+1]+A[-c7+c8][-c7+c9-c8]+A[-c7+c8][-c7+c9-c8-1]+A[-c7+c8-1][-c7+c9-c8+1]+A[-c7+c8-1][-c7+c9-c8]+A[-c7+c8-1][-c7+c9-c8-1]);
A[-c7+c8][-c7+c9-c8+1]=0.111111111111*(A[-c7+c8+1][-c7+c9-c8+2]+A[-c7+c8+1][-c7+c9-c8+1]+A[-c7+c8+1][-c7+c9-c8]+A[-c7+c8][-c7+c9-c8+2]+A[-c7+c8][-c7+c9-c8+1]+A[-c7+c8][-c7+c9-c8]+A[-c7+c8-1][-c7+c9-c8+2]+A[-c7+c8-1][-c7+c9-c8+1]+A[-c7+c8-1][-c7+c9-c8]);
A[-c7+c8][-c7+c9-c8+2]=0.111111111111*(A[-c7+c8+1][-c7+c9-c8+3]+A[-c7+c8+1][-c7+c9-c8+2]+A[-c7+c8+1][-c7+c9-c8+1]+A[-c7+c8][-c7+c9-c8+3]+A[-c7+c8][-c7+c9-c8+2]+A[-c7+c8][-c7+c9-c8+1]+A[-c7+c8-1][-c7+c9-c8+3]+A[-c7+c8-1][-c7+c9-c8+2]+A[-c7+c8-1][-c7+c9-c8+1]);
A[-c7+c8][-c7+c9-c8+3]=0.111111111111*(A[-c7+c8+1][-c7+c9-c8+4]+A[-c7+c8+1][-c7+c9-c8+3]+A[-c7+c8+1][-c7+c9-c8+2]+A[-c7+c8][-c7+c9-c8+4]+A[-c7+c8][-c7+c9-c8+3]+A[-c7+c8][-c7+c9-c8+2]+A[-c7+c8-1][-c7+c9-c8+4]+A[-c7+c8-1][-c7+c9-c8+3]+A[-c7+c8-1][-c7+c9-c8+2]);
}
for (; c9<=min(c7+c8+N-2,32*c6+31); c9=c9+1) {
A[-c7+c8][-c7-c8+c9]=(A[1+-c7+c8][1+-c7-c8+c9]+A[1+-c7+c8][-c7-c8+c9]+A[1+-c7+c8][-c7-c8+c9-1]+A[-c7+c8][1+-c7-c8+c9]+A[-c7+c8][-c7-c8+c9]+A[-c7+c8][-c7-c8+c9-1]+A[-c7+c8-1][1+-c7-c8+c9]+A[-c7+c8-1][-c7-c8+c9]+A[-c7+c8-1][-c7-c8+c9-1])/9;
}
}
}
}
/*@ end @*/
}
}
}
}
}
}
}
}
annot_t_end = rtclock();
annot_t_total += annot_t_end - annot_t_start;
}
annot_t_total = annot_t_total / REPS;
#ifndef TEST
printf("%f\n", annot_t_total);
#else
{
int i, j;
for (i=0; i<N; i++) {
for (j=0; j<N; j++) {
if (j%100==0)
printf("\n");
printf("%f ",A[i][j]);
}
printf("\n");
}
}
#endif
return ((int) A[0][0]);
}
|
convolution_sgemm.h | // BUG1989 is pleased to support the open source community by supporting ncnn available.
//
// Copyright (C) 2019 BUG1989. 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 __AVX__
static void conv_im2col_sgemm_transform_kernel_sse(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_size)
{
const float* kernel = _kernel;
// kernel memory packed 8 x 8
kernel_tm.create(8 * kernel_size, inch, outch / 8 + (outch % 8) / 4 + outch % 4);
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 * 8;
const float* k0 = kernel + (p + 0) * inch * kernel_size;
const float* k1 = kernel + (p + 1) * inch * kernel_size;
const float* k2 = kernel + (p + 2) * inch * kernel_size;
const float* k3 = kernel + (p + 3) * inch * kernel_size;
const float* k4 = kernel + (p + 4) * inch * kernel_size;
const float* k5 = kernel + (p + 5) * inch * kernel_size;
const float* k6 = kernel + (p + 6) * inch * kernel_size;
const float* k7 = kernel + (p + 7) * inch * kernel_size;
float* ktmp = kernel_tm.channel(p / 8);
for (int q = 0; q < inch * kernel_size; q++)
{
ktmp[0] = k0[0];
ktmp[1] = k1[0];
ktmp[2] = k2[0];
ktmp[3] = k3[0];
ktmp[4] = k4[0];
ktmp[5] = k5[0];
ktmp[6] = k6[0];
ktmp[7] = k7[0];
ktmp += 8;
k0 += 1;
k1 += 1;
k2 += 1;
k3 += 1;
k4 += 1;
k5 += 1;
k6 += 1;
k7 += 1;
}
}
nn_outch = (outch - remain_outch_start) >> 2;
for (int pp = 0; pp < nn_outch; pp++)
{
int p = remain_outch_start + pp * 4;
const float* k0 = kernel + (p + 0) * inch * kernel_size;
const float* k1 = kernel + (p + 1) * inch * kernel_size;
const float* k2 = kernel + (p + 2) * inch * kernel_size;
const float* k3 = kernel + (p + 3) * inch * kernel_size;
float* ktmp = kernel_tm.channel(p / 8 + (p % 8) / 4);
for (int q = 0; q < inch * kernel_size; q++)
{
ktmp[0] = k0[0];
ktmp[1] = k1[0];
ktmp[2] = k2[0];
ktmp[3] = k3[0];
ktmp += 4;
k0 += 1;
k1 += 1;
k2 += 1;
k3 += 1;
}
}
remain_outch_start += nn_outch << 2;
for (int p = remain_outch_start; p < outch; p++)
{
const float* k0 = kernel + (p + 0) * inch * kernel_size;
float* ktmp = kernel_tm.channel(p / 8 + (p % 8) / 4 + p % 4);
for (int q = 0; q < inch * kernel_size; q++)
{
ktmp[0] = k0[0];
ktmp++;
k0++;
}
}
}
static void conv_im2col_sgemm_sse(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias,
const int kernel_w, const int kernel_h, const int stride_w, const int stride_h, const Option& opt)
{
int w = bottom_blob.w;
int inch = bottom_blob.c;
size_t elemsize = bottom_blob.elemsize;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const float* bias = _bias;
// im2col
Mat bottom_im2col(outw * outh, kernel_h * kernel_w * inch, elemsize, opt.workspace_allocator);
{
const int stride = kernel_h * kernel_w * outw * outh;
float* ret = (float*)bottom_im2col;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < inch; p++)
{
const float* input = bottom_blob.channel(p);
int retID = stride * p;
for (int u = 0; u < kernel_h; u++)
{
for (int v = 0; v < kernel_w; v++)
{
for (int i = 0; i < outh; i++)
{
for (int j = 0; j < outw; j++)
{
int row = u + i * stride_h;
int col = v + j * stride_w;
int index = row * w + col;
ret[retID] = input[index];
retID++;
}
}
}
}
}
}
int kernel_size = kernel_w * kernel_h;
int out_size = outw * outh;
// bottom_im2col memory packed 8 x 8
Mat bottom_tm(8 * kernel_size, inch, out_size / 8 + out_size % 8, elemsize, opt.workspace_allocator);
{
int nn_size = out_size >> 3;
int remain_size_start = nn_size << 3;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = ii * 8;
const float* img0 = bottom_im2col.channel(0);
img0 += i;
float* tmpptr = bottom_tm.channel(i / 8);
for (int q = 0; q < inch * kernel_size; q++)
{
#if __AVX__
_mm256_storeu_ps(tmpptr, _mm256_loadu_ps(img0));
#else
tmpptr[0] = img0[0];
tmpptr[1] = img0[1];
tmpptr[2] = img0[2];
tmpptr[3] = img0[3];
tmpptr[4] = img0[4];
tmpptr[5] = img0[5];
tmpptr[6] = img0[6];
tmpptr[7] = img0[7];
#endif // __SSE__
tmpptr += 8;
img0 += out_size;
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int i = remain_size_start; i < out_size; i++)
{
const float* img0 = bottom_im2col.channel(0);
img0 += i;
float* tmpptr = bottom_tm.channel(i / 8 + i % 8);
for (int q = 0; q < inch * kernel_size; q++)
{
tmpptr[0] = img0[0];
tmpptr += 1;
img0 += out_size;
}
}
}
// sgemm(int M, int N, int L, float* A, float* B, float* C)
{
//int M = outch; // outch
int N = outw * outh; // outsize or out stride
int L = kernel_w * kernel_h * inch; // ksize * inch
int nn_outch = 0;
int remain_outch_start = 0;
nn_outch = outch >> 3;
remain_outch_start = nn_outch << 3;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp = 0; pp < nn_outch; pp++)
{
int i = pp * 8;
float* output0 = top_blob.channel(i);
float* output1 = top_blob.channel(i + 1);
float* output2 = top_blob.channel(i + 2);
float* output3 = top_blob.channel(i + 3);
float* output4 = top_blob.channel(i + 4);
float* output5 = top_blob.channel(i + 5);
float* output6 = top_blob.channel(i + 6);
float* output7 = top_blob.channel(i + 7);
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 + i : zeros;
int j = 0;
for (; j + 7 < N; j = j + 8)
{
const float* vb = bottom_tm.channel(j / 8);
const float* va = kernel_tm.channel(i / 8);
#if __AVX__
__m256 _sum0 = _mm256_broadcast_ss(biasptr);
__m256 _sum1 = _mm256_broadcast_ss(biasptr + 1);
__m256 _sum2 = _mm256_broadcast_ss(biasptr + 2);
__m256 _sum3 = _mm256_broadcast_ss(biasptr + 3);
__m256 _sum4 = _mm256_broadcast_ss(biasptr + 4);
__m256 _sum5 = _mm256_broadcast_ss(biasptr + 5);
__m256 _sum6 = _mm256_broadcast_ss(biasptr + 6);
__m256 _sum7 = _mm256_broadcast_ss(biasptr + 7);
int k = 0;
for (; k + 3 < L; k = k + 4)
{
// k0
__m256 _va0 = _mm256_broadcast_ss(va);
__m256 _va1 = _mm256_broadcast_ss(va + 1);
__m256 _va2 = _mm256_broadcast_ss(va + 2);
__m256 _va3 = _mm256_broadcast_ss(va + 3);
__m256 _vb0 = _mm256_loadu_ps(vb);
__m256 _vb1 = _mm256_loadu_ps(vb + 8);
__m256 _vb2 = _mm256_loadu_ps(vb + 16);
__m256 _vb3 = _mm256_loadu_ps(vb + 24);
_sum0 = _mm256_fmadd_ps(_vb0, _va0, _sum0); // sum0 = (a00-a07) * k00
_sum1 = _mm256_fmadd_ps(_vb0, _va1, _sum1); // sum1 = (a00-a07) * k10
_sum2 = _mm256_fmadd_ps(_vb0, _va2, _sum2); // sum2 = (a00-a07) * k20
_sum3 = _mm256_fmadd_ps(_vb0, _va3, _sum3); // sum3 = (a00-a07) * k30
_va0 = _mm256_broadcast_ss(va + 4);
_va1 = _mm256_broadcast_ss(va + 5);
_va2 = _mm256_broadcast_ss(va + 6);
_va3 = _mm256_broadcast_ss(va + 7);
_sum4 = _mm256_fmadd_ps(_vb0, _va0, _sum4); // sum4 = (a00-a07) * k40
_sum5 = _mm256_fmadd_ps(_vb0, _va1, _sum5); // sum5 = (a00-a07) * k50
_sum6 = _mm256_fmadd_ps(_vb0, _va2, _sum6); // sum6 = (a00-a07) * k60
_sum7 = _mm256_fmadd_ps(_vb0, _va3, _sum7); // sum7 = (a00-a07) * k70
va += 8;
// k1
_va0 = _mm256_broadcast_ss(va);
_va1 = _mm256_broadcast_ss(va + 1);
_va2 = _mm256_broadcast_ss(va + 2);
_va3 = _mm256_broadcast_ss(va + 3);
_sum0 = _mm256_fmadd_ps(_vb1, _va0, _sum0); // sum0 += (a10-a17) * k01
_sum1 = _mm256_fmadd_ps(_vb1, _va1, _sum1); // sum1 += (a10-a17) * k11
_sum2 = _mm256_fmadd_ps(_vb1, _va2, _sum2); // sum2 += (a10-a17) * k21
_sum3 = _mm256_fmadd_ps(_vb1, _va3, _sum3); // sum3 += (a10-a17) * k31
_va0 = _mm256_broadcast_ss(va + 4);
_va1 = _mm256_broadcast_ss(va + 5);
_va2 = _mm256_broadcast_ss(va + 6);
_va3 = _mm256_broadcast_ss(va + 7);
_sum4 = _mm256_fmadd_ps(_vb1, _va0, _sum4); // sum4 += (a10-a17) * k41
_sum5 = _mm256_fmadd_ps(_vb1, _va1, _sum5); // sum5 += (a10-a17) * k51
_sum6 = _mm256_fmadd_ps(_vb1, _va2, _sum6); // sum6 += (a10-a17) * k61
_sum7 = _mm256_fmadd_ps(_vb1, _va3, _sum7); // sum7 += (a10-a17) * k71
va += 8;
// k2
_va0 = _mm256_broadcast_ss(va);
_va1 = _mm256_broadcast_ss(va + 1);
_va2 = _mm256_broadcast_ss(va + 2);
_va3 = _mm256_broadcast_ss(va + 3);
_sum0 = _mm256_fmadd_ps(_vb2, _va0, _sum0); // sum0 += (a20-a27) * k02
_sum1 = _mm256_fmadd_ps(_vb2, _va1, _sum1); // sum1 += (a20-a27) * k12
_sum2 = _mm256_fmadd_ps(_vb2, _va2, _sum2); // sum2 += (a20-a27) * k22
_sum3 = _mm256_fmadd_ps(_vb2, _va3, _sum3); // sum3 += (a20-a27) * k32
_va0 = _mm256_broadcast_ss(va + 4);
_va1 = _mm256_broadcast_ss(va + 5);
_va2 = _mm256_broadcast_ss(va + 6);
_va3 = _mm256_broadcast_ss(va + 7);
_sum4 = _mm256_fmadd_ps(_vb2, _va0, _sum4); // sum4 += (a20-a27) * k42
_sum5 = _mm256_fmadd_ps(_vb2, _va1, _sum5); // sum5 += (a20-a27) * k52
_sum6 = _mm256_fmadd_ps(_vb2, _va2, _sum6); // sum6 += (a20-a27) * k62
_sum7 = _mm256_fmadd_ps(_vb2, _va3, _sum7); // sum7 += (a20-a27) * k72
va += 8;
// k3
_va0 = _mm256_broadcast_ss(va);
_va1 = _mm256_broadcast_ss(va + 1);
_va2 = _mm256_broadcast_ss(va + 2);
_va3 = _mm256_broadcast_ss(va + 3);
_sum0 = _mm256_fmadd_ps(_vb3, _va0, _sum0); // sum0 += (a30-a37) * k03
_sum1 = _mm256_fmadd_ps(_vb3, _va1, _sum1); // sum1 += (a30-a37) * k13
_sum2 = _mm256_fmadd_ps(_vb3, _va2, _sum2); // sum2 += (a30-a37) * k23
_sum3 = _mm256_fmadd_ps(_vb3, _va3, _sum3); // sum3 += (a30-a37) * k33
_va0 = _mm256_broadcast_ss(va + 4);
_va1 = _mm256_broadcast_ss(va + 5);
_va2 = _mm256_broadcast_ss(va + 6);
_va3 = _mm256_broadcast_ss(va + 7);
_sum4 = _mm256_fmadd_ps(_vb3, _va0, _sum4); // sum4 += (a30-a37) * k43
_sum5 = _mm256_fmadd_ps(_vb3, _va1, _sum5); // sum5 += (a30-a37) * k53
_sum6 = _mm256_fmadd_ps(_vb3, _va2, _sum6); // sum6 += (a30-a37) * k63
_sum7 = _mm256_fmadd_ps(_vb3, _va3, _sum7); // sum7 += (a30-a37) * k73
va += 8;
vb += 32;
}
for (; k < L; k++)
{
// k0
__m256 _va0 = _mm256_broadcast_ss(va);
__m256 _va1 = _mm256_broadcast_ss(va + 1);
__m256 _va2 = _mm256_broadcast_ss(va + 2);
__m256 _va3 = _mm256_broadcast_ss(va + 3);
__m256 _va4 = _mm256_broadcast_ss(va + 4);
__m256 _va5 = _mm256_broadcast_ss(va + 5);
__m256 _va6 = _mm256_broadcast_ss(va + 6);
__m256 _va7 = _mm256_broadcast_ss(va + 7);
__m256 _vb0 = _mm256_loadu_ps(vb);
_sum0 = _mm256_fmadd_ps(_vb0, _va0, _sum0); // sum0 = (a00-a07) * k00
_sum1 = _mm256_fmadd_ps(_vb0, _va1, _sum1); // sum1 = (a00-a07) * k10
_sum2 = _mm256_fmadd_ps(_vb0, _va2, _sum2); // sum2 = (a00-a07) * k20
_sum3 = _mm256_fmadd_ps(_vb0, _va3, _sum3); // sum3 = (a00-a07) * k30
_sum4 = _mm256_fmadd_ps(_vb0, _va4, _sum4); // sum4 = (a00-a07) * k40
_sum5 = _mm256_fmadd_ps(_vb0, _va5, _sum5); // sum5 = (a00-a07) * k50
_sum6 = _mm256_fmadd_ps(_vb0, _va6, _sum6); // sum6 = (a00-a07) * k60
_sum7 = _mm256_fmadd_ps(_vb0, _va7, _sum7); // sum7 = (a00-a07) * k70
va += 8;
vb += 8;
}
_mm256_storeu_ps(output0, _sum0);
_mm256_storeu_ps(output1, _sum1);
_mm256_storeu_ps(output2, _sum2);
_mm256_storeu_ps(output3, _sum3);
_mm256_storeu_ps(output4, _sum4);
_mm256_storeu_ps(output5, _sum5);
_mm256_storeu_ps(output6, _sum6);
_mm256_storeu_ps(output7, _sum7);
#else
float sum0[8] = {0};
float sum1[8] = {0};
float sum2[8] = {0};
float sum3[8] = {0};
float sum4[8] = {0};
float sum5[8] = {0};
float sum6[8] = {0};
float sum7[8] = {0};
int k = 0;
for (; k + 7 < L; k = k + 8)
{
for (int n = 0; n < 8; n++)
{
sum0[n] += va[0] * vb[n];
sum1[n] += va[1] * vb[n];
sum2[n] += va[2] * vb[n];
sum3[n] += va[3] * vb[n];
sum4[n] += va[4] * vb[n];
sum5[n] += va[5] * vb[n];
sum6[n] += va[6] * vb[n];
sum7[n] += va[7] * vb[n];
va += 8;
sum0[n] += va[0] * vb[n + 8];
sum1[n] += va[1] * vb[n + 8];
sum2[n] += va[2] * vb[n + 8];
sum3[n] += va[3] * vb[n + 8];
sum4[n] += va[4] * vb[n + 8];
sum5[n] += va[5] * vb[n + 8];
sum6[n] += va[6] * vb[n + 8];
sum7[n] += va[7] * vb[n + 8];
va += 8;
sum0[n] += va[0] * vb[n + 16];
sum1[n] += va[1] * vb[n + 16];
sum2[n] += va[2] * vb[n + 16];
sum3[n] += va[3] * vb[n + 16];
sum4[n] += va[4] * vb[n + 16];
sum5[n] += va[5] * vb[n + 16];
sum6[n] += va[6] * vb[n + 16];
sum7[n] += va[7] * vb[n + 16];
va += 8;
sum0[n] += va[0] * vb[n + 24];
sum1[n] += va[1] * vb[n + 24];
sum2[n] += va[2] * vb[n + 24];
sum3[n] += va[3] * vb[n + 24];
sum4[n] += va[4] * vb[n + 24];
sum5[n] += va[5] * vb[n + 24];
sum6[n] += va[6] * vb[n + 24];
sum7[n] += va[7] * vb[n + 24];
va += 8;
sum0[n] += va[0] * vb[n + 32];
sum1[n] += va[1] * vb[n + 32];
sum2[n] += va[2] * vb[n + 32];
sum3[n] += va[3] * vb[n + 32];
sum4[n] += va[4] * vb[n + 32];
sum5[n] += va[5] * vb[n + 32];
sum6[n] += va[6] * vb[n + 32];
sum7[n] += va[7] * vb[n + 32];
va += 8;
sum0[n] += va[0] * vb[n + 40];
sum1[n] += va[1] * vb[n + 40];
sum2[n] += va[2] * vb[n + 40];
sum3[n] += va[3] * vb[n + 40];
sum4[n] += va[4] * vb[n + 40];
sum5[n] += va[5] * vb[n + 40];
sum6[n] += va[6] * vb[n + 40];
sum7[n] += va[7] * vb[n + 40];
va += 8;
sum0[n] += va[0] * vb[n + 48];
sum1[n] += va[1] * vb[n + 48];
sum2[n] += va[2] * vb[n + 48];
sum3[n] += va[3] * vb[n + 48];
sum4[n] += va[4] * vb[n + 48];
sum5[n] += va[5] * vb[n + 48];
sum6[n] += va[6] * vb[n + 48];
sum7[n] += va[7] * vb[n + 48];
va += 8;
sum0[n] += va[0] * vb[n + 56];
sum1[n] += va[1] * vb[n + 56];
sum2[n] += va[2] * vb[n + 56];
sum3[n] += va[3] * vb[n + 56];
sum4[n] += va[4] * vb[n + 56];
sum5[n] += va[5] * vb[n + 56];
sum6[n] += va[6] * vb[n + 56];
sum7[n] += va[7] * vb[n + 56];
va -= 56;
}
va += 64;
vb += 64;
}
for (; k < L; k++)
{
for (int n = 0; n < 8; n++)
{
sum0[n] += va[0] * vb[n];
sum1[n] += va[1] * vb[n];
sum2[n] += va[2] * vb[n];
sum3[n] += va[3] * vb[n];
sum4[n] += va[4] * vb[n];
sum5[n] += va[5] * vb[n];
sum6[n] += va[6] * vb[n];
sum7[n] += va[7] * vb[n];
}
va += 8;
vb += 8;
}
for (int n = 0; n < 8; n++)
{
output0[n] = sum0[n] + biasptr[0];
output1[n] = sum1[n] + biasptr[1];
output2[n] = sum2[n] + biasptr[2];
output3[n] = sum3[n] + biasptr[3];
output4[n] = sum4[n] + biasptr[4];
output5[n] = sum5[n] + biasptr[5];
output6[n] = sum6[n] + biasptr[6];
output7[n] = sum7[n] + biasptr[7];
}
#endif // __AVX__
output0 += 8;
output1 += 8;
output2 += 8;
output3 += 8;
output4 += 8;
output5 += 8;
output6 += 8;
output7 += 8;
}
for (; j < N; j++)
{
const float* vb = bottom_tm.channel(j / 8 + j % 8);
const float* va = kernel_tm.channel(i / 8);
#if __AVX__
__m256 _sum0_7 = _mm256_loadu_ps(biasptr);
__m256 _sum0 = _mm256_set1_ps(0.0);
__m256 _sum1 = _mm256_set1_ps(0.0);
__m256 _sum2 = _mm256_set1_ps(0.0);
__m256 _sum3 = _mm256_set1_ps(0.0);
int k = 0;
for (; k + 3 < L; k = k + 4)
{
__m256 _vb0 = _mm256_broadcast_ss(vb);
__m256 _vb1 = _mm256_broadcast_ss(vb + 1);
__m256 _vb2 = _mm256_broadcast_ss(vb + 2);
__m256 _vb3 = _mm256_broadcast_ss(vb + 3);
__m256 _va0 = _mm256_loadu_ps(va);
__m256 _va1 = _mm256_loadu_ps(va + 8);
__m256 _va2 = _mm256_loadu_ps(va + 16);
__m256 _va3 = _mm256_loadu_ps(va + 24);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0); // sum0 += (k00-k70) * a00
_sum1 = _mm256_fmadd_ps(_va1, _vb1, _sum1); // sum1 += (k01-k71) * a10
_sum2 = _mm256_fmadd_ps(_va2, _vb2, _sum2); // sum2 += (k02-k72) * a20
_sum3 = _mm256_fmadd_ps(_va3, _vb3, _sum3); // sum3 += (k03-k73) * a30
va += 32;
vb += 4;
}
_sum0 = _mm256_add_ps(_sum0, _sum1);
_sum2 = _mm256_add_ps(_sum2, _sum3);
_sum0_7 = _mm256_add_ps(_sum0_7, _sum0);
_sum0_7 = _mm256_add_ps(_sum0_7, _sum2);
for (; k < L; k++)
{
__m256 _vb0 = _mm256_broadcast_ss(vb);
__m256 _va = _mm256_loadu_ps(va);
_sum0_7 = _mm256_fmadd_ps(_va, _vb0, _sum0_7); // sum0 += (k00-k70) * a00
va += 8;
vb += 1;
}
float output_sum0_7[8] = {0.f};
_mm256_storeu_ps(output_sum0_7, _sum0_7);
output0[0] = output_sum0_7[0];
output1[0] = output_sum0_7[1];
output2[0] = output_sum0_7[2];
output3[0] = output_sum0_7[3];
output4[0] = output_sum0_7[4];
output5[0] = output_sum0_7[5];
output6[0] = output_sum0_7[6];
output7[0] = output_sum0_7[7];
#else
float sum0 = biasptr[0];
float sum1 = biasptr[1];
float sum2 = biasptr[2];
float sum3 = biasptr[3];
float sum4 = biasptr[4];
float sum5 = biasptr[5];
float sum6 = biasptr[6];
float sum7 = biasptr[7];
for (int k = 0; k < L; k++)
{
sum0 += va[0] * vb[0];
sum1 += va[1] * vb[0];
sum2 += va[2] * vb[0];
sum3 += va[3] * vb[0];
sum4 += va[4] * vb[0];
sum5 += va[5] * vb[0];
sum6 += va[6] * vb[0];
sum7 += va[7] * vb[0];
va += 8;
vb += 1;
}
output0[0] = sum0;
output1[0] = sum1;
output2[0] = sum2;
output3[0] = sum3;
output4[0] = sum4;
output5[0] = sum5;
output6[0] = sum6;
output7[0] = sum7;
#endif // __AVX__
output0++;
output1++;
output2++;
output3++;
output4++;
output5++;
output6++;
output7++;
}
}
nn_outch = (outch - remain_outch_start) >> 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp = 0; pp < nn_outch; pp++)
{
int i = remain_outch_start + pp * 4;
float* output0 = top_blob.channel(i);
float* output1 = top_blob.channel(i + 1);
float* output2 = top_blob.channel(i + 2);
float* output3 = top_blob.channel(i + 3);
const float zeros[4] = {0.f, 0.f, 0.f, 0.f};
const float* biasptr = bias ? bias + i : zeros;
int j = 0;
for (; j + 7 < N; j = j + 8)
{
const float* vb = bottom_tm.channel(j / 8);
const float* va = kernel_tm.channel(i / 8 + (i % 8) / 4);
#if __AVX__
__m256 _sum0 = _mm256_broadcast_ss(biasptr);
__m256 _sum1 = _mm256_broadcast_ss(biasptr + 1);
__m256 _sum2 = _mm256_broadcast_ss(biasptr + 2);
__m256 _sum3 = _mm256_broadcast_ss(biasptr + 3);
int k = 0;
for (; k + 3 < L; k = k + 4)
{
// k0
__m256 _va0 = _mm256_broadcast_ss(va);
__m256 _va1 = _mm256_broadcast_ss(va + 1);
__m256 _va2 = _mm256_broadcast_ss(va + 2);
__m256 _va3 = _mm256_broadcast_ss(va + 3);
__m256 _vb0 = _mm256_loadu_ps(vb);
__m256 _vb1 = _mm256_loadu_ps(vb + 8);
__m256 _vb2 = _mm256_loadu_ps(vb + 16);
__m256 _vb3 = _mm256_loadu_ps(vb + 24);
_sum0 = _mm256_fmadd_ps(_vb0, _va0, _sum0); // sum0 = (a00-a07) * k00
_sum1 = _mm256_fmadd_ps(_vb0, _va1, _sum1); // sum1 = (a00-a07) * k10
_sum2 = _mm256_fmadd_ps(_vb0, _va2, _sum2); // sum2 = (a00-a07) * k20
_sum3 = _mm256_fmadd_ps(_vb0, _va3, _sum3); // sum3 = (a00-a07) * k30
va += 4;
// k1
_va0 = _mm256_broadcast_ss(va);
_va1 = _mm256_broadcast_ss(va + 1);
_va2 = _mm256_broadcast_ss(va + 2);
_va3 = _mm256_broadcast_ss(va + 3);
_sum0 = _mm256_fmadd_ps(_vb1, _va0, _sum0); // sum0 += (a10-a17) * k01
_sum1 = _mm256_fmadd_ps(_vb1, _va1, _sum1); // sum1 += (a10-a17) * k11
_sum2 = _mm256_fmadd_ps(_vb1, _va2, _sum2); // sum2 += (a10-a17) * k21
_sum3 = _mm256_fmadd_ps(_vb1, _va3, _sum3); // sum3 += (a10-a17) * k31
va += 4;
// k2
_va0 = _mm256_broadcast_ss(va);
_va1 = _mm256_broadcast_ss(va + 1);
_va2 = _mm256_broadcast_ss(va + 2);
_va3 = _mm256_broadcast_ss(va + 3);
_sum0 = _mm256_fmadd_ps(_vb2, _va0, _sum0); // sum0 += (a20-a27) * k02
_sum1 = _mm256_fmadd_ps(_vb2, _va1, _sum1); // sum1 += (a20-a27) * k12
_sum2 = _mm256_fmadd_ps(_vb2, _va2, _sum2); // sum2 += (a20-a27) * k22
_sum3 = _mm256_fmadd_ps(_vb2, _va3, _sum3); // sum3 += (a20-a27) * k32
va += 4;
// k3
_va0 = _mm256_broadcast_ss(va);
_va1 = _mm256_broadcast_ss(va + 1);
_va2 = _mm256_broadcast_ss(va + 2);
_va3 = _mm256_broadcast_ss(va + 3);
_sum0 = _mm256_fmadd_ps(_vb3, _va0, _sum0); // sum0 += (a30-a37) * k03
_sum1 = _mm256_fmadd_ps(_vb3, _va1, _sum1); // sum1 += (a30-a37) * k13
_sum2 = _mm256_fmadd_ps(_vb3, _va2, _sum2); // sum2 += (a30-a37) * k23
_sum3 = _mm256_fmadd_ps(_vb3, _va3, _sum3); // sum3 += (a30-a37) * k33
va += 4;
vb += 32;
}
for (; k < L; k++)
{
// k0
__m256 _va0 = _mm256_broadcast_ss(va);
__m256 _va1 = _mm256_broadcast_ss(va + 1);
__m256 _va2 = _mm256_broadcast_ss(va + 2);
__m256 _va3 = _mm256_broadcast_ss(va + 3);
__m256 _vb0 = _mm256_loadu_ps(vb);
_sum0 = _mm256_fmadd_ps(_vb0, _va0, _sum0); // sum0 = (a00-a07) * k00
_sum1 = _mm256_fmadd_ps(_vb0, _va1, _sum1); // sum1 = (a00-a07) * k10
_sum2 = _mm256_fmadd_ps(_vb0, _va2, _sum2); // sum2 = (a00-a07) * k20
_sum3 = _mm256_fmadd_ps(_vb0, _va3, _sum3); // sum3 = (a00-a07) * k30
va += 4;
vb += 8;
}
_mm256_storeu_ps(output0, _sum0);
_mm256_storeu_ps(output1, _sum1);
_mm256_storeu_ps(output2, _sum2);
_mm256_storeu_ps(output3, _sum3);
#else
float sum0[8] = {0};
float sum1[8] = {0};
float sum2[8] = {0};
float sum3[8] = {0};
int k = 0;
for (; k + 7 < L; k = k + 8)
{
for (int n = 0; n < 8; n++)
{
sum0[n] += va[0] * vb[n];
sum1[n] += va[1] * vb[n];
sum2[n] += va[2] * vb[n];
sum3[n] += va[3] * vb[n];
va += 4;
sum0[n] += va[0] * vb[n + 8];
sum1[n] += va[1] * vb[n + 8];
sum2[n] += va[2] * vb[n + 8];
sum3[n] += va[3] * vb[n + 8];
va += 4;
sum0[n] += va[0] * vb[n + 16];
sum1[n] += va[1] * vb[n + 16];
sum2[n] += va[2] * vb[n + 16];
sum3[n] += va[3] * vb[n + 16];
va += 4;
sum0[n] += va[0] * vb[n + 24];
sum1[n] += va[1] * vb[n + 24];
sum2[n] += va[2] * vb[n + 24];
sum3[n] += va[3] * vb[n + 24];
va += 4;
sum0[n] += va[0] * vb[n + 32];
sum1[n] += va[1] * vb[n + 32];
sum2[n] += va[2] * vb[n + 32];
sum3[n] += va[3] * vb[n + 32];
va += 4;
sum0[n] += va[0] * vb[n + 40];
sum1[n] += va[1] * vb[n + 40];
sum2[n] += va[2] * vb[n + 40];
sum3[n] += va[3] * vb[n + 40];
va += 4;
sum0[n] += va[0] * vb[n + 48];
sum1[n] += va[1] * vb[n + 48];
sum2[n] += va[2] * vb[n + 48];
sum3[n] += va[3] * vb[n + 48];
va += 4;
sum0[n] += va[0] * vb[n + 56];
sum1[n] += va[1] * vb[n + 56];
sum2[n] += va[2] * vb[n + 56];
sum3[n] += va[3] * vb[n + 56];
va -= 28;
}
va += 32;
vb += 64;
}
for (; k < L; k++)
{
for (int n = 0; n < 8; n++)
{
sum0[n] += va[0] * vb[n];
sum1[n] += va[1] * vb[n];
sum2[n] += va[2] * vb[n];
sum3[n] += va[3] * vb[n];
}
va += 4;
vb += 8;
}
for (int n = 0; n < 8; n++)
{
output0[n] = sum0[n] + biasptr[0];
output1[n] = sum1[n] + biasptr[1];
output2[n] = sum2[n] + biasptr[2];
output3[n] = sum3[n] + biasptr[3];
}
#endif // __AVX__
output0 += 8;
output1 += 8;
output2 += 8;
output3 += 8;
}
for (; j < N; j++)
{
const float* vb = bottom_tm.channel(j / 8 + j % 8);
const float* va = kernel_tm.channel(i / 8 + (i % 8) / 4);
#if __AVX__
__m128 _sum0_3 = _mm_loadu_ps(biasptr);
__m128 _sum0 = _mm_set1_ps(0.0);
__m128 _sum1 = _mm_set1_ps(0.0);
__m128 _sum2 = _mm_set1_ps(0.0);
__m128 _sum3 = _mm_set1_ps(0.0);
int k = 0;
for (; k + 3 < L; k = k + 4)
{
__m128 _vb0 = _mm_set1_ps(vb[0]);
__m128 _vb1 = _mm_set1_ps(vb[1]);
__m128 _vb2 = _mm_set1_ps(vb[2]);
__m128 _vb3 = _mm_set1_ps(vb[3]);
__m128 _va0 = _mm_loadu_ps(va);
__m128 _va1 = _mm_loadu_ps(va + 4);
__m128 _va2 = _mm_loadu_ps(va + 8);
__m128 _va3 = _mm_loadu_ps(va + 12);
_sum0 = _mm_fmadd_ps(_va0, _vb0, _sum0); // sum0 += (k00-k30) * a00
_sum1 = _mm_fmadd_ps(_va1, _vb1, _sum1); // sum1 += (k01-k31) * a10
_sum2 = _mm_fmadd_ps(_va2, _vb2, _sum2); // sum2 += (k02-k32) * a20
_sum3 = _mm_fmadd_ps(_va3, _vb3, _sum3); // sum3 += (k03-k33) * a30
va += 16;
vb += 4;
}
_sum0 = _mm_add_ps(_sum0, _sum1);
_sum2 = _mm_add_ps(_sum2, _sum3);
_sum0_3 = _mm_add_ps(_sum0_3, _sum0);
_sum0_3 = _mm_add_ps(_sum0_3, _sum2);
for (; k < L; k++)
{
__m128 _vb0 = _mm_set1_ps(vb[0]);
__m128 _va = _mm_loadu_ps(va);
_sum0_3 = _mm_fmadd_ps(_va, _vb0, _sum0_3); // sum0 += (k00-k30) * a00
va += 4;
vb += 1;
}
float output_sum0_3[4] = {0.f};
_mm_storeu_ps(output_sum0_3, _sum0_3);
output0[0] = output_sum0_3[0];
output1[0] = output_sum0_3[1];
output2[0] = output_sum0_3[2];
output3[0] = output_sum0_3[3];
#else
float sum0 = biasptr[0];
float sum1 = biasptr[1];
float sum2 = biasptr[2];
float sum3 = biasptr[3];
for (int k = 0; k < L; k++)
{
sum0 += va[0] * vb[0];
sum1 += va[1] * vb[0];
sum2 += va[2] * vb[0];
sum3 += va[3] * vb[0];
va += 4;
vb += 1;
}
output0[0] = sum0;
output1[0] = sum1;
output2[0] = sum2;
output3[0] = sum3;
#endif // __AVX__
output0++;
output1++;
output2++;
output3++;
}
}
remain_outch_start += nn_outch << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int i = remain_outch_start; i < outch; i++)
{
float* output = top_blob.channel(i);
const float bias0 = bias ? bias[i] : 0.f;
int j = 0;
for (; j + 7 < N; j = j + 8)
{
const float* vb = bottom_tm.channel(j / 8);
const float* va = kernel_tm.channel(i / 8 + (i % 8) / 4 + i % 4);
#if __AVX__
__m256 _sum0 = _mm256_broadcast_ss(&bias0);
int k = 0;
for (; k + 3 < L; k = k + 4)
{
// k0
__m256 _va0 = _mm256_broadcast_ss(va);
__m256 _va1 = _mm256_broadcast_ss(va + 1);
__m256 _va2 = _mm256_broadcast_ss(va + 2);
__m256 _va3 = _mm256_broadcast_ss(va + 3);
__m256 _vb0 = _mm256_loadu_ps(vb);
__m256 _vb1 = _mm256_loadu_ps(vb + 8);
__m256 _vb2 = _mm256_loadu_ps(vb + 16);
__m256 _vb3 = _mm256_loadu_ps(vb + 24);
_sum0 = _mm256_fmadd_ps(_vb0, _va0, _sum0); // sum0 = (a00-a07) * k00
_sum0 = _mm256_fmadd_ps(_vb1, _va1, _sum0); // sum0 += (a10-a17) * k01
_sum0 = _mm256_fmadd_ps(_vb2, _va2, _sum0); // sum0 += (a20-a27) * k02
_sum0 = _mm256_fmadd_ps(_vb3, _va3, _sum0); // sum0 += (a30-a37) * k03
va += 4;
vb += 32;
}
for (; k < L; k++)
{
// k0
__m256 _va0 = _mm256_broadcast_ss(va);
__m256 _vb0 = _mm256_loadu_ps(vb);
_sum0 = _mm256_fmadd_ps(_vb0, _va0, _sum0); // sum0 = (a00-a07) * k00
va += 1;
vb += 8;
}
_mm256_storeu_ps(output, _sum0);
#else
float sum[8] = {0};
int k = 0;
for (; k + 7 < L; k = k + 8)
{
for (int n = 0; n < 8; n++)
{
sum[n] += va[0] * vb[n];
sum[n] += va[1] * vb[n + 8];
sum[n] += va[2] * vb[n + 16];
sum[n] += va[3] * vb[n + 24];
sum[n] += va[4] * vb[n + 32];
sum[n] += va[5] * vb[n + 40];
sum[n] += va[6] * vb[n + 48];
sum[n] += va[7] * vb[n + 56];
}
va += 8;
vb += 64;
}
for (; k < L; k++)
{
for (int n = 0; n < 8; n++)
{
sum[n] += va[0] * vb[n];
}
va += 1;
vb += 8;
}
for (int n = 0; n < 8; n++)
{
output[n] = sum[n] + bias0;
}
#endif // __AVX__
output += 8;
}
for (; j < N; j++)
{
const float* vb = bottom_tm.channel(j / 8 + j % 8);
const float* va = kernel_tm.channel(i / 8 + (i % 8) / 4 + i % 4);
int k = 0;
#if __AVX__
__m128 _sum0 = _mm_set1_ps(0.f);
for (; k + 3 < L; k += 4)
{
__m128 _p0 = _mm_loadu_ps(vb);
vb += 4;
__m128 _k0 = _mm_loadu_ps(va);
va += 4;
_sum0 = _mm_fmadd_ps(_p0, _k0, _sum0);
}
float output_sum0[4] = {0.f};
_mm_storeu_ps(output_sum0, _sum0);
float sum0 = bias0 + output_sum0[0] + output_sum0[1] + output_sum0[2] + output_sum0[3];
#else
float sum0 = bias0;
#endif // __AVX__
for (; k < L; k++)
{
sum0 += va[0] * vb[0];
va += 1;
vb += 1;
}
output[0] = sum0;
output++;
}
}
}
}
#else
static void conv_im2col_sgemm_transform_kernel_sse(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_size)
{
const float* kernel = _kernel;
// kernel memory packed 4 x 4
kernel_tm.create(4 * kernel_size, inch, outch / 4 + outch % 4);
int nn_outch = 0;
int remain_outch_start = 0;
nn_outch = outch >> 2;
remain_outch_start = nn_outch << 2;
for (int pp = 0; pp < nn_outch; pp++)
{
int p = pp * 4;
const float* k0 = kernel + (p + 0) * inch * kernel_size;
const float* k1 = kernel + (p + 1) * inch * kernel_size;
const float* k2 = kernel + (p + 2) * inch * kernel_size;
const float* k3 = kernel + (p + 3) * inch * kernel_size;
float* ktmp = kernel_tm.channel(p / 4);
for (int q = 0; q < inch * kernel_size; q++)
{
ktmp[0] = k0[0];
ktmp[1] = k1[0];
ktmp[2] = k2[0];
ktmp[3] = k3[0];
ktmp += 4;
k0 += 1;
k1 += 1;
k2 += 1;
k3 += 1;
}
}
for (int p = remain_outch_start; p < outch; p++)
{
const float* k0 = kernel + (p + 0) * inch * kernel_size;
float* ktmp = kernel_tm.channel(p / 4 + p % 4);
for (int q = 0; q < inch * kernel_size; q++)
{
ktmp[0] = k0[0];
ktmp++;
k0++;
}
}
}
static void conv_im2col_sgemm_sse(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias,
const int kernel_w, const int kernel_h, const int stride_w, const int stride_h, const Option& opt)
{
int w = bottom_blob.w;
int inch = bottom_blob.c;
size_t elemsize = bottom_blob.elemsize;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const float* bias = _bias;
// im2col
Mat bottom_im2col(outw * outh, kernel_h * kernel_w * inch, elemsize, opt.workspace_allocator);
{
const int stride = kernel_h * kernel_w * outw * outh;
float* ret = (float*)bottom_im2col;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < inch; p++)
{
const float* input = bottom_blob.channel(p);
int retID = stride * p;
for (int u = 0; u < kernel_h; u++)
{
for (int v = 0; v < kernel_w; v++)
{
for (int i = 0; i < outh; i++)
{
for (int j = 0; j < outw; j++)
{
int row = u + i * stride_h;
int col = v + j * stride_w;
int index = row * w + col;
ret[retID] = input[index];
retID++;
}
}
}
}
}
}
int kernel_size = kernel_w * kernel_h;
int out_size = outw * outh;
// bottom_im2col memory packed 4 x 4
Mat bottom_tm(4 * kernel_size, inch, out_size / 4 + out_size % 4, elemsize, opt.workspace_allocator);
{
int nn_size = out_size >> 2;
int remain_size_start = nn_size << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = ii * 4;
const float* img0 = bottom_im2col.channel(0);
img0 += i;
float* tmpptr = bottom_tm.channel(i / 4);
for (int q = 0; q < inch * kernel_size; q++)
{
#if __SSE__
_mm_storeu_ps(tmpptr, _mm_loadu_ps(img0));
#else
tmpptr[0] = img0[0];
tmpptr[1] = img0[1];
tmpptr[2] = img0[2];
tmpptr[3] = img0[3];
#endif // __SSE__
tmpptr += 4;
img0 += out_size;
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int i = remain_size_start; i < out_size; i++)
{
const float* img0 = bottom_im2col.channel(0);
img0 += i;
float* tmpptr = bottom_tm.channel(i / 4 + i % 4);
for (int q = 0; q < inch * kernel_size; q++)
{
tmpptr[0] = img0[0];
tmpptr += 1;
img0 += out_size;
}
}
}
// sgemm(int M, int N, int L, float* A, float* B, float* C)
{
//int M = outch; // outch
int N = outw * outh; // outsize or out stride
int L = kernel_w * kernel_h * inch; // ksize * inch
int nn_outch = 0;
int remain_outch_start = 0;
nn_outch = outch >> 2;
remain_outch_start = nn_outch << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp = 0; pp < nn_outch; pp++)
{
int i = pp * 4;
float* output0 = top_blob.channel(i);
float* output1 = top_blob.channel(i + 1);
float* output2 = top_blob.channel(i + 2);
float* output3 = top_blob.channel(i + 3);
const float zeros[4] = {0.f, 0.f, 0.f, 0.f};
const float* biasptr = bias ? bias + i : zeros;
int j = 0;
for (; j + 3 < N; j = j + 4)
{
const float* vb = bottom_tm.channel(j / 4);
const float* va = kernel_tm.channel(i / 4);
#if __SSE__
__m128 _sum0 = _mm_set1_ps(biasptr[0]);
__m128 _sum1 = _mm_set1_ps(biasptr[1]);
__m128 _sum2 = _mm_set1_ps(biasptr[2]);
__m128 _sum3 = _mm_set1_ps(biasptr[3]);
int k = 0;
for (; k + 3 < L; k = k + 4)
{
// k0
__m128 _vb = _mm_loadu_ps(vb);
__m128 _va0 = _mm_set1_ps(va[0]);
__m128 _va1 = _mm_set1_ps(va[1]);
__m128 _va2 = _mm_set1_ps(va[2]);
__m128 _va3 = _mm_set1_ps(va[3]);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb, _va0)); // sum0 = (a00-a03) * k00
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_vb, _va1)); // sum1 = (a00-a03) * k10
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_vb, _va2)); // sum2 = (a00-a03) * k20
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_vb, _va3)); // sum3 = (a00-a03) * k30
// k1
_vb = _mm_loadu_ps(vb + 4);
_va0 = _mm_set1_ps(va[4]);
_va1 = _mm_set1_ps(va[5]);
_va2 = _mm_set1_ps(va[6]);
_va3 = _mm_set1_ps(va[7]);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb, _va0)); // sum0 = (a10-a13) * k01
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_vb, _va1)); // sum1 = (a10-a13) * k11
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_vb, _va2)); // sum2 = (a10-a13) * k21
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_vb, _va3)); // sum3 = (a10-a13) * k31
// k2
_vb = _mm_loadu_ps(vb + 8);
_va0 = _mm_set1_ps(va[8]);
_va1 = _mm_set1_ps(va[9]);
_va2 = _mm_set1_ps(va[10]);
_va3 = _mm_set1_ps(va[11]);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb, _va0)); // sum0 = (a20-a23) * k02
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_vb, _va1)); // sum1 = (a20-a23) * k12
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_vb, _va2)); // sum2 = (a20-a23) * k22
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_vb, _va3)); // sum3 = (a20-a23) * k32
// k3
_vb = _mm_loadu_ps(vb + 12);
_va0 = _mm_set1_ps(va[12]);
_va1 = _mm_set1_ps(va[13]);
_va2 = _mm_set1_ps(va[14]);
_va3 = _mm_set1_ps(va[15]);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb, _va0)); // sum0 = (a30-a33) * k03
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_vb, _va1)); // sum1 = (a30-a33) * k13
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_vb, _va2)); // sum2 = (a30-a33) * k23
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_vb, _va3)); // sum3 = (a30-a33) * k33
va += 16;
vb += 16;
}
for (; k < L; k++)
{
// k0
__m128 _vb = _mm_loadu_ps(vb);
__m128 _va0 = _mm_set1_ps(va[0]);
__m128 _va1 = _mm_set1_ps(va[1]);
__m128 _va2 = _mm_set1_ps(va[2]);
__m128 _va3 = _mm_set1_ps(va[3]);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb, _va0)); // sum0 = (a00-a03) * k00
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_vb, _va1)); // sum1 = (a00-a03) * k10
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_vb, _va2)); // sum2 = (a00-a03) * k20
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_vb, _va3)); // sum3 = (a00-a03) * k30
va += 4;
vb += 4;
}
_mm_storeu_ps(output0, _sum0);
_mm_storeu_ps(output1, _sum1);
_mm_storeu_ps(output2, _sum2);
_mm_storeu_ps(output3, _sum3);
#else
float sum0[4] = {0};
float sum1[4] = {0};
float sum2[4] = {0};
float sum3[4] = {0};
int k = 0;
for (; k + 7 < L; k = k + 8)
{
for (int n = 0; n < 4; n++)
{
sum0[n] += va[0] * vb[n];
sum1[n] += va[1] * vb[n];
sum2[n] += va[2] * vb[n];
sum3[n] += va[3] * vb[n];
va += 4;
sum0[n] += va[0] * vb[n + 4];
sum1[n] += va[1] * vb[n + 4];
sum2[n] += va[2] * vb[n + 4];
sum3[n] += va[3] * vb[n + 4];
va += 4;
sum0[n] += va[0] * vb[n + 8];
sum1[n] += va[1] * vb[n + 8];
sum2[n] += va[2] * vb[n + 8];
sum3[n] += va[3] * vb[n + 8];
va += 4;
sum0[n] += va[0] * vb[n + 12];
sum1[n] += va[1] * vb[n + 12];
sum2[n] += va[2] * vb[n + 12];
sum3[n] += va[3] * vb[n + 12];
va += 4;
sum0[n] += va[0] * vb[n + 16];
sum1[n] += va[1] * vb[n + 16];
sum2[n] += va[2] * vb[n + 16];
sum3[n] += va[3] * vb[n + 16];
va += 4;
sum0[n] += va[0] * vb[n + 20];
sum1[n] += va[1] * vb[n + 20];
sum2[n] += va[2] * vb[n + 20];
sum3[n] += va[3] * vb[n + 20];
va += 4;
sum0[n] += va[0] * vb[n + 24];
sum1[n] += va[1] * vb[n + 24];
sum2[n] += va[2] * vb[n + 24];
sum3[n] += va[3] * vb[n + 24];
va += 4;
sum0[n] += va[0] * vb[n + 28];
sum1[n] += va[1] * vb[n + 28];
sum2[n] += va[2] * vb[n + 28];
sum3[n] += va[3] * vb[n + 28];
va -= 28;
}
va += 32;
vb += 32;
}
for (; k < L; k++)
{
for (int n = 0; n < 4; n++)
{
sum0[n] += va[0] * vb[n];
sum1[n] += va[1] * vb[n];
sum2[n] += va[2] * vb[n];
sum3[n] += va[3] * vb[n];
}
va += 4;
vb += 4;
}
for (int n = 0; n < 4; n++)
{
output0[n] = sum0[n] + biasptr[0];
output1[n] = sum1[n] + biasptr[1];
output2[n] = sum2[n] + biasptr[2];
output3[n] = sum3[n] + biasptr[3];
}
#endif // __SSE__
output0 += 4;
output1 += 4;
output2 += 4;
output3 += 4;
}
for (; j < N; j++)
{
const float* vb = bottom_tm.channel(j / 4 + j % 4);
const float* va = kernel_tm.channel(i / 4);
#if __SSE__
__m128 _sum0_3 = _mm_loadu_ps(biasptr);
__m128 _sum0 = _mm_set1_ps(0.0);
__m128 _sum1 = _mm_set1_ps(0.0);
__m128 _sum2 = _mm_set1_ps(0.0);
__m128 _sum3 = _mm_set1_ps(0.0);
int k = 0;
for (; k + 3 < L; k = k + 4)
{
__m128 _vb0 = _mm_set1_ps(vb[0]);
__m128 _vb1 = _mm_set1_ps(vb[1]);
__m128 _vb2 = _mm_set1_ps(vb[2]);
__m128 _vb3 = _mm_set1_ps(vb[3]);
__m128 _va0 = _mm_loadu_ps(va);
__m128 _va1 = _mm_loadu_ps(va + 4);
__m128 _va2 = _mm_loadu_ps(va + 8);
__m128 _va3 = _mm_loadu_ps(va + 12);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va0, _vb0)); // sum0 += (k00-k30) * a00
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va1, _vb1)); // sum1 += (k01-k31) * a10
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va2, _vb2)); // sum2 += (k02-k32) * a20
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va3, _vb3)); // sum3 += (k03-k33) * a30
va += 16;
vb += 4;
}
_sum0 = _mm_add_ps(_sum0, _sum1);
_sum2 = _mm_add_ps(_sum2, _sum3);
_sum0_3 = _mm_add_ps(_sum0_3, _sum0);
_sum0_3 = _mm_add_ps(_sum0_3, _sum2);
for (; k < L; k++)
{
__m128 _vb0 = _mm_set1_ps(vb[0]);
__m128 _va = _mm_loadu_ps(va);
_sum0_3 = _mm_add_ps(_sum0_3, _mm_mul_ps(_va, _vb0)); // sum0 += (k00-k30) * a00
va += 4;
vb += 1;
}
float sum0_3_tmp[4];
_mm_storeu_ps(sum0_3_tmp, _sum0_3);
output0[0] = sum0_3_tmp[0];
output1[0] = sum0_3_tmp[1];
output2[0] = sum0_3_tmp[2];
output3[0] = sum0_3_tmp[3];
#else
float sum0 = biasptr[0];
float sum1 = biasptr[1];
float sum2 = biasptr[2];
float sum3 = biasptr[3];
for (int k = 0; k < L; k++)
{
sum0 += va[0] * vb[0];
sum1 += va[1] * vb[0];
sum2 += va[2] * vb[0];
sum3 += va[3] * vb[0];
va += 4;
vb += 1;
}
output0[0] = sum0;
output1[0] = sum1;
output2[0] = sum2;
output3[0] = sum3;
#endif // __SSE__
output0++;
output1++;
output2++;
output3++;
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int i = remain_outch_start; i < outch; i++)
{
float* output = top_blob.channel(i);
const float bias0 = bias ? bias[i] : 0.f;
int j = 0;
for (; j + 3 < N; j = j + 4)
{
const float* vb = bottom_tm.channel(j / 4);
const float* va = kernel_tm.channel(i / 4 + i % 4);
#if __SSE__
__m128 _sum0 = _mm_set1_ps(bias0);
int k = 0;
for (; k + 3 < L; k = k + 4)
{
// k0
__m128 _va0 = _mm_set1_ps(va[0]);
__m128 _va1 = _mm_set1_ps(va[1]);
__m128 _va2 = _mm_set1_ps(va[2]);
__m128 _va3 = _mm_set1_ps(va[3]);
__m128 _vb0 = _mm_loadu_ps(vb);
__m128 _vb1 = _mm_loadu_ps(vb + 4);
__m128 _vb2 = _mm_loadu_ps(vb + 8);
__m128 _vb3 = _mm_loadu_ps(vb + 12);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb0, _va0)); // sum0 = (a00-a03) * k00
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb1, _va1)); // sum0 += (a10-a13) * k01
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb2, _va2)); // sum0 += (a20-a23) * k02
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb3, _va3)); // sum0 += (a30-a33) * k03
va += 4;
vb += 16;
}
for (; k < L; k++)
{
// k0
__m128 _va0 = _mm_set1_ps(va[0]);
__m128 _vb0 = _mm_loadu_ps(vb);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb0, _va0)); // sum0 = (a00-a03) * k00
va += 1;
vb += 4;
}
_mm_storeu_ps(output, _sum0);
#else
float sum[4] = {0};
int k = 0;
for (; k + 3 < L; k = k + 4)
{
for (int n = 0; n < 4; n++)
{
sum[n] += va[0] * vb[n];
sum[n] += va[1] * vb[n + 4];
sum[n] += va[2] * vb[n + 8];
sum[n] += va[3] * vb[n + 12];
//sum[n] += va[4] * vb[n+16];
//sum[n] += va[5] * vb[n+20];
//sum[n] += va[6] * vb[n+24];
//sum[n] += va[7] * vb[n+28];
}
va += 4;
vb += 16;
}
for (; k < L; k++)
{
for (int n = 0; n < 4; n++)
{
sum[n] += va[0] * vb[n];
}
va += 1;
vb += 4;
}
for (int n = 0; n < 4; n++)
{
output[n] = sum[n] + bias0;
}
#endif // __SSE__
output += 4;
}
for (; j < N; j++)
{
const float* vb = bottom_tm.channel(j / 4 + j % 4);
const float* va = kernel_tm.channel(i / 4 + i % 4);
int k = 0;
#if __SSE__
__m128 _sum0 = _mm_set1_ps(0.f);
for (; k + 3 < L; k += 4)
{
__m128 _p0 = _mm_loadu_ps(vb);
__m128 _k0 = _mm_loadu_ps(va);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_p0, _k0));
va += 4;
vb += 4;
}
float sum0_tmp[4];
_mm_storeu_ps(sum0_tmp, _sum0);
float sum0 = bias0 + sum0_tmp[0] + sum0_tmp[1] + sum0_tmp[2] + sum0_tmp[3];
#else
float sum0 = bias0;
#endif // __SSE__
for (; k < L; k++)
{
sum0 += va[0] * vb[0];
va += 1;
vb += 1;
}
output[0] = sum0;
output++;
}
}
}
}
#endif
|
SpatialConvolutionMap.c | #ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "generic/SpatialConvolutionMap.c"
#else
void THNN_(SpatialConvolutionMap_updateOutput)(
THNNState *state, THTensor *input, THTensor *output, THTensor *weight, THTensor *bias,
THTensor *connTable, int nInputPlane, int nOutputPlane,
int dW, int dH)
{
THArgCheck(
weight != NULL && weight->nDimension == 3
&& connTable != NULL && connTable->size[0] == weight->size[0], 4,
"3D weight tensor expected (connTable:size(%d) x kH x kW)", TH_INDEX_BASE
);
int dimw = 2;
int dimh = 1;
int dimc = 0;
int64_t nbatch = 1;
THArgCheck(input->nDimension == 3 || input->nDimension == 4, 2, "3D or 4D(batch mode) tensor expected");
if (input->nDimension == 4)
{
nbatch = input->size[0];
dimc++;
dimw++;
dimh++;
}
const int64_t kH = weight->size[1];
const int64_t kW = weight->size[2];
THArgCheck(input->size[dimc] >= nInputPlane, 2, "invalid number of input planes");
THArgCheck(input->size[dimw] >= kW && input->size[dimh] >= kH, 2, "input image smaller than kernel size");
const int64_t input_w = input->size[dimw];
const int64_t input_h = input->size[dimh];
const int64_t output_w = (input_w - kW) / dW + 1;
const int64_t output_h = (input_h - kH) / dH + 1;
if (input->nDimension == 3)
THTensor_(resize3d)(output, nOutputPlane, output_h, output_w);
else
THTensor_(resize4d)(output, input->size[0], nOutputPlane, output_h, output_w);
/* contiguous */
input = THTensor_(newContiguous)(input);
output = THTensor_(newContiguous)(output);
weight = THTensor_(newContiguous)(weight);
bias = bias ? THTensor_(newContiguous)(bias) : bias;
connTable = THTensor_(newContiguous)(connTable);
/* get raw pointers */
real *input_data = THTensor_(data)(input);
real *output_data = THTensor_(data)(output);
real *weight_data = THTensor_(data)(weight);
real *bias_data = THTensor_(data)(bias);
real *connTable_data = THTensor_(data)(connTable);
int64_t p;
#pragma omp parallel for private(p)
for (p = 0; p < nOutputPlane; p++)
{
int64_t m;
for (m = 0; m < nbatch; m++)
{
/* add bias */
real *ptr_output = output_data + p*output_w*output_h + m*nOutputPlane*output_w*output_h;
int64_t j, k;
real z= bias_data[p];
for (j = 0; j < output_h*output_w; j++)
ptr_output[j] = z;
/* convolve all maps */
int nweight = connTable->size[0];
for (k = 0; k < nweight; k++)
{
/* get offsets for input/output */
int o = (int)connTable_data[k*2+1] - TH_INDEX_BASE;
int i = (int)connTable_data[k*2+0] - TH_INDEX_BASE;
if (o == p)
{
THTensor_(validXCorr2Dptr)(
output_data + o*output_w*output_h + m*nOutputPlane*output_w*output_h,
1.0,
input_data + i*input_w*input_h + m*nInputPlane*input_w*input_h, input_h, input_w,
weight_data + k*kW*kH,
kH, kW,
dH, dW
);
}
}
}
}
/* clean up */
THTensor_(free)(input);
THTensor_(free)(output);
THTensor_(free)(weight);
if (bias) THTensor_(free)(bias);
THTensor_(free)(connTable);
}
void THNN_(SpatialConvolutionMap_updateGradInput)(
THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradInput, THTensor *weight, THTensor *bias,
THTensor *connTable, int nInputPlane, int nOutputPlane,
int dW, int dH)
{
THArgCheck(
weight != NULL && weight->nDimension == 3
&& connTable != NULL && connTable->size[0] == weight->size[0], 5,
"3D weight tensor expected (connTable:size(%d) x kH x kW)", TH_INDEX_BASE
);
/* and dims */
int dimw = 2;
int dimh = 1;
int64_t nbatch = 1;
if (input->nDimension == 4)
{
nbatch = input->size[0];
dimw++;
dimh++;
}
const int64_t input_h = input->size[dimh];
const int64_t input_w = input->size[dimw];
const int64_t output_h = gradOutput->size[dimh];
const int64_t output_w = gradOutput->size[dimw];
const int64_t kH = weight->size[1];
const int64_t kW = weight->size[2];
/* contiguous */
gradInput = THTensor_(newContiguous)(gradInput);
gradOutput = THTensor_(newContiguous)(gradOutput);
weight = THTensor_(newContiguous)(weight);
connTable = THTensor_(newContiguous)(connTable);
/* Resize/Zero */
THTensor_(resizeAs)(gradInput, input);
THTensor_(zero)(gradInput);
/* get raw pointers */
real *gradInput_data = THTensor_(data)(gradInput);
real *gradOutput_data = THTensor_(data)(gradOutput);
real *weight_data = THTensor_(data)(weight);
real *connTable_data = THTensor_(data)(connTable);
int64_t p;
#pragma omp parallel for private(p)
for (p = 0; p < nInputPlane; p++)
{
int64_t m;
for (m = 0; m < nbatch; m++)
{
int64_t k;
/* backward all */
int nkernel = connTable->size[0];
for (k = 0; k < nkernel; k++)
{
int o = (int)connTable_data[k*2+1] - TH_INDEX_BASE;
int i = (int)connTable_data[k*2+0] - TH_INDEX_BASE;
if (i == p)
{
/* gradient to input */
THTensor_(fullConv2Dptr)(
gradInput_data + i*input_w*input_h + m*nInputPlane*input_w*input_h, 1.0,
gradOutput_data + o*output_w*output_h + m*nOutputPlane*output_w*output_h, output_h, output_w,
weight_data + k*kW*kH, kH, kW, dH, dW
);
}
}
}
}
/* clean up */
THTensor_(free)(gradInput);
THTensor_(free)(gradOutput);
THTensor_(free)(weight);
THTensor_(free)(connTable);
}
void THNN_(SpatialConvolutionMap_accGradParameters)(
THNNState *state,
THTensor *input,
THTensor *gradOutput,
THTensor *gradWeight,
THTensor *gradBias,
THTensor *connTable,
int nInputPlane,
int nOutputPlane,
int dW, int dH,
accreal scale_)
{
real scale = TH_CONVERT_ACCREAL_TO_REAL(scale_);
THArgCheck(
gradWeight != NULL && gradWeight->nDimension == 3
&& connTable != NULL && connTable->size[0] == gradWeight->size[0], 5,
"3D gradWeight tensor expected (connTable:size(%d) x kH x kW)", TH_INDEX_BASE
);
/* and dims */
int dimw = 2;
int dimh = 1;
int64_t nbatch = 1;
if (input->nDimension == 4)
{
nbatch = input->size[0];
dimw++;
dimh++;
}
const int64_t input_h = input->size[dimh];
const int64_t input_w = input->size[dimw];
const int64_t output_h = gradOutput->size[dimh];
const int64_t output_w = gradOutput->size[dimw];
const int64_t kH = gradWeight->size[1];
const int64_t kW = gradWeight->size[2];
/* contiguous */
input = THTensor_(newContiguous)(input);
gradOutput = THTensor_(newContiguous)(gradOutput);
THArgCheck(THTensor_(isContiguous)(gradWeight), 4, "gradWeight needs to be contiguous");
THArgCheck(THTensor_(isContiguous)(gradBias), 5, "gradBias needs to be contiguous");
/* get raw pointers */
real *input_data = THTensor_(data)(input);
real *gradOutput_data = THTensor_(data)(gradOutput);
real *gradWeight_data = THTensor_(data)(gradWeight);
real *gradBias_data = THTensor_(data)(gradBias);
int64_t k;
/* gradients wrt bias */
#pragma omp parallel for private(k)
for (k = 0; k < nOutputPlane; k++)
{
int64_t m;
for (m = 0; m < nbatch; m++)
{
real *ptr_gradOutput = gradOutput_data + k*output_w*output_h + m*nOutputPlane*output_w*output_h;
int64_t l;
for (l = 0; l < output_h*output_w; l++)
gradBias_data[k] += scale*ptr_gradOutput[l];
}
}
/* gradients wrt weight */
const int nkernel = connTable->size[0];
#pragma omp parallel for private(k)
for (k = 0; k < nkernel; k++)
{
int64_t m;
for (m = 0; m < nbatch; m++)
{
int o = (int)THTensor_(get2d)(connTable,k,1) - TH_INDEX_BASE;
int i = (int)THTensor_(get2d)(connTable,k,0) - TH_INDEX_BASE;
/* gradient to kernel */
THTensor_(validXCorr2DRevptr)(
gradWeight_data + k*kW*kH,
scale,
input_data + i*input_w*input_h + m*nInputPlane*input_w*input_h, input_h, input_w,
gradOutput_data + o*output_w*output_h + m*nOutputPlane*output_w*output_h , output_h, output_w,
dH, dW
);
}
}
/* clean up */
THTensor_(free)(input);
THTensor_(free)(gradOutput);
}
#endif
|
radix_hash_map.h | #pragma once
#include <new>
#include <malloc.h>
#include "omp.h"
#include "util/search/search_util.h"
inline uint32_t get_log_size(int x) {
int cnt = 0;
for (; x > 0; cnt++) {
x >>= 1;
}
return cnt;
}
inline uint32_t get_part_size(int i) {
return i == 0 ? 0 : 1 << (get_log_size(i) - 1);
}
class RadixFilter {
BoolArray<uint64_t> psum_occupied_bool_;
graph_t *g_;
int radix_val_;
public:
explicit RadixFilter(graph_t *g) : g_(g), radix_val_(-1) {}
void Construct(int u) {
auto deg = g_->num_edges[u + 1] - g_->num_edges[u];
// if (deg > 0) { // assume deg > 0
// 1: Histogram.
constexpr int heuristic_factor = 16;
auto partition_size = get_part_size(deg) * heuristic_factor;
radix_val_ = partition_size - 1;
psum_occupied_bool_ = BoolArray<uint64_t>(partition_size);
auto radix_val = partition_size - 1;
for (auto j = g_->num_edges[u]; j < g_->num_edges[u + 1]; j++) {
auto v = g_->adj[j];
auto bucket_id = v & radix_val;
psum_occupied_bool_.set(bucket_id);
}
// }
}
bool PossibleExist(int v) {
auto bucket_id = v & radix_val_;
return psum_occupied_bool_.get(bucket_id);
}
};
class RadixSet {
vector<int> psum_arr_;
BoolArray<uint64_t> psum_occupied_bool_;
vector<int> tmp_;
vector<int> hash_table_;
graph_t *g_;
public:
explicit RadixSet(graph_t *g) : g_(g) {
psum_arr_.reserve(1024 * 1204 * 2);
hash_table_.reserve(1024 * 1204 * 2);
}
void Construct(int u) {
auto deg = g_->num_edges[u + 1] - g_->num_edges[u];
if (deg > 0) {
// 1: Histogram.
constexpr int heuristic_factor = 16;
auto partition_size = get_part_size(deg) * heuristic_factor;
psum_arr_.resize(partition_size + 1);
memset(&psum_arr_.front(), 0, psum_arr_.size() * sizeof(int));
hash_table_.resize(deg);
psum_occupied_bool_ = BoolArray<uint64_t>(psum_arr_.size());
auto radix_val = partition_size - 1;
for (auto j = g_->num_edges[u]; j < g_->num_edges[u + 1]; j++) {
auto v = g_->adj[j];
auto bucket_id = v & radix_val;
psum_arr_[bucket_id + 1]++;
psum_occupied_bool_.set(bucket_id);
}
// 2: PrefixSum.
for (auto i = 0u; i < partition_size; i++) {
psum_arr_[i + 1] += psum_arr_[i];
}
// 3: Scatter.
tmp_.resize(psum_arr_.size());
memcpy(&tmp_.front(), &psum_arr_.front(), sizeof(int) * psum_arr_.size());
for (auto j = g_->num_edges[u]; j < g_->num_edges[u + 1]; j++) {
auto v = g_->adj[j];
auto bucket_id = v & radix_val;
hash_table_[tmp_[bucket_id]++] = v;
}
} else {
psum_arr_.clear();
}
}
bool Exist(int v) {
// if (psum_arr_.empty())return false; // Assume not zero deg.
auto partition_size = psum_arr_.size() - 1;
auto radix_val = partition_size - 1;
auto bucket_id = v & radix_val;
if (psum_occupied_bool_.get(bucket_id)) {
for (auto j = psum_arr_[bucket_id]; j < psum_arr_[bucket_id + 1]; j++) {
if (hash_table_[j] == v) {
return true;
}
}
}
return false;
}
};
class RadixHashMap {
public:
using hash_entry_t = pair<int, eid_t>;
private:
graph_t *g_;
int size_;
vector<vector<int>> psum_arr_arr_;
// key (v) and eid for (u,v)
vector<vector<pair<int, eid_t>>> hash_table_arr_;
public:
explicit RadixHashMap(graph_t *g) : g_(g), size_(g_->n),
psum_arr_arr_(size_), hash_table_arr_(size_) {
// Construct in Parallel
#pragma omp parallel
{
ParallelPopulate();
#pragma omp for
for (auto u = 0; u < size_; u++) {
Construct(u);
}
}
}
void Construct(int u) {
// 1: Histogram.
auto &psum_arr = psum_arr_arr_[u];
if (psum_arr.empty())return;
auto &hash_table = hash_table_arr_[u];
auto partition_size = psum_arr.size() - 1;
auto radix_val = partition_size - 1;
for (auto j = g_->num_edges[u]; j < g_->num_edges[u + 1]; j++) {
auto v = g_->adj[j];
auto bucket_id = v & radix_val;
// assert(bucket_id < psum_arr.size());
psum_arr[bucket_id + 1]++;
}
// 2: PrefixSum.
for (auto i = 0u; i < partition_size; i++) {
psum_arr[i + 1] += psum_arr[i];
}
// 3: Scatter.
auto tmp = psum_arr;
for (auto j = g_->num_edges[u]; j < g_->num_edges[u + 1]; j++) {
auto v = g_->adj[j];
auto bucket_id = v & radix_val;
hash_table[tmp[bucket_id]++] = make_pair(v, g_->eid[j]);
}
}
void find_u_psum_table_size(int u, vector<int> *&psum_arr_ptr, vector<hash_entry_t> *&hash_table_ptr,
uint32_t &radix_val) {
psum_arr_ptr = &psum_arr_arr_[u];
hash_table_ptr = &hash_table_arr_[u];
auto partition_size = psum_arr_ptr->size() - 1;
radix_val = partition_size - 1;
}
// Assume `psum_arr` is not empty.
eid_t *get(vector<int> *psum_arr_ptr, vector<hash_entry_t> *hash_table_ptr,
uint32_t radix_val, int v) {
auto &psum_arr = *psum_arr_ptr;
auto &hash_table = *hash_table_ptr;
auto bucket_id = v & radix_val;
for (auto j = psum_arr[bucket_id]; j < psum_arr[bucket_id + 1]; j++) {
if (hash_table[j].first == v) {
return &hash_table[j].second;
}
}
return nullptr;
}
eid_t *get(int u, int v) {
auto &psum_arr = psum_arr_arr_[u];
if (psum_arr.empty())return nullptr;
auto &hash_table = hash_table_arr_[u];
auto partition_size = psum_arr.size() - 1;
auto radix_val = partition_size - 1;
auto bucket_id = v & radix_val;
for (auto j = psum_arr[bucket_id]; j < psum_arr[bucket_id + 1]; j++) {
if (hash_table[j].first == v) {
return &hash_table[j].second;
}
}
return nullptr;
}
void ParallelPopulate() {
#pragma omp for
for (auto u = 0; u < size_; u++) {
auto deg = g_->num_edges[u + 1] - g_->num_edges[u];
if (deg > 0) {
auto partition_size = get_part_size(deg);
psum_arr_arr_[u] = vector<int>(partition_size + 1, 0);
}
}
#pragma omp for
for (auto i = 0; i < size_; i++) {
hash_table_arr_[i] = vector<hash_entry_t>(g_->num_edges[i + 1] - g_->num_edges[i]);
}
}
void ManuallyFree() {
Timer free_timer;
#pragma omp parallel
{
#pragma omp for
for (auto i = 0; i < size_; i++) {
vector<int> tmp;
psum_arr_arr_[i].swap(tmp);
}
#pragma omp for
for (auto i = 0; i < size_; i++) {
vector<hash_entry_t> tmp;
hash_table_arr_[i].swap(tmp);
}
}
log_info("Free radix hash map cost: %.6lfs", free_timer.elapsed());
}
~RadixHashMap() {
ManuallyFree();
}
}; |
Example_taskloop.1.c | /*
* @@name: taskloop.c
* @@type: C
* @@compilable: yes
* @@linkable: no
* @@expect: success
* @@version: omp_4.5
*/
void long_running_task(void);
void loop_body(int i, int j);
void parallel_work(void) {
int i, j;
#pragma omp taskgroup
{
#pragma omp task
long_running_task(); // can execute concurrently
#pragma omp taskloop private(j) grainsize(500) nogroup
for (i = 0; i < 10000; i++) { // can execute concurrently
for (j = 0; j < i; j++) {
loop_body(i, j);
}
}
}
}
|
shear.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% SSSSS H H EEEEE AAA RRRR %
% SS H H E A A R R %
% SSS HHHHH EEE AAAAA RRRR %
% SS H H E A A R R %
% SSSSS H H EEEEE A A R R %
% %
% %
% MagickCore Methods to Shear or Rotate an Image by an Arbitrary Angle %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2018 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. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% The XShearImage() and YShearImage() methods are based on the paper "A Fast
% Algorithm for General Raster Rotation" by Alan W. Paeth, Graphics
% Interface '86 (Vancouver). ShearRotateImage() is adapted from a similar
% method based on the Paeth paper written by Michael Halle of the Spatial
% Imaging Group, MIT Media Lab.
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache-private.h"
#include "MagickCore/channel.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/decorate.h"
#include "MagickCore/distort.h"
#include "MagickCore/draw.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/gem.h"
#include "MagickCore/geometry.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/matrix.h"
#include "MagickCore/memory_.h"
#include "MagickCore/list.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/nt-base-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/quantum.h"
#include "MagickCore/resource_.h"
#include "MagickCore/shear.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/threshold.h"
#include "MagickCore/transform.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C r o p T o F i t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CropToFitImage() crops the sheared image as determined by the bounding box
% as defined by width and height and shearing angles.
%
% The format of the CropToFitImage method is:
%
% MagickBooleanType CropToFitImage(Image **image,
% const double x_shear,const double x_shear,
% const double width,const double height,
% const MagickBooleanType rotate,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o x_shear, y_shear, width, height: Defines a region of the image to crop.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType CropToFitImage(Image **image,
const double x_shear,const double y_shear,
const double width,const double height,
const MagickBooleanType rotate,ExceptionInfo *exception)
{
Image
*crop_image;
PointInfo
extent[4],
min,
max;
RectangleInfo
geometry,
page;
register ssize_t
i;
/*
Calculate the rotated image size.
*/
extent[0].x=(double) (-width/2.0);
extent[0].y=(double) (-height/2.0);
extent[1].x=(double) width/2.0;
extent[1].y=(double) (-height/2.0);
extent[2].x=(double) (-width/2.0);
extent[2].y=(double) height/2.0;
extent[3].x=(double) width/2.0;
extent[3].y=(double) height/2.0;
for (i=0; i < 4; i++)
{
extent[i].x+=x_shear*extent[i].y;
extent[i].y+=y_shear*extent[i].x;
if (rotate != MagickFalse)
extent[i].x+=x_shear*extent[i].y;
extent[i].x+=(double) (*image)->columns/2.0;
extent[i].y+=(double) (*image)->rows/2.0;
}
min=extent[0];
max=extent[0];
for (i=1; i < 4; i++)
{
if (min.x > extent[i].x)
min.x=extent[i].x;
if (min.y > extent[i].y)
min.y=extent[i].y;
if (max.x < extent[i].x)
max.x=extent[i].x;
if (max.y < extent[i].y)
max.y=extent[i].y;
}
geometry.x=(ssize_t) ceil(min.x-0.5);
geometry.y=(ssize_t) ceil(min.y-0.5);
geometry.width=(size_t) floor(max.x-min.x+0.5);
geometry.height=(size_t) floor(max.y-min.y+0.5);
page=(*image)->page;
(void) ParseAbsoluteGeometry("0x0+0+0",&(*image)->page);
crop_image=CropImage(*image,&geometry,exception);
if (crop_image == (Image *) NULL)
return(MagickFalse);
crop_image->page=page;
*image=DestroyImage(*image);
*image=crop_image;
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s k e w I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DeskewImage() removes skew from the image. Skew is an artifact that
% occurs in scanned images because of the camera being misaligned,
% imperfections in the scanning or surface, or simply because the paper was
% not placed completely flat when scanned.
%
% The result will be auto-croped if the artifact "deskew:auto-crop" is
% defined, while the amount the image is to be deskewed, in degrees is also
% saved as the artifact "deskew:angle".
%
% The format of the DeskewImage method is:
%
% Image *DeskewImage(const Image *image,const double threshold,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o threshold: separate background from foreground.
%
% o exception: return any errors or warnings in this structure.
%
*/
static void RadonProjection(const Image *image,MatrixInfo *source_matrixs,
MatrixInfo *destination_matrixs,const ssize_t sign,size_t *projection)
{
MatrixInfo
*swap;
register MatrixInfo
*p,
*q;
register ssize_t
x;
size_t
step;
p=source_matrixs;
q=destination_matrixs;
for (step=1; step < GetMatrixColumns(p); step*=2)
{
for (x=0; x < (ssize_t) GetMatrixColumns(p); x+=2*(ssize_t) step)
{
register ssize_t
i;
ssize_t
y;
unsigned short
element,
neighbor;
for (i=0; i < (ssize_t) step; i++)
{
for (y=0; y < (ssize_t) (GetMatrixRows(p)-i-1); y++)
{
if (GetMatrixElement(p,x+i,y,&element) == MagickFalse)
continue;
if (GetMatrixElement(p,x+i+step,y+i,&neighbor) == MagickFalse)
continue;
neighbor+=element;
if (SetMatrixElement(q,x+2*i,y,&neighbor) == MagickFalse)
continue;
if (GetMatrixElement(p,x+i+step,y+i+1,&neighbor) == MagickFalse)
continue;
neighbor+=element;
if (SetMatrixElement(q,x+2*i+1,y,&neighbor) == MagickFalse)
continue;
}
for ( ; y < (ssize_t) (GetMatrixRows(p)-i); y++)
{
if (GetMatrixElement(p,x+i,y,&element) == MagickFalse)
continue;
if (GetMatrixElement(p,x+i+step,y+i,&neighbor) == MagickFalse)
continue;
neighbor+=element;
if (SetMatrixElement(q,x+2*i,y,&neighbor) == MagickFalse)
continue;
if (SetMatrixElement(q,x+2*i+1,y,&element) == MagickFalse)
continue;
}
for ( ; y < (ssize_t) GetMatrixRows(p); y++)
{
if (GetMatrixElement(p,x+i,y,&element) == MagickFalse)
continue;
if (SetMatrixElement(q,x+2*i,y,&element) == MagickFalse)
continue;
if (SetMatrixElement(q,x+2*i+1,y,&element) == MagickFalse)
continue;
}
}
}
swap=p;
p=q;
q=swap;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) \
magick_number_threads(image,image,GetMatrixColumns(p),1)
#endif
for (x=0; x < (ssize_t) GetMatrixColumns(p); x++)
{
register ssize_t
y;
size_t
sum;
sum=0;
for (y=0; y < (ssize_t) (GetMatrixRows(p)-1); y++)
{
ssize_t
delta;
unsigned short
element,
neighbor;
if (GetMatrixElement(p,x,y,&element) == MagickFalse)
continue;
if (GetMatrixElement(p,x,y+1,&neighbor) == MagickFalse)
continue;
delta=(ssize_t) element-(ssize_t) neighbor;
sum+=delta*delta;
}
projection[GetMatrixColumns(p)+sign*x-1]=sum;
}
}
static MagickBooleanType RadonTransform(const Image *image,
const double threshold,size_t *projection,ExceptionInfo *exception)
{
CacheView
*image_view;
MatrixInfo
*destination_matrixs,
*source_matrixs;
MagickBooleanType
status;
size_t
count,
width;
ssize_t
j,
y;
unsigned char
c;
unsigned short
bits[256];
for (width=1; width < ((image->columns+7)/8); width<<=1) ;
source_matrixs=AcquireMatrixInfo(width,image->rows,sizeof(unsigned short),
exception);
destination_matrixs=AcquireMatrixInfo(width,image->rows,
sizeof(unsigned short),exception);
if ((source_matrixs == (MatrixInfo *) NULL) ||
(destination_matrixs == (MatrixInfo *) NULL))
{
if (destination_matrixs != (MatrixInfo *) NULL)
destination_matrixs=DestroyMatrixInfo(destination_matrixs);
if (source_matrixs != (MatrixInfo *) NULL)
source_matrixs=DestroyMatrixInfo(source_matrixs);
return(MagickFalse);
}
if (NullMatrix(source_matrixs) == MagickFalse)
{
destination_matrixs=DestroyMatrixInfo(destination_matrixs);
source_matrixs=DestroyMatrixInfo(source_matrixs);
return(MagickFalse);
}
for (j=0; j < 256; j++)
{
c=(unsigned char) j;
for (count=0; c != 0; c>>=1)
count+=c & 0x01;
bits[j]=(unsigned short) count;
}
status=MagickTrue;
image_view=AcquireVirtualCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
i,
x;
size_t
bit,
byte;
unsigned short
value;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
bit=0;
byte=0;
i=(ssize_t) (image->columns+7)/8;
for (x=0; x < (ssize_t) image->columns; x++)
{
byte<<=1;
if (((MagickRealType) GetPixelRed(image,p) < threshold) ||
((MagickRealType) GetPixelGreen(image,p) < threshold) ||
((MagickRealType) GetPixelBlue(image,p) < threshold))
byte|=0x01;
bit++;
if (bit == 8)
{
value=bits[byte];
(void) SetMatrixElement(source_matrixs,--i,y,&value);
bit=0;
byte=0;
}
p+=GetPixelChannels(image);
}
if (bit != 0)
{
byte<<=(8-bit);
value=bits[byte];
(void) SetMatrixElement(source_matrixs,--i,y,&value);
}
}
RadonProjection(image,source_matrixs,destination_matrixs,-1,projection);
(void) NullMatrix(source_matrixs);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
i,
x;
size_t
bit,
byte;
unsigned short
value;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
bit=0;
byte=0;
i=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
byte<<=1;
if (((MagickRealType) GetPixelRed(image,p) < threshold) ||
((MagickRealType) GetPixelGreen(image,p) < threshold) ||
((MagickRealType) GetPixelBlue(image,p) < threshold))
byte|=0x01;
bit++;
if (bit == 8)
{
value=bits[byte];
(void) SetMatrixElement(source_matrixs,i++,y,&value);
bit=0;
byte=0;
}
p+=GetPixelChannels(image);
}
if (bit != 0)
{
byte<<=(8-bit);
value=bits[byte];
(void) SetMatrixElement(source_matrixs,i++,y,&value);
}
}
RadonProjection(image,source_matrixs,destination_matrixs,1,projection);
image_view=DestroyCacheView(image_view);
destination_matrixs=DestroyMatrixInfo(destination_matrixs);
source_matrixs=DestroyMatrixInfo(source_matrixs);
return(MagickTrue);
}
static void GetImageBackgroundColor(Image *image,const ssize_t offset,
ExceptionInfo *exception)
{
CacheView
*image_view;
PixelInfo
background;
double
count;
ssize_t
y;
/*
Compute average background color.
*/
if (offset <= 0)
return;
GetPixelInfo(image,&background);
count=0.0;
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
if ((y >= offset) && (y < ((ssize_t) image->rows-offset)))
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
continue;
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((x >= offset) && (x < ((ssize_t) image->columns-offset)))
continue;
background.red+=QuantumScale*GetPixelRed(image,p);
background.green+=QuantumScale*GetPixelGreen(image,p);
background.blue+=QuantumScale*GetPixelBlue(image,p);
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
background.alpha+=QuantumScale*GetPixelAlpha(image,p);
count++;
p+=GetPixelChannels(image);
}
}
image_view=DestroyCacheView(image_view);
image->background_color.red=(double) ClampToQuantum(QuantumRange*
background.red/count);
image->background_color.green=(double) ClampToQuantum(QuantumRange*
background.green/count);
image->background_color.blue=(double) ClampToQuantum(QuantumRange*
background.blue/count);
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
image->background_color.alpha=(double) ClampToQuantum(QuantumRange*
background.alpha/count);
}
MagickExport Image *DeskewImage(const Image *image,const double threshold,
ExceptionInfo *exception)
{
AffineMatrix
affine_matrix;
const char
*artifact;
double
degrees;
Image
*clone_image,
*crop_image,
*deskew_image,
*median_image;
MagickBooleanType
status;
RectangleInfo
geometry;
register ssize_t
i;
size_t
max_projection,
*projection,
width;
ssize_t
skew;
/*
Compute deskew angle.
*/
for (width=1; width < ((image->columns+7)/8); width<<=1) ;
projection=(size_t *) AcquireQuantumMemory((size_t) (2*width-1),
sizeof(*projection));
if (projection == (size_t *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
status=RadonTransform(image,threshold,projection,exception);
if (status == MagickFalse)
{
projection=(size_t *) RelinquishMagickMemory(projection);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
max_projection=0;
skew=0;
for (i=0; i < (ssize_t) (2*width-1); i++)
{
if (projection[i] > max_projection)
{
skew=i-(ssize_t) width+1;
max_projection=projection[i];
}
}
projection=(size_t *) RelinquishMagickMemory(projection);
degrees=RadiansToDegrees(-atan((double) skew/width/8));
if (image->debug != MagickFalse)
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" Deskew angle: %g",degrees);
/*
Deskew image.
*/
clone_image=CloneImage(image,0,0,MagickTrue,exception);
if (clone_image == (Image *) NULL)
return((Image *) NULL);
{
char
angle[MagickPathExtent];
(void) FormatLocaleString(angle,MagickPathExtent,"%.20g",degrees);
(void) SetImageArtifact(clone_image,"deskew:angle",angle);
}
(void) SetImageVirtualPixelMethod(clone_image,BackgroundVirtualPixelMethod,
exception);
affine_matrix.sx=cos(DegreesToRadians(fmod((double) degrees,360.0)));
affine_matrix.rx=sin(DegreesToRadians(fmod((double) degrees,360.0)));
affine_matrix.ry=(-sin(DegreesToRadians(fmod((double) degrees,360.0))));
affine_matrix.sy=cos(DegreesToRadians(fmod((double) degrees,360.0)));
affine_matrix.tx=0.0;
affine_matrix.ty=0.0;
artifact=GetImageArtifact(image,"deskew:auto-crop");
if (IsStringTrue(artifact) == MagickFalse)
{
deskew_image=AffineTransformImage(clone_image,&affine_matrix,exception);
clone_image=DestroyImage(clone_image);
return(deskew_image);
}
/*
Auto-crop image.
*/
GetImageBackgroundColor(clone_image,(ssize_t) StringToLong(artifact),
exception);
deskew_image=AffineTransformImage(clone_image,&affine_matrix,exception);
clone_image=DestroyImage(clone_image);
if (deskew_image == (Image *) NULL)
return((Image *) NULL);
median_image=StatisticImage(deskew_image,MedianStatistic,3,3,exception);
if (median_image == (Image *) NULL)
{
deskew_image=DestroyImage(deskew_image);
return((Image *) NULL);
}
geometry=GetImageBoundingBox(median_image,exception);
median_image=DestroyImage(median_image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TransformEvent,GetMagickModule()," Deskew geometry: "
"%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double)
geometry.height,(double) geometry.x,(double) geometry.y);
crop_image=CropImage(deskew_image,&geometry,exception);
deskew_image=DestroyImage(deskew_image);
return(crop_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I n t e g r a l R o t a t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IntegralRotateImage() rotates the image an integral of 90 degrees. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the rotated image.
%
% The format of the IntegralRotateImage method is:
%
% Image *IntegralRotateImage(const Image *image,size_t rotations,
% ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o rotations: Specifies the number of 90 degree rotations.
%
*/
MagickExport Image *IntegralRotateImage(const Image *image,size_t rotations,
ExceptionInfo *exception)
{
#define RotateImageTag "Rotate/Image"
CacheView
*image_view,
*rotate_view;
Image
*rotate_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
page;
/*
Initialize rotated image attributes.
*/
assert(image != (Image *) NULL);
page=image->page;
rotations%=4;
if (rotations == 0)
return(CloneImage(image,0,0,MagickTrue,exception));
if ((rotations == 1) || (rotations == 3))
rotate_image=CloneImage(image,image->rows,image->columns,MagickTrue,
exception);
else
rotate_image=CloneImage(image,0,0,MagickTrue,
exception);
if (rotate_image == (Image *) NULL)
return((Image *) NULL);
/*
Integral rotate the image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
rotate_view=AcquireAuthenticCacheView(rotate_image,exception);
switch (rotations)
{
case 1:
{
size_t
tile_height,
tile_width;
ssize_t
tile_y;
/*
Rotate 90 degrees.
*/
GetPixelCacheTileSize(image,&tile_width,&tile_height);
tile_width=image->columns;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows/tile_height,1)
#endif
for (tile_y=0; tile_y < (ssize_t) image->rows; tile_y+=(ssize_t) tile_height)
{
register ssize_t
tile_x;
if (status == MagickFalse)
continue;
tile_x=0;
for ( ; tile_x < (ssize_t) image->columns; tile_x+=(ssize_t) tile_width)
{
MagickBooleanType
sync;
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
y;
size_t
height,
width;
width=tile_width;
if ((tile_x+(ssize_t) tile_width) > (ssize_t) image->columns)
width=(size_t) (tile_width-(tile_x+tile_width-image->columns));
height=tile_height;
if ((tile_y+(ssize_t) tile_height) > (ssize_t) image->rows)
height=(size_t) (tile_height-(tile_y+tile_height-image->rows));
p=GetCacheViewVirtualPixels(image_view,tile_x,tile_y,width,height,
exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
for (y=0; y < (ssize_t) width; y++)
{
register const Quantum
*magick_restrict tile_pixels;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(rotate_view,(ssize_t)
(rotate_image->columns-(tile_y+height)),y+tile_x,height,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
tile_pixels=p+((height-1)*width+y)*GetPixelChannels(image);
for (x=0; x < (ssize_t) height; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait rotate_traits=GetPixelChannelTraits(rotate_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(rotate_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(rotate_image,channel,tile_pixels[i],q);
}
tile_pixels-=width*GetPixelChannels(image);
q+=GetPixelChannels(rotate_image);
}
sync=SyncCacheViewAuthenticPixels(rotate_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_IntegralRotateImage)
#endif
proceed=SetImageProgress(image,RotateImageTag,progress+=tile_height,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
(void) SetImageProgress(image,RotateImageTag,(MagickOffsetType)
image->rows-1,image->rows);
Swap(page.width,page.height);
Swap(page.x,page.y);
if (page.width != 0)
page.x=(ssize_t) (page.width-rotate_image->columns-page.x);
break;
}
case 2:
{
register ssize_t
y;
/*
Rotate 180 degrees.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(rotate_view,0,(ssize_t) (image->rows-y-
1),image->columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
q+=GetPixelChannels(rotate_image)*image->columns;
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
q-=GetPixelChannels(rotate_image);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait rotate_traits=GetPixelChannelTraits(rotate_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(rotate_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(rotate_image,channel,p[i],q);
}
p+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(rotate_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_IntegralRotateImage)
#endif
proceed=SetImageProgress(image,RotateImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
(void) SetImageProgress(image,RotateImageTag,(MagickOffsetType)
image->rows-1,image->rows);
if (page.width != 0)
page.x=(ssize_t) (page.width-rotate_image->columns-page.x);
if (page.height != 0)
page.y=(ssize_t) (page.height-rotate_image->rows-page.y);
break;
}
case 3:
{
size_t
tile_height,
tile_width;
ssize_t
tile_y;
/*
Rotate 270 degrees.
*/
GetPixelCacheTileSize(image,&tile_width,&tile_height);
tile_width=image->columns;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows/tile_height,1)
#endif
for (tile_y=0; tile_y < (ssize_t) image->rows; tile_y+=(ssize_t) tile_height)
{
register ssize_t
tile_x;
if (status == MagickFalse)
continue;
tile_x=0;
for ( ; tile_x < (ssize_t) image->columns; tile_x+=(ssize_t) tile_width)
{
MagickBooleanType
sync;
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
y;
size_t
height,
width;
width=tile_width;
if ((tile_x+(ssize_t) tile_width) > (ssize_t) image->columns)
width=(size_t) (tile_width-(tile_x+tile_width-image->columns));
height=tile_height;
if ((tile_y+(ssize_t) tile_height) > (ssize_t) image->rows)
height=(size_t) (tile_height-(tile_y+tile_height-image->rows));
p=GetCacheViewVirtualPixels(image_view,tile_x,tile_y,width,height,
exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
for (y=0; y < (ssize_t) width; y++)
{
register const Quantum
*magick_restrict tile_pixels;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(rotate_view,tile_y,(ssize_t) (y+
rotate_image->rows-(tile_x+width)),height,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
tile_pixels=p+((width-1)-y)*GetPixelChannels(image);
for (x=0; x < (ssize_t) height; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait rotate_traits=GetPixelChannelTraits(rotate_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(rotate_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(rotate_image,channel,tile_pixels[i],q);
}
tile_pixels+=width*GetPixelChannels(image);
q+=GetPixelChannels(rotate_image);
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_IntegralRotateImage)
#endif
sync=SyncCacheViewAuthenticPixels(rotate_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,RotateImageTag,progress+=tile_height,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
(void) SetImageProgress(image,RotateImageTag,(MagickOffsetType)
image->rows-1,image->rows);
Swap(page.width,page.height);
Swap(page.x,page.y);
if (page.height != 0)
page.y=(ssize_t) (page.height-rotate_image->rows-page.y);
break;
}
default:
break;
}
rotate_view=DestroyCacheView(rotate_view);
image_view=DestroyCacheView(image_view);
rotate_image->type=image->type;
rotate_image->page=page;
if (status == MagickFalse)
rotate_image=DestroyImage(rotate_image);
return(rotate_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ X S h e a r I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XShearImage() shears the image in the X direction with a shear angle of
% 'degrees'. Positive angles shear counter-clockwise (right-hand rule), and
% negative angles shear clockwise. Angles are measured relative to a vertical
% Y-axis. X shears will widen an image creating 'empty' triangles on the left
% and right sides of the source image.
%
% The format of the XShearImage method is:
%
% MagickBooleanType XShearImage(Image *image,const double degrees,
% const size_t width,const size_t height,
% const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o degrees: A double representing the shearing angle along the X
% axis.
%
% o width, height, x_offset, y_offset: Defines a region of the image
% to shear.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType XShearImage(Image *image,const double degrees,
const size_t width,const size_t height,const ssize_t x_offset,
const ssize_t y_offset,ExceptionInfo *exception)
{
#define XShearImageTag "XShear/Image"
typedef enum
{
LEFT,
RIGHT
} ShearDirection;
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
background;
ssize_t
y;
/*
X shear image.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=MagickTrue;
background=image->background_color;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,height,1)
#endif
for (y=0; y < (ssize_t) height; y++)
{
PixelInfo
pixel,
source,
destination;
double
area,
displacement;
register Quantum
*magick_restrict p,
*magick_restrict q;
register ssize_t
i;
ShearDirection
direction;
ssize_t
step;
if (status == MagickFalse)
continue;
p=GetCacheViewAuthenticPixels(image_view,0,y_offset+y,image->columns,1,
exception);
if (p == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
p+=x_offset*GetPixelChannels(image);
displacement=degrees*(double) (y-height/2.0);
if (displacement == 0.0)
continue;
if (displacement > 0.0)
direction=RIGHT;
else
{
displacement*=(-1.0);
direction=LEFT;
}
step=(ssize_t) floor((double) displacement);
area=(double) (displacement-step);
step++;
pixel=background;
GetPixelInfo(image,&source);
GetPixelInfo(image,&destination);
switch (direction)
{
case LEFT:
{
/*
Transfer pixels left-to-right.
*/
if (step > x_offset)
break;
q=p-step*GetPixelChannels(image);
for (i=0; i < (ssize_t) width; i++)
{
if ((x_offset+i) < step)
{
p+=GetPixelChannels(image);
GetPixelInfoPixel(image,p,&pixel);
q+=GetPixelChannels(image);
continue;
}
GetPixelInfoPixel(image,p,&source);
CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha,
&source,(double) GetPixelAlpha(image,p),area,&destination);
SetPixelViaPixelInfo(image,&destination,q);
GetPixelInfoPixel(image,p,&pixel);
p+=GetPixelChannels(image);
q+=GetPixelChannels(image);
}
CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha,
&background,(double) background.alpha,area,&destination);
SetPixelViaPixelInfo(image,&destination,q);
q+=GetPixelChannels(image);
for (i=0; i < (step-1); i++)
{
SetPixelViaPixelInfo(image,&background,q);
q+=GetPixelChannels(image);
}
break;
}
case RIGHT:
{
/*
Transfer pixels right-to-left.
*/
p+=width*GetPixelChannels(image);
q=p+step*GetPixelChannels(image);
for (i=0; i < (ssize_t) width; i++)
{
p-=GetPixelChannels(image);
q-=GetPixelChannels(image);
if ((size_t) (x_offset+width+step-i) > image->columns)
continue;
GetPixelInfoPixel(image,p,&source);
CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha,
&source,(double) GetPixelAlpha(image,p),area,&destination);
SetPixelViaPixelInfo(image,&destination,q);
GetPixelInfoPixel(image,p,&pixel);
}
CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha,
&background,(double) background.alpha,area,&destination);
q-=GetPixelChannels(image);
SetPixelViaPixelInfo(image,&destination,q);
for (i=0; i < (step-1); i++)
{
q-=GetPixelChannels(image);
SetPixelViaPixelInfo(image,&background,q);
}
break;
}
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_XShearImage)
#endif
proceed=SetImageProgress(image,XShearImageTag,progress++,height);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ Y S h e a r I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% YShearImage shears the image in the Y direction with a shear angle of
% 'degrees'. Positive angles shear counter-clockwise (right-hand rule), and
% negative angles shear clockwise. Angles are measured relative to a
% horizontal X-axis. Y shears will increase the height of an image creating
% 'empty' triangles on the top and bottom of the source image.
%
% The format of the YShearImage method is:
%
% MagickBooleanType YShearImage(Image *image,const double degrees,
% const size_t width,const size_t height,
% const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o degrees: A double representing the shearing angle along the Y
% axis.
%
% o width, height, x_offset, y_offset: Defines a region of the image
% to shear.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType YShearImage(Image *image,const double degrees,
const size_t width,const size_t height,const ssize_t x_offset,
const ssize_t y_offset,ExceptionInfo *exception)
{
#define YShearImageTag "YShear/Image"
typedef enum
{
UP,
DOWN
} ShearDirection;
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
background;
ssize_t
x;
/*
Y Shear image.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=MagickTrue;
progress=0;
background=image->background_color;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,width,1)
#endif
for (x=0; x < (ssize_t) width; x++)
{
ssize_t
step;
double
area,
displacement;
PixelInfo
pixel,
source,
destination;
register Quantum
*magick_restrict p,
*magick_restrict q;
register ssize_t
i;
ShearDirection
direction;
if (status == MagickFalse)
continue;
p=GetCacheViewAuthenticPixels(image_view,x_offset+x,0,1,image->rows,
exception);
if (p == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
p+=y_offset*GetPixelChannels(image);
displacement=degrees*(double) (x-width/2.0);
if (displacement == 0.0)
continue;
if (displacement > 0.0)
direction=DOWN;
else
{
displacement*=(-1.0);
direction=UP;
}
step=(ssize_t) floor((double) displacement);
area=(double) (displacement-step);
step++;
pixel=background;
GetPixelInfo(image,&source);
GetPixelInfo(image,&destination);
switch (direction)
{
case UP:
{
/*
Transfer pixels top-to-bottom.
*/
if (step > y_offset)
break;
q=p-step*GetPixelChannels(image);
for (i=0; i < (ssize_t) height; i++)
{
if ((y_offset+i) < step)
{
p+=GetPixelChannels(image);
GetPixelInfoPixel(image,p,&pixel);
q+=GetPixelChannels(image);
continue;
}
GetPixelInfoPixel(image,p,&source);
CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha,
&source,(double) GetPixelAlpha(image,p),area,
&destination);
SetPixelViaPixelInfo(image,&destination,q);
GetPixelInfoPixel(image,p,&pixel);
p+=GetPixelChannels(image);
q+=GetPixelChannels(image);
}
CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha,
&background,(double) background.alpha,area,&destination);
SetPixelViaPixelInfo(image,&destination,q);
q+=GetPixelChannels(image);
for (i=0; i < (step-1); i++)
{
SetPixelViaPixelInfo(image,&background,q);
q+=GetPixelChannels(image);
}
break;
}
case DOWN:
{
/*
Transfer pixels bottom-to-top.
*/
p+=height*GetPixelChannels(image);
q=p+step*GetPixelChannels(image);
for (i=0; i < (ssize_t) height; i++)
{
p-=GetPixelChannels(image);
q-=GetPixelChannels(image);
if ((size_t) (y_offset+height+step-i) > image->rows)
continue;
GetPixelInfoPixel(image,p,&source);
CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha,
&source,(double) GetPixelAlpha(image,p),area,
&destination);
SetPixelViaPixelInfo(image,&destination,q);
GetPixelInfoPixel(image,p,&pixel);
}
CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha,
&background,(double) background.alpha,area,&destination);
q-=GetPixelChannels(image);
SetPixelViaPixelInfo(image,&destination,q);
for (i=0; i < (step-1); i++)
{
q-=GetPixelChannels(image);
SetPixelViaPixelInfo(image,&background,q);
}
break;
}
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_YShearImage)
#endif
proceed=SetImageProgress(image,YShearImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S h e a r I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ShearImage() creates a new image that is a shear_image copy of an existing
% one. Shearing slides one edge of an image along the X or Y axis, creating
% a parallelogram. An X direction shear slides an edge along the X axis,
% while a Y direction shear slides an edge along the Y axis. The amount of
% the shear is controlled by a shear angle. For X direction shears, x_shear
% is measured relative to the Y axis, and similarly, for Y direction shears
% y_shear is measured relative to the X axis. Empty triangles left over from
% shearing the image are filled with the background color defined by member
% 'background_color' of the image.. ShearImage() allocates the memory
% necessary for the new Image structure and returns a pointer to the new image.
%
% ShearImage() is based on the paper "A Fast Algorithm for General Raster
% Rotatation" by Alan W. Paeth.
%
% The format of the ShearImage method is:
%
% Image *ShearImage(const Image *image,const double x_shear,
% const double y_shear,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o x_shear, y_shear: Specifies the number of degrees to shear the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ShearImage(const Image *image,const double x_shear,
const double y_shear,ExceptionInfo *exception)
{
Image
*integral_image,
*shear_image;
MagickBooleanType
status;
PointInfo
shear;
RectangleInfo
border_info,
bounds;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if ((x_shear != 0.0) && (fmod(x_shear,90.0) == 0.0))
ThrowImageException(ImageError,"AngleIsDiscontinuous");
if ((y_shear != 0.0) && (fmod(y_shear,90.0) == 0.0))
ThrowImageException(ImageError,"AngleIsDiscontinuous");
/*
Initialize shear angle.
*/
integral_image=CloneImage(image,0,0,MagickTrue,exception);
if (integral_image == (Image *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
shear.x=(-tan(DegreesToRadians(fmod(x_shear,360.0))));
shear.y=tan(DegreesToRadians(fmod(y_shear,360.0)));
if ((shear.x == 0.0) && (shear.y == 0.0))
return(integral_image);
if (SetImageStorageClass(integral_image,DirectClass,exception) == MagickFalse)
{
integral_image=DestroyImage(integral_image);
return(integral_image);
}
if (integral_image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(integral_image,OpaqueAlphaChannel,exception);
/*
Compute image size.
*/
bounds.width=image->columns+(ssize_t) floor(fabs(shear.x)*image->rows+0.5);
bounds.x=(ssize_t) ceil((double) image->columns+((fabs(shear.x)*image->rows)-
image->columns)/2.0-0.5);
bounds.y=(ssize_t) ceil((double) image->rows+((fabs(shear.y)*bounds.width)-
image->rows)/2.0-0.5);
/*
Surround image with border.
*/
integral_image->border_color=integral_image->background_color;
integral_image->compose=CopyCompositeOp;
border_info.width=(size_t) bounds.x;
border_info.height=(size_t) bounds.y;
shear_image=BorderImage(integral_image,&border_info,image->compose,exception);
integral_image=DestroyImage(integral_image);
if (shear_image == (Image *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
/*
Shear the image.
*/
if (shear_image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(shear_image,OpaqueAlphaChannel,exception);
status=XShearImage(shear_image,shear.x,image->columns,image->rows,bounds.x,
(ssize_t) (shear_image->rows-image->rows)/2,exception);
if (status == MagickFalse)
{
shear_image=DestroyImage(shear_image);
return((Image *) NULL);
}
status=YShearImage(shear_image,shear.y,bounds.width,image->rows,(ssize_t)
(shear_image->columns-bounds.width)/2,bounds.y,exception);
if (status == MagickFalse)
{
shear_image=DestroyImage(shear_image);
return((Image *) NULL);
}
status=CropToFitImage(&shear_image,shear.x,shear.y,(MagickRealType)
image->columns,(MagickRealType) image->rows,MagickFalse,exception);
shear_image->alpha_trait=image->alpha_trait;
shear_image->compose=image->compose;
shear_image->page.width=0;
shear_image->page.height=0;
if (status == MagickFalse)
shear_image=DestroyImage(shear_image);
return(shear_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S h e a r R o t a t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ShearRotateImage() creates a new image that is a rotated copy of an existing
% one. Positive angles rotate counter-clockwise (right-hand rule), while
% negative angles rotate clockwise. Rotated images are usually larger than
% the originals and have 'empty' triangular corners. X axis. Empty
% triangles left over from shearing the image are filled with the background
% color defined by member 'background_color' of the image. ShearRotateImage
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% ShearRotateImage() is based on the paper "A Fast Algorithm for General
% Raster Rotatation" by Alan W. Paeth. ShearRotateImage is adapted from a
% similar method based on the Paeth paper written by Michael Halle of the
% Spatial Imaging Group, MIT Media Lab.
%
% The format of the ShearRotateImage method is:
%
% Image *ShearRotateImage(const Image *image,const double degrees,
% ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o degrees: Specifies the number of degrees to rotate the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ShearRotateImage(const Image *image,const double degrees,
ExceptionInfo *exception)
{
Image
*integral_image,
*rotate_image;
MagickBooleanType
status;
MagickRealType
angle;
PointInfo
shear;
RectangleInfo
border_info,
bounds;
size_t
height,
rotations,
shear_width,
width;
/*
Adjust rotation angle.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
angle=fmod(degrees,360.0);
if (angle < -45.0)
angle+=360.0;
for (rotations=0; angle > 45.0; rotations++)
angle-=90.0;
rotations%=4;
/*
Calculate shear equations.
*/
integral_image=IntegralRotateImage(image,rotations,exception);
if (integral_image == (Image *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
shear.x=(-tan((double) DegreesToRadians(angle)/2.0));
shear.y=sin((double) DegreesToRadians(angle));
if ((shear.x == 0.0) && (shear.y == 0.0))
return(integral_image);
if (SetImageStorageClass(integral_image,DirectClass,exception) == MagickFalse)
{
integral_image=DestroyImage(integral_image);
return(integral_image);
}
if (integral_image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(integral_image,OpaqueAlphaChannel,exception);
/*
Compute maximum bounds for 3 shear operations.
*/
width=integral_image->columns;
height=integral_image->rows;
bounds.width=(size_t) floor(fabs((double) height*shear.x)+width+0.5);
bounds.height=(size_t) floor(fabs((double) bounds.width*shear.y)+height+0.5);
shear_width=(size_t) floor(fabs((double) bounds.height*shear.x)+
bounds.width+0.5);
bounds.x=(ssize_t) floor((double) ((shear_width > bounds.width) ? width :
bounds.width-shear_width+2)/2.0+0.5);
bounds.y=(ssize_t) floor(((double) bounds.height-height+2)/2.0+0.5);
/*
Surround image with a border.
*/
integral_image->border_color=integral_image->background_color;
integral_image->compose=CopyCompositeOp;
border_info.width=(size_t) bounds.x;
border_info.height=(size_t) bounds.y;
rotate_image=BorderImage(integral_image,&border_info,image->compose,
exception);
integral_image=DestroyImage(integral_image);
if (rotate_image == (Image *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
/*
Rotate the image.
*/
status=XShearImage(rotate_image,shear.x,width,height,bounds.x,(ssize_t)
(rotate_image->rows-height)/2,exception);
if (status == MagickFalse)
{
rotate_image=DestroyImage(rotate_image);
return((Image *) NULL);
}
status=YShearImage(rotate_image,shear.y,bounds.width,height,(ssize_t)
(rotate_image->columns-bounds.width)/2,bounds.y,exception);
if (status == MagickFalse)
{
rotate_image=DestroyImage(rotate_image);
return((Image *) NULL);
}
status=XShearImage(rotate_image,shear.x,bounds.width,bounds.height,(ssize_t)
(rotate_image->columns-bounds.width)/2,(ssize_t) (rotate_image->rows-
bounds.height)/2,exception);
if (status == MagickFalse)
{
rotate_image=DestroyImage(rotate_image);
return((Image *) NULL);
}
status=CropToFitImage(&rotate_image,shear.x,shear.y,(MagickRealType) width,
(MagickRealType) height,MagickTrue,exception);
rotate_image->alpha_trait=image->alpha_trait;
rotate_image->compose=image->compose;
rotate_image->page.width=0;
rotate_image->page.height=0;
if (status == MagickFalse)
rotate_image=DestroyImage(rotate_image);
return(rotate_image);
}
|
Parallelizer.h | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_PARALLELIZER_H
#define EIGEN_PARALLELIZER_H
namespace Eigen {
namespace internal {
/** \internal */
inline void manage_multi_threading(Action action, int* v)
{
static EIGEN_UNUSED int m_maxThreads = -1;
if(action==SetAction)
{
eigen_internal_assert(v!=0);
m_maxThreads = *v;
}
else if(action==GetAction)
{
eigen_internal_assert(v!=0);
#ifdef EIGEN_HAS_OPENMP
if(m_maxThreads>0)
*v = m_maxThreads;
else
*v = omp_get_max_threads();
#else
*v = 1;
#endif
}
else
{
eigen_internal_assert(false);
}
}
}
/** Must be call first when calling Eigen from multiple threads */
inline void initParallel()
{
int nbt;
internal::manage_multi_threading(GetAction, &nbt);
std::ptrdiff_t l1, l2;
internal::manage_caching_sizes(GetAction, &l1, &l2);
}
/** \returns the max number of threads reserved for Eigen
* \sa setNbThreads */
inline int nbThreads()
{
int ret;
internal::manage_multi_threading(GetAction, &ret);
return ret;
}
/** Sets the max number of threads reserved for Eigen
* \sa nbThreads */
inline void setNbThreads(int v)
{
internal::manage_multi_threading(SetAction, &v);
}
namespace internal {
template<typename Index> struct GemmParallelInfo
{
GemmParallelInfo() : sync(-1), users(0), rhs_start(0), rhs_length(0) {}
int volatile sync;
int volatile users;
Index rhs_start;
Index rhs_length;
};
template<bool Condition, typename Functor, typename Index>
void parallelize_gemm(const Functor& func, Index rows, Index cols, bool transpose)
{
// TODO when EIGEN_USE_BLAS is defined,
// we should still enable OMP for other scalar types
#if !(defined (EIGEN_HAS_OPENMP)) || defined (EIGEN_USE_BLAS)
// FIXME the transpose variable is only needed to properly split
// the matrix product when multithreading is enabled. This is a temporary
// fix to support row-major destination matrices. This whole
// parallelizer mechanism has to be redisigned anyway.
EIGEN_UNUSED_VARIABLE(transpose);
func(0,rows, 0,cols);
#else
// Dynamically check whether we should enable or disable OpenMP.
// The conditions are:
// - the max number of threads we can create is greater than 1
// - we are not already in a parallel code
// - the sizes are large enough
// 1- are we already in a parallel session?
// FIXME omp_get_num_threads()>1 only works for openmp, what if the user does not use openmp?
if((!Condition) || (omp_get_num_threads()>1))
return func(0,rows, 0,cols);
Index size = transpose ? cols : rows;
// 2- compute the maximal number of threads from the size of the product:
// FIXME this has to be fine tuned
Index max_threads = std::max<Index>(1,size / 32);
// 3 - compute the number of threads we are going to use
int threads = std::min<Index>(nbThreads(), max_threads);
if(threads==1)
return func(0,rows, 0,cols);
Eigen::initParallel();
func.initParallelSession();
if(transpose)
std::swap(rows,cols);
GemmParallelInfo<Index>* info = new GemmParallelInfo<Index>[threads];
#pragma omp parallel num_threads(threads)
{
Index i = omp_get_thread_num();
// Note that the actual number of threads might be lower than the number of request ones.
Index actual_threads = omp_get_num_threads();
Index blockCols = (cols / actual_threads) & ~Index(0x3);
Index blockRows = (rows / actual_threads) & ~Index(0x7);
Index r0 = i*blockRows;
Index actualBlockRows = (i+1==actual_threads) ? rows-r0 : blockRows;
Index c0 = i*blockCols;
Index actualBlockCols = (i+1==actual_threads) ? cols-c0 : blockCols;
info[i].rhs_start = c0;
info[i].rhs_length = actualBlockCols;
if(transpose)
func(0, cols, r0, actualBlockRows, info);
else
func(r0, actualBlockRows, 0,cols, info);
}
delete[] info;
#endif
}
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_PARALLELIZER_H
|
simd-1.c | /* { dg-do run } */
/* { dg-additional-options "-msse2" { target sse2_runtime } } */
/* { dg-additional-options "-mavx" { target avx_runtime } } */
#define N 100
#define OFF 32
#define EPS 0.0000000000000001
#include <stdlib.h>
void init(double *a, double *a_ref, double *b, double *c, int n, int ioff)
{
int i;
for ( i = 0; i < n; i++ )
{
a[i] = i*i;
a_ref[i] = a[i];
b[i] = i+i;
}
int s = -1;
for ( i = 0; i < n+ioff; i++ )
{
c[i] = s*3;
s = -s;
}
}
void star( double *a, double *b, double *c, int n, int *ioff )
{
int i;
#pragma omp simd
for ( i = 0; i < n; i++ )
a[i] *= b[i] * c[i+ *ioff];
}
void star_ref( double *a, double *b, double *c, int n, int *ioff )
{
int i;
for ( i = 0; i < n; i++ )
a[i] *= b[i] * c[i+ *ioff];
}
void check (double *a, double *b)
{
int i;
for (i = 0; i < N; i++)
if (a[i] - b[i] > EPS || b[i] - a[i] > EPS)
abort ();
}
int main ()
{
double a[N], a_ref[N], b[N], c[N+OFF];
int ioff = OFF;
init(a, a_ref, b, c, N, ioff);
star(a, b, c, N, &ioff);
star_ref(a_ref, b, c, N, &ioff);
check(a, a_ref);
return 0;
}
|
nqueenspre.c | # 1 "nqueens.c"
# 1 "<built-in>" 1
# 1 "<built-in>" 3
# 330 "<built-in>" 3
# 1 "<command line>" 1
# 1 "<built-in>" 2
# 1 "nqueens.c" 2
# 28 "nqueens.c"
# 1 "/usr/include/stdlib.h" 1 3 4
# 24 "/usr/include/stdlib.h" 3 4
# 1 "/usr/include/features.h" 1 3 4
# 345 "/usr/include/features.h" 3 4
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 346 "/usr/include/features.h" 2 3 4
# 367 "/usr/include/features.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 1 3 4
# 410 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/wordsize.h" 1 3 4
# 411 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 2 3 4
# 368 "/usr/include/features.h" 2 3 4
# 391 "/usr/include/features.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/gnu/stubs.h" 1 3 4
# 10 "/usr/include/x86_64-linux-gnu/gnu/stubs.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/gnu/stubs-64.h" 1 3 4
# 11 "/usr/include/x86_64-linux-gnu/gnu/stubs.h" 2 3 4
# 392 "/usr/include/features.h" 2 3 4
# 25 "/usr/include/stdlib.h" 2 3 4
# 1 "/home/nader/llvm-omp/lib/clang/5.0.1/include/stddef.h" 1 3 4
# 62 "/home/nader/llvm-omp/lib/clang/5.0.1/include/stddef.h" 3 4
typedef long unsigned int size_t;
# 90 "/home/nader/llvm-omp/lib/clang/5.0.1/include/stddef.h" 3 4
typedef int wchar_t;
# 33 "/usr/include/stdlib.h" 2 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/waitflags.h" 1 3 4
# 50 "/usr/include/x86_64-linux-gnu/bits/waitflags.h" 3 4
typedef enum
{
P_ALL,
P_PID,
P_PGID
} idtype_t;
# 42 "/usr/include/stdlib.h" 2 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/waitstatus.h" 1 3 4
# 64 "/usr/include/x86_64-linux-gnu/bits/waitstatus.h" 3 4
# 1 "/usr/include/endian.h" 1 3 4
# 36 "/usr/include/endian.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/endian.h" 1 3 4
# 37 "/usr/include/endian.h" 2 3 4
# 60 "/usr/include/endian.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/byteswap.h" 1 3 4
# 27 "/usr/include/x86_64-linux-gnu/bits/byteswap.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/types.h" 1 3 4
# 27 "/usr/include/x86_64-linux-gnu/bits/types.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/wordsize.h" 1 3 4
# 28 "/usr/include/x86_64-linux-gnu/bits/types.h" 2 3 4
typedef unsigned char __u_char;
typedef unsigned short int __u_short;
typedef unsigned int __u_int;
typedef unsigned long int __u_long;
typedef signed char __int8_t;
typedef unsigned char __uint8_t;
typedef signed short int __int16_t;
typedef unsigned short int __uint16_t;
typedef signed int __int32_t;
typedef unsigned int __uint32_t;
typedef signed long int __int64_t;
typedef unsigned long int __uint64_t;
typedef long int __quad_t;
typedef unsigned long int __u_quad_t;
# 121 "/usr/include/x86_64-linux-gnu/bits/types.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/typesizes.h" 1 3 4
# 122 "/usr/include/x86_64-linux-gnu/bits/types.h" 2 3 4
typedef unsigned long int __dev_t;
typedef unsigned int __uid_t;
typedef unsigned int __gid_t;
typedef unsigned long int __ino_t;
typedef unsigned long int __ino64_t;
typedef unsigned int __mode_t;
typedef unsigned long int __nlink_t;
typedef long int __off_t;
typedef long int __off64_t;
typedef int __pid_t;
typedef struct { int __val[2]; } __fsid_t;
typedef long int __clock_t;
typedef unsigned long int __rlim_t;
typedef unsigned long int __rlim64_t;
typedef unsigned int __id_t;
typedef long int __time_t;
typedef unsigned int __useconds_t;
typedef long int __suseconds_t;
typedef int __daddr_t;
typedef int __key_t;
typedef int __clockid_t;
typedef void * __timer_t;
typedef long int __blksize_t;
typedef long int __blkcnt_t;
typedef long int __blkcnt64_t;
typedef unsigned long int __fsblkcnt_t;
typedef unsigned long int __fsblkcnt64_t;
typedef unsigned long int __fsfilcnt_t;
typedef unsigned long int __fsfilcnt64_t;
typedef long int __fsword_t;
typedef long int __ssize_t;
typedef long int __syscall_slong_t;
typedef unsigned long int __syscall_ulong_t;
typedef __off64_t __loff_t;
typedef __quad_t *__qaddr_t;
typedef char *__caddr_t;
typedef long int __intptr_t;
typedef unsigned int __socklen_t;
# 28 "/usr/include/x86_64-linux-gnu/bits/byteswap.h" 2 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/wordsize.h" 1 3 4
# 29 "/usr/include/x86_64-linux-gnu/bits/byteswap.h" 2 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/byteswap-16.h" 1 3 4
# 36 "/usr/include/x86_64-linux-gnu/bits/byteswap.h" 2 3 4
# 61 "/usr/include/endian.h" 2 3 4
# 65 "/usr/include/x86_64-linux-gnu/bits/waitstatus.h" 2 3 4
union wait
{
int w_status;
struct
{
unsigned int __w_termsig:7;
unsigned int __w_coredump:1;
unsigned int __w_retcode:8;
unsigned int:16;
} __wait_terminated;
struct
{
unsigned int __w_stopval:8;
unsigned int __w_stopsig:8;
unsigned int:16;
} __wait_stopped;
};
# 43 "/usr/include/stdlib.h" 2 3 4
# 67 "/usr/include/stdlib.h" 3 4
typedef union
{
union wait *__uptr;
int *__iptr;
} __WAIT_STATUS __attribute__ ((__transparent_union__));
# 97 "/usr/include/stdlib.h" 3 4
typedef struct
{
int quot;
int rem;
} div_t;
typedef struct
{
long int quot;
long int rem;
} ldiv_t;
__extension__ typedef struct
{
long long int quot;
long long int rem;
} lldiv_t;
# 139 "/usr/include/stdlib.h" 3 4
extern size_t __ctype_get_mb_cur_max (void) __attribute__ ((__nothrow__ )) ;
extern double atof (const char *__nptr)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1))) ;
extern int atoi (const char *__nptr)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1))) ;
extern long int atol (const char *__nptr)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1))) ;
__extension__ extern long long int atoll (const char *__nptr)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1))) ;
extern double strtod (const char *__restrict __nptr,
char **__restrict __endptr)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
extern float strtof (const char *__restrict __nptr,
char **__restrict __endptr) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
extern long double strtold (const char *__restrict __nptr,
char **__restrict __endptr)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
extern long int strtol (const char *__restrict __nptr,
char **__restrict __endptr, int __base)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
extern unsigned long int strtoul (const char *__restrict __nptr,
char **__restrict __endptr, int __base)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
__extension__
extern long long int strtoq (const char *__restrict __nptr,
char **__restrict __endptr, int __base)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
__extension__
extern unsigned long long int strtouq (const char *__restrict __nptr,
char **__restrict __endptr, int __base)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
__extension__
extern long long int strtoll (const char *__restrict __nptr,
char **__restrict __endptr, int __base)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
__extension__
extern unsigned long long int strtoull (const char *__restrict __nptr,
char **__restrict __endptr, int __base)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
# 277 "/usr/include/stdlib.h" 3 4
extern __inline __attribute__ ((__gnu_inline__)) int
__attribute__ ((__nothrow__ )) atoi (const char *__nptr)
{
return (int) strtol (__nptr, (char **) ((void*)0), 10);
}
extern __inline __attribute__ ((__gnu_inline__)) long int
__attribute__ ((__nothrow__ )) atol (const char *__nptr)
{
return strtol (__nptr, (char **) ((void*)0), 10);
}
__extension__ extern __inline __attribute__ ((__gnu_inline__)) long long int
__attribute__ ((__nothrow__ )) atoll (const char *__nptr)
{
return strtoll (__nptr, (char **) ((void*)0), 10);
}
# 305 "/usr/include/stdlib.h" 3 4
extern char *l64a (long int __n) __attribute__ ((__nothrow__ )) ;
extern long int a64l (const char *__s)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1))) ;
# 1 "/usr/include/x86_64-linux-gnu/sys/types.h" 1 3 4
# 33 "/usr/include/x86_64-linux-gnu/sys/types.h" 3 4
typedef __u_char u_char;
typedef __u_short u_short;
typedef __u_int u_int;
typedef __u_long u_long;
typedef __quad_t quad_t;
typedef __u_quad_t u_quad_t;
typedef __fsid_t fsid_t;
typedef __loff_t loff_t;
typedef __ino_t ino_t;
# 60 "/usr/include/x86_64-linux-gnu/sys/types.h" 3 4
typedef __dev_t dev_t;
typedef __gid_t gid_t;
typedef __mode_t mode_t;
typedef __nlink_t nlink_t;
typedef __uid_t uid_t;
typedef __off_t off_t;
# 98 "/usr/include/x86_64-linux-gnu/sys/types.h" 3 4
typedef __pid_t pid_t;
typedef __id_t id_t;
typedef __ssize_t ssize_t;
typedef __daddr_t daddr_t;
typedef __caddr_t caddr_t;
typedef __key_t key_t;
# 132 "/usr/include/x86_64-linux-gnu/sys/types.h" 3 4
# 1 "/usr/include/time.h" 1 3 4
# 59 "/usr/include/time.h" 3 4
typedef __clock_t clock_t;
# 75 "/usr/include/time.h" 3 4
typedef __time_t time_t;
# 91 "/usr/include/time.h" 3 4
typedef __clockid_t clockid_t;
# 103 "/usr/include/time.h" 3 4
typedef __timer_t timer_t;
# 133 "/usr/include/x86_64-linux-gnu/sys/types.h" 2 3 4
# 146 "/usr/include/x86_64-linux-gnu/sys/types.h" 3 4
# 1 "/home/nader/llvm-omp/lib/clang/5.0.1/include/stddef.h" 1 3 4
# 147 "/usr/include/x86_64-linux-gnu/sys/types.h" 2 3 4
typedef unsigned long int ulong;
typedef unsigned short int ushort;
typedef unsigned int uint;
# 194 "/usr/include/x86_64-linux-gnu/sys/types.h" 3 4
typedef int int8_t __attribute__ ((__mode__ (__QI__)));
typedef int int16_t __attribute__ ((__mode__ (__HI__)));
typedef int int32_t __attribute__ ((__mode__ (__SI__)));
typedef int int64_t __attribute__ ((__mode__ (__DI__)));
typedef unsigned int u_int8_t __attribute__ ((__mode__ (__QI__)));
typedef unsigned int u_int16_t __attribute__ ((__mode__ (__HI__)));
typedef unsigned int u_int32_t __attribute__ ((__mode__ (__SI__)));
typedef unsigned int u_int64_t __attribute__ ((__mode__ (__DI__)));
typedef int register_t __attribute__ ((__mode__ (__word__)));
# 219 "/usr/include/x86_64-linux-gnu/sys/types.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/sys/select.h" 1 3 4
# 30 "/usr/include/x86_64-linux-gnu/sys/select.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/select.h" 1 3 4
# 22 "/usr/include/x86_64-linux-gnu/bits/select.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/wordsize.h" 1 3 4
# 23 "/usr/include/x86_64-linux-gnu/bits/select.h" 2 3 4
# 31 "/usr/include/x86_64-linux-gnu/sys/select.h" 2 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/sigset.h" 1 3 4
# 22 "/usr/include/x86_64-linux-gnu/bits/sigset.h" 3 4
typedef int __sig_atomic_t;
typedef struct
{
unsigned long int __val[(1024 / (8 * sizeof (unsigned long int)))];
} __sigset_t;
# 34 "/usr/include/x86_64-linux-gnu/sys/select.h" 2 3 4
typedef __sigset_t sigset_t;
# 1 "/usr/include/time.h" 1 3 4
# 120 "/usr/include/time.h" 3 4
struct timespec
{
__time_t tv_sec;
__syscall_slong_t tv_nsec;
};
# 44 "/usr/include/x86_64-linux-gnu/sys/select.h" 2 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/time.h" 1 3 4
# 30 "/usr/include/x86_64-linux-gnu/bits/time.h" 3 4
struct timeval
{
__time_t tv_sec;
__suseconds_t tv_usec;
};
# 46 "/usr/include/x86_64-linux-gnu/sys/select.h" 2 3 4
typedef __suseconds_t suseconds_t;
typedef long int __fd_mask;
# 64 "/usr/include/x86_64-linux-gnu/sys/select.h" 3 4
typedef struct
{
__fd_mask __fds_bits[1024 / (8 * (int) sizeof (__fd_mask))];
} fd_set;
typedef __fd_mask fd_mask;
# 106 "/usr/include/x86_64-linux-gnu/sys/select.h" 3 4
extern int select (int __nfds, fd_set *__restrict __readfds,
fd_set *__restrict __writefds,
fd_set *__restrict __exceptfds,
struct timeval *__restrict __timeout);
# 118 "/usr/include/x86_64-linux-gnu/sys/select.h" 3 4
extern int pselect (int __nfds, fd_set *__restrict __readfds,
fd_set *__restrict __writefds,
fd_set *__restrict __exceptfds,
const struct timespec *__restrict __timeout,
const __sigset_t *__restrict __sigmask);
# 220 "/usr/include/x86_64-linux-gnu/sys/types.h" 2 3 4
# 1 "/usr/include/x86_64-linux-gnu/sys/sysmacros.h" 1 3 4
# 26 "/usr/include/x86_64-linux-gnu/sys/sysmacros.h" 3 4
__extension__
extern unsigned int gnu_dev_major (unsigned long long int __dev)
__attribute__ ((__nothrow__ )) __attribute__ ((__const__));
__extension__
extern unsigned int gnu_dev_minor (unsigned long long int __dev)
__attribute__ ((__nothrow__ )) __attribute__ ((__const__));
__extension__
extern unsigned long long int gnu_dev_makedev (unsigned int __major,
unsigned int __minor)
__attribute__ ((__nothrow__ )) __attribute__ ((__const__));
__extension__ extern __inline __attribute__ ((__gnu_inline__)) __attribute__ ((__const__)) unsigned int
__attribute__ ((__nothrow__ )) gnu_dev_major (unsigned long long int __dev)
{
return ((__dev >> 8) & 0xfff) | ((unsigned int) (__dev >> 32) & ~0xfff);
}
__extension__ extern __inline __attribute__ ((__gnu_inline__)) __attribute__ ((__const__)) unsigned int
__attribute__ ((__nothrow__ )) gnu_dev_minor (unsigned long long int __dev)
{
return (__dev & 0xff) | ((unsigned int) (__dev >> 12) & ~0xff);
}
__extension__ extern __inline __attribute__ ((__gnu_inline__)) __attribute__ ((__const__)) unsigned long long int
__attribute__ ((__nothrow__ )) gnu_dev_makedev (unsigned int __major, unsigned int __minor)
{
return ((__minor & 0xff) | ((__major & 0xfff) << 8)
| (((unsigned long long int) (__minor & ~0xff)) << 12)
| (((unsigned long long int) (__major & ~0xfff)) << 32));
}
# 223 "/usr/include/x86_64-linux-gnu/sys/types.h" 2 3 4
typedef __blksize_t blksize_t;
typedef __blkcnt_t blkcnt_t;
typedef __fsblkcnt_t fsblkcnt_t;
typedef __fsfilcnt_t fsfilcnt_t;
# 270 "/usr/include/x86_64-linux-gnu/sys/types.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/pthreadtypes.h" 1 3 4
# 21 "/usr/include/x86_64-linux-gnu/bits/pthreadtypes.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/wordsize.h" 1 3 4
# 22 "/usr/include/x86_64-linux-gnu/bits/pthreadtypes.h" 2 3 4
# 60 "/usr/include/x86_64-linux-gnu/bits/pthreadtypes.h" 3 4
typedef unsigned long int pthread_t;
union pthread_attr_t
{
char __size[56];
long int __align;
};
typedef union pthread_attr_t pthread_attr_t;
typedef struct __pthread_internal_list
{
struct __pthread_internal_list *__prev;
struct __pthread_internal_list *__next;
} __pthread_list_t;
# 90 "/usr/include/x86_64-linux-gnu/bits/pthreadtypes.h" 3 4
typedef union
{
struct __pthread_mutex_s
{
int __lock;
unsigned int __count;
int __owner;
unsigned int __nusers;
int __kind;
short __spins;
short __elision;
__pthread_list_t __list;
# 125 "/usr/include/x86_64-linux-gnu/bits/pthreadtypes.h" 3 4
} __data;
char __size[40];
long int __align;
} pthread_mutex_t;
typedef union
{
char __size[4];
int __align;
} pthread_mutexattr_t;
typedef union
{
struct
{
int __lock;
unsigned int __futex;
__extension__ unsigned long long int __total_seq;
__extension__ unsigned long long int __wakeup_seq;
__extension__ unsigned long long int __woken_seq;
void *__mutex;
unsigned int __nwaiters;
unsigned int __broadcast_seq;
} __data;
char __size[48];
__extension__ long long int __align;
} pthread_cond_t;
typedef union
{
char __size[4];
int __align;
} pthread_condattr_t;
typedef unsigned int pthread_key_t;
typedef int pthread_once_t;
typedef union
{
struct
{
int __lock;
unsigned int __nr_readers;
unsigned int __readers_wakeup;
unsigned int __writer_wakeup;
unsigned int __nr_readers_queued;
unsigned int __nr_writers_queued;
int __writer;
int __shared;
signed char __rwelision;
unsigned char __pad1[7];
unsigned long int __pad2;
unsigned int __flags;
} __data;
# 220 "/usr/include/x86_64-linux-gnu/bits/pthreadtypes.h" 3 4
char __size[56];
long int __align;
} pthread_rwlock_t;
typedef union
{
char __size[8];
long int __align;
} pthread_rwlockattr_t;
typedef volatile int pthread_spinlock_t;
typedef union
{
char __size[32];
long int __align;
} pthread_barrier_t;
typedef union
{
char __size[4];
int __align;
} pthread_barrierattr_t;
# 271 "/usr/include/x86_64-linux-gnu/sys/types.h" 2 3 4
# 315 "/usr/include/stdlib.h" 2 3 4
extern long int random (void) __attribute__ ((__nothrow__ ));
extern void srandom (unsigned int __seed) __attribute__ ((__nothrow__ ));
extern char *initstate (unsigned int __seed, char *__statebuf,
size_t __statelen) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (2)));
extern char *setstate (char *__statebuf) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
struct random_data
{
int32_t *fptr;
int32_t *rptr;
int32_t *state;
int rand_type;
int rand_deg;
int rand_sep;
int32_t *end_ptr;
};
extern int random_r (struct random_data *__restrict __buf,
int32_t *__restrict __result) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
extern int srandom_r (unsigned int __seed, struct random_data *__buf)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (2)));
extern int initstate_r (unsigned int __seed, char *__restrict __statebuf,
size_t __statelen,
struct random_data *__restrict __buf)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (2, 4)));
extern int setstate_r (char *__restrict __statebuf,
struct random_data *__restrict __buf)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
extern int rand (void) __attribute__ ((__nothrow__ ));
extern void srand (unsigned int __seed) __attribute__ ((__nothrow__ ));
extern int rand_r (unsigned int *__seed) __attribute__ ((__nothrow__ ));
extern double drand48 (void) __attribute__ ((__nothrow__ ));
extern double erand48 (unsigned short int __xsubi[3]) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
extern long int lrand48 (void) __attribute__ ((__nothrow__ ));
extern long int nrand48 (unsigned short int __xsubi[3])
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
extern long int mrand48 (void) __attribute__ ((__nothrow__ ));
extern long int jrand48 (unsigned short int __xsubi[3])
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
extern void srand48 (long int __seedval) __attribute__ ((__nothrow__ ));
extern unsigned short int *seed48 (unsigned short int __seed16v[3])
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
extern void lcong48 (unsigned short int __param[7]) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
struct drand48_data
{
unsigned short int __x[3];
unsigned short int __old_x[3];
unsigned short int __c;
unsigned short int __init;
__extension__ unsigned long long int __a;
};
extern int drand48_r (struct drand48_data *__restrict __buffer,
double *__restrict __result) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
extern int erand48_r (unsigned short int __xsubi[3],
struct drand48_data *__restrict __buffer,
double *__restrict __result) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
extern int lrand48_r (struct drand48_data *__restrict __buffer,
long int *__restrict __result)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
extern int nrand48_r (unsigned short int __xsubi[3],
struct drand48_data *__restrict __buffer,
long int *__restrict __result)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
extern int mrand48_r (struct drand48_data *__restrict __buffer,
long int *__restrict __result)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
extern int jrand48_r (unsigned short int __xsubi[3],
struct drand48_data *__restrict __buffer,
long int *__restrict __result)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
extern int srand48_r (long int __seedval, struct drand48_data *__buffer)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (2)));
extern int seed48_r (unsigned short int __seed16v[3],
struct drand48_data *__buffer) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
extern int lcong48_r (unsigned short int __param[7],
struct drand48_data *__buffer)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
# 466 "/usr/include/stdlib.h" 3 4
extern void *malloc (size_t __size) __attribute__ ((__nothrow__ )) __attribute__ ((__malloc__)) ;
extern void *calloc (size_t __nmemb, size_t __size)
__attribute__ ((__nothrow__ )) __attribute__ ((__malloc__)) ;
# 480 "/usr/include/stdlib.h" 3 4
extern void *realloc (void *__ptr, size_t __size)
__attribute__ ((__nothrow__ )) __attribute__ ((__warn_unused_result__));
extern void free (void *__ptr) __attribute__ ((__nothrow__ ));
extern void cfree (void *__ptr) __attribute__ ((__nothrow__ ));
# 1 "/usr/include/alloca.h" 1 3 4
# 24 "/usr/include/alloca.h" 3 4
# 1 "/home/nader/llvm-omp/lib/clang/5.0.1/include/stddef.h" 1 3 4
# 25 "/usr/include/alloca.h" 2 3 4
extern void *alloca (size_t __size) __attribute__ ((__nothrow__ ));
# 493 "/usr/include/stdlib.h" 2 3 4
extern void *valloc (size_t __size) __attribute__ ((__nothrow__ )) __attribute__ ((__malloc__)) ;
extern int posix_memalign (void **__memptr, size_t __alignment, size_t __size)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1))) ;
extern void *aligned_alloc (size_t __alignment, size_t __size)
__attribute__ ((__nothrow__ )) __attribute__ ((__malloc__)) ;
extern void abort (void) __attribute__ ((__nothrow__ )) __attribute__ ((__noreturn__));
extern int atexit (void (*__func) (void)) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
extern int at_quick_exit (void (*__func) (void)) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
extern int on_exit (void (*__func) (int __status, void *__arg), void *__arg)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
extern void exit (int __status) __attribute__ ((__nothrow__ )) __attribute__ ((__noreturn__));
extern void quick_exit (int __status) __attribute__ ((__nothrow__ )) __attribute__ ((__noreturn__));
extern void _Exit (int __status) __attribute__ ((__nothrow__ )) __attribute__ ((__noreturn__));
extern char *getenv (const char *__name) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1))) ;
# 578 "/usr/include/stdlib.h" 3 4
extern int putenv (char *__string) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
extern int setenv (const char *__name, const char *__value, int __replace)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (2)));
extern int unsetenv (const char *__name) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
extern int clearenv (void) __attribute__ ((__nothrow__ ));
# 606 "/usr/include/stdlib.h" 3 4
extern char *mktemp (char *__template) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
# 619 "/usr/include/stdlib.h" 3 4
extern int mkstemp (char *__template) __attribute__ ((__nonnull__ (1))) ;
# 641 "/usr/include/stdlib.h" 3 4
extern int mkstemps (char *__template, int __suffixlen) __attribute__ ((__nonnull__ (1))) ;
# 662 "/usr/include/stdlib.h" 3 4
extern char *mkdtemp (char *__template) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1))) ;
# 716 "/usr/include/stdlib.h" 3 4
extern int system (const char *__command) ;
# 733 "/usr/include/stdlib.h" 3 4
extern char *realpath (const char *__restrict __name,
char *__restrict __resolved) __attribute__ ((__nothrow__ )) ;
typedef int (*__compar_fn_t) (const void *, const void *);
# 754 "/usr/include/stdlib.h" 3 4
extern void *bsearch (const void *__key, const void *__base,
size_t __nmemb, size_t __size, __compar_fn_t __compar)
__attribute__ ((__nonnull__ (1, 2, 5))) ;
# 1 "/usr/include/x86_64-linux-gnu/bits/stdlib-bsearch.h" 1 3 4
# 19 "/usr/include/x86_64-linux-gnu/bits/stdlib-bsearch.h" 3 4
extern __inline __attribute__ ((__gnu_inline__)) void *
bsearch (const void *__key, const void *__base, size_t __nmemb, size_t __size,
__compar_fn_t __compar)
{
size_t __l, __u, __idx;
const void *__p;
int __comparison;
__l = 0;
__u = __nmemb;
while (__l < __u)
{
__idx = (__l + __u) / 2;
__p = (void *) (((const char *) __base) + (__idx * __size));
__comparison = (*__compar) (__key, __p);
if (__comparison < 0)
__u = __idx;
else if (__comparison > 0)
__l = __idx + 1;
else
return (void *) __p;
}
return ((void*)0);
}
# 760 "/usr/include/stdlib.h" 2 3 4
extern void qsort (void *__base, size_t __nmemb, size_t __size,
__compar_fn_t __compar) __attribute__ ((__nonnull__ (1, 4)));
# 774 "/usr/include/stdlib.h" 3 4
extern int abs (int __x) __attribute__ ((__nothrow__ )) __attribute__ ((__const__)) ;
extern long int labs (long int __x) __attribute__ ((__nothrow__ )) __attribute__ ((__const__)) ;
__extension__ extern long long int llabs (long long int __x)
__attribute__ ((__nothrow__ )) __attribute__ ((__const__)) ;
extern div_t div (int __numer, int __denom)
__attribute__ ((__nothrow__ )) __attribute__ ((__const__)) ;
extern ldiv_t ldiv (long int __numer, long int __denom)
__attribute__ ((__nothrow__ )) __attribute__ ((__const__)) ;
__extension__ extern lldiv_t lldiv (long long int __numer,
long long int __denom)
__attribute__ ((__nothrow__ )) __attribute__ ((__const__)) ;
# 811 "/usr/include/stdlib.h" 3 4
extern char *ecvt (double __value, int __ndigit, int *__restrict __decpt,
int *__restrict __sign) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (3, 4))) ;
extern char *fcvt (double __value, int __ndigit, int *__restrict __decpt,
int *__restrict __sign) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (3, 4))) ;
extern char *gcvt (double __value, int __ndigit, char *__buf)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (3))) ;
extern char *qecvt (long double __value, int __ndigit,
int *__restrict __decpt, int *__restrict __sign)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (3, 4))) ;
extern char *qfcvt (long double __value, int __ndigit,
int *__restrict __decpt, int *__restrict __sign)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (3, 4))) ;
extern char *qgcvt (long double __value, int __ndigit, char *__buf)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (3))) ;
extern int ecvt_r (double __value, int __ndigit, int *__restrict __decpt,
int *__restrict __sign, char *__restrict __buf,
size_t __len) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (3, 4, 5)));
extern int fcvt_r (double __value, int __ndigit, int *__restrict __decpt,
int *__restrict __sign, char *__restrict __buf,
size_t __len) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (3, 4, 5)));
extern int qecvt_r (long double __value, int __ndigit,
int *__restrict __decpt, int *__restrict __sign,
char *__restrict __buf, size_t __len)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (3, 4, 5)));
extern int qfcvt_r (long double __value, int __ndigit,
int *__restrict __decpt, int *__restrict __sign,
char *__restrict __buf, size_t __len)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (3, 4, 5)));
extern int mblen (const char *__s, size_t __n) __attribute__ ((__nothrow__ ));
extern int mbtowc (wchar_t *__restrict __pwc,
const char *__restrict __s, size_t __n) __attribute__ ((__nothrow__ ));
extern int wctomb (char *__s, wchar_t __wchar) __attribute__ ((__nothrow__ ));
extern size_t mbstowcs (wchar_t *__restrict __pwcs,
const char *__restrict __s, size_t __n) __attribute__ ((__nothrow__ ));
extern size_t wcstombs (char *__restrict __s,
const wchar_t *__restrict __pwcs, size_t __n)
__attribute__ ((__nothrow__ ));
# 887 "/usr/include/stdlib.h" 3 4
extern int rpmatch (const char *__response) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1))) ;
# 898 "/usr/include/stdlib.h" 3 4
extern int getsubopt (char **__restrict __optionp,
char *const *__restrict __tokens,
char **__restrict __valuep)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2, 3))) ;
# 950 "/usr/include/stdlib.h" 3 4
extern int getloadavg (double __loadavg[], int __nelem)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
# 1 "/usr/include/x86_64-linux-gnu/bits/stdlib-float.h" 1 3 4
# 25 "/usr/include/x86_64-linux-gnu/bits/stdlib-float.h" 3 4
extern __inline __attribute__ ((__gnu_inline__)) double
__attribute__ ((__nothrow__ )) atof (const char *__nptr)
{
return strtod (__nptr, (char **) ((void*)0));
}
# 955 "/usr/include/stdlib.h" 2 3 4
# 29 "nqueens.c" 2
# 1 "/usr/include/stdio.h" 1 3 4
# 33 "/usr/include/stdio.h" 3 4
# 1 "/home/nader/llvm-omp/lib/clang/5.0.1/include/stddef.h" 1 3 4
# 34 "/usr/include/stdio.h" 2 3 4
# 44 "/usr/include/stdio.h" 3 4
struct _IO_FILE;
typedef struct _IO_FILE FILE;
# 64 "/usr/include/stdio.h" 3 4
typedef struct _IO_FILE __FILE;
# 74 "/usr/include/stdio.h" 3 4
# 1 "/usr/include/libio.h" 1 3 4
# 31 "/usr/include/libio.h" 3 4
# 1 "/usr/include/_G_config.h" 1 3 4
# 15 "/usr/include/_G_config.h" 3 4
# 1 "/home/nader/llvm-omp/lib/clang/5.0.1/include/stddef.h" 1 3 4
# 16 "/usr/include/_G_config.h" 2 3 4
# 1 "/usr/include/wchar.h" 1 3 4
# 82 "/usr/include/wchar.h" 3 4
typedef struct
{
int __count;
union
{
unsigned int __wch;
char __wchb[4];
} __value;
} __mbstate_t;
# 21 "/usr/include/_G_config.h" 2 3 4
typedef struct
{
__off_t __pos;
__mbstate_t __state;
} _G_fpos_t;
typedef struct
{
__off64_t __pos;
__mbstate_t __state;
} _G_fpos64_t;
# 32 "/usr/include/libio.h" 2 3 4
# 49 "/usr/include/libio.h" 3 4
# 1 "/home/nader/llvm-omp/lib/clang/5.0.1/include/stdarg.h" 1 3 4
# 30 "/home/nader/llvm-omp/lib/clang/5.0.1/include/stdarg.h" 3 4
typedef __builtin_va_list va_list;
# 48 "/home/nader/llvm-omp/lib/clang/5.0.1/include/stdarg.h" 3 4
typedef __builtin_va_list __gnuc_va_list;
# 50 "/usr/include/libio.h" 2 3 4
# 144 "/usr/include/libio.h" 3 4
struct _IO_jump_t; struct _IO_FILE;
typedef void _IO_lock_t;
struct _IO_marker {
struct _IO_marker *_next;
struct _IO_FILE *_sbuf;
int _pos;
# 173 "/usr/include/libio.h" 3 4
};
enum __codecvt_result
{
__codecvt_ok,
__codecvt_partial,
__codecvt_error,
__codecvt_noconv
};
# 241 "/usr/include/libio.h" 3 4
struct _IO_FILE {
int _flags;
char* _IO_read_ptr;
char* _IO_read_end;
char* _IO_read_base;
char* _IO_write_base;
char* _IO_write_ptr;
char* _IO_write_end;
char* _IO_buf_base;
char* _IO_buf_end;
char *_IO_save_base;
char *_IO_backup_base;
char *_IO_save_end;
struct _IO_marker *_markers;
struct _IO_FILE *_chain;
int _fileno;
int _flags2;
__off_t _old_offset;
unsigned short _cur_column;
signed char _vtable_offset;
char _shortbuf[1];
_IO_lock_t *_lock;
# 289 "/usr/include/libio.h" 3 4
__off64_t _offset;
void *__pad1;
void *__pad2;
void *__pad3;
void *__pad4;
size_t __pad5;
int _mode;
char _unused2[15 * sizeof (int) - 4 * sizeof (void *) - sizeof (size_t)];
};
typedef struct _IO_FILE _IO_FILE;
struct _IO_FILE_plus;
extern struct _IO_FILE_plus _IO_2_1_stdin_;
extern struct _IO_FILE_plus _IO_2_1_stdout_;
extern struct _IO_FILE_plus _IO_2_1_stderr_;
# 333 "/usr/include/libio.h" 3 4
typedef __ssize_t __io_read_fn (void *__cookie, char *__buf, size_t __nbytes);
typedef __ssize_t __io_write_fn (void *__cookie, const char *__buf,
size_t __n);
typedef int __io_seek_fn (void *__cookie, __off64_t *__pos, int __w);
typedef int __io_close_fn (void *__cookie);
# 385 "/usr/include/libio.h" 3 4
extern int __underflow (_IO_FILE *);
extern int __uflow (_IO_FILE *);
extern int __overflow (_IO_FILE *, int);
# 429 "/usr/include/libio.h" 3 4
extern int _IO_getc (_IO_FILE *__fp);
extern int _IO_putc (int __c, _IO_FILE *__fp);
extern int _IO_feof (_IO_FILE *__fp) __attribute__ ((__nothrow__ ));
extern int _IO_ferror (_IO_FILE *__fp) __attribute__ ((__nothrow__ ));
extern int _IO_peekc_locked (_IO_FILE *__fp);
extern void _IO_flockfile (_IO_FILE *) __attribute__ ((__nothrow__ ));
extern void _IO_funlockfile (_IO_FILE *) __attribute__ ((__nothrow__ ));
extern int _IO_ftrylockfile (_IO_FILE *) __attribute__ ((__nothrow__ ));
# 459 "/usr/include/libio.h" 3 4
extern int _IO_vfscanf (_IO_FILE * __restrict, const char * __restrict,
__gnuc_va_list, int *__restrict);
extern int _IO_vfprintf (_IO_FILE *__restrict, const char *__restrict,
__gnuc_va_list);
extern __ssize_t _IO_padn (_IO_FILE *, int, __ssize_t);
extern size_t _IO_sgetn (_IO_FILE *, void *, size_t);
extern __off64_t _IO_seekoff (_IO_FILE *, __off64_t, int, int);
extern __off64_t _IO_seekpos (_IO_FILE *, __off64_t, int);
extern void _IO_free_backup_area (_IO_FILE *) __attribute__ ((__nothrow__ ));
# 75 "/usr/include/stdio.h" 2 3 4
typedef __gnuc_va_list va_list;
# 110 "/usr/include/stdio.h" 3 4
typedef _G_fpos_t fpos_t;
# 164 "/usr/include/stdio.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/stdio_lim.h" 1 3 4
# 165 "/usr/include/stdio.h" 2 3 4
extern struct _IO_FILE *stdin;
extern struct _IO_FILE *stdout;
extern struct _IO_FILE *stderr;
extern int remove (const char *__filename) __attribute__ ((__nothrow__ ));
extern int rename (const char *__old, const char *__new) __attribute__ ((__nothrow__ ));
extern int renameat (int __oldfd, const char *__old, int __newfd,
const char *__new) __attribute__ ((__nothrow__ ));
# 195 "/usr/include/stdio.h" 3 4
extern FILE *tmpfile (void) ;
# 209 "/usr/include/stdio.h" 3 4
extern char *tmpnam (char *__s) __attribute__ ((__nothrow__ )) ;
extern char *tmpnam_r (char *__s) __attribute__ ((__nothrow__ )) ;
# 227 "/usr/include/stdio.h" 3 4
extern char *tempnam (const char *__dir, const char *__pfx)
__attribute__ ((__nothrow__ )) __attribute__ ((__malloc__)) ;
# 237 "/usr/include/stdio.h" 3 4
extern int fclose (FILE *__stream);
extern int fflush (FILE *__stream);
# 252 "/usr/include/stdio.h" 3 4
extern int fflush_unlocked (FILE *__stream);
# 272 "/usr/include/stdio.h" 3 4
extern FILE *fopen (const char *__restrict __filename,
const char *__restrict __modes) ;
extern FILE *freopen (const char *__restrict __filename,
const char *__restrict __modes,
FILE *__restrict __stream) ;
# 306 "/usr/include/stdio.h" 3 4
extern FILE *fdopen (int __fd, const char *__modes) __attribute__ ((__nothrow__ )) ;
# 319 "/usr/include/stdio.h" 3 4
extern FILE *fmemopen (void *__s, size_t __len, const char *__modes)
__attribute__ ((__nothrow__ )) ;
extern FILE *open_memstream (char **__bufloc, size_t *__sizeloc) __attribute__ ((__nothrow__ )) ;
extern void setbuf (FILE *__restrict __stream, char *__restrict __buf) __attribute__ ((__nothrow__ ));
extern int setvbuf (FILE *__restrict __stream, char *__restrict __buf,
int __modes, size_t __n) __attribute__ ((__nothrow__ ));
extern void setbuffer (FILE *__restrict __stream, char *__restrict __buf,
size_t __size) __attribute__ ((__nothrow__ ));
extern void setlinebuf (FILE *__stream) __attribute__ ((__nothrow__ ));
# 356 "/usr/include/stdio.h" 3 4
extern int fprintf (FILE *__restrict __stream,
const char *__restrict __format, ...);
extern int printf (const char *__restrict __format, ...);
extern int sprintf (char *__restrict __s,
const char *__restrict __format, ...) __attribute__ ((__nothrow__));
extern int vfprintf (FILE *__restrict __s, const char *__restrict __format,
__gnuc_va_list __arg);
extern int vprintf (const char *__restrict __format, __gnuc_va_list __arg);
extern int vsprintf (char *__restrict __s, const char *__restrict __format,
__gnuc_va_list __arg) __attribute__ ((__nothrow__));
extern int snprintf (char *__restrict __s, size_t __maxlen,
const char *__restrict __format, ...)
__attribute__ ((__nothrow__)) __attribute__ ((__format__ (__printf__, 3, 4)));
extern int vsnprintf (char *__restrict __s, size_t __maxlen,
const char *__restrict __format, __gnuc_va_list __arg)
__attribute__ ((__nothrow__)) __attribute__ ((__format__ (__printf__, 3, 0)));
# 412 "/usr/include/stdio.h" 3 4
extern int vdprintf (int __fd, const char *__restrict __fmt,
__gnuc_va_list __arg)
__attribute__ ((__format__ (__printf__, 2, 0)));
extern int dprintf (int __fd, const char *__restrict __fmt, ...)
__attribute__ ((__format__ (__printf__, 2, 3)));
# 425 "/usr/include/stdio.h" 3 4
extern int fscanf (FILE *__restrict __stream,
const char *__restrict __format, ...) ;
extern int scanf (const char *__restrict __format, ...) ;
extern int sscanf (const char *__restrict __s,
const char *__restrict __format, ...) __attribute__ ((__nothrow__ ));
# 443 "/usr/include/stdio.h" 3 4
extern int fscanf (FILE *__restrict __stream, const char *__restrict __format, ...) __asm__ ("" "__isoc99_fscanf") ;
extern int scanf (const char *__restrict __format, ...) __asm__ ("" "__isoc99_scanf") ;
extern int sscanf (const char *__restrict __s, const char *__restrict __format, ...) __asm__ ("" "__isoc99_sscanf") __attribute__ ((__nothrow__ ));
# 471 "/usr/include/stdio.h" 3 4
extern int vfscanf (FILE *__restrict __s, const char *__restrict __format,
__gnuc_va_list __arg)
__attribute__ ((__format__ (__scanf__, 2, 0))) ;
extern int vscanf (const char *__restrict __format, __gnuc_va_list __arg)
__attribute__ ((__format__ (__scanf__, 1, 0))) ;
extern int vsscanf (const char *__restrict __s,
const char *__restrict __format, __gnuc_va_list __arg)
__attribute__ ((__nothrow__ )) __attribute__ ((__format__ (__scanf__, 2, 0)));
# 494 "/usr/include/stdio.h" 3 4
extern int vfscanf (FILE *__restrict __s, const char *__restrict __format, __gnuc_va_list __arg) __asm__ ("" "__isoc99_vfscanf")
__attribute__ ((__format__ (__scanf__, 2, 0))) ;
extern int vscanf (const char *__restrict __format, __gnuc_va_list __arg) __asm__ ("" "__isoc99_vscanf")
__attribute__ ((__format__ (__scanf__, 1, 0))) ;
extern int vsscanf (const char *__restrict __s, const char *__restrict __format, __gnuc_va_list __arg) __asm__ ("" "__isoc99_vsscanf") __attribute__ ((__nothrow__ ))
__attribute__ ((__format__ (__scanf__, 2, 0)));
# 531 "/usr/include/stdio.h" 3 4
extern int fgetc (FILE *__stream);
extern int getc (FILE *__stream);
extern int getchar (void);
# 550 "/usr/include/stdio.h" 3 4
extern int getc_unlocked (FILE *__stream);
extern int getchar_unlocked (void);
# 561 "/usr/include/stdio.h" 3 4
extern int fgetc_unlocked (FILE *__stream);
# 573 "/usr/include/stdio.h" 3 4
extern int fputc (int __c, FILE *__stream);
extern int putc (int __c, FILE *__stream);
extern int putchar (int __c);
# 594 "/usr/include/stdio.h" 3 4
extern int fputc_unlocked (int __c, FILE *__stream);
extern int putc_unlocked (int __c, FILE *__stream);
extern int putchar_unlocked (int __c);
extern int getw (FILE *__stream);
extern int putw (int __w, FILE *__stream);
# 622 "/usr/include/stdio.h" 3 4
extern char *fgets (char *__restrict __s, int __n, FILE *__restrict __stream)
;
# 665 "/usr/include/stdio.h" 3 4
extern __ssize_t __getdelim (char **__restrict __lineptr,
size_t *__restrict __n, int __delimiter,
FILE *__restrict __stream) ;
extern __ssize_t getdelim (char **__restrict __lineptr,
size_t *__restrict __n, int __delimiter,
FILE *__restrict __stream) ;
extern __ssize_t getline (char **__restrict __lineptr,
size_t *__restrict __n,
FILE *__restrict __stream) ;
# 689 "/usr/include/stdio.h" 3 4
extern int fputs (const char *__restrict __s, FILE *__restrict __stream);
extern int puts (const char *__s);
extern int ungetc (int __c, FILE *__stream);
extern size_t fread (void *__restrict __ptr, size_t __size,
size_t __n, FILE *__restrict __stream) ;
extern size_t fwrite (const void *__restrict __ptr, size_t __size,
size_t __n, FILE *__restrict __s);
# 737 "/usr/include/stdio.h" 3 4
extern size_t fread_unlocked (void *__restrict __ptr, size_t __size,
size_t __n, FILE *__restrict __stream) ;
extern size_t fwrite_unlocked (const void *__restrict __ptr, size_t __size,
size_t __n, FILE *__restrict __stream);
# 749 "/usr/include/stdio.h" 3 4
extern int fseek (FILE *__stream, long int __off, int __whence);
extern long int ftell (FILE *__stream) ;
extern void rewind (FILE *__stream);
# 773 "/usr/include/stdio.h" 3 4
extern int fseeko (FILE *__stream, __off_t __off, int __whence);
extern __off_t ftello (FILE *__stream) ;
# 798 "/usr/include/stdio.h" 3 4
extern int fgetpos (FILE *__restrict __stream, fpos_t *__restrict __pos);
extern int fsetpos (FILE *__stream, const fpos_t *__pos);
# 826 "/usr/include/stdio.h" 3 4
extern void clearerr (FILE *__stream) __attribute__ ((__nothrow__ ));
extern int feof (FILE *__stream) __attribute__ ((__nothrow__ )) ;
extern int ferror (FILE *__stream) __attribute__ ((__nothrow__ )) ;
extern void clearerr_unlocked (FILE *__stream) __attribute__ ((__nothrow__ ));
extern int feof_unlocked (FILE *__stream) __attribute__ ((__nothrow__ )) ;
extern int ferror_unlocked (FILE *__stream) __attribute__ ((__nothrow__ )) ;
# 846 "/usr/include/stdio.h" 3 4
extern void perror (const char *__s);
# 1 "/usr/include/x86_64-linux-gnu/bits/sys_errlist.h" 1 3 4
# 26 "/usr/include/x86_64-linux-gnu/bits/sys_errlist.h" 3 4
extern int sys_nerr;
extern const char *const sys_errlist[];
# 854 "/usr/include/stdio.h" 2 3 4
extern int fileno (FILE *__stream) __attribute__ ((__nothrow__ )) ;
extern int fileno_unlocked (FILE *__stream) __attribute__ ((__nothrow__ )) ;
# 872 "/usr/include/stdio.h" 3 4
extern FILE *popen (const char *__command, const char *__modes) ;
extern int pclose (FILE *__stream);
extern char *ctermid (char *__s) __attribute__ ((__nothrow__ ));
# 912 "/usr/include/stdio.h" 3 4
extern void flockfile (FILE *__stream) __attribute__ ((__nothrow__ ));
extern int ftrylockfile (FILE *__stream) __attribute__ ((__nothrow__ )) ;
extern void funlockfile (FILE *__stream) __attribute__ ((__nothrow__ ));
# 933 "/usr/include/stdio.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/stdio.h" 1 3 4
# 35 "/usr/include/x86_64-linux-gnu/bits/stdio.h" 3 4
extern __inline __attribute__ ((__gnu_inline__)) int
vprintf (const char *__restrict __fmt, __gnuc_va_list __arg)
{
return vfprintf (stdout, __fmt, __arg);
}
extern __inline __attribute__ ((__gnu_inline__)) int
getchar (void)
{
return _IO_getc (stdin);
}
extern __inline __attribute__ ((__gnu_inline__)) int
fgetc_unlocked (FILE *__fp)
{
return (__builtin_expect (((__fp)->_IO_read_ptr >= (__fp)->_IO_read_end), 0) ? __uflow (__fp) : *(unsigned char *) (__fp)->_IO_read_ptr++);
}
extern __inline __attribute__ ((__gnu_inline__)) int
getc_unlocked (FILE *__fp)
{
return (__builtin_expect (((__fp)->_IO_read_ptr >= (__fp)->_IO_read_end), 0) ? __uflow (__fp) : *(unsigned char *) (__fp)->_IO_read_ptr++);
}
extern __inline __attribute__ ((__gnu_inline__)) int
getchar_unlocked (void)
{
return (__builtin_expect (((stdin)->_IO_read_ptr >= (stdin)->_IO_read_end), 0) ? __uflow (stdin) : *(unsigned char *) (stdin)->_IO_read_ptr++);
}
extern __inline __attribute__ ((__gnu_inline__)) int
putchar (int __c)
{
return _IO_putc (__c, stdout);
}
extern __inline __attribute__ ((__gnu_inline__)) int
fputc_unlocked (int __c, FILE *__stream)
{
return (__builtin_expect (((__stream)->_IO_write_ptr >= (__stream)->_IO_write_end), 0) ? __overflow (__stream, (unsigned char) (__c)) : (unsigned char) (*(__stream)->_IO_write_ptr++ = (__c)));
}
extern __inline __attribute__ ((__gnu_inline__)) int
putc_unlocked (int __c, FILE *__stream)
{
return (__builtin_expect (((__stream)->_IO_write_ptr >= (__stream)->_IO_write_end), 0) ? __overflow (__stream, (unsigned char) (__c)) : (unsigned char) (*(__stream)->_IO_write_ptr++ = (__c)));
}
extern __inline __attribute__ ((__gnu_inline__)) int
putchar_unlocked (int __c)
{
return (__builtin_expect (((stdout)->_IO_write_ptr >= (stdout)->_IO_write_end), 0) ? __overflow (stdout, (unsigned char) (__c)) : (unsigned char) (*(stdout)->_IO_write_ptr++ = (__c)));
}
# 124 "/usr/include/x86_64-linux-gnu/bits/stdio.h" 3 4
extern __inline __attribute__ ((__gnu_inline__)) int
__attribute__ ((__nothrow__ )) feof_unlocked (FILE *__stream)
{
return (((__stream)->_flags & 0x10) != 0);
}
extern __inline __attribute__ ((__gnu_inline__)) int
__attribute__ ((__nothrow__ )) ferror_unlocked (FILE *__stream)
{
return (((__stream)->_flags & 0x20) != 0);
}
# 934 "/usr/include/stdio.h" 2 3 4
# 30 "nqueens.c" 2
# 1 "/usr/include/memory.h" 1 3 4
# 29 "/usr/include/memory.h" 3 4
# 1 "/usr/include/string.h" 1 3 4
# 32 "/usr/include/string.h" 3 4
# 1 "/home/nader/llvm-omp/lib/clang/5.0.1/include/stddef.h" 1 3 4
# 33 "/usr/include/string.h" 2 3 4
# 42 "/usr/include/string.h" 3 4
extern void *memcpy (void *__restrict __dest, const void *__restrict __src,
size_t __n) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
extern void *memmove (void *__dest, const void *__src, size_t __n)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
extern void *memccpy (void *__restrict __dest, const void *__restrict __src,
int __c, size_t __n)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
extern void *memset (void *__s, int __c, size_t __n) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
extern int memcmp (const void *__s1, const void *__s2, size_t __n)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
# 92 "/usr/include/string.h" 3 4
extern void *memchr (const void *__s, int __c, size_t __n)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
# 125 "/usr/include/string.h" 3 4
extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
extern char *strncpy (char *__restrict __dest,
const char *__restrict __src, size_t __n)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
extern char *strcat (char *__restrict __dest, const char *__restrict __src)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
extern char *strncat (char *__restrict __dest, const char *__restrict __src,
size_t __n) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
extern int strcmp (const char *__s1, const char *__s2)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern int strncmp (const char *__s1, const char *__s2, size_t __n)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern int strcoll (const char *__s1, const char *__s2)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern size_t strxfrm (char *__restrict __dest,
const char *__restrict __src, size_t __n)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (2)));
# 1 "/usr/include/xlocale.h" 1 3 4
# 27 "/usr/include/xlocale.h" 3 4
typedef struct __locale_struct
{
struct __locale_data *__locales[13];
const unsigned short int *__ctype_b;
const int *__ctype_tolower;
const int *__ctype_toupper;
const char *__names[13];
} *__locale_t;
typedef __locale_t locale_t;
# 160 "/usr/include/string.h" 2 3 4
extern int strcoll_l (const char *__s1, const char *__s2, __locale_t __l)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2, 3)));
extern size_t strxfrm_l (char *__dest, const char *__src, size_t __n,
__locale_t __l) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (2, 4)));
extern char *strdup (const char *__s)
__attribute__ ((__nothrow__ )) __attribute__ ((__malloc__)) __attribute__ ((__nonnull__ (1)));
extern char *strndup (const char *__string, size_t __n)
__attribute__ ((__nothrow__ )) __attribute__ ((__malloc__)) __attribute__ ((__nonnull__ (1)));
# 231 "/usr/include/string.h" 3 4
extern char *strchr (const char *__s, int __c)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
# 258 "/usr/include/string.h" 3 4
extern char *strrchr (const char *__s, int __c)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
# 280 "/usr/include/string.h" 3 4
extern size_t strcspn (const char *__s, const char *__reject)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern size_t strspn (const char *__s, const char *__accept)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
# 310 "/usr/include/string.h" 3 4
extern char *strpbrk (const char *__s, const char *__accept)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
# 337 "/usr/include/string.h" 3 4
extern char *strstr (const char *__haystack, const char *__needle)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strtok (char *__restrict __s, const char *__restrict __delim)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (2)));
extern char *__strtok_r (char *__restrict __s,
const char *__restrict __delim,
char **__restrict __save_ptr)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (2, 3)));
extern char *strtok_r (char *__restrict __s, const char *__restrict __delim,
char **__restrict __save_ptr)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (2, 3)));
# 394 "/usr/include/string.h" 3 4
extern size_t strlen (const char *__s)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern size_t strnlen (const char *__string, size_t __maxlen)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern char *strerror (int __errnum) __attribute__ ((__nothrow__ ));
# 422 "/usr/include/string.h" 3 4
extern int strerror_r (int __errnum, char *__buf, size_t __buflen) __asm__ ("" "__xpg_strerror_r") __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (2)));
# 440 "/usr/include/string.h" 3 4
extern char *strerror_l (int __errnum, __locale_t __l) __attribute__ ((__nothrow__ ));
extern void __bzero (void *__s, size_t __n) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
extern void bcopy (const void *__src, void *__dest, size_t __n)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
extern void bzero (void *__s, size_t __n) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
extern int bcmp (const void *__s1, const void *__s2, size_t __n)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
# 484 "/usr/include/string.h" 3 4
extern char *index (const char *__s, int __c)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
# 512 "/usr/include/string.h" 3 4
extern char *rindex (const char *__s, int __c)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern int ffs (int __i) __attribute__ ((__nothrow__ )) __attribute__ ((__const__));
# 529 "/usr/include/string.h" 3 4
extern int strcasecmp (const char *__s1, const char *__s2)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern int strncasecmp (const char *__s1, const char *__s2, size_t __n)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
# 552 "/usr/include/string.h" 3 4
extern char *strsep (char **__restrict __stringp,
const char *__restrict __delim)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
extern char *strsignal (int __sig) __attribute__ ((__nothrow__ ));
extern char *__stpcpy (char *__restrict __dest, const char *__restrict __src)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
extern char *stpcpy (char *__restrict __dest, const char *__restrict __src)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
extern char *__stpncpy (char *__restrict __dest,
const char *__restrict __src, size_t __n)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
extern char *stpncpy (char *__restrict __dest,
const char *__restrict __src, size_t __n)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
# 627 "/usr/include/string.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/string.h" 1 3 4
# 628 "/usr/include/string.h" 2 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/string2.h" 1 3 4
# 393 "/usr/include/x86_64-linux-gnu/bits/string2.h" 3 4
extern void *__rawmemchr (const void *__s, int __c);
# 945 "/usr/include/x86_64-linux-gnu/bits/string2.h" 3 4
extern __inline __attribute__ ((__gnu_inline__)) size_t __strcspn_c1 (const char *__s, int __reject);
extern __inline __attribute__ ((__gnu_inline__)) size_t
__strcspn_c1 (const char *__s, int __reject)
{
size_t __result = 0;
while (__s[__result] != '\0' && __s[__result] != __reject)
++__result;
return __result;
}
extern __inline __attribute__ ((__gnu_inline__)) size_t __strcspn_c2 (const char *__s, int __reject1,
int __reject2);
extern __inline __attribute__ ((__gnu_inline__)) size_t
__strcspn_c2 (const char *__s, int __reject1, int __reject2)
{
size_t __result = 0;
while (__s[__result] != '\0' && __s[__result] != __reject1
&& __s[__result] != __reject2)
++__result;
return __result;
}
extern __inline __attribute__ ((__gnu_inline__)) size_t __strcspn_c3 (const char *__s, int __reject1,
int __reject2, int __reject3);
extern __inline __attribute__ ((__gnu_inline__)) size_t
__strcspn_c3 (const char *__s, int __reject1, int __reject2,
int __reject3)
{
size_t __result = 0;
while (__s[__result] != '\0' && __s[__result] != __reject1
&& __s[__result] != __reject2 && __s[__result] != __reject3)
++__result;
return __result;
}
# 1021 "/usr/include/x86_64-linux-gnu/bits/string2.h" 3 4
extern __inline __attribute__ ((__gnu_inline__)) size_t __strspn_c1 (const char *__s, int __accept);
extern __inline __attribute__ ((__gnu_inline__)) size_t
__strspn_c1 (const char *__s, int __accept)
{
size_t __result = 0;
while (__s[__result] == __accept)
++__result;
return __result;
}
extern __inline __attribute__ ((__gnu_inline__)) size_t __strspn_c2 (const char *__s, int __accept1,
int __accept2);
extern __inline __attribute__ ((__gnu_inline__)) size_t
__strspn_c2 (const char *__s, int __accept1, int __accept2)
{
size_t __result = 0;
while (__s[__result] == __accept1 || __s[__result] == __accept2)
++__result;
return __result;
}
extern __inline __attribute__ ((__gnu_inline__)) size_t __strspn_c3 (const char *__s, int __accept1,
int __accept2, int __accept3);
extern __inline __attribute__ ((__gnu_inline__)) size_t
__strspn_c3 (const char *__s, int __accept1, int __accept2, int __accept3)
{
size_t __result = 0;
while (__s[__result] == __accept1 || __s[__result] == __accept2
|| __s[__result] == __accept3)
++__result;
return __result;
}
# 1097 "/usr/include/x86_64-linux-gnu/bits/string2.h" 3 4
extern __inline __attribute__ ((__gnu_inline__)) char *__strpbrk_c2 (const char *__s, int __accept1,
int __accept2);
extern __inline __attribute__ ((__gnu_inline__)) char *
__strpbrk_c2 (const char *__s, int __accept1, int __accept2)
{
while (*__s != '\0' && *__s != __accept1 && *__s != __accept2)
++__s;
return *__s == '\0' ? ((void*)0) : (char *) (size_t) __s;
}
extern __inline __attribute__ ((__gnu_inline__)) char *__strpbrk_c3 (const char *__s, int __accept1,
int __accept2, int __accept3);
extern __inline __attribute__ ((__gnu_inline__)) char *
__strpbrk_c3 (const char *__s, int __accept1, int __accept2, int __accept3)
{
while (*__s != '\0' && *__s != __accept1 && *__s != __accept2
&& *__s != __accept3)
++__s;
return *__s == '\0' ? ((void*)0) : (char *) (size_t) __s;
}
# 1147 "/usr/include/x86_64-linux-gnu/bits/string2.h" 3 4
extern __inline __attribute__ ((__gnu_inline__)) char *__strtok_r_1c (char *__s, char __sep, char **__nextp);
extern __inline __attribute__ ((__gnu_inline__)) char *
__strtok_r_1c (char *__s, char __sep, char **__nextp)
{
char *__result;
if (__s == ((void*)0))
__s = *__nextp;
while (*__s == __sep)
++__s;
__result = ((void*)0);
if (*__s != '\0')
{
__result = __s++;
while (*__s != '\0')
if (*__s++ == __sep)
{
__s[-1] = '\0';
break;
}
}
*__nextp = __s;
return __result;
}
# 1179 "/usr/include/x86_64-linux-gnu/bits/string2.h" 3 4
extern char *__strsep_g (char **__stringp, const char *__delim);
# 1197 "/usr/include/x86_64-linux-gnu/bits/string2.h" 3 4
extern __inline __attribute__ ((__gnu_inline__)) char *__strsep_1c (char **__s, char __reject);
extern __inline __attribute__ ((__gnu_inline__)) char *
__strsep_1c (char **__s, char __reject)
{
char *__retval = *__s;
if (__retval != ((void*)0) && (*__s = (__extension__ (__builtin_constant_p (__reject) && !__builtin_constant_p (__retval) && (__reject) == '\0' ? (char *) __rawmemchr (__retval, __reject) : __builtin_strchr (__retval, __reject)))) != ((void*)0))
*(*__s)++ = '\0';
return __retval;
}
extern __inline __attribute__ ((__gnu_inline__)) char *__strsep_2c (char **__s, char __reject1, char __reject2);
extern __inline __attribute__ ((__gnu_inline__)) char *
__strsep_2c (char **__s, char __reject1, char __reject2)
{
char *__retval = *__s;
if (__retval != ((void*)0))
{
char *__cp = __retval;
while (1)
{
if (*__cp == '\0')
{
__cp = ((void*)0);
break;
}
if (*__cp == __reject1 || *__cp == __reject2)
{
*__cp++ = '\0';
break;
}
++__cp;
}
*__s = __cp;
}
return __retval;
}
extern __inline __attribute__ ((__gnu_inline__)) char *__strsep_3c (char **__s, char __reject1, char __reject2,
char __reject3);
extern __inline __attribute__ ((__gnu_inline__)) char *
__strsep_3c (char **__s, char __reject1, char __reject2, char __reject3)
{
char *__retval = *__s;
if (__retval != ((void*)0))
{
char *__cp = __retval;
while (1)
{
if (*__cp == '\0')
{
__cp = ((void*)0);
break;
}
if (*__cp == __reject1 || *__cp == __reject2 || *__cp == __reject3)
{
*__cp++ = '\0';
break;
}
++__cp;
}
*__s = __cp;
}
return __retval;
}
# 1278 "/usr/include/x86_64-linux-gnu/bits/string2.h" 3 4
extern char *__strdup (const char *__string) __attribute__ ((__nothrow__ )) __attribute__ ((__malloc__));
# 1297 "/usr/include/x86_64-linux-gnu/bits/string2.h" 3 4
extern char *__strndup (const char *__string, size_t __n)
__attribute__ ((__nothrow__ )) __attribute__ ((__malloc__));
# 631 "/usr/include/string.h" 2 3 4
# 30 "/usr/include/memory.h" 2 3 4
# 31 "nqueens.c" 2
# 1 "./bots.h" 1
# 27 "./bots.h"
extern int bots_sequential_flag;
extern int bots_benchmark_flag;
extern int bots_check_flag;
extern int bots_result;
extern int bots_output_format;
extern int bots_print_header;
extern char bots_name[];
extern char bots_parameters[];
extern char bots_model[];
extern char bots_resources[];
extern char bots_exec_date[];
extern char bots_exec_message[];
extern char bots_comp_date[];
extern char bots_comp_message[];
extern char bots_cc[];
extern char bots_cflags[];
extern char bots_ld[];
extern char bots_ldflags[];
extern double bots_time_program;
extern double bots_time_sequential;
extern unsigned long long bots_number_of_tasks;
extern char bots_cutoff[];
extern int bots_cutoff_value;
extern int bots_app_cutoff_value;
extern int bots_app_cutoff_value_1;
extern int bots_app_cutoff_value_2;
extern int bots_arg_size;
extern int bots_arg_size_1;
extern int bots_arg_size_2;
long bots_usecs();
void bots_error(int error, char *message);
void bots_warning(int warning, char *message);
typedef enum { BOTS_VERBOSE_NONE=0,
BOTS_VERBOSE_DEFAULT,
BOTS_VERBOSE_DEBUG } bots_verbose_mode_t;
extern bots_verbose_mode_t bots_verbose_mode;
# 33 "nqueens.c" 2
# 1 "./app-desc.h" 1
# 21 "./app-desc.h"
# 1 "./omp-tasks-app.h" 1
# 21 "./omp-tasks-app.h"
# 1 "/home/nader/llvm-omp/lib/clang/5.0.1/include/omp.h" 1 3
# 35 "/home/nader/llvm-omp/lib/clang/5.0.1/include/omp.h" 3
typedef enum omp_sched_t {
omp_sched_static = 1,
omp_sched_dynamic = 2,
omp_sched_guided = 3,
omp_sched_auto = 4
} omp_sched_t;
extern void omp_set_num_threads (int);
extern void omp_set_dynamic (int);
extern void omp_set_nested (int);
extern void omp_set_max_active_levels (int);
extern void omp_set_schedule (omp_sched_t, int);
extern int omp_get_num_threads (void);
extern int omp_get_dynamic (void);
extern int omp_get_nested (void);
extern int omp_get_max_threads (void);
extern int omp_get_thread_num (void);
extern int omp_get_num_procs (void);
extern int omp_in_parallel (void);
extern int omp_in_final (void);
extern int omp_get_active_level (void);
extern int omp_get_level (void);
extern int omp_get_ancestor_thread_num (int);
extern int omp_get_team_size (int);
extern int omp_get_thread_limit (void);
extern int omp_get_max_active_levels (void);
extern void omp_get_schedule (omp_sched_t *, int *);
extern int omp_get_max_task_priority (void);
typedef struct omp_lock_t {
void * _lk;
} omp_lock_t;
extern void omp_init_lock (omp_lock_t *);
extern void omp_set_lock (omp_lock_t *);
extern void omp_unset_lock (omp_lock_t *);
extern void omp_destroy_lock (omp_lock_t *);
extern int omp_test_lock (omp_lock_t *);
typedef struct omp_nest_lock_t {
void * _lk;
} omp_nest_lock_t;
extern void omp_init_nest_lock (omp_nest_lock_t *);
extern void omp_set_nest_lock (omp_nest_lock_t *);
extern void omp_unset_nest_lock (omp_nest_lock_t *);
extern void omp_destroy_nest_lock (omp_nest_lock_t *);
extern int omp_test_nest_lock (omp_nest_lock_t *);
typedef enum omp_lock_hint_t {
omp_lock_hint_none = 0,
omp_lock_hint_uncontended = 1,
omp_lock_hint_contended = (1<<1 ),
omp_lock_hint_nonspeculative = (1<<2 ),
omp_lock_hint_speculative = (1<<3 ),
kmp_lock_hint_hle = (1<<16),
kmp_lock_hint_rtm = (1<<17),
kmp_lock_hint_adaptive = (1<<18)
} omp_lock_hint_t;
extern void omp_init_lock_with_hint(omp_lock_t *, omp_lock_hint_t);
extern void omp_init_nest_lock_with_hint(omp_nest_lock_t *, omp_lock_hint_t);
extern double omp_get_wtime (void);
extern double omp_get_wtick (void);
extern int omp_get_default_device (void);
extern void omp_set_default_device (int);
extern int omp_is_initial_device (void);
extern int omp_get_num_devices (void);
extern int omp_get_num_teams (void);
extern int omp_get_team_num (void);
extern int omp_get_cancellation (void);
extern int omp_get_initial_device (void);
extern void* omp_target_alloc(size_t, int);
extern void omp_target_free(void *, int);
extern int omp_target_is_present(void *, int);
extern int omp_target_memcpy(void *, void *, size_t, size_t, size_t, int, int);
extern int omp_target_memcpy_rect(void *, void *, size_t, int, const size_t *,
const size_t *, const size_t *, const size_t *, const size_t *, int, int);
extern int omp_target_associate_ptr(void *, void *, size_t, size_t, int);
extern int omp_target_disassociate_ptr(void *, int);
extern int kmp_get_stacksize (void);
extern void kmp_set_stacksize (int);
extern size_t kmp_get_stacksize_s (void);
extern void kmp_set_stacksize_s (size_t);
extern int kmp_get_blocktime (void);
extern int kmp_get_library (void);
extern void kmp_set_blocktime (int);
extern void kmp_set_library (int);
extern void kmp_set_library_serial (void);
extern void kmp_set_library_turnaround (void);
extern void kmp_set_library_throughput (void);
extern void kmp_set_defaults (char const *);
extern void kmp_set_disp_num_buffers (int);
typedef void * kmp_affinity_mask_t;
extern int kmp_set_affinity (kmp_affinity_mask_t *);
extern int kmp_get_affinity (kmp_affinity_mask_t *);
extern int kmp_get_affinity_max_proc (void);
extern void kmp_create_affinity_mask (kmp_affinity_mask_t *);
extern void kmp_destroy_affinity_mask (kmp_affinity_mask_t *);
extern int kmp_set_affinity_mask_proc (int, kmp_affinity_mask_t *);
extern int kmp_unset_affinity_mask_proc (int, kmp_affinity_mask_t *);
extern int kmp_get_affinity_mask_proc (int, kmp_affinity_mask_t *);
typedef enum omp_proc_bind_t {
omp_proc_bind_false = 0,
omp_proc_bind_true = 1,
omp_proc_bind_master = 2,
omp_proc_bind_close = 3,
omp_proc_bind_spread = 4
} omp_proc_bind_t;
extern omp_proc_bind_t omp_get_proc_bind (void);
extern int omp_get_num_places (void);
extern int omp_get_place_num_procs (int);
extern void omp_get_place_proc_ids (int, int *);
extern int omp_get_place_num (void);
extern int omp_get_partition_num_places (void);
extern void omp_get_partition_place_nums (int *);
extern void * kmp_malloc (size_t);
extern void * kmp_aligned_malloc (size_t, size_t);
extern void * kmp_calloc (size_t, size_t);
extern void * kmp_realloc (void *, size_t);
extern void kmp_free (void *);
extern void kmp_set_warnings_on(void);
extern void kmp_set_warnings_off(void);
typedef int omp_int_t;
typedef double omp_wtime_t;
# 22 "./omp-tasks-app.h" 2
# 22 "./app-desc.h" 2
# 31 "./app-desc.h"
int ok(int n, char *a);
void nqueens(int n, int j, char *a, int depth);
void nqueens_ser (int n, int j, char *a);
int verify_queens(int);
void find_queens (int);
# 34 "nqueens.c" 2
static int solutions[] = {
1,
0,
0,
2,
10,
4,
40,
92,
352,
724,
2680,
14200,
73712,
365596,
};
int mycount=0;
#pragma omp threadprivate(mycount)
int total_count;
int ok(int n, char *a)
{
int i, j;
char p, q;
for (i = 0; i < n; i++) {
p = a[i];
for (j = i + 1; j < n; j++) {
q = a[j];
if (q == p || q == p - (j - i) || q == p + (j - i))
return 0;
}
}
return 1;
}
void nqueens_ser (int n, int j, char *a)
{
int i;
if (n == j) {
mycount++;
return;
}
for (i = 0; i < n; i++) {
{
a[j] = (char) i;
if (ok(j + 1, a)) {
nqueens_ser(n, j + 1, a);
}
}
}
}
# 259 "nqueens.c"
void nqueens(int n, int j, char *a, int depth)
{
int i;
if (n == j) {
mycount++;
return;
}
# 286 "nqueens.c"
for (i = 0; i < n; i++) {
if ( depth < bots_cutoff_value ) {
#pragma omp task
{
char * b = (char*)__builtin_alloca (n * sizeof(char));
memcpy(b, a, j * sizeof(char));
b[j] = (char) i;
if (ok(j + 1, b))
nqueens(n, j + 1, b,depth+1);
}
} else {
a[j] = (char) i;
if (ok(j + 1, a))
nqueens_ser(n, j + 1, a);
}
}
#pragma omp taskwait
}
# 375 "nqueens.c"
void find_queens (int size)
{
total_count=0;
{ if ( bots_verbose_mode >= BOTS_VERBOSE_DEFAULT ) { fprintf(stdout, "Computing N-Queens algorithm (n=%d) " , size); } };
#pragma omp parallel num_threads(4)
{
#pragma omp single
{
char *a;
a = (char*)__builtin_alloca (size * sizeof(char));
nqueens(size, 0, a, 0);
}
#pragma omp atomic
total_count += mycount;
}
{ if ( bots_verbose_mode >= BOTS_VERBOSE_DEFAULT ) { fprintf(stdout, " completed!\n"); } };
}
int verify_queens (int size)
{
if ( size > sizeof(solutions)/sizeof(int) ) return 0;
if ( total_count == solutions[size-1]) return 1;
return 2;
}
|
vbHmmPcFret.c | /*
* vbHmmPcFret.c
* Model-specific core functions for VB-HMM-PC-FRET.
*
* Created by OKAMOTO Kenji, SAKO Yasushi and RIKEN
* Copyright 2011-2015
* Cellular Informatics Laboratory, Advance Science Institute, RIKEN, Japan.
* All rights reserved.
*
* Ver. 1.1.0
* Last modified on 2015.09.17
*/
#include "vbHmmPcFret.h"
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_psi.h>
#include <string.h>
#include "rand.h"
#ifdef _OPENMP
#include "omp.h"
#endif
//#define DEBUG
//// Uncomment one/both of the following defenitions to activate constraint on I and K.
//#define INTENSITY_CAP
#ifdef INTENSITY_CAP
#define maxIntensityRatio 10.0
#endif
#define MAX(a,b) ((a)>(b)?(a):(b))
#define MIN(a,b) ((a)<(b)?(a):(b))
//static int isGlobalAnalysis = 0;
void setFunctions_pcFret(){
commonFunctions funcs;
funcs.newModelParameters = newModelParameters_pcFret;
funcs.freeModelParameters = freeModelParameters_pcFret;
funcs.newModelStats = newModelStats_pcFret;
funcs.freeModelStats = freeModelStats_pcFret;
funcs.initializeVbHmm = initializeVbHmm_pcFret;
funcs.pTilde_z1 = pTilde_z1_pcFret;
funcs.pTilde_zn_zn1 = pTilde_zn_zn1_pcFret;
funcs.pTilde_xn_zn = pTilde_xn_zn_pcFret;
funcs.calcStatsVars = calcStatsVars_pcFret;
funcs.maximization = maximization_pcFret;
funcs.varLowerBound = varLowerBound_pcFret;
funcs.reorderParameters = reorderParameters_pcFret;
funcs.outputResults = outputResults_pcFret;
setFunctions( funcs );
}
//void setGFunctions_pcFret(){
// gCommonFunctions funcs;
// funcs.newModelParameters = newModelParameters_pcFret;
// funcs.freeModelParameters = freeModelParameters_pcFret;
// funcs.newModelStats = newModelStats_pcFret;
// funcs.freeModelStats = freeModelStats_pcFret;
// funcs.newModelStatsG = newModelStatsG_pcFret;
// funcs.freeModelStatsG = freeModelStatsG_pcFret;
// funcs.initializeVbHmmG = initializeVbHmmG_pcFret;
// funcs.pTilde_z1 = pTilde_z1_pcFret;
// funcs.pTilde_zn_zn1 = pTilde_zn_zn1_pcFret;
// funcs.pTilde_xn_zn = pTilde_xn_zn_pcFret;
// funcs.calcStatsVarsG = calcStatsVarsG_pcFret;
// funcs.maximizationG = maximizationG_pcFret;
// funcs.varLowerBoundG = varLowerBoundG_pcFret;
// funcs.reorderParametersG = reorderParametersG_pcFret;
// funcs.outputResultsG = outputResultsG_pcFret;
// setGFunctions( funcs );
// isGlobalAnalysis = 1;
//}
void outputResults_pcFret( xn, gv, iv, logFP )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
FILE *logFP;
{
outputPcFretResults( xn, gv, iv, logFP );
}
//void outputResultsG_pcFret( xns, gv, ivs, logFP )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//FILE *logFP;
//{
// outputPcFretResultsG( xns, gv, ivs, logFP );
//}
void *newModelParameters_pcFret( xn, sNo )
xnDataSet *xn;
int sNo;
{
int i;
pcFretParameters *p = (void*)malloc( sizeof(pcFretParameters) );
p->uPiArr = (double*)malloc( sNo * sizeof(double) );
p->sumUPi = 0.0;
p->uAMat = (double**)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ ){
p->uAMat[i] = (double*)malloc( sNo * sizeof(double) );
}
p->sumUAArr = (double*)malloc( sNo * sizeof(double) );
p->aIArr = (double*)malloc( sNo * sizeof(double) );
p->bIArr = (double*)malloc( sNo * sizeof(double) );
p->uEArr = (double*)malloc( sNo * sizeof(double) );
p->vEArr = (double*)malloc( sNo * sizeof(double) );
p->avgPi = (double *)malloc( sNo * sizeof(double) );
p->avgLnPi = (double *)malloc( sNo * sizeof(double) );
p->avgA = (double **)malloc( sNo * sizeof(double*) );
p->avgLnA = (double **)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ ){
p->avgA[i] = (double *)malloc( sNo * sizeof(double) );
p->avgLnA[i] = (double *)malloc( sNo * sizeof(double) );
}
p->avgI = (double *)malloc( sNo * sizeof(double) );
p->avgLnI = (double *)malloc( sNo * sizeof(double) );
p->avgE = (double *)malloc( sNo * sizeof(double) );
p->avgLnE = (double **)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ )
{ p->avgLnE[i] = (double *)malloc( 2 * sizeof(double) ); }
return p;
}
void freeModelParameters_pcFret( p, xn, sNo )
void **p;
xnDataSet *xn;
int sNo;
{
pcFretParameters *gp = *p;
int i;
free( gp->uPiArr );
for( i = 0 ; i < sNo ; i++ ){
free( gp->uAMat[i] );
}
free( gp->uAMat );
free( gp->sumUAArr );
free( gp->aIArr );
free( gp->bIArr );
free( gp->uEArr );
free( gp->vEArr );
free( gp->avgPi );
free( gp->avgLnPi );
for( i = 0 ; i < sNo ; i++ ){
free( gp->avgA[i] );
free( gp->avgLnA[i] );
}
free( gp->avgA );
free( gp->avgLnA );
free( gp->avgI );
free( gp->avgLnI );
free( gp->avgE );
for( i = 0 ; i < sNo ; i++ ){
free( gp->avgLnE[i] );
}
free( gp->avgLnE );
free( *p );
*p = NULL;
}
void *newModelStats_pcFret( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
// if( isGlobalAnalysis == 0 ){
int sNo = gv->sNo;
pcFretStats *s = (pcFretStats*)malloc( sizeof(pcFretStats) );
int i;
s->Ni = (double *)malloc( sNo * sizeof(double) );
s->Ci = (double *)malloc( sNo * sizeof(double) );
s->Di = (double *)malloc( sNo * sizeof(double) );
s->Ai = (double *)malloc( sNo * sizeof(double) );
s->Mi = (double *)malloc( sNo * sizeof(double) );
s->Nij = (double **)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ )
{ s->Nij[i] = (double *)malloc( sNo * sizeof(double) ); }
return s;
// } else {
//
// return NULL;
//
// }
}
void freeModelStats_pcFret( s, xn, gv, iv )
void **s;
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
// if( isGlobalAnalysis == 0 ){
int sNo = gv->sNo;
pcFretStats *gs = *s;
int i;
free( gs->Ni );
free( gs->Ci );
free( gs->Di );
free( gs->Ai );
free( gs->Mi );
for( i = 0 ; i < sNo ; i++ )
{ free( gs->Nij[i] ); }
free( gs->Nij );
free( gs );
*s = NULL;
// }
}
//void *newModelStatsG_pcFret( xns, gv, ivs)
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
// int sNo = gv->sNo;
// pcFretGlobalStats *gs = (pcFretGlobalStats*)malloc( sizeof(pcFretGlobalStats) );
//
// return gs;
//}
//void freeModelStatsG_pcFret( gs, xns, gv, ivs )
//void **gs;
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
// int sNo = gv->sNo;
// pcFretGlobalStats *ggs = *gs;
//
// free( *gs );
// *gs = NULL;
//}
void initializeVbHmm_pcFret( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
pcFretData *d = xn->data;
size_t dLen = xn->N;
int sNo = gv->sNo;
pcFretParameters *p = gv->params;
int i, j;
size_t totalC = 0;
for( i = 0 ; i < dLen ; i++ ){
totalC += d->dCounts[i] + d->aCounts[i];
}
double meanI = (double)totalC / (double)dLen;
// hyper parameter for p( pi(i) )
p->sumUPi = 0.0;
for( i = 0 ; i < sNo ; i++ ){
p->uPiArr[i] = 1.0;
p->sumUPi += p->uPiArr[i];
}
// hyper parameter for p( A(i,j) )
for( i = 0 ; i < sNo ; i++ ){
p->sumUAArr[i] = 0.0;
for( j = 0 ; j < sNo ; j++ ){
if( j == i ){
p->uAMat[i][j] = 100.0;
} else {
p->uAMat[i][j] = 1.0;
}
p->sumUAArr[i] += p->uAMat[i][j];
}
}
// hyper parameter for p( I(k) )
for( i = 0 ; i < sNo ; i++ ){
p->aIArr[i] = 1.0;
p->bIArr[i] = 1.0 / meanI;
}
// hyper parameter for p( E(i) )
for( i = 0 ; i < sNo ; i++ ){
p->uEArr[i] = 1.0;
p->vEArr[i] = 1.0;
}
initialize_indVars_pcFret( xn, gv, iv );
calcStatsVars_pcFret( xn, gv, iv );
maximization_pcFret( xn, gv, iv );
}
//void initializeVbHmmG_pcFret( xns, gv, ivs )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//}
void initialize_indVars_pcFret( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat;
int i;
size_t n;
double sumPar;
for( n = 0 ; n < dLen ; n++ ){
sumPar = 0.0;
for( i = 0 ; i < sNo ; i++ ){
gmMat[n][i] = enoise(1.0) + 1.0;
sumPar += gmMat[n][i];
}
for( i = 0 ; i < sNo ; i++ ){
gmMat[n][i] /= sumPar;
}
}
}
xnDataSet *newXnDataSet_pcFret( filename )
const char *filename;
{
xnDataSet *xn = (xnDataSet*)malloc( sizeof(xnDataSet) );
xn->name = (char*)malloc( strlen(filename) + 2 );
strncpy( xn->name, filename, strlen(filename)+1 );
xn->data = (pcFretData*)malloc( sizeof(pcFretData) );
pcFretData *d = (pcFretData*)xn->data;
d->binSize = 0.0;
d->dCounts = NULL;
d->aCounts = NULL;
return xn;
}
void freeXnDataSet_pcFret( xn )
xnDataSet **xn;
{
pcFretData *d = (pcFretData*)(*xn)->data;
free( d->dCounts );
free( d->aCounts );
free( (*xn)->data );
free( (*xn)->name );
free( *xn );
*xn = NULL;
}
double pTilde_z1_pcFret( i, params )
int i;
void *params;
{
pcFretParameters *p = (pcFretParameters*)params;
return exp( p->avgLnPi[i] );
}
double pTilde_zn_zn1_pcFret( i, j, params )
int i, j;
void *params;
{
pcFretParameters *p = (pcFretParameters*)params;
return exp( p->avgLnA[i][j] );
}
double pTilde_xn_zn_pcFret( xn, n, i, params )
xnDataSet *xn;
size_t n;
int i;
void *params;
{
pcFretParameters *p = (pcFretParameters*)params;
pcFretData *d = (pcFretData*)xn->data;
return exp( d->dCounts[n]*p->avgLnE[i][0] + d->aCounts[n]*p->avgLnE[i][1] + (d->dCounts[n]+d->aCounts[n])*p->avgLnI[i] - p->avgI[i] ) / gsl_sf_fact( d->dCounts[n] ) / gsl_sf_fact( d->aCounts[n] );
}
void calcStatsVars_pcFret( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
pcFretData *d = (pcFretData*)xn->data;
pcFretStats *s = (pcFretStats*)iv->stats;
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat, ***xiMat = iv->xiMat;
double *Ni = s->Ni, *Ci = s->Ci, *Di = s->Di, *Ai = s->Ai;
double *Mi = s->Mi, **Nij = s->Nij;
size_t n;
int i, j;
for( i = 0 ; i < sNo ; i++ ){
Ni[i] = 1e-10;
Ci[i] = 1e-10;
Di[i] = 1e-10;
Ai[i] = 1e-10;
Mi[i] = 1e-10;
for( j = 0 ; j < sNo ; j++ ){
Nij[i][j] = 1e-10;
}
for( n = 0 ; n < dLen ; n++ ){
Ni[i] += gmMat[n][i];
Di[i] += gmMat[n][i] * (double)d->dCounts[n];
Ai[i] += gmMat[n][i] * (double)d->aCounts[n];
for( j = 0 ; j < sNo ; j++ ){
Mi[i] += xiMat[n][i][j];
Nij[i][j] += xiMat[n][i][j];
}
}
Ci[i] = Di[i] + Ai[i];
}
//#ifdef DEBUG
//#pragma omp critical
//{
// for( n = 0 ; n < 20 ; n++ ){
// for( i = 0 ; i < sNo ; i++ ){
// fprintf(logFP, "%g,", gmMat[n][i]);
// }
// fprintf(logFP, "; ");
// }
// fprintf(logFP, "\n");
// for( i = 0 ; i < sNo ; i++ ){
// fprintf(logFP, "Ni(%d)=%g, ", i, Ni[i]);
// fprintf(logFP, "Ti(%d)=%g, ", i, Ti[i]);
// fprintf(logFP, "Mi(%d)=%g, ", i, Mi[i]);
// for( j = 0 ; j < sNo ; j++ ){
// if( j != i )
// fprintf(logFP, "Nij(%d,%d)=%g, ", i, j, Nij[i][j]);
// }
// fprintf(logFP, "\n");
// }
//}
//#endif
}
//void calcStatsVarsG_pcFret( xns, gv, ivs )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//}
void maximization_pcFret( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
pcFretParameters *p = (pcFretParameters*)gv->params;
pcFretStats *s = (pcFretStats*)iv->stats;
int sNo = gv->sNo;
double **gmMat = iv->gmMat;
double *uPiArr = p->uPiArr, sumUPi = p->sumUPi, *aIArr = p->aIArr, *bIArr = p->bIArr;
double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;
double *uEArr = p->uEArr, *vEArr = p->vEArr;
double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;
double *avgE = p->avgE, **avgLnE = p->avgLnE;
double *avgI = p->avgI, *avgLnI = p->avgLnI;
double *Ni = s->Ni, *Ci = s->Ci, *Di = s->Di, *Ai = s->Ai;
double *Mi = s->Mi, **Nij = s->Nij;
int i, j;
for( i = 0 ; i < sNo ; i++ ){
avgPi[i] = ( uPiArr[i] + gmMat[0][i] ) / ( sumUPi + 1.0 );
avgLnPi[i] = gsl_sf_psi( uPiArr[i] + gmMat[0][i] ) - gsl_sf_psi( sumUPi + 1.0 );
for( j = 0 ; j < sNo ; j++ ){
avgA[i][j] = ( uAMat[i][j] + Nij[i][j] ) / ( sumUAArr[i] + Mi[i] );
avgLnA[i][j] = gsl_sf_psi( uAMat[i][j] + Nij[i][j] ) - gsl_sf_psi( sumUAArr[i] + Mi[i] );
}
avgI[i] = (Ci[i] + aIArr[i]) / (Ni[i] + bIArr[i]);
avgLnI[i] = gsl_sf_psi( Ci[i] + aIArr[i] ) - log( Ni[i] + bIArr[i] );
#ifdef INTENSITY_CAP
size_t n, totalC = 0;
pcFretData *pc = xnWv->data;
for( n = 0 ; n < xnWv->N ; n++ ){
totalC += pc->dCounts[n] + pc->aCounts[n];
}
double meanI = (double)totalC / (double)xnWv->N;
avgI[i] = MIN( avgI[i], maxIntensityRatio * meanI );
avgLnI[i] = MIN( avgLnI[i], log(maxIntensityRatio * meanI) );
#endif
avgE[i] = ( uEArr[i] + Ai[i] ) / ( uEArr[i] + vEArr[i] + Ci[i] );
// ln(1-E) for donor
avgLnE[i][0] = gsl_sf_psi( vEArr[i] + Di[i] ) - gsl_sf_psi( uEArr[i] + vEArr[i] + Ci[i] );
// ln(E) for acceptor
avgLnE[i][1] = gsl_sf_psi( uEArr[i] + Ai[i] ) - gsl_sf_psi( uEArr[i] + vEArr[i] + Ci[i] );
}
}
//void maximizationG_pc( xns, gv, ivs )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//}
double varLowerBound_pcFret( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
pcFretParameters *p = (pcFretParameters*)gv->params;
pcFretStats *s = (pcFretStats*)iv->stats;
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat, *cn = iv->cn;
double *uPiArr = p->uPiArr, sumUPi = p->sumUPi, *aIArr = p->aIArr, *bIArr = p->bIArr;
double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;
double *uEArr = p->uEArr, *vEArr = p->vEArr;
double *avgLnPi = p->avgLnPi, **avgLnA = p->avgLnA;
double *avgI = p->avgI, *avgLnI = p->avgLnI, **avgLnE = p->avgLnE;
double *Ni = s->Ni, *Ci = s->Ci, *Di = s->Di, *Ai = s->Ai;
double *Mi = s->Mi, **Nij = s->Nij;
size_t n;
int i, j;
double lnpPi = gsl_sf_lngamma(sumUPi);
double lnpA = 0.0;
double lnpI = 0.0;
double lnpE = 0.0;
double lnqPi = gsl_sf_lngamma(sumUPi + 1.0);
double lnqA = 0.0;
double lnqI = 0.0;
double lnqE = 0.0;
for( i = 0 ; i < sNo ; i++ ){
lnpPi += (uPiArr[i]-1.0) * avgLnPi[i] - gsl_sf_lngamma(uPiArr[i]);
lnpI += aIArr[i] * log(bIArr[i]) - gsl_sf_lngamma(aIArr[i]);
lnpI += (aIArr[i] - 1.0) * avgLnI[i] - bIArr[i] * avgI[i];
lnpE += gsl_sf_lngamma(uEArr[i]+vEArr[i]) - gsl_sf_lngamma(uEArr[i]);
lnpE += -gsl_sf_lngamma(vEArr[i]);
lnpE += (uEArr[i]-1.0)*avgLnE[i][1] + (vEArr[i]-1.0)*avgLnE[i][0];
lnqPi += (uPiArr[i]+gmMat[0][i]-1.0) * (gsl_sf_psi(uPiArr[i]+gmMat[0][i]) - gsl_sf_psi(sumUPi+1.0));
lnqPi -= gsl_sf_lngamma(uPiArr[i] + gmMat[0][i]);
lnqI += (Ci[i] + aIArr[i]) * log(Ni[i] + bIArr[i]) - gsl_sf_lngamma(Ci[i] + aIArr[i]);
lnqI += (Ci[i] + aIArr[i] - 1.0) * avgLnI[i] - (Ni[i] + bIArr[i]) * avgI[i];
lnqE += gsl_sf_lngamma(uEArr[i] + vEArr[i] + Ci[i]);
lnqE -= gsl_sf_lngamma(uEArr[i] + Ai[i]);
lnqE -= gsl_sf_lngamma(vEArr[i] + Di[i]);
lnqE += (uEArr[i] + Ai[i] - 1.0) * avgLnE[i][1];
lnqE += (vEArr[i] + Di[i] - 1.0) * avgLnE[i][0];
lnpA += gsl_sf_lngamma(sumUAArr[i]);
lnqA += gsl_sf_lngamma(sumUAArr[i] + Mi[i]);
for( j = 0 ; j < sNo ; j++ ){
lnpA += (uAMat[i][j]-1.0)*avgLnA[i][j] - gsl_sf_lngamma(uAMat[i][j]);
lnqA += (uAMat[i][j] + Nij[i][j] - 1.0) * (gsl_sf_psi(uAMat[i][j]+Nij[i][j]) - gsl_sf_psi(sumUAArr[i]+Mi[i]));
lnqA -= gsl_sf_lngamma( uAMat[i][j] + Nij[i][j] );
}
}
double lnpX = 0.0;
for( n = 0 ; n < dLen ; n++ ){
lnpX += log( cn[n] );
}
double val;
val = lnpPi + lnpA + lnpI + lnpE;
val -= lnqPi + lnqA + lnqI + lnqE;
val += lnpX;
val += log(gsl_sf_fact(sNo));
//#ifdef DEBUG
//#pragma omp critical
//{
// FILE *logFP = stderr;
// if( val > 100000 ){
// fprintf(logFP, " > %g; %g; %g; %g;", lnpPi, lnpA, lnpI, lnpE);
// fprintf(logFP, " %g; %g; %g; %g; %g\n", lnqPi, lnqA, lnqI, lnqE, lnpX);
// }
//}
//#endif
return val;
}
//double varLowerBoundG_pcFret( xns, gv, ivs )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//}
void reorderParameters_pcFret( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
pcFretParameters *p = (pcFretParameters*)gv->params;
pcFretStats *s = (pcFretStats*)iv->stats;
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat, ***xiMat = iv->xiMat;
double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA;
double **avgLnA = p->avgLnA;
double *avgI = p->avgI, *avgLnI = p->avgLnI, *avgE = p->avgE, **avgLnE = p->avgLnE;
double *Ni = s->Ni, *Ci = s->Ci, *Di = s->Di, *Ai = s->Ai;
size_t n;
int i, j;
int *index = (int*)malloc( sNo * sizeof(int) );
double *store = (double*)malloc( sNo * sizeof(double) );
double **s2D = (double**)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ )
{ s2D[i] = (double*)malloc( MAX(sNo,2) * sizeof(double) ); }
// index indicates order of avgE values (0=biggest avgE -- sNo=smallest avgE).
for( i = 0 ; i < sNo ; i++ ){
index[i] = sNo - 1;
for( j = 0 ; j < sNo ; j++ ){
if( j != i ){
if( avgE[i] < avgE[j] ){
index[i]--;
} else if( avgE[i] == avgE[j] ){
if( j > i )
{ index[i]--; }
}
}
}
}
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgPi[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgPi[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnPi[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgLnPi[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgI[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgI[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnI[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgLnI[i] = store[i]; }
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgA[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ avgA[i][j] = s2D[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgLnA[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ avgLnA[i][j] = s2D[i][j]; }
}
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgE[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgE[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ )
{ s2D[index[i]][0] = avgLnE[i][0];
s2D[index[i]][1] = avgLnE[i][1]; }
for( i = 0 ; i < sNo ; i++ )
{ avgLnE[i][0] = s2D[i][0];
avgLnE[i][1] = s2D[i][1]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = Ni[i]; }
for( i = 0 ; i < sNo ; i++ ){ Ni[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = Ci[i]; }
for( i = 0 ; i < sNo ; i++ ){ Ci[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = Di[i]; }
for( i = 0 ; i < sNo ; i++ ){ Di[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = Ai[i]; }
for( i = 0 ; i < sNo ; i++ ){ Ai[i] = store[i]; }
for( n = 0 ; n < dLen ; n++ ){
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = gmMat[n][i]; }
for( i = 0 ; i < sNo ; i++ ){ gmMat[n][i] = store[i]; }
}
for( n = 0 ; n < dLen ; n++ ){
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = xiMat[n][i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ xiMat[n][i][j] = s2D[i][j]; }
}
}
for( i = 0 ; i < sNo ; i++ ){ free( s2D[i] ); }
free( s2D );
free( store );
free( index );
}
//void reorderParametersG_pc( xns, gv, ivs )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//}
void outputPcFretResults( xn, gv, iv, logFP )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
FILE *logFP;
{
pcFretParameters *p = (pcFretParameters*)gv->params;
int sNo = gv->sNo;
int i, j;
fprintf(logFP, " results: K = %d \n", sNo);
fprintf(logFP, " intensities: ( %g", p->avgI[0]);
for( i = 1 ; i < sNo ; i++ )
{ fprintf(logFP, ", %g", p->avgI[i]); }
fprintf(logFP, " ) \n");
fprintf(logFP, " FRET efficiencies: ( %g", p->avgE[0]);
for( i = 1 ; i < sNo ; i++ ){
fprintf(logFP, ", %g", p->avgE[i]);
}
fprintf(logFP, " ) \n");
fprintf(logFP, " pi: ( %g", p->avgPi[0]);
for( i = 1 ; i < sNo ; i++ ){
fprintf(logFP, ", %g", p->avgPi[i]);
}
fprintf(logFP, " ) \n");
fprintf(logFP, " A_matrix: [");
for( i = 0 ; i < sNo ; i++ ){
fprintf(logFP, " ( %g", p->avgA[i][0]);
for( j = 1 ; j < sNo ; j++ )
{ fprintf(logFP, ", %g", p->avgA[i][j]); }
fprintf(logFP, ")");
}
fprintf(logFP, " ] \n\n");
char fn[256];
FILE *fp;
size_t n;
sprintf( fn, "%s.param%03d", xn->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
fprintf(fp, "I, E, pi");
for( i = 0 ; i < sNo ; i++ )
{ fprintf(fp, ", A%dx", i); }
fprintf(fp, "\n");
for( i = 0 ; i < sNo ; i++ ){
fprintf(fp, "%g, %g", p->avgI[i], p->avgE[i]);
for( j = 0 ; j < sNo ; j++ )
{ fprintf(fp, ", %g", p->avgA[j][i]); }
fprintf(fp, "\n");
}
fclose(fp);
}
sprintf( fn, "%s.Lq%03d", xn->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
for( n = 0 ; n < gv->iteration ; n++ ){
fprintf( fp, "%24.20e\n", gv->LqArr[n] );
}
fclose(fp);
}
sprintf( fn, "%s.maxS%03d", xn->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
for( n = 0 ; n < xn->N ; n++ ){
fprintf( fp, "%d\n", iv->stateTraj[n] );
}
fclose(fp);
}
}
//void outputPcFretResultsG( xns, gv, ivs, logFP )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//FILE *logFP;
//{
//}
//
|
CutPursuit.h | #pragma once
#include "Graph.h"
#include <math.h>
#include <queue>
#include <iostream>
#include <fstream>
#include <boost/graph/boykov_kolmogorov_max_flow.hpp>
namespace CP {
template <typename T>
struct CPparameter
{
T reg_strenth; //regularization strength, multiply the edge weight
uint32_t cutoff; //minimal component size
uint32_t flow_steps; //number of steps in the optimal binary cut computation
uint32_t kmeans_ite; //number of iteration in the kmeans sampling
uint32_t kmeans_resampling; //number of kmeans re-intilialization
uint32_t verbose; //verbosity
uint32_t max_ite_main; //max number of iterations in the main loop
bool backward_step; //indicates if a backward step should be performed
double stopping_ratio; //when (E(t-1) - E(t) / (E(0) - E(t)) is too small, the algorithm stops
fidelityType fidelity; //the fidelity function
double smoothing; //smoothing term (for Kl divergence only)
bool parallel; //enable/disable parrallelism
T weight_decay; //for continued optimization of the flow steps
};
template <typename T>
class CutPursuit
{
public:
Graph<T> main_graph; //the Graph structure containing the main structure
Graph<T> reduced_graph; //the reduced graph whose vertices are the connected component
std::vector<std::vector<VertexDescriptor<T>>> components; //contains the list of the vertices in each component
std::vector<VertexDescriptor<T>> root_vertex; //the root vertex for each connected components
std::vector<bool> saturated_components; //is the component saturated (uncuttable)
std::vector<std::vector<EdgeDescriptor>> borders; //the list of edges forming the borders between the connected components
VertexDescriptor<T> source; //source vertex for graph cut
VertexDescriptor<T> sink; //sink vertex
uint32_t dim; // dimension of the data
uint32_t nVertex; // number of data point
uint32_t nEdge; // number of edges between vertices (not counting the edge to source/sink)
CP::VertexIterator<T> lastIterator; //iterator pointing to the last vertex which is neither sink nor source
CPparameter<T> parameter;
public:
CutPursuit(uint32_t nbVertex = 1)
{
this->main_graph = Graph<T>(nbVertex);
this->reduced_graph = Graph<T>(1);
this->components = std::vector<std::vector<VertexDescriptor<T>>>(1);
this->root_vertex = std::vector<VertexDescriptor<T>>(1,0);
this->saturated_components = std::vector<bool>(1,false);
this->source = VertexDescriptor<T>();
this->sink = VertexDescriptor<T>();
this->dim = 1;
this->nVertex = 1;
this->nEdge = 0;
this->parameter.flow_steps = 3;
this->parameter.kmeans_ite = 5;
this->parameter.kmeans_resampling = 3;
this->parameter.verbose = 2;
this->parameter.max_ite_main = 6;
this->parameter.backward_step = true;
this->parameter.stopping_ratio = 0.0001;
this->parameter.fidelity = L2;
this->parameter.smoothing = 0.1;
this->parameter.parallel = true;
this->parameter.weight_decay = 0.7;
}
virtual ~CutPursuit(){
};
//=============================================================================================
std::pair<std::vector<T>, std::vector<T>> run()
{
//first initilialize the structure
this->initialize();
if (this->parameter.verbose > 0)
{
std::cout << "Graph " << boost::num_vertices(this->main_graph) << " vertices and "
<< boost::num_edges(this->main_graph) << " edges and observation of dimension "
<< this->dim << '\n';
}
T energy_zero = this->compute_energy().first; //energy with 1 component
T old_energy = energy_zero; //energy at the previous iteration
//vector with time and energy, useful for benchmarking
std::vector<T> energy_out(this->parameter.max_ite_main ),time_out(this->parameter.max_ite_main);
TimeStack ts; ts.tic();
//the main loop
for (uint32_t ite_main = 1; ite_main <= this->parameter.max_ite_main; ite_main++)
{
//--------those two lines are the whole iteration-------------------------
uint32_t saturation = this->split(); //compute optimal binary partition
this->reduce(); //compute the new reduced graph
//-------end of the iteration - rest is stopping check and display------
std::pair<T,T> energy = this->compute_energy();
energy_out.push_back((energy.first + energy.second));
time_out.push_back(ts.tocDouble());
if (this->parameter.verbose > 1)
{
printf("Iteration %3i - %4i components - ", ite_main, (int)this->components.size());
printf("Saturation %5.1f %% - ",100*saturation / (double) this->nVertex);
switch (this->parameter.fidelity)
{
case L2:
{
printf("Quadratic Energy %4.3f %% - ", 100 * (energy.first + energy.second) / energy_zero);
break;
}
case linear:
{
printf("Linear Energy %10.1f - ", energy.first + energy.second);
break;
}
case KL:
{
printf("KL Energy %4.3f %% - ", 100 * (energy.first + energy.second) / energy_zero);
break;
}
case SPG:
{
printf("Quadratic Energy %4.3f %% - ", 100 * (energy.first + energy.second) / energy_zero);
break;
}
}
std::cout << "Timer " << ts.toc() << std::endl;
}
//----stopping checks-----
if (saturation == (double) this->nVertex)
{ //all components are saturated
if (this->parameter.verbose > 1)
{
std::cout << "All components are saturated" << std::endl;
}
break;
}
if ((old_energy - energy.first - energy.second) / (old_energy)
< this->parameter.stopping_ratio)
{ //relative energy progress stopping criterion
if (this->parameter.verbose > 1)
{
std::cout << "Stopping criterion reached" << std::endl;
}
break;
}
if (ite_main>=this->parameter.max_ite_main)
{ //max number of iteration
if (this->parameter.verbose > 1)
{
std::cout << "Max number of iteration reached" << std::endl;
}
break;
}
old_energy = energy.first + energy.second;
}
if (this->parameter.cutoff > 0)
{
this->cutoff();
}
return std::pair<std::vector<T>, std::vector<T>>(energy_out, time_out);
}
//=============================================================================================
//=========== VIRTUAL METHODS DEPENDING ON THE CHOICE OF FIDELITY FUNCTION =====================
//=============================================================================================
//
//=============================================================================================
//============================= SPLIT ===========================================
//=============================================================================================
virtual uint32_t split()
{
//compute the optimal binary partition
return 0;
}
//=============================================================================================
//================================ compute_energy_L2 ====================================
//=============================================================================================
virtual std::pair<T,T> compute_energy()
{
//compute the current energy
return std::pair<T,T>(0,0);
}
//=============================================================================================
//================================= COMPUTE_VALUE =========================================
//=============================================================================================
virtual std::pair<std::vector<T>, T> compute_value(const uint32_t & ind_com)
{
//compute the optimal the values associated with the current partition
return std::pair<std::vector<T>, T>(std::vector<T>(0),0);
}
//=============================================================================================
//================================= COMPUTE_MERGE_GAIN =========================================
//=============================================================================================
virtual std::pair<std::vector<T>, T> compute_merge_gain(const VertexDescriptor<T> & comp1
, const VertexDescriptor<T> & comp2)
{
//compute the gain of mergeing two connected components
return std::pair<std::vector<T>, T>(std::vector<T>(0),0);
}
//=============================================================================================
//========================== END OF VIRTUAL METHODS ===========================================
//=============================================================================================
//
//=============================================================================================
//============================= INITIALIZE ===========================================
//=============================================================================================
void initialize()
{
//build the reduced graph with one component, fill the first vector of components
//and add the sink and source nodes
VertexIterator<T> ite_ver, ite_ver_end;
EdgeAttributeMap<T> edge_attribute_map
= boost::get(boost::edge_bundle, this->main_graph);
this->components[0] = std::vector<VertexDescriptor<T>> (0);//(this->nVertex);
this->root_vertex[0] = *boost::vertices(this->main_graph).first;
this->nVertex = boost::num_vertices(this->main_graph);
this->nEdge = boost::num_edges(this->main_graph);
//--------compute the first reduced graph----------------------------------------------------------
for (boost::tie(ite_ver, ite_ver_end) = boost::vertices(this->main_graph);
ite_ver != ite_ver_end; ++ite_ver)
{
this->components[0].push_back(*ite_ver);
}
this->lastIterator = ite_ver;
this->compute_value(0);
//--------build the link to source and sink--------------------------------------------------------
this->source = boost::add_vertex(this->main_graph);
this->sink = boost::add_vertex(this->main_graph);
uint32_t eIndex = boost::num_edges(this->main_graph);
ite_ver = boost::vertices(this->main_graph).first;
for (uint32_t ind_ver = 0; ind_ver < this->nVertex ; ind_ver++)
{
// note that source and edge will have many nieghbors, and hence boost::edge should never be called to get
// the in_edge. use the out_edge and then reverse_Edge
addDoubledge<T>(this->main_graph, this->source, boost::vertex(ind_ver, this->main_graph), 0.,
eIndex, edge_attribute_map , false);
eIndex +=2;
addDoubledge<T>(this->main_graph, boost::vertex(ind_ver, this->main_graph), this->sink, 0.,
eIndex, edge_attribute_map, false);
eIndex +=2;
++ite_ver;
}
}
//=============================================================================================
//================================ COMPUTE_REDUCE_VALUE ====================================
//=============================================================================================
void compute_reduced_value()
{
for (uint32_t ind_com = 0; ind_com < this->components.size(); ++ind_com)
{ //compute the reduced value of each component
compute_value(ind_com);
}
}
//=============================================================================================
//============================= ACTIVATE_EDGES ==========================================
//=============================================================================================
uint32_t activate_edges(bool allows_saturation = true)
{ //this function analyzes the optimal binary partition to detect:
//- saturated components (i.e. uncuttable)
//- new activated edges
VertexAttributeMap<T> vertex_attribute_map
= boost::get(boost::vertex_bundle, this->main_graph);
EdgeAttributeMap<T> edge_attribute_map
= boost::get(boost::edge_bundle, this->main_graph);
//saturation is the proportion of nodes in saturated components
uint32_t saturation = 0;
uint32_t nb_comp = this->components.size();
//---- first check if the component are saturated-------------------------
//#pragma omp parallel for if (this->parameter.parallel) schedule(dynamic)
for (uint32_t ind_com = 0; ind_com < nb_comp; ind_com++)
{
if (this->saturated_components[ind_com])
{ //ind_com is saturated, we increement saturation by ind_com size
saturation += this->components[ind_com].size();
continue;
}
std::vector<T> totalWeight(2,0);
for (uint32_t ind_ver = 0; ind_ver < this->components[ind_com].size(); ind_ver++)
{
bool isSink
= (vertex_attribute_map(this->components[ind_com][ind_ver]).color
== vertex_attribute_map(this->sink).color);
if (isSink)
{
totalWeight[0] += vertex_attribute_map(this->components[ind_com][ind_ver]).weight;
}
else
{
totalWeight[1] += vertex_attribute_map(this->components[ind_com][ind_ver]).weight;
}
}
if (allows_saturation && ((totalWeight[0] == 0)||(totalWeight[1] == 0)))
{
//the component is saturated
this->saturateComponent(ind_com);
saturation += this->components[ind_com].size();
}
}
//----check which edges have been activated----
EdgeIterator<T> ite_edg, ite_edg_end;
uint32_t color_v1, color_v2, color_combination;
for (boost::tie(ite_edg, ite_edg_end) = boost::edges(this->main_graph);
ite_edg != ite_edg_end; ++ite_edg)
{
if (!edge_attribute_map(*ite_edg).realEdge )
{
continue;
}
color_v1 = vertex_attribute_map(boost::source(*ite_edg, this->main_graph)).color;
color_v2 = vertex_attribute_map(boost::target(*ite_edg, this->main_graph)).color;
//color_source = 0, color_sink = 4, uncolored = 1
//we want an edge when a an interface source/sink
//this corresponds to a sum of 4
//for the case of uncolored nodes we arbitrarily chose source-uncolored
color_combination = color_v1 + color_v2;
if ((color_combination == 0)||(color_combination == 2)||(color_combination == 2)
||(color_combination == 8))
{ //edge between two vertices of the same color
continue;
}
//the edge is active!
edge_attribute_map(*ite_edg).isActive = true;
edge_attribute_map(*ite_edg).capacity = 0;
vertex_attribute_map(boost::source(*ite_edg, this->main_graph)).isBorder = true;
vertex_attribute_map(boost::target(*ite_edg, this->main_graph)).isBorder = true;
}
return saturation;
}
//=============================================================================================
//============================= REDUCE ===========================================
//=============================================================================================
void reduce()
{ //compute the reduced graph, and if need be performed a backward check
this->compute_connected_components();
if (this->parameter.backward_step)
{ //compute the structure of the reduced graph
this->compute_reduced_graph();
//check for beneficial merges
this->merge(false);
}
else
{ //compute only the value associated to each connected components
this->compute_reduced_value();
}
}
//=============================================================================================
//============================== compute_connected_components=========================================
//=============================================================================================
void compute_connected_components()
{ //this function compute the connected components of the graph with active edges removed
//the boolean vector indicating wether or not the edges and vertices have been seen already
//the root is the first vertex of a component
//this function is written such that the new components are appended at the end of components
//this allows not to recompute saturated component
VertexAttributeMap<T> vertex_attribute_map
= boost::get(boost::vertex_bundle, this->main_graph);
VertexIndexMap<T> vertex_index_map =get(boost::vertex_index, this->main_graph);
//indicate which edges and nodes have been seen already by the dpsearch
std::vector<bool> edges_seen (this->nEdge, false);
std::vector<bool> vertices_seen (this->nVertex+2, false);
vertices_seen[vertex_index_map(this->source)] = true;
vertices_seen[vertex_index_map(this->sink)] = true;
//-------- start with the known roots------------------------------------------------------
//#pragma omp parallel for if (this->parameter.parallel) schedule(dynamic)
for (uint32_t ind_com = 0; ind_com < this->root_vertex.size(); ind_com++)
{
VertexDescriptor<T> root = this->root_vertex[ind_com]; //the first vertex of the component
if (this->saturated_components[ind_com])
{ //this component is saturated, we don't need to recompute it
for (uint32_t ind_ver = 0; ind_ver < this->components[ind_com].size(); ++ind_ver)
{
vertices_seen[vertex_index_map(this->components[ind_com][ind_ver])] = true;
}
}
else
{ //compute the new content of this component
this->components.at(ind_com) = connected_comp_from_root(root, this->components.at(ind_com).size()
, vertices_seen , edges_seen);
}
}
//----now look for components that did not already exists----
VertexIterator<T> ite_ver;
for (ite_ver = boost::vertices(this->main_graph).first;
ite_ver != this->lastIterator; ++ite_ver)
{
if (vertices_seen[vertex_index_map(*ite_ver)])
{
continue;
} //this vertex is not currently in a connected component
VertexDescriptor<T> root = *ite_ver; //we define it as the root of a new component
uint32_t current_component_size =
this->components[vertex_attribute_map(root).in_component].size();
this->components.push_back(
connected_comp_from_root(root, current_component_size
, vertices_seen, edges_seen));
this->root_vertex.push_back(root);
this->saturated_components.push_back(false);
}
this->components.shrink_to_fit();
}
//=============================================================================================
//============================== CONNECTED_COMP_FROM_ROOT=========================================
//=============================================================================================
inline std::vector<VertexDescriptor<T>> connected_comp_from_root(const VertexDescriptor<T> & root
, const uint32_t & size_comp, std::vector<bool> & vertices_seen , std::vector<bool> & edges_seen)
{
//this function compute the connected component of the graph with active edges removed
// associated with the root ROOT by performing a depth search first
EdgeAttributeMap<T> edge_attribute_map
= boost::get(boost::edge_bundle, this->main_graph);
VertexIndexMap<T> vertex_index_map = get(boost::vertex_index, this->main_graph);
EdgeIndexMap<T> edge_index_map = get(&EdgeAttribute<T>::index, this->main_graph);
std::vector<VertexDescriptor<T>> vertices_added; //the vertices in the current connected component
// vertices_added contains the vertices that have been added to the current coomponent
vertices_added.reserve(size_comp);
//heap_explore contains the vertices to be added to the current component
std::vector<VertexDescriptor<T>> vertices_to_add;
vertices_to_add.reserve(size_comp);
VertexDescriptor<T> vertex_current; //the node being consideed
EdgeDescriptor edge_current, edge_reverse; //the edge being considered
//fill the heap with the root node
vertices_to_add.push_back(root);
while (vertices_to_add.size()>0)
{ //as long as there are vertices left to add
vertex_current = vertices_to_add.back(); //the current node is the last node to add
vertices_to_add.pop_back(); //remove the current node from the vertices to add
if (vertices_seen[vertex_index_map(vertex_current)])
{ //this vertex has already been treated
continue;
}
vertices_added.push_back(vertex_current); //we add the current node
vertices_seen[vertex_index_map(vertex_current)] = true ; //and flag it as seen
//----we now explore the neighbors of current_node
typename boost::graph_traits<Graph<T>>::out_edge_iterator ite_edg, ite_edg_end;
for (boost::tie(ite_edg,ite_edg_end) = boost::out_edges(vertex_current, this->main_graph);
ite_edg != ite_edg_end; ++ite_edg)
{ //explore edges leaving current_node
edge_current = *ite_edg;
if (edge_attribute_map(*ite_edg).isActive || (edges_seen[edge_index_map(edge_current)]))
{ //edge is either active or treated, we skip it
continue;
}
//the target of this edge is a node to add
edge_reverse = edge_attribute_map(edge_current).edge_reverse;
edges_seen[edge_index_map(edge_current)] = true;
edges_seen[edge_index_map(edge_reverse)] = true;
vertices_to_add.push_back(boost::target(edge_current, this->main_graph));
}
}
vertices_added.shrink_to_fit();
return vertices_added;
}
//=============================================================================================
//================================ COMPUTE_REDUCE_GRAPH ====================================
//=============================================================================================
void compute_reduced_graph()
{ //compute the adjacency structure between components as well as weight and value of each component
//this is stored in the reduced graph structure
EdgeAttributeMap<T> edge_attribute_map
= boost::get(boost::edge_bundle, this->main_graph);
VertexAttributeMap<T> vertex_attribute_map
= boost::get(boost::vertex_bundle, this->main_graph);
this->reduced_graph = Graph<T>(this->components.size());
VertexAttributeMap<T> component_attribute_map = boost::get(boost::vertex_bundle, this->reduced_graph);
//----fill the value sof the reduced graph----
#pragma omp parallel for schedule(dynamic)
for (uint32_t ind_com = 0; ind_com < this->components.size(); ind_com++)
{
std::pair<std::vector<T>, T> component_values_and_weight = this->compute_value(ind_com);
//----fill the value and weight field of the reduced graph-----------------------------
VertexDescriptor<T> reduced_vertex = boost::vertex(ind_com, this->reduced_graph);
component_attribute_map[reduced_vertex] = VertexAttribute<T>(this->dim);
component_attribute_map(reduced_vertex).weight
= component_values_and_weight.second;
for(uint32_t i_dim=0; i_dim<this->dim; i_dim++)
{
component_attribute_map(reduced_vertex).value[i_dim]
= component_values_and_weight.first[i_dim];
}
}
//------compute the edges of the reduced graph
EdgeAttributeMap<T> border_edge_attribute_map = boost::get(boost::edge_bundle, this->reduced_graph);
this->borders.clear();
EdgeDescriptor edge_current, border_edge_current;
uint32_t ind_border_edge = 0, comp1, comp2, component_source, component_target;
VertexDescriptor<T> source_component, target_component;
bool reducedEdgeExists;
typename boost::graph_traits<Graph<T>>::edge_iterator ite_edg, ite_edg_end;
for (boost::tie(ite_edg,ite_edg_end) = boost::edges(this->main_graph); ite_edg != ite_edg_end; ++ite_edg)
{
if (!edge_attribute_map(*ite_edg).realEdge)
{ //edges linking the source or edge node do not take part
continue;
}
edge_current = *ite_edg;
//compute the connected components of the source and target of current_edge
comp1 = vertex_attribute_map(boost::source(edge_current, this->main_graph)).in_component;
comp2 = vertex_attribute_map(boost::target(edge_current, this->main_graph)).in_component;
if (comp1==comp2)
{ //this edge links two nodes in the same connected component
continue;
}
//by convention we note component_source the smallest index and
//component_target the largest
component_source = std::min(comp1,comp2);
component_target = std::max(comp1,comp2);
//retrieve the corresponding vertex in the reduced graph
source_component = boost::vertex(component_source, this->reduced_graph);
target_component = boost::vertex(component_target, this->reduced_graph);
//try to add the border-edge linking those components in the reduced graph
boost::tie(border_edge_current, reducedEdgeExists)
= boost::edge(source_component, target_component, this->reduced_graph);
if (!reducedEdgeExists)
{ //this border-edge did not already existed in the reduced graph
//border_edge_current = boost::add_edge(source_component, target_component, this->reduced_graph).first;
border_edge_current = boost::add_edge(source_component, target_component, this->reduced_graph).first;
border_edge_attribute_map(border_edge_current).index = ind_border_edge;
border_edge_attribute_map(border_edge_current).weight = 0;
ind_border_edge++;
//create a new entry for the borders list containing this border
this->borders.push_back(std::vector<EdgeDescriptor>(0));
}
//add the weight of the current edge to the weight of the border-edge
border_edge_attribute_map(border_edge_current).weight += 0.5*edge_attribute_map(edge_current).weight;
this->borders[border_edge_attribute_map(border_edge_current).index].push_back(edge_current);
}
}
//=============================================================================================
//================================ MERGE ====================================
//=============================================================================================
uint32_t merge(bool is_cutoff)
{
// TODO: right now we only do one loop through the heap of potential mergeing, and only
//authorize one mergeing per component. We could update the gain and merge until it is no longer
//beneficial
//check wether the energy can be decreased by removing edges from the reduced graph
//----load graph structure---
VertexAttributeMap<T> vertex_attribute_map
= boost::get(boost::vertex_bundle, this->main_graph);
VertexAttributeMap<T> component_attribute_map
= boost::get(boost::vertex_bundle, this->reduced_graph);
EdgeAttributeMap<T> border_edge_attribute_map
= boost::get(boost::edge_bundle, this->reduced_graph);
EdgeAttributeMap<T> edge_attribute_map
= boost::get(boost::edge_bundle, this->main_graph);
VertexIndexMap<T> component_index_map = boost::get(boost::vertex_index, this->reduced_graph);
//-----------------------------------
EdgeDescriptor border_edge_current;
typename boost::graph_traits<Graph<T>>::edge_iterator ite_border, ite_border_end;
typename std::vector<EdgeDescriptor>::iterator ite_border_edge;
VertexDescriptor<T> source_component, target_component;
uint32_t ind_source_component, ind_target_component, border_edge_currentIndex;
//gain_current is the vector of gains associated with each mergeing move
//std::vector<T> gain_current(boost::num_edges(this->reduced_graph));
//we store in merge_queue the potential mergeing with a priority on the potential gain
std::priority_queue<ComponentsFusion<T>, std::vector<ComponentsFusion<T>>, lessComponentsFusion<T>> merge_queue;
T gain; // the gain obtained by removing the border corresponding to the edge in the reduced graph
for (boost::tie(ite_border,ite_border_end) = boost::edges(this->reduced_graph); ite_border != ite_border_end; ++ite_border)
{
//a first pass go through all the edges in the reduced graph and compute the gain obtained by
//mergeing the corresponding vertices
border_edge_current = *ite_border;
border_edge_currentIndex = border_edge_attribute_map(border_edge_current).index;
//retrieve the two components corresponding to this border
source_component = boost::source(border_edge_current, this->reduced_graph);
target_component = boost::target(border_edge_current, this->reduced_graph);
if (is_cutoff && component_attribute_map(source_component).weight > this->parameter.cutoff
&&component_attribute_map(target_component).weight > this->parameter.cutoff)
{
continue;
}
ind_source_component = component_index_map(source_component);
ind_target_component = component_index_map(target_component);
//----now compute the gain of mergeing those two components-----
// compute the fidelity lost by mergeing the two connected components
std::pair<std::vector<T>, T> merge_gain = compute_merge_gain(source_component, target_component);
// the second part is due to the removing of the border
gain = merge_gain.second
+ border_edge_attribute_map(border_edge_current).weight * this->parameter.reg_strenth;
//mergeing_information store the indexes of the components as well as the edge index and the gain
//in a structure ordered by the gain
ComponentsFusion<T> mergeing_information(ind_source_component, ind_target_component, border_edge_currentIndex, gain);
mergeing_information.merged_value = merge_gain.first;
if (is_cutoff || gain>0)
{ //it is beneficial to merge those two components
//we add them to the merge_queue
merge_queue.push(mergeing_information);
//gain_current.at(border_edge_currentIndex) = gain;
}
}
uint32_t n_merged = 0;
//----go through the priority queue of merges and perform them as long as it is beneficial---
//is_merged indicate which components no longer exists because they have been merged with a neighboring component
std::vector<bool> is_merged(this->components.size(), false);
//to_destroy indicates the components that are needed to be removed
std::vector<bool> to_destroy(this->components.size(), false);
while(merge_queue.size()>0)
{ //loop through the potential mergeing and accept the ones that decrease the energy
ComponentsFusion<T> mergeing_information = merge_queue.top();
if (!is_cutoff && mergeing_information.merge_gain<=0)
{ //no more mergeing provide a gain in energy
break;
}
merge_queue.pop();
if (is_merged.at(mergeing_information.comp1) || (is_merged.at(mergeing_information.comp2)))
{
//at least one of the components have already been merged
continue;
}
n_merged++;
//---proceed with the fusion of comp1 and comp2----
//add the vertices of comp2 to comp1
this->components[mergeing_information.comp1].insert(this->components[mergeing_information.comp1].end()
,components[mergeing_information.comp2].begin(), this->components[mergeing_information.comp2].end());
//if comp1 was saturated it might not be anymore
this->saturated_components[mergeing_information.comp1] = false;
//the new weight is the sum of both weights
component_attribute_map(mergeing_information.comp1).weight
+= component_attribute_map(mergeing_information.comp2).weight;
//the new value is already computed in mergeing_information
component_attribute_map(mergeing_information.comp1).value = mergeing_information.merged_value;
//we deactivate the border between comp1 and comp2
for (ite_border_edge = this->borders.at(mergeing_information.border_index).begin();
ite_border_edge != this->borders.at(mergeing_information.border_index).end() ; ++ite_border_edge)
{
edge_attribute_map(*ite_border_edge).isActive = false;
}
is_merged.at(mergeing_information.comp1) = true;
is_merged.at(mergeing_information.comp2) = true;
to_destroy.at(mergeing_information.comp2) = true;
}
//we now rebuild the vectors components, rootComponents and saturated_components
std::vector<std::vector<VertexDescriptor<T>>> new_components;
std::vector<VertexDescriptor<T>> new_root_vertex;
std::vector<bool> new_saturated_components;
uint32_t ind_new_component = 0;
for (uint32_t ind_com = 0; ind_com < this->components.size(); ind_com++)
{
if (to_destroy.at(ind_com))
{ //this component has been removed
continue;
}//this components is kept
new_components.push_back(this->components.at(ind_com));
new_root_vertex.push_back(this->root_vertex.at(ind_com));
new_saturated_components.push_back(saturated_components.at(ind_com));
//if (is_merged.at(ind_com))
//{ //we need to update the value of the vertex in this component
for (uint32_t ind_ver = 0; ind_ver < this->components[ind_com].size(); ++ind_ver)
{
vertex_attribute_map(this->components[ind_com][ind_ver]).value
= component_attribute_map(boost::vertex(ind_com, this->reduced_graph)).value;
vertex_attribute_map(this->components[ind_com][ind_ver]).in_component
= ind_new_component;//ind_com;
}
//}
ind_new_component++;
}
this->components = new_components;
this->root_vertex = new_root_vertex;
this->saturated_components = new_saturated_components;
return n_merged;
}
//=============================================================================================
//================================ CUTOFF ====================================
//=============================================================================================
void cutoff()
{
int i = 0;
uint32_t n_merged;
while (true)
{
//this->compute_connected_components();
this->compute_reduced_graph();
n_merged = merge(true);
i++;
if (n_merged==0 || i>50)
{
break;
}
}
}
// //=============================================================================================
// //================================ CUTOFF ====================================
// //=============================================================================================
// void cutoff()
// {
// // Loop through all components and merge the one smaller than the cutoff.
// // It merges components which increase he energy the least
// //----load graph structure---
// VertexAttributeMap<T> vertex_attribute_map
// = boost::get(boost::vertex_bundle, this->main_graph);
// VertexAttributeMap<T> reduced_vertex_attribute_map
// = boost::get(boost::vertex_bundle, this->reduced_graph);
// EdgeAttributeMap<T> reduced_edge_attribute_map
// = boost::get(boost::edge_bundle, this->reduced_graph);
// EdgeAttributeMap<T> edge_attribute_map
// = boost::get(boost::edge_bundle, this->main_graph);
// VertexIndexMap<T> reduced_vertex_index_map = boost::get(boost::vertex_index, this->reduced_graph);
// EdgeIndexMap<T> reduced_edge_index_map = get(&EdgeAttribute<T>::index, this->reduced_graph);
// //-----------------------------------
// typename boost::graph_traits<Graph<T>>::vertex_iterator ite_comp, ite_comp_end;
// typename boost::graph_traits<Graph<T>>::out_edge_iterator ite_edg_out, ite_edg_out_end;
// typename boost::graph_traits<Graph<T>>::in_edge_iterator ite_edg_in, ite_edg_in_end;
// typename std::vector<EdgeDescriptor>::iterator ite_border_edge;
// VertexDescriptor<T> current_vertex, neighbor_vertex;
// //gain_current is the vector of gains associated with each mergeing move
// //we store in merge_queue the potential mergeing with a priority on the potential gain
// T gain; // the gain obtained by removing the border corresponding to the edge in the reduced graph
// std::vector<bool> to_destroy(this->components.size(), false); //components merged to be removed
// while (true)
// {
// this->compute_connected_components();
// this->compute_reduced_graph();
// bool has_merged = false;
// std::cout << "CUTTING OFF : " << this->components.size() << "COMPONENTS " << std::endl;
// for (boost::tie(ite_comp,ite_comp_end) = boost::vertices(this->reduced_graph); ite_comp != ite_comp_end; ++ite_comp)
// {
// current_vertex = *ite_comp;
// if (reduced_vertex_attribute_map(current_vertex).weight > this->parameter.cutoff
// || to_destroy.at(reduced_vertex_index_map(current_vertex)))
// {//component big enough to not be cut or already removed
// continue;
// }
// std::priority_queue<ComponentsFusion<T>, std::vector<ComponentsFusion<T>>, lessComponentsFusion<T>> merge_queue;
//std::cout << "COMPONENT " << reduced_vertex_index_map(current_vertex) << " IS OF SIZE"<< reduced_vertex_attribute_map(current_vertex).weight << std::endl;
// for (boost::tie(ite_edg_out,ite_edg_out_end) = boost::out_edges(current_vertex, this->reduced_graph);
// ite_edg_out != ite_edg_out_end; ++ite_edg_out)
// { //explore all neighbors
// neighbor_vertex = boost::target(*ite_edg_out, this->reduced_graph);
// std::pair<std::vector<T>, T> merge_gain = compute_merge_gain(current_vertex, neighbor_vertex);
// gain = merge_gain.second
// + reduced_edge_attribute_map(*ite_edg_out).weight * this->parameter.reg_strenth;
// ComponentsFusion<T> mergeing_information(reduced_vertex_index_map(current_vertex), reduced_vertex_index_map(neighbor_vertex)
// , reduced_edge_index_map(*ite_edg_out), gain);
// mergeing_information.merged_value = merge_gain.first;
// merge_queue.push(mergeing_information);
//std::cout << " NEI OUT " <<reduced_vertex_index_map(neighbor_vertex) << " GAIN"<< gain << std::endl;
// }
// for (boost::tie(ite_edg_in,ite_edg_in_end) = boost::in_edges(current_vertex, this->reduced_graph);
// ite_edg_in != ite_edg_in_end; ++ite_edg_in)
// { //explore all neighbors
// neighbor_vertex = boost::source(*ite_edg_in, this->reduced_graph);
// std::pair<std::vector<T>, T> merge_gain = compute_merge_gain(current_vertex, neighbor_vertex);
// gain = merge_gain.second
// + reduced_edge_attribute_map(*ite_edg_in).weight * this->parameter.reg_strenth;
// ComponentsFusion<T> mergeing_information(reduced_vertex_index_map(current_vertex), reduced_vertex_index_map(neighbor_vertex)
// , reduced_edge_index_map(*ite_edg_in), gain);
// mergeing_information.merged_value = merge_gain.first;
// merge_queue.push(mergeing_information);
//std::cout << " NEI IN" <<reduced_vertex_index_map(neighbor_vertex) << " GAIN"<< gain << std::endl;
// }
// if (merge_queue.empty())
// {
// continue;
// }
// has_merged = true;
// //select the most advantegeous neighboring components and merge it.
// ComponentsFusion<T> mergeing_information = merge_queue.top();
//std::cout << "BEST NEIGHBORS = " << mergeing_information.comp1 << " - " << mergeing_information.comp2 << " = " << mergeing_information .merge_gain
// << " Weight " << reduced_vertex_attribute_map(mergeing_information.comp2).weight << std::endl;
// this->components[mergeing_information.comp1].insert(this->components[mergeing_information.comp1].end()
// ,components[mergeing_information.comp2].begin(), this->components[mergeing_information.comp2].end());
// //the new weight is the sum of both weights
// reduced_vertex_attribute_map(mergeing_information.comp1).weight
// += reduced_vertex_attribute_map(mergeing_information.comp2).weight;
// //the new value is already computed in mergeing_information
// reduced_vertex_attribute_map(mergeing_information.comp1).value = mergeing_information.merged_value;
// //we deactivate the border between comp1 and comp2
// for (ite_border_edge = this->borders.at(mergeing_information.border_index).begin();
// ite_border_edge != this->borders.at(mergeing_information.border_index).end() ; ++ite_border_edge)
// {
// edge_attribute_map(*ite_border_edge).isActive = false;
// }
// to_destroy.at(mergeing_information.comp2) = true;
//std::cout << "=> " << reduced_vertex_index_map(current_vertex) << " IS OF SIZE"<< reduced_vertex_attribute_map(current_vertex).weight << std::endl;
// }
// //if (!has_merged)
// //{
// break;
// //}
// }
// //we now rebuild the vectors components, rootComponents and saturated_components
// std::vector<std::vector<VertexDescriptor<T>>> new_components;
// uint32_t ind_new_component = 0;
// for (uint32_t ind_com = 0; ind_com < this->components.size(); ind_com++)
// {
// if (to_destroy.at(ind_com))
// { //this component has been removed
// continue;
// }//this components is kept
// new_components.push_back(this->components.at(ind_com));
// //if (is_merged.at(ind_com))
// //{ //we need to update the value of the vertex in this component
// for (uint32_t ind_ver = 0; ind_ver < this->components[ind_com].size(); ++ind_ver)
// {
// vertex_attribute_map(this->components[ind_com][ind_ver]).value
// = reduced_vertex_attribute_map(boost::vertex(ind_com, this->reduced_graph)).value;
// vertex_attribute_map(this->components[ind_com][ind_ver]).in_component
// = ind_new_component;//ind_com;
// }
// //}
// ind_new_component++;
// }
// this->components = new_components;
// }
//===============================================================================================
//==========================saturateComponent====================================================
//===============================================================================================
inline void saturateComponent(const uint32_t & ind_com)
{ //this component is uncuttable and needs to be removed from further graph-cuts
EdgeAttributeMap<T> edge_attribute_map
= boost::get(boost::edge_bundle, this->main_graph);
this->saturated_components[ind_com] = true;
for (uint32_t i_ver = 0; i_ver < this->components[ind_com].size(); i_ver++)
{
VertexDescriptor<T> desc_v = this->components[ind_com][i_ver];
// because of the adjacency structure NEVER access edge (source,v) directly!
EdgeDescriptor edg_ver2source = boost::edge(desc_v, this->source,this->main_graph).first;
EdgeDescriptor edg_source2ver = edge_attribute_map(edg_ver2source).edge_reverse; //use edge_reverse instead
EdgeDescriptor edg_sink2ver = boost::edge(desc_v, this->sink,this->main_graph).first;
// we set the capacities of edges to source and sink to zero
edge_attribute_map(edg_source2ver).capacity = 0.;
edge_attribute_map(edg_sink2ver).capacity = 0.;
}
}
};
}
|
main.c | #include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <math.h>
#include <string.h>
#include <timer.h>
static double printAccuracy(double, double);
extern void ddot_mpfr(int, const double*, const double*, double*);
extern void ddot_blas(int, const double*, const double*, double*);
/* Naive versions. High-level Code */
extern void ddot_naive_scalar_comp(int, const double*, const double*, double*);
extern void ddot_naive_vec_comp(int, const double*, const double*, double*);
/* Kahan: Scalar gets intrinsic variant, because compiler performs poorly */
extern void ddot_kahan_scalar_comp(int, const double*, const double*, double*);
extern void ddot_kahan_scalar_intrin(int, const double*, const double*, double*);
extern void ddot_kahan_sse_intrin(int, const double*, const double*, double*);
extern void ddot_kahan_omp_sse_intrin(int, const double*, const double*, double*);
#ifdef __AVX__
extern void ddot_kahan_avx_intrin(int, const double*, const double*, double*);
extern void ddot_kahan_avx2_asm(int, const double*, const double*, double*);
extern void ddot_kahan_omp_avx_intrin(int, const double*, const double*, double*);
extern void ddot_kahan_omp_avx2_asm(int, const double*, const double*, double*);
#endif
/* Different OpenMP reduction variants */
extern void ddot_kahan_omp_scalar_comp_reduce(int, const double*, const double*, double*);
extern void ddot_kahan_omp_scalar_comp_kahan(int, const double*, const double*, double*);
extern void ddot_kahan_omp_scalar_comp_nokahan(int, const double*, const double*, double*);
/* Kahan-Babuska: Scalar gets intrinsic variant, because compiler performs poorly */
extern void ddot_kahan_babuska_scalar_comp(int, const double*, const double*, double*);
extern void ddot_kahan_babuska_vec_comp(int, const double*, const double*, double*);
extern void ddot_kahan_babuska_scalar_intrin(int, const double*, const double*, double*);
extern void ddot_kahan_babuska_sse_intrin(int, const double*, const double*, double*);
#ifdef __AVX__
extern void ddot_kahan_babuska_avx_intrin(int, const double*, const double*, double*);
#endif
void benchmark(char *version, void(*func)(int, const double *, const double *, double *), int N, const double *x, const double *y) {
static int refrun = 0;
static double ref = 0.0f;
double result;
int i, j;
double runtime = 0.0f;
/* run benchmark and increase number of iterations until runtime > 0.1s */
for (i=1; runtime < 0.1f; i=i*2) {
TimerData tdata;
timer_start(&tdata);
for (j=0; j<i; ++j)
func(N, x, y, &result);
timer_stop(&tdata);
runtime = timer_print(&tdata);
}
/* 'i' was doubled one time too often */
i = i / 2;
/* first run should be MPFR to set reference value */
if (refrun == 0) {
if (strncmp(version, "Reference", 9) != 0) {
printf("First version must be MPFR to set reference value!\n");
exit(EXIT_FAILURE);
}
ref = result;
refrun = 1;
}
/* output results */
printf("%s", version);
printf("Result %20.15f\t\t", result);
printf("Perf %f Elements/s\t",((double)N * (double)i)/runtime);
printf("Accuracy %g bits\t", printAccuracy(ref, result));
printf("%d iterations\n", i);
}
static void mem_allocate(
void** ptr,
int alignment,
uint64_t size)
{
int errorCode;
errorCode = posix_memalign(ptr, alignment, size);
if (errorCode)
{
if (errorCode == EINVAL)
{
fprintf(stderr,
"Alignment parameter is not a power of two\n");
exit(EXIT_FAILURE);
}
if (errorCode == ENOMEM)
{
fprintf(stderr,
"Insufficient memory to fulfill the request\n");
exit(EXIT_FAILURE);
}
}
if ((*ptr) == NULL)
{
fprintf(stderr, "posix_memalign failed!\n");
exit(EXIT_FAILURE);
}
}
static double printAccuracy(double ref, double result)
{
double acc;
if (fabs(ref-result) == 0)
{
acc = 53;
}
else
{
acc = log2(fabs(ref)) - log2(fabs(ref-result));
}
return acc;
}
static void init_benign(int N, double *x)
{
/* produce deterministic results */
srand48(1);
#pragma omp parallel for schedule(static)
for (int i=0; i<N; ++i)
x[i] = drand48()/((double)i*(double)i+1.);
}
static void compare(double ref, double res) {
if (res == ref)
printf("[OK]\n");
else {
printf("[FAIL: Ref: %f Is: %f Ref-Is: %f]\n", ref, res, ref-res);
exit(EXIT_FAILURE);
}
}
static void verify_test(double *A, double *B, int N) {
double ref, res;
ddot_mpfr(N, A, B, &ref); printf("N: %d\t", N);
printf("ddot_blas\t"); ddot_blas(N, A, B, &res); compare(ref, res);
/* Naive */
printf("ddot_naive_scalar_comp\t"); ddot_naive_scalar_comp(N, A, B, &res); compare(ref, res);
printf("ddot_naive_vec_comp\t"); ddot_naive_vec_comp(N, A, B, &res); compare(ref, res);
/* Kahan */
printf("ddot_kahan_scalar_comp\t"); ddot_kahan_scalar_comp(N, A, B, &res); compare(ref, res);
printf("ddot_kahan_scalar_intrin\t"); ddot_kahan_scalar_intrin(N, A, B, &res); compare(ref, res);
printf("ddot_kahan_sse_intrin\t"); ddot_kahan_sse_intrin(N, A, B, &res); compare(ref, res);
printf("ddot_kahan_omp_sse_intrin\t"); ddot_kahan_omp_sse_intrin(N, A, B, &res); compare(ref, res);
#ifdef __AVX__
printf("ddot_kahan_avx_intrin\t"); ddot_kahan_avx_intrin(N, A, B, &res); compare(ref, res);
printf("ddot_kahan_avx2_asm\t"); ddot_kahan_avx2_asm(N, A, B, &res); compare(ref, res);
printf("ddot_kahan_omp_avx_intrin\t"); ddot_kahan_omp_avx_intrin(N, A, B, &res); compare(ref, res);
printf("ddot_kahan_omp_avx2_asm\t"); ddot_kahan_omp_avx2_asm(N, A, B, &res); compare(ref, res);
#endif
/* OpenMP Reduction Variants */
printf("ddot_kahan_omp_scalar_comp_reduce\t"); ddot_kahan_omp_scalar_comp_reduce(N, A, B, &res); compare(ref, res);
printf("ddot_kahan_omp_scalar_comp_kahan\t"); ddot_kahan_omp_scalar_comp_kahan(N, A, B, &res); compare(ref, res);
printf("ddot_kahan_omp_scalar_comp_nokahan\t"); ddot_kahan_omp_scalar_comp_nokahan(N, A, B, &res); compare(ref, res);
/* Kahan-Babuska */
printf("ddot_kahan_babuska_scalar_comp\t"); ddot_kahan_babuska_scalar_comp(N, A, B, &res); compare(ref, res);
printf("ddot_kahan_babuska_vec_comp\t"); ddot_kahan_babuska_vec_comp(N, A, B, &res); compare(ref, res);
printf("ddot_kahan_babuska_scalar_intrin\t"); ddot_kahan_babuska_scalar_intrin(N, A, B, &res); compare(ref, res);
printf("ddot_kahan_babuska_sse_intrin\t"); ddot_kahan_babuska_sse_intrin(N, A, B, &res); compare(ref, res);
#ifdef __AVX__
printf("ddot_kahan_babuska_avx_intrin\t"); ddot_kahan_babuska_avx_intrin(N, A, B, &res); compare(ref, res);
#endif
printf("\n");
}
void verify(void) {
double *A, *B;
int N = 4096;
mem_allocate((void**) &A, 64, N * sizeof(double));
mem_allocate((void**) &B, 64, N * sizeof(double));
for (int i=0; i<4096; ++i) {
A[i] = 1.0f;
B[i] = 1.0f;
}
verify_test(A, B, 4096); /* power of two */
verify_test(A, B, 2); /* small value, smaller than AVX */
verify_test(A, B, 11); /* small value, larger than AVX */
verify_test(A, B, 269); /* medium value */
verify_test(A, B, 3571); /* prime */
for (int i=0; i<4096; ++i) {
A[i] = 1.0;
B[i] = 2.0;
}
verify_test(A, B, 2); /* small value, smaller than AVX */
verify_test(A, B, 11); /* small value, larger than AVX */
verify_test(A, B, 512); /* medium value */
verify_test(A, B, 3000); /* medium value */
}
void test_precision(int N, double *x, double *y) {
benchmark("Reference\t\t\t", ddot_mpfr, N, x, y);
benchmark("ddot_blas\t\t\t", ddot_blas, N, x, y);
/* Naive */
benchmark("ddot_naive_scalar_comp\t\t", ddot_naive_scalar_comp, N, x, y);
benchmark("ddot_naive_vec_comp\t\t", ddot_naive_vec_comp, N, x, y);
/* Kahan */
benchmark("ddot_kahan_scalar_comp\t\t", ddot_kahan_scalar_comp, N, x, y);
benchmark("ddot_kahan_scalar_intrin\t\t", ddot_kahan_scalar_intrin, N, x, y);
benchmark("ddot_kahan_sse_intrin\t\t", ddot_kahan_sse_intrin, N, x, y);
benchmark("ddot_kahan_omp_sse_intrin\t\t", ddot_kahan_omp_sse_intrin, N, x, y);
#ifdef __AVX__
benchmark("ddot_kahan_avx_intrin\t\t", ddot_kahan_avx_intrin, N, x, y);
benchmark("ddot_kahan_avx2_asm\t\t", ddot_kahan_avx2_asm, N, x, y);
benchmark("ddot_kahan_omp_avx_intrin\t\t", ddot_kahan_omp_avx_intrin, N, x, y);
benchmark("ddot_kahan_omp_avx2_asm\t\t", ddot_kahan_omp_avx2_asm, N, x, y);
#endif
/* Different OpenMP reduction variants */
benchmark("ddot_kahan_omp_scalar_comp_reduce\t\t", ddot_kahan_omp_scalar_comp_reduce, N, x, y);
benchmark("ddot_kahan_omp_scalar_comp_kahan\t\t", ddot_kahan_omp_scalar_comp_kahan, N, x, y);
benchmark("ddot_kahan_omp_scalar_comp_nokahan\t\t", ddot_kahan_omp_scalar_comp_nokahan, N, x, y);
/* Kahan-Babuska */
benchmark("ddot_kahan_babuska_scalar_comp\t\t", ddot_kahan_babuska_scalar_comp, N, x, y);
benchmark("ddot_kahan_babuska_vec_comp\t\t", ddot_kahan_babuska_vec_comp, N, x, y);
benchmark("ddot_kahan_babuska_scalar_intrin\t\t", ddot_kahan_babuska_scalar_intrin, N, x, y);
benchmark("ddot_kahan_babuska_sse_intrin\t\t", ddot_kahan_babuska_sse_intrin, N, x, y);
benchmark("ddot_kahan_babuska_avx_intrin\t\t", ddot_kahan_babuska_avx_intrin, N, x, y);
}
int main ( int argc, char * argv[] )
{
if (argc < 2) {
printf("usage: %s <elements per array>\n", argv[0]);
exit(EXIT_FAILURE);
}
double* x;
double* y;
int N = atoi(argv[1]);
if (strncmp("verify", argv[1], 6) == 0) {
verify();
exit(EXIT_SUCCESS);
}
timer_init();
printf("**********************************************************\n");
printf("Length %d\n",N);
mem_allocate((void**) &x, 64, N * sizeof(double));
mem_allocate((void**) &y, 64, N * sizeof(double));
init_benign(N, x);
init_benign(N, y);
test_precision(N, x, y);
}
|
mlp_mnist_f32.c | /******************************************************************************
* 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 *
******************************************************************************/
/* Evangelos Georganas, Alexander Heinecke (Intel Corp.)
******************************************************************************/
#include <libxsmm.h>
#include "../common/mnist.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
#if defined(_OPENMP)
# include <omp.h>
#endif
/* include c-based dnn library */
#include "../common/dnn_common.h"
#define CHKERR_LIBXSMM_DNN(A) { const int chkerr_libxsmm_dnn_ = A; if (LIBXSMM_DNN_SUCCESS != chkerr_libxsmm_dnn_) { \
fprintf(stderr, "%s\n", libxsmm_dnn_get_error(chkerr_libxsmm_dnn_)); global_status = chkerr_libxsmm_dnn_; } \
}
#define TEST_ACCURACY
int main(int argc, char* argv[])
{
float **act_libxsmm, **fil_libxsmm, **delact_libxsmm, **delfil_libxsmm;
float **bias_libxsmm, **delbias_libxsmm;
unsigned char **relumask_libxsmm;
int *label_libxsmm;
void* scratch = NULL;
size_t scratch_size = 0;
/* some parameters we can overwrite via cli,
default is some inner layer of overfeat */
int iters = 10; /* repetitions of benchmark */
int MB = 32; /* mini-batch size, "N" */
int fuse_type = 0; /* 0: nothing fused, 1: relu fused, 2: elementwise fused, 3: relu and elementwise fused */
char type = 'A'; /* 'A': ALL, 'F': FP, 'B': BP */
int bn = 64;
int bk = 64;
int bc = 64;
int *C; /* number of input feature maps, "C" */
int num_layers = 0;
const char *const env_check = getenv("CHECK");
const double check = LIBXSMM_ABS(0 == env_check ? 1 : atof(env_check));
#if defined(_OPENMP)
int nThreads = omp_get_max_threads(); /* number of threads */
#else
int nThreads = 1; /* number of threads */
#endif
unsigned long long l_start, l_end;
double l_total = 0.0;
double gflop = 0.0;
int i, j;
double fil_size = 0.0;
double act_size = 0.0;
libxsmm_dnn_fullyconnected_desc fullyconnected_desc;
libxsmm_dnn_fullyconnected** libxsmm_fc_layer;
libxsmm_dnn_optimizer_desc optimizer_desc;
libxsmm_dnn_optimizer** libxsmm_opt;
libxsmm_dnn_softmaxloss_desc softmaxloss_desc;
libxsmm_dnn_softmaxloss* libxsmm_softmax;
libxsmm_dnn_tensor** libxsmm_act;
libxsmm_dnn_tensor** libxsmm_delact;
libxsmm_dnn_tensor** libxsmm_fil;
libxsmm_dnn_tensor** libxsmm_delfil;
libxsmm_dnn_tensor** libxsmm_bias;
libxsmm_dnn_tensor** libxsmm_delbias;
libxsmm_dnn_tensor** libxsmm_relumask;
libxsmm_dnn_tensor* libxsmm_label;
libxsmm_dnn_tensor_datalayout* libxsmm_layout;
libxsmm_dnn_tensor_datalayout* libxsmm_layout2;
libxsmm_dnn_err_t status;
libxsmm_dnn_err_t global_status = LIBXSMM_DNN_SUCCESS;
if (argc > 1 && !strncmp(argv[1], "-h", 3)) {
printf("Usage: %s iters MB fuse_type type bn bk bc C1 C2 ... CN\n", argv[0]);
return 0;
}
libxsmm_rng_set_seed(1);
/* reading new values from cli */
i = 1;
num_layers = argc - 9;
if (argc > i) iters = atoi(argv[i++]);
if (argc > i) MB = atoi(argv[i++]);
if (argc > i) fuse_type = atoi(argv[i++]);
if (argc > i) type = *(argv[i++]);
if (argc > i) bn = atoi(argv[i++]);
if (argc > i) bk = atoi(argv[i++]);
if (argc > i) bc = atoi(argv[i++]);
/* allocate the number of channles buffer */
if ( num_layers < 1 ) {
printf("Usage: %s iters MB fuse_type type bn bk bc C1 C2 ... CN\n", argv[0]);
return 0;
}
C = (int*)malloc((num_layers+2)*sizeof(int));
for (j = 0 ; i < argc; ++i, ++j ) {
C[j] = atoi(argv[i]);
}
/* handle softmax config */
C[num_layers+1] = C[num_layers];
if (type != 'A' && type != 'F' && type != 'B') {
printf("type needs to be 'A' (All), 'F' (FP only), 'B' (BP only)\n");
return -1;
}
if ( (fuse_type < 0) || (fuse_type > 5) ) {
printf("fuse type needs to be 0 (None), 1 (Bias), 2 (ReLU), 3 (Sigmoid), 4 (Bias+ReLU), 5 (Bias+Sigmoid)\n");
return -1;
}
#if defined(__SSE3__)
_MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
_MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);
_MM_SET_ROUNDING_MODE(_MM_ROUND_NEAREST);
#endif
/* print some summary */
printf("##########################################\n");
printf("# Setting Up (Common) #\n");
printf("##########################################\n");
printf("PARAMS: N:%d\n", MB);
printf("PARAMS: Layers: %d\n", num_layers);
printf("PARAMS: ITERS:%d", iters); if (LIBXSMM_FEQ(0, check)) printf(" Threads:%d\n", nThreads); else printf("\n");
for (i = 0; i < num_layers; ++i ) {
if (i == 0) {
act_size += (double)(MB*C[i]*sizeof(float))/(1024.0*1024.0);
printf("SIZE Activations %i (%dx%d): %10.2f MiB\n", i, MB, C[i], (double)(MB*C[i]*sizeof(float))/(1024.0*1024.0) );
}
act_size += (double)(MB*C[i+1]*sizeof(float))/(1024.0*1024.0);
fil_size += (double)(C[i]*C[i+1]*sizeof(float))/(1024.0*1024.0);
printf("SIZE Filter %i (%dx%d): %10.2f MiB\n", i, C[i], C[i+1], (double)(C[i]*C[i+1]*sizeof(float))/(1024.0*1024.0) );
printf("SIZE Activations %i (%dx%d): %10.2f MiB\n", i+1, MB, C[i+1], (double)(MB*C[i+1]*sizeof(float))/(1024.0*1024.0) );
}
act_size += (double)(MB*C[num_layers+1]*sizeof(float))/(1024.0*1024.0);
printf("SIZE Activations softmax (%dx%d): %10.2f MiB\n", MB, C[num_layers+1], (double)(MB*C[num_layers+1]*sizeof(float))/(1024.0*1024.0) );
printf("\nTOTAL SIZE Activations: %10.2f MiB\n", act_size );
printf("TOTAL SIZE Filter: %10.2f MiB\n", fil_size );
printf("TOTAL SIZE delActivations: %10.2f MiB\n", act_size );
printf("TOTAL SIZE delFilter: %10.2f MiB\n", fil_size );
printf("TOTAL SIZE MLP: %10.2f MiB\n", (2.0*fil_size) + (2.0*act_size) );
/* allocate data */
/* +2 because of the softwax layer */
act_libxsmm = (float**)malloc( (num_layers+2)*sizeof(float*) );
delact_libxsmm = (float**)malloc( (num_layers+1)*sizeof(float*) );
for ( i = 0 ; i < num_layers+2; ++i ) {
act_libxsmm[i] = (float*)libxsmm_aligned_malloc( MB*C[i]*sizeof(float), 2097152);
/* softmax has no incoming gradients */
if ( i < num_layers+1 ) {
delact_libxsmm[i] = (float*)libxsmm_aligned_malloc( MB*C[i]*sizeof(float), 2097152);
}
}
fil_libxsmm = (float**)malloc( num_layers*sizeof(float*) );
delfil_libxsmm = (float**)malloc( num_layers*sizeof(float*) );
for ( i = 0 ; i < num_layers; ++i ) {
fil_libxsmm[i] = (float*)libxsmm_aligned_malloc( C[i]*C[i+1]*sizeof(float), 2097152);
delfil_libxsmm[i] = (float*)libxsmm_aligned_malloc( C[i]*C[i+1]*sizeof(float), 2097152);
}
bias_libxsmm = (float**)malloc( num_layers*sizeof(float*) );
delbias_libxsmm = (float**)malloc( num_layers*sizeof(float*) );
for ( i = 0 ; i < num_layers; ++i ) {
bias_libxsmm[i] = (float*)libxsmm_aligned_malloc( C[i+1]*sizeof(float), 2097152);
delbias_libxsmm[i] = (float*)libxsmm_aligned_malloc( C[i+1]*sizeof(float), 2097152);
}
relumask_libxsmm = (unsigned char**)malloc( num_layers*sizeof(unsigned char*) );
for ( i = 0 ; i < num_layers; ++i ) {
relumask_libxsmm[i] = (unsigned char*)libxsmm_aligned_malloc( MB*C[i+1]*sizeof(unsigned char), 2097152);
}
label_libxsmm = (int*)libxsmm_aligned_malloc( MB*sizeof(int), 2097152 );
/* init data */
for ( i = 0 ; i < num_layers+2; ++i ) {
init_buf( act_libxsmm[i], MB*C[i], 0, 0 );
}
for ( i = 0 ; i < num_layers+1; ++i ) {
init_buf( delact_libxsmm[i], MB*C[i], 0, 0 );
}
for ( i = 0 ; i < num_layers; ++i ) {
init_buf( fil_libxsmm[i], C[i]*C[i+1], 0, 0 );
}
for ( i = 0 ; i < num_layers; ++i ) {
init_buf( delfil_libxsmm[i], C[i]*C[i+1], 0, 0 );
}
for ( i = 0 ; i < num_layers; ++i ) {
init_buf( bias_libxsmm[i], C[i+1], 0, 0 );
}
for ( i = 0 ; i < num_layers; ++i ) {
init_buf( delbias_libxsmm[i], C[i+1], 0, 0 );
}
for ( i = 0 ; i < num_layers; ++i ) {
zero_buf_uint8( relumask_libxsmm[i], MB*C[i+1] );
}
zero_buf_int32( label_libxsmm, MB );
printf("\n");
printf("##########################################\n");
printf("# Setting Up (custom-Storage) #\n");
printf("##########################################\n");
libxsmm_fc_layer = (libxsmm_dnn_fullyconnected**) malloc( num_layers*sizeof(libxsmm_dnn_fullyconnected*) );
libxsmm_opt = (libxsmm_dnn_optimizer**) malloc( num_layers*sizeof(libxsmm_dnn_optimizer*) );
libxsmm_act = (libxsmm_dnn_tensor**) malloc( (num_layers+2)*sizeof(libxsmm_dnn_tensor*) );
libxsmm_delact = (libxsmm_dnn_tensor**) malloc( (num_layers+1)*sizeof(libxsmm_dnn_tensor*) );
libxsmm_fil = (libxsmm_dnn_tensor**) malloc( num_layers*sizeof(libxsmm_dnn_tensor*) );
libxsmm_delfil = (libxsmm_dnn_tensor**) malloc( num_layers*sizeof(libxsmm_dnn_tensor*) );
libxsmm_bias = (libxsmm_dnn_tensor**) malloc( num_layers*sizeof(libxsmm_dnn_tensor*) );
libxsmm_delbias = (libxsmm_dnn_tensor**) malloc( num_layers*sizeof(libxsmm_dnn_tensor*) );
libxsmm_relumask = (libxsmm_dnn_tensor**) malloc( num_layers*sizeof(libxsmm_dnn_tensor*) );
for ( i = 0; i < num_layers; ++i ) {
fullyconnected_desc.N = MB;
fullyconnected_desc.C = C[i];
fullyconnected_desc.K = C[i+1];
fullyconnected_desc.bn = (MB % bn == 0) ? bn : MB;
fullyconnected_desc.bc = (C[i ] % bc == 0) ? bc : C[i ];
fullyconnected_desc.bk = (C[i+1] % bk == 0) ? bk : C[i+1];
fullyconnected_desc.threads = nThreads;
fullyconnected_desc.compressed_A = 0;
fullyconnected_desc.sparsity_factor_A = 1;
fullyconnected_desc.datatype_in = LIBXSMM_DNN_DATATYPE_F32;
fullyconnected_desc.datatype_out = LIBXSMM_DNN_DATATYPE_F32;
fullyconnected_desc.buffer_format = LIBXSMM_DNN_TENSOR_FORMAT_NCPACKED;
fullyconnected_desc.filter_format = LIBXSMM_DNN_TENSOR_FORMAT_CKPACKED;
/* MNIST Specific where everywhere we use relu act except the last layer */
if (i < num_layers - 1) {
fullyconnected_desc.fuse_ops = LIBXSMM_DNN_FULLYCONNECTED_FUSE_RELU;
} else {
fullyconnected_desc.fuse_ops = LIBXSMM_DNN_FULLYCONNECTED_FUSE_NONE;
}
libxsmm_fc_layer[i] = libxsmm_dnn_create_fullyconnected( fullyconnected_desc, &status );
CHKERR_LIBXSMM_DNN( status );
optimizer_desc.C = C[i];
optimizer_desc.K = C[i+1];
optimizer_desc.bc = (C[i ] % bc == 0) ? bc : C[i ];
optimizer_desc.bk = (C[i+1] % bk == 0) ? bk : C[i+1];
optimizer_desc.learning_rate = 0.1f;
optimizer_desc.threads = nThreads;
optimizer_desc.opt_type = LIBXSMM_DNN_OPTIMIZER_SGD;
optimizer_desc.datatype = LIBXSMM_DNN_DATATYPE_F32;
optimizer_desc.datatype_master = LIBXSMM_DNN_DATATYPE_F32;
optimizer_desc.filter_format = LIBXSMM_DNN_TENSOR_FORMAT_CKPACKED;
libxsmm_opt[i] = libxsmm_dnn_create_optimizer( optimizer_desc, &status );
CHKERR_LIBXSMM_DNN( status );
/* setup LIBXSMM buffers */
if ( i == 0 ) {
libxsmm_layout = libxsmm_dnn_fullyconnected_create_tensor_datalayout( libxsmm_fc_layer[i], LIBXSMM_DNN_REGULAR_INPUT, &status ); CHKERR_LIBXSMM_DNN( status );
libxsmm_act[i] = libxsmm_dnn_link_tensor( libxsmm_layout, act_libxsmm[i], &status ); CHKERR_LIBXSMM_DNN( status );
libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout );
libxsmm_layout = libxsmm_dnn_fullyconnected_create_tensor_datalayout( libxsmm_fc_layer[i], LIBXSMM_DNN_GRADIENT_INPUT, &status ); CHKERR_LIBXSMM_DNN( status );
libxsmm_delact[i] = libxsmm_dnn_link_tensor( libxsmm_layout, delact_libxsmm[i], &status ); CHKERR_LIBXSMM_DNN( status );
libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout );
}
libxsmm_layout = libxsmm_dnn_fullyconnected_create_tensor_datalayout( libxsmm_fc_layer[i], LIBXSMM_DNN_REGULAR_OUTPUT, &status ); CHKERR_LIBXSMM_DNN( status );
libxsmm_act[i+1] = libxsmm_dnn_link_tensor( libxsmm_layout, act_libxsmm[i+1], &status ); CHKERR_LIBXSMM_DNN( status );
libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout );
libxsmm_layout = libxsmm_dnn_fullyconnected_create_tensor_datalayout( libxsmm_fc_layer[i], LIBXSMM_DNN_GRADIENT_OUTPUT, &status ); CHKERR_LIBXSMM_DNN( status );
libxsmm_delact[i+1] = libxsmm_dnn_link_tensor( libxsmm_layout, delact_libxsmm[i+1], &status ); CHKERR_LIBXSMM_DNN( status );
libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout );
libxsmm_layout = libxsmm_dnn_fullyconnected_create_tensor_datalayout( libxsmm_fc_layer[i], LIBXSMM_DNN_REGULAR_FILTER, &status ); CHKERR_LIBXSMM_DNN( status );
libxsmm_fil[i] = libxsmm_dnn_link_tensor( libxsmm_layout, fil_libxsmm[i], &status ); CHKERR_LIBXSMM_DNN( status );
libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout );
libxsmm_layout = libxsmm_dnn_fullyconnected_create_tensor_datalayout( libxsmm_fc_layer[i], LIBXSMM_DNN_GRADIENT_FILTER, &status ); CHKERR_LIBXSMM_DNN( status );
libxsmm_delfil[i] = libxsmm_dnn_link_tensor( libxsmm_layout, delfil_libxsmm[i], &status ); CHKERR_LIBXSMM_DNN( status );
libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout );
libxsmm_layout = libxsmm_dnn_fullyconnected_create_tensor_datalayout( libxsmm_fc_layer[i], LIBXSMM_DNN_REGULAR_CHANNEL_BIAS, &status ); CHKERR_LIBXSMM_DNN( status );
libxsmm_bias[i] = libxsmm_dnn_link_tensor( libxsmm_layout, bias_libxsmm[i], &status ); CHKERR_LIBXSMM_DNN( status );
libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout );
libxsmm_layout = libxsmm_dnn_fullyconnected_create_tensor_datalayout( libxsmm_fc_layer[i], LIBXSMM_DNN_GRADIENT_CHANNEL_BIAS, &status ); CHKERR_LIBXSMM_DNN( status );
libxsmm_delbias[i] = libxsmm_dnn_link_tensor( libxsmm_layout, delbias_libxsmm[i], &status ); CHKERR_LIBXSMM_DNN( status );
libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout );
libxsmm_layout = libxsmm_dnn_fullyconnected_create_tensor_datalayout( libxsmm_fc_layer[i], LIBXSMM_DNN_RELU_MASK, &status ); CHKERR_LIBXSMM_DNN( status );
libxsmm_relumask[i] = libxsmm_dnn_link_tensor( libxsmm_layout, relumask_libxsmm[i], &status ); CHKERR_LIBXSMM_DNN( status );
libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout );
/* bind buffers and filter to fc layer */
CHKERR_LIBXSMM_DNN( libxsmm_dnn_fullyconnected_bind_tensor( libxsmm_fc_layer[i], libxsmm_act[ i], LIBXSMM_DNN_REGULAR_INPUT ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_fullyconnected_bind_tensor( libxsmm_fc_layer[i], libxsmm_delact[i ], LIBXSMM_DNN_GRADIENT_INPUT ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_fullyconnected_bind_tensor( libxsmm_fc_layer[i], libxsmm_act[i+1], LIBXSMM_DNN_REGULAR_OUTPUT ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_fullyconnected_bind_tensor( libxsmm_fc_layer[i], libxsmm_delact[i+1], LIBXSMM_DNN_GRADIENT_OUTPUT ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_fullyconnected_bind_tensor( libxsmm_fc_layer[i], libxsmm_fil[i], LIBXSMM_DNN_REGULAR_FILTER ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_fullyconnected_bind_tensor( libxsmm_fc_layer[i], libxsmm_delfil[i], LIBXSMM_DNN_GRADIENT_FILTER ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_fullyconnected_bind_tensor( libxsmm_fc_layer[i], libxsmm_bias[i], LIBXSMM_DNN_REGULAR_CHANNEL_BIAS ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_fullyconnected_bind_tensor( libxsmm_fc_layer[i], libxsmm_delbias[i], LIBXSMM_DNN_GRADIENT_CHANNEL_BIAS ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_fullyconnected_bind_tensor( libxsmm_fc_layer[i], libxsmm_relumask[i], LIBXSMM_DNN_RELU_MASK ) );
/* bind filters to optimizer */
CHKERR_LIBXSMM_DNN( libxsmm_dnn_optimizer_bind_tensor( libxsmm_opt[i], libxsmm_fil[i], LIBXSMM_DNN_REGULAR_FILTER ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_optimizer_bind_tensor( libxsmm_opt[i], libxsmm_delfil[i], LIBXSMM_DNN_GRADIENT_FILTER ) );
/* let's allocate and bind scratch */
if ( libxsmm_dnn_fullyconnected_get_scratch_size( libxsmm_fc_layer[i], &status ) > scratch_size ) {
scratch_size = libxsmm_dnn_fullyconnected_get_scratch_size( libxsmm_fc_layer[i], &status );
CHKERR_LIBXSMM_DNN( status );
if ( scratch != NULL ) {
libxsmm_free( scratch );
}
scratch = libxsmm_aligned_malloc( scratch_size, 2097152 );
init_buf( (float*)scratch, scratch_size/4, 0, 0 );
}
if ( libxsmm_dnn_optimizer_get_scratch_size( libxsmm_opt[i], &status ) > scratch_size ) {
scratch_size = libxsmm_dnn_optimizer_get_scratch_size( libxsmm_opt[i], &status );
CHKERR_LIBXSMM_DNN( status );
if ( scratch != NULL ) {
libxsmm_free( scratch );
}
scratch = libxsmm_aligned_malloc( scratch_size, 2097152 );
init_buf( (float*)scratch, scratch_size/4, 0, 0 );
}
}
/* create softmax layer */
softmaxloss_desc.N = MB;
softmaxloss_desc.C = C[num_layers];
softmaxloss_desc.bn = (MB % bn == 0) ? bn : MB;
softmaxloss_desc.bc = (C[num_layers] % bc == 0) ? bc : C[num_layers];
softmaxloss_desc.loss_weight = 1.0;
softmaxloss_desc.threads = nThreads;
softmaxloss_desc.datatype = LIBXSMM_DNN_DATATYPE_F32;
softmaxloss_desc.buffer_format = LIBXSMM_DNN_TENSOR_FORMAT_NCPACKED;
libxsmm_softmax = libxsmm_dnn_create_softmaxloss( softmaxloss_desc, &status );
CHKERR_LIBXSMM_DNN( status );
libxsmm_layout = libxsmm_dnn_softmaxloss_create_tensor_datalayout( libxsmm_softmax, LIBXSMM_DNN_REGULAR_OUTPUT, &status ); CHKERR_LIBXSMM_DNN( status );
libxsmm_act[num_layers+1] = libxsmm_dnn_link_tensor( libxsmm_layout, act_libxsmm[num_layers+1], &status ); CHKERR_LIBXSMM_DNN( status );
libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout );
libxsmm_layout = libxsmm_dnn_softmaxloss_create_tensor_datalayout( libxsmm_softmax, LIBXSMM_DNN_LABEL, &status ); CHKERR_LIBXSMM_DNN( status );
libxsmm_label = libxsmm_dnn_link_tensor( libxsmm_layout, label_libxsmm, &status ); CHKERR_LIBXSMM_DNN( status );
libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_softmaxloss_bind_tensor( libxsmm_softmax, libxsmm_act[num_layers], LIBXSMM_DNN_REGULAR_INPUT ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_softmaxloss_bind_tensor( libxsmm_softmax, libxsmm_delact[num_layers], LIBXSMM_DNN_GRADIENT_INPUT ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_softmaxloss_bind_tensor( libxsmm_softmax, libxsmm_act[num_layers+1], LIBXSMM_DNN_REGULAR_OUTPUT ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_softmaxloss_bind_tensor( libxsmm_softmax, libxsmm_label, LIBXSMM_DNN_LABEL ) );
if ( libxsmm_dnn_softmaxloss_get_scratch_size( libxsmm_softmax, &status ) > scratch_size ) {
scratch_size = libxsmm_dnn_softmaxloss_get_scratch_size( libxsmm_softmax, &status );
CHKERR_LIBXSMM_DNN( status );
if ( scratch != NULL ) {
libxsmm_free( scratch );
}
scratch = libxsmm_aligned_malloc( scratch_size, 2097152 );
init_buf( (float*)scratch, scratch_size/4, 0, 0 );
}
/* bind scratch to all layers */
for ( i = 0; i < num_layers; ++i ) {
CHKERR_LIBXSMM_DNN( libxsmm_dnn_fullyconnected_bind_scratch( libxsmm_fc_layer[i], scratch ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_optimizer_bind_scratch( libxsmm_opt[i], scratch ) );
}
CHKERR_LIBXSMM_DNN( libxsmm_dnn_softmaxloss_bind_scratch( libxsmm_softmax, scratch ) );
int n_batches = NUM_TRAIN/MB, batch_id = 0;
int n_epochs = iters, epoch_id = 0;
float *input_acts = (float*)libxsmm_aligned_malloc( NUM_TRAIN * C[0] * sizeof(float), 2097152);
/* Read in input data */
char *train_image_path = "./mnist_data/train-images.idx3-ubyte";
char *train_label_path = "./mnist_data/train-labels.idx1-ubyte";
char *test_image_path = "./mnist_data/t10k-images.idx3-ubyte";
char *test_label_path = "./mnist_data/t10k-labels.idx1-ubyte";
load_mnist(train_image_path, train_label_path, test_image_path, test_label_path);
/* Format the input layer in NCNC blocked format */
int _i, _j;
for (_i = 0; _i < n_batches*MB; _i++) {
for (_j = 0; _j < C[0]; _j++) {
float val = (float) train_image[_i][_j];
int batchid = _i/MB;
int mb = _i % MB;
int _bn = (MB % bn == 0) ? bn : MB;
int _bc = (C[0] % bc == 0) ? bc : C[0];
float *cur_pos = input_acts + batchid * MB *C[0] + (mb / _bn) * C[0] * _bn + (_j / _bc) * _bn * _bc + (mb % _bn) * _bc + (_j % _bc);
*cur_pos = val;
}
}
libxsmm_layout = libxsmm_dnn_fullyconnected_create_tensor_datalayout( libxsmm_fc_layer[0], LIBXSMM_DNN_REGULAR_INPUT, &status ); CHKERR_LIBXSMM_DNN( status );
libxsmm_layout2 = libxsmm_dnn_softmaxloss_create_tensor_datalayout( libxsmm_softmax, LIBXSMM_DNN_LABEL, &status ); CHKERR_LIBXSMM_DNN( status );
n_batches = NUM_TRAIN/MB;
printf("###########################################\n");
printf("# Training MNIST with %d training samples #\n", n_batches*MB);
printf("###########################################\n");
l_start = libxsmm_timer_tick();
#if defined(_OPENMP)
# pragma omp parallel private(i,j,epoch_id,batch_id)
#endif
{
#if defined(_OPENMP)
const int tid = omp_get_thread_num();
#else
const int tid = 0;
#endif
for (epoch_id = 0; epoch_id < n_epochs; epoch_id++) {
for (batch_id = 0; batch_id < n_batches; batch_id++) {
/* Initialize input activations with the correct minibatch */
if (tid == 0) {
libxsmm_act[0] = libxsmm_dnn_link_tensor( libxsmm_layout, input_acts + batch_id * MB * C[0], &status ); CHKERR_LIBXSMM_DNN( status );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_fullyconnected_bind_tensor( libxsmm_fc_layer[0], libxsmm_act[0], LIBXSMM_DNN_REGULAR_INPUT ) );
libxsmm_label = libxsmm_dnn_link_tensor( libxsmm_layout2, train_label + batch_id * MB, &status ); CHKERR_LIBXSMM_DNN( status );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_softmaxloss_bind_tensor( libxsmm_softmax, libxsmm_label, LIBXSMM_DNN_LABEL ) );
}
#pragma omp barrier
for ( i = 0; i < num_layers; ++i) {
libxsmm_dnn_fullyconnected_execute_st( libxsmm_fc_layer[i], LIBXSMM_DNN_COMPUTE_KIND_FWD, 0, tid );
}
libxsmm_dnn_softmaxloss_execute_st( libxsmm_softmax, LIBXSMM_DNN_COMPUTE_KIND_FWD, 0, tid );
if ((tid == 0) && (batch_id == 0) && (epoch_id % 10 == 0 || epoch_id == n_epochs - 1 )) {
float new_loss;
new_loss = libxsmm_dnn_softmaxloss_get_loss(libxsmm_softmax, &status); CHKERR_LIBXSMM_DNN( status );
printf("Loss for epoch %d batch_id %d is %f\n", epoch_id, batch_id, new_loss);
}
libxsmm_dnn_softmaxloss_execute_st( libxsmm_softmax, LIBXSMM_DNN_COMPUTE_KIND_BWD, 0, tid );
for ( i = (num_layers-1); i > 0; --i) {
libxsmm_dnn_fullyconnected_execute_st( libxsmm_fc_layer[i], LIBXSMM_DNN_COMPUTE_KIND_BWDUPD, 0, tid );
libxsmm_dnn_optimizer_execute_st( libxsmm_opt[i], 0, tid );
}
libxsmm_dnn_fullyconnected_execute_st( libxsmm_fc_layer[0], LIBXSMM_DNN_COMPUTE_KIND_UPD, 0, tid );
libxsmm_dnn_optimizer_execute_st( libxsmm_opt[i], 0, tid );
}
}
}
l_end = libxsmm_timer_tick();
l_total = libxsmm_timer_duration(l_start, l_end);
gflop = 0.0;
for ( i = num_layers-1; i > 0; --i) {
gflop += (6.0*(double)MB*(double)C[i]*(double)C[i+1]*(double)n_epochs *(double)n_batches) / (1000.0*1000.0*1000.0);
}
gflop += (4.0*(double)MB*(double)C[0]*(double)C[1]*(double)n_epochs *(double)n_batches) / (1000.0*1000.0*1000.0);
printf("GFLOP = %.5g\n", gflop/((double)n_epochs *(double)n_batches));
printf("fp time = %.5g\n", ((double)(l_total/((double)n_epochs *(double)n_batches))));
printf("GFLOPS = %.5g\n", gflop/l_total);
printf("PERFDUMP,BP,%s,%i,%i,", LIBXSMM_VERSION, nThreads, MB );
for ( i = 0; i < num_layers; ++i ) {
printf("%i,", C[i] );
}
printf("%f,%f\n", ((double)(l_total/((double)n_epochs *(double)n_batches))), gflop/l_total);
#ifdef TEST_ACCURACY
/* Test accuracy */
n_batches = NUM_TEST/MB;
for (_i = 0; _i < n_batches * MB; _i++) {
for (_j = 0; _j < C[0]; _j++) {
float val = (float) test_image[_i][_j];
int batchid = _i/MB;
int mb = _i % MB;
int _bn = (MB % bn == 0) ? bn : MB;
int _bc = (C[0] % bc == 0) ? bc : C[0];
float *cur_pos = input_acts + batchid * MB *C[0] + (mb / _bn) * C[0] * _bn + (_j / _bc) * _bn * _bc + (mb % _bn) * _bc + (_j % _bc);
*cur_pos = val;
}
}
n_batches = NUM_TEST/MB;
unsigned int hits = 0;
unsigned int samples = 0;
#if defined(_OPENMP)
# pragma omp parallel private(i,j,batch_id)
#endif
{
#if defined(_OPENMP)
const int tid = omp_get_thread_num();
#else
const int tid = 0;
#endif
for (batch_id = 0; batch_id < n_batches; batch_id++) {
/* Initialize input activations with the correct minibatch */
if (tid == 0) {
libxsmm_act[0] = libxsmm_dnn_link_tensor( libxsmm_layout, input_acts + batch_id * MB * C[0], &status ); CHKERR_LIBXSMM_DNN( status );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_fullyconnected_bind_tensor( libxsmm_fc_layer[0], libxsmm_act[0], LIBXSMM_DNN_REGULAR_INPUT ) );
libxsmm_label = libxsmm_dnn_link_tensor( libxsmm_layout2, test_label + batch_id * MB, &status ); CHKERR_LIBXSMM_DNN( status );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_softmaxloss_bind_tensor( libxsmm_softmax, libxsmm_label, LIBXSMM_DNN_LABEL ) );
}
#pragma omp barrier
for ( i = 0; i < num_layers; ++i) {
libxsmm_dnn_fullyconnected_execute_st( libxsmm_fc_layer[i], LIBXSMM_DNN_COMPUTE_KIND_FWD, 0, tid );
}
libxsmm_dnn_softmaxloss_execute_st( libxsmm_softmax, LIBXSMM_DNN_COMPUTE_KIND_FWD, 0, tid );
if (tid == 0) {
for (_i = 0; _i < MB; _i++) {
int label = *(test_label + batch_id * MB + _i);
int max_id = 0;
float max_val = 0.0;
max_val = *(act_libxsmm[num_layers+1] + _i * 10);
float sum = max_val;
/* Find predicted label */
for (_j = 1; _j < 10; _j++) {
float val = *(act_libxsmm[num_layers+1] + _i * 10 + _j);
sum += val;
if (val > max_val) {
max_id = _j;
max_val = val;
}
}
/* Compare with true label */
if (max_id == label) {
hits++;
}
samples++;
}
}
#pragma omp barrier
}
}
printf("Accuracy is %f %% (%d test samples)\n", (1.0*hits)/(1.0*samples)*100.0, samples);
#endif
libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout );
libxsmm_dnn_destroy_tensor_datalayout( libxsmm_layout2 );
for ( i = 0; i < num_layers; ++i ) {
/* clean-up */
CHKERR_LIBXSMM_DNN( libxsmm_dnn_fullyconnected_release_scratch( libxsmm_fc_layer[i] ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_fullyconnected_release_tensor( libxsmm_fc_layer[i], LIBXSMM_DNN_REGULAR_INPUT ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_fullyconnected_release_tensor( libxsmm_fc_layer[i], LIBXSMM_DNN_GRADIENT_INPUT ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_fullyconnected_release_tensor( libxsmm_fc_layer[i], LIBXSMM_DNN_REGULAR_OUTPUT ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_fullyconnected_release_tensor( libxsmm_fc_layer[i], LIBXSMM_DNN_GRADIENT_OUTPUT ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_fullyconnected_release_tensor( libxsmm_fc_layer[i], LIBXSMM_DNN_REGULAR_FILTER ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_fullyconnected_release_tensor( libxsmm_fc_layer[i], LIBXSMM_DNN_GRADIENT_FILTER ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_fullyconnected_release_tensor( libxsmm_fc_layer[i], LIBXSMM_DNN_REGULAR_CHANNEL_BIAS ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_fullyconnected_release_tensor( libxsmm_fc_layer[i], LIBXSMM_DNN_GRADIENT_CHANNEL_BIAS ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_fullyconnected_release_tensor( libxsmm_fc_layer[i], LIBXSMM_DNN_RELU_MASK ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_destroy_fullyconnected( libxsmm_fc_layer[i] ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_optimizer_release_scratch( libxsmm_opt[i] ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_optimizer_release_tensor( libxsmm_opt[i], LIBXSMM_DNN_REGULAR_FILTER ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_optimizer_release_tensor( libxsmm_opt[i], LIBXSMM_DNN_GRADIENT_FILTER ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_destroy_optimizer( libxsmm_opt[i] ) );
}
CHKERR_LIBXSMM_DNN( libxsmm_dnn_softmaxloss_release_scratch( libxsmm_softmax ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_softmaxloss_release_tensor( libxsmm_softmax, LIBXSMM_DNN_REGULAR_INPUT ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_softmaxloss_release_tensor( libxsmm_softmax, LIBXSMM_DNN_GRADIENT_INPUT ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_softmaxloss_release_tensor( libxsmm_softmax, LIBXSMM_DNN_REGULAR_OUTPUT ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_softmaxloss_release_tensor( libxsmm_softmax, LIBXSMM_DNN_LABEL ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_destroy_softmaxloss( libxsmm_softmax ) );
for ( i = 0; i < num_layers; ++i ) {
if ( i == 0 ) {
CHKERR_LIBXSMM_DNN( libxsmm_dnn_destroy_tensor( libxsmm_act[i] ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_destroy_tensor( libxsmm_delact[i] ) );
}
CHKERR_LIBXSMM_DNN( libxsmm_dnn_destroy_tensor( libxsmm_act[i+1] ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_destroy_tensor( libxsmm_delact[i+1] ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_destroy_tensor( libxsmm_fil[i] ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_destroy_tensor( libxsmm_delfil[i] ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_destroy_tensor( libxsmm_bias[i] ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_destroy_tensor( libxsmm_delbias[i] ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_destroy_tensor( libxsmm_relumask[i] ) );
}
CHKERR_LIBXSMM_DNN( libxsmm_dnn_destroy_tensor( libxsmm_act[num_layers+1] ) );
CHKERR_LIBXSMM_DNN( libxsmm_dnn_destroy_tensor( libxsmm_label ) );
/* deallocate data */
libxsmm_free(scratch);
for ( i = 0; i < num_layers; ++i ) {
if ( i == 0 ) {
libxsmm_free(act_libxsmm[i]);
libxsmm_free(delact_libxsmm[i]);
}
libxsmm_free(act_libxsmm[i+1]);
libxsmm_free(delact_libxsmm[i+1]);
libxsmm_free(fil_libxsmm[i]);
libxsmm_free(delfil_libxsmm[i]);
libxsmm_free(bias_libxsmm[i]);
libxsmm_free(delbias_libxsmm[i]);
libxsmm_free(relumask_libxsmm[i]);
}
libxsmm_free(act_libxsmm[num_layers+1]);
libxsmm_free(label_libxsmm);
libxsmm_free(input_acts);
free( libxsmm_act );
free( libxsmm_delact );
free( libxsmm_fil );
free( libxsmm_delfil );
free( libxsmm_bias );
free( libxsmm_delbias );
free( libxsmm_relumask );
free( libxsmm_fc_layer );
free( libxsmm_opt );
free( act_libxsmm );
free( delact_libxsmm );
free( fil_libxsmm );
free( delfil_libxsmm );
free( bias_libxsmm );
free( delbias_libxsmm );
free( relumask_libxsmm );
free( C );
/* some empty lines at the end */
printf("\n\n\n");
return global_status;
}
|
GB_unop__identity_int64_int16.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_int64_int16)
// op(A') function: GB (_unop_tran__identity_int64_int16)
// C type: int64_t
// A type: int16_t
// cast: int64_t cij = (int64_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
int16_t
#define GB_CTYPE \
int64_t
// 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 = x ;
// casting
#define GB_CAST(z, aij) \
int64_t z = (int64_t) aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
int16_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
int64_t z = (int64_t) aij ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_INT64 || GxB_NO_INT16)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_int64_int16)
(
int64_t *Cx, // Cx and Ax may be aliased
const int16_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++)
{
int16_t aij = Ax [p] ;
int64_t z = (int64_t) aij ;
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 ;
int16_t aij = Ax [p] ;
int64_t z = (int64_t) aij ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__identity_int64_int16)
(
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
|
profile.c | /*
** profile.c
**
** Program written in order to calculate profile, characteristic scales and shapes of haloes
**
** Written by Marcel Zemp
*/
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <malloc.h>
#include <assert.h>
#include <sys/time.h>
#include <omp.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_eigen.h>
#include <iof.h>
#include <artsfc.h>
#define NSPECIESREADMAX 3
#define NSPECIESPROFILEMAX 17
#define NSPECIESBACKGROUND 5
#define NSUBSPECIESMAX 9
#define NPROPERTIESMAX 2
/*
** Be careful with changing order of species here!
** Some loops assume that the order of species are this way.
*/
#define GAS 0
#define DARK 1
#define STAR 2
#define TOT 3
#define BARYON 4
#define GAS_METAL_SNII 5
#define STAR_METAL_SNII 6
#define BARYON_METAL_SNII 7
#define GAS_METAL_SNIa 8
#define STAR_METAL_SNIa 9
#define BARYON_METAL_SNIa 10
#define GAS_HI 11
#define GAS_HII 12
#define GAS_HeI 13
#define GAS_HeII 14
#define GAS_HeIII 15
#define GAS_H2 16
#define MASS_TOT 0
#define MASS_METAL_SNII 1
#define MASS_METAL_SNIa 2
#define MASS_HI 3
#define MASS_HII 4
#define MASS_HeI 5
#define MASS_HeII 6
#define MASS_HeIII 7
#define MASS_H2 8
#define TEMPERATURE 9
#define AGE 10
typedef struct profile_bin_properties {
long int N; /* Number of particles/cells */
double M; /* Mass */
double Menc[2]; /* Enclosed mass - only for internal purposes */
double v[3]; /* Velocity vector */
double vdt[6]; /* Velocity dispersion tensor */
double L[3]; /* Angular momentum vector */
double *P; /* Additional properties */
} PROFILE_BIN_PROPERTIES;
typedef struct profile_shape_properties {
int NLoopConverged;
long int N; /* Number of particles/cells */
double M; /* Mass */
double st[6]; /* Shape tensor */
double a[3]; /* Semi-major axis unit vector */
double b[3]; /* Intermediate axis unit vector */
double c[3]; /* Semi-minor axis unit vector */
double b_a; /* Axis ratio b/a */
double c_a; /* Axis ratio c/a */
double b_a_old; /* Axis ratio b/a for iteration */
double c_a_old; /* Axis ratio c/a for iteration */
/* double dmin; */
/* double dmax; */
/* double propertymin; */
/* double propertymax; */
/* double propertymean; */
} PROFILE_SHAPE_PROPERTIES;
typedef struct profile_bin_structure {
double ri[3];
double rm[3];
double ro[3];
PROFILE_BIN_PROPERTIES *bin;
PROFILE_SHAPE_PROPERTIES *shape;
} PROFILE_BIN_STRUCTURE;
typedef struct halo_data_exclude {
int ID;
double rcentre[3];
double size;
} HALO_DATA_EXCLUDE;
typedef struct halo_data {
int ID;
int HostHaloID;
int ExtraHaloID;
int NBin[3];
int NHaloExclude;
int SizeExcludeHaloData;
int IsTruncated;
double rcentre[3];
double vcentre[3];
double rcentrenew[3];
double vcentrenew[3];
double rmean, Mrmean;
double rcrit, Mrcrit;
double rfix, Mrfix;
double rtrunc, Mrtrunc;
double size, mass;
double rhobg[NSPECIESBACKGROUND];
double rvcmax[NSPECIESBACKGROUND][2];
double Mrvcmax[NSPECIESBACKGROUND][2];
double rtruncindicator;
double zAxis[3], zHeight;
double rmin[3], rmax[3];
PROFILE_BIN_STRUCTURE ***pbs;
HALO_DATA_EXCLUDE *hde;
} HALO_DATA;
typedef struct profile_particle {
double r[3];
double v[3];
double *P; /* Properties array for masses and additional things */
} PROFILE_PARTICLE;
typedef struct general_info {
int DataFormat;
int HaloCatalogueFormat;
int HaloCatalogueNDim;
int HaloCatalogueBinningCoordinateType;
int ExcludeHaloCatalogueFormat;
int ExcludeHaloCatalogueNDim;
int ProfilingMode;
int DataProcessingMode;
int CentreType;
int BinningCoordinateType;
int BinningGridType[3];
int VelocityProjectionType;
int ShapeDeterminationVolume;
int ShapeTensorForm;
int DoMetalSpecies;
int DoChemicalSpecies;
int DoGasTemperature;
int DoStellarAge;
int MoreCharacteristicsOutput;
int HaloSize;
int rmaxFromHaloCatalogue;
int ExcludeParticles;
int zAxisCatalogueSpecified;
int NDimProfile, NBin[3];
int NSpeciesRead, NSpeciesProfile;
int NHalo, NHaloExcludeGlobal, NCellData, NCellHalo;
int SpeciesContained[NSPECIESPROFILEMAX];
int NParticlePerBlock[NSPECIESREADMAX], NParticleInBlock[NSPECIESREADMAX];
int NSubSpecies[NSPECIESREADMAX], NProperties[NSPECIESREADMAX];
int SizeStorage[NSPECIESREADMAX], NParticleInStorage[NSPECIESREADMAX];
int RecentreUse[NSPECIESREADMAX];
int SizeStorageIncrement;
int NLoopRead, NLoopRecentre, NLoopProcessData, NLoopShapeIterationMax, ILoopRead;
int OutputFrequencyShapeIteration;
int pi[NSPECIESREADMAX][NSUBSPECIESMAX+NPROPERTIESMAX];
int bi[NSPECIESPROFILEMAX][NPROPERTIESMAX];
double rhomean, rhocrit;
double rhoencmean, rhoenccrit, rhoencfix;
double Deltamean, Deltacrit, Deltafix;
double afix;
double ascale;
double rmin[3], rmax[3];
double NBinPerDex[3];
double bc[6];
double BinFactor;
double rExclude;
double rRecentre, fRecentreDist;
double fcheckrvcmax;
double slopertruncindicator;
double frhobg;
double ShapeIterationTolerance;
double fhaloduplicate;
double fhaloexcludesize, fhaloexcludedistance;
/* double fincludeshapeproperty, fincludeshaperadius; */
double zAxis[3], zHeight;
COSMOLOGICAL_PARAMETERS cp;
UNIT_SYSTEM us, cosmous;
char HaloCatalogueFileName[256], ExcludeHaloCatalogueFileName[256], zAxisCatalogueFileName[256], OutputName[256], MatterTypeName[NSPECIESPROFILEMAX][20];
/* char TotProfilesFileName[256], GasProfilesFileName[256], DarkProfilesFileName[256], StarProfilesFileName[256]; */
} GI;
void usage(void);
void set_default_values_general_info(GI *);
void calculate_densities(GI *);
void read_halocatalogue_ascii(GI *, HALO_DATA **);
int read_halocatalogue_ascii_excludehalo(GI *, HALO_DATA *, HALO_DATA_EXCLUDE **);
void initialise_halo_profile(GI *, HALO_DATA *);
void reset_halo_profile_shape(GI, HALO_DATA *);
void read_spherical_profiles(GI, HALO_DATA *);
void put_particles_in_bins(GI, HALO_DATA *, const int, PROFILE_PARTICLE *);
void put_particles_in_storage(GI *, HALO_DATA *, HALO_DATA_EXCLUDE *, const int, PROFILE_PARTICLE *, PROFILE_PARTICLE **);
int intersect(double, int, HALO_DATA, int *, double *, double);
void copy_pp(GI *, const int , const PROFILE_PARTICLE *, PROFILE_PARTICLE *);
void calculate_coordinates_principal_axes(PROFILE_SHAPE_PROPERTIES *, double [3], double [3], double *);
void calculate_recentred_halo_coordinates(GI, HALO_DATA *);
void calculate_total_matter_distribution(GI, HALO_DATA *);
void calculate_baryonic_matter_distribution(GI, HALO_DATA *);
int diagonalise_matrix(double [3][3], double *, double [3], double *, double [3], double *, double [3]);
double diagonalise_shape_tensors(GI, HALO_DATA *, int);
void calculate_halo_properties(GI, HALO_DATA *);
void calculate_derived_properties(GI, HALO_DATA *);
void calculate_overdensity_characteristics(GI, HALO_DATA *);
void calculate_truncation_characteristics(GI, HALO_DATA *);
void remove_background(GI, HALO_DATA *);
void calculate_halo_size(GI, HALO_DATA *);
void calculate_velocity_characteristics(GI, HALO_DATA *);
void determine_halo_hierarchy(GI, HALO_DATA *);
void write_output_matter_profile(GI, HALO_DATA *);
void write_output_shape_profile(GI, HALO_DATA *, int);
int main(int argc, char **argv) {
int index[3] = {-1,-1,-1};
int L = -1;
int ICurrentBlockGas, ICurrentBlockDark, ICurrentBlockStar;
int PositionPrecision, VerboseLevel;
int LengthType_rmin[3], LengthType_rmax[3], LengthType_zHeight, LengthType_rRecentre, LengthType_rExclude;
int LmaxGasAnalysis;
int NThreads;
int timestart, timeend, timestartsub, timeendsub, timestartloop, timeendloop, timediff;
long int d, i, j, k;
long int mothercellindex, childcellindex;
long int Nparticleread, Ngasread, Ngasanalysis;
double celllength, cellvolume;
double LBox;
int *cellrefined = NULL;
long int *Icoordinates = NULL;
double ***coordinates = NULL;
double r[3], v[3];
double convergencefraction;
double number_density;
char cdummy[256];
struct timeval time;
/* char TotDensityFileName[256], GasDensityFileName[256], DarkDensityFileName[256], StarDensityFileName[256]; */
/* FILE *TotDensityFile = NULL, *GasDensityFile = NULL, *DarkDensityFile = NULL, *StarDensityFile = NULL; */
/* XDR TotDensityXDR, GasDensityXDR, DarkDensityXDR, StarDensityXDR; */
/* ARRAY_HEADER ahtot, ahgas, ahdark, ahstar; */
/* ARRAY_PARTICLE aptot, apgas, apdark, apstar; */
GI gi;
TIPSY_HEADER th;
TIPSY_GAS_PARTICLE gp;
TIPSY_DARK_PARTICLE dp;
TIPSY_STAR_PARTICLE sp;
TIPSY_GAS_PARTICLE_DPP gpdpp;
TIPSY_DARK_PARTICLE_DPP dpdpp;
TIPSY_STAR_PARTICLE_DPP spdpp;
ART_DATA ad;
ART_GAS_PROPERTIES agp;
ART_STAR_PROPERTIES asp;
ART_COORDINATES *ac = NULL;
HALO_DATA *hd = NULL;
HALO_DATA_EXCLUDE *hdeg = NULL;
PROFILE_PARTICLE **pp = NULL;
PROFILE_PARTICLE **pp_storage = NULL;
COORDINATE_TRANSFORMATION cosmo2internal_ct;
XDR xdrs;
fpos_t *PosGasFile = NULL, *PosCoordinatesDataFile = NULL, *PosStarPropertiesFile = NULL;
u_int PosXDR = 0;
/* u_int PosTotDensityXDR = 0; */
/* u_int PosGasDensityXDR = 0; */
/* u_int PosDarkDensityXDR = 0; */
/* u_int PosStarDensityXDR = 0; */
/*
** Get time
*/
gettimeofday(&time,NULL);
timestart = time.tv_sec;
/*
** Set some default values
*/
PositionPrecision = 0; /* single precision */
VerboseLevel = 0; /* not verbose */
for (d = 0; d < 3; d++) {
LengthType_rmin[d] = 0; /* comoving */
LengthType_rmax[d] = 0; /* comoving */
}
LengthType_zHeight = 0; /* comoving */
LengthType_rExclude = 0; /* comoving */
LengthType_rRecentre = 0; /* comoving */
Nparticleread = 0;
LmaxGasAnalysis = -1;
LBox = 0;
set_default_values_general_info(&gi);
set_default_values_art_data(&ad);
set_default_values_coordinate_transformation(&cosmo2internal_ct);
/*
** Read in arguments
*/
i = 1;
while (i < argc) {
if ((strcmp(argv[i],"-h") == 0) || (strcmp(argv[i],"-help") == 0)) {
usage();
}
if (strcmp(argv[i],"-version") == 0) {
fprintf(stderr,"profile (%s)\n",VERSION);
exit(1);
}
if (strcmp(argv[i],"-spp") == 0) {
PositionPrecision = 0;
i++;
}
else if (strcmp(argv[i],"-dpp") == 0) {
PositionPrecision = 1;
i++;
}
else if (strcmp(argv[i],"-pfm") == 0) {
i++;
if (i >= argc) usage();
ad.particle_file_mode = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-DataFormat") == 0) {
i++;
if (i >= argc) usage();
gi.DataFormat = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-HaloCatalogueFormat") == 0) {
i++;
if (i >= argc) usage();
gi.HaloCatalogueFormat = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-HaloCatalogueNDim") == 0) {
i++;
if (i >= argc) usage();
gi.HaloCatalogueNDim = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-HaloCatalogueBinningCoordinateType") == 0) {
i++;
if (i >= argc) usage();
gi.HaloCatalogueBinningCoordinateType = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-ExcludeHaloCatalogueFormat") == 0) {
i++;
if (i >= argc) usage();
gi.HaloCatalogueFormat = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-ExcludeHaloCatalogueNDim") == 0) {
i++;
if (i >= argc) usage();
gi.ExcludeHaloCatalogueNDim = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-ProfilingMode") == 0) {
i++;
if (i >= argc) usage();
gi.ProfilingMode = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-NDimProfile") == 0) {
i++;
if (i >= argc) usage();
gi.NDimProfile = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-DataProcessingMode") == 0) {
i++;
if (i >= argc) usage();
gi.DataProcessingMode = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-ShapeDeterminationVolume") == 0) {
i++;
if (i >= argc) usage();
gi.ShapeDeterminationVolume = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-ShapeTensorForm") == 0) {
i++;
if (i >= argc) usage();
gi.ShapeTensorForm = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-RecentreUseGas") == 0) {
i++;
if (i >= argc) usage();
gi.RecentreUse[GAS] = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-RecentreUseDark") == 0) {
i++;
if (i >= argc) usage();
gi.RecentreUse[DARK] = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-RecentreUseStar") == 0) {
i++;
if (i >= argc) usage();
gi.RecentreUse[STAR] = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-DoMetalSpecies") == 0) {
gi.DoMetalSpecies = 1;
i++;
}
else if (strcmp(argv[i],"-DoChemicalSpecies") == 0) {
gi.DoChemicalSpecies = 1;
i++;
}
else if (strcmp(argv[i],"-DoGasTemperature") == 0) {
gi.DoGasTemperature = 1;
i++;
}
else if (strcmp(argv[i],"-DoStellarAge") == 0) {
gi.DoStellarAge = 1;
i++;
}
else if (strcmp(argv[i],"-MoreCharacteristicsOutput") == 0) {
gi.MoreCharacteristicsOutput = 1;
i++;
}
else if (strcmp(argv[i],"-HaloSize") == 0) {
i++;
if (i >= argc) usage();
gi.HaloSize = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-ExcludeParticles") == 0) {
i++;
if (i >= argc) usage();
gi.ExcludeParticles = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-LengthType_rmin") == 0) {
i++;
if (i >= argc) usage();
d = atoi(argv[i]);
i++;
if (i >= argc) usage();
LengthType_rmin[d-1] = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-LengthType_rmax") == 0) {
i++;
if (i >= argc) usage();
d = atoi(argv[i]);
i++;
if (i >= argc) usage();
LengthType_rmax[d-1] = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-LengthType_zHeight") == 0) {
i++;
if (i >= argc) usage();
LengthType_zHeight = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-LengthType_rExclude") == 0) {
i++;
if (i >= argc) usage();
LengthType_rExclude = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-LengthType_rRecentre") == 0) {
i++;
if (i >= argc) usage();
LengthType_rRecentre = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-ascale") == 0) {
i++;
if (i >= argc) usage();
gi.ascale = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-rmin") == 0) {
i++;
if (i >= argc) usage();
d = atoi(argv[i]);
i++;
if (i >= argc) usage();
gi.rmin[d-1] = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-rmax") == 0) {
i++;
if (i >= argc) usage();
d = atoi(argv[i]);
i++;
if (i >= argc) usage();
gi.rmax[d-1] = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-NBin") == 0) {
i++;
if (i >= argc) usage();
d = atoi(argv[i]);
i++;
if (i >= argc) usage();
gi.NBin[d-1] = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-NBinPerDex") == 0) {
i++;
if (i >= argc) usage();
d = atoi(argv[i]);
i++;
if (i >= argc) usage();
gi.NBinPerDex[d-1] = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-BinningGridType") == 0) {
i++;
if (i >= argc) usage();
d = atoi(argv[i]);
i++;
if (i >= argc) usage();
gi.BinningGridType[d-1] = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-CentreType") == 0) {
i++;
if (i >= argc) usage();
gi.CentreType = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-BinningCoordinateType") == 0) {
i++;
if (i >= argc) usage();
gi.BinningCoordinateType = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-VelocityProjectionType") == 0) {
i++;
if (i >= argc) usage();
gi.VelocityProjectionType = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-zAxis_x") == 0) {
i++;
if (i >= argc) usage();
gi.zAxis[0] = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-zAxis_y") == 0) {
i++;
if (i >= argc) usage();
gi.zAxis[1] = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-zAxis_z") == 0) {
i++;
if (i >= argc) usage();
gi.zAxis[2] = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-zHeight") == 0) {
i++;
if (i >= argc) usage();
gi.zHeight = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-rmaxFromHaloCatalogue") == 0) {
gi.rmaxFromHaloCatalogue = 1;
i++;
}
else if (strcmp(argv[i],"-BinFactor") == 0) {
i++;
if (i >= argc) usage();
gi.BinFactor = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-Delta_mean") == 0) {
i++;
if (i >= argc) usage();
gi.Deltamean = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-Delta_crit") == 0) {
i++;
if (i >= argc) usage();
gi.Deltacrit = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-Delta_fix") == 0) {
i++;
if (i >= argc) usage();
gi.Deltafix = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-afix") == 0) {
i++;
if (i >= argc) usage();
gi.afix = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-rExclude") == 0) {
i++;
if (i >= argc) usage();
gi.rExclude = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-rRecentre") == 0) {
i++;
if (i >= argc) usage();
gi.rRecentre = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-fRecentreDist") == 0) {
i++;
if (i >= argc) usage();
gi.fRecentreDist = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-fcheckrvcmax") == 0) {
i++;
if (i >= argc) usage();
gi.fcheckrvcmax = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-slopertruncindicator") == 0) {
i++;
if (i >= argc) usage();
gi.slopertruncindicator = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-frhobg") == 0) {
i++;
if (i >= argc) usage();
gi.frhobg = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-ShapeIterationTolerance") == 0) {
i++;
if (i >= argc) usage();
gi.ShapeIterationTolerance = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-fhaloduplicate") == 0) {
i++;
if (i >= argc) usage();
gi.fhaloduplicate = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-fhaloexcludesize") == 0) {
i++;
if (i >= argc) usage();
gi.fhaloexcludesize = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-fhaloexcludedistance") == 0) {
i++;
if (i >= argc) usage();
gi.fhaloexcludedistance = atof(argv[i]);
i++;
}
/* else if (strcmp(argv[i],"-fincludeshapeproperty") == 0) { */
/* i++; */
/* if (i >= argc) usage(); */
/* gi.fincludeshapeproperty = atof(argv[i]); */
/* i++; */
/* } */
/* else if (strcmp(argv[i],"-fincludeshaperadius") == 0) { */
/* i++; */
/* if (i >= argc) usage(); */
/* gi.fincludeshaperadius = atof(argv[i]); */
/* i++; */
/* } */
else if (strcmp(argv[i],"-OmegaM0") == 0) {
i++;
if (i >= argc) usage();
gi.cp.OmegaM0 = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-OmegaL0") == 0) {
i++;
if (i >= argc) usage();
gi.cp.OmegaL0 = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-OmegaK0") == 0) {
i++;
if (i >= argc) usage();
gi.cp.OmegaK0 = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-OmegaR0") == 0) {
i++;
if (i >= argc) usage();
gi.cp.OmegaR0 = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-h0_100") == 0) {
i++;
if (i >= argc) usage();
gi.cp.h0_100 = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-LBox") == 0) {
i++;
if (i >= argc) usage();
LBox = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-LBox_internal") == 0) {
i++;
if (i >= argc) usage();
gi.us.LBox = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-rhocrit0_internal") == 0) {
i++;
if (i >= argc) usage();
gi.us.rhocrit0 = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-Hubble0_internal") == 0) {
i++;
if (i >= argc) usage();
gi.us.Hubble0 = atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-NParticlePerBlockGas") == 0) {
i++;
if (i >= argc) usage();
gi.NParticlePerBlock[GAS] = (int) atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-NParticlePerBlockDark") == 0) {
i++;
if (i >= argc) usage();
gi.NParticlePerBlock[DARK] = (int) atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-NParticlePerBlockStar") == 0) {
i++;
if (i >= argc) usage();
gi.NParticlePerBlock[STAR] = (int) atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-NCellData") == 0) {
i++;
if (i >= argc) usage();
gi.NCellData = (int) atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-NCellHalo") == 0) {
i++;
if (i >= argc) usage();
gi.NCellHalo = (int) atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-NLoopRecentre") == 0) {
i++;
if (i >= argc) usage();
gi.NLoopRecentre = (int) atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-NLoopShapeIterationMax") == 0) {
i++;
if (i >= argc) usage();
gi.NLoopShapeIterationMax = (int) atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-OutputFrequencySI") == 0) {
i++;
if (i >= argc) usage();
gi.OutputFrequencyShapeIteration = (int) atof(argv[i]);
i++;
}
else if (strcmp(argv[i],"-LmaxGasAnalysis") == 0) {
i++;
if (i >= argc) usage();
LmaxGasAnalysis = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-GRAVITY") == 0) {
i++;
if (i >= argc) usage();
ad.GRAVITY = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-HYDRO") == 0) {
i++;
if (i >= argc) usage();
ad.HYDRO = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-ADVECT_SPECIES") == 0) {
i++;
if (i >= argc) usage();
ad.ADVECT_SPECIES = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-STARFORM") == 0) {
i++;
if (i >= argc) usage();
ad.STARFORM = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-ENRICH") == 0) {
i++;
if (i >= argc) usage();
ad.ENRICH = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-ENRICH_SNIa") == 0) {
i++;
if (i >= argc) usage();
ad.ENRICH_SNIa = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-RADIATIVE_TRANSFER") == 0) {
i++;
if (i >= argc) usage();
ad.RADIATIVE_TRANSFER = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-ELECTRON_ION_NONEQUILIBRIUM") == 0) {
i++;
if (i >= argc) usage();
ad.ELECTRON_ION_NONEQUILIBRIUM = atoi(argv[i]);
i++;
}
else if (strcmp(argv[i],"-HaloCatalogue") == 0) {
i++;
if (i >= argc) usage();
strcpy(gi.HaloCatalogueFileName,argv[i]);
i++;
}
else if (strcmp(argv[i],"-ExcludeHaloCatalogue") == 0) {
i++;
if (i >= argc) usage();
strcpy(gi.ExcludeHaloCatalogueFileName,argv[i]);
i++;
}
else if (strcmp(argv[i],"-zAxisCatalogue") == 0) {
i++;
if (i >= argc) usage();
strcpy(gi.zAxisCatalogueFileName,argv[i]);
gi.zAxisCatalogueSpecified = 1;
i++;
}
else if (strcmp(argv[i],"-Output") == 0) {
i++;
if (i >= argc) usage();
strcpy(gi.OutputName,argv[i]);
i++;
}
else if (strcmp(argv[i],"-ARTHeader") == 0) {
i++;
if (i >= argc) usage();
strcpy(ad.HeaderFileName,argv[i]);
i++;
}
else if (strcmp(argv[i],"-ARTCoordinatesData") == 0) {
ad.darkcontained = 1;
i++;
if (i >= argc) usage();
strcpy(ad.CoordinatesDataFileName,argv[i]);
i++;
}
else if (strcmp(argv[i],"-ARTStarProperties") == 0) {
ad.starcontained = 1;
i++;
if (i >= argc) usage();
strcpy(ad.StarPropertiesFileName,argv[i]);
i++;
}
else if (strcmp(argv[i],"-ARTGas") == 0) {
ad.gascontained = 1;
i++;
if (i >= argc) usage();
strcpy(ad.GasFileName,argv[i]);
i++;
}
/* else if (strcmp(argv[i],"-totprofilesfile") == 0) { */
/* i++; */
/* if (i >= argc) usage(); */
/* strcpy(gi.TotProfilesFileName,argv[i]); */
/* i++; */
/* } */
/* else if (strcmp(argv[i],"-gasprofilesfile") == 0) { */
/* i++; */
/* if (i >= argc) usage(); */
/* strcpy(gi.GasProfilesFileName,argv[i]); */
/* i++; */
/* } */
/* else if (strcmp(argv[i],"-darkprofilesfile") == 0) { */
/* i++; */
/* if (i >= argc) usage(); */
/* strcpy(gi.DarkProfilesFileName,argv[i]); */
/* i++; */
/* } */
/* else if (strcmp(argv[i],"-starprofilesfile") == 0) { */
/* i++; */
/* if (i >= argc) usage(); */
/* strcpy(gi.StarProfilesFileName,argv[i]); */
/* i++; */
/* } */
/* else if (strcmp(argv[i],"-totdensityfile") == 0) { */
/* i++; */
/* if (i >= argc) usage(); */
/* strcpy(TotDensityFileName,argv[i]); */
/* i++; */
/* } */
/* else if (strcmp(argv[i],"-gasdensityfile") == 0) { */
/* i++; */
/* if (i >= argc) usage(); */
/* strcpy(GasDensityFileName,argv[i]); */
/* i++; */
/* } */
/* else if (strcmp(argv[i],"-darkdensityfile") == 0) { */
/* i++; */
/* if (i >= argc) usage(); */
/* strcpy(DarkDensityFileName,argv[i]); */
/* i++; */
/* } */
/* else if (strcmp(argv[i],"-stardensityfile") == 0) { */
/* i++; */
/* if (i >= argc) usage(); */
/* strcpy(StarDensityFileName,argv[i]); */
/* i++; */
/* } */
else if (strcmp(argv[i],"-verbose") == 0) {
VerboseLevel = 1;
i++;
}
else {
usage();
}
}
/*
** Get number of threads
*/
NThreads = omp_get_max_threads();
fprintf(stderr,"Using in maximum %d OpenMP threads.\n\n",NThreads);
/*
** Set some defaults and do some checks
*/
if (gi.ProfilingMode == 0) {
if (gi.DataProcessingMode == 1) {
fprintf(stderr,"No normal profiling possible with storage data processing mode. Reset DataProcessingMode = 0.\n\n");
gi.DataProcessingMode = 0;
}
if (gi.NLoopRecentre > 0) {
if (!(gi.rRecentre > 0)) {
fprintf(stderr,"No value for rRecentre set. Abort.\n\n");
exit(1);
}
if (gi.RecentreUse[GAS] == 0 && gi.RecentreUse[DARK] == 0 && gi.RecentreUse[STAR] == 0) {
fprintf(stderr,"No recentring species set. Abort.\n\n");
exit(1);
}
}
}
if (gi.ProfilingMode == 1) {
if (gi.NLoopRecentre > 0) {
fprintf(stderr,"No recentering in shape profiling mode allowed. Reset NLoopRecentre = 0.\n\n");
gi.NLoopRecentre = 0;
}
if (gi.NDimProfile > 1) {
fprintf(stderr,"Only one dimension in shape profiling mode allowed. Reset NDimProfile = 1.\n\n");
gi.NDimProfile = 1;
}
if (gi.DoGasTemperature) {
fprintf(stderr,"No need for gas temperatures in shape profiling mode. Reset DoGasTemperature = 0.\n\n");
gi.DoGasTemperature = 0;
}
if (gi.DoStellarAge) {
fprintf(stderr,"No need for stellar ages in shape profiling mode. Reset DoStellarAge = 0.\n\n");
gi.DoStellarAge = 0;
}
}
if (gi.DataFormat == 0) {
if (gi.DoMetalSpecies) {
fprintf(stderr,"Doing metal species with Tipsy format is not enabled. Reset DoMetalSpecies = 0.\n\n");
gi.DoMetalSpecies = 0;
}
if (gi.DoChemicalSpecies) {
fprintf(stderr,"Doing chemical species with Tipsy format is not enabled. Reset DoChemicalSpecies = 0.\n\n");
gi.DoChemicalSpecies = 0;
}
}
if (gi.DoChemicalSpecies) {
if (gi.DoMetalSpecies == 0) {
fprintf(stderr,"DoMetalSpecies was automatically switched on since it is necessary for doing chemical species.\n\n");
gi.DoMetalSpecies = 1;
}
gi.NSpeciesProfile = 17;
}
else if (gi.DoMetalSpecies) {
gi.NSpeciesProfile = 11;
}
assert(gi.NSpeciesRead <= NSPECIESREADMAX);
assert(gi.NSpeciesProfile <= NSPECIESPROFILEMAX);
for (j = 0; j < gi.NSpeciesRead; j++) assert(gi.NParticlePerBlock[j] > 0);
assert(gi.NCellData > 0);
assert(gi.NCellHalo > 0);
assert(gi.ProfilingMode < 2);
if (gi.ProfilingMode == 1) assert(gi.NDimProfile == 1);
assert(gi.DataProcessingMode < 2);
assert(gi.NDimProfile > 0);
assert(gi.NDimProfile < 3);
assert(gi.HaloCatalogueNDim < 3);
assert(gi.ExcludeHaloCatalogueNDim < 3);
if (gi.HaloCatalogueFormat == 1) assert(gi.HaloCatalogueNDim == 1);
/*
** Prepare data arrays
*/
pp = malloc(gi.NSpeciesRead*sizeof(PROFILE_PARTICLE *));
assert(pp != NULL);
pp_storage = malloc(gi.NSpeciesRead*sizeof(PROFILE_PARTICLE *));
assert(pp_storage != NULL);
for (j = 0; j < gi.NSpeciesRead; j++) {
if (j == GAS) {
if (gi.DoMetalSpecies) {
gi.NSubSpecies[GAS] += 2;
gi.pi[GAS][MASS_METAL_SNII] = 1;
gi.pi[GAS][MASS_METAL_SNIa] = 2;
}
if (gi.DoChemicalSpecies) {
gi.NSubSpecies[GAS] += 6;
gi.pi[GAS][MASS_HI] = 3;
gi.pi[GAS][MASS_HII] = 4;
gi.pi[GAS][MASS_HeI] = 5;
gi.pi[GAS][MASS_HeII] = 6;
gi.pi[GAS][MASS_HeIII] = 7;
gi.pi[GAS][MASS_H2] = 8;
}
if (gi.DoGasTemperature) {
gi.NProperties[GAS] += 1;
gi.pi[GAS][TEMPERATURE] = gi.NSubSpecies[GAS];
}
}
else if (j == STAR) {
if (gi.DoMetalSpecies) {
gi.NSubSpecies[STAR] += 2;
gi.pi[STAR][MASS_METAL_SNII] = 1;
gi.pi[STAR][MASS_METAL_SNIa] = 2;
}
if (gi.DoStellarAge) {
gi.NProperties[STAR] += 1;
gi.pi[STAR][AGE] = gi.NSubSpecies[STAR];
}
}
assert(gi.NSubSpecies[j] > 0);
}
for (j = 0; j < gi.NSpeciesProfile; j++) gi.SpeciesContained[j] = 0;
/*
** Read header files
*/
if (gi.DataFormat == 0) {
/*
** Tipsy
*/
xdrstdio_create(&xdrs,stdin,XDR_DECODE);
read_tipsy_xdr_header(&xdrs,&th);
if (gi.ascale == 0) gi.ascale = th.time;
if (gi.us.LBox == 0) gi.us.LBox = 1;
if (gi.us.Hubble0 == 0) gi.us.Hubble0 = sqrt(8.0*M_PI/3.0);
if (gi.us.rhocrit0 == 0) gi.us.rhocrit0 = 1;
gi.bc[0] = -0.5*gi.us.LBox;
gi.bc[1] = -0.5*gi.us.LBox;
gi.bc[2] = -0.5*gi.us.LBox;
gi.bc[3] = 0.5*gi.us.LBox;
gi.bc[4] = 0.5*gi.us.LBox;
gi.bc[5] = 0.5*gi.us.LBox;
gi.SpeciesContained[GAS] = (th.ngas > 0)?1:0;
gi.SpeciesContained[DARK] = (th.ndark > 0)?1:0;
gi.SpeciesContained[STAR] = (th.nstar > 0)?1:0;
}
else if (gi.DataFormat == 1) {
/*
** ART
*/
prepare_art_data(&ad);
if (gi.ascale == 0) gi.ascale = ad.ah.abox;
gi.cp.OmegaM0 = ad.ah.OmM0;
gi.cp.OmegaB0 = ad.ah.OmB0;
gi.cp.OmegaD0 = gi.cp.OmegaM0 - gi.cp.OmegaB0;
gi.cp.OmegaL0 = ad.ah.OmL0;
gi.cp.OmegaK0 = ad.ah.OmK0;
gi.cp.h0_100 = ad.ah.h100;
if (gi.us.LBox == 0) gi.us.LBox = ad.ah.Ngrid;
if (gi.us.Hubble0 == 0) gi.us.Hubble0 = 2.0/sqrt(gi.cp.OmegaM0);
if (gi.us.rhocrit0 == 0) gi.us.rhocrit0 = 1.0/gi.cp.OmegaM0;
gi.bc[0] = 0;
gi.bc[1] = 0;
gi.bc[2] = 0;
gi.bc[3] = gi.us.LBox;
gi.bc[4] = gi.us.LBox;
gi.bc[5] = gi.us.LBox;
gi.SpeciesContained[GAS] = ad.gascontained;
gi.SpeciesContained[DARK] = ad.darkcontained;
gi.SpeciesContained[STAR] = ad.starcontained;
for (i = ad.Lmindark; i <= ad.Lmaxdark; i++) ad.massdark[i] = ad.ah.mass[ad.Lmaxdark-i];
if (LmaxGasAnalysis == -1) LmaxGasAnalysis = ad.Lmaxgas;
assert(LmaxGasAnalysis >= 0);
assert(LmaxGasAnalysis <= ad.Lmaxgas);
if (ad.gascontained) {
PosGasFile = malloc(2*sizeof(fpos_t));
assert(PosGasFile != NULL);
}
if (ad.darkcontained || ad.starcontained) {
PosCoordinatesDataFile = malloc(1*sizeof(fpos_t));
assert(PosCoordinatesDataFile != NULL);
}
if (ad.starcontained) {
PosStarPropertiesFile = malloc(ad.Nstarproperties*sizeof(fpos_t));
assert(PosStarPropertiesFile != NULL);
}
}
else {
fprintf(stderr,"Not supported format!\n");
exit(1);
}
/*
** Set some parameters
*/
if (gi.SpeciesContained[GAS] || gi.SpeciesContained[DARK] || gi.SpeciesContained[STAR]) gi.SpeciesContained[TOT] = 1;
if (gi.SpeciesContained[GAS] || gi.SpeciesContained[STAR]) gi.SpeciesContained[BARYON] = 1;
if (gi.DoMetalSpecies) {
if (gi.SpeciesContained[GAS]) {
gi.SpeciesContained[GAS_METAL_SNII] = 1;
gi.SpeciesContained[GAS_METAL_SNIa] = 1;
}
if (gi.SpeciesContained[STAR]) {
gi.SpeciesContained[STAR_METAL_SNII] = 1;
gi.SpeciesContained[STAR_METAL_SNIa] = 1;
}
if (gi.SpeciesContained[BARYON]) {
gi.SpeciesContained[BARYON_METAL_SNII] = 1;
gi.SpeciesContained[BARYON_METAL_SNIa] = 1;
}
}
if (gi.DoChemicalSpecies && gi.SpeciesContained[GAS]) {
gi.SpeciesContained[GAS_HI] = 1;
gi.SpeciesContained[GAS_HII] = 1;
gi.SpeciesContained[GAS_HeI] = 1;
gi.SpeciesContained[GAS_HeII] = 1;
gi.SpeciesContained[GAS_HeIII] = 1;
gi.SpeciesContained[GAS_H2] = 1;
}
for (d = 0; d < 3; d++) {
if (LengthType_rmin[d] == 1) gi.rmin[d] /= gi.ascale;
if (LengthType_rmax[d] == 1) gi.rmax[d] /= gi.ascale;
}
if (LengthType_zHeight == 1) gi.zHeight /= gi.ascale;
if (LengthType_rExclude == 1) gi.rExclude /= gi.ascale;
if (LengthType_rRecentre == 1) gi.rRecentre /= gi.ascale;
if (gi.cosmous.LBox == 0) gi.cosmous.LBox = LBox;
if (gi.cosmous.Hubble0 == 0) gi.cosmous.Hubble0 = 100*gi.cp.h0_100*ConversionFactors.km_per_s_2_kpc_per_Gyr/1e3;
if (gi.cosmous.rhocrit0 == 0) gi.cosmous.rhocrit0 = PhysicalConstants.rho_crit_cosmology*pow(gi.cp.h0_100,2);
calculate_units_transformation(gi.cosmous,gi.us,&cosmo2internal_ct);
/*
** Calculate densities in comoving coordinates
*/
calculate_densities(&gi);
/*
** Read halo catalogue
*/
gettimeofday(&time,NULL);
timestartsub = time.tv_sec;
fprintf(stderr,"Reading halo catalogues ... ");
if (gi.ProfilingMode == 0) {
read_halocatalogue_ascii(&gi,&hd);
}
else if (gi.ProfilingMode == 1) {
assert(gi.HaloCatalogueFormat == 2);
read_halocatalogue_ascii(&gi,&hd);
}
else if (gi.ProfilingMode == 3) {
/* if (gi.ProfilingMode == 3) read_spherical_profiles(gi,hd); */
/* for (i = 0; i < gi.NHalo; i++) { */
/* fprintf(stderr,"i %ld ID %d rmin %.6e rmax %.6e NBin %d\n",i,hd[i].ID,hd[i].rmin,hd[i].rmax,hd[i].NBin); */
/* for (j = 0; j <= hd[i].NBin; j++) { */
/* fprintf(stderr,"i %ld j %ld ri %.6e ro %.6e totpropertymin %.6e totpropertymax %.6e gaspropertymin %.6e gaspropertymax %.6e darkpropertymin %.6e darkpropertymax %.6e\n",i,j,hd[i].ps[j].ri,hd[i].ps[j].ro,hd[i].ps[j].totshape->propertymin,hd[i].ps[j].totshape->propertymax,hd[i].ps[j].gasshape->propertymin,hd[i].ps[j].gasshape->propertymax,hd[i].ps[j].darkshape->propertymin,hd[i].ps[j].darkshape->propertymax); */
/* } */
/* } */
}
else {
fprintf(stderr,"Not supported profiling mode!\n");
exit(1);
}
gettimeofday(&time,NULL);
timeendsub = time.tv_sec;
timediff = timeendsub-timestartsub;
fprintf(stderr,"Done. Read in %d haloes. It took %d s = %d h %d m %d s.\n\n",gi.NHalo,timediff,timediff/3600,(timediff/60)%60,timediff%60);
/*
** Read halo catalogue where particles are excluded
*/
if (gi.ExcludeParticles == 1) {
gettimeofday(&time,NULL);
timestartsub = time.tv_sec;
fprintf(stderr,"Reading halo catalogues for particle exclusion ... ");
i = read_halocatalogue_ascii_excludehalo(&gi,hd,&hdeg);
j = 0;
for (k = 0; k < gi.NHalo; k++) j += hd[k].NHaloExclude;
gettimeofday(&time,NULL);
timeendsub = time.tv_sec;
timediff = timeendsub-timestartsub;
fprintf(stderr,"Done. Read in %ld haloes in total leading to %d global and %ld local haloes for exclusion. It took %d s = %d h %d m %d s.\n\n",i,gi.NHaloExcludeGlobal,j,timediff,timediff/3600,(timediff/60)%60,timediff%60);
}
/*
** Get density files ready
*/
/* if (gi.ProfilingMode == 3) { */
/* TotDensityFile = fopen(TotDensityFileName,"r"); */
/* assert(TotDensityFile != NULL); */
/* xdrstdio_create(&TotDensityXDR,TotDensityFile,XDR_DECODE); */
/* read_array_xdr_header(&TotDensityXDR,&ahtot); */
/* allocate_array_particle(&ahtot,&aptot); */
/* if (gi.DataFormat == 0) assert(ahtot.N[0] == th.ntotal); */
/* PosTotDensityXDR = xdr_getpos(&TotDensityXDR); */
/* if (gi.SpeciesContained[GAS]) { */
/* GasDensityFile = fopen(GasDensityFileName,"r"); */
/* assert(GasDensityFile != NULL); */
/* xdrstdio_create(&GasDensityXDR,GasDensityFile,XDR_DECODE); */
/* read_array_xdr_header(&GasDensityXDR,&ahgas); */
/* allocate_array_particle(&ahgas,&apgas); */
/* if (gi.DataFormat == 0) assert(ahgas.N[0] == th.ngas); */
/* PosGasDensityXDR = xdr_getpos(&GasDensityXDR); */
/* } */
/* if (gi.SpeciesContained[DARK]) { */
/* DarkDensityFile = fopen(DarkDensityFileName,"r"); */
/* assert(DarkDensityFile != NULL); */
/* xdrstdio_create(&DarkDensityXDR,DarkDensityFile,XDR_DECODE); */
/* read_array_xdr_header(&DarkDensityXDR,&ahdark); */
/* allocate_array_particle(&ahdark,&apdark); */
/* if (gi.DataFormat == 0) assert(ahdark.N[0] == th.ndark); */
/* if (gi.DataFormat == 1) assert(ahdark.N[0] == ad.Ndark); */
/* PosDarkDensityXDR = xdr_getpos(&DarkDensityXDR); */
/* } */
/* if (gi.SpeciesContained[STAR]) { */
/* StarDensityFile = fopen(StarDensityFileName,"r"); */
/* assert(StarDensityFile != NULL); */
/* xdrstdio_create(&StarDensityXDR,StarDensityFile,XDR_DECODE); */
/* read_array_xdr_header(&StarDensityXDR,&ahstar); */
/* allocate_array_particle(&ahstar,&apstar); */
/* if (gi.DataFormat == 0) assert(ahstar.N[0] == th.nstar); */
/* if (gi.DataFormat == 1) assert(ahstar.N[0] == ad.Nstar); */
/* PosStarDensityXDR = xdr_getpos(&StarDensityXDR); */
/* } */
/* } */
/*
** Harvest data
*/
assert(gi.NLoopProcessData == 1);
gi.NLoopRead = gi.NLoopRecentre + gi.NLoopProcessData;
for (gi.ILoopRead = 0; gi.ILoopRead < gi.NLoopRead; gi.ILoopRead++) {
gettimeofday(&time,NULL);
timestartloop = time.tv_sec;
fprintf(stderr,"Doing loop %d ...\n",gi.ILoopRead+1);
if (gi.DataFormat == 0 && gi.NHalo > 0) {
/*
** Tipsy data
**
** Set file pointers correctly
*/
if (gi.ILoopRead == 0) PosXDR = xdr_getpos(&xdrs);
else xdr_setpos(&xdrs,PosXDR);
/* if (gi.ProfilingMode == 3) { */
/* xdr_setpos(&TotDensityXDR,PosTotDensityXDR); */
/* if (gi.SpeciesContained[GAS]) xdr_setpos(&GasDensityXDR,PosGasDensityXDR); */
/* if (gi.SpeciesContained[DARK]) xdr_setpos(&DarkDensityXDR,PosDarkDensityXDR); */
/* if (gi.SpeciesContained[STAR]) xdr_setpos(&StarDensityXDR,PosStarDensityXDR); */
/* } */
/*
** Gas
*/
gettimeofday(&time,NULL);
timestartsub = time.tv_sec;
fprintf(stderr,"Processing gas ... ");
pp[GAS] = malloc(gi.NParticlePerBlock[GAS]*sizeof(PROFILE_PARTICLE));
assert(pp[GAS] != NULL);
for (i = 0; i < gi.NParticlePerBlock[GAS]; i++) {
pp[GAS][i].P = malloc((gi.NSubSpecies[GAS]+gi.NProperties[GAS])*sizeof(double));
assert(pp[GAS][i].P != NULL);
}
Nparticleread = 0;
ICurrentBlockGas = 0;
for (i = 0; i < th.ngas; i++) {
if (PositionPrecision == 0) {
read_tipsy_xdr_gas(&xdrs,&gp);
for (k = 0; k < 3; k++) {
pp[GAS][ICurrentBlockGas].r[k] = put_in_box(gp.pos[k],gi.bc[k],gi.bc[k+3]);
pp[GAS][ICurrentBlockGas].v[k] = gp.vel[k];
}
pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][MASS_TOT]] = gp.mass;
if (gi.DoGasTemperature) {
pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][TEMPERATURE]] = gp.temp;
}
}
else if (PositionPrecision == 1) {
read_tipsy_xdr_gas_dpp(&xdrs,&gpdpp);
for (k = 0; k < 3; k++) {
pp[GAS][ICurrentBlockGas].r[k] = put_in_box(gpdpp.pos[k],gi.bc[k],gi.bc[k+3]);
pp[GAS][ICurrentBlockGas].v[k] = gpdpp.vel[k];
}
pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][MASS_TOT]] = gpdpp.mass;
if (gi.DoGasTemperature) {
pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][TEMPERATURE]] = gpdpp.temp;
}
}
/* if (gi.ProfilingMode == 3) { */
/* read_array_xdr_particle(&GasDensityXDR,&ahgas,&apgas); */
/* read_array_xdr_particle(&TotDensityXDR,&ahtot,&aptot); */
/* pp[GAS][ICurrentBlockGas].property = apgas.fa[0]; */
/* pp[GAS][ICurrentBlockGas].propertytot = aptot.fa[0]; */
/* } */
Nparticleread++;
ICurrentBlockGas++;
if ((ICurrentBlockGas == gi.NParticlePerBlock[GAS]) || (Nparticleread == th.ngas)) {
/*
** Block is full or we reached end of gas particles
*/
gi.NParticleInBlock[GAS] = ICurrentBlockGas;
if (gi.DataProcessingMode == 0 && gi.ILoopRead >= gi.NLoopRecentre) put_particles_in_bins(gi,hd,GAS,pp[GAS]);
else if (gi.DataProcessingMode == 1) put_particles_in_storage(&gi,hd,hdeg,GAS,pp[GAS],&pp_storage[GAS]);
ICurrentBlockGas = 0;
}
} /* for ngas */
for (i = 0; i < gi.NParticlePerBlock[GAS]; i++) free(pp[GAS][i].P);
free(pp[GAS]);
gettimeofday(&time,NULL);
timeendsub = time.tv_sec;
timediff = timeendsub-timestartsub;
fprintf(stderr,"Done. It took %d s = %d h %d m %d s. Processed in total %d gas particles.\n",timediff,timediff/3600,(timediff/60)%60,timediff%60,th.ngas);
/*
** Dark Matter
*/
gettimeofday(&time,NULL);
timestartsub = time.tv_sec;
fprintf(stderr,"Processing dark matter ... ");
pp[DARK] = malloc(gi.NParticlePerBlock[DARK]*sizeof(PROFILE_PARTICLE));
assert(pp[DARK] != NULL);
for (i = 0; i < gi.NParticlePerBlock[DARK]; i++) {
pp[DARK][i].P = malloc((gi.NSubSpecies[DARK]+gi.NProperties[DARK])*sizeof(double));
assert(pp[DARK][i].P != NULL);
}
Nparticleread = 0;
ICurrentBlockDark = 0;
for (i = 0; i < th.ndark; i++) {
if (PositionPrecision == 0) {
read_tipsy_xdr_dark(&xdrs,&dp);
for (k = 0; k < 3; k++) {
pp[DARK][ICurrentBlockDark].r[k] = put_in_box(dp.pos[k],gi.bc[k],gi.bc[k+3]);
pp[DARK][ICurrentBlockDark].v[k] = dp.vel[k];
}
pp[DARK][ICurrentBlockDark].P[gi.pi[DARK][MASS_TOT]] = dp.mass;
}
else if (PositionPrecision == 1) {
read_tipsy_xdr_dark_dpp(&xdrs,&dpdpp);
for (k = 0; k < 3; k++) {
pp[DARK][ICurrentBlockDark].r[k] = put_in_box(dpdpp.pos[k],gi.bc[k],gi.bc[k+3]);
pp[DARK][ICurrentBlockDark].v[k] = dpdpp.vel[k];
}
pp[DARK][ICurrentBlockDark].P[gi.pi[DARK][MASS_TOT]] = dpdpp.mass;
}
/* if (gi.ProfilingMode == 3) { */
/* read_array_xdr_particle(&DarkDensityXDR,&ahdark,&apdark); */
/* read_array_xdr_particle(&TotDensityXDR,&ahtot,&aptot); */
/* pdp[ICurrentBlockDark].property = apdark.fa[0]; */
/* pdp[ICurrentBlockDark].propertytot = aptot.fa[0]; */
/* } */
Nparticleread++;
ICurrentBlockDark++;
if ((ICurrentBlockDark == gi.NParticlePerBlock[DARK]) || (Nparticleread == th.ndark)) {
/*
** Block is full or we reached end of dark matter particles
*/
gi.NParticleInBlock[DARK] = ICurrentBlockDark;
if (gi.DataProcessingMode == 0) put_particles_in_bins(gi,hd,DARK,pp[DARK]);
else if (gi.DataProcessingMode == 1) put_particles_in_storage(&gi,hd,hdeg,DARK,pp[DARK],&pp_storage[DARK]);
ICurrentBlockDark = 0;
}
} /* for ndark */
for (i = 0; i < gi.NParticlePerBlock[DARK]; i++) free(pp[DARK][i].P);
free(pp[DARK]);
gettimeofday(&time,NULL);
timeendsub = time.tv_sec;
timediff = timeendsub-timestartsub;
fprintf(stderr,"Done. It took %d s = %d h %d m %d s. Processed in total %d dark matter particles.\n",timediff,timediff/3600,(timediff/60)%60,timediff%60,th.ndark);
/*
** Stars
*/
gettimeofday(&time,NULL);
timestartsub = time.tv_sec;
fprintf(stderr,"Processing stars ... ");
pp[STAR] = malloc(gi.NParticlePerBlock[STAR]*sizeof(PROFILE_PARTICLE));
assert(pp[STAR] != NULL);
for (i = 0; i < gi.NParticlePerBlock[STAR]; i++) {
pp[STAR][i].P = malloc((gi.NSubSpecies[STAR]+gi.NProperties[STAR])*sizeof(double));
assert(pp[STAR][i].P != NULL);
}
Nparticleread = 0;
ICurrentBlockStar = 0;
for (i = 0; i < th.nstar; i++) {
if (PositionPrecision == 0) {
read_tipsy_xdr_star(&xdrs,&sp);
for (k = 0; k < 3; k++) {
pp[STAR][ICurrentBlockStar].r[k] = put_in_box(sp.pos[k],gi.bc[k],gi.bc[k+3]);
pp[STAR][ICurrentBlockStar].v[k] = sp.vel[k];
}
pp[STAR][ICurrentBlockStar].P[gi.pi[STAR][MASS_TOT]] = sp.mass;
if (gi.DoStellarAge) {
pp[STAR][ICurrentBlockStar].P[gi.pi[STAR][AGE]] = sp.tform;
}
}
else if (PositionPrecision == 1) {
read_tipsy_xdr_star_dpp(&xdrs,&spdpp);
for (k = 0; k < 3; k++) {
pp[STAR][ICurrentBlockStar].r[k] = put_in_box(spdpp.pos[k],gi.bc[k],gi.bc[k+3]);
pp[STAR][ICurrentBlockStar].v[k] = spdpp.vel[k];
}
pp[STAR][ICurrentBlockStar].P[gi.pi[STAR][MASS_TOT]] = spdpp.mass;
if (gi.DoStellarAge) {
pp[STAR][ICurrentBlockStar].P[gi.pi[STAR][AGE]] = spdpp.tform;
}
}
/* if (gi.ProfilingMode == 3) { */
/* read_array_xdr_particle(&StarDensityXDR,&ahstar,&apstar); */
/* read_array_xdr_particle(&TotDensityXDR,&ahtot,&aptot); */
/* pp[STAR][ICurrentBlockStar].property = apstar.fa[0]; */
/* pp[STAR][ICurrentBlockStar].propertytot = aptot.fa[0]; */
/* } */
Nparticleread++;
ICurrentBlockStar++;
if ((ICurrentBlockStar == gi.NParticlePerBlock[STAR]) || (Nparticleread == th.nstar)) {
/*
** Block is full or we reached end of star matter particles
*/
gi.NParticleInBlock[STAR] = ICurrentBlockStar;
if (gi.DataProcessingMode == 0) put_particles_in_bins(gi,hd,STAR,pp[STAR]);
else if (gi.DataProcessingMode == 1) put_particles_in_storage(&gi,hd,hdeg,STAR,pp[STAR],&pp_storage[STAR]);
ICurrentBlockStar = 0;
}
} /* for nstar */
for (i = 0; i < gi.NParticlePerBlock[STAR]; i++) free(pp[STAR][i].P);
free(pp[STAR]);
gettimeofday(&time,NULL);
timeendsub = time.tv_sec;
timediff = timeendsub-timestartsub;
fprintf(stderr,"Done. It took %d s = %d h %d m %d s. Processed in total %d star particles.\n",timediff,timediff/3600,(timediff/60)%60,timediff%60,th.nstar);
}
else if (gi.DataFormat == 1 && gi.NHalo > 0) {
/*
** ART data
*/
/* if (gi.ProfilingMode == 3) { */
/* xdr_setpos(&TotDensityXDR,PosTotDensityXDR); */
/* if (gi.SpeciesContained[GAS]) xdr_setpos(&GasDensityXDR,PosGasDensityXDR); */
/* if (gi.SpeciesContained[DARK]) xdr_setpos(&DarkDensityXDR,PosDarkDensityXDR); */
/* if (gi.SpeciesContained[STAR]) xdr_setpos(&StarDensityXDR,PosStarDensityXDR); */
/* } */
if (ad.gascontained && gi.ILoopRead >= gi.NLoopRecentre) {
/*
** Gas
*/
gettimeofday(&time,NULL);
timestartsub = time.tv_sec;
fprintf(stderr,"Processing gas ... ");
/*
** Set file pointers correctly
*/
if (gi.ILoopRead == gi.NLoopRecentre) {
assert(fgetpos(ad.GasFile[0],&PosGasFile[0]) == 0);
if (ad.GRAVITY || ad.RADIATIVE_TRANSFER) assert(fgetpos(ad.GasFile[1],&PosGasFile[1]) == 0);
}
else {
assert(fsetpos(ad.GasFile[0],&PosGasFile[0]) == 0);
if (ad.GRAVITY || ad.RADIATIVE_TRANSFER) assert(fsetpos(ad.GasFile[1],&PosGasFile[1]) == 0);
}
/*
** Get arrays ready
*/
pp[GAS] = malloc(gi.NParticlePerBlock[GAS]*sizeof(PROFILE_PARTICLE));
assert(pp[GAS] != NULL);
for (i = 0; i < gi.NParticlePerBlock[GAS]; i++) {
pp[GAS][i].P = malloc((gi.NSubSpecies[GAS]+gi.NProperties[GAS])*sizeof(double));
assert(pp[GAS][i].P != NULL);
}
coordinates = malloc((ad.Lmaxgas+1)*sizeof(double **));
assert(coordinates != NULL);
Icoordinates = malloc((ad.Lmaxgas+1)*sizeof(long int));
assert(Icoordinates != NULL);
for (i = 0; i < (ad.Lmaxgas+1); i++) {
Icoordinates[i] = 0;
ad.Ncellrefined[i] = 0;
}
cellrefined = NULL;
Ngasread = 0;
ICurrentBlockGas = 0;
Ngasanalysis = 0;
init_sfc(&ad.asfci);
/*
** Go through all levels
*/
for (i = ad.Lmingas; i <= LmaxGasAnalysis; i++) {
/*
** Calculate level properties and read level header
*/
celllength = ad.rootcelllength/pow(2,i);
cellvolume = celllength*celllength*celllength;
read_art_nb_gas_header_level(&ad,i,&cellrefined);
/*
** get coordinates array ready
*/
if (i < LmaxGasAnalysis) {
coordinates[i] = malloc(ad.Ncellrefined[i]*sizeof(double *));
assert(coordinates[i] != NULL);
for (j = 0; j < ad.Ncellrefined[i]; j++) {
coordinates[i][j] = malloc(3*sizeof(double));
assert(coordinates[i][j] != NULL);
}
}
/*
** Move file positions
*/
move_art_nb_gas_filepositions_level_begin(ad,i);
/*
** Go through cells in this level
*/
for (j = 0; j < ad.Ncell[i]; j++) {
read_art_nb_gas_properties(ad,&agp);
Ngasread++;
/*
** Calculate coordinates
*/
if (i == ad.Lmingas) {
sfc_coords(ad.asfci,j,index);
for (k = 0; k < 3; k++) {
r[k] = index[k] + 0.5;
}
}
else {
for (k = 0; k < 3; k++) {
mothercellindex = j/8;
childcellindex = j%8;
r[k] = coordinates[i-1][mothercellindex][k] + celllength*art_cell_delta[childcellindex][k];
}
}
/*
** Check if cell is refined
*/
if ((cellrefined[j] == 0) || (i == LmaxGasAnalysis)) {
/*
** not refined or maximum level reached => add it for analysis
*/
Ngasanalysis++;
for (k = 0; k < 3; k++) {
v[k] = agp.momentum[k]/agp.gas_density;
pp[GAS][ICurrentBlockGas].r[k] = r[k];
pp[GAS][ICurrentBlockGas].v[k] = v[k];
}
pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][MASS_TOT]] = cellvolume*agp.gas_density;
if (gi.DoMetalSpecies) {
pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][MASS_METAL_SNII]] = cellvolume*agp.metal_density_SNII;
pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][MASS_METAL_SNIa]] = cellvolume*agp.metal_density_SNIa;
}
if (gi.DoChemicalSpecies) {
pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][MASS_HI]] = cellvolume*agp.HI_density;
pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][MASS_HII]] = cellvolume*agp.HII_density;
pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][MASS_HeI]] = cellvolume*agp.HeI_density;
pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][MASS_HeII]] = cellvolume*agp.HeII_density;
pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][MASS_HeIII]] = cellvolume*agp.HeIII_density;
pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][MASS_H2]] = cellvolume*agp.H2_density;
}
if (gi.DoGasTemperature) {
/*
** Number density 1/LU^3
*/
number_density = agp.HI_density*(PhysicalConstants.Mo/cosmo2internal_ct.M_usf)/PhysicalConstants.m_proton;
number_density += 2*agp.HII_density*(PhysicalConstants.Mo/cosmo2internal_ct.M_usf)/PhysicalConstants.m_proton;
number_density += agp.HeI_density*(PhysicalConstants.Mo/cosmo2internal_ct.M_usf)/(4*PhysicalConstants.m_proton);
number_density += 2*agp.HeII_density*(PhysicalConstants.Mo/cosmo2internal_ct.M_usf)/(4*PhysicalConstants.m_proton);
number_density += 3*agp.HeIII_density*(PhysicalConstants.Mo/cosmo2internal_ct.M_usf)/(4*PhysicalConstants.m_proton);
number_density += agp.H2_density*(PhysicalConstants.Mo/cosmo2internal_ct.M_usf)/(2*PhysicalConstants.m_proton);
/*
** Internal energy => internal energy per unit volume
*/
pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][TEMPERATURE]] = agp.internal_energy*(agp.gamma-1)/number_density;
/*
** Convert to Joules
*/
pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][TEMPERATURE]] /= cosmo2internal_ct.M_usf*pow(cosmo2internal_ct.V_usf,2);
pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][TEMPERATURE]] *= PhysicalConstants.Mo*pow(ConversionFactors.kpc_per_Gyr_2_km_per_s*1000,2);
/*
** Gas temperature in Kelvin
*/
pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][TEMPERATURE]] /= PhysicalConstants.k_Boltzmann;
}
/* if (gi.ProfilingMode == 3) { */
/* read_array_xdr_particle(&GasDensityXDR,&ahgas,&apgas); */
/* read_array_xdr_particle(&TotDensityXDR,&ahtot,&aptot); */
/* pp[GAS][ICurrentBlockGas].property = apgas.fa[0]; */
/* pp[GAS][ICurrentBlockGas].propertytot = aptot.fa[0]; */
/* } */
ICurrentBlockGas++;
if ((ICurrentBlockGas == gi.NParticlePerBlock[GAS]) || (Ngasread == ad.Ngas)) {
/*
** Block is full or we reached end of gas particles
*/
gi.NParticleInBlock[GAS] = ICurrentBlockGas;
if (gi.DataProcessingMode == 0 && gi.ILoopRead >= gi.NLoopRecentre) put_particles_in_bins(gi,hd,GAS,pp[GAS]);
else if (gi.DataProcessingMode == 1) put_particles_in_storage(&gi,hd,hdeg,GAS,pp[GAS],&pp_storage[GAS]);
ICurrentBlockGas = 0;
}
}
else if (i < LmaxGasAnalysis) {
/*
** refined and lower level than LmaxGasAnalysis => add it to corresponding coordinates array
*/
for (k = 0; k < 3; k++) {
coordinates[i][Icoordinates[i]][k] = r[k];
}
Icoordinates[i]++;
}
}
/*
** Move file positions
*/
move_art_nb_gas_filepositions_level_end(ad,i);
/*
** Checks and free coordinates of level below
*/
if (i < LmaxGasAnalysis) assert(Icoordinates[i] == ad.Ncellrefined[i]);
if (i > ad.Lmingas) {
for (j = 0; j < ad.Ncellrefined[i-1]; j++) {
free(coordinates[i-1][j]);
}
free(coordinates[i-1]);
}
}
/*
** Some checks and free remaining arrays
*/
if (LmaxGasAnalysis == ad.Lmaxgas) {
assert(ad.Ncellrefined[ad.Lmaxgas] == 0);
assert(ad.Ngas == Ngasread);
j = 0;
k = 0;
for (i = ad.Lmingas; i <= ad.Lmaxgas; i++) {
j += ad.Ncell[i];
k += ad.Ncellrefined[i];
}
assert(ad.Ngas == j);
assert(ad.Ngas == k + Ngasanalysis);
}
for (i = 0; i < gi.NParticlePerBlock[GAS]; i++) free(pp[GAS][i].P);
free(pp[GAS]);
free(Icoordinates);
free(cellrefined);
gettimeofday(&time,NULL);
timeendsub = time.tv_sec;
timediff = timeendsub-timestartsub;
fprintf(stderr,"Done. It took %d s = %d h %d m %d s. Processed in total %ld gas particles whereof %ld used for analysis.\n",timediff,timediff/3600,(timediff/60)%60,timediff%60,ad.Ngas,Ngasanalysis);
} /* if ad.gascontained && gi.ILoopRead >= gi.NLoopRecentre */
if (ad.darkcontained || ad.starcontained) {
/*
** Dark Matter and Stars
*/
gettimeofday(&time,NULL);
timestartsub = time.tv_sec;
fprintf(stderr,"Processing dark matter and stars ... ");
/*
** Set file pointers correctly
*/
if (gi.ILoopRead == 0) {
assert(fgetpos(ad.CoordinatesDataFile,PosCoordinatesDataFile) == 0);
for (i = 0; i < ad.Nstarproperties; i++) {
assert(fgetpos(ad.StarPropertiesFile[i],&PosStarPropertiesFile[i]) == 0);
}
}
else {
assert(fsetpos(ad.CoordinatesDataFile,PosCoordinatesDataFile) == 0);
for (i = 0; i < ad.Nstarproperties; i++) {
assert(fsetpos(ad.StarPropertiesFile[i],&PosStarPropertiesFile[i]) == 0);
}
}
/*
** Get arrays ready
*/
ac = malloc(ad.Nparticleperrecord*sizeof(ART_COORDINATES));
assert(ac != NULL);
pp[DARK] = malloc(gi.NParticlePerBlock[DARK]*sizeof(PROFILE_PARTICLE));
assert(pp[DARK] != NULL);
for (i = 0; i < gi.NParticlePerBlock[DARK]; i++) {
pp[DARK][i].P = malloc((gi.NSubSpecies[DARK]+gi.NProperties[DARK])*sizeof(double));
assert(pp[DARK][i].P != NULL);
}
if (ad.starcontained) {
pp[STAR] = malloc(gi.NParticlePerBlock[STAR]*sizeof(PROFILE_PARTICLE));
assert(pp[STAR] != NULL);
for (i = 0; i < gi.NParticlePerBlock[STAR]; i++) {
pp[STAR][i].P = malloc((gi.NSubSpecies[STAR]+gi.NProperties[STAR])*sizeof(double));
assert(pp[STAR][i].P != NULL);
}
move_art_nb_star_filepositions_begin(ad);
}
Nparticleread = 0;
ICurrentBlockDark = 0;
ICurrentBlockStar = 0;
for (i = 0; i < ad.Nrecord; i++) {
read_art_nb_coordinates_record(ad,ac);
for (j = 0; j < ad.Nparticleperrecord; j++) {
if (Nparticleread < ad.Ndark) {
/*
** Dark Matter
*/
for (k = 0; k < 3; k++) {
r[k] = put_in_box(ac[j].r[k]-ad.shift,gi.bc[k],gi.bc[k+3]);
v[k] = ac[j].v[k];
pp[DARK][ICurrentBlockDark].r[k] = r[k];
pp[DARK][ICurrentBlockDark].v[k] = v[k];
}
for (k = ad.Lmaxdark; k >=0; k--) {
if (ad.ah.num[k] >= Nparticleread) L = ad.Lmaxdark-k;
}
pp[DARK][ICurrentBlockDark].P[gi.pi[DARK][MASS_TOT]] = ad.massdark[L];
/* if (gi.ProfilingMode == 3) { */
/* read_array_xdr_particle(&DarkDensityXDR,&ahdark,&apdark); */
/* read_array_xdr_particle(&TotDensityXDR,&ahtot,&aptot); */
/* pp[DARK][ICurrentBlockDark].property = apdark.fa[0]; */
/* pp[DARK][ICurrentBlockDark].propertytot = aptot.fa[0]; */
/* } */
Nparticleread++;
ICurrentBlockDark++;
if ((ICurrentBlockDark == gi.NParticlePerBlock[DARK]) || (Nparticleread == ad.Ndark)) {
/*
** Block is full or we reached end of dark matter particles
*/
gi.NParticleInBlock[DARK] = ICurrentBlockDark;
if (gi.DataProcessingMode == 0) put_particles_in_bins(gi,hd,DARK,pp[DARK]);
else if (gi.DataProcessingMode == 1) put_particles_in_storage(&gi,hd,hdeg,DARK,pp[DARK],&pp_storage[DARK]);
ICurrentBlockDark = 0;
}
}
else if (Nparticleread < ad.Ndark+ad.Nstar) {
/*
** Star
*/
for (k = 0; k < 3; k++) {
r[k] = put_in_box(ac[j].r[k]-ad.shift,gi.bc[k],gi.bc[k+3]);
v[k] = ac[j].v[k];
pp[STAR][ICurrentBlockStar].r[k] = r[k];
pp[STAR][ICurrentBlockStar].v[k] = v[k];
}
/*
** Get other star properties
*/
read_art_nb_star_properties(ad,&asp);
pp[STAR][ICurrentBlockStar].P[gi.pi[STAR][MASS_TOT]] = asp.mass;
if (gi.DoMetalSpecies && gi.ILoopRead >= gi.NLoopRecentre) {
pp[STAR][ICurrentBlockStar].P[gi.pi[STAR][MASS_METAL_SNII]] = asp.mass*asp.metallicity_SNII;
pp[STAR][ICurrentBlockStar].P[gi.pi[STAR][MASS_METAL_SNIa]] = asp.mass*asp.metallicity_SNIa;
}
if (gi.DoStellarAge) {
pp[STAR][ICurrentBlockStar].P[gi.pi[STAR][AGE]] = asp.t_form;
}
/* if (gi.ProfilingMode == 3) { */
/* read_array_xdr_particle(&StarDensityXDR,&ahstar,&apstar); */
/* read_array_xdr_particle(&TotDensityXDR,&ahtot,&aptot); */
/* pp[STAR][ICurrentBlockStar].property = apstar.fa[0]; */
/* pp[STAR][ICurrentBlockStar].propertytot = aptot.fa[0]; */
/* } */
Nparticleread++;
ICurrentBlockStar++;
if ((ICurrentBlockStar == gi.NParticlePerBlock[STAR]) || (Nparticleread == ad.Ndark+ad.Nstar)) {
/*
** Block is full or we reached end of star particles
*/
gi.NParticleInBlock[STAR] = ICurrentBlockStar;
if (gi.DataProcessingMode == 0) put_particles_in_bins(gi,hd,STAR,pp[STAR]);
else if (gi.DataProcessingMode == 1) put_particles_in_storage(&gi,hd,hdeg,STAR,pp[STAR],&pp_storage[STAR]);
ICurrentBlockStar = 0;
}
}
}
}
if (ad.starcontained) move_art_nb_star_filepositions_end(ad);
free(ac);
for (i = 0; i < gi.NParticlePerBlock[DARK]; i++) free(pp[DARK][i].P);
free(pp[DARK]);
if (ad.starcontained) {
for (i = 0; i < gi.NParticlePerBlock[STAR]; i++) free(pp[STAR][i].P);
free(pp[STAR]);
}
gettimeofday(&time,NULL);
timeendsub = time.tv_sec;
timediff = timeendsub-timestartsub;
fprintf(stderr,"Done. It took %d s = %d h %d m %d s. Processed in total %ld dark matter and %ld star particles.\n",timediff,timediff/3600,(timediff/60)%60,timediff%60,ad.Ndark,ad.Nstar);
} /* if ad.darkcontained || ad.starcontained */
} /* if DataFormat */
/*
** Do loop specific stuff
*/
if (gi.DataProcessingMode == 0) {
if (gi.ProfilingMode == 0 && gi.ILoopRead < gi.NLoopRecentre) {
/*
** Calculate recentred halo coordinates
*/
calculate_recentred_halo_coordinates(gi,hd);
}
else if (gi.ProfilingMode == 0 && gi.ILoopRead >= gi.NLoopRecentre) {
/*
** Calculate total and baryonic matter distribution
*/
calculate_total_matter_distribution(gi,hd);
calculate_baryonic_matter_distribution(gi,hd);
}
else if (gi.ProfilingMode == 1) {
/*
** Diagonalise enclosed shape tensor
*/
gettimeofday(&time,NULL);
timestartsub = time.tv_sec;
fprintf(stderr,"Diagonalising shape tensors ... ");
convergencefraction = diagonalise_shape_tensors(gi,hd,gi.ILoopRead+1);
gettimeofday(&time,NULL);
timeendsub = time.tv_sec;
timediff = timeendsub-timestartsub;
fprintf(stderr,"Done. It took %d s = %d h %d m %d s. The fraction of converged bins so far is %g.\n",timediff,timediff/3600,(timediff/60)%60,timediff%60,convergencefraction);
if (convergencefraction == 1 ||
(gi.ILoopRead+1)%gi.OutputFrequencyShapeIteration == 0 ||
gi.ILoopRead+1 == gi.NLoopShapeIterationMax) {
gettimeofday(&time,NULL);
timestartsub = time.tv_sec;
fprintf(stderr,"Writing output ... ");
write_output_shape_profile(gi,hd,gi.ILoopRead+1);
gettimeofday(&time,NULL);
timeendsub = time.tv_sec;
timediff = timeendsub-timestartsub;
fprintf(stderr,"Done. It took %d s = %d h %d m %d s.\n",timediff,timediff/3600,(timediff/60)%60,timediff%60);
}
if (convergencefraction < 1 && gi.ILoopRead < gi.NLoopShapeIterationMax-1) {
reset_halo_profile_shape(gi,hd);
gi.NLoopRead++;
gi.NLoopProcessData++;
}
}
/* else if (gi.ProfilingMode == 3 && gi.ILoopRead == 0) { */
/* double fproperty = gi.fincludeshapeproperty; */
/* /\* */
/* ** This is still under construction: the shape values are pretty sensitive to the selected set. */
/* ** Probably worth trying median in stead of mean => how to calculate median efficiently on the fly */
/* ** without storing data & sorting? */
/* ** Maybe try to loop over density iteration as well */
/* *\/ */
/* for (i = 0; i < gi.NHalo; i++) { */
/* for (j = 0; j < hd[i].NBin[0]+1; j++) { */
/* /\* */
/* ** Total matter */
/* *\/ */
/* if (hd[i].pbs[j].totshape->N > 0) hd[i].pbs[j].totshape->propertymean /= hd[i].pbs[j].totshape->N; */
/* hd[i].pbs[j].totshape->propertymin = hd[i].pbs[j].totshape->propertymean/fproperty; */
/* hd[i].pbs[j].totshape->propertymax = hd[i].pbs[j].totshape->propertymean*fproperty; */
/* /\* */
/* fprintf(stderr,"i %ld j %ld N %ld propertymin %.6e propertymean %.6e propertymax %.6e\n",i,j,hd[i].pbs[j].totshape->N, */
/* hd[i].pbs[j].totshape->propertymin,hd[i].pbs[j].totshape->propertymax,hd[i].pbs[j].totshape->propertymean); */
/* *\/ */
/* hd[i].pbs[j].totshape->N = 0; */
/* /\* */
/* ** Gas */
/* *\/ */
/* if (gi.SpeciesContained[GAS]) { */
/* if (hd[i].pbs[j].gasshape->N > 0) hd[i].pbs[j].gasshape->propertymean /= hd[i].pbs[j].gasshape->N; */
/* hd[i].pbs[j].gasshape->propertymin = hd[i].pbs[j].gasshape->propertymean/fproperty; */
/* hd[i].pbs[j].gasshape->propertymax = hd[i].pbs[j].gasshape->propertymean*fproperty; */
/* /\* */
/* fprintf(stderr,"i %ld j %ld N %ld propertymin %.6e propertymean %.6e propertymax %.6e\n",i,j,hd[i].pbs[j].gasshape->N, */
/* hd[i].pbs[j].gasshape->propertymin,hd[i].pbs[j].gasshape->propertymax,hd[i].pbs[j].gasshape->propertymean); */
/* *\/ */
/* hd[i].pbs[j].gasshape->N = 0; */
/* } */
/* /\* */
/* ** Dark matter */
/* *\/ */
/* if (gi.SpeciesContained[DARK]) { */
/* if (hd[i].pbs[j].darkshape->N > 0) hd[i].pbs[j].darkshape->propertymean /= hd[i].pbs[j].darkshape->N; */
/* hd[i].pbs[j].darkshape->propertymin = hd[i].pbs[j].darkshape->propertymean/fproperty; */
/* hd[i].pbs[j].darkshape->propertymax = hd[i].pbs[j].darkshape->propertymean*fproperty; */
/* /\* */
/* fprintf(stderr,"i %ld j %ld N %ld propertymin %.6e propertymean %.6e propertymax %.6e\n",i,j,hd[i].pbs[j].darkshape->N, */
/* hd[i].pbs[j].darkshape->propertymin,hd[i].pbs[j].darkshape->propertymax,hd[i].pbs[j].darkshape->propertymean); */
/* *\/ */
/* hd[i].pbs[j].darkshape->N = 0; */
/* } */
/* /\* */
/* ** Stars */
/* *\/ */
/* if (gi.SpeciesContained[STAR]) { */
/* if (hd[i].pbs[j].starshape->N > 0) hd[i].pbs[j].starshape->propertymean /= hd[i].pbs[j].starshape->N; */
/* hd[i].pbs[j].starshape->propertymin = hd[i].pbs[j].starshape->propertymean/fproperty; */
/* hd[i].pbs[j].starshape->propertymax = hd[i].pbs[j].starshape->propertymean*fproperty; */
/* /\* */
/* fprintf(stderr,"i %ld j %ld N %ld propertymin %.6e propertymean %.6e propertymax %.6e\n",i,j,hd[i].pbs[j].starshape->N, */
/* hd[i].pbs[j].starshape->propertymin,hd[i].pbs[j].starshape->propertymean,hd[i].pbs[j].starshape->propertymax); */
/* *\/ */
/* hd[i].pbs[j].starshape->N = 0; */
/* } */
/* } */
/* } */
/* gi.NLoopRead++; */
/* gi.NLoopProcessData++; */
/* } */
/* else if (gi.ProfilingMode == 3 && gi.ILoopRead == 1) { */
/* /\* */
/* ** Close density files */
/* *\/ */
/* if (0) { */
/* xdr_destroy(&TotDensityXDR); */
/* fclose(TotDensityFile); */
/* if (gi.SpeciesContained[GAS]) { */
/* xdr_destroy(&GasDensityXDR); */
/* fclose(GasDensityFile); */
/* } */
/* if (gi.SpeciesContained[DARK]) { */
/* xdr_destroy(&DarkDensityXDR); */
/* fclose(DarkDensityFile); */
/* } */
/* if (gi.SpeciesContained[STAR]) { */
/* xdr_destroy(&StarDensityXDR); */
/* fclose(StarDensityFile); */
/* } */
/* } */
/* /\* */
/* ** Diagonalise local shape tensor */
/* *\/ */
/* diagonalise_shape_tensors(gi,hd,gi.ILoopRead+1); */
/* gi.NLoopRead++; */
/* gi.NLoopProcessData++; */
/* } */
/* else if (gi.ProfilingMode == 3 && gi.ILoopRead == 2) { */
/* diagonalise_shape_tensors(gi,hd); */
/* } */
}
else if (gi.DataProcessingMode == 1) {
fprintf(stderr,"Put %d gas, %d dark matter and %d star particles into storage.\n",gi.NParticleInStorage[GAS],gi.NParticleInStorage[DARK],gi.NParticleInStorage[STAR]);
}
gettimeofday(&time,NULL);
timeendloop = time.tv_sec;
timediff = timeendloop-timestartloop;
fprintf(stderr,"Done with loop %d. It took %d s = %d h %d m %d s.\n\n",gi.ILoopRead+1,timediff,timediff/3600,(timediff/60)%60,timediff%60);
} /* for ILoopRead */
/*
** After-harvest tasks
*/
if (gi.ProfilingMode == 0) {
/*
** Calculate halo properties
*/
gettimeofday(&time,NULL);
timestartsub = time.tv_sec;
fprintf(stderr,"Calculating halo properties ... ");
calculate_halo_properties(gi,hd);
gettimeofday(&time,NULL);
timeendsub = time.tv_sec;
timediff = timeendsub-timestartsub;
fprintf(stderr,"Done. It took %d s = %d h %d m %d s.\n\n",timediff,timediff/3600,(timediff/60)%60,timediff%60);
/*
** Determine hierarchy of haloes
*/
if (gi.BinningCoordinateType == 0) {
gettimeofday(&time,NULL);
timestartsub = time.tv_sec;
fprintf(stderr,"Determining hierarchy of haloes ... ");
determine_halo_hierarchy(gi,hd);
gettimeofday(&time,NULL);
timeendsub = time.tv_sec;
timediff = timeendsub-timestartsub;
fprintf(stderr,"Done. It took %d s = %d h %d m %d s.\n\n",timediff,timediff/3600,(timediff/60)%60,timediff%60);
}
/*
** Write output
*/
gettimeofday(&time,NULL);
timestartsub = time.tv_sec;
fprintf(stderr,"Writing output ... ");
write_output_matter_profile(gi,hd);
gettimeofday(&time,NULL);
timeendsub = time.tv_sec;
timediff = timeendsub-timestartsub;
fprintf(stderr,"Done. It took %d s = %d h %d m %d s.\n\n",timediff,timediff/3600,(timediff/60)%60,timediff%60);
}
if (gi.ProfilingMode == 1 && gi.DataProcessingMode == 1) {
/*
** Diagonalise enclosed shape tensor
*/
for (i = 0; i < gi.NLoopShapeIterationMax; i++) {
/*
** Put particles in bins
*/
gettimeofday(&time,NULL);
timestartloop = time.tv_sec;
fprintf(stderr,"Doing iteration %ld ...\n",i+1);
for (j = 0; j < gi.NSpeciesRead; j++) {
if (gi.SpeciesContained[j]) {
gettimeofday(&time,NULL);
timestartsub = time.tv_sec;
if (j == GAS) strcpy(cdummy,"gas");
else if (j == DARK) strcpy(cdummy,"dark matter");
else if (j == STAR) strcpy(cdummy,"stars");
else strcpy(cdummy,"a matter type that should not be here");
fprintf(stderr,"Processing %s ... ",cdummy);
put_particles_in_bins(gi,hd,j,pp_storage[j]);
gettimeofday(&time,NULL);
timeendsub = time.tv_sec;
timediff = timeendsub-timestartsub;
if (j == STAR) strcpy(cdummy,"star");
fprintf(stderr,"Done. It took %d s = %d h %d m %d s. Processed in total %d %s particles.\n",timediff,timediff/3600,(timediff/60)%60,timediff%60,gi.NParticleInStorage[j],cdummy);
}
}
/*
** Diagonalise enclosed shape tensor
*/
gettimeofday(&time,NULL);
timestartsub = time.tv_sec;
fprintf(stderr,"Diagonalising shape tensors ... ");
convergencefraction = diagonalise_shape_tensors(gi,hd,i+1);
gettimeofday(&time,NULL);
timeendsub = time.tv_sec;
timediff = timeendsub-timestartsub;
fprintf(stderr,"Done. It took %d s = %d h %d m %d s. The fraction of converged bins so far is %g.\n",timediff,timediff/3600,(timediff/60)%60,timediff%60,convergencefraction);
if (convergencefraction == 1 ||
(i+1)%gi.OutputFrequencyShapeIteration == 0 ||
i+1 == gi.NLoopShapeIterationMax) {
gettimeofday(&time,NULL);
timestartsub = time.tv_sec;
fprintf(stderr,"Writing output ... ");
write_output_shape_profile(gi,hd,i+1);
gettimeofday(&time,NULL);
timeendsub = time.tv_sec;
timediff = timeendsub-timestartsub;
fprintf(stderr,"Done. It took %d s = %d h %d m %d s.\n",timediff,timediff/3600,(timediff/60)%60,timediff%60);
}
if (convergencefraction < 1 && i < gi.NLoopShapeIterationMax-1) reset_halo_profile_shape(gi,hd);
gettimeofday(&time,NULL);
timeendloop = time.tv_sec;
timediff = timeendloop-timestartloop;
fprintf(stderr,"Done with iteration %ld. It took %d s = %d h %d m %d s.\n\n",i+1,timediff,timediff/3600,(timediff/60)%60,timediff%60);
if (convergencefraction == 1) break;
}
}
/*
** Some more output if desired
*/
if (VerboseLevel > 0) {
/*
** 6DFOF
*/
if (gi.HaloCatalogueFormat == 1) {
fprintf(stderr,"6DFOF specific parameters:\n\n");
fprintf(stderr,"BinFactor : %.6e\n",gi.BinFactor);
if (gi.CentreType == 0) fprintf(stderr,"CentreType : centre-of-mass\n");
else if (gi.CentreType == 1) fprintf(stderr,"CentreType : potmin or denmax\n");
fprintf(stderr,"rmaxFromHaloCatalogue : %s\n",(gi.rmaxFromHaloCatalogue == 0)?"no":"yes");
fprintf(stderr,"\n");
}
/*
** ART
*/
if (gi.DataFormat == 1) {
fprintf(stderr,"ART general header:\n\n");
fprintf(stderr,"aunin : %.6e\n",ad.ah.aunin);
fprintf(stderr,"auni0 : %.6e\n",ad.ah.auni0);
fprintf(stderr,"amplt : %.6e\n",ad.ah.amplt);
fprintf(stderr,"astep : %.6e\n",ad.ah.astep);
fprintf(stderr,"istep : %d\n",ad.ah.istep);
fprintf(stderr,"partw : %.6e\n",ad.ah.partw);
fprintf(stderr,"tintg : %.6e\n",ad.ah.tintg);
fprintf(stderr,"ekin : %.6e\n",ad.ah.ekin);
fprintf(stderr,"ekin1 : %.6e\n",ad.ah.ekin1);
fprintf(stderr,"ekin2 : %.6e\n",ad.ah.ekin2);
fprintf(stderr,"au0 : %.6e\n",ad.ah.au0);
fprintf(stderr,"aeu0 : %.6e\n",ad.ah.aeu0);
fprintf(stderr,"Nrow : %d\n",ad.ah.Nrow);
fprintf(stderr,"Ngrid : %d\n",ad.ah.Ngrid);
fprintf(stderr,"Nspecies : %d\n",ad.ah.Nspecies);
fprintf(stderr,"Nseed : %d\n",ad.ah.Nseed);
fprintf(stderr,"OmM0 : %.6e\n",ad.ah.OmM0);
fprintf(stderr,"OmL0 : %.6e\n",ad.ah.OmL0);
fprintf(stderr,"h100 : %.6e\n",ad.ah.h100);
fprintf(stderr,"Wp5 : %.6e\n",ad.ah.Wp5);
fprintf(stderr,"OmK0 : %.6e\n",ad.ah.OmK0);
fprintf(stderr,"OmB0 : %.6e\n",ad.ah.OmB0);
fprintf(stderr,"magic1 : %.6e\n",ad.ah.magic1);
fprintf(stderr,"DelDC : %.6e\n",ad.ah.DelDC);
fprintf(stderr,"abox : %.6e\n",ad.ah.abox);
fprintf(stderr,"Hbox : %.6e\n",ad.ah.Hbox);
fprintf(stderr,"magic2 : %.6e\n",ad.ah.magic2);
fprintf(stderr,"Banner : %s\n",ad.Banner);
fprintf(stderr,"\n");
for (i = 0; i < 10; i++) {
fprintf(stderr,"mass[%ld] : %.6e num[%ld] : %d\n",i,ad.ah.mass[i],i,ad.ah.num[i]);
}
fprintf(stderr,"\n");
fprintf(stderr,"ART data properties:\n\n");
fprintf(stderr,"Particle file mode : %d\n",ad.particle_file_mode);
fprintf(stderr,"Nparticleperrecord : %d\n",ad.Nparticleperrecord);
fprintf(stderr,"Nrecord : %d\n",ad.Nrecord);
fprintf(stderr,"Nhydroproperties : %d\n",ad.Nhydroproperties);
fprintf(stderr,"Notherproperties : %d\n",ad.Notherproperties);
fprintf(stderr,"Nrtchemspecies : %d\n",ad.Nrtchemspecies);
fprintf(stderr,"Nchemspecies : %d\n",ad.Nchemspecies);
fprintf(stderr,"Nstarproperties : %d\n",ad.Nstarproperties);
fprintf(stderr,"Lmingas : %d\n",ad.Lmingas);
fprintf(stderr,"Lmaxgas : %d\n",ad.Lmaxgas);
fprintf(stderr,"Lmindark : %d\n",ad.Lmindark);
fprintf(stderr,"Lmaxdark : %d\n",ad.Lmaxdark);
fprintf(stderr,"\n");
fprintf(stderr,"ART preprocessor flags:\n\n");
fprintf(stderr,"-GRAVITY : %s\n",(ad.GRAVITY == 0)?"not set":"set");
fprintf(stderr,"-HYDRO : %s\n",(ad.HYDRO == 0)?"not set":"set");
fprintf(stderr,"-ADVECT_SPECIES : %s\n",(ad.ADVECT_SPECIES == 0)?"not set":"set");
fprintf(stderr,"-STARFORM : %s\n",(ad.STARFORM == 0)?"not set":"set");
fprintf(stderr,"-ENRICH : %s\n",(ad.ENRICH == 0)?"not set":"set");
fprintf(stderr,"-ENRICH_SNIa : %s\n",(ad.ENRICH_SNIa == 0)?"not set":"set");
fprintf(stderr,"-RADIATIVE_TRANSFER : %s\n",(ad.RADIATIVE_TRANSFER == 0)?"not set":"set");
fprintf(stderr,"-ELECTRON_ION_NONEQUILIBRIUM : %s\n",(ad.ELECTRON_ION_NONEQUILIBRIUM == 0)?"not set":"set");
fprintf(stderr,"\n");
fprintf(stderr,"ART specific parameters:\n\n");
fprintf(stderr,"LmaxGasAnalysis : %d\n",LmaxGasAnalysis);
fprintf(stderr,"\n");
}
/*
** Cosmology
*/
fprintf(stderr,"Cosmology:\n\n");
fprintf(stderr,"OmegaM0 : %.6e\n",gi.cp.OmegaM0);
fprintf(stderr,"OmegaL0 : %.6e\n",gi.cp.OmegaL0);
fprintf(stderr,"OmegaK0 : %.6e\n",gi.cp.OmegaK0);
fprintf(stderr,"OmegaR0 : %.6e\n",gi.cp.OmegaR0);
fprintf(stderr,"h0_100 : %.6e\n",gi.cp.h0_100);
fprintf(stderr,"\n");
/*
** Unit system
*/
fprintf(stderr,"Unit System:\n\n");
fprintf(stderr,"LBox : %.6e LU\n",gi.us.LBox);
fprintf(stderr,"Hubble0 : %.6e TU^{-1}\n",gi.us.Hubble0);
fprintf(stderr,"rhocrit0 : %.6e MU LU^{-3}\n",gi.us.rhocrit0);
fprintf(stderr,"\n");
/*
** Internal units
*/
fprintf(stderr,"Internal units:\n\n");
fprintf(stderr,"LU : %.6e kpc\n",1.0/cosmo2internal_ct.L_usf);
fprintf(stderr,"TU : %.6e Gyr\n",1.0/cosmo2internal_ct.T_usf);
fprintf(stderr,"VU : %.6e kpc Gyr^{-1} = %.6e km s^{-1}\n",1.0/cosmo2internal_ct.V_usf,1.0/cosmo2internal_ct.V_usf*ConversionFactors.kpc_per_Gyr_2_km_per_s);
fprintf(stderr,"MU : %.6e Mo\n",1.0/cosmo2internal_ct.M_usf);
fprintf(stderr,"\n");
/*
** Data properties
*/
fprintf(stderr,"Data properties:\n\n");
switch(gi.DataFormat) {
case 0: strcpy(cdummy,"Tipsy"); break;
case 1: strcpy(cdummy,"ART"); break;
default: strcpy(cdummy,"not supported"); }
fprintf(stderr,"Data format : %s\n",cdummy);
fprintf(stderr,"Contains anything : %s\n",(gi.SpeciesContained[TOT])?"yes":"no");
fprintf(stderr,"Contains gas : %s\n",(gi.SpeciesContained[GAS])?"yes":"no");
fprintf(stderr,"Contains dark matter : %s\n",(gi.SpeciesContained[DARK])?"yes":"no");
fprintf(stderr,"Contains stars : %s\n",(gi.SpeciesContained[STAR])?"yes":"no");
fprintf(stderr,"Contains baryons : %s\n",(gi.SpeciesContained[BARYON])?"yes":"no");
fprintf(stderr,"a : %.6e\n",gi.ascale);
fprintf(stderr,"LBox : %.6e LU (comoving) = %.6e kpc (comoving) = %.6e kpc (physical)\n",
cosmo2internal_ct.L_usf*LBox,LBox,gi.ascale*LBox);
fprintf(stderr,"Box : [%.6e ... %.6e] x [%.6e ... %.6e] x [%.6e ... %.6e] LU (comoving)\n",gi.bc[0],gi.bc[3],gi.bc[1],gi.bc[4],gi.bc[2],gi.bc[5]);
fprintf(stderr,"\n");
/*
** Profiling parameters
*/
fprintf(stderr,"Profiling parameters:\n\n");
switch(gi.ProfilingMode) {
case 0: strcpy(cdummy,"profiles"); break;
case 1: strcpy(cdummy,"shape determination"); break;
default: strcpy(cdummy,"not supported"); }
fprintf(stderr,"Profiling mode : %s\n",cdummy);
switch(gi.DataProcessingMode) {
case 0: strcpy(cdummy,"read data again in every loop"); break;
case 1: strcpy(cdummy,"store data in memory"); break;
default: strcpy(cdummy,"not supported"); }
fprintf(stderr,"Data processing mode : %s\n",cdummy);
fprintf(stderr,"Do metal species : %s\n",(gi.DoMetalSpecies)?"yes":"no");
fprintf(stderr,"Do chemical species : %s\n",(gi.DoChemicalSpecies)?"yes":"no");
fprintf(stderr,"Do gas temperature : %s\n",(gi.DoGasTemperature)?"yes":"no");
fprintf(stderr,"Do stellar age : %s\n",(gi.DoStellarAge)?"yes":"no");
fprintf(stderr,"More characteristics output : %s\n",(gi.MoreCharacteristicsOutput)?"yes":"no");
fprintf(stderr,"Exclude particles : %s\n",(gi.ExcludeParticles)?"yes":"no");
fprintf(stderr,"Number of profile dimensions : %d\n",gi.NDimProfile);
fprintf(stderr,"Number of read species : %d\n",gi.NSpeciesRead);
fprintf(stderr,"Number of profiled species : %d\n",gi.NSpeciesProfile);
for (i = 0; i < gi.NSpeciesRead; i++) {
switch(i) {
case GAS: strcpy(cdummy,"gas"); break;
case DARK: strcpy(cdummy,"dark matter"); break;
case STAR: strcpy(cdummy,"stars"); break;
default: strcpy(cdummy,"not supported"); }
fprintf(stderr,"Number of subspecies / properties : %d / %d (%s)\n",gi.NSubSpecies[i],gi.NProperties[i],cdummy);
}
fprintf(stderr,"NParticlePerBlockGas : %d\n",gi.NParticlePerBlock[GAS]);
fprintf(stderr,"NParticlePerBlockDark : %d\n",gi.NParticlePerBlock[DARK]);
fprintf(stderr,"NParticlePerBlockStar : %d\n",gi.NParticlePerBlock[STAR]);
fprintf(stderr,"NCellData : %d\n",gi.NCellData);
fprintf(stderr,"NCellHalo : %d\n",gi.NCellHalo);
fprintf(stderr,"NLoopProcessData : %d\n",gi.NLoopProcessData);
fprintf(stderr,"NLoopRead : %d\n",gi.NLoopRead);
fprintf(stderr,"\n");
/*
** Halo catalogue
*/
fprintf(stderr,"Halo catalogue properties:\n\n");
switch(gi.HaloCatalogueFormat) {
case 0: strcpy(cdummy,"generic"); break;
case 1: strcpy(cdummy,"6DFOF"); break;
case 2: strcpy(cdummy,"characteristics"); break;
default: strcpy(cdummy,"not supported"); }
fprintf(stderr,"Halocatalogue format : %s\n",cdummy);
switch(gi.HaloCatalogueBinningCoordinateType) {
case 0: strcpy(cdummy,"spherical"); break;
case 1: strcpy(cdummy,"cylindrical"); break;
default: strcpy(cdummy,"not supported"); }
fprintf(stderr,"Halocatalogue binning type : %s\n",cdummy);
fprintf(stderr,"Halocatalogue dimension : %d\n",gi.HaloCatalogueNDim);
fprintf(stderr,"NHalo : %d\n",gi.NHalo);
fprintf(stderr,"\n");
/*
** Exclude halo catalogue
*/
fprintf(stderr,"Exclude halo catalogue properties:\n\n");
if (gi.ExcludeParticles) {
switch(gi.ExcludeHaloCatalogueFormat) {
case 0: strcpy(cdummy,"generic"); break;
case 1: strcpy(cdummy,"6DFOF"); break;
case 2: strcpy(cdummy,"characteristics"); break;
default: strcpy(cdummy,"not supported"); }
fprintf(stderr,"ExcludeHalocatalogue format : %s\n",cdummy);
fprintf(stderr,"ExcludeHalocatalogue binning type : spherical\n");
fprintf(stderr,"ExcludeHalocatalogue dimension : %d\n",gi.ExcludeHaloCatalogueNDim);
fprintf(stderr,"NHaloExcludeGlobal : %d\n",gi.NHaloExcludeGlobal);
}
else {
fprintf(stderr,"No particles were excluded.\n");
}
fprintf(stderr,"\n");
/*
** Recentring
*/
fprintf(stderr,"Recentring:\n\n");
if (gi.NLoopRecentre > 0) {
switch(LengthType_rRecentre) {
case 0: strcpy(cdummy,"comoving"); break;
case 1: strcpy(cdummy,"physical"); break;
default: strcpy(cdummy,"not supported"); }
fprintf(stderr,"Length type rRecentre : %s\n",cdummy);
fprintf(stderr,"rRecentre : %.6e LU (comoving) = %.6e kpc (comoving) = %.6e kpc (physical)\n",
gi.rRecentre,gi.rRecentre/cosmo2internal_ct.L_usf,gi.ascale*gi.rRecentre/cosmo2internal_ct.L_usf);
fprintf(stderr,"fRecentreDist : %.6e\n",gi.fRecentreDist);
fprintf(stderr,"NLoopRecentre : %d\n",gi.NLoopRecentre);
for (i = 0; i < gi.NSpeciesRead; i++) {
switch(i) {
case GAS: strcpy(cdummy,"gas"); break;
case DARK: strcpy(cdummy,"dark matter"); break;
case STAR: strcpy(cdummy,"stars"); break;
default: strcpy(cdummy,"not supported"); }
fprintf(stderr,"Recentre use %s : %s\n",cdummy,gi.RecentreUse[i]?"yes":"no");
}
}
else {
fprintf(stderr,"No recentring was done.\n");
}
fprintf(stderr,"\n");
/*
** Profiles
*/
if (gi.ProfilingMode == 0) {
fprintf(stderr,"General profiling properties:\n\n");
switch(gi.BinningCoordinateType) {
case 0: strcpy(cdummy,"spherical"); break;
case 1: strcpy(cdummy,"cylindrical"); break;
default: strcpy(cdummy,"not supported"); }
fprintf(stderr,"Binning : %s\n",cdummy);
switch(gi.VelocityProjectionType) {
case 0: strcpy(cdummy,"coordinate axes"); break;
case 1: strcpy(cdummy,"spherical"); break;
case 2: strcpy(cdummy,"cylindrical"); break;
default: strcpy(cdummy,"not supported"); }
fprintf(stderr,"Velocity projection : %s\n",cdummy);
fprintf(stderr,"\n");
/*
** Spherical profiles
*/
if (gi.BinningCoordinateType == 0) {
fprintf(stderr,"Spherical profiles:\n\n");
switch(gi.HaloSize) {
case 0: strcpy(cdummy,"rmean"); break;
case 1: strcpy(cdummy,"rcrit"); break;
case 2: strcpy(cdummy,"rfix"); break;
default: strcpy(cdummy,"not supported"); }
fprintf(stderr,"Halo size : %s\n",cdummy);
fprintf(stderr,"rho_mean : %.6e MU LU^{-3} (comoving) = %.6e Mo kpc^{-3} (comoving) = %.6e Mo kpc^{-3} (physical)\n",
gi.rhomean,gi.rhomean*pow(cosmo2internal_ct.L_usf,3)/cosmo2internal_ct.M_usf,
gi.rhomean*pow(cosmo2internal_ct.L_usf,3)/(pow(gi.ascale,3)*cosmo2internal_ct.M_usf));
fprintf(stderr,"rho_crit : %.6e MU LU^{-3} (comoving) = %.6e Mo kpc^{-3} (comoving) = %.6e Mo kpc^{-3} (physical)\n",
gi.rhocrit,gi.rhocrit*pow(cosmo2internal_ct.L_usf,3)/cosmo2internal_ct.M_usf,
gi.rhocrit*pow(cosmo2internal_ct.L_usf,3)/(pow(gi.ascale,3)*cosmo2internal_ct.M_usf));
fprintf(stderr,"Delta_mean : %.6e\n",gi.Deltamean);
fprintf(stderr,"Delta_crit : %.6e\n",gi.Deltacrit);
fprintf(stderr,"Delta_fix : %.6e\n",gi.Deltafix);
fprintf(stderr,"afix : %.6e\n",gi.afix);
fprintf(stderr,"rhoenc_mean : %.6e MU LU^{-3} (comoving) = %.6e Mo kpc^{-3} (comoving) = %.6e Mo kpc^{-3} (physical)\n",
gi.rhoencmean,gi.rhoencmean*pow(cosmo2internal_ct.L_usf,3)/cosmo2internal_ct.M_usf,
gi.rhoencmean*pow(cosmo2internal_ct.L_usf,3)/(pow(gi.ascale,3)*cosmo2internal_ct.M_usf));
fprintf(stderr,"rhoenc_crit : %.6e MU LU^{-3} (comoving) = %.6e Mo kpc^{-3} (comoving) = %.6e Mo kpc^{-3} (physical)\n",
gi.rhoenccrit,gi.rhoenccrit*pow(cosmo2internal_ct.L_usf,3)/cosmo2internal_ct.M_usf,
gi.rhoenccrit*pow(cosmo2internal_ct.L_usf,3)/(pow(gi.ascale,3)*cosmo2internal_ct.M_usf));
fprintf(stderr,"rhoenc_fix : %.6e MU LU^{-3} (comoving) = %.6e Mo kpc^{-3} (comoving) = %.6e Mo kpc^{-3} (physical)\n",
gi.rhoencfix,gi.rhoencfix*pow(cosmo2internal_ct.L_usf,3)/cosmo2internal_ct.M_usf,
gi.rhoencfix*pow(cosmo2internal_ct.L_usf,3)/(pow(gi.ascale,3)*cosmo2internal_ct.M_usf));
switch(LengthType_rExclude) {
case 0: strcpy(cdummy,"comoving"); break;
case 1: strcpy(cdummy,"physical"); break;
default: strcpy(cdummy,"not supported"); }
fprintf(stderr,"Length type rExclude : %s\n",cdummy);
fprintf(stderr,"rExclude : %.6e LU (comoving) = %.6e kpc (comoving) = %.6e kpc (physical)\n",
gi.rExclude,gi.rExclude/cosmo2internal_ct.L_usf,gi.ascale*gi.rExclude/cosmo2internal_ct.L_usf);
fprintf(stderr,"fcheckrvcmax : %.6e\n",gi.fcheckrvcmax);
fprintf(stderr,"slopertruncindicator : %.6e\n",gi.slopertruncindicator);
fprintf(stderr,"frhobg : %.6e\n",gi.frhobg);
fprintf(stderr,"fhaloduplicate : %.6e\n",gi.fhaloduplicate);
fprintf(stderr,"fhaloexcludesize : %.6e\n",gi.fhaloexcludesize);
fprintf(stderr,"fhaloexcludedistance : %.6e\n",gi.fhaloexcludedistance);
fprintf(stderr,"\n");
}
/*
** Cylindrical profiles
*/
if (gi.BinningCoordinateType == 1) {
fprintf(stderr,"Cylindrical profiles:\n\n");
fprintf(stderr,"zAxis_x : %.6e LU\n",gi.zAxis[0]);
fprintf(stderr,"zAxis_y : %.6e LU\n",gi.zAxis[1]);
fprintf(stderr,"zAxis_z : %.6e LU\n",gi.zAxis[2]);
switch(LengthType_zHeight) {
case 0: strcpy(cdummy,"comoving"); break;
case 1: strcpy(cdummy,"physical"); break;
default: strcpy(cdummy,"not supported"); }
fprintf(stderr,"Length type zHeight : %s\n",cdummy);
fprintf(stderr,"zHeight : %.6e LU (comoving) = %.6e kpc (comoving) = %.6e kpc (physical)\n",
gi.zHeight,gi.zHeight/cosmo2internal_ct.L_usf,gi.ascale*gi.zHeight/cosmo2internal_ct.L_usf);
fprintf(stderr,"\n");
}
}
/*
** Shape
*/
if (gi.ProfilingMode == 1) {
fprintf(stderr,"Shape determination:\n\n");
switch(gi.ShapeDeterminationVolume) {
case 0: strcpy(cdummy,"differential volume"); break;
case 1: strcpy(cdummy,"enclosed volume"); break;
default: strcpy(cdummy,"not supported"); }
fprintf(stderr,"Shape determination volume : %s\n",cdummy);
switch(gi.ShapeTensorForm) {
case 0: strcpy(cdummy,"S_ij"); break;
case 1: strcpy(cdummy,"S_ij/r^2"); break;
case 2: strcpy(cdummy,"S_ij/r_ell^2"); break;
default: strcpy(cdummy,"not supported"); }
fprintf(stderr,"Shape tensor form : %s\n",cdummy);
fprintf(stderr,"NLoopShapeIterationMax : %d\n",gi.NLoopShapeIterationMax);
fprintf(stderr,"OutputFrequencyShapeIteration : %d\n",gi.OutputFrequencyShapeIteration);
fprintf(stderr,"ShapeIterationTolerance : %.6e\n",gi.ShapeIterationTolerance);
fprintf(stderr,"\n");
}
/*
** Global binning grid parameters
*/
fprintf(stderr,"Global binning grid parameters:\n\n");
for (d = 0; d < gi.NDimProfile; d++) {
fprintf(stderr,"Dimension %ld:\n",d+1);
switch(LengthType_rmin[d]) {
case 0: strcpy(cdummy,"comoving"); break;
case 1: strcpy(cdummy,"physical"); break;
default: strcpy(cdummy,"not supported"); }
fprintf(stderr,"Length type rmin : %s\n",cdummy);
switch(LengthType_rmax[d]) {
case 0: strcpy(cdummy,"comoving"); break;
case 1: strcpy(cdummy,"physical"); break;
default: strcpy(cdummy,"not supported"); }
fprintf(stderr,"Length type rmax : %s\n",cdummy);
if (gi.rmin[d] >= 0) {
fprintf(stderr,"rmin : %.6e LU (comoving) = %.6e kpc (comoving) = %.6e kpc (physical)\n",
gi.rmin[d],gi.rmin[d]/cosmo2internal_ct.L_usf,gi.ascale*gi.rmin[d]/cosmo2internal_ct.L_usf);
}
else fprintf(stderr,"rmin : not set\n");
if (gi.rmax[d] >= 0) {
fprintf(stderr,"rmax : %.6e LU (comoving) = %.6e kpc (comoving) = %.6e kpc (physical)\n",
gi.rmax[d],gi.rmax[d]/cosmo2internal_ct.L_usf,gi.ascale*gi.rmax[d]/cosmo2internal_ct.L_usf);
}
else fprintf(stderr,"rmax : not set\n");
if (gi.NBin[d] > 0) fprintf(stderr,"NBin : %d\n",gi.NBin[d]);
else fprintf(stderr,"NBin : not set\n");
if (gi.NBinPerDex[d] > 0) fprintf(stderr,"NBinPerDex : %g\n",gi.NBinPerDex[d]);
else fprintf(stderr,"NBinPerDex : not set\n");
switch(gi.BinningGridType[d]) {
case 0: strcpy(cdummy,"logarithmic"); break;
case 1: strcpy(cdummy,"linear"); break;
default: strcpy(cdummy,"not supported"); }
fprintf(stderr,"Binning grid type : %s\n",cdummy);
fprintf(stderr,"\n");
}
}
gettimeofday(&time,NULL);
timeend = time.tv_sec;
timediff = timeend-timestart;
fprintf(stderr,"Done with profiling. It took %d s = %d h %d m %d s in total.\n",timediff,timediff/3600,(timediff/60)%60,timediff%60);
exit(0);
}
void usage(void) {
fprintf(stderr,"\n");
fprintf(stderr,"profile (%s)\n",VERSION);
fprintf(stderr,"\n");
fprintf(stderr,"Program calculates the profiles and characteristics of haloes.\n");
fprintf(stderr,"\n");
fprintf(stderr,"You can specify the following arguments:\n");
fprintf(stderr,"\n");
fprintf(stderr,"-spp : set this flag if Tipsy XDR input files have single precision positions (default)\n");
fprintf(stderr,"-dpp : set this flag if Tipsy XDR input files have double precision positions\n");
fprintf(stderr,"-pfm <value> : set this flag for ART native binary particle file mode: 0 everything double precision; 1 positions and velocities double precision, times single precision; 2 everything single precision (default: 0)\n");
fprintf(stderr,"-ProfilingMode <value> : 0 = NDimProfile-dimensional profiles / 1 = shape determination (default: 0)\n");
fprintf(stderr,"-NDimProfile <value> : number of dimensions for profiling (default: 1)\n");
fprintf(stderr,"-DataProcessingMode <value> : 0 = read data again in every loop / 1 = store data in memory (default: 0)\n");
fprintf(stderr,"-DataFormat <value> : 0 = Tipsy / 1 = ART (default: 0)\n");
fprintf(stderr,"-HaloCatalogueFormat <value> : 0 = generic / 1 = 6DFOF / 2 = characteristics (default: 0)\n");
fprintf(stderr,"-HaloCatalogueNDim <value> : dimension of halo catalouge (default: 1)\n");
fprintf(stderr,"-ShapeDeterminationVolume <value> : 0 = differential volume / 1 enclosed volume (default: 0)\n");
fprintf(stderr,"-ShapeTensorForm <value> : 0 = S_ij / 1 = S_ij/r^2 / 2 = S_ij/r_ell^2 (default: 0)\n");
fprintf(stderr,"-DoMetalSpecies : set this flag for doing metal species\n");
fprintf(stderr,"-DoChemicalSpecies : set this flag for doing chemical species\n");
fprintf(stderr,"-DoGasTemperature : set this flag for doing gas temperature\n");
fprintf(stderr,"-DoStellarAge : set this flag for doing stellar age\n");
fprintf(stderr,"-MoreCharacteristicsOutput : set this flag for more characteristics output\n");
fprintf(stderr,"-RecentreUseGas <value> : 0 = no / 1 = yes (default: 0)\n");
fprintf(stderr,"-RecentreUseDark <value> : 0 = no / 1 = yes (default: 1)\n");
fprintf(stderr,"-RecentreUseStar <value> : 0 = no / 1 = yes (default: 1)\n");
fprintf(stderr,"-HaloSize <value> : 0 = rmean / 1 = rcrit / 2 = rfix (default: 0)\n");
fprintf(stderr,"-ExcludeParticles <value> : 0 = don't exclude any particles / 1 = exclude particles in specified halo catalogue (default: 0)\n");
fprintf(stderr,"-LengthType_rmin <d> <value> : d = dimension (1/2/3) / 0 = comoving / 1 = physical (default: 0)\n");
fprintf(stderr,"-LengthType_rmax <d> <value> : d = dimension (1/2/3) / 0 = comoving / 1 = physical (default: 0)\n");
fprintf(stderr,"-LengthType_zHeight <value> : 0 = comoving / 1 = physical (default: 0)\n");
fprintf(stderr,"-LengthType_rExclude <value> : 0 = comoving / 1 = physical (default: 0)\n");
fprintf(stderr,"-LengthType_rRecentre <value> : 0 = comoving / 1 = physical (default: 0)\n");
fprintf(stderr,"-rmin <d> <value> : d = dimension (1/2/3) / global minimum grid radius for dimension d [LU] - overwrites values form halo catalogue (default: not set)\n");
fprintf(stderr,"-rmax <d> <value> : d = dimension (1/2/3) / global maximum grid radius for dimension d [LU] - overwrites values form halo catalogue (default: not set)\n");
fprintf(stderr,"-NBin <d> <value> : d = dimension (1/2/3) / global number of bins between rmin and rmax for dimension d - overwrites values form halo catalogue (default: not set)\n");
fprintf(stderr,"-NBinPerDex <d> <value> : d = dimension (1/2/3) / global number of bins per decade between rmin and rmax for dimension d (can be a float) (default: not set)\n");
fprintf(stderr,"-BinningGridType <d> <value> : d = dimension (1/2/3) / global binning grid type: 0 = logarithmic / 1 = linear (default: 0)\n");
fprintf(stderr,"-BinningCoordinateType <value> : 0 = spherical coordinates / 1 = cylindrical coordinates (default: 0)\n");
fprintf(stderr,"-VelocityProjectionType <value> : 0 = coordinate axes / 1 = spherical coordinates / 2 = cylindrical coordinates (default: 0)\n");
fprintf(stderr,"-zAxis_x : x-component of global z-axis for cylindrical coordinates [LU] - overwrites values form z-axis catalogue (default: not set)\n");
fprintf(stderr,"-zAxis_y : y-component of global z-axis for cylindrical coordinates [LU] - overwrites values form z-axis catalogue (default: not set)\n");
fprintf(stderr,"-zAxis_z : z-component of global z-axis for cylindrical coordinates [LU] - overwrites values form z-axis catalogue (default: not set)\n");
fprintf(stderr,"-zHeight : height above mid-plane for inclusion for cylindrical binning [LU] - overwrites values form z-axis catalogue (default: not set)\n");
fprintf(stderr,"-CentreType <value> : 0 = centre-of-mass centres / 1 = potmin or denmax centres (only for 6DFOF halocatalogue) (default: 0)\n");
fprintf(stderr,"-BinFactor <value> : extra factor for rmax determined form 6DFOF file (default: 5) (only for 6DFOF halocatalogue)\n");
fprintf(stderr,"-rmaxFromHaloCatalogue : set this flag for rmax determined from 6DFOF file (only for 6DFOF halocatalogue)\n");
fprintf(stderr,"-OmegaM0 <value> : OmegaM0 value (default: 0) (only necessary for Tipsy format)\n");
fprintf(stderr,"-OmegaL0 <value> : OmegaL0 value (default: 0) (only necessary for Tipsy format)\n");
fprintf(stderr,"-OmegaK0 <value> : OmegaK0 value (default: 0) (only necessary for Tipsy format)\n");
fprintf(stderr,"-OmegaR0 <value> : OmegaR0 value (default: 0) (only necessary for Tipsy format)\n");
fprintf(stderr,"-h0_100 <value> : h0_100 value (default: 0) (only necessary for Tipsy format)\n");
fprintf(stderr,"-LBox <value> : box length (comoving) [kpc]\n");
fprintf(stderr,"-LBox_internal <value> : box length (comoving) [LU] (default: standard value depending on file format)\n");
fprintf(stderr,"-Hubble0_internal <value> : Hubble parameter today [TU^{-1}] (default: standard value depending on file format)\n");
fprintf(stderr,"-rhocrit0_internal <value> : critical density today [MU LU^{-3}] (default: standard value depending on file format)\n");
fprintf(stderr,"-Delta_mean <value> : overdensity with respect to current background density (default: 200)\n");
fprintf(stderr,"-Delta_crit <value> : overdensity with respect to current critical density (default: 200)\n");
fprintf(stderr,"-Delta_fix <value> : overdensity with respect to background density at afix (default: 200)\n");
fprintf(stderr,"-afix <value> : scale factor for fixed overdensity (default: 1)\n");
fprintf(stderr,"-ascale <value> : scale factor of the data (default: set from data, needed for non-cosmological simulations)\n");
fprintf(stderr,"-LmaxGasAnalysis <value> : maximum level of gas analysed [counting from 0] (default: Lmaxgas in data)\n");
fprintf(stderr,"-NParticlePerBockGas <value> : number of gas particles per block (default: 1e7)\n");
fprintf(stderr,"-NParticlePerBlockDark <value> : number of dark matter particles per block (default: 1e7)\n");
fprintf(stderr,"-NParticlePerBlockStar <value> : number of star particles per block (default: 1e7)\n");
fprintf(stderr,"-NCellData <value> : number of cells per dimension in linked cell method for data loops (default: 20)\n");
fprintf(stderr,"-NCellHalo <value> : number of cells per dimension in linked cell method for halo loops (default: 10)\n");
fprintf(stderr,"-NLoopRecentre <value> : number of loops for recentering (default: 0)\n");
fprintf(stderr,"-rRecentre <value> : radius for recentering [LU] (default: 0 LU)\n");
fprintf(stderr,"-fRecentreDist <value> : factor for subsequential decrease of region in recentering loops (default: 1.5)\n");
fprintf(stderr,"-rExclude <value> : radius for exclusion [LU] (default: 0 LU)\n");
fprintf(stderr,"-NLoopShapeIterationMax <value> : number of maximum loops for shape iteration (default: 50)\n");
fprintf(stderr,"-GRAVITY <value> : 0 = flag not set / 1 = flag set (default: 1) [only necessary for ART format] \n");
fprintf(stderr,"-HYDRO <value> : 0 = flag not set / 1 = flag set (default: 1) [only necessary for ART format]\n");
fprintf(stderr,"-ADVECT_SPECIES <value> : 0 = flag not set / 1 = flag set (default: 1) [only necessary for ART format]\n");
fprintf(stderr,"-STARFORM <value> : 0 = flag not set / 1 = flag set (default: 1) [only necessary for ART format]\n");
fprintf(stderr,"-ENRICH <value> : 0 = flag not set / 1 = flag set (default: 1) [only necessary for ART format]\n");
fprintf(stderr,"-ENRICH_SNIa <value> : 0 = flag not set / 1 = flag set (default: 1) [only necessary for ART format]\n");
fprintf(stderr,"-RADIATIVE_TRANSFER <value> : 0 = flag not set / 1 = flag set (default: 1) [only necessary for ART format]\n");
fprintf(stderr,"-ELECTRON_ION_NONEQUILIBRIUM <value> : 0 = flag not set / 1 = flag set (default: 0) [only necessary for ART format]\n");
fprintf(stderr,"-verbose : verbose\n");
fprintf(stderr,"< <name> : name of input file in Tipsy XDR format\n");
fprintf(stderr,"-ARTHeader <name> : header file in ART native binary format\n");
fprintf(stderr,"-ARTCoordinatesData <name> : coordinates data file in ART native binary format\n");
fprintf(stderr,"-ARTStarProperties <name> : star properties file in ART native binary format\n");
fprintf(stderr,"-ARTGas <name> : gas file in ART native binary format\n");
fprintf(stderr,"-HaloCatalogue <name> : halo catalouge file\n");
fprintf(stderr,"-ExcludeHaloCatalogue <name> : halo catalouge file (only characteristics format supported)\n");
fprintf(stderr,"-zAxisCatalogue <name> : z-axis catalouge file\n");
fprintf(stderr,"-Output <name> : name of output files (endings like .characteristics etc. appended automatically)\n");
fprintf(stderr,"\n");
exit(1);
}
void set_default_values_general_info(GI *gi) {
int d, i;
/*
** Cosmological parameters
*/
gi->cp.OmegaM0 = 0;
gi->cp.OmegaD0 = 0;
gi->cp.OmegaB0 = 0;
gi->cp.OmegaL0 = 0;
gi->cp.OmegaK0 = 0;
gi->cp.OmegaR0 = 0;
gi->cp.h0_100 = 0;
gi->us.LBox = 0;
gi->us.Hubble0 = 0;
gi->us.rhocrit0 = 0;
gi->cosmous.LBox = 0;
gi->cosmous.Hubble0 = 0;
gi->cosmous.rhocrit0 = 0;
/*
** General parameters
*/
gi->DataFormat = 0; /* Tipsy */
gi->HaloCatalogueFormat = 0; /* generic */
gi->HaloCatalogueNDim = 1; /* 1-dimensional profiles */
gi->HaloCatalogueBinningCoordinateType = 0; /* spherical */
gi->ExcludeHaloCatalogueFormat = 2; /* characteristics */
gi->ExcludeHaloCatalogueNDim = 1; /* 1-dimensional profiles */
gi->ProfilingMode = 0; /* normal profile */
gi->DataProcessingMode = 0; /* looping */
gi->ShapeDeterminationVolume = 0; /* differential volume */
gi->ShapeTensorForm = 0; /* no weights */
gi->DoMetalSpecies = 0; /* no metal species */
gi->DoChemicalSpecies = 0; /* no chemical species */
gi->DoGasTemperature = 0; /* no gas temperature */
gi->DoStellarAge = 0; /* no stellar age */
gi->MoreCharacteristicsOutput = 0; /* not more characteristics output */
gi->HaloSize = 0; /* rmean */
gi->ExcludeParticles = 0; /* no particles excluded */
gi->zAxisCatalogueSpecified = 0; /* no z-axis catalogue sepcified */
gi->CentreType = 0;
gi->VelocityProjectionType = 0;
gi->rmaxFromHaloCatalogue = 0;
gi->NDimProfile = 1;
gi->NSpeciesRead = 3;
gi->NSpeciesProfile = 5;
gi->NHalo = 0;
gi->NHaloExcludeGlobal = 0;
/*
** Binning structure
*/
gi->BinningCoordinateType = 0; /* spherical */
for (d = 0; d < 3; d++) {
gi->rmin[d] = -1;
gi->rmax[d] = -1;
gi->NBin[d] = 0;
gi->NBinPerDex[d] = 0;
gi->BinningGridType[d] = 0; /* logarithmic */
}
gi->zAxis[0] = 0;
gi->zAxis[1] = 0;
gi->zAxis[2] = 0;
gi->zHeight = 0;
gi->SizeStorageIncrement = 1e7;
for (d = 0; d < NSPECIESREADMAX; d++) {
gi->NParticlePerBlock[d] = 1e7;
gi->NParticleInBlock[d] = 0;
gi->SizeStorage[d] = 0;
gi->NParticleInStorage[d] = 0;
gi->NSubSpecies[d] = 1;
gi->NProperties[d] = 0;
for (i = 0; i < NSUBSPECIESMAX+NPROPERTIESMAX; i++) {
gi->pi[d][i] = 0;
}
}
for (d = 0; d < NSPECIESPROFILEMAX; d++) {
for (i = 0; i < NPROPERTIESMAX; i++) {
gi->bi[d][i] = 0;
}
}
gi->RecentreUse[GAS] = 0;
gi->RecentreUse[DARK] = 1;
gi->RecentreUse[STAR] = 1;
gi->NCellData = 20;
gi->NCellHalo = 10;
gi->NLoopShapeIterationMax = 50;
gi->NLoopProcessData = 1;
gi->OutputFrequencyShapeIteration = 10;
gi->ascale = 0;
gi->rhomean = 0;
gi->rhocrit = 0;
gi->Deltamean = 200;
gi->Deltacrit = 200;
gi->Deltafix = 200;
gi->afix = 1;
gi->BinFactor = 5;
gi->rExclude = 0;
gi->rRecentre = 0;
gi->fRecentreDist = 1.5;
gi->NLoopRecentre = 0;
gi->fcheckrvcmax = 2.0;
gi->slopertruncindicator = -0.5;
gi->frhobg = 1.2;
gi->ShapeIterationTolerance = 1e-5;
gi->fhaloduplicate = 0;
gi->fhaloexcludesize = 0.5;
gi->fhaloexcludedistance = 0.5;
/* gi->fincludeshapeproperty = 1.1; */
/* gi->fincludeshaperadius = 2; */
strcpy(gi->MatterTypeName[TOT],"tot");
strcpy(gi->MatterTypeName[GAS],"gas");
strcpy(gi->MatterTypeName[DARK],"dark");
strcpy(gi->MatterTypeName[STAR],"star");
strcpy(gi->MatterTypeName[BARYON],"baryon");
strcpy(gi->MatterTypeName[GAS_METAL_SNII],"gas_metal_SNII");
strcpy(gi->MatterTypeName[GAS_METAL_SNIa],"gas_metal_SNIa");
strcpy(gi->MatterTypeName[STAR_METAL_SNII],"star_metal_SNII");
strcpy(gi->MatterTypeName[STAR_METAL_SNIa],"star_metal_SNIa");
strcpy(gi->MatterTypeName[BARYON_METAL_SNII],"baryon_metal_SNII");
strcpy(gi->MatterTypeName[BARYON_METAL_SNIa],"baryon_metal_SNIa");
strcpy(gi->MatterTypeName[GAS_HI],"gas_HI");
strcpy(gi->MatterTypeName[GAS_HII],"gas_HII");
strcpy(gi->MatterTypeName[GAS_HeI],"gas_HeI");
strcpy(gi->MatterTypeName[GAS_HeII],"gas_HeII");
strcpy(gi->MatterTypeName[GAS_HeIII],"gas_HeIII");
strcpy(gi->MatterTypeName[GAS_H2],"gas_H2");
}
void calculate_densities(GI *gi) {
double E, OmegaM;
E = Ecosmo(gi->ascale,gi->cp);
OmegaM = gi->cp.OmegaM0/(pow(gi->ascale,3)*E*E);
assert(gi->Deltamean > 0);
assert(gi->Deltacrit > 0);
assert(gi->Deltafix > 0);
/*
** The following densities are all comoving densities at ascale
*/
gi->rhocrit = gi->us.rhocrit0*E*E*pow(gi->ascale,3);
gi->rhomean = OmegaM*gi->rhocrit;
gi->rhoencmean = gi->Deltamean*gi->rhomean;
gi->rhoenccrit = gi->Deltacrit*gi->rhocrit;
/*
** Calculate fixed density at afix
*/
E = Ecosmo(gi->afix,gi->cp);
OmegaM = gi->cp.OmegaM0/(pow(gi->afix,3)*E*E);
gi->rhoencfix = gi->Deltafix*OmegaM*gi->us.rhocrit0*E*E; /* physical density */
gi->rhoencfix *= pow(gi->ascale,3); /* comoving density at ascale */
}
void read_halocatalogue_ascii(GI *gi, HALO_DATA **hdin) {
int SizeHaloDataIncrement = 1000;
int SizeHaloData = SizeHaloDataIncrement;
int d, n[3], i, j, idummy, ID, IDz, NBin[3], NHaloRead;
double ddummy;
double r[3], v[3], rcom[3], rpotorden[3], zAxis[3], zHeight;
double rmin[3], rmax[3];
double mass, radius;
char cdummy[1000];
HALO_DATA *hd;
FILE *HaloCatalogueFile = NULL, *zAxisCatalogueFile = NULL;
HaloCatalogueFile = fopen(gi->HaloCatalogueFileName,"r");
assert(HaloCatalogueFile != NULL);
if (gi->zAxisCatalogueSpecified) {
zAxisCatalogueFile = fopen(gi->zAxisCatalogueFileName,"r");
assert(zAxisCatalogueFile != NULL);
fgets(cdummy,1000,zAxisCatalogueFile);
}
hd = *hdin;
hd = realloc(hd,SizeHaloData*sizeof(HALO_DATA));
assert(hd != NULL);
/*
** Read header line if present, then read all halos
*/
if (gi->HaloCatalogueFormat == 0 || gi->HaloCatalogueFormat == 2) fgets(cdummy,1000,HaloCatalogueFile);
NHaloRead = 0;
while (1) {
/*
** Set some default values
*/
for (d = 0; d < 3; d++) {
rmin[d] = 0;
rmax[d] = 0;
NBin[d] = 1; /* at least one bin */
zAxis[d] = 0;
}
zHeight = 0;
/*
** Read halo catalogues
*/
if (gi->HaloCatalogueFormat == 0) {
/*
** Generic format
*/
fscanf(HaloCatalogueFile,"%i",&idummy); ID = idummy;
fscanf(HaloCatalogueFile,"%lg",&ddummy); r[0] = put_in_box(ddummy,gi->bc[0],gi->bc[3]);
fscanf(HaloCatalogueFile,"%lg",&ddummy); r[1] = put_in_box(ddummy,gi->bc[1],gi->bc[4]);
fscanf(HaloCatalogueFile,"%lg",&ddummy); r[2] = put_in_box(ddummy,gi->bc[2],gi->bc[5]);
fscanf(HaloCatalogueFile,"%lg",&ddummy); v[0] = ddummy;
fscanf(HaloCatalogueFile,"%lg",&ddummy); v[1] = ddummy;
fscanf(HaloCatalogueFile,"%lg",&ddummy); v[2] = ddummy;
for (d = 0; d < gi->HaloCatalogueNDim; d++) {
fscanf(HaloCatalogueFile,"%lg",&ddummy); rmin[d] = ddummy;
fscanf(HaloCatalogueFile,"%lg",&ddummy); rmax[d] = ddummy;
fscanf(HaloCatalogueFile,"%i",&idummy); NBin[d] = (idummy > 0)?idummy:NBin[d]; /* NBin between rmin and rmax => no correction for logarithmic bins */
}
if (gi->HaloCatalogueBinningCoordinateType == 1) {
fscanf(HaloCatalogueFile,"%lg",&ddummy); zAxis[0] = ddummy;
fscanf(HaloCatalogueFile,"%lg",&ddummy); zAxis[1] = ddummy;
fscanf(HaloCatalogueFile,"%lg",&ddummy); zAxis[2] = ddummy;
fscanf(HaloCatalogueFile,"%lg",&ddummy); zHeight = ddummy;
}
if (feof(HaloCatalogueFile)) break;
}
else if (gi->HaloCatalogueFormat == 1) {
/*
** 6DFOF format
*/
fscanf(HaloCatalogueFile,"%i",&idummy); ID = idummy;
fscanf(HaloCatalogueFile,"%i",&idummy); /* N = idummy; */
fscanf(HaloCatalogueFile,"%lg",&ddummy); mass = ddummy;
fscanf(HaloCatalogueFile,"%lg",&ddummy); radius = ddummy; /* dispersion in coordinates */
fscanf(HaloCatalogueFile,"%lg",&ddummy); rcom[0] = put_in_box(ddummy,gi->bc[0],gi->bc[3]);
fscanf(HaloCatalogueFile,"%lg",&ddummy); rcom[1] = put_in_box(ddummy,gi->bc[1],gi->bc[4]);
fscanf(HaloCatalogueFile,"%lg",&ddummy); rcom[2] = put_in_box(ddummy,gi->bc[2],gi->bc[5]);
fscanf(HaloCatalogueFile,"%lg",&ddummy); rpotorden[0] = put_in_box(ddummy,gi->bc[0],gi->bc[3]);
fscanf(HaloCatalogueFile,"%lg",&ddummy); rpotorden[1] = put_in_box(ddummy,gi->bc[1],gi->bc[4]);
fscanf(HaloCatalogueFile,"%lg",&ddummy); rpotorden[2] = put_in_box(ddummy,gi->bc[2],gi->bc[5]);
fscanf(HaloCatalogueFile,"%lg",&ddummy); v[0] = ddummy;
fscanf(HaloCatalogueFile,"%lg",&ddummy); v[1] = ddummy;
fscanf(HaloCatalogueFile,"%lg",&ddummy); v[2] = ddummy;
if (feof(HaloCatalogueFile)) break;
if (gi->CentreType == 0) {
for (d = 0; d < 3; d++) r[d] = rcom[d];
}
else if (gi->CentreType == 1) {
for (d = 0; d < 3; d++) r[d] = rpotorden[d];
}
else {
fprintf(stderr,"Not supported center type!\n");
exit(1);
}
rmin[0] = 0;
if (gi->rmaxFromHaloCatalogue == 1) {
/*
** Estimate maximum radius; assume isothermal sphere scaling
*/
rmax[0] = sqrt((3.0*mass/(4.0*M_PI*radius*radius*radius))/gi->rhoencmean)*radius*gi->BinFactor;
assert(rmax[0] > 0);
}
else {
rmax[0] = 0;
}
}
else if (gi->HaloCatalogueFormat == 2) {
/*
** Characteristics format
*/
fscanf(HaloCatalogueFile,"%i",&idummy); ID = idummy;
fscanf(HaloCatalogueFile,"%lg",&ddummy); r[0] = put_in_box(ddummy,gi->bc[0],gi->bc[3]);
fscanf(HaloCatalogueFile,"%lg",&ddummy); r[1] = put_in_box(ddummy,gi->bc[1],gi->bc[4]);
fscanf(HaloCatalogueFile,"%lg",&ddummy); r[2] = put_in_box(ddummy,gi->bc[2],gi->bc[5]);
fscanf(HaloCatalogueFile,"%lg",&ddummy); v[0] = ddummy;
fscanf(HaloCatalogueFile,"%lg",&ddummy); v[1] = ddummy;
fscanf(HaloCatalogueFile,"%lg",&ddummy); v[2] = ddummy;
for (d = 0; d < gi->HaloCatalogueNDim; d++) {
fscanf(HaloCatalogueFile,"%lg",&ddummy); rmin[d] = ddummy;
fscanf(HaloCatalogueFile,"%lg",&ddummy); rmax[d] = ddummy;
fscanf(HaloCatalogueFile,"%i",&idummy); NBin[d] = (idummy > 0)?idummy:NBin[d];
if (gi->BinningGridType[d] == 0) {
/*
** Correct for logarithmic binning: innermost bin is already counted here.
** HaloCatalogue needs to have same binning type as the profiling done now.
** No way to check this at the moment.
*/
NBin[d] -= 1;
}
}
if (gi->HaloCatalogueBinningCoordinateType == 0) {
fgets(cdummy,1000,HaloCatalogueFile);
}
else if (gi->HaloCatalogueBinningCoordinateType == 1) {
fscanf(HaloCatalogueFile,"%lg",&ddummy); zAxis[0] = ddummy;
fscanf(HaloCatalogueFile,"%lg",&ddummy); zAxis[1] = ddummy;
fscanf(HaloCatalogueFile,"%lg",&ddummy); zAxis[2] = ddummy;
fscanf(HaloCatalogueFile,"%lg",&ddummy); zHeight = ddummy;
}
if (feof(HaloCatalogueFile)) break;
}
else {
fprintf(stderr,"Not supported halo catalogue format!\n");
exit(1);
}
if (gi->BinningCoordinateType == 1) {
/*
** Use z-axis catalogue values if specified
*/
if (gi->zAxisCatalogueSpecified) {
fscanf(zAxisCatalogueFile,"%i",&idummy); IDz = idummy;
fscanf(zAxisCatalogueFile,"%lg",&ddummy); zAxis[0] = ddummy;
fscanf(zAxisCatalogueFile,"%lg",&ddummy); zAxis[1] = ddummy;
fscanf(zAxisCatalogueFile,"%lg",&ddummy); zAxis[2] = ddummy;
fscanf(zAxisCatalogueFile,"%lg",&ddummy); zHeight = ddummy;
assert(ID == IDz);
}
/*
** Use global values if specified
*/
if (gi->zAxis[0] != 0 || gi->zAxis[1] != 0 || gi->zAxis[2] != 0) {
for (d = 0; d < 3; d++) zAxis[d] = gi->zAxis[d];
}
if (gi->zHeight > 0) zHeight = gi->zHeight;
}
NHaloRead++;
if (SizeHaloData < NHaloRead){
SizeHaloData += SizeHaloDataIncrement;
hd = realloc(hd,SizeHaloData*sizeof(HALO_DATA));
assert(hd != NULL);
}
i = NHaloRead-1;
/*
** Basic halo properties
*/
hd[i].ID = ID;
for (d = 0; d < 3; d++) {
hd[i].rcentre[d] = r[d];
hd[i].vcentre[d] = v[d];
}
/*
** Set-up bin structure
*/
if (gi->BinningCoordinateType == 1) {
ddummy = 1.0/sqrt(pow(zAxis[0],2)+pow(zAxis[1],2)+pow(zAxis[2],2));
assert(ddummy > 0 && !isnan(ddummy) && !isinf(ddummy));
for (d = 0; d < 3; d++) hd[i].zAxis[d] = zAxis[d]*ddummy;
if (zHeight > 0) rmax[1] = zHeight;
}
for (d = 0; d < 3; d++) {
hd[i].rmin[d] = (gi->rmin[d] >= 0)?gi->rmin[d]:rmin[d];
hd[i].rmax[d] = (gi->rmax[d] >= 0)?gi->rmax[d]:rmax[d];
hd[i].NBin[d] = (gi->NBin[d] > 0)?gi->NBin[d]:NBin[d];
assert(hd[i].rmax[d] >= hd[i].rmin[d]);
assert(hd[i].NBin[d] > 0);
if (gi->BinningGridType[d] == 0 && d < gi->NDimProfile) {
/*
** Logarithmic bins
*/
assert(hd[i].rmin[d] > 0);
assert(hd[i].rmax[d] > 0);
assert(hd[i].rmax[d] > hd[i].rmin[d]);
hd[i].NBin[d] += 1; /* account for inner bin from 0-rmin */
if (gi->NBinPerDex[d] > 0) {
/*
** Calculate NBin and rmax
*/
hd[i].NBin[d] = (int)((log10(hd[i].rmax[d])-log10(hd[i].rmin[d]))*gi->NBinPerDex[d]) + 1;
hd[i].rmax[d] = hd[i].rmin[d]*pow(10,hd[i].NBin[d]/gi->NBinPerDex[d]);
hd[i].NBin[d] += 1; /* account for inner bin from 0-rmin */
}
}
if (gi->NDimProfile == 2 && gi->BinningCoordinateType == 1 && d == 1) {
/*
** 2-dimensional binning in cylindrical coordinates
*/
hd[i].NBin[d] *= 2;
}
}
if (gi->BinningCoordinateType == 1) hd[i].zHeight = hd[i].rmax[1];
/*
** Allocate bins
*/
hd[i].pbs = malloc(hd[i].NBin[0]*sizeof(PROFILE_BIN_STRUCTURE**));
assert(hd[i].pbs != NULL);
for (n[0] = 0; n[0] < hd[i].NBin[0]; n[0]++) {
hd[i].pbs[n[0]] = malloc(hd[i].NBin[1]*sizeof(PROFILE_BIN_STRUCTURE*));
assert(hd[i].pbs[n[0]] != NULL);
for (n[1] = 0; n[1] < hd[i].NBin[1]; n[1]++) {
hd[i].pbs[n[0]][n[1]] = malloc(hd[i].NBin[2]*sizeof(PROFILE_BIN_STRUCTURE));
assert(hd[i].pbs[n[0]][n[1]] != NULL);
for (n[2] = 0; n[2] < hd[i].NBin[2]; n[2]++) {
if (gi->ProfilingMode == 0) {
hd[i].pbs[n[0]][n[1]][n[2]].bin = malloc(gi->NSpeciesProfile*sizeof(PROFILE_BIN_PROPERTIES));
assert(hd[i].pbs[n[0]][n[1]][n[2]].bin != NULL);
hd[i].pbs[n[0]][n[1]][n[2]].shape = NULL;
for (j = 0; j < gi->NSpeciesProfile; j++) {
if (j < gi->NSpeciesRead && gi->NProperties[j] > 0) {
hd[i].pbs[n[0]][n[1]][n[2]].bin[j].P = malloc(gi->NProperties[j]*sizeof(double));
assert(hd[i].pbs[n[0]][n[1]][n[2]].bin[j].P != NULL);
}
else {
hd[i].pbs[n[0]][n[1]][n[2]].bin[j].P = NULL;
}
}
}
else if (gi->ProfilingMode == 1) {
hd[i].pbs[n[0]][n[1]][n[2]].shape = malloc(gi->NSpeciesProfile*sizeof(PROFILE_SHAPE_PROPERTIES));
assert(hd[i].pbs[n[0]][n[1]][n[2]].shape != NULL);
hd[i].pbs[n[0]][n[1]][n[2]].bin = NULL;
}
}
}
}
/*
** Initialise halo profile
*/
initialise_halo_profile(gi,&hd[i]);
}
fclose(HaloCatalogueFile);
if (gi->zAxisCatalogueSpecified) fclose(zAxisCatalogueFile);
*hdin = hd;
gi->NHalo = NHaloRead;
}
int read_halocatalogue_ascii_excludehalo(GI *gi, HALO_DATA *hd, HALO_DATA_EXCLUDE **hdegin) {
int SizeHaloDataIncrement = 1000;
int SizeHaloData = SizeHaloDataIncrement;
int d, i, j, k, l, idummy, ID, NHaloRead, NIndexArray;
int MoveToGlobalList, ContainedInHaloDataList, Ntot, Ncheck;
int *IndexArray = NULL;
double ddummy;
double r[3], rcheck[3];
double dsph;
double sizeorig, size;
double *SizeArray = NULL;
char cdummy[1000];
HALO_DATA_EXCLUDE *hdeg;
FILE *HaloCatalogueFile = NULL;
HaloCatalogueFile = fopen(gi->ExcludeHaloCatalogueFileName,"r");
assert(HaloCatalogueFile != NULL);
for (j = 0; j < gi->NHalo; j++) {
hd[j].SizeExcludeHaloData = SizeHaloDataIncrement;
hd[j].hde = realloc(hd[j].hde,hd[j].SizeExcludeHaloData*sizeof(HALO_DATA_EXCLUDE));
assert(hd[j].hde != NULL);
}
hdeg = *hdegin;
hdeg = realloc(hdeg,SizeHaloData*sizeof(HALO_DATA_EXCLUDE));
assert(hdeg != NULL);
IndexArray = malloc(gi->NHalo*sizeof(int));
assert(IndexArray != NULL);
SizeArray = malloc(gi->NHalo*sizeof(double));
assert(SizeArray != NULL);
/*
** Read header line if present, then read all halos
*/
if (gi->ExcludeHaloCatalogueFormat == 2) fgets(cdummy,1000,HaloCatalogueFile);
NHaloRead = 0;
while (1) {
if (gi->ExcludeHaloCatalogueFormat == 2) {
fscanf(HaloCatalogueFile,"%i",&idummy); ID = idummy;
fscanf(HaloCatalogueFile,"%lg",&ddummy); r[0] = put_in_box(ddummy,gi->bc[0],gi->bc[3]);
fscanf(HaloCatalogueFile,"%lg",&ddummy); r[1] = put_in_box(ddummy,gi->bc[1],gi->bc[4]);
fscanf(HaloCatalogueFile,"%lg",&ddummy); r[2] = put_in_box(ddummy,gi->bc[2],gi->bc[5]);
fscanf(HaloCatalogueFile,"%lg",&ddummy); /* v[0] = ddummy; */
fscanf(HaloCatalogueFile,"%lg",&ddummy); /* v[1] = ddummy; */
fscanf(HaloCatalogueFile,"%lg",&ddummy); /* v[2] = ddummy; */
for (d = 0; d < gi->ExcludeHaloCatalogueNDim; d++) {
fscanf(HaloCatalogueFile,"%lg",&ddummy); /* rmin[d] = ddummy; */
fscanf(HaloCatalogueFile,"%lg",&ddummy); /* rmax[d] = ddummy; */
fscanf(HaloCatalogueFile,"%i",&idummy); /* NBin[d] = idummy; */
}
fscanf(HaloCatalogueFile,"%lg",&ddummy); sizeorig = ddummy;
fgets(cdummy,1000,HaloCatalogueFile);
if (feof(HaloCatalogueFile)) break;
sizeorig *= gi->fhaloexcludesize;
}
else {
fprintf(stderr,"Not supported halo catalogue format!\n");
exit(1);
}
NHaloRead++;
/*
** Now determine if it is a excluded halo
*/
ContainedInHaloDataList = 0;
NIndexArray = 0;
for (i = 0; i < gi->NHalo; i++) {
if (hd[i].ID == ID) {
ContainedInHaloDataList = 1;
continue; /* Don't exclude yourself */
}
for (d = 0; d < 3; d++) {
rcheck[d] = correct_position(hd[i].rcentre[d],r[d],gi->us.LBox);
rcheck[d] = rcheck[d]-hd[i].rcentre[d];
}
dsph = sqrt(rcheck[0]*rcheck[0]+rcheck[1]*rcheck[1]+rcheck[2]*rcheck[2]);
/*
** Check if spheres overlap, i.e. some particles need to be excluded
*/
if (dsph <= hd[i].rmax[0]+sizeorig) {
/*
** Check if halo centre is contained
** => if yes take fraction fhaloexcludedistance of the distance as size
*/
if (sizeorig > dsph) size = gi->fhaloexcludedistance*dsph;
else size = sizeorig;
if (size > 0) {
hd[i].NHaloExclude++;
NIndexArray++;
IndexArray[NIndexArray-1] = i;
SizeArray[NIndexArray-1] = size;
if (hd[i].SizeExcludeHaloData < hd[i].NHaloExclude) {
hd[i].SizeExcludeHaloData += SizeHaloDataIncrement;
hd[i].hde = realloc(hd[i].hde,hd[i].SizeExcludeHaloData*sizeof(HALO_DATA_EXCLUDE));
assert(hd[i].hde != NULL);
}
j = hd[i].NHaloExclude-1;
hd[i].hde[j].ID = ID;
for (d = 0; d < 3; d++) hd[i].hde[j].rcentre[d] = r[d];
hd[i].hde[j].size = size;
}
}
}
/*
** In the case of DataProcessingMode == 0 we're done now.
** But if we use DataProcessingMode == 1 we can move the haloes that have a single size and
** are not in the hd halo list to the global exclude list, i.e. we never have to consider
** these particles at all.
*/
if (gi->DataProcessingMode == 1 && NIndexArray > 0) {
MoveToGlobalList = 0;
Ntot = 0;
Ncheck = 0;
/*
** Only if in all appearances the halo has the same size move it to the global list
*/
if (NIndexArray == 1) MoveToGlobalList = 1;
else if (NIndexArray > 1) {
for (j = 1; j < NIndexArray; j++) {
Ntot++;
if (SizeArray[j] == SizeArray[j-1]) Ncheck++;
}
if (Ntot == Ncheck) MoveToGlobalList = 1;
}
/*
** Halo is not allowed to be in the halo data list
*/
if (ContainedInHaloDataList) MoveToGlobalList = 0;
/*
** Move to global exclusion list
*/
if (MoveToGlobalList) {
for (j = 0; j < NIndexArray; j++) {
i = IndexArray[j];
/*
** Transfer the halo => only need to do that once (j == 0)
*/
if (j == 0) {
gi->NHaloExcludeGlobal++;
if (SizeHaloData < gi->NHaloExcludeGlobal) {
SizeHaloData += SizeHaloDataIncrement;
hdeg = realloc(hdeg,SizeHaloData*sizeof(HALO_DATA_EXCLUDE));
assert(hdeg != NULL);
}
l = gi->NHaloExcludeGlobal-1;
hdeg[l].ID = ID;
for (k = 0; k < 3; k++) hdeg[l].rcentre[k] = r[k];
hdeg[l].size = SizeArray[0];
}
/*
** Remove the haloes from the local list
*/
assert(hd[i].hde[hd[i].NHaloExclude-1].ID == ID);
hd[i].NHaloExclude--;
}
}
}
} /* while loop */
fclose(HaloCatalogueFile);
free(IndexArray);
free(SizeArray);
*hdegin = hdeg;
return NHaloRead;
}
void initialise_halo_profile(GI *gi, HALO_DATA *hd) {
int d, n[3], j, l;
double dr[3] = {0,0,0};
const double ex[3] = {1,0,0};
const double ey[3] = {0,1,0};
const double ez[3] = {0,0,1};
PROFILE_BIN_STRUCTURE *pbs;
PROFILE_BIN_PROPERTIES *bin;
PROFILE_SHAPE_PROPERTIES *shape;
hd->HostHaloID = -1;
hd->ExtraHaloID = -1;
hd->NHaloExclude = 0;
hd->SizeExcludeHaloData = 0;
hd->IsTruncated = 0;
hd->rmean = 0;
hd->Mrmean = 0;
hd->rcrit = 0;
hd->Mrcrit = 0;
hd->rfix = 0;
hd->Mrfix = 0;
hd->rtrunc = 0;
hd->Mrtrunc = 0;
hd->rtruncindicator = 0;
hd->size = 0;
hd->mass = 0;
for (d = 0; d < 3; d++) {
hd->rcentrenew[d] = 0;
hd->vcentrenew[d] = 0;
}
for (j = 0; j < NSPECIESBACKGROUND; j++) {
hd->rhobg[j] = 0;
for (l = 0; l < 2; l++) {
hd->rvcmax[j][l] = 0;
hd->Mrvcmax[j][l] = 0;
}
}
/*
** Calculate bin spacings
*/
for (d = 0; d < gi->NDimProfile; d++) {
if (gi->NDimProfile == 2 && gi->BinningCoordinateType == 1 && d == 1) {
if (gi->BinningGridType[d] == 0) {
dr[d] = (log(hd->rmax[d])-log(hd->rmin[d]))/(hd->NBin[d]/2-1);
}
else if (gi->BinningGridType[d] == 1) {
dr[d] = (hd->rmax[d]-hd->rmin[d])/(hd->NBin[d]/2);
}
}
else {
if (gi->BinningGridType[d] == 0) {
dr[d] = (log(hd->rmax[d])-log(hd->rmin[d]))/(hd->NBin[d]-1);
}
else if (gi->BinningGridType[d] == 1) {
dr[d] = (hd->rmax[d]-hd->rmin[d])/hd->NBin[d];
}
}
}
/*
** Initialise bins
*/
for (n[0] = 0; n[0] < hd->NBin[0]; n[0]++) {
for (n[1] = 0; n[1] < hd->NBin[1]; n[1]++) {
for (n[2] = 0; n[2] < hd->NBin[2]; n[2]++) {
pbs = &hd->pbs[n[0]][n[1]][n[2]];
/*
** Calculate coordinates of bins
*/
for (d = 0; d < gi->NDimProfile; d++) {
if (gi->NDimProfile == 2 && gi->BinningCoordinateType == 1 && d == 1 && n[1] >= hd->NBin[1]/2) {
l = hd->NBin[1]/2;
pbs->ri[d] = (-1)*hd->pbs[n[0]][n[1]-l][n[2]].ro[d];
pbs->rm[d] = (-1)*hd->pbs[n[0]][n[1]-l][n[2]].rm[d];
pbs->ro[d] = (-1)*hd->pbs[n[0]][n[1]-l][n[2]].ri[d];
}
else {
if (gi->BinningGridType[d] == 0) {
if (n[d] == 0) {
pbs->ri[d] = 0;
pbs->rm[d] = exp(log(hd->rmin[d])-0.5*dr[d]);
pbs->ro[d] = hd->rmin[d];
}
else {
pbs->ri[d] = exp(log(hd->rmin[d]) + (n[d]-1)*dr[d]);
pbs->rm[d] = exp(log(hd->rmin[d]) + (n[d]-0.5)*dr[d]);
pbs->ro[d] = exp(log(hd->rmin[d]) + n[d]*dr[d]);
}
}
else if (gi->BinningGridType[d] == 1) {
pbs->ri[d] = hd->rmin[d] + n[d]*dr[d];
pbs->rm[d] = hd->rmin[d] + (n[d]+0.5)*dr[d];
pbs->ro[d] = hd->rmin[d] + (n[d]+1)*dr[d];
}
}
}
/*
** Initialise bin and shape structures
*/
for (j = 0; j < gi->NSpeciesProfile; j++) {
if (gi->SpeciesContained[j]) {
if (gi->ProfilingMode == 0) {
/*
** Bin
*/
bin = &pbs->bin[j];
bin->N = 0;
bin->M = 0;
bin->Menc[0] = 0;
bin->Menc[1] = 0;
for (d = 0; d < 3; d++) {
bin->v[d] = 0;
bin->L[d] = 0;
}
for (d = 0; d < 6; d++) {
bin->vdt[d] = 0;
}
if (j < gi->NSpeciesRead) {
for (d = 0; d < gi->NProperties[j]; d++) {
bin->P[d] = 0;
}
}
}
else if (gi->ProfilingMode == 1) {
/*
** Shape
*/
shape = &pbs->shape[j];
shape->NLoopConverged = 0;
shape->N = 0;
shape->M = 0;
shape->b_a = 0;
shape->c_a = 0;
shape->b_a_old = 0;
shape->c_a_old = 0;
/* shape->dmin = 0; */
/* shape->dmax = 0; */
/* shape->propertymin = 0; */
/* shape->propertymax = 0; */
/* shape->propertymean = 0; */
for (d = 0; d < 3; d++) {
shape->a[d] = ex[d];
shape->b[d] = ey[d];
shape->c[d] = ez[d];
}
for (d = 0; d < 6; d++) {
shape->st[d] = 0;
}
}
} /* if SpeciesContained */
} /* for NSpeciesProfile */
} /* for n[2] */
} /* for n[1] */
} /* for n[0] */
}
void reset_halo_profile_shape(GI gi, HALO_DATA *hd) {
int d, n[3], i, j;
PROFILE_SHAPE_PROPERTIES *shape;
#pragma omp parallel for default(none) private(d,n,i,j,shape) shared(gi,hd)
for (i = 0; i < gi.NHalo; i++) {
for (n[0] = 0; n[0] < hd[i].NBin[0]; n[0]++) {
for (n[1] = 0; n[1] < hd[i].NBin[1]; n[1]++) {
for (n[2] = 0; n[2] < hd[i].NBin[2]; n[2]++) {
for (j = 0; j < gi.NSpeciesProfile; j++) {
if (gi.SpeciesContained[j]) {
shape = &hd[i].pbs[n[0]][n[1]][n[2]].shape[j];
shape->N = 0;
shape->M = 0;
for (d = 0; d < 6; d++) shape->st[d] = 0;
}
}
}
}
}
}
}
void add_particle_to_shape_tensor(GI gi, PROFILE_SHAPE_PROPERTIES *shape, double M, double r[3], double dsph, double dell) {
int d;
double fst;
switch(gi.ShapeTensorForm) {
case 0: fst = 1; break;
case 1: fst = 1/pow(dsph,2); break;
case 2: fst = 1/pow(dell,2); break;
default: fst = 1; }
shape->N++;
shape->M += M;
for (d = 0; d < 3; d++) shape->st[d] += M*r[d]*r[d]*fst;
shape->st[3] += M*r[0]*r[1]*fst;
shape->st[4] += M*r[0]*r[2]*fst;
shape->st[5] += M*r[1]*r[2]*fst;
}
void put_particles_in_bins(GI gi, HALO_DATA *hd, const int MatterType, PROFILE_PARTICLE *pp) {
int d, n[3], i, j, k, l;
int index[3];
int NParticle = 0;
int ParticleAccepted, InThisBin, LoopBroken;
int ***HeadIndex, *NextIndex;
double r[3], rell[3], v[3], vproj[3];
double eA[3], eB[3], eC[3];
double dsph, dell, size;
double dist[3], shift[3];
double M;
PROFILE_BIN_STRUCTURE *pbs;
PROFILE_BIN_PROPERTIES *bin;
PROFILE_SHAPE_PROPERTIES *shape;
if (gi.DataProcessingMode == 0) NParticle = gi.NParticleInBlock[MatterType];
else if (gi.DataProcessingMode == 1) NParticle = gi.NParticleInStorage[MatterType];
/*
** Initialise linked list stuff
*/
HeadIndex = malloc(gi.NCellData*sizeof(int **));
assert(HeadIndex != NULL);
for (i = 0; i < gi.NCellData; i ++) {
HeadIndex[i] = malloc(gi.NCellData*sizeof(int *));
assert(HeadIndex[i] != NULL);
for (j = 0; j < gi.NCellData; j++) {
HeadIndex[i][j] = malloc(gi.NCellData*sizeof(int));
assert(HeadIndex[i][j] != NULL);
}
}
NextIndex = malloc(NParticle*sizeof(int));
assert(NextIndex != NULL);
for (i = 0; i < gi.NCellData; i++) {
for (j = 0; j < gi.NCellData; j++) {
for (k = 0; k < gi.NCellData; k++) {
HeadIndex[i][j][k] = -1;
}
}
}
for (j = 0; j < NParticle; j++) NextIndex[j] = -1;
for (d = 0; d < 3; d++) shift[d] = 0-gi.bc[d];
/*
** Generate linked list
*/
for (j = 0; j < NParticle; j++) {
for (d = 0; d < 3; d++) {
index[d] = (int)(gi.NCellData*(pp[j].r[d]+shift[d])/gi.us.LBox);
if (index[d] == gi.NCellData) index[d] = gi.NCellData-1; /* Case where particles are exactly on the boundary */
assert(index[d] >= 0 && index[d] < gi.NCellData);
}
NextIndex[j] = HeadIndex[index[0]][index[1]][index[2]];
HeadIndex[index[0]][index[1]][index[2]] = j;
}
/*
** Go through linked list
*/
for (index[0] = 0; index[0] < gi.NCellData; index[0]++) {
for (index[1] = 0; index[1] < gi.NCellData; index[1]++) {
for (index[2] = 0; index[2] < gi.NCellData; index[2]++) {
#pragma omp parallel for default(none) private(d,n,i,j,k,l,ParticleAccepted,InThisBin,LoopBroken,r,rell,v,vproj,eA,eB,eC,dsph,dell,size,dist,M,pbs,bin,shape) shared(gi,hd,pp,index,shift,HeadIndex,NextIndex)
for (i = 0; i < gi.NHalo; i++) {
if (gi.ILoopRead < gi.NLoopRecentre && gi.RecentreUse[MatterType] == 1) {
/*
** Recentre halo coordinates
*/
size = gi.rRecentre;
size *= pow(gi.fRecentreDist,gi.NLoopRecentre-1-gi.ILoopRead);
assert(size > 0);
if (intersect(gi.us.LBox,gi.NCellData,hd[i],index,shift,size)) {
j = HeadIndex[index[0]][index[1]][index[2]];
while (j >= 0) {
for (d = 0; d < 3; d++) {
r[d] = correct_position(hd[i].rcentre[d],pp[j].r[d],gi.us.LBox);
r[d] = r[d]-hd[i].rcentre[d];
}
dsph = sqrt(r[0]*r[0]+r[1]*r[1]+r[2]*r[2]);
if (dsph <= size) {
M = pp[j].P[gi.pi[MatterType][MASS_TOT]];
hd[i].Mrtrunc += M; /* temporarily use Mrtrunc */
for (d = 0; d < 3; d++) {
hd[i].rcentrenew[d] += M*correct_position(hd[i].rcentre[d],pp[j].r[d],gi.us.LBox);
hd[i].vcentrenew[d] += M*pp[j].v[d];
}
}
j = NextIndex[j];
} /* while j >= 0 */
} /* if intersect */
} /* if recentre */
else if (gi.ILoopRead >= gi.NLoopRecentre) {
/*
** Process data
*/
size = hd[i].rmax[0];
if (gi.ProfilingMode == 0 && gi.BinningCoordinateType == 1) size = sqrt(pow(hd[i].rmax[0],2)+pow(hd[i].zHeight,2));
/* if (gi.ProfilingMode == 3) size = gi.fincludeshaperadius*hd[i].rmax[0]; */
if (intersect(gi.us.LBox,gi.NCellData,hd[i],index,shift,size)) {
j = HeadIndex[index[0]][index[1]][index[2]];
while (j >= 0) {
for (d = 0; d < 3; d++) {
r[d] = correct_position(hd[i].rcentre[d],pp[j].r[d],gi.us.LBox);
r[d] = r[d]-hd[i].rcentre[d];
}
dsph = sqrt(r[0]*r[0]+r[1]*r[1]+r[2]*r[2]);
if (dsph <= size) {
/*
** Now check if it is outside an excluded subhalo
*/
ParticleAccepted = 1;
if (gi.ExcludeParticles == 1) {
for (l = 0; l < hd[i].NHaloExclude; l++) {
for (d = 0; d < 3; d++) {
rell[d] = correct_position(hd[i].hde[l].rcentre[d],pp[j].r[d],gi.us.LBox);
rell[d] = rell[d]-hd[i].hde[l].rcentre[d];
}
dell = sqrt(rell[0]*rell[0]+rell[1]*rell[1]+rell[2]*rell[2]);
if (dell <= hd[i].hde[l].size) {
ParticleAccepted = 0;
break;
}
}
}
/*
** Check if it is outside the cylindrical disc
*/
if (gi.ProfilingMode == 0 && gi.BinningCoordinateType == 1) {
calculate_unit_vectors_cylindrical(r,hd[i].zAxis,eA,eB,eC);
dell = fabs(r[0]*eC[0] + r[1]*eC[1] + r[2]*eC[2]);
if (dell > hd[i].zHeight) ParticleAccepted = 0;
}
if (ParticleAccepted) {
for (d = 0; d < 3; d++) {
v[d] = pp[j].v[d]-hd[i].vcentre[d];
}
if (gi.ProfilingMode == 0) {
/*
** Normal binning mode
*/
for (d = 0; d < 3; d++) {
dist[d] = -1;
}
if (gi.BinningCoordinateType == 0) { /* spherical */
dist[0] = dsph;
}
else if (gi.BinningCoordinateType == 1) { /* cylindrical */
calculate_unit_vectors_cylindrical(r,hd[i].zAxis,eA,eB,eC);
dist[0] = r[0]*eA[0] + r[1]*eA[1] + r[2]*eA[2];
dist[1] = r[0]*eC[0] + r[1]*eC[1] + r[2]*eC[2];
assert(!(dist[0] < 0));
}
else {
for (d = 0; d < 3; d++) {
dist[d] = -1;
}
}
LoopBroken = 0;
/*
** Go through radial bins from outside inwards => larger bin volume further out
*/
for (n[0] = hd[i].NBin[0]-1; n[0] >= 0 && !LoopBroken; n[0]--) {
for (n[1] = 0; n[1] < hd[i].NBin[1] && !LoopBroken; n[1]++) {
for (n[2] = 0; n[2] < hd[i].NBin[2] && !LoopBroken; n[2]++) {
pbs = &hd[i].pbs[n[0]][n[1]][n[2]];
InThisBin = 1;
for (d = 0; d < gi.NDimProfile; d++) {
if (!(pbs->ri[d] <= dist[d] && pbs->ro[d] > dist[d])) InThisBin = 0;
}
if (InThisBin) {
/*
** Calculate velocity
*/
if (gi.VelocityProjectionType == 1) {
calculate_unit_vectors_spherical(r,eA,eB,eC);
vproj[0] = v[0]*eA[0] + v[1]*eA[1] + v[2]*eA[2];
vproj[1] = v[0]*eB[0] + v[1]*eB[1] + v[2]*eB[2];
vproj[2] = v[0]*eC[0] + v[1]*eC[1] + v[2]*eC[2];
}
else if (gi.VelocityProjectionType == 2) {
calculate_unit_vectors_cylindrical(r,hd[i].zAxis,eA,eB,eC);
vproj[0] = v[0]*eA[0] + v[1]*eA[1] + v[2]*eA[2];
vproj[1] = v[0]*eB[0] + v[1]*eB[1] + v[2]*eB[2];
vproj[2] = v[0]*eC[0] + v[1]*eC[1] + v[2]*eC[2];
}
else {
vproj[0] = v[0];
vproj[1] = v[1];
vproj[2] = v[2];
}
/*
** Current matter type with sub species
*/
for (l = 0; l < gi.NSubSpecies[MatterType]; l++) {
bin = NULL;
if (MatterType == GAS) {
if (l == gi.pi[MatterType][MASS_TOT]) bin = &pbs->bin[GAS];
else if (l == gi.pi[MatterType][MASS_METAL_SNII]) bin = &pbs->bin[GAS_METAL_SNII];
else if (l == gi.pi[MatterType][MASS_METAL_SNIa]) bin = &pbs->bin[GAS_METAL_SNIa];
else if (l == gi.pi[MatterType][MASS_HI]) bin = &pbs->bin[GAS_HI];
else if (l == gi.pi[MatterType][MASS_HII]) bin = &pbs->bin[GAS_HII];
else if (l == gi.pi[MatterType][MASS_HeI]) bin = &pbs->bin[GAS_HeI];
else if (l == gi.pi[MatterType][MASS_HeII]) bin = &pbs->bin[GAS_HeII];
else if (l == gi.pi[MatterType][MASS_HeIII]) bin = &pbs->bin[GAS_HeIII];
else if (l == gi.pi[MatterType][MASS_H2]) bin = &pbs->bin[GAS_H2];
}
else if (MatterType == DARK) {
if (l == gi.pi[MatterType][MASS_TOT]) bin = &pbs->bin[DARK];
}
else if (MatterType == STAR) {
if (l == gi.pi[MatterType][MASS_TOT]) bin = &pbs->bin[STAR];
else if (l == gi.pi[MatterType][MASS_METAL_SNII]) bin = &pbs->bin[STAR_METAL_SNII];
else if (l == gi.pi[MatterType][MASS_METAL_SNIa]) bin = &pbs->bin[STAR_METAL_SNIa];
}
assert(bin != NULL);
M = pp[j].P[l];
bin->N += 1;
bin->M += M;
for (d = 0; d < 3; d++) {
bin->v[d] += M*vproj[d];
bin->vdt[d] += M*vproj[d]*vproj[d];
}
bin->vdt[3] += M*vproj[0]*vproj[1];
bin->vdt[4] += M*vproj[0]*vproj[2];
bin->vdt[5] += M*vproj[1]*vproj[2];
bin->L[0] += M*(r[1]*v[2]-r[2]*v[1]);
bin->L[1] += M*(r[2]*v[0]-r[0]*v[2]);
bin->L[2] += M*(r[0]*v[1]-r[1]*v[0]);
}
/*
** Additional properties
*/
bin = &pbs->bin[MatterType];
assert(bin != NULL);
M = pp[j].P[gi.pi[MatterType][MASS_TOT]];
for (l = 0; l < gi.NProperties[MatterType]; l++) {
bin->P[l] += M*pp[j].P[l+gi.NSubSpecies[MatterType]];
}
LoopBroken = 1;
break;
} /* if InThisBin */
} /* for n[2] */
} /* for n[1] */
} /* for n[0] */
} /* if ProfilingMode */
else if (gi.ProfilingMode == 1) {
/*
** For the shape determination particles can be in more than one bin! => No break!
** Only radial bins are used.
*/
for (n[0] = 0; n[0] < hd[i].NBin[0]; n[0]++) {
n[1] = 0;
n[2] = 0;
pbs = &hd[i].pbs[n[0]][n[1]][n[2]];
/*
** Current matter type with sub species
*/
for (l = 0; l < gi.NSubSpecies[MatterType]; l++) {
shape = NULL;
if (MatterType == GAS) {
if (l == gi.pi[MatterType][MASS_TOT]) shape = &pbs->shape[GAS];
else if (l == gi.pi[MatterType][MASS_METAL_SNII]) shape = &pbs->shape[GAS_METAL_SNII];
else if (l == gi.pi[MatterType][MASS_METAL_SNIa]) shape = &pbs->shape[GAS_METAL_SNIa];
else if (l == gi.pi[MatterType][MASS_HI]) shape = &pbs->shape[GAS_HI];
else if (l == gi.pi[MatterType][MASS_HII]) shape = &pbs->shape[GAS_HII];
else if (l == gi.pi[MatterType][MASS_HeI]) shape = &pbs->shape[GAS_HeI];
else if (l == gi.pi[MatterType][MASS_HeII]) shape = &pbs->shape[GAS_HeII];
else if (l == gi.pi[MatterType][MASS_HeIII]) shape = &pbs->shape[GAS_HeIII];
else if (l == gi.pi[MatterType][MASS_H2]) shape = &pbs->shape[GAS_H2];
}
else if (MatterType == DARK) {
if (l == gi.pi[MatterType][MASS_TOT]) shape = &pbs->shape[DARK];
}
else if (MatterType == STAR) {
if (l == gi.pi[MatterType][MASS_TOT]) shape = &pbs->shape[STAR];
else if (l == gi.pi[MatterType][MASS_METAL_SNII]) shape = &pbs->shape[STAR_METAL_SNII];
else if (l == gi.pi[MatterType][MASS_METAL_SNIa]) shape = &pbs->shape[STAR_METAL_SNIa];
}
assert(shape != NULL);
calculate_coordinates_principal_axes(shape,r,rell,&dell);
InThisBin = 0;
if (gi.ShapeDeterminationVolume == 0) {
if (pbs->ri[0] <= dell && pbs->ro[0] > dell) InThisBin = 1;
}
else if (gi.ShapeDeterminationVolume == 1) {
if (pbs->ro[0] > dell) InThisBin = 1;
}
if (InThisBin) add_particle_to_shape_tensor(gi,shape,pp[j].P[l],r,dsph,dell);
}
/*
** Total matter
*/
if (MatterType == GAS || MatterType == DARK || MatterType == STAR) {
calculate_coordinates_principal_axes(&pbs->shape[TOT],r,rell,&dell);
InThisBin = 0;
if (gi.ShapeDeterminationVolume == 0) {
if (pbs->ri[0] <= dell && pbs->ro[0] > dell) InThisBin = 1;
}
else if (gi.ShapeDeterminationVolume == 1) {
if (pbs->ro[0] > dell) InThisBin = 1;
}
if (InThisBin) add_particle_to_shape_tensor(gi,&pbs->shape[TOT],pp[j].P[gi.pi[MatterType][MASS_TOT]],r,dsph,dell);
}
/*
** Baryonic matter
*/
if (MatterType == GAS || MatterType == STAR) {
calculate_coordinates_principal_axes(&pbs->shape[BARYON],r,rell,&dell);
InThisBin = 0;
if (gi.ShapeDeterminationVolume == 0) {
if (pbs->ri[0] <= dell && pbs->ro[0] > dell) InThisBin = 1;
}
else if (gi.ShapeDeterminationVolume == 1) {
if (pbs->ro[0] > dell) InThisBin = 1;
}
if (InThisBin) add_particle_to_shape_tensor(gi,&pbs->shape[BARYON],pp[j].P[gi.pi[MatterType][MASS_TOT]],r,dsph,dell);
if (gi.DoMetalSpecies) {
calculate_coordinates_principal_axes(&pbs->shape[BARYON_METAL_SNII],r,rell,&dell);
InThisBin = 0;
if (gi.ShapeDeterminationVolume == 0) {
if (pbs->ri[0] <= dell && pbs->ro[0] > dell) InThisBin = 1;
}
else if (gi.ShapeDeterminationVolume == 1) {
if (pbs->ro[0] > dell) InThisBin = 1;
}
if (InThisBin) add_particle_to_shape_tensor(gi,&pbs->shape[BARYON_METAL_SNII],pp[j].P[gi.pi[MatterType][MASS_METAL_SNII]],r,dsph,dell);
calculate_coordinates_principal_axes(&pbs->shape[BARYON_METAL_SNIa],r,rell,&dell);
InThisBin = 0;
if (gi.ShapeDeterminationVolume == 0) {
if (pbs->ri[0] <= dell && pbs->ro[0] > dell) InThisBin = 1;
}
else if (gi.ShapeDeterminationVolume == 1) {
if (pbs->ro[0] > dell) InThisBin = 1;
}
if (InThisBin) add_particle_to_shape_tensor(gi,&pbs->shape[BARYON_METAL_SNIa],pp[j].P[gi.pi[MatterType][MASS_METAL_SNIa]],r,dsph,dell);
}
}
} /* for n[0] */
} /* else if ProfilingMode */
/* else if (gi.ProfilingMode == 3 && gi.ILoopRead == 0) { */
/* for (l = 0; l < hd[i].NBin+1; l++) { */
/* if (hd[i].pbs[l].ri <= d && hd[i].pbs[l].ro > d) { */
/* /\* */
/* ** Total mass */
/* *\/ */
/* hd[i].pbs[l].totshape->N++; */
/* hd[i].pbs[l].totshape->propertymean += pgp[i].propertytot; */
/* /\* */
/* ** Gas */
/* *\/ */
/* hd[i].pbs[l].gasshape->N++; */
/* hd[i].pbs[l].gasshape->propertymean += pgp[i].property; */
/* } */
/* } */
/* } /\* else if ProfilingMode *\/ */
/* else if (gi.ProfilingMode == 3 && gi.ILoopRead > 0) { */
/* for (l = 0; l < hd[i].NBin+1; l++) { */
/* /\* */
/* ** Total mass */
/* *\/ */
/* calculate_coordinates_principal_axes(hd[i].pbs[l].totshape,r,rell,&dell); */
/* if (hd[i].pbs[l].totshape->propertymin <= pgp[i].propertytot && */
/* pgp[i].propertytot <= hd[i].pbs[l].totshape->propertymax && */
/* gi.fincludeshaperadius*hd[i].pbs[l].ro > d) */
/* add_particle_to_shape_tensor(gi,hd[i].pbs[l].totshape,pgp[i].M,r,d,dell); */
/* /\* */
/* ** Gas */
/* *\/ */
/* calculate_coordinates_principal_axes(hd[i].pbs[l].gasshape,r,rell,&dell); */
/* if (hd[i].pbs[l].gasshape->propertymin <= pgp[i].property && */
/* pgp[i].property <= hd[i].pbs[l].gasshape->propertymax && */
/* gi.fincludeshaperadius*hd[i].pbs[l].ro > d) */
/* add_particle_to_shape_tensor(gi,hd[i].pbs[l].gasshape,pgp[i].M,r,d,dell); */
/* } */
/* } /\* else if ProfilingMode *\/ */
} /* if ParticleAccepted */
} /* if dsph <= size */
j = NextIndex[j];
} /* while j >= 0 */
} /* if intersect */
} /* if process data */
} /* for gi.NHalo */
} /* for index[2] */
} /* for index[1] */
} /* for index[0] */
for (i = 0; i < gi.NCellData; i ++) {
for (j = 0; j < gi.NCellData; j++) {
free(HeadIndex[i][j]);
}
free(HeadIndex[i]);
}
free(HeadIndex);
free(NextIndex);
}
void put_particles_in_storage(GI *gi, HALO_DATA *hd, HALO_DATA_EXCLUDE *hdeg, const int MatterType, PROFILE_PARTICLE *pp, PROFILE_PARTICLE **pp_storage_in) {
int d, i, j, k, l;
int index[3];
int NParticle = 0;
int ParticleAccepted;
int ***HeadIndex, *NextIndex, *AlreadyStored;
double r[3], rexclude[3], dsph, dexclude, size, shift[3];
PROFILE_PARTICLE *pp_storage;
NParticle = gi->NParticleInBlock[MatterType];
pp_storage = *pp_storage_in;
/*
** Initialise linked list stuff
*/
HeadIndex = malloc(gi->NCellData*sizeof(int **));
assert(HeadIndex != NULL);
for (i = 0; i < gi->NCellData; i ++) {
HeadIndex[i] = malloc(gi->NCellData*sizeof(int *));
assert(HeadIndex[i] != NULL);
for (j = 0; j < gi->NCellData; j++) {
HeadIndex[i][j] = malloc(gi->NCellData*sizeof(int));
assert(HeadIndex[i][j] != NULL);
}
}
NextIndex = malloc(NParticle*sizeof(int));
assert(NextIndex != NULL);
for (i = 0; i < gi->NCellData; i++) {
for (j = 0; j < gi->NCellData; j++) {
for (k = 0; k < gi->NCellData; k++) {
HeadIndex[i][j][k] = -1;
}
}
}
for (i = 0; i < NParticle; i++) NextIndex[i] = -1;
for (i = 0; i < 3; i++) shift[i] = 0-gi->bc[i];
/*
** Array for quick and dirty way to keep track which particle is already stored
*/
AlreadyStored = malloc(NParticle*sizeof(int));
assert(AlreadyStored != NULL);
for (i = 0; i < NParticle; i++) AlreadyStored[i] = 0;
/*
** Generate linked list
*/
for (i = 0; i < NParticle; i++) {
for (j = 0; j < 3; j++) {
index[j] = (int)(gi->NCellData*(pp[i].r[j]+shift[j])/gi->us.LBox);
if (index[j] == gi->NCellData) index[j] = gi->NCellData-1; /* Case where particles are exactly on the boundary */
assert(index[j] >= 0 && index[j] < gi->NCellData);
}
NextIndex[i] = HeadIndex[index[0]][index[1]][index[2]];
HeadIndex[index[0]][index[1]][index[2]] = i;
}
/*
** Go through linked list
*/
for (index[0] = 0; index[0] < gi->NCellData; index[0]++) {
for (index[1] = 0; index[1] < gi->NCellData; index[1]++) {
for (index[2] = 0; index[2] < gi->NCellData; index[2]++) {
for (i = 0; i < gi->NHalo; i++) {
/*
** Process data
*/
size = hd[i].rmax[0];
if (gi->ProfilingMode == 0 && gi->BinningCoordinateType == 1) size = sqrt(pow(hd[i].rmax[0],2)+pow(hd[i].zHeight,2));
if (intersect(gi->us.LBox,gi->NCellData,hd[i],index,shift,size)) {
j = HeadIndex[index[0]][index[1]][index[2]];
while (j >= 0) {
for (d = 0; d < 3; d++) {
r[d] = correct_position(hd[i].rcentre[d],pp[j].r[d],gi->us.LBox);
r[d] = r[d]-hd[i].rcentre[d];
}
dsph = sqrt(r[0]*r[0]+r[1]*r[1]+r[2]*r[2]);
if (dsph <= size && AlreadyStored[j] == 0) {
/*
** Now check if it is outside a globally excluded subhalo
*/
ParticleAccepted = 1;
if (gi->ExcludeParticles) {
for (l = 0; l < gi->NHaloExcludeGlobal; l++) {
for (d = 0; d < 3; d++) {
rexclude[d] = correct_position(hdeg[l].rcentre[d],pp[j].r[d],gi->us.LBox);
rexclude[d] = rexclude[d]-hdeg[l].rcentre[d];
}
dexclude = sqrt(rexclude[0]*rexclude[0]+rexclude[1]*rexclude[1]+rexclude[2]*rexclude[2]);
if (dexclude <= hdeg[l].size) {
ParticleAccepted = 0;
break;
}
}
}
if (ParticleAccepted) {
/*
** Add particle to storage
*/
gi->NParticleInStorage[MatterType]++;
if (gi->SizeStorage[MatterType] < gi->NParticleInStorage[MatterType]) {
gi->SizeStorage[MatterType] += gi->SizeStorageIncrement;
pp_storage = realloc(pp_storage,gi->SizeStorage[MatterType]*sizeof(PROFILE_PARTICLE));
assert(pp_storage != NULL);
for (l = gi->SizeStorage[MatterType]-gi->SizeStorageIncrement; l < gi->SizeStorage[MatterType]; l++) {
pp_storage[l].P = malloc((gi->NSubSpecies[MatterType]+gi->NProperties[MatterType])*sizeof(double));
assert(pp_storage[l].P != NULL);
}
}
copy_pp(gi,MatterType,&pp[j],&pp_storage[gi->NParticleInStorage[MatterType]-1]);
AlreadyStored[j] = 1;
}
}
j = NextIndex[j];
}
}
}
}
}
}
for (i = 0; i < gi->NCellData; i ++) {
for (j = 0; j < gi->NCellData; j++) {
free(HeadIndex[i][j]);
}
free(HeadIndex[i]);
}
free(HeadIndex);
free(NextIndex);
free(AlreadyStored);
*pp_storage_in = pp_storage;
}
int intersect(double LBox, int NCell, HALO_DATA hd, int index[3], double shift[3], double size) {
int d;
double celllength, distance, dcheck;
double rhalo[3], rcell[3], dsph[3];
celllength = LBox/NCell;
for (d = 0; d < 3; d++) {
rhalo[d] = hd.rcentre[d];
rcell[d] = index[d]*celllength - shift[d]; /* lower edge */
dsph[d] = rhalo[d] - rcell[d];
/*
** Check if the upper edge is closer
*/
if (dsph[d] > 0) {
dsph[d] -= celllength;
if (dsph[d] < 0) {
dsph[d] = 0; /* contained */
}
}
/*
** Check if a periodic copy of the cell is closer
*/
dcheck = LBox - celllength - fabs(dsph[d]);
if (dcheck < fabs(dsph[d])) {
dsph[d] = dcheck;
}
}
distance = sqrt(dsph[0]*dsph[0]+dsph[1]*dsph[1]+dsph[2]*dsph[2]);
if (distance <= size) return 1;
else return 0;
}
void copy_pp(GI *gi, const int MatterType, const PROFILE_PARTICLE *from_pp, PROFILE_PARTICLE *to_pp) {
int d;
for (d = 0; d < 3; d++) {
to_pp->r[d] = from_pp->r[d];
to_pp->v[d] = from_pp->v[d];
}
for (d = 0; d < gi->NSubSpecies[MatterType]+gi->NProperties[MatterType]; d++) {
to_pp->P[d] = from_pp->P[d];
}
}
void calculate_coordinates_principal_axes(PROFILE_SHAPE_PROPERTIES *shape, double r[3], double rell[3], double *dell) {
rell[0] = 0;
rell[0] += r[0]*shape->a[0];
rell[0] += r[1]*shape->a[1];
rell[0] += r[2]*shape->a[2];
rell[1] = 0;
rell[1] += r[0]*shape->b[0];
rell[1] += r[1]*shape->b[1];
rell[1] += r[2]*shape->b[2];
rell[2] = 0;
rell[2] += r[0]*shape->c[0];
rell[2] += r[1]*shape->c[1];
rell[2] += r[2]*shape->c[2];
*dell = 0;
*dell += rell[0]*rell[0];
*dell += rell[1]*rell[1]/pow(shape->b_a,2);
*dell += rell[2]*rell[2]/pow(shape->c_a,2);
*dell = sqrt(*dell);
}
void calculate_recentred_halo_coordinates(GI gi, HALO_DATA *hd) {
int d, i;
#pragma omp parallel for default(none) private(d,i) shared(gi,hd)
for (i = 0; i < gi.NHalo; i++) {
if (hd[i].Mrtrunc > 0) {
for (d = 0; d < 3; d++) {
hd[i].rcentre[d] = hd[i].rcentrenew[d]/hd[i].Mrtrunc;
hd[i].vcentre[d] = hd[i].vcentrenew[d]/hd[i].Mrtrunc;
hd[i].rcentrenew[d] = 0;
hd[i].vcentrenew[d] = 0;
}
}
hd[i].Mrtrunc = 0;
}
}
void calculate_total_matter_distribution(GI gi, HALO_DATA *hd) {
int d, n[3], i, j;
PROFILE_BIN_STRUCTURE *pbs;
#pragma omp parallel for default(none) private(d,n,i,j,pbs) shared(gi,hd)
for (i = 0; i < gi.NHalo; i++) {
for (n[0] = 0; n[0] < hd[i].NBin[0]; n[0]++) {
for (n[1] = 0; n[1] < hd[i].NBin[1]; n[1]++) {
for (n[2] = 0; n[2] < hd[i].NBin[2]; n[2]++) {
pbs = &hd[i].pbs[n[0]][n[1]][n[2]];
for (j = 0; j < gi.NSpeciesRead; j++) {
if (gi.SpeciesContained[j]) {
pbs->bin[TOT].N += pbs->bin[j].N;
pbs->bin[TOT].M += pbs->bin[j].M;
for (d = 0; d < 3; d++) {
pbs->bin[TOT].v[d] += pbs->bin[j].v[d];
pbs->bin[TOT].L[d] += pbs->bin[j].L[d];
}
for (d = 0; d < 6; d++) {
pbs->bin[TOT].vdt[d] += pbs->bin[j].vdt[d];
}
} /* if SpeciesContained */
} /* for NSpeciesRead */
} /* for n[2] */
} /* for n[1] */
} /* for n[0] */
} /* for NHalo */
}
void calculate_baryonic_matter_distribution(GI gi, HALO_DATA *hd) {
int d, n[3], i, j;
PROFILE_BIN_STRUCTURE *pbs;
#pragma omp parallel for default(none) private(d,n,i,j,pbs) shared(gi,hd)
for (i = 0; i < gi.NHalo; i++) {
for (n[0] = 0; n[0] < hd[i].NBin[0]; n[0]++) {
for (n[1] = 0; n[1] < hd[i].NBin[1]; n[1]++) {
for (n[2] = 0; n[2] < hd[i].NBin[2]; n[2]++) {
pbs = &hd[i].pbs[n[0]][n[1]][n[2]];
for (j = 0; j < gi.NSpeciesRead; j++) {
if (j == DARK) continue;
if (gi.SpeciesContained[j]) {
pbs->bin[BARYON].N += pbs->bin[j].N;
pbs->bin[BARYON].M += pbs->bin[j].M;
for (d = 0; d < 3; d++) {
pbs->bin[BARYON].v[d] += pbs->bin[j].v[d];
pbs->bin[BARYON].L[d] += pbs->bin[j].L[d];
}
for (d = 0; d < 6; d++) {
pbs->bin[BARYON].vdt[d] += pbs->bin[j].vdt[d];
}
} /* if SpeciesContained */
} /* for NSpeciesRead */
if (gi.DoMetalSpecies) {
for (j = GAS_METAL_SNII; j <= STAR_METAL_SNII; j++) {
if (gi.SpeciesContained[j]) {
pbs->bin[BARYON_METAL_SNII].N += pbs->bin[j].N;
pbs->bin[BARYON_METAL_SNII].M += pbs->bin[j].M;
for (d = 0; d < 3; d++) {
pbs->bin[BARYON_METAL_SNII].v[d] += pbs->bin[j].v[d];
pbs->bin[BARYON_METAL_SNII].L[d] += pbs->bin[j].L[d];
}
for (d = 0; d < 6; d++) {
pbs->bin[BARYON_METAL_SNII].vdt[d] += pbs->bin[j].vdt[d];
}
} /* if SpeciesContained */
} /* for METAL_SNII */
for (j = GAS_METAL_SNIa; j <= STAR_METAL_SNIa; j++) {
if (gi.SpeciesContained[j]) {
pbs->bin[BARYON_METAL_SNIa].N += pbs->bin[j].N;
pbs->bin[BARYON_METAL_SNIa].M += pbs->bin[j].M;
for (d = 0; d < 3; d++) {
pbs->bin[BARYON_METAL_SNIa].v[d] += pbs->bin[j].v[d];
pbs->bin[BARYON_METAL_SNIa].L[d] += pbs->bin[j].L[d];
}
for (d = 0; d < 6; d++) {
pbs->bin[BARYON_METAL_SNIa].vdt[d] += pbs->bin[j].vdt[d];
}
} /* if SpeciesContained */
} /* for METAL_SNIa */
} /* if DoMetalSpecies */
} /* for n[2] */
} /* for n[1] */
} /* for n[0] */
} /* for NHalo */
}
int diagonalise_matrix(double min[3][3], double *evala, double eveca[3], double *evalb, double evecb[3], double *evalc, double evecc[3]) {
int i, j, N;
int status1, status2;
double x, y, z;
double data[9];
gsl_matrix_view m;
gsl_vector *eval;
gsl_matrix *evec;
gsl_eigen_symmv_workspace *w;
N = 0;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
data[N] = min[i][j];
N++;
}
}
m = gsl_matrix_view_array(data,3,3);
eval = gsl_vector_alloc(3);
evec = gsl_matrix_alloc(3,3);
w = gsl_eigen_symmv_alloc(3);
status1 = gsl_eigen_symmv(&m.matrix,eval,evec,w);
status2 = gsl_eigen_symmv_sort(eval,evec,GSL_EIGEN_SORT_ABS_DESC);
if (status1) fprintf(stderr,"GSL error: %s\n",gsl_strerror(status1));
if (status2) fprintf(stderr,"GSL error: %s\n",gsl_strerror(status2));
*evala = gsl_vector_get(eval,0);
eveca[0] = gsl_matrix_get(evec,0,0);
eveca[1] = gsl_matrix_get(evec,1,0);
eveca[2] = gsl_matrix_get(evec,2,0);
*evalb = gsl_vector_get(eval,1);
evecb[0] = gsl_matrix_get(evec,0,1);
evecb[1] = gsl_matrix_get(evec,1,1);
evecb[2] = gsl_matrix_get(evec,2,1);
*evalc = gsl_vector_get(eval,2);
evecc[0] = gsl_matrix_get(evec,0,2);
evecc[1] = gsl_matrix_get(evec,1,2);
evecc[2] = gsl_matrix_get(evec,2,2);
gsl_vector_free(eval);
gsl_matrix_free(evec);
gsl_eigen_symmv_free(w);
/*
** Check for right-handedness and orientation
*/
if (eveca[0] < 0) {
eveca[0] *= -1;
eveca[1] *= -1;
eveca[2] *= -1;
}
if (evecb[1] < 0) {
evecb[0] *= -1;
evecb[1] *= -1;
evecb[2] *= -1;
}
x = eveca[1]*evecb[2] - eveca[2]*evecb[1];
y = eveca[2]*evecb[0] - eveca[0]*evecb[2];
z = eveca[0]*evecb[1] - eveca[1]*evecb[0];
if (x*evecc[0] + y*evecc[1] + z*evecc[2] < 0) {
evecc[0] *= -1;
evecc[1] *= -1;
evecc[2] *= -1;
}
return status1+status2;
}
double diagonalise_shape_tensors(GI gi, HALO_DATA *hd, int ILoop) {
int d, n[3], i, j;
int status;
int Ntot, Nconverged;
double m[3][3];
double evala, evalb, evalc;
double eveca[3], evecb[3], evecc[3];
const double ex[3] = {1,0,0};
const double ey[3] = {0,1,0};
const double ez[3] = {0,0,1};
double sp, ec[3];
double re_b_a, re_c_a;
PROFILE_SHAPE_PROPERTIES *shape;
Ntot = 0;
Nconverged = 0;
for (i = 0; i < gi.NHalo; i++) {
/*
** Go from outside inwards for the alignment
*/
for (n[0] = hd[i].NBin[0]-1; n[0] >= 0; n[0]--) {
n[1] = 0;
n[2] = 0;
for (j = 0; j < gi.NSpeciesProfile; j++) {
if (gi.SpeciesContained[j]) {
shape = &hd[i].pbs[n[0]][n[1]][n[2]].shape[j];
if (shape->NLoopConverged == 0) {
Ntot++;
shape->b_a_old = shape->b_a;
shape->c_a_old = shape->c_a;
/*
** Calculate shape
*/
if (shape->N > 2) {
/*
** Only calculate a shape if there are at least 3 particles
*/
assert(shape->M > 0);
m[0][0] = shape->st[0]/shape->M;
m[1][1] = shape->st[1]/shape->M;
m[2][2] = shape->st[2]/shape->M;
m[0][1] = shape->st[3]/shape->M;
m[0][2] = shape->st[4]/shape->M;
m[1][2] = shape->st[5]/shape->M;
m[1][0] = m[0][1];
m[2][0] = m[0][2];
m[2][1] = m[1][2];
status = diagonalise_matrix(m,&evala,eveca,&evalb,evecb,&evalc,evecc);
if (status) fprintf(stderr,"This was halo ID %d Bin %d\n",hd[i].ID,n[0]);
shape->b_a = sqrt(evalb/evala);
shape->c_a = sqrt(evalc/evala);
for (d = 0; d < 3; d++) {
shape->a[d] = eveca[d];
shape->b[d] = evecb[d];
shape->c[d] = evecc[d];
}
}
else {
if (n[0] == hd[i].NBin[0]-1) {
/*
** Set values for sphere
*/
shape->b_a = 1;
shape->c_a = 1;
for (d = 0; d < 3; d++) {
shape->a[d] = ex[d];
shape->b[d] = ey[d];
shape->c[d] = ez[d];
}
}
else {
/*
** Copy values from outer bin
*/
shape->b_a = hd[i].pbs[n[0]+1][n[1]][n[2]].shape[j].b_a;
shape->c_a = hd[i].pbs[n[0]+1][n[1]][n[2]].shape[j].c_a;
for (d = 0; d < 3; d++) {
shape->a[d] = hd[i].pbs[n[0]+1][n[1]][n[2]].shape[j].a[d];
shape->b[d] = hd[i].pbs[n[0]+1][n[1]][n[2]].shape[j].b[d];
shape->c[d] = hd[i].pbs[n[0]+1][n[1]][n[2]].shape[j].c[d];
}
}
}
/*
** Align orientation
*/
if (n[0] < hd[i].NBin[0]-1) {
sp = 0;
for (d = 0; d < 3; d++) sp += shape->a[d]*hd[i].pbs[n[0]+1][n[1]][n[2]].shape[j].a[d];
if (sp < 0) {
for (d = 0; d < 3; d++) shape->a[d] *= -1;
}
sp = 0;
for (d = 0; d < 3; d++) sp += shape->b[d]*hd[i].pbs[n[0]+1][n[1]][n[2]].shape[j].b[d];
if (sp < 0) {
for (d = 0; d < 3; d++) shape->b[d] *= -1;
}
ec[0] = shape->a[1]*shape->b[2] - shape->a[2]*shape->b[1];
ec[1] = shape->a[2]*shape->b[0] - shape->a[0]*shape->b[2];
ec[2] = shape->a[0]*shape->b[1] - shape->a[1]*shape->b[0];
sp = 0;
for (d = 0; d < 3; d++) sp += ec[d]*shape->c[d];
if (sp < 0) {
for (d = 0; d < 3; d++) shape->c[d] *= -1;
}
}
/*
** Check if already converged
*/
re_b_a = (shape->b_a-shape->b_a_old)/shape->b_a_old;
re_c_a = (shape->c_a-shape->c_a_old)/shape->c_a_old;
if (fabs(re_b_a) <= gi.ShapeIterationTolerance && fabs(re_c_a) <= gi.ShapeIterationTolerance && shape->N > 2) {
Nconverged++;
shape->NLoopConverged = ILoop;
}
}
else {
Ntot++;
Nconverged++;
}
} /* if SpeciesContained */
} /* for NSpeciesProfile */
} /* for NBin[0] */
} /* for NHalo */
return (double)Nconverged/(double)Ntot;
}
void calculate_halo_properties(GI gi, HALO_DATA *hd) {
int i;
#pragma omp parallel for default(none) private(i) shared(gi,hd)
for (i = 0; i < gi.NHalo; i++) {
/*
** Calculate derived properties
*/
calculate_derived_properties(gi,&hd[i]);
/*
** Calculate overdensity characteristics
*/
calculate_overdensity_characteristics(gi,&hd[i]);
/*
** Calculate truncation of halo
*/
calculate_truncation_characteristics(gi,&hd[i]);
/*
** Remove background
** Attention: Numbers and velocities not correct any more!
*/
remove_background(gi,&hd[i]);
/*
** Calculate size & mass
*/
calculate_halo_size(gi,&hd[i]);
/*
** Calculate velocity characteristics
*/
calculate_velocity_characteristics(gi,&hd[i]);
}
}
void calculate_derived_properties(GI gi, HALO_DATA *hd) {
int d, n[3], j;
PROFILE_BIN_PROPERTIES *bin;
for (n[0] = 0; n[0] < hd->NBin[0]; n[0]++) {
for (n[1] = 0; n[1] < hd->NBin[1]; n[1]++) {
for (n[2] = 0; n[2] < hd->NBin[2]; n[2]++) {
for (j = 0; j < gi.NSpeciesProfile; j++) {
if (gi.SpeciesContained[j]) {
bin = &hd->pbs[n[0]][n[1]][n[2]].bin[j];
for (d = 0; d < 3; d++) {
if (bin->M > 0) bin->v[d] /= bin->M;
}
for (d = 0; d < 6; d++) {
if (bin->M > 0) bin->vdt[d] /= bin->M;
}
if (bin->N > 1) {
for (d = 0; d < 3; d++) bin->vdt[d] -= pow(bin->v[d],2);
bin->vdt[3] -= bin->v[0]*bin->v[1];
bin->vdt[4] -= bin->v[0]*bin->v[2];
bin->vdt[5] -= bin->v[1]*bin->v[2];
}
else {
for (d = 0; d < 6; d++) bin->vdt[d] = 0;
}
for (d = 0; d <= n[0]; d++) {
bin->Menc[0] += hd->pbs[d][n[1]][n[2]].bin[j].M;
}
bin->Menc[1] = bin->Menc[0];
if (j < gi.NSpeciesRead) {
for (d = 0; d < gi.NProperties[j]; d++) {
if (bin->M > 0) bin->P[d] /= bin->M;
}
}
}
}
}
}
}
}
void calculate_overdensity_characteristics(GI gi, HALO_DATA *hd) {
int n[3], j;
int Ncheck, Scheck;
double rscale[3], Mrscale[3], rhoencscale[3];
double radius[2], rhoenc[2], Menc[2], Venc[2];
double minter, dinter, rcheck, Mrcheck;
double rminok;
for (j = 0; j < 3; j++) {
rscale[j] = 0;
Mrscale[j] = 0;
}
rhoencscale[0] = gi.rhoencmean;
rhoencscale[1] = gi.rhoenccrit;
rhoencscale[2] = gi.rhoencfix;
rminok = gi.rExclude;
/*
** Search from inside out!
*/
for (n[0] = 1; n[0] < hd->NBin[0]; n[0]++) {
n[1] = 0;
n[2] = 0;
radius[0] = hd->pbs[n[0]-1][n[1]][n[2]].ro[0];
radius[1] = hd->pbs[n[0]][n[1]][n[2]].ro[0];
Venc[0] = 4*M_PI*pow(radius[0],3)/3.0;
Venc[1] = 4*M_PI*pow(radius[1],3)/3.0;
Menc[0] = hd->pbs[n[0]-1][n[1]][n[2]].bin[TOT].Menc[0];
Menc[1] = hd->pbs[n[0]][n[1]][n[2]].bin[TOT].Menc[0];
rhoenc[0] = Menc[0]/Venc[0];
rhoenc[1] = Menc[1]/Venc[1];
for (j = 0; j < 3; j++) {
if (rhoenc[0] >= rhoencscale[j] && rhoenc[1] < rhoencscale[j] && rscale[j] == 0) {
minter = (log(radius[1])-log(radius[0]))/(log(rhoenc[1])-log(rhoenc[0]));
dinter = log(rhoencscale[j])-log(rhoenc[0]);
rcheck = exp(log(radius[0])+minter*dinter);
minter = (log(Menc[1])-log(Menc[0]))/(log(radius[1])-log(radius[0]));
dinter = log(rcheck)-log(radius[0]);
Mrcheck = exp(log(Menc[0])+minter*dinter);
if (rcheck >= rminok) {
rscale[j] = rcheck;
Mrscale[j] = Mrcheck;
assert(rscale[j] > 0);
assert(Mrscale[j] > 0);
}
} /* if */
} /* for j */
/*
** Check if all overdensity scales have been found already
*/
Ncheck = 0;
Scheck = 0;
for (j = 0; j < 3; j++) {
Ncheck++;
if (rscale[j] > 0) Scheck++;
}
if (Scheck == Ncheck) break;
} /* for n[0] */
hd->rmean = rscale[0];
hd->rcrit = rscale[1];
hd->rfix = rscale[2];
hd->Mrmean = Mrscale[0];
hd->Mrcrit = Mrscale[1];
hd->Mrfix = Mrscale[2];
}
/*
** Indicator: local minimum in enclosed density at scales larger than rminok
** i.e. bump is significant enough to cause a minimum or saddle in enclosed density
** => in practise use the location where the value of slopertruncindicator is reached
*/
void calculate_truncation_characteristics(GI gi, HALO_DATA *hd) {
int n[3], j;
int StartIndex;
double radius[2], logslope[2], Menc[2];
double minter, dinter, rcheck, V;
double rho[NSPECIESBACKGROUND], rhomin[NSPECIESBACKGROUND];
double slope;
double rminok;
slope = 3 + gi.slopertruncindicator;
rminok = gi.rExclude;
StartIndex = -1;
/*
** Search from inside out!
*/
for (n[0] = 2; n[0] < hd->NBin[0]; n[0]++) {
n[1] = 0;
n[2] = 0;
radius[0] = hd->pbs[n[0]-1][n[1]][n[2]].rm[0];
radius[1] = hd->pbs[n[0]][n[1]][n[2]].rm[0];
if (hd->pbs[n[0]-2][n[1]][n[2]].bin[TOT].Menc[0] > 0) {
logslope[0] = log(hd->pbs[n[0]-1][n[1]][n[2]].bin[TOT].Menc[0])-log(hd->pbs[n[0]-2][n[1]][n[2]].bin[TOT].Menc[0]);
logslope[1] = log(hd->pbs[n[0]][n[1]][n[2]].bin[TOT].Menc[0])-log(hd->pbs[n[0]-1][n[1]][n[2]].bin[TOT].Menc[0]);
}
else {
logslope[0] = 0;
logslope[1] = 0;
}
logslope[0] /= log(hd->pbs[n[0]-1][n[1]][n[2]].ro[0])-log(hd->pbs[n[0]-2][n[1]][n[2]].ro[0]);
logslope[1] /= log(hd->pbs[n[0]][n[1]][n[2]].ro[0])-log(hd->pbs[n[0]-1][n[1]][n[2]].ro[0]);
if (logslope[0] <= slope && logslope[1] > slope && hd->rtruncindicator == 0) {
minter = (log(radius[1])-log(radius[0]))/(logslope[1]-logslope[0]);
dinter = slope-logslope[0];
rcheck = exp(log(radius[0])+minter*dinter);
if (rcheck >= rminok && hd->pbs[n[0]-1][n[1]][n[2]].bin[TOT].M > 0) {
StartIndex = n[0];
hd->rtruncindicator = rcheck;
assert(hd->rtruncindicator > 0);
}
}
if (hd->rtruncindicator > 0) break;
}
/*
** Now determine rtrunc
** We define the location of the absolute minimum (within specified range of frhobg)
** of the local density within rtruncindicator as rtrunc
*/
if (StartIndex > 0) {
for (j = 0; j < NSPECIESBACKGROUND; j++) rhomin[j] = 1e100;
for (n[0] = StartIndex; n[0] > 0; n[0]--) {
n[1] = 0;
n[2] = 0;
V = 4*M_PI*(pow(hd->pbs[n[0]][n[1]][n[2]].ro[0],3)-pow(hd->pbs[n[0]][n[1]][n[2]].ri[0],3))/3.0;
for (j = 0; j < 5; j++) rho[j] = (gi.SpeciesContained[j])?hd->pbs[n[0]][n[1]][n[2]].bin[j].M/V:0;
if (rho[TOT] < gi.frhobg*rhomin[TOT] && rho[TOT] > 0 && hd->pbs[n[0]-1][n[1]][n[2]].bin[TOT].Menc[0] > 0 && hd->pbs[n[0]][n[1]][n[2]].rm[0] >= rminok) {
for (j = 0; j < NSPECIESBACKGROUND; j++) {
if (rho[j] < rhomin[j] && rho[j] > 0 && gi.SpeciesContained[j]) rhomin[j] = rho[j];
}
hd->rtrunc = hd->pbs[n[0]][n[1]][n[2]].rm[0];
assert(hd->rtrunc > 0);
radius[0] = hd->pbs[n[0]-1][n[1]][n[2]].ro[0];
radius[1] = hd->pbs[n[0]][n[1]][n[2]].ro[0];
Menc[0] = hd->pbs[n[0]-1][n[1]][n[2]].bin[TOT].Menc[0];
Menc[1] = hd->pbs[n[0]][n[1]][n[2]].bin[TOT].Menc[0];
minter = (log(Menc[1])-log(Menc[0]))/(log(radius[1])-log(radius[0]));
dinter = log(hd->rtrunc)-log(radius[0]);
hd->Mrtrunc = exp(log(Menc[0])+minter*dinter);
assert(hd->Mrtrunc > 0);
for (j = 0; j < NSPECIESBACKGROUND; j++) {
if (gi.SpeciesContained[j]) {
if (rho[j] > 0 && rhomin[j] != 1e100) hd->rhobg[j] = 0.5*(rho[j]+rhomin[j]);
else if (rho[j] == 0 && rhomin[j] != 1e100) hd->rhobg[j] = rhomin[j];
}
}
}
}
}
}
void remove_background(GI gi, HALO_DATA *hd) {
int n[3], j;
double Venc;
if (hd->rtrunc > 0) {
hd->Mrtrunc -= hd->rhobg[TOT]*4*M_PI*pow(hd->rtrunc,3)/3.0;
if (hd->Mrtrunc > 0) {
/*
** Calculate enclosed mass with background removed
*/
for (n[0] = 0; n[0] < hd->NBin[0]; n[0]++) {
n[1] = 0;
n[2] = 0;
Venc = 4*M_PI*pow(hd->pbs[n[0]][n[1]][n[2]].ro[0],3)/3.0;
for (j = 0; j < NSPECIESBACKGROUND; j++) {
if(gi.SpeciesContained[j]) hd->pbs[n[0]][n[1]][n[2]].bin[j].Menc[1] -= hd->rhobg[j]*Venc;
}
}
}
else {
/*
** Unphysical truncation scale found
** => probably noisy profile
*/
hd->rtrunc = 0;
hd->Mrtrunc = 0;
}
}
}
void calculate_halo_size(GI gi, HALO_DATA *hd) {
if (gi.HaloSize == 0) {
hd->size = hd->rmean;
hd->mass = hd->Mrmean;
}
else if (gi.HaloSize == 1) {
hd->size = hd->rcrit;
hd->mass = hd->Mrcrit;
}
else if (gi.HaloSize == 2) {
hd->size = hd->rfix;
hd->mass = hd->Mrfix;
}
if (hd->rtrunc > 0 && (hd->rtrunc < hd->size || hd->size == 0)) {
hd->IsTruncated = 1;
hd->size = hd->rtrunc;
hd->mass = hd->Mrtrunc;
}
}
void calculate_velocity_characteristics(GI gi, HALO_DATA *hd) {
int n[3], j, k, l;
int Ncheck, Scheck;
double rscale[NSPECIESBACKGROUND][2], Mrscale[NSPECIESBACKGROUND][2];
double radius[2], logslope[2], Menc[2];
double minter, dinter, rcheck, Mrcheck, Qcheck, Qcomp;
double slope;
slope = 1;
for (j = 0; j < NSPECIESBACKGROUND; j++) {
for (l = 0; l < 2; l++) {
rscale[j][l] = 0;
Mrscale[j][l] = 0;
}
}
n[1] = 0;
n[2] = 0;
for (n[0] = 2; n[0] < hd->NBin[0]; n[0]++) {
for (j = 0; j < NSPECIESBACKGROUND; j++) {
for (l = 0; l < 2; l++) {
radius[0] = hd->pbs[n[0]-1][n[1]][n[2]].rm[0];
radius[1] = hd->pbs[n[0]][n[1]][n[2]].rm[0];
if (hd->pbs[n[0]-2][n[1]][n[2]].bin[j].Menc[l] > 0) {
logslope[0] = (log(hd->pbs[n[0]-1][n[1]][n[2]].bin[j].Menc[l])-log(hd->pbs[n[0]-2][n[1]][n[2]].bin[j].Menc[l]));
logslope[1] = (log(hd->pbs[n[0]][n[1]][n[2]].bin[j].Menc[l])-log(hd->pbs[n[0]-1][n[1]][n[2]].bin[j].Menc[l]));
}
else {
logslope[0] = 0;
logslope[1] = 0;
}
logslope[0] /= log(hd->pbs[n[0]-1][n[1]][n[2]].ro[0])-log(hd->pbs[n[0]-2][n[1]][n[2]].ro[0]);
logslope[1] /= log(hd->pbs[n[0]][n[1]][n[2]].ro[0])-log(hd->pbs[n[0]-1][n[1]][n[2]].ro[0]);
if (logslope[0] >= slope && logslope[1] < slope) {
minter = (log(radius[1])-log(radius[0]))/(logslope[1]-logslope[0]);
dinter = slope-logslope[0];
rcheck = exp(log(radius[0])+minter*dinter);
if (rcheck <= hd->pbs[n[0]-1][n[1]][n[2]].ro[0]) {
radius[0] = hd->pbs[n[0]-2][n[1]][n[2]].ro[0];
radius[1] = hd->pbs[n[0]-1][n[1]][n[2]].ro[0];
Menc[0] = hd->pbs[n[0]-2][n[1]][n[2]].bin[j].Menc[l];
Menc[1] = hd->pbs[n[0]-1][n[1]][n[2]].bin[j].Menc[l];
}
else {
radius[0] = hd->pbs[n[0]-1][n[1]][n[2]].ro[0];
radius[1] = hd->pbs[n[0]][n[1]][n[2]].ro[0];
Menc[0] = hd->pbs[n[0]-1][n[1]][n[2]].bin[j].Menc[l];
Menc[1] = hd->pbs[n[0]][n[1]][n[2]].bin[j].Menc[l];
}
minter = (log(Menc[1])-log(Menc[0]))/(log(radius[1])-log(radius[0]));
dinter = log(rcheck)-log(radius[0]);
Mrcheck = exp(log(Menc[0])+minter*dinter);
/*
** Check criteria
*/
Qcheck = Mrcheck/rcheck;
Ncheck = 0;
Scheck = 0;
for (k = n[0]; k < hd->NBin[0] && hd->pbs[k][n[1]][n[2]].ro[0] <= gi.fcheckrvcmax*rcheck; k++) {
Ncheck++;
Qcomp = hd->pbs[k][n[1]][n[2]].bin[j].Menc[l];
Qcomp /= hd->pbs[k][n[1]][n[2]].ro[0];
if (Qcheck >= Qcomp) Scheck++;
}
if (Scheck == Ncheck) {
/*
** The circular velocity curve is generally nicely behaving
** => for the first local maximum there is no size restriction (sometimes halos have rvcmax around size)
** => if more than one local maximum => take the highest local maximum within the size of the halo
** => avoid peaks in the outer parts of the halo
*/
if (rscale[j][l] == 0) {
rscale[j][l] = rcheck;
Mrscale[j][l] = Mrcheck;
}
else if (Mrcheck/rcheck > Mrscale[j][l]/rscale[j][l] && rcheck <= hd->size) {
rscale[j][l] = rcheck;
Mrscale[j][l] = Mrcheck;
}
assert(rscale[j][l] > 0);
assert(Mrscale[j][l] > 0);
}
} /* if logslope */
} /* for l */
} /* for j */
} /* for n[0] */
for (j = 0; j < NSPECIESBACKGROUND; j++) {
for (l = 0; l < 2; l++) {
hd->rvcmax[j][l] = rscale[j][l];
hd->Mrvcmax[j][l] = Mrscale[j][l];
}
}
}
void determine_halo_hierarchy(GI gi, HALO_DATA *hd) {
int i, j, k;
int index[3];
int index0, index1, index2;
int ***HeadIndex, *NextIndex;
double r[3], shift[3];
double d, size, sizeother, *sizecomp;
/*
** Initialise linked list stuff
*/
HeadIndex = malloc(gi.NCellHalo*sizeof(int **));
assert(HeadIndex != NULL);
for (i = 0; i < gi.NCellHalo; i ++) {
HeadIndex[i] = malloc(gi.NCellHalo*sizeof(int *));
assert(HeadIndex[i] != NULL);
for (j = 0; j < gi.NCellHalo; j++) {
HeadIndex[i][j] = malloc(gi.NCellHalo*sizeof(int));
assert(HeadIndex[i][j] != NULL);
}
}
NextIndex = malloc(gi.NHalo*sizeof(int));
assert(NextIndex != NULL);
for (i = 0; i < gi.NCellHalo; i++) {
for (j = 0; j < gi.NCellHalo; j++) {
for (k = 0; k < gi.NCellHalo; k++) {
HeadIndex[i][j][k] = -1;
}
}
}
for (i = 0; i < gi.NHalo; i++) NextIndex[i] = -1;
for (i = 0; i < 3; i++) shift[i] = 0-gi.bc[i];
/*
** Generate linked list
*/
for (i = 0; i < gi.NHalo; i++) {
for (j = 0; j < 3; j++) {
index[j] = (int)(gi.NCellHalo*(hd[i].rcentre[j]+shift[j])/gi.us.LBox);
if (index[j] == gi.NCellHalo) index[j] = gi.NCellHalo-1; /* Case where haloes are exactly on the boundary */
assert(index[j] >= 0 && index[j] < gi.NCellHalo);
}
NextIndex[i] = HeadIndex[index[0]][index[1]][index[2]];
HeadIndex[index[0]][index[1]][index[2]] = i;
}
/*
** Find top level haloes
*/
sizecomp = malloc(gi.NHalo*sizeof(double));
assert(sizecomp != NULL);
for (i = 0; i < gi.NHalo; i++) sizecomp[i] = 0;
for (i = 0; i < gi.NHalo; i++) {
size = hd[i].size;
/*
** Go through linked list
*/
#pragma omp parallel for default(none) private(index,index0,index1,index2,j,k,r,d) shared(gi,hd,i,size,sizecomp,shift,HeadIndex,NextIndex)
for (index0 = 0; index0 < gi.NCellHalo; index0++) {
for (index1 = 0; index1 < gi.NCellHalo; index1++) {
for (index2 = 0; index2 < gi.NCellHalo; index2++) {
index[0] = index0;
index[1] = index1;
index[2] = index2;
if (intersect(gi.us.LBox,gi.NCellHalo,hd[i],index,shift,size)) {
j = HeadIndex[index[0]][index[1]][index[2]];
while (j >= 0) {
if (j != i) {
for (k = 0; k < 3; k++) {
r[k] = correct_position(hd[i].rcentre[k],hd[j].rcentre[k],gi.us.LBox);
r[k] = r[k] - hd[i].rcentre[k];
}
d = sqrt(r[0]*r[0]+r[1]*r[1]+r[2]*r[2]);
if (d <= size) {
/*
** contained => use largest sized halo
*/
if (size > sizecomp[j]) {
sizecomp[j] = size;
hd[j].HostHaloID = hd[i].ID;
}
}
}
j = NextIndex[j];
}
}
}
}
}
}
/*
** Find duplicates and mergers
*/
#pragma omp parallel for default(none) private(i,j,k,r,d,size,sizeother) shared(gi,hd)
for (i = 0; i < gi.NHalo; i++) {
for (j = i+1; j < gi.NHalo; j++) {
if (hd[i].HostHaloID == hd[j].ID && hd[j].HostHaloID == hd[i].ID) {
/*
** Found a pair
*/
for (k = 0; k < 3; k++) {
r[k] = correct_position(hd[i].rcentre[k],hd[j].rcentre[k],gi.us.LBox);
r[k] = r[k] - hd[i].rcentre[k];
}
d = sqrt(r[0]*r[0]+r[1]*r[1]+r[2]*r[2]);
size = hd[i].size;
sizeother = hd[j].size;
/*
** Check if the pair is close enough
*/
if (d <= gi.fhaloduplicate*(0.5*(size+sizeother))) {
/*
** Found a duplicate
*/
if (size >= sizeother) {
hd[j].ExtraHaloID = hd[i].ID;
hd[i].HostHaloID = -1;
for (k = 0; k < gi.NHalo; k++) {
if (hd[k].HostHaloID == hd[j].ID) hd[k].HostHaloID = hd[i].ID;
}
}
else {
hd[i].ExtraHaloID = hd[j].ID;
hd[j].HostHaloID = -1;
for (k = 0; k < gi.NHalo; k++) {
if (hd[k].HostHaloID == hd[i].ID) hd[k].HostHaloID = hd[j].ID;
}
}
}
else {
/*
** Probably a merger
*/
hd[i].HostHaloID = -1;
hd[j].HostHaloID = -1;
hd[i].ExtraHaloID = hd[j].ID;
hd[j].ExtraHaloID = hd[i].ID;
}
}
}
}
free(sizecomp);
for (i = 0; i < gi.NCellHalo; i ++) {
for (j = 0; j < gi.NCellHalo; j++) {
free(HeadIndex[i][j]);
}
free(HeadIndex[i]);
}
free(HeadIndex);
free(NextIndex);
}
void write_output_matter_profile(GI gi, HALO_DATA *hd) {
int d, n[3], i, j, k, l;
int NBinMax[3] = {0,0,0};
char outputfilename[256];
FILE *outputfile;
PROFILE_BIN_PROPERTIES *bin;
/*
** Characteristics
*/
if (gi.BinningCoordinateType == 0 && gi.NDimProfile == 1) sprintf(outputfilename,"%s.profile.sph.d1.characteristics",gi.OutputName);
else if (gi.BinningCoordinateType == 1 && gi.NDimProfile == 1) sprintf(outputfilename,"%s.profile.cyl.d1.characteristics",gi.OutputName);
else if (gi.BinningCoordinateType == 1 && gi.NDimProfile == 2) sprintf(outputfilename,"%s.profile.cyl.d2.characteristics",gi.OutputName);
outputfile = fopen(outputfilename,"w");
assert(outputfile != NULL);
fprintf(outputfile,"#ID/1 r_x/2 r_y/3 r_z/4 v_x/5 v_y/6 v_z/7");
k = 8;
for (d = 0; d < gi.NDimProfile; d++) {
fprintf(outputfile," rmin_%d/%d rmax_%d/%d NBin_%d/%d",d+1,k,d+1,k+1,d+1,k+2); k += 3;
}
if (gi.BinningCoordinateType == 0) {
fprintf(outputfile," size/%d mass/%d",k,k+1); k += 2;
fprintf(outputfile," rvcmax_tot/%d Mrvcmax_tot/%d",k,k+1); k += 2;
fprintf(outputfile," rvcmax_dark/%d Mrvcmax_dark/%d",k,k+1); k += 2;
fprintf(outputfile," IsTruncated/%d HostHaloID/%d ExtraHaloID/%d",k,k+1,k+2); k += 3;
if (gi.MoreCharacteristicsOutput) {
fprintf(outputfile," rmean/%d Mrmean/%d",k,k+1); k += 2;
fprintf(outputfile," rcrit/%d Mrcrit/%d",k,k+1); k += 2;
fprintf(outputfile," rfix/%d Mrfix/%d",k,k+1); k += 2;
fprintf(outputfile," rtrunc/%d Mrtrunc/%d",k,k+1); k += 2;
fprintf(outputfile," rvcmax_tot/%d Mrvcmax_tot/%d rvcmax_tottrunc/%d Mrvcmax_tottrunc/%d",k,k+1,k+2,k+3); k += 4;
fprintf(outputfile," rvcmax_dark/%d Mrvcmax_dark/%d rvcmax_darktrunc/%d Mrvcmax_darktrunc/%d",k,k+1,k+2,k+3); k += 4;
fprintf(outputfile," rhobg_tot/%d rhobg_gas/%d rhobg_dark/%d rhobg_star/%d rhobg_baryon/%d",k,k+1,k+2,k+3,k+4); k += 5;
fprintf(outputfile," rtruncindicator/%d",k);
}
}
else if (gi.BinningCoordinateType == 1) {
fprintf(outputfile," zAxis_x/%d zAxis_y/%d zAxis_z/%d zHeight/%d",k,k+1,k+2,k+3);
}
fprintf(outputfile,"\n");
for (i = 0; i < gi.NHalo; i++) {
fprintf(outputfile,"%d",hd[i].ID);
fprintf(outputfile," %.6e %.6e %.6e",hd[i].rcentre[0],hd[i].rcentre[1],hd[i].rcentre[2]);
fprintf(outputfile," %.6e %.6e %.6e",hd[i].vcentre[0],hd[i].vcentre[1],hd[i].vcentre[2]);
for (d = 0; d < gi.NDimProfile; d++) fprintf(outputfile," %.6e %.6e %d",hd[i].rmin[d],hd[i].rmax[d],hd[i].NBin[d]);
if (gi.BinningCoordinateType == 0) {
fprintf(outputfile," %.6e %.6e",hd[i].size,hd[i].mass);
l = hd[i].IsTruncated;
fprintf(outputfile," %.6e %.6e",hd[i].rvcmax[TOT][l],hd[i].Mrvcmax[TOT][l]);
fprintf(outputfile," %.6e %.6e",hd[i].rvcmax[DARK][l],hd[i].Mrvcmax[DARK][l]);
fprintf(outputfile," %d %d %d",hd[i].IsTruncated,hd[i].HostHaloID,hd[i].ExtraHaloID);
if (gi.MoreCharacteristicsOutput) {
fprintf(outputfile," %.6e %.6e",hd[i].rmean,hd[i].Mrmean);
fprintf(outputfile," %.6e %.6e",hd[i].rcrit,hd[i].Mrcrit);
fprintf(outputfile," %.6e %.6e",hd[i].rfix,hd[i].Mrfix);
fprintf(outputfile," %.6e %.6e",hd[i].rtrunc,hd[i].Mrtrunc);
fprintf(outputfile," %.6e %.6e %.6e %.6e",hd[i].rvcmax[TOT][0],hd[i].Mrvcmax[TOT][0],hd[i].rvcmax[TOT][1],hd[i].Mrvcmax[TOT][1]);
fprintf(outputfile," %.6e %.6e %.6e %.6e",hd[i].rvcmax[DARK][0],hd[i].Mrvcmax[DARK][0],hd[i].rvcmax[DARK][1],hd[i].Mrvcmax[DARK][1]);
fprintf(outputfile," %.6e %.6e %.6e %.6e %.6e",hd[i].rhobg[TOT],hd[i].rhobg[GAS],hd[i].rhobg[DARK],hd[i].rhobg[STAR],hd[i].rhobg[BARYON]);
fprintf(outputfile," %.6e",hd[i].rtruncindicator);
}
}
else if (gi.BinningCoordinateType == 1) {
fprintf(outputfile," %.6e %.6e %.6e %.6e",hd[i].zAxis[0],hd[i].zAxis[1],hd[i].zAxis[2],hd[i].zHeight);
}
fprintf(outputfile,"\n");
}
fclose(outputfile);
/*
** Matter profiles
*/
for (j = 0; j < gi.NSpeciesProfile; j++) {
if (gi.SpeciesContained[j]) {
n[2] = 0;
for (i = 0; i < gi.NHalo; i++) NBinMax[1] = (hd[i].NBin[1]>NBinMax[1])?hd[i].NBin[1]:NBinMax[1];
for (n[1] = 0; n[1] < NBinMax[1]; n[1]++) {
if (gi.BinningCoordinateType == 0 && gi.NDimProfile == 1) {
assert(n[1] == 0);
sprintf(outputfilename,"%s.profile.sph.d1.pro.%s",gi.OutputName,gi.MatterTypeName[j]);
}
else if (gi.BinningCoordinateType == 1 && gi.NDimProfile == 1) {
assert(n[1] == 0);
sprintf(outputfilename,"%s.profile.cyl.d1.pro.%s",gi.OutputName,gi.MatterTypeName[j]);
}
else if (gi.BinningCoordinateType == 1 && gi.NDimProfile == 2) {
if (n[1] < NBinMax[1]/2) {
d = n[1]+1;
sprintf(outputfilename,"%s.profile.cyl.d2.p%03d.pro.%s",gi.OutputName,d,gi.MatterTypeName[j]);
}
else {
d = n[1]+1-NBinMax[1]/2;
sprintf(outputfilename,"%s.profile.cyl.d2.m%03d.pro.%s",gi.OutputName,d,gi.MatterTypeName[j]);
}
}
else {
sprintf(outputfilename,"garbage");
}
outputfile = fopen(outputfilename,"w");
assert(outputfile != NULL);
fprintf(outputfile,"#ID/1");
k = 2;
for (d = 0; d < gi.NDimProfile; d++) {
fprintf(outputfile," ri_%d/%d rm_%d/%d ro_%d/%d",d+1,k,d+1,k+1,d+1,k+2); k += 3;
}
fprintf(outputfile," M/%d N/%d",k,k+1); k += 2;
fprintf(outputfile," v_1/%d v_2/%d v_3/%d",k,k+1,k+2); k += 3;
fprintf(outputfile," vdt_11/%d vdt_22/%d vdt_33/%d vdt_12/%d vdt_13/%d vdt_23/%d",k,k+1,k+2,k+3,k+4,k+5); k += 6;
fprintf(outputfile," L_x/%d L_y/%d L_z/%d",k,k+1,k+2); k +=3;
if (j == GAS && gi.DoGasTemperature) fprintf(outputfile," T[K]/%d",k);
if (j == STAR && gi.DoStellarAge) fprintf(outputfile," Age/%d",k);
fprintf(outputfile,"\n");
for (i = 0; i < gi.NHalo; i++) {
for (n[0] = 0; n[0] < hd[i].NBin[0]; n[0]++) {
if (hd[i].NBin[1] <= n[1]) {
/*
** Less bins in 2. dimension for this halo than maximum of all haloes
** => just output 0
** Necessary to keep the file structure intact
*/
fprintf(outputfile,"%d",0);
for (d = 0; d < gi.NDimProfile; d++) {
fprintf(outputfile," %.6e %.6e %.6e",0.0,0.0,0.0);
}
fprintf(outputfile," %.6e %d",0.0,0);
for (d = 0; d < 3; d++) fprintf(outputfile," %.6e",0.0);
for (d = 0; d < 6; d++) fprintf(outputfile," %.6e",0.0);
for (d = 0; d < 3; d++) fprintf(outputfile," %.6e",0.0);
if (j == GAS && gi.DoGasTemperature) fprintf(outputfile," %.6e",0.0);
if (j == STAR && gi.DoStellarAge) fprintf(outputfile," %.6e",0.0);
fprintf(outputfile,"\n");
}
else {
bin = &hd[i].pbs[n[0]][n[1]][n[2]].bin[j];
fprintf(outputfile,"%d",hd[i].ID);
for (d = 0; d < gi.NDimProfile; d++) {
fprintf(outputfile," %.6e %.6e %.6e",hd[i].pbs[n[0]][n[1]][n[2]].ri[d],hd[i].pbs[n[0]][n[1]][n[2]].rm[d],hd[i].pbs[n[0]][n[1]][n[2]].ro[d]);
}
fprintf(outputfile," %.6e %ld",bin->M,bin->N);
for (d = 0; d < 3; d++) fprintf(outputfile," %.6e",bin->v[d]);
for (d = 0; d < 6; d++) fprintf(outputfile," %.6e",bin->vdt[d]);
for (d = 0; d < 3; d++) fprintf(outputfile," %.6e",bin->L[d]);
if (j == GAS && gi.DoGasTemperature) fprintf(outputfile," %.6e",bin->P[gi.pi[GAS][TEMPERATURE]-gi.NSubSpecies[GAS]]);
if (j == STAR && gi.DoStellarAge) fprintf(outputfile," %.6e",bin->P[gi.pi[STAR][AGE]-gi.NSubSpecies[STAR]]);
fprintf(outputfile,"\n");
}
} /* for n[0] */
} /* for NHalo */
fclose(outputfile);
} /* for n[1] */
} /* if SpeciesContained */
} /* for NSpeciesProfile */
}
void write_output_shape_profile(GI gi, HALO_DATA *hd, int ILoop) {
int d, n[3], i, j;
char outputfilename[256];
FILE *outputfile;
/*
** Characteristics
*/
sprintf(outputfilename,"%s.shape.%03d.characteristics",gi.OutputName,ILoop);
outputfile = fopen(outputfilename,"w");
assert(outputfile != NULL);
fprintf(outputfile,"#ID/1 r_x/2 r_y/3 r_z/4 v_x/5 v_y/6 v_z/7 rmin/8 rmax/9 NBin/10\n");
for (i = 0; i < gi.NHalo; i++) {
fprintf(outputfile,"%d",hd[i].ID);
fprintf(outputfile," %.6e %.6e %.6e",hd[i].rcentre[0],hd[i].rcentre[1],hd[i].rcentre[2]);
fprintf(outputfile," %.6e %.6e %.6e",hd[i].vcentre[0],hd[i].vcentre[1],hd[i].vcentre[2]);
fprintf(outputfile," %.6e %.6e",hd[i].rmin[0],hd[i].rmax[0]);
fprintf(outputfile," %d",hd[i].NBin[0]);
fprintf(outputfile,"\n");
}
fclose(outputfile);
/*
** Matter profiles
*/
for (j = 0; j < gi.NSpeciesProfile; j++) {
if (gi.SpeciesContained[j]) {
n[2] = 0;
n[1] = 0;
sprintf(outputfilename,"%s.shape.%03d.pro.%s",gi.OutputName,ILoop,gi.MatterTypeName[j]);
outputfile = fopen(outputfilename,"w");
assert(outputfile != NULL);
fprintf(outputfile,"#ID/1 ri/2 rm/3 ro/4 M/5 N/6 b:a/7 c:a/8 a_x/9 a_y/10 a_z/11 b_x/12 b_y/13 b_z/14 c_x/15 c_y/16 c_z/17 re_b:a/18 re_c:a/19 NLoopConverged/20\n");
for (i = 0; i < gi.NHalo; i++) {
for (n[0] = 0; n[0] < hd[i].NBin[0]; n[0]++) {
fprintf(outputfile,"%d",hd[i].ID);
fprintf(outputfile," %.6e %.6e %.6e",hd[i].pbs[n[0]][n[1]][n[2]].ri[0],hd[i].pbs[n[0]][n[1]][n[2]].rm[0],hd[i].pbs[n[0]][n[1]][n[2]].ro[0]);
fprintf(outputfile," %.6e %ld",hd[i].pbs[n[0]][n[1]][n[2]].shape[j].M,hd[i].pbs[n[0]][n[1]][n[2]].shape[j].N);
fprintf(outputfile," %.6e %.6e",hd[i].pbs[n[0]][n[1]][n[2]].shape[j].b_a,hd[i].pbs[n[0]][n[1]][n[2]].shape[j].c_a);
for (d = 0; d < 3; d++) fprintf(outputfile," %.6e",hd[i].pbs[n[0]][n[1]][n[2]].shape[j].a[d]);
for (d = 0; d < 3; d++) fprintf(outputfile," %.6e",hd[i].pbs[n[0]][n[1]][n[2]].shape[j].b[d]);
for (d = 0; d < 3; d++) fprintf(outputfile," %.6e",hd[i].pbs[n[0]][n[1]][n[2]].shape[j].c[d]);
fprintf(outputfile," %.6e",(hd[i].pbs[n[0]][n[1]][n[2]].shape[j].b_a/hd[i].pbs[n[0]][n[1]][n[2]].shape[j].b_a_old)-1);
fprintf(outputfile," %.6e",(hd[i].pbs[n[0]][n[1]][n[2]].shape[j].c_a/hd[i].pbs[n[0]][n[1]][n[2]].shape[j].c_a_old)-1);
fprintf(outputfile," %d",hd[i].pbs[n[0]][n[1]][n[2]].shape[j].NLoopConverged);
fprintf(outputfile,"\n");
}
}
fclose(outputfile);
} /* if SpeciesContained */
} /* for NSpeciesProfile */
}
/* void read_spherical_profiles(GI gi, HALO_DATA *hd) { */
/* int i, j, k; */
/* int ID, IDold, hit, NHaloFound, idummy; */
/* double V, M, property; */
/* double ddummy; */
/* double fproperty = 1.1; */
/* char cdummy[1000]; */
/* FILE *InputFile; */
/* /\* */
/* ** Total matter */
/* *\/ */
/* InputFile = fopen(gi.TotProfilesFileName,"r"); */
/* assert(InputFile != NULL); */
/* NHaloFound = 0; */
/* fgets(cdummy,1000,InputFile); */
/* fscanf(InputFile,"%i",&idummy); ID = idummy; */
/* while (1) { */
/* for (j = 0; j < 3; j++) fscanf(InputFile,"%le",&ddummy); */
/* fscanf(InputFile,"%le",&ddummy); V = ddummy; */
/* fscanf(InputFile,"%le",&ddummy); */
/* fscanf(InputFile,"%le",&ddummy); M = ddummy; */
/* for (j = 0; j < 16; j++) fscanf(InputFile,"%le",&ddummy); */
/* if (feof(InputFile)) break; */
/* hit = 0; */
/* for (i = 0; i < gi.NHalo; i++) { */
/* if (hd[i].ID == ID) { */
/* property = M/V; */
/* hd[i].pbs[0].totshape->propertymin = property/fproperty; */
/* hd[i].pbs[0].totshape->propertymax = property*fproperty; */
/* for (j = 1; j < hd[i].NBin+1; j++) { */
/* fscanf(InputFile,"%i",&idummy); ID = idummy; */
/* for (k = 0; k < 3; k++) fscanf(InputFile,"%le",&ddummy); */
/* fscanf(InputFile,"%le",&ddummy); V = ddummy; */
/* fscanf(InputFile,"%le",&ddummy); */
/* fscanf(InputFile,"%le",&ddummy); M = ddummy; */
/* for (k = 0; k < 16; k++) fscanf(InputFile,"%le",&ddummy); */
/* property = M/V; */
/* assert(hd[i].ID == ID); */
/* hd[i].pbs[j].totshape->propertymin = property/fproperty; */
/* hd[i].pbs[j].totshape->propertymax = property*fproperty; */
/* } */
/* NHaloFound++; */
/* hit = 1; */
/* fscanf(InputFile,"%i",&idummy); ID = idummy; */
/* } */
/* if (hit == 1) break; */
/* } */
/* if (NHaloFound == gi.NHalo) break; */
/* if (hit == 0) { */
/* /\* */
/* ** Halo is not in list */
/* *\/ */
/* IDold = ID; */
/* fscanf(InputFile,"%i",&idummy); ID = idummy; */
/* while (IDold == ID) { */
/* for (i = 0; i < 22; i++) fscanf(InputFile,"%le",&ddummy); */
/* fscanf(InputFile,"%i",&idummy); ID = idummy; */
/* } */
/* } */
/* } */
/* fclose(InputFile); */
/* /\* */
/* ** Gas */
/* *\/ */
/* if (gi.SpeciesContained[GAS]) { */
/* InputFile = fopen(gi.GasProfilesFileName,"r"); */
/* assert(InputFile != NULL); */
/* NHaloFound = 0; */
/* fgets(cdummy,1000,InputFile); */
/* fscanf(InputFile,"%i",&idummy); ID = idummy; */
/* while (1) { */
/* for (j = 0; j < 3; j++) fscanf(InputFile,"%le",&ddummy); */
/* fscanf(InputFile,"%le",&ddummy); V = ddummy; */
/* fscanf(InputFile,"%le",&ddummy); */
/* fscanf(InputFile,"%le",&ddummy); M = ddummy; */
/* for (j = 0; j < 32; j++) fscanf(InputFile,"%le",&ddummy); */
/* if (feof(InputFile)) break; */
/* hit = 0; */
/* for (i = 0; i < gi.NHalo; i++) { */
/* if (hd[i].ID == ID) { */
/* property = M/V; */
/* hd[i].pbs[0].gasshape->propertymin = property/fproperty; */
/* hd[i].pbs[0].gasshape->propertymax = property*fproperty; */
/* for (j = 1; j < hd[i].NBin+1; j++) { */
/* fscanf(InputFile,"%i",&idummy); ID = idummy; */
/* for (k = 0; k < 3; k++) fscanf(InputFile,"%le",&ddummy); */
/* fscanf(InputFile,"%le",&ddummy); V = ddummy; */
/* fscanf(InputFile,"%le",&ddummy); */
/* fscanf(InputFile,"%le",&ddummy); M = ddummy; */
/* for (k = 0; k < 32; k++) fscanf(InputFile,"%le",&ddummy); */
/* property = M/V; */
/* assert(hd[i].ID == ID); */
/* hd[i].pbs[j].gasshape->propertymin = property/fproperty; */
/* hd[i].pbs[j].gasshape->propertymax = property*fproperty; */
/* } */
/* NHaloFound++; */
/* hit = 1; */
/* fscanf(InputFile,"%i",&idummy); ID = idummy; */
/* } */
/* if (hit == 1) break; */
/* } */
/* if (NHaloFound == gi.NHalo) break; */
/* if (hit == 0) { */
/* /\* */
/* ** Halo is not in list */
/* *\/ */
/* IDold = ID; */
/* fscanf(InputFile,"%i",&idummy); ID = idummy; */
/* while (IDold == ID) { */
/* for (i = 0; i < 38; i++) fscanf(InputFile,"%le",&ddummy); */
/* fscanf(InputFile,"%i",&idummy); ID = idummy; */
/* } */
/* } */
/* } */
/* fclose(InputFile); */
/* } */
/* /\* */
/* ** Dark matter */
/* *\/ */
/* if (gi.SpeciesContained[DARK]) { */
/* InputFile = fopen(gi.DarkProfilesFileName,"r"); */
/* assert(InputFile != NULL); */
/* NHaloFound = 0; */
/* fgets(cdummy,1000,InputFile); */
/* fscanf(InputFile,"%i",&idummy); ID = idummy; */
/* while (1) { */
/* for (j = 0; j < 3; j++) fscanf(InputFile,"%le",&ddummy); */
/* fscanf(InputFile,"%le",&ddummy); V = ddummy; */
/* fscanf(InputFile,"%le",&ddummy); */
/* fscanf(InputFile,"%le",&ddummy); M = ddummy; */
/* for (j = 0; j < 15; j++) fscanf(InputFile,"%le",&ddummy); */
/* if (feof(InputFile)) break; */
/* hit = 0; */
/* for (i = 0; i < gi.NHalo; i++) { */
/* if (hd[i].ID == ID) { */
/* property = M/V; */
/* hd[i].pbs[0].darkshape->propertymin = property/fproperty; */
/* hd[i].pbs[0].darkshape->propertymax = property*fproperty; */
/* for (j = 1; j < hd[i].NBin+1; j++) { */
/* fscanf(InputFile,"%i",&idummy); ID = idummy; */
/* for (k = 0; k < 3; k++) fscanf(InputFile,"%le",&ddummy); */
/* fscanf(InputFile,"%le",&ddummy); V = ddummy; */
/* fscanf(InputFile,"%le",&ddummy); */
/* fscanf(InputFile,"%le",&ddummy); M = ddummy; */
/* for (k = 0; k < 15; k++) fscanf(InputFile,"%le",&ddummy); */
/* property = M/V; */
/* assert(hd[i].ID == ID); */
/* hd[i].pbs[j].darkshape->propertymin = property/fproperty; */
/* hd[i].pbs[j].darkshape->propertymax = property*fproperty; */
/* } */
/* NHaloFound++; */
/* hit = 1; */
/* fscanf(InputFile,"%i",&idummy); ID = idummy; */
/* } */
/* if (hit == 1) break; */
/* } */
/* if (NHaloFound == gi.NHalo) break; */
/* if (hit == 0) { */
/* /\* */
/* ** Halo is not in list */
/* *\/ */
/* IDold = ID; */
/* fscanf(InputFile,"%i",&idummy); ID = idummy; */
/* while (IDold == ID) { */
/* for (i = 0; i < 21; i++) fscanf(InputFile,"%le",&ddummy); */
/* fscanf(InputFile,"%i",&idummy); ID = idummy; */
/* } */
/* } */
/* } */
/* fclose(InputFile); */
/* } */
/* /\* */
/* ** Stars */
/* *\/ */
/* if (gi.SpeciesContained[STAR]) { */
/* InputFile = fopen(gi.StarProfilesFileName,"r"); */
/* assert(InputFile != NULL); */
/* NHaloFound = 0; */
/* fgets(cdummy,1000,InputFile); */
/* fscanf(InputFile,"%i",&idummy); ID = idummy; */
/* while (1) { */
/* for (j = 0; j < 3; j++) fscanf(InputFile,"%le",&ddummy); */
/* fscanf(InputFile,"%le",&ddummy); V = ddummy; */
/* fscanf(InputFile,"%le",&ddummy); */
/* fscanf(InputFile,"%le",&ddummy); M = ddummy; */
/* for (j = 0; j < 21; j++) fscanf(InputFile,"%le",&ddummy); */
/* if (feof(InputFile)) break; */
/* hit = 0; */
/* for (i = 0; i < gi.NHalo; i++) { */
/* if (hd[i].ID == ID) { */
/* property = M/V; */
/* hd[i].pbs[0].starshape->propertymin = property/fproperty; */
/* hd[i].pbs[0].starshape->propertymax = property*fproperty; */
/* for (j = 1; j < hd[i].NBin+1; j++) { */
/* fscanf(InputFile,"%i",&idummy); ID = idummy; */
/* for (k = 0; k < 3; k++) fscanf(InputFile,"%le",&ddummy); */
/* fscanf(InputFile,"%le",&ddummy); V = ddummy; */
/* fscanf(InputFile,"%le",&ddummy); */
/* fscanf(InputFile,"%le",&ddummy); M = ddummy; */
/* for (k = 0; k < 21; k++) fscanf(InputFile,"%le",&ddummy); */
/* property = M/V; */
/* assert(hd[i].ID == ID); */
/* hd[i].pbs[j].starshape->propertymin = property/fproperty; */
/* hd[i].pbs[j].starshape->propertymax = property*fproperty; */
/* } */
/* NHaloFound++; */
/* hit = 1; */
/* fscanf(InputFile,"%i",&idummy); ID = idummy; */
/* } */
/* if (hit == 1) break; */
/* } */
/* if (NHaloFound == gi.NHalo) break; */
/* if (hit == 0) { */
/* /\* */
/* ** Halo is not in list */
/* *\/ */
/* IDold = ID; */
/* fscanf(InputFile,"%i",&idummy); ID = idummy; */
/* while (IDold == ID) { */
/* for (i = 0; i < 27; i++) fscanf(InputFile,"%le",&ddummy); */
/* fscanf(InputFile,"%i",&idummy); ID = idummy; */
/* } */
/* } */
/* } */
/* fclose(InputFile); */
/* } */
/* } */
|
ex10.c | /**
\file
\brief A program for APPFS ex10
\author Tri-Peter Shrive
*/
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <math.h>
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
#include "ex10.h"
/**
utility function that simplifies error handling
*/
void error_exit_fun(
const char* const msg, /**< message to be displayed */
const char* const file, /**< file name */
const unsigned int lineno /**< line number */
)
{
assert( NULL != msg );
assert( NULL != file );
fprintf( stderr, "%s(%u) ", file, lineno );
perror( msg );
exit( EXIT_FAILURE );
}
/**
sifts an entry up through binary heap
*/
int sift_up(
unsigned int* heap, /**< nodes in heap */
INTEGER* distance, /**< distance of nodes in heap */
unsigned int* index, /**< index of nodes in heap */
unsigned int current /**< current position of node in heap */
)
{
// store child node in temp variable
unsigned int temp_a = heap[current];
// store distance to child node in temp variable
INTEGER dist = distance[temp_a];
int parent;
unsigned int temp_b;
while( 0 < current )
{
// calculate parents location in heap array
parent = ( current - 1 ) / 2;
assert( 0 <= parent );
// store parent in temp variable
temp_b = heap[parent];
// is the distance to parent node greater than the distance to child?
// if not break out of loop
if( distance[temp_b] <= dist )
break;
// replace child node with parent node
heap[current] = temp_b;
// update parent nodes heap index
index[temp_b] = current;
// parent becomes next child
current = parent;
}
// replace child with first child
heap[current] = temp_a;
// update child nodes heap index
index[temp_a] = current;
return 0;
}
/**
sifts an entry down through binary heap
*/
int sift_down(
unsigned int* heap, /**< nodes in heap */
INTEGER* distance, /**< distance of nodes in heap */
unsigned int* index, /**< index of nodes in heap */
unsigned int current, /**< current position of node in heap */
const int size /**< size of heap */
)
{
INTEGER dist;
int child;
unsigned int temp_a;
unsigned int temp_b;
// calculate location of child in heap array
child = current + current + 1;
// store parent node as temporary variable
temp_a = heap[current];
// store distance of current node as temporary variable
dist = distance[temp_a];
// while node has a child
while( child <= size )
{
// store first child node as temporary variable
temp_b = heap[child];
// does a second child exist?
if( child + 1 <= size )
{
// is the distance to the second child less than that of the first?
if( distance[ heap[child + 1] ] < distance[temp_b] )
{
child++;
// replace first child node with second child node
temp_b = heap[child];
}
}
// is the distance to child node less than the distance to parent?
// if not break out of loop
if( distance[temp_b] >= dist )
break;
// replace parent node with child node
heap[current] = temp_b;
// update child nodes heap index
index[temp_b] = current;
// child becomes next parent
current = child;
// calculate new child
child = child + child + 1;
}
// replace current parent with first parent
heap[current] = temp_a;
// update the parents heap index
index[temp_a] = current;
return 0;
}
#ifndef NDEBUG
/**
assesses validity of heap index
*/
int is_heap_index_valid(
unsigned int* heap, /**< nodes in heap */
unsigned int* index, /**< index of nodes in heap */
const int size /**< size of heap */
)
{
unsigned int sum = 0;
for( int i = 0; i <= size; i++ )
{
sum += ( heap[ index[heap[i]] ] != heap[i] );
}
return ( 0 == sum);
}
int is_heap_order_valid(
unsigned int* heap,
INTEGER* distance,
const int size
)
{
unsigned int sum = 0;
int current = 0;
int child = current + current + 1;
while( child <= size )
{
sum += ( distance[ heap[ current ] ] > distance[ heap [ child ] ] );
child++;
if( child <= size )
{
sum += ( distance[ heap[ current ] ] > distance[ heap [ child ] ] );
}
current++;
child= current + current + 1;
}
return ( 0 == sum );
}
int is_tree_valid(
unsigned int* predecessor,
unsigned int* terminal,
unsigned int* source,
const unsigned int n_nodes,
const unsigned int n_term
)
{
int next;
int current;
for( unsigned int i = 0; i < n_term; i++ )
{
current = terminal[i];
next = predecessor[ current ];
while( INT_MAX > next )
{
current = next;
next = predecessor[ current ];
if( current == next )
return -1;
}
source[i] = current;
}
// there should only be one source
unsigned int sum = 0;
for( unsigned int i = 1; i < n_term; i++ )
{
sum += ( source[0] != source[i] );
}
return ( 0 == sum );
}
#endif
/**
calculates steiner tree for given graph and source terminal using dijkstra's algorithm
*/
int steiner(
struct graph* G, /**< static graph attributes */
struct graph* H, /**< variable graph attributes */
unsigned int* is_prime, /**< array where entries are 1 when index is prime */
unsigned int source /**< source node */
)
{
assert( G );
assert( H->predecessor );
assert( H->distance );
assert( H->tree_pred );
assert( G->sorted_heads );
assert( G->sorted_weights );
assert( G->number_of_neighbours );
assert( G->index_of_first_neighbour );
// create set containing all vetrices
// datastructure used is a binary heap
// index 0 is highest priority
// if node not on heap it has lowest priority
unsigned int* heap = NULL;
heap = malloc( G->number_of_nodes * sizeof(unsigned int) );
unsigned int* index_on_heap = NULL;
index_on_heap = malloc( G->number_of_nodes * sizeof(unsigned int) );
for( unsigned int i = 0; i < G->number_of_nodes; i++ )
{
// heap entry is initially empty
// meaning all vetrices have lowest priority
heap[i] = INT_MAX;
index_on_heap[i] = INT_MAX;
// the vetrex's predecessor in shortest path tree is unknown
H->predecessor[i] = INT_MAX;
// the vetre's predecessor in steiner tree is unknown
H->tree_pred[i] = INT_MAX;
// the vetrex's distance from source is assumed to be infinite
H->distance[i] = INTEGER_MAX;
}
assert( source < G->number_of_nodes );
// distance to source is zero
H->distance[source] = 0;
// add source to heap
heap[0] = source;
index_on_heap[source] = 0;
// largest valid heap index is set to 0
int size_of_heap = 0;
// tempary variables for storing edge attributes
unsigned int tail;
unsigned int head;
INTEGER dist;
unsigned int index_of_neighbour;
unsigned int root;
unsigned int close;
unsigned int next;
H->sum = 0;
H->count = 0;
// loop while heap has entries
while( size_of_heap >= 0 )
{
// extract the vetrex with highest priority from heap
// and setting it as current tail
tail = heap[0];
// replace the extracted vetrex with the vetrex of lowest priority
root = heap[size_of_heap];
heap[0] = root;
index_on_heap[heap[0]] = 0;
// decrese the largest valid heap index
size_of_heap--;
// sift the replacement vetrex down in the heap
// until it is at it's correct place in the priority queue
sift_down( heap, H->distance, index_on_heap, 0, size_of_heap );
assert( is_heap_index_valid( heap, index_on_heap, size_of_heap ) );
assert( is_heap_order_valid( heap, H->distance, size_of_heap ) );
// if tail is terminal add all nodes on shortest path to source to subtree
// i.e. set distance to zero and then add to heap or decrease key
if( 1 == is_prime[tail] )
{
// increase count of terminals in subtree
H->count++;
// add weights on path from subtree to terminal to objective value
H->sum += H->distance[tail];
// ensure we don't add this terminal twice
is_prime[tail] = 0;
// loop through nodes on shortest path to subtree
close = tail;
next = H->predecessor[close];
while( INT_MAX != next )
{
// record this node as child nodes' predecessor
H->tree_pred[close] = next;
// is the node already on heap?
if( INT_MAX == index_on_heap[close] )
{
// add node with distance zero
size_of_heap++;
heap[size_of_heap] = close;
index_on_heap[close] = size_of_heap;
H->distance[close] = 0;
sift_up( heap, H->distance, index_on_heap, size_of_heap );
assert( is_heap_index_valid( heap, index_on_heap, size_of_heap ) );
assert( is_heap_order_valid( heap, H->distance, size_of_heap ) );
}
else
{
// node already on heap, set distance to zero and sift up from current possition
H->distance[close] = 0;
sift_up( heap, H->distance, index_on_heap, index_on_heap[close] );
assert( is_heap_index_valid( heap, index_on_heap, size_of_heap ) );
assert( is_heap_order_valid( heap, H->distance, size_of_heap ) );
}
// move along shortest path toward subtree
close = next;
next = H->predecessor[close];
}
// are all terminals connected?
if( H->count == G->number_of_terminals )
break;
}
// for each of the tail's neighbours we do the following
for( unsigned int i = 0; i < G->number_of_neighbours[tail]; i++ )
{
index_of_neighbour = G->index_of_first_neighbour[tail]+i;
// set the current neighbour as the temporary head
head = G->sorted_heads[index_of_neighbour];
// calculate the current distance
dist = H->distance[tail] + G->sorted_weights[index_of_neighbour];
// can we best the current shortest path?
if( dist < H->distance[head] )
{
// update the distance to head
H->distance[head] = dist;
// update the heads predecessor
H->predecessor[head] = tail;
// is the current head already on heap?
if( index_on_heap[head] == INT_MAX )
{
// add head at bottom of heap
size_of_heap++;
assert( size_of_heap < G->number_of_nodes + 1 );
heap[size_of_heap] = head;
index_on_heap[head] = size_of_heap;
// sift head upwards in heap
// until at correct place in priority queue
sift_up( heap, H->distance, index_on_heap, size_of_heap );
assert( is_heap_index_valid( heap, index_on_heap, size_of_heap ) );
assert( is_heap_order_valid( heap, H->distance, size_of_heap ) );
}
else
{
// decrease key
sift_up( heap, H->distance, index_on_heap, index_on_heap[head] );
assert( is_heap_index_valid( heap, index_on_heap, size_of_heap ) );
assert( is_heap_order_valid( heap, H->distance, size_of_heap ) );
}
}
}
}
free( heap );
free( index_on_heap );
return 0;
}
/**
sets entry at index of prime numbers to 1
*/
int get_primes(
unsigned int* is_prime, /**< allocate memory for this array of size max and set the memory to zero */
unsigned int max /**< size of array is_prime, the largest number to be assessed for primality */
)
{
unsigned int rest;
is_prime[2] = 1;
unsigned int count = 1;
unsigned int last_div;
unsigned int i;
unsigned int j;
#ifdef THREADS
#pragma omp parallel for default(none) shared(is_prime, max, count) private(i, j, last_div, rest) num_threads(THREADS)
#else
#pragma omp parallel for default(none) shared(is_prime, max, count) private(i, j, last_div, rest)
#endif
for( i = 3; i < max; i += 2 )
{
last_div = (unsigned int) ceil( sqrt(i) );
for( j = 2; j <= last_div ; j++ )
{
rest = i % j;
if( 0 == rest )
break;
if( j == last_div )
{
#pragma omp atomic
count++;
is_prime[i] = 1;
}
}
}
return count;
}
/**
reads data from file storing nodes and weights in graph structure. then calls dijkstra's algorithm and assesses longest shortes path
*/
int main(
int argc,
const char* const* const argv
)
{
if( argc < 2 )
{
fprintf( stderr, "usage: %s *.gph (n_start_points) (-s)\n", argv[1] );
exit( EXIT_FAILURE );
}
size_t array_of_edges_next = 0;
size_t array_of_edges_length = EXT_SIZE;
struct graph* G = NULL;
G = malloc( sizeof(struct graph) );
if( NULL == G )
error_exit( "malloc: " );
G->tail = NULL;
G->head = NULL;
G->edge_weight = NULL;
G->predecessor = NULL;
G->sorted_heads = NULL;
G->sorted_weights = NULL;
G->number_of_neighbours = NULL;
G->index_of_first_neighbour = NULL;
G->number_of_nodes = 0;
G->number_of_edges = 0;
G->tail = malloc( array_of_edges_length * sizeof(unsigned int) );
G->head = malloc( array_of_edges_length * sizeof(unsigned int) );
G->edge_weight = malloc( array_of_edges_length * sizeof(INTEGER) );
if( NULL == G->tail || NULL == G->head || NULL == G->edge_weight )
error_exit( "malloc: " );
// open file for reading
FILE* fp = fopen( argv[1], "r" );
if( NULL == fp )
error_exit( "fopen: " );
unsigned int lineno = 0;
char line[MAX_LINE_LEN];
fgets( line, sizeof(line), fp );
lineno++;
// remove comments and anything after newline
char* s = strpbrk( line, "#\n" );
if( NULL != s )
*s = '\0';
// skip initial spaces
for( s = &line[0]; isspace( *s ); s++ );
assert( '\0' != *s );
int ret = sscanf( s, "%u %u", &G->number_of_nodes, &G->number_of_edges );
assert( 2 == ret );
// undirected graph
G->number_of_edges *= 2;
// unused node 0
G->number_of_nodes++;
G->number_of_neighbours = calloc( G->number_of_nodes, sizeof(unsigned int) );
G->index_of_first_neighbour = calloc( G->number_of_nodes, sizeof(unsigned int) );
if( NULL == G->number_of_neighbours || NULL == G->index_of_first_neighbour )
error_exit( "malloc: " );
while( NULL != fgets( line, sizeof(line), fp ) )
{
lineno++;
// remove comments and anything after newline
char* s = strpbrk( line, "#\n" );
if( NULL != s )
*s = '\0';
// skip initial spaces
for( s = &line[0]; isspace(*s); s++ )
;
// skip line if empty
if( '\0' == *s )
continue;
unsigned int temp_tail = 0;
unsigned int temp_head = 0;
INTEGER temp_edge_weight = INTEGER_MAX;
ret = sscanf( s, "%u %u %llu", &temp_tail, &temp_head, &temp_edge_weight );
if( 3 != ret )
{
fprintf( stderr, "\nWarning: Line %u, sscanf returned %u != 3\n", lineno, ret );
continue;
}
if( 0 > temp_tail || 0 > temp_head )
{
fprintf( stderr, "\nWarning: Line %u, tail = %u, head = %u\n", lineno, temp_tail, temp_head );
continue;
}
if( 2000000000 <= temp_edge_weight )
{
fprintf( stderr, "\nWarning: Line %u, edge_weight = %llu\n", lineno, temp_edge_weight );
continue;
}
// check there's enought space in the array, if not enlarge the array
if( array_of_edges_next == array_of_edges_length )
{
array_of_edges_length += EXT_SIZE;
G->tail = realloc( G->tail, array_of_edges_length * sizeof(unsigned int) );
G->head = realloc( G->head, array_of_edges_length * sizeof(unsigned int) );
G->edge_weight = realloc( G->edge_weight, array_of_edges_length * sizeof(INTEGER) );
if( NULL == G->tail || NULL == G->head || NULL == G->edge_weight )
error_exit("realloc: ");
}
assert( G->number_of_nodes > temp_tail );
assert( G->number_of_nodes > temp_head );
// store the edge in memory
G->tail[array_of_edges_next] = temp_tail;
G->head[array_of_edges_next] = temp_head;
G->edge_weight[array_of_edges_next] = temp_edge_weight;
G->number_of_neighbours[temp_tail]++;
array_of_edges_next++;
// repeat with head and tail inverted for undirected graph
if( array_of_edges_next == array_of_edges_length )
{
array_of_edges_length += EXT_SIZE;
G->tail = realloc( G->tail, array_of_edges_length * sizeof(unsigned int) );
G->head = realloc( G->head, array_of_edges_length * sizeof(unsigned int) );
G->edge_weight = realloc( G->edge_weight, array_of_edges_length * sizeof(INTEGER) );
if ( NULL == G->tail || NULL == G->head || NULL == G->edge_weight )
error_exit( "realloc: " );
}
assert( G->number_of_nodes > temp_tail );
assert( G->number_of_nodes > temp_head );
// store reversed edge in memory
G->tail[array_of_edges_next] = temp_head;
G->head[array_of_edges_next] = temp_tail;
G->edge_weight[array_of_edges_next] = temp_edge_weight;
G->number_of_neighbours[temp_head]++;
array_of_edges_next++;
}
if( fclose(fp) )
error_exit("fclose: ");
// calculate index of first neighbour for sorted lists
for( unsigned int i = 1; i < G->number_of_nodes; i++ )
G->index_of_first_neighbour[i] = G->index_of_first_neighbour[i - 1] + G->number_of_neighbours[i - 1];
unsigned int* neighbours_found = NULL;
neighbours_found = calloc( G->number_of_nodes, sizeof(unsigned int) );
G->sorted_heads = malloc( G->number_of_edges * sizeof(unsigned int) );
G->sorted_weights = malloc( G->number_of_edges * sizeof(INTEGER) );
if( NULL == neighbours_found || NULL == G->sorted_heads || NULL == G->sorted_weights )
error_exit( "malloc/calloc: " );
// sort edges by tails
unsigned int tail;
unsigned int index;
for( unsigned int i = 0; i < G->number_of_edges; i++ )
{
tail = G->tail[i];
index = G->index_of_first_neighbour[tail];
G->sorted_heads[index + neighbours_found[tail]] = G->head[i];
G->sorted_weights[index + neighbours_found[tail]] = G->edge_weight[i];
neighbours_found[tail] += 1;
}
#ifndef NDEBUG
unsigned int total_neighbours = 0;
for( unsigned int i = 0; i < G->number_of_nodes; i++ )
total_neighbours += neighbours_found[i];
assert( G->number_of_edges == total_neighbours );
#endif
free(neighbours_found);
free( G->tail );
free( G->head );
free( G->edge_weight );
// calculate prime numbers
unsigned int* is_prime = NULL;
is_prime = calloc( G->number_of_nodes, sizeof(unsigned int) );
G->number_of_terminals = get_primes( is_prime, G->number_of_nodes );
// create array of terminal nodes
unsigned int* terminals = NULL;
terminals = malloc( G->number_of_terminals * sizeof(unsigned int) );
if( NULL == terminals || NULL == is_prime )
error_exit( "malloc: " );
unsigned int k = 0;
for( unsigned int i = 0; i < G->number_of_nodes; i++ )
if( 1 == is_prime[i] )
{
terminals[k] = i;
k++;
}
assert( k == G->number_of_terminals );
// process the argv[2] and if present the argv[3]
unsigned int n = 0;
unsigned int m = 1;
unsigned int s_flag = 0;
unsigned int max_t = INT_MAX;
for( unsigned int i = 2; i < argc; i++ )
{
// optionally print steiner tree
m = strcmp( argv[i], "-s" );
if( 0 == m ) s_flag = 1;
// read in max number of terminals to use as source
else if( 2 == i )
{
// the number of terminals to start from must be equal or less than the total number of terminals
// the default is 100 terminals if that is less than the total number of terminals
// otherwise the default is all terminals
n = sscanf( argv[i], "%u", &max_t );
if( max_t < k && 1 == n ) k = max_t;
else if( 100 < k && 1 != n ) k = 100;
}
}
// declare variables and allocate memory used in parallel for loop
unsigned int t;
unsigned int* prime = NULL;
INTEGER obj_val = INTEGER_MAX;
struct graph* H = NULL;
G->distance = NULL;
G->distance = calloc( G->number_of_nodes, sizeof(INTEGER) );
G->tree_pred = NULL;
G->tree_pred = malloc( G->number_of_nodes * sizeof(unsigned int) );
if ( NULL == G->tree_pred || NULL == G->distance )
error_exit( "calloc: " );
// start wall clock
struct timeval start_wall;
unsigned int fail = gettimeofday( &start_wall, NULL );
assert( 0 == fail );
// start counting cpu clocks
double start_cpu = (double)clock() / (double)CLOCKS_PER_SEC;
#ifdef THREADS
#pragma omp parallel for default(none) shared(is_prime, k, G, obj_val, terminals) private(t, H, prime) num_threads(THREADS)
#else
#pragma omp parallel for default(none) shared(is_prime, k, G, obj_val, terminals) private(t, H, prime)
#endif
for( t = 0; t < k; t++ )
{
H = malloc(sizeof(struct graph));
if(NULL == H)
error_exit("malloc: ");
H->predecessor = malloc( G->number_of_nodes * sizeof(unsigned int) );
H->distance = malloc( G->number_of_nodes * sizeof(INTEGER) );
H->tree_pred = malloc( G->number_of_nodes * sizeof(unsigned int) );
if ( NULL == H->predecessor || NULL == H->distance || NULL == H->tree_pred )
error_exit( "malloc: " );
prime = malloc( G->number_of_nodes * sizeof(unsigned int) );
if( NULL == prime )
error_exit("malloc: ");
memcpy( prime, is_prime, G->number_of_nodes * sizeof(unsigned int) );
steiner( G, H, prime, terminals[t] );
free( H->predecessor );
free( H->distance );
for( int j = 0; j < G->number_of_terminals; j++ )
assert( 0 == prime[j] );
free( prime );
#pragma omp critical ( objective_value )
{
// can we best our current objective value
if( obj_val > H->sum )
{
obj_val = H->sum;
memcpy( G->tree_pred, H->tree_pred, G->number_of_nodes * sizeof(unsigned int) );
}
}
free( H->tree_pred );
free( H );
}
// stop the wall clock
struct timeval stop_wall;
fail = gettimeofday( &stop_wall, NULL );
assert( 0 == fail );
// stop counting cpu clocks
double stop_cpu = (double)clock() / (double)CLOCKS_PER_SEC;
// calculate durations of both
double duration_wall = ( stop_wall.tv_sec + stop_wall.tv_usec * 0.000001 ) - ( start_wall.tv_sec + start_wall.tv_usec * 0.000001 );
double duration_cpu = stop_cpu - start_cpu;
unsigned int* source = NULL;
source = calloc( G->number_of_terminals, sizeof(unsigned int) );
if( NULL == source )
error_exit("calloc: ");
assert( is_tree_valid( G->tree_pred, terminals, source, G->number_of_nodes, G->number_of_terminals ) );
// print results
printf( "\n" );
printf( "TLEN:\t%llu\n", obj_val );
if( s_flag )
{
printf( "TREE:\t" );
for( unsigned int i = 0; i < G->number_of_nodes; i++ )
if( INT_MAX != G->tree_pred[i] )
printf( "(%u,%u) ", i, G->tree_pred[i] );
printf( "\n\n" );
}
printf( "TIME:\t%lf sec\n", duration_cpu );
printf( "WALL:\t%lf sec\n\n", duration_wall );
free( is_prime );
free( terminals );
free( G->tree_pred );
free( G->distance );
free( G->sorted_heads );
free( G->sorted_weights );
free( G->number_of_neighbours );
free( G->index_of_first_neighbour );
free( G );
return 0;
}
|
sparsify.h | /******************************************************************************
* sparsify.h
*
* Source of VieCut.
*
******************************************************************************
* Copyright (C) 2017 Alexander Noe <alexander.noe@univie.ac.at>
*
* Published under the MIT license in the LICENSE file.
*****************************************************************************/
#pragma once
#include <algorithm>
#include <memory>
#include <random>
#include <utility>
#include <vector>
#include "data_structure/graph_access.h"
#include "parallel/coarsening/contract_graph.h"
#include "parallel/data_structure/union_find.h"
#include "tlx/logger.hpp"
#include "tools/random_functions.h"
#include "tools/timer.h"
class sparsify {
private:
NodeID elementsToReduce(std::shared_ptr<graph_access> G) {
return static_cast<NodeID>(
static_cast<double>(G->number_of_nodes())
* configuration::getConfig()->contraction_factor);
}
auto createMappings(std::shared_ptr<graph_access> G,
union_find* uf) {
timer t;
std::vector<NodeID> mapping(G->number_of_nodes());
std::vector<NodeID> part(G->number_of_nodes(), UNDEFINED_NODE);
NodeID current_pid = 0;
for (size_t n = 0; n < G->number_of_nodes(); ++n) {
NodeID part_id = uf->Find(n);
if (part[part_id] == UNDEFINED_NODE) {
part[part_id] = current_pid++;
}
mapping[n] = part[part_id];
}
return std::make_tuple(mapping, current_pid);
}
public:
NodeID sample_contractible_weighted(std::shared_ptr<graph_access> G,
union_find* uf) {
NodeID n_reduce;
timer t;
size_t num_threads = omp_get_num_threads();
std::vector<std::vector<EdgeWeight> > prefixsum;
std::vector<EdgeWeight> processor_prefixes;
#pragma omp parallel
{
if (!omp_get_thread_num()) {
prefixsum.resize(num_threads);
processor_prefixes.resize(num_threads);
}
#pragma omp barrier
EdgeID m = G->number_of_edges();
size_t wgt = 0;
EdgeID per_thread =
std::ceil(static_cast<double>(m)
/ static_cast<double>(num_threads));
auto id = omp_get_thread_num();
prefixsum[id].reserve(per_thread);
EdgeID my_start = id * per_thread;
EdgeID my_end = std::min((id + 1) * per_thread,
G->number_of_edges());
for (size_t m = my_start; m < my_end; ++m) {
wgt += G->getEdgeWeight(m);
prefixsum[id].push_back(wgt);
}
processor_prefixes[id] = wgt;
#pragma omp barrier
EdgeWeight my_prefix = 0;
for (int i = 0; i < id; ++i) {
my_prefix += processor_prefixes[i];
}
for (size_t m = my_start; m < my_end; ++m) {
prefixsum[m / per_thread][m % per_thread] += my_prefix;
}
double factor = configuration::getConfig()->contraction_factor;
n_reduce = std::min(static_cast<NodeID>(
static_cast<double>(G->number_of_nodes())
* factor),
G->number_of_nodes() - 2);
size_t contracted = 0;
std::mt19937_64 m_mt(configuration::getConfig()->seed);
n_reduce /= num_threads;
#pragma omp barrier
while (contracted < n_reduce) {
auto random = m_mt();
EdgeWeight e_rand = (random % processor_prefixes[id])
+ my_prefix;
auto edge = std::lower_bound(
prefixsum[id].begin(), prefixsum[id].end(), e_rand,
[](const auto& in1, const EdgeWeight& e) {
return in1 < e;
});
EdgeID e = edge - prefixsum[id].begin() + (per_thread * id);
NodeID src = G->getEdgeSource(e);
NodeID tgt = G->getEdgeTarget(e);
if (!uf->SameSet(src, tgt)) {
if (uf->Union(src, tgt)) {
++contracted;
}
}
}
}
return G->number_of_nodes() - n_reduce * num_threads;
}
NodeID sample_contractible_separate(std::shared_ptr<graph_access> G,
union_find* uf) {
NodeID to_reduce = elementsToReduce(G);
std::atomic<NodeID> reduced = 0;
timer t;
NodeID to_try = to_reduce / configuration::getConfig()->threads;
const EdgeID my_range = G->number_of_edges()
/ configuration::getConfig()->threads;
#pragma omp parallel
{
std::mt19937_64 m_mt(configuration::getConfig()->seed
+ omp_get_thread_num());
EdgeID my_start = my_range * omp_get_thread_num();
size_t tries = 0;
NodeID my_reduced = 0;
while (tries < to_try) {
EdgeWeight e_rand = (m_mt() % my_range) + my_start;
tries++;
NodeID src = G->getEdgeSource(e_rand);
NodeID tgt = G->getEdgeTarget(e_rand);
if (uf->Union(src, tgt)) {
++my_reduced;
}
}
LOG1 << tries << " tries in " << t.elapsed()
<< "s (success in " << my_reduced << ")";
}
return G->number_of_nodes() - reduced;
}
NodeID sample_geometric(std::shared_ptr<graph_access> G,
union_find* uf) {
timer t;
#pragma omp parallel
{
NodeID local_samples = 0;
NodeID contracted = 0;
double n = G->number_of_nodes();
double m = G->number_of_edges();
double samples = n * configuration::getConfig()->contraction_factor;
// as we do not want to sample an edge multiple times,
// we sample without replacement
// this is O(realized) by removing 'samples'
// from the sampled range and adding +1 to e after every sample
double prob =
samples / (m * configuration::getConfig()->threads - samples);
if (prob > 1) {
LOG1 << "WARNING: Edge Sampling Probability larger than 1.";
LOG1 << "Setting it to a valid value of 0.5.";
prob = 0.5;
}
std::default_random_engine generator(
configuration::getConfig()->seed + omp_get_thread_num());
std::geometric_distribution<EdgeID> distribution(prob);
EdgeID prev = 0;
EdgeID e = prev;
while (e < G->number_of_edges()) {
const NodeID src = G->getEdgeSource(e);
const NodeID tgt = G->getEdgeTarget(e);
++local_samples;
if (uf->Union(src, tgt)) {
++contracted;
}
e += (distribution(generator) + 1);
}
}
return uf->n();
}
NodeID sample_contractible(std::shared_ptr<graph_access> G,
union_find* uf) {
timer t;
NodeID to_reduce = elementsToReduce(G);
NodeID to_try = to_reduce / configuration::getConfig()->threads;
#pragma omp parallel
{
NodeID n_reduce = elementsToReduce(G);
std::mt19937_64 m_mt(configuration::getConfig()->seed
+ omp_get_thread_num());
EdgeID num_edges = G->number_of_edges();
size_t my_n = 0;
size_t tries = 0;
n_reduce = n_reduce / configuration::getConfig()->threads;
while (tries < to_try) {
EdgeWeight e_rand = m_mt() % num_edges;
tries++;
NodeID src = G->getEdgeSource(e_rand);
NodeID tgt = G->getEdgeTarget(e_rand);
if (!uf->SameSet(src, tgt)) {
if (uf->Union(src, tgt)) {
++my_n;
}
}
}
LOG1 << tries << " tries in "
<< t.elapsed() << "s (success in " << my_n << ")";
}
return uf->n();
}
std::shared_ptr<graph_access> one_ks(
std::shared_ptr<graph_access> G_in) {
union_find uf(G_in->number_of_nodes());
timer t;
if (configuration::getConfig()->sampling_type == "geometric")
sample_geometric(G_in, &uf);
if (configuration::getConfig()->sampling_type == "random")
sample_contractible(G_in, &uf);
if (configuration::getConfig()->sampling_type == "separate")
sample_contractible_separate(G_in, &uf);
if (configuration::getConfig()->sampling_type == "weighted")
sample_contractible_weighted(G_in, &uf);
LOG1 << "t " << t.elapsed() << " sample";
auto [map, rev_map] = createMappings(G_in, &uf);
std::shared_ptr<graph_access> G2 =
contraction::contractGraph(G_in, map, rev_map);
LOG1 << "t " << t.elapsed() << " for contraction from "
<< G_in->number_of_nodes() << " to " << G2->number_of_nodes();
return G2;
}
std::shared_ptr<graph_access> random_matching(
std::shared_ptr<graph_access> G_in) {
std::shared_ptr<graph_access> G_out = std::make_shared<graph_access>();
const size_t MAX_TRIES = 50;
size_t no_of_coarse_vertices = 0;
std::vector<NodeID> edge_matching(G_in->number_of_nodes());
for (NodeID n : G_in->nodes()) {
edge_matching[n] = n;
}
std::vector<NodeID> coarse_mapping(G_in->number_of_nodes());
for (NodeID n : G_in->nodes()) {
if (edge_matching[n] == n) {
size_t no_try = 0;
NodeID matchingPartner = n;
while (no_try < MAX_TRIES) {
// match with a random neighbor
EdgeID s = G_in->get_first_edge(n);
EdgeID modulo = G_in->getNodeDegree(n);
EdgeID r = s + (random_functions::next() % modulo);
NodeID tgt = G_in->getEdgeTarget(r);
if (edge_matching[tgt] == tgt) {
matchingPartner = tgt;
break;
}
no_try++;
}
if (no_try == MAX_TRIES) {
coarse_mapping[n] = no_of_coarse_vertices;
edge_matching[n] = n;
no_of_coarse_vertices++;
} else {
coarse_mapping[matchingPartner] = no_of_coarse_vertices;
coarse_mapping[n] = no_of_coarse_vertices;
edge_matching[matchingPartner] = n;
edge_matching[n] = matchingPartner;
no_of_coarse_vertices++;
}
}
}
G_out->start_construction(no_of_coarse_vertices,
G_in->number_of_edges());
std::vector<std::pair<NodeID, NodeID> > edge_positions(
no_of_coarse_vertices,
std::make_pair(-1, -1));
NodeID cur_no_vertices = 0;
size_t edgerino = 0;
for (NodeID n : G_in->nodes()) {
// we look only at the coarser nodes
if (coarse_mapping[n] < cur_no_vertices)
continue;
NodeID coarseNode = G_out->new_node();
// do something with all outgoing edges (in auxillary graph)
for (EdgeID e : G_in->edges_of(n)) {
edgerino++;
EdgeID new_coarse_edge_target = coarse_mapping[
G_in->getEdgeTarget(e)];
if (new_coarse_edge_target == coarseNode) continue;
auto pos = edge_positions[new_coarse_edge_target];
if (pos.first != coarseNode) {
EdgeID coarseEdge =
G_out->new_edge(coarseNode, new_coarse_edge_target);
G_out->setEdgeWeight(coarseEdge, G_in->getEdgeWeight(e));
edge_positions[new_coarse_edge_target] =
std::make_pair(coarseNode, coarseEdge);
} else {
EdgeWeight new_weight = G_out->getEdgeWeight(pos.second)
+ G_in->getEdgeWeight(e);
G_out->setEdgeWeight(pos.second, new_weight);
}
}
// this node was really matched
NodeID matched_neighbor = edge_matching[n];
if (n != matched_neighbor) {
for (EdgeID e : G_in->edges_of(matched_neighbor)) {
EdgeID new_coarse_edge_target = coarse_mapping[
G_in->getEdgeTarget(e)];
if (new_coarse_edge_target == coarseNode) continue;
auto pos = edge_positions[new_coarse_edge_target];
if (pos.first != coarseNode) {
EdgeID coarseEdge = G_out->new_edge(
coarseNode, new_coarse_edge_target);
G_out->setEdgeWeight(coarseEdge,
G_in->getEdgeWeight(e));
edge_positions[new_coarse_edge_target] =
std::make_pair(coarseNode, coarseEdge);
} else {
EdgeWeight new_weight = G_out->getEdgeWeight(pos.second)
+ G_in->getEdgeWeight(e);
G_out->setEdgeWeight(pos.second, new_weight);
}
}
}
cur_no_vertices++;
}
// this also resizes the edge fields ...
G_out->finish_construction();
return G_out;
}
std::shared_ptr<graph_access> remove_heavy_vertices(
std::shared_ptr<graph_access> G_in, double percentile,
std::vector<NodeID>* ps) {
std::vector<NodeID>& prefixsum = *ps;
std::shared_ptr<graph_access> G_out = std::make_shared<graph_access>();
EdgeWeight bound_deg = G_in->getPercentile(percentile);
// new vertex ids in sparser graph
prefixsum.resize(G_in->number_of_nodes());
size_t ctr = 0;
// this is an upper bound, as edges to dense vectors are also counted.
// we can resize the edge vector afterwards though, no need to check
// each edge (todo: if slow, this needs to be changed for parallelism)
size_t existing_edges = 0;
for (NodeID n : G_in->nodes()) {
if (G_in->getWeightedNodeDegree(n) < bound_deg) {
prefixsum[n] = ctr++;
existing_edges += G_in->getNodeDegree(n);
} else {
prefixsum[n] = G_in->number_of_nodes();
}
}
G_out->start_construction(ctr, existing_edges);
size_t actually_edges = 0;
for (NodeID n : G_in->nodes()) {
size_t pre = prefixsum[n];
if (pre < G_in->number_of_nodes()) {
G_out->new_node();
for (EdgeID e : G_in->edges_of(n)) {
NodeID target = G_in->getEdgeTarget(e);
size_t pretgt = prefixsum[target];
if (prefixsum[target] < G_in->number_of_nodes()) {
G_out->new_edge(pre, pretgt);
actually_edges++;
}
}
}
}
G_out->finish_construction();
return G_out;
}
};
|
HR_HDRImageTool.h | #pragma once
#include <vector>
#include <string>
#if defined WIN32
#include <windows.h>
#endif
#include <cmath>
#include <cstdint>
#include "FreeImage.h"
#include "HR_HDRImage.h"
namespace HydraRender
{
void FreeImageErrorHandler(FREE_IMAGE_FORMAT fif, const char *message);
void SaveHDRImageToFileHDR(const std::string& a_fileName, int w, int h, const float* a_data);
void SaveImageToFile(const std::string& a_fileName, int w, int h, unsigned int* data);
void SaveImageToFile(const std::string& a_fileName, const HydraRender::HDRImage4f& image, float a_gamma = 2.2f);
void SaveHDRImageToFileHDR(const std::wstring& a_fileName, int w, int h, const float* a_data);
void SaveImageToFile (const std::wstring& a_fileName, int w, int h, const unsigned int* data);
void SaveImageToFile (const std::wstring& a_fileName, const HydraRender::HDRImage4f& image, float a_gamma = 2.2f);
void LoadImageFromFile(const std::string& a_fileName, std::vector<float>& data, int& w, int& h);
void LoadImageFromFile(const std::string& a_fileName, HydraRender::HDRImage4f& image);
void LoadImageFromFile(const std::wstring& a_fileName, std::vector<float>& data, int& w, int& h);
void LoadImageFromFile(const std::wstring& a_fileName, HydraRender::HDRImage4f& image);
bool LoadLDRImageFromFile(const char* a_fileName,
int* pW, int* pH, std::vector<int32_t>& a_data);
float MSE_RGB_LDR(const std::vector<int32_t>& image1, const std::vector<int32_t>& image2);
template<typename ContainerT>
float MSE(const ContainerT& image1, const ContainerT& image2)
{
if (image1.size() != image2.size())
return 100000.0f;
double summ = 0;
#pragma omp parallel for reduction(+:summ)
for (int i = 0; i < image1.size(); i++)
{
auto c1 = image1[i];
auto c2 = image2[i];
summ += double((c1 - c2)*(c1 - c2));
}
return float(summ) / float(image1.size());
}
template<typename ContainerT>
float MSE3(const ContainerT& image1, const ContainerT& image2)
{
if (image1.size() != image2.size())
return 100000.0f;
double summ = 0;
#pragma omp parallel for reduction(+:summ)
for (int i = 0; i < image1.size(); i+=4)
{
auto c1x = image1[i + 0];
auto c2x = image2[i + 0];
auto c1y = image1[i + 1];
auto c2y = image2[i + 1];
auto c1z = image1[i + 2];
auto c2z = image2[i + 2];
summ += double((c1x - c2x)*(c1x - c2x) + (c1y - c2y)*(c1y - c2y) + (c1z - c2z)*(c1z - c2z));
}
return float(summ) / float(image1.size());
}
};
|
Sema.h | //===--- Sema.h - Semantic Analysis & AST Building --------------*- 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
//
//===----------------------------------------------------------------------===//
//
// This file defines the Sema class, which performs semantic analysis and
// builds ASTs.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_SEMA_H
#define LLVM_CLANG_SEMA_SEMA_H
#include "clang/AST/ASTConcept.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Availability.h"
#include "clang/AST/ComparisonCategories.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/DeclarationName.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/ExternalASTSource.h"
#include "clang/AST/LocInfoType.h"
#include "clang/AST/MangleNumberingContext.h"
#include "clang/AST/NSAPI.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/AST/StmtCXX.h"
#include "clang/AST/TypeLoc.h"
#include "clang/APINotes/APINotesManager.h"
#include "clang/AST/TypeOrdering.h"
#include "clang/Basic/BitmaskEnum.h"
#include "clang/Basic/ExpressionTraits.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/OpenMPKinds.h"
#include "clang/Basic/PragmaKinds.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Basic/TemplateKinds.h"
#include "clang/Basic/TypeTraits.h"
#include "clang/Sema/AnalysisBasedWarnings.h"
#include "clang/Sema/CleanupInfo.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/ExternalSemaSource.h"
#include "clang/Sema/IdentifierResolver.h"
#include "clang/Sema/ObjCMethodList.h"
#include "clang/Sema/Ownership.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/TypoCorrection.h"
#include "clang/Sema/Weak.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/TinyPtrVector.h"
#include <deque>
#include <functional>
#include <memory>
#include <string>
#include <tuple>
#include <vector>
namespace llvm {
class APSInt;
template <typename ValueT> struct DenseMapInfo;
template <typename ValueT, typename ValueInfoT> class DenseSet;
class SmallBitVector;
struct InlineAsmIdentifierInfo;
}
namespace clang {
class ADLResult;
class ASTConsumer;
class ASTContext;
class ASTMutationListener;
class ASTReader;
class ASTWriter;
class ArrayType;
class ParsedAttr;
class BindingDecl;
class BlockDecl;
class CapturedDecl;
class CXXBasePath;
class CXXBasePaths;
class CXXBindTemporaryExpr;
typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
class CXXConstructorDecl;
class CXXConversionDecl;
class CXXDeleteExpr;
class CXXDestructorDecl;
class CXXFieldCollector;
class CXXMemberCallExpr;
class CXXMethodDecl;
class CXXScopeSpec;
class CXXTemporary;
class CXXTryStmt;
class CallExpr;
class ClassTemplateDecl;
class ClassTemplatePartialSpecializationDecl;
class ClassTemplateSpecializationDecl;
class VarTemplatePartialSpecializationDecl;
class CodeCompleteConsumer;
class CodeCompletionAllocator;
class CodeCompletionTUInfo;
class CodeCompletionResult;
class CoroutineBodyStmt;
class Decl;
class DeclAccessPair;
class DeclContext;
class DeclRefExpr;
class DeclaratorDecl;
class DeducedTemplateArgument;
class DependentDiagnostic;
class DesignatedInitExpr;
class Designation;
class EnableIfAttr;
class EnumConstantDecl;
class Expr;
class ExtVectorType;
class FormatAttr;
class FriendDecl;
class FunctionDecl;
class FunctionProtoType;
class FunctionTemplateDecl;
class ImplicitConversionSequence;
typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
class InitListExpr;
class InitializationKind;
class InitializationSequence;
class InitializedEntity;
class IntegerLiteral;
class LabelStmt;
class LambdaExpr;
class LangOptions;
class LocalInstantiationScope;
class LookupResult;
class MacroInfo;
typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
class ModuleLoader;
class MultiLevelTemplateArgumentList;
class NamedDecl;
class ObjCCategoryDecl;
class ObjCCategoryImplDecl;
class ObjCCompatibleAliasDecl;
class ObjCContainerDecl;
class ObjCImplDecl;
class ObjCImplementationDecl;
class ObjCInterfaceDecl;
class ObjCIvarDecl;
template <class T> class ObjCList;
class ObjCMessageExpr;
class ObjCMethodDecl;
class ObjCPropertyDecl;
class ObjCProtocolDecl;
class OMPThreadPrivateDecl;
class OMPRequiresDecl;
class OMPDeclareReductionDecl;
class OMPDeclareSimdDecl;
class OMPClause;
struct OMPVarListLocTy;
struct OverloadCandidate;
enum class OverloadCandidateParamOrder : char;
enum OverloadCandidateRewriteKind : unsigned;
class OverloadCandidateSet;
class OverloadExpr;
class ParenListExpr;
class ParmVarDecl;
class Preprocessor;
class PseudoDestructorTypeStorage;
class PseudoObjectExpr;
class QualType;
class StandardConversionSequence;
class Stmt;
class StringLiteral;
class SwitchStmt;
class TemplateArgument;
class TemplateArgumentList;
class TemplateArgumentLoc;
class TemplateDecl;
class TemplateInstantiationCallback;
class TemplateParameterList;
class TemplatePartialOrderingContext;
class TemplateTemplateParmDecl;
class Token;
class TypeAliasDecl;
class TypedefDecl;
class TypedefNameDecl;
class TypeLoc;
class TypoCorrectionConsumer;
class UnqualifiedId;
class UnresolvedLookupExpr;
class UnresolvedMemberExpr;
class UnresolvedSetImpl;
class UnresolvedSetIterator;
class UsingDecl;
class UsingShadowDecl;
class ValueDecl;
class VarDecl;
class VarTemplateSpecializationDecl;
class VisibilityAttr;
class VisibleDeclConsumer;
class IndirectFieldDecl;
struct DeductionFailureInfo;
class TemplateSpecCandidateSet;
namespace sema {
class AccessedEntity;
class BlockScopeInfo;
class Capture;
class CapturedRegionScopeInfo;
class CapturingScopeInfo;
class CompoundScopeInfo;
class DelayedDiagnostic;
class DelayedDiagnosticPool;
class FunctionScopeInfo;
class LambdaScopeInfo;
class PossiblyUnreachableDiag;
class SemaPPCallbacks;
class TemplateDeductionInfo;
}
namespace threadSafety {
class BeforeSet;
void threadSafetyCleanup(BeforeSet* Cache);
}
// FIXME: No way to easily map from TemplateTypeParmTypes to
// TemplateTypeParmDecls, so we have this horrible PointerUnion.
typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
SourceLocation> UnexpandedParameterPack;
/// Describes whether we've seen any nullability information for the given
/// file.
struct FileNullability {
/// The first pointer declarator (of any pointer kind) in the file that does
/// not have a corresponding nullability annotation.
SourceLocation PointerLoc;
/// The end location for the first pointer declarator in the file. Used for
/// placing fix-its.
SourceLocation PointerEndLoc;
/// Which kind of pointer declarator we saw.
uint8_t PointerKind;
/// Whether we saw any type nullability annotations in the given file.
bool SawTypeNullability = false;
};
/// A mapping from file IDs to a record of whether we've seen nullability
/// information in that file.
class FileNullabilityMap {
/// A mapping from file IDs to the nullability information for each file ID.
llvm::DenseMap<FileID, FileNullability> Map;
/// A single-element cache based on the file ID.
struct {
FileID File;
FileNullability Nullability;
} Cache;
public:
FileNullability &operator[](FileID file) {
// Check the single-element cache.
if (file == Cache.File)
return Cache.Nullability;
// It's not in the single-element cache; flush the cache if we have one.
if (!Cache.File.isInvalid()) {
Map[Cache.File] = Cache.Nullability;
}
// Pull this entry into the cache.
Cache.File = file;
Cache.Nullability = Map[file];
return Cache.Nullability;
}
};
/// Keeps track of expected type during expression parsing. The type is tied to
/// a particular token, all functions that update or consume the type take a
/// start location of the token they are looking at as a parameter. This allows
/// to avoid updating the type on hot paths in the parser.
class PreferredTypeBuilder {
public:
PreferredTypeBuilder() = default;
explicit PreferredTypeBuilder(QualType Type) : Type(Type) {}
void enterCondition(Sema &S, SourceLocation Tok);
void enterReturn(Sema &S, SourceLocation Tok);
void enterVariableInit(SourceLocation Tok, Decl *D);
/// Computing a type for the function argument may require running
/// overloading, so we postpone its computation until it is actually needed.
///
/// Clients should be very careful when using this funciton, as it stores a
/// function_ref, clients should make sure all calls to get() with the same
/// location happen while function_ref is alive.
void enterFunctionArgument(SourceLocation Tok,
llvm::function_ref<QualType()> ComputeType);
void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
SourceLocation OpLoc);
void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
/// Handles all type casts, including C-style cast, C++ casts, etc.
void enterTypeCast(SourceLocation Tok, QualType CastType);
QualType get(SourceLocation Tok) const {
if (Tok != ExpectedLoc)
return QualType();
if (!Type.isNull())
return Type;
if (ComputeType)
return ComputeType();
return QualType();
}
private:
/// Start position of a token for which we store expected type.
SourceLocation ExpectedLoc;
/// Expected type for a token starting at ExpectedLoc.
QualType Type;
/// A function to compute expected type at ExpectedLoc. It is only considered
/// if Type is null.
llvm::function_ref<QualType()> ComputeType;
};
/// Sema - This implements semantic analysis and AST building for C.
class Sema final {
Sema(const Sema &) = delete;
void operator=(const Sema &) = delete;
/// A key method to reduce duplicate debug info from Sema.
virtual void anchor();
///Source of additional semantic information.
ExternalSemaSource *ExternalSource;
///Whether Sema has generated a multiplexer and has to delete it.
bool isMultiplexExternalSource;
static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
bool isVisibleSlow(const NamedDecl *D);
/// Determine whether two declarations should be linked together, given that
/// the old declaration might not be visible and the new declaration might
/// not have external linkage.
bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
const NamedDecl *New) {
if (isVisible(Old))
return true;
// See comment in below overload for why it's safe to compute the linkage
// of the new declaration here.
if (New->isExternallyDeclarable()) {
assert(Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl");
return true;
}
return false;
}
bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
QualType ResultTy,
ArrayRef<QualType> Args);
public:
typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
typedef OpaquePtr<TemplateName> TemplateTy;
typedef OpaquePtr<QualType> TypeTy;
OpenCLOptions OpenCLFeatures;
FPOptions FPFeatures;
const LangOptions &LangOpts;
Preprocessor &PP;
ASTContext &Context;
ASTConsumer &Consumer;
DiagnosticsEngine &Diags;
SourceManager &SourceMgr;
api_notes::APINotesManager APINotes;
/// Flag indicating whether or not to collect detailed statistics.
bool CollectStats;
/// Code-completion consumer.
CodeCompleteConsumer *CodeCompleter;
/// CurContext - This is the current declaration context of parsing.
DeclContext *CurContext;
/// Generally null except when we temporarily switch decl contexts,
/// like in \see ActOnObjCTemporaryExitContainerContext.
DeclContext *OriginalLexicalContext;
/// VAListTagName - The declaration name corresponding to __va_list_tag.
/// This is used as part of a hack to omit that class from ADL results.
DeclarationName VAListTagName;
bool MSStructPragmaOn; // True when \#pragma ms_struct on
/// Controls member pointer representation format under the MS ABI.
LangOptions::PragmaMSPointersToMembersKind
MSPointerToMemberRepresentationMethod;
/// Stack of active SEH __finally scopes. Can be empty.
SmallVector<Scope*, 2> CurrentSEHFinally;
/// Source location for newly created implicit MSInheritanceAttrs
SourceLocation ImplicitMSInheritanceAttrLoc;
/// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
/// `TransformTypos` in order to keep track of any TypoExprs that are created
/// recursively during typo correction and wipe them away if the correction
/// fails.
llvm::SmallVector<TypoExpr *, 2> TypoExprs;
/// pragma clang section kind
enum PragmaClangSectionKind {
PCSK_Invalid = 0,
PCSK_BSS = 1,
PCSK_Data = 2,
PCSK_Rodata = 3,
PCSK_Text = 4,
PCSK_Relro = 5
};
enum PragmaClangSectionAction {
PCSA_Set = 0,
PCSA_Clear = 1
};
struct PragmaClangSection {
std::string SectionName;
bool Valid = false;
SourceLocation PragmaLocation;
void Act(SourceLocation PragmaLocation,
PragmaClangSectionAction Action,
StringLiteral* Name);
};
PragmaClangSection PragmaClangBSSSection;
PragmaClangSection PragmaClangDataSection;
PragmaClangSection PragmaClangRodataSection;
PragmaClangSection PragmaClangRelroSection;
PragmaClangSection PragmaClangTextSection;
enum PragmaMsStackAction {
PSK_Reset = 0x0, // #pragma ()
PSK_Set = 0x1, // #pragma (value)
PSK_Push = 0x2, // #pragma (push[, id])
PSK_Pop = 0x4, // #pragma (pop[, id])
PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
};
template<typename ValueType>
struct PragmaStack {
struct Slot {
llvm::StringRef StackSlotLabel;
ValueType Value;
SourceLocation PragmaLocation;
SourceLocation PragmaPushLocation;
Slot(llvm::StringRef StackSlotLabel, ValueType Value,
SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
: StackSlotLabel(StackSlotLabel), Value(Value),
PragmaLocation(PragmaLocation),
PragmaPushLocation(PragmaPushLocation) {}
};
void Act(SourceLocation PragmaLocation,
PragmaMsStackAction Action,
llvm::StringRef StackSlotLabel,
ValueType Value);
// MSVC seems to add artificial slots to #pragma stacks on entering a C++
// method body to restore the stacks on exit, so it works like this:
//
// struct S {
// #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
// void Method {}
// #pragma <name>(pop, InternalPragmaSlot)
// };
//
// It works even with #pragma vtordisp, although MSVC doesn't support
// #pragma vtordisp(push [, id], n)
// syntax.
//
// Push / pop a named sentinel slot.
void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
assert((Action == PSK_Push || Action == PSK_Pop) &&
"Can only push / pop #pragma stack sentinels!");
Act(CurrentPragmaLocation, Action, Label, CurrentValue);
}
// Constructors.
explicit PragmaStack(const ValueType &Default)
: DefaultValue(Default), CurrentValue(Default) {}
bool hasValue() const { return CurrentValue != DefaultValue; }
SmallVector<Slot, 2> Stack;
ValueType DefaultValue; // Value used for PSK_Reset action.
ValueType CurrentValue;
SourceLocation CurrentPragmaLocation;
};
// FIXME: We should serialize / deserialize these if they occur in a PCH (but
// we shouldn't do so if they're in a module).
/// Whether to insert vtordisps prior to virtual bases in the Microsoft
/// C++ ABI. Possible values are 0, 1, and 2, which mean:
///
/// 0: Suppress all vtordisps
/// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
/// structors
/// 2: Always insert vtordisps to support RTTI on partially constructed
/// objects
PragmaStack<MSVtorDispMode> VtorDispStack;
// #pragma pack.
// Sentinel to represent when the stack is set to mac68k alignment.
static const unsigned kMac68kAlignmentSentinel = ~0U;
PragmaStack<unsigned> PackStack;
// The current #pragma pack values and locations at each #include.
struct PackIncludeState {
unsigned CurrentValue;
SourceLocation CurrentPragmaLocation;
bool HasNonDefaultValue, ShouldWarnOnInclude;
};
SmallVector<PackIncludeState, 8> PackIncludeStack;
// Segment #pragmas.
PragmaStack<StringLiteral *> DataSegStack;
PragmaStack<StringLiteral *> BSSSegStack;
PragmaStack<StringLiteral *> ConstSegStack;
PragmaStack<StringLiteral *> CodeSegStack;
// RAII object to push / pop sentinel slots for all MS #pragma stacks.
// Actions should be performed only if we enter / exit a C++ method body.
class PragmaStackSentinelRAII {
public:
PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
~PragmaStackSentinelRAII();
private:
Sema &S;
StringRef SlotLabel;
bool ShouldAct;
};
/// A mapping that describes the nullability we've seen in each header file.
FileNullabilityMap NullabilityMap;
/// Last section used with #pragma init_seg.
StringLiteral *CurInitSeg;
SourceLocation CurInitSegLoc;
/// VisContext - Manages the stack for \#pragma GCC visibility.
void *VisContext; // Really a "PragmaVisStack*"
/// This an attribute introduced by \#pragma clang attribute.
struct PragmaAttributeEntry {
SourceLocation Loc;
ParsedAttr *Attribute;
SmallVector<attr::SubjectMatchRule, 4> MatchRules;
bool IsUsed;
};
/// A push'd group of PragmaAttributeEntries.
struct PragmaAttributeGroup {
/// The location of the push attribute.
SourceLocation Loc;
/// The namespace of this push group.
const IdentifierInfo *Namespace;
SmallVector<PragmaAttributeEntry, 2> Entries;
};
SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
/// The declaration that is currently receiving an attribute from the
/// #pragma attribute stack.
const Decl *PragmaAttributeCurrentTargetDecl;
/// This represents the last location of a "#pragma clang optimize off"
/// directive if such a directive has not been closed by an "on" yet. If
/// optimizations are currently "on", this is set to an invalid location.
SourceLocation OptimizeOffPragmaLocation;
/// Flag indicating if Sema is building a recovery call expression.
///
/// This flag is used to avoid building recovery call expressions
/// if Sema is already doing so, which would cause infinite recursions.
bool IsBuildingRecoveryCallExpr;
/// Used to control the generation of ExprWithCleanups.
CleanupInfo Cleanup;
/// ExprCleanupObjects - This is the stack of objects requiring
/// cleanup that are created by the current full expression. The
/// element type here is ExprWithCleanups::Object.
SmallVector<BlockDecl*, 8> ExprCleanupObjects;
/// Store a set of either DeclRefExprs or MemberExprs that contain a reference
/// to a variable (constant) that may or may not be odr-used in this Expr, and
/// we won't know until all lvalue-to-rvalue and discarded value conversions
/// have been applied to all subexpressions of the enclosing full expression.
/// This is cleared at the end of each full expression.
using MaybeODRUseExprSet = llvm::SmallPtrSet<Expr *, 2>;
MaybeODRUseExprSet MaybeODRUseExprs;
std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
/// Stack containing information about each of the nested
/// function, block, and method scopes that are currently active.
SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadExtVectorDecls, 2, 2>
ExtVectorDeclsType;
/// ExtVectorDecls - This is a list all the extended vector types. This allows
/// us to associate a raw vector type with one of the ext_vector type names.
/// This is only necessary for issuing pretty diagnostics.
ExtVectorDeclsType ExtVectorDecls;
/// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
std::unique_ptr<CXXFieldCollector> FieldCollector;
typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
/// Set containing all declared private fields that are not used.
NamedDeclSetType UnusedPrivateFields;
/// Set containing all typedefs that are likely unused.
llvm::SmallSetVector<const TypedefNameDecl *, 4>
UnusedLocalTypedefNameCandidates;
/// Delete-expressions to be analyzed at the end of translation unit
///
/// This list contains class members, and locations of delete-expressions
/// that could not be proven as to whether they mismatch with new-expression
/// used in initializer of the field.
typedef std::pair<SourceLocation, bool> DeleteExprLoc;
typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
/// PureVirtualClassDiagSet - a set of class declarations which we have
/// emitted a list of pure virtual functions. Used to prevent emitting the
/// same list more than once.
std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
/// ParsingInitForAutoVars - a set of declarations with auto types for which
/// we are currently parsing the initializer.
llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
/// Look for a locally scoped extern "C" declaration by the given name.
NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
typedef LazyVector<VarDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
TentativeDefinitionsType;
/// All the tentative definitions encountered in the TU.
TentativeDefinitionsType TentativeDefinitions;
/// All the external declarations encoutered and used in the TU.
SmallVector<VarDecl *, 4> ExternalDeclarations;
typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
UnusedFileScopedDeclsType;
/// The set of file scoped decls seen so far that have not been used
/// and must warn if not used. Only contains the first declaration.
UnusedFileScopedDeclsType UnusedFileScopedDecls;
typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
DelegatingCtorDeclsType;
/// All the delegating constructors seen so far in the file, used for
/// cycle detection at the end of the TU.
DelegatingCtorDeclsType DelegatingCtorDecls;
/// All the overriding functions seen during a class definition
/// that had their exception spec checks delayed, plus the overridden
/// function.
SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
DelayedOverridingExceptionSpecChecks;
/// All the function redeclarations seen during a class definition that had
/// their exception spec checks delayed, plus the prior declaration they
/// should be checked against. Except during error recovery, the new decl
/// should always be a friend declaration, as that's the only valid way to
/// redeclare a special member before its class is complete.
SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
DelayedEquivalentExceptionSpecChecks;
typedef llvm::MapVector<const FunctionDecl *,
std::unique_ptr<LateParsedTemplate>>
LateParsedTemplateMapT;
LateParsedTemplateMapT LateParsedTemplateMap;
/// Callback to the parser to parse templated functions when needed.
typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
typedef void LateTemplateParserCleanupCB(void *P);
LateTemplateParserCB *LateTemplateParser;
LateTemplateParserCleanupCB *LateTemplateParserCleanup;
void *OpaqueParser;
void SetLateTemplateParser(LateTemplateParserCB *LTP,
LateTemplateParserCleanupCB *LTPCleanup,
void *P) {
LateTemplateParser = LTP;
LateTemplateParserCleanup = LTPCleanup;
OpaqueParser = P;
}
/// \brief Callback to the parser to parse a type expressed as a string.
std::function<TypeResult(StringRef, StringRef, SourceLocation)>
ParseTypeFromStringCallback;
class DelayedDiagnostics;
class DelayedDiagnosticsState {
sema::DelayedDiagnosticPool *SavedPool;
friend class Sema::DelayedDiagnostics;
};
typedef DelayedDiagnosticsState ParsingDeclState;
typedef DelayedDiagnosticsState ProcessingContextState;
/// A class which encapsulates the logic for delaying diagnostics
/// during parsing and other processing.
class DelayedDiagnostics {
/// The current pool of diagnostics into which delayed
/// diagnostics should go.
sema::DelayedDiagnosticPool *CurPool;
public:
DelayedDiagnostics() : CurPool(nullptr) {}
/// Adds a delayed diagnostic.
void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
/// Determines whether diagnostics should be delayed.
bool shouldDelayDiagnostics() { return CurPool != nullptr; }
/// Returns the current delayed-diagnostics pool.
sema::DelayedDiagnosticPool *getCurrentPool() const {
return CurPool;
}
/// Enter a new scope. Access and deprecation diagnostics will be
/// collected in this pool.
DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
DelayedDiagnosticsState state;
state.SavedPool = CurPool;
CurPool = &pool;
return state;
}
/// Leave a delayed-diagnostic state that was previously pushed.
/// Do not emit any of the diagnostics. This is performed as part
/// of the bookkeeping of popping a pool "properly".
void popWithoutEmitting(DelayedDiagnosticsState state) {
CurPool = state.SavedPool;
}
/// Enter a new scope where access and deprecation diagnostics are
/// not delayed.
DelayedDiagnosticsState pushUndelayed() {
DelayedDiagnosticsState state;
state.SavedPool = CurPool;
CurPool = nullptr;
return state;
}
/// Undo a previous pushUndelayed().
void popUndelayed(DelayedDiagnosticsState state) {
assert(CurPool == nullptr);
CurPool = state.SavedPool;
}
} DelayedDiagnostics;
/// A RAII object to temporarily push a declaration context.
class ContextRAII {
private:
Sema &S;
DeclContext *SavedContext;
ProcessingContextState SavedContextState;
QualType SavedCXXThisTypeOverride;
public:
ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
: S(S), SavedContext(S.CurContext),
SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
{
assert(ContextToPush && "pushing null context");
S.CurContext = ContextToPush;
if (NewThisContext)
S.CXXThisTypeOverride = QualType();
}
void pop() {
if (!SavedContext) return;
S.CurContext = SavedContext;
S.DelayedDiagnostics.popUndelayed(SavedContextState);
S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
SavedContext = nullptr;
}
~ContextRAII() {
pop();
}
};
/// Used to change context to isConstantEvaluated without pushing a heavy
/// ExpressionEvaluationContextRecord object.
bool isConstantEvaluatedOverride;
bool isConstantEvaluated() {
return ExprEvalContexts.back().isConstantEvaluated() ||
isConstantEvaluatedOverride;
}
/// RAII object to handle the state changes required to synthesize
/// a function body.
class SynthesizedFunctionScope {
Sema &S;
Sema::ContextRAII SavedContext;
bool PushedCodeSynthesisContext = false;
public:
SynthesizedFunctionScope(Sema &S, DeclContext *DC)
: S(S), SavedContext(S, DC) {
S.PushFunctionScope();
S.PushExpressionEvaluationContext(
Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
if (auto *FD = dyn_cast<FunctionDecl>(DC))
FD->setWillHaveBody(true);
else
assert(isa<ObjCMethodDecl>(DC));
}
void addContextNote(SourceLocation UseLoc) {
assert(!PushedCodeSynthesisContext);
Sema::CodeSynthesisContext Ctx;
Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
Ctx.PointOfInstantiation = UseLoc;
Ctx.Entity = cast<Decl>(S.CurContext);
S.pushCodeSynthesisContext(Ctx);
PushedCodeSynthesisContext = true;
}
~SynthesizedFunctionScope() {
if (PushedCodeSynthesisContext)
S.popCodeSynthesisContext();
if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
FD->setWillHaveBody(false);
S.PopExpressionEvaluationContext();
S.PopFunctionScopeInfo();
}
};
/// WeakUndeclaredIdentifiers - Identifiers contained in
/// \#pragma weak before declared. rare. may alias another
/// identifier, declared or undeclared
llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
/// ExtnameUndeclaredIdentifiers - Identifiers contained in
/// \#pragma redefine_extname before declared. Used in Solaris system headers
/// to define functions that occur in multiple standards to call the version
/// in the currently selected standard.
llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
/// Load weak undeclared identifiers from the external source.
void LoadExternalWeakUndeclaredIdentifiers();
/// WeakTopLevelDecl - Translation-unit scoped declarations generated by
/// \#pragma weak during processing of other Decls.
/// I couldn't figure out a clean way to generate these in-line, so
/// we store them here and handle separately -- which is a hack.
/// It would be best to refactor this.
SmallVector<Decl*,2> WeakTopLevelDecl;
IdentifierResolver IdResolver;
/// Translation Unit Scope - useful to Objective-C actions that need
/// to lookup file scope declarations in the "ordinary" C decl namespace.
/// For example, user-defined classes, built-in "id" type, etc.
Scope *TUScope;
/// The C++ "std" namespace, where the standard library resides.
LazyDeclPtr StdNamespace;
/// The C++ "std::bad_alloc" class, which is defined by the C++
/// standard library.
LazyDeclPtr StdBadAlloc;
/// The C++ "std::align_val_t" enum class, which is defined by the C++
/// standard library.
LazyDeclPtr StdAlignValT;
/// The C++ "std::experimental" namespace, where the experimental parts
/// of the standard library resides.
NamespaceDecl *StdExperimentalNamespaceCache;
/// The C++ "std::initializer_list" template, which is defined in
/// \<initializer_list>.
ClassTemplateDecl *StdInitializerList;
/// The C++ "std::coroutine_traits" template, which is defined in
/// \<coroutine_traits>
ClassTemplateDecl *StdCoroutineTraitsCache;
/// The C++ "type_info" declaration, which is defined in \<typeinfo>.
RecordDecl *CXXTypeInfoDecl;
/// The MSVC "_GUID" struct, which is defined in MSVC header files.
RecordDecl *MSVCGuidDecl;
/// Caches identifiers/selectors for NSFoundation APIs.
std::unique_ptr<NSAPI> NSAPIObj;
/// The declaration of the Objective-C NSNumber class.
ObjCInterfaceDecl *NSNumberDecl;
/// The declaration of the Objective-C NSValue class.
ObjCInterfaceDecl *NSValueDecl;
/// Pointer to NSNumber type (NSNumber *).
QualType NSNumberPointer;
/// Pointer to NSValue type (NSValue *).
QualType NSValuePointer;
/// The Objective-C NSNumber methods used to create NSNumber literals.
ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
/// The declaration of the Objective-C NSString class.
ObjCInterfaceDecl *NSStringDecl;
/// Pointer to NSString type (NSString *).
QualType NSStringPointer;
/// The declaration of the stringWithUTF8String: method.
ObjCMethodDecl *StringWithUTF8StringMethod;
/// The declaration of the valueWithBytes:objCType: method.
ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
/// The declaration of the Objective-C NSArray class.
ObjCInterfaceDecl *NSArrayDecl;
/// The declaration of the arrayWithObjects:count: method.
ObjCMethodDecl *ArrayWithObjectsMethod;
/// The declaration of the Objective-C NSDictionary class.
ObjCInterfaceDecl *NSDictionaryDecl;
/// The declaration of the dictionaryWithObjects:forKeys:count: method.
ObjCMethodDecl *DictionaryWithObjectsMethod;
/// id<NSCopying> type.
QualType QIDNSCopying;
/// will hold 'respondsToSelector:'
Selector RespondsToSelectorSel;
/// A flag to remember whether the implicit forms of operator new and delete
/// have been declared.
bool GlobalNewDeleteDeclared;
/// A flag to indicate that we're in a context that permits abstract
/// references to fields. This is really a
bool AllowAbstractFieldReference;
/// Describes how the expressions currently being parsed are
/// evaluated at run-time, if at all.
enum class ExpressionEvaluationContext {
/// The current expression and its subexpressions occur within an
/// unevaluated operand (C++11 [expr]p7), such as the subexpression of
/// \c sizeof, where the type of the expression may be significant but
/// no code will be generated to evaluate the value of the expression at
/// run time.
Unevaluated,
/// The current expression occurs within a braced-init-list within
/// an unevaluated operand. This is mostly like a regular unevaluated
/// context, except that we still instantiate constexpr functions that are
/// referenced here so that we can perform narrowing checks correctly.
UnevaluatedList,
/// The current expression occurs within a discarded statement.
/// This behaves largely similarly to an unevaluated operand in preventing
/// definitions from being required, but not in other ways.
DiscardedStatement,
/// The current expression occurs within an unevaluated
/// operand that unconditionally permits abstract references to
/// fields, such as a SIZE operator in MS-style inline assembly.
UnevaluatedAbstract,
/// The current context is "potentially evaluated" in C++11 terms,
/// but the expression is evaluated at compile-time (like the values of
/// cases in a switch statement).
ConstantEvaluated,
/// The current expression is potentially evaluated at run time,
/// which means that code may be generated to evaluate the value of the
/// expression at run time.
PotentiallyEvaluated,
/// The current expression is potentially evaluated, but any
/// declarations referenced inside that expression are only used if
/// in fact the current expression is used.
///
/// This value is used when parsing default function arguments, for which
/// we would like to provide diagnostics (e.g., passing non-POD arguments
/// through varargs) but do not want to mark declarations as "referenced"
/// until the default argument is used.
PotentiallyEvaluatedIfUsed
};
/// Data structure used to record current or nested
/// expression evaluation contexts.
struct ExpressionEvaluationContextRecord {
/// The expression evaluation context.
ExpressionEvaluationContext Context;
/// Whether the enclosing context needed a cleanup.
CleanupInfo ParentCleanup;
/// Whether we are in a decltype expression.
bool IsDecltype;
/// The number of active cleanup objects when we entered
/// this expression evaluation context.
unsigned NumCleanupObjects;
/// The number of typos encountered during this expression evaluation
/// context (i.e. the number of TypoExprs created).
unsigned NumTypos;
MaybeODRUseExprSet SavedMaybeODRUseExprs;
/// The lambdas that are present within this context, if it
/// is indeed an unevaluated context.
SmallVector<LambdaExpr *, 2> Lambdas;
/// The declaration that provides context for lambda expressions
/// and block literals if the normal declaration context does not
/// suffice, e.g., in a default function argument.
Decl *ManglingContextDecl;
/// If we are processing a decltype type, a set of call expressions
/// for which we have deferred checking the completeness of the return type.
SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
/// If we are processing a decltype type, a set of temporary binding
/// expressions for which we have deferred checking the destructor.
SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
/// Expressions appearing as the LHS of a volatile assignment in this
/// context. We produce a warning for these when popping the context if
/// they are not discarded-value expressions nor unevaluated operands.
SmallVector<Expr*, 2> VolatileAssignmentLHSs;
/// \brief Describes whether we are in an expression constext which we have
/// to handle differently.
enum ExpressionKind {
EK_Decltype, EK_TemplateArgument, EK_Other
} ExprContext;
ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
unsigned NumCleanupObjects,
CleanupInfo ParentCleanup,
Decl *ManglingContextDecl,
ExpressionKind ExprContext)
: Context(Context), ParentCleanup(ParentCleanup),
NumCleanupObjects(NumCleanupObjects), NumTypos(0),
ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {}
bool isUnevaluated() const {
return Context == ExpressionEvaluationContext::Unevaluated ||
Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
Context == ExpressionEvaluationContext::UnevaluatedList;
}
bool isConstantEvaluated() const {
return Context == ExpressionEvaluationContext::ConstantEvaluated;
}
};
/// A stack of expression evaluation contexts.
SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
/// Emit a warning for all pending noderef expressions that we recorded.
void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
/// Compute the mangling number context for a lambda expression or
/// block literal. Also return the extra mangling decl if any.
///
/// \param DC - The DeclContext containing the lambda expression or
/// block literal.
std::tuple<MangleNumberingContext *, Decl *>
getCurrentMangleNumberContext(const DeclContext *DC);
/// SpecialMemberOverloadResult - The overloading result for a special member
/// function.
///
/// This is basically a wrapper around PointerIntPair. The lowest bits of the
/// integer are used to determine whether overload resolution succeeded.
class SpecialMemberOverloadResult {
public:
enum Kind {
NoMemberOrDeleted,
Ambiguous,
Success
};
private:
llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
public:
SpecialMemberOverloadResult() : Pair() {}
SpecialMemberOverloadResult(CXXMethodDecl *MD)
: Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
void setKind(Kind K) { Pair.setInt(K); }
};
class SpecialMemberOverloadResultEntry
: public llvm::FastFoldingSetNode,
public SpecialMemberOverloadResult {
public:
SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
: FastFoldingSetNode(ID)
{}
};
/// A cache of special member function overload resolution results
/// for C++ records.
llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
/// A cache of the flags available in enumerations with the flag_bits
/// attribute.
mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
/// The kind of translation unit we are processing.
///
/// When we're processing a complete translation unit, Sema will perform
/// end-of-translation-unit semantic tasks (such as creating
/// initializers for tentative definitions in C) once parsing has
/// completed. Modules and precompiled headers perform different kinds of
/// checks.
TranslationUnitKind TUKind;
llvm::BumpPtrAllocator BumpAlloc;
/// The number of SFINAE diagnostics that have been trapped.
unsigned NumSFINAEErrors;
typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
UnparsedDefaultArgInstantiationsMap;
/// A mapping from parameters with unparsed default arguments to the
/// set of instantiations of each parameter.
///
/// This mapping is a temporary data structure used when parsing
/// nested class templates or nested classes of class templates,
/// where we might end up instantiating an inner class before the
/// default arguments of its methods have been parsed.
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
// Contains the locations of the beginning of unparsed default
// argument locations.
llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
/// UndefinedInternals - all the used, undefined objects which require a
/// definition in this translation unit.
llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
/// Determine if VD, which must be a variable or function, is an external
/// symbol that nonetheless can't be referenced from outside this translation
/// unit because its type has no linkage and it's not extern "C".
bool isExternalWithNoLinkageType(ValueDecl *VD);
/// Obtain a sorted list of functions that are undefined but ODR-used.
void getUndefinedButUsed(
SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
/// Retrieves list of suspicious delete-expressions that will be checked at
/// the end of translation unit.
const llvm::MapVector<FieldDecl *, DeleteLocs> &
getMismatchingDeleteExpressions() const;
typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
/// Method Pool - allows efficient lookup when typechecking messages to "id".
/// We need to maintain a list, since selectors can have differing signatures
/// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
/// of selectors are "overloaded").
/// At the head of the list it is recorded whether there were 0, 1, or >= 2
/// methods inside categories with a particular selector.
GlobalMethodPool MethodPool;
/// Method selectors used in a \@selector expression. Used for implementation
/// of -Wselector.
llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
/// List of SourceLocations where 'self' is implicitly retained inside a
/// block.
llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
ImplicitlyRetainedSelfLocs;
/// Kinds of C++ special members.
enum CXXSpecialMember {
CXXDefaultConstructor,
CXXCopyConstructor,
CXXMoveConstructor,
CXXCopyAssignment,
CXXMoveAssignment,
CXXDestructor,
CXXInvalid
};
typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
SpecialMemberDecl;
/// The C++ special members which we are currently in the process of
/// declaring. If this process recursively triggers the declaration of the
/// same special member, we should act as if it is not yet declared.
llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
/// Kinds of defaulted comparison operator functions.
enum class DefaultedComparisonKind : unsigned char {
/// This is not a defaultable comparison operator.
None,
/// This is an operator== that should be implemented as a series of
/// subobject comparisons.
Equal,
/// This is an operator<=> that should be implemented as a series of
/// subobject comparisons.
ThreeWay,
/// This is an operator!= that should be implemented as a rewrite in terms
/// of a == comparison.
NotEqual,
/// This is an <, <=, >, or >= that should be implemented as a rewrite in
/// terms of a <=> comparison.
Relational,
};
/// The function definitions which were renamed as part of typo-correction
/// to match their respective declarations. We want to keep track of them
/// to ensure that we don't emit a "redefinition" error if we encounter a
/// correctly named definition after the renamed definition.
llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
/// Stack of types that correspond to the parameter entities that are
/// currently being copy-initialized. Can be empty.
llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
void ReadMethodPool(Selector Sel);
void updateOutOfDateSelector(Selector Sel);
/// Private Helper predicate to check for 'self'.
bool isSelfExpr(Expr *RExpr);
bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
/// Cause the active diagnostic on the DiagosticsEngine to be
/// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
/// should not be used elsewhere.
void EmitCurrentDiagnostic(unsigned DiagID);
/// Records and restores the FP_CONTRACT state on entry/exit of compound
/// statements.
class FPContractStateRAII {
public:
FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
private:
Sema& S;
FPOptions OldFPFeaturesState;
};
void addImplicitTypedef(StringRef Name, QualType T);
bool WarnedStackExhausted = false;
public:
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
TranslationUnitKind TUKind = TU_Complete,
CodeCompleteConsumer *CompletionConsumer = nullptr);
~Sema();
/// Perform initialization that occurs after the parser has been
/// initialized but before it parses anything.
void Initialize();
const LangOptions &getLangOpts() const { return LangOpts; }
OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
FPOptions &getFPOptions() { return FPFeatures; }
DiagnosticsEngine &getDiagnostics() const { return Diags; }
SourceManager &getSourceManager() const { return SourceMgr; }
Preprocessor &getPreprocessor() const { return PP; }
ASTContext &getASTContext() const { return Context; }
ASTConsumer &getASTConsumer() const { return Consumer; }
ASTMutationListener *getASTMutationListener() const;
ExternalSemaSource* getExternalSource() const { return ExternalSource; }
///Registers an external source. If an external source already exists,
/// creates a multiplex external source and appends to it.
///
///\param[in] E - A non-null external sema source.
///
void addExternalSource(ExternalSemaSource *E);
void PrintStats() const;
/// Warn that the stack is nearly exhausted.
void warnStackExhausted(SourceLocation Loc);
/// Run some code with "sufficient" stack space. (Currently, at least 256K is
/// guaranteed). Produces a warning if we're low on stack space and allocates
/// more in that case. Use this in code that may recurse deeply (for example,
/// in template instantiation) to avoid stack overflow.
void runWithSufficientStackSpace(SourceLocation Loc,
llvm::function_ref<void()> Fn);
/// Helper class that creates diagnostics with optional
/// template instantiation stacks.
///
/// This class provides a wrapper around the basic DiagnosticBuilder
/// class that emits diagnostics. SemaDiagnosticBuilder is
/// responsible for emitting the diagnostic (as DiagnosticBuilder
/// does) and, if the diagnostic comes from inside a template
/// instantiation, printing the template instantiation stack as
/// well.
class SemaDiagnosticBuilder : public DiagnosticBuilder {
Sema &SemaRef;
unsigned DiagID;
public:
SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
: DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
// This is a cunning lie. DiagnosticBuilder actually performs move
// construction in its copy constructor (but due to varied uses, it's not
// possible to conveniently express this as actual move construction). So
// the default copy ctor here is fine, because the base class disables the
// source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
// in that case anwyay.
SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
~SemaDiagnosticBuilder() {
// If we aren't active, there is nothing to do.
if (!isActive()) return;
// Otherwise, we need to emit the diagnostic. First flush the underlying
// DiagnosticBuilder data, and clear the diagnostic builder itself so it
// won't emit the diagnostic in its own destructor.
//
// This seems wasteful, in that as written the DiagnosticBuilder dtor will
// do its own needless checks to see if the diagnostic needs to be
// emitted. However, because we take care to ensure that the builder
// objects never escape, a sufficiently smart compiler will be able to
// eliminate that code.
FlushCounts();
Clear();
// Dispatch to Sema to emit the diagnostic.
SemaRef.EmitCurrentDiagnostic(DiagID);
}
/// Teach operator<< to produce an object of the correct type.
template<typename T>
friend const SemaDiagnosticBuilder &operator<<(
const SemaDiagnosticBuilder &Diag, const T &Value) {
const DiagnosticBuilder &BaseDiag = Diag;
BaseDiag << Value;
return Diag;
}
};
/// Emit a diagnostic.
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
return SemaDiagnosticBuilder(DB, *this, DiagID);
}
/// Emit a partial diagnostic.
SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
/// Build a partial diagnostic.
PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
bool findMacroSpelling(SourceLocation &loc, StringRef name);
/// Get a string to suggest for zero-initialization of a type.
std::string
getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
/// Calls \c Lexer::getLocForEndOfToken()
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
/// Retrieve the module loader associated with the preprocessor.
ModuleLoader &getModuleLoader() const;
void emitAndClearUnusedLocalTypedefWarnings();
enum TUFragmentKind {
/// The global module fragment, between 'module;' and a module-declaration.
Global,
/// A normal translation unit fragment. For a non-module unit, this is the
/// entire translation unit. Otherwise, it runs from the module-declaration
/// to the private-module-fragment (if any) or the end of the TU (if not).
Normal,
/// The private module fragment, between 'module :private;' and the end of
/// the translation unit.
Private
};
void ActOnStartOfTranslationUnit();
void ActOnEndOfTranslationUnit();
void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
void CheckDelegatingCtorCycles();
Scope *getScopeForContext(DeclContext *Ctx);
void PushFunctionScope();
void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
sema::LambdaScopeInfo *PushLambdaScope();
/// This is used to inform Sema what the current TemplateParameterDepth
/// is during Parsing. Currently it is used to pass on the depth
/// when parsing generic lambda 'auto' parameters.
void RecordParsingTemplateParameterDepth(unsigned Depth);
void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
RecordDecl *RD, CapturedRegionKind K,
unsigned OpenMPCaptureLevel = 0);
/// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
/// time after they've been popped.
class PoppedFunctionScopeDeleter {
Sema *Self;
public:
explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
void operator()(sema::FunctionScopeInfo *Scope) const;
};
using PoppedFunctionScopePtr =
std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
PoppedFunctionScopePtr
PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
const Decl *D = nullptr,
QualType BlockType = QualType());
sema::FunctionScopeInfo *getCurFunction() const {
return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
}
sema::FunctionScopeInfo *getEnclosingFunction() const;
void setFunctionHasBranchIntoScope();
void setFunctionHasBranchProtectedScope();
void setFunctionHasIndirectGoto();
void PushCompoundScope(bool IsStmtExpr);
void PopCompoundScope();
sema::CompoundScopeInfo &getCurCompoundScope() const;
bool hasAnyUnrecoverableErrorsInThisFunction() const;
/// Retrieve the current block, if any.
sema::BlockScopeInfo *getCurBlock();
/// Get the innermost lambda enclosing the current location, if any. This
/// looks through intervening non-lambda scopes such as local functions and
/// blocks.
sema::LambdaScopeInfo *getEnclosingLambda() const;
/// Retrieve the current lambda scope info, if any.
/// \param IgnoreNonLambdaCapturingScope true if should find the top-most
/// lambda scope info ignoring all inner capturing scopes that are not
/// lambda scopes.
sema::LambdaScopeInfo *
getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
/// Retrieve the current generic lambda info, if any.
sema::LambdaScopeInfo *getCurGenericLambda();
/// Retrieve the current captured region, if any.
sema::CapturedRegionScopeInfo *getCurCapturedRegion();
/// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
void ActOnComment(SourceRange Comment);
//===--------------------------------------------------------------------===//
// Type Analysis / Processing: SemaType.cpp.
//
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
const DeclSpec *DS = nullptr);
QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
const DeclSpec *DS = nullptr);
QualType BuildPointerType(QualType T,
SourceLocation Loc, DeclarationName Entity);
QualType BuildReferenceType(QualType T, bool LValueRef,
SourceLocation Loc, DeclarationName Entity);
QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
Expr *ArraySize, unsigned Quals,
SourceRange Brackets, DeclarationName Entity);
QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
QualType BuildExtVectorType(QualType T, Expr *ArraySize,
SourceLocation AttrLoc);
QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
SourceLocation AttrLoc);
/// Same as above, but constructs the AddressSpace index if not provided.
QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
SourceLocation AttrLoc);
bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
/// Build a function type.
///
/// This routine checks the function type according to C++ rules and
/// under the assumption that the result type and parameter types have
/// just been instantiated from a template. It therefore duplicates
/// some of the behavior of GetTypeForDeclarator, but in a much
/// simpler form that is only suitable for this narrow use case.
///
/// \param T The return type of the function.
///
/// \param ParamTypes The parameter types of the function. This array
/// will be modified to account for adjustments to the types of the
/// function parameters.
///
/// \param Loc The location of the entity whose type involves this
/// function type or, if there is no such entity, the location of the
/// type that will have function type.
///
/// \param Entity The name of the entity that involves the function
/// type, if known.
///
/// \param EPI Extra information about the function type. Usually this will
/// be taken from an existing function with the same prototype.
///
/// \returns A suitable function type, if there are no errors. The
/// unqualified type will always be a FunctionProtoType.
/// Otherwise, returns a NULL type.
QualType BuildFunctionType(QualType T,
MutableArrayRef<QualType> ParamTypes,
SourceLocation Loc, DeclarationName Entity,
const FunctionProtoType::ExtProtoInfo &EPI);
QualType BuildMemberPointerType(QualType T, QualType Class,
SourceLocation Loc,
DeclarationName Entity);
QualType BuildBlockPointerType(QualType T,
SourceLocation Loc, DeclarationName Entity);
QualType BuildParenType(QualType T);
QualType BuildAtomicType(QualType T, SourceLocation Loc);
QualType BuildReadPipeType(QualType T,
SourceLocation Loc);
QualType BuildWritePipeType(QualType T,
SourceLocation Loc);
TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
/// Package the given type and TSI into a ParsedType.
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
DeclarationNameInfo GetNameForDeclarator(Declarator &D);
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
static QualType GetTypeFromParser(ParsedType Ty,
TypeSourceInfo **TInfo = nullptr);
CanThrowResult canThrow(const Stmt *E);
const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
const FunctionProtoType *FPT);
void UpdateExceptionSpec(FunctionDecl *FD,
const FunctionProtoType::ExceptionSpecInfo &ESI);
bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
bool CheckDistantExceptionSpec(QualType T);
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
bool CheckEquivalentExceptionSpec(
const FunctionProtoType *Old, SourceLocation OldLoc,
const FunctionProtoType *New, SourceLocation NewLoc);
bool CheckEquivalentExceptionSpec(
const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
const FunctionProtoType *Old, SourceLocation OldLoc,
const FunctionProtoType *New, SourceLocation NewLoc);
bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
const PartialDiagnostic &NestedDiagID,
const PartialDiagnostic &NoteID,
const PartialDiagnostic &NoThrowDiagID,
const FunctionProtoType *Superset,
SourceLocation SuperLoc,
const FunctionProtoType *Subset,
SourceLocation SubLoc);
bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
const PartialDiagnostic &NoteID,
const FunctionProtoType *Target,
SourceLocation TargetLoc,
const FunctionProtoType *Source,
SourceLocation SourceLoc);
TypeResult ActOnTypeName(Scope *S, Declarator &D);
/// The parser has parsed the context-sensitive type 'instancetype'
/// in an Objective-C message declaration. Return the appropriate type.
ParsedType ActOnObjCInstanceType(SourceLocation Loc);
/// Abstract class used to diagnose incomplete types.
struct TypeDiagnoser {
TypeDiagnoser() {}
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
virtual ~TypeDiagnoser() {}
};
static int getPrintable(int I) { return I; }
static unsigned getPrintable(unsigned I) { return I; }
static bool getPrintable(bool B) { return B; }
static const char * getPrintable(const char *S) { return S; }
static StringRef getPrintable(StringRef S) { return S; }
static const std::string &getPrintable(const std::string &S) { return S; }
static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
return II;
}
static DeclarationName getPrintable(DeclarationName N) { return N; }
static QualType getPrintable(QualType T) { return T; }
static SourceRange getPrintable(SourceRange R) { return R; }
static SourceRange getPrintable(SourceLocation L) { return L; }
static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
unsigned DiagID;
std::tuple<const Ts &...> Args;
template <std::size_t... Is>
void emit(const SemaDiagnosticBuilder &DB,
std::index_sequence<Is...>) const {
// Apply all tuple elements to the builder in order.
bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
(void)Dummy;
}
public:
BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
: TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
assert(DiagID != 0 && "no diagnostic for type diagnoser");
}
void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
emit(DB, std::index_sequence_for<Ts...>());
DB << T;
}
};
/// Do a check to make sure \p Name looks like a legal swift_name
/// attribute for the decl \p D. Raise a diagnostic if the name is invalid
/// for the given declaration.
///
/// For a function, this will validate a compound Swift name,
/// e.g. <code>init(foo:bar:baz:)</code> or <code>controllerForName(_:)</code>,
/// and the function will output the number of parameter names, and whether
/// this is a single-arg initializer.
///
/// For a type, enum constant, property, or variable declaration, this will
/// validate either a simple identifier, or a qualified
/// <code>context.identifier</code> name.
///
/// \returns true if the name is a valid swift name for \p D, false otherwise.
bool DiagnoseSwiftName(Decl *D, StringRef Name,
SourceLocation ArgLoc,
const IdentifierInfo *AttrName);
private:
/// Methods for marking which expressions involve dereferencing a pointer
/// marked with the 'noderef' attribute. Expressions are checked bottom up as
/// they are parsed, meaning that a noderef pointer may not be accessed. For
/// example, in `&*p` where `p` is a noderef pointer, we will first parse the
/// `*p`, but need to check that `address of` is called on it. This requires
/// keeping a container of all pending expressions and checking if the address
/// of them are eventually taken.
void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
void CheckAddressOfNoDeref(const Expr *E);
void CheckMemberAccessOfNoDeref(const MemberExpr *E);
bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
TypeDiagnoser *Diagnoser);
struct ModuleScope {
SourceLocation BeginLoc;
clang::Module *Module = nullptr;
bool ModuleInterface = false;
bool ImplicitGlobalModuleFragment = false;
VisibleModuleSet OuterVisibleModules;
};
/// The modules we're currently parsing.
llvm::SmallVector<ModuleScope, 16> ModuleScopes;
/// Namespace definitions that we will export when they finish.
llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
/// Get the module whose scope we are currently within.
Module *getCurrentModule() const {
return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
}
VisibleModuleSet VisibleModules;
public:
/// Get the module owning an entity.
Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); }
/// Make a merged definition of an existing hidden definition \p ND
/// visible at the specified location.
void makeMergedDefinitionVisible(NamedDecl *ND);
bool isModuleVisible(const Module *M, bool ModulePrivate = false);
/// Determine whether a declaration is visible to name lookup.
bool isVisible(const NamedDecl *D) {
return !D->isHidden() || isVisibleSlow(D);
}
/// Determine whether any declaration of an entity is visible.
bool
hasVisibleDeclaration(const NamedDecl *D,
llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
}
bool hasVisibleDeclarationSlow(const NamedDecl *D,
llvm::SmallVectorImpl<Module *> *Modules);
bool hasVisibleMergedDefinition(NamedDecl *Def);
bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
/// Determine if \p D and \p Suggested have a structurally compatible
/// layout as described in C11 6.2.7/1.
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
/// Determine if \p D has a visible definition. If not, suggest a declaration
/// that should be made visible to expose the definition.
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
bool OnlyNeedComplete = false);
bool hasVisibleDefinition(const NamedDecl *D) {
NamedDecl *Hidden;
return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
}
/// Determine if the template parameter \p D has a visible default argument.
bool
hasVisibleDefaultArgument(const NamedDecl *D,
llvm::SmallVectorImpl<Module *> *Modules = nullptr);
/// Determine if there is a visible declaration of \p D that is an explicit
/// specialization declaration for a specialization of a template. (For a
/// member specialization, use hasVisibleMemberSpecialization.)
bool hasVisibleExplicitSpecialization(
const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
/// Determine if there is a visible declaration of \p D that is a member
/// specialization declaration (as opposed to an instantiated declaration).
bool hasVisibleMemberSpecialization(
const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
/// Determine if \p A and \p B are equivalent internal linkage declarations
/// from different modules, and thus an ambiguity error can be downgraded to
/// an extension warning.
bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
const NamedDecl *B);
void diagnoseEquivalentInternalLinkageDeclarations(
SourceLocation Loc, const NamedDecl *D,
ArrayRef<const NamedDecl *> Equiv);
bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
bool isCompleteType(SourceLocation Loc, QualType T) {
return !RequireCompleteTypeImpl(Loc, T, nullptr);
}
bool RequireCompleteType(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
bool RequireCompleteType(SourceLocation Loc, QualType T,
unsigned DiagID);
template <typename... Ts>
bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireCompleteType(Loc, T, Diagnoser);
}
void completeExprArrayBound(Expr *E);
bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
bool RequireCompleteExprType(Expr *E, unsigned DiagID);
template <typename... Ts>
bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireCompleteExprType(E, Diagnoser);
}
bool RequireLiteralType(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
template <typename... Ts>
bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireLiteralType(Loc, T, Diagnoser);
}
QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
const CXXScopeSpec &SS, QualType T,
TagDecl *OwnedTagDecl = nullptr);
QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
/// If AsUnevaluated is false, E is treated as though it were an evaluated
/// context, such as when building a type for decltype(auto).
QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
bool AsUnevaluated = true);
QualType BuildUnaryTransformType(QualType BaseType,
UnaryTransformType::UTTKind UKind,
SourceLocation Loc);
//===--------------------------------------------------------------------===//
// Symbol table / Decl tracking callbacks: SemaDecl.cpp.
//
struct SkipBodyInfo {
SkipBodyInfo()
: ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
New(nullptr) {}
bool ShouldSkip;
bool CheckSameAsPrevious;
NamedDecl *Previous;
NamedDecl *New;
};
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
void DiagnoseUseOfUnimplementedSelectors();
bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
Scope *S, CXXScopeSpec *SS = nullptr,
bool isClassName = false, bool HasTrailingDot = false,
ParsedType ObjectType = nullptr,
bool IsCtorOrDtorName = false,
bool WantNontrivialTypeSourceInfo = false,
bool IsClassTemplateDeductionContext = true,
IdentifierInfo **CorrectedII = nullptr);
TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
void DiagnoseUnknownTypeName(IdentifierInfo *&II,
SourceLocation IILoc,
Scope *S,
CXXScopeSpec *SS,
ParsedType &SuggestedType,
bool IsTemplateName = false);
/// Attempt to behave like MSVC in situations where lookup of an unqualified
/// type name has failed in a dependent context. In these situations, we
/// automatically form a DependentTypeName that will retry lookup in a related
/// scope during instantiation.
ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
SourceLocation NameLoc,
bool IsTemplateTypeArg);
/// Describes the result of the name lookup and resolution performed
/// by \c ClassifyName().
enum NameClassificationKind {
/// This name is not a type or template in this context, but might be
/// something else.
NC_Unknown,
/// Classification failed; an error has been produced.
NC_Error,
/// The name has been typo-corrected to a keyword.
NC_Keyword,
/// The name was classified as a type.
NC_Type,
/// The name was classified as a specific non-type, non-template
/// declaration. ActOnNameClassifiedAsNonType should be called to
/// convert the declaration to an expression.
NC_NonType,
/// The name was classified as an ADL-only function name.
/// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
/// result to an expression.
NC_UndeclaredNonType,
/// The name denotes a member of a dependent type that could not be
/// resolved. ActOnNameClassifiedAsDependentNonType should be called to
/// convert the result to an expression.
NC_DependentNonType,
/// The name was classified as a non-type, and an expression representing
/// that name has been formed.
NC_ContextIndependentExpr,
/// The name was classified as a template whose specializations are types.
NC_TypeTemplate,
/// The name was classified as a variable template name.
NC_VarTemplate,
/// The name was classified as a function template name.
NC_FunctionTemplate,
/// The name was classified as an ADL-only function template name.
NC_UndeclaredTemplate,
};
class NameClassification {
NameClassificationKind Kind;
union {
ExprResult Expr;
NamedDecl *NonTypeDecl;
TemplateName Template;
ParsedType Type;
};
explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
public:
NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
static NameClassification Error() {
return NameClassification(NC_Error);
}
static NameClassification Unknown() {
return NameClassification(NC_Unknown);
}
static NameClassification ContextIndependentExpr(ExprResult E) {
NameClassification Result(NC_ContextIndependentExpr);
Result.Expr = E;
return Result;
}
static NameClassification NonType(NamedDecl *D) {
NameClassification Result(NC_NonType);
Result.NonTypeDecl = D;
return Result;
}
static NameClassification UndeclaredNonType() {
return NameClassification(NC_UndeclaredNonType);
}
static NameClassification DependentNonType() {
return NameClassification(NC_DependentNonType);
}
static NameClassification TypeTemplate(TemplateName Name) {
NameClassification Result(NC_TypeTemplate);
Result.Template = Name;
return Result;
}
static NameClassification VarTemplate(TemplateName Name) {
NameClassification Result(NC_VarTemplate);
Result.Template = Name;
return Result;
}
static NameClassification FunctionTemplate(TemplateName Name) {
NameClassification Result(NC_FunctionTemplate);
Result.Template = Name;
return Result;
}
static NameClassification UndeclaredTemplate(TemplateName Name) {
NameClassification Result(NC_UndeclaredTemplate);
Result.Template = Name;
return Result;
}
NameClassificationKind getKind() const { return Kind; }
ExprResult getExpression() const {
assert(Kind == NC_ContextIndependentExpr);
return Expr;
}
ParsedType getType() const {
assert(Kind == NC_Type);
return Type;
}
NamedDecl *getNonTypeDecl() const {
assert(Kind == NC_NonType);
return NonTypeDecl;
}
TemplateName getTemplateName() const {
assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate);
return Template;
}
TemplateNameKind getTemplateNameKind() const {
switch (Kind) {
case NC_TypeTemplate:
return TNK_Type_template;
case NC_FunctionTemplate:
return TNK_Function_template;
case NC_VarTemplate:
return TNK_Var_template;
case NC_UndeclaredTemplate:
return TNK_Undeclared_template;
default:
llvm_unreachable("unsupported name classification.");
}
}
};
/// Perform name lookup on the given name, classifying it based on
/// the results of name lookup and the following token.
///
/// This routine is used by the parser to resolve identifiers and help direct
/// parsing. When the identifier cannot be found, this routine will attempt
/// to correct the typo and classify based on the resulting name.
///
/// \param S The scope in which we're performing name lookup.
///
/// \param SS The nested-name-specifier that precedes the name.
///
/// \param Name The identifier. If typo correction finds an alternative name,
/// this pointer parameter will be updated accordingly.
///
/// \param NameLoc The location of the identifier.
///
/// \param NextToken The token following the identifier. Used to help
/// disambiguate the name.
///
/// \param CCC The correction callback, if typo correction is desired.
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
IdentifierInfo *&Name, SourceLocation NameLoc,
const Token &NextToken,
CorrectionCandidateCallback *CCC = nullptr);
/// Act on the result of classifying a name as an undeclared (ADL-only)
/// non-type declaration.
ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
SourceLocation NameLoc);
/// Act on the result of classifying a name as an undeclared member of a
/// dependent base class.
ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
IdentifierInfo *Name,
SourceLocation NameLoc,
bool IsAddressOfOperand);
/// Act on the result of classifying a name as a specific non-type
/// declaration.
ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
NamedDecl *Found,
SourceLocation NameLoc,
const Token &NextToken);
/// Describes the detailed kind of a template name. Used in diagnostics.
enum class TemplateNameKindForDiagnostics {
ClassTemplate,
FunctionTemplate,
VarTemplate,
AliasTemplate,
TemplateTemplateParam,
Concept,
DependentTemplate
};
TemplateNameKindForDiagnostics
getTemplateNameKindForDiagnostics(TemplateName Name);
/// Determine whether it's plausible that E was intended to be a
/// template-name.
bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
if (!getLangOpts().CPlusPlus || E.isInvalid())
return false;
Dependent = false;
if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
return !DRE->hasExplicitTemplateArgs();
if (auto *ME = dyn_cast<MemberExpr>(E.get()))
return !ME->hasExplicitTemplateArgs();
Dependent = true;
if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
return !DSDRE->hasExplicitTemplateArgs();
if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
return !DSME->hasExplicitTemplateArgs();
// Any additional cases recognized here should also be handled by
// diagnoseExprIntendedAsTemplateName.
return false;
}
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
SourceLocation Less,
SourceLocation Greater);
Decl *ActOnDeclarator(Scope *S, Declarator &D);
NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParameterLists);
void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
DeclarationName Name, SourceLocation Loc,
bool IsTemplateId);
void
diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
SourceLocation FallbackLoc,
SourceLocation ConstQualLoc = SourceLocation(),
SourceLocation VolatileQualLoc = SourceLocation(),
SourceLocation RestrictQualLoc = SourceLocation(),
SourceLocation AtomicQualLoc = SourceLocation(),
SourceLocation UnalignedQualLoc = SourceLocation());
void diagnosePointerAuthDisabled(SourceLocation loc, SourceRange range);
bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key);
static bool adjustContextForLocalExternDecl(DeclContext *&DC);
void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
const LookupResult &R);
NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
const LookupResult &R);
void CheckShadow(Scope *S, VarDecl *D);
/// Warn if 'E', which is an expression that is about to be modified, refers
/// to a shadowing declaration.
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
private:
/// Map of current shadowing declarations to shadowed declarations. Warn if
/// it looks like the user is trying to modify the shadowing declaration.
llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
public:
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
TypedefNameDecl *NewTD);
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
TypeSourceInfo *TInfo,
LookupResult &Previous);
NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
LookupResult &Previous, bool &Redeclaration);
NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
TypeSourceInfo *TInfo,
LookupResult &Previous,
MultiTemplateParamsArg TemplateParamLists,
bool &AddToScope,
ArrayRef<BindingDecl *> Bindings = None);
NamedDecl *
ActOnDecompositionDeclarator(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParamLists);
// Returns true if the variable declaration is a redeclaration
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
void CheckVariableDeclarationType(VarDecl *NewVD);
bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
Expr *Init);
void CheckCompleteVariableDeclaration(VarDecl *VD);
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
TypeSourceInfo *TInfo,
LookupResult &Previous,
MultiTemplateParamsArg TemplateParamLists,
bool &AddToScope);
bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
enum class CheckConstexprKind {
/// Diagnose issues that are non-constant or that are extensions.
Diagnose,
/// Identify whether this function satisfies the formal rules for constexpr
/// functions in the current lanugage mode (with no extensions).
CheckValid
};
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
CheckConstexprKind Kind);
void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
void FindHiddenVirtualMethods(CXXMethodDecl *MD,
SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
// Returns true if the function declaration is a redeclaration
bool CheckFunctionDeclaration(Scope *S,
FunctionDecl *NewFD, LookupResult &Previous,
bool IsMemberSpecialization);
bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
QualType NewT, QualType OldT);
void CheckMain(FunctionDecl *FD, const DeclSpec &D);
void CheckMSVCRTEntryPoint(FunctionDecl *FD);
Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
bool IsDefinition);
void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
SourceLocation Loc,
QualType T);
QualType adjustParameterTypeForObjCAutoRefCount(QualType T,
SourceLocation NameLoc,
TypeSourceInfo *TSInfo);
ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
SourceLocation NameLoc, IdentifierInfo *Name,
QualType T, TypeSourceInfo *TSInfo,
StorageClass SC);
void ActOnParamDefaultArgument(Decl *param,
SourceLocation EqualLoc,
Expr *defarg);
void ActOnParamUnparsedDefaultArgument(Decl *param,
SourceLocation EqualLoc,
SourceLocation ArgLoc);
void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
SourceLocation EqualLoc);
// Contexts where using non-trivial C union types can be disallowed. This is
// passed to err_non_trivial_c_union_in_invalid_context.
enum NonTrivialCUnionContext {
// Function parameter.
NTCUC_FunctionParam,
// Function return.
NTCUC_FunctionReturn,
// Default-initialized object.
NTCUC_DefaultInitializedObject,
// Variable with automatic storage duration.
NTCUC_AutoVar,
// Initializer expression that might copy from another object.
NTCUC_CopyInit,
// Assignment.
NTCUC_Assignment,
// Compound literal.
NTCUC_CompoundLiteral,
// Block capture.
NTCUC_BlockCapture,
// lvalue-to-rvalue conversion of volatile type.
NTCUC_LValueToRValueVolatile,
};
/// Emit diagnostics if the initializer or any of its explicit or
/// implicitly-generated subexpressions require copying or
/// default-initializing a type that is or contains a C union type that is
/// non-trivial to copy or default-initialize.
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
// These flags are passed to checkNonTrivialCUnion.
enum NonTrivialCUnionKind {
NTCUK_Init = 0x1,
NTCUK_Destruct = 0x2,
NTCUK_Copy = 0x4,
};
/// Emit diagnostics if a non-trivial C union type or a struct that contains
/// a non-trivial C union is used in an invalid context.
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
NonTrivialCUnionContext UseContext,
unsigned NonTrivialKind);
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
void ActOnUninitializedDecl(Decl *dcl);
void ActOnInitializerError(Decl *Dcl);
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
void ActOnCXXForRangeDecl(Decl *D);
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
IdentifierInfo *Ident,
ParsedAttributes &Attrs,
SourceLocation AttrEnd);
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
void CheckStaticLocalForDllExport(VarDecl *VD);
void FinalizeDeclaration(Decl *D);
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
ArrayRef<Decl *> Group);
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
/// Should be called on all declarations that might have attached
/// documentation comments.
void ActOnDocumentableDecl(Decl *D);
void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
SourceLocation LocAfterDecls);
void CheckForFunctionRedefinition(
FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
SkipBodyInfo *SkipBody = nullptr);
Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParamLists,
SkipBodyInfo *SkipBody = nullptr);
Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
SkipBodyInfo *SkipBody = nullptr);
void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
bool isObjCMethodDecl(Decl *D) {
return D && isa<ObjCMethodDecl>(D);
}
/// Determine whether we can delay parsing the body of a function or
/// function template until it is used, assuming we don't care about emitting
/// code for that function.
///
/// This will be \c false if we may need the body of the function in the
/// middle of parsing an expression (where it's impractical to switch to
/// parsing a different function), for instance, if it's constexpr in C++11
/// or has an 'auto' return type in C++14. These cases are essentially bugs.
bool canDelayFunctionBody(const Declarator &D);
/// Determine whether we can skip parsing the body of a function
/// definition, assuming we don't care about analyzing its body or emitting
/// code for that function.
///
/// This will be \c false only if we may need the body of the function in
/// order to parse the rest of the program (for instance, if it is
/// \c constexpr in C++11 or has an 'auto' return type in C++14).
bool canSkipFunctionBody(Decl *D);
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
Decl *ActOnSkippedFunctionBody(Decl *Decl);
void ActOnFinishInlineFunctionDef(FunctionDecl *D);
/// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
/// attribute for which parsing is delayed.
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
/// Diagnose any unused parameters in the given sequence of
/// ParmVarDecl pointers.
void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
/// Diagnose whether the size of parameters or return value of a
/// function or obj-c method definition is pass-by-value and larger than a
/// specified threshold.
void
DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
QualType ReturnTy, NamedDecl *D);
void DiagnoseInvalidJumps(Stmt *Body);
Decl *ActOnFileScopeAsmDecl(Expr *expr,
SourceLocation AsmLoc,
SourceLocation RParenLoc);
/// Handle a C++11 empty-declaration and attribute-declaration.
Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
SourceLocation SemiLoc);
enum class ModuleDeclKind {
Interface, ///< 'export module X;'
Implementation, ///< 'module X;'
};
/// The parser has processed a module-declaration that begins the definition
/// of a module interface or implementation.
DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
SourceLocation ModuleLoc, ModuleDeclKind MDK,
ModuleIdPath Path, bool IsFirstDecl);
/// The parser has processed a global-module-fragment declaration that begins
/// the definition of the global module fragment of the current module unit.
/// \param ModuleLoc The location of the 'module' keyword.
DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
/// The parser has processed a private-module-fragment declaration that begins
/// the definition of the private module fragment of the current module unit.
/// \param ModuleLoc The location of the 'module' keyword.
/// \param PrivateLoc The location of the 'private' keyword.
DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
SourceLocation PrivateLoc);
/// The parser has processed a module import declaration.
///
/// \param StartLoc The location of the first token in the declaration. This
/// could be the location of an '@', 'export', or 'import'.
/// \param ExportLoc The location of the 'export' keyword, if any.
/// \param ImportLoc The location of the 'import' keyword.
/// \param Path The module access path.
DeclResult ActOnModuleImport(SourceLocation StartLoc,
SourceLocation ExportLoc,
SourceLocation ImportLoc, ModuleIdPath Path);
DeclResult ActOnModuleImport(SourceLocation StartLoc,
SourceLocation ExportLoc,
SourceLocation ImportLoc, Module *M,
ModuleIdPath Path = {});
/// The parser has processed a module import translated from a
/// #include or similar preprocessing directive.
void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
/// The parsed has entered a submodule.
void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
/// The parser has left a submodule.
void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
/// Create an implicit import of the given module at the given
/// source location, for error recovery, if possible.
///
/// This routine is typically used when an entity found by name lookup
/// is actually hidden within a module that we know about but the user
/// has forgotten to import.
void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
Module *Mod);
/// Kinds of missing import. Note, the values of these enumerators correspond
/// to %select values in diagnostics.
enum class MissingImportKind {
Declaration,
Definition,
DefaultArgument,
ExplicitSpecialization,
PartialSpecialization
};
/// Diagnose that the specified declaration needs to be visible but
/// isn't, and suggest a module import that would resolve the problem.
void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
MissingImportKind MIK, bool Recover = true);
void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
SourceLocation DeclLoc, ArrayRef<Module *> Modules,
MissingImportKind MIK, bool Recover);
Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
SourceLocation LBraceLoc);
Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
SourceLocation RBraceLoc);
/// We've found a use of a templated declaration that would trigger an
/// implicit instantiation. Check that any relevant explicit specializations
/// and partial specializations are visible, and diagnose if not.
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
/// We've found a use of a template specialization that would select a
/// partial specialization. Check that the partial specialization is visible,
/// and diagnose if not.
void checkPartialSpecializationVisibility(SourceLocation Loc,
NamedDecl *Spec);
/// Retrieve a suitable printing policy for diagnostics.
PrintingPolicy getPrintingPolicy() const {
return getPrintingPolicy(Context, PP);
}
/// Retrieve a suitable printing policy for diagnostics.
static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
const Preprocessor &PP);
/// Scope actions.
void ActOnPopScope(SourceLocation Loc, Scope *S);
void ActOnTranslationUnitScope(Scope *S);
Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
RecordDecl *&AnonRecord);
Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
MultiTemplateParamsArg TemplateParams,
bool IsExplicitInstantiation,
RecordDecl *&AnonRecord);
Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
AccessSpecifier AS,
RecordDecl *Record,
const PrintingPolicy &Policy);
Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
RecordDecl *Record);
/// Common ways to introduce type names without a tag for use in diagnostics.
/// Keep in sync with err_tag_reference_non_tag.
enum NonTagKind {
NTK_NonStruct,
NTK_NonClass,
NTK_NonUnion,
NTK_NonEnum,
NTK_Typedef,
NTK_TypeAlias,
NTK_Template,
NTK_TypeAliasTemplate,
NTK_TemplateTemplateArgument,
};
/// Given a non-tag type declaration, returns an enum useful for indicating
/// what kind of non-tag type this is.
NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
bool isAcceptableTagRedeclaration(const TagDecl *Previous,
TagTypeKind NewTag, bool isDefinition,
SourceLocation NewTagLoc,
const IdentifierInfo *Name);
enum TagUseKind {
TUK_Reference, // Reference to a tag: 'struct foo *X;'
TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
TUK_Friend // Friend declaration: 'friend struct foo;'
};
Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
SourceLocation NameLoc, const ParsedAttributesView &Attr,
AccessSpecifier AS, SourceLocation ModulePrivateLoc,
MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
bool &IsDependent, SourceLocation ScopedEnumKWLoc,
bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
bool IsTypeSpecifier, bool IsTemplateParamOrArg,
SkipBodyInfo *SkipBody = nullptr);
Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
unsigned TagSpec, SourceLocation TagLoc,
CXXScopeSpec &SS, IdentifierInfo *Name,
SourceLocation NameLoc,
const ParsedAttributesView &Attr,
MultiTemplateParamsArg TempParamLists);
TypeResult ActOnDependentTag(Scope *S,
unsigned TagSpec,
TagUseKind TUK,
const CXXScopeSpec &SS,
IdentifierInfo *Name,
SourceLocation TagLoc,
SourceLocation NameLoc);
void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
IdentifierInfo *ClassName,
SmallVectorImpl<Decl *> &Decls);
Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth);
FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth,
InClassInitStyle InitStyle,
AccessSpecifier AS);
MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
SourceLocation DeclStart, Declarator &D,
Expr *BitfieldWidth,
InClassInitStyle InitStyle,
AccessSpecifier AS,
const ParsedAttr &MSPropertyAttr);
FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
TypeSourceInfo *TInfo,
RecordDecl *Record, SourceLocation Loc,
bool Mutable, Expr *BitfieldWidth,
InClassInitStyle InitStyle,
SourceLocation TSSL,
AccessSpecifier AS, NamedDecl *PrevDecl,
Declarator *D = nullptr);
bool CheckNontrivialField(FieldDecl *FD);
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
enum TrivialABIHandling {
/// The triviality of a method unaffected by "trivial_abi".
TAH_IgnoreTrivialABI,
/// The triviality of a method affected by "trivial_abi".
TAH_ConsiderTrivialABI
};
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
bool Diagnose = false);
/// For a defaulted function, the kind of defaulted function that it is.
class DefaultedFunctionKind {
CXXSpecialMember SpecialMember : 8;
DefaultedComparisonKind Comparison : 8;
public:
DefaultedFunctionKind()
: SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
}
DefaultedFunctionKind(CXXSpecialMember CSM)
: SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
DefaultedFunctionKind(DefaultedComparisonKind Comp)
: SpecialMember(CXXInvalid), Comparison(Comp) {}
bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
bool isComparison() const {
return Comparison != DefaultedComparisonKind::None;
}
explicit operator bool() const {
return isSpecialMember() || isComparison();
}
CXXSpecialMember asSpecialMember() const { return SpecialMember; }
DefaultedComparisonKind asComparison() const { return Comparison; }
/// Get the index of this function kind for use in diagnostics.
unsigned getDiagnosticIndex() const {
static_assert(CXXInvalid > CXXDestructor,
"invalid should have highest index");
static_assert((unsigned)DefaultedComparisonKind::None == 0,
"none should be equal to zero");
return SpecialMember + (unsigned)Comparison;
}
};
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
return getDefaultedFunctionKind(MD).asSpecialMember();
}
DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
return getDefaultedFunctionKind(FD).asComparison();
}
void ActOnLastBitfield(SourceLocation DeclStart,
SmallVectorImpl<Decl *> &AllIvarDecls);
Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth,
tok::ObjCKeywordKind visibility);
// This is used for both record definitions and ObjC interface declarations.
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
ArrayRef<Decl *> Fields, SourceLocation LBrac,
SourceLocation RBrac, const ParsedAttributesView &AttrList);
/// ActOnTagStartDefinition - Invoked when we have entered the
/// scope of a tag's definition (e.g., for an enumeration, class,
/// struct, or union).
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
/// Perform ODR-like check for C/ObjC when merging tag types from modules.
/// Differently from C++, actually parse the body and reject / error out
/// in case of a structural mismatch.
bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
SkipBodyInfo &SkipBody);
typedef void *SkippedDefinitionContext;
/// Invoked when we enter a tag definition that we're skipping.
SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
/// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
/// C++ record definition's base-specifiers clause and are starting its
/// member declarations.
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
SourceLocation FinalLoc,
bool IsFinalSpelledSealed,
SourceLocation LBraceLoc);
/// ActOnTagFinishDefinition - Invoked once we have finished parsing
/// the definition of a tag (enumeration, class, struct, or union).
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
SourceRange BraceRange);
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
void ActOnObjCContainerFinishDefinition();
/// Invoked when we must temporarily exit the objective-c container
/// scope for parsing/looking-up C constructs.
///
/// Must be followed by a call to \see ActOnObjCReenterContainerContext
void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
void ActOnObjCReenterContainerContext(DeclContext *DC);
/// ActOnTagDefinitionError - Invoked when there was an unrecoverable
/// error parsing the definition of a tag.
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
EnumConstantDecl *LastEnumConst,
SourceLocation IdLoc,
IdentifierInfo *Id,
Expr *val);
bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
QualType EnumUnderlyingTy, bool IsFixed,
const EnumDecl *Prev);
/// Determine whether the body of an anonymous enumeration should be skipped.
/// \param II The name of the first enumerator.
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
SourceLocation IILoc);
Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
SourceLocation IdLoc, IdentifierInfo *Id,
const ParsedAttributesView &Attrs,
SourceLocation EqualLoc, Expr *Val);
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
const ParsedAttributesView &Attr);
DeclContext *getContainingDC(DeclContext *DC);
/// Set the current declaration context until it gets popped.
void PushDeclContext(Scope *S, DeclContext *DC);
void PopDeclContext();
/// EnterDeclaratorContext - Used when we must lookup names in the context
/// of a declarator's nested name specifier.
void EnterDeclaratorContext(Scope *S, DeclContext *DC);
void ExitDeclaratorContext(Scope *S);
/// Push the parameters of D, which must be a function, into scope.
void ActOnReenterFunctionContext(Scope* S, Decl* D);
void ActOnExitFunctionContext();
DeclContext *getFunctionLevelDeclContext();
/// getCurFunctionDecl - If inside of a function body, this returns a pointer
/// to the function decl for the function being parsed. If we're currently
/// in a 'block', this returns the containing context.
FunctionDecl *getCurFunctionDecl();
/// getCurMethodDecl - If inside of a method body, this returns a pointer to
/// the method decl for the method being parsed. If we're currently
/// in a 'block', this returns the containing context.
ObjCMethodDecl *getCurMethodDecl();
/// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
/// or C function we're in, otherwise return null. If we're currently
/// in a 'block', this returns the containing context.
NamedDecl *getCurFunctionOrMethodDecl();
/// Add this decl to the scope shadowed decl chains.
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
/// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
/// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
/// true if 'D' belongs to the given declaration context.
///
/// \param AllowInlineNamespace If \c true, allow the declaration to be in the
/// enclosing namespace set of the context, rather than contained
/// directly within it.
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
bool AllowInlineNamespace = false);
/// Finds the scope corresponding to the given decl context, if it
/// happens to be an enclosing scope. Otherwise return NULL.
static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
/// Subroutines of ActOnDeclarator().
TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
TypeSourceInfo *TInfo);
bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
/// Describes the kind of merge to perform for availability
/// attributes (including "deprecated", "unavailable", and "availability").
enum AvailabilityMergeKind {
/// Don't merge availability attributes at all.
AMK_None,
/// Merge availability attributes for a redeclaration, which requires
/// an exact match.
AMK_Redeclaration,
/// Merge availability attributes for an override, which requires
/// an exact match or a weakening of constraints.
AMK_Override,
/// Merge availability attributes for an implementation of
/// a protocol requirement.
AMK_ProtocolImplementation,
};
/// Describes the kind of priority given to an availability attribute.
///
/// The sum of priorities deteremines the final priority of the attribute.
/// The final priority determines how the attribute will be merged.
/// An attribute with a lower priority will always remove higher priority
/// attributes for the specified platform when it is being applied. An
/// attribute with a higher priority will not be applied if the declaration
/// already has an availability attribute with a lower priority for the
/// specified platform. The final prirority values are not expected to match
/// the values in this enumeration, but instead should be treated as a plain
/// integer value. This enumeration just names the priority weights that are
/// used to calculate that final vaue.
enum AvailabilityPriority : int {
/// The availability attribute was specified explicitly next to the
/// declaration.
AP_Explicit = 0,
/// The availability attribute was applied using '#pragma clang attribute'.
AP_PragmaClangAttribute = 1,
/// The availability attribute for a specific platform was inferred from
/// an availability attribute for another platform.
AP_InferredFromOtherPlatform = 2
};
/// Attribute merging methods. Return true if a new attribute was added.
AvailabilityAttr *
mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
IdentifierInfo *Platform, bool Implicit,
VersionTuple Introduced, VersionTuple Deprecated,
VersionTuple Obsoleted, bool IsUnavailable,
StringRef Message, bool IsStrict, StringRef Replacement,
AvailabilityMergeKind AMK, int Priority);
TypeVisibilityAttr *
mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
TypeVisibilityAttr::VisibilityType Vis);
VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
VisibilityAttr::VisibilityType Vis);
UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
StringRef Uuid);
DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
const AttributeCommonInfo &CI,
bool BestCase,
MSInheritanceModel Model);
FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
IdentifierInfo *Format, int FormatIdx,
int FirstArg);
SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
StringRef Name);
CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
StringRef Name);
AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
const AttributeCommonInfo &CI,
const IdentifierInfo *Ident);
MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
NoSpeculativeLoadHardeningAttr *
mergeNoSpeculativeLoadHardeningAttr(Decl *D,
const NoSpeculativeLoadHardeningAttr &AL);
SpeculativeLoadHardeningAttr *
mergeSpeculativeLoadHardeningAttr(Decl *D,
const SpeculativeLoadHardeningAttr &AL);
OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
const AttributeCommonInfo &CI);
SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const AttributeCommonInfo &CI,
StringRef Name, bool Override);
InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
const InternalLinkageAttr &AL);
CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL);
CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL);
void mergeDeclAttributes(NamedDecl *New, Decl *Old,
AvailabilityMergeKind AMK = AMK_Redeclaration);
void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
LookupResult &OldDecls);
bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
bool MergeTypeWithOld);
bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Scope *S, bool MergeTypeWithOld);
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
void MergeVarDecl(VarDecl *New, LookupResult &Previous);
void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
// AssignmentAction - This is used by all the assignment diagnostic functions
// to represent what is actually causing the operation
enum AssignmentAction {
AA_Assigning,
AA_Passing,
AA_Returning,
AA_Converting,
AA_Initializing,
AA_Sending,
AA_Casting,
AA_Passing_CFAudited
};
/// C++ Overloading.
enum OverloadKind {
/// This is a legitimate overload: the existing declarations are
/// functions or function templates with different signatures.
Ovl_Overload,
/// This is not an overload because the signature exactly matches
/// an existing declaration.
Ovl_Match,
/// This is not an overload because the lookup results contain a
/// non-function.
Ovl_NonFunction
};
OverloadKind CheckOverload(Scope *S,
FunctionDecl *New,
const LookupResult &OldDecls,
NamedDecl *&OldDecl,
bool IsForUsingDecl);
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
bool ConsiderCudaAttrs = true);
ImplicitConversionSequence
TryImplicitConversion(Expr *From, QualType ToType,
bool SuppressUserConversions,
bool AllowExplicit,
bool InOverloadResolution,
bool CStyle,
bool AllowObjCWritebackConversion);
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
bool IsComplexPromotion(QualType FromType, QualType ToType);
bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
bool InOverloadResolution,
QualType& ConvertedType, bool &IncompatibleObjC);
bool isObjCPointerConversion(QualType FromType, QualType ToType,
QualType& ConvertedType, bool &IncompatibleObjC);
bool isObjCWritebackConversion(QualType FromType, QualType ToType,
QualType &ConvertedType);
bool IsBlockPointerConversion(QualType FromType, QualType ToType,
QualType& ConvertedType);
bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
const FunctionProtoType *NewType,
unsigned *ArgPos = nullptr);
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
QualType FromType, QualType ToType);
void maybeExtendBlockObject(ExprResult &E);
CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
bool CheckPointerConversion(Expr *From, QualType ToType,
CastKind &Kind,
CXXCastPath& BasePath,
bool IgnoreBaseAccess,
bool Diagnose = true);
bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
bool InOverloadResolution,
QualType &ConvertedType);
bool CheckMemberPointerConversion(Expr *From, QualType ToType,
CastKind &Kind,
CXXCastPath &BasePath,
bool IgnoreBaseAccess);
bool IsQualificationConversion(QualType FromType, QualType ToType,
bool CStyle, bool &ObjCLifetimeConversion);
bool IsFunctionConversion(QualType FromType, QualType ToType,
QualType &ResultTy);
bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
const VarDecl *NRVOCandidate,
QualType ResultType,
Expr *Value,
bool AllowNRVO = true);
bool CanPerformAggregateInitializationForOverloadResolution(
const InitializedEntity &Entity, InitListExpr *From);
bool CanPerformCopyInitialization(const InitializedEntity &Entity,
ExprResult Init);
ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
SourceLocation EqualLoc,
ExprResult Init,
bool TopLevelOfInitList = false,
bool AllowExplicit = false);
ExprResult PerformObjectArgumentInitialization(Expr *From,
NestedNameSpecifier *Qualifier,
NamedDecl *FoundDecl,
CXXMethodDecl *Method);
/// Check that the lifetime of the initializer (and its subobjects) is
/// sufficient for initializing the entity, and perform lifetime extension
/// (when permitted) if not.
void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
ExprResult PerformContextuallyConvertToBool(Expr *From);
ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
/// Contexts in which a converted constant expression is required.
enum CCEKind {
CCEK_CaseValue, ///< Expression in a case label.
CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
CCEK_TemplateArg, ///< Value of a non-type template parameter.
CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
CCEK_ConstexprIf, ///< Condition in a constexpr if statement.
CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier.
};
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
llvm::APSInt &Value, CCEKind CCE);
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
APValue &Value, CCEKind CCE);
/// Abstract base class used to perform a contextual implicit
/// conversion from an expression to any type passing a filter.
class ContextualImplicitConverter {
public:
bool Suppress;
bool SuppressConversion;
ContextualImplicitConverter(bool Suppress = false,
bool SuppressConversion = false)
: Suppress(Suppress), SuppressConversion(SuppressConversion) {}
/// Determine whether the specified type is a valid destination type
/// for this conversion.
virtual bool match(QualType T) = 0;
/// Emits a diagnostic complaining that the expression does not have
/// integral or enumeration type.
virtual SemaDiagnosticBuilder
diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
/// Emits a diagnostic when the expression has incomplete class type.
virtual SemaDiagnosticBuilder
diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
/// Emits a diagnostic when the only matching conversion function
/// is explicit.
virtual SemaDiagnosticBuilder diagnoseExplicitConv(
Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
/// Emits a note for the explicit conversion function.
virtual SemaDiagnosticBuilder
noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
/// Emits a diagnostic when there are multiple possible conversion
/// functions.
virtual SemaDiagnosticBuilder
diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
/// Emits a note for one of the candidate conversions.
virtual SemaDiagnosticBuilder
noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
/// Emits a diagnostic when we picked a conversion function
/// (for cases when we are not allowed to pick a conversion function).
virtual SemaDiagnosticBuilder diagnoseConversion(
Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
virtual ~ContextualImplicitConverter() {}
};
class ICEConvertDiagnoser : public ContextualImplicitConverter {
bool AllowScopedEnumerations;
public:
ICEConvertDiagnoser(bool AllowScopedEnumerations,
bool Suppress, bool SuppressConversion)
: ContextualImplicitConverter(Suppress, SuppressConversion),
AllowScopedEnumerations(AllowScopedEnumerations) {}
/// Match an integral or (possibly scoped) enumeration type.
bool match(QualType T) override;
SemaDiagnosticBuilder
diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
return diagnoseNotInt(S, Loc, T);
}
/// Emits a diagnostic complaining that the expression does not have
/// integral or enumeration type.
virtual SemaDiagnosticBuilder
diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
};
/// Perform a contextual implicit conversion.
ExprResult PerformContextualImplicitConversion(
SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
enum ObjCSubscriptKind {
OS_Array,
OS_Dictionary,
OS_Error
};
ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
// Note that LK_String is intentionally after the other literals, as
// this is used for diagnostics logic.
enum ObjCLiteralKind {
LK_Array,
LK_Dictionary,
LK_Numeric,
LK_Boxed,
LK_String,
LK_Block,
LK_None
};
ObjCLiteralKind CheckLiteralKind(Expr *FromE);
ExprResult PerformObjectMemberConversion(Expr *From,
NestedNameSpecifier *Qualifier,
NamedDecl *FoundDecl,
NamedDecl *Member);
// Members have to be NamespaceDecl* or TranslationUnitDecl*.
// TODO: make this is a typesafe union.
typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
using ADLCallKind = CallExpr::ADLCallKind;
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false,
bool AllowExplicit = true,
bool AllowExplicitConversion = false,
ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
ConversionSequenceList EarlyConversions = None,
OverloadCandidateParamOrder PO = {});
void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
bool SuppressUserConversions = false,
bool PartialOverloading = false,
bool FirstArgumentIsBase = false);
void AddMethodCandidate(DeclAccessPair FoundDecl,
QualType ObjectType,
Expr::Classification ObjectClassification,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversion = false,
OverloadCandidateParamOrder PO = {});
void AddMethodCandidate(CXXMethodDecl *Method,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext, QualType ObjectType,
Expr::Classification ObjectClassification,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false,
ConversionSequenceList EarlyConversions = None,
OverloadCandidateParamOrder PO = {});
void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext,
TemplateArgumentListInfo *ExplicitTemplateArgs,
QualType ObjectType,
Expr::Classification ObjectClassification,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false,
OverloadCandidateParamOrder PO = {});
void AddTemplateOverloadCandidate(
FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
bool PartialOverloading = false, bool AllowExplicit = true,
ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
OverloadCandidateParamOrder PO = {});
bool CheckNonDependentConversions(
FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
ConversionSequenceList &Conversions, bool SuppressUserConversions,
CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
Expr::Classification ObjectClassification = {},
OverloadCandidateParamOrder PO = {});
void AddConversionCandidate(
CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
bool AllowExplicit, bool AllowResultConversion = true);
void AddTemplateConversionCandidate(
FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
bool AllowExplicit, bool AllowResultConversion = true);
void AddSurrogateCandidate(CXXConversionDecl *Conversion,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext,
const FunctionProtoType *Proto,
Expr *Object, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet);
void AddNonMemberOperatorCandidates(
const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
SourceLocation OpLoc, ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
OverloadCandidateParamOrder PO = {});
void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool IsAssignmentOperator = false,
unsigned NumContextualBoolArguments = 0);
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
SourceLocation OpLoc, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet);
void AddArgumentDependentLookupCandidates(DeclarationName Name,
SourceLocation Loc,
ArrayRef<Expr *> Args,
TemplateArgumentListInfo *ExplicitTemplateArgs,
OverloadCandidateSet& CandidateSet,
bool PartialOverloading = false);
// Emit as a 'note' the specific overload candidate
void NoteOverloadCandidate(
NamedDecl *Found, FunctionDecl *Fn,
OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
QualType DestType = QualType(), bool TakingAddress = false);
// Emit as a series of 'note's all template and non-templates identified by
// the expression Expr
void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
bool TakingAddress = false);
/// Check the enable_if expressions on the given function. Returns the first
/// failing attribute, or NULL if they were all successful.
EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
bool MissingImplicitThis = false);
/// Find the failed Boolean condition within a given Boolean
/// constant expression, and describe it with a string.
std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
/// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
/// non-ArgDependent DiagnoseIfAttrs.
///
/// Argument-dependent diagnose_if attributes should be checked each time a
/// function is used as a direct callee of a function call.
///
/// Returns true if any errors were emitted.
bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
const Expr *ThisArg,
ArrayRef<const Expr *> Args,
SourceLocation Loc);
/// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
/// ArgDependent DiagnoseIfAttrs.
///
/// Argument-independent diagnose_if attributes should be checked on every use
/// of a function.
///
/// Returns true if any errors were emitted.
bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
SourceLocation Loc);
/// Returns whether the given function's address can be taken or not,
/// optionally emitting a diagnostic if the address can't be taken.
///
/// Returns false if taking the address of the function is illegal.
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
bool Complain = false,
SourceLocation Loc = SourceLocation());
// [PossiblyAFunctionType] --> [Return]
// NonFunctionType --> NonFunctionType
// R (A) --> R(A)
// R (*)(A) --> R (A)
// R (&)(A) --> R (A)
// R (S::*)(A) --> R (A)
QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
FunctionDecl *
ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
QualType TargetType,
bool Complain,
DeclAccessPair &Found,
bool *pHadMultipleCandidates = nullptr);
FunctionDecl *
resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
DeclAccessPair &FoundResult);
bool resolveAndFixAddressOfOnlyViableOverloadCandidate(
ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
FunctionDecl *
ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
bool Complain = false,
DeclAccessPair *Found = nullptr);
bool ResolveAndFixSingleFunctionTemplateSpecialization(
ExprResult &SrcExpr,
bool DoFunctionPointerConverion = false,
bool Complain = false,
SourceRange OpRangeForComplaining = SourceRange(),
QualType DestTypeForComplaining = QualType(),
unsigned DiagIDForComplaining = 0);
Expr *FixOverloadedFunctionReference(Expr *E,
DeclAccessPair FoundDecl,
FunctionDecl *Fn);
ExprResult FixOverloadedFunctionReference(ExprResult,
DeclAccessPair FoundDecl,
FunctionDecl *Fn);
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
bool PartialOverloading = false);
// An enum used to represent the different possible results of building a
// range-based for loop.
enum ForRangeStatus {
FRS_Success,
FRS_NoViableFunction,
FRS_DiagnosticIssued
};
ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
SourceLocation RangeLoc,
const DeclarationNameInfo &NameInfo,
LookupResult &MemberLookup,
OverloadCandidateSet *CandidateSet,
Expr *Range, ExprResult *CallExpr);
ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
UnresolvedLookupExpr *ULE,
SourceLocation LParenLoc,
MultiExprArg Args,
SourceLocation RParenLoc,
Expr *ExecConfig,
bool AllowTypoCorrection=true,
bool CalleesAddressIsTaken=false);
bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
MultiExprArg Args, SourceLocation RParenLoc,
OverloadCandidateSet *CandidateSet,
ExprResult *Result);
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
UnaryOperatorKind Opc,
const UnresolvedSetImpl &Fns,
Expr *input, bool RequiresADL = true);
void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
OverloadedOperatorKind Op,
const UnresolvedSetImpl &Fns,
ArrayRef<Expr *> Args, bool RequiresADL = true);
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
BinaryOperatorKind Opc,
const UnresolvedSetImpl &Fns,
Expr *LHS, Expr *RHS,
bool RequiresADL = true,
bool AllowRewrittenCandidates = true,
FunctionDecl *DefaultedFn = nullptr);
ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
const UnresolvedSetImpl &Fns,
Expr *LHS, Expr *RHS,
FunctionDecl *DefaultedFn);
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
SourceLocation RLoc,
Expr *Base,Expr *Idx);
ExprResult
BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
SourceLocation LParenLoc,
MultiExprArg Args,
SourceLocation RParenLoc);
ExprResult
BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
MultiExprArg Args,
SourceLocation RParenLoc);
ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
bool *NoArrowOperatorFound = nullptr);
/// CheckCallReturnType - Checks that a call expression's return type is
/// complete. Returns true on failure. The location passed in is the location
/// that best represents the call.
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
CallExpr *CE, FunctionDecl *FD);
/// Helpers for dealing with blocks and functions.
bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
bool CheckParameterNames);
void CheckCXXDefaultArguments(FunctionDecl *FD);
void CheckExtraCXXDefaultArguments(Declarator &D);
Scope *getNonFieldDeclScope(Scope *S);
/// \name Name lookup
///
/// These routines provide name lookup that is used during semantic
/// analysis to resolve the various kinds of names (identifiers,
/// overloaded operator names, constructor names, etc.) into zero or
/// more declarations within a particular scope. The major entry
/// points are LookupName, which performs unqualified name lookup,
/// and LookupQualifiedName, which performs qualified name lookup.
///
/// All name lookup is performed based on some specific criteria,
/// which specify what names will be visible to name lookup and how
/// far name lookup should work. These criteria are important both
/// for capturing language semantics (certain lookups will ignore
/// certain names, for example) and for performance, since name
/// lookup is often a bottleneck in the compilation of C++. Name
/// lookup criteria is specified via the LookupCriteria enumeration.
///
/// The results of name lookup can vary based on the kind of name
/// lookup performed, the current language, and the translation
/// unit. In C, for example, name lookup will either return nothing
/// (no entity found) or a single declaration. In C++, name lookup
/// can additionally refer to a set of overloaded functions or
/// result in an ambiguity. All of the possible results of name
/// lookup are captured by the LookupResult class, which provides
/// the ability to distinguish among them.
//@{
/// Describes the kind of name lookup to perform.
enum LookupNameKind {
/// Ordinary name lookup, which finds ordinary names (functions,
/// variables, typedefs, etc.) in C and most kinds of names
/// (functions, variables, members, types, etc.) in C++.
LookupOrdinaryName = 0,
/// Tag name lookup, which finds the names of enums, classes,
/// structs, and unions.
LookupTagName,
/// Label name lookup.
LookupLabel,
/// Member name lookup, which finds the names of
/// class/struct/union members.
LookupMemberName,
/// Look up of an operator name (e.g., operator+) for use with
/// operator overloading. This lookup is similar to ordinary name
/// lookup, but will ignore any declarations that are class members.
LookupOperatorName,
/// Look up of a name that precedes the '::' scope resolution
/// operator in C++. This lookup completely ignores operator, object,
/// function, and enumerator names (C++ [basic.lookup.qual]p1).
LookupNestedNameSpecifierName,
/// Look up a namespace name within a C++ using directive or
/// namespace alias definition, ignoring non-namespace names (C++
/// [basic.lookup.udir]p1).
LookupNamespaceName,
/// Look up all declarations in a scope with the given name,
/// including resolved using declarations. This is appropriate
/// for checking redeclarations for a using declaration.
LookupUsingDeclName,
/// Look up an ordinary name that is going to be redeclared as a
/// name with linkage. This lookup ignores any declarations that
/// are outside of the current scope unless they have linkage. See
/// C99 6.2.2p4-5 and C++ [basic.link]p6.
LookupRedeclarationWithLinkage,
/// Look up a friend of a local class. This lookup does not look
/// outside the innermost non-class scope. See C++11 [class.friend]p11.
LookupLocalFriendName,
/// Look up the name of an Objective-C protocol.
LookupObjCProtocolName,
/// Look up implicit 'self' parameter of an objective-c method.
LookupObjCImplicitSelfParam,
/// Look up the name of an OpenMP user-defined reduction operation.
LookupOMPReductionName,
/// Look up the name of an OpenMP user-defined mapper.
LookupOMPMapperName,
/// Look up any declaration with any name.
LookupAnyName
};
/// Specifies whether (or how) name lookup is being performed for a
/// redeclaration (vs. a reference).
enum RedeclarationKind {
/// The lookup is a reference to this name that is not for the
/// purpose of redeclaring the name.
NotForRedeclaration = 0,
/// The lookup results will be used for redeclaration of a name,
/// if an entity by that name already exists and is visible.
ForVisibleRedeclaration,
/// The lookup results will be used for redeclaration of a name
/// with external linkage; non-visible lookup results with external linkage
/// may also be found.
ForExternalRedeclaration
};
RedeclarationKind forRedeclarationInCurContext() {
// A declaration with an owning module for linkage can never link against
// anything that is not visible. We don't need to check linkage here; if
// the context has internal linkage, redeclaration lookup won't find things
// from other TUs, and we can't safely compute linkage yet in general.
if (cast<Decl>(CurContext)
->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
return ForVisibleRedeclaration;
return ForExternalRedeclaration;
}
/// The possible outcomes of name lookup for a literal operator.
enum LiteralOperatorLookupResult {
/// The lookup resulted in an error.
LOLR_Error,
/// The lookup found no match but no diagnostic was issued.
LOLR_ErrorNoDiagnostic,
/// The lookup found a single 'cooked' literal operator, which
/// expects a normal literal to be built and passed to it.
LOLR_Cooked,
/// The lookup found a single 'raw' literal operator, which expects
/// a string literal containing the spelling of the literal token.
LOLR_Raw,
/// The lookup found an overload set of literal operator templates,
/// which expect the characters of the spelling of the literal token to be
/// passed as a non-type template argument pack.
LOLR_Template,
/// The lookup found an overload set of literal operator templates,
/// which expect the character type and characters of the spelling of the
/// string literal token to be passed as template arguments.
LOLR_StringTemplate
};
SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
CXXSpecialMember SM,
bool ConstArg,
bool VolatileArg,
bool RValueThis,
bool ConstThis,
bool VolatileThis);
typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
TypoRecoveryCallback;
private:
bool CppLookupName(LookupResult &R, Scope *S);
struct TypoExprState {
std::unique_ptr<TypoCorrectionConsumer> Consumer;
TypoDiagnosticGenerator DiagHandler;
TypoRecoveryCallback RecoveryHandler;
TypoExprState();
TypoExprState(TypoExprState &&other) noexcept;
TypoExprState &operator=(TypoExprState &&other) noexcept;
};
/// The set of unhandled TypoExprs and their associated state.
llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
/// Creates a new TypoExpr AST node.
TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
TypoDiagnosticGenerator TDG,
TypoRecoveryCallback TRC);
// The set of known/encountered (unique, canonicalized) NamespaceDecls.
//
// The boolean value will be true to indicate that the namespace was loaded
// from an AST/PCH file, or false otherwise.
llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
/// Whether we have already loaded known namespaces from an extenal
/// source.
bool LoadedExternalKnownNamespaces;
/// Helper for CorrectTypo and CorrectTypoDelayed used to create and
/// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
/// should be skipped entirely.
std::unique_ptr<TypoCorrectionConsumer>
makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
Sema::LookupNameKind LookupKind, Scope *S,
CXXScopeSpec *SS,
CorrectionCandidateCallback &CCC,
DeclContext *MemberContext, bool EnteringContext,
const ObjCObjectPointerType *OPT,
bool ErrorRecovery);
public:
const TypoExprState &getTypoExprState(TypoExpr *TE) const;
/// Clears the state of the given TypoExpr.
void clearDelayedTypo(TypoExpr *TE);
/// Look up a name, looking for a single declaration. Return
/// null if the results were absent, ambiguous, or overloaded.
///
/// It is preferable to use the elaborated form and explicitly handle
/// ambiguity and overloaded.
NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
SourceLocation Loc,
LookupNameKind NameKind,
RedeclarationKind Redecl
= NotForRedeclaration);
bool LookupBuiltin(LookupResult &R);
bool LookupName(LookupResult &R, Scope *S,
bool AllowBuiltinCreation = false);
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
bool InUnqualifiedLookup = false);
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
CXXScopeSpec &SS);
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
bool AllowBuiltinCreation = false,
bool EnteringContext = false);
ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
RedeclarationKind Redecl
= NotForRedeclaration);
bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
QualType T1, QualType T2,
UnresolvedSetImpl &Functions);
LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
SourceLocation GnuLabelLoc = SourceLocation());
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
unsigned Quals);
CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
bool RValueThis, unsigned ThisQuals);
CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
unsigned Quals);
CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
bool RValueThis, unsigned ThisQuals);
CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
ArrayRef<QualType> ArgTys,
bool AllowRaw,
bool AllowTemplate,
bool AllowStringTemplate,
bool DiagnoseMissing);
bool isKnownName(StringRef name);
/// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
enum class FunctionEmissionStatus {
Emitted,
CUDADiscarded, // Discarded due to CUDA/HIP hostness
OMPDiscarded, // Discarded due to OpenMP hostness
TemplateDiscarded, // Discarded due to uninstantiated templates
Unknown,
};
FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl);
// Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
ArrayRef<Expr *> Args, ADLResult &Functions);
void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
VisibleDeclConsumer &Consumer,
bool IncludeGlobalScope = true,
bool LoadExternal = true);
void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
VisibleDeclConsumer &Consumer,
bool IncludeGlobalScope = true,
bool IncludeDependentBases = false,
bool LoadExternal = true);
enum CorrectTypoKind {
CTK_NonError, // CorrectTypo used in a non error recovery situation.
CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
};
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
Sema::LookupNameKind LookupKind,
Scope *S, CXXScopeSpec *SS,
CorrectionCandidateCallback &CCC,
CorrectTypoKind Mode,
DeclContext *MemberContext = nullptr,
bool EnteringContext = false,
const ObjCObjectPointerType *OPT = nullptr,
bool RecordFailure = true);
TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
Sema::LookupNameKind LookupKind, Scope *S,
CXXScopeSpec *SS,
CorrectionCandidateCallback &CCC,
TypoDiagnosticGenerator TDG,
TypoRecoveryCallback TRC, CorrectTypoKind Mode,
DeclContext *MemberContext = nullptr,
bool EnteringContext = false,
const ObjCObjectPointerType *OPT = nullptr);
/// Process any TypoExprs in the given Expr and its children,
/// generating diagnostics as appropriate and returning a new Expr if there
/// were typos that were all successfully corrected and ExprError if one or
/// more typos could not be corrected.
///
/// \param E The Expr to check for TypoExprs.
///
/// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
/// initializer.
///
/// \param Filter A function applied to a newly rebuilt Expr to determine if
/// it is an acceptable/usable result from a single combination of typo
/// corrections. As long as the filter returns ExprError, different
/// combinations of corrections will be tried until all are exhausted.
ExprResult
CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
llvm::function_ref<ExprResult(Expr *)> Filter =
[](Expr *E) -> ExprResult { return E; });
ExprResult
CorrectDelayedTyposInExpr(Expr *E,
llvm::function_ref<ExprResult(Expr *)> Filter) {
return CorrectDelayedTyposInExpr(E, nullptr, Filter);
}
ExprResult
CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
llvm::function_ref<ExprResult(Expr *)> Filter =
[](Expr *E) -> ExprResult { return E; }) {
return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
}
ExprResult
CorrectDelayedTyposInExpr(ExprResult ER,
llvm::function_ref<ExprResult(Expr *)> Filter) {
return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
}
void diagnoseTypo(const TypoCorrection &Correction,
const PartialDiagnostic &TypoDiag,
bool ErrorRecovery = true);
void diagnoseTypo(const TypoCorrection &Correction,
const PartialDiagnostic &TypoDiag,
const PartialDiagnostic &PrevNote,
bool ErrorRecovery = true);
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
ArrayRef<Expr *> Args,
AssociatedNamespaceSet &AssociatedNamespaces,
AssociatedClassSet &AssociatedClasses);
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
bool ConsiderLinkage, bool AllowInlineNamespace);
bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
void DiagnoseAmbiguousLookup(LookupResult &Result);
//@}
ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
SourceLocation IdLoc,
bool TypoCorrection = false);
NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
Scope *S, bool ForRedeclaration,
SourceLocation Loc);
NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
Scope *S);
void AddKnownFunctionAttributes(FunctionDecl *FD);
// More parsing and symbol table subroutines.
void ProcessPragmaWeak(Scope *S, Decl *D);
// Decl attributes - this routine is the top level dispatcher.
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
// Helper for delayed processing of attributes.
void ProcessDeclAttributeDelayed(Decl *D,
const ParsedAttributesView &AttrList);
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL,
bool IncludeCXX11Attributes = true);
bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
const ParsedAttributesView &AttrList);
void checkUnusedDeclAttributes(Declarator &D);
/// Map any API notes provided for this declaration to attributes on the
/// declaration.
///
/// Triggered by declaration-attribute processing.
void ProcessAPINotes(Decl *D);
/// Determine if type T is a valid subject for a nonnull and similar
/// attributes. By default, we look through references (the behavior used by
/// nonnull), but if the second parameter is true, then we treat a reference
/// type as valid.
bool isValidPointerAttrType(QualType T, bool RefOkay = false);
bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
const FunctionDecl *FD = nullptr);
bool CheckAttrTarget(const ParsedAttr &CurrAttr);
bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
StringRef &Str,
SourceLocation *ArgLocation = nullptr);
bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
bool checkMSInheritanceAttrOnDefinition(
CXXRecordDecl *RD, SourceRange Range, bool BestCase,
MSInheritanceModel SemanticSpelling);
void CheckAlignasUnderalignment(Decl *D);
/// Adjust the calling convention of a method to be the ABI default if it
/// wasn't specified explicitly. This handles method types formed from
/// function type typedefs and typename template arguments.
void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
SourceLocation Loc);
// Check if there is an explicit attribute, but only look through parens.
// The intent is to look for an attribute on the current declarator, but not
// one that came from a typedef.
bool hasExplicitCallingConv(QualType T);
/// Get the outermost AttributedType node that sets a calling convention.
/// Valid types should not have multiple attributes with different CCs.
const AttributedType *getCallingConvAttributedType(QualType T) const;
/// Check whether a nullability type specifier can be added to the given
/// type through some means not written in source (e.g. API notes).
///
/// \param type The type to which the nullability specifier will be
/// added. On success, this type will be updated appropriately.
///
/// \param nullability The nullability specifier to add.
///
/// \param diagLoc The location to use for diagnostics.
///
/// \param allowArrayTypes Whether to accept nullability specifiers on an
/// array type (e.g., because it will decay to a pointer).
///
/// \param overrideExisting Whether to override an existing, locally-specified
/// nullability specifier rather than complaining about the conflict.
///
/// \returns true if nullability cannot be applied, false otherwise.
bool checkImplicitNullabilityTypeSpecifier(QualType &type,
NullabilityKind nullability,
SourceLocation diagLoc,
bool allowArrayTypes,
bool overrideExisting);
/// Stmt attributes - this routine is the top level dispatcher.
StmtResult ProcessStmtAttributes(Stmt *Stmt,
const ParsedAttributesView &Attrs,
SourceRange Range);
void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
ObjCMethodDecl *MethodDecl,
bool IsProtocolMethodDecl);
void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
ObjCMethodDecl *Overridden,
bool IsProtocolMethodDecl);
/// WarnExactTypedMethods - This routine issues a warning if method
/// implementation declaration matches exactly that of its declaration.
void WarnExactTypedMethods(ObjCMethodDecl *Method,
ObjCMethodDecl *MethodDecl,
bool IsProtocolMethodDecl);
typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
/// CheckImplementationIvars - This routine checks if the instance variables
/// listed in the implelementation match those listed in the interface.
void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
ObjCIvarDecl **Fields, unsigned nIvars,
SourceLocation Loc);
/// ImplMethodsVsClassMethods - This is main routine to warn if any method
/// remains unimplemented in the class or category \@implementation.
void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
ObjCContainerDecl* IDecl,
bool IncompleteImpl = false);
/// DiagnoseUnimplementedProperties - This routine warns on those properties
/// which must be implemented by this implementation.
void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
ObjCContainerDecl *CDecl,
bool SynthesizeProperties);
/// Diagnose any null-resettable synthesized setters.
void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
/// DefaultSynthesizeProperties - This routine default synthesizes all
/// properties which must be synthesized in the class's \@implementation.
void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
ObjCInterfaceDecl *IDecl,
SourceLocation AtEnd);
void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
/// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
/// an ivar synthesized for 'Method' and 'Method' is a property accessor
/// declared in class 'IFace'.
bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
ObjCMethodDecl *Method, ObjCIvarDecl *IV);
/// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
/// backs the property is not used in the property's accessor.
void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
const ObjCImplementationDecl *ImplD);
/// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
/// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
/// It also returns ivar's property on success.
ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
const ObjCPropertyDecl *&PDecl) const;
/// Called by ActOnProperty to handle \@property declarations in
/// class extensions.
ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
SourceLocation AtLoc,
SourceLocation LParenLoc,
FieldDeclarator &FD,
Selector GetterSel,
SourceLocation GetterNameLoc,
Selector SetterSel,
SourceLocation SetterNameLoc,
const bool isReadWrite,
unsigned &Attributes,
const unsigned AttributesAsWritten,
QualType T,
TypeSourceInfo *TSI,
tok::ObjCKeywordKind MethodImplKind);
/// Called by ActOnProperty and HandlePropertyInClassExtension to
/// handle creating the ObjcPropertyDecl for a category or \@interface.
ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
ObjCContainerDecl *CDecl,
SourceLocation AtLoc,
SourceLocation LParenLoc,
FieldDeclarator &FD,
Selector GetterSel,
SourceLocation GetterNameLoc,
Selector SetterSel,
SourceLocation SetterNameLoc,
const bool isReadWrite,
const unsigned Attributes,
const unsigned AttributesAsWritten,
QualType T,
TypeSourceInfo *TSI,
tok::ObjCKeywordKind MethodImplKind,
DeclContext *lexicalDC = nullptr);
/// AtomicPropertySetterGetterRules - This routine enforces the rule (via
/// warning) when atomic property has one but not the other user-declared
/// setter or getter.
void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
ObjCInterfaceDecl* IDecl);
void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
void DiagnoseMissingDesignatedInitOverrides(
const ObjCImplementationDecl *ImplD,
const ObjCInterfaceDecl *IFD);
void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
enum MethodMatchStrategy {
MMS_loose,
MMS_strict
};
/// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
/// true, or false, accordingly.
bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
const ObjCMethodDecl *PrevMethod,
MethodMatchStrategy strategy = MMS_strict);
/// MatchAllMethodDeclarations - Check methods declaraed in interface or
/// or protocol against those declared in their implementations.
void MatchAllMethodDeclarations(const SelectorSet &InsMap,
const SelectorSet &ClsMap,
SelectorSet &InsMapSeen,
SelectorSet &ClsMapSeen,
ObjCImplDecl* IMPDecl,
ObjCContainerDecl* IDecl,
bool &IncompleteImpl,
bool ImmediateClass,
bool WarnCategoryMethodImpl=false);
/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
/// category matches with those implemented in its primary class and
/// warns each time an exact match is found.
void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
/// Add the given method to the list of globally-known methods.
void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
/// Returns default addr space for method qualifiers.
LangAS getDefaultCXXMethodAddrSpace() const;
private:
/// AddMethodToGlobalPool - Add an instance or factory method to the global
/// pool. See descriptoin of AddInstanceMethodToGlobalPool.
void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
/// LookupMethodInGlobalPool - Returns the instance or factory method and
/// optionally warns if there are multiple signatures.
ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
bool receiverIdOrClass,
bool instance);
public:
/// - Returns instance or factory methods in global method pool for
/// given selector. It checks the desired kind first, if none is found, and
/// parameter checkTheOther is set, it then checks the other kind. If no such
/// method or only one method is found, function returns false; otherwise, it
/// returns true.
bool
CollectMultipleMethodsInGlobalPool(Selector Sel,
SmallVectorImpl<ObjCMethodDecl*>& Methods,
bool InstanceFirst, bool CheckTheOther,
const ObjCObjectType *TypeBound = nullptr);
bool
AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
SourceRange R, bool receiverIdOrClass,
SmallVectorImpl<ObjCMethodDecl*>& Methods);
void
DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
Selector Sel, SourceRange R,
bool receiverIdOrClass);
private:
/// - Returns a selector which best matches given argument list or
/// nullptr if none could be found
ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
bool IsInstance,
SmallVectorImpl<ObjCMethodDecl*>& Methods);
/// Record the typo correction failure and return an empty correction.
TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
bool RecordFailure = true) {
if (RecordFailure)
TypoCorrectionFailures[Typo].insert(TypoLoc);
return TypoCorrection();
}
public:
/// AddInstanceMethodToGlobalPool - All instance methods in a translation
/// unit are added to a global pool. This allows us to efficiently associate
/// a selector with a method declaraation for purposes of typechecking
/// messages sent to "id" (where the class of the object is unknown).
void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
AddMethodToGlobalPool(Method, impl, /*instance*/true);
}
/// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
AddMethodToGlobalPool(Method, impl, /*instance*/false);
}
/// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
/// pool.
void AddAnyMethodToGlobalPool(Decl *D);
/// LookupInstanceMethodInGlobalPool - Returns the method and warns if
/// there are multiple signatures.
ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
bool receiverIdOrClass=false) {
return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
/*instance*/true);
}
/// LookupFactoryMethodInGlobalPool - Returns the method and warns if
/// there are multiple signatures.
ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
bool receiverIdOrClass=false) {
return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
/*instance*/false);
}
const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
QualType ObjectType=QualType());
/// LookupImplementedMethodInGlobalPool - Returns the method which has an
/// implementation.
ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
/// initialization.
void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
SmallVectorImpl<ObjCIvarDecl*> &Ivars);
//===--------------------------------------------------------------------===//
// Statement Parsing Callbacks: SemaStmt.cpp.
public:
class FullExprArg {
public:
FullExprArg() : E(nullptr) { }
FullExprArg(Sema &actions) : E(nullptr) { }
ExprResult release() {
return E;
}
Expr *get() const { return E; }
Expr *operator->() {
return E;
}
private:
// FIXME: No need to make the entire Sema class a friend when it's just
// Sema::MakeFullExpr that needs access to the constructor below.
friend class Sema;
explicit FullExprArg(Expr *expr) : E(expr) {}
Expr *E;
};
FullExprArg MakeFullExpr(Expr *Arg) {
return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
}
FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
return FullExprArg(
ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
}
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
ExprResult FE =
ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
/*DiscardedValue*/ true);
return FullExprArg(FE.get());
}
StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
StmtResult ActOnExprStmtError();
StmtResult ActOnNullStmt(SourceLocation SemiLoc,
bool HasLeadingEmptyMacro = false);
void ActOnStartOfCompoundStmt(bool IsStmtExpr);
void ActOnFinishOfCompoundStmt();
StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
ArrayRef<Stmt *> Elts, bool isStmtExpr);
/// A RAII object to enter scope of a compound statement.
class CompoundScopeRAII {
public:
CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
S.ActOnStartOfCompoundStmt(IsStmtExpr);
}
~CompoundScopeRAII() {
S.ActOnFinishOfCompoundStmt();
}
private:
Sema &S;
};
/// An RAII helper that pops function a function scope on exit.
struct FunctionScopeRAII {
Sema &S;
bool Active;
FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
~FunctionScopeRAII() {
if (Active)
S.PopFunctionScopeInfo();
}
void disable() { Active = false; }
};
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
SourceLocation StartLoc,
SourceLocation EndLoc);
void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
StmtResult ActOnForEachLValueExpr(Expr *E);
ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
SourceLocation DotDotDotLoc, ExprResult RHS,
SourceLocation ColonLoc);
void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
SourceLocation ColonLoc,
Stmt *SubStmt, Scope *CurScope);
StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
SourceLocation ColonLoc, Stmt *SubStmt);
StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
ArrayRef<const Attr*> Attrs,
Stmt *SubStmt);
class ConditionResult;
StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
Stmt *InitStmt,
ConditionResult Cond, Stmt *ThenVal,
SourceLocation ElseLoc, Stmt *ElseVal);
StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
Stmt *InitStmt,
ConditionResult Cond, Stmt *ThenVal,
SourceLocation ElseLoc, Stmt *ElseVal);
StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
Stmt *InitStmt,
ConditionResult Cond);
StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
Stmt *Switch, Stmt *Body);
StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
Stmt *Body);
StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
SourceLocation WhileLoc, SourceLocation CondLParen,
Expr *Cond, SourceLocation CondRParen);
StmtResult ActOnForStmt(SourceLocation ForLoc,
SourceLocation LParenLoc,
Stmt *First,
ConditionResult Second,
FullExprArg Third,
SourceLocation RParenLoc,
Stmt *Body);
ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
Expr *collection);
StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
Stmt *First, Expr *collection,
SourceLocation RParenLoc);
StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
enum BuildForRangeKind {
/// Initial building of a for-range statement.
BFRK_Build,
/// Instantiation or recovery rebuild of a for-range statement. Don't
/// attempt any typo-correction.
BFRK_Rebuild,
/// Determining whether a for-range statement could be built. Avoid any
/// unnecessary or irreversible actions.
BFRK_Check
};
StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
SourceLocation CoawaitLoc,
Stmt *InitStmt,
Stmt *LoopVar,
SourceLocation ColonLoc, Expr *Collection,
SourceLocation RParenLoc,
BuildForRangeKind Kind);
StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
SourceLocation CoawaitLoc,
Stmt *InitStmt,
SourceLocation ColonLoc,
Stmt *RangeDecl, Stmt *Begin, Stmt *End,
Expr *Cond, Expr *Inc,
Stmt *LoopVarDecl,
SourceLocation RParenLoc,
BuildForRangeKind Kind);
StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
SourceLocation LabelLoc,
LabelDecl *TheDecl);
StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
SourceLocation StarLoc,
Expr *DestExp);
StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
CapturedRegionKind Kind, unsigned NumParams);
typedef std::pair<StringRef, QualType> CapturedParamNameType;
void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
CapturedRegionKind Kind,
ArrayRef<CapturedParamNameType> Params,
unsigned OpenMPCaptureLevel = 0);
StmtResult ActOnCapturedRegionEnd(Stmt *S);
void ActOnCapturedRegionError();
RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
SourceLocation Loc,
unsigned NumParams);
enum CopyElisionSemanticsKind {
CES_Strict = 0,
CES_AllowParameters = 1,
CES_AllowDifferentTypes = 2,
CES_AllowExceptionVariables = 4,
CES_FormerDefault = (CES_AllowParameters),
CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes),
CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes |
CES_AllowExceptionVariables),
};
VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
CopyElisionSemanticsKind CESK);
bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
CopyElisionSemanticsKind CESK);
StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
Scope *CurScope);
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
bool IsVolatile, unsigned NumOutputs,
unsigned NumInputs, IdentifierInfo **Names,
MultiExprArg Constraints, MultiExprArg Exprs,
Expr *AsmString, MultiExprArg Clobbers,
unsigned NumLabels,
SourceLocation RParenLoc);
void FillInlineAsmIdentifierInfo(Expr *Res,
llvm::InlineAsmIdentifierInfo &Info);
ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &Id,
bool IsUnevaluatedContext);
bool LookupInlineAsmField(StringRef Base, StringRef Member,
unsigned &Offset, SourceLocation AsmLoc);
ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
SourceLocation AsmLoc);
StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
ArrayRef<Token> AsmToks,
StringRef AsmString,
unsigned NumOutputs, unsigned NumInputs,
ArrayRef<StringRef> Constraints,
ArrayRef<StringRef> Clobbers,
ArrayRef<Expr*> Exprs,
SourceLocation EndLoc);
LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
SourceLocation Location,
bool AlwaysCreate);
VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
SourceLocation StartLoc,
SourceLocation IdLoc, IdentifierInfo *Id,
bool Invalid = false);
Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
Decl *Parm, Stmt *Body);
StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
MultiStmtArg Catch, Stmt *Finally);
StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Scope *CurScope);
ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
Expr *operand);
StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
Expr *SynchExpr,
Stmt *SynchBody);
StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
SourceLocation StartLoc,
SourceLocation IdLoc,
IdentifierInfo *Id);
Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
Decl *ExDecl, Stmt *HandlerBlock);
StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
ArrayRef<Stmt *> Handlers);
StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
SourceLocation TryLoc, Stmt *TryBlock,
Stmt *Handler);
StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
Expr *FilterExpr,
Stmt *Block);
void ActOnStartSEHFinallyBlock();
void ActOnAbortSEHFinallyBlock();
StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
/// If it's a file scoped decl that must warn if not used, keep track
/// of it.
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
/// DiagnoseUnusedExprResult - If the statement passed in is an expression
/// whose result is unused, warn.
void DiagnoseUnusedExprResult(const Stmt *S);
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
void DiagnoseUnusedDecl(const NamedDecl *ND);
/// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
/// statement as a \p Body, and it is located on the same line.
///
/// This helps prevent bugs due to typos, such as:
/// if (condition);
/// do_stuff();
void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
const Stmt *Body,
unsigned DiagID);
/// Warn if a for/while loop statement \p S, which is followed by
/// \p PossibleBody, has a suspicious null statement as a body.
void DiagnoseEmptyLoopBody(const Stmt *S,
const Stmt *PossibleBody);
/// Warn if a value is moved to itself.
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
SourceLocation OpLoc);
/// Warn if we're implicitly casting from a _Nullable pointer type to a
/// _Nonnull one.
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
SourceLocation Loc);
/// Warn when implicitly casting 0 to nullptr.
void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
return DelayedDiagnostics.push(pool);
}
void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
typedef ProcessingContextState ParsingClassState;
ParsingClassState PushParsingClass() {
ParsingClassDepth++;
return DelayedDiagnostics.pushUndelayed();
}
void PopParsingClass(ParsingClassState state) {
ParsingClassDepth--;
DelayedDiagnostics.popUndelayed(state);
}
void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
const ObjCInterfaceDecl *UnknownObjCClass,
bool ObjCPropertyAccess,
bool AvoidPartialAvailabilityChecks = false,
ObjCInterfaceDecl *ClassReceiver = nullptr);
bool makeUnavailableInSystemHeader(SourceLocation loc,
UnavailableAttr::ImplicitReason reason);
/// Issue any -Wunguarded-availability warnings in \c FD
void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
//===--------------------------------------------------------------------===//
// Expression Parsing Callbacks: SemaExpr.cpp.
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
bool ObjCPropertyAccess = false,
bool AvoidPartialAvailabilityChecks = false,
ObjCInterfaceDecl *ClassReciever = nullptr);
void NoteDeletedFunction(FunctionDecl *FD);
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
ObjCMethodDecl *Getter,
SourceLocation Loc);
void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
ArrayRef<Expr *> Args);
void PushExpressionEvaluationContext(
ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
ExpressionEvaluationContextRecord::ExpressionKind Type =
ExpressionEvaluationContextRecord::EK_Other);
enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
void PushExpressionEvaluationContext(
ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
ExpressionEvaluationContextRecord::ExpressionKind Type =
ExpressionEvaluationContextRecord::EK_Other);
void PopExpressionEvaluationContext();
void DiscardCleanupsInEvaluationContext();
ExprResult TransformToPotentiallyEvaluated(Expr *E);
ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
ExprResult CheckUnevaluatedOperand(Expr *E);
void CheckUnusedVolatileAssignment(Expr *E);
ExprResult ActOnConstantExpression(ExprResult Res);
// Functions for marking a declaration referenced. These functions also
// contain the relevant logic for marking if a reference to a function or
// variable is an odr-use (in the C++11 sense). There are separate variants
// for expressions referring to a decl; these exist because odr-use marking
// needs to be delayed for some constant variables when we build one of the
// named expressions.
//
// MightBeOdrUse indicates whether the use could possibly be an odr-use, and
// should usually be true. This only needs to be set to false if the lack of
// odr-use cannot be determined from the current context (for instance,
// because the name denotes a virtual function and was written without an
// explicit nested-name-specifier).
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
bool MightBeOdrUse = true);
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
void MarkMemberReferenced(MemberExpr *E);
void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc,
unsigned CapturingScopeIndex);
ExprResult CheckLValueToRValueConversionOperand(Expr *E);
void CleanupVarDeclMarking();
enum TryCaptureKind {
TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
};
/// Try to capture the given variable.
///
/// \param Var The variable to capture.
///
/// \param Loc The location at which the capture occurs.
///
/// \param Kind The kind of capture, which may be implicit (for either a
/// block or a lambda), or explicit by-value or by-reference (for a lambda).
///
/// \param EllipsisLoc The location of the ellipsis, if one is provided in
/// an explicit lambda capture.
///
/// \param BuildAndDiagnose Whether we are actually supposed to add the
/// captures or diagnose errors. If false, this routine merely check whether
/// the capture can occur without performing the capture itself or complaining
/// if the variable cannot be captured.
///
/// \param CaptureType Will be set to the type of the field used to capture
/// this variable in the innermost block or lambda. Only valid when the
/// variable can be captured.
///
/// \param DeclRefType Will be set to the type of a reference to the capture
/// from within the current scope. Only valid when the variable can be
/// captured.
///
/// \param FunctionScopeIndexToStopAt If non-null, it points to the index
/// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
/// This is useful when enclosing lambdas must speculatively capture
/// variables that may or may not be used in certain specializations of
/// a nested generic lambda.
///
/// \returns true if an error occurred (i.e., the variable cannot be
/// captured) and false if the capture succeeded.
bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
SourceLocation EllipsisLoc, bool BuildAndDiagnose,
QualType &CaptureType,
QualType &DeclRefType,
const unsigned *const FunctionScopeIndexToStopAt);
/// Try to capture the given variable.
bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
TryCaptureKind Kind = TryCapture_Implicit,
SourceLocation EllipsisLoc = SourceLocation());
/// Checks if the variable must be captured.
bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
/// Given a variable, determine the type that a reference to that
/// variable will have in the given scope.
QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
/// Mark all of the declarations referenced within a particular AST node as
/// referenced. Used when template instantiation instantiates a non-dependent
/// type -- entities referenced by the type are now referenced.
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
void MarkDeclarationsReferencedInExpr(Expr *E,
bool SkipLocalVariables = false);
/// Try to recover by turning the given expression into a
/// call. Returns true if recovery was attempted or an error was
/// emitted; this may also leave the ExprResult invalid.
bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
bool ForceComplain = false,
bool (*IsPlausibleResult)(QualType) = nullptr);
/// Figure out if an expression could be turned into a call.
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
UnresolvedSetImpl &NonTemplateOverloads);
/// Conditionally issue a diagnostic based on the current
/// evaluation context.
///
/// \param Statement If Statement is non-null, delay reporting the
/// diagnostic until the function body is parsed, and then do a basic
/// reachability analysis to determine if the statement is reachable.
/// If it is unreachable, the diagnostic will not be emitted.
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
const PartialDiagnostic &PD);
/// Similar, but diagnostic is only produced if all the specified statements
/// are reachable.
bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
const PartialDiagnostic &PD);
// Primary Expressions.
SourceRange getExprRange(Expr *E) const;
ExprResult ActOnIdExpression(
Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
CorrectionCandidateCallback *CCC = nullptr,
bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
void DecomposeUnqualifiedId(const UnqualifiedId &Id,
TemplateArgumentListInfo &Buffer,
DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *&TemplateArgs);
bool
DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
CorrectionCandidateCallback &CCC,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
IdentifierInfo *II);
ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV);
ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
IdentifierInfo *II,
bool AllowBuiltinCreation=false);
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
bool isAddressOfOperand,
const TemplateArgumentListInfo *TemplateArgs);
/// If \p D cannot be odr-used in the current expression evaluation context,
/// return a reason explaining why. Otherwise, return NOUR_None.
NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
SourceLocation Loc,
const CXXScopeSpec *SS = nullptr);
DeclRefExpr *
BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
const DeclarationNameInfo &NameInfo,
const CXXScopeSpec *SS = nullptr,
NamedDecl *FoundD = nullptr,
SourceLocation TemplateKWLoc = SourceLocation(),
const TemplateArgumentListInfo *TemplateArgs = nullptr);
DeclRefExpr *
BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
const DeclarationNameInfo &NameInfo,
NestedNameSpecifierLoc NNS,
NamedDecl *FoundD = nullptr,
SourceLocation TemplateKWLoc = SourceLocation(),
const TemplateArgumentListInfo *TemplateArgs = nullptr);
ExprResult
BuildAnonymousStructUnionMemberReference(
const CXXScopeSpec &SS,
SourceLocation nameLoc,
IndirectFieldDecl *indirectField,
DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
Expr *baseObjectExpr = nullptr,
SourceLocation opLoc = SourceLocation());
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
LookupResult &R,
const TemplateArgumentListInfo *TemplateArgs,
const Scope *S);
ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
LookupResult &R,
const TemplateArgumentListInfo *TemplateArgs,
bool IsDefiniteInstance,
const Scope *S);
bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
const LookupResult &R,
bool HasTrailingLParen);
ExprResult
BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
const DeclarationNameInfo &NameInfo,
bool IsAddressOfOperand, const Scope *S,
TypeSourceInfo **RecoveryTSI = nullptr);
ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
LookupResult &R,
bool NeedsADL,
bool AcceptInvalidDecl = false);
ExprResult BuildDeclarationNameExpr(
const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
NamedDecl *FoundD = nullptr,
const TemplateArgumentListInfo *TemplateArgs = nullptr,
bool AcceptInvalidDecl = false);
ExprResult BuildLiteralOperatorCall(LookupResult &R,
DeclarationNameInfo &SuffixInfo,
ArrayRef<Expr *> Args,
SourceLocation LitEndLoc,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
ExprResult BuildPredefinedExpr(SourceLocation Loc,
PredefinedExpr::IdentKind IK);
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
ExprResult ActOnCharacterConstant(const Token &Tok,
Scope *UDLScope = nullptr);
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
ExprResult ActOnParenListExpr(SourceLocation L,
SourceLocation R,
MultiExprArg Val);
/// ActOnStringLiteral - The specified tokens were lexed as pasted string
/// fragments (e.g. "foo" "bar" L"baz").
ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
Scope *UDLScope = nullptr);
ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
SourceLocation DefaultLoc,
SourceLocation RParenLoc,
Expr *ControllingExpr,
ArrayRef<ParsedType> ArgTypes,
ArrayRef<Expr *> ArgExprs);
ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
SourceLocation DefaultLoc,
SourceLocation RParenLoc,
Expr *ControllingExpr,
ArrayRef<TypeSourceInfo *> Types,
ArrayRef<Expr *> Exprs);
// Binary/Unary Operators. 'Tok' is the token for the operator.
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
Expr *InputExpr);
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
UnaryOperatorKind Opc, Expr *Input);
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
tok::TokenKind Op, Expr *Input);
bool isQualifiedMemberAccess(Expr *E);
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind,
SourceRange R);
ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind);
ExprResult
ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind,
bool IsType, void *TyOrEx,
SourceRange ArgRange);
ExprResult CheckPlaceholderExpr(Expr *E);
bool CheckVecStepExpr(Expr *E);
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
SourceRange ExprRange,
UnaryExprOrTypeTrait ExprKind);
ExprResult ActOnSizeofParameterPackExpr(Scope *S,
SourceLocation OpLoc,
IdentifierInfo &Name,
SourceLocation NameLoc,
SourceLocation RParenLoc);
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
tok::TokenKind Kind, Expr *Input);
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
Expr *Idx, SourceLocation RLoc);
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Expr *Idx, SourceLocation RLoc);
ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
Expr *LowerBound, SourceLocation ColonLoc,
Expr *Length, SourceLocation RBLoc);
// This struct is for use by ActOnMemberAccess to allow
// BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
// changing the access operator from a '.' to a '->' (to see if that is the
// change needed to fix an error about an unknown member, e.g. when the class
// defines a custom operator->).
struct ActOnMemberAccessExtraArgs {
Scope *S;
UnqualifiedId &Id;
Decl *ObjCImpDecl;
};
ExprResult BuildMemberReferenceExpr(
Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs,
const Scope *S,
ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
ExprResult
BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
bool IsArrow, const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
NamedDecl *FirstQualifierInScope, LookupResult &R,
const TemplateArgumentListInfo *TemplateArgs,
const Scope *S,
bool SuppressQualifierCheck = false,
ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
SourceLocation OpLoc,
const CXXScopeSpec &SS, FieldDecl *Field,
DeclAccessPair FoundDecl,
const DeclarationNameInfo &MemberNameInfo);
ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
const CXXScopeSpec &SS,
const LookupResult &R);
ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
bool IsArrow, SourceLocation OpLoc,
const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
NamedDecl *FirstQualifierInScope,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &Member,
Decl *ObjCImpDecl);
MemberExpr *
BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
ValueDecl *Member, DeclAccessPair FoundDecl,
bool HadMultipleCandidates,
const DeclarationNameInfo &MemberNameInfo, QualType Ty,
ExprValueKind VK, ExprObjectKind OK,
const TemplateArgumentListInfo *TemplateArgs = nullptr);
MemberExpr *
BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
ValueDecl *Member, DeclAccessPair FoundDecl,
bool HadMultipleCandidates,
const DeclarationNameInfo &MemberNameInfo, QualType Ty,
ExprValueKind VK, ExprObjectKind OK,
const TemplateArgumentListInfo *TemplateArgs = nullptr);
void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
FunctionDecl *FDecl,
const FunctionProtoType *Proto,
ArrayRef<Expr *> Args,
SourceLocation RParenLoc,
bool ExecConfig = false);
void CheckStaticArrayArgument(SourceLocation CallLoc,
ParmVarDecl *Param,
const Expr *ArgExpr);
/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
/// This provides the location of the left/right parens and a list of comma
/// locations.
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
MultiExprArg ArgExprs, SourceLocation RParenLoc,
Expr *ExecConfig = nullptr);
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
MultiExprArg ArgExprs, SourceLocation RParenLoc,
Expr *ExecConfig = nullptr,
bool IsExecConfig = false);
enum class AtomicArgumentOrder { API, AST };
ExprResult
BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
SourceLocation RParenLoc, MultiExprArg Args,
AtomicExpr::AtomicOp Op,
AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
ExprResult
BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
Expr *Config = nullptr, bool IsExecConfig = false,
ADLCallKind UsesADL = ADLCallKind::NotADL);
ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
MultiExprArg ExecConfig,
SourceLocation GGGLoc);
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
Declarator &D, ParsedType &Ty,
SourceLocation RParenLoc, Expr *CastExpr);
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
TypeSourceInfo *Ty,
SourceLocation RParenLoc,
Expr *Op);
CastKind PrepareScalarCast(ExprResult &src, QualType destType);
/// Build an altivec or OpenCL literal.
ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
SourceLocation RParenLoc, Expr *E,
TypeSourceInfo *TInfo);
ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
ParsedType Ty,
SourceLocation RParenLoc,
Expr *InitExpr);
ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
TypeSourceInfo *TInfo,
SourceLocation RParenLoc,
Expr *LiteralExpr);
ExprResult ActOnInitList(SourceLocation LBraceLoc,
MultiExprArg InitArgList,
SourceLocation RBraceLoc);
ExprResult BuildInitList(SourceLocation LBraceLoc,
MultiExprArg InitArgList,
SourceLocation RBraceLoc);
ExprResult ActOnDesignatedInitializer(Designation &Desig,
SourceLocation EqualOrColonLoc,
bool GNUSyntax,
ExprResult Init);
private:
static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
public:
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
Expr *LHSExpr, Expr *RHSExpr);
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
/// in the case of a the GNU conditional expr extension.
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
SourceLocation ColonLoc,
Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
LabelDecl *TheDecl);
void ActOnStartStmtExpr();
ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
SourceLocation RPLoc); // "({..})"
// Handle the final expression in a statement expression.
ExprResult ActOnStmtExprResult(ExprResult E);
void ActOnStmtExprError();
// __builtin_offsetof(type, identifier(.identifier|[expr])*)
struct OffsetOfComponent {
SourceLocation LocStart, LocEnd;
bool isBrackets; // true if [expr], false if .ident
union {
IdentifierInfo *IdentInfo;
Expr *E;
} U;
};
/// __builtin_offsetof(type, a.b[123][456].c)
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
TypeSourceInfo *TInfo,
ArrayRef<OffsetOfComponent> Components,
SourceLocation RParenLoc);
ExprResult ActOnBuiltinOffsetOf(Scope *S,
SourceLocation BuiltinLoc,
SourceLocation TypeLoc,
ParsedType ParsedArgTy,
ArrayRef<OffsetOfComponent> Components,
SourceLocation RParenLoc);
// __builtin_choose_expr(constExpr, expr1, expr2)
ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
Expr *CondExpr, Expr *LHSExpr,
Expr *RHSExpr, SourceLocation RPLoc);
// __builtin_va_arg(expr, type)
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
SourceLocation RPLoc);
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
TypeSourceInfo *TInfo, SourceLocation RPLoc);
// __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(),
// __builtin_COLUMN()
ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
SourceLocation BuiltinLoc,
SourceLocation RPLoc);
// Build a potentially resolved SourceLocExpr.
ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
SourceLocation BuiltinLoc, SourceLocation RPLoc,
DeclContext *ParentContext);
// __null
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
bool CheckCaseExpression(Expr *E);
/// Describes the result of an "if-exists" condition check.
enum IfExistsResult {
/// The symbol exists.
IER_Exists,
/// The symbol does not exist.
IER_DoesNotExist,
/// The name is a dependent name, so the results will differ
/// from one instantiation to the next.
IER_Dependent,
/// An error occurred.
IER_Error
};
IfExistsResult
CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
const DeclarationNameInfo &TargetNameInfo);
IfExistsResult
CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
bool IsIfExists, CXXScopeSpec &SS,
UnqualifiedId &Name);
StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
bool IsIfExists,
NestedNameSpecifierLoc QualifierLoc,
DeclarationNameInfo NameInfo,
Stmt *Nested);
StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
bool IsIfExists,
CXXScopeSpec &SS, UnqualifiedId &Name,
Stmt *Nested);
//===------------------------- "Block" Extension ------------------------===//
/// ActOnBlockStart - This callback is invoked when a block literal is
/// started.
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
/// ActOnBlockArguments - This callback allows processing of block arguments.
/// If there are no arguments, this is still invoked.
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
Scope *CurScope);
/// ActOnBlockError - If there is an error parsing a block, this callback
/// is invoked to pop the information about the block from the action impl.
void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
/// ActOnBlockStmtExpr - This is called when the body of a block statement
/// literal was successfully completed. ^(int x){...}
ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
Scope *CurScope);
//===---------------------------- Clang Extensions ----------------------===//
/// __builtin_convertvector(...)
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc);
//===---------------------------- OpenCL Features -----------------------===//
/// __builtin_astype(...)
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc);
//===---------------------------- C++ Features --------------------------===//
// Act on C++ namespaces
Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
SourceLocation NamespaceLoc,
SourceLocation IdentLoc, IdentifierInfo *Ident,
SourceLocation LBrace,
const ParsedAttributesView &AttrList,
UsingDirectiveDecl *&UsingDecl);
void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
NamespaceDecl *getStdNamespace() const;
NamespaceDecl *getOrCreateStdNamespace();
NamespaceDecl *lookupStdExperimentalNamespace();
CXXRecordDecl *getStdBadAlloc() const;
EnumDecl *getStdAlignValT() const;
private:
// A cache representing if we've fully checked the various comparison category
// types stored in ASTContext. The bit-index corresponds to the integer value
// of a ComparisonCategoryType enumerator.
llvm::SmallBitVector FullyCheckedComparisonCategories;
ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
CXXScopeSpec &SS,
ParsedType TemplateTypeTy,
IdentifierInfo *MemberOrBase);
public:
enum class ComparisonCategoryUsage {
/// The '<=>' operator was used in an expression and a builtin operator
/// was selected.
OperatorInExpression,
/// A defaulted 'operator<=>' needed the comparison category. This
/// typically only applies to 'std::strong_ordering', due to the implicit
/// fallback return value.
DefaultedOperator,
};
/// Lookup the specified comparison category types in the standard
/// library, an check the VarDecls possibly returned by the operator<=>
/// builtins for that type.
///
/// \return The type of the comparison category type corresponding to the
/// specified Kind, or a null type if an error occurs
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
SourceLocation Loc,
ComparisonCategoryUsage Usage);
/// Tests whether Ty is an instance of std::initializer_list and, if
/// it is and Element is not NULL, assigns the element type to Element.
bool isStdInitializerList(QualType Ty, QualType *Element);
/// Looks for the std::initializer_list template and instantiates it
/// with Element, or emits an error if it's not found.
///
/// \returns The instantiated template, or null on error.
QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
/// Determine whether Ctor is an initializer-list constructor, as
/// defined in [dcl.init.list]p2.
bool isInitListConstructor(const FunctionDecl *Ctor);
Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
SourceLocation NamespcLoc, CXXScopeSpec &SS,
SourceLocation IdentLoc,
IdentifierInfo *NamespcName,
const ParsedAttributesView &AttrList);
void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
Decl *ActOnNamespaceAliasDef(Scope *CurScope,
SourceLocation NamespaceLoc,
SourceLocation AliasLoc,
IdentifierInfo *Alias,
CXXScopeSpec &SS,
SourceLocation IdentLoc,
IdentifierInfo *Ident);
void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
const LookupResult &PreviousDecls,
UsingShadowDecl *&PrevShadow);
UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
NamedDecl *Target,
UsingShadowDecl *PrevDecl);
bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
bool HasTypenameKeyword,
const CXXScopeSpec &SS,
SourceLocation NameLoc,
const LookupResult &Previous);
bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
bool HasTypename,
const CXXScopeSpec &SS,
const DeclarationNameInfo &NameInfo,
SourceLocation NameLoc);
NamedDecl *BuildUsingDeclaration(
Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
const ParsedAttributesView &AttrList, bool IsInstantiation);
NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
ArrayRef<NamedDecl *> Expansions);
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
/// Given a derived-class using shadow declaration for a constructor and the
/// correspnding base class constructor, find or create the implicit
/// synthesized derived class constructor to use for this initialization.
CXXConstructorDecl *
findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
ConstructorUsingShadowDecl *DerivedShadow);
Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
SourceLocation UsingLoc,
SourceLocation TypenameLoc, CXXScopeSpec &SS,
UnqualifiedId &Name, SourceLocation EllipsisLoc,
const ParsedAttributesView &AttrList);
Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
MultiTemplateParamsArg TemplateParams,
SourceLocation UsingLoc, UnqualifiedId &Name,
const ParsedAttributesView &AttrList,
TypeResult Type, Decl *DeclFromDeclSpec);
/// BuildCXXConstructExpr - Creates a complete call to a constructor,
/// including handling of its default argument expressions.
///
/// \param ConstructKind - a CXXConstructExpr::ConstructionKind
ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
NamedDecl *FoundDecl,
CXXConstructorDecl *Constructor, MultiExprArg Exprs,
bool HadMultipleCandidates, bool IsListInitialization,
bool IsStdInitListInitialization,
bool RequiresZeroInit, unsigned ConstructKind,
SourceRange ParenRange);
/// Build a CXXConstructExpr whose constructor has already been resolved if
/// it denotes an inherited constructor.
ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
CXXConstructorDecl *Constructor, bool Elidable,
MultiExprArg Exprs,
bool HadMultipleCandidates, bool IsListInitialization,
bool IsStdInitListInitialization,
bool RequiresZeroInit, unsigned ConstructKind,
SourceRange ParenRange);
// FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
// the constructor can be elidable?
ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
NamedDecl *FoundDecl,
CXXConstructorDecl *Constructor, bool Elidable,
MultiExprArg Exprs, bool HadMultipleCandidates,
bool IsListInitialization,
bool IsStdInitListInitialization, bool RequiresZeroInit,
unsigned ConstructKind, SourceRange ParenRange);
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
/// Instantiate or parse a C++ default argument expression as necessary.
/// Return true on error.
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
ParmVarDecl *Param);
/// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
/// the default expr if needed.
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
FunctionDecl *FD,
ParmVarDecl *Param);
/// FinalizeVarWithDestructor - Prepare for calling destructor on the
/// constructed variable.
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
/// Helper class that collects exception specifications for
/// implicitly-declared special member functions.
class ImplicitExceptionSpecification {
// Pointer to allow copying
Sema *Self;
// We order exception specifications thus:
// noexcept is the most restrictive, but is only used in C++11.
// throw() comes next.
// Then a throw(collected exceptions)
// Finally no specification, which is expressed as noexcept(false).
// throw(...) is used instead if any called function uses it.
ExceptionSpecificationType ComputedEST;
llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
SmallVector<QualType, 4> Exceptions;
void ClearExceptions() {
ExceptionsSeen.clear();
Exceptions.clear();
}
public:
explicit ImplicitExceptionSpecification(Sema &Self)
: Self(&Self), ComputedEST(EST_BasicNoexcept) {
if (!Self.getLangOpts().CPlusPlus11)
ComputedEST = EST_DynamicNone;
}
/// Get the computed exception specification type.
ExceptionSpecificationType getExceptionSpecType() const {
assert(!isComputedNoexcept(ComputedEST) &&
"noexcept(expr) should not be a possible result");
return ComputedEST;
}
/// The number of exceptions in the exception specification.
unsigned size() const { return Exceptions.size(); }
/// The set of exceptions in the exception specification.
const QualType *data() const { return Exceptions.data(); }
/// Integrate another called method into the collected data.
void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
/// Integrate an invoked expression into the collected data.
void CalledExpr(Expr *E) { CalledStmt(E); }
/// Integrate an invoked statement into the collected data.
void CalledStmt(Stmt *S);
/// Overwrite an EPI's exception specification with this
/// computed exception specification.
FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
FunctionProtoType::ExceptionSpecInfo ESI;
ESI.Type = getExceptionSpecType();
if (ESI.Type == EST_Dynamic) {
ESI.Exceptions = Exceptions;
} else if (ESI.Type == EST_None) {
/// C++11 [except.spec]p14:
/// The exception-specification is noexcept(false) if the set of
/// potential exceptions of the special member function contains "any"
ESI.Type = EST_NoexceptFalse;
ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
tok::kw_false).get();
}
return ESI;
}
};
/// Determine what sort of exception specification a defaulted
/// copy constructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
CXXMethodDecl *MD);
/// Determine what sort of exception specification a defaulted
/// default constructor of a class will have, and whether the parameter
/// will be const.
ImplicitExceptionSpecification
ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
/// Determine what sort of exception specification a defaulted
/// copy assignment operator of a class will have, and whether the
/// parameter will be const.
ImplicitExceptionSpecification
ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
/// Determine what sort of exception specification a defaulted move
/// constructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
/// Determine what sort of exception specification a defaulted move
/// assignment operator of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
/// Determine what sort of exception specification a defaulted
/// destructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
/// Determine what sort of exception specification an inheriting
/// constructor of a class will have.
ImplicitExceptionSpecification
ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
CXXConstructorDecl *CD);
/// Evaluate the implicit exception specification for a defaulted
/// special member function.
void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
/// Check the given noexcept-specifier, convert its expression, and compute
/// the appropriate ExceptionSpecificationType.
ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr,
ExceptionSpecificationType &EST);
/// Check the given exception-specification and update the
/// exception specification information with the results.
void checkExceptionSpecification(bool IsTopLevel,
ExceptionSpecificationType EST,
ArrayRef<ParsedType> DynamicExceptions,
ArrayRef<SourceRange> DynamicExceptionRanges,
Expr *NoexceptExpr,
SmallVectorImpl<QualType> &Exceptions,
FunctionProtoType::ExceptionSpecInfo &ESI);
/// Determine if we're in a case where we need to (incorrectly) eagerly
/// parse an exception specification to work around a libstdc++ bug.
bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
/// Add an exception-specification to the given member function
/// (or member function template). The exception-specification was parsed
/// after the method itself was declared.
void actOnDelayedExceptionSpecification(Decl *Method,
ExceptionSpecificationType EST,
SourceRange SpecificationRange,
ArrayRef<ParsedType> DynamicExceptions,
ArrayRef<SourceRange> DynamicExceptionRanges,
Expr *NoexceptExpr);
class InheritedConstructorInfo;
/// Determine if a special member function should have a deleted
/// definition when it is defaulted.
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
InheritedConstructorInfo *ICI = nullptr,
bool Diagnose = false);
/// Produce notes explaining why a defaulted function was defined as deleted.
void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
/// Declare the implicit default constructor for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// default constructor will be added.
///
/// \returns The implicitly-declared default constructor.
CXXConstructorDecl *DeclareImplicitDefaultConstructor(
CXXRecordDecl *ClassDecl);
/// DefineImplicitDefaultConstructor - Checks for feasibility of
/// defining this constructor as the default constructor.
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *Constructor);
/// Declare the implicit destructor for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// destructor will be added.
///
/// \returns The implicitly-declared destructor.
CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
/// DefineImplicitDestructor - Checks for feasibility of
/// defining this destructor as the default destructor.
void DefineImplicitDestructor(SourceLocation CurrentLocation,
CXXDestructorDecl *Destructor);
/// Build an exception spec for destructors that don't have one.
///
/// C++11 says that user-defined destructors with no exception spec get one
/// that looks as if the destructor was implicitly declared.
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
/// Define the specified inheriting constructor.
void DefineInheritingConstructor(SourceLocation UseLoc,
CXXConstructorDecl *Constructor);
/// Declare the implicit copy constructor for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// copy constructor will be added.
///
/// \returns The implicitly-declared copy constructor.
CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
/// DefineImplicitCopyConstructor - Checks for feasibility of
/// defining this constructor as the copy constructor.
void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *Constructor);
/// Declare the implicit move constructor for the given class.
///
/// \param ClassDecl The Class declaration into which the implicit
/// move constructor will be added.
///
/// \returns The implicitly-declared move constructor, or NULL if it wasn't
/// declared.
CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
/// DefineImplicitMoveConstructor - Checks for feasibility of
/// defining this constructor as the move constructor.
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *Constructor);
/// Declare the implicit copy assignment operator for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// copy assignment operator will be added.
///
/// \returns The implicitly-declared copy assignment operator.
CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
/// Defines an implicitly-declared copy assignment operator.
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
CXXMethodDecl *MethodDecl);
/// Declare the implicit move assignment operator for the given class.
///
/// \param ClassDecl The Class declaration into which the implicit
/// move assignment operator will be added.
///
/// \returns The implicitly-declared move assignment operator, or NULL if it
/// wasn't declared.
CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
/// Defines an implicitly-declared move assignment operator.
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
CXXMethodDecl *MethodDecl);
/// Force the declaration of any implicitly-declared members of this
/// class.
void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
/// Check a completed declaration of an implicit special member.
void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
/// Determine whether the given function is an implicitly-deleted
/// special member function.
bool isImplicitlyDeleted(FunctionDecl *FD);
/// Check whether 'this' shows up in the type of a static member
/// function after the (naturally empty) cv-qualifier-seq would be.
///
/// \returns true if an error occurred.
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
/// Whether this' shows up in the exception specification of a static
/// member function.
bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
/// Check whether 'this' shows up in the attributes of the given
/// static member function.
///
/// \returns true if an error occurred.
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
/// MaybeBindToTemporary - If the passed in expression has a record type with
/// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
/// it simply returns the passed in expression.
ExprResult MaybeBindToTemporary(Expr *E);
bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
MultiExprArg ArgsPtr,
SourceLocation Loc,
SmallVectorImpl<Expr*> &ConvertedArgs,
bool AllowExplicit = false,
bool IsListInitialization = false);
ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
SourceLocation NameLoc,
IdentifierInfo &Name);
ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc,
Scope *S, CXXScopeSpec &SS,
bool EnteringContext);
ParsedType getDestructorName(SourceLocation TildeLoc,
IdentifierInfo &II, SourceLocation NameLoc,
Scope *S, CXXScopeSpec &SS,
ParsedType ObjectType,
bool EnteringContext);
ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
ParsedType ObjectType);
// Checks that reinterpret casts don't have undefined behavior.
void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
bool IsDereference, SourceRange Range);
/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
tok::TokenKind Kind,
SourceLocation LAngleBracketLoc,
Declarator &D,
SourceLocation RAngleBracketLoc,
SourceLocation LParenLoc,
Expr *E,
SourceLocation RParenLoc);
ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
tok::TokenKind Kind,
TypeSourceInfo *Ty,
Expr *E,
SourceRange AngleBrackets,
SourceRange Parens);
ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
ExprResult Operand,
SourceLocation RParenLoc);
ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
Expr *Operand, SourceLocation RParenLoc);
ExprResult BuildCXXTypeId(QualType TypeInfoType,
SourceLocation TypeidLoc,
TypeSourceInfo *Operand,
SourceLocation RParenLoc);
ExprResult BuildCXXTypeId(QualType TypeInfoType,
SourceLocation TypeidLoc,
Expr *Operand,
SourceLocation RParenLoc);
/// ActOnCXXTypeid - Parse typeid( something ).
ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
SourceLocation LParenLoc, bool isType,
void *TyOrExpr,
SourceLocation RParenLoc);
ExprResult BuildCXXUuidof(QualType TypeInfoType,
SourceLocation TypeidLoc,
TypeSourceInfo *Operand,
SourceLocation RParenLoc);
ExprResult BuildCXXUuidof(QualType TypeInfoType,
SourceLocation TypeidLoc,
Expr *Operand,
SourceLocation RParenLoc);
/// ActOnCXXUuidof - Parse __uuidof( something ).
ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
SourceLocation LParenLoc, bool isType,
void *TyOrExpr,
SourceLocation RParenLoc);
/// Handle a C++1z fold-expression: ( expr op ... op expr ).
ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
tok::TokenKind Operator,
SourceLocation EllipsisLoc, Expr *RHS,
SourceLocation RParenLoc);
ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
BinaryOperatorKind Operator,
SourceLocation EllipsisLoc, Expr *RHS,
SourceLocation RParenLoc,
Optional<unsigned> NumExpansions);
ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
BinaryOperatorKind Operator);
//// ActOnCXXThis - Parse 'this' pointer.
ExprResult ActOnCXXThis(SourceLocation loc);
/// Build a CXXThisExpr and mark it referenced in the current context.
Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
void MarkThisReferenced(CXXThisExpr *This);
/// Try to retrieve the type of the 'this' pointer.
///
/// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
QualType getCurrentThisType();
/// When non-NULL, the C++ 'this' expression is allowed despite the
/// current context not being a non-static member function. In such cases,
/// this provides the type used for 'this'.
QualType CXXThisTypeOverride;
/// RAII object used to temporarily allow the C++ 'this' expression
/// to be used, with the given qualifiers on the current class type.
class CXXThisScopeRAII {
Sema &S;
QualType OldCXXThisTypeOverride;
bool Enabled;
public:
/// Introduce a new scope where 'this' may be allowed (when enabled),
/// using the given declaration (which is either a class template or a
/// class) along with the given qualifiers.
/// along with the qualifiers placed on '*this'.
CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
bool Enabled = true);
~CXXThisScopeRAII();
};
/// Make sure the value of 'this' is actually available in the current
/// context, if it is a potentially evaluated context.
///
/// \param Loc The location at which the capture of 'this' occurs.
///
/// \param Explicit Whether 'this' is explicitly captured in a lambda
/// capture list.
///
/// \param FunctionScopeIndexToStopAt If non-null, it points to the index
/// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
/// This is useful when enclosing lambdas must speculatively capture
/// 'this' that may or may not be used in certain specializations of
/// a nested generic lambda (depending on whether the name resolves to
/// a non-static member function or a static function).
/// \return returns 'true' if failed, 'false' if success.
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
bool BuildAndDiagnose = true,
const unsigned *const FunctionScopeIndexToStopAt = nullptr,
bool ByCopy = false);
/// Determine whether the given type is the type of *this that is used
/// outside of the body of a member function for a type that is currently
/// being defined.
bool isThisOutsideMemberFunctionBody(QualType BaseType);
/// ActOnCXXBoolLiteral - Parse {true,false} literals.
ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
ExprResult
ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
SourceLocation AtLoc, SourceLocation RParen);
/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
//// ActOnCXXThrow - Parse throw expressions.
ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
bool IsThrownVarInScope);
bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
/// Can be interpreted either as function-style casting ("int(x)")
/// or class type construction ("ClassType(x,y,z)")
/// or creation of a value-initialized type ("int()").
ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
SourceLocation LParenOrBraceLoc,
MultiExprArg Exprs,
SourceLocation RParenOrBraceLoc,
bool ListInitialization);
ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
SourceLocation LParenLoc,
MultiExprArg Exprs,
SourceLocation RParenLoc,
bool ListInitialization);
/// ActOnCXXNew - Parsed a C++ 'new' expression.
ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
SourceLocation PlacementLParen,
MultiExprArg PlacementArgs,
SourceLocation PlacementRParen,
SourceRange TypeIdParens, Declarator &D,
Expr *Initializer);
ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
SourceLocation PlacementLParen,
MultiExprArg PlacementArgs,
SourceLocation PlacementRParen,
SourceRange TypeIdParens,
QualType AllocType,
TypeSourceInfo *AllocTypeInfo,
Optional<Expr *> ArraySize,
SourceRange DirectInitRange,
Expr *Initializer);
/// Determine whether \p FD is an aligned allocation or deallocation
/// function that is unavailable.
bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
/// Produce diagnostics if \p FD is an aligned allocation or deallocation
/// function that is unavailable.
void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
SourceLocation Loc);
bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
SourceRange R);
/// The scope in which to find allocation functions.
enum AllocationFunctionScope {
/// Only look for allocation functions in the global scope.
AFS_Global,
/// Only look for allocation functions in the scope of the
/// allocated class.
AFS_Class,
/// Look for allocation functions in both the global scope
/// and in the scope of the allocated class.
AFS_Both
};
/// Finds the overloads of operator new and delete that are appropriate
/// for the allocation.
bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
AllocationFunctionScope NewScope,
AllocationFunctionScope DeleteScope,
QualType AllocType, bool IsArray,
bool &PassAlignment, MultiExprArg PlaceArgs,
FunctionDecl *&OperatorNew,
FunctionDecl *&OperatorDelete,
bool Diagnose = true);
void DeclareGlobalNewDelete();
void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
ArrayRef<QualType> Params);
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
DeclarationName Name, FunctionDecl* &Operator,
bool Diagnose = true);
FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
bool CanProvideSize,
bool Overaligned,
DeclarationName Name);
FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
CXXRecordDecl *RD);
/// ActOnCXXDelete - Parsed a C++ 'delete' expression
ExprResult ActOnCXXDelete(SourceLocation StartLoc,
bool UseGlobal, bool ArrayForm,
Expr *Operand);
void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
bool IsDelete, bool CallCanBeVirtual,
bool WarnOnNonAbstractTypes,
SourceLocation DtorLoc);
ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
Expr *Operand, SourceLocation RParen);
ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
SourceLocation RParen);
/// Parsed one of the type trait support pseudo-functions.
ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
ArrayRef<ParsedType> Args,
SourceLocation RParenLoc);
ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
ArrayRef<TypeSourceInfo *> Args,
SourceLocation RParenLoc);
/// ActOnArrayTypeTrait - Parsed one of the binary type trait support
/// pseudo-functions.
ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
SourceLocation KWLoc,
ParsedType LhsTy,
Expr *DimExpr,
SourceLocation RParen);
ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
SourceLocation KWLoc,
TypeSourceInfo *TSInfo,
Expr *DimExpr,
SourceLocation RParen);
/// ActOnExpressionTrait - Parsed one of the unary type trait support
/// pseudo-functions.
ExprResult ActOnExpressionTrait(ExpressionTrait OET,
SourceLocation KWLoc,
Expr *Queried,
SourceLocation RParen);
ExprResult BuildExpressionTrait(ExpressionTrait OET,
SourceLocation KWLoc,
Expr *Queried,
SourceLocation RParen);
ExprResult ActOnStartCXXMemberReference(Scope *S,
Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
ParsedType &ObjectType,
bool &MayBePseudoDestructor);
ExprResult BuildPseudoDestructorExpr(Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
const CXXScopeSpec &SS,
TypeSourceInfo *ScopeType,
SourceLocation CCLoc,
SourceLocation TildeLoc,
PseudoDestructorTypeStorage DestroyedType);
ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
CXXScopeSpec &SS,
UnqualifiedId &FirstTypeName,
SourceLocation CCLoc,
SourceLocation TildeLoc,
UnqualifiedId &SecondTypeName);
ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
SourceLocation TildeLoc,
const DeclSpec& DS);
/// MaybeCreateExprWithCleanups - If the current full-expression
/// requires any cleanups, surround it with a ExprWithCleanups node.
/// Otherwise, just returns the passed-in expression.
Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
MaterializeTemporaryExpr *
CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
bool BoundToLvalueReference);
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
return ActOnFinishFullExpr(
Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
}
ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
bool DiscardedValue, bool IsConstexpr = false);
StmtResult ActOnFinishFullStmt(Stmt *Stmt);
// Marks SS invalid if it represents an incomplete type.
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
DeclContext *computeDeclContext(QualType T);
DeclContext *computeDeclContext(const CXXScopeSpec &SS,
bool EnteringContext = false);
bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
/// The parser has parsed a global nested-name-specifier '::'.
///
/// \param CCLoc The location of the '::'.
///
/// \param SS The nested-name-specifier, which will be updated in-place
/// to reflect the parsed nested-name-specifier.
///
/// \returns true if an error occurred, false otherwise.
bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
/// The parser has parsed a '__super' nested-name-specifier.
///
/// \param SuperLoc The location of the '__super' keyword.
///
/// \param ColonColonLoc The location of the '::'.
///
/// \param SS The nested-name-specifier, which will be updated in-place
/// to reflect the parsed nested-name-specifier.
///
/// \returns true if an error occurred, false otherwise.
bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
SourceLocation ColonColonLoc, CXXScopeSpec &SS);
bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
bool *CanCorrect = nullptr);
NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
/// Keeps information about an identifier in a nested-name-spec.
///
struct NestedNameSpecInfo {
/// The type of the object, if we're parsing nested-name-specifier in
/// a member access expression.
ParsedType ObjectType;
/// The identifier preceding the '::'.
IdentifierInfo *Identifier;
/// The location of the identifier.
SourceLocation IdentifierLoc;
/// The location of the '::'.
SourceLocation CCLoc;
/// Creates info object for the most typical case.
NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
: ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
CCLoc(ColonColonLoc) {
}
NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
SourceLocation ColonColonLoc, QualType ObjectType)
: ObjectType(ParsedType::make(ObjectType)), Identifier(II),
IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
}
};
bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
NestedNameSpecInfo &IdInfo);
bool BuildCXXNestedNameSpecifier(Scope *S,
NestedNameSpecInfo &IdInfo,
bool EnteringContext,
CXXScopeSpec &SS,
NamedDecl *ScopeLookupResult,
bool ErrorRecoveryLookup,
bool *IsCorrectedToColon = nullptr,
bool OnlyNamespace = false);
/// The parser has parsed a nested-name-specifier 'identifier::'.
///
/// \param S The scope in which this nested-name-specifier occurs.
///
/// \param IdInfo Parser information about an identifier in the
/// nested-name-spec.
///
/// \param EnteringContext Whether we're entering the context nominated by
/// this nested-name-specifier.
///
/// \param SS The nested-name-specifier, which is both an input
/// parameter (the nested-name-specifier before this type) and an
/// output parameter (containing the full nested-name-specifier,
/// including this new type).
///
/// \param ErrorRecoveryLookup If true, then this method is called to improve
/// error recovery. In this case do not emit error message.
///
/// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
/// are allowed. The bool value pointed by this parameter is set to 'true'
/// if the identifier is treated as if it was followed by ':', not '::'.
///
/// \param OnlyNamespace If true, only considers namespaces in lookup.
///
/// \returns true if an error occurred, false otherwise.
bool ActOnCXXNestedNameSpecifier(Scope *S,
NestedNameSpecInfo &IdInfo,
bool EnteringContext,
CXXScopeSpec &SS,
bool ErrorRecoveryLookup = false,
bool *IsCorrectedToColon = nullptr,
bool OnlyNamespace = false);
ExprResult ActOnDecltypeExpression(Expr *E);
bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
const DeclSpec &DS,
SourceLocation ColonColonLoc);
bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
NestedNameSpecInfo &IdInfo,
bool EnteringContext);
/// The parser has parsed a nested-name-specifier
/// 'template[opt] template-name < template-args >::'.
///
/// \param S The scope in which this nested-name-specifier occurs.
///
/// \param SS The nested-name-specifier, which is both an input
/// parameter (the nested-name-specifier before this type) and an
/// output parameter (containing the full nested-name-specifier,
/// including this new type).
///
/// \param TemplateKWLoc the location of the 'template' keyword, if any.
/// \param TemplateName the template name.
/// \param TemplateNameLoc The location of the template name.
/// \param LAngleLoc The location of the opening angle bracket ('<').
/// \param TemplateArgs The template arguments.
/// \param RAngleLoc The location of the closing angle bracket ('>').
/// \param CCLoc The location of the '::'.
///
/// \param EnteringContext Whether we're entering the context of the
/// nested-name-specifier.
///
///
/// \returns true if an error occurred, false otherwise.
bool ActOnCXXNestedNameSpecifier(Scope *S,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
TemplateTy TemplateName,
SourceLocation TemplateNameLoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc,
SourceLocation CCLoc,
bool EnteringContext);
/// Given a C++ nested-name-specifier, produce an annotation value
/// that the parser can use later to reconstruct the given
/// nested-name-specifier.
///
/// \param SS A nested-name-specifier.
///
/// \returns A pointer containing all of the information in the
/// nested-name-specifier \p SS.
void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
/// Given an annotation pointer for a nested-name-specifier, restore
/// the nested-name-specifier structure.
///
/// \param Annotation The annotation pointer, produced by
/// \c SaveNestedNameSpecifierAnnotation().
///
/// \param AnnotationRange The source range corresponding to the annotation.
///
/// \param SS The nested-name-specifier that will be updated with the contents
/// of the annotation pointer.
void RestoreNestedNameSpecifierAnnotation(void *Annotation,
SourceRange AnnotationRange,
CXXScopeSpec &SS);
bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
/// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
/// scope or nested-name-specifier) is parsed, part of a declarator-id.
/// After this method is called, according to [C++ 3.4.3p3], names should be
/// looked up in the declarator-id's scope, until the declarator is parsed and
/// ActOnCXXExitDeclaratorScope is called.
/// The 'SS' should be a non-empty valid CXXScopeSpec.
bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
/// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
/// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
/// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
/// Used to indicate that names should revert to being looked up in the
/// defining scope.
void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
/// initializer for the declaration 'Dcl'.
/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
/// static data member of class X, names should be looked up in the scope of
/// class X.
void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
/// initializer for the declaration 'Dcl'.
void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
/// Create a new lambda closure type.
CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
TypeSourceInfo *Info,
bool KnownDependent,
LambdaCaptureDefault CaptureDefault);
/// Start the definition of a lambda expression.
CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
SourceRange IntroducerRange,
TypeSourceInfo *MethodType,
SourceLocation EndLoc,
ArrayRef<ParmVarDecl *> Params,
ConstexprSpecKind ConstexprKind);
/// Number lambda for linkage purposes if necessary.
void handleLambdaNumbering(
CXXRecordDecl *Class, CXXMethodDecl *Method,
Optional<std::tuple<unsigned, bool, Decl *>> Mangling = None);
/// Endow the lambda scope info with the relevant properties.
void buildLambdaScope(sema::LambdaScopeInfo *LSI,
CXXMethodDecl *CallOperator,
SourceRange IntroducerRange,
LambdaCaptureDefault CaptureDefault,
SourceLocation CaptureDefaultLoc,
bool ExplicitParams,
bool ExplicitResultType,
bool Mutable);
/// Perform initialization analysis of the init-capture and perform
/// any implicit conversions such as an lvalue-to-rvalue conversion if
/// not being used to initialize a reference.
ParsedType actOnLambdaInitCaptureInitialization(
SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
return ParsedType::make(buildLambdaInitCaptureInitialization(
Loc, ByRef, EllipsisLoc, None, Id,
InitKind != LambdaCaptureInitKind::CopyInit, Init));
}
QualType buildLambdaInitCaptureInitialization(
SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit,
Expr *&Init);
/// Create a dummy variable within the declcontext of the lambda's
/// call operator, for name lookup purposes for a lambda init capture.
///
/// CodeGen handles emission of lambda captures, ignoring these dummy
/// variables appropriately.
VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
QualType InitCaptureType,
SourceLocation EllipsisLoc,
IdentifierInfo *Id,
unsigned InitStyle, Expr *Init);
/// Add an init-capture to a lambda scope.
void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var);
/// Note that we have finished the explicit captures for the
/// given lambda.
void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
/// \brief This is called after parsing the explicit template parameter list
/// on a lambda (if it exists) in C++2a.
void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
ArrayRef<NamedDecl *> TParams,
SourceLocation RAngleLoc);
/// Introduce the lambda parameters into scope.
void addLambdaParameters(
ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
CXXMethodDecl *CallOperator, Scope *CurScope);
/// Deduce a block or lambda's return type based on the return
/// statements present in the body.
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
/// ActOnStartOfLambdaDefinition - This is called just before we start
/// parsing the body of a lambda; it analyzes the explicit captures and
/// arguments, and sets up various data-structures for the body of the
/// lambda.
void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
Declarator &ParamInfo, Scope *CurScope);
/// ActOnLambdaError - If there is an error parsing a lambda, this callback
/// is invoked to pop the information about the lambda.
void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
bool IsInstantiation = false);
/// ActOnLambdaExpr - This is called when the body of a lambda expression
/// was successfully completed.
ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Scope *CurScope);
/// Does copying/destroying the captured variable have side effects?
bool CaptureHasSideEffects(const sema::Capture &From);
/// Diagnose if an explicit lambda capture is unused. Returns true if a
/// diagnostic is emitted.
bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
const sema::Capture &From);
/// Build a FieldDecl suitable to hold the given capture.
FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
/// Initialize the given capture with a suitable expression.
ExprResult BuildCaptureInit(const sema::Capture &Capture,
SourceLocation ImplicitCaptureLoc,
bool IsOpenMPMapping = false);
/// Complete a lambda-expression having processed and attached the
/// lambda body.
ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
sema::LambdaScopeInfo *LSI);
/// Get the return type to use for a lambda's conversion function(s) to
/// function pointer type, given the type of the call operator.
QualType
getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType);
/// Define the "body" of the conversion from a lambda object to a
/// function pointer.
///
/// This routine doesn't actually define a sensible body; rather, it fills
/// in the initialization expression needed to copy the lambda object into
/// the block, and IR generation actually generates the real body of the
/// block pointer conversion.
void DefineImplicitLambdaToFunctionPointerConversion(
SourceLocation CurrentLoc, CXXConversionDecl *Conv);
/// Define the "body" of the conversion from a lambda object to a
/// block pointer.
///
/// This routine doesn't actually define a sensible body; rather, it fills
/// in the initialization expression needed to copy the lambda object into
/// the block, and IR generation actually generates the real body of the
/// block pointer conversion.
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
CXXConversionDecl *Conv);
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
SourceLocation ConvLocation,
CXXConversionDecl *Conv,
Expr *Src);
/// Check whether the given expression is a valid constraint expression.
/// A diagnostic is emitted if it is not, and false is returned.
bool CheckConstraintExpression(Expr *CE);
/// \brief Check whether the given list of constraint expressions are
/// satisfied (as if in a 'conjunction') given template arguments.
/// \param ConstraintExprs a list of constraint expressions, treated as if
/// they were 'AND'ed together.
/// \param TemplateArgs the list of template arguments to substitute into the
/// constraint expression.
/// \param TemplateIDRange The source range of the template id that
/// caused the constraints check.
/// \param Satisfaction if true is returned, will contain details of the
/// satisfaction, with enough information to diagnose an unsatisfied
/// expression.
/// \returns true if an error occurred and satisfaction could not be checked,
/// false otherwise.
bool CheckConstraintSatisfaction(TemplateDecl *Template,
ArrayRef<const Expr *> ConstraintExprs,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange TemplateIDRange,
ConstraintSatisfaction &Satisfaction);
bool CheckConstraintSatisfaction(ClassTemplatePartialSpecializationDecl *TD,
ArrayRef<const Expr *> ConstraintExprs,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange TemplateIDRange,
ConstraintSatisfaction &Satisfaction);
bool CheckConstraintSatisfaction(VarTemplatePartialSpecializationDecl *TD,
ArrayRef<const Expr *> ConstraintExprs,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange TemplateIDRange,
ConstraintSatisfaction &Satisfaction);
/// \brief Check whether the given non-dependent constraint expression is
/// satisfied. Returns false and updates Satisfaction with the satisfaction
/// verdict if successful, emits a diagnostic and returns true if an error
/// occured and satisfaction could not be determined.
///
/// \returns true if an error occurred, false otherwise.
bool CheckConstraintSatisfaction(const Expr *ConstraintExpr,
ConstraintSatisfaction &Satisfaction);
/// Check that the associated constraints of a template declaration match the
/// associated constraints of an older declaration of which it is a
/// redeclaration.
bool CheckRedeclarationConstraintMatch(TemplateParameterList *Old,
TemplateParameterList *New);
/// \brief Ensure that the given template arguments satisfy the constraints
/// associated with the given template, emitting a diagnostic if they do not.
///
/// \param Template The template to which the template arguments are being
/// provided.
///
/// \param TemplateArgs The converted, canonicalized template arguments.
///
/// \param TemplateIDRange The source range of the template id that
/// caused the constraints check.
///
/// \returns true if the constrains are not satisfied or could not be checked
/// for satisfaction, false if the constraints are satisfied.
bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange TemplateIDRange);
/// \brief Emit diagnostics explaining why a constraint expression was deemed
/// unsatisfied.
void
DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction& Satisfaction);
/// \brief Emit diagnostics explaining why a constraint expression was deemed
/// unsatisfied.
void
DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction& Satisfaction);
/// \brief Emit diagnostics explaining why a constraint expression was deemed
/// unsatisfied because it was ill-formed.
void DiagnoseUnsatisfiedIllFormedConstraint(SourceLocation DiagnosticLocation,
StringRef Diagnostic);
// ParseObjCStringLiteral - Parse Objective-C string literals.
ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
ArrayRef<Expr *> Strings);
ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
/// numeric literal expression. Type of the expression will be "NSNumber *"
/// or "id" if NSNumber is unavailable.
ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
bool Value);
ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
/// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
/// '@' prefixed parenthesized expression. The type of the expression will
/// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
/// of ValueType, which is allowed to be a built-in numeric type, "char *",
/// "const char *" or C structure with attribute 'objc_boxable'.
ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
Expr *IndexExpr,
ObjCMethodDecl *getterMethod,
ObjCMethodDecl *setterMethod);
ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
MutableArrayRef<ObjCDictionaryElement> Elements);
ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
TypeSourceInfo *EncodedTypeInfo,
SourceLocation RParenLoc);
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
CXXConversionDecl *Method,
bool HadMultipleCandidates);
ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
SourceLocation EncodeLoc,
SourceLocation LParenLoc,
ParsedType Ty,
SourceLocation RParenLoc);
/// ParseObjCSelectorExpression - Build selector expression for \@selector
ExprResult ParseObjCSelectorExpression(Selector Sel,
SourceLocation AtLoc,
SourceLocation SelLoc,
SourceLocation LParenLoc,
SourceLocation RParenLoc,
bool WarnMultipleSelectors);
/// ParseObjCProtocolExpression - Build protocol expression for \@protocol
ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
SourceLocation AtLoc,
SourceLocation ProtoLoc,
SourceLocation LParenLoc,
SourceLocation ProtoIdLoc,
SourceLocation RParenLoc);
//===--------------------------------------------------------------------===//
// C++ Declarations
//
Decl *ActOnStartLinkageSpecification(Scope *S,
SourceLocation ExternLoc,
Expr *LangStr,
SourceLocation LBraceLoc);
Decl *ActOnFinishLinkageSpecification(Scope *S,
Decl *LinkageSpec,
SourceLocation RBraceLoc);
//===--------------------------------------------------------------------===//
// C++ Classes
//
CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
const CXXScopeSpec *SS = nullptr);
bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
SourceLocation ColonLoc,
const ParsedAttributesView &Attrs);
NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
Declarator &D,
MultiTemplateParamsArg TemplateParameterLists,
Expr *BitfieldWidth, const VirtSpecifiers &VS,
InClassInitStyle InitStyle);
void ActOnStartCXXInClassMemberInitializer();
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
SourceLocation EqualLoc,
Expr *Init);
MemInitResult ActOnMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
SourceLocation LParenLoc,
ArrayRef<Expr *> Args,
SourceLocation RParenLoc,
SourceLocation EllipsisLoc);
MemInitResult ActOnMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
Expr *InitList,
SourceLocation EllipsisLoc);
MemInitResult BuildMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
Expr *Init,
SourceLocation EllipsisLoc);
MemInitResult BuildMemberInitializer(ValueDecl *Member,
Expr *Init,
SourceLocation IdLoc);
MemInitResult BuildBaseInitializer(QualType BaseType,
TypeSourceInfo *BaseTInfo,
Expr *Init,
CXXRecordDecl *ClassDecl,
SourceLocation EllipsisLoc);
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
Expr *Init,
CXXRecordDecl *ClassDecl);
bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
CXXCtorInitializer *Initializer);
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
ArrayRef<CXXCtorInitializer *> Initializers = None);
void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
/// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
/// mark all the non-trivial destructors of its members and bases as
/// referenced.
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
CXXRecordDecl *Record);
/// The list of classes whose vtables have been used within
/// this translation unit, and the source locations at which the
/// first use occurred.
typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
/// The list of vtables that are required but have not yet been
/// materialized.
SmallVector<VTableUse, 16> VTableUses;
/// The set of classes whose vtables have been used within
/// this translation unit, and a bit that will be true if the vtable is
/// required to be emitted (otherwise, it should be emitted only if needed
/// by code generation).
llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
/// Load any externally-stored vtable uses.
void LoadExternalVTableUses();
/// Note that the vtable for the given class was used at the
/// given location.
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
bool DefinitionRequired = false);
/// Mark the exception specifications of all virtual member functions
/// in the given class as needed.
void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
const CXXRecordDecl *RD);
/// MarkVirtualMembersReferenced - Will mark all members of the given
/// CXXRecordDecl referenced.
void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
bool ConstexprOnly = false);
/// Define all of the vtables that have been used in this
/// translation unit and reference any virtual members used by those
/// vtables.
///
/// \returns true if any work was done, false otherwise.
bool DefineUsedVTables();
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
void ActOnMemInitializers(Decl *ConstructorDecl,
SourceLocation ColonLoc,
ArrayRef<CXXCtorInitializer*> MemInits,
bool AnyErrors);
/// Check class-level dllimport/dllexport attribute. The caller must
/// ensure that referenceDLLExportedClassMethods is called some point later
/// when all outer classes of Class are complete.
void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
void referenceDLLExportedClassMethods();
void propagateDLLAttrToBaseClassTemplate(
CXXRecordDecl *Class, Attr *ClassAttr,
ClassTemplateSpecializationDecl *BaseTemplateSpec,
SourceLocation BaseLoc);
/// Add gsl::Pointer attribute to std::container::iterator
/// \param ND The declaration that introduces the name
/// std::container::iterator. \param UnderlyingRecord The record named by ND.
void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
/// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
/// Add [[gsl::Pointer]] attributes for std:: types.
void inferGslPointerAttribute(TypedefNameDecl *TD);
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
/// Check that the C++ class annoated with "trivial_abi" satisfies all the
/// conditions that are needed for the attribute to have an effect.
void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
Decl *TagDecl, SourceLocation LBrac,
SourceLocation RBrac,
const ParsedAttributesView &AttrList);
void ActOnFinishCXXMemberDecls();
void ActOnFinishCXXNonNestedClass();
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
void ActOnFinishDelayedMemberInitializers(Decl *Record);
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
CachedTokens &Toks);
void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
bool IsInsideALocalClassWithinATemplateFunction();
Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
Expr *AssertExpr,
Expr *AssertMessageExpr,
SourceLocation RParenLoc);
Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
Expr *AssertExpr,
StringLiteral *AssertMessageExpr,
SourceLocation RParenLoc,
bool Failed);
FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
SourceLocation FriendLoc,
TypeSourceInfo *TSInfo);
Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
MultiTemplateParamsArg TemplateParams);
NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParams);
QualType CheckConstructorDeclarator(Declarator &D, QualType R,
StorageClass& SC);
void CheckConstructor(CXXConstructorDecl *Constructor);
QualType CheckDestructorDeclarator(Declarator &D, QualType R,
StorageClass& SC);
bool CheckDestructor(CXXDestructorDecl *Destructor);
void CheckConversionDeclarator(Declarator &D, QualType &R,
StorageClass& SC);
Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
StorageClass &SC);
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
CXXSpecialMember CSM);
void CheckDelayedMemberExceptionSpecs();
bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
DefaultedComparisonKind DCK);
void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
FunctionDecl *Spaceship);
void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
DefaultedComparisonKind DCK);
//===--------------------------------------------------------------------===//
// C++ Derived Classes
//
/// ActOnBaseSpecifier - Parsed a base specifier
CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
SourceRange SpecifierRange,
bool Virtual, AccessSpecifier Access,
TypeSourceInfo *TInfo,
SourceLocation EllipsisLoc);
BaseResult ActOnBaseSpecifier(Decl *classdecl,
SourceRange SpecifierRange,
ParsedAttributes &Attrs,
bool Virtual, AccessSpecifier Access,
ParsedType basetype,
SourceLocation BaseLoc,
SourceLocation EllipsisLoc);
bool AttachBaseSpecifiers(CXXRecordDecl *Class,
MutableArrayRef<CXXBaseSpecifier *> Bases);
void ActOnBaseSpecifiers(Decl *ClassDecl,
MutableArrayRef<CXXBaseSpecifier *> Bases);
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
CXXBasePaths &Paths);
// FIXME: I don't like this name.
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
SourceLocation Loc, SourceRange Range,
CXXCastPath *BasePath = nullptr,
bool IgnoreAccess = false);
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
unsigned InaccessibleBaseID,
unsigned AmbigiousBaseConvID,
SourceLocation Loc, SourceRange Range,
DeclarationName Name,
CXXCastPath *BasePath,
bool IgnoreAccess = false);
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
/// CheckOverridingFunctionReturnType - Checks whether the return types are
/// covariant, according to C++ [class.virtual]p5.
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
/// CheckOverridingFunctionExceptionSpec - Checks whether the exception
/// spec is a subset of base spec.
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
/// CheckOverrideControl - Check C++11 override control semantics.
void CheckOverrideControl(NamedDecl *D);
/// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
/// not used in the declaration of an overriding method.
void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
/// CheckForFunctionMarkedFinal - Checks whether a virtual member function
/// overrides a virtual member function marked 'final', according to
/// C++11 [class.virtual]p4.
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
//===--------------------------------------------------------------------===//
// C++ Access Control
//
enum AccessResult {
AR_accessible,
AR_inaccessible,
AR_dependent,
AR_delayed
};
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
NamedDecl *PrevMemberDecl,
AccessSpecifier LexicalAS);
AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
DeclAccessPair FoundDecl);
AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
DeclAccessPair FoundDecl);
AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
SourceRange PlacementRange,
CXXRecordDecl *NamingClass,
DeclAccessPair FoundDecl,
bool Diagnose = true);
AccessResult CheckConstructorAccess(SourceLocation Loc,
CXXConstructorDecl *D,
DeclAccessPair FoundDecl,
const InitializedEntity &Entity,
bool IsCopyBindingRefToTemp = false);
AccessResult CheckConstructorAccess(SourceLocation Loc,
CXXConstructorDecl *D,
DeclAccessPair FoundDecl,
const InitializedEntity &Entity,
const PartialDiagnostic &PDiag);
AccessResult CheckDestructorAccess(SourceLocation Loc,
CXXDestructorDecl *Dtor,
const PartialDiagnostic &PDiag,
QualType objectType = QualType());
AccessResult CheckFriendAccess(NamedDecl *D);
AccessResult CheckMemberAccess(SourceLocation UseLoc,
CXXRecordDecl *NamingClass,
DeclAccessPair Found);
AccessResult
CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
CXXRecordDecl *DecomposedClass,
DeclAccessPair Field);
AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
Expr *ObjectExpr,
Expr *ArgExpr,
DeclAccessPair FoundDecl);
AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
DeclAccessPair FoundDecl);
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
QualType Base, QualType Derived,
const CXXBasePath &Path,
unsigned DiagID,
bool ForceCheck = false,
bool ForceUnprivileged = false);
void CheckLookupAccess(const LookupResult &R);
bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
QualType BaseType);
bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
DeclAccessPair Found, QualType ObjectType,
SourceLocation Loc,
const PartialDiagnostic &Diag);
bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
DeclAccessPair Found,
QualType ObjectType) {
return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
SourceLocation(), PDiag());
}
void HandleDependentAccessCheck(const DependentDiagnostic &DD,
const MultiLevelTemplateArgumentList &TemplateArgs);
void PerformDependentDiagnostics(const DeclContext *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs);
void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
/// When true, access checking violations are treated as SFINAE
/// failures rather than hard errors.
bool AccessCheckingSFINAE;
enum AbstractDiagSelID {
AbstractNone = -1,
AbstractReturnType,
AbstractParamType,
AbstractVariableType,
AbstractFieldType,
AbstractIvarType,
AbstractSynthesizedIvarType,
AbstractArrayType
};
bool isAbstractType(SourceLocation Loc, QualType T);
bool RequireNonAbstractType(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
template <typename... Ts>
bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireNonAbstractType(Loc, T, Diagnoser);
}
void DiagnoseAbstractType(const CXXRecordDecl *RD);
//===--------------------------------------------------------------------===//
// C++ Overloaded Operators [C++ 13.5]
//
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
//===--------------------------------------------------------------------===//
// C++ Templates [C++ 14]
//
void FilterAcceptableTemplateNames(LookupResult &R,
bool AllowFunctionTemplates = true,
bool AllowDependent = true);
bool hasAnyAcceptableTemplateNames(LookupResult &R,
bool AllowFunctionTemplates = true,
bool AllowDependent = true,
bool AllowNonTemplateFunctions = false);
/// Try to interpret the lookup result D as a template-name.
///
/// \param D A declaration found by name lookup.
/// \param AllowFunctionTemplates Whether function templates should be
/// considered valid results.
/// \param AllowDependent Whether unresolved using declarations (that might
/// name templates) should be considered valid results.
NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
bool AllowFunctionTemplates = true,
bool AllowDependent = true);
enum class AssumedTemplateKind {
/// This is not assumed to be a template name.
None,
/// This is assumed to be a template name because lookup found nothing.
FoundNothing,
/// This is assumed to be a template name because lookup found one or more
/// functions (but no function templates).
FoundFunctions,
};
bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
QualType ObjectType, bool EnteringContext,
bool &MemberOfUnknownSpecialization,
SourceLocation TemplateKWLoc = SourceLocation(),
AssumedTemplateKind *ATK = nullptr);
TemplateNameKind isTemplateName(Scope *S,
CXXScopeSpec &SS,
bool hasTemplateKeyword,
const UnqualifiedId &Name,
ParsedType ObjectType,
bool EnteringContext,
TemplateTy &Template,
bool &MemberOfUnknownSpecialization);
/// Try to resolve an undeclared template name as a type template.
///
/// Sets II to the identifier corresponding to the template name, and updates
/// Name to a corresponding (typo-corrected) type template name and TNK to
/// the corresponding kind, if possible.
void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
TemplateNameKind &TNK,
SourceLocation NameLoc,
IdentifierInfo *&II);
bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
SourceLocation NameLoc,
bool Diagnose = true);
/// Determine whether a particular identifier might be the name in a C++1z
/// deduction-guide declaration.
bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
SourceLocation NameLoc,
ParsedTemplateTy *Template = nullptr);
bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
SourceLocation IILoc,
Scope *S,
const CXXScopeSpec *SS,
TemplateTy &SuggestedTemplate,
TemplateNameKind &SuggestedKind);
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
NamedDecl *Instantiation,
bool InstantiatedFromMember,
const NamedDecl *Pattern,
const NamedDecl *PatternDef,
TemplateSpecializationKind TSK,
bool Complain = true);
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
SourceLocation EllipsisLoc,
SourceLocation KeyLoc,
IdentifierInfo *ParamName,
SourceLocation ParamNameLoc,
unsigned Depth, unsigned Position,
SourceLocation EqualLoc,
ParsedType DefaultArg);
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
SourceLocation Loc);
QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
unsigned Depth,
unsigned Position,
SourceLocation EqualLoc,
Expr *DefaultArg);
NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
SourceLocation TmpLoc,
TemplateParameterList *Params,
SourceLocation EllipsisLoc,
IdentifierInfo *ParamName,
SourceLocation ParamNameLoc,
unsigned Depth,
unsigned Position,
SourceLocation EqualLoc,
ParsedTemplateArgument DefaultArg);
TemplateParameterList *
ActOnTemplateParameterList(unsigned Depth,
SourceLocation ExportLoc,
SourceLocation TemplateLoc,
SourceLocation LAngleLoc,
ArrayRef<NamedDecl *> Params,
SourceLocation RAngleLoc,
Expr *RequiresClause);
/// The context in which we are checking a template parameter list.
enum TemplateParamListContext {
TPC_ClassTemplate,
TPC_VarTemplate,
TPC_FunctionTemplate,
TPC_ClassTemplateMember,
TPC_FriendClassTemplate,
TPC_FriendFunctionTemplate,
TPC_FriendFunctionTemplateDefinition,
TPC_TypeAliasTemplate
};
bool CheckTemplateParameterList(TemplateParameterList *NewParams,
TemplateParameterList *OldParams,
TemplateParamListContext TPC,
SkipBodyInfo *SkipBody = nullptr);
TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
SourceLocation DeclStartLoc, SourceLocation DeclLoc,
const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
ArrayRef<TemplateParameterList *> ParamLists,
bool IsFriend, bool &IsMemberSpecialization, bool &Invalid);
DeclResult CheckClassTemplate(
Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
AccessSpecifier AS, SourceLocation ModulePrivateLoc,
SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
TemplateParameterList **OuterTemplateParamLists,
SkipBodyInfo *SkipBody = nullptr);
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
QualType NTTPType,
SourceLocation Loc);
void translateTemplateArguments(const ASTTemplateArgsPtr &In,
TemplateArgumentListInfo &Out);
ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
void NoteAllFoundTemplates(TemplateName Name);
QualType CheckTemplateIdType(TemplateName Template,
SourceLocation TemplateLoc,
TemplateArgumentListInfo &TemplateArgs);
TypeResult
ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
TemplateTy Template, IdentifierInfo *TemplateII,
SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
bool IsCtorOrDtorName = false, bool IsClassName = false);
/// Parsed an elaborated-type-specifier that refers to a template-id,
/// such as \c class T::template apply<U>.
TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
TypeSpecifierType TagSpec,
SourceLocation TagLoc,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
TemplateTy TemplateD,
SourceLocation TemplateLoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgsIn,
SourceLocation RAngleLoc);
DeclResult ActOnVarTemplateSpecialization(
Scope *S, Declarator &D, TypeSourceInfo *DI,
SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
StorageClass SC, bool IsPartialSpecialization);
DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
SourceLocation TemplateLoc,
SourceLocation TemplateNameLoc,
const TemplateArgumentListInfo &TemplateArgs);
ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
const DeclarationNameInfo &NameInfo,
VarTemplateDecl *Template,
SourceLocation TemplateLoc,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult
CheckConceptTemplateId(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
SourceLocation ConceptNameLoc, NamedDecl *FoundDecl,
ConceptDecl *NamedConcept,
const TemplateArgumentListInfo *TemplateArgs);
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
LookupResult &R,
bool RequiresADL,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs);
TemplateNameKind ActOnDependentTemplateName(
Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
TemplateTy &Template, bool AllowInjectedClassName = false);
DeclResult ActOnClassTemplateSpecialization(
Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId,
const ParsedAttributesView &Attr,
MultiTemplateParamsArg TemplateParameterLists,
SkipBodyInfo *SkipBody = nullptr);
bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
TemplateDecl *PrimaryTemplate,
unsigned NumExplicitArgs,
ArrayRef<TemplateArgument> Args);
void CheckTemplatePartialSpecialization(
ClassTemplatePartialSpecializationDecl *Partial);
void CheckTemplatePartialSpecialization(
VarTemplatePartialSpecializationDecl *Partial);
Decl *ActOnTemplateDeclarator(Scope *S,
MultiTemplateParamsArg TemplateParameterLists,
Declarator &D);
bool
CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
TemplateSpecializationKind NewTSK,
NamedDecl *PrevDecl,
TemplateSpecializationKind PrevTSK,
SourceLocation PrevPtOfInstantiation,
bool &SuppressNew);
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
const TemplateArgumentListInfo &ExplicitTemplateArgs,
LookupResult &Previous);
bool CheckFunctionTemplateSpecialization(
FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
LookupResult &Previous, bool QualifiedFriend = false);
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
DeclResult ActOnExplicitInstantiation(
Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
TemplateTy Template, SourceLocation TemplateNameLoc,
SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
SourceLocation TemplateLoc,
unsigned TagSpec, SourceLocation KWLoc,
CXXScopeSpec &SS, IdentifierInfo *Name,
SourceLocation NameLoc,
const ParsedAttributesView &Attr);
DeclResult ActOnExplicitInstantiation(Scope *S,
SourceLocation ExternLoc,
SourceLocation TemplateLoc,
Declarator &D);
TemplateArgumentLoc
SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
SourceLocation TemplateLoc,
SourceLocation RAngleLoc,
Decl *Param,
SmallVectorImpl<TemplateArgument>
&Converted,
bool &HasDefaultArg);
/// Specifies the context in which a particular template
/// argument is being checked.
enum CheckTemplateArgumentKind {
/// The template argument was specified in the code or was
/// instantiated with some deduced template arguments.
CTAK_Specified,
/// The template argument was deduced via template argument
/// deduction.
CTAK_Deduced,
/// The template argument was deduced from an array bound
/// via template argument deduction.
CTAK_DeducedFromArrayBound
};
bool CheckTemplateArgument(NamedDecl *Param,
TemplateArgumentLoc &Arg,
NamedDecl *Template,
SourceLocation TemplateLoc,
SourceLocation RAngleLoc,
unsigned ArgumentPackIndex,
SmallVectorImpl<TemplateArgument> &Converted,
CheckTemplateArgumentKind CTAK = CTAK_Specified);
/// Check that the given template arguments can be be provided to
/// the given template, converting the arguments along the way.
///
/// \param Template The template to which the template arguments are being
/// provided.
///
/// \param TemplateLoc The location of the template name in the source.
///
/// \param TemplateArgs The list of template arguments. If the template is
/// a template template parameter, this function may extend the set of
/// template arguments to also include substituted, defaulted template
/// arguments.
///
/// \param PartialTemplateArgs True if the list of template arguments is
/// intentionally partial, e.g., because we're checking just the initial
/// set of template arguments.
///
/// \param Converted Will receive the converted, canonicalized template
/// arguments.
///
/// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
/// contain the converted forms of the template arguments as written.
/// Otherwise, \p TemplateArgs will not be modified.
///
/// \param ConstraintsNotSatisfied If provided, and an error occured, will
/// receive true if the cause for the error is the associated constraints of
/// the template not being satisfied by the template arguments.
///
/// \returns true if an error occurred, false otherwise.
bool CheckTemplateArgumentList(TemplateDecl *Template,
SourceLocation TemplateLoc,
TemplateArgumentListInfo &TemplateArgs,
bool PartialTemplateArgs,
SmallVectorImpl<TemplateArgument> &Converted,
bool UpdateArgsWithConversions = true,
bool *ConstraintsNotSatisfied = nullptr);
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
TemplateArgumentLoc &Arg,
SmallVectorImpl<TemplateArgument> &Converted);
bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
TypeSourceInfo *Arg);
ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
QualType InstantiatedParamType, Expr *Arg,
TemplateArgument &Converted,
CheckTemplateArgumentKind CTAK = CTAK_Specified);
bool CheckTemplateTemplateArgument(TemplateParameterList *Params,
TemplateArgumentLoc &Arg);
ExprResult
BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
QualType ParamType,
SourceLocation Loc);
ExprResult
BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
SourceLocation Loc);
/// Enumeration describing how template parameter lists are compared
/// for equality.
enum TemplateParameterListEqualKind {
/// We are matching the template parameter lists of two templates
/// that might be redeclarations.
///
/// \code
/// template<typename T> struct X;
/// template<typename T> struct X;
/// \endcode
TPL_TemplateMatch,
/// We are matching the template parameter lists of two template
/// template parameters as part of matching the template parameter lists
/// of two templates that might be redeclarations.
///
/// \code
/// template<template<int I> class TT> struct X;
/// template<template<int Value> class Other> struct X;
/// \endcode
TPL_TemplateTemplateParmMatch,
/// We are matching the template parameter lists of a template
/// template argument against the template parameter lists of a template
/// template parameter.
///
/// \code
/// template<template<int Value> class Metafun> struct X;
/// template<int Value> struct integer_c;
/// X<integer_c> xic;
/// \endcode
TPL_TemplateTemplateArgumentMatch
};
bool TemplateParameterListsAreEqual(TemplateParameterList *New,
TemplateParameterList *Old,
bool Complain,
TemplateParameterListEqualKind Kind,
SourceLocation TemplateArgLoc
= SourceLocation());
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
/// Called when the parser has parsed a C++ typename
/// specifier, e.g., "typename T::type".
///
/// \param S The scope in which this typename type occurs.
/// \param TypenameLoc the location of the 'typename' keyword
/// \param SS the nested-name-specifier following the typename (e.g., 'T::').
/// \param II the identifier we're retrieving (e.g., 'type' in the example).
/// \param IdLoc the location of the identifier.
TypeResult
ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
const CXXScopeSpec &SS, const IdentifierInfo &II,
SourceLocation IdLoc);
/// Called when the parser has parsed a C++ typename
/// specifier that ends in a template-id, e.g.,
/// "typename MetaFun::template apply<T1, T2>".
///
/// \param S The scope in which this typename type occurs.
/// \param TypenameLoc the location of the 'typename' keyword
/// \param SS the nested-name-specifier following the typename (e.g., 'T::').
/// \param TemplateLoc the location of the 'template' keyword, if any.
/// \param TemplateName The template name.
/// \param TemplateII The identifier used to name the template.
/// \param TemplateIILoc The location of the template name.
/// \param LAngleLoc The location of the opening angle bracket ('<').
/// \param TemplateArgs The template arguments.
/// \param RAngleLoc The location of the closing angle bracket ('>').
TypeResult
ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
const CXXScopeSpec &SS,
SourceLocation TemplateLoc,
TemplateTy TemplateName,
IdentifierInfo *TemplateII,
SourceLocation TemplateIILoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc);
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
SourceLocation KeywordLoc,
NestedNameSpecifierLoc QualifierLoc,
const IdentifierInfo &II,
SourceLocation IILoc);
TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
SourceLocation Loc,
DeclarationName Name);
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
ExprResult RebuildExprInCurrentInstantiation(Expr *E);
bool RebuildTemplateParamsInCurrentInstantiation(
TemplateParameterList *Params);
std::string
getTemplateArgumentBindingsText(const TemplateParameterList *Params,
const TemplateArgumentList &Args);
std::string
getTemplateArgumentBindingsText(const TemplateParameterList *Params,
const TemplateArgument *Args,
unsigned NumArgs);
// Concepts
Decl *ActOnConceptDefinition(
Scope *S, MultiTemplateParamsArg TemplateParameterLists,
IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr);
//===--------------------------------------------------------------------===//
// C++ Variadic Templates (C++0x [temp.variadic])
//===--------------------------------------------------------------------===//
/// Determine whether an unexpanded parameter pack might be permitted in this
/// location. Useful for error recovery.
bool isUnexpandedParameterPackPermitted();
/// The context in which an unexpanded parameter pack is
/// being diagnosed.
///
/// Note that the values of this enumeration line up with the first
/// argument to the \c err_unexpanded_parameter_pack diagnostic.
enum UnexpandedParameterPackContext {
/// An arbitrary expression.
UPPC_Expression = 0,
/// The base type of a class type.
UPPC_BaseType,
/// The type of an arbitrary declaration.
UPPC_DeclarationType,
/// The type of a data member.
UPPC_DataMemberType,
/// The size of a bit-field.
UPPC_BitFieldWidth,
/// The expression in a static assertion.
UPPC_StaticAssertExpression,
/// The fixed underlying type of an enumeration.
UPPC_FixedUnderlyingType,
/// The enumerator value.
UPPC_EnumeratorValue,
/// A using declaration.
UPPC_UsingDeclaration,
/// A friend declaration.
UPPC_FriendDeclaration,
/// A declaration qualifier.
UPPC_DeclarationQualifier,
/// An initializer.
UPPC_Initializer,
/// A default argument.
UPPC_DefaultArgument,
/// The type of a non-type template parameter.
UPPC_NonTypeTemplateParameterType,
/// The type of an exception.
UPPC_ExceptionType,
/// Partial specialization.
UPPC_PartialSpecialization,
/// Microsoft __if_exists.
UPPC_IfExists,
/// Microsoft __if_not_exists.
UPPC_IfNotExists,
/// Lambda expression.
UPPC_Lambda,
/// Block expression,
UPPC_Block
};
/// Diagnose unexpanded parameter packs.
///
/// \param Loc The location at which we should emit the diagnostic.
///
/// \param UPPC The context in which we are diagnosing unexpanded
/// parameter packs.
///
/// \param Unexpanded the set of unexpanded parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
UnexpandedParameterPackContext UPPC,
ArrayRef<UnexpandedParameterPack> Unexpanded);
/// If the given type contains an unexpanded parameter pack,
/// diagnose the error.
///
/// \param Loc The source location where a diagnostc should be emitted.
///
/// \param T The type that is being checked for unexpanded parameter
/// packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
UnexpandedParameterPackContext UPPC);
/// If the given expression contains an unexpanded parameter
/// pack, diagnose the error.
///
/// \param E The expression that is being checked for unexpanded
/// parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(Expr *E,
UnexpandedParameterPackContext UPPC = UPPC_Expression);
/// If the given nested-name-specifier contains an unexpanded
/// parameter pack, diagnose the error.
///
/// \param SS The nested-name-specifier that is being checked for
/// unexpanded parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
UnexpandedParameterPackContext UPPC);
/// If the given name contains an unexpanded parameter pack,
/// diagnose the error.
///
/// \param NameInfo The name (with source location information) that
/// is being checked for unexpanded parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
UnexpandedParameterPackContext UPPC);
/// If the given template name contains an unexpanded parameter pack,
/// diagnose the error.
///
/// \param Loc The location of the template name.
///
/// \param Template The template name that is being checked for unexpanded
/// parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
TemplateName Template,
UnexpandedParameterPackContext UPPC);
/// If the given template argument contains an unexpanded parameter
/// pack, diagnose the error.
///
/// \param Arg The template argument that is being checked for unexpanded
/// parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
UnexpandedParameterPackContext UPPC);
/// Collect the set of unexpanded parameter packs within the given
/// template argument.
///
/// \param Arg The template argument that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(TemplateArgument Arg,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Collect the set of unexpanded parameter packs within the given
/// template argument.
///
/// \param Arg The template argument that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Collect the set of unexpanded parameter packs within the given
/// type.
///
/// \param T The type that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(QualType T,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Collect the set of unexpanded parameter packs within the given
/// type.
///
/// \param TL The type that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(TypeLoc TL,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Collect the set of unexpanded parameter packs within the given
/// nested-name-specifier.
///
/// \param NNS The nested-name-specifier that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Collect the set of unexpanded parameter packs within the given
/// name.
///
/// \param NameInfo The name that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Invoked when parsing a template argument followed by an
/// ellipsis, which creates a pack expansion.
///
/// \param Arg The template argument preceding the ellipsis, which
/// may already be invalid.
///
/// \param EllipsisLoc The location of the ellipsis.
ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
SourceLocation EllipsisLoc);
/// Invoked when parsing a type followed by an ellipsis, which
/// creates a pack expansion.
///
/// \param Type The type preceding the ellipsis, which will become
/// the pattern of the pack expansion.
///
/// \param EllipsisLoc The location of the ellipsis.
TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
/// Construct a pack expansion type from the pattern of the pack
/// expansion.
TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions);
/// Construct a pack expansion type from the pattern of the pack
/// expansion.
QualType CheckPackExpansion(QualType Pattern,
SourceRange PatternRange,
SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions);
/// Invoked when parsing an expression followed by an ellipsis, which
/// creates a pack expansion.
///
/// \param Pattern The expression preceding the ellipsis, which will become
/// the pattern of the pack expansion.
///
/// \param EllipsisLoc The location of the ellipsis.
ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
/// Invoked when parsing an expression followed by an ellipsis, which
/// creates a pack expansion.
///
/// \param Pattern The expression preceding the ellipsis, which will become
/// the pattern of the pack expansion.
///
/// \param EllipsisLoc The location of the ellipsis.
ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions);
/// Determine whether we could expand a pack expansion with the
/// given set of parameter packs into separate arguments by repeatedly
/// transforming the pattern.
///
/// \param EllipsisLoc The location of the ellipsis that identifies the
/// pack expansion.
///
/// \param PatternRange The source range that covers the entire pattern of
/// the pack expansion.
///
/// \param Unexpanded The set of unexpanded parameter packs within the
/// pattern.
///
/// \param ShouldExpand Will be set to \c true if the transformer should
/// expand the corresponding pack expansions into separate arguments. When
/// set, \c NumExpansions must also be set.
///
/// \param RetainExpansion Whether the caller should add an unexpanded
/// pack expansion after all of the expanded arguments. This is used
/// when extending explicitly-specified template argument packs per
/// C++0x [temp.arg.explicit]p9.
///
/// \param NumExpansions The number of separate arguments that will be in
/// the expanded form of the corresponding pack expansion. This is both an
/// input and an output parameter, which can be set by the caller if the
/// number of expansions is known a priori (e.g., due to a prior substitution)
/// and will be set by the callee when the number of expansions is known.
/// The callee must set this value when \c ShouldExpand is \c true; it may
/// set this value in other cases.
///
/// \returns true if an error occurred (e.g., because the parameter packs
/// are to be instantiated with arguments of different lengths), false
/// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
/// must be set.
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
SourceRange PatternRange,
ArrayRef<UnexpandedParameterPack> Unexpanded,
const MultiLevelTemplateArgumentList &TemplateArgs,
bool &ShouldExpand,
bool &RetainExpansion,
Optional<unsigned> &NumExpansions);
/// Determine the number of arguments in the given pack expansion
/// type.
///
/// This routine assumes that the number of arguments in the expansion is
/// consistent across all of the unexpanded parameter packs in its pattern.
///
/// Returns an empty Optional if the type can't be expanded.
Optional<unsigned> getNumArgumentsInExpansion(QualType T,
const MultiLevelTemplateArgumentList &TemplateArgs);
/// Determine whether the given declarator contains any unexpanded
/// parameter packs.
///
/// This routine is used by the parser to disambiguate function declarators
/// with an ellipsis prior to the ')', e.g.,
///
/// \code
/// void f(T...);
/// \endcode
///
/// To determine whether we have an (unnamed) function parameter pack or
/// a variadic function.
///
/// \returns true if the declarator contains any unexpanded parameter packs,
/// false otherwise.
bool containsUnexpandedParameterPacks(Declarator &D);
/// Returns the pattern of the pack expansion for a template argument.
///
/// \param OrigLoc The template argument to expand.
///
/// \param Ellipsis Will be set to the location of the ellipsis.
///
/// \param NumExpansions Will be set to the number of expansions that will
/// be generated from this pack expansion, if known a priori.
TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
TemplateArgumentLoc OrigLoc,
SourceLocation &Ellipsis,
Optional<unsigned> &NumExpansions) const;
/// Given a template argument that contains an unexpanded parameter pack, but
/// which has already been substituted, attempt to determine the number of
/// elements that will be produced once this argument is fully-expanded.
///
/// This is intended for use when transforming 'sizeof...(Arg)' in order to
/// avoid actually expanding the pack where possible.
Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
//===--------------------------------------------------------------------===//
// C++ Template Argument Deduction (C++ [temp.deduct])
//===--------------------------------------------------------------------===//
/// Adjust the type \p ArgFunctionType to match the calling convention,
/// noreturn, and optionally the exception specification of \p FunctionType.
/// Deduction often wants to ignore these properties when matching function
/// types.
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
bool AdjustExceptionSpec = false);
/// Describes the result of template argument deduction.
///
/// The TemplateDeductionResult enumeration describes the result of
/// template argument deduction, as returned from
/// DeduceTemplateArguments(). The separate TemplateDeductionInfo
/// structure provides additional information about the results of
/// template argument deduction, e.g., the deduced template argument
/// list (if successful) or the specific template parameters or
/// deduced arguments that were involved in the failure.
enum TemplateDeductionResult {
/// Template argument deduction was successful.
TDK_Success = 0,
/// The declaration was invalid; do nothing.
TDK_Invalid,
/// Template argument deduction exceeded the maximum template
/// instantiation depth (which has already been diagnosed).
TDK_InstantiationDepth,
/// Template argument deduction did not deduce a value
/// for every template parameter.
TDK_Incomplete,
/// Template argument deduction did not deduce a value for every
/// expansion of an expanded template parameter pack.
TDK_IncompletePack,
/// Template argument deduction produced inconsistent
/// deduced values for the given template parameter.
TDK_Inconsistent,
/// Template argument deduction failed due to inconsistent
/// cv-qualifiers on a template parameter type that would
/// otherwise be deduced, e.g., we tried to deduce T in "const T"
/// but were given a non-const "X".
TDK_Underqualified,
/// Substitution of the deduced template argument values
/// resulted in an error.
TDK_SubstitutionFailure,
/// After substituting deduced template arguments, a dependent
/// parameter type did not match the corresponding argument.
TDK_DeducedMismatch,
/// After substituting deduced template arguments, an element of
/// a dependent parameter type did not match the corresponding element
/// of the corresponding argument (when deducing from an initializer list).
TDK_DeducedMismatchNested,
/// A non-depnedent component of the parameter did not match the
/// corresponding component of the argument.
TDK_NonDeducedMismatch,
/// When performing template argument deduction for a function
/// template, there were too many call arguments.
TDK_TooManyArguments,
/// When performing template argument deduction for a function
/// template, there were too few call arguments.
TDK_TooFewArguments,
/// The explicitly-specified template arguments were not valid
/// template arguments for the given template.
TDK_InvalidExplicitArguments,
/// Checking non-dependent argument conversions failed.
TDK_NonDependentConversionFailure,
/// The deduced arguments did not satisfy the constraints associated
/// with the template.
TDK_ConstraintsNotSatisfied,
/// Deduction failed; that's all we know.
TDK_MiscellaneousDeductionFailure,
/// CUDA Target attributes do not match.
TDK_CUDATargetMismatch
};
TemplateDeductionResult
DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
const TemplateArgumentList &TemplateArgs,
sema::TemplateDeductionInfo &Info);
TemplateDeductionResult
DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
const TemplateArgumentList &TemplateArgs,
sema::TemplateDeductionInfo &Info);
TemplateDeductionResult SubstituteExplicitTemplateArguments(
FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo &ExplicitTemplateArgs,
SmallVectorImpl<DeducedTemplateArgument> &Deduced,
SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
sema::TemplateDeductionInfo &Info);
/// brief A function argument from which we performed template argument
// deduction for a call.
struct OriginalCallArg {
OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
unsigned ArgIdx, QualType OriginalArgType)
: OriginalParamType(OriginalParamType),
DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
OriginalArgType(OriginalArgType) {}
QualType OriginalParamType;
bool DecomposedParam;
unsigned ArgIdx;
QualType OriginalArgType;
};
TemplateDeductionResult FinishTemplateArgumentDeduction(
FunctionTemplateDecl *FunctionTemplate,
SmallVectorImpl<DeducedTemplateArgument> &Deduced,
unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
bool PartialOverloading = false,
llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
TemplateDeductionResult DeduceTemplateArguments(
FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
bool PartialOverloading,
llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo *ExplicitTemplateArgs,
QualType ArgFunctionType,
FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
bool IsAddressOfFunction = false);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
QualType ToType,
CXXConversionDecl *&Specialization,
sema::TemplateDeductionInfo &Info);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo *ExplicitTemplateArgs,
FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
bool IsAddressOfFunction = false);
/// Substitute Replacement for \p auto in \p TypeWithAuto
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
/// Substitute Replacement for auto in TypeWithAuto
TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
QualType Replacement);
/// Completely replace the \c auto in \p TypeWithAuto by
/// \p Replacement. This does not retain any \c auto type sugar.
QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
/// Result type of DeduceAutoType.
enum DeduceAutoResult {
DAR_Succeeded,
DAR_Failed,
DAR_FailedAlreadyDiagnosed
};
DeduceAutoResult
DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
Optional<unsigned> DependentDeductionDepth = None);
DeduceAutoResult
DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
Optional<unsigned> DependentDeductionDepth = None);
void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
bool Diagnose = true);
/// Declare implicit deduction guides for a class template if we've
/// not already done so.
void DeclareImplicitDeductionGuides(TemplateDecl *Template,
SourceLocation Loc);
QualType DeduceTemplateSpecializationFromInitializer(
TypeSourceInfo *TInfo, const InitializedEntity &Entity,
const InitializationKind &Kind, MultiExprArg Init);
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
QualType Type, TypeSourceInfo *TSI,
SourceRange Range, bool DirectInit,
Expr *Init);
TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
SourceLocation ReturnLoc,
Expr *&RetExpr, AutoType *AT);
FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
FunctionTemplateDecl *FT2,
SourceLocation Loc,
TemplatePartialOrderingContext TPOC,
unsigned NumCallArguments1,
unsigned NumCallArguments2);
UnresolvedSetIterator
getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
TemplateSpecCandidateSet &FailedCandidates,
SourceLocation Loc,
const PartialDiagnostic &NoneDiag,
const PartialDiagnostic &AmbigDiag,
const PartialDiagnostic &CandidateDiag,
bool Complain = true, QualType TargetType = QualType());
ClassTemplatePartialSpecializationDecl *
getMoreSpecializedPartialSpecialization(
ClassTemplatePartialSpecializationDecl *PS1,
ClassTemplatePartialSpecializationDecl *PS2,
SourceLocation Loc);
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
sema::TemplateDeductionInfo &Info);
VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
VarTemplatePartialSpecializationDecl *PS1,
VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
sema::TemplateDeductionInfo &Info);
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc);
void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
bool OnlyDeduced,
unsigned Depth,
llvm::SmallBitVector &Used);
void MarkDeducedTemplateParameters(
const FunctionTemplateDecl *FunctionTemplate,
llvm::SmallBitVector &Deduced) {
return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
}
static void MarkDeducedTemplateParameters(ASTContext &Ctx,
const FunctionTemplateDecl *FunctionTemplate,
llvm::SmallBitVector &Deduced);
//===--------------------------------------------------------------------===//
// C++ Template Instantiation
//
MultiLevelTemplateArgumentList
getTemplateInstantiationArgs(NamedDecl *D,
const TemplateArgumentList *Innermost = nullptr,
bool RelativeToPrimary = false,
const FunctionDecl *Pattern = nullptr);
/// A context in which code is being synthesized (where a source location
/// alone is not sufficient to identify the context). This covers template
/// instantiation and various forms of implicitly-generated functions.
struct CodeSynthesisContext {
/// The kind of template instantiation we are performing
enum SynthesisKind {
/// We are instantiating a template declaration. The entity is
/// the declaration we're instantiating (e.g., a CXXRecordDecl).
TemplateInstantiation,
/// We are instantiating a default argument for a template
/// parameter. The Entity is the template parameter whose argument is
/// being instantiated, the Template is the template, and the
/// TemplateArgs/NumTemplateArguments provide the template arguments as
/// specified.
DefaultTemplateArgumentInstantiation,
/// We are instantiating a default argument for a function.
/// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
/// provides the template arguments as specified.
DefaultFunctionArgumentInstantiation,
/// We are substituting explicit template arguments provided for
/// a function template. The entity is a FunctionTemplateDecl.
ExplicitTemplateArgumentSubstitution,
/// We are substituting template argument determined as part of
/// template argument deduction for either a class template
/// partial specialization or a function template. The
/// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
/// a TemplateDecl.
DeducedTemplateArgumentSubstitution,
/// We are substituting prior template arguments into a new
/// template parameter. The template parameter itself is either a
/// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
PriorTemplateArgumentSubstitution,
/// We are checking the validity of a default template argument that
/// has been used when naming a template-id.
DefaultTemplateArgumentChecking,
/// We are computing the exception specification for a defaulted special
/// member function.
ExceptionSpecEvaluation,
/// We are instantiating the exception specification for a function
/// template which was deferred until it was needed.
ExceptionSpecInstantiation,
/// We are declaring an implicit special member function.
DeclaringSpecialMember,
/// We are declaring an implicit 'operator==' for a defaulted
/// 'operator<=>'.
DeclaringImplicitEqualityComparison,
/// We are defining a synthesized function (such as a defaulted special
/// member).
DefiningSynthesizedFunction,
// We are checking the constraints associated with a constrained entity or
// the constraint expression of a concept. This includes the checks that
// atomic constraints have the type 'bool' and that they can be constant
// evaluated.
ConstraintsCheck,
// We are substituting template arguments into a constraint expression.
ConstraintSubstitution,
/// We are rewriting a comparison operator in terms of an operator<=>.
RewritingOperatorAsSpaceship,
/// Added for Template instantiation observation.
/// Memoization means we are _not_ instantiating a template because
/// it is already instantiated (but we entered a context where we
/// would have had to if it was not already instantiated).
Memoization
} Kind;
/// Was the enclosing context a non-instantiation SFINAE context?
bool SavedInNonInstantiationSFINAEContext;
/// The point of instantiation or synthesis within the source code.
SourceLocation PointOfInstantiation;
/// The entity that is being synthesized.
Decl *Entity;
/// The template (or partial specialization) in which we are
/// performing the instantiation, for substitutions of prior template
/// arguments.
NamedDecl *Template;
/// The list of template arguments we are substituting, if they
/// are not part of the entity.
const TemplateArgument *TemplateArgs;
// FIXME: Wrap this union around more members, or perhaps store the
// kind-specific members in the RAII object owning the context.
union {
/// The number of template arguments in TemplateArgs.
unsigned NumTemplateArgs;
/// The special member being declared or defined.
CXXSpecialMember SpecialMember;
};
ArrayRef<TemplateArgument> template_arguments() const {
assert(Kind != DeclaringSpecialMember);
return {TemplateArgs, NumTemplateArgs};
}
/// The template deduction info object associated with the
/// substitution or checking of explicit or deduced template arguments.
sema::TemplateDeductionInfo *DeductionInfo;
/// The source range that covers the construct that cause
/// the instantiation, e.g., the template-id that causes a class
/// template instantiation.
SourceRange InstantiationRange;
CodeSynthesisContext()
: Kind(TemplateInstantiation),
SavedInNonInstantiationSFINAEContext(false), Entity(nullptr),
Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0),
DeductionInfo(nullptr) {}
/// Determines whether this template is an actual instantiation
/// that should be counted toward the maximum instantiation depth.
bool isInstantiationRecord() const;
};
/// List of active code synthesis contexts.
///
/// This vector is treated as a stack. As synthesis of one entity requires
/// synthesis of another, additional contexts are pushed onto the stack.
SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
/// Specializations whose definitions are currently being instantiated.
llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
/// Non-dependent types used in templates that have already been instantiated
/// by some template instantiation.
llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
/// Extra modules inspected when performing a lookup during a template
/// instantiation. Computed lazily.
SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
/// Cache of additional modules that should be used for name lookup
/// within the current template instantiation. Computed lazily; use
/// getLookupModules() to get a complete set.
llvm::DenseSet<Module*> LookupModulesCache;
/// Get the set of additional modules that should be checked during
/// name lookup. A module and its imports become visible when instanting a
/// template defined within it.
llvm::DenseSet<Module*> &getLookupModules();
/// Map from the most recent declaration of a namespace to the most
/// recent visible declaration of that namespace.
llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
/// Whether we are in a SFINAE context that is not associated with
/// template instantiation.
///
/// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
/// of a template instantiation or template argument deduction.
bool InNonInstantiationSFINAEContext;
/// The number of \p CodeSynthesisContexts that are not template
/// instantiations and, therefore, should not be counted as part of the
/// instantiation depth.
///
/// When the instantiation depth reaches the user-configurable limit
/// \p LangOptions::InstantiationDepth we will abort instantiation.
// FIXME: Should we have a similar limit for other forms of synthesis?
unsigned NonInstantiationEntries;
/// The depth of the context stack at the point when the most recent
/// error or warning was produced.
///
/// This value is used to suppress printing of redundant context stacks
/// when there are multiple errors or warnings in the same instantiation.
// FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
unsigned LastEmittedCodeSynthesisContextDepth = 0;
/// The template instantiation callbacks to trace or track
/// instantiations (objects can be chained).
///
/// This callbacks is used to print, trace or track template
/// instantiations as they are being constructed.
std::vector<std::unique_ptr<TemplateInstantiationCallback>>
TemplateInstCallbacks;
/// The current index into pack expansion arguments that will be
/// used for substitution of parameter packs.
///
/// The pack expansion index will be -1 to indicate that parameter packs
/// should be instantiated as themselves. Otherwise, the index specifies
/// which argument within the parameter pack will be used for substitution.
int ArgumentPackSubstitutionIndex;
/// RAII object used to change the argument pack substitution index
/// within a \c Sema object.
///
/// See \c ArgumentPackSubstitutionIndex for more information.
class ArgumentPackSubstitutionIndexRAII {
Sema &Self;
int OldSubstitutionIndex;
public:
ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
: Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
}
~ArgumentPackSubstitutionIndexRAII() {
Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
}
};
friend class ArgumentPackSubstitutionRAII;
/// For each declaration that involved template argument deduction, the
/// set of diagnostics that were suppressed during that template argument
/// deduction.
///
/// FIXME: Serialize this structure to the AST file.
typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
SuppressedDiagnosticsMap;
SuppressedDiagnosticsMap SuppressedDiagnostics;
/// A stack object to be created when performing template
/// instantiation.
///
/// Construction of an object of type \c InstantiatingTemplate
/// pushes the current instantiation onto the stack of active
/// instantiations. If the size of this stack exceeds the maximum
/// number of recursive template instantiations, construction
/// produces an error and evaluates true.
///
/// Destruction of this object will pop the named instantiation off
/// the stack.
struct InstantiatingTemplate {
/// Note that we are instantiating a class template,
/// function template, variable template, alias template,
/// or a member thereof.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Decl *Entity,
SourceRange InstantiationRange = SourceRange());
struct ExceptionSpecification {};
/// Note that we are instantiating an exception specification
/// of a function template.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
FunctionDecl *Entity, ExceptionSpecification,
SourceRange InstantiationRange = SourceRange());
/// Note that we are instantiating a default argument in a
/// template-id.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
TemplateParameter Param, TemplateDecl *Template,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange = SourceRange());
/// Note that we are substituting either explicitly-specified or
/// deduced template arguments during function template argument deduction.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
FunctionTemplateDecl *FunctionTemplate,
ArrayRef<TemplateArgument> TemplateArgs,
CodeSynthesisContext::SynthesisKind Kind,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// Note that we are instantiating as part of template
/// argument deduction for a class template declaration.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
TemplateDecl *Template,
ArrayRef<TemplateArgument> TemplateArgs,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// Note that we are instantiating as part of template
/// argument deduction for a class template partial
/// specialization.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
ClassTemplatePartialSpecializationDecl *PartialSpec,
ArrayRef<TemplateArgument> TemplateArgs,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// Note that we are instantiating as part of template
/// argument deduction for a variable template partial
/// specialization.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
VarTemplatePartialSpecializationDecl *PartialSpec,
ArrayRef<TemplateArgument> TemplateArgs,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// Note that we are instantiating a default argument for a function
/// parameter.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
ParmVarDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange = SourceRange());
/// Note that we are substituting prior template arguments into a
/// non-type parameter.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
NamedDecl *Template,
NonTypeTemplateParmDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
/// Note that we are substituting prior template arguments into a
/// template template parameter.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
NamedDecl *Template,
TemplateTemplateParmDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
/// Note that we are checking the default template argument
/// against the template parameter for a given template-id.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
TemplateDecl *Template,
NamedDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
struct ConstraintsCheck {};
/// \brief Note that we are checking the constraints associated with some
/// constrained entity (a concept declaration or a template with associated
/// constraints).
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
ConstraintsCheck, NamedDecl *Template,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
struct ConstraintSubstitution {};
/// \brief Note that we are checking a constraint expression associated
/// with a template declaration or as part of the satisfaction check of a
/// concept.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
ConstraintSubstitution, NamedDecl *Template,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange);
/// Note that we have finished instantiating this template.
void Clear();
~InstantiatingTemplate() { Clear(); }
/// Determines whether we have exceeded the maximum
/// recursive template instantiations.
bool isInvalid() const { return Invalid; }
/// Determine whether we are already instantiating this
/// specialization in some surrounding active instantiation.
bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
private:
Sema &SemaRef;
bool Invalid;
bool AlreadyInstantiating;
bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
SourceRange InstantiationRange);
InstantiatingTemplate(
Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
Decl *Entity, NamedDecl *Template = nullptr,
ArrayRef<TemplateArgument> TemplateArgs = None,
sema::TemplateDeductionInfo *DeductionInfo = nullptr);
InstantiatingTemplate(const InstantiatingTemplate&) = delete;
InstantiatingTemplate&
operator=(const InstantiatingTemplate&) = delete;
};
void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
void popCodeSynthesisContext();
/// Determine whether we are currently performing template instantiation.
bool inTemplateInstantiation() const {
return CodeSynthesisContexts.size() > NonInstantiationEntries;
}
void PrintContextStack() {
if (!CodeSynthesisContexts.empty() &&
CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
PrintInstantiationStack();
LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
}
if (PragmaAttributeCurrentTargetDecl)
PrintPragmaAttributeInstantiationPoint();
}
void PrintInstantiationStack();
void PrintPragmaAttributeInstantiationPoint();
/// Determines whether we are currently in a context where
/// template argument substitution failures are not considered
/// errors.
///
/// \returns An empty \c Optional if we're not in a SFINAE context.
/// Otherwise, contains a pointer that, if non-NULL, contains the nearest
/// template-deduction context object, which can be used to capture
/// diagnostics that will be suppressed.
Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
/// Determines whether we are currently in a context that
/// is not evaluated as per C++ [expr] p5.
bool isUnevaluatedContext() const {
assert(!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context");
return ExprEvalContexts.back().isUnevaluated();
}
/// RAII class used to determine whether SFINAE has
/// trapped any errors that occur during template argument
/// deduction.
class SFINAETrap {
Sema &SemaRef;
unsigned PrevSFINAEErrors;
bool PrevInNonInstantiationSFINAEContext;
bool PrevAccessCheckingSFINAE;
bool PrevLastDiagnosticIgnored;
public:
explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
: SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
PrevInNonInstantiationSFINAEContext(
SemaRef.InNonInstantiationSFINAEContext),
PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
PrevLastDiagnosticIgnored(
SemaRef.getDiagnostics().isLastDiagnosticIgnored())
{
if (!SemaRef.isSFINAEContext())
SemaRef.InNonInstantiationSFINAEContext = true;
SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
}
~SFINAETrap() {
SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
SemaRef.InNonInstantiationSFINAEContext
= PrevInNonInstantiationSFINAEContext;
SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
SemaRef.getDiagnostics().setLastDiagnosticIgnored(
PrevLastDiagnosticIgnored);
}
/// Determine whether any SFINAE errors have been trapped.
bool hasErrorOccurred() const {
return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
}
};
/// RAII class used to indicate that we are performing provisional
/// semantic analysis to determine the validity of a construct, so
/// typo-correction and diagnostics in the immediate context (not within
/// implicitly-instantiated templates) should be suppressed.
class TentativeAnalysisScope {
Sema &SemaRef;
// FIXME: Using a SFINAETrap for this is a hack.
SFINAETrap Trap;
bool PrevDisableTypoCorrection;
public:
explicit TentativeAnalysisScope(Sema &SemaRef)
: SemaRef(SemaRef), Trap(SemaRef, true),
PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
SemaRef.DisableTypoCorrection = true;
}
~TentativeAnalysisScope() {
SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
}
};
/// The current instantiation scope used to store local
/// variables.
LocalInstantiationScope *CurrentInstantiationScope;
/// Tracks whether we are in a context where typo correction is
/// disabled.
bool DisableTypoCorrection;
/// The number of typos corrected by CorrectTypo.
unsigned TyposCorrected;
typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
/// A cache containing identifiers for which typo correction failed and
/// their locations, so that repeated attempts to correct an identifier in a
/// given location are ignored if typo correction already failed for it.
IdentifierSourceLocations TypoCorrectionFailures;
/// Worker object for performing CFG-based warnings.
sema::AnalysisBasedWarnings AnalysisWarnings;
threadSafety::BeforeSet *ThreadSafetyDeclCache;
/// An entity for which implicit template instantiation is required.
///
/// The source location associated with the declaration is the first place in
/// the source code where the declaration was "used". It is not necessarily
/// the point of instantiation (which will be either before or after the
/// namespace-scope declaration that triggered this implicit instantiation),
/// However, it is the location that diagnostics should generally refer to,
/// because users will need to know what code triggered the instantiation.
typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
/// The queue of implicit template instantiations that are required
/// but have not yet been performed.
std::deque<PendingImplicitInstantiation> PendingInstantiations;
/// Queue of implicit template instantiations that cannot be performed
/// eagerly.
SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
class GlobalEagerInstantiationScope {
public:
GlobalEagerInstantiationScope(Sema &S, bool Enabled)
: S(S), Enabled(Enabled) {
if (!Enabled) return;
SavedPendingInstantiations.swap(S.PendingInstantiations);
SavedVTableUses.swap(S.VTableUses);
}
void perform() {
if (Enabled) {
S.DefineUsedVTables();
S.PerformPendingInstantiations();
}
}
~GlobalEagerInstantiationScope() {
if (!Enabled) return;
// Restore the set of pending vtables.
assert(S.VTableUses.empty() &&
"VTableUses should be empty before it is discarded.");
S.VTableUses.swap(SavedVTableUses);
// Restore the set of pending implicit instantiations.
assert(S.PendingInstantiations.empty() &&
"PendingInstantiations should be empty before it is discarded.");
S.PendingInstantiations.swap(SavedPendingInstantiations);
}
private:
Sema &S;
SmallVector<VTableUse, 16> SavedVTableUses;
std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
bool Enabled;
};
/// The queue of implicit template instantiations that are required
/// and must be performed within the current local scope.
///
/// This queue is only used for member functions of local classes in
/// templates, which must be instantiated in the same scope as their
/// enclosing function, so that they can reference function-local
/// types, static variables, enumerators, etc.
std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
class LocalEagerInstantiationScope {
public:
LocalEagerInstantiationScope(Sema &S) : S(S) {
SavedPendingLocalImplicitInstantiations.swap(
S.PendingLocalImplicitInstantiations);
}
void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
~LocalEagerInstantiationScope() {
assert(S.PendingLocalImplicitInstantiations.empty() &&
"there shouldn't be any pending local implicit instantiations");
SavedPendingLocalImplicitInstantiations.swap(
S.PendingLocalImplicitInstantiations);
}
private:
Sema &S;
std::deque<PendingImplicitInstantiation>
SavedPendingLocalImplicitInstantiations;
};
/// A helper class for building up ExtParameterInfos.
class ExtParameterInfoBuilder {
SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
bool HasInteresting = false;
public:
/// Set the ExtParameterInfo for the parameter at the given index,
///
void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
assert(Infos.size() <= index);
Infos.resize(index);
Infos.push_back(info);
if (!HasInteresting)
HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
}
/// Return a pointer (suitable for setting in an ExtProtoInfo) to the
/// ExtParameterInfo array we've built up.
const FunctionProtoType::ExtParameterInfo *
getPointerOrNull(unsigned numParams) {
if (!HasInteresting) return nullptr;
Infos.resize(numParams);
return Infos.data();
}
};
void PerformPendingInstantiations(bool LocalOnly = false);
TypeSourceInfo *SubstType(TypeSourceInfo *T,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc, DeclarationName Entity,
bool AllowDeducedTST = false);
QualType SubstType(QualType T,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc, DeclarationName Entity);
TypeSourceInfo *SubstType(TypeLoc TL,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc, DeclarationName Entity);
TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc,
DeclarationName Entity,
CXXRecordDecl *ThisContext,
Qualifiers ThisTypeQuals);
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
const MultiLevelTemplateArgumentList &Args);
bool SubstExceptionSpec(SourceLocation Loc,
FunctionProtoType::ExceptionSpecInfo &ESI,
SmallVectorImpl<QualType> &ExceptionStorage,
const MultiLevelTemplateArgumentList &Args);
ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
const MultiLevelTemplateArgumentList &TemplateArgs,
int indexAdjustment,
Optional<unsigned> NumExpansions,
bool ExpectParameterPack);
bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
const MultiLevelTemplateArgumentList &TemplateArgs,
SmallVectorImpl<QualType> &ParamTypes,
SmallVectorImpl<ParmVarDecl *> *OutParams,
ExtParameterInfoBuilder &ParamInfos);
ExprResult SubstExpr(Expr *E,
const MultiLevelTemplateArgumentList &TemplateArgs);
/// Substitute the given template arguments into a list of
/// expressions, expanding pack expansions if required.
///
/// \param Exprs The list of expressions to substitute into.
///
/// \param IsCall Whether this is some form of call, in which case
/// default arguments will be dropped.
///
/// \param TemplateArgs The set of template arguments to substitute.
///
/// \param Outputs Will receive all of the substituted arguments.
///
/// \returns true if an error occurred, false otherwise.
bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
const MultiLevelTemplateArgumentList &TemplateArgs,
SmallVectorImpl<Expr *> &Outputs);
StmtResult SubstStmt(Stmt *S,
const MultiLevelTemplateArgumentList &TemplateArgs);
TemplateParameterList *
SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
const MultiLevelTemplateArgumentList &TemplateArgs);
Decl *SubstDecl(Decl *D, DeclContext *Owner,
const MultiLevelTemplateArgumentList &TemplateArgs);
/// Substitute the name and return type of a defaulted 'operator<=>' to form
/// an implicit 'operator=='.
FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
FunctionDecl *Spaceship);
ExprResult SubstInitializer(Expr *E,
const MultiLevelTemplateArgumentList &TemplateArgs,
bool CXXDirectInit);
bool
SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
CXXRecordDecl *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs);
bool
InstantiateClass(SourceLocation PointOfInstantiation,
CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK,
bool Complain = true);
bool InstantiateEnum(SourceLocation PointOfInstantiation,
EnumDecl *Instantiation, EnumDecl *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK);
bool InstantiateInClassInitializer(
SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
struct LateInstantiatedAttribute {
const Attr *TmplAttr;
LocalInstantiationScope *Scope;
Decl *NewDecl;
LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
Decl *D)
: TmplAttr(A), Scope(S), NewDecl(D)
{ }
};
typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
const Decl *Pattern, Decl *Inst,
LateInstantiatedAttrVec *LateAttrs = nullptr,
LocalInstantiationScope *OuterMostScope = nullptr);
void
InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
const Decl *Pattern, Decl *Inst,
LateInstantiatedAttrVec *LateAttrs = nullptr,
LocalInstantiationScope *OuterMostScope = nullptr);
bool usesPartialOrExplicitSpecialization(
SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
bool
InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
ClassTemplateSpecializationDecl *ClassTemplateSpec,
TemplateSpecializationKind TSK,
bool Complain = true);
void InstantiateClassMembers(SourceLocation PointOfInstantiation,
CXXRecordDecl *Instantiation,
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK);
void InstantiateClassTemplateSpecializationMembers(
SourceLocation PointOfInstantiation,
ClassTemplateSpecializationDecl *ClassTemplateSpec,
TemplateSpecializationKind TSK);
NestedNameSpecifierLoc
SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
const MultiLevelTemplateArgumentList &TemplateArgs);
DeclarationNameInfo
SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
const MultiLevelTemplateArgumentList &TemplateArgs);
TemplateName
SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
SourceLocation Loc,
const MultiLevelTemplateArgumentList &TemplateArgs);
bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
TemplateArgumentListInfo &Result,
const MultiLevelTemplateArgumentList &TemplateArgs);
void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
FunctionDecl *Function);
FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
const TemplateArgumentList *Args,
SourceLocation Loc);
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
FunctionDecl *Function,
bool Recursive = false,
bool DefinitionRequired = false,
bool AtEndOfTU = false);
VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
VarTemplateDecl *VarTemplate, VarDecl *FromVar,
const TemplateArgumentList &TemplateArgList,
const TemplateArgumentListInfo &TemplateArgsInfo,
SmallVectorImpl<TemplateArgument> &Converted,
SourceLocation PointOfInstantiation, void *InsertPos,
LateInstantiatedAttrVec *LateAttrs = nullptr,
LocalInstantiationScope *StartingScope = nullptr);
VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
const MultiLevelTemplateArgumentList &TemplateArgs);
void
BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
const MultiLevelTemplateArgumentList &TemplateArgs,
LateInstantiatedAttrVec *LateAttrs,
DeclContext *Owner,
LocalInstantiationScope *StartingScope,
bool InstantiatingVarTemplate = false,
VarTemplateSpecializationDecl *PrevVTSD = nullptr);
VarDecl *getVarTemplateSpecialization(
VarTemplateDecl *VarTempl, const TemplateArgumentListInfo *TemplateArgs,
const DeclarationNameInfo &MemberNameInfo, SourceLocation TemplateKWLoc);
void InstantiateVariableInitializer(
VarDecl *Var, VarDecl *OldVar,
const MultiLevelTemplateArgumentList &TemplateArgs);
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
VarDecl *Var, bool Recursive = false,
bool DefinitionRequired = false,
bool AtEndOfTU = false);
void InstantiateMemInitializers(CXXConstructorDecl *New,
const CXXConstructorDecl *Tmpl,
const MultiLevelTemplateArgumentList &TemplateArgs);
NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
const MultiLevelTemplateArgumentList &TemplateArgs,
bool FindingInstantiatedContext = false);
DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
const MultiLevelTemplateArgumentList &TemplateArgs);
// Objective-C declarations.
enum ObjCContainerKind {
OCK_None = -1,
OCK_Interface = 0,
OCK_Protocol,
OCK_Category,
OCK_ClassExtension,
OCK_Implementation,
OCK_CategoryImplementation
};
ObjCContainerKind getObjCContainerKind() const;
DeclResult actOnObjCTypeParam(Scope *S,
ObjCTypeParamVariance variance,
SourceLocation varianceLoc,
unsigned index,
IdentifierInfo *paramName,
SourceLocation paramLoc,
SourceLocation colonLoc,
ParsedType typeBound);
ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
ArrayRef<Decl *> typeParams,
SourceLocation rAngleLoc);
void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
Decl *ActOnStartClassInterface(
Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
IdentifierInfo *SuperName, SourceLocation SuperLoc,
ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
Decl *const *ProtoRefs, unsigned NumProtoRefs,
const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
const ParsedAttributesView &AttrList);
void ActOnSuperClassOfClassInterface(Scope *S,
SourceLocation AtInterfaceLoc,
ObjCInterfaceDecl *IDecl,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
IdentifierInfo *SuperName,
SourceLocation SuperLoc,
ArrayRef<ParsedType> SuperTypeArgs,
SourceRange SuperTypeArgsRange);
void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
SmallVectorImpl<SourceLocation> &ProtocolLocs,
IdentifierInfo *SuperName,
SourceLocation SuperLoc);
Decl *ActOnCompatibilityAlias(
SourceLocation AtCompatibilityAliasLoc,
IdentifierInfo *AliasName, SourceLocation AliasLocation,
IdentifierInfo *ClassName, SourceLocation ClassLocation);
bool CheckForwardProtocolDeclarationForCircularDependency(
IdentifierInfo *PName,
SourceLocation &PLoc, SourceLocation PrevLoc,
const ObjCList<ObjCProtocolDecl> &PList);
Decl *ActOnStartProtocolInterface(
SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
SourceLocation ProtocolLoc, Decl *const *ProtoRefNames,
unsigned NumProtoRefs, const SourceLocation *ProtoLocs,
SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList);
Decl *ActOnStartCategoryInterface(
SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
Decl *const *ProtoRefs, unsigned NumProtoRefs,
const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
const ParsedAttributesView &AttrList);
Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
IdentifierInfo *SuperClassname,
SourceLocation SuperClassLoc,
const ParsedAttributesView &AttrList);
Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
IdentifierInfo *CatName,
SourceLocation CatLoc,
const ParsedAttributesView &AttrList);
DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
ArrayRef<Decl *> Decls);
DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
IdentifierInfo **IdentList,
SourceLocation *IdentLocs,
ArrayRef<ObjCTypeParamList *> TypeParamLists,
unsigned NumElts);
DeclGroupPtrTy
ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
ArrayRef<IdentifierLocPair> IdentList,
const ParsedAttributesView &attrList);
void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
ArrayRef<IdentifierLocPair> ProtocolId,
SmallVectorImpl<Decl *> &Protocols);
void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
SourceLocation ProtocolLoc,
IdentifierInfo *TypeArgId,
SourceLocation TypeArgLoc,
bool SelectProtocolFirst = false);
/// Given a list of identifiers (and their locations), resolve the
/// names to either Objective-C protocol qualifiers or type
/// arguments, as appropriate.
void actOnObjCTypeArgsOrProtocolQualifiers(
Scope *S,
ParsedType baseType,
SourceLocation lAngleLoc,
ArrayRef<IdentifierInfo *> identifiers,
ArrayRef<SourceLocation> identifierLocs,
SourceLocation rAngleLoc,
SourceLocation &typeArgsLAngleLoc,
SmallVectorImpl<ParsedType> &typeArgs,
SourceLocation &typeArgsRAngleLoc,
SourceLocation &protocolLAngleLoc,
SmallVectorImpl<Decl *> &protocols,
SourceLocation &protocolRAngleLoc,
bool warnOnIncompleteProtocols);
/// Build a an Objective-C protocol-qualified 'id' type where no
/// base type was specified.
TypeResult actOnObjCProtocolQualifierType(
SourceLocation lAngleLoc,
ArrayRef<Decl *> protocols,
ArrayRef<SourceLocation> protocolLocs,
SourceLocation rAngleLoc);
/// Build a specialized and/or protocol-qualified Objective-C type.
TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
Scope *S,
SourceLocation Loc,
ParsedType BaseType,
SourceLocation TypeArgsLAngleLoc,
ArrayRef<ParsedType> TypeArgs,
SourceLocation TypeArgsRAngleLoc,
SourceLocation ProtocolLAngleLoc,
ArrayRef<Decl *> Protocols,
ArrayRef<SourceLocation> ProtocolLocs,
SourceLocation ProtocolRAngleLoc);
/// Build an Objective-C type parameter type.
QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
SourceLocation ProtocolLAngleLoc,
ArrayRef<ObjCProtocolDecl *> Protocols,
ArrayRef<SourceLocation> ProtocolLocs,
SourceLocation ProtocolRAngleLoc,
bool FailOnError = false);
/// Build an Objective-C object pointer type.
QualType BuildObjCObjectType(QualType BaseType,
SourceLocation Loc,
SourceLocation TypeArgsLAngleLoc,
ArrayRef<TypeSourceInfo *> TypeArgs,
SourceLocation TypeArgsRAngleLoc,
SourceLocation ProtocolLAngleLoc,
ArrayRef<ObjCProtocolDecl *> Protocols,
ArrayRef<SourceLocation> ProtocolLocs,
SourceLocation ProtocolRAngleLoc,
bool FailOnError = false);
/// Ensure attributes are consistent with type.
/// \param [in, out] Attributes The attributes to check; they will
/// be modified to be consistent with \p PropertyTy.
void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
SourceLocation Loc,
unsigned &Attributes,
bool propertyInPrimaryClass);
/// Process the specified property declaration and create decls for the
/// setters and getters as needed.
/// \param property The property declaration being processed
void ProcessPropertyDecl(ObjCPropertyDecl *property);
void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
ObjCPropertyDecl *SuperProperty,
const IdentifierInfo *Name,
bool OverridingProtocolProperty);
void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
ObjCInterfaceDecl *ID);
Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
ArrayRef<Decl *> allMethods = None,
ArrayRef<DeclGroupPtrTy> allTUVars = None);
Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
SourceLocation LParenLoc,
FieldDeclarator &FD, ObjCDeclSpec &ODS,
Selector GetterSel, Selector SetterSel,
tok::ObjCKeywordKind MethodImplKind,
DeclContext *lexicalDC = nullptr);
Decl *ActOnPropertyImplDecl(Scope *S,
SourceLocation AtLoc,
SourceLocation PropertyLoc,
bool ImplKind,
IdentifierInfo *PropertyId,
IdentifierInfo *PropertyIvar,
SourceLocation PropertyIvarLoc,
ObjCPropertyQueryKind QueryKind);
enum ObjCSpecialMethodKind {
OSMK_None,
OSMK_Alloc,
OSMK_New,
OSMK_Copy,
OSMK_RetainingInit,
OSMK_NonRetainingInit
};
struct ObjCArgInfo {
IdentifierInfo *Name;
SourceLocation NameLoc;
// The Type is null if no type was specified, and the DeclSpec is invalid
// in this case.
ParsedType Type;
ObjCDeclSpec DeclSpec;
/// ArgAttrs - Attribute list for this argument.
ParsedAttributesView ArgAttrs;
};
Decl *ActOnMethodDeclaration(
Scope *S,
SourceLocation BeginLoc, // location of the + or -.
SourceLocation EndLoc, // location of the ; or {.
tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
// optional arguments. The number of types/arguments is obtained
// from the Sel.getNumArgs().
ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
unsigned CNumArgs, // c-style args
const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind,
bool isVariadic, bool MethodDefinition);
ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
const ObjCObjectPointerType *OPT,
bool IsInstance);
ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
bool IsInstance);
bool CheckARCMethodDecl(ObjCMethodDecl *method);
bool inferObjCARCLifetime(ValueDecl *decl);
void deduceOpenCLAddressSpace(ValueDecl *decl);
ExprResult
HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Expr *BaseExpr,
SourceLocation OpLoc,
DeclarationName MemberName,
SourceLocation MemberLoc,
SourceLocation SuperLoc, QualType SuperType,
bool Super);
ExprResult
ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
IdentifierInfo &propertyName,
SourceLocation receiverNameLoc,
SourceLocation propertyNameLoc);
ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
/// Describes the kind of message expression indicated by a message
/// send that starts with an identifier.
enum ObjCMessageKind {
/// The message is sent to 'super'.
ObjCSuperMessage,
/// The message is an instance message.
ObjCInstanceMessage,
/// The message is a class message, and the identifier is a type
/// name.
ObjCClassMessage
};
ObjCMessageKind getObjCMessageKind(Scope *S,
IdentifierInfo *Name,
SourceLocation NameLoc,
bool IsSuper,
bool HasTrailingDot,
ParsedType &ReceiverType);
ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args);
ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
QualType ReceiverType,
SourceLocation SuperLoc,
Selector Sel,
ObjCMethodDecl *Method,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args,
bool isImplicit = false);
ExprResult BuildClassMessageImplicit(QualType ReceiverType,
bool isSuperReceiver,
SourceLocation Loc,
Selector Sel,
ObjCMethodDecl *Method,
MultiExprArg Args);
ExprResult ActOnClassMessage(Scope *S,
ParsedType Receiver,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args);
ExprResult BuildInstanceMessage(Expr *Receiver,
QualType ReceiverType,
SourceLocation SuperLoc,
Selector Sel,
ObjCMethodDecl *Method,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args,
bool isImplicit = false);
ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
QualType ReceiverType,
SourceLocation Loc,
Selector Sel,
ObjCMethodDecl *Method,
MultiExprArg Args);
ExprResult ActOnInstanceMessage(Scope *S,
Expr *Receiver,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args);
ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
ObjCBridgeCastKind Kind,
SourceLocation BridgeKeywordLoc,
TypeSourceInfo *TSInfo,
Expr *SubExpr);
ExprResult ActOnObjCBridgedCast(Scope *S,
SourceLocation LParenLoc,
ObjCBridgeCastKind Kind,
SourceLocation BridgeKeywordLoc,
ParsedType Type,
SourceLocation RParenLoc,
Expr *SubExpr);
void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
CastKind &Kind);
bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
QualType DestType, QualType SrcType,
ObjCInterfaceDecl *&RelatedClass,
ObjCMethodDecl *&ClassMethod,
ObjCMethodDecl *&InstanceMethod,
TypedefNameDecl *&TDNDecl,
bool CfToNs, bool Diagnose = true);
bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
QualType DestType, QualType SrcType,
Expr *&SrcExpr, bool Diagnose = true);
bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
bool Diagnose = true);
bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
/// Check whether the given new method is a valid override of the
/// given overridden method, and set any properties that should be inherited.
void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
const ObjCMethodDecl *Overridden);
/// Describes the compatibility of a result type with its method.
enum ResultTypeCompatibilityKind {
RTC_Compatible,
RTC_Incompatible,
RTC_Unknown
};
/// Check whether the declared result type of the given Objective-C
/// method declaration is compatible with the method's class.
ResultTypeCompatibilityKind
checkRelatedResultTypeCompatibility(const ObjCMethodDecl *Method,
const ObjCInterfaceDecl *CurrentClass);
void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method,
ObjCMethodDecl *overridden);
void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
ObjCInterfaceDecl *CurrentClass,
ResultTypeCompatibilityKind RTC);
enum PragmaOptionsAlignKind {
POAK_Native, // #pragma options align=native
POAK_Natural, // #pragma options align=natural
POAK_Packed, // #pragma options align=packed
POAK_Power, // #pragma options align=power
POAK_Mac68k, // #pragma options align=mac68k
POAK_Reset // #pragma options align=reset
};
/// ActOnPragmaClangSection - Called on well formed \#pragma clang section
void ActOnPragmaClangSection(SourceLocation PragmaLoc,
PragmaClangSectionAction Action,
PragmaClangSectionKind SecKind, StringRef SecName);
/// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
SourceLocation PragmaLoc);
/// ActOnPragmaPack - Called on well formed \#pragma pack(...).
void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
StringRef SlotLabel, Expr *Alignment);
enum class PragmaPackDiagnoseKind {
NonDefaultStateAtInclude,
ChangedStateAtExit
};
void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind,
SourceLocation IncludeLoc);
void DiagnoseUnterminatedPragmaPack();
/// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
/// ActOnPragmaMSComment - Called on well formed
/// \#pragma comment(kind, "arg").
void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
StringRef Arg);
/// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
/// pointers_to_members(representation method[, general purpose
/// representation]).
void ActOnPragmaMSPointersToMembers(
LangOptions::PragmaMSPointersToMembersKind Kind,
SourceLocation PragmaLoc);
/// Called on well formed \#pragma vtordisp().
void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
SourceLocation PragmaLoc,
MSVtorDispMode Value);
enum PragmaSectionKind {
PSK_DataSeg,
PSK_BSSSeg,
PSK_ConstSeg,
PSK_CodeSeg,
};
bool UnifySection(StringRef SectionName,
int SectionFlags,
DeclaratorDecl *TheDecl);
bool UnifySection(StringRef SectionName,
int SectionFlags,
SourceLocation PragmaSectionLocation);
/// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
PragmaMsStackAction Action,
llvm::StringRef StackSlotLabel,
StringLiteral *SegmentName,
llvm::StringRef PragmaName);
/// Called on well formed \#pragma section().
void ActOnPragmaMSSection(SourceLocation PragmaLocation,
int SectionFlags, StringLiteral *SegmentName);
/// Called on well-formed \#pragma init_seg().
void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
StringLiteral *SegmentName);
/// Called on #pragma clang __debug dump II
void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
/// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
StringRef Value);
/// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
void ActOnPragmaUnused(const Token &Identifier,
Scope *curScope,
SourceLocation PragmaLoc);
/// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
void ActOnPragmaVisibility(const IdentifierInfo* VisType,
SourceLocation PragmaLoc);
NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
SourceLocation Loc);
void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
/// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
void ActOnPragmaWeakID(IdentifierInfo* WeakName,
SourceLocation PragmaLoc,
SourceLocation WeakNameLoc);
/// ActOnPragmaRedefineExtname - Called on well formed
/// \#pragma redefine_extname oldname newname.
void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
IdentifierInfo* AliasName,
SourceLocation PragmaLoc,
SourceLocation WeakNameLoc,
SourceLocation AliasNameLoc);
/// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
IdentifierInfo* AliasName,
SourceLocation PragmaLoc,
SourceLocation WeakNameLoc,
SourceLocation AliasNameLoc);
/// ActOnPragmaFPContract - Called on well formed
/// \#pragma {STDC,OPENCL} FP_CONTRACT and
/// \#pragma clang fp contract
void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
/// ActOnPragmaFenvAccess - Called on well formed
/// \#pragma STDC FENV_ACCESS
void ActOnPragmaFEnvAccess(LangOptions::FEnvAccessModeKind FPC);
/// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
/// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
void AddAlignmentAttributesForRecord(RecordDecl *RD);
/// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
void AddMsStructLayoutForRecord(RecordDecl *RD);
/// FreePackedContext - Deallocate and null out PackContext.
void FreePackedContext();
/// PushNamespaceVisibilityAttr - Note that we've entered a
/// namespace with a visibility attribute.
void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
SourceLocation Loc);
/// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
/// add an appropriate visibility attribute.
void AddPushedVisibilityAttribute(Decl *RD);
/// PopPragmaVisibility - Pop the top element of the visibility stack; used
/// for '\#pragma GCC visibility' and visibility attributes on namespaces.
void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
/// FreeVisContext - Deallocate and null out VisContext.
void FreeVisContext();
/// AddCFAuditedAttribute - Check whether we're currently within
/// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
/// the appropriate attribute.
void AddCFAuditedAttribute(Decl *D);
void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
SourceLocation PragmaLoc,
attr::ParsedSubjectMatchRuleSet Rules);
void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
const IdentifierInfo *Namespace);
/// Called on well-formed '\#pragma clang attribute pop'.
void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
const IdentifierInfo *Namespace);
/// Adds the attributes that have been specified using the
/// '\#pragma clang attribute push' directives to the given declaration.
void AddPragmaAttributes(Scope *S, Decl *D);
void DiagnoseUnterminatedPragmaAttribute();
/// Called on well formed \#pragma clang optimize.
void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
/// Get the location for the currently active "\#pragma clang optimize
/// off". If this location is invalid, then the state of the pragma is "on".
SourceLocation getOptimizeOffPragmaLocation() const {
return OptimizeOffPragmaLocation;
}
/// Only called on function definitions; if there is a pragma in scope
/// with the effect of a range-based optnone, consider marking the function
/// with attribute optnone.
void AddRangeBasedOptnone(FunctionDecl *FD);
/// Adds the 'optnone' attribute to the function declaration if there
/// are no conflicts; Loc represents the location causing the 'optnone'
/// attribute to be added (usually because of a pragma).
void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
/// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
bool IsPackExpansion);
void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
bool IsPackExpansion);
/// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
/// declaration.
void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
Expr *OE);
/// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
/// declaration.
void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
Expr *ParamExpr);
/// AddAlignValueAttr - Adds an align_value attribute to a particular
/// declaration.
void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
/// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
/// declaration.
void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
Expr *MaxThreads, Expr *MinBlocks);
/// AddModeAttr - Adds a mode attribute to a particular declaration.
void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
bool InInstantiation = false);
void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
ParameterABI ABI);
enum class RetainOwnershipKind {NS, CF, OS};
void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
RetainOwnershipKind K, bool IsTemplateInstantiation);
/// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size
/// attribute to a particular declaration.
void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI,
Expr *Min, Expr *Max);
/// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a
/// particular declaration.
void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
Expr *Min, Expr *Max);
bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
//===--------------------------------------------------------------------===//
// C++ Coroutines TS
//
bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
StringRef Keyword);
ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
bool IsImplicit = false);
ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
UnresolvedLookupExpr* Lookup);
ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
bool IsImplicit = false);
StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
bool buildCoroutineParameterMoves(SourceLocation Loc);
VarDecl *buildCoroutinePromise(SourceLocation Loc);
void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
SourceLocation FuncLoc);
//===--------------------------------------------------------------------===//
// OpenCL extensions.
//
private:
std::string CurrOpenCLExtension;
/// Extensions required by an OpenCL type.
llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
/// Extensions required by an OpenCL declaration.
llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
public:
llvm::StringRef getCurrentOpenCLExtension() const {
return CurrOpenCLExtension;
}
/// Check if a function declaration \p FD associates with any
/// extensions present in OpenCLDeclExtMap and if so return the
/// extension(s) name(s).
std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD);
/// Check if a function type \p FT associates with any
/// extensions present in OpenCLTypeExtMap and if so return the
/// extension(s) name(s).
std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT);
/// Find an extension in an appropriate extension map and return its name
template<typename T, typename MapT>
std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map);
void setCurrentOpenCLExtension(llvm::StringRef Ext) {
CurrOpenCLExtension = Ext;
}
/// Set OpenCL extensions for a type which can only be used when these
/// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
/// \param Exts A space separated list of OpenCL extensions.
void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
/// Set OpenCL extensions for a declaration which can only be
/// used when these OpenCL extensions are enabled. If \p Exts is empty, do
/// nothing.
/// \param Exts A space separated list of OpenCL extensions.
void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
/// Set current OpenCL extensions for a type which can only be used
/// when these OpenCL extensions are enabled. If current OpenCL extension is
/// empty, do nothing.
void setCurrentOpenCLExtensionForType(QualType T);
/// Set current OpenCL extensions for a declaration which
/// can only be used when these OpenCL extensions are enabled. If current
/// OpenCL extension is empty, do nothing.
void setCurrentOpenCLExtensionForDecl(Decl *FD);
bool isOpenCLDisabledDecl(Decl *FD);
/// Check if type \p T corresponding to declaration specifier \p DS
/// is disabled due to required OpenCL extensions being disabled. If so,
/// emit diagnostics.
/// \return true if type is disabled.
bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
/// Check if declaration \p D used by expression \p E
/// is disabled due to required OpenCL extensions being disabled. If so,
/// emit diagnostics.
/// \return true if type is disabled.
bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E);
//===--------------------------------------------------------------------===//
// OpenMP directives and clauses.
//
private:
void *VarDataSharingAttributesStack;
/// Number of nested '#pragma omp declare target' directives.
unsigned DeclareTargetNestingLevel = 0;
/// Initialization of data-sharing attributes stack.
void InitDataSharingAttributesStack();
void DestroyDataSharingAttributesStack();
ExprResult
VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
bool StrictlyPositive = true);
/// Returns OpenMP nesting level for current directive.
unsigned getOpenMPNestingLevel() const;
/// Adjusts the function scopes index for the target-based regions.
void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
unsigned Level) const;
/// Returns the number of scopes associated with the construct on the given
/// OpenMP level.
int getNumberOfConstructScopes(unsigned Level) const;
/// Push new OpenMP function region for non-capturing function.
void pushOpenMPFunctionRegion();
/// Pop OpenMP function region for non-capturing function.
void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
/// Check whether we're allowed to call Callee from the current function.
void checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
bool CheckForDelayedContext = true);
/// Check whether we're allowed to call Callee from the current function.
void checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
bool CheckCaller = true);
/// Check if the expression is allowed to be used in expressions for the
/// OpenMP devices.
void checkOpenMPDeviceExpr(const Expr *E);
/// Finishes analysis of the deferred functions calls that may be declared as
/// host/nohost during device/host compilation.
void finalizeOpenMPDelayedAnalysis();
/// Checks if a type or a declaration is disabled due to the owning extension
/// being disabled, and emits diagnostic messages if it is disabled.
/// \param D type or declaration to be checked.
/// \param DiagLoc source location for the diagnostic message.
/// \param DiagInfo information to be emitted for the diagnostic message.
/// \param SrcRange source range of the declaration.
/// \param Map maps type or declaration to the extensions.
/// \param Selector selects diagnostic message: 0 for type and 1 for
/// declaration.
/// \return true if the type or declaration is disabled.
template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
MapT &Map, unsigned Selector = 0,
SourceRange SrcRange = SourceRange());
/// Marks all the functions that might be required for the currently active
/// OpenMP context.
void markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
FunctionDecl *Func,
bool MightBeOdrUse);
public:
/// Struct to store the context selectors info for declare variant directive.
using OMPCtxStringType = SmallString<8>;
using OMPCtxSelectorData =
OpenMPCtxSelectorData<SmallVector<OMPCtxStringType, 4>, ExprResult>;
/// Checks if the variant/multiversion functions are compatible.
bool areMultiversionVariantFunctionsCompatible(
const FunctionDecl *OldFD, const FunctionDecl *NewFD,
const PartialDiagnostic &NoProtoDiagID,
const PartialDiagnosticAt &NoteCausedDiagIDAt,
const PartialDiagnosticAt &NoSupportDiagIDAt,
const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
bool ConstexprSupported, bool CLinkageMayDiffer);
/// Function tries to capture lambda's captured variables in the OpenMP region
/// before the original lambda is captured.
void tryCaptureOpenMPLambdas(ValueDecl *V);
/// Return true if the provided declaration \a VD should be captured by
/// reference.
/// \param Level Relative level of nested OpenMP construct for that the check
/// is performed.
/// \param OpenMPCaptureLevel Capture level within an OpenMP construct.
bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
unsigned OpenMPCaptureLevel) const;
/// Check if the specified variable is used in one of the private
/// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
/// constructs.
VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false,
unsigned StopAt = 0);
ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
ExprObjectKind OK, SourceLocation Loc);
/// If the current region is a loop-based region, mark the start of the loop
/// construct.
void startOpenMPLoop();
/// If the current region is a range loop-based region, mark the start of the
/// loop construct.
void startOpenMPCXXRangeFor();
/// Check if the specified variable is used in 'private' clause.
/// \param Level Relative level of nested OpenMP construct for that the check
/// is performed.
bool isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const;
/// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
/// for \p FD based on DSA for the provided corresponding captured declaration
/// \p D.
void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level);
/// Check if the specified variable is captured by 'target' directive.
/// \param Level Relative level of nested OpenMP construct for that the check
/// is performed.
bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level) const;
ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
Expr *Op);
/// Called on start of new data sharing attribute block.
void StartOpenMPDSABlock(OpenMPDirectiveKind K,
const DeclarationNameInfo &DirName, Scope *CurScope,
SourceLocation Loc);
/// Start analysis of clauses.
void StartOpenMPClause(OpenMPClauseKind K);
/// End analysis of clauses.
void EndOpenMPClause();
/// Called on end of data sharing attribute block.
void EndOpenMPDSABlock(Stmt *CurDirective);
/// Check if the current region is an OpenMP loop region and if it is,
/// mark loop control variable, used in \p Init for loop initialization, as
/// private by default.
/// \param Init First part of the for loop.
void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
// OpenMP directives and clauses.
/// Called on correct id-expression from the '#pragma omp
/// threadprivate'.
ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec,
const DeclarationNameInfo &Id,
OpenMPDirectiveKind Kind);
/// Called on well-formed '#pragma omp threadprivate'.
DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
SourceLocation Loc,
ArrayRef<Expr *> VarList);
/// Builds a new OpenMPThreadPrivateDecl and checks its correctness.
OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc,
ArrayRef<Expr *> VarList);
/// Called on well-formed '#pragma omp allocate'.
DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc,
ArrayRef<Expr *> VarList,
ArrayRef<OMPClause *> Clauses,
DeclContext *Owner = nullptr);
/// Called on well-formed '#pragma omp requires'.
DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc,
ArrayRef<OMPClause *> ClauseList);
/// Check restrictions on Requires directive
OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc,
ArrayRef<OMPClause *> Clauses);
/// Check if the specified type is allowed to be used in 'omp declare
/// reduction' construct.
QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
TypeResult ParsedType);
/// Called on start of '#pragma omp declare reduction'.
DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
Scope *S, DeclContext *DC, DeclarationName Name,
ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
/// Initialize declare reduction construct initializer.
void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
/// Finish current declare reduction construct initializer.
void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
/// Initialize declare reduction construct initializer.
/// \return omp_priv variable.
VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
/// Finish current declare reduction construct initializer.
void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
VarDecl *OmpPrivParm);
/// Called at the end of '#pragma omp declare reduction'.
DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
/// Check variable declaration in 'omp declare mapper' construct.
TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D);
/// Check if the specified type is allowed to be used in 'omp declare
/// mapper' construct.
QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
TypeResult ParsedType);
/// Called on start of '#pragma omp declare mapper'.
OMPDeclareMapperDecl *ActOnOpenMPDeclareMapperDirectiveStart(
Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
Decl *PrevDeclInScope = nullptr);
/// Build the mapper variable of '#pragma omp declare mapper'.
void ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
Scope *S, QualType MapperType,
SourceLocation StartLoc,
DeclarationName VN);
/// Called at the end of '#pragma omp declare mapper'.
DeclGroupPtrTy
ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
ArrayRef<OMPClause *> ClauseList);
/// Called on the start of target region i.e. '#pragma omp declare target'.
bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
/// Called at the end of target region i.e. '#pragme omp end declare target'.
void ActOnFinishOpenMPDeclareTargetDirective();
/// Searches for the provided declaration name for OpenMP declare target
/// directive.
NamedDecl *
lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
const DeclarationNameInfo &Id,
NamedDeclSetType &SameDirectiveDecls);
/// Called on correct id-expression from the '#pragma omp declare target'.
void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
OMPDeclareTargetDeclAttr::MapTypeTy MT,
OMPDeclareTargetDeclAttr::DevTypeTy DT);
/// Check declaration inside target region.
void
checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
SourceLocation IdLoc = SourceLocation());
/// Return true inside OpenMP declare target region.
bool isInOpenMPDeclareTargetContext() const {
return DeclareTargetNestingLevel > 0;
}
/// Return true inside OpenMP target region.
bool isInOpenMPTargetExecutionDirective() const;
/// Return the number of captured regions created for an OpenMP directive.
static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
/// Initialization of captured region for OpenMP region.
void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
/// End of OpenMP region.
///
/// \param S Statement associated with the current OpenMP region.
/// \param Clauses List of clauses for the current OpenMP region.
///
/// \returns Statement for finished OpenMP region.
StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
StmtResult ActOnOpenMPExecutableDirective(
OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp parallel' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
using VarsWithInheritedDSAType =
llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>;
/// Called on well-formed '\#pragma omp simd' after parsing
/// of the associated statement.
StmtResult
ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp for' after parsing
/// of the associated statement.
StmtResult
ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp for simd' after parsing
/// of the associated statement.
StmtResult
ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp sections' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp section' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp single' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp master' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp critical' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp parallel for' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp parallel for simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp parallel master' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp parallel sections' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp task' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp taskyield'.
StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp barrier'.
StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp taskwait'.
StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp taskgroup'.
StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp flush'.
StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp ordered' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp atomic' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp target' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp target data' after parsing of
/// the associated statement.
StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp target enter data' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc,
Stmt *AStmt);
/// Called on well-formed '\#pragma omp target exit data' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc,
Stmt *AStmt);
/// Called on well-formed '\#pragma omp target parallel' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp target parallel for' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp teams' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp cancellation point'.
StmtResult
ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
OpenMPDirectiveKind CancelRegion);
/// Called on well-formed '\#pragma omp cancel'.
StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc,
OpenMPDirectiveKind CancelRegion);
/// Called on well-formed '\#pragma omp taskloop' after parsing of the
/// associated statement.
StmtResult
ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp taskloop simd' after parsing of
/// the associated statement.
StmtResult ActOnOpenMPTaskLoopSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp master taskloop' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPMasterTaskLoopDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp master taskloop simd' after parsing of
/// the associated statement.
StmtResult ActOnOpenMPMasterTaskLoopSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp parallel master taskloop' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelMasterTaskLoopDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp parallel master taskloop simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp distribute' after parsing
/// of the associated statement.
StmtResult
ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target update'.
StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc,
Stmt *AStmt);
/// Called on well-formed '\#pragma omp distribute parallel for' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPDistributeParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp distribute parallel for simd'
/// after parsing of the associated statement.
StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp distribute simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPDistributeSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target parallel for simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target simd' after parsing of
/// the associated statement.
StmtResult
ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp teams distribute' after parsing of
/// the associated statement.
StmtResult ActOnOpenMPTeamsDistributeDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp teams distribute simd' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp teams distribute parallel for simd'
/// after parsing of the associated statement.
StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp teams distribute parallel for'
/// after parsing of the associated statement.
StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target teams' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp target teams distribute' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target teams distribute parallel for'
/// after parsing of the associated statement.
StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target teams distribute parallel for
/// simd' after parsing of the associated statement.
StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target teams distribute simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Checks correctness of linear modifiers.
bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
SourceLocation LinLoc);
/// Checks that the specified declaration matches requirements for the linear
/// decls.
bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
OpenMPLinearClauseKind LinKind, QualType Type);
/// Called on well-formed '\#pragma omp declare simd' after parsing of
/// the associated method/function.
DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
/// Checks '\#pragma omp declare variant' variant function and original
/// functions after parsing of the associated method/function.
/// \param DG Function declaration to which declare variant directive is
/// applied to.
/// \param VariantRef Expression that references the variant function, which
/// must be used instead of the original one, specified in \p DG.
/// \returns None, if the function/variant function are not compatible with
/// the pragma, pair of original function/variant ref expression otherwise.
Optional<std::pair<FunctionDecl *, Expr *>> checkOpenMPDeclareVariantFunction(
DeclGroupPtrTy DG, Expr *VariantRef, SourceRange SR);
/// Called on well-formed '\#pragma omp declare variant' after parsing of
/// the associated method/function.
/// \param FD Function declaration to which declare variant directive is
/// applied to.
/// \param VariantRef Expression that references the variant function, which
/// must be used instead of the original one, specified in \p DG.
/// \param Data Set of context-specific data for the specified context
/// selector.
void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef,
SourceRange SR,
ArrayRef<OMPCtxSelectorData> Data);
OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
Expr *Expr,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'allocator' clause.
OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'if' clause.
OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
Expr *Condition, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation NameModifierLoc,
SourceLocation ColonLoc,
SourceLocation EndLoc);
/// Called on well-formed 'final' clause.
OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'num_threads' clause.
OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'safelen' clause.
OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'simdlen' clause.
OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'collapse' clause.
OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'ordered' clause.
OMPClause *
ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
SourceLocation LParenLoc = SourceLocation(),
Expr *NumForLoops = nullptr);
/// Called on well-formed 'grainsize' clause.
OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'num_tasks' clause.
OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'hint' clause.
OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
unsigned Argument,
SourceLocation ArgumentLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'default' clause.
OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
SourceLocation KindLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'proc_bind' clause.
OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
SourceLocation KindLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
OMPClause *ActOnOpenMPSingleExprWithArgClause(
OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
SourceLocation StartLoc, SourceLocation LParenLoc,
ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
SourceLocation EndLoc);
/// Called on well-formed 'schedule' clause.
OMPClause *ActOnOpenMPScheduleClause(
OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'nowait' clause.
OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'untied' clause.
OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'mergeable' clause.
OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'read' clause.
OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'write' clause.
OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'update' clause.
OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'capture' clause.
OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'seq_cst' clause.
OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'threads' clause.
OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'simd' clause.
OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'nogroup' clause.
OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'unified_address' clause.
OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'unified_address' clause.
OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'reverse_offload' clause.
OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'dynamic_allocators' clause.
OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'atomic_default_mem_order' clause.
OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause(
OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc,
SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
OMPClause *ActOnOpenMPVarListClause(
OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
CXXScopeSpec &ReductionOrMapperIdScopeSpec,
DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
OpenMPLinearClauseKind LinKind,
ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
bool IsMapTypeImplicit, SourceLocation DepLinMapLoc);
/// Called on well-formed 'allocate' clause.
OMPClause *
ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList,
SourceLocation StartLoc, SourceLocation ColonLoc,
SourceLocation LParenLoc, SourceLocation EndLoc);
/// Called on well-formed 'private' clause.
OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'firstprivate' clause.
OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'lastprivate' clause.
OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'shared' clause.
OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'reduction' clause.
OMPClause *ActOnOpenMPReductionClause(
ArrayRef<Expr *> VarList, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
CXXScopeSpec &ReductionIdScopeSpec,
const DeclarationNameInfo &ReductionId,
ArrayRef<Expr *> UnresolvedReductions = llvm::None);
/// Called on well-formed 'task_reduction' clause.
OMPClause *ActOnOpenMPTaskReductionClause(
ArrayRef<Expr *> VarList, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
CXXScopeSpec &ReductionIdScopeSpec,
const DeclarationNameInfo &ReductionId,
ArrayRef<Expr *> UnresolvedReductions = llvm::None);
/// Called on well-formed 'in_reduction' clause.
OMPClause *ActOnOpenMPInReductionClause(
ArrayRef<Expr *> VarList, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
CXXScopeSpec &ReductionIdScopeSpec,
const DeclarationNameInfo &ReductionId,
ArrayRef<Expr *> UnresolvedReductions = llvm::None);
/// Called on well-formed 'linear' clause.
OMPClause *
ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
SourceLocation StartLoc, SourceLocation LParenLoc,
OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
SourceLocation ColonLoc, SourceLocation EndLoc);
/// Called on well-formed 'aligned' clause.
OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
Expr *Alignment,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation ColonLoc,
SourceLocation EndLoc);
/// Called on well-formed 'copyin' clause.
OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'copyprivate' clause.
OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'flush' pseudo clause.
OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'depend' clause.
OMPClause *
ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'device' clause.
OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'map' clause.
OMPClause *
ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
ArrayRef<SourceLocation> MapTypeModifiersLoc,
CXXScopeSpec &MapperIdScopeSpec,
DeclarationNameInfo &MapperId,
OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
SourceLocation MapLoc, SourceLocation ColonLoc,
ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
ArrayRef<Expr *> UnresolvedMappers = llvm::None);
/// Called on well-formed 'num_teams' clause.
OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'thread_limit' clause.
OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'priority' clause.
OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'dist_schedule' clause.
OMPClause *ActOnOpenMPDistScheduleClause(
OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
SourceLocation CommaLoc, SourceLocation EndLoc);
/// Called on well-formed 'defaultmap' clause.
OMPClause *ActOnOpenMPDefaultmapClause(
OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
SourceLocation KindLoc, SourceLocation EndLoc);
/// Called on well-formed 'to' clause.
OMPClause *
ActOnOpenMPToClause(ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec,
DeclarationNameInfo &MapperId,
const OMPVarListLocTy &Locs,
ArrayRef<Expr *> UnresolvedMappers = llvm::None);
/// Called on well-formed 'from' clause.
OMPClause *ActOnOpenMPFromClause(
ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec,
DeclarationNameInfo &MapperId, const OMPVarListLocTy &Locs,
ArrayRef<Expr *> UnresolvedMappers = llvm::None);
/// Called on well-formed 'use_device_ptr' clause.
OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
const OMPVarListLocTy &Locs);
/// Called on well-formed 'is_device_ptr' clause.
OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
const OMPVarListLocTy &Locs);
/// Called on well-formed 'nontemporal' clause.
OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// The kind of conversion being performed.
enum CheckedConversionKind {
/// An implicit conversion.
CCK_ImplicitConversion,
/// A C-style cast.
CCK_CStyleCast,
/// A functional-style cast.
CCK_FunctionalCast,
/// A cast other than a C-style cast.
CCK_OtherCast,
/// A conversion for an operand of a builtin overloaded operator.
CCK_ForBuiltinOverloadedOp
};
static bool isCast(CheckedConversionKind CCK) {
return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast ||
CCK == CCK_OtherCast;
}
/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
/// cast. If there is already an implicit cast, merge into the existing one.
/// If isLvalue, the result of the cast is an lvalue.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
ExprValueKind VK = VK_RValue,
const CXXCastPath *BasePath = nullptr,
CheckedConversionKind CCK
= CCK_ImplicitConversion);
/// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
/// to the conversion from scalar type ScalarTy to the Boolean type.
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
/// IgnoredValueConversions - Given that an expression's result is
/// syntactically ignored, perform any conversions that are
/// required.
ExprResult IgnoredValueConversions(Expr *E);
// UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
// functions and arrays to their respective pointers (C99 6.3.2.1).
ExprResult UsualUnaryConversions(Expr *E);
/// CallExprUnaryConversions - a special case of an unary conversion
/// performed on a function designator of a call expression.
ExprResult CallExprUnaryConversions(Expr *E);
// DefaultFunctionArrayConversion - converts functions and arrays
// to their respective pointers (C99 6.3.2.1).
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
// DefaultFunctionArrayLvalueConversion - converts functions and
// arrays to their respective pointers and performs the
// lvalue-to-rvalue conversion.
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
bool Diagnose = true);
// DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
// the operand. This is DefaultFunctionArrayLvalueConversion,
// except that it assumes the operand isn't of function or array
// type.
ExprResult DefaultLvalueConversion(Expr *E);
// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
// do not have a prototype. Integer promotions are performed on each
// argument, and arguments that have type float are promoted to double.
ExprResult DefaultArgumentPromotion(Expr *E);
/// If \p E is a prvalue denoting an unmaterialized temporary, materialize
/// it as an xvalue. In C++98, the result will still be a prvalue, because
/// we don't have xvalues there.
ExprResult TemporaryMaterializationConversion(Expr *E);
// Used for emitting the right warning by DefaultVariadicArgumentPromotion
enum VariadicCallType {
VariadicFunction,
VariadicBlock,
VariadicMethod,
VariadicConstructor,
VariadicDoesNotApply
};
VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
const FunctionProtoType *Proto,
Expr *Fn);
// Used for determining in which context a type is allowed to be passed to a
// vararg function.
enum VarArgKind {
VAK_Valid,
VAK_ValidInCXX11,
VAK_Undefined,
VAK_MSVCUndefined,
VAK_Invalid
};
// Determines which VarArgKind fits an expression.
VarArgKind isValidVarArgType(const QualType &Ty);
/// Check to see if the given expression is a valid argument to a variadic
/// function, issuing a diagnostic if not.
void checkVariadicArgument(const Expr *E, VariadicCallType CT);
/// Check to see if a given expression could have '.c_str()' called on it.
bool hasCStrMethod(const Expr *E);
/// GatherArgumentsForCall - Collector argument expressions for various
/// form of call prototypes.
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
const FunctionProtoType *Proto,
unsigned FirstParam, ArrayRef<Expr *> Args,
SmallVectorImpl<Expr *> &AllArgs,
VariadicCallType CallType = VariadicDoesNotApply,
bool AllowExplicit = false,
bool IsListInitialization = false);
// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
// will create a runtime trap if the resulting type is not a POD type.
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
FunctionDecl *FDecl);
/// Context in which we're performing a usual arithmetic conversion.
enum ArithConvKind {
/// An arithmetic operation.
ACK_Arithmetic,
/// A bitwise operation.
ACK_BitwiseOp,
/// A comparison.
ACK_Comparison,
/// A conditional (?:) operator.
ACK_Conditional,
/// A compound assignment expression.
ACK_CompAssign,
};
// UsualArithmeticConversions - performs the UsualUnaryConversions on it's
// operands and then handles various conversions that are common to binary
// operators (C99 6.3.1.8). If both operands aren't arithmetic, this
// routine returns the first non-arithmetic type found. The client is
// responsible for emitting appropriate error diagnostics.
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc, ArithConvKind ACK);
/// AssignConvertType - All of the 'assignment' semantic checks return this
/// enum to indicate whether the assignment was allowed. These checks are
/// done for simple assignments, as well as initialization, return from
/// function, argument passing, etc. The query is phrased in terms of a
/// source and destination type.
enum AssignConvertType {
/// Compatible - the types are compatible according to the standard.
Compatible,
/// PointerToInt - The assignment converts a pointer to an int, which we
/// accept as an extension.
PointerToInt,
/// IntToPointer - The assignment converts an int to a pointer, which we
/// accept as an extension.
IntToPointer,
/// FunctionVoidPointer - The assignment is between a function pointer and
/// void*, which the standard doesn't allow, but we accept as an extension.
FunctionVoidPointer,
/// IncompatiblePointer - The assignment is between two pointers types that
/// are not compatible, but we accept them as an extension.
IncompatiblePointer,
/// IncompatiblePointerSign - The assignment is between two pointers types
/// which point to integers which have a different sign, but are otherwise
/// identical. This is a subset of the above, but broken out because it's by
/// far the most common case of incompatible pointers.
IncompatiblePointerSign,
/// CompatiblePointerDiscardsQualifiers - The assignment discards
/// c/v/r qualifiers, which we accept as an extension.
CompatiblePointerDiscardsQualifiers,
/// IncompatiblePointerDiscardsQualifiers - The assignment
/// discards qualifiers that we don't permit to be discarded,
/// like address spaces.
IncompatiblePointerDiscardsQualifiers,
/// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
/// changes address spaces in nested pointer types which is not allowed.
/// For instance, converting __private int ** to __generic int ** is
/// illegal even though __private could be converted to __generic.
IncompatibleNestedPointerAddressSpaceMismatch,
/// IncompatibleNestedPointerQualifiers - The assignment is between two
/// nested pointer types, and the qualifiers other than the first two
/// levels differ e.g. char ** -> const char **, but we accept them as an
/// extension.
IncompatibleNestedPointerQualifiers,
/// IncompatibleVectors - The assignment is between two vector types that
/// have the same size, which we accept as an extension.
IncompatibleVectors,
/// IntToBlockPointer - The assignment converts an int to a block
/// pointer. We disallow this.
IntToBlockPointer,
/// IncompatibleBlockPointer - The assignment is between two block
/// pointers types that are not compatible.
IncompatibleBlockPointer,
/// IncompatibleObjCQualifiedId - The assignment is between a qualified
/// id type and something else (that is incompatible with it). For example,
/// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
IncompatibleObjCQualifiedId,
/// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
/// object with __weak qualifier.
IncompatibleObjCWeakRef,
/// Incompatible - We reject this conversion outright, it is invalid to
/// represent it in the AST.
Incompatible
};
/// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
/// assignment conversion type specified by ConvTy. This returns true if the
/// conversion was invalid or false if the conversion was accepted.
bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
SourceLocation Loc,
QualType DstType, QualType SrcType,
Expr *SrcExpr, AssignmentAction Action,
bool *Complained = nullptr);
/// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
/// enum. If AllowMask is true, then we also allow the complement of a valid
/// value, to be used as a mask.
bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
bool AllowMask) const;
/// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
/// integer not in the range of enum values.
void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
Expr *SrcExpr);
/// CheckAssignmentConstraints - Perform type checking for assignment,
/// argument passing, variable initialization, and function return values.
/// C99 6.5.16.
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
QualType LHSType,
QualType RHSType);
/// Check assignment constraints and optionally prepare for a conversion of
/// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
/// is true.
AssignConvertType CheckAssignmentConstraints(QualType LHSType,
ExprResult &RHS,
CastKind &Kind,
bool ConvertRHS = true);
/// Check assignment constraints for an assignment of RHS to LHSType.
///
/// \param LHSType The destination type for the assignment.
/// \param RHS The source expression for the assignment.
/// \param Diagnose If \c true, diagnostics may be produced when checking
/// for assignability. If a diagnostic is produced, \p RHS will be
/// set to ExprError(). Note that this function may still return
/// without producing a diagnostic, even for an invalid assignment.
/// \param DiagnoseCFAudited If \c true, the target is a function parameter
/// in an audited Core Foundation API and does not need to be checked
/// for ARC retain issues.
/// \param ConvertRHS If \c true, \p RHS will be updated to model the
/// conversions necessary to perform the assignment. If \c false,
/// \p Diagnose must also be \c false.
AssignConvertType CheckSingleAssignmentConstraints(
QualType LHSType, ExprResult &RHS, bool Diagnose = true,
bool DiagnoseCFAudited = false, bool ConvertRHS = true);
// If the lhs type is a transparent union, check whether we
// can initialize the transparent union with the given expression.
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
ExprResult &RHS);
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
AssignmentAction Action,
bool AllowExplicit = false);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
AssignmentAction Action,
bool AllowExplicit,
ImplicitConversionSequence& ICS);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
const ImplicitConversionSequence& ICS,
AssignmentAction Action,
CheckedConversionKind CCK
= CCK_ImplicitConversion);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
const StandardConversionSequence& SCS,
AssignmentAction Action,
CheckedConversionKind CCK);
ExprResult PerformQualificationConversion(
Expr *E, QualType Ty, ExprValueKind VK = VK_RValue,
CheckedConversionKind CCK = CCK_ImplicitConversion);
/// the following "Check" methods will return a valid/converted QualType
/// or a null QualType (indicating an error diagnostic was issued).
/// type checking binary operators (subroutines of CreateBuiltinBinOp).
QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
ExprResult &RHS);
QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
ExprResult &RHS);
QualType CheckPointerToMemberOperands( // C++ 5.5
ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
SourceLocation OpLoc, bool isIndirect);
QualType CheckMultiplyDivideOperands( // C99 6.5.5
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
bool IsDivide);
QualType CheckRemainderOperands( // C99 6.5.5
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
bool IsCompAssign = false);
QualType CheckAdditionOperands( // C99 6.5.6
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
QualType CheckSubtractionOperands( // C99 6.5.6
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
QualType* CompLHSTy = nullptr);
QualType CheckShiftOperands( // C99 6.5.7
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc, bool IsCompAssign = false);
void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
QualType CheckCompareOperands( // C99 6.5.8/9
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc);
QualType CheckBitwiseOperands( // C99 6.5.[10...12]
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc);
QualType CheckLogicalOperands( // C99 6.5.[13,14]
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc);
// CheckAssignmentOperands is used for both simple and compound assignment.
// For simple assignment, pass both expressions and a null converted type.
// For compound assignment, pass both expressions and the converted type.
QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
UnaryOperatorKind Opcode, Expr *Op);
ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
BinaryOperatorKind Opcode,
Expr *LHS, Expr *RHS);
ExprResult checkPseudoObjectRValue(Expr *E);
Expr *recreateSyntacticForm(PseudoObjectExpr *E);
QualType CheckConditionalOperands( // C99 6.5.15
ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
QualType CXXCheckConditionalOperands( // C++ 5.16
ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
bool ConvertArgs = true);
QualType FindCompositePointerType(SourceLocation Loc,
ExprResult &E1, ExprResult &E2,
bool ConvertArgs = true) {
Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
QualType Composite =
FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
E1 = E1Tmp;
E2 = E2Tmp;
return Composite;
}
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
SourceLocation QuestionLoc);
bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
SourceLocation QuestionLoc);
void DiagnoseAlwaysNonNullPointer(Expr *E,
Expr::NullPointerConstantKind NullType,
bool IsEqual, SourceRange Range);
/// type checking for vector binary operators.
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc, bool IsCompAssign,
bool AllowBothBool, bool AllowBoolConversion);
QualType GetSignedVectorType(QualType V);
QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc,
BinaryOperatorKind Opc);
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc);
bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
bool isLaxVectorConversion(QualType srcType, QualType destType);
/// type checking declaration initializers (C99 6.7.8)
bool CheckForConstantInitializer(Expr *e, QualType t);
// type checking C++ declaration initializers (C++ [dcl.init]).
/// ReferenceCompareResult - Expresses the result of comparing two
/// types (cv1 T1 and cv2 T2) to determine their compatibility for the
/// purposes of initialization by reference (C++ [dcl.init.ref]p4).
enum ReferenceCompareResult {
/// Ref_Incompatible - The two types are incompatible, so direct
/// reference binding is not possible.
Ref_Incompatible = 0,
/// Ref_Related - The two types are reference-related, which means
/// that their unqualified forms (T1 and T2) are either the same
/// or T1 is a base class of T2.
Ref_Related,
/// Ref_Compatible - The two types are reference-compatible.
Ref_Compatible
};
// Fake up a scoped enumeration that still contextually converts to bool.
struct ReferenceConversionsScope {
/// The conversions that would be performed on an lvalue of type T2 when
/// binding a reference of type T1 to it, as determined when evaluating
/// whether T1 is reference-compatible with T2.
enum ReferenceConversions {
Qualification = 0x1,
Function = 0x2,
DerivedToBase = 0x4,
ObjC = 0x8,
ObjCLifetime = 0x10,
LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)
};
};
using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
ReferenceCompareResult
CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
ReferenceConversions *Conv = nullptr);
ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
Expr *CastExpr, CastKind &CastKind,
ExprValueKind &VK, CXXCastPath &Path);
/// Force an expression with unknown-type to an expression of the
/// given type.
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
/// Type-check an expression that's being passed to an
/// __unknown_anytype parameter.
ExprResult checkUnknownAnyArg(SourceLocation callLoc,
Expr *result, QualType ¶mType);
// CheckVectorCast - check type constraints for vectors.
// Since vectors are an extension, there are no C standard reference for this.
// We allow casting between vectors and integer datatypes of the same size.
// returns true if the cast is invalid
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
CastKind &Kind);
/// Prepare `SplattedExpr` for a vector splat operation, adding
/// implicit casts if necessary.
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
// CheckExtVectorCast - check type constraints for extended vectors.
// Since vectors are an extension, there are no C standard reference for this.
// We allow casting between vectors and integer datatypes of the same size,
// or vectors and the element type of that vector.
// returns the cast expr
ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
CastKind &Kind);
ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
SourceLocation LParenLoc,
Expr *CastExpr,
SourceLocation RParenLoc);
enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
/// Checks for invalid conversions and casts between
/// retainable pointers and other pointer kinds for ARC and Weak.
ARCConversionResult CheckObjCConversion(SourceRange castRange,
QualType castType, Expr *&op,
CheckedConversionKind CCK,
bool Diagnose = true,
bool DiagnoseCFAudited = false,
BinaryOperatorKind Opc = BO_PtrMemD
);
Expr *stripARCUnbridgedCast(Expr *e);
void diagnoseARCUnbridgedCast(Expr *e);
bool CheckObjCARCUnavailableWeakConversion(QualType castType,
QualType ExprType);
/// checkRetainCycles - Check whether an Objective-C message send
/// might create an obvious retain cycle.
void checkRetainCycles(ObjCMessageExpr *msg);
void checkRetainCycles(Expr *receiver, Expr *argument);
void checkRetainCycles(VarDecl *Var, Expr *Init);
/// checkUnsafeAssigns - Check whether +1 expr is being assigned
/// to weak/__unsafe_unretained type.
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
/// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
/// to weak/__unsafe_unretained expression.
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
/// CheckMessageArgumentTypes - Check types in an Obj-C message send.
/// \param Method - May be null.
/// \param [out] ReturnType - The return type of the send.
/// \return true iff there were any incompatible types.
bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType,
MultiExprArg Args, Selector Sel,
ArrayRef<SourceLocation> SelectorLocs,
ObjCMethodDecl *Method, bool isClassMessage,
bool isSuperMessage, SourceLocation lbrac,
SourceLocation rbrac, SourceRange RecRange,
QualType &ReturnType, ExprValueKind &VK);
/// Determine the result of a message send expression based on
/// the type of the receiver, the method expected to receive the message,
/// and the form of the message send.
QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType,
ObjCMethodDecl *Method, bool isClassMessage,
bool isSuperMessage);
/// If the given expression involves a message send to a method
/// with a related result type, emit a note describing what happened.
void EmitRelatedResultTypeNote(const Expr *E);
/// Given that we had incompatible pointer types in a return
/// statement, check whether we're in a method with a related result
/// type, and if so, emit a note describing what happened.
void EmitRelatedResultTypeNoteForReturn(QualType destType);
class ConditionResult {
Decl *ConditionVar;
FullExprArg Condition;
bool Invalid;
bool HasKnownValue;
bool KnownValue;
friend class Sema;
ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
bool IsConstexpr)
: ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
HasKnownValue(IsConstexpr && Condition.get() &&
!Condition.get()->isValueDependent()),
KnownValue(HasKnownValue &&
!!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
explicit ConditionResult(bool Invalid)
: ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
HasKnownValue(false), KnownValue(false) {}
public:
ConditionResult() : ConditionResult(false) {}
bool isInvalid() const { return Invalid; }
std::pair<VarDecl *, Expr *> get() const {
return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
Condition.get());
}
llvm::Optional<bool> getKnownValue() const {
if (!HasKnownValue)
return None;
return KnownValue;
}
};
static ConditionResult ConditionError() { return ConditionResult(true); }
enum class ConditionKind {
Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
Switch ///< An integral condition for a 'switch' statement.
};
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
Expr *SubExpr, ConditionKind CK);
ConditionResult ActOnConditionVariable(Decl *ConditionVar,
SourceLocation StmtLoc,
ConditionKind CK);
DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
ExprResult CheckConditionVariable(VarDecl *ConditionVar,
SourceLocation StmtLoc,
ConditionKind CK);
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
/// CheckBooleanCondition - Diagnose problems involving the use of
/// the given expression as a boolean condition (e.g. in an if
/// statement). Also performs the standard function and array
/// decays, possibly changing the input variable.
///
/// \param Loc - A location associated with the condition, e.g. the
/// 'if' keyword.
/// \return true iff there were any errors
ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
bool IsConstexpr = false);
/// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
/// found in an explicit(bool) specifier.
ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
/// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
/// Returns true if the explicit specifier is now resolved.
bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
/// DiagnoseAssignmentAsCondition - Given that an expression is
/// being used as a boolean condition, warn if it's an assignment.
void DiagnoseAssignmentAsCondition(Expr *E);
/// Redundant parentheses over an equality comparison can indicate
/// that the user intended an assignment used as condition.
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
/// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
/// the specified width and sign. If an overflow occurs, detect it and emit
/// the specified diagnostic.
void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
unsigned NewWidth, bool NewSign,
SourceLocation Loc, unsigned DiagID);
/// Checks that the Objective-C declaration is declared in the global scope.
/// Emits an error and marks the declaration as invalid if it's not declared
/// in the global scope.
bool CheckObjCDeclScope(Decl *D);
/// Abstract base class used for diagnosing integer constant
/// expression violations.
class VerifyICEDiagnoser {
public:
bool Suppress;
VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
virtual ~VerifyICEDiagnoser() { }
};
/// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
/// and reports the appropriate diagnostics. Returns false on success.
/// Can optionally return the value of the expression.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
VerifyICEDiagnoser &Diagnoser,
bool AllowFold = true);
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
unsigned DiagID,
bool AllowFold = true);
ExprResult VerifyIntegerConstantExpression(Expr *E,
llvm::APSInt *Result = nullptr);
/// VerifyBitField - verifies that a bit field expression is an ICE and has
/// the correct width, and that the field type is valid.
/// Returns false on success.
/// Can optionally return whether the bit-field is of width 0
ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
QualType FieldTy, bool IsMsStruct,
Expr *BitWidth, bool *ZeroWidth = nullptr);
private:
unsigned ForceCUDAHostDeviceDepth = 0;
public:
/// Increments our count of the number of times we've seen a pragma forcing
/// functions to be __host__ __device__. So long as this count is greater
/// than zero, all functions encountered will be __host__ __device__.
void PushForceCUDAHostDevice();
/// Decrements our count of the number of times we've seen a pragma forcing
/// functions to be __host__ __device__. Returns false if the count is 0
/// before incrementing, so you can emit an error.
bool PopForceCUDAHostDevice();
/// Diagnostics that are emitted only if we discover that the given function
/// must be codegen'ed. Because handling these correctly adds overhead to
/// compilation, this is currently only enabled for CUDA compilations.
llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
std::vector<PartialDiagnosticAt>>
DeviceDeferredDiags;
/// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
/// key in a hashtable, both the FD and location are hashed.
struct FunctionDeclAndLoc {
CanonicalDeclPtr<FunctionDecl> FD;
SourceLocation Loc;
};
/// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
/// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
/// same deferred diag twice.
llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
/// An inverse call graph, mapping known-emitted functions to one of their
/// known-emitted callers (plus the location of the call).
///
/// Functions that we can tell a priori must be emitted aren't added to this
/// map.
llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
/* Caller = */ FunctionDeclAndLoc>
DeviceKnownEmittedFns;
/// A partial call graph maintained during CUDA/OpenMP device code compilation
/// to support deferred diagnostics.
///
/// Functions are only added here if, at the time they're considered, they are
/// not known-emitted. As soon as we discover that a function is
/// known-emitted, we remove it and everything it transitively calls from this
/// set and add those functions to DeviceKnownEmittedFns.
llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
/* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
SourceLocation>>
DeviceCallGraph;
/// Diagnostic builder for CUDA/OpenMP devices errors which may or may not be
/// deferred.
///
/// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
/// which are not allowed to appear inside __device__ functions and are
/// allowed to appear in __host__ __device__ functions only if the host+device
/// function is never codegen'ed.
///
/// To handle this, we use the notion of "deferred diagnostics", where we
/// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
///
/// This class lets you emit either a regular diagnostic, a deferred
/// diagnostic, or no diagnostic at all, according to an argument you pass to
/// its constructor, thus simplifying the process of creating these "maybe
/// deferred" diagnostics.
class DeviceDiagBuilder {
public:
enum Kind {
/// Emit no diagnostics.
K_Nop,
/// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
K_Immediate,
/// Emit the diagnostic immediately, and, if it's a warning or error, also
/// emit a call stack showing how this function can be reached by an a
/// priori known-emitted function.
K_ImmediateWithCallStack,
/// Create a deferred diagnostic, which is emitted only if the function
/// it's attached to is codegen'ed. Also emit a call stack as with
/// K_ImmediateWithCallStack.
K_Deferred
};
DeviceDiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
FunctionDecl *Fn, Sema &S);
DeviceDiagBuilder(DeviceDiagBuilder &&D);
DeviceDiagBuilder(const DeviceDiagBuilder &) = default;
~DeviceDiagBuilder();
/// Convertible to bool: True if we immediately emitted an error, false if
/// we didn't emit an error or we created a deferred error.
///
/// Example usage:
///
/// if (DeviceDiagBuilder(...) << foo << bar)
/// return ExprError();
///
/// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
/// want to use these instead of creating a DeviceDiagBuilder yourself.
operator bool() const { return ImmediateDiag.hasValue(); }
template <typename T>
friend const DeviceDiagBuilder &operator<<(const DeviceDiagBuilder &Diag,
const T &Value) {
if (Diag.ImmediateDiag.hasValue())
*Diag.ImmediateDiag << Value;
else if (Diag.PartialDiagId.hasValue())
Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
<< Value;
return Diag;
}
private:
Sema &S;
SourceLocation Loc;
unsigned DiagID;
FunctionDecl *Fn;
bool ShowCallStack;
// Invariant: At most one of these Optionals has a value.
// FIXME: Switch these to a Variant once that exists.
llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
llvm::Optional<unsigned> PartialDiagId;
};
/// Indicate that this function (and thus everything it transtively calls)
/// will be codegen'ed, and emit any deferred diagnostics on this function and
/// its (transitive) callees.
void markKnownEmitted(
Sema &S, FunctionDecl *OrigCaller, FunctionDecl *OrigCallee,
SourceLocation OrigLoc,
const llvm::function_ref<bool(Sema &, FunctionDecl *)> IsKnownEmitted);
/// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
/// is "used as device code".
///
/// - If CurContext is a __host__ function, does not emit any diagnostics.
/// - If CurContext is a __device__ or __global__ function, emits the
/// diagnostics immediately.
/// - If CurContext is a __host__ __device__ function and we are compiling for
/// the device, creates a diagnostic which is emitted if and when we realize
/// that the function will be codegen'ed.
///
/// Example usage:
///
/// // Variable-length arrays are not allowed in CUDA device code.
/// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
/// return ExprError();
/// // Otherwise, continue parsing as normal.
DeviceDiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
/// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
/// is "used as host code".
///
/// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
DeviceDiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
/// Creates a DeviceDiagBuilder that emits the diagnostic if the current
/// context is "used as device code".
///
/// - If CurContext is a `declare target` function or it is known that the
/// function is emitted for the device, emits the diagnostics immediately.
/// - If CurContext is a non-`declare target` function and we are compiling
/// for the device, creates a diagnostic which is emitted if and when we
/// realize that the function will be codegen'ed.
///
/// Example usage:
///
/// // Variable-length arrays are not allowed in NVPTX device code.
/// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported))
/// return ExprError();
/// // Otherwise, continue parsing as normal.
DeviceDiagBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID);
/// Creates a DeviceDiagBuilder that emits the diagnostic if the current
/// context is "used as host code".
///
/// - If CurContext is a `declare target` function or it is known that the
/// function is emitted for the host, emits the diagnostics immediately.
/// - If CurContext is a non-host function, just ignore it.
///
/// Example usage:
///
/// // Variable-length arrays are not allowed in NVPTX device code.
/// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported))
/// return ExprError();
/// // Otherwise, continue parsing as normal.
DeviceDiagBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID);
DeviceDiagBuilder targetDiag(SourceLocation Loc, unsigned DiagID);
enum CUDAFunctionTarget {
CFT_Device,
CFT_Global,
CFT_Host,
CFT_HostDevice,
CFT_InvalidTarget
};
/// Determines whether the given function is a CUDA device/host/kernel/etc.
/// function.
///
/// Use this rather than examining the function's attributes yourself -- you
/// will get it wrong. Returns CFT_Host if D is null.
CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
bool IgnoreImplicitHDAttr = false);
CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs);
/// Gets the CUDA target for the current context.
CUDAFunctionTarget CurrentCUDATarget() {
return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
}
// CUDA function call preference. Must be ordered numerically from
// worst to best.
enum CUDAFunctionPreference {
CFP_Never, // Invalid caller/callee combination.
CFP_WrongSide, // Calls from host-device to host or device
// function that do not match current compilation
// mode.
CFP_HostDevice, // Any calls to host/device functions.
CFP_SameSide, // Calls from host-device to host or device
// function matching current compilation mode.
CFP_Native, // host-to-host or device-to-device calls.
};
/// Identifies relative preference of a given Caller/Callee
/// combination, based on their host/device attributes.
/// \param Caller function which needs address of \p Callee.
/// nullptr in case of global context.
/// \param Callee target function
///
/// \returns preference value for particular Caller/Callee combination.
CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
const FunctionDecl *Callee);
/// Determines whether Caller may invoke Callee, based on their CUDA
/// host/device attributes. Returns false if the call is not allowed.
///
/// Note: Will return true for CFP_WrongSide calls. These may appear in
/// semantically correct CUDA programs, but only if they're never codegen'ed.
bool IsAllowedCUDACall(const FunctionDecl *Caller,
const FunctionDecl *Callee) {
return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
}
/// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
/// depending on FD and the current compilation settings.
void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
const LookupResult &Previous);
public:
/// Check whether we're allowed to call Callee from the current context.
///
/// - If the call is never allowed in a semantically-correct program
/// (CFP_Never), emits an error and returns false.
///
/// - If the call is allowed in semantically-correct programs, but only if
/// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
/// be emitted if and when the caller is codegen'ed, and returns true.
///
/// Will only create deferred diagnostics for a given SourceLocation once,
/// so you can safely call this multiple times without generating duplicate
/// deferred errors.
///
/// - Otherwise, returns true without emitting any diagnostics.
bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
/// Set __device__ or __host__ __device__ attributes on the given lambda
/// operator() method.
///
/// CUDA lambdas declared inside __device__ or __global__ functions inherit
/// the __device__ attribute. Similarly, lambdas inside __host__ __device__
/// functions become __host__ __device__ themselves.
void CUDASetLambdaAttrs(CXXMethodDecl *Method);
/// Finds a function in \p Matches with highest calling priority
/// from \p Caller context and erases all functions with lower
/// calling priority.
void EraseUnwantedCUDAMatches(
const FunctionDecl *Caller,
SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
/// Given a implicit special member, infer its CUDA target from the
/// calls it needs to make to underlying base/field special members.
/// \param ClassDecl the class for which the member is being created.
/// \param CSM the kind of special member.
/// \param MemberDecl the special member itself.
/// \param ConstRHS true if this is a copy operation with a const object on
/// its RHS.
/// \param Diagnose true if this call should emit diagnostics.
/// \return true if there was an error inferring.
/// The result of this call is implicit CUDA target attribute(s) attached to
/// the member declaration.
bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
CXXSpecialMember CSM,
CXXMethodDecl *MemberDecl,
bool ConstRHS,
bool Diagnose);
/// \return true if \p CD can be considered empty according to CUDA
/// (E.2.3.1 in CUDA 7.5 Programming guide).
bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
// \brief Checks that initializers of \p Var satisfy CUDA restrictions. In
// case of error emits appropriate diagnostic and invalidates \p Var.
//
// \details CUDA allows only empty constructors as initializers for global
// variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
// __shared__ variables whether they are local or not (they all are implicitly
// static in CUDA). One exception is that CUDA allows constant initializers
// for __constant__ and __device__ variables.
void checkAllowedCUDAInitializer(VarDecl *VD);
/// Check whether NewFD is a valid overload for CUDA. Emits
/// diagnostics and invalidates NewFD if not.
void checkCUDATargetOverload(FunctionDecl *NewFD,
const LookupResult &Previous);
/// Copies target attributes from the template TD to the function FD.
void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
/// Returns the name of the launch configuration function. This is the name
/// of the function that will be called to configure kernel call, with the
/// parameters specified via <<<>>>.
std::string getCudaConfigureFuncName() const;
/// \name Code completion
//@{
/// Describes the context in which code completion occurs.
enum ParserCompletionContext {
/// Code completion occurs at top-level or namespace context.
PCC_Namespace,
/// Code completion occurs within a class, struct, or union.
PCC_Class,
/// Code completion occurs within an Objective-C interface, protocol,
/// or category.
PCC_ObjCInterface,
/// Code completion occurs within an Objective-C implementation or
/// category implementation
PCC_ObjCImplementation,
/// Code completion occurs within the list of instance variables
/// in an Objective-C interface, protocol, category, or implementation.
PCC_ObjCInstanceVariableList,
/// Code completion occurs following one or more template
/// headers.
PCC_Template,
/// Code completion occurs following one or more template
/// headers within a class.
PCC_MemberTemplate,
/// Code completion occurs within an expression.
PCC_Expression,
/// Code completion occurs within a statement, which may
/// also be an expression or a declaration.
PCC_Statement,
/// Code completion occurs at the beginning of the
/// initialization statement (or expression) in a for loop.
PCC_ForInit,
/// Code completion occurs within the condition of an if,
/// while, switch, or for statement.
PCC_Condition,
/// Code completion occurs within the body of a function on a
/// recovery path, where we do not have a specific handle on our position
/// in the grammar.
PCC_RecoveryInFunction,
/// Code completion occurs where only a type is permitted.
PCC_Type,
/// Code completion occurs in a parenthesized expression, which
/// might also be a type cast.
PCC_ParenthesizedExpression,
/// Code completion occurs within a sequence of declaration
/// specifiers within a function, method, or block.
PCC_LocalDeclarationSpecifiers
};
void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
void CodeCompleteOrdinaryName(Scope *S,
ParserCompletionContext CompletionContext);
void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
bool AllowNonIdentifiers,
bool AllowNestedNameSpecifiers);
struct CodeCompleteExpressionData;
void CodeCompleteExpression(Scope *S,
const CodeCompleteExpressionData &Data);
void CodeCompleteExpression(Scope *S, QualType PreferredType,
bool IsParenthesized = false);
void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase,
SourceLocation OpLoc, bool IsArrow,
bool IsBaseExprStatement,
QualType PreferredType);
void CodeCompletePostfixExpression(Scope *S, ExprResult LHS,
QualType PreferredType);
void CodeCompleteTag(Scope *S, unsigned TagSpec);
void CodeCompleteTypeQualifiers(DeclSpec &DS);
void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
const VirtSpecifiers *VS = nullptr);
void CodeCompleteBracketDeclarator(Scope *S);
void CodeCompleteCase(Scope *S);
/// Reports signatures for a call to CodeCompleteConsumer and returns the
/// preferred type for the current argument. Returned type can be null.
QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args,
SourceLocation OpenParLoc);
QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type,
SourceLocation Loc,
ArrayRef<Expr *> Args,
SourceLocation OpenParLoc);
QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl,
CXXScopeSpec SS,
ParsedType TemplateTypeTy,
ArrayRef<Expr *> ArgExprs,
IdentifierInfo *II,
SourceLocation OpenParLoc);
void CodeCompleteInitializer(Scope *S, Decl *D);
void CodeCompleteAfterIf(Scope *S);
void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext,
bool IsUsingDeclaration, QualType BaseType,
QualType PreferredType);
void CodeCompleteUsing(Scope *S);
void CodeCompleteUsingDirective(Scope *S);
void CodeCompleteNamespaceDecl(Scope *S);
void CodeCompleteNamespaceAliasDecl(Scope *S);
void CodeCompleteOperatorName(Scope *S);
void CodeCompleteConstructorInitializer(
Decl *Constructor,
ArrayRef<CXXCtorInitializer *> Initializers);
void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
bool AfterAmpersand);
void CodeCompleteObjCAtDirective(Scope *S);
void CodeCompleteObjCAtVisibility(Scope *S);
void CodeCompleteObjCAtStatement(Scope *S);
void CodeCompleteObjCAtExpression(Scope *S);
void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
void CodeCompleteObjCPropertyGetter(Scope *S);
void CodeCompleteObjCPropertySetter(Scope *S);
void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
bool IsParameter);
void CodeCompleteObjCMessageReceiver(Scope *S);
void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression);
void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression,
bool IsSuper = false);
void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression,
ObjCInterfaceDecl *Super = nullptr);
void CodeCompleteObjCForCollection(Scope *S,
DeclGroupPtrTy IterationVar);
void CodeCompleteObjCSelector(Scope *S,
ArrayRef<IdentifierInfo *> SelIdents);
void CodeCompleteObjCProtocolReferences(
ArrayRef<IdentifierLocPair> Protocols);
void CodeCompleteObjCProtocolDecl(Scope *S);
void CodeCompleteObjCInterfaceDecl(Scope *S);
void CodeCompleteObjCSuperclass(Scope *S,
IdentifierInfo *ClassName,
SourceLocation ClassNameLoc);
void CodeCompleteObjCImplementationDecl(Scope *S);
void CodeCompleteObjCInterfaceCategory(Scope *S,
IdentifierInfo *ClassName,
SourceLocation ClassNameLoc);
void CodeCompleteObjCImplementationCategory(Scope *S,
IdentifierInfo *ClassName,
SourceLocation ClassNameLoc);
void CodeCompleteObjCPropertyDefinition(Scope *S);
void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
IdentifierInfo *PropertyName);
void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
ParsedType ReturnType);
void CodeCompleteObjCMethodDeclSelector(Scope *S,
bool IsInstanceMethod,
bool AtParameterName,
ParsedType ReturnType,
ArrayRef<IdentifierInfo *> SelIdents);
void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
SourceLocation ClassNameLoc,
bool IsBaseExprStatement);
void CodeCompletePreprocessorDirective(bool InConditional);
void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
void CodeCompletePreprocessorMacroName(bool IsDefinition);
void CodeCompletePreprocessorExpression();
void CodeCompletePreprocessorMacroArgument(Scope *S,
IdentifierInfo *Macro,
MacroInfo *MacroInfo,
unsigned Argument);
void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled);
void CodeCompleteNaturalLanguage();
void CodeCompleteAvailabilityPlatformName();
void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
CodeCompletionTUInfo &CCTUInfo,
SmallVectorImpl<CodeCompletionResult> &Results);
//@}
//===--------------------------------------------------------------------===//
// Extra semantic analysis beyond the C type system
public:
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
unsigned ByteNo) const;
private:
void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
const ArraySubscriptExpr *ASE=nullptr,
bool AllowOnePastEnd=true, bool IndexNegated=false);
void CheckArrayAccess(const Expr *E);
// Used to grab the relevant information from a FormatAttr and a
// FunctionDeclaration.
struct FormatStringInfo {
unsigned FormatIdx;
unsigned FirstDataArg;
bool HasVAListArg;
};
static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
FormatStringInfo *FSI);
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
const FunctionProtoType *Proto);
bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
ArrayRef<const Expr *> Args);
bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
const FunctionProtoType *Proto);
bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
void CheckConstructorCall(FunctionDecl *FDecl,
ArrayRef<const Expr *> Args,
const FunctionProtoType *Proto,
SourceLocation Loc);
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
const Expr *ThisArg, ArrayRef<const Expr *> Args,
bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
VariadicCallType CallType);
bool CheckObjCString(Expr *Arg);
ExprResult CheckOSLogFormatStringArg(Expr *Arg);
ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
unsigned BuiltinID, CallExpr *TheCall);
void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
unsigned MaxWidth);
bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall);
bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall);
bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
bool SemaBuiltinVSX(CallExpr *TheCall);
bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
public:
// Used by C++ template instantiation.
ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc);
private:
bool SemaBuiltinPrefetch(CallExpr *TheCall);
bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
bool SemaBuiltinAssume(CallExpr *TheCall);
bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
bool SemaBuiltinLongjmp(CallExpr *TheCall);
bool SemaBuiltinSetjmp(CallExpr *TheCall);
ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
AtomicExpr::AtomicOp Op);
ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
bool IsDelete);
bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
llvm::APSInt &Result);
bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
int High, bool RangeIsError = true);
bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
unsigned Multiple);
bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum);
bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum);
bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum);
bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
int ArgNum, unsigned ExpectedFieldNum,
bool AllowName);
bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall);
public:
enum FormatStringType {
FST_Scanf,
FST_Printf,
FST_NSString,
FST_Strftime,
FST_Strfmon,
FST_Kprintf,
FST_FreeBSDKPrintf,
FST_OSTrace,
FST_OSLog,
FST_Unknown
};
static FormatStringType GetFormatStringType(const FormatAttr *Format);
bool FormatStringHasSArg(const StringLiteral *FExpr);
static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
private:
bool CheckFormatArguments(const FormatAttr *Format,
ArrayRef<const Expr *> Args,
bool IsCXXMember,
VariadicCallType CallType,
SourceLocation Loc, SourceRange Range,
llvm::SmallBitVector &CheckedVarArgs);
bool CheckFormatArguments(ArrayRef<const Expr *> Args,
bool HasVAListArg, unsigned format_idx,
unsigned firstDataArg, FormatStringType Type,
VariadicCallType CallType,
SourceLocation Loc, SourceRange range,
llvm::SmallBitVector &CheckedVarArgs);
void CheckAbsoluteValueFunction(const CallExpr *Call,
const FunctionDecl *FDecl);
void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
void CheckMemaccessArguments(const CallExpr *Call,
unsigned BId,
IdentifierInfo *FnName);
void CheckStrlcpycatArguments(const CallExpr *Call,
IdentifierInfo *FnName);
void CheckStrncatArguments(const CallExpr *Call,
IdentifierInfo *FnName);
void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
SourceLocation ReturnLoc,
bool isObjCMethod = false,
const AttrVec *Attrs = nullptr,
const FunctionDecl *FD = nullptr);
public:
void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS);
private:
void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
void CheckForIntOverflow(Expr *E);
void CheckUnsequencedOperations(Expr *E);
/// Perform semantic checks on a completed expression. This will either
/// be a full-expression or a default argument expression.
void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
bool IsConstexpr = false);
void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
Expr *Init);
/// Check if there is a field shadowing.
void CheckShadowInheritedFields(const SourceLocation &Loc,
DeclarationName FieldName,
const CXXRecordDecl *RD,
bool DeclIsField = true);
/// Check if the given expression contains 'break' or 'continue'
/// statement that produces control flow different from GCC.
void CheckBreakContinueBinding(Expr *E);
/// Check whether receiver is mutable ObjC container which
/// attempts to add itself into the container
void CheckObjCCircularContainer(ObjCMessageExpr *Message);
void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
bool DeleteWasArrayForm);
public:
/// Register a magic integral constant to be used as a type tag.
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
uint64_t MagicValue, QualType Type,
bool LayoutCompatible, bool MustBeNull);
struct TypeTagData {
TypeTagData() {}
TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
Type(Type), LayoutCompatible(LayoutCompatible),
MustBeNull(MustBeNull)
{}
QualType Type;
/// If true, \c Type should be compared with other expression's types for
/// layout-compatibility.
unsigned LayoutCompatible : 1;
unsigned MustBeNull : 1;
};
/// A pair of ArgumentKind identifier and magic value. This uniquely
/// identifies the magic value.
typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
private:
/// A map from magic value to type information.
std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
TypeTagForDatatypeMagicValues;
/// Peform checks on a call of a function with argument_with_type_tag
/// or pointer_with_type_tag attributes.
void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
const ArrayRef<const Expr *> ExprArgs,
SourceLocation CallSiteLoc);
/// Check if we are taking the address of a packed field
/// as this may be a problem if the pointer value is dereferenced.
void CheckAddressOfPackedMember(Expr *rhs);
/// The parser's current scope.
///
/// The parser maintains this state here.
Scope *CurScope;
mutable IdentifierInfo *Ident_super;
mutable IdentifierInfo *Ident___float128;
/// Nullability type specifiers.
IdentifierInfo *Ident__Nonnull = nullptr;
IdentifierInfo *Ident__Nullable = nullptr;
IdentifierInfo *Ident__Null_unspecified = nullptr;
IdentifierInfo *Ident_NSError = nullptr;
/// The handler for the FileChanged preprocessor events.
///
/// Used for diagnostics that implement custom semantic analysis for #include
/// directives, like -Wpragma-pack.
sema::SemaPPCallbacks *SemaPPCallbackHandler;
protected:
friend class Parser;
friend class InitializationSequence;
friend class ASTReader;
friend class ASTDeclReader;
friend class ASTWriter;
public:
/// Retrieve the keyword associated
IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
/// The struct behind the CFErrorRef pointer.
RecordDecl *CFError = nullptr;
bool isCFError(RecordDecl *D);
/// Retrieve the identifier "NSError".
IdentifierInfo *getNSErrorIdent();
/// Retrieve the parser's current scope.
///
/// This routine must only be used when it is certain that semantic analysis
/// and the parser are in precisely the same context, which is not the case
/// when, e.g., we are performing any kind of template instantiation.
/// Therefore, the only safe places to use this scope are in the parser
/// itself and in routines directly invoked from the parser and *never* from
/// template substitution or instantiation.
Scope *getCurScope() const { return CurScope; }
void incrementMSManglingNumber() const {
return CurScope->incrementMSManglingNumber();
}
IdentifierInfo *getSuperIdentifier() const;
IdentifierInfo *getFloat128Identifier() const;
Decl *getObjCDeclContext() const;
DeclContext *getCurLexicalContext() const {
return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
}
const DeclContext *getCurObjCLexicalContext() const {
const DeclContext *DC = getCurLexicalContext();
// A category implicitly has the attribute of the interface.
if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
DC = CatD->getClassInterface();
return DC;
}
/// To be used for checking whether the arguments being passed to
/// function exceeds the number of parameters expected for it.
static bool TooManyArguments(size_t NumParams, size_t NumArgs,
bool PartialOverloading = false) {
// We check whether we're just after a comma in code-completion.
if (NumArgs > 0 && PartialOverloading)
return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
return NumArgs > NumParams;
}
// Emitting members of dllexported classes is delayed until the class
// (including field initializers) is fully parsed.
SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions;
private:
int ParsingClassDepth = 0;
class SavePendingParsedClassStateRAII {
public:
SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
~SavePendingParsedClassStateRAII() {
assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
"there shouldn't be any pending delayed exception spec checks");
assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
"there shouldn't be any pending delayed exception spec checks");
swapSavedState();
}
private:
Sema &S;
decltype(DelayedOverridingExceptionSpecChecks)
SavedOverridingExceptionSpecChecks;
decltype(DelayedEquivalentExceptionSpecChecks)
SavedEquivalentExceptionSpecChecks;
void swapSavedState() {
SavedOverridingExceptionSpecChecks.swap(
S.DelayedOverridingExceptionSpecChecks);
SavedEquivalentExceptionSpecChecks.swap(
S.DelayedEquivalentExceptionSpecChecks);
}
};
/// Helper class that collects misaligned member designations and
/// their location info for delayed diagnostics.
struct MisalignedMember {
Expr *E;
RecordDecl *RD;
ValueDecl *MD;
CharUnits Alignment;
MisalignedMember() : E(), RD(), MD(), Alignment() {}
MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
CharUnits Alignment)
: E(E), RD(RD), MD(MD), Alignment(Alignment) {}
explicit MisalignedMember(Expr *E)
: MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
bool operator==(const MisalignedMember &m) { return this->E == m.E; }
};
/// Small set of gathered accesses to potentially misaligned members
/// due to the packed attribute.
SmallVector<MisalignedMember, 4> MisalignedMembers;
/// Adds an expression to the set of gathered misaligned members.
void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
CharUnits Alignment);
public:
/// Diagnoses the current set of gathered accesses. This typically
/// happens at full expression level. The set is cleared after emitting the
/// diagnostics.
void DiagnoseMisalignedMembers();
/// This function checks if the expression is in the sef of potentially
/// misaligned members and it is converted to some pointer type T with lower
/// or equal alignment requirements. If so it removes it. This is used when
/// we do not want to diagnose such misaligned access (e.g. in conversions to
/// void*).
void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
/// This function calls Action when it determines that E designates a
/// misaligned member due to the packed attribute. This is used to emit
/// local diagnostics like in reference binding.
void RefersToMemberWithReducedAlignment(
Expr *E,
llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
Action);
/// Describes the reason a calling convention specification was ignored, used
/// for diagnostics.
enum class CallingConventionIgnoredReason {
ForThisTarget = 0,
VariadicFunction,
ConstructorDestructor,
BuiltinFunction
};
};
/// RAII object that enters a new expression evaluation context.
class EnterExpressionEvaluationContext {
Sema &Actions;
bool Entered = true;
public:
EnterExpressionEvaluationContext(
Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
Decl *LambdaContextDecl = nullptr,
Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
Sema::ExpressionEvaluationContextRecord::EK_Other,
bool ShouldEnter = true)
: Actions(Actions), Entered(ShouldEnter) {
if (Entered)
Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
ExprContext);
}
EnterExpressionEvaluationContext(
Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
Sema::ReuseLambdaContextDecl_t,
Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
Sema::ExpressionEvaluationContextRecord::EK_Other)
: Actions(Actions) {
Actions.PushExpressionEvaluationContext(
NewContext, Sema::ReuseLambdaContextDecl, ExprContext);
}
enum InitListTag { InitList };
EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
bool ShouldEnter = true)
: Actions(Actions), Entered(false) {
// In C++11 onwards, narrowing checks are performed on the contents of
// braced-init-lists, even when they occur within unevaluated operands.
// Therefore we still need to instantiate constexpr functions used in such
// a context.
if (ShouldEnter && Actions.isUnevaluatedContext() &&
Actions.getLangOpts().CPlusPlus11) {
Actions.PushExpressionEvaluationContext(
Sema::ExpressionEvaluationContext::UnevaluatedList);
Entered = true;
}
}
~EnterExpressionEvaluationContext() {
if (Entered)
Actions.PopExpressionEvaluationContext();
}
};
DeductionFailureInfo
MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
sema::TemplateDeductionInfo &Info);
/// Contains a late templated function.
/// Will be parsed at the end of the translation unit, used by Sema & Parser.
struct LateParsedTemplate {
CachedTokens Toks;
/// The template function declaration to be late parsed.
Decl *D;
};
} // end namespace clang
namespace llvm {
// Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
// SourceLocation.
template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
static FunctionDeclAndLoc getEmptyKey() {
return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
}
static FunctionDeclAndLoc getTombstoneKey() {
return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
}
static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
FDL.Loc.getRawEncoding());
}
static bool isEqual(const FunctionDeclAndLoc &LHS,
const FunctionDeclAndLoc &RHS) {
return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
}
};
} // namespace llvm
#endif
|
DRB013-nowait-orig-yes.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.
*/
/*
This example is extracted from a paper:
Ma etc. Symbolic Analysis of Concurrency Errors in OpenMP Programs, ICPP 2013
Some threads may finish the for loop early and execute errors = dt[9]+1
while another thread may still be simultaneously executing
the for worksharing region by writing to d[9], causing data races.
Data race pair: a[i]@72:7 vs. a[9]@75:13.
*/
#include <stdio.h>
int main()
{
int i,error;
int len = 1000;
int a[len], b=5;
#pragma omp parallel for private(i )
for (i=0; i<len; i++)
a[i]= i;
{
#pragma omp parallel for private(i )
for(i = 0; i < len; i++)
a[i] = b + a[i]*5;
error = a[9] + 1;
}
printf ("error = %d\n", error);
return 0;
}
|
openmp1.c | #include <math.h>
#include <omp.h>
void
cholesky(double *A, double *L, int n)
{
for (int j = 0; j < n; j++) {
#pragma omp parallel for
for (int i = j; i < n; i++) {
double s = 0;
for (int k = 0; k < j; k++) {
s += L[i * n + k] * L[j * n + k];
}
L[i * n + j] = (i == j) ? sqrt(A[i * n + i] - s)
: (1.0 / L[j * n + j] * (A[i * n + j] - s));
}
}
}
|
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] = 4;
tile_size[1] = 4;
tile_size[2] = 4;
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,2);t1++) {
lbp=max(ceild(t1,2),ceild(4*t1-Nt+3,4));
ubp=min(floord(Nt+Nz-4,4),floord(2*t1+Nz-1,4));
#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(t1-1,2)),ceild(4*t2-Nz,4));t3<=min(min(min(floord(4*t2+Ny,4),floord(Nt+Ny-4,4)),floord(2*t1+Ny+1,4)),floord(4*t1-4*t2+Nz+Ny-1,4));t3++) {
for (t4=max(max(max(0,ceild(t1-1023,1024)),ceild(4*t2-Nz-2044,2048)),ceild(4*t3-Ny-2044,2048));t4<=min(min(min(min(floord(4*t2+Nx,2048),floord(4*t3+Nx,2048)),floord(Nt+Nx-4,2048)),floord(2*t1+Nx+1,2048)),floord(4*t1-4*t2+Nz+Nx-1,2048));t4++) {
for (t5=max(max(max(max(max(0,2*t1),4*t1-4*t2+1),4*t2-Nz+2),4*t3-Ny+2),2048*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,2*t1+3),4*t2+2),4*t3+2),2048*t4+2046),4*t1-4*t2+Nz+1);t5++) {
for (t6=max(max(4*t2,t5+1),-4*t1+4*t2+2*t5-3);t6<=min(min(4*t2+3,-4*t1+4*t2+2*t5),t5+Nz-2);t6++) {
for (t7=max(4*t3,t5+1);t7<=min(4*t3+3,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;
}
|
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] = 16;
tile_size[1] = 16;
tile_size[2] = 24;
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,8);t1++) {
lbp=max(ceild(t1,2),ceild(16*t1-Nt+3,16));
ubp=min(floord(Nt+Nz-4,16),floord(8*t1+Nz+5,16));
#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(t1-2,3)),ceild(16*t2-Nz-20,24));t3<=min(min(min(floord(Nt+Ny-4,24),floord(8*t1+Ny+13,24)),floord(16*t2+Ny+12,24)),floord(16*t1-16*t2+Nz+Ny+11,24));t3++) {
for (t4=max(max(max(0,ceild(t1-255,256)),ceild(16*t2-Nz-2044,2048)),ceild(24*t3-Ny-2044,2048));t4<=min(min(min(min(floord(Nt+Nx-4,2048),floord(8*t1+Nx+13,2048)),floord(16*t2+Nx+12,2048)),floord(24*t3+Nx+20,2048)),floord(16*t1-16*t2+Nz+Nx+11,2048));t4++) {
for (t5=max(max(max(max(max(0,8*t1),16*t1-16*t2+1),16*t2-Nz+2),24*t3-Ny+2),2048*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,8*t1+15),16*t2+14),24*t3+22),2048*t4+2046),16*t1-16*t2+Nz+13);t5++) {
for (t6=max(max(16*t2,t5+1),-16*t1+16*t2+2*t5-15);t6<=min(min(16*t2+15,-16*t1+16*t2+2*t5),t5+Nz-2);t6++) {
for (t7=max(24*t3,t5+1);t7<=min(24*t3+23,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;
}
|
ms_non.c | /*=======================
M A N D E L B R O T
=======================*/
// Implementation Based on Rosetta Code Example
// 1) Draws Mandelbrot set for Fc(z)=z*z +c using
// Mandelbrot algorithm (boolean escape time).
// 2) Technique of creating ppm file is based on
// the code of Claudio Rocchini. http://en.
// wikipedia.org/wiki/Image:Color_complex_plot
// .jpg. Create 24 bit color graphic file,
// portable pixmap file = PPM, see http://en.
// wikipedia.org/wiki/Portable_pixmap to see
// the file use external application (graphic
// viewer).
// Inclusions
#include <math.h>
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Definitions
#define SHOW_TIMES 1
// Image Structure Definition
typedef struct {
unsigned char color[3];
} image;
// Main
int main ( int argc, char *argv[ ] ) {
const unsigned int maxColorComponentValue = 255; // Color Component - 24-bit RGB Coded from 0 to 255
const unsigned int iMax = 200; // Maximum Number of Iterations
unsigned int i = 0; // Iteration Number
unsigned int iX = 0; // Screen (Integer) X Coordinate
unsigned int iY = 0; // Screen (Integer) Y Coordinate
unsigned int iXMax = 2048; // Generated Image Width
unsigned int iYMax = 2048; // Generated Image Height
unsigned int cores = 0; // Number of Cores Utilized in Parallel
unsigned int display = 0; // Argument to Display Debug Text
unsigned int size = 0; // Size of Generated Image in Pixels
unsigned int thisPixelNum = 0; // Iterator for Tracking Pixel Number
const double cXMin = -1.5; // Generated View Window X Minimum
const double cXMax = 0.5; // Generated View Window X Maximum
const double cYMin = -1.0; // Generated View Window Y Minimum
const double cYMax = 1.0; // Generated View Window Y Maximum
const double escapeRadius = 2.0; // Bail-Out Value - Radius of Circle
double cX = 0.0; // World (Double) X Coordinate
double cY = 0.0; // World (Double) Y Coordinate
double escapeRadius2 = 4.0; // Square of EscapeRadius
double pixelWidth = 0.0; // Determination of Relative Pixel Width from Window and Size Parameters
double pixelHeight = 0.0; // Determination of Relative Pixel Height from Window and Size Parameters
double zX = 0.0; // Z = Zx + Zy * i; Z0 = 0
double zY = 0.0; // (see just above)
double zX2 = 0.0; // Square of Zx
double zY2 = 0.0; // Square of Zy
char *filename = NULL; // Filename to Save Mandelbrot Image
char *comment = "# "; // Dynamic File Header Comment
image *fractal; // Image Being Built
FILE *fp = NULL; // A File
double jobStart = 0.0; // Timer for Program Start
double mandelbrotStart = 0.0; // Timer for Mandelbrot Fractal Generation Start
double mandelbrotEnd = 0.0; // Timer for Mandelbrot Fractal Generation End
double writeStart = 0.0; // Timer for Image Write Out Start
double writeEnd = 0.0; // Timer for Image Write Out End
double jobEnd = 0.0; // Timer for Program Completion
double mandelbrotTime = 0.0; // Program Time in Color Search Operation Phase
double writeTime = 0.0; // Program Time in Image Write Phase
double addTime = 0.0; // Additional Overhead Time
double totalTime = 0.0; // Total Program Time
// Set Job Start Timer
jobStart = omp_get_wtime( );
// Display Usage Instructions If Argument Count Incorrect
if( argc != 5 ) {
printf( "\nUsage: %s <output> <x/y> <cores> <display>\n", argv[0] );
printf( " Output - a .ppm image to output with the fractal.\n" );
printf( " X/Y - width and height of image in pixels.\n" );
printf( " Cores - number of cores to utilize for parallel operation.\n" );
printf( " Display - 1 displays debug text, 0 just displays time values for raw data tables.\n\n" );
return 1;
}
// Parse Input Arguments
filename = argv[1];
iXMax = atoi( argv[2] );
iYMax = iXMax;
cores = atoi( argv[3] );
display = atoi( argv[4] );
// Intro Text
if( display ) {
printf( "\n = = = Mandelbrot Set Generator = = = \n\n" );
}
// Early Calculations
size = iXMax * iYMax; // Determination of Size from
pixelWidth = ( cXMax - cXMin ) / iXMax; // Determination of Relative Pixel Width from Window and Size Parameters
pixelHeight = ( cYMax - cYMin ) / iYMax; // Determination of Relative Pixel Height from Window and Size Parameters
escapeRadius2 = escapeRadius * escapeRadius; // Calculate Square of EscapeRadius.
// OpenMP Initial Tasks and Tests
omp_set_num_threads( cores );
if( display ) {
printf( "Using %d Cores of Maximum %d Cores Available\nTesting - Report\n", cores, omp_get_max_threads( ) );
#pragma omp parallel for
for( size_t i = 0; i < (size_t)omp_get_num_threads( ); i++ ) {
printf( " Core %d of %d Reporting!\n", omp_get_thread_num( ), omp_get_num_threads( ) );
}
}
// Allocate Storage for Image Colors
fractal = malloc( size * sizeof( *fractal ) );
// Compute Fractal Image
if( display ) {
printf( "\nGenerating Mandelbrot Set...\n" );
}
mandelbrotStart = omp_get_wtime( );
#pragma omp parallel for shared( fractal, iXMax, iYMax, pixelHeight, pixelWidth, escapeRadius2 ) \
private( i, iX, iY, cX, cY, zX, zY, zX2, zY2, thisPixelNum ) schedule(guided,100)
//default( none ) \
schedule( dynamic )
for( iY = 0; iY < iYMax; iY++ )
{
cY = cYMin + iY * pixelHeight;
if( fabs( cY ) < ( pixelHeight / 2 ) )
{
cY = 0.0; // Main Antenna
}
for( iX = 0; iX < iXMax; iX++ )
{
cX = cXMin + iX * pixelWidth;
// Initial Value of Orbit - Critical Point Z = 0
zX = 0.0;
zY = 0.0;
zX2 = zX * zX;
zY2 = zY * zY;
for( i = 0; ( i < iMax ) && ( ( zX2 + zY2 ) < escapeRadius2 ); i++ )
{
zY = 2 * zX * zY + cY;
zX = zX2 - zY2 + cX;
zX2 = zX * zX;
zY2 = zY * zY;
};
// Save Pixel Color
thisPixelNum = iY * iYMax + iX; // Where is this pixel in the image?
if( i == iMax )
{ // Color for Interior of Mandelbrot Set - Dark Gray
fractal[thisPixelNum].color[0] = 37; // Red Component
fractal[thisPixelNum].color[1] = 37; // Green Component
fractal[thisPixelNum].color[2] = 37; // Blue Component
} else { // Color for Exterior of Mandelbrot Set - Blue
fractal[thisPixelNum].color[0] = 0; // Red Component
fractal[thisPixelNum].color[1] = 0; // Green Component
fractal[thisPixelNum].color[2] = 255; // Blue Component
} // End If
} // End iX For
} // End iY For
mandelbrotEnd = omp_get_wtime( );
// Image File Write Phase
if( display ) {
printf( "Writing File Out...\n" );
}
writeStart = omp_get_wtime( );
// Create New File - give it a name and open it in binary mode.
fp = fopen( filename, "wb" ); // b - Binary Mode
// Write ASCII Header to the File
fprintf( fp, "P6\n %s\n %d\n %d\n %d\n", comment, iXMax, iYMax, maxColorComponentValue );
// Image File Write Out - must be done serially.
for( iY = 0; iY < iYMax; iY++ ) {
for( iX = 0; iX < iXMax; iX++ ) {
thisPixelNum = iY * iYMax + iX;
// Write Color to the File
fwrite( fractal[thisPixelNum].color, 1, 3, fp );
}
}
fclose( fp );
writeEnd = omp_get_wtime( );
// Final Tasks
free( fractal );
if( display ) {
printf( "Operation Complete!\n\n" );
}
// Timing Calculations
jobEnd = omp_get_wtime( );
mandelbrotTime = mandelbrotEnd - mandelbrotStart;
writeTime = writeEnd - writeStart;
totalTime = jobEnd - jobStart;
addTime = totalTime - mandelbrotTime - writeTime;
// Timing Display
if( SHOW_TIMES ) {
if( display ) {
printf( " === Timing Data ===\n Mandelbrot:\t\t" );
}
printf( "%0.9lf ", mandelbrotTime );
if( display ) {
printf( "\n Image Write:\t\t" );
printf( "%0.9lf\n", writeTime );
printf( " Ending Overhead:\t" );
printf( "%0.9lf\n", addTime );
printf( " Total Job Time:\t" );
printf( "%0.9lf\n\n", totalTime );
}
}
return 0;
}
|
Scalar3DUpdater1.h | /*
###################################################################################
#
# BCMTools
#
# Copyright (c) 2011-2014 Institute of Industrial Science, The University of Tokyo.
# All rights reserved.
#
# Copyright (c) 2012-2016 Advanced Institute for Computational Science (AICS), RIKEN.
# All rights reserved.
#
# Copyright (c) 2017 Research Institute for Information Technology (RIIT), Kyushu University.
# All rights reserved.
#
###################################################################################
*/
///
/// @file Scalar3DUpdater1.h
/// @brief スカラデータクラス仮想セルアップデータ
///
#ifndef SCALAR_3D_UPDATER1_H
#define SCALAR_3D_UPDATER1_H
#include "BCMTools.h"
#include "VCUpdater.h"
#include "Scalar3D.h"
#include "real.h"
#ifdef BCMT_NAMESPACE
namespace BCMT_NAMESPACE {
#endif
/// スカラデータクラス仮想セルアップデータ.
///
/// @note 通信と補間の順序は,簡単のためL→L+1もL+1→Lも,
/// 送信元で補間を行なってから通信.
///
/// @todo 補間計算部分をFortranで実装
///
///
template <typename T>
class Scalar3DUpdater1 : public VCUpdater {
private:
Scalar3D<T>* dataClass; ///< 仮想セル同期対象データクラス
T* sendBuffer[NUM_FACE][NUM_SUBFACE]; ///< 送信データバッファテーブル
T* recvBuffer[NUM_FACE][NUM_SUBFACE]; ///< 受信データバッファテーブル
Scalar3D<T>* neighborDataClass[NUM_FACE][NUM_SUBFACE]; ///< 隣接データクラステーブル
int nx, ny, nz, vc;
public:
/// コンストラクタ.
///
/// @param[in] neighborInfo 隣接情報配列
/// @param[in] comm MPIコミュニケータ(ディフォルトMPI::COMM_WORLD)
///
Scalar3DUpdater1(const NeighborInfo* neighborInfo,
const MPI::Comm& comm = MPI::COMM_WORLD)
: VCUpdater(neighborInfo, comm) {
clearCommBufferPointer();
clearNeighbor();
}
/// デストラクタ.
~Scalar3DUpdater1() {}
/// 仮想セル同期対象データクラスを登録.
void setDataClass(DataClass* dc) {
dataClass = dynamic_cast<Scalar3D<T>*>(dc);
nx = dataClass->getSizeX();
ny = dataClass->getSizeY();
nz = dataClass->getSizeZ();
vc = dataClass->getVCSize();
}
/// 仮想セル同期データ送信に必要なバッファサイズを取得(同レベル間).
size_t getSendBufferByteSize(Face face) const {
return sizeof(T) * getCommBufferSize(face);
}
/// 仮想セル同期データ送信に必要なバッファサイズを取得(レベルL+1→L).
size_t getSendBufferByteSizeF2C(Face face, Subface subface) const {
return sizeof(T) * getCommBufferSize(face) / 4;
}
/// 仮想セル同期データ送信に必要なバッファサイズを取得(レベルL→L+1).
size_t getSendBufferByteSizeC2F(Face face, Subface subface) const {
return sizeof(T) * getCommBufferSize(face);
}
/// 仮想セル同期データ受信に必要なバッファサイズを取得(同レベル間).
size_t getRecvBufferByteSize(Face face) const {
return sizeof(T) * getCommBufferSize(face);
}
/// 仮想セル同期データ受信に必要なバッファサイズを取得(レベルL+1→L).
size_t getRecvBufferByteSizeF2C(Face face, Subface subface) const {
return sizeof(T) * getCommBufferSize(face) / 4;
}
/// 仮想セル同期データ受信に必要なバッファサイズを取得(レベルL→L+1).
size_t getRecvBufferByteSizeC2F(Face face, Subface subface) const {
return sizeof(T) * getCommBufferSize(face);
}
/// 仮想セル同期データ送信バッファ用PointerSetterオブジェクトを取得.
PointerSetterBase* getSendBufferPointerSetter(Face face, Subface subface) {
return new PointerSetter<T>(&sendBuffer[face][subface]);
}
/// 仮想セル同期データ受信バッファ用PointerSetterオブジェクトを取得.
PointerSetterBase* getRecvBufferPointerSetter(Face face, Subface subface) {
return new PointerSetter<T>(&recvBuffer[face][subface]);
}
public:
/// 同並列計算ノード内の隣接データクラスを登録.
void setNeighbor(Face face, Subface subface, DataClass* dataClass) {
neighborDataClass[face][subface] = dynamic_cast<Scalar3D<T>*>(dataClass);
}
/// 隣接データクラスの登録解除.
void clearNeighbor(Face face, Subface subface) {
neighborDataClass[face][subface] = 0;
}
/// 隣接データクラスの登録解除.
void clearNeighbor() {
for (int i = 0; i < NUM_FACE; ++i) {
for (int j = 0; j < NUM_SUBFACE; ++j) {
clearNeighbor(Face(i), Subface(j));
}
}
}
/// 通信バッファテーブルのエントリをクリア.
void clearCommBufferPointer(Face face, Subface subface) {
sendBuffer[face][subface] = recvBuffer[face][subface] = 0;
}
/// 通信バッファテーブルをクリア.
void clearCommBufferPointer() {
for (int i = 0; i < NUM_FACE; ++i) {
for (int j = 0; j < NUM_SUBFACE; ++j) {
clearCommBufferPointer(Face(i), Subface(j));
}
}
}
private:
/// 通信バッファサイズを計算.
size_t getCommBufferSize(Face face) const {
switch (face) {
case X_M:
case X_P:
return ny * nz * vc;
case Y_M:
case Y_P:
return nz * nx * vc;
case Z_M:
case Z_P:
return nx * ny * vc;
default:
Exit(EX_FAILURE);
}
/* NOTREACHED */
}
/// レベルL+1→Lの線形補間 (細f(i,j,k) → 粗c(I,J,K)).
T interpolateF2C(const Scalar3D<T>& f, int I, int J, int K) {
int i = 2 * I;
int j = 2 * J;
int k = 2 * K;
return 0.125 * (f(i,j,k) + f(i+1,j,k) + f(i,j+1,k) + f(i+1,j+1,k)
+ f(i,j,k+1) + f(i+1,j,k+1) + f(i,j+1,k+1) + f(i+1,j+1,k+1));
}
/// レベルL+1→Lの線形補間 (細f(i,j,k) → 粗c(I,J,K)).
T interpolateF2C(const T* fData, const Index3DS& fIndex, int I, int J, int K) {
int i = 2 * I;
int j = 2 * J;
int k = 2 * K;
return 0.125 * (fData[fIndex(i ,j ,k )] + fData[fIndex(i+1,j ,k )]
+ fData[fIndex(i ,j+1,k )] + fData[fIndex(i+1,j+1,k )]
+ fData[fIndex(i ,j ,k+1)] + fData[fIndex(i+1,j ,k+1)]
+ fData[fIndex(i ,j+1,k+1)] + fData[fIndex(i+1,j+1,k+1)]);
}
/// レベルL→L+1の線形補間 (粗c(I,J,K) → 細f(i,j,k)).
T interpolateC2F(const Scalar3D<T>& c, int i, int j, int k) {
int I, J, K;
double r, s, t;
linearInterpolate(i, nx, I, r);
linearInterpolate(j, ny, J, s);
linearInterpolate(k, nz, K, t);
return (1.0-t)*(
(1.0-s)*( (1.0-r)*c(I ,J ,K ) + r*c(I+1,J ,K ) )
+ s*( (1.0-r)*c(I ,J+1,K ) + r*c(I+1,J+1,K ) )
)
+t*(
(1.0-s)*( (1.0-r)*c(I ,J ,K+1) + r*c(I+1,J ,K+1) )
+ s*( (1.0-r)*c(I ,J+1,K+1) + r*c(I+1,J+1,K+1) )
);
}
/// レベルL→L+1の線形補間 (粗c(I,J,K) → 細f(i,j,k)).
T interpolateC2F(const T* cData, const Index3DS& cIndex, int i, int j, int k) {
int I, J, K;
double r, s, t;
linearInterpolate(i, nx, I, r);
linearInterpolate(j, ny, J, s);
linearInterpolate(k, nz, K, t);
return (1.0-t)*(
(1.0-s)*( (1.0-r)*cData[cIndex(I ,J ,K )] + r*cData[cIndex(I+1,J ,K )] )
+ s*( (1.0-r)*cData[cIndex(I ,J+1,K )] + r*cData[cIndex(I+1,J+1,K )] )
)
+t*(
(1.0-s)*( (1.0-r)*cData[cIndex(I ,J ,K+1)] + r*cData[cIndex(I+1,J ,K+1)] )
+ s*( (1.0-r)*cData[cIndex(I ,J+1,K+1)] + r*cData[cIndex(I+1,J+1,K+1)] )
);
}
/// C2F補間における補間パラメータの計算.
///
/// @note 端点では,内挿ではなく外挿
///
void linearInterpolate(int i, int n, int& I, double& r) {
#if 1
I = std::min(std::max(i/2 - 1 + i%2, 0), n - 2);
r = -0.25 + 0.5 * i - double(I);
#else
if (i == 0) {
// 外挿
I = 0;
r = -0.25;
}
else if (i == 2*n-1) {
// 外挿
I = n - 2;
r = 1.25;
}
else if (i%2 == 0) {
I = i/2 - 1;
r = 0.75;
}
else {
I = i/2;
r = 0.25;
}
#endif
}
/*
/// 隣接データクラスから仮想セルデータをコピー(同レベル間).
void copyFromNeighbor(Face face);
/// 隣接データクラスから仮想セルデータをコピー(レベルL+1→L).
void copyFromNeighborF2C(Face face, Subface subface);
/// 隣接データクラスから仮想セルデータをコピー(レベルL→L+1).
void copyFromNeighborC2F(Face face, Subface subface);
/// 送信バッファに仮想セルデータをコピー(同レベル間).
void copyToCommBuffer(Face face);
/// 送信バッファに仮想セルデータをコピー(レベルL+1→L).
void copyToCommBufferF2C(Face face, Subface subface);
/// 送信バッファに仮想セルデータをコピー(レベルL→L+1).
void copyToCommBufferC2F(Face face, Subface subface);
/// 受信バッファから仮想セルデータをコピー(同レベル間).
void copyFromCommBuffer(Face face);
/// 受信バッファから仮想セルデータをコピー(レベルL+1→L).
void copyFromCommBufferF2C(Face face, Subface subface);
/// 受信バッファから仮想セルデータをコピー(レベルL→L+1).
void copyFromCommBufferC2F(Face face, Subface subface);
void copyFromNeighborF2C_0(int nx, int ny, int nz, int vc,
Face face, Subface subface,
const T* fData, Index3DS fIndex,
T* cData, Index3DS cIndex);
void copyFromNeighborC2F_0(int nx, int ny, int nz, int vc,
Face face, Subface subface,
const T* cData, Index3DS cIndex,
T* fData, Index3DS fIndex);
void copyToCommBufferC2F_0(int nx, int ny, int nz, int vc,
Face face, Subface subface,
const T* cData, Index3DS cIndex,
T* buffer);
void copyToCommBufferF2C_0(int nx, int ny, int nz, int vc,
Face face, Subface subface,
const T* fData, Index3DS fIndex,
T* buffer);
*/
/// 隣接データクラスから仮想セルデータをコピー(同レベル間).
void copyFromNeighbor(Face face)
{
Scalar3D<T>* dc = neighborDataClass[face][0];
if (!dc) return;
switch (face) {
case X_M:
dataClass->copyFromDataClass(-vc, 0, 0, dc->getSizeX()-vc, 0, 0, vc, ny, nz, dc);
break;
case X_P:
dataClass->copyFromDataClass(nx, 0, 0, 0, 0, 0, vc, ny, nz, dc);
break;
case Y_M:
dataClass->copyFromDataClass(0, -vc, 0, 0, dc->getSizeY()-vc, 0, nx, vc, nz, dc);
break;
case Y_P:
dataClass->copyFromDataClass(0, ny, 0, 0, 0, 0, nx, vc, nz, dc);
break;
case Z_M:
dataClass->copyFromDataClass(0, 0, -vc, 0, 0, dc->getSizeZ()-vc, nx, ny, vc, dc);
break;
case Z_P:
dataClass->copyFromDataClass(0, 0, nz, 0, 0, 0, nx, ny, vc, dc);
break;
default:
break;
}
}
/// 隣接データクラスから仮想セルデータをコピー(レベルL+1→L).
void copyFromNeighborF2C(Face face, Subface subface)
{
T* cData = dataClass->getData();
Index3DS cIndex = dataClass->getIndex();
Scalar3D<T>* f = neighborDataClass[face][subface];
T* fData = f->getData();
Index3DS fIndex = f->getIndex();
copyFromNeighborF2C_0(nx, ny, nz, vc, face, subface, fData, fIndex, cData, cIndex);
}
/// 隣接データクラスから仮想セルデータをコピー(レベルL→L+1).
void copyFromNeighborC2F(Face face, Subface subface)
{
T* fData = dataClass->getData();
Index3DS fIndex = dataClass->getIndex();
Scalar3D<T>* c = neighborDataClass[face][0];
T* cData = c->getData();
Index3DS cIndex = c->getIndex();
copyFromNeighborC2F_0(nx, ny, nz, vc, face, subface, cData, cIndex, fData, fIndex);
}
/// 送信バッファに仮想セルデータをコピー(同レベル間).
void copyToCommBuffer(Face face)
{
T* buffer = sendBuffer[face][0];
if (!buffer) return;
switch (face) {
case X_M:
dataClass->copyToBuffer(0, 0, 0, vc, ny, nz, buffer);
break;
case X_P:
dataClass->copyToBuffer(nx-vc, 0, 0, vc, ny, nz, buffer);
break;
case Y_M:
dataClass->copyToBuffer(0, 0, 0, nx, vc, nz, buffer);
break;
case Y_P:
dataClass->copyToBuffer(0, ny-vc, 0, nx, vc, nz, buffer);
break;
case Z_M:
dataClass->copyToBuffer(0, 0, 0, nx, ny, vc, buffer);
break;
case Z_P:
dataClass->copyToBuffer(0, 0, nz-vc, nx, ny, vc, buffer);
break;
default:
break;
}
}
/// 送信バッファに仮想セルデータをコピー(レベルL+1→L).
void copyToCommBufferF2C(Face face, Subface subface)
{
T* buffer = sendBuffer[face][0];
T* fData = dataClass->getData();
Index3DS fIndex = dataClass->getIndex();
copyToCommBufferF2C_0(nx, ny, nz, vc, face, subface, fData, fIndex, buffer);
}
/// 送信バッファに仮想セルデータをコピー(レベルL→L+1).
void copyToCommBufferC2F(Face face, Subface subface)
{
T* cData = dataClass->getData();
Index3DS cIndex = dataClass->getIndex();
T* buffer = sendBuffer[face][subface];
copyToCommBufferC2F_0(nx, ny, nz, vc, face, subface, cData, cIndex, buffer);
}
/// 受信バッファから仮想セルデータをコピー(同レベル間).
void copyFromCommBuffer(Face face)
{
T* buffer = recvBuffer[face][0];
if (!buffer) return;
switch (face) {
case X_M:
dataClass->copyFromBuffer(-vc, 0, 0, vc, ny, nz, buffer);
break;
case X_P:
dataClass->copyFromBuffer(nx, 0, 0, vc, ny, nz, buffer);
break;
case Y_M:
dataClass->copyFromBuffer(0, -vc, 0, nx, vc, nz, buffer);
break;
case Y_P:
dataClass->copyFromBuffer(0, ny, 0, nx, vc, nz, buffer);
break;
case Z_M:
dataClass->copyFromBuffer(0, 0, -vc, nx, ny, vc, buffer);
break;
case Z_P:
dataClass->copyFromBuffer(0, 0, nz, nx, ny, vc, buffer);
break;
default:
break;
}
}
/// 受信バッファから仮想セルデータをコピー(レベルL+1→L).
void copyFromCommBufferF2C(Face face, Subface subface)
{
T* buffer = recvBuffer[face][subface];
switch (face) {
case X_M:
{
int j0 = (ny/2) * subfaceOrigin0(subface);
int k0 = (nz/2) * subfaceOrigin1(subface);
dataClass->copyFromBuffer(-vc, j0, k0, vc, ny/2, nz/2, buffer);
break;
}
case X_P:
{
int j0 = (ny/2) * subfaceOrigin0(subface);
int k0 = (nz/2) * subfaceOrigin1(subface);
dataClass->copyFromBuffer(nx, j0, k0, vc, ny/2, nz/2, buffer);
break;
}
case Y_M:
{
int k0 = (nz/2) * subfaceOrigin0(subface);
int i0 = (nx/2) * subfaceOrigin1(subface);
dataClass->copyFromBuffer(i0, -vc, k0, nx/2, vc, nz/2, buffer);
break;
}
case Y_P:
{
int k0 = (nz/2) * subfaceOrigin0(subface);
int i0 = (nx/2) * subfaceOrigin1(subface);
dataClass->copyFromBuffer(i0, ny, k0, nx/2, vc, nz/2, buffer);
break;
}
case Z_M:
{
int i0 = (nx/2) * subfaceOrigin0(subface);
int j0 = (ny/2) * subfaceOrigin1(subface);
dataClass->copyFromBuffer(i0, j0, -vc, nx/2, ny/2, vc, buffer);
break;
}
case Z_P:
{
int i0 = (nx/2) * subfaceOrigin0(subface);
int j0 = (ny/2) * subfaceOrigin1(subface);
dataClass->copyFromBuffer(i0, j0, nz, nx/2, ny/2, vc, buffer);
break;
}
default:
break;
}
}
/// 受信バッファから仮想セルデータをコピー(レベルL→L+1).
void copyFromCommBufferC2F(Face face, Subface subface)
{
copyFromCommBuffer(face);
}
void copyFromNeighborF2C_0(int nx, int ny, int nz, int vc,
Face face, Subface subface,
const T* fData, Index3DS fIndex,
T* cData, Index3DS cIndex)
{
switch (face) {
case X_M:
{
int j0 = (ny/2) * subfaceOrigin0(subface);
int k0 = (nz/2) * subfaceOrigin1(subface);
#pragma omp parallel for collapse(3)
for (int k = 0; k < nz/2; k++) {
for (int j = 0; j < ny/2; j++) {
for (int i = 0; i < vc; i++) {
cData[cIndex(i-vc, j+j0, k+k0)] = interpolateF2C(fData, fIndex, i+nx/2-vc, j, k);
}
}
}
break;
}
case X_P:
{
int j0 = (ny/2) * subfaceOrigin0(subface);
int k0 = (nz/2) * subfaceOrigin1(subface);
#pragma omp parallel for collapse(3)
for (int k = 0; k < nz/2; k++) {
for (int j = 0; j < ny/2; j++) {
for (int i = 0; i < vc; i++) {
cData[cIndex(i+nx, j+j0, k+k0)] = interpolateF2C(fData, fIndex, i, j, k);
}
}
}
break;
}
case Y_M:
{
int k0 = (nz/2) * subfaceOrigin0(subface);
int i0 = (nx/2) * subfaceOrigin1(subface);
#pragma omp parallel for collapse(3)
for (int k = 0; k < nz/2; k++) {
for (int j = 0; j < vc; j++) {
for (int i = 0; i < nx/2; i++) {
cData[cIndex(i+i0, j-vc, k+k0)] = interpolateF2C(fData, fIndex, i, j+ny/2-vc, k);
}
}
}
break;
}
case Y_P:
{
int k0 = (nz/2) * subfaceOrigin0(subface);
int i0 = (nx/2) * subfaceOrigin1(subface);
#pragma omp parallel for collapse(3)
for (int k = 0; k < nz/2; k++) {
for (int j = 0; j < vc; j++) {
for (int i = 0; i < nx/2; i++) {
cData[cIndex(i+i0, j+ny, k+k0)] = interpolateF2C(fData, fIndex, i, j, k);
}
}
}
break;
}
case Z_M:
{
int i0 = (nx/2) * subfaceOrigin0(subface);
int j0 = (ny/2) * subfaceOrigin1(subface);
#pragma omp parallel for collapse(3)
for (int k = 0; k < vc; k++) {
for (int j = 0; j < ny/2; j++) {
for (int i = 0; i < nx/2; i++) {
cData[cIndex(i+i0, j+j0, k-vc)] = interpolateF2C(fData, fIndex, i, j, k+nz/2-vc);
}
}
}
break;
}
case Z_P:
{
int i0 = (nx/2) * subfaceOrigin0(subface);
int j0 = (ny/2) * subfaceOrigin1(subface);
#pragma omp parallel for collapse(3)
for (int k = 0; k < vc; k++) {
for (int j = 0; j < ny/2; j++) {
for (int i = 0; i < nx/2; i++) {
cData[cIndex(i+i0, j+j0, k+nz)] = interpolateF2C(fData, fIndex, i, j, k);
}
}
}
break;
}
default:
break;
}
}
void copyFromNeighborC2F_0(int nx, int ny, int nz, int vc,
Face face, Subface subface,
const T* cData, Index3DS cIndex,
T* fData, Index3DS fIndex)
{
switch (face) {
case X_M:
{
int J0 = ny * subfaceOrigin0(subface);
int K0 = nz * subfaceOrigin1(subface);
#pragma omp parallel for collapse(3)
for (int K = 0; K < nz; K++) {
for (int J = 0; J < ny; J++) {
for (int I = 0; I < vc; I++) {
fData[fIndex(I-vc, J, K)] = interpolateC2F(cData, cIndex, I+2*nx-vc, J+J0, K+K0);
}
}
}
break;
}
case X_P:
{
int J0 = ny * subfaceOrigin0(subface);
int K0 = nz * subfaceOrigin1(subface);
#pragma omp parallel for collapse(3)
for (int K = 0; K < nz; K++) {
for (int J = 0; J < ny; J++) {
for (int I = 0; I < vc; I++) {
fData[fIndex(I+nx, J, K)] = interpolateC2F(cData, cIndex, I, J+J0, K+K0);
}
}
}
break;
}
case Y_M:
{
int K0 = nz * subfaceOrigin0(subface);
int I0 = nx * subfaceOrigin1(subface);
#pragma omp parallel for collapse(3)
for (int K = 0; K < nz; K++) {
for (int J = 0; J < vc; J++) {
for (int I = 0; I < nx; I++) {
fData[fIndex(I, J-vc, K)] = interpolateC2F(cData, cIndex, I+I0, J+2*ny-vc, K+K0);
}
}
}
break;
}
case Y_P:
{
int K0 = nz * subfaceOrigin0(subface);
int I0 = nx * subfaceOrigin1(subface);
#pragma omp parallel for collapse(3)
for (int K = 0; K < nz; K++) {
for (int J = 0; J < vc; J++) {
for (int I = 0; I < nx; I++) {
fData[fIndex(I, J+ny, K)] = interpolateC2F(cData, cIndex, I+I0, J, K+K0);
}
}
}
break;
}
case Z_M:
{
int I0 = nx * subfaceOrigin0(subface);
int J0 = ny * subfaceOrigin1(subface);
#pragma omp parallel for collapse(3)
for (int K = 0; K < vc; K++) {
for (int J = 0; J < ny; J++) {
for (int I = 0; I < nx; I++) {
fData[fIndex(I, J, K-vc)] = interpolateC2F(cData, cIndex, I+I0, J+J0, K+2*nz-vc);
}
}
}
break;
}
case Z_P:
{
int I0 = nx * subfaceOrigin0(subface);
int J0 = ny * subfaceOrigin1(subface);
#pragma omp parallel for collapse(3)
for (int K = 0; K < vc; K++) {
for (int J = 0; J < ny; J++) {
for (int I = 0; I < nx; I++) {
fData[fIndex(I, J, K+nz)] = interpolateC2F(cData, cIndex, I+I0, J+J0, K);
}
}
}
break;
}
default:
break;
}
}
void copyToCommBufferC2F_0(int nx, int ny, int nz, int vc,
Face face, Subface subface,
const T* cData, Index3DS cIndex,
T* buffer)
{
int ii = 0;
switch (face) {
case X_M:
{
int J0 = ny * subfaceOrigin0(subface);
int K0 = nz * subfaceOrigin1(subface);
#pragma omp parallel for collapse(3)
for (int K = 0; K < nz; K++) {
for (int J = 0; J < ny; J++) {
for (int I = 0; I < vc; I++) {
int m = I + vc*(J + ny*K);
buffer[m] = interpolateC2F(cData, cIndex, I, J+J0, K+K0);
}
}
}
break;
}
case X_P:
{
int J0 = ny * subfaceOrigin0(subface);
int K0 = nz * subfaceOrigin1(subface);
#pragma omp parallel for collapse(3)
for (int K = 0; K < nz; K++) {
for (int J = 0; J < ny; J++) {
for (int I = 0; I < vc; I++) {
int m = I + vc*(J + ny*K);
buffer[m] = interpolateC2F(cData, cIndex, I+2*nx-vc, J+J0, K+K0);
}
}
}
break;
}
case Y_M:
{
int K0 = nz * subfaceOrigin0(subface);
int I0 = nx * subfaceOrigin1(subface);
#pragma omp parallel for collapse(3)
for (int K = 0; K < nz; K++) {
for (int J = 0; J < vc; J++) {
for (int I = 0; I < nx; I++) {
int m = I + nx*(J + vc*K);
buffer[m] = interpolateC2F(cData, cIndex, I+I0, J, K+K0);
}
}
}
break;
}
case Y_P:
{
int K0 = nz * subfaceOrigin0(subface);
int I0 = nx * subfaceOrigin1(subface);
#pragma omp parallel for collapse(3)
for (int K = 0; K < nz; K++) {
for (int J = 0; J < vc; J++) {
for (int I = 0; I < nx; I++) {
int m = I + nx*(J + vc*K);
buffer[m] = interpolateC2F(cData, cIndex, I+I0, J+2*ny-vc, K+K0);
}
}
}
break;
}
case Z_M:
{
int I0 = nx * subfaceOrigin0(subface);
int J0 = ny * subfaceOrigin1(subface);
#pragma omp parallel for collapse(3)
for (int K = 0; K < vc; K++) {
for (int J = 0; J < ny; J++) {
for (int I = 0; I < nx; I++) {
int m = I + nx*(J + ny*K);
buffer[m] = interpolateC2F(cData, cIndex, I+I0, J+J0, K);
}
}
}
break;
}
case Z_P:
{
int I0 = nx * subfaceOrigin0(subface);
int J0 = ny * subfaceOrigin1(subface);
#pragma omp parallel for collapse(3)
for (int K = 0; K < vc; K++) {
for (int J = 0; J < ny; J++) {
for (int I = 0; I < nx; I++) {
int m = I + nx*(J + ny*K);
buffer[m] = interpolateC2F(cData, cIndex, I+I0, J+J0, K+2*nz-vc);
}
}
}
break;
}
default:
break;
}
}
void copyToCommBufferF2C_0(int nx, int ny, int nz, int vc,
Face face, Subface subface,
const T* fData, Index3DS fIndex,
T* buffer)
{
int ii = 0;
switch (face) {
case X_M:
{
#pragma omp parallel for collapse(3)
for (int k = 0; k < nz/2; k++) {
for (int j = 0; j < ny/2; j++) {
for (int i = 0; i < vc; i++) {
int m = i + vc*(j + ny/2*k);
buffer[m] = interpolateF2C(fData, fIndex, i, j, k);
}
}
}
break;
}
case X_P:
{
#pragma omp parallel for collapse(3)
for (int k = 0; k < nz/2; k++) {
for (int j = 0; j < ny/2; j++) {
for (int i = 0; i < vc; i++) {
int m = i + vc*(j + ny/2*k);
buffer[m] = interpolateF2C(fData, fIndex, i+nx/2-vc, j, k);
}
}
}
break;
}
case Y_M:
{
#pragma omp parallel for collapse(3)
for (int k = 0; k < nz/2; k++) {
for (int j = 0; j < vc; j++) {
for (int i = 0; i < nx/2; i++) {
int m = i + nx/2*(j + vc*k);
buffer[m] = interpolateF2C(fData, fIndex, i, j, k);
}
}
}
break;
}
case Y_P:
{
#pragma omp parallel for collapse(3)
for (int k = 0; k < nz/2; k++) {
for (int j = 0; j < vc; j++) {
for (int i = 0; i < nx/2; i++) {
int m = i + nx/2*(j + vc*k);
buffer[m] = interpolateF2C(fData, fIndex, i, j+ny/2-vc, k);
}
}
}
break;
}
case Z_M:
{
#pragma omp parallel for collapse(3)
for (int k = 0; k < vc; k++) {
for (int j = 0; j < ny/2; j++) {
for (int i = 0; i < nx/2; i++) {
int m = i + nx/2*(j + ny/2*k);
buffer[m] = interpolateF2C(fData, fIndex, i, j, k);
}
}
}
break;
}
case Z_P:
{
#pragma omp parallel for collapse(3)
for (int k = 0; k < vc; k++) {
for (int j = 0; j < ny/2; j++) {
for (int i = 0; i < nx/2; i++) {
int m = i + nx/2*(j + ny/2*k);
buffer[m] = interpolateF2C(fData, fIndex, i, j, k+nz/2-vc);
}
}
}
break;
}
default:
break;
}
}
};
template <>
void Scalar3DUpdater1<real>::copyFromNeighbor(Face face);
template <>
void Scalar3DUpdater1<real>::copyFromNeighborC2F(Face face, Subface subface);
template <>
void Scalar3DUpdater1<real>::copyFromNeighborF2C(Face face, Subface subface);
template <>
void Scalar3DUpdater1<real>::copyFromCommBuffer(Face face);
template <>
void Scalar3DUpdater1<real>::copyFromCommBufferC2F(Face face, Subface subface);
template <>
void Scalar3DUpdater1<real>::copyFromCommBufferF2C(Face face, Subface subface);
template <>
void Scalar3DUpdater1<real>::copyToCommBuffer(Face face);
template <>
void Scalar3DUpdater1<real>::copyToCommBufferC2F(Face face, Subface subface);
template <>
void Scalar3DUpdater1<real>::copyToCommBufferF2C(Face face, Subface subface);
#ifdef BCMT_NAMESPACE
} // namespace BCMT_NAMESPACE
#endif
#endif // SCALAR_3D_UPDATER1_H
|
csr_mat.c | #include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <stdio.h>
#include "mmio.h"
/*#include "mkl.h"*/ /* mkl_cspblas_dcsrgemv*/
#include "arch.h"
#include "csr_mat.h"
#include "wallclock.h"
#include <omp.h>
#define MAX(a,b) ((a)>(b) ? (a) : (b))
#define LINESIZE 100
#define MAXN 2000000
typedef enum symm_t {
symmetric,
unsymmetric,
} symm_t;
csr_mat *csr_mat_create_empty(int n, int nnz)
{
csr_mat *mat = (csr_mat *) malloc(sizeof(csr_mat));
mat->n = n;
mat->ia = (mw_index *) malloc((n+1)*sizeof(mw_index));
mat->ja = (mw_index *) malloc(nnz*sizeof(mw_index));
mat->a = (double *) malloc(nnz*sizeof(double));
return mat;
}
csr_mat *csr_mat_read(const char *filename)
{
csr_mat *mat = (csr_mat *) malloc(sizeof(csr_mat));
FILE *fp = fopen(filename, "rb");
if (fp == NULL)
{
printf("could not open file: %s\n", filename);
return NULL;
}
int n, nnz;
fread(&n, sizeof(int), 1, fp);
fread(&nnz, sizeof(int), 1, fp);
mat->n = n;
mat->ia = (mw_index *) malloc((mat->n+1)*sizeof(mw_index));
mat->ja = (mw_index *) malloc(nnz*sizeof(mw_index));
mat->a = (double *) malloc(nnz*sizeof(double));
fread(mat->ia, sizeof(int), n+1, fp);
fread(mat->ja, sizeof(int), nnz, fp);
fread(mat->a, sizeof(double), nnz, fp);
fclose(fp);
return mat;
}
/* input is 1-based
* will allocate space for matrix, therefore this is a create function */
csr_mat *csr_mat_create(const char *filename)
{
csr_mat *mat = (csr_mat *) malloc(sizeof(csr_mat));
char line[LINESIZE];
int indi, indj;
double val;
int nnz = 0;
int maxi = 0, maxj = 0;
FILE *fp = fopen(filename, "r");
if (fp == NULL)
{
printf("could not open file: %s\n", filename);
return NULL;
}
int *counts = (int *) calloc(MAXN, sizeof(int));
// first pass to count number of nonzeros per row
while (fgets(line, LINESIZE, fp) != NULL)
{
sscanf(line, "%d %d %lf", &indi, &indj, &val);
maxi = MAX(maxi, indi);
maxj = MAX(maxj, indj);
counts[indi-1]++;
nnz++;
}
if (maxi > MAXN || maxj > MAXN)
{
printf("matrix is too large\n");
free(counts);
return NULL;
}
mat->n = MAX(maxi, maxj); // assume matrix is square
mat->ia = (mw_index *) malloc((mat->n+1)*sizeof(mw_index));
mat->ja = (mw_index *) malloc(nnz*sizeof(mw_index));
mat->a = (double *) malloc(nnz*sizeof(double));
// set ia pointers
int i;
mat->ia[0] = 0;
for (i=0; i<mat->n; i++)
{
mat->ia[i+1] = mat->ia[i] + counts[i];
counts[i] = mat->ia[i];
// use counts array to point to empty space in ja array
}
// second pass
rewind(fp);
while (fgets(line, LINESIZE, fp) != NULL)
{
sscanf(line, "%d %d %lf", &indi, &indj, &val);
int k = counts[indi-1]++;
mat->ja[k] = indj-1;
mat->a[k] = val;
}
fclose(fp);
free(counts);
return mat;
}
csr_mat *csr_mat_create_mm(const char *filename)
{
symm_t symmetry_code;
csr_mat *mat;
int ret_code;
MM_typecode matcode;
FILE *f;
int M, N, nnz, nnz_;
int off_diag;
int i, *I, *J;
int k;
double *val;
int *counts;
if ((f = fopen(filename, "r")) == NULL) {
fprintf(stderr, "CSRMatCreateMM: Error: File read error.\n");
return NULL;
}
if(mm_read_banner(f, &matcode) != 0) {
fprintf(stderr, "CSRMatCreateMM: Error: Could not process MM"
"banner.\n");
return NULL;
}
if (mm_is_complex(matcode)) {
fprintf(stderr, "CSRMatCreateMM: Error: Complex matrices not"
"supported.\n");
return NULL;
}
if ((ret_code = mm_read_mtx_crd_size(f, &M, &N, &nnz_)) != 0) {
fprintf(stderr, "CSRMatCreateMM: Error: Can't read matrix"
"size.\n");
return NULL;
}
if (mm_is_symmetric(matcode)) {
symmetry_code = symmetric;
#if 0
fprintf(stdout, "Reading symmetric matrix with:\n");
fprintf(stdout, "nnz = %d\n", nnz_);
fprintf(stdout, "n = %d\n", N);
#endif
} else {
symmetry_code = unsymmetric;
#if 0
fprintf(stdout, "Reading unsymmetric matrix with:\n");
fprintf(stdout, "nnz = %d\n", nnz_);
fprintf(stdout, "n = %d\n", N);
fprintf(stdout, "m = %d\n", M);
#endif
}
/*Because we don't do anything special for symmetric matrices*/
/*Irritatingly MM stores only the upper/lower triangle*/
if (symmetry_code == symmetric) {
nnz = (2*nnz_) - N;
} else {
nnz = nnz_;
}
mat = (csr_mat *)malloc(sizeof(csr_mat));
I = (int *) malloc(nnz * sizeof(int));
J = (int *) malloc(nnz * sizeof(int));
val = (double *)malloc(nnz * sizeof(double));
for (i = 0; i < nnz_; i++) {
fscanf(f, "%d %d %lg\n", &I[i], &J[i], &val[i]);
I[i]--;
J[i]--;
}
fclose(f);
/*More annoying nonsense to be done because only unique entries
* are stored by MM for symmetric matrices */
if (symmetry_code == symmetric) {
off_diag = 0;
for (i = 0; i < nnz_; i++) {
if (I[i] != J[i]) {
I[off_diag + nnz_] = J[i];
J[off_diag + nnz_] = I[i];
val[off_diag + nnz_] = val[i];
off_diag++;
}
}
}
/*Now fill in the corresponding CSRMat structure*/
mat->n = N;
mat->nnz = nnz;
mat->ia = (mw_index *) malloc(((mat->n) + 1) * sizeof(mw_index));
mat->ja = (mw_index *) malloc(nnz * sizeof(mw_index));
mat->a = (double *) malloc(nnz * sizeof(double));
counts = (int *) calloc(mat->n, sizeof(int));
/*Set counts*/
for (i = 0; i < nnz; i++) {
counts[I[i]]++;
}
/* set ia pointers */
mat->ia[0] = 0;
for (i=0; i<mat->n; i++)
{
mat->ia[i+1] = mat->ia[i] + counts[i];
counts[i] = mat->ia[i];
/* use counts array to point to empty space in ja array*/
}
for (i = 0; i < nnz; i++) {
k = counts[I[i]]++;
mat->ja[k] = J[i];
mat->a[k] = val[i];
}
free(I);
free(J);
free(counts);
free(val);
return mat;
}
void csr_mat_destroy(csr_mat *mat)
{
free(mat->ia);
free(mat->ja);
free(mat->a);
free(mat);
}
void csr_mat_dump(const csr_mat *mat)
{
const mw_index *ia = mat->ia;
const mw_index *ja = mat->ja;
const double *a = mat->a;
int i, j;
for (i=0; i<mat->n; i++)
{
for (j=ia[i]; j<ia[i+1]; j++)
printf("%d %d %f\n", i+1, (int)ja[j]+1, a[j]);
}
}
void csr_mat_mult_vec(const csr_mat *mat, const double *x, double *y)
{
const mw_index *ia = mat->ia;
const mw_index *ja = mat->ja;
const double *a = mat->a;
int i, j;
double t;
#pragma omp parallel for private(i,j,t)
for (i=0; i<mat->n; i++)
{
t = 0.;
for (j=ia[i]; j<ia[i+1]; j++)
t += a[j]*x[ja[j]];
y[i] = t;
}
}
void csr_mat_mult_vec_block(const csr_mat *mat, const double *x, double *y, int
blk_sz)
{
int i;
for (i = 0; i < blk_sz; i++) {
csr_mat_mult_vec(mat, &(x[i*(mat->n)]), &(y[i*(mat->n)]));
}
}
#if 0
void CSRMatMultVec_instru(const CSRMat *mat, const double *x, double *y)
{
int numthreads;
const mw_index *ia = mat->ia;
const mw_index *ja = mat->ja;
const double *a = mat->a;
int i, j;
double t;
int id;
double time0[256], time1[256], time2, time3;
numthreads = NUMTHREADS;
WALLCLOCK(time2);
#pragma omp parallel num_threads(numthreads) private(i,j,t,id)
{
id = omp_get_thread_num();
WALLCLOCK(time0[id]);
//#pragma omp for schedule(dynamic,4096)
#pragma omp for
for (i=0; i<mat->n; i++)
{
t = 0.;
for (j=ia[i]; j<ia[i+1]; j++)
t += a[j]*x[ja[j]];
y[i] = t;
}
WALLCLOCK(time1[id]);
}
WALLCLOCK(time3);
double min = 1.e100;
double max = 0.;
double ave = 0.;
for (id=0; id<numthreads; id++)
{
double t = time1[id] - time0[id];
if (t > max) max = t;
if (t < min) min = t;
ave += t/numthreads;
// printf("thread %d time %f numiter %d numthreads %d\n", id, time1[id]-time0[id], numiter, numthreads);
}
printf("min %f max %f ave %f\n", min, max, ave);
printf("total time %f\n", time3-time2);
printf("rate %f (peak is 163 GB/s)\n", (8.+4.) / 1.e9 * mat->ia[mat->n] / (time3-time2));
}
#endif
void csr_mat_trans(csr_mat *ain, csr_mat *aout)
{
int i, j, k, next, n;
mw_index *ia;
mw_index *ja;
mw_index *iao;
mw_index *jao;
double *a;
double *ao;
n = ain->n;
ia = ain->ia;
ja = ain->ja;
iao = aout->ia;
jao = aout->ja;
a = ain->a;
ao = aout->a;
/* initialize */
for (i=0; i<=n; i++)
iao[i] = 0;
/* compute lengths of rows of transpose of A*/
for (i=0; i<n; i++)
for (k=ia[i]; k<ia[i+1]; k++)
iao[ja[k]+1]++;
/* compute pointers from lengths*/
iao[0] = 0;
for (i=0; i<n; i++)
iao[i+1] = iao[i] + iao[i+1];
/* now do the actual copying*/
for (i=0; i<n; i++)
{
for (k=ia[i]; k<ia[i+1]; k++)
{
j = ja[k];
next = iao[j];
ao[next] = a[k];
jao[next] = i;
iao[j] = next+1;
}
}
/* reshift iao into ia*/
for (i=n-1; i>=0; i--)
iao[i+1] = iao[i];
iao[0] = 0;
}
#if 0
// y = alpha A x + beta y
void xx(double alpha, const CSRMat *mat,
const double *x, double beta, double *y)
{
char transa = 'N';
char matdesra[6] = "G C";
int n;
mkl_dcsrmv(&transa, &n, &n, &alpha,
matdescra, mat->a, mat->ia, mat->ja, // undone: need two arrays...
x, &beta, y);
/*
void mkl_dcsrmv(char *transa, MKL_INT *m, MKL_INT *k, double *alpha,
char *matdescra, double *val, MKL_INT *indx, MKL_INT *pntrb, MKL_INT *pntre,
double *x, double *beta, double *y);
*/
}
#endif
#if 0
void CSRMatMultVec_MKL(const CSRMat *mat, const double *x, double *y)
{
mkl_cspblas_dcsrgemv("N", (int *)&mat->n,
(double *)mat->a, (int *)mat->ia, (int *)mat->ja, (double *)x, y);
}
#endif
|
sufsort_priv.h | /*
* nvbio
* Copyright (c) 2011-2014, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the NVIDIA CORPORATION nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 NVIDIA CORPORATION 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.
*/
#pragma once
#include <cub/cub.cuh>
#include <mgpuhost.cuh>
#include <moderngpu.cuh>
#include <nvbio/strings/string_set.h>
#include <nvbio/basic/thrust_view.h>
#include <nvbio/basic/cuda/sort.h>
#include <nvbio/basic/cuda/timer.h>
#include <nvbio/basic/cuda/ldg.h>
#include <nvbio/basic/cuda/primitives.h>
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <thrust/adjacent_difference.h>
#include <thrust/binary_search.h>
#include <thrust/iterator/constant_iterator.h>
#include <thrust/gather.h>
#if defined(PLATFORM_X86)
#include <emmintrin.h> // SSE intrinsics
#endif
namespace nvbio {
namespace priv {
template <uint32 BITS> struct word_selector {};
template <> struct word_selector<4> { typedef uint8 type; };
template <> struct word_selector<6> { typedef uint8 type; };
template <> struct word_selector<8> { typedef uint8 type; };
template <> struct word_selector<10> { typedef uint8 type; };
template <> struct word_selector<12> { typedef uint16 type; };
template <> struct word_selector<14> { typedef uint16 type; };
template <> struct word_selector<16> { typedef uint16 type; };
template <> struct word_selector<18> { typedef uint16 type; };
template <> struct word_selector<20> { typedef uint32 type; };
template <> struct word_selector<22> { typedef uint32 type; };
template <> struct word_selector<24> { typedef uint32 type; };
template <> struct word_selector<26> { typedef uint32 type; };
template <> struct word_selector<28> { typedef uint32 type; };
template <> struct word_selector<30> { typedef uint32 type; };
template <> struct word_selector<32> { typedef uint32 type; };
template <> struct word_selector<48> { typedef uint64 type; };
template <> struct word_selector<64> { typedef uint64 type; };
typedef ConcatenatedStringSet<
PackedStream<uint32*,uint8,2u,false,uint64>,
uint64*> string_set_2bit;
typedef ConcatenatedStringSet<
PackedStream<uint32*,uint8,2u,false,uint64>,
uint64*> string_set_4bit;
typedef ConcatenatedStringSet<
PackedStream<uint32*,uint8,8u,false,uint64>,
uint64*> string_set_8bit;
typedef ConcatenatedStringSet<
PackedStream<uint32*,uint8,2u,true,uint64>,
uint64*> string_set_2bit_be;
typedef ConcatenatedStringSet<
PackedStream<uint64*,uint8,2u,true,uint64>,
uint64*> string_set_2bit_u64_be;
typedef PackedStream<uint32*,uint8,2u,false,uint64> string_2bit_le;
typedef PackedStream<uint32*,uint8,4u,false,uint64> string_4bit_le;
typedef PackedStream<uint32*,uint8,8u,false,uint64> string_8bit_le;
typedef PackedStream<uint32*,uint8,2u,true,uint64> string_2bit_be;
typedef PackedStream<uint32*,uint8,4u,true,uint64> string_4bit_be;
typedef PackedStream<uint32*,uint8,8u,true,uint64> string_8bit_be;
void extract_radices(
const priv::string_set_2bit_be string_set,
const uint32 n_suffixes,
const uint32 word_begin,
const uint32 word_end,
const uint32 word_bits,
const uint2* suffixes,
uint32* radices,
uint8* symbols = NULL);
void extract_radices(
const priv::string_set_2bit_u64_be string_set,
const uint32 n_suffixes,
const uint32 word_begin,
const uint32 word_end,
const uint32 word_bits,
const uint2* suffixes,
uint64* radices,
uint8* symbols = NULL);
// make sure a given buffer is big enough
//
template <typename VectorType>
void alloc_storage(VectorType& vec, const uint64 size)
{
if (vec.size() < size)
{
try
{
vec.clear();
vec.resize( size );
}
catch (...)
{
log_error(stderr,"alloc_storage() : allocation failed!\n");
throw;
}
}
}
/// set the last n bits to 0
///
template <typename storage_type>
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
storage_type clearmask(const uint32 n) { return ~((storage_type(1u) << n)-1u); }
/// A functor to cast from one type into another
///
struct in_range_functor
{
typedef uint32 argument_type;
typedef bool result_type;
/// constructor
///
in_range_functor(const uint32 _begin, const uint32 _end) : begin(_begin), end(_end) {}
/// return true if i is in the range
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
bool operator() (const uint32 i) const { return i >= begin && i < end; }
const uint32 begin, end;
};
/// A functor subtracting the second element of a pair from the first
///
struct minus_one
{
typedef uint32 argument_type;
typedef uint32 result_type;
/// return the length of the i-th string
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
uint32 operator() (const uint32 i) const { return i - 1; }
};
/// A functor adding the given constant to all intergers
///
struct offset_functor
{
typedef uint32 argument_type;
typedef uint32 result_type;
/// constructor
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
offset_functor(const uint32 _offset) : offset(_offset) {}
/// return the length of the i-th string
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
uint32 operator() (const uint32 i) const { return i + offset; }
const uint32 offset;
};
/// A functor dividing all integers by the given constant
///
struct add_divide_functor
{
typedef uint32 argument_type;
typedef uint32 result_type;
/// constructor
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
add_divide_functor(const uint32 _a, const uint32 _k) : a(_a), k(_k) {}
/// return the length of the i-th string
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
uint32 operator() (const uint32 i) const { return (i + a) / k; }
const uint32 a;
const uint32 k;
};
/// A functor fetching the length of the i-th string in a set
///
template <typename string_set_type>
struct length_functor
{
typedef uint32 argument_type;
typedef uint32 result_type;
/// constructor
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
length_functor(const string_set_type _string_set, const bool _extended) : string_set(_string_set), extended(_extended) {}
/// return the length of the i-th string
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
uint32 operator() (const uint32 i) const
{
return string_set[i].length() + (extended ? 1u : 0u);
}
string_set_type string_set;
bool extended;
};
/// A functor adding the given constant to the string id of a suffix
///
struct suffix_offset_functor
{
typedef uint2 argument_type;
typedef uint2 result_type;
/// constructor
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
suffix_offset_functor(const uint32 _offset) : offset(_offset) {}
/// return the length of the i-th string
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
uint2 operator() (const uint2 suffix) const { return make_uint2( suffix.x, suffix.y + offset ); }
const uint32 offset;
};
/// A functor returning the given component of a suffix
///
enum SuffixComponent
{
SUFFIX_ID = 0,
STRING_ID = 1
};
template <SuffixComponent COMP>
struct suffix_component_functor
{
typedef uint2 argument_type;
typedef uint32 result_type;
/// return the length of the i-th string
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
uint32 operator() (const uint2 suffix) const { return COMP == STRING_ID ? suffix.y : suffix.x; }
};
template <uint32 WORD_BITS, uint32 DOLLAR_BITS, uint32 SYMBOL_SIZE, typename string_type, typename index_type>
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
uint32 extract_word_generic(
const string_type string,
const index_type string_len,
const index_type suffix_idx,
const uint32 w)
{
const uint32 SYMBOLS_PER_WORD = uint32(WORD_BITS - DOLLAR_BITS)/SYMBOL_SIZE;
const uint32 SYMBOL_OFFSET = uint32(WORD_BITS) - SYMBOL_SIZE;
uint32 word = 0u;
for (uint32 j = 0; j < SYMBOLS_PER_WORD; ++j)
{
const index_type jj = suffix_idx + w*SYMBOLS_PER_WORD + j;
const uint32 c = jj < string_len ? string[jj] : 0u;
word |= (c << (SYMBOL_OFFSET - j*SYMBOL_SIZE));
}
if (DOLLAR_BITS)
{
// encode the dollar's position in the least significant bits of the word
const uint32 dollar_offset =
string_len <= suffix_idx + w*SYMBOLS_PER_WORD + SYMBOLS_PER_WORD ? // is there a dollar sign?
(string_len < suffix_idx + w*SYMBOLS_PER_WORD) ? 0u :
uint32(string_len - suffix_idx - w*SYMBOLS_PER_WORD) :
(1u << DOLLAR_BITS)-1u; // no dollar sign in this word
return word | dollar_offset;
}
else
return word;
}
/// return how many symbols are encoded per word
///
template <uint32 SYMBOL_SIZE, uint32 WORD_BITS, uint32 DOLLAR_BITS>
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
uint32 symbols_per_word()
{
const uint32 SYMBOLS_PER_WORD = (WORD_BITS - DOLLAR_BITS)/SYMBOL_SIZE;
return SYMBOLS_PER_WORD;
}
template <uint32 WORD_BITS, uint32 DOLLAR_BITS, uint32 SYMBOL_SIZE, typename storage_type, typename index_type, typename sufindex_type>
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
typename std::iterator_traits<storage_type>::value_type extract_word_packed(
const storage_type base_words,
const index_type string_len,
const index_type string_off,
const sufindex_type suffix_idx,
const uint32 w)
{
typedef typename std::iterator_traits<storage_type>::value_type word_type;
const uint32 STORAGE_BITS = uint32( 8u * sizeof(word_type) );
const uint32 STORAGE_SYMBOLS = STORAGE_BITS / SYMBOL_SIZE;
const uint32 SYMBOLS_PER_WORD = uint32(WORD_BITS - DOLLAR_BITS)/SYMBOL_SIZE;
//const uint32 SYMBOL_OFFSET = uint32(WORD_BITS) - SYMBOL_SIZE;
const sufindex_type suffix_off = suffix_idx + w*SYMBOLS_PER_WORD; // suffix offset
// do we have any symbols to encode?
if (suffix_off >= string_len)
return 0u;
const index_type range_len = string_len - suffix_off; // partial suffix length
const index_type range_off = string_off + suffix_off; // partial suffix offset
const uint32 n_symbols = (uint32)nvbio::min( range_len, index_type(SYMBOLS_PER_WORD) ); // symbols to pack
//
// As SYMBOLS_PER_WORD is less than 32, we know that the symbols we are looking for
// will span at most 2 32-bit words.
// Of the n_symbols we want to read, there might be n1 in the first word, and n2 in the
// second word.
// As the beginning of our symbol stream (range_off) might stride the 32-bit word boundary,
// the highest m1 = range_off % 16 symbols of the first word might have to be discarded,
// and we'll find our n1 symbols in the following position:
//
// |-------------------------------------------|
// |* * * * * *| x x x x x x x x x | * * * * * |
// |-------------------------------------------|
// | m1 | n1 | r1 |
//
// What we do is shifting the n1 symbols to the top of the 32-bit word (i.e. m1 to the left).
// Clearing the remaining symbols is only needed if n1 == n_symbols; if n1 < n_symbols, r1 will
// be necessarily zero.
//
// At this point, we might have n2 more symbols to read in the highest bits of the second word:
//
// |-------------------------------------------|
// | y y y y y y y y | * * * * * * * * * * * * |
// |-------------------------------------------|
// | n2 | r2 |
//
// which we need to shift right by (n1*SYMBOL_SIZE) bits.
// At the very end, we'll shift everything right by (32 - WORD_BITS) bits in order to have
// our output tightly packed in the lowest WORD_BITS:
//
// 32 WORD_BITS DOLLAR_BITS 0
// |-----------|-----------------------|-------|
// | * * * * * | x x x x | y y y | 0 0 | $ $ $ | // notice the possible presence of 0's before
// |-------------------------------------------| // the $ sign: these are bits that need to be
// | | n1 | n2 | | | // cleared if the suffix is short
//
const uint32 k1 = uint32( range_off/STORAGE_SYMBOLS ); // index of the first word
const uint32 m1 = range_off & (STORAGE_SYMBOLS-1); // offset in the word
const uint32 r1 = STORAGE_SYMBOLS - m1; // symbols to read
const word_type word1 = (base_words[ k1 ] << (m1*SYMBOL_SIZE)); // fetch the first word, shifted left
word_type word = word1;
if (n_symbols > r1) // do we need to read another word?
{
const word_type word2 = base_words[ k1+1u ]; // fetch the second word
word |= word2 >> (r1*SYMBOL_SIZE); // shift by n1 symbols to the right
}
word >>= (STORAGE_BITS - WORD_BITS); // align the top to WORD_BITS
// clear every symbol we don't need among the word's LSD
word &= clearmask<word_type>( WORD_BITS - n_symbols*SYMBOL_SIZE );
if (DOLLAR_BITS)
{
// encode the dollar's position in the least significant bits of the word
const word_type dollar_offset =
range_len <= SYMBOLS_PER_WORD ? // is there a dollar sign?
range_len :
(1u << DOLLAR_BITS)-1u; // no dollar sign in this word
return word | dollar_offset;
}
else
return word;
}
template <uint32 WORD_BITS, uint32 DOLLAR_BITS, uint32 SYMBOL_SIZE, typename storage_type, typename index_type, typename sufindex_type, typename output_iterator>
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
void extract_word_packed(
const storage_type base_words,
const index_type string_len,
const index_type string_off,
const sufindex_type suffix_idx,
const uint32 word_begin,
const uint32 word_end,
output_iterator words)
{
typedef typename std::iterator_traits<storage_type>::value_type word_type;
const uint32 STORAGE_BITS = uint32( 8u * sizeof(word_type) );
const uint32 STORAGE_SYMBOLS = STORAGE_BITS / SYMBOL_SIZE;
const uint32 SYMBOLS_PER_WORD = uint32(WORD_BITS - DOLLAR_BITS)/SYMBOL_SIZE;
//const uint32 SYMBOL_OFFSET = uint32(WORD_BITS) - SYMBOL_SIZE;
sufindex_type suffix_off = suffix_idx + word_begin*SYMBOLS_PER_WORD; // suffix offset
index_type range_len = string_len - suffix_off; // partial suffix length
index_type range_off = string_off + suffix_off; // partial suffix offset
const uint32 cache_begin = uint32( range_off / STORAGE_SYMBOLS );
#if defined(PLATFORM_X86) && !defined(NVBIO_DEVICE_COMPILATION)
// use SSE to load all the words we need in a small cache
const uint32 SSE_WORDS = 16u / sizeof( word_type );
const uint32 cache_end = uint32( (range_off + (word_end - word_begin)*SYMBOLS_PER_WORD) / STORAGE_SYMBOLS );
__m128i sse_cache[8];
for (uint32 w = cache_begin; w < cache_end; w += SSE_WORDS)
sse_cache[ (w - cache_begin)/SSE_WORDS ] = _mm_loadu_si128( (const __m128i*)(base_words + w) );
const word_type* cached_words = (const word_type*)sse_cache;
#elif 0
const_cached_iterator<storage_type> cached_words( base_words + cache_begin );
#else
const storage_type cached_words = base_words + cache_begin;
#endif
for (uint32 w = word_begin; w < word_end; ++w)
{
// do we have any symbols to encode?
if (suffix_off >= string_len)
{
words[w - word_begin] = 0u;
continue;
}
const uint32 n_symbols = (uint32)nvbio::min( range_len, index_type(SYMBOLS_PER_WORD) ); // symbols to pack
//
// As SYMBOLS_PER_WORD is less than 32, we know that the symbols we are looking for
// will span at most 2 32-bit words.
// Of the n_symbols we want to read, there might be n1 in the first word, and n2 in the
// second word.
// As the beginning of our symbol stream (range_off) might stride the 32-bit word boundary,
// the highest m1 = range_off % 16 symbols of the first word might have to be discarded,
// and we'll find our n1 symbols in the following position:
//
// |-------------------------------------------|
// |* * * * * *| x x x x x x x x x | * * * * * |
// |-------------------------------------------|
// | m1 | n1 | r1 |
//
// What we do is shifting the n1 symbols to the top of the 32-bit word (i.e. m1 to the left).
// Clearing the remaining symbols is only needed if n1 == n_symbols; if n1 < n_symbols, r1 will
// be necessarily zero.
//
// At this point, we might have n2 more symbols to read in the highest bits of the second word:
//
// |-------------------------------------------|
// | y y y y y y y y | * * * * * * * * * * * * |
// |-------------------------------------------|
// | n2 | r2 |
//
// which we need to shift right by (n1*SYMBOL_SIZE) bits.
// At the very end, we'll shift everything right by (32 - WORD_BITS) bits in order to have
// our output tightly packed in the lowest WORD_BITS:
//
// 32 WORD_BITS DOLLAR_BITS 0
// |-----------|-----------------------|-------|
// | * * * * * | x x x x | y y y | 0 0 | $ $ $ | // notice the possible presence of 0's before
// |-------------------------------------------| // the $ sign: these are bits that need to be
// | | n1 | n2 | | | // cleared if the suffix is short
//
const uint32 k1 = uint32( range_off/STORAGE_SYMBOLS ) - cache_begin; // index of the first word
const uint32 m1 = range_off & (STORAGE_SYMBOLS-1); // offset in the word
const uint32 r1 = STORAGE_SYMBOLS - m1; // symbols left in the word
const word_type word1 = (cached_words[ k1 ] << (m1*SYMBOL_SIZE)); // fetch the first word, shifted left
word_type word = word1;
if (n_symbols > r1) // do we need to read another word?
{
const word_type word2 = cached_words[ k1+1u ]; // fetch the second word
word |= word2 >> (r1*SYMBOL_SIZE); // shift by n1 symbols to the right
}
word >>= (STORAGE_BITS - WORD_BITS); // align the top to WORD_BITS
// clear every symbol we don't need among the word's LSD
word &= clearmask<word_type>( WORD_BITS - n_symbols*SYMBOL_SIZE );
if (DOLLAR_BITS)
{
// encode the dollar's position in the least significant bits of the word
const word_type dollar_offset =
range_len <= SYMBOLS_PER_WORD ? // is there a dollar sign?
range_len :
(1u << DOLLAR_BITS)-1u; // no dollar sign in this word
word |= dollar_offset;
}
// write the word out
words[ w - word_begin ] = word;
suffix_off += SYMBOLS_PER_WORD;
range_len -= SYMBOLS_PER_WORD;
range_off += SYMBOLS_PER_WORD;
}
}
/// A functor to localize suffixes, making the conversion: global-suffix-id -> (string-id,suffix-id)
///
struct localize_suffix_functor
{
typedef uint32 argument_type;
typedef uint2 result_type;
/// constructor
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
localize_suffix_functor(const uint32* _cum_lengths, const uint32* _string_ids, const uint32 _string_offset = 0u) :
cum_lengths(_cum_lengths),
string_ids(_string_ids),
string_offset( _string_offset ) {}
/// return the localized suffix
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
result_type operator() (const uint32 global_suffix_idx) const
{
const uint32 string_idx = string_ids[ global_suffix_idx ];
const uint32 suffix_idx = global_suffix_idx - (string_idx ? cum_lengths[ string_idx-1u ] : 0u);
return make_uint2( suffix_idx, string_offset + string_idx );
}
const uint32* cum_lengths;
const uint32* string_ids;
const uint32 string_offset;
};
/// A functor fetching the w'th word worth of 2-bit symbols from the i-th string in a set
///
template <uint32 SYMBOL_SIZE, uint32 WORD_BITS, uint32 DOLLAR_BITS, typename string_set_type, typename word_type>
struct local_set_suffix_word_functor
{
typedef uint2 argument_type;
typedef word_type result_type;
/// constructor
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
local_set_suffix_word_functor(const string_set_type _string_set, const uint32 _w) :
string_set(_string_set),
w(_w) {}
/// return the w'th word of the i-th string
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
result_type operator() (const uint2 local_suffix_idx) const
{
typedef typename string_set_type::string_type string_type;
const uint32 string_idx = local_suffix_idx.y;
const uint32 suffix_idx = local_suffix_idx.x;
const string_type string = string_set[string_idx];
const uint32 string_len = string.length();
return result_type( extract_word_generic<WORD_BITS,DOLLAR_BITS,SYMBOL_SIZE>(
string,
string_len,
suffix_idx,
w ) );
}
string_set_type string_set;
uint32 w;
};
/// A functor fetching the w'th word worth of 2-bit symbols from the given (string,suffix) in a set
///
template <uint32 SYMBOL_SIZE, uint32 WORD_BITS, uint32 DOLLAR_BITS, typename storage_type, typename word_type, typename offsets_iterator>
struct local_set_suffix_word_functor<
SYMBOL_SIZE, WORD_BITS, DOLLAR_BITS,
ConcatenatedStringSet<
PackedStream<storage_type,uint8,SYMBOL_SIZE,true,typename std::iterator_traits<offsets_iterator>::value_type>,
offsets_iterator>,
word_type>
{
typedef typename std::iterator_traits<offsets_iterator>::value_type index_type;
typedef ConcatenatedStringSet<
PackedStream<storage_type,uint8,SYMBOL_SIZE,true,index_type>,
offsets_iterator> string_set_type;
typedef uint2 argument_type;
typedef word_type result_type;
/// constructor
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
local_set_suffix_word_functor(const string_set_type _string_set, const uint32 _w) :
string_set(_string_set),
w(_w) {}
/// return the w'th word of the i-th string
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
result_type operator() (const uint2 local_suffix_idx) const
{
typedef typename string_set_type::string_type string_type;
const uint32 string_idx = local_suffix_idx.y;
const uint32 suffix_idx = local_suffix_idx.x;
const index_type string_off = string_set.offsets()[ string_idx ];
const index_type string_end = string_set.offsets()[ string_idx+1u ];
const index_type string_len = uint32( string_end - string_off );
const storage_type base_words = string_set.base_string().stream();
return result_type( extract_word_packed<WORD_BITS,DOLLAR_BITS,SYMBOL_SIZE>(
base_words,
string_len,
string_off,
suffix_idx,
w ) );
}
string_set_type string_set;
uint32 w;
};
/// A functor fetching the w'th word worth of 2-bit symbols from the i-th suffix in a set
///
template <uint32 SYMBOL_SIZE, uint32 WORD_BITS, uint32 DOLLAR_BITS, typename string_set_type, typename word_type>
struct global_set_suffix_word_functor
{
typedef uint32 argument_type;
typedef word_type result_type;
/// constructor
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
global_set_suffix_word_functor(const string_set_type _string_set, const uint32* _cum_lengths, const uint32* _string_ids, const uint32 _w) :
word_functor( _string_set, _w ),
localizer( _cum_lengths, _string_ids ) {}
/// return the w'th word of the i-th string
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
result_type operator() (const uint32 global_suffix_idx) const
{
return word_functor( localizer( global_suffix_idx ) );
}
local_set_suffix_word_functor<SYMBOL_SIZE,WORD_BITS,DOLLAR_BITS,string_set_type,word_type> word_functor;
localize_suffix_functor localizer;
};
/// A functor fetching the w'th word worth of 2-bit symbols from the i-th string in a set
///
template <uint32 SYMBOL_SIZE, uint32 WORD_BITS, uint32 DOLLAR_BITS, typename string_type, typename word_type>
struct string_suffix_word_functor
{
typedef uint32 argument_type;
typedef word_type result_type;
/// constructor
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
string_suffix_word_functor(const uint64 _string_len, const string_type _string, const uint32 _w) :
string_len(_string_len),
string(_string),
w(_w) {}
/// return the w'th word of the i-th string
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
result_type operator() (const uint64 suffix_idx) const
{
return result_type( extract_word_generic<WORD_BITS,DOLLAR_BITS,SYMBOL_SIZE>(
string,
string_len,
suffix_idx,
w ) );
}
const uint64 string_len;
string_type string;
uint32 w;
};
/// A functor fetching the w'th word worth of 2-bit symbols from the i-th string in a set
///
template <uint32 SYMBOL_SIZE, uint32 WORD_BITS, uint32 DOLLAR_BITS, typename storage_type, typename symbol_type, typename index_type, typename word_type>
struct string_suffix_word_functor<
SYMBOL_SIZE, WORD_BITS, DOLLAR_BITS,
PackedStream<storage_type,symbol_type,SYMBOL_SIZE,true,index_type>,
word_type>
{
typedef typename PackedStream<storage_type,symbol_type,SYMBOL_SIZE,true,index_type>::iterator string_type;
typedef uint2 argument_type;
typedef word_type result_type;
/// constructor
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
string_suffix_word_functor(const index_type _string_len, const string_type _string, const uint32 _w) :
string_len(_string_len),
string(_string),
w(_w) {}
/// return the w'th word of the i-th string
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
result_type operator() (const index_type suffix_idx) const
{
const storage_type base_words = string.stream();
return result_type( extract_word_packed<WORD_BITS,DOLLAR_BITS,SYMBOL_SIZE>(
base_words,
string_len,
string.index(),
suffix_idx,
w ) );
}
const index_type string_len;
string_type string;
uint32 w;
};
/// A binary functor calculating whether two suffixes differ (returning 1) or not (returning 0)
///
template <typename string_type>
struct string_suffix_difference
{
typedef uint32 first_argument_type;
typedef uint32 second_argument_type;
typedef uint32 result_type;
/// constructor
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
string_suffix_difference(const uint64 _string_len, const string_type _string, const uint32 _cmp_len) :
string_len(_string_len),
string(_string),
cmp_len( _cmp_len ) {}
/// return the w'th word of the i-th string
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
result_type operator() (const uint64 suffix_idx1, const uint64 suffix_idx2) const
{
// if one of the two suffixes is less than cmp_len, then the two suffixes must
// necessarily differ (because no two suffixes have the same length)
if (string_len - suffix_idx1 < cmp_len ||
string_len - suffix_idx2 < cmp_len)
return 1u;
for (uint32 i = 0; i < cmp_len; ++i)
{
if (string[suffix_idx1 + i] != string[suffix_idx2 + i])
return 1u;
}
return 0u;
}
const uint64 string_len;
string_type string;
uint32 cmp_len;
};
/// A binary functor comparing two suffixes lexicographically
///
template <uint32 SYMBOL_SIZE, typename string_type>
struct string_suffix_less
{
typedef uint32 first_argument_type;
typedef uint32 second_argument_type;
typedef uint32 result_type;
/// constructor
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
string_suffix_less(const uint64 _string_len, const string_type _string) :
string_len(_string_len),
string(_string) {}
/// return true if the first suffix is lexicographically smaller than the second, false otherwise
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
result_type operator() (const uint64 suffix_idx1, const uint64 suffix_idx2) const
{
const uint32 WORD_BITS = 32u; // use 32-bit words
const uint32 DOLLAR_BITS = 4u; // 4 is the minimum number needed to encode up to 16 symbols per word
const uint32 SYMBOLS_PER_WORD = symbols_per_word<SYMBOL_SIZE,WORD_BITS,DOLLAR_BITS>();
const uint32 n_words = uint32( nvbio::min(
(string_len - suffix_idx1),
(string_len - suffix_idx2) ) + SYMBOLS_PER_WORD-1 ) / SYMBOLS_PER_WORD;
// loop through all string-words
for (uint32 w = 0; w < n_words; ++w)
{
string_suffix_word_functor<SYMBOL_SIZE,WORD_BITS,DOLLAR_BITS,string_type,uint32> word_functor( string_len, string, w );
const uint32 w1 = word_functor( suffix_idx1 );
const uint32 w2 = word_functor( suffix_idx2 );
if (w1 < w2) return true;
if (w1 > w2) return false;
}
return false;
}
const uint64 string_len;
string_type string;
};
/// given a string, return the symbol preceding each of its suffixes, or 255u to mark the
/// special $ symbol used for the first suffix.
///
template <typename string_type>
struct string_bwt_functor
{
typedef uint64 argument_type;
typedef uint8 result_type;
/// constructor
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
string_bwt_functor(const uint64 _string_len, const string_type _string) :
string_len(_string_len),
string(_string) {}
/// return the symbol preceding the given suffix
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
result_type operator() (const argument_type suffix_idx) const
{
return suffix_idx ? string[suffix_idx-1] : 255u; // use 255u to mark the dollar sign
}
const uint64 string_len;
const string_type string;
};
/// given a string set, return the symbol preceding each of its suffixes, or 255u to mark the
/// special $ symbol used for the first suffix.
///
template <typename string_set_type>
struct string_set_bwt_functor
{
typedef uint2 argument_type;
typedef uint8 result_type;
/// constructor
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
string_set_bwt_functor(const string_set_type _string_set) :
string_set(_string_set) {}
/// return the symbol preceding the given suffix
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
result_type operator() (const argument_type local_suffix_idx) const
{
typedef typename string_set_type::string_type string_type;
const uint32 string_idx = local_suffix_idx.y;
const uint32 suffix_idx = local_suffix_idx.x;
const string_type string = string_set[string_idx];
return suffix_idx ? string[suffix_idx-1] : 255u; // use 255u to mark the dollar sign
}
/// return the last symbol of a given string
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
result_type operator() (const uint32 string_idx) const
{
typedef typename string_set_type::string_type string_type;
const string_type string = string_set[string_idx];
return string[ string.length()-1 ];
}
const string_set_type string_set;
};
/// A binary functor implementing some custom logic to remove singletons from a set of segment-flags
///
struct remove_singletons
{
typedef uint32 first_argument_type;
typedef uint32 second_argument_type;
typedef uint32 result_type;
/// functor operator
///
/// \return flag1 && flag2 ? 0 : 1
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
result_type operator() (const uint32 flag1, const uint32 flag2) const
{
return (flag1 && flag2) ? 0u : 1u;
}
};
/// A binary functor to merge keys with new radices
///
struct merge_keys
{
typedef uint32 first_argument_type;
typedef uint64 second_argument_type;
typedef uint64 result_type;
/// functor operator
///
/// \return (key << 32u) | radix
///
NVBIO_FORCEINLINE NVBIO_HOST_DEVICE
result_type operator() (const first_argument_type radix, const second_argument_type key) const
{
return (key << 32u) | second_argument_type( radix );
}
};
/*
template <uint32 SYMBOL_SIZE, uint32 WORD_BITS, uint32 DOLLAR_BITS, typename string_set_type>
struct dispatch_set_suffix_radices
{
template <typename radix_iterator>
void enact(
const string_set_type& string_set,
const SetSuffixFlattener<SYMBOL_SIZE>& set_flattener,
radix_iterator radices)
{
typedef typename std::iterator_traits<radix_iterator>::value_type word_type;
thrust::transform(
thrust::make_counting_iterator(0u),
thrust::make_counting_iterator(0u) + set_flattener.n_suffixes,
radices,
global_set_suffix_word_functor<SYMBOL_SIZE,BITS,DOLLAR_BITS,string_set_type,word_type>(
string_set,
nvbio::device_view( set_flattener.cum_lengths ),
nvbio::device_view( set_flattener.string_ids ),
0u ) );
}
};
template <uint32 SYMBOL_SIZE, uint32 WORD_BITS, uint32 DOLLAR_BITS, typename storage_type, typename index_type>
struct dispatch_set_suffix_radices<
SYMBOL_SIZE, WORD_BITS, DOLLAR_BITS,
ConcatenatedStringSet<PackedStream<storage_type,uint8,SYMBOL_SIZE,true,index_type>,index_type*>,
word_type>
{
typedef ConcatenatedStringSet<
PackedStream<storage_type,uint8,SYMBOL_SIZE,true,index_type>,
index_type*> string_set_type;
template <typename radix_iterator>
void enact(
const string_set_type& string_set,
const SetSuffixFlattener<SYMBOL_SIZE>& set_flattener,
radix_iterator radices)
{
typedef typename std::iterator_traits<radix_iterator>::value_type word_type;
thrust::transform(
thrust::make_counting_iterator(0u),
thrust::make_counting_iterator(0u) + set_flattener.n_suffixes,
radices,
global_set_suffix_word_functor<SYMBOL_SIZE,BITS,DOLLAR_BITS,string_set_type,word_type>(
string_set,
nvbio::device_view( set_flattener.cum_lengths ),
nvbio::device_view( set_flattener.string_ids ),
word_idx ) );
}
};
*/
template <uint32 BITS, uint32 DOLLAR_BITS>
struct Bits {};
/// A helper class allowing to "flatten" the suffixes in a given string-set, i.e. to extract
/// all of them word-by-word in a flattened array.
///
template <uint32 SYMBOL_SIZE>
struct SetSuffixFlattener
{
SetSuffixFlattener(mgpu::ContextPtr _mgpu) :
d_scan_time(0.0f),
d_search_time(0.0f),
m_mgpu( _mgpu ) {}
/// clear internal timers
///
void clear_timers()
{
d_scan_time = 0.0f;
d_search_time = 0.0f;
}
/// reserve storage
///
void reserve(const uint32 n_strings, const uint32 n_suffixes)
{
alloc_storage( cum_lengths, n_strings );
alloc_storage( string_ids, n_suffixes );
}
/// return the amount of device memory needed
///
uint64 needed_device_memory(const uint32 n_strings, const uint32 n_suffixes) const
{
return (n_strings + n_suffixes) * sizeof(uint32);
}
/// initialize this flattener, building the auxiliary data-structures needed
/// to extract the radices
///
template <typename string_set_type>
void set(const string_set_type& string_set, const bool empty_suffixes = true)
{
const uint32 n = string_set.size();
cuda::Timer timer;
timer.start();
// compute the cumulative sum of the string lengths in the set - we will use this for
// building the map: (global suffix index -> string index)
alloc_storage( cum_lengths, n );
cuda::inclusive_scan(
n,
thrust::make_transform_iterator( thrust::make_counting_iterator(0u), length_functor<string_set_type>( string_set, empty_suffixes ) ),
cum_lengths.begin(),
thrust::plus<uint32>(),
temp_storage );
// compute the number of suffixes
n_suffixes = cum_lengths[n-1];
timer.stop();
d_scan_time += timer.seconds();
timer.start();
// assign the string id to each suffix - this is done by a simple binary search on the suffix index
// in the vector of cumulative string lengths
alloc_storage( string_ids, n_suffixes );
// find the end of each bin of values
mgpu::SortedSearch<mgpu::MgpuBoundsLower>(
thrust::make_counting_iterator<uint32>(0u),
n_suffixes,
thrust::make_transform_iterator( cum_lengths.begin(), minus_one() ),
n,
string_ids.begin(),
*m_mgpu );
timer.stop();
d_search_time += timer.seconds();
}
/// extract the given radix of all suffixes
///
template <uint32 BITS, uint32 DOLLAR_BITS, typename string_set_type, typename index_iterator, typename radix_iterator>
void flatten(
const string_set_type& string_set,
const uint32 word_idx,
const Bits<BITS,DOLLAR_BITS> word_bits,
const index_iterator indices,
radix_iterator radices)
{
typedef typename std::iterator_traits<radix_iterator>::value_type word_type;
thrust::transform(
indices,
indices + n_suffixes,
radices,
global_set_suffix_word_functor<SYMBOL_SIZE,BITS,DOLLAR_BITS,string_set_type,word_type>(
string_set,
nvbio::device_view( cum_lengths ),
nvbio::device_view( string_ids ),
word_idx ) );
}
/// compute the maximum suffix length among the specified range
///
template <typename string_set_type>
uint32 max_length(
const string_set_type& string_set, const bool empty_suffixes = true)
{
// compute the maximum string length in the set
return cuda::reduce(
uint32( string_set.size() ),
thrust::make_transform_iterator(
thrust::make_counting_iterator<uint32>(0u),
length_functor<string_set_type>( string_set, empty_suffixes ) ),
thrust::maximum<uint32>(),
temp_storage );
}
/// compute the maximum suffix length among the specified range
///
template <typename string_set_type, typename index_iterator>
uint32 max_length(
const string_set_type& string_set,
const index_iterator indices_begin,
const index_iterator indices_end)
{
// TODO: this function is conservative, in the sense it returns the maximum *string* length;
// however, each suffix might be shorter than the string it belongs to.
return indices_end <= indices_begin ? 0u :
cuda::reduce(
indices_end - indices_begin,
thrust::make_transform_iterator(
thrust::make_permutation_iterator( string_ids.begin(), indices_begin ),
length_functor<string_set_type>( string_set, false ) ),
thrust::maximum<uint32>(),
temp_storage );
}
/// return the amount of used device memory
///
uint64 allocated_device_memory() const
{
return
cum_lengths.size() * sizeof(uint32) +
string_ids.size() * sizeof(uint32) +
temp_storage.size() * sizeof(uint8);
}
uint32 n_suffixes; ///< number of suffixes in the string set
thrust::device_vector<uint32> cum_lengths; ///< cumulative string lengths
thrust::device_vector<uint32> string_ids; ///< a vector containing the string index corresponding
/// to each flattened suffixes; i.e. if the set contains
/// 3 strings of length (3, 2, 5), the string ids will be
/// the vector (0,0,0,1,1,2,2,2,2,2).
thrust::device_vector<uint8> temp_storage;
float d_scan_time;
float d_search_time;
mgpu::ContextPtr m_mgpu;
};
/// A helper class to load a chunk of a string_set from the host onto the device
///
template <uint32 SYMBOL_SIZE, bool BIG_ENDIAN, typename storage_type, typename offsets_iterator, typename input_tag, typename output_tag>
struct ChunkLoader {};
/// A helper class to load a chunk of a string_set from the host onto the device
///
template <uint32 SYMBOL_SIZE, bool BIG_ENDIAN, typename storage_type, typename offsets_iterator>
struct ChunkLoader<SYMBOL_SIZE,BIG_ENDIAN,storage_type,offsets_iterator,host_tag,device_tag>
{
// infer the word type
typedef typename std::iterator_traits<storage_type>::value_type word_type;
typedef typename std::iterator_traits<offsets_iterator>::value_type index_type;
typedef cuda::load_pointer<word_type,cuda::LOAD_LDG> word_pointer;
typedef PackedStream<word_pointer,uint8,SYMBOL_SIZE,BIG_ENDIAN> packed_stream_type;
typedef typename packed_stream_type::iterator packed_stream_iterator;
typedef ConcatenatedStringSet<packed_stream_iterator,uint32*> chunk_set_type;
// infer the word size
static const uint32 SYMBOLS_PER_WORD = uint32(8u*sizeof(word_type))/SYMBOL_SIZE;
uint64 needed_device_memory(const uint32 max_strings, const uint32 max_symbols) const
{
const uint32 max_words = util::divide_ri( max_symbols, SYMBOLS_PER_WORD ) + 2;
return (max_strings+1) * sizeof(uint32) +
max_words * sizeof(word_type);
}
void reserve(const uint32 max_strings, const uint32 max_symbols)
{
const uint32 max_words = util::divide_ri( max_symbols, SYMBOLS_PER_WORD ) + 2;
alloc_storage( h_chunk_offsets, max_strings+1 );
alloc_storage( d_chunk_offsets, max_strings+1 );
alloc_storage( d_chunk_string, max_words );
}
chunk_set_type load(
const ConcatenatedStringSet<
typename PackedStream<storage_type,uint8,SYMBOL_SIZE,BIG_ENDIAN,index_type>::iterator,
offsets_iterator> string_set,
const uint32 chunk_begin,
const uint32 chunk_end)
{
const uint32 chunk_size = chunk_end - chunk_begin;
alloc_storage( h_chunk_offsets, chunk_size+1 );
alloc_storage( d_chunk_offsets, chunk_size+1 );
// find the words overlapped by the chunk
const uint64 begin_index = string_set.offsets()[ chunk_begin ];
const uint64 end_index = string_set.offsets()[ chunk_end ];
const uint64 begin_word = (begin_index / SYMBOLS_PER_WORD);
const uint64 end_word = (end_index + SYMBOLS_PER_WORD-1) / SYMBOLS_PER_WORD;
const uint32 chunk_words = uint32( end_word - begin_word );
const word_type* base_words = string_set.base_string().stream();
alloc_storage( d_chunk_string, chunk_words );
// copy them to the device
thrust::copy(
base_words + begin_word,
base_words + begin_word + chunk_words,
d_chunk_string.begin() );
// build the host offsets
uint32 chunk_symbols = uint32( begin_index % SYMBOLS_PER_WORD );
h_chunk_offsets[0] = chunk_symbols;
for (uint32 i = 0; i < chunk_size; ++i)
{
chunk_symbols += string_set[ chunk_begin + i ].size();
h_chunk_offsets[i+1] = chunk_symbols;
}
// copy the offsets to the device
thrust::copy(
h_chunk_offsets.begin(),
h_chunk_offsets.begin() + chunk_size+1,
d_chunk_offsets.begin() );
// finally assemble the device chunk string-set
packed_stream_type d_packed_stream( word_pointer( nvbio::plain_view( d_chunk_string ) ) );
return chunk_set_type(
chunk_size,
d_packed_stream.begin(),
nvbio::plain_view( d_chunk_offsets ) );
}
thrust::host_vector<uint32> h_chunk_offsets;
thrust::device_vector<word_type> d_chunk_string;
thrust::device_vector<uint32> d_chunk_offsets;
};
/// A helper class to load a chunk of a string_set from the host onto the device
///
template <uint32 SYMBOL_SIZE, bool BIG_ENDIAN, typename storage_type, typename offsets_iterator, typename system_tag>
struct ChunkLoader<SYMBOL_SIZE,BIG_ENDIAN,storage_type,offsets_iterator,system_tag,system_tag>
{
typedef typename std::iterator_traits<offsets_iterator>::value_type index_type;
typedef const ConcatenatedStringSet<
typename PackedStream<storage_type,uint8,SYMBOL_SIZE,BIG_ENDIAN,index_type>::iterator,
offsets_iterator> string_set_type;
typedef string_set_type chunk_set_type;
chunk_set_type load(
const string_set_type string_set,
const uint32 chunk_begin,
const uint32 chunk_end)
{
// assemble the device chunk string-set
return chunk_set_type(
uint32( chunk_end - chunk_begin ),
string_set.base_string(),
string_set.offsets() + chunk_begin );
}
};
/// extract the given radix from the given suffixes of a string
///
template <uint32 SYMBOL_SIZE, uint32 BITS, uint32 DOLLAR_BITS, typename string_type, typename index_iterator, typename radix_iterator>
void flatten_string_suffixes(
const uint64 string_len,
const string_type& string,
const uint32 word_idx,
const index_iterator indices_begin,
const index_iterator indices_end,
radix_iterator radices)
{
typedef typename std::iterator_traits<radix_iterator>::value_type word_type;
thrust::transform(
indices_begin,
indices_end,
radices,
string_suffix_word_functor<SYMBOL_SIZE, BITS, DOLLAR_BITS,string_type,word_type>(
string_len,
string,
word_idx ) );
}
/// A context class to perform suffix bucketing
///
template <uint32 SYMBOL_SIZE, uint32 N_BITS, uint32 DOLLAR_BITS>
struct StringSuffixBucketer
{
typedef uint32 word_type;
StringSuffixBucketer() : d_setup_time(0.0f), d_flatten_time(0.0f), d_count_sort_time(0.0f), d_collect_sort_time(0.0f), d_remap_time(0.0f), d_copy_time(0.0f), d_filter_time(0.0f) {}
/// count the number of suffixes falling in each bucket, where the buckets
/// are defined by the first n_bits of the suffix
///
template <typename suffix_iterator, typename string_type>
void count(
const uint32 n_suffixes,
const suffix_iterator suffixes,
const uint32 string_length,
const string_type& string)
{
cuda::Timer timer;
const uint32 n_buckets = 1u << (N_BITS);
// initialize the temporary and output vectors
alloc_storage( d_indices, n_suffixes * 2u );
alloc_storage( d_radices, n_suffixes * 2u );
alloc_storage( d_buckets, n_buckets );
timer.start();
// extract the first radix word from each of the suffixes
flatten_string_suffixes<SYMBOL_SIZE, N_BITS,DOLLAR_BITS>(
string_length,
string,
0u, // load the first word
suffixes,
suffixes + n_suffixes,
d_radices.begin() );
timer.stop();
d_flatten_time += timer.seconds();
timer.start();
// sort the radices so as to make binning easy
cuda::SortBuffers<word_type*> sort_buffers;
cuda::SortEnactor sort_enactor;
sort_buffers.selector = 0;
sort_buffers.keys[0] = nvbio::device_view( d_radices );
sort_buffers.keys[1] = nvbio::device_view( d_radices ) + n_suffixes;
sort_enactor.sort( n_suffixes, sort_buffers, 0u, N_BITS );
//thrust::sort( d_radices.begin(), d_radices.begin() + n_suffixes );
timer.stop();
d_count_sort_time += timer.seconds();
// initialize the bucket counters
thrust::fill( d_buckets.begin(), d_buckets.end(), 0u );
// compute the number of effectively used buckets looking at the last non-empty one
const uint32 n_used_buckets = d_radices[ sort_buffers.selector * n_suffixes + n_suffixes-1 ] + 1u;
// find the end of each bin of values
thrust::upper_bound(
d_radices.begin() + sort_buffers.selector * n_suffixes,
d_radices.begin() + sort_buffers.selector * n_suffixes + n_suffixes,
thrust::make_counting_iterator<uint32>(0u),
thrust::make_counting_iterator<uint32>(0u) + n_used_buckets,
d_buckets.begin() );
// compute the histogram by taking differences of the cumulative histogram
thrust::adjacent_difference(
d_buckets.begin(), d_buckets.begin() + n_used_buckets,
d_buckets.begin());
}
/// collect the suffixes falling in a given set of buckets, where the buckets
/// are defined by the first n_bits of the suffix
///
template <typename suffix_iterator, typename string_type, typename bucketmap_iterator, typename output_iterator>
uint32 collect(
const uint32 n_suffixes,
const suffix_iterator suffixes,
const uint64 string_length,
const string_type& string,
const uint32 bucket_begin,
const uint32 bucket_end,
const bucketmap_iterator bucketmap,
output_iterator output_radices,
output_iterator output_indices)
{
cuda::Timer timer;
const uint32 n_buckets = 1u << N_BITS;
// initialize the temporary and output vectors
alloc_storage( d_indices, n_suffixes * 2u );
alloc_storage( d_radices, n_suffixes * 2u );
alloc_storage( d_buckets, n_buckets );
timer.start();
// extract the first radix word from each of the suffixes
flatten_string_suffixes<SYMBOL_SIZE,N_BITS,DOLLAR_BITS>(
string_length,
string,
0u, // load the first word
suffixes,
suffixes + n_suffixes,
d_radices.begin() );
timer.stop();
d_flatten_time += timer.seconds();
timer.start();
// determine if a radix is in the given bucket range
const priv::in_range_functor in_range = priv::in_range_functor( bucket_begin, bucket_end );
// retain only suffixes whose radix is between the specified buckets
const uint32 n_collected = cuda::copy_flagged(
n_suffixes,
thrust::make_zip_iterator( thrust::make_tuple( suffixes, d_radices.begin() ) ),
thrust::make_transform_iterator( d_radices.begin(), in_range ),
thrust::make_zip_iterator( thrust::make_tuple( d_indices.begin(), d_radices.begin() ) ) + n_suffixes,
d_temp_storage );
timer.stop();
d_filter_time += timer.seconds();
timer.start();
// remap the collected radices
thrust::gather(
d_radices.begin() + n_suffixes,
d_radices.begin() + n_suffixes + n_collected,
bucketmap,
d_radices.begin() + n_suffixes );
timer.stop();
d_remap_time += timer.seconds();
timer.start();
// sort the radices so as to make binning easy
cuda::SortBuffers<word_type*,uint64*> sort_buffers;
cuda::SortEnactor sort_enactor;
sort_buffers.selector = 0;
//#define SORT_BY_BUCKETS
#if defined(SORT_BY_BUCKETS)
sort_buffers.keys[0] = nvbio::device_view( d_radices ) + n_suffixes;
sort_buffers.keys[1] = nvbio::device_view( d_radices );
sort_buffers.values[0] = (uint64*)nvbio::device_view( d_indices ) + buffer_stride;
sort_buffers.values[1] = (uint64*)nvbio::device_view( d_indices );
sort_enactor.sort( n_collected, sort_buffers, 0u, N_BITS );
#endif
timer.stop();
d_collect_sort_time += timer.seconds();
//
// copy all the indices inside the range to the output
//
//alloc_storage( output_suffixes, n_suffixes );
//alloc_storage( output_radices, n_suffixes );
timer.start();
// the buffer selector had inverted semantics
sort_buffers.selector = 1 - sort_buffers.selector;
// and copy everything to the output
thrust::copy(
d_indices.begin() + sort_buffers.selector * n_suffixes,
d_indices.begin() + sort_buffers.selector * n_suffixes + n_collected,
output_indices );
// and copy everything to the output
thrust::copy(
d_radices.begin() + sort_buffers.selector * n_suffixes,
d_radices.begin() + sort_buffers.selector * n_suffixes + n_collected,
output_radices );
timer.stop();
d_copy_time += timer.seconds();
return n_collected;
}
thrust::device_vector<uint32> d_indices;
thrust::device_vector<word_type> d_radices;
thrust::device_vector<uint32> d_buckets;
thrust::device_vector<uint8> d_temp_storage;
float d_setup_time;
float d_flatten_time;
float d_count_sort_time;
float d_collect_sort_time;
float d_remap_time;
float d_copy_time;
float d_filter_time;
};
//
// A host-side radix extractor context
//
template <typename string_set_type, uint32 SYMBOL_SIZE, uint32 DOLLAR_BITS, uint32 WORD_BITS>
struct HostStringSetRadices
{
HostStringSetRadices(const string_set_type string_set) : m_string_set( string_set ) {}
/// return the number of words needed to represent a given string length
///
uint32 num_words(const uint32 max_string_len) const
{
const uint32 SYMBOLS_PER_WORD = priv::symbols_per_word<SYMBOL_SIZE,WORD_BITS,DOLLAR_BITS>();
return (max_string_len + SYMBOLS_PER_WORD-1) / SYMBOLS_PER_WORD;
}
/// needed amount of device storage
///
uint64 needed_device_memory(const uint32 n_suffixes) const
{
return n_suffixes * sizeof(uint8) + // d_symbols
n_suffixes * sizeof(uint32); // d_active_suffixes
}
/// reserve any temporary space for the given amount of suffixes
///
void reserve(const uint32 n_suffixes, const uint32 block_size)
{
try
{
d_active_suffixes.resize( n_suffixes );
d_symbols.resize( n_suffixes );
h_symbols.resize( n_suffixes );
h_active_suffixes.resize( n_suffixes );
m_block.resize( n_suffixes * block_size );
}
catch (...)
{
log_error(stderr, "HostStringSetRadices::reserve() : allocation failed!\n");
throw;
}
}
/// initialize the suffixes to extract
///
void init(const uint32 n_suffixes, const uint2* _h_suffixes, const uint2* _d_suffixes)
{
m_suffixes = _h_suffixes;
d_suffixes = thrust::device_ptr<const uint2>( _d_suffixes );
}
/// initialize extraction of a slice of words
///
void init_slice(
const uint32 n_indices,
const uint32* d_indices,
const uint32 word_block_begin,
const uint32 word_block_end)
{
try
{
if (d_indices == NULL)
{
// extract the given radix word from each of the partially sorted suffixes on the host
priv::extract_radices(
m_string_set,
n_indices,
word_block_begin,
word_block_end,
WORD_BITS,
m_suffixes,
&m_block[0],
word_block_begin == 0 ? &h_symbols[0] : NULL ); // on the first iteration, load the BWT symbols too
}
else
{
// gather the list of active suffixes
thrust::gather(
thrust::device_ptr<const uint32>( d_indices ),
thrust::device_ptr<const uint32>( d_indices ) + n_indices,
d_suffixes,
d_active_suffixes.begin() );
// copy the list of active suffixes to the host
thrust::copy(
d_active_suffixes.begin(),
d_active_suffixes.begin() + n_indices,
h_active_suffixes.begin() );
// extract the given radix word from each of the partially sorted suffixes on the host
priv::extract_radices(
m_string_set,
n_indices,
word_block_begin,
word_block_end,
WORD_BITS,
&h_active_suffixes[0],
&m_block[0] );
}
}
catch (...)
{
log_error(stderr, "HostStringSetRadices::init_slice() : exception caught!\n");
throw;
}
}
/// extract the radices corresponding to a given word of the given suffixes
///
/// \param n_indices the input number of suffixes
/// \param d_indices a device vector of the indices to extract
/// \param word_idx the word index to extract
/// \param word_begin the beginning of the current slice range
/// \param word_idx the end of the current slice range
/// \param d_radices the destination device array to hold the output
///
void extract(
const uint32 n_indices,
const uint32* d_indices,
const uint32 word_idx,
const uint32 word_block_begin,
const uint32 word_block_end,
uint32* d_radices) const
{
try
{
// and copy them to the device
thrust::copy(
m_block.begin() + n_indices * (word_idx - word_block_begin),
m_block.begin() + n_indices * (word_idx - word_block_begin) + n_indices,
thrust::device_ptr<uint32>( d_radices ) );
}
catch (...)
{
log_error(stderr, "HostStringSetRadices::extract() : exception caught!\n");
throw;
}
}
/// extract the bwt of the given block
///
void dollar_bwt(
const uint32 begin,
const uint32 end,
uint8* h_bwt)
{
const int n_strings = int( end - begin );
// fetch the BWT symbols for the given strings
#pragma omp parallel for
for (int i = 0; i < n_strings; ++i)
{
const priv::string_set_bwt_functor<string_set_type> bwt( m_string_set );
h_bwt[i] = bwt( i + begin );
}
}
/// extract the bwt of the given block
///
void bwt(
const uint32 n_suffixes,
const uint32* d_indices,
uint8* h_bwt,
uint8* d_bwt)
{
try
{
if (d_indices != NULL)
{
#if 0
// fetch the BWT symbols for this block of suffixes
#pragma omp parallel for
for (int i = 0; i < n_suffixes; ++i)
{
const priv::string_set_bwt_functor<string_set_type> bwt( m_string_set );
h_symbols[i] = bwt( m_suffixes[i] );
}
#endif
#if 0
alloc_storage( m_block, n_suffixes );
// re-purpose the radix-block storage
uint32* h_indices = &m_block[0];
// copy the sorted indices to the host
thrust::copy(
thrust::device_ptr<const uint32>( d_indices ),
thrust::device_ptr<const uint32>( d_indices ) + n_suffixes,
h_indices );
// and compute the bwt of the block by gathering the symbols in suffix-sorted order
thrust::gather(
h_indices,
h_indices + n_suffixes,
h_symbols.begin(),
h_bwt );
#else
alloc_storage( d_symbols, n_suffixes );
// copy the symbols to the device
thrust::copy(
h_symbols.begin(),
h_symbols.begin() + n_suffixes,
d_symbols.begin() );
// gather the symbols in proper order
thrust::gather(
thrust::device_ptr<const uint32>( d_indices ),
thrust::device_ptr<const uint32>( d_indices ) + n_suffixes,
d_symbols.begin(),
thrust::device_ptr<uint8>( d_bwt ) );
// and copy the sorted symbols back to the host
thrust::copy(
thrust::device_ptr<uint8>( d_bwt ),
thrust::device_ptr<uint8>( d_bwt ) + n_suffixes,
h_bwt );
#endif
}
else
{
// fetch the BWT symbols for this block of suffixes
#pragma omp parallel for
for (unsigned int i = 0; i < n_suffixes; ++i)
{
const priv::string_set_bwt_functor<string_set_type> bwt( m_string_set );
h_bwt[i] = bwt( m_suffixes[i] );
}
// and copy the sorted symbols back to the device
thrust::copy(
h_bwt,
h_bwt + n_suffixes,
thrust::device_ptr<uint8>( d_bwt ) );
}
}
catch (...)
{
log_error(stderr, "HostStringSetRadices::bwt() : exception caught!\n");
throw;
}
}
/// return the amount of used device memory
///
uint64 allocated_device_memory() const
{
return
d_active_suffixes.size() * sizeof(uint2) +
d_symbols.size() * sizeof(uint8);
}
/// return the amount of used device memory
///
uint64 allocated_host_memory() const
{
return
m_block.size() * sizeof(uint2) +
h_active_suffixes.size() * sizeof(uint2) +
h_symbols.size() * sizeof(uint8);
}
string_set_type m_string_set;
const uint2* m_suffixes;
thrust::device_ptr<const uint2> d_suffixes;
thrust::device_vector<uint2> d_active_suffixes;
thrust::device_vector<uint8> d_symbols;
thrust::host_vector<uint2> h_active_suffixes;
thrust::host_vector<uint8> h_symbols;
thrust::host_vector<uint32> m_block;
};
//
// A host-side radix extractor context
//
template <typename string_set_type, uint32 SYMBOL_SIZE, uint32 DOLLAR_BITS, uint32 WORD_BITS>
struct DeviceStringSetRadices
{
DeviceStringSetRadices() {}
DeviceStringSetRadices(const string_set_type string_set) : m_string_set( string_set ) {}
/// return the number of words needed to represent a given string length
///
uint32 num_words(const uint32 max_string_len) const
{
const uint32 SYMBOLS_PER_WORD = priv::symbols_per_word<SYMBOL_SIZE,WORD_BITS,DOLLAR_BITS>();
return (max_string_len + SYMBOLS_PER_WORD-1) / SYMBOLS_PER_WORD;
}
/// needed amount of device storage
///
uint64 needed_device_memory(const uint32 n_suffixes) const
{
return n_suffixes; // d_symbols
}
/// reserve any temporary space for the given amount of suffixes
///
void reserve(const uint32 n_suffixes, const uint32 slice_size)
{
d_symbols.resize( n_suffixes );
}
/// set string set
///
void set(const string_set_type string_set) { m_string_set = string_set; }
/// initialize the suffixes to extract
///
void init(const uint32 n_suffixes, const uint2* _h_suffixes, const uint2* _d_suffixes)
{
d_suffixes = thrust::device_ptr<const uint2>( _d_suffixes );
}
/// initialize extraction of a slice of words
///
void init_slice(
const uint32 n_indices,
const uint32* d_indices,
const uint32 word_block_begin,
const uint32 word_block_end) {}
/// extract the radices corresponding to a given word of the given suffixes
///
/// \param n_indices the input number of suffixes
/// \param d_indices a device vector of the indices to extract
/// \param word_idx the word index to extract
/// \param word_begin the beginning of the current slice range
/// \param word_idx the end of the current slice range
/// \param d_radices the destination device array to hold the output
///
void extract(
const uint32 n_indices,
const uint32* d_indices,
const uint32 word_idx,
const uint32 word_block_begin,
const uint32 word_block_end,
uint32* d_radices) const
{
// extract the given radix word from each of the partially sorted suffixes in a device temp buffer
priv::local_set_suffix_word_functor<SYMBOL_SIZE,WORD_BITS,DOLLAR_BITS,string_set_type,uint32> word_functor( m_string_set, word_idx );
if (d_indices == NULL)
{
thrust::copy(
thrust::make_transform_iterator( d_suffixes, word_functor ),
thrust::make_transform_iterator( d_suffixes, word_functor ) + n_indices,
thrust::device_ptr<uint32>( d_radices ) );
}
else
{
thrust::copy(
thrust::make_transform_iterator( thrust::make_permutation_iterator( d_suffixes, thrust::device_ptr<const uint32>( d_indices ) ), word_functor ),
thrust::make_transform_iterator( thrust::make_permutation_iterator( d_suffixes, thrust::device_ptr<const uint32>( d_indices ) ), word_functor ) + n_indices,
thrust::device_ptr<uint32>( d_radices ) );
}
}
/// extract the bwt of the given block
///
void dollar_bwt(
const uint32 begin,
const uint32 end,
uint8* h_bwt)
{
const int n_strings = end - begin;
alloc_storage( d_symbols, n_strings );
// fetch the BWT symbols for the given strings
thrust::transform(
thrust::make_counting_iterator<uint32>(begin),
thrust::make_counting_iterator<uint32>(end),
d_symbols.begin(),
priv::string_set_bwt_functor<string_set_type>( m_string_set ) );
// and copy the result to the host
thrust::copy(
d_symbols.begin(),
d_symbols.begin() + n_strings,
h_bwt );
}
/// extract the bwt of the given block
///
void bwt(
const uint32 n_suffixes,
const uint32* d_indices,
uint8* h_bwt,
uint8* d_bwt)
{
if (d_indices != NULL)
{
alloc_storage( d_symbols, n_suffixes );
// fetch the BWT symbols for this block of suffixes
thrust::transform(
d_suffixes,
d_suffixes + n_suffixes,
d_symbols.begin(),
priv::string_set_bwt_functor<string_set_type>( m_string_set ) );
// and compute the bwt of the block by gathering the symbols in suffix-sorted order
thrust::gather(
thrust::device_ptr<const uint32>( d_indices ),
thrust::device_ptr<const uint32>( d_indices ) + n_suffixes,
d_symbols.begin(),
thrust::device_ptr<uint8>( d_bwt ) );
}
else
{
// fetch the BWT symbols for this block of suffixes
thrust::transform(
d_suffixes,
d_suffixes + n_suffixes,
thrust::device_ptr<uint8>( d_bwt ),
priv::string_set_bwt_functor<string_set_type>( m_string_set ) );
}
// and copy the result to the host
thrust::copy(
thrust::device_ptr<uint8>( d_bwt ),
thrust::device_ptr<uint8>( d_bwt ) + n_suffixes,
h_bwt );
}
/// return the amount of used device memory
///
uint64 allocated_device_memory() const
{
return d_symbols.size() * sizeof(uint8);
}
/// return the amount of used device memory
///
uint64 allocated_host_memory() const
{
return 0u;
}
string_set_type m_string_set;
thrust::device_ptr<const uint2> d_suffixes;
thrust::device_vector<uint8> d_symbols;
};
/// Collect dollar symbols out of a BWT + SA block
///
struct DollarExtractor
{
/// constructor
///
DollarExtractor() :
offset(0),
n_dollars(0) {}
/// process a batch of BWT symbols
///
uint32 extract(
const uint32 n_suffixes,
const uint8* h_bwt,
const uint8* d_bwt,
const uint2* h_suffixes,
const uint2* d_suffixes,
const uint32* d_indices);
uint64 offset;
uint32 n_dollars;
thrust::device_vector<uint64> d_dollar_ranks;
thrust::device_vector<uint32> d_dollar_indices;
thrust::device_vector<uint64> d_dollars;
thrust::host_vector<uint64> h_dollar_ranks;
thrust::host_vector<uint64> h_dollars;
thrust::device_vector<uint8> d_temp_storage;
};
// ------------------------------------------------------------------------------------------------------------- //
// the following functions implement device_copy() and device_scatter() - special-purpose functions to copy
// and scatter a set of symbols to a packed stream.
// ------------------------------------------------------------------------------------------------------------- //
/// a simple auxiliary kernel to perform generic device-to-device copies, specialized for packed streams
///
template <typename input_iterator, typename output_iterator, typename index_type>
__global__ void simple_device_copy_kernel(
const uint32 n,
const input_iterator input,
output_iterator output,
const index_type offset)
{
const uint32 thread_id = threadIdx.x + blockIdx.x*blockDim.x;
if (thread_id < n)
output[offset + thread_id] = input[thread_id];
}
/// a simple auxiliary kernel to perform generic device-to-device copies, specialized for packed streams
///
template <typename input_iterator, typename storage_type, uint32 SYMBOL_SIZE, bool BIG_ENDIAN, typename index_type>
__global__ void packed_device_copy_kernel(
const uint32 n,
const input_iterator input,
PackedStream<storage_type,uint8,SYMBOL_SIZE,BIG_ENDIAN,index_type> output,
const index_type offset)
{
const uint32 thread_id = threadIdx.x + blockIdx.x*blockDim.x;
//
// care must be used to avoid write-conflicts, hence we assign all symbols belonging
// to the same output word to a single thread
//
typedef typename PackedStream<storage_type,uint8,SYMBOL_SIZE,BIG_ENDIAN,index_type>::storage_type word_type;
const uint32 SYMBOLS_PER_WORD = (8u*sizeof(word_type))/SYMBOL_SIZE;
const uint32 word_offset = uint32( (offset + output.index()) & (SYMBOLS_PER_WORD-1) );
const uint32 elem_begin = thread_id ? (thread_id+0) * SYMBOLS_PER_WORD - word_offset : 0u;
const uint32 elem_end = nvbio::min( (thread_id+1) * SYMBOLS_PER_WORD - word_offset, n );
if (elem_begin < n)
{
for (uint32 i = elem_begin; i < elem_end; ++i)
output[offset+i] = input[i];
}
}
/// a dispatcher for device_copy
///
template <typename input_iterator, typename output_iterator, typename index_type>
struct device_copy_dispatch
{
/// copy n elements from the input stream to the output
///
static void copy(
const uint32 n,
const input_iterator input,
const output_iterator output,
const index_type offset)
{
const uint32 batch_size = cuda::max_grid_size();
for (uint32 batch_begin = 0; batch_begin < n; batch_begin += batch_size)
{
const uint32 batch_end = nvbio::min( batch_begin + batch_size, n );
const uint32 blockdim = 128;
const uint32 n_blocks = util::divide_ri( batch_end - batch_begin, blockdim );
simple_device_copy_kernel<<<n_blocks,blockdim>>>( n, input, output, offset );
}
}
};
/// a dispatcher for device_copy
///
template <typename input_iterator, typename storage_type, uint32 SYMBOL_SIZE, bool BIG_ENDIAN, typename index_type>
struct device_copy_dispatch<
input_iterator,
PackedStream<storage_type,uint8,SYMBOL_SIZE,BIG_ENDIAN,index_type>,
index_type>
{
typedef PackedStream<storage_type,uint8,SYMBOL_SIZE,BIG_ENDIAN,index_type> output_iterator;
/// copy n elements from the input stream to the output
///
static void copy(
const uint32 n,
const input_iterator input,
const output_iterator output,
const index_type offset)
{
typedef typename PackedStream<storage_type,uint8,SYMBOL_SIZE,BIG_ENDIAN,index_type>::storage_type word_type;
const uint32 SYMBOLS_PER_WORD = (8u*sizeof(word_type))/SYMBOL_SIZE;
const uint32 batch_size = cuda::max_grid_size();
for (uint32 batch_begin = 0; batch_begin < n; batch_begin += batch_size)
{
const uint32 batch_end = nvbio::min( batch_begin + batch_size, n );
const uint32 blockdim = 128;
const uint32 n_words = util::divide_ri( batch_end - batch_begin, SYMBOLS_PER_WORD ) + 1u;
const uint32 n_blocks = util::divide_ri( n_words, blockdim );
packed_device_copy_kernel<<<n_blocks,blockdim>>>( batch_end - batch_begin, input, output, offset + batch_begin );
}
}
};
/// copy a set of n symbols from a given input stream to a given output stream
///
template <typename input_iterator, typename output_iterator, typename index_type>
void device_copy(
const uint32 n,
const input_iterator input,
const output_iterator output,
const index_type offset)
{
device_copy_dispatch<input_iterator,output_iterator,index_type>::copy( n, input, output, offset );
}
/// an auxiliary kernel to scatter a set of symbols into a sparse set of slots of a given output stream;
/// this kernel copies a full range of symbols per thread, where individual ranges are guaranteed to
/// touch distinct words of the underlying storage where the output is packed.
///
template <typename input_iterator, typename slot_iterator, typename range_iterator, typename storage_type, uint32 SYMBOL_SIZE, bool BIG_ENDIAN, typename index_type>
__global__ void device_scatter_kernel(
const uint32 begin,
const uint32 end,
const range_iterator ranges,
const input_iterator input,
const slot_iterator slots,
PackedStream<storage_type,uint8,SYMBOL_SIZE,BIG_ENDIAN,index_type> output)
{
const uint32 thread_id = threadIdx.x + blockIdx.x*blockDim.x;
const uint32 idx = thread_id + begin;
if (idx >= end)
return;
//
// care must be used to avoid write-conflicts, hence we assign all symbols belonging
// to the same output word to a single thread
//
const uint32 elem_begin = idx ? ranges[ idx-1 ] : 0u;
const uint32 elem_end = ranges[ idx ];
for (uint32 i = elem_begin; i < elem_end; ++i)
{
const uint32 slot = slots[i];
output[ slot ] = input[i];
}
}
/// scatter a set of symbols into a sparse set of slots of a given output stream
///
template <typename input_iterator, typename slot_iterator, typename output_iterator>
struct device_scatter_dispatch
{
static void enact(
const uint32 n,
const input_iterator input,
const slot_iterator slots,
output_iterator output)
{
thrust::scatter(
input,
input + n,
slots,
output );
}
};
/// scatter a set of symbols into a sparse set of slots of a given output stream
///
template <typename input_iterator, typename slot_iterator, typename storage_type, uint32 SYMBOL_SIZE, bool BIG_ENDIAN, typename index_type>
struct device_scatter_dispatch<
input_iterator,
slot_iterator,
PackedStream<storage_type,uint8,SYMBOL_SIZE,BIG_ENDIAN,index_type> >
{
typedef PackedStream<storage_type,uint8,SYMBOL_SIZE,BIG_ENDIAN,index_type> output_iterator;
static void enact(
const uint32 n,
const input_iterator input,
const slot_iterator slots,
output_iterator output)
{
// find out a set of ranges of input symbols covering distinct words in the output: this is done
// looking at the words covered by each of the symbols, and reducing together all symbols falling
// in the same word.
thrust::device_vector<uint32> d_ranges( n );
thrust::device_vector<uint32> d_keys( n );
typedef typename PackedStream<storage_type,uint8,SYMBOL_SIZE,BIG_ENDIAN,index_type>::storage_type word_type;
const uint32 SYMBOLS_PER_WORD = (8u*sizeof(word_type))/SYMBOL_SIZE;
const uint32 n_ranges = uint32( thrust::reduce_by_key(
thrust::make_transform_iterator( slots, add_divide_functor( output.index(), SYMBOLS_PER_WORD ) ),
thrust::make_transform_iterator( slots + n, add_divide_functor( output.index(), SYMBOLS_PER_WORD ) ),
thrust::make_counting_iterator<uint32>(1u),
d_keys.begin(),
d_ranges.begin(),
thrust::equal_to<uint32>(),
thrust::maximum<uint32>() ).first - d_keys.begin() );
const uint32 batch_size = cuda::max_grid_size();
for (uint32 batch_begin = 0; batch_begin < n_ranges; batch_begin += batch_size)
{
const uint32 batch_end = nvbio::min( batch_begin + batch_size, n_ranges );
// at this point we can scatter the identified ranges
const uint32 blockdim = 128;
const uint32 n_blocks = util::divide_ri( batch_end - batch_begin, blockdim );
device_scatter_kernel<<<n_blocks,blockdim>>>(
batch_begin,
batch_end,
d_ranges.begin(),
input,
slots,
output );
}
}
};
/// scatter a set of symbols into a sparse set of slots of a given output stream
///
template <typename input_iterator, typename slot_iterator, typename output_iterator>
void device_scatter(
const uint32 n,
const input_iterator input,
const slot_iterator slots,
output_iterator output)
{
device_scatter_dispatch<input_iterator,slot_iterator,output_iterator>::enact(
n,
input,
slots,
output );
}
// ------------------------------------------------------------------------------------------------------------- //
/// pack a set of head flags into a bit-packed array
///
void pack_flags(
const uint32 n,
const uint8* flags,
uint32* comp_flags);
/// build a set of head flags looking at adjacent keys
///
void build_head_flags(
const uint32 n,
const uint32* keys,
uint8* flags);
/// build a set of head flags looking at adjacent keys
///
void build_head_flags(
const uint32 n,
const uint64* keys,
uint8* flags);
} // namespace priv
} // namespace nvbio
|
FeatureLPPooling.c | #ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "generic/FeatureLPPooling.c"
#else
#ifndef FEATURE_LP_DEFS
#define FEATURE_LP_DEFS
typedef struct {
size_t size[4];
size_t stride[4];
} FeatureLPPoolingSizes;
static inline size_t flpGetOffset(FeatureLPPoolingSizes* s,
size_t batch,
size_t feature,
size_t opt1,
size_t opt2) {
return s->stride[0] * batch +
s->stride[1] * feature +
s->stride[2] * opt1 +
s->stride[3] * opt2;
}
static inline size_t flpOutputSize(size_t inputSize,
size_t width,
size_t stride) {
return ((inputSize - width) / stride) + 1;
}
#endif // FEATURE_LP_DEFS
FeatureLPPoolingSizes
THNN_(FeatureLPPooling_upcastCPU)(THTensor* t, bool batchMode) {
int dim = THTensor_(nDimension)(t);
// Upcast to [batch dim][feature dim][opt dim 1][opt dim 2]
FeatureLPPoolingSizes s;
for (int i = 0; i < 4; ++i) {
s.size[i] = 1;
s.stride[i] = 1;
}
if (dim == 1) {
THAssert(!batchMode);
// [feature dim]
s.size[1] = THTensor_(size)(t, 0);
s.stride[1] = THTensor_(stride)(t, 0);
} else if (dim == 2) {
if (batchMode) {
// [batch dim][feature dim]
for (int i = 0; i < 2; ++i) {
s.size[i] = THTensor_(size)(t, i);
s.stride[i] = THTensor_(stride)(t, i);
}
} else {
// [feature dim][opt dim 1]
s.size[1] = THTensor_(size)(t, 0);
s.stride[1] = THTensor_(stride)(t, 0);
s.size[2] = THTensor_(size)(t, 1);
s.stride[2] = THTensor_(stride)(t, 1);
}
} else if (dim == 3) {
if (batchMode) {
// [batch dim][feature dim][opt dim 1]
for (int i = 0; i < 3; ++i) {
s.size[i] = THTensor_(size)(t, i);
s.stride[i] = THTensor_(stride)(t, i);
}
} else {
// [feature dim][opt dim 1][opt dim 2]
for (int i = 1; i < 4; ++i) {
s.size[i] = THTensor_(size)(t, i - 1);
s.stride[i] = THTensor_(stride)(t, i - 1);
}
}
} else if (dim == 4) {
// [batch dim][feature dim][opt dim 1][opt dim 2]
THAssert(batchMode);
for (int i = 0; i < 4; ++i) {
s.size[i] = THTensor_(size)(t, i);
s.stride[i] = THTensor_(stride)(t, i);
}
}
return s;
}
void
THNN_(FeatureLPPooling_resizeForOutputCPU)(THTensor* toResize,
THTensor* input,
bool batchMode,
int width,
int stride) {
int inputDim = THTensor_(nDimension)(input);
THAssert(inputDim >= 1 && inputDim <= 4);
long outSize =
flpOutputSize(THTensor_(size)(input, 0), width, stride);
if (batchMode) {
THAssert(inputDim > 1);
outSize =
flpOutputSize(THTensor_(size)(input, 1), width, stride);
} else {
THAssert(inputDim < 4);
}
if (inputDim == 1) {
THTensor_(resize1d)(toResize, outSize);
} else if (inputDim == 2) {
if (batchMode) {
THTensor_(resize2d)(toResize,
THTensor_(size)(input, 0),
outSize);
} else {
THTensor_(resize2d)(toResize,
outSize,
THTensor_(size)(input, 1));
}
} else if (inputDim == 3) {
if (batchMode) {
THTensor_(resize3d)(toResize,
THTensor_(size)(input, 0), outSize,
THTensor_(size)(input, 2));
} else {
THTensor_(resize3d)(toResize,
outSize, THTensor_(size)(input, 1),
THTensor_(size)(input, 2));
}
} else if (inputDim == 4) {
THTensor_(resize4d)(toResize,
THTensor_(size)(input, 0),
outSize,
THTensor_(size)(input, 2),
THTensor_(size)(input, 3));
}
}
// Makes `toResize` the same size/dimensionality as `src`
void
THNN_(FeatureLPPooling_resizeCPU)(THTensor* toResize,
THTensor* src) {
int inputDim = THTensor_(nDimension)(src);
THAssert(inputDim >= 1 && inputDim <= 4);
if (inputDim == 1) {
THTensor_(resize1d)(toResize,
THTensor_(size)(src, 0));
} else if (inputDim == 2) {
THTensor_(resize2d)(
toResize,
THTensor_(size)(src, 0),
THTensor_(size)(src, 1));
} else if (inputDim == 3) {
THTensor_(resize3d)(
toResize,
THTensor_(size)(src, 0),
THTensor_(size)(src, 1),
THTensor_(size)(src, 2));
} else if (inputDim == 4) {
THTensor_(resize4d)(
toResize,
THTensor_(size)(src, 0),
THTensor_(size)(src, 1),
THTensor_(size)(src, 2),
THTensor_(size)(src, 3));
}
}
void
THNN_(FeatureLPPooling_updateOutput)(
THNNState *state,
THTensor *input,
THTensor *output,
accreal power,
int width,
int stride,
bool batchMode) {
int inputDim = THTensor_(nDimension)(input);
if (batchMode) {
THArgCheck(inputDim >= 2 && inputDim <= 4, 2,
"input must be 2-4 dimensions for batch mode");
} else {
THArgCheck(inputDim >= 1 && inputDim <= 3, 2,
"input must be 1-3 dimensions for non-batch mode");
}
FeatureLPPoolingSizes inputDesc =
THNN_(FeatureLPPooling_upcastCPU)(input, batchMode);
// Make sure the feature dimension is properly sized
THArgCheck(inputDesc.size[1] >= width, 3,
"input: feature dimension must be >= width");
// Make sure that width and stride are within range
THArgCheck(width >= 2 && width <= 16, 5,
"width must be between 2 - 16");
THArgCheck(stride >= 1 && stride <= 4, 6,
"stride must be between 1 - 4");
// Resize output
THNN_(FeatureLPPooling_resizeForOutputCPU)(
output, input, batchMode, width, stride);
FeatureLPPoolingSizes outputDesc =
THNN_(FeatureLPPooling_upcastCPU)(output, batchMode);
real* inputP = THTensor_(data)(input);
real* outputP = THTensor_(data)(output);
#pragma omp parallel for
for (size_t batch = 0; batch < inputDesc.size[0]; ++batch) {
for (size_t opt1 = 0; opt1 < inputDesc.size[2]; ++opt1) {
for (size_t opt2 = 0; opt2 < inputDesc.size[3]; ++opt2) {
for (size_t outputFeature = 0;
outputFeature < outputDesc.size[1]; ++outputFeature) {
accreal v = (accreal) 0;
for (size_t i = 0; i < width; ++i) {
size_t inputFeature = outputFeature * stride + i;
if (inputFeature >= inputDesc.size[1]) {
break;
}
v +=
pow(inputP[flpGetOffset(&inputDesc,
batch,
inputFeature,
opt1,
opt2)], power);
}
outputP[flpGetOffset(&outputDesc, batch, outputFeature, opt1, opt2)] =
pow(v, (accreal) 1 / power);
}
}
}
}
}
void
THNN_(FeatureLPPooling_updateGradInput)(
THNNState *state,
THTensor* gradOutput,
THTensor* input,
THTensor* output,
THTensor* gradInput,
accreal power,
int width,
int stride,
bool batchMode) {
int inputDim = THTensor_(nDimension)(input);
if (batchMode) {
THArgCheck(inputDim >= 2 && inputDim <= 4, 3,
"input must be 2-4 dimensions for batch mode");
} else {
THArgCheck(inputDim >= 1 && inputDim <= 3, 3,
"input must be 1-3 dimensions for non-batch mode");
}
FeatureLPPoolingSizes inputDesc =
THNN_(FeatureLPPooling_upcastCPU)(input, batchMode);
FeatureLPPoolingSizes gradOutputDesc =
THNN_(FeatureLPPooling_upcastCPU)(gradOutput, batchMode);
FeatureLPPoolingSizes outputDesc =
THNN_(FeatureLPPooling_upcastCPU)(output, batchMode);
// Make sure the feature dimension is properly sized
THArgCheck(inputDesc.size[1] >= width, 3,
"input: feature dimension must be >= width");
// Make sure that width and stride are within range
THArgCheck(width >= 2 && width <= 16, 7,
"width must be between 2 - 16");
THArgCheck(stride >= 1 && stride <= 4, 8,
"stride must be between 1 - 4");
for (int i = 0; i < 4; ++i) {
THAssertMsg(outputDesc.size[i] == gradOutputDesc.size[i],
"output and gradOutput sizes do not match");
}
// Make sure that the input sizes produce the output sizes
THArgCheck(flpOutputSize(inputDesc.size[1], width, stride) ==
outputDesc.size[1], 3,
"input and output sizes do not match with respect to "
"width and stride");
// Resize `gradInput` based on `input`
THNN_(FeatureLPPooling_resizeCPU)(gradInput, input);
// Zero gradInput for accumulation
THTensor_(zero)(gradInput);
FeatureLPPoolingSizes gradInputDesc =
THNN_(FeatureLPPooling_upcastCPU)(gradInput, batchMode);
real* gradOutputP = THTensor_(data)(gradOutput);
real* gradInputP = THTensor_(data)(gradInput);
real* outputP = THTensor_(data)(output);
real* inputP = THTensor_(data)(input);
#pragma omp parallel for
for (size_t batch = 0; batch < inputDesc.size[0]; ++batch) {
for (size_t opt1 = 0; opt1 < inputDesc.size[2]; ++opt1) {
for (size_t opt2 = 0; opt2 < inputDesc.size[3]; ++opt2) {
for (size_t outputFeature = 0;
outputFeature < outputDesc.size[1]; ++outputFeature) {
// Load output (f(x_is)). It is possible that this is zero, in
// which case we'll ignore this point.
real outputV =
outputP[
flpGetOffset(&outputDesc, batch, outputFeature, opt1, opt2)];
if (outputV == (real) 0) {
continue;
}
for (size_t i = 0; i < width; ++i) {
size_t inputFeature = outputFeature * stride + i;
THAssert(inputFeature < inputDesc.size[1]);
real gradOutputV =
gradOutputP[
flpGetOffset(&gradOutputDesc, batch, outputFeature, opt1, opt2)];
real inputV =
inputP[
flpGetOffset(&inputDesc, batch, inputFeature, opt1, opt2)];
// Calculate grad * (x_i / f(x_is))^(p - 1)
real v = gradOutputV * pow(inputV / outputV, power - (accreal) 1);
gradInputP[
flpGetOffset(&gradInputDesc, batch, inputFeature, opt1, opt2)]
+= v;
}
}
}
}
}
}
#endif
|
labels.h | /*
An Experimental Study on Hub Labeling based Shortest Path Algorithms [Experiments and Analyses]
Authors: Ye Li, Leong Hou U, Man Lung Yiu, Ngai Meng Kou
Contact: yb47438@umac.mo
Affiliation: University of Macau
The MIT License (MIT)
Copyright (c) 2016 University of Macau
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
#ifndef LABELS_H
#define LABELS_H
#include <limits>
#include <climits>
#include <stdlib.h>
#include <iostream>
#include <sys/time.h>
#include "graph.h"
#include "paras.h"
#include <malloc.h>
#include <xmmintrin.h>
//typedef unsigned __int64 BPSeed;
#include <omp.h>
#include<bitset>
#define numOfVertices SP_Constants::numOfVertices
#define numOfEdges SP_Constants::numOfEdges
#define INF_WEIGHT SP_Constants::INF_WEIGHT
struct index_t {
vector<NodeID> spt_v;
vector<EdgeWeight> spt_d;
NodeID size() {
return spt_v.size();
}
};
struct index_t_p {
NodeID* spt_v;
EdgeWeight* spt_d;
}__attribute__((aligned(64))); // Aligned for cache lines;
struct two_index_t_p {
NodeID* spt_v;
EdgeWeight* spt_d;
uint8_t* spt_lv;
EdgeWeight* spt_ld;
}__attribute__((aligned(64))); // Aligned for cache lines;
struct index_t_path {
vector<NodeID> spt_v;
vector<NodeID> spt_p;//parent nodes
vector<EdgeWeight> spt_d;
NodeID size() {
return spt_v.size();
}
};
struct index_t_path_p {
NodeID* spt_v;
NodeID* spt_p;
EdgeWeight* spt_d;
};
struct query_info {
NodeID meet_node;
NodeID search_len;
double time_cost;
EdgeWeight distance;
};
template<int kNumBitParallelRoots = 50>
struct index_t_bp {
NodeID* spt_v;
EdgeWeight* spt_d;
EdgeWeight bpspt_d[kNumBitParallelRoots];
uint64_t bpspt_s[kNumBitParallelRoots][2];
}__attribute__((aligned(64))); // Aligned for cache lines;
struct token_t {
NodeID* sptc_v; // sptc_v[0] is the root
EdgeWeight* sptc_d; // |*| = k + 1, sptc_d[0] is the number of children - k
unsigned char* sptc_fbv; // first-level bit vector
unsigned char* sptc_sbv; // second-level bit vector
NodeID* sptc_pathv; // intermediate point for a path
}__attribute__((aligned(64)));
class CLabel {
public:
token_t* supertokenindex_p;
token_t* tokenindex_p;
NodeID* anchor_p;
NodeID numOfTokens;
long total_children;
token_t* r_supertokenindex_p;
token_t* r_tokenindex_p;
NodeID* r_anchor_p;
NodeID r_numOfTokens;
long r_total_children;
void save_labels(const char* save_filename) {
ofstream ofs(save_filename, ios::binary | ios::out);
ofs.write((const char*)&numOfVertices, sizeof(numOfVertices));
for (NodeID v = 0; v < numOfVertices; ++v) {
ofs.write((const char*)&anchor_p[v], sizeof(anchor_p[v]));
// ofs.write((const char*)&index_[v].spt_d[i], sizeof(index_[v].spt_d[i]));
}
ofs.write((const char*)&numOfTokens, sizeof(numOfTokens));
for (NodeID t = 0; t < numOfTokens; ++t) {
token_t& tt = tokenindex_p[t];
EdgeWeight tsize = tt.sptc_d[0];
ofs.write((const char*)&tt.sptc_v[0], sizeof(tt.sptc_v[0]));
ofs.write((const char*)&tsize, sizeof(tsize));
for(NodeID c = 0; c < tsize; ++c){
ofs.write((const char*)&tt.sptc_v[1 + c], sizeof(tt.sptc_v[1 + c]));
ofs.write((const char*)&tt.sptc_d[1 + c], sizeof(tt.sptc_d[1 + c]));
}
}
ofs.close();
}
void save_labels_path(const char* save_filename) {
ofstream ofs(save_filename, ios::binary | ios::out);
ofs.write((const char*)&numOfVertices, sizeof(numOfVertices));
for (NodeID v = 0; v < numOfVertices; ++v) {
ofs.write((const char*)&anchor_p[v], sizeof(anchor_p[v]));
// ofs.write((const char*)&index_[v].spt_d[i], sizeof(index_[v].spt_d[i]));
}
ofs.write((const char*)&numOfTokens, sizeof(numOfTokens));
for (NodeID t = 0; t < numOfTokens; ++t) {
token_t& tt = tokenindex_p[t];
EdgeWeight tsize = tt.sptc_d[0];
ofs.write((const char*)&tt.sptc_v[0], sizeof(tt.sptc_v[0]));
ofs.write((const char*)&tsize, sizeof(tsize));
for(NodeID c = 0; c < tsize; ++c){
ofs.write((const char*)&tt.sptc_v[1 + c], sizeof(tt.sptc_v[1 + c]));
ofs.write((const char*)&tt.sptc_d[1 + c], sizeof(tt.sptc_d[1 + c]));
ofs.write((const char*)&tt.sptc_pathv[1 + c], sizeof(tt.sptc_pathv[1 + c]));
}
}
ofs.close();
}
void save_labels_d(const char* save_filename) {
ofstream ofs(save_filename, ios::binary | ios::out);
ofs.write((const char*)&numOfVertices, sizeof(numOfVertices));
for (NodeID v = 0; v < numOfVertices; ++v) {
ofs.write((const char*)&anchor_p[v], sizeof(anchor_p[v]));
// ofs.write((const char*)&index_[v].spt_d[i], sizeof(index_[v].spt_d[i]));
}
for (NodeID v = 0; v < numOfVertices; ++v) {
ofs.write((const char*)&r_anchor_p[v], sizeof(r_anchor_p[v]));
// ofs.write((const char*)&index_[v].spt_d[i], sizeof(index_[v].spt_d[i]));
}
ofs.write((const char*)&numOfTokens, sizeof(numOfTokens));
for (NodeID t = 0; t < numOfTokens; ++t) {
token_t& tt = tokenindex_p[t];
EdgeWeight tsize = tt.sptc_d[0];
ofs.write((const char*)&tt.sptc_v[0], sizeof(tt.sptc_v[0]));
ofs.write((const char*)&tsize, sizeof(tsize));
for(NodeID c = 0; c < tsize; ++c){
ofs.write((const char*)&tt.sptc_v[1 + c], sizeof(tt.sptc_v[1 + c]));
ofs.write((const char*)&tt.sptc_d[1 + c], sizeof(tt.sptc_d[1 + c]));
}
}
ofs.write((const char*)&r_numOfTokens, sizeof(r_numOfTokens));
for (NodeID t = 0; t < r_numOfTokens; ++t) {
token_t& tt = r_tokenindex_p[t];
EdgeWeight tsize = tt.sptc_d[0];
ofs.write((const char*)&tt.sptc_v[0], sizeof(tt.sptc_v[0]));
ofs.write((const char*)&tsize, sizeof(tsize));
for(NodeID c = 0; c < tsize; ++c){
ofs.write((const char*)&tt.sptc_v[1 + c], sizeof(tt.sptc_v[1 + c]));
ofs.write((const char*)&tt.sptc_d[1 + c], sizeof(tt.sptc_d[1 + c]));
}
}
ofs.close();
}
void load_labels_path(const char* load_filename) {
total_children = 0;
tokenindex_p = NULL;
anchor_p = NULL;
ifstream ifs(load_filename);
NodeID isize = 0;
ifs.read((char*)&isize, sizeof(isize));
numOfVertices = isize;
anchor_p = (NodeID*)memalign(64, numOfVertices * sizeof(NodeID));
NodeID anchor_id;
for (NodeID v = 0; v < numOfVertices; ++v) {
ifs.read((char*)&anchor_id, sizeof(anchor_id));
anchor_p[v] = anchor_id;
}
ifs.read((char*)&isize, sizeof(isize));
numOfTokens = isize;
tokenindex_p = (token_t*)memalign(64, numOfTokens * sizeof(token_t));
EdgeWeight csize;
NodeID cid;
EdgeWeight cd;
for (NodeID v = 0; v < numOfTokens; ++v) {
token_t& tt = tokenindex_p[v];
ifs.read((char*)&cid, sizeof(cid));
ifs.read((char*)&csize, sizeof(csize));
tt.sptc_v = (NodeID*)memalign(64, (csize + 1) * sizeof(NodeID));
tt.sptc_d = (EdgeWeight*)memalign(64, (csize + 1 ) * sizeof(EdgeWeight));
total_children += (csize + 1);
tt.sptc_v[0] = cid;
tt.sptc_d[0] = csize;
for (NodeID i = 0; i < csize; ++i) {
ifs.read((char*)&cid, sizeof(cid));
ifs.read((char*)&cd, sizeof(cd));
tt.sptc_v[i + 1] = cid;
tt.sptc_d[i + 1] = cd;
}
}
ifs.close();
}
void load_labels(const char* load_filename) {
total_children = 0;
tokenindex_p = NULL;
anchor_p = NULL;
ifstream ifs(load_filename);
NodeID isize = 0;
ifs.read((char*)&isize, sizeof(isize));
numOfVertices = isize;
anchor_p = (NodeID*)memalign(64, numOfVertices * sizeof(NodeID));
NodeID anchor_id;
for (NodeID v = 0; v < numOfVertices; ++v) {
ifs.read((char*)&anchor_id, sizeof(anchor_id));
anchor_p[v] = anchor_id;
}
ifs.read((char*)&isize, sizeof(isize));
numOfTokens = isize;
tokenindex_p = (token_t*)memalign(64, numOfTokens * sizeof(token_t));
EdgeWeight csize;
NodeID cid;
EdgeWeight cd;
for (NodeID v = 0; v < numOfTokens; ++v) {
token_t& tt = tokenindex_p[v];
ifs.read((char*)&cid, sizeof(cid));
ifs.read((char*)&csize, sizeof(csize));
tt.sptc_v = (NodeID*)memalign(64, (csize + 1) * sizeof(NodeID));
tt.sptc_d = (EdgeWeight*)memalign(64, (csize + 1 ) * sizeof(EdgeWeight));
total_children += (csize + 1);
tt.sptc_v[0] = cid;
tt.sptc_d[0] = csize;
for (NodeID i = 0; i < csize; ++i) {
ifs.read((char*)&cid, sizeof(cid));
ifs.read((char*)&cd, sizeof(cd));
tt.sptc_v[i + 1] = cid;
tt.sptc_d[i + 1] = cd;
}
}
ifs.close();
}
void load_labels_d(const char* load_filename) {
total_children = 0;
r_total_children = 0;
tokenindex_p = NULL;
anchor_p = NULL;
r_tokenindex_p = NULL;
r_anchor_p = NULL;
ifstream ifs(load_filename);
NodeID isize = 0;
ifs.read((char*)&isize, sizeof(isize));
numOfVertices = isize;
anchor_p = (NodeID*)memalign(64, numOfVertices * sizeof(NodeID));
r_anchor_p = (NodeID*)memalign(64, numOfVertices * sizeof(NodeID));
NodeID anchor_id;
for (NodeID v = 0; v < numOfVertices; ++v) {
ifs.read((char*)&anchor_id, sizeof(anchor_id));
anchor_p[v] = anchor_id;
}
for (NodeID v = 0; v < numOfVertices; ++v) {
ifs.read((char*)&anchor_id, sizeof(anchor_id));
r_anchor_p[v] = anchor_id;
}
ifs.read((char*)&isize, sizeof(isize));
numOfTokens = isize;
tokenindex_p = (token_t*)memalign(64, numOfTokens * sizeof(token_t));
EdgeWeight csize;
NodeID cid;
EdgeWeight cd;
for (NodeID v = 0; v < numOfTokens; ++v) {
token_t& tt = tokenindex_p[v];
ifs.read((char*)&cid, sizeof(cid));
ifs.read((char*)&csize, sizeof(csize));
tt.sptc_v = (NodeID*)memalign(64, (csize + 1) * sizeof(NodeID));
tt.sptc_d = (EdgeWeight*)memalign(64, (csize + 1 ) * sizeof(EdgeWeight));
total_children += (csize + 1);
tt.sptc_v[0] = cid;
tt.sptc_d[0] = csize;
for (NodeID i = 0; i < csize; ++i) {
ifs.read((char*)&cid, sizeof(cid));
ifs.read((char*)&cd, sizeof(cd));
tt.sptc_v[i + 1] = cid;
tt.sptc_d[i + 1] = cd;
}
}
ifs.read((char*)&isize, sizeof(isize));
r_numOfTokens = isize;
r_tokenindex_p = (token_t*)memalign(64, r_numOfTokens * sizeof(token_t));
for (NodeID v = 0; v < r_numOfTokens; ++v) {
token_t& tt = r_tokenindex_p[v];
ifs.read((char*)&cid, sizeof(cid));
ifs.read((char*)&csize, sizeof(csize));
tt.sptc_v = (NodeID*)memalign(64, (csize + 1) * sizeof(NodeID));
tt.sptc_d = (EdgeWeight*)memalign(64, (csize + 1 ) * sizeof(EdgeWeight));
r_total_children += (csize + 1);
tt.sptc_v[0] = cid;
tt.sptc_d[0] = csize;
for (NodeID i = 0; i < csize; ++i) {
ifs.read((char*)&cid, sizeof(cid));
ifs.read((char*)&cd, sizeof(cd));
tt.sptc_v[i + 1] = cid;
tt.sptc_d[i + 1] = cd;
}
}
cout << "finish loading" << endl;
ifs.close();
}
void print_stat() {
cout << "Total Token #: " << numOfTokens << endl;
cout << "Average Children (Super) Token #: " << (double)total_children/(double)numOfTokens << endl;
//cout << "Maximum Label Size: " << max_size() << endl;
}
void print_stat_d() {
cout << "Total Token #: " << numOfTokens << endl;
cout << "Total r_Token #: " << r_numOfTokens << endl;
cout << "Average Children (Super) Token #: " << (double)total_children/(double)numOfTokens << endl;
cout << "Average Children (Super) Token #: " << (double)r_total_children/(double)r_numOfTokens << endl;
// cout << "Maximum Label Size: " << max_size() << endl;
}
EdgeWeight query_p(NodeID s, NodeID t, long ts, vector<NodeID>& dis_vec, vector<long>& ts_vec, vector<NodeID>& que, vector<EdgeWeight>& que_d) {
if(s==t) return 0;
EdgeWeight distance = INF_WEIGHT;
NodeID anchor_s = anchor_p[s];
NodeID anchor_t = anchor_p[t];
NodeID que_t0 = 0, que_t1 = 0, que_h = 0;
que_d[que_h] = 0;
que[que_h++] = anchor_s;
que_t1 = que_h;
if(anchor_s < numOfVertices){
if(ts_vec[anchor_s] != ts){
ts_vec[anchor_s] = ts;
dis_vec[anchor_s] = 0;
}
}
else{
for (; que_t0 < que_h;) {
for (NodeID que_i = que_t0; que_i < que_t1; ++que_i) {
NodeID tid = que[que_i];
EdgeWeight tdis = que_d[que_i];
const token_t& token_v = tokenindex_p[tid - numOfVertices];
_mm_prefetch(&token_v.sptc_v[0], _MM_HINT_T0);
_mm_prefetch(&token_v.sptc_d[0], _MM_HINT_T0);
NodeID r = token_v.sptc_v[0];
EdgeWeight csize = token_v.sptc_d[0];
// hashing, can be replaced by 1024 linear probing for efficiency.
if(ts_vec[r] != ts){
ts_vec[r] = ts;
dis_vec[r] = tdis;
}
for (EdgeWeight i = 0; i < csize; ++i){
NodeID w = token_v.sptc_v[i+1];
EdgeWeight w_d = token_v.sptc_d[i+1] + tdis;
if( w < numOfVertices){// hashing, can be replaced by 1024 linear probing for efficiency.
if(ts_vec[w] != ts){
ts_vec[w] = ts;
dis_vec[w] = w_d;
}
}else{
que_d[que_h] = w_d;
que[que_h++] = w;
}
}
}
que_t0 = que_t1;
que_t1 = que_h;
}
}
que_t0 = 0, que_t1 = 0, que_h = 0;
que_d[que_h] = 0;
que[que_h++] = anchor_t;
if(anchor_t < numOfVertices){
if(ts_vec[anchor_t] == ts){
EdgeWeight current_dis = dis_vec[anchor_t] + 0;
if(current_dis < distance)
distance = current_dis;
}
}else{
que_t1 = que_h;
for (; que_t0 < que_h;) {
for (NodeID que_i = que_t0; que_i < que_t1; ++que_i) {
NodeID tid = que[que_i];
EdgeWeight tdis = que_d[que_i];
const token_t& token_v = tokenindex_p[tid - numOfVertices];
_mm_prefetch(&token_v.sptc_v[0], _MM_HINT_T0);
_mm_prefetch(&token_v.sptc_d[0], _MM_HINT_T0);
NodeID r = token_v.sptc_v[0];
EdgeWeight csize = token_v.sptc_d[0];
// hashing, can be replaced by 1024 linear probing for efficiency.
if(ts_vec[r] == ts){
EdgeWeight current_dis = dis_vec[r] + tdis;
if(current_dis < distance)
distance = current_dis;
}
for (EdgeWeight i = 0; i < csize; ++i){
NodeID w = token_v.sptc_v[i+1];
EdgeWeight w_d = token_v.sptc_d[i+1] + tdis;
if( w < numOfVertices){
// hashing, can be replaced by 1024 linear probing for efficiency.
if(ts_vec[w] == ts){
EdgeWeight current_dis = dis_vec[w] + w_d;
if(current_dis < distance)
distance = current_dis;
}
}else{
que_d[que_h] = w_d;
que[que_h++] = w;
}
}
}
que_t0 = que_t1;
que_t1 = que_h;
}
}
return distance;
}
EdgeWeight query_p_d(NodeID s, NodeID t, long ts, vector<NodeID>& dis_vec, vector<long>& ts_vec, vector<NodeID>& que, vector<EdgeWeight>& que_d) {
if(s==t) return 0;
EdgeWeight distance = INF_WEIGHT;
NodeID anchor_s = anchor_p[s];
NodeID anchor_t = r_anchor_p[t];
NodeID que_t0 = 0, que_t1 = 0, que_h = 0;
que_d[que_h] = 0;
que[que_h++] = anchor_s;
que_t1 = que_h;
if(anchor_s < numOfVertices){
if(ts_vec[anchor_s] != ts){
ts_vec[anchor_s] = ts;
dis_vec[anchor_s] = 0;
}
}
else{
for (; que_t0 < que_h;) {
for (NodeID que_i = que_t0; que_i < que_t1; ++que_i) {
NodeID tid = que[que_i];
EdgeWeight tdis = que_d[que_i];
const token_t& token_v = tokenindex_p[tid - numOfVertices];
_mm_prefetch(&token_v.sptc_v[0], _MM_HINT_T0);
_mm_prefetch(&token_v.sptc_d[0], _MM_HINT_T0);
NodeID r = token_v.sptc_v[0];
EdgeWeight csize = token_v.sptc_d[0];
// hashing, can be replaced by 1024 linear probing for efficiency.
if(ts_vec[r] != ts){
ts_vec[r] = ts;
dis_vec[r] = tdis;
}
for (EdgeWeight i = 0; i < csize; ++i){
NodeID w = token_v.sptc_v[i+1];
EdgeWeight w_d = token_v.sptc_d[i+1] + tdis;
if( w < numOfVertices){// hashing, can be replaced by 1024 linear probing for efficiency.
if(ts_vec[w] != ts){
ts_vec[w] = ts;
dis_vec[w] = w_d;
}
}else{
que_d[que_h] = w_d;
que[que_h++] = w;
}
}
}
que_t0 = que_t1;
que_t1 = que_h;
}
}
que_t0 = 0, que_t1 = 0, que_h = 0;
que_d[que_h] = 0;
que[que_h++] = anchor_t;
if(anchor_t < numOfVertices){
if(ts_vec[anchor_t] == ts){
EdgeWeight current_dis = dis_vec[anchor_t] + 0;
if(current_dis < distance)
distance = current_dis;
}
}else{
que_t1 = que_h;
for (; que_t0 < que_h;) {
for (NodeID que_i = que_t0; que_i < que_t1; ++que_i) {
NodeID tid = que[que_i];
EdgeWeight tdis = que_d[que_i];
const token_t& token_v = r_tokenindex_p[tid - numOfVertices];
_mm_prefetch(&token_v.sptc_v[0], _MM_HINT_T0);
_mm_prefetch(&token_v.sptc_d[0], _MM_HINT_T0);
NodeID r = token_v.sptc_v[0];
EdgeWeight csize = token_v.sptc_d[0];
// hashing, can be replaced by 1024 linear probing for efficiency.
if(ts_vec[r] == ts){
EdgeWeight current_dis = dis_vec[r] + tdis;
if(current_dis < distance)
distance = current_dis;
}
for (EdgeWeight i = 0; i < csize; ++i){
NodeID w = token_v.sptc_v[i+1];
EdgeWeight w_d = token_v.sptc_d[i+1] + tdis;
if( w < numOfVertices){
// hashing, can be replaced by 1024 linear probing for efficiency.
if(ts_vec[w] == ts){
EdgeWeight current_dis = dis_vec[w] + w_d;
if(current_dis < distance)
distance = current_dis;
}
}else{
que_d[que_h] = w_d;
que[que_h++] = w;
}
}
}
que_t0 = que_t1;
que_t1 = que_h;
}
}
return distance;
}
void save_two_level_labels(const char* save_filename) {
ofstream ofs(save_filename, ios::binary | ios::out);
ofs.write((const char*)&numOfVertices, sizeof(numOfVertices));
for (NodeID v = 0; v < numOfVertices; ++v) {
ofs.write((const char*)&anchor_p[v], sizeof(anchor_p[v]));
// ofs.write((const char*)&index_[v].spt_d[i], sizeof(index_[v].spt_d[i]));
}
// Store supertokens
for (NodeID v = 0; v < numOfVertices; ++v) {
token_t& supertoken_v = supertokenindex_p[v];
NodeID isize = supertoken_v.sptc_v[0];
ofs.write((const char*)&isize, sizeof(isize));
for(NodeID i = 0; i < isize; ++i){
NodeID tid = supertoken_v.sptc_v[i + 1];
EdgeWeight ew = supertoken_v.sptc_d[i + 1];
ofs.write((const char*)&tid, sizeof(tid));
ofs.write((const char*)&ew, sizeof(ew));
}
// ofs.write((const char*)&index_[v].spt_d[i], sizeof(index_[v].spt_d[i]));
}
// Store normal tokens
ofs.write((const char*)&numOfTokens, sizeof(numOfTokens));
for (NodeID t = 0; t < numOfTokens; ++t) {
token_t& tt = tokenindex_p[t];
NodeID sid = tt.sptc_v[0];
EdgeWeight ssize = tt.sptc_d[0];
EdgeWeight fsize = supertokenindex_p[sid].sptc_d[0];
ofs.write((const char*)&sid, sizeof(sid));
ofs.write((const char*)&ssize, sizeof(ssize));
if(ssize == 0) continue;
//ofs.write((const char*)&fsize, sizeof(fsize));
//if(t < 10)
// cout << sid << "vs" << fsize << "vs" << ssize << endl;
for(NodeID c = 0; c < fsize; ++c){
//char a = tt.sptc_fbv[c];
//ofs.write((const char*)&a, sizeof(a));
ofs.write((const char*)&tt.sptc_fbv[c], sizeof(tt.sptc_fbv[c]));
// if(t < 10){
// bitset<8> s(tt.sptc_fbv[c]);
// cout << s;
// }
}
//if(t < 10)
// cout << endl;
for(NodeID c = 0; c < ssize; ++c){
//char a = tt.sptc_sbv[c];
//ofs.write((const char*)&a, sizeof(a));
ofs.write((const char*)&tt.sptc_sbv[c], sizeof(tt.sptc_sbv[c]));
// if(t < 10){
// bitset<8> s(tt.sptc_sbv[c]);
// cout << s;
// }
}
//if(t < 10)
// cout << endl;
}
ofs.close();
}
void load_two_level_labels(const char* load_filename) {
total_children = 0;
tokenindex_p = NULL;
anchor_p = NULL;
supertokenindex_p = NULL;
ifstream ifs(load_filename);
NodeID isize = 0;
ifs.read((char*)&isize, sizeof(isize));
numOfVertices = isize;
anchor_p = (NodeID*)memalign(64, numOfVertices * sizeof(NodeID));
NodeID anchor_id;
for (NodeID v = 0; v < numOfVertices; ++v) {
ifs.read((char*)&anchor_id, sizeof(anchor_id));
anchor_p[v] = anchor_id;
}
//load supertokens
NodeID cid;
EdgeWeight cd;
supertokenindex_p = (token_t*)memalign(64, numOfVertices * sizeof(token_t));
for (NodeID v = 0; v < numOfVertices; ++v) {
token_t& supertoken_v = supertokenindex_p[v];
NodeID csize;
ifs.read((char*)&csize, sizeof(csize));
supertoken_v.sptc_v = (NodeID*)memalign(64, (csize + 1) * sizeof(NodeID));
supertoken_v.sptc_d = (EdgeWeight*)memalign(64, (csize + 1 ) * sizeof(EdgeWeight));
supertoken_v.sptc_v[0] = csize;
NodeID intsize = ceil((double)ceil((double)csize / (double)8) / (double)8);
supertoken_v.sptc_d[0] = intsize;
total_children += csize;
for(EdgeWeight i = 0; i < csize; ++i){
ifs.read((char*)&cid, sizeof(cid));
ifs.read((char*)&cd, sizeof(cd));
supertoken_v.sptc_v[i + 1] = cid;
supertoken_v.sptc_d[i + 1] = cd;
}
}
cout << "loaded supertokens" << endl;
cout << "Average Children Super Token #: " << (double)total_children/(double)numOfVertices << endl;
ifs.read((char*)&isize, sizeof(isize));
numOfTokens = isize;
NodeID sid;
EdgeWeight ssize;
EdgeWeight fsize;
cout<< numOfTokens << " tokens in total." << endl;
tokenindex_p = (token_t*)memalign(64, numOfTokens * sizeof(token_t));
for (NodeID v = 0; v < numOfTokens; ++v) {
token_t& tt = tokenindex_p[v];
ifs.read((char*)&sid, sizeof(sid));
ifs.read((char*)&ssize, sizeof(ssize));
tt.sptc_v = (NodeID*)memalign(64, 1 * sizeof(NodeID));
tt.sptc_d = (EdgeWeight*)memalign(64, 1 * sizeof(EdgeWeight));
tt.sptc_v[0] = sid;
tt.sptc_d[0] = ssize;
fsize = supertokenindex_p[sid].sptc_d[0];
if(ssize == 0) continue;
//if(v < 10)
// cout << sid << "vs" << fsize << "vs" << ssize << endl;
tt.sptc_fbv = (unsigned char*)memalign(64, fsize * sizeof(unsigned char));
// unsigned char fb;
char fb;
for (NodeID i = 0; i < fsize; ++i) {
ifs.read((char*)&(tt.sptc_fbv[i]), sizeof(tt.sptc_fbv[i]));
//ifs.read((char*)&fb, sizeof(fb));
// if(v < 10){
// bitset<8> s(tt.sptc_fbv[i]);
// cout << s;
// }
}
//if(v < 10)
// cout << endl;
tt.sptc_sbv = (unsigned char*)memalign(64, ssize * sizeof(unsigned char));
//unsigned char sb;
char sb;
for (NodeID i = 0; i < ssize; ++i) {
ifs.read((char*)&(tt.sptc_sbv[i]), sizeof(tt.sptc_sbv[i]));
//ifs.read((char*)&sb, sizeof(sb));
// if(v < 10){
// bitset<8> s(tt.sptc_sbv[i]);
// cout << s;
//}
}
//if(v < 10)
// cout << endl;
//
}
cout << "loaded standard tokens" << endl;
ifs.close();
}
void save_two_level_labels_path(const char* save_filename) {
ofstream ofs(save_filename, ios::binary | ios::out);
ofs.write((const char*)&numOfVertices, sizeof(numOfVertices));
for (NodeID v = 0; v < numOfVertices; ++v) {
ofs.write((const char*)&anchor_p[v], sizeof(anchor_p[v]));
// ofs.write((const char*)&index_[v].spt_d[i], sizeof(index_[v].spt_d[i]));
}
// Store supertokens
for (NodeID v = 0; v < numOfVertices; ++v) {
token_t& supertoken_v = supertokenindex_p[v];
NodeID isize = supertoken_v.sptc_v[0];
ofs.write((const char*)&isize, sizeof(isize));
for(NodeID i = 0; i < isize; ++i){
NodeID tid = supertoken_v.sptc_v[i + 1];
EdgeWeight ew = supertoken_v.sptc_d[i + 1];
NodeID pid = supertoken_v.sptc_pathv[i + 1];
ofs.write((const char*)&tid, sizeof(tid));
ofs.write((const char*)&ew, sizeof(ew));
ofs.write((const char*)&pid, sizeof(pid));
}
// ofs.write((const char*)&index_[v].spt_d[i], sizeof(index_[v].spt_d[i]));
}
// Store normal tokens
ofs.write((const char*)&numOfTokens, sizeof(numOfTokens));
for (NodeID t = 0; t < numOfTokens; ++t) {
token_t& tt = tokenindex_p[t];
NodeID sid = tt.sptc_v[0];
EdgeWeight ssize = tt.sptc_d[0];
EdgeWeight fsize = supertokenindex_p[sid].sptc_d[0];
ofs.write((const char*)&sid, sizeof(sid));
ofs.write((const char*)&ssize, sizeof(ssize));
if(ssize == 0) continue;
//ofs.write((const char*)&fsize, sizeof(fsize));
//if(t < 10)
// cout << sid << "vs" << fsize << "vs" << ssize << endl;
for(NodeID c = 0; c < fsize; ++c){
//char a = tt.sptc_fbv[c];
//ofs.write((const char*)&a, sizeof(a));
ofs.write((const char*)&tt.sptc_fbv[c], sizeof(tt.sptc_fbv[c]));
// if(t < 10){
// bitset<8> s(tt.sptc_fbv[c]);
// cout << s;
// }
}
//if(t < 10)
// cout << endl;
for(NodeID c = 0; c < ssize; ++c){
//char a = tt.sptc_sbv[c];
//ofs.write((const char*)&a, sizeof(a));
ofs.write((const char*)&tt.sptc_sbv[c], sizeof(tt.sptc_sbv[c]));
// if(t < 10){
// bitset<8> s(tt.sptc_sbv[c]);
// cout << s;
// }
}
//if(t < 10)
// cout << endl;
}
ofs.close();
}
void load_two_level_labels_path(const char* load_filename) {
total_children = 0;
tokenindex_p = NULL;
anchor_p = NULL;
supertokenindex_p = NULL;
ifstream ifs(load_filename);
NodeID isize = 0;
ifs.read((char*)&isize, sizeof(isize));
numOfVertices = isize;
anchor_p = (NodeID*)memalign(64, numOfVertices * sizeof(NodeID));
NodeID anchor_id;
for (NodeID v = 0; v < numOfVertices; ++v) {
ifs.read((char*)&anchor_id, sizeof(anchor_id));
anchor_p[v] = anchor_id;
}
//load supertokens
NodeID cid;
EdgeWeight cd;
supertokenindex_p = (token_t*)memalign(64, numOfVertices * sizeof(token_t));
for (NodeID v = 0; v < numOfVertices; ++v) {
token_t& supertoken_v = supertokenindex_p[v];
NodeID csize;
ifs.read((char*)&csize, sizeof(csize));
supertoken_v.sptc_v = (NodeID*)memalign(64, (csize + 1) * sizeof(NodeID));
supertoken_v.sptc_d = (EdgeWeight*)memalign(64, (csize + 1 ) * sizeof(EdgeWeight));
supertoken_v.sptc_pathv = (EdgeWeight*)memalign(64, (csize + 1 ) * sizeof(EdgeWeight));
supertoken_v.sptc_v[0] = csize;
NodeID intsize = ceil((double)ceil((double)csize / (double)8) / (double)8);
supertoken_v.sptc_d[0] = intsize;
supertoken_v.sptc_pathv[0] = numOfVertices;
total_children += csize;
for(EdgeWeight i = 0; i < csize; ++i){
ifs.read((char*)&cid, sizeof(cid));
ifs.read((char*)&cd, sizeof(cd));
supertoken_v.sptc_v[i + 1] = cid;
supertoken_v.sptc_d[i + 1] = cd;
ifs.read((char*)&cid, sizeof(cid));
supertoken_v.sptc_pathv[i + 1] = cid;
}
}
cout << "loaded supertokens" << endl;
cout << "Average Children Super Token #: " << (double)total_children/(double)numOfVertices << endl;
ifs.read((char*)&isize, sizeof(isize));
numOfTokens = isize;
NodeID sid;
EdgeWeight ssize;
EdgeWeight fsize;
cout<< numOfTokens << " tokens in total." << endl;
tokenindex_p = (token_t*)memalign(64, numOfTokens * sizeof(token_t));
for (NodeID v = 0; v < numOfTokens; ++v) {
token_t& tt = tokenindex_p[v];
ifs.read((char*)&sid, sizeof(sid));
ifs.read((char*)&ssize, sizeof(ssize));
tt.sptc_v = (NodeID*)memalign(64, 1 * sizeof(NodeID));
tt.sptc_d = (EdgeWeight*)memalign(64, 1 * sizeof(EdgeWeight));
tt.sptc_v[0] = sid;
tt.sptc_d[0] = ssize;
fsize = supertokenindex_p[sid].sptc_d[0];
if(ssize == 0) continue;
//if(v < 10)
// cout << sid << "vs" << fsize << "vs" << ssize << endl;
tt.sptc_fbv = (unsigned char*)memalign(64, fsize * sizeof(unsigned char));
// unsigned char fb;
char fb;
for (NodeID i = 0; i < fsize; ++i) {
ifs.read((char*)&(tt.sptc_fbv[i]), sizeof(tt.sptc_fbv[i]));
//ifs.read((char*)&fb, sizeof(fb));
// if(v < 10){
// bitset<8> s(tt.sptc_fbv[i]);
// cout << s;
// }
}
//if(v < 10)
// cout << endl;
tt.sptc_sbv = (unsigned char*)memalign(64, ssize * sizeof(unsigned char));
//unsigned char sb;
char sb;
for (NodeID i = 0; i < ssize; ++i) {
ifs.read((char*)&(tt.sptc_sbv[i]), sizeof(tt.sptc_sbv[i]));
//ifs.read((char*)&sb, sizeof(sb));
// if(v < 10){
// bitset<8> s(tt.sptc_sbv[i]);
// cout << s;
//}
}
//if(v < 10)
// cout << endl;
//
}
cout << "loaded standard tokens" << endl;
ifs.close();
}
void save_two_level_labels_d(const char* save_filename) {
ofstream ofs(save_filename, ios::binary | ios::out);
//cout << "1" << endl;
ofs.write((const char*)&numOfVertices, sizeof(numOfVertices));
for (NodeID v = 0; v < numOfVertices; ++v) {
ofs.write((const char*)&anchor_p[v], sizeof(anchor_p[v]));
// ofs.write((const char*)&index_[v].spt_d[i], sizeof(index_[v].spt_d[i]));
}
for (NodeID v = 0; v < numOfVertices; ++v) {
ofs.write((const char*)&r_anchor_p[v], sizeof(r_anchor_p[v]));
// ofs.write((const char*)&index_[v].spt_d[i], sizeof(index_[v].spt_d[i]));
}
// Store supertokens
// cout << "2" << endl;
for (NodeID v = 0; v < numOfVertices; ++v) {
token_t& supertoken_v = supertokenindex_p[v];
NodeID isize = supertoken_v.sptc_v[0];
ofs.write((const char*)&isize, sizeof(isize));
for(NodeID i = 0; i < isize; ++i){
NodeID tid = supertoken_v.sptc_v[i + 1];
EdgeWeight ew = supertoken_v.sptc_d[i + 1];
ofs.write((const char*)&tid, sizeof(tid));
ofs.write((const char*)&ew, sizeof(ew));
}
}
for (NodeID v = 0; v < numOfVertices; ++v) {
token_t& supertoken_v = r_supertokenindex_p[v];
NodeID isize = supertoken_v.sptc_v[0];
ofs.write((const char*)&isize, sizeof(isize));
for(NodeID i = 0; i < isize; ++i){
NodeID tid = supertoken_v.sptc_v[i + 1];
EdgeWeight ew = supertoken_v.sptc_d[i + 1];
ofs.write((const char*)&tid, sizeof(tid));
ofs.write((const char*)&ew, sizeof(ew));
}
}
// Store normal tokens
//cout << "3" << endl;
ofs.write((const char*)&numOfTokens, sizeof(numOfTokens));
for (NodeID t = 0; t < numOfTokens; ++t) {
// cout << "31:" << t << endl;
token_t& tt = tokenindex_p[t];
NodeID sid = tt.sptc_v[0];
EdgeWeight ssize = tt.sptc_d[0];
EdgeWeight fsize = supertokenindex_p[sid].sptc_d[0];
ofs.write((const char*)&sid, sizeof(sid));
ofs.write((const char*)&ssize, sizeof(ssize));
// cout << "32:" << t << endl;
if(ssize == 0) continue;
//ofs.write((const char*)&fsize, sizeof(fsize));
//if(t < 10)
// cout << sid << "vs" << fsize << "vs" << ssize << endl;
// cout << "33:" << t << endl;
for(NodeID c = 0; c < fsize; ++c){
//char a = tt.sptc_fbv[c];
//ofs.write((const char*)&a, sizeof(a));
ofs.write((const char*)&tt.sptc_fbv[c], sizeof(tt.sptc_fbv[c]));
// if(t < 10){
// bitset<8> s(tt.sptc_fbv[c]);
// cout << s;
// }
}
//if(t < 10)
// cout << endl;
// cout << "34:" << t << endl;
for(NodeID c = 0; c < ssize; ++c){
//char a = tt.sptc_sbv[c];
//ofs.write((const char*)&a, sizeof(a));
ofs.write((const char*)&tt.sptc_sbv[c], sizeof(tt.sptc_sbv[c]));
// if(t < 10){
// bitset<8> s(tt.sptc_sbv[c]);
// cout << s;
// }
}
//if(t < 10)
// cout << endl;
}
//cout << "4" << endl;
ofs.write((const char*)&r_numOfTokens, sizeof(r_numOfTokens));
for (NodeID t = 0; t < r_numOfTokens; ++t) {
//cout << "41:" << t << endl;
token_t& tt = r_tokenindex_p[t];
NodeID sid = tt.sptc_v[0];
EdgeWeight ssize = tt.sptc_d[0];
EdgeWeight fsize = r_supertokenindex_p[sid].sptc_d[0];
ofs.write((const char*)&sid, sizeof(sid));
ofs.write((const char*)&ssize, sizeof(ssize));
if(ssize == 0) continue;
//ofs.write((const char*)&fsize, sizeof(fsize));
//if(t < 10)
// cout << sid << "vs" << fsize << "vs" << ssize << endl;
//cout << "42:" << t << "," << fsize << endl;
for(NodeID c = 0; c < fsize; ++c){
ofs.write((const char*)&tt.sptc_fbv[c], sizeof(tt.sptc_fbv[c]));
}
//cout << "43:" << t << "," << ssize << endl;
for(NodeID c = 0; c < ssize; ++c){
ofs.write((const char*)&tt.sptc_sbv[c], sizeof(tt.sptc_sbv[c]));
}
}
ofs.close();
}
void load_two_level_labels_d(const char* load_filename) {
total_children = 0;
tokenindex_p = NULL;
anchor_p = NULL;
supertokenindex_p = NULL;
r_total_children = 0;
r_tokenindex_p = NULL;
r_anchor_p = NULL;
r_supertokenindex_p = NULL;
ifstream ifs(load_filename);
NodeID isize = 0;
ifs.read((char*)&isize, sizeof(isize));
numOfVertices = isize;
anchor_p = (NodeID*)memalign(64, numOfVertices * sizeof(NodeID));
r_anchor_p = (NodeID*)memalign(64, numOfVertices * sizeof(NodeID));
NodeID anchor_id;
for (NodeID v = 0; v < numOfVertices; ++v) {
ifs.read((char*)&anchor_id, sizeof(anchor_id));
anchor_p[v] = anchor_id;
}
for (NodeID v = 0; v < numOfVertices; ++v) {
ifs.read((char*)&anchor_id, sizeof(anchor_id));
r_anchor_p[v] = anchor_id;
}
//load supertokens
NodeID cid;
EdgeWeight cd;
supertokenindex_p = (token_t*)memalign(64, numOfVertices * sizeof(token_t));
for (NodeID v = 0; v < numOfVertices; ++v) {
token_t& supertoken_v = supertokenindex_p[v];
NodeID csize;
ifs.read((char*)&csize, sizeof(csize));
supertoken_v.sptc_v = (NodeID*)memalign(64, (csize + 1) * sizeof(NodeID));
supertoken_v.sptc_d = (EdgeWeight*)memalign(64, (csize + 1 ) * sizeof(EdgeWeight));
supertoken_v.sptc_v[0] = csize;
NodeID intsize = ceil((double)ceil((double)csize / (double)8) / (double)8);
supertoken_v.sptc_d[0] = intsize;
total_children += csize;
for(EdgeWeight i = 0; i < csize; ++i){
ifs.read((char*)&cid, sizeof(cid));
ifs.read((char*)&cd, sizeof(cd));
supertoken_v.sptc_v[i + 1] = cid;
supertoken_v.sptc_d[i + 1] = cd;
}
}
r_supertokenindex_p = (token_t*)memalign(64, numOfVertices * sizeof(token_t));
for (NodeID v = 0; v < numOfVertices; ++v) {
token_t& supertoken_v = r_supertokenindex_p[v];
NodeID csize;
ifs.read((char*)&csize, sizeof(csize));
supertoken_v.sptc_v = (NodeID*)memalign(64, (csize + 1) * sizeof(NodeID));
supertoken_v.sptc_d = (EdgeWeight*)memalign(64, (csize + 1 ) * sizeof(EdgeWeight));
supertoken_v.sptc_v[0] = csize;
NodeID intsize = ceil((double)ceil((double)csize / (double)8) / (double)8);
supertoken_v.sptc_d[0] = intsize;
r_total_children += csize;
for(EdgeWeight i = 0; i < csize; ++i){
ifs.read((char*)&cid, sizeof(cid));
ifs.read((char*)&cd, sizeof(cd));
supertoken_v.sptc_v[i + 1] = cid;
supertoken_v.sptc_d[i + 1] = cd;
}
}
cout << "loaded supertokens" << endl;
cout << "Average Children Super Token #: " << (double)total_children/(double)numOfVertices << endl;
cout << "Average Children Super Token #: " << (double)r_total_children/(double)numOfVertices << endl;
ifs.read((char*)&isize, sizeof(isize));
numOfTokens = isize;
NodeID sid;
EdgeWeight ssize;
EdgeWeight fsize;
cout<< numOfTokens << " tokens in total." << endl;
tokenindex_p = (token_t*)memalign(64, numOfTokens * sizeof(token_t));
for (NodeID v = 0; v < numOfTokens; ++v) {
token_t& tt = tokenindex_p[v];
ifs.read((char*)&sid, sizeof(sid));
ifs.read((char*)&ssize, sizeof(ssize));
tt.sptc_v = (NodeID*)memalign(64, 1 * sizeof(NodeID));
tt.sptc_d = (EdgeWeight*)memalign(64, 1 * sizeof(EdgeWeight));
tt.sptc_v[0] = sid;
tt.sptc_d[0] = ssize;
fsize = supertokenindex_p[sid].sptc_d[0];
if(ssize == 0) continue;
//if(v < 10)
// cout << sid << "vs" << fsize << "vs" << ssize << endl;
tt.sptc_fbv = (unsigned char*)memalign(64, fsize * sizeof(unsigned char));
// unsigned char fb;
char fb;
for (NodeID i = 0; i < fsize; ++i) {
ifs.read((char*)&(tt.sptc_fbv[i]), sizeof(tt.sptc_fbv[i]));
//ifs.read((char*)&fb, sizeof(fb));
// if(v < 10){
// bitset<8> s(tt.sptc_fbv[i]);
// cout << s;
// }
}
//if(v < 10)
// cout << endl;
tt.sptc_sbv = (unsigned char*)memalign(64, ssize * sizeof(unsigned char));
//unsigned char sb;
char sb;
for (NodeID i = 0; i < ssize; ++i) {
ifs.read((char*)&(tt.sptc_sbv[i]), sizeof(tt.sptc_sbv[i]));
//ifs.read((char*)&sb, sizeof(sb));
// if(v < 10){
// bitset<8> s(tt.sptc_sbv[i]);
// cout << s;
//}
}
//if(v < 10)
// cout << endl;
//
}
ifs.read((char*)&isize, sizeof(isize));
r_numOfTokens = isize;
cout<< r_numOfTokens << " tokens in total." << endl;
r_tokenindex_p = (token_t*)memalign(64, r_numOfTokens * sizeof(token_t));
for (NodeID v = 0; v < r_numOfTokens; ++v) {
token_t& tt = r_tokenindex_p[v];
ifs.read((char*)&sid, sizeof(sid));
ifs.read((char*)&ssize, sizeof(ssize));
tt.sptc_v = (NodeID*)memalign(64, 1 * sizeof(NodeID));
tt.sptc_d = (EdgeWeight*)memalign(64, 1 * sizeof(EdgeWeight));
tt.sptc_v[0] = sid;
tt.sptc_d[0] = ssize;
fsize = r_supertokenindex_p[sid].sptc_d[0];
if(ssize == 0) continue;
//if(v < 10)
// cout << sid << "vs" << fsize << "vs" << ssize << endl;
tt.sptc_fbv = (unsigned char*)memalign(64, fsize * sizeof(unsigned char));
// unsigned char fb;
char fb;
for (NodeID i = 0; i < fsize; ++i) {
ifs.read((char*)&(tt.sptc_fbv[i]), sizeof(tt.sptc_fbv[i]));
//ifs.read((char*)&fb, sizeof(fb));
// if(v < 10){
// bitset<8> s(tt.sptc_fbv[i]);
// cout << s;
// }
}
//if(v < 10)
// cout << endl;
tt.sptc_sbv = (unsigned char*)memalign(64, ssize * sizeof(unsigned char));
//unsigned char sb;
char sb;
for (NodeID i = 0; i < ssize; ++i) {
ifs.read((char*)&(tt.sptc_sbv[i]), sizeof(tt.sptc_sbv[i]));
//ifs.read((char*)&sb, sizeof(sb));
// if(v < 10){
// bitset<8> s(tt.sptc_sbv[i]);
// cout << s;
//}
}
//if(v < 10)
// cout << endl;
//
}
cout << "loaded standard tokens" << endl;
ifs.close();
}
EdgeWeight query_p_two_level(NodeID s, NodeID t, long ts, vector<NodeID>& dis_vec, vector<long>& ts_vec, vector<NodeID>& que, vector<EdgeWeight>& que_d) {
if(s==t) return 0;
EdgeWeight distance = INF_WEIGHT;
NodeID anchor_s = anchor_p[s];
NodeID anchor_t = anchor_p[t];
NodeID que_t0 = 0, que_t1 = 0, que_h = 0;
que_d[que_h] = 0;
que[que_h++] = anchor_s;
que_t1 = que_h;
if(anchor_s < numOfVertices){
if(ts_vec[anchor_s] != ts){
ts_vec[anchor_s] = ts;
dis_vec[anchor_s] = 0;
}
}
else{
for (; que_t0 < que_h;) {
for (NodeID que_i = que_t0; que_i < que_t1; ++que_i) {
NodeID tid = que[que_i];
EdgeWeight tdis = que_d[que_i];
const token_t& token_v = tokenindex_p[tid - numOfVertices];
_mm_prefetch(&token_v.sptc_v[0], _MM_HINT_T0);
_mm_prefetch(&token_v.sptc_d[0], _MM_HINT_T0);
NodeID r = token_v.sptc_v[0];
EdgeWeight ssize = token_v.sptc_d[0];
token_t& supertoken_r = supertokenindex_p[r];
EdgeWeight fsize = supertoken_r.sptc_d[0];
// hashing, can be replaced by 1024 linear probing for efficiency.
if(ts_vec[r] != ts){
ts_vec[r] = ts;
dis_vec[r] = tdis;
}
EdgeWeight spos = 0;
for(EdgeWeight i = 0; i < fsize; ++i){
unsigned char fmask = token_v.sptc_fbv[i];
bitset<8> fbs(fmask);
for(NodeID j = 0; j < 8; ++j){
if(fbs[ 7 - j]){
unsigned char smask = token_v.sptc_sbv[spos++];
bitset<8> sbs(smask);
for(NodeID k = 0; k < 8; ++k){
if(sbs[7 - k]){
NodeID w = supertoken_r.sptc_v[ (i * 8 + j) * 8 + k + 1];
EdgeWeight w_d = supertoken_r.sptc_d[(i * 8 + j) * 8 + k + 1] + tdis;
if( w < numOfVertices){// hashing, can be replaced by 1024 linear probing for efficiency.
if(ts_vec[w] != ts){
ts_vec[w] = ts;
dis_vec[w] = w_d;
}
}else{
que_d[que_h] = w_d;
que[que_h++] = w;
}
}
}
//if(spos == ssize) break;
}
}
//if(spos == ssize) break;
}
}
que_t0 = que_t1;
que_t1 = que_h;
}
}
que_t0 = 0, que_t1 = 0, que_h = 0;
que_d[que_h] = 0;
que[que_h++] = anchor_t;
if(anchor_t < numOfVertices){
if(ts_vec[anchor_t] == ts){
EdgeWeight current_dis = dis_vec[anchor_t] + 0;
if(current_dis < distance)
distance = current_dis;
}
}else{
que_t1 = que_h;
for (; que_t0 < que_h;) {
for (NodeID que_i = que_t0; que_i < que_t1; ++que_i) {
NodeID tid = que[que_i];
EdgeWeight tdis = que_d[que_i];
const token_t& token_v = tokenindex_p[tid - numOfVertices];
_mm_prefetch(&token_v.sptc_v[0], _MM_HINT_T0);
_mm_prefetch(&token_v.sptc_d[0], _MM_HINT_T0);
NodeID r = token_v.sptc_v[0];
EdgeWeight ssize = token_v.sptc_d[0];
token_t& supertoken_r = supertokenindex_p[r];
EdgeWeight fsize = supertoken_r.sptc_d[0];
// hashing, can be replaced by 1024 linear probing for efficiency.
if(ts_vec[r] == ts){
EdgeWeight current_dis = dis_vec[r] + tdis;
if(current_dis < distance)
distance = current_dis;
}
EdgeWeight spos = 0;
for(EdgeWeight i = 0; i < fsize; ++i){
unsigned char fmask = token_v.sptc_fbv[i];
bitset<8> fbs(fmask);
for(NodeID j = 0; j < 8; ++j){
if(fbs[7 - j]){
unsigned char smask = token_v.sptc_sbv[spos++];
bitset<8> sbs(smask);
for(NodeID k = 0; k < 8; ++k){
if(sbs[7 - k]){
NodeID w = supertoken_r.sptc_v[ (i * 8 + j) * 8 + k + 1];
EdgeWeight w_d = supertoken_r.sptc_d[(i * 8 + j) * 8 + k + 1] + tdis;
if( w < numOfVertices){// hashing, can be replaced by 1024 linear probing for efficiency.
if(ts_vec[w] == ts){
EdgeWeight current_dis = dis_vec[w] + w_d;
if(current_dis < distance)
distance = current_dis;
}
}else{
que_d[que_h] = w_d;
que[que_h++] = w;
}
}
}
//if(spos == ssize) break;
}
}
//if(spos == ssize) break;
}
}
que_t0 = que_t1;
que_t1 = que_h;
}
}
return distance;
}
EdgeWeight query_p_two_level_d(NodeID s, NodeID t, long ts, vector<NodeID>& dis_vec, vector<long>& ts_vec, vector<NodeID>& que, vector<EdgeWeight>& que_d) {
if(s==t) return 0;
EdgeWeight distance = INF_WEIGHT;
NodeID anchor_s = anchor_p[s];
NodeID anchor_t = r_anchor_p[t];
NodeID que_t0 = 0, que_t1 = 0, que_h = 0;
que_d[que_h] = 0;
que[que_h++] = anchor_s;
que_t1 = que_h;
if(anchor_s < numOfVertices){
if(ts_vec[anchor_s] != ts){
ts_vec[anchor_s] = ts;
dis_vec[anchor_s] = 0;
}
}
else{
for (; que_t0 < que_h;) {
for (NodeID que_i = que_t0; que_i < que_t1; ++que_i) {
NodeID tid = que[que_i];
EdgeWeight tdis = que_d[que_i];
const token_t& token_v = tokenindex_p[tid - numOfVertices];
_mm_prefetch(&token_v.sptc_v[0], _MM_HINT_T0);
_mm_prefetch(&token_v.sptc_d[0], _MM_HINT_T0);
NodeID r = token_v.sptc_v[0];
EdgeWeight ssize = token_v.sptc_d[0];
token_t& supertoken_r = supertokenindex_p[r];
EdgeWeight fsize = supertoken_r.sptc_d[0];
// hashing, can be replaced by 1024 linear probing for efficiency.
if(ts_vec[r] != ts){
ts_vec[r] = ts;
dis_vec[r] = tdis;
}
EdgeWeight spos = 0;
for(EdgeWeight i = 0; i < fsize; ++i){
unsigned char fmask = token_v.sptc_fbv[i];
bitset<8> fbs(fmask);
for(NodeID j = 0; j < 8; ++j){
if(fbs[ 7 - j]){
unsigned char smask = token_v.sptc_sbv[spos++];
bitset<8> sbs(smask);
for(NodeID k = 0; k < 8; ++k){
if(sbs[7 - k]){
NodeID w = supertoken_r.sptc_v[ (i * 8 + j) * 8 + k + 1];
EdgeWeight w_d = supertoken_r.sptc_d[(i * 8 + j) * 8 + k + 1] + tdis;
if( w < numOfVertices){// hashing, can be replaced by 1024 linear probing for efficiency.
if(ts_vec[w] != ts){
ts_vec[w] = ts;
dis_vec[w] = w_d;
}
}else{
que_d[que_h] = w_d;
que[que_h++] = w;
}
}
}
//if(spos == ssize) break;
}
}
//if(spos == ssize) break;
}
}
que_t0 = que_t1;
que_t1 = que_h;
}
}
que_t0 = 0, que_t1 = 0, que_h = 0;
que_d[que_h] = 0;
que[que_h++] = anchor_t;
if(anchor_t < numOfVertices){
if(ts_vec[anchor_t] == ts){
EdgeWeight current_dis = dis_vec[anchor_t] + 0;
if(current_dis < distance)
distance = current_dis;
}
}else{
que_t1 = que_h;
for (; que_t0 < que_h;) {
for (NodeID que_i = que_t0; que_i < que_t1; ++que_i) {
NodeID tid = que[que_i];
EdgeWeight tdis = que_d[que_i];
const token_t& token_v = r_tokenindex_p[tid - numOfVertices];
_mm_prefetch(&token_v.sptc_v[0], _MM_HINT_T0);
_mm_prefetch(&token_v.sptc_d[0], _MM_HINT_T0);
NodeID r = token_v.sptc_v[0];
EdgeWeight ssize = token_v.sptc_d[0];
token_t& supertoken_r = r_supertokenindex_p[r];
EdgeWeight fsize = supertoken_r.sptc_d[0];
// hashing, can be replaced by 1024 linear probing for efficiency.
if(ts_vec[r] == ts){
EdgeWeight current_dis = dis_vec[r] + tdis;
if(current_dis < distance)
distance = current_dis;
}
EdgeWeight spos = 0;
for(EdgeWeight i = 0; i < fsize; ++i){
unsigned char fmask = token_v.sptc_fbv[i];
bitset<8> fbs(fmask);
for(NodeID j = 0; j < 8; ++j){
if(fbs[7 - j]){
unsigned char smask = token_v.sptc_sbv[spos++];
bitset<8> sbs(smask);
for(NodeID k = 0; k < 8; ++k){
if(sbs[7 - k]){
NodeID w = supertoken_r.sptc_v[ (i * 8 + j) * 8 + k + 1];
EdgeWeight w_d = supertoken_r.sptc_d[(i * 8 + j) * 8 + k + 1] + tdis;
if( w < numOfVertices){// hashing, can be replaced by 1024 linear probing for efficiency.
if(ts_vec[w] == ts){
EdgeWeight current_dis = dis_vec[w] + w_d;
if(current_dis < distance)
distance = current_dis;
}
}else{
que_d[que_h] = w_d;
que[que_h++] = w;
}
}
}
//if(spos == ssize) break;
}
}
//if(spos == ssize) break;
}
}
que_t0 = que_t1;
que_t1 = que_h;
}
}
return distance;
}
};
class Label {
public:
vector<index_t> index_;
index_t_p* index_p;
two_index_t_p* two_index_p;
double GetCurrentTimeSec() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec + tv.tv_usec * 1e-6;
}
Label() {
index_.resize(numOfVertices);
}
~Label() {
Free();
}
EdgeWeight query_p(NodeID s, NodeID t) {
//
//EdgeWeight distance = INF_WEIGHT;
//NodeID *vs = index_p[s].spt_v;
//NodeID *vt = index_p[t].spt_v;
//EdgeWeight* ws = index_p[s].spt_d;
//EdgeWeight* wt = index_p[t].spt_d;
//_mm_prefetch(vs, _MM_HINT_T0);
//_mm_prefetch(vt, _MM_HINT_T0);
//_mm_prefetch(ws, _MM_HINT_T0);
//_mm_prefetch(wt, _MM_HINT_T0);
//for (unsigned i = 0, j = 0; ; ) {
// if (*(vs + i) == *(vt + j)) {
// if (*(vs + i) == numOfVertices) break; // Sentinel
// EdgeWeight td = *(ws + i) + *(wt + j);
// if (td < distance) distance = td;
// ++i;
// ++j;
// }
// else {
// i += *(vs + i) < *(vt + j) ? 1 : 0;
// j += *(vs + i) > *(vt + j) ? 1 : 0;
// }
//}
//return distance;
EdgeWeight distance = INF_WEIGHT;
const index_t_p &idx_s = index_p[s];
const index_t_p &idx_t = index_p[t];
_mm_prefetch(&idx_s.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_s.spt_d[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_d[0], _MM_HINT_T0);
for (int i = 0, j = 0; ; ) {
NodeID v1 = idx_s.spt_v[i], v2 = idx_t.spt_v[j];
if (v1 == numOfVertices) break; // Sentinel
if (v1 == v2) {
EdgeWeight td = idx_s.spt_d[i] + idx_t.spt_d[j];
if (td < distance) distance = td;
++i;
++j;
}
else {
i += v1 < v2 ? 1 : 0;
j += v1 > v2 ? 1 : 0;
}
}
return distance;
}
EdgeWeight two_query_p_sequential(NodeID s, NodeID t) {
EdgeWeight distance = INF_WEIGHT;
EdgeWeight ldistance = INF_WEIGHT;
const two_index_t_p &idx_s = two_index_p[s];
const two_index_t_p &idx_t = two_index_p[t];
_mm_prefetch(&idx_s.spt_lv[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_lv[0], _MM_HINT_T0);
_mm_prefetch(&idx_s.spt_ld[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_ld[0], _MM_HINT_T0);
for (uint8_t i = 0, j = 0; ; ) {
uint8_t uv8_1 = idx_s.spt_lv[i], uv8_2 = idx_t.spt_lv[j];
if (uv8_1 == UCHAR_MAX) break; // Sentinel
if (uv8_1 == uv8_2) {
EdgeWeight td = idx_s.spt_ld[i] + idx_t.spt_ld[j];
if (td < ldistance) ldistance = td;
++i;
++j;
}
else {
i += uv8_1 < uv8_2 ? 1 : 0;
j += uv8_1 > uv8_2 ? 1 : 0;
}
}
_mm_prefetch(&idx_s.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_s.spt_d[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_d[0], _MM_HINT_T0);
for (int i = 0, j = 0; ; ) {
NodeID v1 = idx_s.spt_v[i], v2 = idx_t.spt_v[j];
if (v1 == numOfVertices) break; // Sentinel
if (v1 == v2) {
EdgeWeight td = idx_s.spt_d[i] + idx_t.spt_d[j];
if (td < distance) distance = td;
++i;
++j;
}
else {
i += v1 < v2 ? 1 : 0;
j += v1 > v2 ? 1 : 0;
}
}
if(distance < ldistance)
return distance;
else
return ldistance;
}
EdgeWeight two_query_p_parallel(NodeID s, NodeID t) {
EdgeWeight distance = INF_WEIGHT;
EdgeWeight ldistance = INF_WEIGHT;
const two_index_t_p &idx_s = two_index_p[s];
const two_index_t_p &idx_t = two_index_p[t];
#pragma omp parallel sections
{
#pragma omp section
{
_mm_prefetch(&idx_s.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_s.spt_d[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_d[0], _MM_HINT_T0);
for (int i = 0, j = 0; ; ) {
NodeID v1 = idx_s.spt_v[i], v2 = idx_t.spt_v[j];
if (v1 == numOfVertices) break; // Sentinel
if (v1 == v2) {
EdgeWeight td = idx_s.spt_d[i] + idx_t.spt_d[j];
if (td < distance) distance = td;
++i;
++j;
}
else {
i += v1 < v2 ? 1 : 0;
j += v1 > v2 ? 1 : 0;
}
}
}
#pragma omp section
{
_mm_prefetch(&idx_s.spt_lv[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_lv[0], _MM_HINT_T0);
_mm_prefetch(&idx_s.spt_ld[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_ld[0], _MM_HINT_T0);
for (uint8_t i = 0, j = 0; ; ) {
uint8_t uv8_1 = idx_s.spt_lv[i], uv8_2 = idx_t.spt_lv[j];
if (uv8_1 == UCHAR_MAX) break; // Sentinel
if (uv8_1 == uv8_2) {
EdgeWeight td = idx_s.spt_ld[i] + idx_t.spt_ld[j];
if (td < ldistance) ldistance = td;
++i;
++j;
}
else {
i += uv8_1 < uv8_2 ? 1 : 0;
j += uv8_1 > uv8_2 ? 1 : 0;
}
}
}
}
if(distance < ldistance)
return distance;
else
return ldistance;
}
EdgeWeight query_p_with_nums(NodeID s, NodeID t, int k) {
//
//EdgeWeight distance = INF_WEIGHT;
//NodeID *vs = index_p[s].spt_v;
//NodeID *vt = index_p[t].spt_v;
//EdgeWeight* ws = index_p[s].spt_d;
//EdgeWeight* wt = index_p[t].spt_d;
//_mm_prefetch(vs, _MM_HINT_T0);
//_mm_prefetch(vt, _MM_HINT_T0);
//_mm_prefetch(ws, _MM_HINT_T0);
//_mm_prefetch(wt, _MM_HINT_T0);
//for (unsigned i = 0, j = 0; ; ) {
// if (*(vs + i) == *(vt + j)) {
// if (*(vs + i) == numOfVertices) break; // Sentinel
// EdgeWeight td = *(ws + i) + *(wt + j);
// if (td < distance) distance = td;
// ++i;
// ++j;
// }
// else {
// i += *(vs + i) < *(vt + j) ? 1 : 0;
// j += *(vs + i) > *(vt + j) ? 1 : 0;
// }
//}
//return distance;
EdgeWeight distance = INF_WEIGHT;
const index_t_p &idx_s = index_p[s];
const index_t_p &idx_t = index_p[t];
_mm_prefetch(&idx_s.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_s.spt_d[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_d[0], _MM_HINT_T0);
int k1 = k, k2 = k;
for (int i = 0, j = 0; ; ) {
NodeID v1 = idx_s.spt_v[i], v2 = idx_t.spt_v[j];
if (v1 == numOfVertices) break; // Sentinel
if (v1 == v2) {
EdgeWeight td = idx_s.spt_d[i] + idx_t.spt_d[j];
if (td < distance) distance = td;
++i;
++j;
}
else {
i += v1 < v2 ? 1 : 0;
j += v1 > v2 ? 1 : 0;
}
if (i > k1 || j > k2) break;
}
return distance;
}
EdgeWeight query(NodeID s, NodeID t) {
EdgeWeight distance = INF_WEIGHT;
vector<NodeID>& index_s = index_[s].spt_v;
vector<EdgeWeight>& index_s_d = index_[s].spt_d;
vector<NodeID>& index_t = index_[t].spt_v;
vector<EdgeWeight>& index_t_d = index_[t].spt_d;
for (int i = 0, j = 0; i < index_s.size(), j < index_t.size(); ) {
if (index_s[i] == index_t[j])
distance = min(distance, (EdgeWeight)(index_s_d[i++] + index_t_d[j++]));
else {
if (index_s[i] < index_t[j])
++i;
else
++j;
}
}
return distance;
}
EdgeWeight query(NodeID s, NodeID t, NodeID& meet, EdgeWeight& dis1, EdgeWeight& dis2) {
EdgeWeight distance = INF_WEIGHT;
vector<NodeID>& index_s = index_[s].spt_v;
vector<EdgeWeight>& index_s_d = index_[s].spt_d;
vector<NodeID>& index_t = index_[t].spt_v;
vector<EdgeWeight>& index_t_d = index_[t].spt_d;
meet = numeric_limits<NodeID>::max();
dis1 = numeric_limits<EdgeWeight>::max();
dis2 = numeric_limits<EdgeWeight>::max();
for (int i = 0, j = 0; i < index_s.size(), j < index_t.size(); ) {
if (index_s[i] == index_t[j]) {
if (distance > (EdgeWeight)(index_s_d[i] + index_t_d[j])) {
distance = (EdgeWeight)(index_s_d[i] + index_t_d[j]);
meet = index_s[i];
dis1 = index_s_d[i];
dis2 = index_t_d[j];
}
++i; ++j;
}
else {
if (index_s[i] < index_t[j])
++i;
else
++j;
}
}
return distance;
}
/*EdgeWeight query_new(NodeID s, NodeID t, Ordering& ordering) {
EdgeWeight distance = INF_WEIGHT;
vector<NodeID>& index_s = index_[s].spt_v;
vector<EdgeWeight>& index_s_d = index_[s].spt_d;
vector<NodeID>& index_t = index_[t].spt_v;
vector<EdgeWeight>& index_t_d = index_[t].spt_d;
for (int i = 0, j = 0; i < index_s.size(), j < index_t.size(); ) {
if (index_s[i] == index_t[j])
distance = min(distance, (EdgeWeight)(index_s_d[i++] + index_t_d[j++]));
else {
if (index_s[i] < index_t[j])
++i;
else
++j;
}
}
return distance;
}
*/
double avg_size() {
double total = 0;
if(index_.size()!=0){
for (int i = 0; i < numOfVertices; ++i) total += index_[i].spt_v.size();
double avg = total / numOfVertices - 1; // We do not count the trivial label (V, INF_WEIGHT).
return avg;
}
total = 0;
for (int i = 0; i < numOfVertices; ++i) {
int unit_count = 0;
const index_t_p &idx_s = index_p[i];
for(int j = 0; ;){
NodeID v = idx_s.spt_v[j++];
++unit_count;
if( v == numOfVertices) break;
}
total += unit_count;
}
double avg = total / numOfVertices - 1; // We do not count the trivial label (V, INF_WEIGHT).
return avg;
}
/*
NodeID max_size() {
NodeID maxsize = numeric_limits<NodeID>::min();
for (int i = 0; i < V; ++i) maxsize = max(maxsize, index_[i].spt_v.size());
return maxsize;
}*/
void append(NodeID v, NodeID root, EdgeWeight distance) {
index_[v].spt_v.push_back(root);
index_[v].spt_d.push_back(distance);
}
void print_stat() {
cout << "Average Label Size: " << avg_size() << endl;
//cout << "Maximum Label Size: " << max_size() << endl;
}
void Free() {
if (index_.size() == 0) return;
for (int v = 0; v < numOfVertices; ++v) {
index_[v].spt_v.clear();
index_[v].spt_d.clear();
}
index_.clear();
}
void save_labels(const char* save_filename) {
puts("AAA");
print_stat();
ofstream ofs(save_filename, ios::binary | ios::out);
ofs.write((const char*)&numOfVertices, sizeof(numOfVertices));
for (NodeID v = 0; v < numOfVertices; ++v) {
NodeID isize = index_[v].size();
ofs.write((const char*)&isize, sizeof(isize));
for (NodeID i = 0; i < index_[v].size(); ++i) {
ofs.write((const char*)&index_[v].spt_v[i], sizeof(index_[v].spt_v[i]));
ofs.write((const char*)&index_[v].spt_d[i], sizeof(index_[v].spt_d[i]));
}
}
ofs.close();
}
void load_labels(const char* load_filename) {
/* for (NodeID v = 0; v < numOfVertices; ++v) {
free(index_p[v].spt_v);
free(index_p[v].spt_d);
}
*/
//free(index_p);
index_p = NULL;
ifstream ifs(load_filename);
NodeID isize = 0;
ifs.read((char*)&isize, sizeof(isize));
numOfVertices = isize;
index_p = (index_t_p*)memalign(64, numOfVertices * sizeof(index_t_p));
for (NodeID v = 0; v < numOfVertices; ++v) {
index_t_p &idx = index_p[v];
ifs.read((char*)&isize, sizeof(isize));
idx.spt_v = (NodeID*)memalign(64, isize * sizeof(NodeID));
idx.spt_d = (EdgeWeight*)memalign(64, isize * sizeof(EdgeWeight));
// index_[v].spt_v.resize(isize);
// index_[v].spt_d.resize(isize);
for (NodeID i = 0; i < isize; ++i) {
NodeID hub;
EdgeWeight hub_weight;
ifs.read((char*)&hub, sizeof(hub));
ifs.read((char*)&hub_weight, sizeof(hub_weight));
//index_[v].spt_v[i] = hub;
//index_[v].spt_d[i] = hub_weight;
idx.spt_v[i] = hub;
idx.spt_d[i] = hub_weight;
}
}
ifs.close();
/*
index_.clear();
ifstream ifs(load_filename);
NodeID isize = 0;
ifs.read((char*)&isize, sizeof(isize));
numOfVertices = isize;
index_.resize(numOfVertices);
for (NodeID v = 0; v < numOfVertices; ++v) {
ifs.read((char*)&isize, sizeof(isize));
index_[v].spt_v.resize(isize);
index_[v].spt_d.resize(isize);
for (NodeID i = 0; i < index_[v].size(); ++i) {
NodeID hub;
EdgeWeight hub_weight;
ifs.read((char*)&hub, sizeof(hub));
ifs.read((char*)&hub_weight, sizeof(hub_weight));
index_[v].spt_v[i] = hub;
index_[v].spt_d[i] = hub_weight;
}
}
ifs.close();
*/
}
void convert_to_fewerbit(){
two_index_p = NULL;
two_index_p = (two_index_t_p*)memalign(64, numOfVertices * sizeof(two_index_t_p));
double compressed_size = 0;
double total_size = 0;
for (NodeID v = 0; v < numOfVertices; ++v) {
two_index_t_p &idx = two_index_p[v];
index_t_p &idx_original = index_p[v];
NodeID isize = 0;
for(NodeID i = 0; idx_original.spt_v[i] < UCHAR_MAX; ++i){
++isize;
}
idx.spt_lv = (uint8_t*)memalign(64, (isize + 1) * sizeof(uint8_t));
idx.spt_ld = (EdgeWeight*)memalign(64, (isize + 1) * sizeof(EdgeWeight));
// index_[v].spt_v.resize(isize);
// index_[v].spt_d.resize(isize);
for (NodeID i = 0; i < isize; ++i) {
uint8_t hub;
EdgeWeight hub_weight;
//index_[v].spt_v[i] = hub;
//index_[v].spt_d[i] = hub_weight;
idx.spt_lv[i] = idx_original.spt_v[i];
idx.spt_ld[i] = idx_original.spt_d[i];
}
compressed_size += 4 * (isize - 1) - isize;
idx.spt_lv[isize] = UCHAR_MAX;
idx.spt_ld[isize] = INF_WEIGHT;
NodeID larger_size = 0;
for(NodeID i = isize; idx_original.spt_v[i] != numOfVertices; ++i){
++larger_size;
}
larger_size++;
idx.spt_v = (NodeID*)memalign(64, larger_size * sizeof(NodeID));
idx.spt_d = (EdgeWeight*)memalign(64, larger_size * sizeof(EdgeWeight));
for (NodeID i = 0; i < larger_size; ++i) {
uint8_t hub;
EdgeWeight hub_weight;
//index_[v].spt_v[i] = hub;
//index_[v].spt_d[i] = hub_weight;
idx.spt_v[i] = idx_original.spt_v[i + isize];
idx.spt_d[i] = idx_original.spt_d[i + isize];
}
total_size += 4 * (isize - 1 + larger_size) * 2;
}
cout << "reduce size :" << compressed_size << " out of " << total_size << " saving " << int(compressed_size * 100 / total_size) << "%" << endl;
}
void load_labels_with_k(const char* load_filename, int k) {
/* for (NodeID v = 0; v < numOfVertices; ++v) {
free(index_p[v].spt_v);
free(index_p[v].spt_d);
}
*/
//free(index_p);
long total_amount = 0;
long actual_amount = 0;
index_p = NULL;
ifstream ifs(load_filename);
NodeID isize = 0;
ifs.read((char*)&isize, sizeof(isize));
numOfVertices = isize;
index_p = (index_t_p*)memalign(64, numOfVertices * sizeof(index_t_p));
for (NodeID v = 0; v < numOfVertices; ++v) {
index_t_p &idx = index_p[v];
ifs.read((char*)&isize, sizeof(isize));
int actual_isize = k;
if (isize > k) actual_isize = k;
else actual_isize = isize;
total_amount += isize;
actual_amount += actual_isize;
idx.spt_v = (NodeID*)memalign(64, actual_isize * sizeof(NodeID));
idx.spt_d = (EdgeWeight*)memalign(64, actual_isize * sizeof(EdgeWeight));
// index_[v].spt_v.resize(isize);
// index_[v].spt_d.resize(isize);
for (NodeID i = 0; i < isize; ++i) {
NodeID hub;
EdgeWeight hub_weight;
ifs.read((char*)&hub, sizeof(hub));
ifs.read((char*)&hub_weight, sizeof(hub_weight));
//index_[v].spt_v[i] = hub;
//index_[v].spt_d[i] = hub_weight;
if (i > actual_isize) continue;
if (i == actual_isize - 1) {
idx.spt_v[i] = numOfVertices;
idx.spt_d[i] = INF_WEIGHT;
}else {
idx.spt_v[i] = hub;
idx.spt_d[i] = hub_weight;
}
}
}
ifs.close();
cout << "Total Labels:" << total_amount << endl;
cout << "Actual Labels:" << actual_amount << endl;
/*
index_.clear();
ifstream ifs(load_filename);
NodeID isize = 0;
ifs.read((char*)&isize, sizeof(isize));
numOfVertices = isize;
index_.resize(numOfVertices);
for (NodeID v = 0; v < numOfVertices; ++v) {
ifs.read((char*)&isize, sizeof(isize));
index_[v].spt_v.resize(isize);
index_[v].spt_d.resize(isize);
for (NodeID i = 0; i < index_[v].size(); ++i) {
NodeID hub;
EdgeWeight hub_weight;
ifs.read((char*)&hub, sizeof(hub));
ifs.read((char*)&hub_weight, sizeof(hub_weight));
index_[v].spt_v[i] = hub;
index_[v].spt_d[i] = hub_weight;
}
}
ifs.close();
*/
}
void save_labels_iteration_stats(const char* save_filename) {
vector<NodeID> stat(numOfVertices);
for (NodeID v = 0; v < numOfVertices; ++v) {
for (NodeID i = 0; i < index_[v].size(); ++i)
stat[index_[v].spt_v[i]]++;
}
ofstream ofs(save_filename);
for (NodeID v = 0; v < numOfVertices; ++v) {
ofs << stat[v] << endl;
}
ofs.close();
}
EdgeWeight query_with_info(NodeID s, NodeID t, query_info& q_info) {
double stime = GetCurrentTimeSec();
EdgeWeight distance = INF_WEIGHT;
vector<NodeID>& index_s = index_[s].spt_v;
vector<EdgeWeight>& index_s_d = index_[s].spt_d;
vector<NodeID>& index_t = index_[t].spt_v;
vector<EdgeWeight>& index_t_d = index_[t].spt_d;
q_info.meet_node = numOfVertices;
double meet_distance;
for (int i = 0, j = 0; i < index_s.size(), j < index_t.size(); ) {
if (index_s[i] == index_t[j]) {
meet_distance = (EdgeWeight)(index_s_d[i++] + index_t_d[j++]);
if ( distance > meet_distance) {
distance = meet_distance;
q_info.meet_node = index_s[i];
}
}
else {
if (index_s[i] < index_t[j])
++i;
else
++j;
}
};
stime = GetCurrentTimeSec() - stime;
q_info.time_cost = stime;
if (index_s.size() < index_t.size())
q_info.search_len = index_s.size();
else
q_info.search_len = index_t.size();
return distance;
}
};
class PLabel {
public:
vector<index_t_path> index_;
index_t_path_p* index_p;
double GetCurrentTimeSec() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec + tv.tv_usec * 1e-6;
}
PLabel() {
index_.resize(numOfVertices);
}
~PLabel() {
Free();
}
EdgeWeight query_p(NodeID s, NodeID t) {
//EdgeWeight distance = INF_WEIGHT;
//NodeID *vs = index_p[s].spt_v;
//NodeID *vt = index_p[t].spt_v;
//EdgeWeight* ws = index_p[s].spt_d;
//EdgeWeight* wt = index_p[t].spt_d;
//_mm_prefetch(vs, _MM_HINT_T0);
//_mm_prefetch(vt, _MM_HINT_T0);
//_mm_prefetch(ws, _MM_HINT_T0);
//_mm_prefetch(wt, _MM_HINT_T0);
//for (unsigned i = 0, j = 0; ; ) {
// if (*(vs + i) == *(vt + j)) {
// if (*(vs + i) == numOfVertices) break; // Sentinel
// EdgeWeight td = *(ws + i) + *(wt + j);
// if (td < distance) distance = td;
// ++i;
// ++j;
// }
// else {
// i += *(vs + i) < *(vt + j) ? 1 : 0;
// j += *(vs + i) > *(vt + j) ? 1 : 0;
// }
//}
//return distance;
EdgeWeight distance = INF_WEIGHT;
NodeID meet;
const index_t_path_p &idx_s = index_p[s];
const index_t_path_p &idx_t = index_p[t];
_mm_prefetch(&idx_s.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_s.spt_d[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_d[0], _MM_HINT_T0);
for (int i = 0, j = 0; ; ) {
NodeID v1 = idx_s.spt_v[i], v2 = idx_t.spt_v[j];
if (v1 == numOfVertices) break; // Sentinel
if (v1 == v2) {
EdgeWeight td = idx_s.spt_d[i] + idx_t.spt_d[j];
if (td < distance) {
distance = td;
}
++i;
++j;
}
else {
i += v1 < v2 ? 1 : 0;
j += v1 > v2 ? 1 : 0;
}
}
return distance;
}
EdgeWeight query(NodeID s, NodeID t) {
EdgeWeight distance = INF_WEIGHT;
vector<NodeID>& index_s = index_[s].spt_v;
vector<EdgeWeight>& index_s_d = index_[s].spt_d;
vector<NodeID>& index_t = index_[t].spt_v;
vector<EdgeWeight>& index_t_d = index_[t].spt_d;
for (int i = 0, j = 0; i < index_s.size(), j < index_t.size(); ) {
if (index_s[i] == index_t[j])
distance = min(distance, (EdgeWeight)(index_s_d[i++] + index_t_d[j++]));
else {
if (index_s[i] < index_t[j])
++i;
else
++j;
}
}
return distance;
}
EdgeWeight query(NodeID s, NodeID t, NodeID& meet, EdgeWeight& dis1, EdgeWeight& dis2) {
EdgeWeight distance = INF_WEIGHT;
vector<NodeID>& index_s = index_[s].spt_v;
vector<EdgeWeight>& index_s_d = index_[s].spt_d;
vector<NodeID>& index_t = index_[t].spt_v;
vector<EdgeWeight>& index_t_d = index_[t].spt_d;
meet = numeric_limits<NodeID>::max();
dis1 = numeric_limits<EdgeWeight>::max();
dis2 = numeric_limits<EdgeWeight>::max();
for (int i = 0, j = 0; i < index_s.size(), j < index_t.size(); ) {
if (index_s[i] == index_t[j]) {
if (distance >(EdgeWeight)(index_s_d[i] + index_t_d[j])) {
distance = (EdgeWeight)(index_s_d[i] + index_t_d[j]);
meet = index_s[i];
dis1 = index_s_d[i];
dis2 = index_t_d[j];
}
++i; ++j;
}
else {
if (index_s[i] < index_t[j])
++i;
else
++j;
}
}
return distance;
}
EdgeWeight query_path(NodeID s, NodeID t, vector<NodeID>& rank, vector<NodeID>& inv) {
EdgeWeight distance = INF_WEIGHT;
NodeID meetnode = numOfVertices;
NodeID s_parent;
NodeID t_parent;
const index_t_path_p &idx_s = index_p[s];
const index_t_path_p &idx_t = index_p[t];
_mm_prefetch(&idx_s.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_s.spt_d[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_d[0], _MM_HINT_T0);
_mm_prefetch(&idx_s.spt_p[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_p[0], _MM_HINT_T0);
for (int i = 0, j = 0; ; ) {
NodeID v1 = idx_s.spt_v[i], v2 = idx_t.spt_v[j];
if (v1 == numOfVertices) break; // Sentinel
if (v1 == v2) {
EdgeWeight td = idx_s.spt_d[i] + idx_t.spt_d[j];
if (td < distance) {
distance = td;
// if (v1 < meetnode) {
meetnode = v1;
s_parent = idx_s.spt_p[i];
t_parent = idx_t.spt_p[j];
//}
}
++i;
++j;
}
else {
i += v1 < v2 ? 1 : 0;
j += v1 > v2 ? 1 : 0;
}
}
//Next, retrieve path from s - meetnode and meetnode - t.
vector<NodeID> path_from_s;
vector<NodeID> path_to_t;
path_from_s.push_back(s_parent);
path_to_t.push_back(t_parent);
int operation = 0;
/* if (s == 194569 && t == 20072)
cout << "debug." << " meet: " << meetnode << " sparent:" << s_parent << " tparent:" << t_parent << endl;*/
NodeID inv_meetnode = inv[meetnode];
while (path_from_s.back() != inv_meetnode) {
/*if (s == 194569 && t == 20072)
cout << "s meet:" << path_from_s.back() << endl;*/
const index_t_path_p &idx_from_s = index_p[path_from_s.back()];
_mm_prefetch(&idx_from_s.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_from_s.spt_p[0], _MM_HINT_T0);
// vector<NodeID>& index_from_s = index_[path_from_s.back()].spt_v;
for (int i = 0; ; ++i) {
operation++;
if (idx_from_s.spt_v[i] == numOfVertices) break;
if (idx_from_s.spt_v[i] == meetnode) {
path_from_s.push_back(idx_from_s.spt_p[i]);
break;
}
}
}
while (path_to_t.back() != inv_meetnode) {
/*if (s == 194569 && t == 20072)
cout << "t meet:" << path_to_t.back() << endl;*/
// vector<NodeID>& index_to_t = index_[path_to_t.back()].spt_v;
const index_t_path_p &idx_to_t = index_p[path_to_t.back()];
_mm_prefetch(&idx_to_t.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_to_t.spt_p[0], _MM_HINT_T0);
for (int i = 0; ; ++i) {
operation++;
if (idx_to_t.spt_v[i] == numOfVertices) break;
if (idx_to_t.spt_v[i] == meetnode) {
path_to_t.push_back(idx_to_t.spt_p[i]);
break;
}
}
}
distance = 0;
distance += path_from_s.size() + path_to_t.size();
// return distance;
return distance;
//EdgeWeight distance = INF_WEIGHT;
//vector<NodeID>& index_s = index_[s].spt_v;
//vector<EdgeWeight>& index_s_d = index_[s].spt_d;
//vector<NodeID>& bindex_t = index_[t].spt_v;
//vector<EdgeWeight>& bindex_t_d = index_[t].spt_d;
//NodeID meetnode = numOfVertices;
//int s_parent;
//int t_parent;
//for (int i = 0, j = 0; i < index_s.size(), j < bindex_t.size(); ) {
// if (index_s[i] == bindex_t[j]) {
// if (distance >(EdgeWeight)(index_s_d[i] + bindex_t_d[j])) {
// distance = (EdgeWeight)(index_s_d[i] + bindex_t_d[j]);
// if (index_s[i] < meetnode) {
// meetnode = index_s[i];
// s_parent = index_[s].spt_p[i];
// t_parent = index_[t].spt_p[j];
// }
// }
// //distance = min(distance, (EdgeWeight)(index_s_d[i] + bindex_t_d[j]));
// ++i;
// ++j;
// }
// else {
// if (index_s[i] < bindex_t[j])
// ++i;
// else
// ++j;
// }
//}
////Next, retrieve path from s - meetnode and meetnode - t.
//vector<NodeID> path_from_s;
//vector<NodeID> path_to_t;
//path_from_s.push_back(s_parent);
//path_to_t.push_back(t_parent);
///* if (s == 194569 && t == 20072)
//cout << "debug." << " meet: " << meetnode << " sparent:" << s_parent << " tparent:" << t_parent << endl;*/
//while (path_from_s.back() != inv[meetnode]) {
// /*if (s == 194569 && t == 20072)
// cout << "s meet:" << path_from_s.back() << endl;*/
// vector<NodeID>& index_from_s = index_[path_from_s.back()].spt_v;
// for (int i = 0; i < index_from_s.size(); ++i) {
// if (index_from_s[i] == meetnode) {
// path_from_s.push_back(index_[path_from_s.back()].spt_p[i]);
// break;
// }
// }
//}
//while (path_to_t.back() != inv[meetnode]) {
// /*if (s == 194569 && t == 20072)
// cout << "t meet:" << path_to_t.back() << endl;*/
// vector<NodeID>& index_to_t = index_[path_to_t.back()].spt_v;
// for (int i = 0; i < index_to_t.size(); ++i) {
// if (index_to_t[i] == meetnode) {
// path_to_t.push_back(index_[path_to_t.back()].spt_p[i]);
// break;
// }
// }
//}
////for (int i = 0; i < path_from_s.size(); ++i)
//// path_from_s[i] = inv[path_from_s[i]];
////for (int i = 0; i < path_to_t.size(); ++i)
//// path_to_t[i] = inv[path_to_t[i]];
//return path_from_s.size() + path_to_t.size();
}
EdgeWeight query_path_check(NodeID s, NodeID t, vector<NodeID>& rank, vector<NodeID>& inv) {
EdgeWeight distance = INF_WEIGHT;
NodeID meetnode = numOfVertices;
NodeID s_parent;
NodeID t_parent;
const index_t_path_p &idx_s = index_p[s];
const index_t_path_p &idx_t = index_p[t];
_mm_prefetch(&idx_s.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_s.spt_d[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_d[0], _MM_HINT_T0);
_mm_prefetch(&idx_s.spt_p[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_p[0], _MM_HINT_T0);
for (int i = 0, j = 0; ; ) {
NodeID v1 = idx_s.spt_v[i], v2 = idx_t.spt_v[j];
if (v1 == numOfVertices) break; // Sentinel
if (v1 == v2) {
EdgeWeight td = idx_s.spt_d[i] + idx_t.spt_d[j];
if (td < distance) {
distance = td;
// if (v1 < meetnode) {
meetnode = v1;
s_parent = idx_s.spt_p[i];
t_parent = idx_t.spt_p[j];
//}
}
++i;
++j;
}
else {
i += v1 < v2 ? 1 : 0;
j += v1 > v2 ? 1 : 0;
}
}
NodeID inv_meetnode = inv[meetnode];
//Next, retrieve path from s - meetnode and meetnode - t.
vector<NodeID> path_from_s;
vector<NodeID> path_to_t;
if(s !=inv_meetnode)
path_from_s.push_back(s);
path_from_s.push_back(s_parent);
if (t != inv_meetnode)
path_to_t.push_back(t);
path_to_t.push_back(t_parent);
/* if (s == 194569 && t == 20072)
cout << "debug." << " meet: " << meetnode << " sparent:" << s_parent << " tparent:" << t_parent << endl;*/
while (path_from_s.back() != inv_meetnode) {
/*if (s == 194569 && t == 20072)
cout << "s meet:" << path_from_s.back() << endl;*/
const index_t_path_p &idx_from_s = index_p[path_from_s.back()];
_mm_prefetch(&idx_from_s.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_from_s.spt_p[0], _MM_HINT_T0);
// vector<NodeID>& index_from_s = index_[path_from_s.back()].spt_v;
for (int i = 0; ; ++i) {
if (idx_from_s.spt_v[i] == numOfVertices) break;
if (idx_from_s.spt_v[i] == meetnode) {
path_from_s.push_back(idx_from_s.spt_p[i]);
break;
}
}
}
while (path_to_t.back() != inv_meetnode) {
/*if (s == 194569 && t == 20072)
cout << "t meet:" << path_to_t.back() << endl;*/
// vector<NodeID>& index_to_t = index_[path_to_t.back()].spt_v;
const index_t_path_p &idx_to_t = index_p[path_to_t.back()];
_mm_prefetch(&idx_to_t.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_to_t.spt_p[0], _MM_HINT_T0);
for (int i = 0; ; ++i) {
if (idx_to_t.spt_v[i] == numOfVertices) break;
if (idx_to_t.spt_v[i] == meetnode) {
path_to_t.push_back(idx_to_t.spt_p[i]);
break;
}
}
}
//return distance;
EdgeWeight alldis = 0;
if (path_from_s.size() == 1)
if (s != inv_meetnode)
alldis += query_p(s, inv_meetnode);
if (path_to_t.size() == 1)
if (t != inv_meetnode)
alldis += query_p(t, inv_meetnode);
for (int i = 0; i < path_from_s.size() - 1; ++i) {
alldis += query_p(path_from_s[i], path_from_s[i + 1]);
//cout << "s " << path_from_s[i] << "," << path_from_s[i + 1] << endl;
}
for (int i = 0; i < path_to_t.size() - 1; ++i) {
alldis += query_p(path_to_t[i], path_to_t[i + 1]);
//cout <<"t " << path_to_t[i] << "," << path_to_t[i + 1] << endl;
}
/*if (distance != alldis)
cout << "a?" << endl;*/
//cout << distance << "," << alldis << "," << path_from_s.size() + path_to_t.size() << endl;
// cout << s << "," << t << "," << inv_meetnode << " " << distance << "vs." << alldis << endl;
return distance;
}
//EdgeWeight query_path_check(NodeID s, NodeID t, vector<NodeID>& rank, vector<NodeID>& inv) {
// EdgeWeight distance = INF_WEIGHT;
// NodeID meetnode = numOfVertices;
// NodeID s_parent;
// NodeID t_parent;
// const index_t_path_p &idx_s = index_p[s];
// const index_t_path_p &idx_t = index_p[t];
// _mm_prefetch(&idx_s.spt_v[0], _MM_HINT_T0);
// _mm_prefetch(&idx_t.spt_v[0], _MM_HINT_T0);
// _mm_prefetch(&idx_s.spt_d[0], _MM_HINT_T0);
// _mm_prefetch(&idx_t.spt_d[0], _MM_HINT_T0);
// _mm_prefetch(&idx_s.spt_p[0], _MM_HINT_T0);
// _mm_prefetch(&idx_t.spt_p[0], _MM_HINT_T0);
// for (int i = 0, j = 0; ; ) {
// NodeID v1 = idx_s.spt_v[i], v2 = idx_t.spt_v[j];
// if (v1 == numOfVertices) break; // Sentinel
// if (v1 == v2) {
// EdgeWeight td = idx_s.spt_d[i] + idx_t.spt_d[j];
// if (td < distance) {
// distance = td;
// if (v1 < meetnode) {
// meetnode = v1;
// s_parent = idx_s.spt_p[i];
// t_parent = idx_t.spt_p[j];
// }
// }
// ++i;
// ++j;
// }
// else {
// i += v1 < v2 ? 1 : 0;
// j += v1 > v2 ? 1 : 0;
// }
// }
// //Next, retrieve path from s - meetnode and meetnode - t.
// vector<NodeID> path_from_s;
// vector<NodeID> path_to_t;
// path_from_s.push_back(s_parent);
// path_to_t.push_back(t_parent);
// /* if (s == 194569 && t == 20072)
// cout << "debug." << " meet: " << meetnode << " sparent:" << s_parent << " tparent:" << t_parent << endl;*/
// NodeID inv_meetnode = inv[meetnode];
// while (path_from_s.back() != inv_meetnode) {
// /*if (s == 194569 && t == 20072)
// cout << "s meet:" << path_from_s.back() << endl;*/
// const index_t_path_p &idx_from_s = index_p[path_from_s.back()];
// _mm_prefetch(&idx_from_s.spt_v[0], _MM_HINT_T0);
// _mm_prefetch(&idx_from_s.spt_p[0], _MM_HINT_T0);
// // vector<NodeID>& index_from_s = index_[path_from_s.back()].spt_v;
// for (int i = 0; ; ++i) {
// if (idx_from_s.spt_v[i] == numOfVertices) break;
// if (idx_from_s.spt_v[i] == meetnode) {
// path_from_s.push_back(idx_from_s.spt_p[i]);
// break;
// }
// }
// }
// while (path_to_t.back() != inv_meetnode) {
// /*if (s == 194569 && t == 20072)
// cout << "t meet:" << path_to_t.back() << endl;*/
// // vector<NodeID>& index_to_t = index_[path_to_t.back()].spt_v;
// const index_t_path_p &idx_to_t = index_p[path_to_t.back()];
// _mm_prefetch(&idx_to_t.spt_v[0], _MM_HINT_T0);
// _mm_prefetch(&idx_to_t.spt_p[0], _MM_HINT_T0);
// for (int i = 0; ; ++i) {
// if (idx_to_t.spt_v[i] == numOfVertices) break;
// if (idx_to_t.spt_v[i] == meetnode) {
// path_to_t.push_back(idx_to_t.spt_p[i]);
// break;
// }
// }
// }
// EdgeWeight path_from_s = 0;
// for (int i = 0; i < path_from_s.size(); ++i) {
// }
//
// return distance;
//
//}
/*EdgeWeight query_new(NodeID s, NodeID t, Ordering& ordering) {
EdgeWeight distance = INF_WEIGHT;
vector<NodeID>& index_s = index_[s].spt_v;
vector<EdgeWeight>& index_s_d = index_[s].spt_d;
vector<NodeID>& index_t = index_[t].spt_v;
vector<EdgeWeight>& index_t_d = index_[t].spt_d;
for (int i = 0, j = 0; i < index_s.size(), j < index_t.size(); ) {
if (index_s[i] == index_t[j])
distance = min(distance, (EdgeWeight)(index_s_d[i++] + index_t_d[j++]));
else {
if (index_s[i] < index_t[j])
++i;
else
++j;
}
}
return distance;
}
*/
double avg_size() {
double total = 0;
for (int i = 0; i < numOfVertices; ++i) total += index_[i].spt_v.size();
double avg = total / numOfVertices - 1; // We do not count the trivial label (V, INF_WEIGHT).
return avg;
}
/*
NodeID max_size() {
NodeID maxsize = numeric_limits<NodeID>::min();
for (int i = 0; i < V; ++i) maxsize = max(maxsize, index_[i].spt_v.size());
return maxsize;
}*/
void append(NodeID v, NodeID root, EdgeWeight distance) {
index_[v].spt_v.push_back(root);
index_[v].spt_d.push_back(distance);
}
void print_stat() {
cout << "Average Label Size: " << avg_size() << endl;
//cout << "Maximum Label Size: " << max_size() << endl;
}
void Free() {
if (index_.size() == 0) return;
for (int v = 0; v < numOfVertices; ++v) {
index_[v].spt_v.clear();
index_[v].spt_d.clear();
}
index_.clear();
}
void save_labels(const char* save_filename) {
ofstream ofs(save_filename, ios::binary | ios::out);
ofs.write((const char*)&numOfVertices, sizeof(numOfVertices));
for (NodeID v = 0; v < numOfVertices; ++v) {
NodeID isize = index_[v].size();
ofs.write((const char*)&isize, sizeof(isize));
for (NodeID i = 0; i < index_[v].size(); ++i) {
ofs.write((const char*)&index_[v].spt_v[i], sizeof(index_[v].spt_v[i]));
ofs.write((const char*)&index_[v].spt_p[i], sizeof(index_[v].spt_p[i]));
ofs.write((const char*)&index_[v].spt_d[i], sizeof(index_[v].spt_d[i]));
}
}
ofs.close();
}
void load_labels(const char* load_filename) {
/* for (NodeID v = 0; v < numOfVertices; ++v) {
free(index_p[v].spt_v);
free(index_p[v].spt_d);
}
*/
//free(index_p);
index_p = NULL;
ifstream ifs(load_filename);
NodeID isize = 0;
ifs.read((char*)&isize, sizeof(isize));
numOfVertices = isize;
index_p = (index_t_path_p*)memalign(64, numOfVertices * sizeof(index_t_path_p));
for (NodeID v = 0; v < numOfVertices; ++v) {
index_t_path_p &idx = index_p[v];
ifs.read((char*)&isize, sizeof(isize));
idx.spt_v = (NodeID*)memalign(64, isize * sizeof(NodeID));
idx.spt_p = (NodeID*)memalign(64, isize * sizeof(NodeID));
idx.spt_d = (EdgeWeight*)memalign(64, isize * sizeof(EdgeWeight));
// index_[v].spt_v.resize(isize);
// index_[v].spt_d.resize(isize);
for (NodeID i = 0; i < isize; ++i) {
NodeID hub;
NodeID hub_parent;
EdgeWeight hub_weight;
ifs.read((char*)&hub, sizeof(hub));
ifs.read((char*)&hub_parent, sizeof(hub_parent));
ifs.read((char*)&hub_weight, sizeof(hub_weight));
//index_[v].spt_v[i] = hub;
//index_[v].spt_d[i] = hub_weight;
idx.spt_v[i] = hub;
idx.spt_p[i] = hub_parent;
idx.spt_d[i] = hub_weight;
}
}
ifs.close();
/*
index_.clear();
ifstream ifs(load_filename);
NodeID isize = 0;
ifs.read((char*)&isize, sizeof(isize));
numOfVertices = isize;
index_.resize(numOfVertices);
for (NodeID v = 0; v < numOfVertices; ++v) {
ifs.read((char*)&isize, sizeof(isize));
index_[v].spt_v.resize(isize);
index_[v].spt_d.resize(isize);
for (NodeID i = 0; i < index_[v].size(); ++i) {
NodeID hub;
EdgeWeight hub_weight;
ifs.read((char*)&hub, sizeof(hub));
ifs.read((char*)&hub_weight, sizeof(hub_weight));
index_[v].spt_v[i] = hub;
index_[v].spt_d[i] = hub_weight;
}
}
ifs.close();
*/
}
void save_labels_iteration_stats(const char* save_filename) {
vector<NodeID> stat(numOfVertices);
for (NodeID v = 0; v < numOfVertices; ++v) {
for (NodeID i = 0; i < index_[v].size(); ++i)
stat[index_[v].spt_v[i]]++;
}
ofstream ofs(save_filename);
for (NodeID v = 0; v < numOfVertices; ++v) {
ofs << stat[v] << endl;
}
ofs.close();
}
EdgeWeight query_with_info(NodeID s, NodeID t, query_info& q_info) {
double stime = GetCurrentTimeSec();
EdgeWeight distance = INF_WEIGHT;
vector<NodeID>& index_s = index_[s].spt_v;
vector<EdgeWeight>& index_s_d = index_[s].spt_d;
vector<NodeID>& index_t = index_[t].spt_v;
vector<EdgeWeight>& index_t_d = index_[t].spt_d;
q_info.meet_node = numOfVertices;
double meet_distance;
for (int i = 0, j = 0; i < index_s.size(), j < index_t.size(); ) {
if (index_s[i] == index_t[j]) {
meet_distance = (EdgeWeight)(index_s_d[i++] + index_t_d[j++]);
if (distance > meet_distance) {
distance = meet_distance;
q_info.meet_node = index_s[i];
}
}
else {
if (index_s[i] < index_t[j])
++i;
else
++j;
}
};
stime = GetCurrentTimeSec() - stime;
q_info.time_cost = stime;
if (index_s.size() < index_t.size())
q_info.search_len = index_s.size();
else
q_info.search_len = index_t.size();
return distance;
}
};
class DLabel : public Label {
public:
vector<index_t> bindex_; // Backward labels.
index_t_p* bindex_p;
two_index_t_p* b_two_index_p;
DLabel() {
index_.resize(numOfVertices);
bindex_.resize(numOfVertices);
}
~DLabel() {
Free();
}
EdgeWeight query(NodeID s, NodeID t) {
EdgeWeight distance = INF_WEIGHT;
vector<NodeID>& index_s = index_[s].spt_v;
vector<EdgeWeight>& index_s_d = index_[s].spt_d;
vector<NodeID>& bindex_t = bindex_[t].spt_v;
vector<EdgeWeight>& bindex_t_d = bindex_[t].spt_d;
for (int i = 0, j = 0; i < index_s.size(), j < bindex_t.size(); ) {
if (index_s[i] == bindex_t[j]) {
distance = min(distance, (EdgeWeight)(index_s_d[i] + bindex_t_d[j]));
++i;
++j;
}
else {
if (index_s[i] < bindex_t[j])
++i;
else
++j;
}
}
return distance;
}
EdgeWeight query(NodeID s, NodeID t, NodeID& meet, EdgeWeight& dis1, EdgeWeight& dis2) {
EdgeWeight distance = INF_WEIGHT;
vector<NodeID>& index_s = index_[s].spt_v;
vector<EdgeWeight>& index_s_d = index_[s].spt_d;
vector<NodeID>& bindex_t = bindex_[t].spt_v;
vector<EdgeWeight>& bindex_t_d = bindex_[t].spt_d;
meet = numeric_limits<NodeID>::max();
dis1 = numeric_limits<EdgeWeight>::max();
dis2 = numeric_limits<EdgeWeight>::max();
for (int i = 0, j = 0; i < index_s.size(), j < bindex_t.size(); ) {
if (index_s[i] == bindex_t[j]) {
if (distance > (EdgeWeight)(index_s_d[i] + bindex_t_d[j])) {
distance = (EdgeWeight)(index_s_d[i] + bindex_t_d[j]);
meet = index_s[i];
dis1 = index_s_d[i];
dis2 = bindex_t_d[j];
}
++i;
++j;
}
else {
if (index_s[i] < bindex_t[j])
++i;
else
++j;
}
}
return distance;
}
inline EdgeWeight query_p(NodeID s, NodeID t) {
//EdgeWeight distance = INF_WEIGHT;
//
////const index_t_p &idx_s = index_p[s];
////const index_t_p &idx_t = bindex_p[t];
//NodeID *vs = index_p[s].spt_v;
//NodeID *vt = bindex_p[t].spt_v;
//EdgeWeight* ws = index_p[s].spt_d;
//EdgeWeight* wt = bindex_p[t].spt_d;
//_mm_prefetch(vs, _MM_HINT_T0);
//_mm_prefetch(vt, _MM_HINT_T0);
//_mm_prefetch(ws, _MM_HINT_T0);
//_mm_prefetch(wt, _MM_HINT_T0);
//for (unsigned i = 0, j = 0; ; ) {
// if (*(vs + i) == *(vt + j)) {
// if (*(vs + i) == numOfVertices) break; // Sentinel
// EdgeWeight td = *(ws + i) + *(wt + j);
// if (td < distance) distance = td;
// ++i;
// ++j;
// }
// else {
// i += *(vs + i) < *(vt + j) ? 1 : 0;
// j += *(vs + i) > *(vt + j) ? 1 : 0;
// }
//}
//return distance;
EdgeWeight distance = INF_WEIGHT;
const index_t_p &idx_s = index_p[s];
const index_t_p &idx_t = bindex_p[t];
_mm_prefetch(&idx_s.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_s.spt_d[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_d[0], _MM_HINT_T0);
for (int i = 0, j = 0; ; ) {
NodeID v1 = idx_s.spt_v[i], v2 = idx_t.spt_v[j];
if (v1 == v2) {
if (v1 == numOfVertices) break; // Sentinel
EdgeWeight td = idx_s.spt_d[i] + idx_t.spt_d[j];
if (td < distance) distance = td;
++i;
++j;
}
else {
i += v1 < v2 ? 1 : 0;
j += v1 > v2 ? 1 : 0;
}
}
return distance;
}
EdgeWeight query_with_info(NodeID s, NodeID t, query_info& q_info) {
double stime = GetCurrentTimeSec();
EdgeWeight distance = INF_WEIGHT;
vector<NodeID>& index_s = index_[s].spt_v;
vector<EdgeWeight>& index_s_d = index_[s].spt_d;
// vector<NodeID>& index_t = index_[t].spt_v;
// vector<EdgeWeight>& index_t_d = index_[t].spt_d;
vector<NodeID>& bindex_t = bindex_[t].spt_v;
vector<EdgeWeight>& bindex_t_d = bindex_[t].spt_d;
q_info.meet_node = numOfVertices;
double meet_distance;
for (int i = 0, j = 0; i < index_s.size(), j < bindex_t.size(); ) {
if (index_s[i] == bindex_t[j]) {
meet_distance = (EdgeWeight)(index_s_d[i++] + bindex_t[j++]);
if (distance > meet_distance) {
distance = meet_distance;
q_info.meet_node = index_s[i];
}
}
else {
if (index_s[i] < bindex_t[j])
++i;
else
++j;
}
};
stime = GetCurrentTimeSec() - stime;
q_info.time_cost = stime;
if (index_s.size() < bindex_t.size())
q_info.search_len = index_s.size();
else
q_info.search_len = bindex_t.size();
return distance;
}
void append(NodeID v, NodeID root, EdgeWeight distance, bool forward) { // forward(backward) search from root to vertex v.
if (forward) { // forward search from root to vertex v, hence append (root, distance) to backward index of vertex v.
bindex_[v].spt_v.push_back(root);
bindex_[v].spt_d.push_back(distance);
}
else { // backward search from root to vertex v, hence append (root, distance) to forward index of vertex v.
index_[v].spt_v.push_back(root);
index_[v].spt_d.push_back(distance);
}
}
void Free() {
if (index_.size() == 0 || bindex_.size() == 0) return;
for (int v = 0; v < numOfVertices; ++v) {
index_[v].spt_v.clear();
index_[v].spt_d.clear();
if (DIRECTED_FLAG == true) {
bindex_[v].spt_v.clear();
bindex_[v].spt_d.clear();
}
}
index_.clear();
bindex_.clear();
}
double avg_size() {
double total = 0;
for (int i = 0; i < numOfVertices; ++i) {
total += index_[i].spt_v.size() ;
total += bindex_[i].spt_v.size();
}
double avg = total / numOfVertices / 2 - 1; // We do not count the trivial labels (V, INF_WEIGHT).
return avg;
}
void print_stat() {
cout << "Average Label Size: " << avg_size() << endl;
//cout << "Maximum Label Size: " << max_size() << endl;
}
void save_labels(const char* save_filename) {
ofstream ofs(save_filename, ios::binary | ios::out);
ofs.write((const char*)&numOfVertices, sizeof(numOfVertices));
for (NodeID v = 0; v < numOfVertices; ++v) {
int isize = index_[v].size();
ofs.write((const char*)&isize, sizeof(isize));
for (NodeID i = 0; i < index_[v].size(); ++i) {
ofs.write((const char*)&index_[v].spt_v[i], sizeof(index_[v].spt_v[i]));
ofs.write((const char*)&index_[v].spt_d[i], sizeof(index_[v].spt_d[i]));
}
int bisize = bindex_[v].size();
ofs.write((const char*)&bisize, sizeof(bisize));
for (NodeID i = 0; i < bindex_[v].size(); ++i) {
ofs.write((const char*)&bindex_[v].spt_v[i], sizeof(bindex_[v].spt_v[i]));
ofs.write((const char*)&bindex_[v].spt_d[i], sizeof(bindex_[v].spt_d[i]));
}
}
ofs.close();
}
void load_labels(const char* load_filename) {
cout << "Loading Labels" << endl;
/*
for (NodeID v = 0; v < numOfVertices; ++v) {
free(index_p[v].spt_v);
free(index_p[v].spt_d);
}*/
//free(index_p);
index_p = NULL;
bindex_p = NULL;
ifstream ifs(load_filename);
NodeID isize = 0;
ifs.read((char*)&isize, sizeof(isize));
numOfVertices = isize;
index_p = (index_t_p*)memalign(64, numOfVertices * sizeof(index_t_p));
bindex_p = (index_t_p*)memalign(64, numOfVertices * sizeof(index_t_p));
cout << numOfVertices << " vertices." << endl;
for (NodeID v = 0; v < numOfVertices; ++v) {
index_t_p &idx = index_p[v];
ifs.read((char*)&isize, sizeof(isize));
idx.spt_v = (NodeID*)memalign(64, isize * sizeof(NodeID));
idx.spt_d = (EdgeWeight*)memalign(64, isize * sizeof(EdgeWeight));
for (NodeID i = 0; i < isize; ++i) {
NodeID hub;
EdgeWeight hub_weight;
ifs.read((char*)&hub, sizeof(hub));
ifs.read((char*)&hub_weight, sizeof(hub_weight));
//index_[v].spt_v[i] = hub;
//index_[v].spt_d[i] = hub_weight;
idx.spt_v[i] = hub;
idx.spt_d[i] = hub_weight;
}
// index_[v].spt_v.resize(isize);
// index_[v].spt_d.resize(isize);
index_t_p &bidx = bindex_p[v];
ifs.read((char*)&isize, sizeof(isize));
bidx.spt_v = (NodeID*)memalign(64, isize * sizeof(NodeID));
bidx.spt_d = (EdgeWeight*)memalign(64, isize * sizeof(EdgeWeight));
for (NodeID i = 0; i < isize; ++i) {
NodeID hub;
EdgeWeight hub_weight;
ifs.read((char*)&hub, sizeof(hub));
ifs.read((char*)&hub_weight, sizeof(hub_weight));
//index_[v].spt_v[i] = hub;
//index_[v].spt_d[i] = hub_weight;
bidx.spt_v[i] = hub;
bidx.spt_d[i] = hub_weight;
}
}
ifs.close();
/*
index_.clear();
bindex_.clear();
ifs.open(load_filename, ios::binary | ios::in);
ifs.read((char*)&isize, sizeof(isize));
numOfVertices = isize;
index_.resize(numOfVertices);
bindex_.resize(numOfVertices);
for (NodeID v = 0; v < numOfVertices; ++v) {
ifs.read((char*)&isize, sizeof(isize));
index_[v].spt_v.resize(isize);
index_[v].spt_d.resize(isize);
for (NodeID i = 0; i < index_[v].size(); ++i) {
NodeID hub;
EdgeWeight hub_weight;
ifs.read((char*)&hub, sizeof(hub));
ifs.read((char*)&hub_weight, sizeof(hub_weight));
index_[v].spt_v[i] = hub;
index_[v].spt_d[i] = hub_weight;
}
ifs.read((char*)&isize, sizeof(isize));
bindex_[v].spt_v.resize(isize);
bindex_[v].spt_d.resize(isize);
for (NodeID i = 0; i < bindex_[v].size(); ++i) {
NodeID hub;
EdgeWeight hub_weight;
ifs.read((char*)&hub, sizeof(hub));
ifs.read((char*)&hub_weight, sizeof(hub_weight));
bindex_[v].spt_v[i] = hub;
bindex_[v].spt_d[i] = hub_weight;
}
}
ifs.close();
*/
/* for (int i = 0; i < numOfVertices; ++i) {
for (int j = 0; j < index_[i].size(); ++j)
if (index_[i].spt_v[j] != index_p[i].spt_v[j])
cout << "warning." << endl;
}*/
}
void convert_to_fewerbit(){
two_index_p = NULL;
b_two_index_p = NULL;
two_index_p = (two_index_t_p*)memalign(64, numOfVertices * sizeof(two_index_t_p));
b_two_index_p = (two_index_t_p*)memalign(64, numOfVertices * sizeof(two_index_t_p));
for (NodeID v = 0; v < numOfVertices; ++v) {
two_index_t_p &idx = two_index_p[v];
index_t_p &idx_original = index_p[v];
NodeID isize = 0;
for(NodeID i = 0; idx_original.spt_v[i] < UCHAR_MAX; ++i){
++isize;
}
idx.spt_lv = (uint8_t*)memalign(64, (isize + 1) * sizeof(uint8_t));
idx.spt_ld = (EdgeWeight*)memalign(64, (isize + 1) * sizeof(EdgeWeight));
// index_[v].spt_v.resize(isize);
// index_[v].spt_d.resize(isize);
for (NodeID i = 0; i < isize; ++i) {
uint8_t hub;
EdgeWeight hub_weight;
//index_[v].spt_v[i] = hub;
//index_[v].spt_d[i] = hub_weight;
idx.spt_lv[i] = idx_original.spt_v[i];
idx.spt_ld[i] = idx_original.spt_d[i];
}
idx.spt_lv[isize] = UCHAR_MAX;
idx.spt_ld[isize] = INF_WEIGHT;
NodeID larger_size = 0;
for(NodeID i = isize; idx_original.spt_v[i] != numOfVertices; ++i){
++larger_size;
}
idx.spt_v = (NodeID*)memalign(64, larger_size * sizeof(NodeID));
idx.spt_d = (EdgeWeight*)memalign(64, larger_size * sizeof(EdgeWeight));
for (NodeID i = 0; i < larger_size; ++i) {
uint8_t hub;
EdgeWeight hub_weight;
//index_[v].spt_v[i] = hub;
//index_[v].spt_d[i] = hub_weight;
idx.spt_v[i] = idx_original.spt_v[i + isize];
idx.spt_d[i] = idx_original.spt_d[i + isize];
}
two_index_t_p &b_idx = b_two_index_p[v];
index_t_p &b_idx_original = bindex_p[v];
isize = 0;
for(NodeID i = 0; b_idx_original.spt_v[i] < UCHAR_MAX; ++i){
++isize;
}
b_idx.spt_lv = (uint8_t*)memalign(64, (isize + 1) * sizeof(uint8_t));
b_idx.spt_ld = (EdgeWeight*)memalign(64, (isize + 1) * sizeof(EdgeWeight));
// index_[v].spt_v.resize(isize);
// index_[v].spt_d.resize(isize);
for (NodeID i = 0; i < isize; ++i) {
uint8_t hub;
EdgeWeight hub_weight;
//index_[v].spt_v[i] = hub;
//index_[v].spt_d[i] = hub_weight;
b_idx.spt_lv[i] = b_idx_original.spt_v[i];
b_idx.spt_ld[i] = b_idx_original.spt_d[i];
}
b_idx.spt_lv[isize] = UCHAR_MAX;
b_idx.spt_ld[isize] = INF_WEIGHT;
larger_size = 0;
for(NodeID i = isize; b_idx_original.spt_v[i] != numOfVertices; ++i){
++larger_size;
}
b_idx.spt_v = (NodeID*)memalign(64, larger_size * sizeof(NodeID));
b_idx.spt_d = (EdgeWeight*)memalign(64, larger_size * sizeof(EdgeWeight));
for (NodeID i = 0; i < larger_size; ++i) {
uint8_t hub;
EdgeWeight hub_weight;
//index_[v].spt_v[i] = hub;
//index_[v].spt_d[i] = hub_weight;
b_idx.spt_v[i] = b_idx_original.spt_v[i + isize];
b_idx.spt_d[i] = b_idx_original.spt_d[i + isize];
}
}
}
void save_labels_iteration_stats(const char* save_filename) {
vector<NodeID> stat(numOfVertices);
for (NodeID v = 0; v < numOfVertices; ++v) {
for (NodeID i = 0; i < index_[v].size(); ++i)
stat[index_[v].spt_v[i]]++;
for (NodeID i = 0; i < bindex_[v].size(); ++i)
stat[bindex_[v].spt_v[i]]++;
}
ofstream ofs(save_filename);
for (NodeID v = 0; v < numOfVertices; ++v) {
ofs << stat[v] << endl;
}
ofs.close();
}
};
class DPLabel{
public:
vector<index_t_path> index_;
vector<index_t_path> bindex_; // Backward labels.
index_t_path_p* index_p;
index_t_path_p* bindex_p;
DPLabel() {
index_.resize(numOfVertices);
bindex_.resize(numOfVertices);
}
~DPLabel() {
Free();
}
inline EdgeWeight query_path(NodeID s, NodeID t, vector<NodeID>& rank, vector<NodeID>& inv) {
EdgeWeight distance = INF_WEIGHT;
NodeID meetnode = numOfVertices;
NodeID s_parent;
NodeID t_parent;
const index_t_path_p &idx_s = index_p[s];
const index_t_path_p &idx_t = bindex_p[t];
_mm_prefetch(&idx_s.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_s.spt_d[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_d[0], _MM_HINT_T0);
_mm_prefetch(&idx_s.spt_p[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_p[0], _MM_HINT_T0);
for (int i = 0, j = 0; ; ) {
NodeID v1 = idx_s.spt_v[i], v2 = idx_t.spt_v[j];
if (v1 == numOfVertices) break; // Sentinel
if (v1 == v2) {
EdgeWeight td = idx_s.spt_d[i] + idx_t.spt_d[j];
if (td < distance) {
distance = td;
//if (v1 < meetnode) {
meetnode = v1;
s_parent = idx_s.spt_p[i];
t_parent = idx_t.spt_p[j];
// }
}
++i;
++j;
}
else {
i += v1 < v2 ? 1 : 0;
j += v1 > v2 ? 1 : 0;
}
}
//Next, retrieve path from s - meetnode and meetnode - t.
vector<NodeID> path_from_s;
vector<NodeID> path_to_t;
path_from_s.push_back(s_parent);
path_to_t.push_back(t_parent);
/* if (s == 194569 && t == 20072)
cout << "debug." << " meet: " << meetnode << " sparent:" << s_parent << " tparent:" << t_parent << endl;*/
NodeID inv_meetnode = inv[meetnode];
while (path_from_s.back() != inv_meetnode) {
/*if (s == 194569 && t == 20072)
cout << "s meet:" << path_from_s.back() << endl;*/
const index_t_path_p &idx_from_s = index_p[path_from_s.back()];
_mm_prefetch(&idx_from_s.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_from_s.spt_p[0], _MM_HINT_T0);
// vector<NodeID>& index_from_s = index_[path_from_s.back()].spt_v;
for (int i = 0; ; ++i) {
if (idx_from_s.spt_v[i] == numOfVertices) break;
if (idx_from_s.spt_v[i] == meetnode) {
path_from_s.push_back(idx_from_s.spt_p[i]);
break;
}
}
}
while (path_to_t.back() != inv_meetnode) {
/*if (s == 194569 && t == 20072)
cout << "t meet:" << path_to_t.back() << endl;*/
// vector<NodeID>& index_to_t = index_[path_to_t.back()].spt_v;
const index_t_path_p &idx_to_t = bindex_p[path_to_t.back()];
_mm_prefetch(&idx_to_t.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_to_t.spt_p[0], _MM_HINT_T0);
for (int i = 0; ; ++i) {
if (idx_to_t.spt_v[i] == numOfVertices) break;
if (idx_to_t.spt_v[i] == meetnode) {
path_to_t.push_back(idx_to_t.spt_p[i]);
break;
}
}
}
return distance;
}
EdgeWeight query_path_p(NodeID s, NodeID t, vector<NodeID>& rank, vector<NodeID>& inv) {
EdgeWeight distance = INF_WEIGHT;
vector<NodeID>& index_s = index_[s].spt_v;
vector<EdgeWeight>& index_s_d = index_[s].spt_d;
vector<NodeID>& bindex_t = bindex_[t].spt_v;
vector<EdgeWeight>& bindex_t_d = bindex_[t].spt_d;
NodeID meetnode = numOfVertices;
int s_parent;
int t_parent;
for (int i = 0, j = 0; i < index_s.size(), j < bindex_t.size(); ) {
if (index_s[i] == bindex_t[j]) {
if (distance >(EdgeWeight)(index_s_d[i] + bindex_t_d[j])) {
distance = (EdgeWeight)(index_s_d[i] + bindex_t_d[j]);
// if (index_s[i] < meetnode) {
meetnode = index_s[i];
s_parent = index_[s].spt_p[i];
t_parent = index_[t].spt_p[j];
// }
}
//distance = min(distance, (EdgeWeight)(index_s_d[i] + bindex_t_d[j]));
++i;
++j;
}
else {
if (index_s[i] < bindex_t[j])
++i;
else
++j;
}
}
//Next, retrieve path from s - meetnode and meetnode - t.
vector<NodeID> path_from_s;
vector<NodeID> path_to_t;
path_from_s.push_back(s_parent);
path_to_t.push_back(t_parent);
/* if (s == 194569 && t == 20072)
cout << "debug." << " meet: " << meetnode << " sparent:" << s_parent << " tparent:" << t_parent << endl;*/
while (path_from_s.back() != inv[meetnode]) {
/*if (s == 194569 && t == 20072)
cout << "s meet:" << path_from_s.back() << endl;*/
vector<NodeID>& index_from_s = index_[path_from_s.back()].spt_v;
for (int i = 0; i < index_from_s.size(); ++i) {
if (index_from_s[i] == meetnode) {
path_from_s.push_back(index_[path_from_s.back()].spt_p[i]);
break;
}
}
}
while (path_to_t.back() != inv[meetnode]) {
/*if (s == 194569 && t == 20072)
cout << "t meet:" << path_to_t.back() << endl;*/
vector<NodeID>& index_to_t = bindex_[path_to_t.back()].spt_v;
for (int i = 0; i < index_to_t.size(); ++i) {
if (index_to_t[i] == meetnode) {
path_to_t.push_back(bindex_[path_to_t.back()].spt_p[i]);
break;
}
}
}
//for (int i = 0; i < path_from_s.size(); ++i)
// path_from_s[i] = inv[path_from_s[i]];
//for (int i = 0; i < path_to_t.size(); ++i)
// path_to_t[i] = inv[path_to_t[i]];
return path_from_s.size() + path_to_t.size();
}
void Free() {
if (index_.size() == 0 || bindex_.size() == 0) return;
for (int v = 0; v < numOfVertices; ++v) {
index_[v].spt_v.clear();
index_[v].spt_d.clear();
if (DIRECTED_FLAG == true) {
bindex_[v].spt_v.clear();
bindex_[v].spt_d.clear();
}
}
index_.clear();
bindex_.clear();
}
double avg_size() {
double total = 0;
for (int i = 0; i < numOfVertices; ++i) {
total += index_[i].spt_v.size();
total += bindex_[i].spt_v.size();
}
double avg = total / numOfVertices / 2 - 1; // We do not count the trivial labels (V, INF_WEIGHT).
return avg;
}
void print_stat() {
cout << "Average Label Size: " << avg_size() << endl;
//cout << "Maximum Label Size: " << max_size() << endl;
}
void save_labels(const char* save_filename) {
ofstream ofs(save_filename, ios::binary | ios::out);
ofs.write((const char*)&numOfVertices, sizeof(numOfVertices));
for (NodeID v = 0; v < numOfVertices; ++v) {
int isize = index_[v].size();
ofs.write((const char*)&isize, sizeof(isize));
for (NodeID i = 0; i < index_[v].size(); ++i) {
ofs.write((const char*)&index_[v].spt_v[i], sizeof(index_[v].spt_v[i]));
ofs.write((const char*)&index_[v].spt_p[i], sizeof(index_[v].spt_p[i]));
ofs.write((const char*)&index_[v].spt_d[i], sizeof(index_[v].spt_d[i]));
}
int bisize = bindex_[v].size();
ofs.write((const char*)&bisize, sizeof(bisize));
for (NodeID i = 0; i < bindex_[v].size(); ++i) {
ofs.write((const char*)&bindex_[v].spt_v[i], sizeof(bindex_[v].spt_v[i]));
ofs.write((const char*)&bindex_[v].spt_p[i], sizeof(bindex_[v].spt_p[i]));
ofs.write((const char*)&bindex_[v].spt_d[i], sizeof(bindex_[v].spt_d[i]));
}
}
ofs.close();
}
void load_labels(const char* load_filename) {
index_p = NULL;
bindex_p = NULL;
ifstream ifs(load_filename, ios::binary | ios::in);
NodeID isize;
ifs.read((char*)&isize, sizeof(isize));
numOfVertices = isize;
index_p = (index_t_path_p*)memalign(64, numOfVertices * sizeof(index_t_path_p));
bindex_p = (index_t_path_p*)memalign(64, numOfVertices * sizeof(index_t_path_p));
cout << numOfVertices << " vertices." << endl;
for (NodeID v = 0; v < numOfVertices; ++v) {
index_t_path_p &idx = index_p[v];
ifs.read((char*)&isize, sizeof(isize));
idx.spt_v = (NodeID*)memalign(64, isize * sizeof(NodeID));
idx.spt_p = (NodeID*)memalign(64, isize * sizeof(NodeID));
idx.spt_d = (EdgeWeight*)memalign(64, isize * sizeof(EdgeWeight));
for (NodeID i = 0; i < isize; ++i) {
NodeID hub;
EdgeWeight hub_weight;
NodeID hub_parent;
ifs.read((char*)&hub, sizeof(hub));
ifs.read((char*)&hub_parent, sizeof(hub_parent));
ifs.read((char*)&hub_weight, sizeof(hub_weight));
//index_[v].spt_v[i] = hub;
//index_[v].spt_d[i] = hub_weight;
idx.spt_v[i] = hub;
idx.spt_d[i] = hub_weight;
idx.spt_p[i] = hub_parent;
}
// index_[v].spt_v.resize(isize);
// index_[v].spt_d.resize(isize);
index_t_path_p &bidx = bindex_p[v];
ifs.read((char*)&isize, sizeof(isize));
bidx.spt_v = (NodeID*)memalign(64, isize * sizeof(NodeID));
bidx.spt_d = (EdgeWeight*)memalign(64, isize * sizeof(EdgeWeight));
bidx.spt_p = (NodeID*)memalign(64, isize * sizeof(NodeID));
for (NodeID i = 0; i < isize; ++i) {
NodeID hub;
EdgeWeight hub_weight;
NodeID hub_parent;
ifs.read((char*)&hub, sizeof(hub));
ifs.read((char*)&hub_parent, sizeof(hub_parent));
ifs.read((char*)&hub_weight, sizeof(hub_weight));
//index_[v].spt_v[i] = hub;
//index_[v].spt_d[i] = hub_weight;
bidx.spt_v[i] = hub;
bidx.spt_d[i] = hub_weight;
bidx.spt_p[i] = hub_parent;
}
}
ifs.close();
/*index_.clear();
bindex_.clear();
ifstream ifs(load_filename, ios::binary | ios::in);
NodeID isize;
ifs.read((char*)&isize, sizeof(isize));
numOfVertices = isize;
index_.resize(numOfVertices);
bindex_.resize(numOfVertices);
for (NodeID v = 0; v < numOfVertices; ++v) {
ifs.read((char*)&isize, sizeof(isize));
index_[v].spt_v.resize(isize);
index_[v].spt_p.resize(isize);
index_[v].spt_d.resize(isize);
for (NodeID i = 0; i < index_[v].size(); ++i) {
NodeID hub;
NodeID parent;
EdgeWeight hub_weight;
ifs.read((char*)&hub, sizeof(hub));
ifs.read((char*)&parent, sizeof(parent));
ifs.read((char*)&hub_weight, sizeof(hub_weight));
index_[v].spt_v[i] = hub;
index_[v].spt_p[i] = parent;
index_[v].spt_d[i] = hub_weight;
}
ifs.read((char*)&isize, sizeof(isize));
bindex_[v].spt_v.resize(isize);
bindex_[v].spt_d.resize(isize);
for (NodeID i = 0; i < bindex_[v].size(); ++i) {
NodeID hub;
NodeID parent;
EdgeWeight hub_weight;
ifs.read((char*)&hub, sizeof(hub));
ifs.read((char*)&parent, sizeof(parent));
ifs.read((char*)&hub_weight, sizeof(hub_weight));
bindex_[v].spt_v[i] = hub;
bindex_[v].spt_p[i] = parent;
bindex_[v].spt_d[i] = hub_weight;
}
}
ifs.close();*/
}
inline EdgeWeight query_p(NodeID s, NodeID t) {
//EdgeWeight distance = INF_WEIGHT;
//
////const index_t_p &idx_s = index_p[s];
////const index_t_p &idx_t = bindex_p[t];
//NodeID *vs = index_p[s].spt_v;
//NodeID *vt = bindex_p[t].spt_v;
//EdgeWeight* ws = index_p[s].spt_d;
//EdgeWeight* wt = bindex_p[t].spt_d;
//_mm_prefetch(vs, _MM_HINT_T0);
//_mm_prefetch(vt, _MM_HINT_T0);
//_mm_prefetch(ws, _MM_HINT_T0);
//_mm_prefetch(wt, _MM_HINT_T0);
//for (unsigned i = 0, j = 0; ; ) {
// if (*(vs + i) == *(vt + j)) {
// if (*(vs + i) == numOfVertices) break; // Sentinel
// EdgeWeight td = *(ws + i) + *(wt + j);
// if (td < distance) distance = td;
// ++i;
// ++j;
// }
// else {
// i += *(vs + i) < *(vt + j) ? 1 : 0;
// j += *(vs + i) > *(vt + j) ? 1 : 0;
// }
//}
//return distance;
EdgeWeight distance = INF_WEIGHT;
const index_t_path_p &idx_s = index_p[s];
const index_t_path_p &idx_t = bindex_p[t];
_mm_prefetch(&idx_s.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_s.spt_d[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_d[0], _MM_HINT_T0);
for (int i = 0, j = 0; ; ) {
NodeID v1 = idx_s.spt_v[i], v2 = idx_t.spt_v[j];
if (v1 == v2) {
if (v1 == numOfVertices) break; // Sentinel
EdgeWeight td = idx_s.spt_d[i] + idx_t.spt_d[j];
if (td < distance) distance = td;
++i;
++j;
}
else {
i += v1 < v2 ? 1 : 0;
j += v1 > v2 ? 1 : 0;
}
}
return distance;
}
};
template<int kNumBitParallelRoots = 50>
class BPLabel {
public:
index_t_bp<kNumBitParallelRoots>* index_bp;
BPLabel() {
}
~BPLabel() {
//Free();
}
EdgeWeight query_p(NodeID s, NodeID t) {
EdgeWeight distance = INF_WEIGHT;
NodeID *vs = index_bp[s].spt_v;
NodeID *vt = index_bp[t].spt_v;
EdgeWeight* ws = index_bp[s].spt_d;
EdgeWeight* wt = index_bp[t].spt_d;
_mm_prefetch(vs, _MM_HINT_T0);
_mm_prefetch(vt, _MM_HINT_T0);
_mm_prefetch(ws, _MM_HINT_T0);
_mm_prefetch(wt, _MM_HINT_T0);
for (int i = 0; i < kNumBitParallelRoots; ++i) {
EdgeWeight td = index_bp[s].bpspt_d[i] + index_bp[t].bpspt_d[i];
if (td - 2 <= distance) {
td +=
(index_bp[s].bpspt_s[i][0] & index_bp[t].bpspt_s[i][0]) ? -2 :
((index_bp[s].bpspt_s[i][0] & index_bp[t].bpspt_s[i][1]) | (index_bp[s].bpspt_s[i][1] & index_bp[t].bpspt_s[i][0]))
? -1 : 0;
if (td < distance) distance = td;
}
}
for (unsigned i = 0, j = 0; ; ) {
if (*(vs + i) == *(vt + j)) {
if (*(vs + i) == numOfVertices) break; // Sentinel
EdgeWeight td = *(ws + i) + *(wt + j);
if (td < distance) distance = td;
++i;
++j;
}
else {
i += *(vs + i) < *(vt + j) ? 1 : 0;
j += *(vs + i) > *(vt + j) ? 1 : 0;
}
}
return distance;
}
EdgeWeight query_p(NodeID s, NodeID t, bool& isBP) {
EdgeWeight distance = INF_WEIGHT;
const index_t_bp<kNumBitParallelRoots> &idx_s = index_bp[s];
const index_t_bp<kNumBitParallelRoots> &idx_t = index_bp[t];
_mm_prefetch(&idx_s.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_v[0], _MM_HINT_T0);
_mm_prefetch(&idx_s.spt_d[0], _MM_HINT_T0);
_mm_prefetch(&idx_t.spt_d[0], _MM_HINT_T0);
isBP = false;
for (int i = 0; i < kNumBitParallelRoots; ++i) {
EdgeWeight td = index_bp[s].bpspt_d[i] + index_bp[t].bpspt_d[i];
if (td - 2 <= distance) {
td +=
(index_bp[s].bpspt_s[i][0] & index_bp[t].bpspt_s[i][0]) ? -2 :
((index_bp[s].bpspt_s[i][0] & index_bp[t].bpspt_s[i][1]) | (index_bp[s].bpspt_s[i][1] & index_bp[t].bpspt_s[i][0]))
? -1 : 0;
if (td < distance) {
distance = td;
isBP = true;
}
}
}
for (int i = 0, j = 0; ; ) {
NodeID v1 = idx_s.spt_v[i], v2 = idx_t.spt_v[j];
if (v1 == numOfVertices) break; // Sentinel
if (v1 == v2) {
EdgeWeight td = idx_s.spt_d[i] + idx_t.spt_d[j];
if (td < distance) {
distance = td;
isBP = false;
}
++i;
++j;
}
else {
i += v1 < v2 ? 1 : 0;
j += v1 > v2 ? 1 : 0;
}
}
return distance;
}
/*
NodeID max_size() {
NodeID maxsize = numeric_limits<NodeID>::min();
for (int i = 0; i < V; ++i) maxsize = max(maxsize, index_[i].spt_v.size());
return maxsize;
}*/
void print_stat() {
cout << "Average Label Size: " << avg_size() << endl;
//cout << "Maximum Label Size: " << max_size() << endl;
}
double avg_size() {
double lab_count = 0;
for (NodeID v = 0; v < numOfVertices; ++v) {
NodeID isize;
for (isize = 1; index_bp[v].spt_v[isize - 1] != numOfVertices; ++isize) continue;
lab_count += isize;
}
lab_count = (double)lab_count / (double)numOfVertices - 1;
return lab_count;
}
void Free() {
for (int v = 0; v < numOfVertices; ++v) {
free(index_bp[v].spt_v);
free(index_bp[v].spt_d);
}
free(index_bp);
index_bp = NULL;
}
void save_labels(const char* save_filename) {
ofstream ofs(save_filename, ios::binary | ios::out);
ofs.write((const char*)&numOfVertices, sizeof(numOfVertices));
int knumbit = kNumBitParallelRoots;
ofs.write((const char*)&knumbit, sizeof(knumbit));
for (NodeID v = 0; v < numOfVertices; ++v) {
index_t_bp<kNumBitParallelRoots> &idx = index_bp[v];
for (int i = 0; i < kNumBitParallelRoots; ++i) {
EdgeWeight d = idx.bpspt_d[i];
uint64_t a = idx.bpspt_s[i][0];
uint64_t b = idx.bpspt_s[i][1];
ofs.write((const char*)&d, sizeof(d));
ofs.write((const char*)&a, sizeof(a));
ofs.write((const char*)&b, sizeof(b));
}
NodeID isize;
for (isize = 1; idx.spt_v[isize - 1] != numOfVertices; ++isize) continue; // Find the sentinel
ofs.write((const char*)&isize, sizeof(isize));
for (NodeID i = 0; i < isize; ++i) {
ofs.write((const char*)&idx.spt_v[i], sizeof(idx.spt_v[i]));
ofs.write((const char*)&idx.spt_d[i], sizeof(idx.spt_d[i]));
}
}
ofs.close();
}
void load_labels(const char* load_filename){
index_bp = NULL;
int knumbit;
ifstream ifs(load_filename);
NodeID isize = 0;
ifs.read((char*)&isize, sizeof(isize));
numOfVertices = isize;
ifs.read((char*)&knumbit, sizeof(isize));
if (knumbit != kNumBitParallelRoots) {
cout << knumbit << "!=" << kNumBitParallelRoots << endl;
return;
}
index_bp = (index_t_bp<kNumBitParallelRoots>*)memalign(64, numOfVertices * sizeof(index_t_bp<kNumBitParallelRoots>));
for (NodeID v = 0; v < numOfVertices; ++v) {
index_t_bp<kNumBitParallelRoots> &idx = index_bp[v];
for (int i = 0; i < kNumBitParallelRoots; ++i) {
//idx.bpspt_s[i] = (uint64_t*)memalign(64, 2 * sizeof(uint64_t));
EdgeWeight d;
uint64_t a, b;
ifs.read((char*)&d, sizeof(EdgeWeight));
ifs.read((char*)&a, sizeof(uint64_t));
ifs.read((char*)&b, sizeof(uint64_t));
idx.bpspt_d[i] = d;
idx.bpspt_s[i][0] = a;
idx.bpspt_s[i][1] = b;
}
ifs.read((char*)&isize, sizeof(isize));
idx.spt_v = (NodeID*)memalign(64, isize * sizeof(NodeID));
idx.spt_d = (EdgeWeight*)memalign(64, isize * sizeof(EdgeWeight));
for (NodeID i = 0; i < isize; ++i) {
NodeID hub;
EdgeWeight hub_weight;
ifs.read((char*)&hub, sizeof(hub));
ifs.read((char*)&hub_weight, sizeof(hub_weight));
idx.spt_v[i] = hub;
idx.spt_d[i] = hub_weight;
}
}
ifs.close();
}
};
template<int kNumBitParallelRoots = 50>
class DBPLabel {
public:
index_t_bp<kNumBitParallelRoots>* index_bp;
index_t_bp<kNumBitParallelRoots>* bindex_bp;
DBPLabel() {
}
~DBPLabel() {
}
/*EdgeWeight query_p(NodeID s, NodeID t) {
EdgeWeight distance = INF_WEIGHT;
NodeID *vs = index_p[s].spt_v;
NodeID *vt = index_p[t].spt_v;
EdgeWeight* ws = index_p[s].spt_d;
EdgeWeight* wt = index_p[t].spt_d;
_mm_prefetch(vs, _MM_HINT_T0);
_mm_prefetch(vt, _MM_HINT_T0);
_mm_prefetch(ws, _MM_HINT_T0);
_mm_prefetch(wt, _MM_HINT_T0);
for (unsigned i = 0, j = 0; ; ) {
if (*(vs + i) == *(vt + j)) {
if (*(vs + i) == numOfVertices) break; // Sentinel
EdgeWeight td = *(ws + i) + *(wt + j);
if (td < distance) distance = td;
++i;
++j;
}
else {
i += *(vs + i) < *(vt + j) ? 1 : 0;
j += *(vs + i) > *(vt + j) ? 1 : 0;
}
}
return distance;
//EdgeWeight distance = INF_WEIGHT;
//const index_t_p &idx_s = index_p[s];
//const index_t_p &idx_t = index_p[t];
//_mm_prefetch(&idx_s.spt_v[0], _MM_HINT_T0);
//_mm_prefetch(&idx_t.spt_v[0], _MM_HINT_T0);
//_mm_prefetch(&idx_s.spt_d[0], _MM_HINT_T0);
//_mm_prefetch(&idx_t.spt_d[0], _MM_HINT_T0);
//for (int i = 0, j = 0; ; ) {
// NodeID v1 = idx_s.spt_v[i], v2 = idx_t.spt_v[j];
// if (v1 == numOfVertices) break; // Sentinel
// if (v1 == v2) {
// EdgeWeight td = idx_s.spt_d[i] + idx_t.spt_d[j];
// if (td < distance) distance = td;
// ++i;
// ++j;
// }
// else {
// i += v1 < v2 ? 1 : 0;
// j += v1 > v2 ? 1 : 0;
// }
//}
//return distance;
}
*/
/*
NodeID max_size() {
NodeID maxsize = numeric_limits<NodeID>::min();
for (int i = 0; i < V; ++i) maxsize = max(maxsize, index_[i].spt_v.size());
return maxsize;
}*/
EdgeWeight query_p(NodeID s, NodeID t) {
EdgeWeight distance = INF_WEIGHT;
NodeID *vs = index_bp[s].spt_v;
NodeID *vt = bindex_bp[t].spt_v;
EdgeWeight* ws = index_bp[s].spt_d;
EdgeWeight* wt = bindex_bp[t].spt_d;
_mm_prefetch(vs, _MM_HINT_T0);
_mm_prefetch(vt, _MM_HINT_T0);
_mm_prefetch(ws, _MM_HINT_T0);
_mm_prefetch(wt, _MM_HINT_T0);
for (int i = 0; i < kNumBitParallelRoots; ++i) {
EdgeWeight td = index_bp[s].bpspt_d[i] + bindex_bp[t].bpspt_d[i];
if (td - 2 <= distance) {
td +=
(index_bp[s].bpspt_s[i][0] & bindex_bp[t].bpspt_s[i][0]) ? -2 :
((index_bp[s].bpspt_s[i][0] & bindex_bp[t].bpspt_s[i][1]) | (index_bp[s].bpspt_s[i][1] & bindex_bp[t].bpspt_s[i][0]))
? -1 : 0;
if (td < distance) distance = td;
}
}
for (unsigned i = 0, j = 0; ; ) {
if (*(vs + i) == *(vt + j)) {
if (*(vs + i) == numOfVertices) break; // Sentinel
EdgeWeight td = *(ws + i) + *(wt + j);
if (td < distance) distance = td;
++i;
++j;
}
else {
i += *(vs + i) < *(vt + j) ? 1 : 0;
j += *(vs + i) > *(vt + j) ? 1 : 0;
}
}
return distance;
}
EdgeWeight query_p(NodeID s, NodeID t, bool& isBP) {
isBP = false;
EdgeWeight distance = INF_WEIGHT;
NodeID *vs = index_bp[s].spt_v;
NodeID *vt = bindex_bp[t].spt_v;
EdgeWeight* ws = index_bp[s].spt_d;
EdgeWeight* wt = bindex_bp[t].spt_d;
_mm_prefetch(vs, _MM_HINT_T0);
_mm_prefetch(vt, _MM_HINT_T0);
_mm_prefetch(ws, _MM_HINT_T0);
_mm_prefetch(wt, _MM_HINT_T0);
for (int i = 0; i < kNumBitParallelRoots; ++i) {
EdgeWeight td = index_bp[s].bpspt_d[i] + bindex_bp[t].bpspt_d[i];
if (td - 2 <= distance) {
td +=
(index_bp[s].bpspt_s[i][0] & bindex_bp[t].bpspt_s[i][0]) ? -2 :
((index_bp[s].bpspt_s[i][0] & bindex_bp[t].bpspt_s[i][1]) | (index_bp[s].bpspt_s[i][1] & bindex_bp[t].bpspt_s[i][0]))
? -1 : 0;
if (td < distance) {
distance = td;
isBP = true;
}
}
}
for (unsigned i = 0, j = 0; ; ) {
if (*(vs + i) == *(vt + j)) {
if (*(vs + i) == numOfVertices) break; // Sentinel
EdgeWeight td = *(ws + i) + *(wt + j);
if (td < distance) {
distance = td;
isBP = false;
}
++i;
++j;
}
else {
i += *(vs + i) < *(vt + j) ? 1 : 0;
j += *(vs + i) > *(vt + j) ? 1 : 0;
}
}
return distance;
}
void print_stat() {
cout << "Average Label Size: " << avg_size() << endl;
//cout << "Maximum Label Size: " << max_size() << endl;
}
double avg_size() {
double lab_count = 0;
for (NodeID v = 0; v < numOfVertices; ++v) {
NodeID isize;
for (isize = 1; index_bp[v].spt_v[isize - 1] != numOfVertices; ++isize) continue;
lab_count += isize;
for (isize = 1; bindex_bp[v].spt_v[isize - 1] != numOfVertices; ++isize) continue;
}
lab_count = (double)lab_count / (double)numOfVertices - 1 / (double)2;
return lab_count;
}
void Free() {
for (int v = 0; v < numOfVertices; ++v) {
free(index_bp[v].spt_v);
free(index_bp[v].spt_d);
free(index_bp[v].bpspt_d);
free(index_bp[v].bpspt_s);
free(bindex_bp[v].spt_v);
free(bindex_bp[v].spt_d);
free(bindex_bp[v].bpspt_d);
free(bindex_bp[v].bpspt_s);
}
free(index_bp);
free(bindex_bp);
index_bp = NULL;
bindex_bp = NULL;
}
void save_labels(const char* save_filename) {
ofstream ofs(save_filename, ios::binary | ios::out);
ofs.write((const char*)&numOfVertices, sizeof(numOfVertices));
int knumbit = kNumBitParallelRoots;
ofs.write((const char*)&knumbit, sizeof(knumbit));
for (NodeID v = 0; v < numOfVertices; ++v) {
index_t_bp<kNumBitParallelRoots> &idx = index_bp[v];
index_t_bp<kNumBitParallelRoots> &r_idx = bindex_bp[v];
for (int i = 0; i < kNumBitParallelRoots; ++i) {
EdgeWeight d = idx.bpspt_d[i];
uint64_t a = idx.bpspt_s[i][0];
uint64_t b = idx.bpspt_s[i][1];
ofs.write((const char*)&d, sizeof(d));
ofs.write((const char*)&a, sizeof(a));
ofs.write((const char*)&b, sizeof(b));
}
for (int i = 0; i < kNumBitParallelRoots; ++i) {
EdgeWeight d = r_idx.bpspt_d[i];
uint64_t a = r_idx.bpspt_s[i][0];
uint64_t b = r_idx.bpspt_s[i][1];
ofs.write((const char*)&d, sizeof(d));
ofs.write((const char*)&a, sizeof(a));
ofs.write((const char*)&b, sizeof(b));
}
NodeID isize;
for (isize = 1; idx.spt_v[isize - 1] != numOfVertices; ++isize) continue; // Find the sentinel
ofs.write((const char*)&isize, sizeof(isize));
for (NodeID i = 0; i < isize; ++i) {
ofs.write((const char*)&idx.spt_v[i], sizeof(idx.spt_v[i]));
ofs.write((const char*)&idx.spt_d[i], sizeof(idx.spt_d[i]));
}
for (isize = 1; r_idx.spt_v[isize - 1] != numOfVertices; ++isize) continue; // Find the sentinel
ofs.write((const char*)&isize, sizeof(isize));
for (NodeID i = 0; i < isize; ++i) {
ofs.write((const char*)&r_idx.spt_v[i], sizeof(r_idx.spt_v[i]));
ofs.write((const char*)&r_idx.spt_d[i], sizeof(r_idx.spt_d[i]));
}
}
ofs.close();
}
void load_labels(const char* load_filename) {
index_bp = NULL;
int knumbit;
ifstream ifs(load_filename);
NodeID isize = 0;
ifs.read((char*)&isize, sizeof(isize));
numOfVertices = isize;
ifs.read((char*)&knumbit, sizeof(isize));
if (knumbit != kNumBitParallelRoots) {
cout << knumbit << "!=" << kNumBitParallelRoots << endl;
return;
}
index_bp = (index_t_bp<kNumBitParallelRoots>*)memalign(64, numOfVertices * sizeof(index_t_bp<kNumBitParallelRoots>));
bindex_bp = (index_t_bp<kNumBitParallelRoots>*)memalign(64, numOfVertices * sizeof(index_t_bp<kNumBitParallelRoots>));
for (NodeID v = 0; v < numOfVertices; ++v) {
index_t_bp<kNumBitParallelRoots> &idx = index_bp[v];
index_t_bp<kNumBitParallelRoots> &r_idx = bindex_bp[v];
for (int i = 0; i < kNumBitParallelRoots; ++i) {
//idx.bpspt_s[i] = (uint64_t*)memalign(64, 2 * sizeof(uint64_t));
EdgeWeight d;
uint64_t a, b;
ifs.read((char*)&d, sizeof(EdgeWeight));
ifs.read((char*)&a, sizeof(uint64_t));
ifs.read((char*)&b, sizeof(uint64_t));
idx.bpspt_d[i] = d;
idx.bpspt_s[i][0] = a;
idx.bpspt_s[i][1] = b;
}
for (int i = 0; i < kNumBitParallelRoots; ++i) {
//idx.bpspt_s[i] = (uint64_t*)memalign(64, 2 * sizeof(uint64_t));
EdgeWeight d;
uint64_t a, b;
ifs.read((char*)&d, sizeof(EdgeWeight));
ifs.read((char*)&a, sizeof(uint64_t));
ifs.read((char*)&b, sizeof(uint64_t));
r_idx.bpspt_d[i] = d;
r_idx.bpspt_s[i][0] = a;
r_idx.bpspt_s[i][1] = b;
}
ifs.read((char*)&isize, sizeof(isize));
idx.spt_v = (NodeID*)memalign(64, isize * sizeof(NodeID));
idx.spt_d = (EdgeWeight*)memalign(64, isize * sizeof(EdgeWeight));
for (NodeID i = 0; i < isize; ++i) {
NodeID hub;
EdgeWeight hub_weight;
ifs.read((char*)&hub, sizeof(hub));
ifs.read((char*)&hub_weight, sizeof(hub_weight));
idx.spt_v[i] = hub;
idx.spt_d[i] = hub_weight;
}
ifs.read((char*)&isize, sizeof(isize));
r_idx.spt_v = (NodeID*)memalign(64, isize * sizeof(NodeID));
r_idx.spt_d = (EdgeWeight*)memalign(64, isize * sizeof(EdgeWeight));
for (NodeID i = 0; i < isize; ++i) {
NodeID hub;
EdgeWeight hub_weight;
ifs.read((char*)&hub, sizeof(hub));
ifs.read((char*)&hub_weight, sizeof(hub_weight));
r_idx.spt_v[i] = hub;
r_idx.spt_d[i] = hub_weight;
}
}
ifs.close();
}
};
#endif
|
papi.c | #include"SimpleMOC_header.h"
#ifdef PAPI
// initialize papi with one thread first
void papi_serial_init(void)
{
if ( PAPI_library_init(PAPI_VER_CURRENT) != PAPI_VER_CURRENT){
fprintf(stderr, "PAPI library init error!\n");
exit(1);
}
if (( PAPI_thread_init((long unsigned int (*)(void))
pthread_self )) != PAPI_OK){
PAPI_perror("PAPI_thread_init");
exit(1);
}
}
void counter_init( int *eventset, int *num_papi_events, Input * I )
{
char error_str[PAPI_MAX_STR_LEN];
int stat;
int * events;
// Command line event
if( I->papi_event_set == -1){
*num_papi_events = 1;
events = (int *) malloc( *num_papi_events * sizeof(int));
PAPI_event_name_to_code( I->event_name, &events[0]);
}
// FLOPS
if( I->papi_event_set == 0 )
{
*num_papi_events = 2;
events = (int *) malloc( *num_papi_events * sizeof(int));
events[0] = PAPI_SP_OPS;
events[1] = PAPI_TOT_CYC;
}
// Bandwidth
if( I->papi_event_set == 1 )
{
*num_papi_events = 2;
events = (int *) malloc( *num_papi_events * sizeof(int));
events[0] = PAPI_L3_TCM;
events[1] = PAPI_TOT_CYC;
}
// CPU Stall Reason
if( I->papi_event_set == 2 )
{
*num_papi_events = 4;
events = (int *) malloc( *num_papi_events * sizeof(int));
int EventCode;
char * event1 = "RESOURCE_STALLS:ANY";
char * event2 = "RESOURCE_STALLS:SB";
char * event3 = "RESOURCE_STALLS:RS";
char * event4 = "RESOURCE_STALLS2:OOO_RSRC";
PAPI_event_name_to_code( event1, &EventCode );
events[0] = EventCode;
PAPI_event_name_to_code( event2, &EventCode );
events[1] = EventCode;
PAPI_event_name_to_code( event3, &EventCode );
events[2] = EventCode;
PAPI_event_name_to_code( event4, &EventCode );
events[3] = EventCode;
}
// CPU Stall Percentage
if( I->papi_event_set == 3 )
{
*num_papi_events = 2;
events = (int *) malloc( *num_papi_events * sizeof(int));
int EventCode;
char * event1 = "RESOURCE_STALLS:ANY";
char * event2 = "PAPI_TOT_CYC";
PAPI_event_name_to_code( event1, &EventCode );
events[0] = EventCode;
PAPI_event_name_to_code( event2, &EventCode );
events[1] = EventCode;
}
// Memory Loads
if( I->papi_event_set == 4 )
{
*num_papi_events = 4;
events = (int *) malloc( *num_papi_events * sizeof(int));
int EventCode;
char * event1 = "MEM_LOAD_UOPS_RETIRED";
char * event2 = "MEM_LOAD_UOPS_RETIRED:L1_HIT";
char * event3 = "MEM_LOAD_UOPS_RETIRED:L2_HIT";
char * event4 = "MEM_LOAD_UOPS_RETIRED:L3_HIT";
PAPI_event_name_to_code( event1, &EventCode );
events[0] = EventCode;
PAPI_event_name_to_code( event2, &EventCode );
events[1] = EventCode;
PAPI_event_name_to_code( event3, &EventCode );
events[2] = EventCode;
PAPI_event_name_to_code( event4, &EventCode );
events[3] = EventCode;
}
// LLC Miss Rate
if( I->papi_event_set == 5 )
{
*num_papi_events = 2;
events = (int *) malloc( *num_papi_events * sizeof(int));
events[0] = PAPI_L3_TCM;
events[1] = PAPI_L3_TCA;
}
// Branch MisPrediction
if( I->papi_event_set == 6 )
{
*num_papi_events = 3;
events = (int *) malloc( *num_papi_events * sizeof(int));
events[0] = PAPI_BR_MSP;
events[1] = PAPI_BR_CN;
events[2] = PAPI_BR_PRC;
}
// TLB Misses
if( I->papi_event_set == 7 )
{
*num_papi_events = 4;
events = (int *) malloc( *num_papi_events * sizeof(int));
int EventCode;
char * event1 = "perf::DTLB-LOADS";
char * event2 = "perf::DTLB-LOAD-MISSES";
char * event3 = "perf::DTLB-STORES";
char * event4 = "perf::DTLB-STORE-MISSES";
PAPI_event_name_to_code( event1, &EventCode );
events[0] = EventCode;
PAPI_event_name_to_code( event2, &EventCode );
events[1] = EventCode;
PAPI_event_name_to_code( event3, &EventCode );
events[2] = EventCode;
PAPI_event_name_to_code( event4, &EventCode );
events[3] = EventCode;
}
/////////////////////////////////////////////////////////////////////////
// PAPI EVENT SELECTION
/////////////////////////////////////////////////////////////////////////
// User can comment/uncomment blocks as they see fit within this seciton
// Some Standard Events
//int events[] = {PAPI_TOT_INS,PAPI_LD_INS,PAPI_FP_INS};
// Bandwidth Used
// ((PAPI_Lx_TCM * Lx_linesize) / PAPI_TOT_CYC) * Clock(MHz)
//int events[] = {PAPI_L3_TCM, PAPI_TOT_CYC};
// L3 Total Cache Miss Ratio
// PAPI_L3_TCM / PAPI_L3_TCA
// (On Xeon dual octo - 65%, not dependent on # of threads)
//int events[] = {PAPI_L3_TCM, PAPI_L3_TCA};
// % Cycles with no instruction use
// PAPI_STL_ICY / PAPI_TOT_CYC
//int events[] = { PAPI_STL_ICY, PAPI_TOT_CYC };
// % Branch instructions Mispredicted
// PAPI_BR_MSP / PAPI_BR_CN
//int events[] = { PAPI_BR_MSP, PAPI_BR_CN, PAPI_BR_PRC };
// TLB Misses
//int events[] = { PAPI_TLB_DM };
// MFlops
// (PAPI_FP_INS/PAPI_TOT_CYC) * Clock(MHz)
//int events[] = { PAPI_FP_INS, PAPI_TOT_CYC };
// MFlops (Alternate?)
// (PAPI_FP_INS/PAPI_TOT_CYC) * Clock(MHz)
//int events[] = { PAPI_DP_OPS, PAPI_TOT_CYC };
// TLB misses (Using native counters)
/*
int events[2];
int EventCode;
char * event1 = "perf::DTLB-LOADS";
char * event2 = "perf::DTLB-LOAD-MISSES";
PAPI_event_name_to_code( event1, &EventCode );
events[0] = EventCode;
PAPI_event_name_to_code( event2, &EventCode );
events[1] = EventCode;
*/
/*
// Stalled Cycles, front v back (Using native counters)
int events[3];
int EventCode;
char * event1 = "perf::STALLED-CYCLES-FRONTEND";
char * event2 = "perf::STALLED-CYCLES-BACKEND";
char * event3 = "perf::PERF_COUNT_HW_CPU_CYCLES";
PAPI_event_name_to_code( event1, &EventCode );
events[0] = EventCode;
PAPI_event_name_to_code( event2, &EventCode );
events[1] = EventCode;
PAPI_event_name_to_code( event3, &EventCode );
events[2] = EventCode;
*/
/*
// LLC Cache Misses (Using native counters)
int events[2];
int EventCode;
char * event1 = "ix86arch::LLC_REFERENCES";
char * event2 = "ix86arch::LLC_MISSES";
PAPI_event_name_to_code( event1, &EventCode );
events[0] = EventCode;
PAPI_event_name_to_code( event2, &EventCode );
events[1] = EventCode;
*/
/*
// Node Prefetch Misses (Using native counters)
int events[1];
int EventCode;
//char * event1 = "perf::NODE-PREFETCHES";
//char * event2 = "perf::NODE-PREFETCH-MISSES";
char * event1 = "perf::NODE-PREFETCHES";
char * event2 = "perf::NODE-LOAD-MISSES:COUNT";
//PAPI_event_name_to_code( event1, &EventCode );
//events[0] = EventCode;
PAPI_event_name_to_code( event2, &EventCode );
events[0] = EventCode;
*/
/*
// CPU Stalls Due to lack of Load Buffers (Using native counters)
int events[2];
int EventCode;
char * event1 = "RESOURCE_STALLS:LB";
char * event2 = "perf::PERF_COUNT_HW_CPU_CYCLES";
PAPI_event_name_to_code( event1, &EventCode );
events[0] = EventCode;
PAPI_event_name_to_code( event2, &EventCode );
events[1] = EventCode;
*/
/*
// CPU Stalls Due to ANY Resource (Using native counters)
int events[2];
int EventCode;
char * event1 = "RESOURCE_STALLS:ANY";
char * event2 = "PAPI_TOT_CYC";
PAPI_event_name_to_code( event1, &EventCode );
events[0] = EventCode;
PAPI_event_name_to_code( event2, &EventCode );
events[1] = EventCode;
*/
/*
// CPU Stalls at Reservation Station (Using native counters)
int events[2];
int EventCode;
char * event1 = "RESOURCE_STALLS:RS";
char * event2 = "perf::PERF_COUNT_HW_CPU_CYCLES";
PAPI_event_name_to_code( event1, &EventCode );
events[0] = EventCode;
PAPI_event_name_to_code( event2, &EventCode );
events[1] = EventCode;
*/
/*
// CPU Stall Reason Breakdown (Using native counters)
int events[4];
int EventCode;
// Set 1
char * event1 = "RESOURCE_STALLS:ANY";
char * event2 = "RESOURCE_STALLS:LB";
char * event3 = "RESOURCE_STALLS:RS";
char * event4 = "RESOURCE_STALLS:SB";
// Set 1
// Set 2
char * event1 = "RESOURCE_STALLS:ANY";
char * event2 = "RESOURCE_STALLS:ROB";
char * event3 = "RESOURCE_STALLS:MEM_RS";
char * event4 = "RESOURCE_STALLS2:ALL_FL_EMPTY";
// Set 2
// Set 3
char * event1 = "RESOURCE_STALLS:ANY";
char * event2 = "RESOURCE_STALLS2:ALL_PRF_CONTROL";
char * event3 = "RESOURCE_STALLS2:ANY_PRF_CONTROL"; // duplicate
char * event4 = "RESOURCE_STALLS2:OOO_RSRC";
// Set 3
char * event1 = "RESOURCE_STALLS:ANY";
char * event2 = "RESOURCE_STALLS:SB";
char * event3 = "RESOURCE_STALLS:RS"; // duplicate
char * event4 = "RESOURCE_STALLS2:OOO_RSRC";
// Events that don't need to be counted
// Don't bother measuring these
//char * event1 = "RESOURCE_STALLS:FCSW"; // Always 0, don't measure
//char * event1 = "RESOURCE_STALLS:MXCSR"; // Always 0, don't measure
//char * event3 = "RESOURCE_STALLS2:BOB_FULL"; // Always trivial
//char * event3 = "RESOURCE_STALLS2:ANY_PRF_CONTROL"; // duplicate
PAPI_event_name_to_code( event1, &EventCode );
events[0] = EventCode;
PAPI_event_name_to_code( event2, &EventCode );
events[1] = EventCode;
PAPI_event_name_to_code( event3, &EventCode );
events[2] = EventCode;
PAPI_event_name_to_code( event4, &EventCode );
events[3] = EventCode;
*/
/////////////////////////////////////////////////////////////////////////
// PAPI EVENT LOADING
/////////////////////////////////////////////////////////////////////////
// Users should not need to alter anything within this section
int thread = omp_get_thread_num();
if ( (stat= PAPI_create_eventset(eventset)) != PAPI_OK)
{
PAPI_perror("PAPI_create_eventset");
exit(1);
}
for( int i = 0; i < *num_papi_events; i++ )
{
if ((stat=PAPI_add_event(*eventset,events[i])) != PAPI_OK)
{
PAPI_perror("PAPI_add_event");
exit(1);
}
}
if ((stat=PAPI_start(*eventset)) != PAPI_OK)
{
PAPI_perror("PAPI_start");
exit(1);
}
}
/*
void counter_init( int *eventset, int *num_papi_events )
{
char error_str[PAPI_MAX_STR_LEN];
// int events[] = {PAPI_TOT_INS,PAPI_BR_INS,PAPI_SR_INS};
int events[] = {PAPI_TOT_INS,PAPI_LD_INS,PAPI_FP_INS};
int events[] = {ix86arch::LLC_REFERENCES,
int stat;
int thread = omp_get_thread_num();
if( thread == 0 )
printf("Initializing PAPI counters...\n");
*num_papi_events = sizeof(events) / sizeof(int);
if ((stat = PAPI_thread_init((long unsigned int (*)(void)) omp_get_thread_num)) != PAPI_OK){
PAPI_perror("PAPI_thread_init");
exit(1);
}
if ( (stat= PAPI_create_eventset(eventset)) != PAPI_OK){
PAPI_perror("PAPI_create_eventset");
exit(1);
}
for( int i = 0; i < *num_papi_events; i++ ){
if ((stat=PAPI_add_event(*eventset,events[i])) != PAPI_OK){
PAPI_perror("PAPI_add_event");
exit(1);
}
}
if ((stat=PAPI_start(*eventset)) != PAPI_OK){
PAPI_perror("PAPI_start");
exit(1);
}
}
*/
// Stops the papi counters and prints results
void counter_stop( int * eventset, int num_papi_events, Input * I )
{
int * events = malloc(num_papi_events * sizeof(int));
int n = num_papi_events;
PAPI_list_events( *eventset, events, &n );
PAPI_event_info_t info;
long_long * values = malloc( num_papi_events * sizeof(long_long));
PAPI_stop(*eventset, values);
int thread = omp_get_thread_num();
int nthreads = omp_get_num_threads();
static long LLC_cache_miss = 0;
static long total_cycles = 0;
static long FLOPS = 0;
static long stall_any = 0;
static long stall_SB = 0;
static long stall_RS = 0;
static long stall_OO = 0;
static long tlb_load = 0;
static long tlb_load_m = 0;
static long tlb_store = 0;
static long tlb_store_m = 0;
#pragma omp master
{
I->vals_accum = malloc( num_papi_events * sizeof(long long));
for(int i=0; i < num_papi_events ; i ++)
I->vals_accum[i] = 0;
}
#pragma omp barrier
#pragma omp critical (papi)
{
printf("Thread %d\n", thread);
for( int i = 0; i < num_papi_events; i++ )
{
I->vals_accum[i] += values[i];
PAPI_get_event_info(events[i], &info);
printf("%-15lld\t%s\t%s\n", values[i],info.symbol,info.long_descr);
if( strcmp(info.symbol, "PAPI_L3_TCM") == 0 )
LLC_cache_miss += values[i];
if( strcmp(info.symbol, "PAPI_TOT_CYC") == 0 )
total_cycles += values[i];
if( strcmp(info.symbol, "PAPI_SP_OPS") == 0 )
FLOPS += values[i];
if( strcmp(info.symbol, "RESOURCE_STALLS:ANY") == 0 )
stall_any += values[i];
if( strcmp(info.symbol, "RESOURCE_STALLS:SB") == 0 )
stall_SB += values[i];
if( strcmp(info.symbol, "RESOURCE_STALLS:RS") == 0 )
stall_RS += values[i];
if( strcmp(info.symbol, "RESOURCE_STALLS2:OOO_RSRC") == 0 )
stall_OO += values[i];
if( strcmp(info.symbol, "perf::DTLB-LOADS") == 0 )
tlb_load += values[i];
if( strcmp(info.symbol, "perf::DTLB-LOAD-MISSES") == 0 )
tlb_load_m += values[i];
if( strcmp(info.symbol, "perf::DTLB-STORES") == 0 )
tlb_store += values[i];
if( strcmp(info.symbol, "perf::DTLB-STORE-MISSES") == 0 )
tlb_store_m += values[i];
}
free(values);
}
{
#pragma omp barrier
}
#pragma omp master
{
if( omp_get_num_threads() > 1){
printf("Thread Totals:\n");
for( int i = 0; i < num_papi_events; i++ )
{
PAPI_get_event_info(events[i], &info);
printf("%-15lld\t%s\t%s\n", I->vals_accum[i],info.symbol,info.long_descr);
}
}
free( I->vals_accum );
border_print();
center_print("PERFORMANCE SUMMARY", 79);
border_print();
long cycles = (long) (total_cycles / (double) nthreads);
double bw = LLC_cache_miss*64./cycles*2.8e9/1024./1024./1024.;
if( I->papi_event_set == 0 )
printf("GFLOPs: %.3lf\n", FLOPS / (double) cycles * 2.8 );
if( I->papi_event_set == 1 )
printf("Bandwidth: %.3lf (GB/s)\n", bw);
if( I->papi_event_set == 2 )
{
printf("%-30s %.2lf%%\n", "Store Buffer Full:",
stall_SB / (double) stall_any * 100.);
printf("%-30s %.2lf%%\n", "Reservation Station Full:",
stall_RS / (double) stall_any * 100.);
printf("%-30s %.2lf%%\n", "OO Pipeline Full:",
stall_OO / (double) stall_any * 100.);
}
if( I->papi_event_set == 3 )
printf("CPU Stalled Cycles: %.2lf%%\n",
stall_any / (double) total_cycles * 100.);
if( I->papi_event_set == 7 )
{
printf("%-30s %.2lf%%\n", "Data TLB Load Miss Rate: ",
tlb_load_m / (double) tlb_load * 100 );
printf("%-30s %.2lf%%\n", "Data TLB Store Miss Rate: ",
tlb_store_m / (double) tlb_store * 100 );
}
border_print();
}
free(events);
}
#endif
|
convolution_1x1_pack4.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_pack4_sse(const Mat& kernel, Mat& kernel_pack4, int inch, int outch)
{
// interleave
// src = inch-outch
// dst = 4b-4a-inch/4a-outch/4b
kernel_pack4.create(1, inch / 4, outch / 4, (size_t)4u * 16, 16);
int q = 0;
for (; q + 3 < outch; q += 4)
{
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;
float* g0 = kernel_pack4.channel(q / 4);
for (int p = 0; p + 3 < inch; p += 4)
{
g0[0] = k0[0];
g0[1] = k1[0];
g0[2] = k2[0];
g0[3] = k3[0];
g0[4] = k0[1];
g0[5] = k1[1];
g0[6] = k2[1];
g0[7] = k3[1];
g0[8] = k0[2];
g0[9] = k1[2];
g0[10] = k2[2];
g0[11] = k3[2];
g0[12] = k0[3];
g0[13] = k1[3];
g0[14] = k2[3];
g0[15] = k3[3];
k0 += 4;
k1 += 4;
k2 += 4;
k3 += 4;
g0 += 16;
}
}
}
static void conv1x1s1_sgemm_pack4_sse(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
Mat tmp(4, inch, size / 4 + (size % 4) / 2 + size % 2, elemsize, elempack, opt.workspace_allocator);
{
int nn_size;
int remain_size_start;
remain_size_start = 0;
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;
float* tmpptr = tmp.channel(i / 4);
for (int q = 0; q < inch; q++)
{
__m128 _r0 = _mm_loadu_ps(img0);
__m128 _r1 = _mm_loadu_ps(img0 + 4);
__m128 _r2 = _mm_loadu_ps(img0 + 8);
__m128 _r3 = _mm_loadu_ps(img0 + 12);
_mm_storeu_ps(tmpptr, _r0);
_mm_storeu_ps(tmpptr + 4, _r1);
_mm_storeu_ps(tmpptr + 8, _r2);
_mm_storeu_ps(tmpptr + 12, _r3);
tmpptr += 16;
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;
float* tmpptr = tmp.channel(i / 4 + (i % 4) / 2);
for (int q = 0; q < inch; q++)
{
__m128 _r0 = _mm_loadu_ps(img0);
__m128 _r1 = _mm_loadu_ps(img0 + 4);
_mm_storeu_ps(tmpptr, _r0);
_mm_storeu_ps(tmpptr + 4, _r1);
tmpptr += 8;
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;
float* tmpptr = tmp.channel(i / 4 + (i % 4) / 2 + i % 2);
for (int q = 0; q < inch; q++)
{
__m128 _r0 = _mm_loadu_ps(img0);
_mm_storeu_ps(tmpptr, _r0);
tmpptr += 4;
img0 += bottom_blob.cstep * 4;
}
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; 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;
for (; i + 3 < size; i += 4)
{
float* tmpptr = tmp.channel(i / 4);
const float* kptr0 = (const float*)kernel.channel(p);
__m128 _sum0 = _mm_loadu_ps(biasptr);
__m128 _sum1 = _mm_loadu_ps(biasptr);
__m128 _sum2 = _mm_loadu_ps(biasptr);
__m128 _sum3 = _mm_loadu_ps(biasptr);
for (int q = 0; q < inch; q++)
{
__m128 _val00 = _mm_load1_ps(tmpptr);
__m128 _val01 = _mm_load1_ps(tmpptr + 1);
__m128 _val02 = _mm_load1_ps(tmpptr + 2);
__m128 _val03 = _mm_load1_ps(tmpptr + 3);
__m128 _val10 = _mm_load1_ps(tmpptr + 4);
__m128 _val11 = _mm_load1_ps(tmpptr + 5);
__m128 _val12 = _mm_load1_ps(tmpptr + 6);
__m128 _val13 = _mm_load1_ps(tmpptr + 7);
__m128 _val20 = _mm_load1_ps(tmpptr + 8);
__m128 _val21 = _mm_load1_ps(tmpptr + 9);
__m128 _val22 = _mm_load1_ps(tmpptr + 10);
__m128 _val23 = _mm_load1_ps(tmpptr + 11);
__m128 _val30 = _mm_load1_ps(tmpptr + 12);
__m128 _val31 = _mm_load1_ps(tmpptr + 13);
__m128 _val32 = _mm_load1_ps(tmpptr + 14);
__m128 _val33 = _mm_load1_ps(tmpptr + 15);
__m128 _w0 = _mm_load_ps(kptr0);
__m128 _w1 = _mm_load_ps(kptr0 + 4);
__m128 _w2 = _mm_load_ps(kptr0 + 8);
__m128 _w3 = _mm_load_ps(kptr0 + 12);
_sum0 = _mm_comp_fmadd_ps(_w0, _val00, _sum0);
_sum0 = _mm_comp_fmadd_ps(_w1, _val01, _sum0);
_sum0 = _mm_comp_fmadd_ps(_w2, _val02, _sum0);
_sum0 = _mm_comp_fmadd_ps(_w3, _val03, _sum0);
_sum1 = _mm_comp_fmadd_ps(_w0, _val10, _sum1);
_sum1 = _mm_comp_fmadd_ps(_w1, _val11, _sum1);
_sum1 = _mm_comp_fmadd_ps(_w2, _val12, _sum1);
_sum1 = _mm_comp_fmadd_ps(_w3, _val13, _sum1);
_sum2 = _mm_comp_fmadd_ps(_w0, _val20, _sum2);
_sum2 = _mm_comp_fmadd_ps(_w1, _val21, _sum2);
_sum2 = _mm_comp_fmadd_ps(_w2, _val22, _sum2);
_sum2 = _mm_comp_fmadd_ps(_w3, _val23, _sum2);
_sum3 = _mm_comp_fmadd_ps(_w0, _val30, _sum3);
_sum3 = _mm_comp_fmadd_ps(_w1, _val31, _sum3);
_sum3 = _mm_comp_fmadd_ps(_w2, _val32, _sum3);
_sum3 = _mm_comp_fmadd_ps(_w3, _val33, _sum3);
tmpptr += 16;
kptr0 += 16;
}
_mm_store_ps(outptr0, _sum0);
_mm_store_ps(outptr0 + 4, _sum1);
_mm_store_ps(outptr0 + 8, _sum2);
_mm_store_ps(outptr0 + 12, _sum3);
outptr0 += 16;
}
for (; i + 1 < size; i += 2)
{
float* tmpptr = tmp.channel(i / 4 + (i % 4) / 2);
const float* kptr0 = (const float*)kernel.channel(p);
__m128 _sum0 = _mm_loadu_ps(biasptr);
__m128 _sum1 = _mm_loadu_ps(biasptr);
for (int q = 0; q < inch; q++)
{
__m128 _val00 = _mm_load1_ps(tmpptr);
__m128 _val01 = _mm_load1_ps(tmpptr + 1);
__m128 _val02 = _mm_load1_ps(tmpptr + 2);
__m128 _val03 = _mm_load1_ps(tmpptr + 3);
__m128 _val10 = _mm_load1_ps(tmpptr + 4);
__m128 _val11 = _mm_load1_ps(tmpptr + 5);
__m128 _val12 = _mm_load1_ps(tmpptr + 6);
__m128 _val13 = _mm_load1_ps(tmpptr + 7);
__m128 _w0 = _mm_load_ps(kptr0);
__m128 _w1 = _mm_load_ps(kptr0 + 4);
__m128 _w2 = _mm_load_ps(kptr0 + 8);
__m128 _w3 = _mm_load_ps(kptr0 + 12);
_sum0 = _mm_comp_fmadd_ps(_w0, _val00, _sum0);
_sum0 = _mm_comp_fmadd_ps(_w1, _val01, _sum0);
_sum0 = _mm_comp_fmadd_ps(_w2, _val02, _sum0);
_sum0 = _mm_comp_fmadd_ps(_w3, _val03, _sum0);
_sum1 = _mm_comp_fmadd_ps(_w0, _val10, _sum1);
_sum1 = _mm_comp_fmadd_ps(_w1, _val11, _sum1);
_sum1 = _mm_comp_fmadd_ps(_w2, _val12, _sum1);
_sum1 = _mm_comp_fmadd_ps(_w3, _val13, _sum1);
tmpptr += 8;
kptr0 += 16;
}
_mm_store_ps(outptr0, _sum0);
_mm_store_ps(outptr0 + 4, _sum1);
outptr0 += 8;
}
for (; i < size; i++)
{
float* tmpptr = tmp.channel(i / 4 + (i % 4) / 2 + i % 2);
const float* kptr0 = (const float*)kernel.channel(p);
__m128 _sum = _mm_loadu_ps(biasptr);
for (int q = 0; q < inch; q++)
{
__m128 _val0 = _mm_load1_ps(tmpptr);
__m128 _val1 = _mm_load1_ps(tmpptr + 1);
__m128 _val2 = _mm_load1_ps(tmpptr + 2);
__m128 _val3 = _mm_load1_ps(tmpptr + 3);
__m128 _w0 = _mm_load_ps(kptr0);
__m128 _w1 = _mm_load_ps(kptr0 + 4);
__m128 _w2 = _mm_load_ps(kptr0 + 8);
__m128 _w3 = _mm_load_ps(kptr0 + 12);
_sum = _mm_comp_fmadd_ps(_w0, _val0, _sum);
_sum = _mm_comp_fmadd_ps(_w1, _val1, _sum);
_sum = _mm_comp_fmadd_ps(_w2, _val2, _sum);
_sum = _mm_comp_fmadd_ps(_w3, _val3, _sum);
tmpptr += 4;
kptr0 += 16;
}
_mm_store_ps(outptr0, _sum);
outptr0 += 4;
}
}
// // 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;
// }
// }
}
static void conv1x1s2_pack4_sse(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 float* r0 = bottom_blob.channel(p);
float* outptr = bottom_blob_shrinked.channel(p);
for (int i = 0; i < outh; i++)
{
for (int j = 0; j < outw; j++)
{
__m128 _v = _mm_load_ps(r0);
_mm_store_ps(outptr, _v);
r0 += 8;
outptr += 4;
}
r0 += tailstep;
}
}
conv1x1s1_sgemm_pack4_sse(bottom_blob_shrinked, top_blob, kernel, _bias, opt);
}
|
fci_contract.c | /*
* Full CI
*/
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <math.h>
#include <assert.h>
//#include <omp.h>
#include "config.h"
#include "vhf/fblas.h"
#include "np_helper/np_helper.h"
#include "fci.h"
// for (16e,16o) ~ 11 MB buffer = 120 * 12870 * 8
#define STRB_BLKSIZE 112
/*
* CPU timing of single thread can be estimated:
* na*nb*nnorb*8(bytes)*5 / (mem_freq*64 (*2 if dual-channel mem))
* + na*nb*nnorb**2 (*2 for spin1, *1 for spin0)
* / (CPU_freq (*4 for SSE3 blas, or *6-8 for AVX blas))
* where the 5 times memory accesses are 3 in prog_a_t1, prog0_b_t1,
* spread_b_t1 and 2 in spread_a_t1
*
* multi threads
* na*nb*nnorb*8(bytes)*2 / (mem_freq*64 (*2 if dual-channel mem)) due to single thread
* + na*nb*nnorb*8(bytes)*3 / max_mem_bandwidth due to N-thread
* + na*nb*nnorb**2 (*2 for spin1, *1 for spin0)
* / (CPU_freq (*4 for SSE3 blas, or *6-8 for AVX blas)) / num_threads
*/
/*
***********************************************************
*
* Need the permutation symmetry
* h2e[i,j,k,l] = h2e[j,i,k,l] = h2e[i,j,l,k] = h2e[j,i,l,k]
*
***********************************************************
*/
/*
* optimize for OpenMP, to reduce memory/CPU data transfer
* add software prefetch, it's especially important for OpenMP
*/
/*
* For given stra_id, spread alpah-strings (which can propagate to stra_id)
* into t1[:nstrb,nnorb]
* str1-of-alpha -> create/annihilate -> str0-of-alpha
* ci0[:nstra,:nstrb] is contiguous in beta-strings
* bcount control the number of beta strings to be calculated.
* for spin=0 system, only lower triangle of the intermediate ci vector
* needs to be calculated
*/
void FCIprog_a_t1(double *ci0, double *t1,
int bcount, int stra_id, int strb_id,
int norb, int nstrb, int nlinka, _LinkTrilT *clink_indexa)
{
ci0 += strb_id;
int j, k, ia, sign;
size_t str1;
const _LinkTrilT *tab = clink_indexa + stra_id * nlinka;
double *pt1, *pci;
for (j = 0; j < nlinka; j++) {
ia = EXTRACT_IA (tab[j]);
str1 = EXTRACT_ADDR(tab[j]);
sign = EXTRACT_SIGN(tab[j]);
pt1 = t1 + ia*bcount;
pci = ci0 + str1*nstrb;
if (sign == 0) {
break;
} else if (sign > 0) {
for (k = 0; k < bcount; k++) {
pt1[k] += pci[k];
}
} else if (sign < 0) {
for (k = 0; k < bcount; k++) {
pt1[k] -= pci[k];
}
}
}
}
/*
* For given stra_id, spread all beta-strings into t1[:nstrb,nnorb]
* all str0-of-beta -> create/annihilate -> str1-of-beta
* ci0[:nstra,:nstrb] is contiguous in beta-strings
* bcount control the number of beta strings to be calculated.
* for spin=0 system, only lower triangle of the intermediate ci vector
* needs to be calculated
*/
void FCIprog_b_t1(double *ci0, double *t1,
int bcount, int stra_id, int strb_id,
int norb, int nstrb, int nlinkb, _LinkTrilT *clink_indexb)
{
int j, ia, str0, str1, sign;
const _LinkTrilT *tab = clink_indexb + strb_id * nlinkb;
double *pci = ci0 + stra_id*(size_t)nstrb;
for (str0 = 0; str0 < bcount; str0++) {
for (j = 0; j < nlinkb; j++) {
ia = EXTRACT_IA (tab[j]);
str1 = EXTRACT_ADDR(tab[j]);
sign = EXTRACT_SIGN(tab[j]);
if (sign == 0) {
break;
} else {
t1[ia*bcount+str0] += sign * pci[str1];
}
}
tab += nlinkb;
}
}
/*
* spread t1 into ci1
*/
void FCIspread_a_t1(double *ci1, double *t1,
int bcount, int stra_id, int strb_id,
int norb, int nstrb, int nlinka, _LinkTrilT *clink_indexa)
{
ci1 += strb_id;
int j, k, ia, sign;
size_t str1;
const _LinkTrilT *tab = clink_indexa + stra_id * nlinka;
double *cp0, *cp1;
for (j = 0; j < nlinka; j++) {
ia = EXTRACT_IA (tab[j]);
str1 = EXTRACT_ADDR(tab[j]);
sign = EXTRACT_SIGN(tab[j]);
cp0 = t1 + ia*bcount;
cp1 = ci1 + str1*nstrb;
if (sign == 0) {
break;
} else if (sign > 0) {
for (k = 0; k < bcount; k++) {
cp1[k] += cp0[k];
}
} else {
for (k = 0; k < bcount; k++) {
cp1[k] -= cp0[k];
}
}
}
}
void FCIspread_b_t1(double *ci1, double *t1,
int bcount, int stra_id, int strb_id,
int norb, int nstrb, int nlinkb, _LinkTrilT *clink_indexb)
{
int j, ia, str0, str1, sign;
const _LinkTrilT *tab = clink_indexb + strb_id * nlinkb;
double *pci = ci1 + stra_id * (size_t)nstrb;
for (str0 = 0; str0 < bcount; str0++) {
for (j = 0; j < nlinkb; j++) {
ia = EXTRACT_IA (tab[j]);
str1 = EXTRACT_ADDR(tab[j]);
sign = EXTRACT_SIGN(tab[j]);
if (sign == 0) {
break;
} else {
pci[str1] += sign * t1[ia*bcount+str0];
}
}
tab += nlinkb;
}
}
/*
* f1e_tril is the 1e hamiltonian for spin alpha
*/
void FCIcontract_a_1e(double *f1e_tril, double *ci0, double *ci1,
int norb, int nstra, int nstrb, int nlinka, int nlinkb,
int *link_indexa, int *link_indexb)
{
int j, k, ia, sign;
size_t str0, str1;
double *pci0, *pci1;
double tmp;
_LinkTrilT *tab;
_LinkTrilT *clink = malloc(sizeof(_LinkTrilT) * nlinka * nstra);
FCIcompress_link_tril(clink, link_indexa, nstra, nlinka);
for (str0 = 0; str0 < nstra; str0++) {
tab = clink + str0 * nlinka;
for (j = 0; j < nlinka; j++) {
ia = EXTRACT_IA (tab[j]);
str1 = EXTRACT_ADDR(tab[j]);
sign = EXTRACT_SIGN(tab[j]);
pci0 = ci0 + str0 * nstrb;
pci1 = ci1 + str1 * nstrb;
tmp = sign * f1e_tril[ia];
for (k = 0; k < nstrb; k++) {
pci1[k] += tmp * pci0[k];
}
}
}
free(clink);
}
/*
* f1e_tril is the 1e hamiltonian for spin beta
*/
void FCIcontract_b_1e(double *f1e_tril, double *ci0, double *ci1,
int norb, int nstra, int nstrb, int nlinka, int nlinkb,
int *link_indexa, int *link_indexb)
{
int j, k, ia, sign;
size_t str0, str1;
double *pci1;
double tmp;
_LinkTrilT *tab;
_LinkTrilT *clink = malloc(sizeof(_LinkTrilT) * nlinkb * nstrb);
FCIcompress_link_tril(clink, link_indexb, nstrb, nlinkb);
for (str0 = 0; str0 < nstra; str0++) {
pci1 = ci1 + str0 * nstrb;
for (k = 0; k < nstrb; k++) {
tab = clink + k * nlinkb;
tmp = ci0[str0*nstrb+k];
for (j = 0; j < nlinkb; j++) {
ia = EXTRACT_IA (tab[j]);
str1 = EXTRACT_ADDR(tab[j]);
sign = EXTRACT_SIGN(tab[j]);
pci1[str1] += sign * tmp * f1e_tril[ia];
}
}
}
free(clink);
}
void FCIcontract_1e_spin0(double *f1e_tril, double *ci0, double *ci1,
int norb, int na, int nlink, int *link_index)
{
memset(ci1, 0, sizeof(double)*na*na);
FCIcontract_a_1e(f1e_tril, ci0, ci1, norb, na, na, nlink, nlink,
link_index, link_index);
}
/*
* spread t1 into ci1buf
*/
static void spread_bufa_t1(double *ci1, double *t1, int nrow_t1,
int bcount, int stra_id, int strb_id,
int norb, int nstrb, int nlinka, _LinkTrilT *clink_indexa)
{
int j, k, ia, sign;
size_t str1;
const _LinkTrilT *tab = clink_indexa + stra_id * nlinka;
double *cp0, *cp1;
for (j = 0; j < nlinka; j++) {
ia = EXTRACT_IA (tab[j]);
str1 = EXTRACT_ADDR(tab[j]);
sign = EXTRACT_SIGN(tab[j]);
cp0 = t1 + ia*nrow_t1;
cp1 = ci1 + str1*nstrb;
if (sign == 0) {
break;
} else if (sign > 0) {
for (k = 0; k < bcount; k++) {
cp1[k] += cp0[k];
}
} else {
for (k = 0; k < bcount; k++) {
cp1[k] -= cp0[k];
}
}
}
}
/*
* bcount_for_spread_a is different for spin1 and spin0
*/
static void ctr_rhf2e_kern(double *eri, double *ci0, double *ci1,
double *ci1buf, double *t1buf,
int bcount_for_spread_a, int ncol_ci1buf,
int bcount, int stra_id, int strb_id,
int norb, int na, int nb, int nlinka, int nlinkb,
_LinkTrilT *clink_indexa, _LinkTrilT *clink_indexb)
{
const char TRANS_N = 'N';
const double D0 = 0;
const double D1 = 1;
const int nnorb = norb * (norb+1)/2;
double *t1 = t1buf;
double *vt1 = t1buf + nnorb*bcount;
memset(t1, 0, sizeof(double)*nnorb*bcount);
FCIprog_a_t1(ci0, t1, bcount, stra_id, strb_id,
norb, nb, nlinka, clink_indexa);
FCIprog_b_t1(ci0, t1, bcount, stra_id, strb_id,
norb, nb, nlinkb, clink_indexb);
dgemm_(&TRANS_N, &TRANS_N, &bcount, &nnorb, &nnorb,
&D1, t1, &bcount, eri, &nnorb, &D0, vt1, &bcount);
FCIspread_b_t1(ci1, vt1, bcount, stra_id, strb_id,
norb, nb, nlinkb, clink_indexb);
//FCIspread_a_t1(ci1buf, vt1, bcount_for_spread_a, stra_id, 0,
// norb, ncol_ci1buf, nlinka, clink_indexa);
spread_bufa_t1(ci1buf, vt1, bcount, bcount_for_spread_a, stra_id, 0,
norb, ncol_ci1buf, nlinka, clink_indexa);
}
void FCIaxpy2d(double *out, double *in, size_t count, size_t no, size_t ni)
{
int i, j;
for (i = 0; i < count; i++) {
for (j = 0; j < ni; j++) {
out[i*no+j] += in[i*ni+j];
}
}
}
/*
* nlink = nocc*nvir, num. all possible strings that a string can link to
* link_index[str0] == linking map between str0 and other strings
* link_index[str0][ith-linking-string] ==
* [tril(creation_op,annihilation_op),0,linking-string-id,sign]
* FCIcontract_2e_spin0 only compute half of the contraction, due to the
* symmetry between alpha and beta spin. The right contracted ci vector
* is (ci1+ci1.T)
*/
void FCIcontract_2e_spin0(double *eri, double *ci0, double *ci1,
int norb, int na, int nlink, int *link_index)
{
_LinkTrilT *clink = malloc(sizeof(_LinkTrilT) * nlink * na);
FCIcompress_link_tril(clink, link_index, na, nlink);
memset(ci1, 0, sizeof(double)*na*na);
double *ci1bufs[MAX_THREADS];
#pragma omp parallel default(none) \
shared(eri, ci0, ci1, norb, na, nlink, clink, ci1bufs)
{
int strk, ib;
size_t blen;
double *t1buf = malloc(sizeof(double) * STRB_BLKSIZE*norb*(norb+1));
double *ci1buf = malloc(sizeof(double) * na*STRB_BLKSIZE);
ci1bufs[omp_get_thread_num()] = ci1buf;
for (ib = 0; ib < na; ib += STRB_BLKSIZE) {
blen = MIN(STRB_BLKSIZE, na-ib);
memset(ci1buf, 0, sizeof(double) * na*blen);
#pragma omp for schedule(static, 112)
/* strk starts from MAX(strk0, ib), because [0:ib,0:ib] have been evaluated */
for (strk = ib; strk < na; strk++) {
ctr_rhf2e_kern(eri, ci0, ci1, ci1buf, t1buf,
MIN(STRB_BLKSIZE, strk-ib), blen,
MIN(STRB_BLKSIZE, strk+1-ib),
strk, ib, norb, na, na, nlink, nlink,
clink, clink);
}
NPomp_dsum_reduce_inplace(ci1bufs, blen*na);
#pragma omp master
FCIaxpy2d(ci1+ib, ci1buf, na, na, blen);
}
free(ci1buf);
free(t1buf);
}
free(clink);
}
void FCIcontract_2e_spin1(double *eri, double *ci0, double *ci1,
int norb, int na, int nb, int nlinka, int nlinkb,
int *link_indexa, int *link_indexb)
{
_LinkTrilT *clinka = malloc(sizeof(_LinkTrilT) * nlinka * na);
_LinkTrilT *clinkb = malloc(sizeof(_LinkTrilT) * nlinkb * nb);
FCIcompress_link_tril(clinka, link_indexa, na, nlinka);
FCIcompress_link_tril(clinkb, link_indexb, nb, nlinkb);
memset(ci1, 0, sizeof(double)*na*nb);
double *ci1bufs[MAX_THREADS];
#pragma omp parallel default(none) \
shared(eri, ci0, ci1, norb, na, nb, nlinka, nlinkb, \
clinka, clinkb, ci1bufs)
{
int strk, ib;
size_t blen;
double *t1buf = malloc(sizeof(double) * STRB_BLKSIZE*norb*(norb+1));
double *ci1buf = malloc(sizeof(double) * na*STRB_BLKSIZE);
ci1bufs[omp_get_thread_num()] = ci1buf;
for (ib = 0; ib < nb; ib += STRB_BLKSIZE) {
blen = MIN(STRB_BLKSIZE, nb-ib);
memset(ci1buf, 0, sizeof(double) * na*blen);
#pragma omp for schedule(static)
for (strk = 0; strk < na; strk++) {
ctr_rhf2e_kern(eri, ci0, ci1, ci1buf, t1buf,
blen, blen, blen, strk, ib,
norb, na, nb, nlinka, nlinkb,
clinka, clinkb);
}
NPomp_dsum_reduce_inplace(ci1bufs, blen*na);
#pragma omp master
FCIaxpy2d(ci1+ib, ci1buf, na, nb, blen);
}
free(ci1buf);
free(t1buf);
}
free(clinka);
free(clinkb);
}
/*
* eri_ab is mixed integrals (alpha,alpha|beta,beta), |beta,beta) in small strides
*/
static void ctr_uhf2e_kern(double *eri_aa, double *eri_ab, double *eri_bb,
double *ci0, double *ci1, double *ci1buf, double *t1buf,
int bcount, int stra_id, int strb_id,
int norb, int na, int nb, int nlinka, int nlinkb,
_LinkTrilT *clink_indexa, _LinkTrilT *clink_indexb)
{
const char TRANS_T = 'T';
const char TRANS_N = 'N';
const double D0 = 0;
const double D1 = 1;
const int nnorb = norb * (norb+1)/2;
double *t1a = t1buf;
double *t1b = t1a + nnorb*bcount;
double *vt1 = t1b + nnorb*bcount;
memset(t1a, 0, sizeof(double)*nnorb*bcount);
memset(t1b, 0, sizeof(double)*nnorb*bcount);
FCIprog_a_t1(ci0, t1a, bcount, stra_id, strb_id,
norb, nb, nlinka, clink_indexa);
FCIprog_b_t1(ci0, t1b, bcount, stra_id, strb_id,
norb, nb, nlinkb, clink_indexb);
dgemm_(&TRANS_N, &TRANS_T, &bcount, &nnorb, &nnorb,
&D1, t1a, &bcount, eri_ab, &nnorb, &D0, vt1, &bcount);
dgemm_(&TRANS_N, &TRANS_N, &bcount, &nnorb, &nnorb,
&D1, t1b, &bcount, eri_bb, &nnorb, &D1, vt1, &bcount);
FCIspread_b_t1(ci1, vt1, bcount, stra_id, strb_id,
norb, nb, nlinkb, clink_indexb);
dgemm_(&TRANS_N, &TRANS_N, &bcount, &nnorb, &nnorb,
&D1, t1a, &bcount, eri_aa, &nnorb, &D0, vt1, &bcount);
dgemm_(&TRANS_N, &TRANS_N, &bcount, &nnorb, &nnorb,
&D1, t1b, &bcount, eri_ab, &nnorb, &D1, vt1, &bcount);
FCIspread_a_t1(ci1buf, vt1, bcount, stra_id, 0,
norb, bcount, nlinka, clink_indexa);
}
void FCIcontract_uhf2e(double *eri_aa, double *eri_ab, double *eri_bb,
double *ci0, double *ci1,
int norb, int na, int nb, int nlinka, int nlinkb,
int *link_indexa, int *link_indexb)
{
_LinkTrilT *clinka = malloc(sizeof(_LinkTrilT) * nlinka * na);
_LinkTrilT *clinkb = malloc(sizeof(_LinkTrilT) * nlinkb * nb);
FCIcompress_link_tril(clinka, link_indexa, na, nlinka);
FCIcompress_link_tril(clinkb, link_indexb, nb, nlinkb);
memset(ci1, 0, sizeof(double)*na*nb);
double *ci1bufs[MAX_THREADS];
#pragma omp parallel default(none) \
shared(eri_aa, eri_ab, eri_bb, ci0, ci1, norb, na, nb, nlinka, nlinkb,\
clinka, clinkb, ci1bufs)
{
int strk, ib;
size_t blen;
double *t1buf = malloc(sizeof(double) * STRB_BLKSIZE*norb*(norb+1)*2);
double *ci1buf = malloc(sizeof(double) * na*STRB_BLKSIZE);
ci1bufs[omp_get_thread_num()] = ci1buf;
for (ib = 0; ib < nb; ib += STRB_BLKSIZE) {
blen = MIN(STRB_BLKSIZE, nb-ib);
memset(ci1buf, 0, sizeof(double) * na*blen);
#pragma omp for schedule(static)
for (strk = 0; strk < na; strk++) {
ctr_uhf2e_kern(eri_aa, eri_ab, eri_bb, ci0, ci1,
ci1buf, t1buf, blen, strk, ib,
norb, na, nb, nlinka, nlinkb,
clinka, clinkb);
}
NPomp_dsum_reduce_inplace(ci1bufs, blen*na);
#pragma omp master
FCIaxpy2d(ci1+ib, ci1buf, na, nb, blen);
}
free(t1buf);
free(ci1buf);
}
free(clinka);
free(clinkb);
}
/*************************************************
* hdiag
*************************************************/
void FCImake_hdiag_uhf(double *hdiag, double *h1e_a, double *h1e_b,
double *jdiag_aa, double *jdiag_ab, double *jdiag_bb,
double *kdiag_aa, double *kdiag_bb,
int norb, int nstra, int nstrb, int nocca, int noccb,
int *occslista, int *occslistb)
{
#pragma omp parallel default(none) \
shared(hdiag, h1e_a, h1e_b, \
jdiag_aa, jdiag_ab, jdiag_bb, kdiag_aa, kdiag_bb, \
norb, nstra, nstrb, nocca, noccb, occslista, occslistb)
{
int j, j0, k0, jk, jk0;
size_t ia, ib;
double e1, e2;
int *paocc, *pbocc;
#pragma omp for schedule(static)
for (ia = 0; ia < nstra; ia++) {
paocc = occslista + ia * nocca;
for (ib = 0; ib < nstrb; ib++) {
e1 = 0;
e2 = 0;
pbocc = occslistb + ib * noccb;
for (j0 = 0; j0 < nocca; j0++) {
j = paocc[j0];
jk0 = j * norb;
e1 += h1e_a[j*norb+j];
for (k0 = 0; k0 < nocca; k0++) { // (alpha|alpha)
jk = jk0 + paocc[k0];
e2 += jdiag_aa[jk] - kdiag_aa[jk];
}
for (k0 = 0; k0 < noccb; k0++) { // (alpha|beta)
jk = jk0 + pbocc[k0];
e2 += jdiag_ab[jk] * 2;
}
}
for (j0 = 0; j0 < noccb; j0++) {
j = pbocc[j0];
jk0 = j * norb;
e1 += h1e_b[j*norb+j];
for (k0 = 0; k0 < noccb; k0++) { // (beta|beta)
jk = jk0 + pbocc[k0];
e2 += jdiag_bb[jk] - kdiag_bb[jk];
}
}
hdiag[ia*nstrb+ib] = e1 + e2 * .5;
}
}
}
}
void FCImake_hdiag(double *hdiag, double *h1e, double *jdiag, double *kdiag,
int norb, int na, int nocc, int *occslst)
{
FCImake_hdiag_uhf(hdiag, h1e, h1e, jdiag, jdiag, jdiag, kdiag, kdiag,
norb, na, na, nocc, nocc, occslst, occslst);
}
static int first1(uint64_t r)
{
#ifdef HAVE_FFS
return ffsll(r) - 1;
#else
int n = 0;
if (r >> (n + 32)) n += 32;
if (r >> (n + 16)) n += 16;
if (r >> (n + 8)) n += 8;
if (r >> (n + 4)) n += 4;
if (r >> (n + 2)) n += 2;
if (r >> (n + 1)) n += 1;
return n;
#endif
}
/*************************************************
* pspace Hamiltonian, ref CPL, 169, 463
*************************************************/
/*
* sub-space Hamiltonian (tril part) of the determinants (stra,strb)
*/
void FCIpspace_h0tril_uhf(double *h0, double *h1e_a, double *h1e_b,
double *g2e_aa, double *g2e_ab, double *g2e_bb,
uint64_t *stra, uint64_t *strb,
int norb, int np)
{
const int d2 = norb * norb;
const int d3 = norb * norb * norb;
#pragma omp parallel default(none) \
shared(h0, h1e_a, h1e_b, g2e_aa, g2e_ab, g2e_bb, \
stra, strb, norb, np)
{
int i, j, k, pi, pj, pk, pl;
int n1da, n1db;
uint64_t da, db, str1;
double tmp;
#pragma omp for schedule(dynamic)
for (i = 0; i < np; i++) {
for (j = 0; j < i; j++) {
da = stra[i] ^ stra[j];
db = strb[i] ^ strb[j];
n1da = FCIpopcount_1(da);
n1db = FCIpopcount_1(db);
switch (n1da) {
case 0: switch (n1db) {
case 2:
pi = first1(db & strb[i]);
pj = first1(db & strb[j]);
tmp = h1e_b[pi*norb+pj];
for (k = 0; k < norb; k++) {
if (stra[i] & (1ULL<<k)) {
tmp += g2e_ab[pi*norb+pj+k*d3+k*d2];
}
if (strb[i] & (1ULL<<k)) {
tmp += g2e_bb[pi*d3+pj*d2+k*norb+k]
- g2e_bb[pi*d3+k*d2+k*norb+pj];
}
}
if (FCIcre_des_sign(pi, pj, strb[j]) > 0) {
h0[i*np+j] = tmp;
} else {
h0[i*np+j] = -tmp;
} break;
case 4:
pi = first1(db & strb[i]);
pj = first1(db & strb[j]);
pk = first1((db & strb[i]) ^ (1ULL<<pi));
pl = first1((db & strb[j]) ^ (1ULL<<pj));
str1 = strb[j] ^ (1ULL<<pi) ^ (1ULL<<pj);
if (FCIcre_des_sign(pi, pj, strb[j])
*FCIcre_des_sign(pk, pl, str1) > 0) {
h0[i*np+j] = g2e_bb[pi*d3+pj*d2+pk*norb+pl]
- g2e_bb[pi*d3+pl*d2+pk*norb+pj];
} else {
h0[i*np+j] =-g2e_bb[pi*d3+pj*d2+pk*norb+pl]
+ g2e_bb[pi*d3+pl*d2+pk*norb+pj];
} } break;
case 2: switch (n1db) {
case 0:
pi = first1(da & stra[i]);
pj = first1(da & stra[j]);
tmp = h1e_a[pi*norb+pj];
for (k = 0; k < norb; k++) {
if (strb[i] & (1ULL<<k)) {
tmp += g2e_ab[pi*d3+pj*d2+k*norb+k];
}
if (stra[i] & (1ULL<<k)) {
tmp += g2e_aa[pi*d3+pj*d2+k*norb+k]
- g2e_aa[pi*d3+k*d2+k*norb+pj];
}
}
if (FCIcre_des_sign(pi, pj, stra[j]) > 0) {
h0[i*np+j] = tmp;
} else {
h0[i*np+j] = -tmp;
} break;
case 2:
pi = first1(da & stra[i]);
pj = first1(da & stra[j]);
pk = first1(db & strb[i]);
pl = first1(db & strb[j]);
if (FCIcre_des_sign(pi, pj, stra[j])
*FCIcre_des_sign(pk, pl, strb[j]) > 0) {
h0[i*np+j] = g2e_ab[pi*d3+pj*d2+pk*norb+pl];
} else {
h0[i*np+j] =-g2e_ab[pi*d3+pj*d2+pk*norb+pl];
} } break;
case 4: switch (n1db) {
case 0:
pi = first1(da & stra[i]);
pj = first1(da & stra[j]);
pk = first1((da & stra[i]) ^ (1ULL<<pi));
pl = first1((da & stra[j]) ^ (1ULL<<pj));
str1 = stra[j] ^ (1ULL<<pi) ^ (1ULL<<pj);
if (FCIcre_des_sign(pi, pj, stra[j])
*FCIcre_des_sign(pk, pl, str1) > 0) {
h0[i*np+j] = g2e_aa[pi*d3+pj*d2+pk*norb+pl]
- g2e_aa[pi*d3+pl*d2+pk*norb+pj];
} else {
h0[i*np+j] =-g2e_aa[pi*d3+pj*d2+pk*norb+pl]
+ g2e_aa[pi*d3+pl*d2+pk*norb+pj];
}
} break;
}
} }
}
}
void FCIpspace_h0tril(double *h0, double *h1e, double *g2e,
uint64_t *stra, uint64_t *strb, int norb, int np)
{
FCIpspace_h0tril_uhf(h0, h1e, h1e, g2e, g2e, g2e, stra, strb, norb, np);
}
/***********************************************************************
*
* With symmetry
*
* Note the ordering in eri and the index in link_index
* eri is a tril matrix, it should be reordered wrt the irrep of the
* direct product E_i^j. The 2D array eri(ij,kl) is a diagonal block
* matrix. Each block is associated with an irrep.
* link_index[str_id,pair_id,0] which is the index of pair_id, should be
* reordered wrt the irreps accordingly
*
* dimirrep stores the number of occurence for each irrep
*
***********************************************************************/
static void pick_link_by_irrep(_LinkTrilT *clink, int *link_index,
int nstr, int nlink, int eri_irrep)
{
int i, j, k;
for (i = 0; i < nstr; i++) {
for (k = 0, j = 0; k < nlink; k++) {
if (link_index[k*4+1] == eri_irrep) {
clink[j].ia = link_index[k*4+0];
clink[j].addr = link_index[k*4+2];
clink[j].sign = link_index[k*4+3];
j++;
}
}
if (j < nlink) {
clink[j].sign = 0;
}
clink += nlink;
link_index += nlink * 4;
}
}
static void ctr_rhf2esym_kern1(double *eri, double *ci0, double *ci1ab,
double *ci1buf, double *t1buf, int ncol_ci1buf,
int bcount, int stra_id, int strb_id,
int nnorb, int nb_intermediate,
int na, int nb, int nlinka, int nlinkb,
_LinkTrilT *clink_indexa, _LinkTrilT *clink_indexb)
{
const char TRANS_N = 'N';
const double D0 = 0;
const double D1 = 1;
double *t1 = t1buf;
double *vt1 = t1buf + nnorb*bcount;
memset(t1, 0, sizeof(double)*nnorb*bcount);
FCIprog_a_t1(ci0, t1, bcount, stra_id, strb_id,
0, nb, nlinka, clink_indexa);
dgemm_(&TRANS_N, &TRANS_N, &bcount, &nnorb, &nnorb,
&D1, t1, &bcount, eri, &nnorb, &D0, vt1, &bcount);
FCIspread_b_t1(ci1ab, vt1, bcount, stra_id, strb_id,
0, nb_intermediate, nlinkb, clink_indexb);
spread_bufa_t1(ci1buf, vt1, bcount, bcount, stra_id, 0,
0, ncol_ci1buf, nlinka, clink_indexa);
}
static void loop_c2e_symm1(double *eri, double *ci0, double *ci1aa, double *ci1ab,
int nnorb, int na_intermediate, int nb_intermediate,
int na, int nb, int nlinka, int nlinkb,
_LinkTrilT *clinka, _LinkTrilT *clinkb)
{
double *ci1bufs[MAX_THREADS];
#pragma omp parallel default(none) \
shared(eri, ci0, ci1aa, ci1ab, nnorb, na, nb, nlinka, nlinkb, \
na_intermediate, nb_intermediate, clinka, clinkb, ci1bufs)
{
int strk, ib;
size_t blen;
double *t1buf = malloc(sizeof(double) * STRB_BLKSIZE*nnorb*2);
double *ci1buf = malloc(sizeof(double) * na*STRB_BLKSIZE);
ci1bufs[omp_get_thread_num()] = ci1buf;
for (ib = 0; ib < nb; ib += STRB_BLKSIZE) {
blen = MIN(STRB_BLKSIZE, nb-ib);
memset(ci1buf, 0, sizeof(double) * na*blen);
#pragma omp for schedule(static)
for (strk = 0; strk < na_intermediate; strk++) {
ctr_rhf2esym_kern1(eri, ci0, ci1ab, ci1buf, t1buf,
blen, blen, strk, ib,
nnorb, nb_intermediate, na, nb,
nlinka, nlinkb, clinka, clinkb);
}
NPomp_dsum_reduce_inplace(ci1bufs, blen*na);
#pragma omp master
FCIaxpy2d(ci1aa+ib, ci1buf, na, nb, blen);
}
free(ci1buf);
free(t1buf);
}
}
#define TOTIRREPS 8
void FCIcontract_2e_symm1(double **eris, double **ci0, double **ci1,
int norb, int *nas, int *nbs, int nlinka, int nlinkb,
int **linka, int **linkb, int *dimirrep, int wfnsym)
{
int i;
int na = 0;
int nb = 0;
for (i = 0; i < TOTIRREPS; i++) {
na = MAX(nas[i], na);
nb = MAX(nbs[i], nb);
}
_LinkTrilT *clinka = malloc(sizeof(_LinkTrilT) * nlinka * na);
_LinkTrilT *clinkb = malloc(sizeof(_LinkTrilT) * nlinkb * nb);
int ai_ir, stra_ir, strb_ir, intera_ir, interb_ir, ma, mb;
for (stra_ir = 0; stra_ir < TOTIRREPS; stra_ir++) {
for (ai_ir = 0; ai_ir < TOTIRREPS; ai_ir++) {
strb_ir = wfnsym^stra_ir;
ma = nas[stra_ir];
mb = nbs[strb_ir];
if (ma > 0 && mb > 0 && dimirrep[ai_ir] > 0) {
intera_ir = ai_ir^stra_ir;
interb_ir = ai_ir^strb_ir;
// clinka for inter_ir*ai_ir -> stra_ir
pick_link_by_irrep(clinka, linka[intera_ir],
nas[intera_ir], nlinka, ai_ir);
// clinka for strb_ir*ai_ir -> inter_ir
pick_link_by_irrep(clinkb, linkb[strb_ir],
nbs[strb_ir], nlinkb, ai_ir);
loop_c2e_symm1(eris[ai_ir], ci0[stra_ir],
ci1[stra_ir], ci1[intera_ir],
dimirrep[ai_ir], nas[intera_ir],
nbs[interb_ir], ma, mb,
nlinka, nlinkb, clinka, clinkb);
}
} }
free(clinka);
free(clinkb);
}
|
ctrmm.c | /**
*
* @file
*
* PLASMA is a software package provided by:
* University of Tennessee, US,
* University of Manchester, UK.
*
* @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/compute/ztrmm.c, normal z -> c, Fri Sep 28 17:38:03 2018
*
**/
#include "plasma.h"
#include "plasma_async.h"
#include "plasma_context.h"
#include "plasma_descriptor.h"
#include "plasma_internal.h"
#include "plasma_tuning.h"
#include "plasma_types.h"
#include "plasma_workspace.h"
/***************************************************************************//**
*
* @ingroup plasma_trmm
*
* Performs a triangular matrix-matrix multiply of the form
*
* \f[B = \alpha [op(A) \times B] \f], if side = PlasmaLeft or
* \f[B = \alpha [B \times op(A)] \f], if side = PlasmaRight
*
* where op( X ) is one of:
*
* - op(A) = A or
* - op(A) = A^T or
* - op(A) = A^H
*
* alpha is a scalar, B is an m-by-n matrix and A is a unit or non-unit, upper
* or lower triangular matrix.
*
*******************************************************************************
*
* @param[in] side
* Specifies whether op( A ) appears on the left or on the right of B:
* - PlasmaLeft: alpha*op( A )*B
* - PlasmaRight: alpha*B*op( A )
*
* @param[in] uplo
* Specifies whether the matrix A is upper triangular or lower
* triangular:
* - PlasmaUpper: Upper triangle of A is stored;
* - PlasmaLower: Lower triangle of A is stored.
*
* @param[in] transa
* Specifies whether the matrix A is transposed, not transposed or
* conjugate transposed:
* - PlasmaNoTrans: A is transposed;
* - PlasmaTrans: A is not transposed;
* - PlasmaConjTrans: A is conjugate transposed.
*
* @param[in] diag
* Specifies whether or not A is unit triangular:
* - PlasmaNonUnit: A is non-unit triangular;
* - PlasmaUnit: A is unit triangular.
*
* @param[in] m
* The number of rows of matrix B.
* m >= 0.
*
* @param[in] n
* The number of columns of matrix B.
* n >= 0.
*
* @param[in] alpha
* The scalar alpha.
*
* @param[in] pA
* The triangular matrix A of dimension lda-by-k, where k is m when
* side='L' or 'l' and k is n when when side='R' or 'r'. If uplo =
* PlasmaUpper, the leading k-by-k upper triangular part of the array
* A contains the upper triangular matrix, and the strictly lower
* triangular part of A is not referenced. If uplo = PlasmaLower, the
* leading k-by-k lower triangular part of the array A contains the
* lower triangular matrix, and the strictly upper triangular part of
* A is not referenced. If diag = PlasmaUnit, the diagonal elements of
* A are also not referenced and are assumed to be 1.
*
* @param[in] lda
* The leading dimension of the array A. When side='L' or 'l',
* lda >= max(1,m), when side='R' or 'r' then lda >= max(1,n).
*
* @param[in,out] pB
* On entry, the matrix B of dimension ldb-by-n.
* On exit, the result of a triangular matrix-matrix multiply
* ( alpha*op(A)*B ) or ( alpha*B*op(A) ).
*
* @param[in] ldb
* The leading dimension of the array B. ldb >= max(1,m).
*
*******************************************************************************
*
* @retval PlasmaSuccess successful exit
*
*******************************************************************************
*
* @sa plasma_omp_ctrmm
* @sa plasma_ctrmm
* @sa plasma_dtrmm
* @sa plasma_strmm
*
******************************************************************************/
int plasma_ctrmm(plasma_enum_t side, plasma_enum_t uplo,
plasma_enum_t transa, plasma_enum_t diag,
int m, int n,
plasma_complex32_t alpha, plasma_complex32_t *pA, int lda,
plasma_complex32_t *pB, int ldb)
{
// Get PLASMA context.
plasma_context_t *plasma = plasma_context_self();
if (plasma == NULL) {
plasma_error("PLASMA not initialized");
return PlasmaErrorNotInitialized;
}
// Check input arguments.
if (side != PlasmaLeft && side != PlasmaRight) {
plasma_error("illegal value of side");
return -1;
}
if (uplo != PlasmaUpper && uplo != PlasmaLower) {
plasma_error("illegal value of uplo");
return -2;
}
if (transa != PlasmaConjTrans &&
transa != PlasmaNoTrans &&
transa != PlasmaTrans )
{
plasma_error("illegal value of transa");
return -3;
}
if (diag != PlasmaUnit && diag != PlasmaNonUnit) {
plasma_error("illegal value of diag");
return -4;
}
if (m < 0) {
plasma_error("illegal value of m");
return -5;
}
if (n < 0) {
plasma_error("illegal value of n");
return -6;
}
int k = (side == PlasmaLeft) ? m : n;
if (lda < imax(1, k)) {
plasma_error("illegal value of lda");
return -8;
}
if (ldb < imax(1, m)) {
plasma_error("illegal value of ldb");
return -10;
}
// quick return
if (imin(m, n) == 0)
return PlasmaSuccess;
// Tune parameters.
if (plasma->tuning)
plasma_tune_trmm(plasma, PlasmaComplexFloat, m, n);
// Set tiling parameters.
int nb = plasma->nb;
// Create tile matrices.
plasma_desc_t A;
plasma_desc_t B;
int retval;
retval = plasma_desc_triangular_create(PlasmaComplexFloat, uplo, nb, nb,
k, k, 0, 0, k, k, &A);
if (retval != PlasmaSuccess) {
plasma_error("plasma_desc_triangular_create() failed");
return retval;
}
retval = plasma_desc_general_create(PlasmaComplexFloat, nb, nb,
m, n, 0, 0, m, n, &B);
if (retval != PlasmaSuccess) {
plasma_error("plasma_desc_general_create() failed");
plasma_desc_destroy(&A);
return retval;
}
// Initialize sequence.
plasma_sequence_t sequence;
retval = plasma_sequence_init(&sequence);
// Initialize request.
plasma_request_t request;
retval = plasma_request_init(&request);
// asynchronous block
#pragma omp parallel
#pragma omp master
{
// Translate matrices to tile layout.
plasma_omp_ctr2desc(pA, lda, A, &sequence, &request);
plasma_omp_cge2desc(pB, ldb, B, &sequence, &request);
// Call tile async interface.
plasma_omp_ctrmm(side, uplo, transa, diag,
alpha, A,
B,
&sequence, &request);
// Translate back to LAPACK layout.
plasma_omp_cdesc2ge(B, pB, ldb, &sequence, &request);
}
// implicit synchronization
// Free matrices in tile layout.
plasma_desc_destroy(&A);
plasma_desc_destroy(&B);
// Return status.
return sequence.status;
}
/***************************************************************************//**
*
* @ingroup plasma_trmm
*
* Performs triangular matrix multiplication. Non-blocking tile version of
* plasma_ctrmm(). May return before the computation is finished. Operates on
* matrices stored by tiles. All matrices are passed through descriptors. All
* dimensions are taken from the descriptors. Allows for pipelining of
* operations at runtime.
*
*******************************************************************************
*
* @param[in] side
* Specifies whether op( A ) appears on the left or on the right of B:
* - PlasmaLeft: alpha*op( A )*B
* - PlasmaRight: alpha*B*op( A )
*
* @param[in] uplo
* Specifies whether the matrix A is upper triangular or lower
* triangular:
* - PlasmaUpper: Upper triangle of A is stored;
* - PlasmaLower: Lower triangle of A is stored.
*
* @param[in] transa
* Specifies whether the matrix A is transposed, not transposed or
* conjugate transposed:
* - PlasmaNoTrans: A is transposed;
* - PlasmaTrans: A is not transposed;
* - PlasmaConjTrans: A is conjugate transposed.
*
* @param[in] diag
* Specifies whether or not A is unit triangular:
* - PlasmaNonUnit: A is non-unit triangular;
* - PlasmaUnit: A is unit triangular.
*
* @param[in] alpha
* The scalar alpha.
*
* @param[in] A
* Descriptor of the triangular matrix A.
*
* @param[in,out] B
* Descriptor of matrix B.
*
* @param[in] sequence
* Identifies the sequence of function calls that this call belongs to
* (for completion checks and exception handling purposes).
*
* @param[out] request
* Identifies this function call (for exception handling purposes).
*
* @retval void
* Errors are returned by setting sequence->status and
* request->status to error values. The sequence->status and
* request->status should never be set to PlasmaSuccess (the
* initial values) since another async call may be setting a
* failure value at the same time.
*
*******************************************************************************
*
* @sa plasma_ctrmm
* @sa plasma_omp_ctrmm
* @sa plasma_omp_dtrmm
* @sa plasma_omp_strmm
*
******************************************************************************/
void plasma_omp_ctrmm(plasma_enum_t side, plasma_enum_t uplo,
plasma_enum_t transa, plasma_enum_t diag,
plasma_complex32_t alpha, plasma_desc_t A,
plasma_desc_t B,
plasma_sequence_t *sequence, plasma_request_t *request)
{
// Get PLASMA context.
plasma_context_t *plasma = plasma_context_self();
if (plasma == NULL) {
plasma_error("PLASMA not initialized");
plasma_request_fail(sequence, request, PlasmaErrorNotInitialized);
return;
}
// Check input arguments.
if (side != PlasmaLeft && side != PlasmaRight) {
plasma_error("illegal value of side");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (uplo != PlasmaUpper && uplo != PlasmaLower) {
plasma_error("illegal value of uplo");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (transa != PlasmaConjTrans &&
transa != PlasmaNoTrans &&
transa != PlasmaTrans) {
plasma_error("illegal value of transa");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (diag != PlasmaUnit && diag != PlasmaNonUnit) {
plasma_error("illegal value of diag");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (plasma_desc_check(A) != PlasmaSuccess) {
plasma_error("invalid A");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (plasma_desc_check(B) != PlasmaSuccess) {
plasma_error("invalid B");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (sequence == NULL) {
plasma_error("NULL sequence");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (request == NULL) {
plasma_error("NULL request");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
// quick return
if (A.m == 0 || A.n == 0 || B.m == 0 || B.n == 0)
return;
if (alpha == 0.0) {
plasma_complex32_t zzero = 0.0;
plasma_pclaset(PlasmaGeneral, zzero, zzero, B, sequence, request);
return;
}
// Call parallel function.
plasma_pctrmm(side, uplo, transa, diag, alpha,
A, B,
sequence, request);
}
|
mixed_tentusscher_myo_epi_2004_S2_17.c | // Scenario 2 - Mixed-Model TenTusscher 2004 (Myocardium + Epicardium)
// (AP + max:dvdt)
#include <stdio.h>
#include "mixed_tentusscher_myo_epi_2004_S2_17.h"
GET_CELL_MODEL_DATA(init_cell_model_data)
{
if(get_initial_v)
cell_model->initial_v = INITIAL_V;
if(get_neq)
cell_model->number_of_ode_equations = NEQ;
}
SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu)
{
static bool first_call = true;
if(first_call)
{
print_to_stdout_and_file("Using mixed version of TenTusscher 2004 myocardium + epicardium CPU model\n");
first_call = false;
}
// Get the mapping array
uint32_t *mapping = NULL;
if(extra_data)
{
mapping = (uint32_t*)extra_data;
}
else
{
print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n");
}
// Initial conditions for TenTusscher myocardium
if (mapping[sv_id] == 0)
{
// Default initial conditions
/*
sv[0] = INITIAL_V; // V; millivolt
sv[1] = 0.f; //M
sv[2] = 0.75; //H
sv[3] = 0.75f; //J
sv[4] = 0.f; //Xr1
sv[5] = 1.f; //Xr2
sv[6] = 0.f; //Xs
sv[7] = 1.f; //S
sv[8] = 0.f; //R
sv[9] = 0.f; //D
sv[10] = 1.f; //F
sv[11] = 1.f; //FCa
sv[12] = 1.f; //G
sv[13] = 0.0002; //Cai
sv[14] = 0.2f; //CaSR
sv[15] = 11.6f; //Nai
sv[16] = 138.3f; //Ki
*/
// Elnaz's steady-state initial conditions
real sv_sst[]={-86.3965119057144,0.00133824305081220,0.775463576993407,0.775278393595599,0.000179499343643571,0.483303039835057,0.00297647859235379,0.999998290403642,1.98961879737287e-08,1.93486789479597e-05,0.999599147019885,1.00646342475688,0.999975178010127,5.97703651642618e-05,0.418325344820368,10.7429775420171,138.918155900633};
for (uint32_t i = 0; i < NEQ; i++)
sv[i] = sv_sst[i];
}
// Initial conditions for TenTusscher epicardium
else
{
// Default initial conditions
/*
sv[0] = INITIAL_V; // V; millivolt
sv[1] = 0.f; //M
sv[2] = 0.75; //H
sv[3] = 0.75f; //J
sv[4] = 0.f; //Xr1
sv[5] = 1.f; //Xr2
sv[6] = 0.f; //Xs
sv[7] = 1.f; //S
sv[8] = 0.f; //R
sv[9] = 0.f; //D
sv[10] = 1.f; //F
sv[11] = 1.f; //FCa
sv[12] = 1.f; //G
sv[13] = 0.0002; //Cai
sv[14] = 0.2f; //CaSR
sv[15] = 11.6f; //Nai
sv[16] = 138.3f; //Ki
*/
// Elnaz's steady-state initial conditions
real sv_sst[]={-86.5285006584511,0.00130106729313035,0.778730090563051,0.778532170509002,0.000175864034699588,0.484676327494511,0.00294864118836231,0.999998334805594,1.94635926887894e-08,1.90111810990968e-05,0.999770708859905,1.00748136518757,0.999998809936904,3.60224813237435e-05,1.18254991511234,9.21308723760909,140.066635187809};
for (uint32_t i = 0; i < NEQ; i++)
sv[i] = sv_sst[i];
}
}
SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu)
{
// Get the mapping array
uint32_t *mapping = NULL;
if(extra_data)
{
mapping = (uint32_t*)extra_data;
}
else
{
print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n");
}
uint32_t sv_id;
int i;
#pragma omp parallel for private(sv_id)
for (i = 0; i < num_cells_to_solve; i++)
{
if(cells_to_solve)
sv_id = cells_to_solve[i];
else
sv_id = (uint32_t )i;
for (int j = 0; j < num_steps; ++j)
{
if (mapping[i] == 0)
solve_model_ode_cpu_myo(dt, sv + (sv_id * NEQ), stim_currents[i]);
else
solve_model_ode_cpu_epi(dt, sv + (sv_id * NEQ), stim_currents[i]);
}
}
}
void solve_model_ode_cpu_myo (real dt, real *sv, real stim_current)
{
real rY[NEQ], rDY[NEQ];
for(int i = 0; i < NEQ; i++)
rY[i] = sv[i];
RHS_cpu_myo(rY, rDY, stim_current, dt);
for(int i = 0; i < NEQ; i++)
sv[i] = rDY[i];
}
void RHS_cpu_myo(const real *sv, real *rDY_, real stim_current, real dt)
{
// State variables
real svolt = sv[0];
real sm = sv[1];
real sh = sv[2];
real sj = sv[3];
real sxr1 = sv[4];
real sxr2 = sv[5];
real sxs = sv[6];
real ss = sv[7];
real sr = sv[8];
real sd = sv[9];
real sf = sv[10];
real sfca = sv[11];
real sg = sv[12];
real Cai = sv[13];
real CaSR = sv[14];
real Nai = sv[15];
real Ki = sv[16];
//External concentrations
real Ko=5.4;
real Cao=2.0;
real Nao=140.0;
//Intracellular volumes
real Vc=0.016404;
real Vsr=0.001094;
//Calcium dynamics
real Bufc=0.15f;
real Kbufc=0.001f;
real Bufsr=10.f;
real Kbufsr=0.3f;
real taufca=2.f;
real taug=2.f;
real Vmaxup=0.000425f;
real Kup=0.00025f;
//Constants
const real R = 8314.472f;
const real F = 96485.3415f;
const real T =310.0f;
real RTONF =(R*T)/F;
//Cellular capacitance
real CAPACITANCE=0.185;
//Parameters for currents
//Parameters for IKr
real Gkr=0.096;
//Parameters for Iks
real pKNa=0.03;
// [!] Myocardium cell
real Gks=0.062;
//Parameters for Ik1
real GK1=5.405;
//Parameters for Ito
// [!] Myocardium cell
real Gto=0.294;
//Parameters for INa
real GNa=14.838;
//Parameters for IbNa
real GbNa=0.00029;
//Parameters for INaK
real KmK=1.0;
real KmNa=40.0;
real knak=1.362;
//Parameters for ICaL
real GCaL=0.000175;
//Parameters for IbCa
real GbCa=0.000592;
//Parameters for INaCa
real knaca=1000;
real KmNai=87.5;
real KmCa=1.38;
real ksat=0.1;
real n=0.35;
//Parameters for IpCa
real GpCa=0.825;
real KpCa=0.0005;
//Parameters for IpK;
real GpK=0.0146;
real IKr;
real IKs;
real IK1;
real Ito;
real INa;
real IbNa;
real ICaL;
real IbCa;
real INaCa;
real IpCa;
real IpK;
real INaK;
real Irel;
real Ileak;
real dNai;
real dKi;
real dCai;
real dCaSR;
real A;
// real BufferFactorc;
// real BufferFactorsr;
real SERCA;
real Caisquare;
real CaSRsquare;
real CaCurrent;
real CaSRCurrent;
real fcaold;
real gold;
real Ek;
real Ena;
real Eks;
real Eca;
real CaCSQN;
real bjsr;
real cjsr;
real CaBuf;
real bc;
real cc;
real Ak1;
real Bk1;
real rec_iK1;
real rec_ipK;
real rec_iNaK;
real AM;
real BM;
real AH_1;
real BH_1;
real AH_2;
real BH_2;
real AJ_1;
real BJ_1;
real AJ_2;
real BJ_2;
real M_INF;
real H_INF;
real J_INF;
real TAU_M;
real TAU_H;
real TAU_J;
real axr1;
real bxr1;
real axr2;
real bxr2;
real Xr1_INF;
real Xr2_INF;
real TAU_Xr1;
real TAU_Xr2;
real Axs;
real Bxs;
real Xs_INF;
real TAU_Xs;
real R_INF;
real TAU_R;
real S_INF;
real TAU_S;
real Ad;
real Bd;
real Cd;
real TAU_D;
real D_INF;
real TAU_F;
real F_INF;
real FCa_INF;
real G_INF;
real inverseVcF2=1/(2*Vc*F);
real inverseVcF=1./(Vc*F);
real Kupsquare=Kup*Kup;
// real BufcKbufc=Bufc*Kbufc;
// real Kbufcsquare=Kbufc*Kbufc;
// real Kbufc2=2*Kbufc;
// real BufsrKbufsr=Bufsr*Kbufsr;
// const real Kbufsrsquare=Kbufsr*Kbufsr;
// const real Kbufsr2=2*Kbufsr;
const real exptaufca=exp(-dt/taufca);
const real exptaug=exp(-dt/taug);
real sItot;
//Needed to compute currents
Ek=RTONF*(log((Ko/Ki)));
Ena=RTONF*(log((Nao/Nai)));
Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai)));
Eca=0.5*RTONF*(log((Cao/Cai)));
Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200)));
Bk1=(3.*exp(0.0002*(svolt-Ek+100))+
exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek)));
rec_iK1=Ak1/(Ak1+Bk1);
rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T))));
rec_ipK=1./(1.+exp((25-svolt)/5.98));
//Compute currents
INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena);
ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))*
(exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.);
Ito=Gto*sr*ss*(svolt-Ek);
IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek);
IKs=Gks*sxs*sxs*(svolt-Eks);
IK1=GK1*rec_iK1*(svolt-Ek);
INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))*
(1./(1+ksat*exp((n-1)*svolt*F/(R*T))))*
(exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao-
exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5);
INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK;
IpCa=GpCa*Cai/(KpCa+Cai);
IpK=GpK*rec_ipK*(svolt-Ek);
IbNa=GbNa*(svolt-Ena);
IbCa=GbCa*(svolt-Eca);
//Determine total current
(sItot) = IKr +
IKs +
IK1 +
Ito +
INa +
IbNa +
ICaL +
IbCa +
INaK +
INaCa +
IpCa +
IpK +
stim_current;
//update concentrations
Caisquare=Cai*Cai;
CaSRsquare=CaSR*CaSR;
CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE;
A=0.016464f*CaSRsquare/(0.0625f+CaSRsquare)+0.008232f;
Irel=A*sd*sg;
Ileak=0.00008f*(CaSR-Cai);
SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare));
CaSRCurrent=SERCA-Irel-Ileak;
CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr);
dCaSR=dt*(Vc/Vsr)*CaSRCurrent;
bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr;
cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR);
CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.;
CaBuf=Bufc*Cai/(Cai+Kbufc);
dCai=dt*(CaCurrent-CaSRCurrent);
bc=Bufc-CaBuf-dCai-Cai+Kbufc;
cc=Kbufc*(CaBuf+dCai+Cai);
Cai=(sqrt(bc*bc+4*cc)-bc)/2;
dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE;
Nai+=dt*dNai;
dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE;
Ki+=dt*dKi;
//compute steady state values and time constants
AM=1./(1.+exp((-60.-svolt)/5.));
BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.));
TAU_M=AM*BM;
M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03)));
if (svolt>=-40.)
{
AH_1=0.;
BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1))));
TAU_H= 1.0/(AH_1+BH_1);
}
else
{
AH_2=(0.057*exp(-(svolt+80.)/6.8));
BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt));
TAU_H=1.0/(AH_2+BH_2);
}
H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43)));
if(svolt>=-40.)
{
AJ_1=0.;
BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.))));
TAU_J= 1.0/(AJ_1+BJ_1);
}
else
{
AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)*
exp(-0.04391*svolt))*(svolt+37.78)/
(1.+exp(0.311*(svolt+79.23))));
BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14))));
TAU_J= 1.0/(AJ_2+BJ_2);
}
J_INF=H_INF;
Xr1_INF=1./(1.+exp((-26.-svolt)/7.));
axr1=450./(1.+exp((-45.-svolt)/10.));
bxr1=6./(1.+exp((svolt-(-30.))/11.5));
TAU_Xr1=axr1*bxr1;
Xr2_INF=1./(1.+exp((svolt-(-88.))/24.));
axr2=3./(1.+exp((-60.-svolt)/20.));
bxr2=1.12/(1.+exp((svolt-60.)/20.));
TAU_Xr2=axr2*bxr2;
Xs_INF=1./(1.+exp((-5.-svolt)/14.));
Axs=1100./(sqrt(1.+exp((-10.-svolt)/6)));
Bxs=1./(1.+exp((svolt-60.)/20.));
TAU_Xs=Axs*Bxs;
// [!] Myocardium cell
R_INF=1./(1.+exp((20-svolt)/6.));
S_INF=1./(1.+exp((svolt+20)/5.));
TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8;
TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.;
D_INF=1./(1.+exp((-5-svolt)/7.5));
Ad=1.4/(1.+exp((-35-svolt)/13))+0.25;
Bd=1.4/(1.+exp((svolt+5)/5));
Cd=1./(1.+exp((50-svolt)/20));
TAU_D=Ad*Bd+Cd;
F_INF=1./(1.+exp((svolt+20)/7));
//TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10));
TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML
FCa_INF=(1./(1.+pow((Cai/0.000325),8))+
0.1/(1.+exp((Cai-0.0005)/0.0001))+
0.20/(1.+exp((Cai-0.00075)/0.0008))+
0.23 )/1.46;
if(Cai<0.00035)
G_INF=1./(1.+pow((Cai/0.00035),6));
else
G_INF=1./(1.+pow((Cai/0.00035),16));
//Update gates
rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M);
rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H);
rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J);
rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1);
rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2);
rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs);
rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S);
rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R);
rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D);
rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F);
fcaold= sfca;
sfca = FCa_INF-(FCa_INF-sfca)*exptaufca;
if(sfca>fcaold && (svolt)>-37.0)
sfca = fcaold;
gold = sg;
sg = G_INF-(G_INF-sg)*exptaug;
if(sg>gold && (svolt)>-37.0)
sg=gold;
//update voltage
rDY_[0] = svolt + dt*(-sItot);
rDY_[11] = sfca;
rDY_[12] = sg;
rDY_[13] = Cai;
rDY_[14] = CaSR;
rDY_[15] = Nai;
rDY_[16] = Ki;
}
void solve_model_ode_cpu_epi (real dt, real *sv, real stim_current)
{
real rY[NEQ], rDY[NEQ];
for(int i = 0; i < NEQ; i++)
rY[i] = sv[i];
RHS_cpu_epi(rY, rDY, stim_current, dt);
for(int i = 0; i < NEQ; i++)
sv[i] = rDY[i];
}
void RHS_cpu_epi(const real *sv, real *rDY_, real stim_current, real dt)
{
// State variables
real svolt = sv[0];
real sm = sv[1];
real sh = sv[2];
real sj = sv[3];
real sxr1 = sv[4];
real sxr2 = sv[5];
real sxs = sv[6];
real ss = sv[7];
real sr = sv[8];
real sd = sv[9];
real sf = sv[10];
real sfca = sv[11];
real sg = sv[12];
real Cai = sv[13];
real CaSR = sv[14];
real Nai = sv[15];
real Ki = sv[16];
//External concentrations
real Ko=5.4;
real Cao=2.0;
real Nao=140.0;
//Intracellular volumes
real Vc=0.016404;
real Vsr=0.001094;
//Calcium dynamics
real Bufc=0.15f;
real Kbufc=0.001f;
real Bufsr=10.f;
real Kbufsr=0.3f;
real taufca=2.f;
real taug=2.f;
real Vmaxup=0.000425f;
real Kup=0.00025f;
//Constants
const real R = 8314.472f;
const real F = 96485.3415f;
const real T =310.0f;
real RTONF =(R*T)/F;
//Cellular capacitance
real CAPACITANCE=0.185;
//Parameters for currents
//Parameters for IKr
real Gkr=0.096;
//Parameters for Iks
real pKNa=0.03;
// [!] Epicardium cell
real Gks=0.245;
//Parameters for Ik1
real GK1=5.405;
//Parameters for Ito
// [!] Epicardium cell
real Gto=0.294;
//Parameters for INa
real GNa=14.838;
//Parameters for IbNa
real GbNa=0.00029;
//Parameters for INaK
real KmK=1.0;
real KmNa=40.0;
real knak=1.362;
//Parameters for ICaL
real GCaL=0.000175;
//Parameters for IbCa
real GbCa=0.000592;
//Parameters for INaCa
real knaca=1000;
real KmNai=87.5;
real KmCa=1.38;
real ksat=0.1;
real n=0.35;
//Parameters for IpCa
real GpCa=0.825;
real KpCa=0.0005;
//Parameters for IpK;
real GpK=0.0146;
real parameters []={13.7219011711698,0.000373800660274715,0.000150569617335446,0.000654485626385041,0.257379206595380,0.173802542474158,0.132458241657246,3.93296187661537,0.0158924919170214,2.50168625879054,1095.95864752453,0.000511327811652900,0.243193135425503,0.0192821673745436,0.00636346797017134,9.00104876078144e-06};
GNa=parameters[0];
GbNa=parameters[1];
GCaL=parameters[2];
GbCa=parameters[3];
Gto=parameters[4];
Gkr=parameters[5];
Gks=parameters[6];
GK1=parameters[7];
GpK=parameters[8];
knak=parameters[9];
knaca=parameters[10];
Vmaxup=parameters[11];
GpCa=parameters[12];
real arel=parameters[13];
real crel=parameters[14];
real Vleak=parameters[15];
real IKr;
real IKs;
real IK1;
real Ito;
real INa;
real IbNa;
real ICaL;
real IbCa;
real INaCa;
real IpCa;
real IpK;
real INaK;
real Irel;
real Ileak;
real dNai;
real dKi;
real dCai;
real dCaSR;
real A;
// real BufferFactorc;
// real BufferFactorsr;
real SERCA;
real Caisquare;
real CaSRsquare;
real CaCurrent;
real CaSRCurrent;
real fcaold;
real gold;
real Ek;
real Ena;
real Eks;
real Eca;
real CaCSQN;
real bjsr;
real cjsr;
real CaBuf;
real bc;
real cc;
real Ak1;
real Bk1;
real rec_iK1;
real rec_ipK;
real rec_iNaK;
real AM;
real BM;
real AH_1;
real BH_1;
real AH_2;
real BH_2;
real AJ_1;
real BJ_1;
real AJ_2;
real BJ_2;
real M_INF;
real H_INF;
real J_INF;
real TAU_M;
real TAU_H;
real TAU_J;
real axr1;
real bxr1;
real axr2;
real bxr2;
real Xr1_INF;
real Xr2_INF;
real TAU_Xr1;
real TAU_Xr2;
real Axs;
real Bxs;
real Xs_INF;
real TAU_Xs;
real R_INF;
real TAU_R;
real S_INF;
real TAU_S;
real Ad;
real Bd;
real Cd;
real TAU_D;
real D_INF;
real TAU_F;
real F_INF;
real FCa_INF;
real G_INF;
real inverseVcF2=1/(2*Vc*F);
real inverseVcF=1./(Vc*F);
real Kupsquare=Kup*Kup;
// real BufcKbufc=Bufc*Kbufc;
// real Kbufcsquare=Kbufc*Kbufc;
// real Kbufc2=2*Kbufc;
// real BufsrKbufsr=Bufsr*Kbufsr;
// const real Kbufsrsquare=Kbufsr*Kbufsr;
// const real Kbufsr2=2*Kbufsr;
const real exptaufca=exp(-dt/taufca);
const real exptaug=exp(-dt/taug);
real sItot;
//Needed to compute currents
Ek=RTONF*(log((Ko/Ki)));
Ena=RTONF*(log((Nao/Nai)));
Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai)));
Eca=0.5*RTONF*(log((Cao/Cai)));
Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200)));
Bk1=(3.*exp(0.0002*(svolt-Ek+100))+
exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek)));
rec_iK1=Ak1/(Ak1+Bk1);
rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T))));
rec_ipK=1./(1.+exp((25-svolt)/5.98));
//Compute currents
INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena);
ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))*
(exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.);
Ito=Gto*sr*ss*(svolt-Ek);
IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek);
IKs=Gks*sxs*sxs*(svolt-Eks);
IK1=GK1*rec_iK1*(svolt-Ek);
INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))*
(1./(1+ksat*exp((n-1)*svolt*F/(R*T))))*
(exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao-
exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5);
INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK;
IpCa=GpCa*Cai/(KpCa+Cai);
IpK=GpK*rec_ipK*(svolt-Ek);
IbNa=GbNa*(svolt-Ena);
IbCa=GbCa*(svolt-Eca);
//Determine total current
(sItot) = IKr +
IKs +
IK1 +
Ito +
INa +
IbNa +
ICaL +
IbCa +
INaK +
INaCa +
IpCa +
IpK +
stim_current;
//update concentrations
Caisquare=Cai*Cai;
CaSRsquare=CaSR*CaSR;
CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE;
A=arel*CaSRsquare/(0.0625f+CaSRsquare)+crel;
Irel=A*sd*sg;
Ileak=Vleak*(CaSR-Cai);
SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare));
CaSRCurrent=SERCA-Irel-Ileak;
CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr);
dCaSR=dt*(Vc/Vsr)*CaSRCurrent;
bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr;
cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR);
CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.;
CaBuf=Bufc*Cai/(Cai+Kbufc);
dCai=dt*(CaCurrent-CaSRCurrent);
bc=Bufc-CaBuf-dCai-Cai+Kbufc;
cc=Kbufc*(CaBuf+dCai+Cai);
Cai=(sqrt(bc*bc+4*cc)-bc)/2;
dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE;
Nai+=dt*dNai;
dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE;
Ki+=dt*dKi;
//compute steady state values and time constants
AM=1./(1.+exp((-60.-svolt)/5.));
BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.));
TAU_M=AM*BM;
M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03)));
if (svolt>=-40.)
{
AH_1=0.;
BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1))));
TAU_H= 1.0/(AH_1+BH_1);
}
else
{
AH_2=(0.057*exp(-(svolt+80.)/6.8));
BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt));
TAU_H=1.0/(AH_2+BH_2);
}
H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43)));
if(svolt>=-40.)
{
AJ_1=0.;
BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.))));
TAU_J= 1.0/(AJ_1+BJ_1);
}
else
{
AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)*
exp(-0.04391*svolt))*(svolt+37.78)/
(1.+exp(0.311*(svolt+79.23))));
BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14))));
TAU_J= 1.0/(AJ_2+BJ_2);
}
J_INF=H_INF;
Xr1_INF=1./(1.+exp((-26.-svolt)/7.));
axr1=450./(1.+exp((-45.-svolt)/10.));
bxr1=6./(1.+exp((svolt-(-30.))/11.5));
TAU_Xr1=axr1*bxr1;
Xr2_INF=1./(1.+exp((svolt-(-88.))/24.));
axr2=3./(1.+exp((-60.-svolt)/20.));
bxr2=1.12/(1.+exp((svolt-60.)/20.));
TAU_Xr2=axr2*bxr2;
Xs_INF=1./(1.+exp((-5.-svolt)/14.));
Axs=1100./(sqrt(1.+exp((-10.-svolt)/6)));
Bxs=1./(1.+exp((svolt-60.)/20.));
TAU_Xs=Axs*Bxs;
R_INF=1./(1.+exp((20-svolt)/6.));
S_INF=1./(1.+exp((svolt+20)/5.));
TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8;
TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.;
D_INF=1./(1.+exp((-5-svolt)/7.5));
Ad=1.4/(1.+exp((-35-svolt)/13))+0.25;
Bd=1.4/(1.+exp((svolt+5)/5));
Cd=1./(1.+exp((50-svolt)/20));
TAU_D=Ad*Bd+Cd;
F_INF=1./(1.+exp((svolt+20)/7));
//TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10));
TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML
FCa_INF=(1./(1.+pow((Cai/0.000325),8))+
0.1/(1.+exp((Cai-0.0005)/0.0001))+
0.20/(1.+exp((Cai-0.00075)/0.0008))+
0.23 )/1.46;
if(Cai<0.00035)
G_INF=1./(1.+pow((Cai/0.00035),6));
else
G_INF=1./(1.+pow((Cai/0.00035),16));
//Update gates
rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M);
rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H);
rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J);
rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1);
rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2);
rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs);
rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S);
rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R);
rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D);
rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F);
fcaold= sfca;
sfca = FCa_INF-(FCa_INF-sfca)*exptaufca;
if(sfca>fcaold && (svolt)>-37.0)
sfca = fcaold;
gold = sg;
sg = G_INF-(G_INF-sg)*exptaug;
if(sg>gold && (svolt)>-37.0)
sg=gold;
//update voltage
rDY_[0] = svolt + dt*(-sItot);
rDY_[11] = sfca;
rDY_[12] = sg;
rDY_[13] = Cai;
rDY_[14] = CaSR;
rDY_[15] = Nai;
rDY_[16] = Ki;
}
|
GB_binop__isgt_uint8.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_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__isgt_uint8
// A.*B function (eWiseMult): GB_AemultB__isgt_uint8
// A*D function (colscale): GB_AxD__isgt_uint8
// D*A function (rowscale): GB_DxB__isgt_uint8
// C+=B function (dense accum): GB_Cdense_accumB__isgt_uint8
// C+=b function (dense accum): GB_Cdense_accumb__isgt_uint8
// C+=A+B function (dense ewise3): (none)
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__isgt_uint8
// C=scalar+B GB_bind1st__isgt_uint8
// C=scalar+B' GB_bind1st_tran__isgt_uint8
// C=A+scalar GB_bind2nd__isgt_uint8
// C=A'+scalar GB_bind2nd_tran__isgt_uint8
// C type: uint8_t
// A type: uint8_t
// B,b type: uint8_t
// 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) \
uint8_t aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
uint8_t bij = Bx [pB]
// 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) \
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 = (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_ISGT || GxB_NO_UINT8 || GxB_NO_ISGT_UINT8)
//------------------------------------------------------------------------------
// 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__isgt_uint8
(
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__isgt_uint8
(
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__isgt_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__isgt_uint8
(
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
uint8_t *GB_RESTRICT Cx = (uint8_t *) 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__isgt_uint8
(
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
uint8_t *GB_RESTRICT Cx = (uint8_t *) C->x ;
#include "GB_AxB_rowscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
#undef GB_FREE_ALL
#define GB_FREE_ALL \
{ \
GB_ek_slice_free (&pstart_Mslice, &kfirst_Mslice, &klast_Mslice) ; \
GB_ek_slice_free (&pstart_Aslice, &kfirst_Aslice, &klast_Aslice) ; \
GB_ek_slice_free (&pstart_Bslice, &kfirst_Bslice, &klast_Bslice) ; \
}
GrB_Info GB_AaddB__isgt_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 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 C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ;
int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ;
int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ;
#include "GB_add_template.c"
GB_FREE_ALL ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C = A.*B or C<M> = A.*B
//------------------------------------------------------------------------------
GrB_Info GB_AemultB__isgt_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 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 C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ;
int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ;
int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ;
#include "GB_emult_template.c"
GB_FREE_ALL ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB_bind1st__isgt_uint8
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *GB_RESTRICT Bb,
int64_t anz,
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 < anz ; p++)
{
if (!GBB (Bb, p)) continue ;
uint8_t 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__isgt_uint8
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *GB_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 = 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 typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint8_t aij = Ax [pA] ; \
Cx [pC] = (x > aij) ; \
}
GrB_Info GB_bind1st_tran__isgt_uint8
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Workspaces,
const int64_t *GB_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 = Ax [pA] ; \
Cx [pC] = (aij > y) ; \
}
GrB_Info GB_bind2nd_tran__isgt_uint8
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *GB_RESTRICT *Workspaces,
const int64_t *GB_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_unop__identity_fc64_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 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__identity_fc64_fc32
// op(A') function: GB_unop_tran__identity_fc64_fc32
// C type: GxB_FC64_t
// A type: GxB_FC32_t
// cast: GxB_FC64_t cij = GxB_CMPLX ((double) crealf (aij), (double) cimagf (aij))
// unaryop: cij = aij
#define GB_ATYPE \
GxB_FC32_t
#define GB_CTYPE \
GxB_FC64_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 = x ;
// casting
#define GB_CAST(z, aij) \
GxB_FC64_t z = GxB_CMPLX ((double) crealf (aij), (double) cimagf (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_FC64_t z = GxB_CMPLX ((double) crealf (aij), (double) cimagf (aij)) ; \
Cx [pC] = 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_IDENTITY || GxB_NO_FC64 || GxB_NO_FC32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__identity_fc64_fc32
(
GxB_FC64_t *Cx, // Cx and Ax may be aliased
const GxB_FC32_t *Ax,
const int8_t *GB_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)
{
#if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST )
GB_memcpy (Cx, Ax, anz * sizeof (GxB_FC32_t), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GxB_FC32_t aij = Ax [p] ;
GxB_FC64_t z = GxB_CMPLX ((double) crealf (aij), (double) cimagf (aij)) ;
Cx [p] = 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 ;
GxB_FC32_t aij = Ax [p] ;
GxB_FC64_t z = GxB_CMPLX ((double) crealf (aij), (double) cimagf (aij)) ;
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_fc32
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Workspaces,
const int64_t *GB_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
|
fibonacci.c | /*
* Copyright 2020 Ricardo Ortiz, ricardo.ortiz@alumnos.ucn.cl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom
* the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
/**
*
* Fibonacci
*@author Ricardo Ortiz-Hidalgo
*/
//method that calculates the fibonacci
int fibonacci(int n) {
int i, j;
if (n<2)
return n;
else {
#pragma omp task shared(i)
i=fibonacci(n-1);
#pragma omp task shared(j)
j=fibonacci(n-2);
#pragma omp taskwait
return i+j;
}
}
// The main method
int main(int argc, char **argv){
int valor = 2;
int n, resultado;
char *a = argv[1];
n = atoi(a);
#pragma omp parallel
{
#pragma omp single
{
for(int i = 0; i<=n;i++)
{
result = fibonacci(n);
result= fibonacci(i);
printf("fibonacci de (%d) %d =",i,result);
if(result<5)
{
printf("%d\n",result);
}else
{
while (result != 1)
{
if(result%valor==0)
{
printf("%d",valor);
result=result/valor;
if (result != 1)
{
printf("X");
}
}else
{
valor++;
}
}
valor = 2;
printf("\n");
}
factoredFibonacci(result);
newResult= factoredFibonacci(result);
printf("FIB(%d) = %ld\n", i,newResult);
}
}
}
printf("Result is %d\n", result);
}
//method that calculates the factored fibonacci series
void factoredFibonacci(int numFibonacci) {
int div = 2;
if (numFibonacci <= 5) {
printf("%d", numFibonacci);
} else {
while (numFibonacci != 1) {
if (numFibonacci % div == 0) {
printf("%d ", div);
numFibonacci = numFibonacci / div;
if (numFibonacci != 1)
printf("x ");
} else {
div++;
}
}
}
}
|
3d7pt.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
* 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, 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]);
double ****A = (double ****) malloc(sizeof(double***)*2);
A[0] = (double ***) malloc(sizeof(double**)*Nz);
A[1] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[0][i] = (double**) malloc(sizeof(double*)*Ny);
A[1][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[0][i][j] = (double*) malloc(sizeof(double)*Nx);
A[1][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] = 32;
tile_size[1] = 32;
tile_size[2] = 32;
tile_size[3] = 32;
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;
const double alpha = 0.0876;
const double beta = 0.0765;
// 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);
}
}
}
#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,16);t1++) {
lbp=max(ceild(t1,2),ceild(32*t1-Nt+3,32));
ubp=min(floord(Nt+Nz-4,32),floord(16*t1+Nz+13,32));
#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(t1-1,2)),ceild(32*t2-Nz-28,32));t3<=min(min(min(floord(Nt+Ny-4,32),floord(16*t1+Ny+29,32)),floord(32*t2+Ny+28,32)),floord(32*t1-32*t2+Nz+Ny+27,32));t3++) {
for (t4=max(max(max(0,ceild(t1-1,2)),ceild(32*t2-Nz-28,32)),ceild(32*t3-Ny-28,32));t4<=min(min(min(min(floord(Nt+Nx-4,32),floord(16*t1+Nx+29,32)),floord(32*t2+Nx+28,32)),floord(32*t3+Nx+28,32)),floord(32*t1-32*t2+Nz+Nx+27,32));t4++) {
for (t5=max(max(max(max(max(0,16*t1),32*t1-32*t2+1),32*t2-Nz+2),32*t3-Ny+2),32*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,16*t1+31),32*t2+30),32*t3+30),32*t4+30),32*t1-32*t2+Nz+29);t5++) {
for (t6=max(max(32*t2,t5+1),-32*t1+32*t2+2*t5-31);t6<=min(min(32*t2+31,-32*t1+32*t2+2*t5),t5+Nz-2);t6++) {
for (t7=max(32*t3,t5+1);t7<=min(32*t3+31,t5+Ny-2);t7++) {
lbv=max(32*t4,t5+1);
ubv=min(32*t4+31,t5+Nx-2);
#pragma ivdep
#pragma vector always
for (t8=lbv;t8<=ubv;t8++) {
A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = ((alpha * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (beta * (((((A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)] + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1]) + A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-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, "constant")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays (Causing performance degradation
/* 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]);
*/
return 0;
}
|
DeclOpenMP.h | //===- DeclOpenMP.h - Classes for representing OpenMP directives -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file defines OpenMP nodes for declarative directives.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_DECLOPENMP_H
#define LLVM_CLANG_AST_DECLOPENMP_H
#include "clang/AST/Decl.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExternalASTSource.h"
#include "clang/AST/OpenMPClause.h"
#include "clang/AST/Type.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/Support/TrailingObjects.h"
namespace clang {
/// This represents '#pragma omp threadprivate ...' directive.
/// For example, in the following, both 'a' and 'A::b' are threadprivate:
///
/// \code
/// int a;
/// #pragma omp threadprivate(a)
/// struct A {
/// static int b;
/// #pragma omp threadprivate(b)
/// };
/// \endcode
///
class OMPThreadPrivateDecl final
: public Decl,
private llvm::TrailingObjects<OMPThreadPrivateDecl, Expr *> {
friend class ASTDeclReader;
friend TrailingObjects;
unsigned NumVars;
virtual void anchor();
OMPThreadPrivateDecl(Kind DK, DeclContext *DC, SourceLocation L) :
Decl(DK, DC, L), NumVars(0) { }
ArrayRef<const Expr *> getVars() const {
return llvm::makeArrayRef(getTrailingObjects<Expr *>(), NumVars);
}
MutableArrayRef<Expr *> getVars() {
return MutableArrayRef<Expr *>(getTrailingObjects<Expr *>(), NumVars);
}
void setVars(ArrayRef<Expr *> VL);
public:
static OMPThreadPrivateDecl *Create(ASTContext &C, DeclContext *DC,
SourceLocation L,
ArrayRef<Expr *> VL);
static OMPThreadPrivateDecl *CreateDeserialized(ASTContext &C,
unsigned ID, unsigned N);
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 getVars().begin(); }
varlist_iterator varlist_end() { return getVars().end(); }
varlist_const_iterator varlist_begin() const { return getVars().begin(); }
varlist_const_iterator varlist_end() const { return getVars().end(); }
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == OMPThreadPrivate; }
};
/// This represents '#pragma omp declare reduction ...' directive.
/// For example, in the following, declared reduction 'foo' for types 'int' and
/// 'float':
///
/// \code
/// #pragma omp declare reduction (foo : int,float : omp_out += omp_in) \
/// initializer (omp_priv = 0)
/// \endcode
///
/// Here 'omp_out += omp_in' is a combiner and 'omp_priv = 0' is an initializer.
class OMPDeclareReductionDecl final : public ValueDecl, public DeclContext {
// This class stores some data in DeclContext::OMPDeclareReductionDeclBits
// to save some space. Use the provided accessors to access it.
public:
enum InitKind {
CallInit, // Initialized by function call.
DirectInit, // omp_priv(<expr>)
CopyInit // omp_priv = <expr>
};
private:
friend class ASTDeclReader;
/// Combiner for declare reduction construct.
Expr *Combiner = nullptr;
/// Initializer for declare reduction construct.
Expr *Initializer = nullptr;
/// In parameter of the combiner.
Expr *In = nullptr;
/// Out parameter of the combiner.
Expr *Out = nullptr;
/// Priv parameter of the initializer.
Expr *Priv = nullptr;
/// Orig parameter of the initializer.
Expr *Orig = nullptr;
/// Reference to the previous declare reduction construct in the same
/// scope with the same name. Required for proper templates instantiation if
/// the declare reduction construct is declared inside compound statement.
LazyDeclPtr PrevDeclInScope;
virtual void anchor();
OMPDeclareReductionDecl(Kind DK, DeclContext *DC, SourceLocation L,
DeclarationName Name, QualType Ty,
OMPDeclareReductionDecl *PrevDeclInScope);
void setPrevDeclInScope(OMPDeclareReductionDecl *Prev) {
PrevDeclInScope = Prev;
}
public:
/// Create declare reduction node.
static OMPDeclareReductionDecl *
Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name,
QualType T, OMPDeclareReductionDecl *PrevDeclInScope);
/// Create deserialized declare reduction node.
static OMPDeclareReductionDecl *CreateDeserialized(ASTContext &C,
unsigned ID);
/// Get combiner expression of the declare reduction construct.
Expr *getCombiner() { return Combiner; }
const Expr *getCombiner() const { return Combiner; }
/// Get In variable of the combiner.
Expr *getCombinerIn() { return In; }
const Expr *getCombinerIn() const { return In; }
/// Get Out variable of the combiner.
Expr *getCombinerOut() { return Out; }
const Expr *getCombinerOut() const { return Out; }
/// Set combiner expression for the declare reduction construct.
void setCombiner(Expr *E) { Combiner = E; }
/// Set combiner In and Out vars.
void setCombinerData(Expr *InE, Expr *OutE) {
In = InE;
Out = OutE;
}
/// Get initializer expression (if specified) of the declare reduction
/// construct.
Expr *getInitializer() { return Initializer; }
const Expr *getInitializer() const { return Initializer; }
/// Get initializer kind.
InitKind getInitializerKind() const {
return static_cast<InitKind>(OMPDeclareReductionDeclBits.InitializerKind);
}
/// Get Orig variable of the initializer.
Expr *getInitOrig() { return Orig; }
const Expr *getInitOrig() const { return Orig; }
/// Get Priv variable of the initializer.
Expr *getInitPriv() { return Priv; }
const Expr *getInitPriv() const { return Priv; }
/// Set initializer expression for the declare reduction construct.
void setInitializer(Expr *E, InitKind IK) {
Initializer = E;
OMPDeclareReductionDeclBits.InitializerKind = IK;
}
/// Set initializer Orig and Priv vars.
void setInitializerData(Expr *OrigE, Expr *PrivE) {
Orig = OrigE;
Priv = PrivE;
}
/// Get reference to previous declare reduction construct in the same
/// scope with the same name.
OMPDeclareReductionDecl *getPrevDeclInScope();
const OMPDeclareReductionDecl *getPrevDeclInScope() const;
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == OMPDeclareReduction; }
static DeclContext *castToDeclContext(const OMPDeclareReductionDecl *D) {
return static_cast<DeclContext *>(const_cast<OMPDeclareReductionDecl *>(D));
}
static OMPDeclareReductionDecl *castFromDeclContext(const DeclContext *DC) {
return static_cast<OMPDeclareReductionDecl *>(
const_cast<DeclContext *>(DC));
}
};
/// Pseudo declaration for capturing expressions. Also is used for capturing of
/// non-static data members in non-static member functions.
///
/// Clang supports capturing of variables only, but OpenMP 4.5 allows to
/// privatize non-static members of current class in non-static member
/// functions. This pseudo-declaration allows properly handle this kind of
/// capture by wrapping captured expression into a variable-like declaration.
class OMPCapturedExprDecl final : public VarDecl {
friend class ASTDeclReader;
void anchor() override;
OMPCapturedExprDecl(ASTContext &C, DeclContext *DC, IdentifierInfo *Id,
QualType Type, TypeSourceInfo *TInfo,
SourceLocation StartLoc)
: VarDecl(OMPCapturedExpr, C, DC, StartLoc, StartLoc, Id, Type, TInfo,
SC_None) {
setImplicit();
}
public:
static OMPCapturedExprDecl *Create(ASTContext &C, DeclContext *DC,
IdentifierInfo *Id, QualType T,
SourceLocation StartLoc);
static OMPCapturedExprDecl *CreateDeserialized(ASTContext &C, unsigned ID);
SourceRange getSourceRange() const override LLVM_READONLY;
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == OMPCapturedExpr; }
};
/// This represents '#pragma omp requires...' directive.
/// For example
///
/// \code
/// #pragma omp requires unified_address
/// \endcode
///
class OMPRequiresDecl final
: public Decl,
private llvm::TrailingObjects<OMPRequiresDecl, OMPClause *> {
friend class ASTDeclReader;
friend TrailingObjects;
// Number of clauses associated with this requires declaration
unsigned NumClauses = 0;
virtual void anchor();
OMPRequiresDecl(Kind DK, DeclContext *DC, SourceLocation L)
: Decl(DK, DC, L), NumClauses(0) {}
/// Returns an array of immutable clauses associated with this requires
/// declaration
ArrayRef<const OMPClause *> getClauses() const {
return llvm::makeArrayRef(getTrailingObjects<OMPClause *>(), NumClauses);
}
/// Returns an array of clauses associated with this requires declaration
MutableArrayRef<OMPClause *> getClauses() {
return MutableArrayRef<OMPClause *>(getTrailingObjects<OMPClause *>(),
NumClauses);
}
/// Sets an array of clauses to this requires declaration
void setClauses(ArrayRef<OMPClause *> CL);
public:
/// Create requires node.
static OMPRequiresDecl *Create(ASTContext &C, DeclContext *DC,
SourceLocation L, ArrayRef<OMPClause *> CL);
/// Create deserialized requires node.
static OMPRequiresDecl *CreateDeserialized(ASTContext &C, unsigned ID,
unsigned N);
using clauselist_iterator = MutableArrayRef<OMPClause *>::iterator;
using clauselist_const_iterator = ArrayRef<const OMPClause *>::iterator;
using clauselist_range = llvm::iterator_range<clauselist_iterator>;
using clauselist_const_range = llvm::iterator_range<clauselist_const_iterator>;
unsigned clauselist_size() const { return NumClauses; }
bool clauselist_empty() const { return NumClauses == 0; }
clauselist_range clauselists() {
return clauselist_range(clauselist_begin(), clauselist_end());
}
clauselist_const_range clauselists() const {
return clauselist_const_range(clauselist_begin(), clauselist_end());
}
clauselist_iterator clauselist_begin() { return getClauses().begin(); }
clauselist_iterator clauselist_end() { return getClauses().end(); }
clauselist_const_iterator clauselist_begin() const {
return getClauses().begin();
}
clauselist_const_iterator clauselist_end() const {
return getClauses().end();
}
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == OMPRequires; }
};
} // end namespace clang
#endif
|
queues.c | // -*-Mode: C++;-*- // technically C99
// * BeginRiceCopyright *****************************************************
//
// $HeadURL$
// $Id$
//
// --------------------------------------------------------------------------
// Part of HPCToolkit (hpctoolkit.org)
//
// Information about sources of support for research and development of
// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.
// --------------------------------------------------------------------------
//
// Copyright ((c)) 2002-2020, Rice 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 Rice University (RICE) 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 RICE 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 RICE 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.
//
// ******************************************************* EndRiceCopyright *
//*****************************************************************************
// local includes
//*****************************************************************************
#include "queues.h"
//*****************************************************************************
// interface functions
//*****************************************************************************
#define Sd(q) q.ptr
#define Sp(q) q->ptr
#define Ad(q) q.aptr
#define Ap(q) q->aptr
void
squeue_ptr_set
(
q_element_ptr_t *p,
q_element_t *v
)
{
Sp(p) = v;
}
q_element_t *
squeue_ptr_get
(
q_element_ptr_t *e
)
{
return Sp(e);
}
q_element_t *
squeue_swap
(
q_element_ptr_t *q,
q_element_t *r
)
{
q_element_t *e = Sp(q);
Sp(q) = r;
return e;
}
void
squeue_push
(
q_element_ptr_t *q,
q_element_t *e
)
{
e->Sd(next) = Sp(q);
Sp(q) = e;
}
q_element_t *
squeue_pop
(
q_element_ptr_t *q
)
{
q_element_t *e = 0;
if (Sp(q)) {
e = Sp(q);
Sp(q) = e->Sd(next);
e->Sd(next) = 0;
}
return e;
}
q_element_t *
squeue_steal
(
q_element_ptr_t *q
)
{
q_element_t *e = squeue_swap(q, 0);
return e;
}
void
cqueue_ptr_set
(
q_element_ptr_t *e,
q_element_t *v
)
{
atomic_init(&Ap(e), v);
}
q_element_t *
cqueue_ptr_get
(
q_element_ptr_t *e
)
{
return atomic_load(&Ap(e));
}
q_element_t *
cqueue_swap
(
q_element_ptr_t *q,
q_element_t *r
)
{
q_element_t *e = atomic_exchange(&Ap(q),r);
return e;
}
void
cqueue_push
(
q_element_ptr_t *q,
q_element_t *e
)
{
q_element_t *head = atomic_load(&Ap(q));
q_element_t *new_head = e;
// push a singleton or a chain on the list
for (;;) {
q_element_t *enext = atomic_load(&e->Ad(next));
if (enext == 0) break;
e = enext;
}
do {
atomic_store(&e->Ad(next), head);
} while (!atomic_compare_exchange_strong(&Ap(q), &head, new_head));
}
q_element_t *
cqueue_pop
(
q_element_ptr_t *q
)
{
q_element_t *oldhead = atomic_load(&Ap(q));
q_element_t *next = 0;
do {
if (oldhead == 0) return 0;
next = atomic_load(&oldhead->Ad(next));
} while (!atomic_compare_exchange_strong(&Ap(q), &oldhead, next));
atomic_store(&oldhead->Ad(next),0);
return oldhead;
}
q_element_t *
cqueue_steal
(
q_element_ptr_t *q
)
{
q_element_t *e = cqueue_swap(q, 0);
return e;
}
//*****************************************************************************
// unit test
//*****************************************************************************
#define UNIT_TEST 0
#if UNIT_TEST
#include <stdlib.h>
#include <stdio.h>
#include <omp.h>
typedef struct {
q_element_ptr_t next;
int value;
} typed_queue_elem(int);
typedef q_element_ptr_t typed_queue_elem_ptr(int);
typed_queue_elem_ptr(int) queue;
#define qtype cqueue
typed_queue(int, qtype)
typed_queue_elem(int) *
typed_queue_elem_fn(int,new)(int value)
{
typed_queue_elem(int) *e =(typed_queue_elem(int) *) malloc(sizeof(int_q_element_t));
e->value = value;
typed_queue_elem_ptr_set(int, qtype)(&e->next, 0);
}
void
pop
(
int n
)
{
int i;
for(i = 0; i < n; i++) {
typed_queue_elem(int) *e = typed_queue_pop(int, qtype)(&queue);
if (e == 0) {
printf("%d queue empty\n", omp_get_thread_num());
break;
} else {
printf("%d popping %d\n", omp_get_thread_num(), e->value);
}
}
}
void
push
(
int min,
int n
)
{
int i;
for(i = min; i < min+n; i++) {
printf("%d pushing %d\n", omp_get_thread_num(), i);
typed_queue_push(int, qtype)(&queue, typed_queue_elem_fn(int, new)(i));
}
}
void
dump
(
int_q_element_t *e
)
{
int i;
for(; e; e = (int_q_element_t *) typed_queue_elem_ptr_get(int,qtype)(&e->next)) {
printf("%d stole %d\n", omp_get_thread_num(), e->value);
}
}
int
main
(
int argc,
char **argv
)
{
typed_queue_elem_ptr_set(int, qtype)(&queue, 0);
#pragma omp parallel
{
push(0, 30);
pop(10);
push(100, 12);
// pop(100);
int_q_element_t *e = typed_queue_steal(int, qtype)(&queue);
dump(e);
push(300, 30);
typed_queue_push(int, qtype)(&queue, e);
pop(100);
}
}
#endif
|
par_grid_list.c | #include "par_grid_list.h"
int main(int argc, char* argv[]){
char* file; /**< Input data file name */
int generations = 0; /**< Number of generations to proccess */
int cube_size = 0; /**< Size of the 3D space */
GraphNode*** graph; /**< Graph representation - 2D array of lists */
List* update; /**< Contains the information of nodes that might change state */
/* Iterator variables */
int g, i, j;
GraphNode* g_it = NULL;
Node* it = NULL;
/* Lock variables */
omp_lock_t list_lock;
omp_lock_t** graph_lock;
parseArgs(argc, argv, &file, &generations);
/* Create an empty list, with size 0 */
update = listCreate();
graph = parseFile(file, update, &cube_size);
/* Initialize lock variables */
omp_init_lock(&list_lock);
graph_lock = (omp_lock_t**)malloc(cube_size * sizeof(omp_lock_t*));
for(i = 0; i < cube_size; i++){
graph_lock[i] = (omp_lock_t*) malloc(cube_size * sizeof(omp_lock_t));
for(j = 0; j < cube_size; j++){
omp_init_lock(&(graph_lock[i][j]));
}
}
double start = omp_get_wtime(); // Start Timer
for(g = 1; g <= generations; g++){
/* Convert list to vector */
i = 0;
int size = update->size;
Node** vector = (Node**) malloc(sizeof(Node*) * size);
for (it = listFirst(update); it != NULL; it = it->next){
vector[i++] = it;
}
Node** proccessed;
/* For each live node, inform its neighbors */
#pragma omp parallel
{
#pragma omp for
for (i = 0; i < size; i++){
//printf("Neighbours processing by thread: %d\n", omp_get_thread_num());
visitNeighbours(graph, graph_lock, cube_size, update, &list_lock, vector[i]->x, vector[i]->y, vector[i]->z);
}
/* Convert list to vector */
#pragma omp single
{
i = 0;
size = update->size;
proccessed = (Node**) malloc(sizeof(Node*) * size);
for (it = listFirst(update); it != NULL; it = it->next){
proccessed[i++] = it;
}
}
/* Update graph and update set */
#pragma omp for
for (i = 0; i < size; i++){
//printf("Update graph processing by thread: %d\n", omp_get_thread_num());
Node* it = proccessed[i];
unsigned char live_neighbours = it->ptr->neighbours;
it->ptr->neighbours = 0;
if(it->ptr->state == ALIVE){
if(live_neighbours < 2 || live_neighbours > 4){
graphNodeRemove(&(graph[it->x][it->y]), it->z, &(graph_lock[it->x][it->y]));
it->x = REMOVE;
}
}else{
if(live_neighbours == 2 || live_neighbours == 3){
it->ptr->state = ALIVE;
}
else{
graphNodeRemove(&(graph[it->x][it->y]), it->z, &(graph_lock[it->x][it->y]));
it->x = REMOVE;
}
}
}
}
/* Clean dead cells from the set */
listCleanup(update);
free(proccessed);
free(vector);
}
double end = omp_get_wtime(); // Stop Timer
/* Print the final set of live cells */
printAndSortActive(graph, cube_size);
time_print("%f\n", end - start);
/* Free resources */
freeGraph(graph, cube_size);
listDelete(update);
omp_destroy_lock(&list_lock);
for(i = 0; i < cube_size; i++){
for(j=0; j<cube_size; j++){
omp_destroy_lock(&(graph_lock[i][j]));
}
}
free(file);
return 0;
}
/**************************************************************************/
void visitNeighbours(GraphNode*** graph, omp_lock_t** graph_lock, int cube_size,
List* list, omp_lock_t* list_lock,
coordinate x, coordinate y, coordinate z){
GraphNode* ptr;
coordinate x1, x2, y1, y2, z1, z2;
x1 = (x+1)%cube_size; x2 = (x-1) < 0 ? (cube_size-1) : (x-1);
y1 = (y+1)%cube_size; y2 = (y-1) < 0 ? (cube_size-1) : (y-1);
z1 = (z+1)%cube_size; z2 = (z-1) < 0 ? (cube_size-1) : (z-1);
/* If a cell is visited for the first time, add it to the update list, for fast access */
if(graphNodeAddNeighbour(&(graph[x1][y]), z, &ptr, &graph_lock[x1][y])){
listInsertLock(list, x1, y, z, ptr, list_lock);
}
if(graphNodeAddNeighbour(&(graph[x2][y]), z, &ptr, &graph_lock[x2][y])){
listInsertLock(list, x2, y, z, ptr, list_lock);
}
if(graphNodeAddNeighbour(&(graph[x][y1]), z, &ptr, &graph_lock[x][y1])){
listInsertLock(list, x, y1, z, ptr, list_lock);
}
if(graphNodeAddNeighbour(&(graph[x][y2]), z, &ptr, &graph_lock[x][y2])){
listInsertLock(list, x, y2, z, ptr, list_lock);
}
if(graphNodeAddNeighbour(&(graph[x][y]), z1, &ptr, &graph_lock[x][y])){
listInsertLock(list, x, y, z1, ptr, list_lock);
}
if(graphNodeAddNeighbour(&(graph[x][y]), z2, &ptr, &graph_lock[x][y])){
listInsertLock(list, x, y, z2, ptr, list_lock);
}
}
/**************************************************************************/
GraphNode*** initGraph(int size){
int i,j;
GraphNode*** graph = (GraphNode***) malloc(sizeof(GraphNode**) * size);
for (i = 0; i < size; i++){
graph[i] = (GraphNode**) malloc(sizeof(GraphNode*) * size);
for (j = 0; j < size; j++){
graph[i][j] = NULL;
}
}
return graph;
}
/**************************************************************************/
void freeGraph(GraphNode*** graph, int size){
int i, j;
if (graph != NULL){
for (i = 0; i < size; i++){
for (j = 0; j < size; j++){
graphNodeDelete(graph[i][j]);
}
free(graph[i]);
}
free(graph);
}
}
/**************************************************************************/
void printAndSortActive(GraphNode*** graph, int cube_size){
int x,y;
GraphNode* it;
for (x = 0; x < cube_size; ++x){
for (y = 0; y < cube_size; ++y){
/* Sort the list by ascending coordinate z */
graphNodeSort(&(graph[x][y]));
for (it = graph[x][y]; it != NULL; it = it->next){
/* At the end of each generation, the graph is guranteed to only have live cells */
out_print("%d %d %d\n", x, y, it->z);
}
}
}
}
/**************************************************************************/
void parseArgs(int argc, char* argv[], char** file, int* generations){
if (argc == 3){
char* file_name = malloc(sizeof(char) * (strlen(argv[1]) + 1));
strcpy(file_name, argv[1]);
*file = file_name;
*generations = atoi(argv[2]);
if (*generations > 0 && file_name != NULL)
return;
}
printf("Usage: %s [data_file.in] [number_generations]", argv[0]);
exit(EXIT_FAILURE);
}
/**************************************************************************/
GraphNode*** parseFile(char* file, List* list, int* cube_size){
int first = 0;
char line[BUFFER_SIZE];
int x, y, z;
FILE* fp = fopen(file, "r");
if(fp == NULL){
err_print("Please input a valid file name");
exit(EXIT_FAILURE);
}
GraphNode*** graph;
while(fgets(line, sizeof(line), fp)){
if(!first){
if(sscanf(line, "%d\n", cube_size) == 1){
first = 1;
graph = initGraph(*cube_size);
}
}else{
if(sscanf(line, "%d %d %d\n", &x, &y, &z) == 3){
/* Insert live nodes in the graph and the update set */
graph[x][y] = graphNodeInsert(graph[x][y], z, ALIVE);
listInsert(list, x, y, z, (GraphNode*) (graph[x][y]));
}
}
}
fclose(fp);
return graph;
} |
ex2-parallel.c | #include <stdio.h>
void primeNumbers(int n);
int main(){
int n = 100000;
primeNumbers(n);
}
void primeNumbers(int number){
int j, i = 0;
int primes[number+1];
//populating array with naturals numbers
for(i = 0; i<=number; i++)
primes[i] = i;
#pragma omp parallel
{
#pragma omp for schedule(guided, 2000)
for(i = number; i > 0; --i){
for(j = 2; j < i; j++){
if (i % j == 0){
primes[i] = 0;
break;
}
}
}
}
int nOfPrimes = 0;
for(i = 2; i<=number; i++){
//If number is not 0 then it is prime
if (primes[i]!=0){
nOfPrimes++;
// printf("%d %d\n",primes[i], nOfPrimes);
}
}
}
|
task_tied_thread_scheduling.c | // RUN: %libomp-compile && env KMP_ABT_NUM_ESS=4 %libomp-run
// REQUIRES: abt
#include "omp_testsuite.h"
#include "bolt_scheduling_util.h"
int test_task_tied_thread_scheduling(int num_threads) {
int vals[num_threads * num_threads];
memset(vals, 0, sizeof(int) * num_threads * num_threads);
omp_set_max_active_levels(2);
timeout_barrier_t barrier;
timeout_barrier_init(&barrier);
#pragma omp parallel num_threads(num_threads)
#pragma omp master
{
check_num_ess(4);
int i;
for (i = 0; i < num_threads; i++) {
#pragma omp task firstprivate(i)
{
#pragma omp parallel num_threads(num_threads)
{
if (omp_get_thread_num() == 1) {
// We should not block a master thread since it might need to create
// other outer tasks.
timeout_barrier_wait(&barrier, 4);
}
vals[i * num_threads + omp_get_thread_num()] += 1;
}
}
}
}
#pragma omp parallel num_threads(num_threads)
#pragma omp master
{
check_num_ess(4);
int i;
for (i = 0; i < num_threads; i++) {
#pragma omp task firstprivate(i)
{
int j;
#pragma omp parallel for num_threads(num_threads)
for (j = 0; j < num_threads; j++) {
if (omp_get_thread_num() == 1) {
// We should not block a master thread since it might need to create
// other outer tasks.
timeout_barrier_wait(&barrier, 4);
}
vals[i * num_threads + j] += 2;
}
}
}
}
int index;
for (index = 0; index < num_threads * num_threads; index++) {
if (vals[index] != 3) {
printf("vals[%d] == %d\n", index, vals[index]);
return 0;
}
}
return 1;
}
int main() {
int i, num_failed = 0;
for (i = 1; i < 3; i++) {
if (!test_task_tied_thread_scheduling(i * 4)) {
num_failed++;
}
}
return num_failed;
}
|
stack-propagate.c | // RUN: %libomp-compile-and-run
// https://bugs.llvm.org/show_bug.cgi?id=26540 requested
// stack size to be propagated from master to workers.
// Library implements propagation of not too big stack
// for Linux x86_64 platform (skipped Windows for now).
//
// The test checks that workers can use more than 4MB
// of stack (4MB - was historical default for
// stack size of worker thread in runtime library).
#include <stdio.h>
#include <omp.h>
#if !defined(_WIN32)
#include <sys/resource.h> // getrlimit
#endif
#define STK 4800000
double foo(int n, int th)
{
double arr[n];
int i;
double res = 0.0;
for (i = 0; i < n; ++i) {
arr[i] = (double)i / (n + 2);
}
for (i = 0; i < n; ++i) {
res += arr[i] / n;
}
return res;
}
int main(int argc, char *argv[])
{
#if defined(_WIN32)
// don't test Windows
printf("stack propagation not implemented, skipping test...\n");
return 0;
#else
int status;
double val = 0.0;
int m = STK / 8; // > 4800000 bytes per thread
// read stack size of calling thread, save it as default
struct rlimit rlim;
status = getrlimit(RLIMIT_STACK, &rlim);
if (sizeof(void *) > 4 && // do not test 32-bit systems,
status == 0 && rlim.rlim_cur > STK) { // or small initial stack size
#pragma omp parallel reduction(+:val)
{
val += foo(m, omp_get_thread_num());
}
} else {
printf("too small stack size limit (needs about 8MB), skipping test...\n");
return 0;
}
if (val > 0.1) {
printf("passed\n");
return 0;
} else {
printf("failed, val = %f\n", val);
return 1;
}
#endif // _WIN32
}
|
GB_binop__pow_uint32.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__pow_uint32)
// A.*B function (eWiseMult): GB (_AemultB)
// A.*B function (eWiseMult): GB (_AemultB_02__pow_uint32)
// A.*B function (eWiseMult): GB (_AemultB_03__pow_uint32)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__pow_uint32)
// A*D function (colscale): GB ((none))
// D*A function (rowscale): GB ((node))
// C+=B function (dense accum): GB (_Cdense_accumB__pow_uint32)
// C+=b function (dense accum): GB (_Cdense_accumb__pow_uint32)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__pow_uint32)
// C=scalar+B GB (_bind1st__pow_uint32)
// C=scalar+B' GB (_bind1st_tran__pow_uint32)
// C=A+scalar GB (_bind2nd__pow_uint32)
// C=A'+scalar GB (_bind2nd_tran__pow_uint32)
// C type: uint32_t
// A type: uint32_t
// B,b type: uint32_t
// BinaryOp: cij = GB_pow_uint32 (aij, bij)
#define GB_ATYPE \
uint32_t
#define GB_BTYPE \
uint32_t
#define GB_CTYPE \
uint32_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) \
uint32_t aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
uint32_t bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
uint32_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_pow_uint32 (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_UINT32 || GxB_NO_POW_UINT32)
//------------------------------------------------------------------------------
// 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_uint32)
(
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_uint32)
(
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_uint32)
(
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 uint32_t
uint32_t bwork = (*((uint32_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
uint32_t *restrict Cx = (uint32_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
uint32_t *restrict Cx = (uint32_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__pow_uint32)
(
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__pow_uint32)
(
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__pow_uint32)
(
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__pow_uint32)
(
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__pow_uint32)
(
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_uint32)
(
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
uint32_t *Cx = (uint32_t *) Cx_output ;
uint32_t x = (*((uint32_t *) x_input)) ;
uint32_t *Bx = (uint32_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 ;
uint32_t bij = Bx [p] ;
Cx [p] = GB_pow_uint32 (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_uint32)
(
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 ;
uint32_t *Cx = (uint32_t *) Cx_output ;
uint32_t *Ax = (uint32_t *) Ax_input ;
uint32_t y = (*((uint32_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
uint32_t aij = Ax [p] ;
Cx [p] = GB_pow_uint32 (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) \
{ \
uint32_t aij = Ax [pA] ; \
Cx [pC] = GB_pow_uint32 (x, aij) ; \
}
GrB_Info GB (_bind1st_tran__pow_uint32)
(
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 \
uint32_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t x = (*((const uint32_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint32_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) \
{ \
uint32_t aij = Ax [pA] ; \
Cx [pC] = GB_pow_uint32 (aij, y) ; \
}
GrB_Info GB (_bind2nd_tran__pow_uint32)
(
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
uint32_t y = (*((const uint32_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
cts_S_mex.c |
// compile: mex -largeArrayDims OPTIMFLAGS="/openmp $OPTIMFLAGS" cts_S_mex.c
#include "mex.h"
#include <math.h>
#include <omp.h>
/* The gateway function */
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
/* INPUTS */
double *E; /* input matrix E [MxN] */
double *WCL; /* input matrix WCL [nCls x nCls] */
double *C; /* input matrix WCL [1 x M] */
double dc; /* decay ratio - scalar */
/* OUTPUTS */
double * S; /* output matrix S [N x N] */
/* INTERNALS */
long long N,M; /* size of matrix E */
long long nCls, nCls2; /* number of all clusters */
long long Crow, Ccol;
mxArray *wCT_mat;
double *wCT; /* matrix wCT [nCls x nCls]*/
double wCT_val, wCT_max, local_max, S_val;
long long q, i, j, m, WCLi, Ei, Ej;
/*===================================================================*/
/* check for proper number of arguments */
if(nrhs != 4) {
mexErrMsgIdAndTxt("LCE:cts:nrhs","Four inputs required.");
}
if(nlhs != 1) {
mexErrMsgIdAndTxt("LCE:cts:nlhs","One output required.");
}
/* make sure the fourth input argument is scalar */
if( !mxIsDouble(prhs[3]) ||
mxIsComplex(prhs[3]) ||
mxGetNumberOfElements(prhs[3])!=1 ) {
mexErrMsgIdAndTxt("LCE:cts:notScalar","dc must be a scalar.");
}
/* get number of rows and columns of first input argument */
N = mxGetM(prhs[0]); // number of data points
M = mxGetN(prhs[0]); // number of ensemble members
E = mxGetPr(prhs[0]);
/* get number of rows and columns of second input argument */
nCls = mxGetM(prhs[1]);
nCls2 = mxGetN(prhs[1]);
if( nCls != nCls2 ) {
mexErrMsgIdAndTxt("LCE:cts:err","Second input (WCL matrix) mot square.");
}
WCL = mxGetPr(prhs[1]);
/* get number of rows and columns of third input argument */
Crow = mxGetM(prhs[2]);
Ccol = mxGetN(prhs[2]);
if( Crow != 1 ) {
mexErrMsgIdAndTxt("LCE:cts:err","C has to be row vector.");
}
if( Ccol != M ) {
mexErrMsgIdAndTxt("LCE:cts:err","C has to be row vector with M number of elements.");
}
C = mxGetPr(prhs[2]);
/* get the value of the scalar input */
dc = mxGetScalar(prhs[3]);
/* create the output matrix S */
plhs[0] = mxCreateDoubleMatrix(N,N,mxREAL);
/* get a pointer to the real data in the output matrix */
S = mxGetPr(plhs[0]);
// mexPrintf("M: %d, N:%d, nCls: %d\n",M,N,nCls);
//===================================================================
// COMPUTE wCT
//===================================================================
wCT_mat = mxCreateDoubleMatrix(nCls,nCls,mxREAL);
wCT = mxGetPr(wCT_mat);
//omp_set_num_threads(8);
wCT_max = 0;
#pragma omp parallel for shared(WCL,nCls,wCT,C) private(i,q,j,WCLi,wCT_val)
//#pragma omp parallel for
for (i=0;i<nCls-1;i++){ // for each cluster
//mexPrintf("Num threads %d, thread ID %d.\n", omp_get_num_threads(), omp_get_thread_num());
// which ensemble member?
q = 0;
while ( (i+1) > C[q]){
q++;
}
for (j=i+1;j<C[q];j++){ // for each other cluster
// sum of pairwise minimum values of WCL(i,:) and WCL(j,:)
wCT_val = 0;
for (WCLi=0;WCLi<nCls;WCLi++){
wCT_val += fmin(WCL[WCLi*nCls+i], WCL[WCLi*nCls+j]);
}
// if (wCT[j*nCls+i]!=0 || wCT[i*nCls+j]!=0){
// mexPrintf("!!! i: %d, j: %d\n",i,j);
// }
wCT[j*nCls+i] = wCT_val;
wCT[i*nCls+j] = wCT_val;
}
}
for(i=0;i<nCls*nCls;i++){
if (wCT[i] > wCT_max){
wCT_max = wCT[i];
}
}
// wCT_max = 0;
// #pragma omp parallel for
// for ( i=0;i<nCls*nCls;i++) {
// if (wCT[i] > wCT_max){
// #pragma omp critical
// {
// if (wCT[i] > wCT_max){
// wCT_max = wCT[i];
// }
// }
// }
// }
//mexPrintf("wCT_max: %lf\n",wCT_max);
if(wCT_max > 0){
#pragma omp parallel for
for(i=0;i<nCls*nCls;i++){
wCT[i] = wCT[i] / wCT_max;
}
}
#pragma omp parallel for
for(i=0;i<nCls;i++){
wCT[i*nCls+i] = 1;
}
// // Display
// mexPrintf("\nwCT matrix:\n");
// for(i=0;i<nCls;i++){
// for(j=0;j<nCls;j++){
// mexPrintf("%lf ",wCT[j*nCls+i]);
// }
// mexPrintf("\n");
// }
//===================================================================
// COMPUTE S
//===================================================================
//#pragma omp parallel for shared(M,N,E,S,wCT,dc,nCls) private(m,i,j,Ei,Ej,S_val)
//#pragma omp parallel for
for (m=0;m<M;m++){
for (i=0;i<N-1;i++){
for (j=i+1;j<N;j++){
Ei = (long long)E[m*N+i]-1;
Ej = (long long)E[m*N+j]-1;
S_val = S[j*N+i];
if(Ei == Ej){
S_val += 1.0/M;
}
else {
S_val += wCT[Ej*nCls+Ei]*dc/(double)M;
}
S[j*N+i] = S_val;
S[i*N+j] = S_val;
}
}
}
#pragma omp parallel for shared(N,S) private(i)
for(i=0;i<N;i++){
S[i*N+i] = 1;
}
// // Display
// mexPrintf("\nS matrix:\n");
// for(i=0;i<N;i++){
// for(j=0;j<N;j++){
// mexPrintf("%lf ",S[j*N+i]);
// }
// mexPrintf("\n");
// }
}
|
relu6_ref.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 "graph/tensor.h"
#include "graph/node.h"
#include "graph/graph.h"
#include "utility/sys_port.h"
#include "utility/float.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_relu6_uint8(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 batch = input_tensor->dims[0];
int size = h * w;
int c_step = h * w;
int batch_step = c_step * channels;
int total_size = batch_step * batch;
// dequant
uint8_t* input_uint8 = (uint8_t*)input_tensor->data;
uint8_t* output_uint8 = (uint8_t*)output_tensor->data;
float input_scale = input_tensor->scale;
float output_scale = output_tensor->scale;
int32_t input_zero = input_tensor->zero_point;
int32_t output_zero = output_tensor->zero_point;
float* data_fp32 = (float*)sys_malloc(total_size * sizeof(float));
for (int i = 0; i < total_size; i++)
data_fp32[i] = ((float)input_uint8[i] - (float)input_zero) * input_scale;
for (int n = 0; n < batch; n++)
{
//#pragma omp parallel for num_threads(num_thread)
for (int q = 0; q < channels; q++)
{
float* src = data_fp32 + batch_step * n + c_step * q;
float* dst = data_fp32 + batch_step * n + c_step * q;
for (int i = 0; i < size; i++)
{
dst[i] = src[i];
if (src[i] > 6)
dst[i] = 6;
else if (src[i] < 0)
dst[i] = 0;
}
}
}
// quant
for (int i = 0; i < total_size; i++)
{
int udata = round(data_fp32[i] / output_scale + output_zero);
if (udata > 255)
udata = 255;
else if (udata < 0)
udata = 0;
output_uint8[i] = udata;
}
sys_free(data_fp32);
return 0;
}
int ref_relu6_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];
if (dst[i] > 6)
dst[i] = 6;
if (dst[i] < 0)
dst[i] = 0;
}
}
return 0;
}
static int init_node(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph)
{
return 0;
}
static int release_node(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph)
{
return 0;
}
static int run(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph)
{
struct node* ir_node = exec_node->ir_node;
struct graph* ir_graph = ir_node->graph;
struct tensor* input_tensor;
struct tensor* output_tensor;
input_tensor = get_ir_graph_tensor(ir_graph, ir_node->input_tensors[0]);
output_tensor = get_ir_graph_tensor(ir_graph, ir_node->output_tensors[0]);
int ret = -1;
if (input_tensor->data_type == TENGINE_DT_FP32)
ret = ref_relu6_fp32(input_tensor, output_tensor, exec_graph->num_thread);
else if (input_tensor->data_type == TENGINE_DT_UINT8)
ret = ref_relu6_uint8(input_tensor, output_tensor, exec_graph->num_thread);
return ret;
}
static int reshape(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph)
{
struct node* node = exec_node->ir_node;
struct graph* ir_graph = node->graph;
struct tensor* input = get_ir_graph_tensor(ir_graph, node->input_tensors[0]);
struct tensor* output = get_ir_graph_tensor(ir_graph, node->output_tensors[0]);
int ret = set_ir_tensor_shape(output, input->dims, input->dim_num);
return ret;
}
static int score(struct node_ops* node_ops, struct exec_graph* exec_graph, struct node* exec_node)
{
return OPS_SCORE_CANDO;
}
static struct node_ops hcl_node_ops = {.prerun = NULL,
.run = run,
.reshape = reshape,
.postrun = NULL,
.init_node = init_node,
.release_node = release_node,
.score = score};
int register_relu6_ref_op()
{
return register_builtin_node_ops(OP_RELU6, &hcl_node_ops);
}
int unregister_relu6_ref_op()
{
return unregister_builtin_node_ops(OP_RELU6, &hcl_node_ops);
}
|
mult_vMv_split.h | #ifndef _MULT_VMV_SPLIT_H
#define _MULT_VMV_SPLIT_H
//Try to save memory at the cost of some performance
#define VMV_SPLIT_MEM_SAVE
template<typename ComplexMatrixType>
class SCFoperation{
public:
virtual void operator()(const ComplexMatrixType& M, const int scf, const int rows, const int cols) = 0;
};
template<typename ScalarComplexType>
class multiply_M_r_op: public SCFoperation<typename gsl_wrapper<typename ScalarComplexType::value_type>::matrix_complex>{
typedef typename ScalarComplexType::value_type mf_Float;
typedef gsl_wrapper<mf_Float> gw;
std::vector<std::vector<ScalarComplexType> >& Mr;
const std::vector<std::vector<ScalarComplexType> >& rreord;
std::vector<int> const* i_packed_unmap_all; //array of vectors, one for each scf
//Internal
typename gw::vector_complex* Mr_packed;
typename gw::complex one;
typename gw::complex zero;
public:
multiply_M_r_op(std::vector<std::vector<ScalarComplexType> >& _Mr, const std::vector<std::vector<ScalarComplexType> >& _rreord,
std::vector<int> const* _i_packed_unmap_all, const int _nrows_used): Mr(_Mr), rreord(_rreord),i_packed_unmap_all(_i_packed_unmap_all){
Mr_packed = gw::vector_complex_alloc(_nrows_used);
GSL_SET_COMPLEX(&one,1.0,0.0);
GSL_SET_COMPLEX(&zero,0.0,0.0);
}
~multiply_M_r_op(){
gw::vector_complex_free(Mr_packed);
}
void operator()(const typename gw::matrix_complex& M_packed, const int scf, const int rows, const int cols){
const std::vector<int> &i_packed_unmap = i_packed_unmap_all[scf];
int block_width_max = cols;
int block_height_max = 8; //4;
for(int i0=0; i0<rows; i0+=block_height_max){
int iblock_size = std::min(rows - i0, block_height_max);
for(int j0=0; j0<cols; j0+=block_width_max){
int jblock_size = std::min(cols - j0, block_width_max);
typename gw::matrix_complex_const_view submatrix = gw::matrix_complex_const_submatrix(&M_packed, i0, j0, iblock_size, jblock_size);
mf_Float const* base = (mf_Float const*)&rreord[scf][j0];
typename gw::block_complex_struct block;
block.data = base;
block.size = jblock_size;
typename gw::vector_complex rgsl;
rgsl.block = █
rgsl.data = base;
rgsl.stride = 1;
rgsl.owner = 1;
rgsl.size = jblock_size;
Mr_packed->size = iblock_size;
Mr_packed->block->size = iblock_size;
gw::blas_gemv(CblasNoTrans, one, &submatrix.matrix, &rgsl, zero, Mr_packed);
typename gw::complex tmp;
for(int i_packed=0;i_packed < iblock_size; i_packed++){
mf_Float(&tmp)[2] = reinterpret_cast<mf_Float(&)[2]>(Mr[scf][ i_packed_unmap[i0+i_packed] ]);
mf_Float *t = Mr_packed->data + 2*i_packed*Mr_packed->stride;
tmp[0] += *t++; tmp[1] += *t;
}
}
}
}
};
template<typename mf_Policies,
template <typename> class lA2AfieldL, template <typename> class lA2AfieldR,
template <typename> class rA2AfieldL, template <typename> class rA2AfieldR,
typename ComplexClass
>
class mult_vMv_split_v{};
template<typename mf_Policies,
template <typename> class lA2AfieldL, template <typename> class lA2AfieldR,
template <typename> class rA2AfieldL, template <typename> class rA2AfieldR
>
class mult_vMv_split: public mult_vMv_split_v<mf_Policies,lA2AfieldL,lA2AfieldR,rA2AfieldL,rA2AfieldR,typename ComplexClassify<typename mf_Policies::ComplexType>::type>{};
template<typename mf_Policies,
template <typename> class lA2AfieldL, template <typename> class lA2AfieldR,
template <typename> class rA2AfieldL, template <typename> class rA2AfieldR>
class multiply_M_r_singlescf_op: public SCFoperation<typename gsl_wrapper<typename mf_Policies::ScalarComplexType::value_type>::matrix_complex>{
typedef typename mf_Policies::ScalarComplexType ScalarComplexType;
typedef gsl_wrapper<typename ScalarComplexType::value_type> gw;
const int* work; //one for each thread
const int* off; //one for each thread
std::vector< std::vector<std::vector<ScalarComplexType> > > &Mr;
std::vector< std::vector<std::vector<ScalarComplexType> > > &rreord;
mult_vMv_split_v<mf_Policies,lA2AfieldL,lA2AfieldR,rA2AfieldL,rA2AfieldR,complex_double_or_float_mark> const* split_obj;
public:
multiply_M_r_singlescf_op(const int* _work, const int* _off, std::vector< std::vector<std::vector<ScalarComplexType> > > &_Mr, std::vector< std::vector<std::vector<ScalarComplexType> > > &_rreord,mult_vMv_split_v<mf_Policies,lA2AfieldL,lA2AfieldR,rA2AfieldL,rA2AfieldR,complex_double_or_float_mark> const* _split_obj): work(_work),off(_off),Mr(_Mr),rreord(_rreord),split_obj(_split_obj){}
void operator()(const typename gw::matrix_complex& M_packed, const int scf, const int rows, const int cols){
#pragma omp parallel
{
int me = omp_get_thread_num();
split_obj->multiply_M_r_singlescf(Mr,rreord,M_packed,off[me], work[me],scf);
}
}
};
template<typename mf_Policies,
template <typename> class lA2AfieldL, template <typename> class lA2AfieldR,
template <typename> class rA2AfieldL, template <typename> class rA2AfieldR
>
class mult_vMv_split_base{
protected:
typedef typename lA2AfieldL<mf_Policies>::DilutionType iLeftDilutionType;
typedef typename A2AmesonField<mf_Policies,lA2AfieldR,rA2AfieldL>::LeftDilutionType iRightDilutionType;
typedef typename A2AmesonField<mf_Policies,lA2AfieldR,rA2AfieldL>::RightDilutionType jLeftDilutionType;
typedef typename rA2AfieldR<mf_Policies>::DilutionType jRightDilutionType;
typedef typename mf_Policies::ScalarComplexType ScalarComplexType;
typedef typename mf_Policies::ComplexType ComplexType;
const static int nscf = 2*3*4;
//Mapping information
int ni[nscf], nj[nscf]; //mapping f+2*(c+3*s)
std::vector<int> ilmap[nscf], irmap[nscf];
std::vector<int> jlmap[nscf], jrmap[nscf];
std::vector< std::vector<std::pair<int,int> > > blocks_scf; //[scf] contiguous blocks of 'i' indices
//Info of the row packing
bool* rowidx_used;
int nrows_used; //number of packed rows in the output
const lA2AfieldL<mf_Policies> *lptr;
const A2AmesonField<mf_Policies,lA2AfieldR,rA2AfieldL> *Mptr;
const rA2AfieldR<mf_Policies> *rptr;
int top_glb;
int Mrows, Mcols;
mult_vMv_split_base():rowidx_used(NULL){}
void setup_base(const lA2AfieldL<mf_Policies> &l, const A2AmesonField<mf_Policies,lA2AfieldR,rA2AfieldL> &M, const rA2AfieldR<mf_Policies> &r, const int &_top_glb,
const ModeContractionIndices<iLeftDilutionType,iRightDilutionType> &i_ind, const ModeContractionIndices<jLeftDilutionType,jRightDilutionType>& j_ind){
lptr = &l; rptr = &r; Mptr = &M; top_glb = _top_glb;
modeIndexSet ilp, irp, jlp, jrp;
ilp.time = top_glb;
irp.time = M.getRowTimeslice();
jlp.time = M.getColTimeslice();
jrp.time = top_glb;
Mrows = M.getNrows();
Mcols = M.getNcols();
if(rowidx_used != NULL) free(rowidx_used);
rowidx_used = (bool*)malloc(Mrows*sizeof(bool)); //Is a particular row of M actually used?
for(int i=0;i<Mrows;i++) rowidx_used[i] = false;
//Store maps
for(int s=0;s<4;s++){
for(int c=0;c<3;c++){
int sc = c + 3*s;
ilp.spin_color = jrp.spin_color = sc;
for(int f=0;f<2;f++){
ilp.flavor = jrp.flavor = f;
int scf = f + 2*ilp.spin_color;
//i index
int ni_this = i_ind.getNindices(ilp,irp);
ni[scf] = ni_this;
std::vector<int> &ilmap_this = ilmap[scf]; ilmap_this.resize(ni_this);
std::vector<int> &irmap_this = irmap[scf]; irmap_this.resize(ni_this);
for(int i = 0; i < ni_this; i++){
i_ind.getBothIndices(ilmap_this[i],irmap_this[i],i,ilp,irp);
rowidx_used[ irmap_this[i] ] = true; //this row index is used
}
//j index
int nj_this = j_ind.getNindices(jlp,jrp);
nj[scf] = nj_this;
std::vector<int> &jlmap_this = jlmap[scf]; jlmap_this.resize(nj_this);
std::vector<int> &jrmap_this = jrmap[scf]; jrmap_this.resize(nj_this);
for(int j = 0; j < nj_this; j++)
j_ind.getBothIndices(jlmap_this[j],jrmap_this[j],j,jlp,jrp);
}
}
}
nrows_used = 0;
for(int i=0;i<Mrows;i++)
if(rowidx_used[i]) ++nrows_used;
//Get contiguous blocks of i indices
blocks_scf.resize(nscf);
for(int scfl=0;scfl<nscf;scfl++){
int ni_this = ni[scfl];
find_contiguous_blocks(blocks_scf[scfl],&irmap[scfl][0],ni_this);
}
}
template<typename MatrixVectorComplex>
void site_reorder_lr(MatrixVectorComplex &lreord, //[scf][reordered mode]
MatrixVectorComplex &rreord,
const bool conj_l, const bool conj_r, const int site4dop) const{
lreord.resize(nscf); rreord.resize(nscf);
for(int sc=0;sc<12;sc++){
for(int f=0;f<2;f++){
int scf = f + 2*sc;
//i index
int ni_this = this->ni[scf];
const std::vector<int> &ilmap_this = this->ilmap[scf];
lreord[scf].resize(ni_this);
for(int i = 0; i < ni_this; i++){
const ComplexType &lval_tmp = this->lptr->nativeElem(ilmap_this[i], site4dop, sc, f);
#ifndef MEMTEST_MODE
lreord[scf][i] = conj_l ? cconj(lval_tmp) : lval_tmp;
#endif
}
//j index
int nj_this = this->nj[scf];
const std::vector<int> &jrmap_this = this->jrmap[scf]; //jrmap_this.resize(nj_this);
rreord[scf].resize(nj_this);
for(int j = 0; j < nj_this; j++){
const ComplexType &rval_tmp = this->rptr->nativeElem(jrmap_this[j], site4dop, sc, f);
#ifndef MEMTEST_MODE
rreord[scf][j] = conj_r ? cconj(rval_tmp) : rval_tmp;
#endif
}
}
}
}
#define FREEIT(A) if(A != NULL){ free(A); A=NULL; }
void free_mem_base(){
FREEIT(rowidx_used);
}
~mult_vMv_split_base(){
FREEIT(rowidx_used);
}
};
//For local outer contraction of meson field by two vectors we can save a lot of time by column reordering the meson field to improve cache use.
//Save even more time by doing this outside the site loop (it makes no reference to the 3d position, only the time at which the vectors
//are evaluated)
template<typename mf_Policies,
template <typename> class lA2AfieldL, template <typename> class lA2AfieldR,
template <typename> class rA2AfieldL, template <typename> class rA2AfieldR
>
class mult_vMv_split_v<mf_Policies,lA2AfieldL,lA2AfieldR,rA2AfieldL,rA2AfieldR, complex_double_or_float_mark>: public mult_vMv_split_base<mf_Policies,lA2AfieldL,lA2AfieldR,rA2AfieldL,rA2AfieldR>{
typedef mult_vMv_split_base<mf_Policies,lA2AfieldL,lA2AfieldR,rA2AfieldL,rA2AfieldR> Base;
//Note:
//il is the index of l,
//ir is the row index of M,
//jl is the column index of M and
//jr is the index of r
typedef typename Base::ScalarComplexType ScalarComplexType;
typedef typename Base::iLeftDilutionType iLeftDilutionType;
typedef typename Base::iRightDilutionType iRightDilutionType;
typedef typename Base::jLeftDilutionType jLeftDilutionType;
typedef typename Base::jRightDilutionType jRightDilutionType;
typedef typename ScalarComplexType::value_type mf_Float;
//Packed matrices
typedef gsl_wrapper<mf_Float> gw;
const static int nscf = 2*3*4;
#ifdef VMV_SPLIT_MEM_SAVE
ScalarComplexType *mf_reord_lo_lo; //shared nl*nl submatrix
ScalarComplexType *mf_reord_lo_hi[nscf]; //the nl * nh[scf] submatrix
ScalarComplexType *mf_reord_hi_lo[nscf]; //the nh[scf] * nl submatrix
ScalarComplexType *mf_reord_hi_hi[nscf]; //the nh[scf] * nh[scf] submatrix
#else
std::vector<typename gw::matrix_complex*> mf_reord; //vector of gsl matrices in packed format where only the rows used are stored. One matrix for each spin/color/flavor combination of the vector r
#endif
std::vector<int> i_packed_unmap_all[nscf];
bool setup_called;
template<typename ,
template <typename> class, template <typename> class,
template <typename> class, template <typename> class>
friend class multiply_M_r_singlescf_op;
void constructPackedMloopSCF(SCFoperation<typename gw::matrix_complex> &op){
#ifdef VMV_SPLIT_MEM_SAVE
int nl_row = this->Mptr->getRowParams().getNl();
int nl_col = this->Mptr->getColParams().getNl();
int nj_max = 0;
bool nj_all_same = true;
for(int scf=0;scf<nscf;scf++){
if(this->nj[scf] > nj_max) nj_max = this->nj[scf];
if(this->nj[scf] != this->nj[0]) nj_all_same = false;
}
typename gw::matrix_complex* M_packed = gw::matrix_complex_alloc(this->nrows_used,nj_max); //use as buffer
if(nj_all_same) pokeSubmatrix<ScalarComplexType>( (ScalarComplexType*)M_packed->data, (const ScalarComplexType*)mf_reord_lo_lo, this->nrows_used, nj_max, 0, 0, nl_row, nl_col);
#endif
//M * r
for(int scf=0;scf<nscf;scf++){
int nj_this = this->nj[scf]; //vector size
#ifdef VMV_SPLIT_MEM_SAVE
int nh_row = this->nrows_used - nl_row;
int nh_col = nj_this - nl_col;
M_packed->size2 = nj_this;
if(!nj_all_same) pokeSubmatrix<ScalarComplexType>( (ScalarComplexType*)M_packed->data, (const ScalarComplexType*)mf_reord_lo_lo, this->nrows_used, nj_this, 0, 0, nl_row, nl_col);
pokeSubmatrix<ScalarComplexType>( (ScalarComplexType*)M_packed->data, (const ScalarComplexType*)mf_reord_lo_hi[scf], this->nrows_used, nj_this, 0, nl_col, nl_row, nh_col);
pokeSubmatrix<ScalarComplexType>( (ScalarComplexType*)M_packed->data, (const ScalarComplexType*)mf_reord_hi_lo[scf], this->nrows_used, nj_this, nl_row, 0, nh_row, nl_col);
pokeSubmatrix<ScalarComplexType>( (ScalarComplexType*)M_packed->data, (const ScalarComplexType*)mf_reord_hi_hi[scf], this->nrows_used, nj_this, nl_row, nl_col, nh_row, nh_col);
#else
typename gw::matrix_complex* M_packed = mf_reord[scf]; //scope for reuse here
#endif
op(*M_packed, scf, this->nrows_used, nj_this);
}
#ifdef VMV_SPLIT_MEM_SAVE
gw::matrix_complex_free(M_packed);
#endif
}
void multiply_M_r(std::vector<std::vector<ScalarComplexType> >& Mr, const std::vector<std::vector<ScalarComplexType> >& rreord) const{
multiply_M_r_op<ScalarComplexType> op(Mr, rreord, this->i_packed_unmap_all, this->nrows_used);
constructPackedMloopSCF(op);
}
//off is the 3d site offset for the start of the internal site loop, and work is the number of sites to iterate over
//M_packed is the Mesonfield in packed format.
void multiply_M_r_singlescf(std::vector<std::vector<std::vector<ScalarComplexType> > >& Mr, const std::vector<std::vector<std::vector<ScalarComplexType> > >& rreord,
const typename gw::matrix_complex & M_packed,
const int off, const int work, const int scf) const{
typename gw::vector_complex* Mr_packed = gw::vector_complex_alloc(this->nrows_used);
typename gw::complex one; GSL_SET_COMPLEX(&one,1.0,0.0);
typename gw::complex zero; GSL_SET_COMPLEX(&zero,0.0,0.0);
//M * r
int nj_this = this->nj[scf]; //vector size
const std::vector<int> &i_packed_unmap = this->i_packed_unmap_all[scf];
size_t block_width_max = M_packed.size2;
size_t block_height_max = 8; //4;
for(int j0=0; j0<M_packed.size2; j0+=block_width_max){ //columns on outer loop as GSL matrices are row major
int jblock_size = std::min(M_packed.size2 - j0, block_width_max);
for(int i0=0; i0<M_packed.size1; i0+=block_height_max){
int iblock_size = std::min(M_packed.size1 - i0, block_height_max);
//if(!me) printf("i0=%d j0=%d iblock_size=%d jblock_size=%d total rows=%d cols=%d\n",i0,j0,iblock_size,jblock_size,M_packed->size1,M_packed->size2);
typename gw::matrix_complex_const_view submatrix = gw::matrix_complex_const_submatrix(&M_packed, i0, j0, iblock_size, jblock_size);
for(int s=off;s<off+work;s++){
mf_Float* base = (mf_Float*)&rreord[s][scf][j0];
typename gw::block_complex_struct block;
block.data = base;
block.size = jblock_size;
typename gw::vector_complex rgsl;
rgsl.block = █
rgsl.data = base;
rgsl.stride = 1;
rgsl.owner = 1;
rgsl.size = jblock_size;
Mr_packed->size = iblock_size;
Mr_packed->block->size = iblock_size;
gw::blas_gemv(CblasNoTrans, one, &submatrix.matrix, &rgsl, zero, Mr_packed);
typename gw::complex tmp;
for(int i_packed=0;i_packed < iblock_size; i_packed++){
mf_Float(&tmp)[2] = reinterpret_cast<mf_Float(&)[2]>(Mr[s][scf][ i_packed_unmap[i0+i_packed] ]);
mf_Float *t = Mr_packed->data + 2*i_packed*Mr_packed->stride;
tmp[0] += *t++; tmp[1] += *t;
}
}
}
}
gw::vector_complex_free(Mr_packed);
}
void site_multiply_l_Mr(CPSspinColorFlavorMatrix<ScalarComplexType> &out,
const std::vector<std::vector<ScalarComplexType> > &lreord,
const std::vector<std::vector<ScalarComplexType> > &Mr,
typename gw::vector_complex* Mr_gsl_buffer) const{
//Vector vector multiplication l*(M*r)
for(int sl=0;sl<4;sl++){
for(int cl=0;cl<3;cl++){
for(int fl=0;fl<2;fl++){
int scfl = fl + 2*(cl + 3*sl);
int ni_this = this->ni[scfl];
mf_Float* base = (mf_Float*)&lreord[scfl][0];
typename gw::block_complex_struct block;
block.data = base;
block.size = ni_this;
typename gw::vector_complex lreord_gsl;
lreord_gsl.block = █
lreord_gsl.data = base;
lreord_gsl.stride = 1;
lreord_gsl.owner = 1;
lreord_gsl.size = ni_this;
const std::vector<std::pair<int,int> > &blocks = this->blocks_scf[scfl];
for(int sr=0;sr<4;sr++){
for(int cr=0;cr<3;cr++){
for(int fr=0;fr<2;fr++){
ScalarComplexType &into = out(sl,sr)(cl,cr)(fl,fr);
int scfr = fr + 2*(cr + 3*sr);
typename gw::vector_complex* Mr_gsl = Mr_gsl_buffer;
Mr_gsl->size = ni_this;
Mr_gsl->block->size = ni_this;
ScalarComplexType const* Mr_base = &Mr[scfr][0];
for(int b=0;b<blocks.size();b++){
ScalarComplexType const* block_ptr = Mr_base + this->irmap[scfl][blocks[b].first];
mf_Float *t = Mr_gsl->data + 2*blocks[b].first*Mr_gsl->stride;
memcpy((void*)t, (void*)block_ptr, 2*blocks[b].second*sizeof(mf_Float));
}
typename gw::complex dot;
gw::blas_dotu(&lreord_gsl, Mr_gsl, &dot);
reinterpret_cast<typename ScalarComplexType::value_type(&)[2]>(into)[0] = GSL_REAL(dot);
reinterpret_cast<typename ScalarComplexType::value_type(&)[2]>(into)[1] = GSL_IMAG(dot);
}
}
}
}
}
}
}
public:
mult_vMv_split_v(): setup_called(false){
#ifdef VMV_SPLIT_MEM_SAVE
mf_reord_lo_lo = NULL;
for(int scf=0;scf<nscf;scf++){
mf_reord_lo_hi[scf] = NULL;
mf_reord_hi_lo[scf] = NULL;
mf_reord_hi_hi[scf] = NULL;
}
#endif
}
void free_mem(){
this->free_mem_base();
#ifdef VMV_SPLIT_MEM_SAVE
FREEIT(mf_reord_lo_lo);
for(int scf=0;scf<nscf;scf++){
FREEIT(mf_reord_lo_hi[scf]);
FREEIT(mf_reord_hi_lo[scf]);
FREEIT(mf_reord_hi_hi[scf]);
}
#else
for(int i=0;i<mf_reord.size();i++) gw::matrix_complex_free(mf_reord[i]);
#endif
}
~mult_vMv_split_v(){
#ifdef VMV_SPLIT_MEM_SAVE
FREEIT(mf_reord_lo_lo);
for(int scf=0;scf<nscf;scf++){
FREEIT(mf_reord_lo_hi[scf]);
FREEIT(mf_reord_hi_lo[scf]);
FREEIT(mf_reord_hi_hi[scf]);
}
#else
for(int i=0;i<mf_reord.size();i++) gw::matrix_complex_free(mf_reord[i]);
#endif
}
//This should be called outside the site loop (and outside any parallel region)
//top_glb is the time in global lattice coordinates.
void setup(const lA2AfieldL<mf_Policies> &l, const A2AmesonField<mf_Policies,lA2AfieldR,rA2AfieldL> &M, const rA2AfieldR<mf_Policies> &r, const int &_top_glb){
//Precompute index mappings
ModeContractionIndices<iLeftDilutionType,iRightDilutionType> i_ind(l);
ModeContractionIndices<jLeftDilutionType,jRightDilutionType> j_ind(r);
setup(l,M,r,_top_glb,i_ind,j_ind);
}
void setup(const lA2AfieldL<mf_Policies> &l, const A2AmesonField<mf_Policies,lA2AfieldR,rA2AfieldL> &M, const rA2AfieldR<mf_Policies> &r, const int &_top_glb,
const ModeContractionIndices<iLeftDilutionType,iRightDilutionType> &i_ind, const ModeContractionIndices<jLeftDilutionType,jRightDilutionType>& j_ind){
setup_base(l,M,r,_top_glb,i_ind,j_ind);
//Use GSL BLAS
#ifndef VMV_SPLIT_MEM_SAVE
mf_reord.resize(nscf);
#endif
assert(sizeof(typename gw::complex) == sizeof(std::complex<mf_Float>) );
//Not all rows or columns of M are used, so lets use a packed matrix
for(int scf=0;scf<nscf;scf++){
int nj_this = this->nj[scf];
std::vector<int> &jlmap_this = this->jlmap[scf];
typename gw::matrix_complex* mf_scf_reord = M.GSLpackedColReorder(&jlmap_this.front(), nj_this, this->rowidx_used); //packs the GSL matrix
#ifdef VMV_SPLIT_MEM_SAVE
int nl_row = M.getRowParams().getNl();
int nl_col = M.getColParams().getNl();
int nh_row = this->nrows_used - nl_row;
int nh_col = nj_this - nl_col;
if(scf == 0){
mf_reord_lo_lo = (ScalarComplexType*)malloc(nl_row*nl_col*sizeof(ScalarComplexType));
getSubmatrix<ScalarComplexType >(mf_reord_lo_lo, (const ScalarComplexType*)mf_scf_reord->data, this->nrows_used, nj_this, 0, 0, nl_row, nl_col);
}
mf_reord_lo_hi[scf] = (ScalarComplexType*)malloc(nl_row*nh_col*sizeof(ScalarComplexType));
getSubmatrix<ScalarComplexType >(mf_reord_lo_hi[scf], (const ScalarComplexType*)mf_scf_reord->data, this->nrows_used, nj_this, 0, nl_col, nl_row, nh_col);
mf_reord_hi_lo[scf] = (ScalarComplexType*)malloc(nh_row*nl_col*sizeof(ScalarComplexType));
getSubmatrix<ScalarComplexType >(mf_reord_hi_lo[scf], (const ScalarComplexType*)mf_scf_reord->data, this->nrows_used, nj_this, nl_row, 0, nh_row, nl_col);
mf_reord_hi_hi[scf] = (ScalarComplexType*)malloc(nh_row*nh_col*sizeof(ScalarComplexType));
getSubmatrix<ScalarComplexType >(mf_reord_hi_hi[scf], (const ScalarComplexType*)mf_scf_reord->data, this->nrows_used, nj_this, nl_row, nl_col, nh_row, nh_col);
gw::matrix_complex_free(mf_scf_reord);
#else
mf_reord[scf] = mf_scf_reord;
#endif
//Store the map between packed and full indices
int i_packed = 0;
i_packed_unmap_all[scf].resize(this->nrows_used);
for(int i_full=0;i_full<this->Mrows;i_full++)
if(this->rowidx_used[i_full]) i_packed_unmap_all[scf][i_packed++] = i_full;
}
setup_called = true;
}
public:
//Contract on all 3d sites on this node with fixed operator time coord top_glb into a canonically ordered output vector
void contract(std::vector<CPSspinColorFlavorMatrix<ScalarComplexType>> &out, const bool conj_l, const bool conj_r) const{
int top = this->top_glb - GJP.TnodeSites()*GJP.TnodeCoor();
assert(top >= 0 && top < GJP.TnodeSites()); //make sure you use this method on the appropriate node!
int sites_3d = GJP.VolNodeSites()/GJP.TnodeSites();
out.resize(sites_3d);
std::vector< std::vector<std::vector<ScalarComplexType> > > lreord(sites_3d); //[3d site][scf][reordered mode]
std::vector< std::vector<std::vector<ScalarComplexType> > > rreord(sites_3d);
assert(sizeof(typename gw::complex) == sizeof(std::complex<mf_Float>) );
typedef gsl_wrapper<mf_Float> gw;
std::vector< std::vector<std::vector<ScalarComplexType> > > Mr(sites_3d); //[3d site][scf][M row]
//Run everything in parallel environment to avoid thread creation overheads
int work[omp_get_max_threads()], off[omp_get_max_threads()];
#pragma omp parallel
{
int me = omp_get_thread_num();
int team = omp_get_num_threads();
//Reorder rows and columns of left and right fields such that they can be accessed sequentially
thread_work(work[me], off[me], sites_3d, me, team);
for(int s=off[me];s<off[me]+work[me];s++){
int site4dop = s + sites_3d*top;
site_reorder_lr(lreord[s],rreord[s],conj_l,conj_r,site4dop);
}
for(int s=off[me];s<off[me]+work[me];s++){
Mr[s].resize(nscf);
for(int scf=0;scf<nscf;scf++){
Mr[s][scf].resize(this->Mrows);
for(int i=0;i<this->Mrows;i++)
Mr[s][scf][i] = 0.0;
}
}
}
multiply_M_r_singlescf_op<mf_Policies,lA2AfieldL,lA2AfieldR,rA2AfieldL,rA2AfieldR> op(work,off,Mr,rreord,this);
constructPackedMloopSCF(op);
#pragma omp parallel
{
int me = omp_get_thread_num();
//M * r
//multiply_M_r(&Mr[0],&rreord[0],off,work);
//Vector vector multiplication l*(M*r)
typename gw::vector_complex* Mr_gsl_buffer = gw::vector_complex_alloc(this->Mrows);
for(int x3d=off[me];x3d<off[me]+work[me];x3d++)
site_multiply_l_Mr(out[x3d], lreord[x3d], Mr[x3d], Mr_gsl_buffer);
gw::vector_complex_free(Mr_gsl_buffer);
} //end of parallel region
}//end of method
//Run inside a threaded/parallelized loop over 3d sites. xop is a 3d coordinate!
void contract(CPSspinColorFlavorMatrix<ScalarComplexType> &out, const int &xop, const bool &conj_l, const bool &conj_r) const{
int top = this->top_glb - GJP.TnodeSites()*GJP.TnodeCoor();
assert(top >= 0 && top < GJP.TnodeSites()); //make sure you use this method on the appropriate node!
std::vector<std::vector<ScalarComplexType > > lreord; //[scf][reordered mode]
std::vector<std::vector<ScalarComplexType > > rreord;
assert(sizeof(typename gw::complex) == sizeof(ScalarComplexType) );
typedef gsl_wrapper<mf_Float> gw;
std::vector<std::vector<ScalarComplexType > > Mr(nscf); //[scf][M row]
for(int scf=0;scf<nscf;scf++){
Mr[scf].resize(this->Mrows);
for(int i=0;i<this->Mrows;i++)
Mr[scf][i] = 0.0;
}
int sites_3d = GJP.VolNodeSites()/GJP.TnodeSites();
int site4dop = xop + sites_3d*top;
site_reorder_lr(lreord,rreord,conj_l,conj_r,site4dop);
//M * r
multiply_M_r(Mr,rreord);
//Vector vector multiplication l*(M*r)
typename gw::vector_complex* Mr_gsl_buffer = gw::vector_complex_alloc(this->Mrows);
site_multiply_l_Mr(out, lreord, Mr, Mr_gsl_buffer);
gw::vector_complex_free(Mr_gsl_buffer);
}
};
#endif
|
mttkrp.c | /*
This file is part of ParTI!.
ParTI! 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 3 of
the License, or (at your option) any later version.
ParTI! 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 Lesser General Public
License along with ParTI!.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <HiParTI.h>
#include "hicoo.h"
int ptiMTTKRPHiCOO_3D(
ptiSparseTensorHiCOO const * const hitsr,
ptiMatrix * mats[], // mats[nmodes] as temporary space.
ptiIndex const mats_order[], // Correspond to the mode order of X.
ptiIndex const mode);
int ptiMTTKRPHiCOO_3D_Blocked(
ptiSparseTensorHiCOO const * const hitsr,
ptiMatrix * mats[], // mats[nmodes] as temporary space.
ptiIndex const mats_order[], // Correspond to the mode order of X.
ptiIndex const mode);
int ptiMTTKRPHiCOO_3D_MatrixTiling(
ptiSparseTensorHiCOO const * const hitsr,
ptiRankMatrix * mats[], // mats[nmodes] as temporary space.
ptiIndex const mats_order[], // Correspond to the mode order of X.
ptiIndex const mode);
int ptiMTTKRPHiCOO_4D_MatrixTiling(
ptiSparseTensorHiCOO const * const hitsr,
ptiRankMatrix * mats[], // mats[nmodes] as temporary space.
ptiIndex const mats_order[], // Correspond to the mode order of X.
ptiIndex const mode);
int ptiMTTKRPHiCOO_3D_MatrixTiling_init(
ptiSparseTensorHiCOO const * const hitsr,
ptiMatrix * mats[], // mats[nmodes] as temporary space.
ptiIndex const mats_order[], // Correspond to the mode order of X.
ptiIndex const mode);
/**
* Matriced sparse tensor in HiCOO format times a sequence of dense matrix Khatri-Rao products (MTTKRP) on a specified mode
* @param[out] mats[nmodes] the result of MTTKRP, a dense matrix, with size
* ndims[mode] * R
* @param[in] hitsr the HiCOO sparse tensor input
* @param[in] mats (N+1) dense matrices, with mats[nmodes] as temporary
* @param[in] mats_order the order of the Khatri-Rao products
* @param[in] mode the mode on which the MTTKRP is performed
* @param[in] scratch an temporary array to store intermediate results, space assigned before this function
*
* This function uses support arbitrary-order sparse tensors with Khatri-Rao
* products of dense factor matrices, the output is the updated dense matrix for the "mode".
*/
int ptiMTTKRPHiCOO(
ptiSparseTensorHiCOO const * const hitsr,
ptiMatrix * mats[], // mats[nmodes] as temporary space.
ptiIndex const mats_order[], // Correspond to the mode order of X.
ptiIndex const mode)
{
ptiIndex const nmodes = hitsr->nmodes;
if(nmodes == 3) {
ptiAssert(ptiMTTKRPHiCOO_3D_Blocked(hitsr, mats, mats_order, mode) == 0);
return 0;
}
ptiIndex const * const ndims = hitsr->ndims;
ptiValue const * const restrict vals = hitsr->values.data;
ptiIndex const stride = mats[0]->stride;
ptiValueVector scratch; // Temporary array
/* Check the mats. */
for(ptiIndex i=0; i<nmodes; ++i) {
if(mats[i]->ncols != mats[nmodes]->ncols) {
pti_CheckError(PTIERR_SHAPE_MISMATCH, "CPU HiCOO SpTns MTTKRP", "mats[i]->cols != mats[nmodes]->ncols");
}
if(mats[i]->nrows != ndims[i]) {
pti_CheckError(PTIERR_SHAPE_MISMATCH, "CPU HiCOO SpTns MTTKRP", "mats[i]->nrows != ndims[i]");
}
}
ptiIndex const tmpI = mats[mode]->nrows;
ptiIndex const R = mats[mode]->ncols;
ptiMatrix * const restrict M = mats[nmodes];
ptiValue * const restrict mvals = M->values;
memset(mvals, 0, tmpI*stride*sizeof(*mvals));
ptiNewValueVector(&scratch, R, R);
ptiIndex * block_coord = (ptiIndex*)malloc(nmodes * sizeof(*block_coord));
ptiIndex * ele_coord = (ptiIndex*)malloc(nmodes * sizeof(*ele_coord));
/* Loop kernels */
for(ptiIndex k=0; k<hitsr->kptr.len - 1; ++k) {
ptiNnzIndex kptr_begin = hitsr->kptr.data[k];
ptiNnzIndex kptr_end = hitsr->kptr.data[k+1];
/* Loop blocks in a kernel */
for(ptiIndex b=kptr_begin; b<kptr_end; ++b) {
/* Block indices */
for(ptiIndex m=0; m<nmodes; ++m)
block_coord[m] = hitsr->binds[m].data[b];
ptiNnzIndex bptr_begin = hitsr->bptr.data[b];
ptiNnzIndex bptr_end = hitsr->bptr.data[b+1];
/* Loop entries in a block */
for(ptiIndex z=bptr_begin; z<bptr_end; ++z) {
/* Element indices */
for(ptiIndex m=0; m<nmodes; ++m)
ele_coord[m] = (block_coord[m] << hitsr->sb_bits) + hitsr->einds[m].data[z];
/* Multiply the 1st matrix */
ptiIndex times_mat_index = mats_order[1];
ptiMatrix * times_mat = mats[times_mat_index];
ptiIndex tmp_i = ele_coord[times_mat_index];
ptiValue const entry = vals[z];
for(ptiIndex r=0; r<R; ++r) {
scratch.data[r] = entry * times_mat->values[tmp_i * stride + r];
}
/* Multiply the rest matrices */
for(ptiIndex m=2; m<nmodes; ++m) {
times_mat_index = mats_order[m];
times_mat = mats[times_mat_index];
tmp_i = ele_coord[times_mat_index];
for(ptiIndex r=0; r<R; ++r) {
scratch.data[r] *= times_mat->values[tmp_i * stride + r];
}
}
ptiIndex const mode_i = ele_coord[mode];
for(ptiIndex r=0; r<R; ++r) {
mvals[mode_i * stride + r] += scratch.data[r];
}
} // End loop entries
} // End loop blocks
} // End loop kernels
free(block_coord);
free(ele_coord);
ptiFreeValueVector(&scratch);
return 0;
}
/* Very slow version! Slower than COO in Morton order. */
int ptiMTTKRPHiCOO_3D(
ptiSparseTensorHiCOO const * const hitsr,
ptiMatrix * mats[], // mats[nmodes] as temporary space.
ptiIndex const mats_order[], // Correspond to the mode order of X.
ptiIndex const mode)
{
ptiIndex const nmodes = hitsr->nmodes;
ptiIndex const * const ndims = hitsr->ndims;
ptiValue const * const restrict vals = hitsr->values.data;
ptiIndex const stride = mats[0]->stride;
/* Check the mats. */
ptiAssert(nmodes ==3);
for(ptiIndex i=0; i<nmodes; ++i) {
if(mats[i]->ncols != mats[nmodes]->ncols) {
pti_CheckError(PTIERR_SHAPE_MISMATCH, "CPU HiCOO SpTns MTTKRP", "mats[i]->cols != mats[nmodes]->ncols");
}
if(mats[i]->nrows != ndims[i]) {
pti_CheckError(PTIERR_SHAPE_MISMATCH, "CPU HiCOO SpTns MTTKRP", "mats[i]->nrows != ndims[i]");
}
}
ptiIndex const tmpI = mats[mode]->nrows;
ptiIndex const R = mats[mode]->ncols;
ptiMatrix * const restrict M = mats[nmodes];
ptiValue * const restrict mvals = M->values;
memset(mvals, 0, tmpI*stride*sizeof(*mvals));
ptiIndex times_mat_index_1 = mats_order[1];
ptiMatrix * restrict times_mat_1 = mats[times_mat_index_1];
ptiIndex times_mat_index_2 = mats_order[2];
ptiMatrix * restrict times_mat_2 = mats[times_mat_index_2];
/* block_coord is reused, no need to store ele_coord for 3D tensors */
ptiBlockIndex * block_coord = (ptiBlockIndex*)malloc(nmodes * sizeof(*block_coord));
ptiIndex mode_i;
ptiIndex tmp_i_1, tmp_i_2;
ptiValue entry;
/* Loop kernels */
for(ptiIndex k=0; k<hitsr->kptr.len - 1; ++k) {
ptiNnzIndex kptr_begin = hitsr->kptr.data[k];
ptiNnzIndex kptr_end = hitsr->kptr.data[k+1];
/* Loop blocks in a kernel */
for(ptiIndex b=kptr_begin; b<kptr_end; ++b) {
/* Block indices */
for(ptiIndex m=0; m<nmodes; ++m)
block_coord[m] = hitsr->binds[m].data[b];
ptiNnzIndex bptr_begin = hitsr->bptr.data[b];
ptiNnzIndex bptr_end = hitsr->bptr.data[b+1];
/* Loop entries in a block */
for(ptiIndex z=bptr_begin; z<bptr_end; ++z) {
mode_i = (block_coord[mode] << hitsr->sb_bits) + hitsr->einds[mode].data[z];
tmp_i_1 = (block_coord[times_mat_index_1] << hitsr->sb_bits) + hitsr->einds[times_mat_index_1].data[z];
tmp_i_2 = (block_coord[times_mat_index_2] << hitsr->sb_bits) + hitsr->einds[times_mat_index_2].data[z];
entry = vals[z];
for(ptiIndex r=0; r<R; ++r) {
mvals[mode_i * stride + r] += entry * times_mat_1->values[tmp_i_1 * stride + r] * times_mat_2->values[tmp_i_2 * stride + r];
}
} // End loop entries
} // End loop blocks
} // End loop kernels
free(block_coord);
return 0;
}
int ptiMTTKRPHiCOO_3D_Blocked(
ptiSparseTensorHiCOO const * const hitsr,
ptiMatrix * mats[], // mats[nmodes] as temporary space.
ptiIndex const mats_order[], // Correspond to the mode order of X.
ptiIndex const mode)
{
ptiIndex const nmodes = hitsr->nmodes;
ptiIndex const * const ndims = hitsr->ndims;
ptiValue const * const restrict vals = hitsr->values.data;
ptiIndex const stride = mats[0]->stride;
/* Check the mats. */
ptiAssert(nmodes ==3);
for(ptiIndex i=0; i<nmodes; ++i) {
if(mats[i]->ncols != mats[nmodes]->ncols) {
pti_CheckError(PTIERR_SHAPE_MISMATCH, "CPU HiCOO SpTns MTTKRP", "mats[i]->cols != mats[nmodes]->ncols");
}
if(mats[i]->nrows != ndims[i]) {
pti_CheckError(PTIERR_SHAPE_MISMATCH, "CPU HiCOO SpTns MTTKRP", "mats[i]->nrows != ndims[i]");
}
}
ptiIndex const tmpI = mats[mode]->nrows;
ptiIndex const R = mats[mode]->ncols;
ptiMatrix * const restrict M = mats[nmodes];
ptiValue * const restrict mvals = M->values;
memset(mvals, 0, tmpI*stride*sizeof(*mvals));
ptiIndex times_mat_index_1 = mats_order[1];
ptiMatrix * restrict times_mat_1 = mats[times_mat_index_1];
ptiIndex times_mat_index_2 = mats_order[2];
ptiMatrix * restrict times_mat_2 = mats[times_mat_index_2];
ptiElementIndex mode_i;
ptiElementIndex tmp_i_1, tmp_i_2;
ptiValue entry;
ptiValue * restrict blocked_mvals;
ptiValue * restrict blocked_times_mat_1;
ptiValue * restrict blocked_times_mat_2;
/* Loop kernels */
for(ptiIndex k=0; k<hitsr->kptr.len - 1; ++k) {
ptiNnzIndex kptr_begin = hitsr->kptr.data[k];
ptiNnzIndex kptr_end = hitsr->kptr.data[k+1];
/* Loop blocks in a kernel */
for(ptiIndex b=kptr_begin; b<kptr_end; ++b) {
blocked_mvals = mvals + (hitsr->binds[mode].data[b] << hitsr->sb_bits) * stride;
blocked_times_mat_1 = times_mat_1->values + (hitsr->binds[times_mat_index_1].data[b] << hitsr->sb_bits) * stride;
blocked_times_mat_2 = times_mat_2->values + (hitsr->binds[times_mat_index_2].data[b] << hitsr->sb_bits) * stride;
ptiNnzIndex bptr_begin = hitsr->bptr.data[b];
ptiNnzIndex bptr_end = hitsr->bptr.data[b+1];
/* Loop entries in a block */
for(ptiIndex z=bptr_begin; z<bptr_end; ++z) {
mode_i = hitsr->einds[mode].data[z];
tmp_i_1 = hitsr->einds[times_mat_index_1].data[z];
tmp_i_2 = hitsr->einds[times_mat_index_2].data[z];
entry = vals[z];
ptiValue * const restrict bmvals_row = blocked_mvals + mode_i * stride;
ptiValue * const restrict blocked_times_mat_1_row = blocked_times_mat_1 + tmp_i_1 * stride;
ptiValue * const restrict blocked_times_mat_2_row = blocked_times_mat_2 + tmp_i_2 * stride;
for(ptiIndex r=0; r<R; ++r) {
bmvals_row[r] += entry *
blocked_times_mat_1_row[r]
* blocked_times_mat_2_row[r];
}
} // End loop entries
} // End loop blocks
} // End loop kernels
return 0;
}
int ptiMTTKRPHiCOO_MatrixTiling(
ptiSparseTensorHiCOO const * const hitsr,
ptiRankMatrix * mats[], // mats[nmodes] as temporary space.
ptiIndex const mats_order[], // Correspond to the mode order of X.
ptiIndex const mode)
{
ptiIndex const nmodes = hitsr->nmodes;
if(nmodes == 3) {
ptiAssert(ptiMTTKRPHiCOO_3D_MatrixTiling(hitsr, mats, mats_order, mode) == 0);
return 0;
}
// else if(nmodes == 4) {
// ptiAssert(ptiMTTKRPHiCOO_4D_MatrixTiling(hitsr, mats, mats_order, mode) == 0);
// return 0;
// }
ptiIndex const * const ndims = hitsr->ndims;
ptiValue const * const restrict vals = hitsr->values.data;
ptiElementIndex const stride = mats[0]->stride;
ptiValueVector scratch; // Temporary array
/* Check the mats. */
for(ptiIndex i=0; i<nmodes; ++i) {
if(mats[i]->ncols != mats[nmodes]->ncols) {
pti_CheckError(PTIERR_SHAPE_MISMATCH, "CPU HiCOO SpTns MTTKRP", "mats[i]->cols != mats[nmodes]->ncols");
}
if(mats[i]->nrows != ndims[i]) {
pti_CheckError(PTIERR_SHAPE_MISMATCH, "CPU HiCOO SpTns MTTKRP", "mats[i]->nrows != ndims[i]");
}
}
ptiIndex const tmpI = mats[mode]->nrows;
ptiElementIndex const R = mats[mode]->ncols;
ptiRankMatrix * const restrict M = mats[nmodes];
ptiValue * const restrict mvals = M->values;
memset(mvals, 0, tmpI*stride*sizeof(*mvals));
ptiNewValueVector(&scratch, R, R);
ptiValue ** blocked_times_mat = (ptiValue**)malloc(nmodes * sizeof(*blocked_times_mat));
/* Loop kernels */
for(ptiIndex k=0; k<hitsr->kptr.len - 1; ++k) {
ptiNnzIndex kptr_begin = hitsr->kptr.data[k];
ptiNnzIndex kptr_end = hitsr->kptr.data[k+1];
/* Loop blocks in a kernel */
for(ptiIndex b=kptr_begin; b<kptr_end; ++b) {
/* Block indices */
for(ptiIndex m=0; m<nmodes; ++m)
blocked_times_mat[m] = mats[m]->values + (hitsr->binds[m].data[b] << hitsr->sb_bits) * stride;
ptiValue * blocked_mvals = mvals + (hitsr->binds[mode].data[b] << hitsr->sb_bits) * stride;
ptiNnzIndex bptr_begin = hitsr->bptr.data[b];
ptiNnzIndex bptr_end = hitsr->bptr.data[b+1];
/* Loop entries in a block */
for(ptiIndex z=bptr_begin; z<bptr_end; ++z) {
/* Multiply the 1st matrix */
ptiIndex times_mat_index = mats_order[1];
ptiElementIndex tmp_i = hitsr->einds[times_mat_index].data[z];
ptiValue const entry = vals[z];
#pragma omp simd
for(ptiElementIndex r=0; r<R; ++r) {
scratch.data[r] = entry * blocked_times_mat[times_mat_index][(ptiBlockMatrixIndex)tmp_i * stride + r];
}
/* Multiply the rest matrices */
for(ptiIndex m=2; m<nmodes; ++m) {
times_mat_index = mats_order[m];
tmp_i = hitsr->einds[times_mat_index].data[z];
#pragma omp simd
for(ptiElementIndex r=0; r<R; ++r) {
scratch.data[r] *= blocked_times_mat[times_mat_index][(ptiBlockMatrixIndex)tmp_i * stride + r];
}
}
ptiElementIndex const mode_i = hitsr->einds[mode].data[z];
#pragma omp simd
for(ptiElementIndex r=0; r<R; ++r) {
blocked_mvals[(ptiBlockMatrixIndex)mode_i * stride + r] += scratch.data[r];
}
} // End loop entries
} // End loop blocks
} // End loop kernels
free(blocked_times_mat);
ptiFreeValueVector(&scratch);
return 0;
}
int ptiMTTKRPHiCOO_3D_MatrixTiling(
ptiSparseTensorHiCOO const * const hitsr,
ptiRankMatrix * mats[], // mats[nmodes] as temporary space.
ptiIndex const mats_order[], // Correspond to the mode order of X.
ptiIndex const mode)
{
ptiIndex const nmodes = hitsr->nmodes;
ptiIndex const * const ndims = hitsr->ndims;
ptiValue const * const restrict vals = hitsr->values.data;
ptiElementIndex const stride = mats[0]->stride;
/* Check the mats. */
ptiAssert(nmodes ==3);
for(ptiIndex i=0; i<nmodes; ++i) {
if(mats[i]->ncols != mats[nmodes]->ncols) {
pti_CheckError(PTIERR_SHAPE_MISMATCH, "CPU HiCOO SpTns MTTKRP", "mats[i]->cols != mats[nmodes]->ncols");
}
if(mats[i]->nrows != ndims[i]) {
pti_CheckError(PTIERR_SHAPE_MISMATCH, "CPU HiCOO SpTns MTTKRP", "mats[i]->nrows != ndims[i]");
}
}
ptiIndex const tmpI = mats[mode]->nrows;
ptiElementIndex const R = mats[mode]->ncols;
ptiRankMatrix * const restrict M = mats[nmodes];
ptiValue * const restrict mvals = M->values;
memset(mvals, 0, tmpI*stride*sizeof(*mvals));
ptiIndex times_mat_index_1 = mats_order[1];
ptiRankMatrix * restrict times_mat_1 = mats[times_mat_index_1];
ptiIndex times_mat_index_2 = mats_order[2];
ptiRankMatrix * restrict times_mat_2 = mats[times_mat_index_2];
ptiElementIndex mode_i;
ptiElementIndex tmp_i_1, tmp_i_2;
ptiValue entry;
ptiValue * restrict blocked_mvals;
ptiValue * restrict blocked_times_mat_1;
ptiValue * restrict blocked_times_mat_2;
/* Loop kernels */
// ptiTimer loop_timer, kernel_timer, block_timer, element_timer, elementmat_timer, blockmat_timer;
// double loop_etime = 0, kernel_etime = 0, block_etime = 0, element_etime = 0, elementmat_etime = 0, blockmat_etime = 0;
// ptiNewTimer(&loop_timer, 0);
// ptiNewTimer(&kernel_timer, 0);
// ptiNewTimer(&block_timer, 0);
// ptiNewTimer(&element_timer, 0);
// ptiNewTimer(&elementmat_timer, 0);
// ptiNewTimer(&blockmat_timer, 0);
// ptiStartTimer(loop_timer);
for(ptiIndex k=0; k<hitsr->kptr.len - 1; ++k) {
ptiNnzIndex kptr_begin = hitsr->kptr.data[k];
ptiNnzIndex kptr_end = hitsr->kptr.data[k+1];
/* Loop blocks in a kernel */
// printf("kptr_begin: %"HIPARTI_PRI_NNZ_INDEX", kptr_end: %"HIPARTI_PRI_NNZ_INDEX"\n", kptr_begin, kptr_end);
// ptiStartTimer(kernel_timer);
for(ptiIndex b=kptr_begin; b<kptr_end; ++b) {
// ptiStartTimer(blockmat_timer);
blocked_mvals = mvals + (hitsr->binds[mode].data[b] << hitsr->sb_bits) * stride;
blocked_times_mat_1 = times_mat_1->values + (hitsr->binds[times_mat_index_1].data[b] << hitsr->sb_bits) * stride;
blocked_times_mat_2 = times_mat_2->values + (hitsr->binds[times_mat_index_2].data[b] << hitsr->sb_bits) * stride;
ptiNnzIndex bptr_begin = hitsr->bptr.data[b];
ptiNnzIndex bptr_end = hitsr->bptr.data[b+1];
// ptiStopTimer(blockmat_timer);
// blockmat_etime += ptiElapsedTime(blockmat_timer);
// ptiPrintElapsedTime(blockmat_timer, "===Blockmat Timer");
/* Loop entries in a block */
// printf("bptr_begin: %"HIPARTI_PRI_INDEX", bptr_end: %"HIPARTI_PRI_INDEX"\n", bptr_begin, bptr_end);
// ptiStartTimer(block_timer);
for(ptiIndex z=bptr_begin; z<bptr_end; ++z) {
// ptiStartTimer(elementmat_timer);
mode_i = hitsr->einds[mode].data[z];
tmp_i_1 = hitsr->einds[times_mat_index_1].data[z];
tmp_i_2 = hitsr->einds[times_mat_index_2].data[z];
// mode_i = (ptiBlockMatrixIndex)hitsr->einds[mode].data[z];
// tmp_i_1 = (ptiBlockMatrixIndex)hitsr->einds[times_mat_index_1].data[z];
// tmp_i_2 = (ptiBlockMatrixIndex)hitsr->einds[times_mat_index_2].data[z];
entry = vals[z];
ptiValue * const restrict bmvals_row = blocked_mvals + mode_i * stride;
ptiValue * const restrict blocked_times_mat_1_row = blocked_times_mat_1 + tmp_i_1 * stride;
ptiValue * const restrict blocked_times_mat_2_row = blocked_times_mat_2 + tmp_i_2 * stride;
// ptiStopTimer(elementmat_timer);
// elementmat_etime += ptiElapsedTime(elementmat_timer);
// ptiPrintElapsedTime(elementmat_timer, "===Elementmat Timer");
// ptiStartTimer(element_timer);
#pragma omp simd
for(ptiElementIndex r=0; r<R; ++r) {
// blocked_mvals[mode_i * stride + r] += entry *
// blocked_times_mat_1[tmp_i_1 * stride + r] *
// blocked_times_mat_2[tmp_i_2 * stride + r];
bmvals_row[r] += entry *
blocked_times_mat_1_row[r]
* blocked_times_mat_2_row[r];
}
// ptiStopTimer(element_timer);
// element_etime += ptiElapsedTime(element_timer);
// ptiPrintElapsedTime(element_timer, "===Element Timer");
} // End loop entries
// ptiStopTimer(block_timer);
// block_etime += ptiElapsedTime(block_timer);
// ptiPrintElapsedTime(block_timer, "==Block Timer");
} // End loop blocks
// ptiStopTimer(kernel_timer);
// kernel_etime += ptiElapsedTime(kernel_timer);
// ptiPrintElapsedTime(kernel_timer, "=Kernel Timer");
} // End loop kernels
// ptiStopTimer(loop_timer);
// loop_etime += ptiElapsedTime(loop_timer);
// ptiPrintElapsedTime(loop_timer, "=Loop Timer");
// printf("\nTotal Elementmat Time: %lf\n", elementmat_etime);
// printf("Total Element Time: %lf\n", element_etime);
// printf("Total Blockmat Time: %lf\n", blockmat_etime);
// printf("Total Block Time: %lf\n", block_etime);
// printf("Total Kernel Time: %lf\n", kernel_etime);
// printf("Total Loop Time: %lf\n\n", loop_etime);
// ptiFreeTimer(loop_timer);
// ptiFreeTimer(kernel_timer);
// ptiFreeTimer(block_timer);
// ptiFreeTimer(element_timer);
// ptiFreeTimer(elementmat_timer);
// ptiFreeTimer(blockmat_timer);
return 0;
}
int ptiMTTKRPHiCOO_4D_MatrixTiling(
ptiSparseTensorHiCOO const * const hitsr,
ptiRankMatrix * mats[], // mats[nmodes] as temporary space.
ptiIndex const mats_order[], // Correspond to the mode order of X.
ptiIndex const mode)
{
ptiIndex const nmodes = hitsr->nmodes;
ptiIndex const * const ndims = hitsr->ndims;
ptiValue const * const restrict vals = hitsr->values.data;
ptiElementIndex const stride = mats[0]->stride;
/* Check the mats. */
ptiAssert(nmodes == 4);
for(ptiIndex i=0; i<nmodes; ++i) {
if(mats[i]->ncols != mats[nmodes]->ncols) {
pti_CheckError(PTIERR_SHAPE_MISMATCH, "CPU HiCOO SpTns MTTKRP", "mats[i]->cols != mats[nmodes]->ncols");
}
if(mats[i]->nrows != ndims[i]) {
pti_CheckError(PTIERR_SHAPE_MISMATCH, "CPU HiCOO SpTns MTTKRP", "mats[i]->nrows != ndims[i]");
}
}
ptiIndex const tmpI = mats[mode]->nrows;
ptiElementIndex const R = mats[mode]->ncols;
ptiRankMatrix * const restrict M = mats[nmodes];
ptiValue * const restrict mvals = M->values;
memset(mvals, 0, tmpI*stride*sizeof(*mvals));
ptiIndex times_mat_index_1 = mats_order[1];
ptiRankMatrix * restrict times_mat_1 = mats[times_mat_index_1];
ptiIndex times_mat_index_2 = mats_order[2];
ptiRankMatrix * restrict times_mat_2 = mats[times_mat_index_2];
ptiIndex times_mat_index_3 = mats_order[3];
ptiRankMatrix * restrict times_mat_3 = mats[times_mat_index_3];
ptiElementIndex mode_i;
ptiElementIndex tmp_i_1, tmp_i_2, tmp_i_3;
ptiValue entry;
ptiValue * restrict blocked_mvals;
ptiValue * restrict blocked_times_mat_1;
ptiValue * restrict blocked_times_mat_2;
ptiValue * restrict blocked_times_mat_3;
/* Loop kernels */
// ptiTimer loop_timer, kernel_timer, block_timer, element_timer, elementmat_timer, blockmat_timer;
// double loop_etime = 0, kernel_etime = 0, block_etime = 0, element_etime = 0, elementmat_etime = 0, blockmat_etime = 0;
// ptiNewTimer(&loop_timer, 0);
// ptiNewTimer(&kernel_timer, 0);
// ptiNewTimer(&block_timer, 0);
// ptiNewTimer(&element_timer, 0);
// ptiNewTimer(&elementmat_timer, 0);
// ptiNewTimer(&blockmat_timer, 0);
// ptiStartTimer(loop_timer);
for(ptiIndex k=0; k<hitsr->kptr.len - 1; ++k) {
ptiNnzIndex kptr_begin = hitsr->kptr.data[k];
ptiNnzIndex kptr_end = hitsr->kptr.data[k+1];
/* Loop blocks in a kernel */
// printf("kptr_begin: %"HIPARTI_PRI_NNZ_INDEX", kptr_end: %"HIPARTI_PRI_NNZ_INDEX"\n", kptr_begin, kptr_end);
// ptiStartTimer(kernel_timer);
for(ptiIndex b=kptr_begin; b<kptr_end; ++b) {
// ptiStartTimer(blockmat_timer);
blocked_mvals = mvals + (hitsr->binds[mode].data[b] << hitsr->sb_bits) * stride;
blocked_times_mat_1 = times_mat_1->values + (hitsr->binds[times_mat_index_1].data[b] << hitsr->sb_bits) * stride;
blocked_times_mat_2 = times_mat_2->values + (hitsr->binds[times_mat_index_2].data[b] << hitsr->sb_bits) * stride;
blocked_times_mat_3 = times_mat_3->values + (hitsr->binds[times_mat_index_3].data[b] << hitsr->sb_bits) * stride;
ptiNnzIndex bptr_begin = hitsr->bptr.data[b];
ptiNnzIndex bptr_end = hitsr->bptr.data[b+1];
// ptiStopTimer(blockmat_timer);
// blockmat_etime += ptiElapsedTime(blockmat_timer);
// ptiPrintElapsedTime(blockmat_timer, "===Blockmat Timer");
/* Loop entries in a block */
// printf("bptr_begin: %"HIPARTI_PRI_INDEX", bptr_end: %"HIPARTI_PRI_INDEX"\n", bptr_begin, bptr_end);
// ptiStartTimer(block_timer);
for(ptiIndex z=bptr_begin; z<bptr_end; ++z) {
// ptiStartTimer(elementmat_timer);
mode_i = hitsr->einds[mode].data[z];
tmp_i_1 = hitsr->einds[times_mat_index_1].data[z];
tmp_i_2 = hitsr->einds[times_mat_index_2].data[z];
tmp_i_3 = hitsr->einds[times_mat_index_3].data[z];
// mode_i = (ptiBlockMatrixIndex)hitsr->einds[mode].data[z];
// tmp_i_1 = (ptiBlockMatrixIndex)hitsr->einds[times_mat_index_1].data[z];
// tmp_i_2 = (ptiBlockMatrixIndex)hitsr->einds[times_mat_index_2].data[z];
// tmp_i_3 = (ptiBlockMatrixIndex)hitsr->einds[times_mat_index_3].data[z];
entry = vals[z];
ptiValue * const restrict bmvals_row = blocked_mvals + mode_i * stride;
ptiValue * const restrict blocked_times_mat_1_row = blocked_times_mat_1 + tmp_i_1 * stride;
ptiValue * const restrict blocked_times_mat_2_row = blocked_times_mat_2 + tmp_i_2 * stride;
ptiValue * const restrict blocked_times_mat_3_row = blocked_times_mat_3 + tmp_i_3 * stride;
// ptiStopTimer(elementmat_timer);
// elementmat_etime += ptiElapsedTime(elementmat_timer);
// ptiPrintElapsedTime(elementmat_timer, "===Elementmat Timer");
// ptiStartTimer(element_timer);
#pragma omp simd
for(ptiElementIndex r=0; r<R; ++r) {
// blocked_mvals[mode_i * stride + r] += entry *
// blocked_times_mat_1[tmp_i_1 * stride + r] *
// blocked_times_mat_2[tmp_i_2 * stride + r] *
// blocked_times_mat_3[tmp_i_3 * stride + r];
bmvals_row[r] += entry *
blocked_times_mat_1_row[r]
* blocked_times_mat_2_row[r]
* blocked_times_mat_3_row[r];
}
// ptiStopTimer(element_timer);
// element_etime += ptiElapsedTime(element_timer);
// ptiPrintElapsedTime(element_timer, "===Element Timer");
} // End loop entries
// ptiStopTimer(block_timer);
// block_etime += ptiElapsedTime(block_timer);
// ptiPrintElapsedTime(block_timer, "==Block Timer");
} // End loop blocks
// ptiStopTimer(kernel_timer);
// kernel_etime += ptiElapsedTime(kernel_timer);
// ptiPrintElapsedTime(kernel_timer, "=Kernel Timer");
} // End loop kernels
// ptiStopTimer(loop_timer);
// loop_etime += ptiElapsedTime(loop_timer);
// ptiPrintElapsedTime(loop_timer, "=Loop Timer");
// printf("\nTotal Elementmat Time: %lf\n", elementmat_etime);
// printf("Total Element Time: %lf\n", element_etime);
// printf("Total Blockmat Time: %lf\n", blockmat_etime);
// printf("Total Block Time: %lf\n", block_etime);
// printf("Total Kernel Time: %lf\n", kernel_etime);
// printf("Total Loop Time: %lf\n\n", loop_etime);
// ptiFreeTimer(loop_timer);
// ptiFreeTimer(kernel_timer);
// ptiFreeTimer(block_timer);
// ptiFreeTimer(element_timer);
// ptiFreeTimer(elementmat_timer);
// ptiFreeTimer(blockmat_timer);
return 0;
}
int ptiMTTKRPHiCOO_3D_MatrixTiling_init(
ptiSparseTensorHiCOO const * const hitsr,
ptiMatrix * mats[], // mats[nmodes] as temporary space.
ptiIndex const mats_order[], // Correspond to the mode order of X.
ptiIndex const mode)
{
ptiIndex const nmodes = hitsr->nmodes;
ptiIndex const * const ndims = hitsr->ndims;
ptiValue const * const restrict vals = hitsr->values.data;
ptiIndex const stride = mats[0]->stride;
/* Check the mats. */
ptiAssert(nmodes ==3);
for(ptiIndex i=0; i<nmodes; ++i) {
if(mats[i]->ncols != mats[nmodes]->ncols) {
pti_CheckError(PTIERR_SHAPE_MISMATCH, "CPU HiCOO SpTns MTTKRP", "mats[i]->cols != mats[nmodes]->ncols");
}
if(mats[i]->nrows != ndims[i]) {
pti_CheckError(PTIERR_SHAPE_MISMATCH, "CPU HiCOO SpTns MTTKRP", "mats[i]->nrows != ndims[i]");
}
}
ptiIndex const tmpI = mats[mode]->nrows;
ptiIndex const R = mats[mode]->ncols;
ptiMatrix * const restrict M = mats[nmodes];
ptiValue * const restrict mvals = M->values;
memset(mvals, 0, tmpI*stride*sizeof(*mvals));
ptiIndex times_mat_index_1 = mats_order[1];
ptiMatrix * restrict times_mat_1 = mats[times_mat_index_1];
ptiIndex times_mat_index_2 = mats_order[2];
ptiMatrix * restrict times_mat_2 = mats[times_mat_index_2];
ptiElementIndex mode_i;
ptiElementIndex tmp_i_1, tmp_i_2;
ptiValue entry;
ptiValue * blocked_mvals;
ptiValue * blocked_times_mat_1;
ptiValue * blocked_times_mat_2;
/* Loop kernels */
for(ptiIndex k=0; k<hitsr->kptr.len - 1; ++k) {
ptiNnzIndex kptr_begin = hitsr->kptr.data[k];
ptiNnzIndex kptr_end = hitsr->kptr.data[k+1];
/* Loop blocks in a kernel */
for(ptiIndex b=kptr_begin; b<kptr_end; ++b) {
blocked_mvals = mvals + (hitsr->binds[mode].data[b] << hitsr->sb_bits) * stride;
blocked_times_mat_1 = times_mat_1->values + (hitsr->binds[times_mat_index_1].data[b] << hitsr->sb_bits) * stride;
blocked_times_mat_2 = times_mat_2->values + (hitsr->binds[times_mat_index_2].data[b] << hitsr->sb_bits) * stride;
ptiNnzIndex bptr_begin = hitsr->bptr.data[b];
ptiNnzIndex bptr_end = hitsr->bptr.data[b+1];
/* Loop entries in a block */
for(ptiIndex z=bptr_begin; z<bptr_end; ++z) {
mode_i = hitsr->einds[mode].data[z];
tmp_i_1 = hitsr->einds[times_mat_index_1].data[z];
tmp_i_2 = hitsr->einds[times_mat_index_2].data[z];
entry = vals[z];
for(ptiIndex r=0; r<R; ++r) {
blocked_mvals[mode_i * stride + r] += entry *
blocked_times_mat_1[tmp_i_1 * stride + r] *
blocked_times_mat_2[tmp_i_2 * stride + r];
}
} // End loop entries
} // End loop blocks
} // End loop kernels
return 0;
}
|
_ex1.c | void ex1(int n, double ss, double* a, double* b, double* y) {
register int i;
#pragma Orio Loops(transform Pragma(pragma_str="omp parallel for"))
{
#pragma omp parallel for
for (i=0; i<n; i++ ) {
y[i]=b[i]+ss*a[i];
}
}
#pragma Oiro
}
|
kmeans_omp.c | #include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#define BIGNUM 1000
float* k_means_omp(float *imageIn, int clusters, int dimension, int iterations)
{
// the cluster vector
int numElements = (dimension)*(dimension);
size_t size = numElements * sizeof(float);
float *cluster = (float*) malloc(size);// which centroid does each cluster belong to?
float *imageOut = (float*) malloc(size);//output image
// the centroids or means
int means = clusters;
size_t size2 = means * sizeof(float);
float *centroids = (float*) malloc(size2);// list of centroids(means)
float *accumulator = (float*) malloc(size2);/*needed for average step */
float *numPixelsCentroid = (float*) malloc(size2);/*needed for the update average step*/
int i,j,h,m,n,temp1,temp2;
float distance;
float min_temp = BIGNUM;
float range = 255/(means-1);
//omp_set_num_threads(8);
//Paralelizando a iniciacao dos vetores
#pragma omp parallel for
for ( m = 0; m < means; m++) {
centroids[m] = range*m;
accumulator[m] =0;
numPixelsCentroid[m] =0;
}
for(int iters = 0; iters<iterations ; iters++) {
for ( i=0; i < numElements-1; i++){ //assignment step-> assign each point to cluster of closest centroid
for ( j = 0; j < means; j++) {
distance = fabs(imageIn[i]-centroids[j]);// compare image to centroids
if (distance < min_temp){
min_temp = distance;
cluster[i] = j; // assign this point to current cluster
}
}
// set variables used to find average
temp1 = (int)cluster[i];
accumulator[temp1] += imageIn[i];
numPixelsCentroid[temp1]+=1;
min_temp = BIGNUM; //reset mintemp
}
//paralelizando a atualizacao dos centroids
#pragma omp parallel for schedule(guided)
for ( h = 0; h < means; h++) {
if (numPixelsCentroid[h] != 0){
centroids[h] = accumulator[h]/numPixelsCentroid[h];
//reset
}
accumulator[h] = 0;
numPixelsCentroid[h] =0;
}
}
// paralelizando a configuracao da imagem de saida
#pragma omp parallel for
for ( n=0; n < numElements-1; n++){
temp2 = (int)cluster[n];
imageOut[n] = centroids[temp2];
}
for ( m = 0; m < means; m++) {
printf("%f \n", centroids[m]);
}
return imageOut;
}
|
symv_x_coo_u_lo.c | #include "alphasparse/kernel.h"
#include "alphasparse/kernel_plain.h"
#include "alphasparse/opt.h"
#include "alphasparse/util.h"
#include <string.h>
#ifdef _OPENMP
#include <omp.h>
#endif
static alphasparse_status_t
symv_coo_u_lo_omp(const ALPHA_Number alpha,
const ALPHA_SPMAT_COO *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 nnz = A->nnz;
const ALPHA_INT thread_num = alpha_get_thread_num();
ALPHA_Number **tmp = (ALPHA_Number **)malloc(sizeof(ALPHA_Number *) * thread_num);
#ifdef _OPENMP
#pragma omp parallel for num_threads(thread_num)
#endif
for (int i = 0; i < thread_num; ++i)
{
tmp[i] = malloc(sizeof(ALPHA_Number) * m);
memset(tmp[i], 0, sizeof(ALPHA_Number) * m);
}
#ifdef _OPENMP
#pragma omp parallel for num_threads(thread_num)
#endif
for (ALPHA_INT i = 0; i < nnz; i++)
{
const ALPHA_INT threadId = alpha_get_thread_id();
const ALPHA_INT r = A->row_indx[i];
const ALPHA_INT c = A->col_indx[i];
if (r <= c)
{
continue;
}
ALPHA_Number v;
alpha_mul(v, alpha, A->values[i]);
alpha_madde(tmp[threadId][r], v, x[c]);
alpha_madde(tmp[threadId][c], v, x[r]);
}
#ifdef _OPENMP
#pragma omp parallel for num_threads(thread_num)
#endif
for (ALPHA_INT i = 0; i < m; ++i)
{
alpha_mul(y[i], beta, y[i]);
alpha_madde(y[i], alpha, x[i]);
for (ALPHA_INT j = 0; j < thread_num; ++j)
{
alpha_add(y[i], y[i], tmp[j][i]);
}
}
#ifdef _OPENMP
#pragma omp parallel for num_threads(thread_num)
#endif
for (int i = 0; i < thread_num; ++i)
{
alpha_free(tmp[i]);
}
alpha_free(tmp);
return ALPHA_SPARSE_STATUS_SUCCESS;
}
alphasparse_status_t
ONAME(const ALPHA_Number alpha,
const ALPHA_SPMAT_COO *A,
const ALPHA_Number *x,
const ALPHA_Number beta,
ALPHA_Number *y)
{
const ALPHA_INT thread_num = alpha_get_thread_num();
return symv_coo_u_lo_omp(alpha, A, x, beta, y);
}
|
generator_gemm_common.c | /******************************************************************************
* 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/hfp/libxsmm/ *
* SPDX-License-Identifier: BSD-3-Clause *
******************************************************************************/
/* Alexander Heinecke (Intel Corp.)
******************************************************************************/
#include "generator_gemm_common.h"
#include "generator_common.h"
#include "generator_x86_instructions.h"
#include "libxsmm_main.h"
LIBXSMM_API_INTERN
int libxsmm_generator_gemm_get_rbp_relative_offset( libxsmm_gemm_stack_var stack_var ) {
/* The stack at exit of setup looks like this:
*
* 10th param (if applicable) <-- RBP+40
* 9th param (if applicable) <-- RBP+32
* 8th param (if applicable) <-- RBP+24
* 7th param (if applicable) <-- RBP+16
* Return address <-- RBP+8
* Entry/saved RBP <-- RBP
* prefetch A ptr <-- RBP-8
* prefetch B ptr <-- RBP-16
* Offset A array ptr <-- RBP-24
* Offset B array ptr <-- RBP-32
* Int8 scaling factor <-- RBP-40
* GEMM_scratch ptr in stack (to be filled) <-- RBP-48
* Eltwise bias ptr <-- RBP-56
* Eltwise output_ptr <-- RBP-64
* Eltwise buf1_ptr <-- RBP-72
* Eltwise buf2_ptr <-- RBP-80
*
* */
switch ( stack_var ) {
case LIBXSMM_GEMM_STACK_VAR_NONE:
return 0;
case LIBXSMM_GEMM_STACK_VAR_PFA_PTR:
return -8;
case LIBXSMM_GEMM_STACK_VAR_PFB_PTR:
return -16;
case LIBXSMM_GEMM_STACK_VAR_A_OFFS_BRGEMM_PTR:
return -24;
case LIBXSMM_GEMM_STACK_VAR_B_OFFS_BRGEMM_PTR:
return -32;
case LIBXSMM_GEMM_STACK_VAR_INT8_SCF:
return -40;
case LIBXSMM_GEMM_STACK_VAR_GEMM_SCRATCH_PTR:
return -48;
case LIBXSMM_GEMM_STACK_VAR_ELT_BIAS_PTR:
return -56;
case LIBXSMM_GEMM_STACK_VAR_ELT_OUTPUT_PTR:
return -64;
case LIBXSMM_GEMM_STACK_VAR_ELT_RELU_BITMASK_PTR:
return -72;
case LIBXSMM_GEMM_STACK_VAR_ELT_BUF1:
return -72;
case LIBXSMM_GEMM_STACK_VAR_ELT_BUF2:
return -80;
case LIBXSMM_GEMM_STACK_VAR_TRANS_EXT_BUF_B:
return -72;
case LIBXSMM_GEMM_STACK_VAR_TRANS_EXT_BUF_C:
return -80;
case LIBXSMM_GEMM_STACK_VAR_ELT_BITMAP_PTR:
return -72;
case LIBXSMM_GEMM_STACK_VAR_ELT_DECOMPRESS_BUF:
return -80;
case LIBXSMM_GEMM_STACK_VAR_ARG_7:
return 16;
case LIBXSMM_GEMM_STACK_VAR_ARG_8:
return 24;
case LIBXSMM_GEMM_STACK_VAR_ARG_9:
return 32;
case LIBXSMM_GEMM_STACK_VAR_ARG_10:
return 40;
default:
return 0;
}
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_getval_stack_var( libxsmm_generated_code* io_generated_code,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
libxsmm_gemm_stack_var stack_var,
unsigned int i_gp_reg ) {
int offset = libxsmm_generator_gemm_get_rbp_relative_offset(stack_var);
/* make sure we requested a legal stack var */
if (offset == 0) {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_GENERAL );
return;
}
libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction, LIBXSMM_X86_GP_REG_RBP, LIBXSMM_X86_GP_REG_UNDEF, 0, offset, i_gp_reg, 0 );
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_setval_stack_var( libxsmm_generated_code* io_generated_code,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
libxsmm_gemm_stack_var stack_var,
unsigned int i_gp_reg ) {
int offset = libxsmm_generator_gemm_get_rbp_relative_offset(stack_var);
/* make sure we requested to set a legal stack var */
if (offset >= 0) {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_GENERAL );
return;
}
libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction, LIBXSMM_X86_GP_REG_RBP, LIBXSMM_X86_GP_REG_UNDEF, 0, offset, i_gp_reg, 1 );
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_init_micro_kernel_config_fullvector( libxsmm_micro_kernel_config* io_micro_kernel_config,
const unsigned int i_arch,
const libxsmm_gemm_descriptor* i_xgemm_desc,
const unsigned int i_use_masking_a_c ) {
memset(io_micro_kernel_config, 0, sizeof(*io_micro_kernel_config)); /* avoid warning "maybe used uninitialized" */
if ( (i_arch < LIBXSMM_X86_SSE3) || (i_arch > LIBXSMM_X86_ALLFEAT) ) {
io_micro_kernel_config->instruction_set = LIBXSMM_X86_GENERIC;
io_micro_kernel_config->vector_reg_count = 0;
io_micro_kernel_config->use_masking_a_c = 0;
io_micro_kernel_config->vector_name = 'a';
io_micro_kernel_config->vector_length = 0;
io_micro_kernel_config->datatype_size = 0;
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_UNDEF;
} else if ( i_arch <= LIBXSMM_X86_SSE4 ) {
io_micro_kernel_config->instruction_set = LIBXSMM_X86_SSE3;
io_micro_kernel_config->vector_reg_count = 16;
io_micro_kernel_config->use_masking_a_c = i_use_masking_a_c;
io_micro_kernel_config->vector_name = 'x';
if ( LIBXSMM_GEMM_PRECISION_F64 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
io_micro_kernel_config->vector_length = 2;
io_micro_kernel_config->datatype_size = 8;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_MOVAPD;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_MOVUPD;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_MOVDDUP;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_MOVAPD;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_MOVAPD;
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_MOVUPD;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_MOVUPD;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_XORPD;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_MULPD;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_ADDPD;
} else {
io_micro_kernel_config->vector_length = 4;
io_micro_kernel_config->datatype_size = 4;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_MOVAPS;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_MOVUPS;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_MOVSS;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_SHUFPS;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_MOVAPS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_MOVAPS;
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_MOVUPS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_MOVUPS;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_XORPS;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_MULPS;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_ADDPS;
}
} else if ( i_arch <= LIBXSMM_X86_AVX2 ) {
io_micro_kernel_config->instruction_set = i_arch;
io_micro_kernel_config->vector_reg_count = 16;
io_micro_kernel_config->use_masking_a_c = i_use_masking_a_c;
io_micro_kernel_config->vector_name = 'y';
if ( LIBXSMM_GEMM_PRECISION_F64 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
io_micro_kernel_config->vector_length = 4;
io_micro_kernel_config->datatype_size = 8;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPD;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPD;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VBROADCASTSD;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPD;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPD;
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPD;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPD;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VXORPD;
if ( i_arch == LIBXSMM_X86_AVX ) {
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VMULPD;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPD;
} else {
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231PD;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPD;
}
} else {
io_micro_kernel_config->vector_length = 8;
io_micro_kernel_config->datatype_size = 4;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VBROADCASTSS;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPS;
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VXORPS;
if ( i_arch == LIBXSMM_X86_AVX ) {
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VMULPS;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPS;
} else {
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231PS;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPS;
}
}
} else if ( i_arch <= LIBXSMM_X86_ALLFEAT ) {
io_micro_kernel_config->instruction_set = i_arch;
io_micro_kernel_config->vector_reg_count = 32;
io_micro_kernel_config->use_masking_a_c = i_use_masking_a_c;
io_micro_kernel_config->vector_name = 'z';
if ( LIBXSMM_GEMM_PRECISION_F64 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
io_micro_kernel_config->vector_length = 8;
io_micro_kernel_config->datatype_size = 8;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPD;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPD;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VBROADCASTSD;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPD;
if ( (i_use_masking_a_c == 0) ) {
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPD;
} else {
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVAPD;
}
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPD;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPD;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VPXORD;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231PD;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPD;
} else if ( LIBXSMM_GEMM_PRECISION_F32 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
io_micro_kernel_config->vector_length = 16;
io_micro_kernel_config->datatype_size = 4;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VBROADCASTSS;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
if ( (i_use_masking_a_c == 0) ) {
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPS;
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
}
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VPXORD;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231PS;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPS;
} else if ( LIBXSMM_GEMM_PRECISION_I16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
/* C is 32bit, so we treat all 3 matrices as 32bit element arrays */
io_micro_kernel_config->vector_length = 16;
io_micro_kernel_config->datatype_size = 4;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VPBROADCASTD;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
if ( (i_use_masking_a_c == 0) ) {
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPS;
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
}
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VPXORD;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VPDPWSSD;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VPADDD;
} else if ( LIBXSMM_GEMM_PRECISION_I8 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
/* C is 32bit, so we treat all 3 matrices as 32bit element arrays */
io_micro_kernel_config->vector_length = 16;
io_micro_kernel_config->datatype_size = 4;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VPBROADCASTD;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
if ( (i_use_masking_a_c == 0) ) {
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPS;
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
}
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VPXORD;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VPDPBUSD;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VPADDD;
} else if ( LIBXSMM_GEMM_PRECISION_BF16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
/* C is 32bit, so we treat all 3 matrices as 32bit element arrays */
io_micro_kernel_config->vector_length = 16;
io_micro_kernel_config->datatype_size = 4;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VPBROADCASTD;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
if ( (i_use_masking_a_c == 0) ) {
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPS;
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
}
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VPXORD;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VDPBF16PS;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPS;
} else {
/* shouldn't happen as we caught this case earlier */
io_micro_kernel_config->instruction_set = LIBXSMM_X86_GENERIC;
io_micro_kernel_config->vector_reg_count = 0;
io_micro_kernel_config->use_masking_a_c = 0;
io_micro_kernel_config->vector_name = 'a';
io_micro_kernel_config->vector_length = 0;
io_micro_kernel_config->datatype_size = 0;
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_UNDEF;
}
} else {
/* that should no happen */
}
io_micro_kernel_config->prefetch_instruction = LIBXSMM_X86_INSTR_PREFETCHT1;
io_micro_kernel_config->alu_add_instruction = LIBXSMM_X86_INSTR_ADDQ;
io_micro_kernel_config->alu_sub_instruction = LIBXSMM_X86_INSTR_SUBQ;
io_micro_kernel_config->alu_cmp_instruction = LIBXSMM_X86_INSTR_CMPQ;
io_micro_kernel_config->alu_jmp_instruction = LIBXSMM_X86_INSTR_JL;
io_micro_kernel_config->alu_mov_instruction = LIBXSMM_X86_INSTR_MOVQ;
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_init_micro_kernel_config_halfvector( libxsmm_micro_kernel_config* io_micro_kernel_config,
const unsigned int i_arch,
const libxsmm_gemm_descriptor* i_xgemm_desc,
const unsigned int i_use_masking_a_c ) {
if ( (i_arch < LIBXSMM_X86_SSE3) || (i_arch > LIBXSMM_X86_ALLFEAT) ) {
io_micro_kernel_config->instruction_set = LIBXSMM_X86_GENERIC;
io_micro_kernel_config->vector_reg_count = 0;
io_micro_kernel_config->use_masking_a_c = 0;
io_micro_kernel_config->vector_name = 'a';
io_micro_kernel_config->vector_length = 0;
io_micro_kernel_config->datatype_size = 0;
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_UNDEF;
} else if ( i_arch <= LIBXSMM_X86_SSE4 ) {
#if !defined(NDEBUG)
fprintf(stderr, "LIBXSMM WARNING, libxsmm_generator_gemm_init_micro_kernel_config_halfvector, redirecting to scalar, please fix the generation code!!!\n");
#endif
libxsmm_generator_gemm_init_micro_kernel_config_scalar( io_micro_kernel_config, i_arch, i_xgemm_desc, i_use_masking_a_c );
} else if ( i_arch <= LIBXSMM_X86_AVX2 ) {
io_micro_kernel_config->instruction_set = LIBXSMM_X86_AVX;
io_micro_kernel_config->vector_reg_count = 16;
io_micro_kernel_config->use_masking_a_c = i_use_masking_a_c;
io_micro_kernel_config->vector_name = 'x';
if ( LIBXSMM_GEMM_PRECISION_F64 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
io_micro_kernel_config->vector_length = 2;
io_micro_kernel_config->datatype_size = 8;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPD;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPD;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VMOVDDUP;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPD;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPD;
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPD;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPD;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VXORPD;
if ( i_arch == LIBXSMM_X86_AVX ) {
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VMULPD;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPD;
} else {
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231PD;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_UNDEF;
}
} else {
io_micro_kernel_config->vector_length = 4;
io_micro_kernel_config->datatype_size = 4;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VBROADCASTSS;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPS;
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VXORPS;
if ( i_arch == LIBXSMM_X86_AVX ) {
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VMULPS;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPS;
} else {
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231PS;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_UNDEF;
}
}
} else if ( i_arch <= LIBXSMM_X86_ALLFEAT ) {
#if !defined(NDEBUG)
fprintf(stderr, "LIBXSMM WARNING, libxsmm_generator_gemm_init_micro_kernel_config_halfvector, AVX512 redirecting to fullvector!\n");
#endif
libxsmm_generator_gemm_init_micro_kernel_config_fullvector( io_micro_kernel_config, i_arch, i_xgemm_desc, i_use_masking_a_c );
} else {
/* should not happen */
}
io_micro_kernel_config->prefetch_instruction = LIBXSMM_X86_INSTR_PREFETCHT1;
io_micro_kernel_config->alu_add_instruction = LIBXSMM_X86_INSTR_ADDQ;
io_micro_kernel_config->alu_sub_instruction = LIBXSMM_X86_INSTR_SUBQ;
io_micro_kernel_config->alu_cmp_instruction = LIBXSMM_X86_INSTR_CMPQ;
io_micro_kernel_config->alu_jmp_instruction = LIBXSMM_X86_INSTR_JL;
io_micro_kernel_config->alu_mov_instruction = LIBXSMM_X86_INSTR_MOVQ;
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_init_micro_kernel_config_scalar( libxsmm_micro_kernel_config* io_micro_kernel_config,
const unsigned int i_arch,
const libxsmm_gemm_descriptor* i_xgemm_desc,
const unsigned int i_use_masking_a_c ) {
if ( ( i_arch < LIBXSMM_X86_SSE3 ) || ( i_arch > LIBXSMM_X86_ALLFEAT ) ) {
io_micro_kernel_config->instruction_set = LIBXSMM_X86_GENERIC;
io_micro_kernel_config->vector_reg_count = 0;
io_micro_kernel_config->use_masking_a_c = 0;
io_micro_kernel_config->vector_name = 'a';
io_micro_kernel_config->vector_length = 0;
io_micro_kernel_config->datatype_size = 0;
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_UNDEF;
} else if ( i_arch <= LIBXSMM_X86_SSE4 ) {
io_micro_kernel_config->instruction_set = LIBXSMM_X86_SSE3;
io_micro_kernel_config->vector_reg_count = 16;
io_micro_kernel_config->use_masking_a_c = i_use_masking_a_c;
io_micro_kernel_config->vector_name = 'x';
if ( LIBXSMM_GEMM_PRECISION_F64 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
io_micro_kernel_config->vector_length = 1;
io_micro_kernel_config->datatype_size = 8;
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_MOVSD;
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_MOVSD;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_MOVSD;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_MOVSD;
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_XORPD;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_MULSD;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_ADDSD;
} else {
io_micro_kernel_config->vector_length = 1;
io_micro_kernel_config->datatype_size = 4;
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_MOVSS;
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_MOVSS;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_MOVSS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_MOVSS;
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_XORPS;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_MULSS;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_ADDSS;
}
} else if ( i_arch <= LIBXSMM_X86_ALLFEAT ) {
io_micro_kernel_config->instruction_set = i_arch;
io_micro_kernel_config->vector_reg_count = 16;
io_micro_kernel_config->use_masking_a_c = i_use_masking_a_c;
io_micro_kernel_config->vector_name = 'x';
if ( LIBXSMM_GEMM_PRECISION_F64 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
io_micro_kernel_config->vector_length = 1;
io_micro_kernel_config->datatype_size = 8;
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVSD;
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VMOVSD;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVSD;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVSD;
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VXORPD;
if ( i_arch == LIBXSMM_X86_AVX ) {
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VMULSD;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDSD;
} else {
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231SD;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_UNDEF;
}
} else {
io_micro_kernel_config->vector_length = 1;
io_micro_kernel_config->datatype_size = 4;
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVSS;
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VMOVSS;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVSS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVSS;
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VXORPS;
if ( i_arch == LIBXSMM_X86_AVX ) {
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VMULSS;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDSS;
} else {
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231SS;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_UNDEF;
}
}
} else {
/* should not happen */
}
io_micro_kernel_config->prefetch_instruction = LIBXSMM_X86_INSTR_PREFETCHT1;
io_micro_kernel_config->alu_add_instruction = LIBXSMM_X86_INSTR_ADDQ;
io_micro_kernel_config->alu_sub_instruction = LIBXSMM_X86_INSTR_SUBQ;
io_micro_kernel_config->alu_cmp_instruction = LIBXSMM_X86_INSTR_CMPQ;
io_micro_kernel_config->alu_jmp_instruction = LIBXSMM_X86_INSTR_JL;
io_micro_kernel_config->alu_mov_instruction = LIBXSMM_X86_INSTR_MOVQ;
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_add_flop_counter( libxsmm_generated_code* io_generated_code,
const libxsmm_gemm_descriptor* i_xgemm_desc ) {
if ( io_generated_code->code_type == 0 ) {
char l_new_code[512];
const unsigned int l_max_code_length = sizeof(l_new_code) - 1;
int l_code_length = 0;
l_code_length = LIBXSMM_SNPRINTF( l_new_code, l_max_code_length, "#ifndef NDEBUG\n" );
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
l_code_length = LIBXSMM_SNPRINTF( l_new_code, l_max_code_length, "#ifdef _OPENMP\n" );
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
l_code_length = LIBXSMM_SNPRINTF( l_new_code, l_max_code_length, "#pragma omp atomic\n" );
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
l_code_length = LIBXSMM_SNPRINTF( l_new_code, l_max_code_length, "#endif\n" );
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
l_code_length = LIBXSMM_SNPRINTF( l_new_code, l_max_code_length, "libxsmm_num_total_flops += %u;\n", 2u * i_xgemm_desc->m * i_xgemm_desc->n * i_xgemm_desc->k);
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
l_code_length = LIBXSMM_SNPRINTF( l_new_code, l_max_code_length, "#endif\n" );
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
}
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_header_kloop( libxsmm_generated_code* io_generated_code,
libxsmm_loop_label_tracker* io_loop_label_tracker,
const libxsmm_gp_reg_mapping* i_gp_reg_mapping,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
const unsigned int i_m_blocking,
const unsigned int i_k_blocking ) {
LIBXSMM_UNUSED(i_m_blocking);
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_mov_instruction, i_gp_reg_mapping->gp_reg_kloop, 0);
libxsmm_x86_instruction_register_jump_back_label( io_generated_code, io_loop_label_tracker );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_kloop, i_k_blocking);
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_footer_kloop( libxsmm_generated_code* io_generated_code,
libxsmm_loop_label_tracker* io_loop_label_tracker,
const libxsmm_gp_reg_mapping* i_gp_reg_mapping,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
const libxsmm_gemm_descriptor* i_xgemm_desc,
const unsigned int i_m_blocking,
const unsigned int i_max_blocked_k,
const unsigned int i_kloop_complete ) {
LIBXSMM_UNUSED(i_m_blocking);
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_cmp_instruction, i_gp_reg_mapping->gp_reg_kloop, i_max_blocked_k );
libxsmm_x86_instruction_jump_back_to_label( io_generated_code, i_micro_kernel_config->alu_jmp_instruction, io_loop_label_tracker );
if ( i_kloop_complete != 0 ) {
int l_b_offset = 0;
if ( (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_TRANS_B) > 0 ) {
l_b_offset = i_xgemm_desc->ldb * i_xgemm_desc->k * i_micro_kernel_config->datatype_size;
} else {
l_b_offset = i_xgemm_desc->k * i_micro_kernel_config->datatype_size;
}
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction,
i_gp_reg_mapping->gp_reg_b, l_b_offset );
}
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_header_reduceloop( libxsmm_generated_code* io_generated_code,
libxsmm_loop_label_tracker* io_loop_label_tracker,
const libxsmm_gp_reg_mapping* i_gp_reg_mapping,
const libxsmm_micro_kernel_config* i_micro_kernel_config ) {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_mov_instruction, i_gp_reg_mapping->gp_reg_reduce_loop, 0);
libxsmm_x86_instruction_register_jump_back_label( io_generated_code, io_loop_label_tracker );
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_footer_reduceloop( libxsmm_generated_code* io_generated_code,
libxsmm_loop_label_tracker* io_loop_label_tracker,
const libxsmm_gp_reg_mapping* i_gp_reg_mapping,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
const libxsmm_gemm_descriptor* i_xgemm_desc) {
LIBXSMM_UNUSED(i_xgemm_desc);
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_reduce_loop, 1);
libxsmm_x86_instruction_alu_reg( io_generated_code, i_micro_kernel_config->alu_cmp_instruction, i_gp_reg_mapping->gp_reg_reduce_count, i_gp_reg_mapping->gp_reg_reduce_loop);
libxsmm_x86_instruction_jump_back_to_label( io_generated_code, i_micro_kernel_config->alu_jmp_instruction, io_loop_label_tracker );
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_header_nloop( libxsmm_generated_code* io_generated_code,
libxsmm_loop_label_tracker* io_loop_label_tracker,
const libxsmm_gp_reg_mapping* i_gp_reg_mapping,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
const unsigned int i_n_blocking) {
libxsmm_x86_instruction_register_jump_back_label( io_generated_code, io_loop_label_tracker );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_nloop, i_n_blocking );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_mov_instruction, i_gp_reg_mapping->gp_reg_mloop, 0 );
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_footer_nloop( libxsmm_generated_code* io_generated_code,
libxsmm_loop_label_tracker* io_loop_label_tracker,
const libxsmm_gp_reg_mapping* i_gp_reg_mapping,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
const libxsmm_gemm_descriptor* i_xgemm_desc,
const unsigned int i_n_blocking,
const unsigned int i_n_done ) {
if ( LIBXSMM_GEMM_PRECISION_BF16 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_c,
(i_n_blocking*(i_xgemm_desc->ldc)*(i_micro_kernel_config->datatype_size/2)) - ((i_xgemm_desc->m)*(i_micro_kernel_config->datatype_size/2)) );
} else if ( LIBXSMM_GEMM_PRECISION_I8 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_c,
(i_n_blocking*(i_xgemm_desc->ldc)*(i_micro_kernel_config->datatype_size/4)) - ((i_xgemm_desc->m)*(i_micro_kernel_config->datatype_size/4)) );
} else {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_c,
(i_n_blocking*(i_xgemm_desc->ldc)*(i_micro_kernel_config->datatype_size)) - ((i_xgemm_desc->m)*(i_micro_kernel_config->datatype_size)) );
}
/* B prefetch */
if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_BL2_VIA_C ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C_AHEAD ) {
if ( (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_TRANS_B) == 0 ) {
unsigned int l_type_scaling;
if ( (LIBXSMM_GEMM_PRECISION_BF16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype )) ||
(LIBXSMM_GEMM_PRECISION_I16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype )) ) {
l_type_scaling = 2;
} else if ( LIBXSMM_GEMM_PRECISION_I8 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
l_type_scaling = 4;
} else {
l_type_scaling = 1;
}
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_b_prefetch,
(i_n_blocking*(i_xgemm_desc->ldc)*(i_micro_kernel_config->datatype_size/l_type_scaling)) - ((i_xgemm_desc->m)*(i_micro_kernel_config->datatype_size/l_type_scaling)) );
}
}
#if 0
if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_CL2 ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2CL2BL2_VIA_C ) {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_c_prefetch,
(i_n_blocking*(i_xgemm_desc->ldc)*(i_micro_kernel_config->datatype_size)) - ((i_xgemm_desc->m)*(i_micro_kernel_config->datatype_size)) );
}
#endif
if (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_BATCH_REDUCE_ADDRESS) {
/* handle trans B */
int l_b_offset = 0;
if ( (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_TRANS_B) > 0 ) {
l_b_offset = i_n_blocking * i_micro_kernel_config->datatype_size;
} else {
l_b_offset = i_n_blocking * i_xgemm_desc->ldb * i_micro_kernel_config->datatype_size;
}
libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_0 );
libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_reduce_loop );
libxsmm_generator_gemm_header_reduceloop( io_generated_code, io_loop_label_tracker, i_gp_reg_mapping, i_micro_kernel_config );
libxsmm_x86_instruction_alu_mem( io_generated_code,
i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_a,
i_gp_reg_mapping->gp_reg_reduce_loop, 8,
0,
i_gp_reg_mapping->gp_reg_help_0,
0 );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction,
i_gp_reg_mapping->gp_reg_help_0, ((i_xgemm_desc->m)*(i_micro_kernel_config->datatype_size)) );
libxsmm_x86_instruction_alu_mem( io_generated_code,
i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_a,
i_gp_reg_mapping->gp_reg_reduce_loop, 8,
0,
i_gp_reg_mapping->gp_reg_help_0,
1 );
libxsmm_x86_instruction_alu_mem( io_generated_code,
i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_b,
i_gp_reg_mapping->gp_reg_reduce_loop, 8,
0,
i_gp_reg_mapping->gp_reg_help_0,
0 );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction,
i_gp_reg_mapping->gp_reg_help_0, l_b_offset );
libxsmm_x86_instruction_alu_mem( io_generated_code,
i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_b,
i_gp_reg_mapping->gp_reg_reduce_loop, 8,
0,
i_gp_reg_mapping->gp_reg_help_0,
1 );
if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2 ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C ) {
libxsmm_x86_instruction_alu_mem( io_generated_code,
i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_a_prefetch,
i_gp_reg_mapping->gp_reg_reduce_loop, 8,
0,
i_gp_reg_mapping->gp_reg_help_0,
0 );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction,
i_gp_reg_mapping->gp_reg_help_0, ((i_xgemm_desc->m)*(i_micro_kernel_config->datatype_size)) );
libxsmm_x86_instruction_alu_mem( io_generated_code,
i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_a_prefetch,
i_gp_reg_mapping->gp_reg_reduce_loop, 8,
0,
i_gp_reg_mapping->gp_reg_help_0,
1 );
}
libxsmm_generator_gemm_footer_reduceloop( io_generated_code, io_loop_label_tracker, i_gp_reg_mapping, i_micro_kernel_config, i_xgemm_desc);
libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_reduce_loop );
libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_0 );
} else {
/* handle trans B */
int l_b_offset = 0;
if ( (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_TRANS_B) > 0 ) {
l_b_offset = i_n_blocking * i_micro_kernel_config->datatype_size;
} else {
l_b_offset = i_n_blocking * i_xgemm_desc->ldb * i_micro_kernel_config->datatype_size;
}
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction,
i_gp_reg_mapping->gp_reg_b, l_b_offset );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction,
i_gp_reg_mapping->gp_reg_a, ((i_xgemm_desc->m)*(i_micro_kernel_config->datatype_size)) );
if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2 ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C ) {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction,
i_gp_reg_mapping->gp_reg_a_prefetch, ((i_xgemm_desc->m)*(i_micro_kernel_config->datatype_size)) );
}
}
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_cmp_instruction, i_gp_reg_mapping->gp_reg_nloop, i_n_done );
libxsmm_x86_instruction_jump_back_to_label( io_generated_code, i_micro_kernel_config->alu_jmp_instruction, io_loop_label_tracker );
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_header_mloop( libxsmm_generated_code* io_generated_code,
libxsmm_loop_label_tracker* io_loop_label_tracker,
const libxsmm_gp_reg_mapping* i_gp_reg_mapping,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
const unsigned int i_m_blocking ) {
libxsmm_x86_instruction_register_jump_back_label( io_generated_code, io_loop_label_tracker );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_mloop, i_m_blocking );
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_footer_mloop( libxsmm_generated_code* io_generated_code,
libxsmm_loop_label_tracker* io_loop_label_tracker,
const libxsmm_gp_reg_mapping* i_gp_reg_mapping,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
const libxsmm_gemm_descriptor* i_xgemm_desc,
const unsigned int i_m_blocking,
const unsigned int i_m_done ) {
/* advance C pointer */
if ( LIBXSMM_GEMM_PRECISION_BF16 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction,
i_gp_reg_mapping->gp_reg_c, i_m_blocking*(i_micro_kernel_config->datatype_size/2) );
} else if ( LIBXSMM_GEMM_PRECISION_I8 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction,
i_gp_reg_mapping->gp_reg_c, i_m_blocking*(i_micro_kernel_config->datatype_size/4) );
} else {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction,
i_gp_reg_mapping->gp_reg_c, i_m_blocking*(i_micro_kernel_config->datatype_size) );
}
/* C prefetch */
#if 0
if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_CL2 ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2CL2BL2_VIA_C ) {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction,
i_gp_reg_mapping->gp_reg_c_prefetch, i_m_blocking*(i_micro_kernel_config->datatype_size) );
}
#endif
/* B prefetch */
if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_BL2_VIA_C ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C_AHEAD ) {
if ( (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_TRANS_B) == 0 ) {
unsigned int l_type_scaling;
if ( (LIBXSMM_GEMM_PRECISION_BF16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype )) ||
(LIBXSMM_GEMM_PRECISION_I16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype )) ) {
l_type_scaling = 2;
} else if ( LIBXSMM_GEMM_PRECISION_I8 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
l_type_scaling = 4;
} else {
l_type_scaling = 1;
}
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction,
i_gp_reg_mapping->gp_reg_b_prefetch, i_m_blocking*(i_micro_kernel_config->datatype_size/l_type_scaling) );
}
}
/* A prefetch */
if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2 ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C) {
if (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_BATCH_REDUCE_ADDRESS) {
if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2 ) {
libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_0 );
libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_reduce_loop );
libxsmm_generator_gemm_header_reduceloop( io_generated_code, io_loop_label_tracker, i_gp_reg_mapping, i_micro_kernel_config );
libxsmm_x86_instruction_alu_mem( io_generated_code,
i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_a_prefetch,
i_gp_reg_mapping->gp_reg_reduce_loop, 8,
0,
i_gp_reg_mapping->gp_reg_help_0,
0 );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction, i_gp_reg_mapping->gp_reg_help_0,
((i_xgemm_desc->k) * (i_micro_kernel_config->datatype_size) * (i_xgemm_desc->lda) ) -
(i_m_blocking * (i_micro_kernel_config->datatype_size)) );
libxsmm_x86_instruction_alu_mem( io_generated_code,
i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_a_prefetch,
i_gp_reg_mapping->gp_reg_reduce_loop, 8,
0,
i_gp_reg_mapping->gp_reg_help_0,
1 );
libxsmm_generator_gemm_footer_reduceloop( io_generated_code, io_loop_label_tracker, i_gp_reg_mapping, i_micro_kernel_config, i_xgemm_desc);
libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_reduce_loop );
libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_0 );
}
} else {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction, i_gp_reg_mapping->gp_reg_a_prefetch,
((i_xgemm_desc->k) * (i_micro_kernel_config->datatype_size) * (i_xgemm_desc->lda) ) -
(i_m_blocking * (i_micro_kernel_config->datatype_size)) );
}
}
/* advance A pointer */
if (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_BATCH_REDUCE_ADDRESS) {
libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_0 );
libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_reduce_loop );
libxsmm_generator_gemm_header_reduceloop( io_generated_code, io_loop_label_tracker, i_gp_reg_mapping, i_micro_kernel_config );
libxsmm_x86_instruction_alu_mem( io_generated_code,
i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_a,
i_gp_reg_mapping->gp_reg_reduce_loop, 8,
0,
i_gp_reg_mapping->gp_reg_help_0,
0 );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction, i_gp_reg_mapping->gp_reg_help_0,
((i_xgemm_desc->k) * (i_micro_kernel_config->datatype_size) * (i_xgemm_desc->lda) ) - (i_m_blocking * (i_micro_kernel_config->datatype_size)) );
libxsmm_x86_instruction_alu_mem( io_generated_code,
i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_a,
i_gp_reg_mapping->gp_reg_reduce_loop, 8,
0,
i_gp_reg_mapping->gp_reg_help_0,
1 );
libxsmm_generator_gemm_footer_reduceloop( io_generated_code, io_loop_label_tracker, i_gp_reg_mapping, i_micro_kernel_config, i_xgemm_desc);
libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_reduce_loop );
libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_0 );
} else {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction, i_gp_reg_mapping->gp_reg_a,
((i_xgemm_desc->k) * (i_micro_kernel_config->datatype_size) * (i_xgemm_desc->lda) ) - (i_m_blocking * (i_micro_kernel_config->datatype_size)) );
}
/* loop handling */
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_cmp_instruction, i_gp_reg_mapping->gp_reg_mloop, i_m_done );
libxsmm_x86_instruction_jump_back_to_label( io_generated_code, i_micro_kernel_config->alu_jmp_instruction, io_loop_label_tracker );
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_load_C( libxsmm_generated_code* io_generated_code,
const libxsmm_gp_reg_mapping* i_gp_reg_mapping,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
const libxsmm_gemm_descriptor* i_xgemm_desc,
const unsigned int i_m_blocking,
const unsigned int i_n_blocking ) {
unsigned int l_m_blocking, l_vec_reg_acc_start;
/* register blocking counter in n */
unsigned int l_n = 0;
/* register blocking counter in m */
unsigned int l_m = 0;
assert(0 < i_micro_kernel_config->vector_length);
/* deriving register blocking from kernel config */
l_m_blocking = ( i_m_blocking % i_micro_kernel_config->vector_length == 0 ) ? i_m_blocking/i_micro_kernel_config->vector_length : (i_m_blocking/i_micro_kernel_config->vector_length)+1;
/* start register of accumulator */
l_vec_reg_acc_start = i_micro_kernel_config->vector_reg_count - (i_n_blocking * l_m_blocking);
#if !defined(NDEBUG)
/* Do some test if it is possible to generate the requested code.
This is not done in release mode and therefore bad
things might happen.... HUAAH */
if (i_micro_kernel_config->instruction_set == LIBXSMM_X86_SSE3 ||
i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX ||
i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX2 ) {
if ( (i_n_blocking > 3) || (i_n_blocking < 1) || (i_m_blocking < 1) ) {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_REG_BLOCK );
return;
}
} else if ( i_micro_kernel_config->instruction_set < LIBXSMM_X86_AVX512_CORE ) {
if ( (i_n_blocking > 30) || (i_n_blocking < 1) || (l_m_blocking != 1) ) {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_REG_BLOCK );
return;
}
} else if ( i_micro_kernel_config->instruction_set >= LIBXSMM_X86_AVX512_CORE ) {
if ( (i_n_blocking > 30) || (i_n_blocking < 1) || (l_m_blocking < 1) || (l_m_blocking > 6) ) {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_REG_BLOCK );
return;
}
} else {}
#if 0
if ( i_m_blocking % i_micro_kernel_config->vector_length != 0 ) {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_M_BLOCK );
return;
}
#endif
#endif /*!defined(NDEBUG)*/
/* load C accumulator */
if (0 == (LIBXSMM_GEMM_FLAG_BETA_0 & i_xgemm_desc->flags)) { /* Beta=1 */
/* pure BF16 kernel */
if ( ( (i_micro_kernel_config->instruction_set >= LIBXSMM_X86_AVX512_CORE) && (i_micro_kernel_config->instruction_set <= LIBXSMM_X86_ALLFEAT) ) &&
( (LIBXSMM_GEMM_PRECISION_BF16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) && (LIBXSMM_GEMM_PRECISION_BF16 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) ) ) {
/* we add when scaling during conversion to FP32 */
for ( l_n = 0; l_n < i_n_blocking; l_n++ ) {
for ( l_m = 0; l_m < l_m_blocking; l_m++ ) {
/* load 16 bit values into ymm portion of the register */
if ( (i_micro_kernel_config->use_masking_a_c != 0) && ( l_m == (l_m_blocking - 1) ) ) {
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
LIBXSMM_X86_INSTR_VMOVDQU16,
i_gp_reg_mapping->gp_reg_c,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size/2),
'z',
0, 2, 1, 0 );
} else {
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
i_micro_kernel_config->c_vmove_instruction,
i_gp_reg_mapping->gp_reg_c,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size/2),
'y',
0, 0, 1, 0 );
}
/* convert 16 bit values into 32 bit (integer convert) */
libxsmm_x86_instruction_vec_compute_2reg( io_generated_code,
LIBXSMM_X86_INSTR_VPMOVSXWD,
i_micro_kernel_config->vector_name,
0, l_vec_reg_acc_start + l_m + (l_m_blocking * l_n) );
/* shift 16 bits to the left to generate valid FP32 numbers */
libxsmm_x86_instruction_vec_compute_2reg_imm8(io_generated_code,
LIBXSMM_X86_INSTR_VPSLLD_I,
i_micro_kernel_config->vector_name,
l_vec_reg_acc_start + l_m + (l_m_blocking * l_n),
l_vec_reg_acc_start + l_m + (l_m_blocking * l_n),
16);
}
}
/* pure int8 kernel */
} else if ( ( (i_micro_kernel_config->instruction_set >= LIBXSMM_X86_AVX512_CORE) && (i_micro_kernel_config->instruction_set <= LIBXSMM_X86_ALLFEAT) ) &&
( (LIBXSMM_GEMM_PRECISION_I8 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) && (LIBXSMM_GEMM_PRECISION_I8 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) ) ) {
/* we need to up convert int8 to int32 */
for ( l_n = 0; l_n < i_n_blocking; l_n++ ) {
for ( l_m = 0; l_m < l_m_blocking; l_m++ ) {
/* load 16 bit values into xmm portion of the register */
if ( (i_micro_kernel_config->use_masking_a_c != 0) && ( l_m == (l_m_blocking - 1) ) ) {
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
LIBXSMM_X86_INSTR_VMOVDQU8,
i_gp_reg_mapping->gp_reg_c,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size/4),
'z',
0, 2, 1, 0 );
} else {
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
i_micro_kernel_config->c_vmove_instruction,
i_gp_reg_mapping->gp_reg_c,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size/4),
'x',
0, 0, 1, 0 );
}
/* convert 8 bit values into 32 bit (integer convert) */
if ( (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_C_UNSIGNED) != 0 ) {
libxsmm_x86_instruction_vec_compute_2reg( io_generated_code,
LIBXSMM_X86_INSTR_VPMOVZXBD,
i_micro_kernel_config->vector_name,
0, l_vec_reg_acc_start + l_m + (l_m_blocking * l_n) );
} else {
libxsmm_x86_instruction_vec_compute_2reg( io_generated_code,
LIBXSMM_X86_INSTR_VPMOVSXBD,
i_micro_kernel_config->vector_name,
0, l_vec_reg_acc_start + l_m + (l_m_blocking * l_n) );
}
}
}
} else {
/* adding to C, so let's load C */
for ( l_n = 0; l_n < i_n_blocking; l_n++ ) {
for ( l_m = 0; l_m < l_m_blocking; l_m++ ) {
/* we only mask the last m-blocked load */
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
i_micro_kernel_config->c_vmove_instruction,
i_gp_reg_mapping->gp_reg_c,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size),
i_micro_kernel_config->vector_name,
l_vec_reg_acc_start + l_m + (l_m_blocking * l_n), ( l_m == (l_m_blocking - 1) ) ? i_micro_kernel_config->use_masking_a_c : 0, 1, 0 );
}
#if 0
if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_CL2 ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2CL2BL2_VIA_C ) {
for (l_m = 0; l_m < l_m_blocking; l_m += l_m++ ) {
libxsmm_x86_instruction_prefetch( io_generated_code,
i_micro_kernel_config->prefetch_instruction,
i_gp_reg_mapping->gp_reg_c_prefetch,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size));
}
}
#endif
}
}
} else {
/* overwriting C, so let's xout accumulator */
for ( l_n = 0; l_n < i_n_blocking; l_n++ ) {
for ( l_m = 0; l_m < l_m_blocking; l_m++ ) {
/* @TODO: cannot migrate to new encoder as this is also SSE */
libxsmm_x86_instruction_vec_compute_reg( io_generated_code,
io_generated_code->arch,
i_micro_kernel_config->vxor_instruction,
i_micro_kernel_config->vector_name,
l_vec_reg_acc_start + l_m + (l_m_blocking * l_n),
l_vec_reg_acc_start + l_m + (l_m_blocking * l_n),
l_vec_reg_acc_start + l_m + (l_m_blocking * l_n) );
}
#if 0
if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_CL2 ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2CL2BL2_VIA_C ) {
for (l_m = 0; l_m < l_m_blocking; l_m += l_m++ ) {
libxsmm_x86_instruction_prefetch( io_generated_code,
i_micro_kernel_config->prefetch_instruction,
i_gp_reg_mapping->gp_reg_c_prefetch,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size));
}
}
#endif
}
}
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_store_C( libxsmm_generated_code* io_generated_code,
const libxsmm_gp_reg_mapping* i_gp_reg_mapping,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
const libxsmm_gemm_descriptor* i_xgemm_desc,
const unsigned int i_m_blocking,
const unsigned int i_n_blocking )
{
/* deriving register blocking from kernel config */
unsigned int l_m_blocking = ( i_m_blocking % i_micro_kernel_config->vector_length == 0 ) ? i_m_blocking/i_micro_kernel_config->vector_length : (i_m_blocking/i_micro_kernel_config->vector_length)+1;
/* register blocking counter in n */
unsigned int l_n = 0;
/* register blocking counter in m */
unsigned int l_m = 0;
/* start register of accumulator */
unsigned int l_vec_reg_acc_start = i_micro_kernel_config->vector_reg_count - (i_n_blocking * l_m_blocking);
/* select store instruction */
unsigned int l_vstore = (LIBXSMM_GEMM_FLAG_ALIGN_C_NTS_HINT == (LIBXSMM_GEMM_FLAG_ALIGN_C_NTS_HINT & i_xgemm_desc->flags)) ? i_micro_kernel_config->c_vmove_nts_instruction : i_micro_kernel_config->c_vmove_instruction;
/* @TODO fix this test */
#if !defined(NDEBUG)
if (i_micro_kernel_config->instruction_set == LIBXSMM_X86_SSE3 ||
i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX ||
i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX2 ) {
if ( (i_n_blocking > 3) || (i_n_blocking < 1) || (i_m_blocking < 1) ) {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_REG_BLOCK );
return;
}
} else if ( i_micro_kernel_config->instruction_set < LIBXSMM_X86_AVX512_CORE ) {
if ( (i_n_blocking > 30) || (i_n_blocking < 1) || (i_m_blocking != i_micro_kernel_config->vector_length) ) {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_REG_BLOCK );
return;
}
} else if ( i_micro_kernel_config->instruction_set >= LIBXSMM_X86_AVX512_CORE ) {
if ( (i_n_blocking > 30) || (i_n_blocking < 1) || (l_m_blocking < 1) || (l_m_blocking > 6) ) {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_REG_BLOCK );
return;
}
} else {}
#if 0
if ( i_m_blocking % i_micro_kernel_config->vector_length != 0 ) {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_M_BLOCK );
return;
}
#endif
#endif
if ( ( (i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX512_CORE) || (i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX512_CLX) ) &&
( (LIBXSMM_GEMM_PRECISION_BF16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) && (LIBXSMM_GEMM_PRECISION_BF16 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) ) ) {
/* init stack with helper variables for SW-based RNE rounding */
/* push 0x7f800000 on the stack, naninf masking */
libxsmm_x86_instruction_alu_imm( io_generated_code, LIBXSMM_X86_INSTR_MOVQ, i_gp_reg_mapping->gp_reg_help_2, 0x7f800000);
libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_2 );
/* push 0x00010000 on the stack, fixup masking */
libxsmm_x86_instruction_alu_imm( io_generated_code, LIBXSMM_X86_INSTR_MOVQ, i_gp_reg_mapping->gp_reg_help_2, 0x00010000);
libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_2 );
/* push 0x00007fff on the stack, rneadd */
libxsmm_x86_instruction_alu_imm( io_generated_code, LIBXSMM_X86_INSTR_MOVQ, i_gp_reg_mapping->gp_reg_help_2, 0x00007fff);
libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_2 );
/* push 0x00000001 on the stack, fixup */
libxsmm_x86_instruction_alu_imm( io_generated_code, LIBXSMM_X86_INSTR_MOVQ, i_gp_reg_mapping->gp_reg_help_2, 0x00000001);
libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_2 );
/* storing downconverted and rounded C accumulator */
for ( l_n = 0; l_n < i_n_blocking; l_n++ ) {
for ( l_m = 0; l_m < l_m_blocking; l_m++ ) {
unsigned int reg_X = l_vec_reg_acc_start + l_m + (l_m_blocking * l_n);
/* and with naninf */
libxsmm_x86_instruction_vec_compute_mem( io_generated_code,
i_micro_kernel_config->instruction_set,
LIBXSMM_X86_INSTR_VPANDD,
1,
LIBXSMM_X86_GP_REG_RSP,
LIBXSMM_X86_GP_REG_UNDEF,
0,
24,
i_micro_kernel_config->vector_name,
reg_X,
0 );
/* and with fixup */
libxsmm_x86_instruction_vec_compute_mem( io_generated_code,
i_micro_kernel_config->instruction_set,
LIBXSMM_X86_INSTR_VPANDD,
1,
LIBXSMM_X86_GP_REG_RSP,
LIBXSMM_X86_GP_REG_UNDEF,
0,
16,
i_micro_kernel_config->vector_name,
reg_X,
1 );
/* compute naninf mask k7 */
libxsmm_x86_instruction_vec_compute_mem_2reg_imm8( io_generated_code,
LIBXSMM_X86_INSTR_VPCMPD,
i_micro_kernel_config->vector_name,
LIBXSMM_X86_GP_REG_RSP,
LIBXSMM_X86_GP_REG_UNDEF,
0,
24,
1,
0,
7,
4 );
/* compute fixup mask k6 */
libxsmm_x86_instruction_vec_compute_mem_2reg_imm8( io_generated_code,
LIBXSMM_X86_INSTR_VPCMPD,
i_micro_kernel_config->vector_name,
LIBXSMM_X86_GP_REG_RSP,
LIBXSMM_X86_GP_REG_UNDEF,
0,
16,
1,
1,
6,
0 );
/* load rneadd */
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
LIBXSMM_X86_INSTR_VBROADCASTSS,
LIBXSMM_X86_GP_REG_RSP,
LIBXSMM_X86_GP_REG_UNDEF, 0,
8,
i_micro_kernel_config->vector_name,
0, 0, 1, 0 );
/* load fixup */
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
LIBXSMM_X86_INSTR_VBROADCASTSS,
LIBXSMM_X86_GP_REG_RSP,
LIBXSMM_X86_GP_REG_UNDEF, 0,
0,
i_micro_kernel_config->vector_name,
1, 0, 1, 0 );
/* compute fixup */
libxsmm_x86_instruction_vec_compute_3reg_mask( io_generated_code,
LIBXSMM_X86_INSTR_VPADDD,
i_micro_kernel_config->vector_name,
1,
0,
0,
6,
0 );
/* compute fixup */
libxsmm_x86_instruction_vec_compute_3reg_mask( io_generated_code,
LIBXSMM_X86_INSTR_VPADDD,
i_micro_kernel_config->vector_name,
0,
reg_X,
reg_X,
7,
0 );
/* shift FP32 by 16bit to right */
libxsmm_x86_instruction_vec_compute_2reg_imm8(io_generated_code,
LIBXSMM_X86_INSTR_VPSRAD_I,
i_micro_kernel_config->vector_name,
reg_X,
reg_X,
16);
/* shift FP32 by 16bit to right */
libxsmm_x86_instruction_vec_compute_2reg( io_generated_code,
LIBXSMM_X86_INSTR_VPMOVDW,
i_micro_kernel_config->vector_name,
reg_X,
0 );
/* store 16 bit values into ymm portion of the register */
if ( (i_micro_kernel_config->use_masking_a_c != 0) && ( l_m == (l_m_blocking - 1) ) ) {
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
LIBXSMM_X86_INSTR_VMOVDQU16,
i_gp_reg_mapping->gp_reg_c,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size/2),
'z',
0, 2, 0, 1 );
} else {
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
l_vstore,
i_gp_reg_mapping->gp_reg_c,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size/2),
'y',
0, 0, 0, 1 );
}
}
}
/* clean stack and restore help5 */
libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_2 );
libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_2 );
libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_2 );
libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_2 );
} else if ( ( (i_micro_kernel_config->instruction_set <= LIBXSMM_X86_ALLFEAT) && (i_micro_kernel_config->instruction_set >= LIBXSMM_X86_AVX512_CPX) ) &&
( (LIBXSMM_GEMM_PRECISION_BF16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) && (LIBXSMM_GEMM_PRECISION_BF16 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) ) ) {
/* storing downconverted and rounded C accumulator */
for ( l_n = 0; l_n < i_n_blocking; l_n++ ) {
unsigned int l_m_2_blocking = (l_m_blocking/2)*2;
l_m = 0;
if ( i_micro_kernel_config->use_masking_a_c != 0 ) {
for ( l_m = 0 ; l_m < l_m_blocking; l_m++ ) {
unsigned int reg_X = l_vec_reg_acc_start + l_m + (l_m_blocking * l_n);
libxsmm_x86_instruction_vec_compute_2reg( io_generated_code,
LIBXSMM_X86_INSTR_VCVTNEPS2BF16,
i_micro_kernel_config->vector_name,
reg_X, 0 );
/* store 16 bit values into ymm portion of the register */
if ( l_m == (l_m_blocking - 1) ) {
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
LIBXSMM_X86_INSTR_VMOVDQU16,
i_gp_reg_mapping->gp_reg_c,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size/2),
'z',
0, 2, 0, 1 );
} else {
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
l_vstore,
i_gp_reg_mapping->gp_reg_c,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size/2),
'y',
0, 0, 0, 1 );
}
}
} else {
for (; l_m < l_m_2_blocking; l_m+=2 ) {
unsigned int reg_X = l_vec_reg_acc_start + l_m + (l_m_blocking * l_n);
unsigned int reg_X2 = l_vec_reg_acc_start + l_m+1 + (l_m_blocking * l_n);
libxsmm_x86_instruction_vec_compute_3reg( io_generated_code,
LIBXSMM_X86_INSTR_VCVTNE2PS2BF16,
i_micro_kernel_config->vector_name,
reg_X, reg_X2, 0 );
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
l_vstore,
i_gp_reg_mapping->gp_reg_c,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size/2),
'z',
0, 0, 0, 1 );
}
for (; l_m < l_m_blocking; l_m++ ) {
unsigned int reg_X = l_vec_reg_acc_start + l_m + (l_m_blocking * l_n);
libxsmm_x86_instruction_vec_compute_2reg( io_generated_code,
LIBXSMM_X86_INSTR_VCVTNEPS2BF16,
i_micro_kernel_config->vector_name,
reg_X, 0 );
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
l_vstore,
i_gp_reg_mapping->gp_reg_c,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size/2),
'y',
0, 0, 0, 1 );
}
}
}
} else if ( ( (i_micro_kernel_config->instruction_set <= LIBXSMM_X86_ALLFEAT) || (i_micro_kernel_config->instruction_set >= LIBXSMM_X86_AVX512_CORE) ) &&
( (LIBXSMM_GEMM_PRECISION_I8 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) && (LIBXSMM_GEMM_PRECISION_I8 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) ) ) {
/* pick the right instrucitons */
unsigned int inst_f32_i32 = ( ( i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_C_UNSIGNED ) != 0 ) ? LIBXSMM_X86_INSTR_VCVTPS2UDQ : LIBXSMM_X86_INSTR_VCVTPS2DQ;
unsigned int inst_i32_i8 = ( ( i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_C_UNSIGNED ) != 0 ) ? LIBXSMM_X86_INSTR_VPMOVUSDB : LIBXSMM_X86_INSTR_VPMOVSDB;
/* there are case where we need to load the scaling factor's address from the stack argument list */
if ( (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_BATCH_REDUCE_OFFSET) != 0 ) {
libxsmm_x86_instruction_load_arg_to_reg( io_generated_code, 0, i_gp_reg_mapping->gp_reg_scf );
}
/* loading scf into register 3 */
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
LIBXSMM_X86_INSTR_VBROADCASTSS,
i_gp_reg_mapping->gp_reg_scf,
LIBXSMM_X86_GP_REG_UNDEF, 0, 0,
i_micro_kernel_config->vector_name,
3, 0, 1, 0 );
/* Zero out register 0 to perform relu */
libxsmm_x86_instruction_vec_compute_3reg( io_generated_code,
i_micro_kernel_config->vxor_instruction,
i_micro_kernel_config->vector_name,
0,
0,
0);
/* storing downconverted and rounded C accumulator */
for ( l_n = 0; l_n < i_n_blocking; l_n++ ) {
for ( l_m = 0; l_m < l_m_blocking; l_m++ ) {
unsigned int reg_X = l_vec_reg_acc_start + l_m + (l_m_blocking * l_n);
/* Convert result to F32 */
libxsmm_x86_instruction_vec_compute_2reg( io_generated_code,
LIBXSMM_X86_INSTR_VCVTDQ2PS,
i_micro_kernel_config->vector_name,
reg_X,
reg_X );
/* Multiply with scaling factor */
libxsmm_x86_instruction_vec_compute_3reg( io_generated_code,
LIBXSMM_X86_INSTR_VMULPS,
i_micro_kernel_config->vector_name,
reg_X,
3,
reg_X );
/* Perform RELU */
libxsmm_x86_instruction_vec_compute_3reg( io_generated_code,
LIBXSMM_X86_INSTR_VMAXPS,
i_micro_kernel_config->vector_name,
reg_X,
0,
reg_X);
/* Round result to int32 */
libxsmm_x86_instruction_vec_compute_2reg( io_generated_code,
inst_f32_i32,
i_micro_kernel_config->vector_name,
reg_X, reg_X );
/* down-convert to int8 */
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
inst_i32_i8,
i_gp_reg_mapping->gp_reg_c,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size/4),
i_micro_kernel_config->vector_name,
reg_X, ( ( l_m == (l_m_blocking - 1)) && ( i_micro_kernel_config->use_masking_a_c != 0 ) ) ? 2 : 0, 0, 1 );
}
}
} else {
/* storing C accumulator */
for ( l_n = 0; l_n < i_n_blocking; l_n++ ) {
for ( l_m = 0; l_m < l_m_blocking; l_m++ ) {
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
l_vstore,
i_gp_reg_mapping->gp_reg_c,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size),
i_micro_kernel_config->vector_name,
l_vec_reg_acc_start + l_m + (l_m_blocking * l_n), ( l_m == (l_m_blocking - 1) ) ? i_micro_kernel_config->use_masking_a_c : 0, 0, 1 );
}
if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_BL2_VIA_C ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C_AHEAD ) {
if ( (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_TRANS_B) == 0 ) {
/* determining how many prefetches we need in M direction as we just need one prefetch per cache line */
unsigned int l_m_advance = 64 / ((i_micro_kernel_config->vector_length) * (i_micro_kernel_config->datatype_size)); /* 64: hardcoded cache line length */
for (l_m = 0; l_m < l_m_blocking; l_m += l_m_advance ) {
libxsmm_x86_instruction_prefetch( io_generated_code,
i_micro_kernel_config->prefetch_instruction,
i_gp_reg_mapping->gp_reg_b_prefetch,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size));
}
}
}
}
}
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_initialize_avx512_mask( libxsmm_generated_code* io_generated_code,
const unsigned int i_gp_reg_tmp,
const libxsmm_gemm_descriptor* i_xgemm_desc,
const unsigned int i_mask_count ) {
unsigned int l_mask;
/* init full mask */
if ( LIBXSMM_GEMM_PRECISION_F64 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
l_mask = 0xff;
} else {
l_mask = 0xffff;
}
/* shift right by "inverse" remainder */
l_mask = l_mask >> i_mask_count;
/* move mask to GP register */
libxsmm_x86_instruction_alu_imm( io_generated_code,
LIBXSMM_X86_INSTR_MOVQ,
i_gp_reg_tmp,
l_mask );
if ( ( io_generated_code->arch >= LIBXSMM_X86_AVX512 ) && ( io_generated_code->arch <= LIBXSMM_X86_ALLFEAT ) ) {
libxsmm_x86_instruction_mask_move( io_generated_code,
LIBXSMM_X86_INSTR_KMOVW_GPR_LD,
i_gp_reg_tmp,
LIBXSMM_X86_AVX512_MASK );
if ( ( LIBXSMM_GEMM_PRECISION_BF16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) && ( LIBXSMM_GEMM_PRECISION_BF16 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) ) {
libxsmm_x86_instruction_mask_move( io_generated_code,
LIBXSMM_X86_INSTR_KMOVD_GPR_LD,
i_gp_reg_tmp,
2 );
} else if ( ( LIBXSMM_GEMM_PRECISION_I8 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) && ( LIBXSMM_GEMM_PRECISION_I8 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) ) {
libxsmm_x86_instruction_mask_move( io_generated_code,
LIBXSMM_X86_INSTR_KMOVQ_GPR_LD,
i_gp_reg_tmp,
2 );
} else {
/* no addtional mask is needed */
}
} else {
/* shouldn't happen */
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_ARCH );
return;
}
}
|
9541.c | // this source is derived from CHILL AST originally from file '/uufs/chpc.utah.edu/common/home/u1142914/lib/ytopt_vinu/polybench/polybench-code/stencils/fdtd-2d/kernel.c' as parsed by frontend compiler rose
void kernel_fdtd_2d(int tmax, int nx, int ny, double ex[1000 + 0][1200 + 0], double ey[1000 + 0][1200 + 0], double hz[1000 + 0][1200 + 0], double _fict_[500 + 0]) {
int t10;
int t8;
int t6;
int t4;
int t2;
for (t2 = 0; t2 <= tmax - 1; t2 += 1) {
for (t4 = 0; t4 <= ny - 1; t4 += 1)
ey[0][t4] = _fict_[t2];
for (t4 = 1; t4 <= nx - 1; t4 += 1)
for (t6 = 0; t6 <= ny - 1; t6 += 1)
ey[t4][t6] = ey[t4][t6] - 0.5 * (hz[t4][t6] - hz[t4 - 1][t6]);
#pragma omp parallel for private(t4,t6,t8,t10)
for (t4 = 0; t4 <= nx - 1; t4 += 16)
for (t6 = t4; t6 <= (t4 + 15 < nx - 1 ? t4 + 15 : nx - 1); t6 += 1)
for (t8 = 1; t8 <= ny - 1; t8 += 64)
for (t10 = t8; t10 <= (ny - 1 < t8 + 63 ? ny - 1 : t8 + 63); t10 += 1)
ex[t6][t10] = ex[t6][t10] - 0.5 * (hz[t6][t10] - hz[t6][t10 - 1]);
#pragma omp parallel for private(t4,t6,t8,t10)
for (t4 = 0; t4 <= nx - 2; t4 += 16)
for (t6 = t4; t6 <= (t4 + 15 < nx - 2 ? t4 + 15 : nx - 2); t6 += 1)
for (t8 = 0; t8 <= ny - 2; t8 += 64)
for (t10 = t8; t10 <= (ny - 2 < t8 + 63 ? ny - 2 : t8 + 63); t10 += 1)
hz[t6][t10] = hz[t6][t10] - 0.69999999999999996 * (ex[t6][t10 + 1] - ex[t6][t10] + ey[t6 + 1][t10] - ey[t6][t10]);
}
}
|
omp-parallel-2.c | #include <omp.h>
#define THREADS 2
int main(void)
{
#pragma omp parallel num_threads(THREADS)
{
// pass
}
#pragma omp parallel num_threads(THREADS*4)
{
// pass
}
#pragma omp parallel num_threads(THREADS*2)
{
// pass
}
} |
7601.c | /* POLYBENCH/GPU-OPENMP
*
* This file is a part of the Polybench/GPU-OpenMP suite
*
* Contact:
* William Killian <killian@udel.edu>
*
* Copyright 2013, The University of Delaware
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
/* Include polybench common header. */
#include <polybench.h>
/* Include benchmark-specific header. */
/* Default data type is double, default size is 4000. */
#include "covariance.h"
/* Array initialization. */
static
void init_array (int m, int n,
DATA_TYPE *float_n,
DATA_TYPE POLYBENCH_2D(data,M,N,m,n))
{
int i, j;
*float_n = 1.2;
for (i = 0; i < M; i++)
for (j = 0; j < N; j++)
data[i][j] = ((DATA_TYPE) i*j) / M;
}
/* 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 m,
DATA_TYPE POLYBENCH_2D(symmat,M,M,m,m))
{
int i, j;
for (i = 0; i < m; i++)
for (j = 0; j < m; j++) {
fprintf (stderr, DATA_PRINTF_MODIFIER, symmat[i][j]);
if ((i * m + 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_covariance(int m, int n,
DATA_TYPE float_n,
DATA_TYPE POLYBENCH_2D(data,M,N,m,n),
DATA_TYPE POLYBENCH_2D(symmat,M,M,m,m),
DATA_TYPE POLYBENCH_1D(mean,M,m))
{
int i, j, j1, j2;
#pragma scop
/* Determine mean of column vectors of input data matrix */
{
#pragma omp target teams distribute
for (j = 0; j < _PB_M; j++)
{
mean[j] = 0.0;
for (i = 0; i < _PB_N; i++)
mean[j] += data[i][j];
mean[j] /= float_n;
}
/* Center the column vectors. */
#pragma omp target teams distribute
for (i = 0; i < _PB_N; i++)
{
#pragma omp target teams distribute
for (j = 0; j < _PB_M; j++)
{
data[i][j] -= mean[j];
}
}
/* Calculate the m * m covariance matrix. */
#pragma omp target teams distribute
for (j1 = 0; j1 < _PB_M; j1++)
{
#pragma omp target teams distribute
for (j2 = j1; j2 < _PB_M; j2++)
{
symmat[j1][j2] = 0.0;
for (i = 0; i < _PB_N; i++)
symmat[j1][j2] += data[i][j1] * data[i][j2];
symmat[j2][j1] = symmat[j1][j2];
}
}
}
#pragma endscop
}
int main(int argc, char** argv)
{
/* Retrieve problem size. */
int n = N;
int m = M;
/* Variable declaration/allocation. */
DATA_TYPE float_n;
POLYBENCH_2D_ARRAY_DECL(data,DATA_TYPE,M,N,m,n);
POLYBENCH_2D_ARRAY_DECL(symmat,DATA_TYPE,M,M,m,m);
POLYBENCH_1D_ARRAY_DECL(mean,DATA_TYPE,M,m);
/* Initialize array(s). */
init_array (m, n, &float_n, POLYBENCH_ARRAY(data));
/* Start timer. */
polybench_start_instruments;
/* Run kernel. */
kernel_covariance (m, n, float_n,
POLYBENCH_ARRAY(data),
POLYBENCH_ARRAY(symmat),
POLYBENCH_ARRAY(mean));
/* Stop and print timer. */
polybench_stop_instruments;
polybench_print_instruments;
/* Prevent dead-code elimination. All live-out data must be printed
by the function call in argument. */
polybench_prevent_dce(print_array(m, POLYBENCH_ARRAY(symmat)));
/* Be clean. */
POLYBENCH_FREE_ARRAY(data);
POLYBENCH_FREE_ARRAY(symmat);
POLYBENCH_FREE_ARRAY(mean);
return 0;
}
|
pr39495-2.c | /* PR c/39495 */
/* { dg-do compile } */
/* { dg-options "-fopenmp" } */
#define INT_MIN (-__INT_MAX__ - 1)
#define INT_MAX __INT_MAX__
#define UINT_MAX (2U * __INT_MAX__ + 1)
int
foo (void)
{
int i;
unsigned int u;
#pragma omp for
for (i = INT_MIN + 6; i != INT_MIN; i--) /* { dg-error "invalid controlling predicate" } */
;
#pragma omp for
for (i = INT_MIN + 6; i == INT_MIN; i--) /* { dg-error "invalid controlling predicate" } */
;
#pragma omp for
for (i = INT_MAX - 6; i != INT_MAX; i++) /* { dg-error "invalid controlling predicate" } */
;
#pragma omp for
for (i = INT_MAX - 6; i == INT_MAX; i++) /* { dg-error "invalid controlling predicate" } */
;
#pragma omp for
for (u = 6; u != 0; u--) /* { dg-error "invalid controlling predicate" } */
;
#pragma omp for
for (u = 6; u == 0; u--) /* { dg-error "invalid controlling predicate" } */
;
#pragma omp for
for (u = UINT_MAX - 6; u != UINT_MAX; u++) /* { dg-error "invalid controlling predicate" } */
;
#pragma omp for
for (u = UINT_MAX - 6; u == UINT_MAX; u++) /* { dg-error "invalid controlling predicate" } */
;
}
|
GB_unaryop__ainv_fp32_uint32.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__ainv_fp32_uint32
// op(A') function: GB_tran__ainv_fp32_uint32
// C type: float
// A type: uint32_t
// cast: float cij = (float) aij
// unaryop: cij = -aij
#define GB_ATYPE \
uint32_t
#define GB_CTYPE \
float
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = -x ;
// casting
#define GB_CASTING(z, aij) \
float z = (float) 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_AINV || GxB_NO_FP32 || GxB_NO_UINT32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__ainv_fp32_uint32
(
float *Cx, // Cx and Ax may be aliased
uint32_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__ainv_fp32_uint32
(
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
|
GB_unop__exp2_fp64_fp64.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__exp2_fp64_fp64
// op(A') function: GB_unop_tran__exp2_fp64_fp64
// C type: double
// A type: double
// cast: double cij = aij
// unaryop: cij = exp2 (aij)
#define GB_ATYPE \
double
#define GB_CTYPE \
double
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
double aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = exp2 (x) ;
// casting
#define GB_CAST(z, aij) \
double z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
double aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
double z = aij ; \
Cx [pC] = exp2 (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_EXP2 || GxB_NO_FP64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__exp2_fp64_fp64
(
double *Cx, // Cx and Ax may be aliased
const double *Ax,
const int8_t *GB_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)
{
#if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST )
GB_memcpy (Cx, Ax, anz * sizeof (double), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
double aij = Ax [p] ;
double z = aij ;
Cx [p] = exp2 (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 ;
double aij = Ax [p] ;
double z = aij ;
Cx [p] = exp2 (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_tran__exp2_fp64_fp64
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Workspaces,
const int64_t *GB_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
|
ten_tusscher_2004_epi_S2_20.c | //Original Ten Tusscher
#include <assert.h>
#include <stdlib.h>
#include "ten_tusscher_2004_epi_S2_20.h"
GET_CELL_MODEL_DATA(init_cell_model_data) {
assert(cell_model);
if(get_initial_v)
cell_model->initial_v = INITIAL_V;
if(get_neq)
cell_model->number_of_ode_equations = NEQ;
}
//TODO: this should be called only once for the whole mesh, like in the GPU code
SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu) {
// Default initial conditions
/*
sv[0] = INITIAL_V; // V; millivolt
sv[1] = 0.f; //M
sv[2] = 0.75; //H
sv[3] = 0.75f; //J
sv[4] = 0.f; //Xr1
sv[5] = 1.f; //Xr2
sv[6] = 0.f; //Xs
sv[7] = 1.f; //S
sv[8] = 0.f; //R
sv[9] = 0.f; //D
sv[10] = 1.f; //F
sv[11] = 1.f; //FCa
sv[12] = 1.f; //G
sv[13] = 0.0002; //Cai
sv[14] = 0.2f; //CaSR
sv[15] = 11.6f; //Nai
sv[16] = 138.3f; //Ki
*/
// Elnaz's steady-state initial conditions
real sv_sst[]={-86.5626314873864,0.00129162059588251,0.779565841868151,0.779314339768234,0.000174937390688145,0.485031353960147,0.00294149195344193,0.999998346418836,1.93534486766886e-08,1.89248872699741e-05,0.999775353607234,1.00753388054703,0.999999038303684,3.47610047822055e-05,1.00562825829621,9.46957015137721,139.869479747257};
for (uint32_t i = 0; i < NEQ; i++)
sv[i] = sv_sst[i];
}
SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu) {
uint32_t sv_id;
int i;
#pragma omp parallel for private(sv_id)
for (i = 0; i < num_cells_to_solve; i++) {
if(cells_to_solve)
sv_id = cells_to_solve[i];
else
sv_id = i;
for (int j = 0; j < num_steps; ++j) {
solve_model_ode_cpu(dt, sv + (sv_id * NEQ), stim_currents[i]);
}
}
}
void solve_model_ode_cpu(real dt, real *sv, real stim_current) {
assert(sv);
real rY[NEQ], rDY[NEQ];
for(int i = 0; i < NEQ; i++)
rY[i] = sv[i];
RHS_cpu(rY, rDY, stim_current, dt);
for(int i = 0; i < NEQ; i++)
sv[i] = rDY[i];
}
void RHS_cpu(const real *sv, real *rDY_, real stim_current, real dt) {
// State variables
real svolt = sv[0];
real sm = sv[1];
real sh = sv[2];
real sj = sv[3];
real sxr1 = sv[4];
real sxr2 = sv[5];
real sxs = sv[6];
real ss = sv[7];
real sr = sv[8];
real sd = sv[9];
real sf = sv[10];
real sfca = sv[11];
real sg = sv[12];
real Cai = sv[13];
real CaSR = sv[14];
real Nai = sv[15];
real Ki = sv[16];
//External concentrations
real Ko=5.4;
real Cao=2.0;
real Nao=140.0;
//Intracellular volumes
real Vc=0.016404;
real Vsr=0.001094;
//Calcium dynamics
real Bufc=0.15f;
real Kbufc=0.001f;
real Bufsr=10.f;
real Kbufsr=0.3f;
real taufca=2.f;
real taug=2.f;
real Vmaxup=0.000425f;
real Kup=0.00025f;
//Constants
const real R = 8314.472f;
const real F = 96485.3415f;
const real T =310.0f;
real RTONF =(R*T)/F;
//Cellular capacitance
real CAPACITANCE=0.185;
//Parameters for currents
//Parameters for IKr
real Gkr=0.096;
//Parameters for Iks
real pKNa=0.03;
///#ifdef EPI
real Gks=0.245;
///#endif
///#ifdef ENDO
/// real Gks=0.245;
///#endif
///#ifdef MCELL
/// real Gks=0.062;
///#endif
//Parameters for Ik1
real GK1=5.405;
//Parameters for Ito
//#ifdef EPI
real Gto=0.294;
//#endif
// #ifdef ENDO
// real Gto=0.073;
//#endif
//#ifdef MCELL
// real Gto=0.294;
///#endif
//Parameters for INa
real GNa=14.838;
//Parameters for IbNa
real GbNa=0.00029;
//Parameters for INaK
real KmK=1.0;
real KmNa=40.0;
real knak=1.362;
//Parameters for ICaL
real GCaL=0.000175;
//Parameters for IbCa
real GbCa=0.000592;
//Parameters for INaCa
real knaca=1000;
real KmNai=87.5;
real KmCa=1.38;
real ksat=0.1;
real n=0.35;
//Parameters for IpCa
real GpCa=0.825;
real KpCa=0.0005;
//Parameters for IpK;
real GpK=0.0146;
real parameters []={13.9266422007604,0.000306211763267299,0.000130134845221041,0.000571745609978391,0.247335217693447,0.185194358577401,0.103790172036162,3.70853519439188,0.0133585353452839,2.20377995116952,1098.12344962390,0.000446735827598516,0.252881711351026,0.0117635663866967,0.00515418083406778,9.05330255534724e-06};
GNa=parameters[0];
GbNa=parameters[1];
GCaL=parameters[2];
GbCa=parameters[3];
Gto=parameters[4];
Gkr=parameters[5];
Gks=parameters[6];
GK1=parameters[7];
GpK=parameters[8];
knak=parameters[9];
knaca=parameters[10];
Vmaxup=parameters[11];
GpCa=parameters[12];
real arel=parameters[13];
real crel=parameters[14];
real Vleak=parameters[15];
real IKr;
real IKs;
real IK1;
real Ito;
real INa;
real IbNa;
real ICaL;
real IbCa;
real INaCa;
real IpCa;
real IpK;
real INaK;
real Irel;
real Ileak;
real dNai;
real dKi;
real dCai;
real dCaSR;
real A;
// real BufferFactorc;
// real BufferFactorsr;
real SERCA;
real Caisquare;
real CaSRsquare;
real CaCurrent;
real CaSRCurrent;
real fcaold;
real gold;
real Ek;
real Ena;
real Eks;
real Eca;
real CaCSQN;
real bjsr;
real cjsr;
real CaBuf;
real bc;
real cc;
real Ak1;
real Bk1;
real rec_iK1;
real rec_ipK;
real rec_iNaK;
real AM;
real BM;
real AH_1;
real BH_1;
real AH_2;
real BH_2;
real AJ_1;
real BJ_1;
real AJ_2;
real BJ_2;
real M_INF;
real H_INF;
real J_INF;
real TAU_M;
real TAU_H;
real TAU_J;
real axr1;
real bxr1;
real axr2;
real bxr2;
real Xr1_INF;
real Xr2_INF;
real TAU_Xr1;
real TAU_Xr2;
real Axs;
real Bxs;
real Xs_INF;
real TAU_Xs;
real R_INF;
real TAU_R;
real S_INF;
real TAU_S;
real Ad;
real Bd;
real Cd;
real TAU_D;
real D_INF;
real TAU_F;
real F_INF;
real FCa_INF;
real G_INF;
real inverseVcF2=1/(2*Vc*F);
real inverseVcF=1./(Vc*F);
real Kupsquare=Kup*Kup;
// real BufcKbufc=Bufc*Kbufc;
// real Kbufcsquare=Kbufc*Kbufc;
// real Kbufc2=2*Kbufc;
// real BufsrKbufsr=Bufsr*Kbufsr;
// const real Kbufsrsquare=Kbufsr*Kbufsr;
// const real Kbufsr2=2*Kbufsr;
const real exptaufca=exp(-dt/taufca);
const real exptaug=exp(-dt/taug);
real sItot;
//Needed to compute currents
Ek=RTONF*(log((Ko/Ki)));
Ena=RTONF*(log((Nao/Nai)));
Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai)));
Eca=0.5*RTONF*(log((Cao/Cai)));
Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200)));
Bk1=(3.*exp(0.0002*(svolt-Ek+100))+
exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek)));
rec_iK1=Ak1/(Ak1+Bk1);
rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T))));
rec_ipK=1./(1.+exp((25-svolt)/5.98));
//Compute currents
INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena);
ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))*
(exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.);
Ito=Gto*sr*ss*(svolt-Ek);
IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek);
IKs=Gks*sxs*sxs*(svolt-Eks);
IK1=GK1*rec_iK1*(svolt-Ek);
INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))*
(1./(1+ksat*exp((n-1)*svolt*F/(R*T))))*
(exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao-
exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5);
INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK;
IpCa=GpCa*Cai/(KpCa+Cai);
IpK=GpK*rec_ipK*(svolt-Ek);
IbNa=GbNa*(svolt-Ena);
IbCa=GbCa*(svolt-Eca);
//Determine total current
(sItot) = IKr +
IKs +
IK1 +
Ito +
INa +
IbNa +
ICaL +
IbCa +
INaK +
INaCa +
IpCa +
IpK +
stim_current;
//update concentrations
Caisquare=Cai*Cai;
CaSRsquare=CaSR*CaSR;
CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE;
///A=0.016464f*CaSRsquare/(0.0625f+CaSRsquare)+0.008232f;
A=arel*CaSRsquare/(0.0625f+CaSRsquare)+crel;
Irel=A*sd*sg;
///Ileak=0.00008f*(CaSR-Cai);
Ileak=Vleak*(CaSR-Cai);
SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare));
CaSRCurrent=SERCA-Irel-Ileak;
CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr);
dCaSR=dt*(Vc/Vsr)*CaSRCurrent;
bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr;
cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR);
CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.;
CaBuf=Bufc*Cai/(Cai+Kbufc);
dCai=dt*(CaCurrent-CaSRCurrent);
bc=Bufc-CaBuf-dCai-Cai+Kbufc;
cc=Kbufc*(CaBuf+dCai+Cai);
Cai=(sqrt(bc*bc+4*cc)-bc)/2;
dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE;
Nai+=dt*dNai;
dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE;
Ki+=dt*dKi;
//compute steady state values and time constants
AM=1./(1.+exp((-60.-svolt)/5.));
BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.));
TAU_M=AM*BM;
M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03)));
if (svolt>=-40.)
{
AH_1=0.;
BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1))));
TAU_H= 1.0/(AH_1+BH_1);
}
else
{
AH_2=(0.057*exp(-(svolt+80.)/6.8));
BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt));
TAU_H=1.0/(AH_2+BH_2);
}
H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43)));
if(svolt>=-40.)
{
AJ_1=0.;
BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.))));
TAU_J= 1.0/(AJ_1+BJ_1);
}
else
{
AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)*
exp(-0.04391*svolt))*(svolt+37.78)/
(1.+exp(0.311*(svolt+79.23))));
BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14))));
TAU_J= 1.0/(AJ_2+BJ_2);
}
J_INF=H_INF;
Xr1_INF=1./(1.+exp((-26.-svolt)/7.));
axr1=450./(1.+exp((-45.-svolt)/10.));
bxr1=6./(1.+exp((svolt-(-30.))/11.5));
TAU_Xr1=axr1*bxr1;
Xr2_INF=1./(1.+exp((svolt-(-88.))/24.));
axr2=3./(1.+exp((-60.-svolt)/20.));
bxr2=1.12/(1.+exp((svolt-60.)/20.));
TAU_Xr2=axr2*bxr2;
Xs_INF=1./(1.+exp((-5.-svolt)/14.));
Axs=1100./(sqrt(1.+exp((-10.-svolt)/6)));
Bxs=1./(1.+exp((svolt-60.)/20.));
TAU_Xs=Axs*Bxs;
#ifdef EPI
R_INF=1./(1.+exp((20-svolt)/6.));
S_INF=1./(1.+exp((svolt+20)/5.));
TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8;
TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.;
#endif
#ifdef ENDO
R_INF=1./(1.+exp((20-svolt)/6.));
S_INF=1./(1.+exp((svolt+28)/5.));
TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8;
TAU_S=1000.*exp(-(svolt+67)*(svolt+67)/1000.)+8.;
#endif
#ifdef MCELL
R_INF=1./(1.+exp((20-svolt)/6.));
S_INF=1./(1.+exp((svolt+20)/5.));
TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8;
TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.;
#endif
D_INF=1./(1.+exp((-5-svolt)/7.5));
Ad=1.4/(1.+exp((-35-svolt)/13))+0.25;
Bd=1.4/(1.+exp((svolt+5)/5));
Cd=1./(1.+exp((50-svolt)/20));
TAU_D=Ad*Bd+Cd;
F_INF=1./(1.+exp((svolt+20)/7));
TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10));
FCa_INF=(1./(1.+pow((Cai/0.000325),8))+
0.1/(1.+exp((Cai-0.0005)/0.0001))+
0.20/(1.+exp((Cai-0.00075)/0.0008))+
0.23 )/1.46;
if(Cai<0.00035)
G_INF=1./(1.+pow((Cai/0.00035),6));
else
G_INF=1./(1.+pow((Cai/0.00035),16));
//Update gates
rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M);
rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H);
rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J);
rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1);
rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2);
rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs);
rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S);
rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R);
rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D);
rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F);
fcaold= sfca;
sfca = FCa_INF-(FCa_INF-sfca)*exptaufca;
if(sfca>fcaold && (svolt)>-37.0)
sfca = fcaold;
gold = sg;
sg = G_INF-(G_INF-sg)*exptaug;
if(sg>gold && (svolt)>-37.0)
sg=gold;
//update voltage
rDY_[0] = svolt + dt*(-sItot);
rDY_[11] = sfca;
rDY_[12] = sg;
rDY_[13] = Cai;
rDY_[14] = CaSR;
rDY_[15] = Nai;
rDY_[16] = Ki;
}
|
Graph.h | /******************************************************************************
** Copyright (c) 2015, Intel Corporation **
** All rights reserved. **
** **
** Redistribution and use in source and binary forms, with or without **
** modification, are permitted provided that the following conditions **
** are met: **
** 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 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.
* ******************************************************************************/
/* Narayanan Sundaram (Intel Corp.), Michael Anderson (Intel Corp.)
* ******************************************************************************/
#include <cstring>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <unistd.h>
#include <cstdlib>
#include <sys/time.h>
#include <parallel/algorithm>
#include <omp.h>
#include <cassert>
namespace GraphMat {
inline double sec(struct timeval start, struct timeval end)
{
return ((double)(((end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec))))/1.0e6;
}
template<class T>
void AddFn(const T& a, const T& b, T* c, void* vsp) {
*c = a + b ;
}
template <class V, class E=int>
class Graph {
public:
int nvertices;
long long int nnz;
bool vertexpropertyowner;
int tiles_per_dim;
int num_threads;
GraphMat::SpMat<GraphMat::DCSCTile<E> > *A;
GraphMat::SpMat<GraphMat::DCSCTile<E> > *AT;
GraphMat::SpVec<GraphMat::DenseSegment<V> > * vertexproperty;
GraphMat::SpVec<GraphMat::DenseSegment<bool> > * active;
public:
Graph(): nvertices(0), nnz(0), vertexpropertyowner(true),
tiles_per_dim(GraphMat::get_global_nrank()),
A(nullptr), AT(nullptr), num_threads(omp_get_max_threads()),
vertexproperty(nullptr), active(nullptr) {}
void ReadEdgelist(GraphMat::edgelist_t<E> A_edges);
void getVertexEdgelist(GraphMat::edgelist_t<V> & myedges);
void getEdgelist(GraphMat::edgelist_t<E> & myedges);
void ReadMTX(const char* filename);
void ReadGraphMatBin(const char* filename);
void WriteGraphMatBin(const char* filename);
void setAllActive();
void setAllInactive();
void setActive(int v);
void setInactive(int v);
void setAllVertexproperty(const V& val);
void setVertexproperty(int v, const V& val);
V getVertexproperty(int v) const;
bool vertexNodeOwner(const int v) const;
void saveVertexproperty(std::string fname, bool includeHeader=true) const;
void reset();
void shareVertexProperty(Graph<V,E>& g);
int getNumberOfVertices() const;
void applyToAllVertices(void (*ApplyFn)(const V&, V*, void*), void* param=nullptr);
template<class T> void applyReduceAllVertices(T* val, void (*ApplyFn)(V*, T*, void*), void (*ReduceFn)(const T&, const T&,T*,void*)=AddFn<T>, void* param=nullptr);
void applyToAllEdges(void (*ApplyFn)(E*, const V&, const V&, void*), void* param=nullptr);
~Graph();
private:
int vertexToNative(int vertex, int nsegments, int len) const;
int nativeToVertex(int vertex, int nsegments, int len) const;
};
template<class V, class E>
int Graph<V,E>::vertexToNative(int vertex, int nsegments, int len) const
{
if (true) {
int v = vertex-1;
int npartitions = num_threads * 16 * nsegments;
int height = len / npartitions;
int vmax = height * npartitions;
if(v >= vmax)
{
return v+1;
}
int col = v%npartitions;
int row = v/npartitions;
return row + col * height+ 1;
} else {
return vertex;
}
}
template<class V, class E>
int Graph<V,E>::nativeToVertex(int vertex, int nsegments, int len) const
{
if (true) {
int v = vertex-1;
int npartitions = num_threads * 16 * nsegments;
int height = len / npartitions;
int vmax = height * npartitions;
if(v >= vmax)
{
return v+1;
}
int col = v/height;
int row = v%height;
return col + row * npartitions+ 1;
} else {
return vertex;
}
}
template<class V, class E>
void Graph<V,E>::ReadGraphMatBin(const char* filename) {
std::stringstream fname_ss;
fname_ss << filename << GraphMat::get_global_myrank();
std::cout << "Reading file " << fname_ss.str() << std::endl;
std::ifstream ifilestream(fname_ss.str().c_str(), std::ios::in|std::ios::binary);
boost::archive::binary_iarchive bi(ifilestream);
struct timeval start, end;
gettimeofday(&start, 0);
bi >> A;
bi >> AT;
tiles_per_dim = GraphMat::get_global_nrank();
if(A->ntiles_x != tiles_per_dim || A->ntiles_y != tiles_per_dim ||
AT->ntiles_x != tiles_per_dim || AT->ntiles_y != tiles_per_dim) {
std::cout << "Error reading file - mismatch in number of MPI ranks used in load vs save graph" << std::endl;
exit(1);
}
bi >> num_threads;
if(num_threads != omp_get_max_threads()) {
std::cout << "Error reading file - mismatch in number of OpenMP threads used in load vs save graph" << std::endl;
exit(1);
}
nvertices = A->m;
vertexproperty = new GraphMat::SpVec<GraphMat::DenseSegment<V> >(A->m, tiles_per_dim, GraphMat::vector_partition_fn);
V *__v = new V;
vertexproperty->setAll(*__v);
delete __v;
active = new GraphMat::SpVec<GraphMat::DenseSegment<bool> >(A->m, tiles_per_dim, GraphMat::vector_partition_fn);
active->setAll(false);
vertexpropertyowner = true;
nnz = A->getNNZ();
gettimeofday(&end, 0);
std::cout << "Finished GraphMat read + construction, time: " << sec(start,end) << std::endl;
ifilestream.close();
MPI_Barrier(MPI_COMM_WORLD);
}
template<class V, class E>
void Graph<V,E>::WriteGraphMatBin(const char* filename) {
std::stringstream fname_ss;
fname_ss << filename << GraphMat::get_global_myrank();
std::cout << "Writing file " << fname_ss.str() << std::endl;
std::ofstream ofilestream(fname_ss.str().c_str(), std::ios::out|std::ios::binary);
boost::archive::binary_oarchive bo(ofilestream);
bo << A;
bo << AT;
bo << num_threads;
ofilestream.close();
MPI_Barrier(MPI_COMM_WORLD);
}
template<class V, class E>
void Graph<V,E>::ReadEdgelist(GraphMat::edgelist_t<E> A_edges) {
struct timeval start, end;
gettimeofday(&start, 0);
tiles_per_dim = GraphMat::get_global_nrank();
num_threads = omp_get_max_threads();
#pragma omp parallel for
for(int i = 0 ; i < A_edges.nnz ; i++)
{
A_edges.edges[i].src = vertexToNative(A_edges.edges[i].src, tiles_per_dim, A_edges.m);
A_edges.edges[i].dst = vertexToNative(A_edges.edges[i].dst, tiles_per_dim, A_edges.m);
}
A = new GraphMat::SpMat<GraphMat::DCSCTile<E> >(A_edges, tiles_per_dim, tiles_per_dim, GraphMat::partition_fn_2d);
GraphMat::Transpose(A, &AT, tiles_per_dim, tiles_per_dim, GraphMat::partition_fn_2d);
int m_ = A->m;
assert(A->m == A->n);
nnz = A->getNNZ();
vertexproperty = new GraphMat::SpVec<GraphMat::DenseSegment<V> >(A->m, tiles_per_dim, GraphMat::vector_partition_fn);
V *__v = new V;
vertexproperty->setAll(*__v);
delete __v;
active = new GraphMat::SpVec<GraphMat::DenseSegment<bool> >(A->m, tiles_per_dim, GraphMat::vector_partition_fn);
active->setAll(false);
nvertices = m_;
vertexpropertyowner = true;
gettimeofday(&end, 0);
std::cout << "Finished GraphMat read + construction, time: " << sec(start,end) << std::endl;
}
template<class V, class E>
void Graph<V,E>::ReadMTX(const char* filename) {
GraphMat::edgelist_t<E> A_edges;
GraphMat::load_edgelist(filename, &A_edges, true, true, true);// binary format with header and edge weights
if (A_edges.m != A_edges.n) {
auto maxn = std::max(A_edges.m, A_edges.n);
A_edges.m = maxn;
A_edges.n = maxn;
}
ReadEdgelist(A_edges);
A_edges.clear();
}
template<class V, class E>
void Graph<V,E>::setAllActive() {
active->setAll(true);
}
template<class V, class E>
void Graph<V,E>::setAllInactive() {
active->setAll(false);
int global_myrank = GraphMat::get_global_myrank();
for(int segmentId = 0 ; segmentId < active->nsegments ; segmentId++)
{
if(active->nodeIds[segmentId] == global_myrank)
{
GraphMat::DenseSegment<bool>* s1 = active->segments[segmentId];
GraphMat::clear_dense_segment(s1->properties->value, s1->properties->bit_vector, s1->num_ints);
}
}
}
template<class V, class E>
void Graph<V,E>::setActive(int v) {
int v_new = vertexToNative(v, tiles_per_dim, nvertices);
active->set(v_new, true);
}
template<class V, class E>
void Graph<V,E>::setInactive(int v) {
int v_new = vertexToNative(v, tiles_per_dim, nvertices);
active->unset(v_new);
}
template<class V, class E>
void Graph<V,E>::reset() {
setAllInactive();
V v;
vertexproperty->setAll(v);
}
template<class V, class E>
void Graph<V,E>::shareVertexProperty(Graph<V,E>& g) {
if (vertexproperty != nullptr) delete vertexproperty;
vertexproperty = g.vertexproperty;
vertexpropertyowner = false;
}
template<class V, class E>
void Graph<V,E>::setAllVertexproperty(const V& val) {
vertexproperty->setAll(val);
}
template<class V, class E>
void Graph<V,E>::setVertexproperty(int v, const V& val) {
int v_new = vertexToNative(v, tiles_per_dim, nvertices);
vertexproperty->set(v_new, val);
}
template<class V, class E>
void Graph<V,E>::getVertexEdgelist(GraphMat::edgelist_t<V> & myedges) {
vertexproperty->get_edges(&myedges);
for(unsigned int i = 0 ; i < myedges.nnz ; i++)
{
myedges.edges[i].src = nativeToVertex(myedges.edges[i].src, tiles_per_dim, nvertices);
}
}
template<class V, class E>
void Graph<V,E>::getEdgelist(GraphMat::edgelist_t<E> & myedges) {
A->get_edges(&myedges);
for(unsigned int i = 0 ; i < myedges.nnz ; i++)
{
myedges.edges[i].src = nativeToVertex(myedges.edges[i].src, tiles_per_dim, nvertices);
myedges.edges[i].dst = nativeToVertex(myedges.edges[i].dst, tiles_per_dim, nvertices);
}
}
template<class V, class E>
void Graph<V,E>::saveVertexproperty(std::string fname, bool includeHeader) const {
GraphMat::edgelist_t<V> myedges;
vertexproperty->get_edges(&myedges);
for(unsigned int i = 0 ; i < myedges.nnz ; i++)
{
myedges.edges[i].src = nativeToVertex(myedges.edges[i].src, tiles_per_dim, nvertices);
}
GraphMat::SpVec<GraphMat::DenseSegment<V> > * vertexproperty2 = new GraphMat::SpVec<GraphMat::DenseSegment<V> >(nvertices, tiles_per_dim, GraphMat::vector_partition_fn);
vertexproperty2->ingestEdgelist(myedges);
myedges.clear();
vertexproperty2->save(fname, includeHeader);
delete vertexproperty2;
}
template<class V, class E>
bool Graph<V,E>::vertexNodeOwner(const int v) const {
int v_new = vertexToNative(v, tiles_per_dim, nvertices);
return vertexproperty->node_owner(v_new);
}
template<class V, class E>
V Graph<V,E>::getVertexproperty(const int v) const {
V vp ;
int v_new = vertexToNative(v, tiles_per_dim, nvertices);
vertexproperty->get(v_new, &vp);
return vp;
}
template<class V, class E>
int Graph<V,E>::getNumberOfVertices() const {
return nvertices;
}
template<class V, class E>
void Graph<V,E>::applyToAllVertices( void (*ApplyFn)(const V&, V*, void*), void* param) {
GraphMat::Apply(vertexproperty, vertexproperty, ApplyFn, param);
}
template<class V, class E>
template<class T>
void Graph<V,E>::applyReduceAllVertices(T* val, void (*ApplyFn)(V*, T*, void*), void (*ReduceFn)(const T&, const T&,T*,void*), void* param) {
GraphMat::MapReduce(vertexproperty, val, ApplyFn, ReduceFn, param);
}
template <class V, class E>
struct func_with_param {
void (*Func)(E*, const V&, const V&, void*);
void* param;
};
template<class V, class E>
void Graph<V,E>::applyToAllEdges(void (*ApplyFn)(E* edge, const V& src, const V& dst, void*), void* param) {
GraphMat::ApplyEdges(AT, vertexproperty, ApplyFn, param);
struct func_with_param<V,E> s;
s.Func = ApplyFn;
s.param = param;
void (*ApplyFn2)(E*, const V&, const V&, void*);
ApplyFn2 = [](E* e, const V& src, const V& dst, void* p){
struct func_with_param<V,E>* f =(struct func_with_param<V,E>*)(p);
f->Func(e, dst, src, f->param);
};
GraphMat::ApplyEdges(A, vertexproperty, ApplyFn2, (void*)(&s) );
}
template<class V, class E>
Graph<V,E>::~Graph() {
if (A != nullptr) {
delete A;
A = nullptr;
}
if (AT != nullptr) {
delete AT;
AT = nullptr;
}
if (vertexpropertyowner) {
if (vertexproperty != nullptr) {
delete vertexproperty;
vertexproperty = nullptr;
}
}
if (active != nullptr) {
delete active;
active = nullptr;
}
}
} //namespace GraphMat
|
fluxes.c | /*---------------------------------------------------------------------------------
FLUXES.C
-Compute fluid fluxes
-Apply constrained transport
---------------------------------------------------------------------------------*/
#include "decs.h"
void lr_to_flux(struct GridGeom *G, struct FluidState *Sl, struct FluidState *Sr, int dir, int loc, GridPrim *flux, GridVector *ctop);
double ndt_min(GridVector *ctop);
double ndt_min(GridVector *ctop)
{
timer_start(TIMER_CMAX);
double ndt_min = 1e20;
#if DEBUG
int min_x1, min_x2;
#endif
#pragma omp parallel for collapse(2) reduction(min:ndt_min)
ZLOOP
{
double ndt_zone = 0;
for (int mu = 1; mu < NDIM-1; mu++)
ndt_zone += 1/(cour*dx[mu]/(*ctop)[mu][j][i]);
ndt_zone = 1/ndt_zone;
if(ndt_zone < ndt_min)
{
ndt_min = ndt_zone;
#if DEBUG
min_x1 = i;
min_x2 = j;
#endif
}
}
#if DEBUG
fprintf(stderr, "Timestep set by %d %d\n",min_x1, min_x2);
#endif
timer_stop(TIMER_CMAX);
return ndt_min;
}
double get_flux(struct GridGeom *G, struct FluidState *S, struct FluidFlux *F)
{
static struct FluidState *Sl, *Sr;
static GridVector *ctop;
double cmax[NDIM], ndts[NDIM];
memset(cmax, 0, NDIM*sizeof(double));
memset(ndts, 0, NDIM*sizeof(double));
static int firstc = 1;
if (firstc)
{
Sl = calloc(1,sizeof(struct FluidState));
Sr = calloc(1,sizeof(struct FluidState));
ctop = calloc(1,sizeof(GridVector));
firstc = 0;
}
// reconstruct X1
reconstruct(S, Sl->P, Sr->P, 1);
// lr_to_flux X1
lr_to_flux(G, Sl, Sr, 1, FACE1, &(F->X1), ctop);
// reconstruct X2
reconstruct(S, Sl->P, Sr->P, 2);
// lr_to_flux X2
lr_to_flux(G, Sl, Sr, 2, FACE2, &(F->X2), ctop);
return ndt_min(ctop);
}
// Note that the sense of L/R flips from zone to interface during function call
void lr_to_flux(struct GridGeom *G, struct FluidState *Sr, struct FluidState *Sl, int dir, int loc, GridPrim *flux, GridVector *ctop)
{
timer_start(TIMER_LR_TO_F);
static GridPrim *fluxL, *fluxR;
static GridDouble *cmaxL, *cmaxR, *cminL, *cminR, *cmax, *cmin;
static int firstc = 1;
if (firstc)
{
fluxL = calloc(1,sizeof(GridPrim));
fluxR = calloc(1,sizeof(GridPrim));
cmaxL = calloc(1,sizeof(GridDouble));
cmaxR = calloc(1,sizeof(GridDouble));
cminL = calloc(1,sizeof(GridDouble));
cminR = calloc(1,sizeof(GridDouble));
cmax = calloc(1,sizeof(GridDouble));
cmin = calloc(1,sizeof(GridDouble));
firstc = 0;
}
// Properly offset left face
// These are un-macro'd to bundle OpenMP thread tasks rather than memory accesses
PLOOP
{
if (dir == 1)
{
#pragma omp parallel for
ZSLOOP_REVERSE(-1, N2, -1, N1)
Sl->P[ip][j][i] = Sl->P[ip][j][i - 1];
}
else if (dir == 2)
{
#pragma omp parallel for
for (int i = (N1) + NG; i >= (-1) + NG; i--)
for (int j = (N2) + NG; j >= (-1) + NG; j--)
Sl->P[ip][j][i] = Sl->P[ip][j - 1][i];
}
}
timer_start(TIMER_LR_STATE);
get_state_vec(G, Sl, loc, -1, N2, -1, N1);
get_state_vec(G, Sr, loc, -1, N2, -1, N1);
timer_stop(TIMER_LR_STATE);
timer_start(TIMER_LR_PTOF);
prim_to_flux_vec(G, Sl, 0, loc, -1, N2, -1, N1, Sl->U);
prim_to_flux_vec(G, Sl, dir, loc, -1, N2, -1, N1, *fluxL);
prim_to_flux_vec(G, Sr, 0, loc, -1, N2, -1, N1, Sr->U);
prim_to_flux_vec(G, Sr, dir, loc, -1, N2, -1, N1, *fluxR);
timer_stop(TIMER_LR_PTOF);
timer_start(TIMER_LR_VCHAR);
#pragma omp parallel
{
#pragma omp for nowait
ZSLOOP(-1, N2, -1, N1)
mhd_vchar(G, Sl, i, j, loc, dir, *cmaxL, *cminL);
#pragma omp for
ZSLOOP(-1, N2, -1, N1)
mhd_vchar(G, Sr, i, j, loc, dir, *cmaxR, *cminR);
}
timer_stop(TIMER_LR_VCHAR);
timer_start(TIMER_LR_CMAX);
#pragma omp parallel for
ZSLOOP(-1, N2, -1, N1)
{
(*cmax)[j][i] = fabs(MY_MAX(MY_MAX(0., (*cmaxL)[j][i]), (*cmaxR)[j][i]));
(*cmin)[j][i] = fabs(MY_MAX(MY_MAX(0., -(*cminL)[j][i]), -(*cminR)[j][i]));
(*ctop)[dir][j][i] = MY_MAX((*cmax)[j][i], (*cmin)[j][i]);
if (isnan(1./(*ctop)[dir][j][i]))
{
printf("ctop is 0 or NaN at zone: %i %i (%i) ", i, j, dir);
#if METRIC == MKS
double X[NDIM];
double r, th;
coord(i, j, CENT, X);
bl_coord(X, &r, &th);
printf("(r,th = %f %f)\n", r, th);
#endif
printf("\n");
exit(-1);
}
}
timer_stop(TIMER_LR_CMAX);
timer_start(TIMER_LR_FLUX);
#pragma omp parallel for simd collapse(2)
PLOOP
ZSLOOP(-1, N2, -1, N1)
(*flux)[ip][j][i] = 0.5*((*fluxL)[ip][j][i] + (*fluxR)[ip][j][i] - (*ctop)[dir][j][i]*(Sr->U[ip][j][i] - Sl->U[ip][j][i]));
timer_stop(TIMER_LR_FLUX);
timer_stop(TIMER_LR_TO_F);
}
void flux_ct(struct FluidFlux *F)
{
timer_start(TIMER_FLUX_CT);
static GridDouble emf;
static int firstc = 1;
if (firstc)
{
firstc = 0;
}
#pragma omp parallel
{
#pragma omp for simd
ZSLOOP(0, N2, 0, N1)
emf[j][i] = 0.25*(F->X1[B2][j][i] + F->X1[B2][j-1][i] - F->X2[B1][j][i] - F->X2[B1][j][i-1]);
// Rewrite EMFs as fluxes, after Toth
#pragma omp for simd nowait
ZSLOOP(0, N2 - 1, 0, N1)
{
F->X1[B1][j][i] = 0.;
F->X1[B2][j][i] = 0.5*(emf[j][i] + emf[j+1][i]);
}
#pragma omp for simd nowait
ZSLOOP(0, N2, 0, N1 - 1)
{
F->X2[B1][j][i] = -0.5*(emf[j][i] + emf[j][i+1]);
F->X2[B2][j][i] = 0.;
}
} // omp parallel
timer_stop(TIMER_FLUX_CT);
}
|
timing.c | /******************************************************************************
* *
* TIMING.C *
* *
* PERFORMANCE TIMING AND REPORTING *
* *
******************************************************************************/
#include "decs.h"
static double timers[NUM_TIMERS];
static double times[NUM_TIMERS];
static int nstep_start;
void time_set(int n, double val) { times[n] = val; }
double time_read(int n) { return times[n]; }
void time_init() {
for (int n = 0; n < NUM_TIMERS; n++) {
times[n] = 0.;
}
nstep_start = nstep;
}
void timer_start(int timerCode) {
#pragma omp barrier
#pragma omp single
{
mpi_barrier();
timers[timerCode] = omp_get_wtime();
}
}
void timer_stop(int timerCode) {
#pragma omp barrier
#pragma omp single
{
mpi_barrier();
times[timerCode] += (omp_get_wtime() - timers[timerCode]);
}
}
void timers_reset() {
for (int n = 0; n < NUM_TIMERS; n++) {
times[n] = 0.;
}
}
double get_time_per_step(int timerCode) {
int dnstep = nstep - nstep_start;
return times[timerCode] / dnstep;
}
// Report a running average of timing data
void report_performance() {
if (mpi_myrank() == 0) {
int dnstep = nstep - nstep_start;
fprintf(stdout, "\n********** PERFORMANCE **********\n");
fprintf(stdout, " UPDATE: %8.4g s (%.4g %%)\n",
times[TIMER_UPDATE] / dnstep,
100. * times[TIMER_UPDATE] / times[TIMER_ALL]);
fprintf(stdout, " FLUXCALC: %8.4g s (%.4g %%)\n",
times[TIMER_FLUXCALC] / dnstep,
100. * times[TIMER_FLUXCALC] / times[TIMER_ALL]);
fprintf(stdout, " FIXUP: %8.4g s (%.4g %%)\n",
times[TIMER_FIXUP] / dnstep,
100. * times[TIMER_FIXUP] / times[TIMER_ALL]);
fprintf(stdout, " BOUND: %8.4g s (%.4g %%)\n",
times[TIMER_BOUND] / dnstep,
100. * times[TIMER_BOUND] / times[TIMER_ALL]);
fprintf(stdout, " DIAG: %8.4g s (%.4g %%)\n",
times[TIMER_DIAG] / dnstep,
100. * times[TIMER_DIAG] / times[TIMER_ALL]);
fprintf(stdout, " OUTPUT: %8.4g s (%.4g %%)\n",
times[TIMER_OUT] / dnstep, 100. * times[TIMER_OUT] / times[TIMER_ALL]);
#if ELECTRONS
fprintf(stdout, " ELECTRON: %8.4g s (%.4g %%)\n",
times[TIMER_ELECTRON] / dnstep,
100. * times[TIMER_ELECTRON] / times[TIMER_ALL]);
#endif
#if RADIATION
fprintf(stdout, " MAKE: %8.4g s (%.4g %%)\n",
times[TIMER_MAKE] / dnstep,
100. * times[TIMER_MAKE] / times[TIMER_ALL]);
fprintf(stdout, " PUSH: %8.4g s (%.4g %%)\n",
times[TIMER_PUSH] / dnstep,
100. * times[TIMER_PUSH] / times[TIMER_ALL]);
fprintf(stdout, " INTERACT: %8.4g s (%.4g %%)\n",
times[TIMER_INTERACT] / dnstep,
100. * times[TIMER_INTERACT] / times[TIMER_ALL]);
fprintf(stdout, " MICRPHYS: %8.4g s (%.4g %%)\n",
times[TIMER_MICRO] / dnstep,
100. * times[TIMER_MICRO] / times[TIMER_ALL]);
#endif
fprintf(stdout, " ALL: %8.4g s\n", times[TIMER_ALL] / dnstep);
fprintf(stdout, " ZONE CYCLES PER\n");
fprintf(stdout, " CORE-SECOND: %e\n",
N1 * N2 * N3 / (times[TIMER_ALL] * nthreads / dnstep));
fprintf(stdout, " NODE-SECOND: %e\n",
N1 * N2 * N3 / (times[TIMER_ALL] / dnstep));
fprintf(stdout, "*********************************\n\n");
}
}
|
GB_binop__rdiv_fc32.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__rdiv_fc32)
// A.*B function (eWiseMult): GB (_AemultB_08__rdiv_fc32)
// A.*B function (eWiseMult): GB (_AemultB_02__rdiv_fc32)
// A.*B function (eWiseMult): GB (_AemultB_04__rdiv_fc32)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__rdiv_fc32)
// A*D function (colscale): GB (_AxD__rdiv_fc32)
// D*A function (rowscale): GB (_DxB__rdiv_fc32)
// C+=B function (dense accum): GB (_Cdense_accumB__rdiv_fc32)
// C+=b function (dense accum): GB (_Cdense_accumb__rdiv_fc32)
// C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__rdiv_fc32)
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__rdiv_fc32)
// C=scalar+B GB (_bind1st__rdiv_fc32)
// C=scalar+B' GB (_bind1st_tran__rdiv_fc32)
// C=A+scalar GB (_bind2nd__rdiv_fc32)
// C=A'+scalar GB (_bind2nd_tran__rdiv_fc32)
// C type: GxB_FC32_t
// A type: GxB_FC32_t
// A pattern? 0
// B type: GxB_FC32_t
// B pattern? 0
// BinaryOp: cij = GB_FC32_div (bij, aij)
#define GB_ATYPE \
GxB_FC32_t
#define GB_BTYPE \
GxB_FC32_t
#define GB_CTYPE \
GxB_FC32_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) \
GxB_FC32_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) \
GxB_FC32_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) \
GxB_FC32_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_FC32_div (y, x) ;
// 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_RDIV || GxB_NO_FC32 || GxB_NO_RDIV_FC32)
//------------------------------------------------------------------------------
// 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__rdiv_fc32)
(
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
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__rdiv_fc32)
(
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__rdiv_fc32)
(
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__rdiv_fc32)
(
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 GxB_FC32_t
GxB_FC32_t bwork = (*((GxB_FC32_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__rdiv_fc32)
(
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
GxB_FC32_t *restrict Cx = (GxB_FC32_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__rdiv_fc32)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GxB_FC32_t *restrict Cx = (GxB_FC32_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__rdiv_fc32)
(
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) ;
GxB_FC32_t alpha_scalar ;
GxB_FC32_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((GxB_FC32_t *) alpha_scalar_in)) ;
beta_scalar = (*((GxB_FC32_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__rdiv_fc32)
(
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__rdiv_fc32)
(
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__rdiv_fc32)
(
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__rdiv_fc32)
(
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__rdiv_fc32)
(
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
GxB_FC32_t *Cx = (GxB_FC32_t *) Cx_output ;
GxB_FC32_t x = (*((GxB_FC32_t *) x_input)) ;
GxB_FC32_t *Bx = (GxB_FC32_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 ;
GxB_FC32_t bij = GBX (Bx, p, false) ;
Cx [p] = GB_FC32_div (bij, x) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__rdiv_fc32)
(
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 ;
GxB_FC32_t *Cx = (GxB_FC32_t *) Cx_output ;
GxB_FC32_t *Ax = (GxB_FC32_t *) Ax_input ;
GxB_FC32_t y = (*((GxB_FC32_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
GxB_FC32_t aij = GBX (Ax, p, false) ;
Cx [p] = GB_FC32_div (y, aij) ;
}
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) \
{ \
GxB_FC32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_FC32_div (aij, x) ; \
}
GrB_Info GB (_bind1st_tran__rdiv_fc32)
(
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 \
GxB_FC32_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GxB_FC32_t x = (*((const GxB_FC32_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
GxB_FC32_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) \
{ \
GxB_FC32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_FC32_div (y, aij) ; \
}
GrB_Info GB (_bind2nd_tran__rdiv_fc32)
(
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
GxB_FC32_t y = (*((const GxB_FC32_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
composite.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% CCCC OOO M M PPPP OOO SSSSS IIIII TTTTT EEEEE %
% C O O MM MM P P O O SS I T E %
% C O O M M M PPPP O O SSS I T EEE %
% C O O M M P O O SS I T E %
% CCCC OOO M M P OOO SSSSS IIIII T EEEEE %
% %
% %
% MagickCore Image Composite Methods %
% %
% Software Design %
% John Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2013 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 %
% %
% http://www.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 "magick/studio.h"
#include "magick/artifact.h"
#include "magick/cache-view.h"
#include "magick/channel.h"
#include "magick/client.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/composite.h"
#include "magick/composite-private.h"
#include "magick/constitute.h"
#include "magick/draw.h"
#include "magick/fx.h"
#include "magick/gem.h"
#include "magick/geometry.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/memory_.h"
#include "magick/option.h"
#include "magick/pixel-private.h"
#include "magick/property.h"
#include "magick/quantum.h"
#include "magick/resample.h"
#include "magick/resource_.h"
#include "magick/string_.h"
#include "magick/thread-private.h"
#include "magick/threshold.h"
#include "magick/token.h"
#include "magick/utility.h"
#include "magick/version.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o m p o s i t e I m a g e C h a n n e l %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CompositeImageChannel() returns the second image composited onto the first
% at the specified offset, using the specified composite method.
%
% The format of the CompositeImageChannel method is:
%
% MagickBooleanType CompositeImage(Image *image,
% const CompositeOperator compose,Image *composite_image,
% const ssize_t x_offset,const ssize_t y_offset)
% MagickBooleanType CompositeImageChannel(Image *image,
% const ChannelType channel,const CompositeOperator compose,
% Image *composite_image,const ssize_t x_offset,const ssize_t y_offset)
%
% A description of each parameter follows:
%
% o image: the destination image, modified by he composition
%
% o channel: the channel.
%
% o compose: This operator affects how the composite is applied to
% the image. The operators and how they are utilized are listed here
% http://www.w3.org/TR/SVG12/#compositing.
%
% o composite_image: the composite (source) image.
%
% o x_offset: the column offset of the composited image.
%
% o y_offset: the row offset of the composited image.
%
% Extra Controls from Image meta-data in 'composite_image' (artifacts)
%
% o "compose:args"
% A string containing extra numerical arguments for specific compose
% methods, generally expressed as a 'geometry' or a comma separated list
% of numbers.
%
% Compose methods needing such arguments include "BlendCompositeOp" and
% "DisplaceCompositeOp".
%
% o "compose:outside-overlay"
% Modify how the composition is to effect areas not directly covered
% by the 'composite_image' at the offset given. Normally this is
% dependant on the 'compose' method, especially Duff-Porter methods.
%
% If set to "false" then disable all normal handling of pixels not
% covered by the composite_image. Typically used for repeated tiling
% of the composite_image by the calling API.
%
% Previous to IM v6.5.3-3 this was called "modify-outside-overlay"
%
*/
static inline double MagickMin(const double x,const double y)
{
if (x < y)
return(x);
return(y);
}
static inline double MagickMax(const double x,const double y)
{
if (x > y)
return(x);
return(y);
}
/*
** Programmers notes on SVG specification.
**
** A Composition is defined by...
** Color Function : f(Sc,Dc) where Sc and Dc are the normizalized colors
** Blending areas : X = 1 for area of overlap ie: f(Sc,Dc)
** Y = 1 for source preserved
** Z = 1 for destination preserved
**
** Conversion to transparency (then optimized)
** Dca' = f(Sc, Dc)*Sa*Da + Y*Sca*(1-Da) + Z*Dca*(1-Sa)
** Da' = X*Sa*Da + Y*Sa*(1-Da) + Z*Da*(1-Sa)
**
** Where...
** Sca = Sc*Sa normalized Source color divided by Source alpha
** Dca = Dc*Da normalized Dest color divided by Dest alpha
** Dc' = Dca'/Da' the desired color value for this channel.
**
** Da' in in the follow formula as 'gamma' The resulting alpla value.
**
**
** Most functions use a blending mode of over (X=1,Y=1,Z=1)
** this results in the following optimizations...
** gamma = Sa+Da-Sa*Da;
** gamma = 1 - QuantiumScale*alpha * QuantiumScale*beta;
** opacity = QuantiumScale*alpha*beta; // over blend, optimized 1-Gamma
**
** The above SVG definitions also definate that Mathematical Composition
** methods should use a 'Over' blending mode for Alpha Channel.
** It however was not applied for composition modes of 'Plus', 'Minus',
** the modulus versions of 'Add' and 'Subtract'.
**
**
** Mathematical operator changes to be applied from IM v6.7...
**
** 1/ Modulus modes 'Add' and 'Subtract' are obsoleted and renamed
** 'ModulusAdd' and 'ModulusSubtract' for clarity.
**
** 2/ All mathematical compositions work as per the SVG specification
** with regard to blending. This now includes 'ModulusAdd' and
** 'ModulusSubtract'.
**
** 3/ When the special channel flag 'sync' (syncronize channel updates)
** is turned off (enabled by default) then mathematical compositions are
** only performed on the channels specified, and are applied
** independantally of each other. In other words the mathematics is
** performed as 'pure' mathematical operations, rather than as image
** operations.
*/
static inline MagickRealType Atop(const MagickRealType p,
const MagickRealType Sa,const MagickRealType q,
const MagickRealType magick_unused(Da))
{
return(p*Sa+q*(1.0-Sa)); /* Da optimized out, Da/gamma => 1.0 */
}
static inline void CompositeAtop(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
MagickRealType
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
composite->opacity=q->opacity; /* optimized Da = 1.0-Gamma */
composite->red=Atop(p->red,Sa,q->red,1.0);
composite->green=Atop(p->green,Sa,q->green,1.0);
composite->blue=Atop(p->blue,Sa,q->blue,1.0);
if (q->colorspace == CMYKColorspace)
composite->index=Atop(p->index,Sa,q->index,1.0);
}
/*
What is this Composition method for? Can't find any specification!
WARNING this is not doing correct 'over' blend handling (Anthony Thyssen).
*/
static inline void CompositeBumpmap(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
MagickRealType
intensity;
intensity=MagickPixelIntensity(p);
composite->red=QuantumScale*intensity*q->red;
composite->green=QuantumScale*intensity*q->green;
composite->blue=QuantumScale*intensity*q->blue;
composite->opacity=(MagickRealType) QuantumScale*intensity*
p->opacity;
if (q->colorspace == CMYKColorspace)
composite->index=QuantumScale*intensity*q->index;
}
static inline void CompositeClear(const MagickPixelPacket *q,
MagickPixelPacket *composite)
{
composite->opacity=(MagickRealType) TransparentOpacity;
composite->red=0.0;
composite->green=0.0;
composite->blue=0.0;
if (q->colorspace == CMYKColorspace)
composite->index=0.0;
}
static MagickRealType ColorBurn(const MagickRealType Sca,
const MagickRealType Sa, const MagickRealType Dca,const MagickRealType Da)
{
#if 0
/*
Oct 2004 SVG specification.
*/
if (Sca*Da + Dca*Sa <= Sa*Da)
return(Sca*(1.0-Da)+Dca*(1.0-Sa));
return(Sa*(Sca*Da+Dca*Sa-Sa*Da)/Sca + Sca*(1.0-Da) + Dca*(1.0-Sa));
#else
/*
March 2009 SVG specification.
*/
if ((fabs(Sca) < MagickEpsilon) && (fabs(Dca-Da) < MagickEpsilon))
return(Sa*Da+Dca*(1.0-Sa));
if (Sca < MagickEpsilon)
return(Dca*(1.0-Sa));
return(Sa*Da-Sa*MagickMin(Da,(Da-Dca)*Sa/Sca)+Sca*(1.0-Da)+Dca*(1.0-Sa));
#endif
}
static inline void CompositeColorBurn(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
MagickRealType
Da,
gamma,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*ColorBurn(QuantumScale*p->red*Sa,Sa,QuantumScale*
q->red*Da,Da);
composite->green=gamma*ColorBurn(QuantumScale*p->green*Sa,Sa,QuantumScale*
q->green*Da,Da);
composite->blue=gamma*ColorBurn(QuantumScale*p->blue*Sa,Sa,QuantumScale*
q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*ColorBurn(QuantumScale*p->index*Sa,Sa,QuantumScale*
q->index*Da,Da);
}
static MagickRealType ColorDodge(const MagickRealType Sca,
const MagickRealType Sa, const MagickRealType Dca,const MagickRealType Da)
{
#if 0
/*
Oct 2004 SVG specification.
*/
if ((Sca*Da+Dca*Sa) >= Sa*Da)
return( Sa*Da + Sca*(1.0-Da) + Dca*(1.0-Sa) );
return( Dca*Sa*Sa/(Sa-Sca) + Sca*(1.0-Da) + Dca*(1.0-Sa) );
#endif
#if 0
/*
New specification, March 2009 SVG specification. This specification was
also wrong of non-overlap cases.
*/
if ((fabs(Sca-Sa) < MagickEpsilon) && (fabs(Dca) < MagickEpsilon))
return(Sca*(1.0-Da));
if (fabs(Sca-Sa) < MagickEpsilon)
return(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa));
return(Sa*MagickMin(Da,Dca*Sa/(Sa-Sca)));
#endif
/*
Working from first principles using the original formula:
f(Sc,Dc) = Dc/(1-Sc)
This works correctly! Looks like the 2004 model was right but just
required a extra condition for correct handling.
*/
if ((fabs(Sca-Sa) < MagickEpsilon) && (fabs(Dca) < MagickEpsilon))
return(Sca*(1.0-Da)+Dca*(1.0-Sa));
if (fabs(Sca-Sa) < MagickEpsilon)
return(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa));
return(Dca*Sa*Sa/(Sa-Sca)+Sca*(1.0-Da)+Dca*(1.0-Sa));
}
static inline void CompositeColorDodge(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
MagickRealType
Da,
gamma,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*ColorDodge(QuantumScale*p->red*Sa,Sa,QuantumScale*
q->red*Da,Da);
composite->green=gamma*ColorDodge(QuantumScale*p->green*Sa,Sa,QuantumScale*
q->green*Da,Da);
composite->blue=gamma*ColorDodge(QuantumScale*p->blue*Sa,Sa,QuantumScale*
q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*ColorDodge(QuantumScale*p->index*Sa,Sa,QuantumScale*
q->index*Da,Da);
}
static inline MagickRealType Darken(const MagickRealType p,
const MagickRealType alpha,const MagickRealType q,const MagickRealType beta)
{
if (p < q)
return(MagickOver_(p,alpha,q,beta)); /* src-over */
return(MagickOver_(q,beta,p,alpha)); /* dst-over */
}
static inline void CompositeDarken(const MagickPixelPacket *p,
const MagickPixelPacket *q,const ChannelType channel,
MagickPixelPacket *composite)
{
/*
Darken is equivalent to a 'Minimum' method
OR a greyscale version of a binary 'Or'
OR the 'Intersection' of pixel sets.
*/
double
gamma;
if ( (channel & SyncChannels) != 0 ) {
composite->opacity=QuantumScale*p->opacity*q->opacity; /* Over Blend */
gamma=1.0-QuantumScale*composite->opacity;
gamma=PerceptibleReciprocal(gamma);
composite->red=gamma*Darken(p->red,p->opacity,q->red,q->opacity);
composite->green=gamma*Darken(p->green,p->opacity,q->green,q->opacity);
composite->blue=gamma*Darken(p->blue,p->opacity,q->blue,q->opacity);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*Darken(p->index,p->opacity,q->index,q->opacity);
}
else { /* handle channels as separate grayscale channels */
if ( (channel & AlphaChannel) != 0 )
composite->opacity=MagickMax(p->opacity,q->opacity);
if ( (channel & RedChannel) != 0 )
composite->red=MagickMin(p->red,q->red);
if ( (channel & GreenChannel) != 0 )
composite->green=MagickMin(p->green,q->green);
if ( (channel & BlueChannel) != 0 )
composite->blue=MagickMin(p->blue,q->blue);
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index=MagickMin(p->index,q->index);
}
}
static inline void CompositeDarkenIntensity(const MagickPixelPacket *p,
const MagickPixelPacket *q,const ChannelType channel,
MagickPixelPacket *composite)
{
/*
Select the pixel based on the intensity level.
If 'Sync' flag select whole pixel based on alpha weighted intensity.
Otherwise use intensity only, but restrict copy according to channel.
*/
if ( (channel & SyncChannels) != 0 ) {
MagickRealType
Da,
Sa;
Sa=1.0-QuantumScale*p->opacity;
Da=1.0-QuantumScale*q->opacity;
*composite = (Sa*MagickPixelIntensity(p) < Da*MagickPixelIntensity(q))
? *p : *q;
}
else {
int from_p = (MagickPixelIntensity(p) < MagickPixelIntensity(q));
if ( (channel & AlphaChannel) != 0 )
composite->opacity = from_p ? p->opacity : q->opacity;
if ( (channel & RedChannel) != 0 )
composite->red = from_p ? p->red : q->red;
if ( (channel & GreenChannel) != 0 )
composite->green = from_p ? p->green : q->green;
if ( (channel & BlueChannel) != 0 )
composite->blue = from_p ? p->blue : q->blue;
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index = from_p ? p->index : q->index;
}
}
static inline MagickRealType Difference(const MagickRealType p,
const MagickRealType Sa,const MagickRealType q,const MagickRealType Da)
{
/* Optimized by Multipling by QuantumRange (taken from gamma). */
return(Sa*p+Da*q-Sa*Da*2.0*MagickMin(p,q));
}
static inline void CompositeDifference(const MagickPixelPacket *p,
const MagickPixelPacket *q,const ChannelType channel,
MagickPixelPacket *composite)
{
double
gamma;
MagickRealType
Da,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
if ( (channel & SyncChannels) != 0 ) {
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=PerceptibleReciprocal(gamma);
/* Values are not normalized as an optimization. */
composite->red=gamma*Difference(p->red,Sa,q->red,Da);
composite->green=gamma*Difference(p->green,Sa,q->green,Da);
composite->blue=gamma*Difference(p->blue,Sa,q->blue,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*Difference(p->index,Sa,q->index,Da);
}
else { /* handle channels as separate grayscale channels */
if ( (channel & AlphaChannel) != 0 )
composite->opacity=QuantumRange-fabs(p->opacity - q->opacity);
if ( (channel & RedChannel) != 0 )
composite->red=fabs(p->red - q->red);
if ( (channel & GreenChannel) != 0 )
composite->green=fabs(p->green - q->green);
if ( (channel & BlueChannel) != 0 )
composite->blue=fabs(p->blue - q->blue);
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index=fabs(p->index - q->index);
}
}
static MagickRealType Divide(const MagickRealType Sca,const MagickRealType Sa,
const MagickRealType Dca,const MagickRealType Da)
{
/*
Divide Source by Destination
f(Sc,Dc) = Sc / Dc
But with appropriate handling for special case of Dc == 0 specifically
so that f(Black,Black)=Black and f(non-Black,Black)=White.
It is however also important to correctly do 'over' alpha blending which
is why the formula becomes so complex.
*/
if ((fabs(Sca) < MagickEpsilon) && (fabs(Dca) < MagickEpsilon))
return(Sca*(1.0-Da)+Dca*(1.0-Sa));
if (fabs(Dca) < MagickEpsilon)
return(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa));
return(Sca*Da*Da/Dca+Sca*(1.0-Da)+Dca*(1.0-Sa));
}
static inline void CompositeDivide(const MagickPixelPacket *p,
const MagickPixelPacket *q,const ChannelType channel,
MagickPixelPacket *composite)
{
MagickRealType
Da,
gamma,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
if ( (channel & SyncChannels) != 0 ) {
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*Divide(QuantumScale*p->red*Sa,Sa,QuantumScale*
q->red*Da,Da);
composite->green=gamma*Divide(QuantumScale*p->green*Sa,Sa,QuantumScale*
q->green*Da,Da);
composite->blue=gamma*Divide(QuantumScale*p->blue*Sa,Sa,QuantumScale*
q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*Divide(QuantumScale*p->index*Sa,Sa,QuantumScale*
q->index*Da,Da);
}
else { /* handle channels as separate grayscale channels */
if ( (channel & AlphaChannel) != 0 )
composite->opacity=QuantumRange*(1.0-Divide(Sa,1.0,Da,1.0));
if ( (channel & RedChannel) != 0 )
composite->red=QuantumRange*
Divide(QuantumScale*p->red,1.0,QuantumScale*q->red,1.0);
if ( (channel & GreenChannel) != 0 )
composite->green=QuantumRange*
Divide(QuantumScale*p->green,1.0,QuantumScale*q->green,1.0);
if ( (channel & BlueChannel) != 0 )
composite->blue=QuantumRange*
Divide(QuantumScale*p->blue,1.0,QuantumScale*q->blue,1.0);
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index=QuantumRange*
Divide(QuantumScale*p->index,1.0,QuantumScale*q->index,1.0);
}
}
static MagickRealType Exclusion(const MagickRealType Sca,
const MagickRealType Sa, const MagickRealType Dca,const MagickRealType Da)
{
return(Sca*Da+Dca*Sa-2.0*Sca*Dca+Sca*(1.0-Da)+Dca*(1.0-Sa));
}
static inline void CompositeExclusion(const MagickPixelPacket *p,
const MagickPixelPacket *q,const ChannelType channel,
MagickPixelPacket *composite)
{
MagickRealType
gamma,
Sa,
Da;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
if ( (channel & SyncChannels) != 0 ) {
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*Exclusion(QuantumScale*p->red*Sa,Sa,QuantumScale*
q->red*Da,Da);
composite->green=gamma*Exclusion(QuantumScale*p->green*Sa,Sa,QuantumScale*
q->green*Da,Da);
composite->blue=gamma*Exclusion(QuantumScale*p->blue*Sa,Sa,QuantumScale*
q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*Exclusion(QuantumScale*p->index*Sa,Sa,QuantumScale*
q->index*Da,Da);
}
else { /* handle channels as separate grayscale channels */
if ( (channel & AlphaChannel) != 0 )
composite->opacity=QuantumRange*(1.0-Exclusion(Sa,1.0,Da,1.0));
if ( (channel & RedChannel) != 0 )
composite->red=QuantumRange*
Exclusion(QuantumScale*p->red,1.0,QuantumScale*q->red,1.0);
if ( (channel & GreenChannel) != 0 )
composite->green=QuantumRange*
Exclusion(QuantumScale*p->green,1.0,QuantumScale*q->green,1.0);
if ( (channel & BlueChannel) != 0 )
composite->blue=QuantumRange*
Exclusion(QuantumScale*p->blue,1.0,QuantumScale*q->blue,1.0);
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index=QuantumRange*
Exclusion(QuantumScale*p->index,1.0,QuantumScale*q->index,1.0);
}
}
static MagickRealType HardLight(const MagickRealType Sca,
const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da)
{
if ((2.0*Sca) < Sa)
return(2.0*Sca*Dca+Sca*(1.0-Da)+Dca*(1.0-Sa));
return(Sa*Da-2.0*(Da-Dca)*(Sa-Sca)+Sca*(1.0-Da)+Dca*(1.0-Sa));
}
static inline void CompositeHardLight(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
MagickRealType
Da,
gamma,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*HardLight(QuantumScale*p->red*Sa,Sa,QuantumScale*
q->red*Da,Da);
composite->green=gamma*HardLight(QuantumScale*p->green*Sa,Sa,QuantumScale*
q->green*Da,Da);
composite->blue=gamma*HardLight(QuantumScale*p->blue*Sa,Sa,QuantumScale*
q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*HardLight(QuantumScale*p->index*Sa,Sa,QuantumScale*
q->index*Da,Da);
}
static inline MagickRealType ConvertHueToRGB(MagickRealType m1,
MagickRealType m2,MagickRealType hue)
{
if (hue < 0.0)
hue+=1.0;
if (hue > 1.0)
hue-=1.0;
if ((6.0*hue) < 1.0)
return(m1+6.0*(m2-m1)*hue);
if ((2.0*hue) < 1.0)
return(m2);
if ((3.0*hue) < 2.0)
return(m1+6.0*(m2-m1)*(2.0/3.0-hue));
return(m1);
}
static void HCLComposite(const double hue,const double chroma,const double luma,
MagickRealType *red,MagickRealType *green,MagickRealType *blue)
{
double
b,
c,
g,
h,
m,
r,
x,
z;
/*
Convert HCL to RGB colorspace.
*/
assert(red != (MagickRealType *) NULL);
assert(green != (MagickRealType *) NULL);
assert(blue != (MagickRealType *) NULL);
h=6.0*hue;
c=chroma;
x=c*(1.0-fabs(fmod(h,2.0)-1.0));
r=0.0;
g=0.0;
b=0.0;
if ((0.0 <= h) && (h < 1.0))
{
r=c;
g=x;
}
else
if ((1.0 <= h) && (h < 2.0))
{
r=x;
g=c;
}
else
if ((2.0 <= h) && (h < 3.0))
{
g=c;
b=x;
}
else
if ((3.0 <= h) && (h < 4.0))
{
g=x;
b=c;
}
else
if ((4.0 <= h) && (h < 5.0))
{
r=x;
b=c;
}
else
if ((5.0 <= h) && (h < 6.0))
{
r=c;
b=x;
}
m=luma-(0.298839*r+0.586811*g+0.114350*b);
z=1.0;
if (m < 0.0)
{
z=luma/(luma-m);
m=0.0;
}
else
if (m+c > 1.0)
{
z=(1.0-luma)/(m+c-luma);
m=1.0-z*c;
}
*red=QuantumRange*(z*r+m);
*green=QuantumRange*(z*g+m);
*blue=QuantumRange*(z*b+m);
}
static void CompositeHCL(const MagickRealType red,const MagickRealType green,
const MagickRealType blue,double *hue,double *chroma,double *luma)
{
double
b,
c,
g,
h,
max,
r;
/*
Convert RGB to HCL colorspace.
*/
assert(hue != (double *) NULL);
assert(chroma != (double *) NULL);
assert(luma != (double *) NULL);
r=(double) red;
g=(double) green;
b=(double) blue;
max=MagickMax(r,MagickMax(g,b));
c=max-(double) MagickMin(r,MagickMin(g,b));
h=0.0;
if (c == 0)
h=0.0;
else
if (red == (MagickRealType) max)
h=fmod((g-b)/c+6.0,6.0);
else
if (green == (MagickRealType) max)
h=((b-r)/c)+2.0;
else
if (blue == (MagickRealType) max)
h=((r-g)/c)+4.0;
*hue=(h/6.0);
*chroma=QuantumScale*c;
*luma=QuantumScale*(0.298839*r+0.586811*g+0.114350*b);
}
static inline MagickRealType In(const MagickRealType p,const MagickRealType Sa,
const MagickRealType magick_unused(q),const MagickRealType Da)
{
return(Sa*p*Da);
}
static inline void CompositeIn(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
double
gamma;
MagickRealType
Sa,
Da;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=Sa*Da;
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=PerceptibleReciprocal(gamma);
composite->red=gamma*In(p->red,Sa,q->red,Da);
composite->green=gamma*In(p->green,Sa,q->green,Da);
composite->blue=gamma*In(p->blue,Sa,q->blue,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*In(p->index,Sa,q->index,Da);
}
static inline MagickRealType Lighten(const MagickRealType p,
const MagickRealType alpha,const MagickRealType q,const MagickRealType beta)
{
if (p > q)
return(MagickOver_(p,alpha,q,beta)); /* src-over */
return(MagickOver_(q,beta,p,alpha)); /* dst-over */
}
static inline void CompositeLighten(const MagickPixelPacket *p,
const MagickPixelPacket *q,const ChannelType channel,
MagickPixelPacket *composite)
{
/*
Lighten is also equvalent to a 'Maximum' method
OR a greyscale version of a binary 'And'
OR the 'Union' of pixel sets.
*/
double
gamma;
if ( (channel & SyncChannels) != 0 ) {
composite->opacity=QuantumScale*p->opacity*q->opacity; /* Over Blend */
gamma=1.0-QuantumScale*composite->opacity;
gamma=PerceptibleReciprocal(gamma);
composite->red=gamma*Lighten(p->red,p->opacity,q->red,q->opacity);
composite->green=gamma*Lighten(p->green,p->opacity,q->green,q->opacity);
composite->blue=gamma*Lighten(p->blue,p->opacity,q->blue,q->opacity);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*Lighten(p->index,p->opacity,q->index,q->opacity);
}
else { /* handle channels as separate grayscale channels */
if ( (channel & AlphaChannel) != 0 )
composite->opacity=MagickMin(p->opacity,q->opacity);
if ( (channel & RedChannel) != 0 )
composite->red=MagickMax(p->red,q->red);
if ( (channel & GreenChannel) != 0 )
composite->green=MagickMax(p->green,q->green);
if ( (channel & BlueChannel) != 0 )
composite->blue=MagickMax(p->blue,q->blue);
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index=MagickMax(p->index,q->index);
}
}
static inline void CompositeLightenIntensity(const MagickPixelPacket *p,
const MagickPixelPacket *q,const ChannelType channel,
MagickPixelPacket *composite)
{
/*
Select the pixel based on the intensity level.
If 'Sync' flag select whole pixel based on alpha weighted intensity.
Otherwise use Intenisty only, but restrict copy according to channel.
*/
if ( (channel & SyncChannels) != 0 ) {
MagickRealType
Da,
Sa;
Sa=1.0-QuantumScale*p->opacity;
Da=1.0-QuantumScale*q->opacity;
*composite = (Sa*MagickPixelIntensity(p) > Da*MagickPixelIntensity(q))
? *p : *q;
}
else {
int from_p = (MagickPixelIntensity(p) > MagickPixelIntensity(q));
if ( (channel & AlphaChannel) != 0 )
composite->opacity = from_p ? p->opacity : q->opacity;
if ( (channel & RedChannel) != 0 )
composite->red = from_p ? p->red : q->red;
if ( (channel & GreenChannel) != 0 )
composite->green = from_p ? p->green : q->green;
if ( (channel & BlueChannel) != 0 )
composite->blue = from_p ? p->blue : q->blue;
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index = from_p ? p->index : q->index;
}
}
#if 0
static inline MagickRealType LinearDodge(const MagickRealType Sca,
const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da)
{
/*
LinearDodge: simplifies to a trivial formula
f(Sc,Dc) = Sc + Dc
Dca' = Sca + Dca
*/
return(Sca+Dca);
}
#endif
static inline void CompositeLinearDodge(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
double
gamma;
MagickRealType
Da,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=PerceptibleReciprocal(gamma);
composite->red=gamma*(p->red*Sa+q->red*Da);
composite->green=gamma*(p->green*Sa+q->green*Da);
composite->blue=gamma*(p->blue*Sa+q->blue*Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*(p->index*Sa+q->index*Da);
}
static inline MagickRealType LinearBurn(const MagickRealType Sca,
const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da)
{
/*
LinearBurn: as defined by Abode Photoshop, according to
http://www.simplefilter.de/en/basics/mixmods.html is:
f(Sc,Dc) = Sc + Dc - 1
*/
return(Sca+Dca-Sa*Da);
}
static inline void CompositeLinearBurn(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
MagickRealType
Da,
gamma,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*LinearBurn(QuantumScale*p->red*Sa,Sa,QuantumScale*
q->red*Da,Da);
composite->green=gamma*LinearBurn(QuantumScale*p->green*Sa,Sa,QuantumScale*
q->green*Da,Da);
composite->blue=gamma*LinearBurn(QuantumScale*p->blue*Sa,Sa,QuantumScale*
q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*LinearBurn(QuantumScale*p->index*Sa,Sa,QuantumScale*
q->index*Da,Da);
}
static inline MagickRealType LinearLight(const MagickRealType Sca,
const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da)
{
#if 0
/*
Previous formula, was only valid for fully-opaque images.
*/
return(Dca+2*Sca-1.0);
#else
/*
LinearLight: as defined by Abode Photoshop, according to
http://www.simplefilter.de/en/basics/mixmods.html is:
f(Sc,Dc) = Dc + 2*Sc - 1
*/
return((Sca-Sa)*Da+Sca+Dca);
#endif
}
static inline void CompositeLinearLight(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
MagickRealType
Da,
gamma,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*LinearLight(QuantumScale*p->red*Sa,Sa,QuantumScale*
q->red*Da,Da);
composite->green=gamma*LinearLight(QuantumScale*p->green*Sa,Sa,QuantumScale*
q->green*Da,Da);
composite->blue=gamma*LinearLight(QuantumScale*p->blue*Sa,Sa,QuantumScale*
q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*LinearLight(QuantumScale*p->index*Sa,Sa,QuantumScale*
q->index*Da,Da);
}
static inline MagickRealType Mathematics(const MagickRealType Sca,
const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da,
const GeometryInfo *geometry_info)
{
/*
'Mathematics' a free form user control mathematical composition is defined
as...
f(Sc,Dc) = A*Sc*Dc + B*Sc + C*Dc + D
Where the arguments A,B,C,D are (currently) passed to composite as
a command separated 'geometry' string in "compose:args" image artifact.
A = a->rho, B = a->sigma, C = a->xi, D = a->psi
Applying the SVG transparency formula (see above), we get...
Dca' = Sa*Da*f(Sc,Dc) + Sca*(1.0-Da) + Dca*(1.0-Sa)
Dca' = A*Sca*Dca + B*Sca*Da + C*Dca*Sa + D*Sa*Da + Sca*(1.0-Da) +
Dca*(1.0-Sa)
*/
return(geometry_info->rho*Sca*Dca+geometry_info->sigma*Sca*Da+
geometry_info->xi*Dca*Sa+geometry_info->psi*Sa*Da+Sca*(1.0-Da)+
Dca*(1.0-Sa));
}
static inline void CompositeMathematics(const MagickPixelPacket *p,
const MagickPixelPacket *q,const ChannelType channel, const GeometryInfo
*args, MagickPixelPacket *composite)
{
double
gamma;
MagickRealType
Da,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* ??? - AT */
Da=1.0-QuantumScale*q->opacity;
if ( (channel & SyncChannels) != 0 ) {
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*Mathematics(QuantumScale*p->red*Sa,Sa,QuantumScale*
q->red*Da,Da,args);
composite->green=gamma*Mathematics(QuantumScale*p->green*Sa,Sa,QuantumScale*
q->green*Da,Da,args);
composite->blue=gamma*Mathematics(QuantumScale*p->blue*Sa,Sa,QuantumScale*
q->blue*Da,Da,args);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*Mathematics(QuantumScale*p->index*Sa,Sa,QuantumScale*
q->index*Da,Da,args);
}
else { /* handle channels as separate grayscale channels */
if ( (channel & AlphaChannel) != 0 )
composite->opacity=QuantumRange*(1.0-Mathematics(Sa,1.0,Da,1.0,args));
if ( (channel & RedChannel) != 0 )
composite->red=QuantumRange*
Mathematics(QuantumScale*p->red,1.0,QuantumScale*q->red,1.0,args);
if ( (channel & GreenChannel) != 0 )
composite->green=QuantumRange*
Mathematics(QuantumScale*p->green,1.0,QuantumScale*q->green,1.0,args);
if ( (channel & BlueChannel) != 0 )
composite->blue=QuantumRange*
Mathematics(QuantumScale*p->blue,1.0,QuantumScale*q->blue,1.0,args);
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index=QuantumRange*
Mathematics(QuantumScale*p->index,1.0,QuantumScale*q->index,1.0,args);
}
}
static inline void CompositePlus(const MagickPixelPacket *p,
const MagickPixelPacket *q,const ChannelType channel,
MagickPixelPacket *composite)
{
if ( (channel & SyncChannels) != 0 ) {
/*
NOTE: "Plus" does not use 'over' alpha-blending but uses a
special 'plus' form of alph-blending. It is the ONLY mathematical
operator to do this. this is what makes it different to the
otherwise equivalent "LinearDodge" composition method.
Note however that color channels are still effected by the alpha channel
as a result of the blending, making it just as useless for independant
channel maths, just like all other mathematical composition methods.
As such the removal of the 'sync' flag, is still a usful convention.
The MagickPixelCompositePlus() function is defined in
"composite-private.h" so it can also be used for Image Blending.
*/
MagickPixelCompositePlus(p,p->opacity,q,q->opacity,composite);
}
else { /* handle channels as separate grayscale channels */
if ( (channel & AlphaChannel) != 0 )
composite->opacity=p->opacity+q->opacity-QuantumRange;
if ( (channel & RedChannel) != 0 )
composite->red=p->red+q->red;
if ( (channel & GreenChannel) != 0 )
composite->green=p->green+q->green;
if ( (channel & BlueChannel) != 0 )
composite->blue=p->blue+q->blue;
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index=p->index+q->index;
}
}
static inline MagickRealType Minus(const MagickRealType Sca,
const MagickRealType Sa,const MagickRealType Dca,
const MagickRealType magick_unused(Da))
{
/*
Minus Source from Destination
f(Sc,Dc) = Sc - Dc
*/
return(Sca + Dca - 2*Dca*Sa);
}
static inline void CompositeMinus(const MagickPixelPacket *p,
const MagickPixelPacket *q,const ChannelType channel,
MagickPixelPacket *composite)
{
double
gamma;
MagickRealType
Da,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
if ( (channel & SyncChannels) != 0 ) {
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=PerceptibleReciprocal(gamma);
composite->red=gamma*Minus(p->red*Sa,Sa,q->red*Da,Da);
composite->green=gamma*Minus(p->green*Sa,Sa,q->green*Da,Da);
composite->blue=gamma*Minus(p->blue*Sa,Sa,q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*Minus(p->index*Sa,Sa,q->index*Da,Da);
}
else { /* handle channels as separate grayscale channels */
if ( (channel & AlphaChannel) != 0 )
composite->opacity=QuantumRange*(1.0-(Sa-Da));
if ( (channel & RedChannel) != 0 )
composite->red=p->red-q->red;
if ( (channel & GreenChannel) != 0 )
composite->green=p->green-q->green;
if ( (channel & BlueChannel) != 0 )
composite->blue=p->blue-q->blue;
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index=p->index-q->index;
}
}
static inline MagickRealType ModulusAdd(const MagickRealType p,
const MagickRealType Sa, const MagickRealType q, const MagickRealType Da)
{
MagickRealType
pixel;
pixel=p+q;
if (pixel > QuantumRange)
pixel-=(QuantumRange+1.0);
return(pixel*Sa*Da + p*Sa*(1-Da) + q*Da*(1-Sa));
}
static inline void CompositeModulusAdd(const MagickPixelPacket *p,
const MagickPixelPacket *q, const ChannelType channel,
MagickPixelPacket *composite)
{
if ( (channel & SyncChannels) != 0 ) {
double
gamma;
MagickRealType
Sa,
Da;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=PerceptibleReciprocal(gamma);
composite->red=ModulusAdd(p->red,Sa,q->red,Da);
composite->green=ModulusAdd(p->green,Sa,q->green,Da);
composite->blue=ModulusAdd(p->blue,Sa,q->blue,Da);
if (q->colorspace == CMYKColorspace)
composite->index=ModulusAdd(p->index,Sa,q->index,Da);
}
else { /* handle channels as separate grayscale channels */
if ( (channel & AlphaChannel) != 0 )
composite->opacity=QuantumRange-ModulusAdd(QuantumRange-p->opacity,
1.0,QuantumRange-q->opacity,1.0);
if ( (channel & RedChannel) != 0 )
composite->red=ModulusAdd(p->red,1.0,q->red,1.0);
if ( (channel & GreenChannel) != 0 )
composite->green=ModulusAdd(p->green,1.0,q->green,1.0);
if ( (channel & BlueChannel) != 0 )
composite->blue=ModulusAdd(p->blue,1.0,q->blue,1.0);
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index=ModulusAdd(p->index,1.0,q->index,1.0);
}
}
static inline MagickRealType ModulusSubtract(const MagickRealType p,
const MagickRealType Sa, const MagickRealType q, const MagickRealType Da)
{
MagickRealType
pixel;
pixel=p-q;
if (pixel < 0.0)
pixel+=(QuantumRange+1.0);
return(pixel*Sa*Da + p*Sa*(1-Da) + q*Da*(1-Sa));
}
static inline void CompositeModulusSubtract(const MagickPixelPacket *p,
const MagickPixelPacket *q, const ChannelType channel,
MagickPixelPacket *composite)
{
if ( (channel & SyncChannels) != 0 ) {
double
gamma;
MagickRealType
Da,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma = RoundToUnity(Sa+Da-Sa*Da);
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=PerceptibleReciprocal(gamma);
composite->red=ModulusSubtract(p->red,Sa,q->red,Da);
composite->green=ModulusSubtract(p->green,Sa,q->green,Da);
composite->blue=ModulusSubtract(p->blue,Sa,q->blue,Da);
if (q->colorspace == CMYKColorspace)
composite->index=ModulusSubtract(p->index,Sa,q->index,Da);
}
else { /* handle channels as separate grayscale channels */
if ( (channel & AlphaChannel) != 0 )
composite->opacity=QuantumRange-ModulusSubtract(QuantumRange-p->opacity,
1.0,QuantumRange-q->opacity,1.0);
if ( (channel & RedChannel) != 0 )
composite->red=ModulusSubtract(p->red,1.0,q->red,1.0);
if ( (channel & GreenChannel) != 0 )
composite->green=ModulusSubtract(p->green,1.0,q->green,1.0);
if ( (channel & BlueChannel) != 0 )
composite->blue=ModulusSubtract(p->blue,1.0,q->blue,1.0);
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index=ModulusSubtract(p->index,1.0,q->index,1.0);
}
}
static inline MagickRealType Multiply(const MagickRealType Sca,
const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da)
{
return(Sca*Dca+Sca*(1.0-Da)+Dca*(1.0-Sa));
}
static inline void CompositeMultiply(const MagickPixelPacket *p,
const MagickPixelPacket *q,const ChannelType channel,
MagickPixelPacket *composite)
{
MagickRealType
Da,
gamma,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
if ( (channel & SyncChannels) != 0 ) {
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*Multiply(QuantumScale*p->red*Sa,Sa,QuantumScale*
q->red*Da,Da);
composite->green=gamma*Multiply(QuantumScale*p->green*Sa,Sa,QuantumScale*
q->green*Da,Da);
composite->blue=gamma*Multiply(QuantumScale*p->blue*Sa,Sa,QuantumScale*
q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*Multiply(QuantumScale*p->index*Sa,Sa,QuantumScale*
q->index*Da,Da);
}
else { /* handle channels as separate grayscale channels */
if ( (channel & AlphaChannel) != 0 )
composite->opacity=QuantumRange*(1.0-Sa*Da);
if ( (channel & RedChannel) != 0 )
composite->red=QuantumScale*p->red*q->red;
if ( (channel & GreenChannel) != 0 )
composite->green=QuantumScale*p->green*q->green;
if ( (channel & BlueChannel) != 0 )
composite->blue=QuantumScale*p->blue*q->blue;
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index=QuantumScale*p->index*q->index;
}
}
static inline MagickRealType Out(const MagickRealType p,
const MagickRealType Sa,const MagickRealType magick_unused(q),
const MagickRealType Da)
{
return(Sa*p*(1.0-Da));
}
static inline void CompositeOut(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
double
gamma;
MagickRealType
Da,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=Sa*(1.0-Da);
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=PerceptibleReciprocal(gamma);
composite->red=gamma*Out(p->red,Sa,q->red,Da);
composite->green=gamma*Out(p->green,Sa,q->green,Da);
composite->blue=gamma*Out(p->blue,Sa,q->blue,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*Out(p->index,Sa,q->index,Da);
}
static MagickRealType PegtopLight(const MagickRealType Sca,
const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da)
{
/*
PegTop: A Soft-Light alternative: A continuous version of the Softlight
function, producing very similar results.
f(Sc,Dc) = Dc^2*(1-2*Sc) + 2*Sc*Dc
See http://www.pegtop.net/delphi/articles/blendmodes/softlight.htm.
*/
if (fabs(Da) < MagickEpsilon)
return(Sca);
return(Dca*Dca*(Sa-2*Sca)/Da+Sca*(2*Dca+1-Da)+Dca*(1-Sa));
}
static inline void CompositePegtopLight(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
MagickRealType
Da,
gamma,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*PegtopLight(QuantumScale*p->red*Sa,Sa,QuantumScale*
q->red*Da,Da);
composite->green=gamma*PegtopLight(QuantumScale*p->green*Sa,Sa,QuantumScale*
q->green*Da,Da);
composite->blue=gamma*PegtopLight(QuantumScale*p->blue*Sa,Sa,QuantumScale*
q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*PegtopLight(QuantumScale*p->index*Sa,Sa,QuantumScale*
q->index*Da,Da);
}
static MagickRealType PinLight(const MagickRealType Sca,
const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da)
{
/*
PinLight: A Photoshop 7 composition method
http://www.simplefilter.de/en/basics/mixmods.html
f(Sc,Dc) = Dc<2*Sc-1 ? 2*Sc-1 : Dc>2*Sc ? 2*Sc : Dc
*/
if (Dca*Sa < Da*(2*Sca-Sa))
return(Sca*(Da+1.0)-Sa*Da+Dca*(1.0-Sa));
if ((Dca*Sa) > (2*Sca*Da))
return(Sca*Da+Sca+Dca*(1.0-Sa));
return(Sca*(1.0-Da)+Dca);
}
static inline void CompositePinLight(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
MagickRealType
Da,
gamma,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*PinLight(QuantumScale*p->red*Sa,Sa,QuantumScale*
q->red*Da,Da);
composite->green=gamma*PinLight(QuantumScale*p->green*Sa,Sa,QuantumScale*
q->green*Da,Da);
composite->blue=gamma*PinLight(QuantumScale*p->blue*Sa,Sa,QuantumScale*
q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*PinLight(QuantumScale*p->index*Sa,Sa,QuantumScale*
q->index*Da,Da);
}
static inline MagickRealType Screen(const MagickRealType Sca,
const MagickRealType Dca)
{
/* Screen: A negated multiply
f(Sc,Dc) = 1.0-(1.0-Sc)*(1.0-Dc)
*/
return(Sca+Dca-Sca*Dca);
}
static inline void CompositeScreen(const MagickPixelPacket *p,
const MagickPixelPacket *q,const ChannelType channel,
MagickPixelPacket *composite)
{
double
gamma;
MagickRealType
Da,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
if ( (channel & SyncChannels) != 0 ) {
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
Sa*=(MagickRealType) QuantumScale;
Da*=(MagickRealType) QuantumScale; /* optimization */
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*Screen(p->red*Sa,q->red*Da);
composite->green=gamma*Screen(p->green*Sa,q->green*Da);
composite->blue=gamma*Screen(p->blue*Sa,q->blue*Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*Screen(p->index*Sa,q->index*Da);
}
else { /* handle channels as separate grayscale channels */
if ( (channel & AlphaChannel) != 0 )
composite->opacity=QuantumRange*(1.0-Screen(Sa,Da));
if ( (channel & RedChannel) != 0 )
composite->red=QuantumRange*Screen(QuantumScale*p->red,
QuantumScale*q->red);
if ( (channel & GreenChannel) != 0 )
composite->green=QuantumRange*Screen(QuantumScale*p->green,
QuantumScale*q->green);
if ( (channel & BlueChannel) != 0 )
composite->blue=QuantumRange*Screen(QuantumScale*p->blue,
QuantumScale*q->blue);
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index=QuantumRange*Screen(QuantumScale*p->index,
QuantumScale*q->index);
}
}
static MagickRealType SoftLight(const MagickRealType Sca,
const MagickRealType Sa, const MagickRealType Dca, const MagickRealType Da)
{
#if 0
/*
Oct 2004 SVG specification -- was found to be incorrect
See http://lists.w3.org/Archives/Public/www-svg/2009Feb/0014.html.
*/
if (2.0*Sca < Sa)
return(Dca*(Sa-(1.0-Dca/Da)*(2.0*Sca-Sa))+Sca*(1.0-Da)+Dca*(1.0-Sa));
if (8.0*Dca <= Da)
return(Dca*(Sa-(1.0-Dca/Da)*(2.0*Sca-Sa)*(3.0-8.0*Dca/Da))+
Sca*(1.0-Da)+Dca*(1.0-Sa));
return((Dca*Sa+(pow(Dca/Da,0.5)*Da-Dca)*(2.0*Sca-Sa))+Sca*(1.0-Da)+
Dca*(1.0-Sa));
#else
MagickRealType
alpha,
beta;
/*
New specification: March 2009 SVG specification.
*/
alpha=Dca/Da;
if ((2.0*Sca) < Sa)
return(Dca*(Sa+(2.0*Sca-Sa)*(1.0-alpha))+Sca*(1.0-Da)+Dca*(1.0-Sa));
if (((2.0*Sca) > Sa) && ((4.0*Dca) <= Da))
{
beta=Dca*Sa+Da*(2.0*Sca-Sa)*(4.0*alpha*(4.0*alpha+1.0)*(alpha-1.0)+7.0*
alpha)+Sca*(1.0-Da)+Dca*(1.0-Sa);
return(beta);
}
beta=Dca*Sa+Da*(2.0*Sca-Sa)*(pow(alpha,0.5)-alpha)+Sca*(1.0-Da)+Dca*(1.0-Sa);
return(beta);
#endif
}
static inline void CompositeSoftLight(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
MagickRealType
Da,
gamma,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*SoftLight(QuantumScale*p->red*Sa,Sa,QuantumScale*
q->red*Da,Da);
composite->green=gamma*SoftLight(QuantumScale*p->green*Sa,Sa,QuantumScale*
q->green*Da,Da);
composite->blue=gamma*SoftLight(QuantumScale*p->blue*Sa,Sa,QuantumScale*
q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*SoftLight(QuantumScale*p->index*Sa,Sa,QuantumScale*
q->index*Da,Da);
}
/*
Depreciated
Multiply difference by amount, if differance larger than threshold???
What use this is is completely unknown
The Opacity calculation appears to be inverted -- Anthony Thyssen
*/
static inline MagickRealType Threshold(const MagickRealType p,
const MagickRealType q,const MagickRealType threshold,
const MagickRealType amount)
{
MagickRealType
delta;
delta=p-q;
if ((MagickRealType) fabs((double) (2.0*delta)) < threshold)
return(q);
return(q+delta*amount);
}
static inline void CompositeThreshold(const MagickPixelPacket *p,
const MagickPixelPacket *q,const MagickRealType threshold,
const MagickRealType amount,MagickPixelPacket *composite)
{
composite->red=Threshold(p->red,q->red,threshold,amount);
composite->green=Threshold(p->green,q->green,threshold,amount);
composite->blue=Threshold(p->blue,q->blue,threshold,amount);
composite->opacity=QuantumRange-Threshold(p->opacity,q->opacity,
threshold,amount);
if (q->colorspace == CMYKColorspace)
composite->index=Threshold(p->index,q->index,threshold,amount);
}
static MagickRealType VividLight(const MagickRealType Sca,
const MagickRealType Sa, const MagickRealType Dca, const MagickRealType Da)
{
/*
VividLight: A Photoshop 7 composition method. See
http://www.simplefilter.de/en/basics/mixmods.html.
f(Sc,Dc) = (2*Sc < 1) ? 1-(1-Dc)/(2*Sc) : Dc/(2*(1-Sc))
*/
if ((fabs(Sa) < MagickEpsilon) || (fabs(Sca-Sa) < MagickEpsilon))
return(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa));
if ((2*Sca) <= Sa)
return(Sa*(Da+Sa*(Dca-Da)/(2.0*Sca))+Sca*(1.0-Da)+Dca*(1.0-Sa));
return(Dca*Sa*Sa/(2.0*(Sa-Sca))+Sca*(1.0-Da)+Dca*(1.0-Sa));
}
static inline void CompositeVividLight(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
MagickRealType
Da,
gamma,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*VividLight(QuantumScale*p->red*Sa,Sa,QuantumScale*
q->red*Da,Da);
composite->green=gamma*VividLight(QuantumScale*p->green*Sa,Sa,QuantumScale*
q->green*Da,Da);
composite->blue=gamma*VividLight(QuantumScale*p->blue*Sa,Sa,QuantumScale*
q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*VividLight(QuantumScale*p->index*Sa,Sa,QuantumScale*
q->index*Da,Da);
}
static MagickRealType Xor(const MagickRealType Sca,const MagickRealType Sa,
const MagickRealType Dca,const MagickRealType Da)
{
return(Sca*(1-Da)+Dca*(1-Sa));
}
static inline void CompositeXor(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
MagickRealType
Da,
gamma,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=Sa+Da-2*Sa*Da; /* Xor blend mode X=0,Y=1,Z=1 */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=PerceptibleReciprocal(gamma);
composite->red=gamma*Xor(p->red*Sa,Sa,q->red*Da,Da);
composite->green=gamma*Xor(p->green*Sa,Sa,q->green*Da,Da);
composite->blue=gamma*Xor(p->blue*Sa,Sa,q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*Xor(p->index*Sa,Sa,q->index*Da,Da);
}
MagickExport MagickBooleanType CompositeImage(Image *image,
const CompositeOperator compose,const Image *composite_image,
const ssize_t x_offset,const ssize_t y_offset)
{
MagickBooleanType
status;
status=CompositeImageChannel(image,DefaultChannels,compose,composite_image,
x_offset,y_offset);
return(status);
}
MagickExport MagickBooleanType CompositeImageChannel(Image *image,
const ChannelType channel,const CompositeOperator compose,
const Image *composite,const ssize_t x_offset,const ssize_t y_offset)
{
#define CompositeImageTag "Composite/Image"
CacheView
*composite_view,
*image_view;
const char
*value;
ExceptionInfo
*exception;
GeometryInfo
geometry_info;
Image
*composite_image,
*destination_image;
MagickBooleanType
clip_to_self,
status;
MagickOffsetType
progress;
MagickPixelPacket
zero;
MagickRealType
amount,
destination_dissolve,
midpoint,
percent_luma,
percent_chroma,
source_dissolve,
threshold;
MagickStatusType
flags;
ssize_t
y;
/*
Prepare composite image.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(composite != (Image *) NULL);
assert(composite->signature == MagickSignature);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
exception=(&image->exception);
composite_image=CloneImage(composite,0,0,MagickTrue,exception);
if (composite_image == (const Image *) NULL)
return(MagickFalse);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace);
(void) SetImageColorspace(composite_image,image->colorspace);
GetMagickPixelPacket(image,&zero);
destination_image=(Image *) NULL;
amount=0.5;
destination_dissolve=1.0;
clip_to_self=MagickTrue;
percent_luma=100.0;
percent_chroma=100.0;
source_dissolve=1.0;
threshold=0.05f;
switch (compose)
{
case ClearCompositeOp:
case SrcCompositeOp:
case InCompositeOp:
case SrcInCompositeOp:
case OutCompositeOp:
case SrcOutCompositeOp:
case DstInCompositeOp:
case DstAtopCompositeOp:
{
/*
Modify destination outside the overlaid region.
*/
clip_to_self=MagickFalse;
break;
}
case OverCompositeOp:
{
if (image->matte != MagickFalse)
break;
if (composite_image->matte != MagickFalse)
break;
}
case CopyCompositeOp:
{
if ((x_offset < 0) || (y_offset < 0))
break;
if ((x_offset+(ssize_t) composite_image->columns) >= (ssize_t) image->columns)
break;
if ((y_offset+(ssize_t) composite_image->rows) >= (ssize_t) image->rows)
break;
status=MagickTrue;
composite_view=AcquireVirtualCacheView(composite_image,exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(composite_image,image,composite_image->rows,1)
#endif
for (y=0; y < (ssize_t) composite_image->rows; y++)
{
MagickBooleanType
sync;
register const IndexPacket
*composite_indexes;
register const PixelPacket
*p;
register IndexPacket
*indexes;
register PixelPacket
*q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(composite_view,0,y,composite_image->columns,
1,exception);
q=GetCacheViewAuthenticPixels(image_view,x_offset,y+y_offset,
composite_image->columns,1,exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
composite_indexes=GetCacheViewVirtualIndexQueue(composite_view);
indexes=GetCacheViewAuthenticIndexQueue(image_view);
(void) CopyMagickMemory(q,p,composite_image->columns*sizeof(*p));
if ((indexes != (IndexPacket *) NULL) &&
(composite_indexes != (const IndexPacket *) NULL))
(void) CopyMagickMemory(indexes,composite_indexes,
composite_image->columns*sizeof(*indexes));
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_CompositeImage)
#endif
proceed=SetImageProgress(image,CompositeImageTag,
(MagickOffsetType) y,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
composite_view=DestroyCacheView(composite_view);
image_view=DestroyCacheView(image_view);
composite_image=DestroyImage(composite_image);
return(status);
}
case CopyOpacityCompositeOp:
case ChangeMaskCompositeOp:
{
/*
Modify destination outside the overlaid region and require an alpha
channel to exist, to add transparency.
*/
if (image->matte == MagickFalse)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel);
clip_to_self=MagickFalse;
break;
}
case BlurCompositeOp:
{
CacheView
*composite_view,
*destination_view;
MagickPixelPacket
pixel;
MagickRealType
angle_range,
angle_start,
height,
width;
ResampleFilter
*resample_filter;
SegmentInfo
blur;
/*
Blur Image by resampling.
Blur Image dictated by an overlay gradient map: X = red_channel;
Y = green_channel; compose:args = x_scale[,y_scale[,angle]].
*/
destination_image=CloneImage(image,image->columns,image->rows,MagickTrue,
exception);
if (destination_image == (Image *) NULL)
{
composite_image=DestroyImage(composite_image);
return(MagickFalse);
}
/*
Gather the maximum blur sigma values from user.
*/
SetGeometryInfo(&geometry_info);
flags=NoValue;
value=GetImageArtifact(composite_image,"compose:args");
if (value != (char *) NULL)
flags=ParseGeometry(value,&geometry_info);
if ((flags & WidthValue) == 0 ) {
(void) ThrowMagickException(exception,GetMagickModule(),
OptionWarning,"InvalidGeometry","'%s' '%s'",
"compose:args",value);
composite_image=DestroyImage(composite_image);
destination_image=DestroyImage(destination_image);
return(MagickFalse);
}
/*
Users input sigma now needs to be converted to the EWA ellipse size.
The filter defaults to a sigma of 0.5 so to make this match the
users input the ellipse size needs to be doubled.
*/
width=height=geometry_info.rho*2.0;
if ((flags & HeightValue) != 0 )
height=geometry_info.sigma*2.0;
/* default the unrotated ellipse width and height axis vectors */
blur.x1=width;
blur.x2=0.0;
blur.y1=0.0;
blur.y2=height;
/* rotate vectors if a rotation angle is given */
if ((flags & XValue) != 0 )
{
MagickRealType
angle;
angle=DegreesToRadians(geometry_info.xi);
blur.x1=width*cos(angle);
blur.x2=width*sin(angle);
blur.y1=(-height*sin(angle));
blur.y2=height*cos(angle);
}
/* Otherwise lets set a angle range and calculate in the loop */
angle_start=0.0;
angle_range=0.0;
if ((flags & YValue) != 0 )
{
angle_start=DegreesToRadians(geometry_info.xi);
angle_range=DegreesToRadians(geometry_info.psi)-angle_start;
}
/*
Set up a gaussian cylindrical filter for EWA Bluring.
As the minimum ellipse radius of support*1.0 the EWA algorithm
can only produce a minimum blur of 0.5 for Gaussian (support=2.0)
This means that even 'No Blur' will be still a little blurry!
The solution (as well as the problem of preventing any user
expert filter settings, is to set our own user settings, then
restore them afterwards.
*/
resample_filter=AcquireResampleFilter(image,exception);
SetResampleFilter(resample_filter,GaussianFilter,1.0);
/* do the variable blurring of each pixel in image */
pixel=zero;
composite_view=AcquireVirtualCacheView(composite_image,exception);
destination_view=AcquireAuthenticCacheView(destination_image,exception);
for (y=0; y < (ssize_t) composite_image->rows; y++)
{
MagickBooleanType
sync;
register const PixelPacket
*restrict p;
register PixelPacket
*restrict r;
register IndexPacket
*restrict destination_indexes;
register ssize_t
x;
if (((y+y_offset) < 0) || ((y+y_offset) >= (ssize_t) image->rows))
continue;
p=GetCacheViewVirtualPixels(composite_view,0,y,composite_image->columns,
1,exception);
r=QueueCacheViewAuthenticPixels(destination_view,0,y,
destination_image->columns,1,exception);
if ((p == (const PixelPacket *) NULL) || (r == (PixelPacket *) NULL))
break;
destination_indexes=GetCacheViewAuthenticIndexQueue(destination_view);
for (x=0; x < (ssize_t) composite_image->columns; x++)
{
if (((x_offset+x) < 0) || ((x_offset+x) >= (ssize_t) image->columns))
{
p++;
continue;
}
if (fabs(angle_range) > MagickEpsilon)
{
MagickRealType
angle;
angle=angle_start+angle_range*QuantumScale*
GetPixelBlue(p);
blur.x1=width*cos(angle);
blur.x2=width*sin(angle);
blur.y1=(-height*sin(angle));
blur.y2=height*cos(angle);
}
#if 0
if ( x == 10 && y == 60 ) {
fprintf(stderr, "blur.x=%lf,%lf, blur.y=%lf,%lf\n",
blur.x1, blur.x2, blur.y1, blur.y2);
fprintf(stderr, "scaled by=%lf,%lf\n",
QuantumScale*GetPixelRed(p), QuantumScale*GetPixelGreen(p));
}
#endif
ScaleResampleFilter(resample_filter,
blur.x1*QuantumScale*GetPixelRed(p),
blur.y1*QuantumScale*GetPixelGreen(p),
blur.x2*QuantumScale*GetPixelRed(p),
blur.y2*QuantumScale*GetPixelGreen(p) );
(void) ResamplePixelColor(resample_filter,(double) x_offset+x,
(double) y_offset+y,&pixel);
SetPixelPacket(destination_image,&pixel,r,destination_indexes+x);
p++;
r++;
}
sync=SyncCacheViewAuthenticPixels(destination_view,exception);
if (sync == MagickFalse)
break;
}
resample_filter=DestroyResampleFilter(resample_filter);
composite_view=DestroyCacheView(composite_view);
destination_view=DestroyCacheView(destination_view);
composite_image=DestroyImage(composite_image);
composite_image=destination_image;
break;
}
case DisplaceCompositeOp:
case DistortCompositeOp:
{
CacheView
*composite_view,
*destination_view,
*image_view;
MagickPixelPacket
pixel;
MagickRealType
horizontal_scale,
vertical_scale;
PointInfo
center,
offset;
register IndexPacket
*restrict destination_indexes;
register PixelPacket
*restrict r;
/*
Displace/Distort based on overlay gradient map:
X = red_channel; Y = green_channel;
compose:args = x_scale[,y_scale[,center.x,center.y]]
*/
destination_image=CloneImage(image,image->columns,image->rows,MagickTrue,
exception);
if (destination_image == (Image *) NULL)
{
composite_image=DestroyImage(composite_image);
return(MagickFalse);
}
SetGeometryInfo(&geometry_info);
flags=NoValue;
value=GetImageArtifact(composite_image,"compose:args");
if (value != (char *) NULL)
flags=ParseGeometry(value,&geometry_info);
if ((flags & (WidthValue|HeightValue)) == 0 )
{
if ((flags & AspectValue) == 0)
{
horizontal_scale=(MagickRealType) (composite_image->columns-1.0)/
2.0;
vertical_scale=(MagickRealType) (composite_image->rows-1.0)/2.0;
}
else
{
horizontal_scale=(MagickRealType) (image->columns-1.0)/2.0;
vertical_scale=(MagickRealType) (image->rows-1.0)/2.0;
}
}
else
{
horizontal_scale=geometry_info.rho;
vertical_scale=geometry_info.sigma;
if ((flags & PercentValue) != 0)
{
if ((flags & AspectValue) == 0)
{
horizontal_scale*=(composite_image->columns-1.0)/200.0;
vertical_scale*=(composite_image->rows-1.0)/200.0;
}
else
{
horizontal_scale*=(image->columns-1.0)/200.0;
vertical_scale*=(image->rows-1.0)/200.0;
}
}
if ((flags & HeightValue) == 0)
vertical_scale=horizontal_scale;
}
/*
Determine fixed center point for absolute distortion map
Absolute distort ==
Displace offset relative to a fixed absolute point
Select that point according to +X+Y user inputs.
default = center of overlay image
arg flag '!' = locations/percentage relative to background image
*/
center.x=(MagickRealType) x_offset;
center.y=(MagickRealType) y_offset;
if (compose == DistortCompositeOp)
{
if ((flags & XValue) == 0)
if ((flags & AspectValue) == 0)
center.x=(MagickRealType) (x_offset+(composite_image->columns-1)/
2.0);
else
center.x=((MagickRealType) image->columns-1)/2.0;
else
if ((flags & AspectValue) == 0)
center.x=(MagickRealType) (x_offset+geometry_info.xi);
else
center.x=geometry_info.xi;
if ((flags & YValue) == 0)
if ((flags & AspectValue) == 0)
center.y=(MagickRealType) (y_offset+(composite_image->rows-1)/2.0);
else
center.y=((MagickRealType) image->rows-1)/2.0;
else
if ((flags & AspectValue) == 0)
center.y=(MagickRealType) (y_offset+geometry_info.psi);
else
center.y=geometry_info.psi;
}
/*
Shift the pixel offset point as defined by the provided,
displacement/distortion map. -- Like a lens...
*/
pixel=zero;
image_view=AcquireVirtualCacheView(image,exception);
composite_view=AcquireVirtualCacheView(composite_image,exception);
destination_view=AcquireAuthenticCacheView(destination_image,exception);
for (y=0; y < (ssize_t) composite_image->rows; y++)
{
MagickBooleanType
sync;
register const PixelPacket
*restrict p;
register ssize_t
x;
if (((y+y_offset) < 0) || ((y+y_offset) >= (ssize_t) image->rows))
continue;
p=GetCacheViewVirtualPixels(composite_view,0,y,composite_image->columns,
1,exception);
r=QueueCacheViewAuthenticPixels(destination_view,0,y,
destination_image->columns,1,exception);
if ((p == (const PixelPacket *) NULL) || (r == (PixelPacket *) NULL))
break;
destination_indexes=GetCacheViewAuthenticIndexQueue(destination_view);
for (x=0; x < (ssize_t) composite_image->columns; x++)
{
if (((x_offset+x) < 0) || ((x_offset+x) >= (ssize_t) image->columns))
{
p++;
continue;
}
/*
Displace the offset.
*/
offset.x=(double) ((horizontal_scale*(GetPixelRed(p)-
(((MagickRealType) QuantumRange+1.0)/2.0)))/(((MagickRealType)
QuantumRange+1.0)/2.0)+center.x+((compose == DisplaceCompositeOp) ?
x : 0));
offset.y=(double) ((vertical_scale*(GetPixelGreen(p)-
(((MagickRealType) QuantumRange+1.0)/2.0)))/(((MagickRealType)
QuantumRange+1.0)/2.0)+center.y+((compose == DisplaceCompositeOp) ?
y : 0));
(void) InterpolateMagickPixelPacket(image,image_view,
UndefinedInterpolatePixel,(double) offset.x,(double) offset.y,
&pixel,exception);
/*
Mask with the 'invalid pixel mask' in alpha channel.
*/
pixel.opacity=(MagickRealType) QuantumRange*(1.0-(1.0-QuantumScale*
pixel.opacity)*(1.0-QuantumScale*GetPixelOpacity(p)));
SetPixelPacket(destination_image,&pixel,r,destination_indexes+x);
p++;
r++;
}
sync=SyncCacheViewAuthenticPixels(destination_view,exception);
if (sync == MagickFalse)
break;
}
destination_view=DestroyCacheView(destination_view);
composite_view=DestroyCacheView(composite_view);
image_view=DestroyCacheView(image_view);
composite_image=DestroyImage(composite_image);
composite_image=destination_image;
break;
}
case DissolveCompositeOp:
{
/*
Geometry arguments to dissolve factors.
*/
value=GetImageArtifact(composite_image,"compose:args");
if (value != (char *) NULL)
{
flags=ParseGeometry(value,&geometry_info);
source_dissolve=geometry_info.rho/100.0;
destination_dissolve=1.0;
if ((source_dissolve-MagickEpsilon) < 0.0)
source_dissolve=0.0;
if ((source_dissolve+MagickEpsilon) > 1.0)
{
destination_dissolve=2.0-source_dissolve;
source_dissolve=1.0;
}
if ((flags & SigmaValue) != 0)
destination_dissolve=geometry_info.sigma/100.0;
if ((destination_dissolve-MagickEpsilon) < 0.0)
destination_dissolve=0.0;
clip_to_self=MagickFalse;
if ((destination_dissolve+MagickEpsilon) > 1.0 )
{
destination_dissolve=1.0;
clip_to_self=MagickTrue;
}
}
break;
}
case BlendCompositeOp:
{
value=GetImageArtifact(composite_image,"compose:args");
if (value != (char *) NULL)
{
flags=ParseGeometry(value,&geometry_info);
source_dissolve=geometry_info.rho/100.0;
destination_dissolve=1.0-source_dissolve;
if ((flags & SigmaValue) != 0)
destination_dissolve=geometry_info.sigma/100.0;
clip_to_self=MagickFalse;
if ((destination_dissolve+MagickEpsilon) > 1.0)
clip_to_self=MagickTrue;
}
break;
}
case MathematicsCompositeOp:
{
/*
Just collect the values from "compose:args", setting.
Unused values are set to zero automagically.
Arguments are normally a comma separated list, so this probably should
be changed to some 'general comma list' parser, (with a minimum
number of values)
*/
SetGeometryInfo(&geometry_info);
value=GetImageArtifact(composite_image,"compose:args");
if (value != (char *) NULL)
(void) ParseGeometry(value,&geometry_info);
break;
}
case ModulateCompositeOp:
{
/*
Determine the luma and chroma scale.
*/
value=GetImageArtifact(composite_image,"compose:args");
if (value != (char *) NULL)
{
flags=ParseGeometry(value,&geometry_info);
percent_luma=geometry_info.rho;
if ((flags & SigmaValue) != 0)
percent_chroma=geometry_info.sigma;
}
break;
}
case ThresholdCompositeOp:
{
/*
Determine the amount and threshold.
This Composition method is depreciated
*/
value=GetImageArtifact(composite_image,"compose:args");
if (value != (char *) NULL)
{
flags=ParseGeometry(value,&geometry_info);
amount=geometry_info.rho;
threshold=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
threshold=0.05f;
}
threshold*=QuantumRange;
break;
}
default:
break;
}
value=GetImageArtifact(composite_image,"compose:outside-overlay");
if (value != (const char *) NULL)
clip_to_self=IsMagickTrue(value) == MagickFalse ? MagickTrue : MagickFalse;
/*
Composite image.
*/
status=MagickTrue;
progress=0;
midpoint=((MagickRealType) QuantumRange+1.0)/2;
GetMagickPixelPacket(composite_image,&zero);
composite_view=AcquireVirtualCacheView(composite_image,exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(composite_image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const PixelPacket
*pixels;
double
luma,
hue,
chroma,
sans;
MagickPixelPacket
composite,
destination,
source;
register const IndexPacket
*restrict composite_indexes;
register const PixelPacket
*restrict p;
register IndexPacket
*restrict indexes;
register ssize_t
x;
register PixelPacket
*restrict q;
if (status == MagickFalse)
continue;
if (clip_to_self != MagickFalse)
{
if (y < y_offset)
continue;
if ((y-y_offset) >= (ssize_t) composite_image->rows)
continue;
}
/*
If pixels is NULL, y is outside overlay region.
*/
pixels=(PixelPacket *) NULL;
p=(PixelPacket *) NULL;
if ((y >= y_offset) && ((y-y_offset) < (ssize_t) composite_image->rows))
{
p=GetCacheViewVirtualPixels(composite_view,0,y-y_offset,
composite_image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
pixels=p;
if (x_offset < 0)
p-=x_offset;
}
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
composite_indexes=GetCacheViewVirtualIndexQueue(composite_view);
GetMagickPixelPacket(composite_image,&source);
GetMagickPixelPacket(image,&destination);
hue=0.0;
chroma=0.0;
luma=0.0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (clip_to_self != MagickFalse)
{
if (x < x_offset)
{
q++;
continue;
}
if ((x-x_offset) >= (ssize_t) composite_image->columns)
break;
}
destination.red=(MagickRealType) GetPixelRed(q);
destination.green=(MagickRealType) GetPixelGreen(q);
destination.blue=(MagickRealType) GetPixelBlue(q);
if (image->matte != MagickFalse)
destination.opacity=(MagickRealType) GetPixelOpacity(q);
if (image->colorspace == CMYKColorspace)
destination.index=(MagickRealType) GetPixelIndex(indexes+x);
if (image->colorspace == CMYKColorspace)
{
destination.red=(MagickRealType) QuantumRange-destination.red;
destination.green=(MagickRealType) QuantumRange-destination.green;
destination.blue=(MagickRealType) QuantumRange-destination.blue;
destination.index=(MagickRealType) QuantumRange-destination.index;
}
/*
Handle destination modifications outside overlaid region.
*/
composite=destination;
if ((pixels == (PixelPacket *) NULL) || (x < x_offset) ||
((x-x_offset) >= (ssize_t) composite_image->columns))
{
switch (compose)
{
case DissolveCompositeOp:
case BlendCompositeOp:
{
composite.opacity=(MagickRealType) (QuantumRange-
destination_dissolve*(QuantumRange-composite.opacity));
break;
}
case ClearCompositeOp:
case SrcCompositeOp:
{
CompositeClear(&destination,&composite);
break;
}
case InCompositeOp:
case SrcInCompositeOp:
case OutCompositeOp:
case SrcOutCompositeOp:
case DstInCompositeOp:
case DstAtopCompositeOp:
case CopyOpacityCompositeOp:
case ChangeMaskCompositeOp:
{
composite.opacity=(MagickRealType) TransparentOpacity;
break;
}
default:
{
(void) GetOneVirtualMagickPixel(composite_image,x-x_offset,
y-y_offset,&composite,exception);
break;
}
}
if (image->colorspace == CMYKColorspace)
{
composite.red=(MagickRealType) QuantumRange-composite.red;
composite.green=(MagickRealType) QuantumRange-composite.green;
composite.blue=(MagickRealType) QuantumRange-composite.blue;
composite.index=(MagickRealType) QuantumRange-composite.index;
}
SetPixelRed(q,ClampToQuantum(composite.red));
SetPixelGreen(q,ClampToQuantum(composite.green));
SetPixelBlue(q,ClampToQuantum(composite.blue));
if (image->matte != MagickFalse)
SetPixelOpacity(q,ClampToQuantum(composite.opacity));
if (image->colorspace == CMYKColorspace)
SetPixelIndex(indexes+x,ClampToQuantum(composite.index));
q++;
continue;
}
/*
Handle normal overlay of source onto destination.
*/
source.red=(MagickRealType) GetPixelRed(p);
source.green=(MagickRealType) GetPixelGreen(p);
source.blue=(MagickRealType) GetPixelBlue(p);
if (composite_image->matte != MagickFalse)
source.opacity=(MagickRealType) GetPixelOpacity(p);
if (composite_image->colorspace == CMYKColorspace)
source.index=(MagickRealType) GetPixelIndex(composite_indexes+
x-x_offset);
if (composite_image->colorspace == CMYKColorspace)
{
source.red=(MagickRealType) QuantumRange-source.red;
source.green=(MagickRealType) QuantumRange-source.green;
source.blue=(MagickRealType) QuantumRange-source.blue;
source.index=(MagickRealType) QuantumRange-source.index;
}
switch (compose)
{
/* Duff-Porter Compositions */
case ClearCompositeOp:
{
CompositeClear(&destination,&composite);
break;
}
case SrcCompositeOp:
case CopyCompositeOp:
case ReplaceCompositeOp:
{
composite=source;
break;
}
case NoCompositeOp:
case DstCompositeOp:
break;
case OverCompositeOp:
case SrcOverCompositeOp:
{
MagickPixelCompositeOver(&source,source.opacity,&destination,
destination.opacity,&composite);
break;
}
case DstOverCompositeOp:
{
MagickPixelCompositeOver(&destination,destination.opacity,&source,
source.opacity,&composite);
break;
}
case SrcInCompositeOp:
case InCompositeOp:
{
CompositeIn(&source,&destination,&composite);
break;
}
case DstInCompositeOp:
{
CompositeIn(&destination,&source,&composite);
break;
}
case OutCompositeOp:
case SrcOutCompositeOp:
{
CompositeOut(&source,&destination,&composite);
break;
}
case DstOutCompositeOp:
{
CompositeOut(&destination,&source,&composite);
break;
}
case AtopCompositeOp:
case SrcAtopCompositeOp:
{
CompositeAtop(&source,&destination,&composite);
break;
}
case DstAtopCompositeOp:
{
CompositeAtop(&destination,&source,&composite);
break;
}
case XorCompositeOp:
{
CompositeXor(&source,&destination,&composite);
break;
}
/* Mathematical Compositions */
case PlusCompositeOp:
{
CompositePlus(&source,&destination,channel,&composite);
break;
}
case MinusDstCompositeOp:
{
CompositeMinus(&source,&destination,channel,&composite);
break;
}
case MinusSrcCompositeOp:
{
CompositeMinus(&destination,&source,channel,&composite);
break;
}
case ModulusAddCompositeOp:
{
CompositeModulusAdd(&source,&destination,channel,&composite);
break;
}
case ModulusSubtractCompositeOp:
{
CompositeModulusSubtract(&source,&destination,channel,&composite);
break;
}
case DifferenceCompositeOp:
{
CompositeDifference(&source,&destination,channel,&composite);
break;
}
case ExclusionCompositeOp:
{
CompositeExclusion(&source,&destination,channel,&composite);
break;
}
case MultiplyCompositeOp:
{
CompositeMultiply(&source,&destination,channel,&composite);
break;
}
case ScreenCompositeOp:
{
CompositeScreen(&source,&destination,channel,&composite);
break;
}
case DivideDstCompositeOp:
{
CompositeDivide(&source,&destination,channel,&composite);
break;
}
case DivideSrcCompositeOp:
{
CompositeDivide(&destination,&source,channel,&composite);
break;
}
case DarkenCompositeOp:
{
CompositeDarken(&source,&destination,channel,&composite);
break;
}
case LightenCompositeOp:
{
CompositeLighten(&source,&destination,channel,&composite);
break;
}
case DarkenIntensityCompositeOp:
{
CompositeDarkenIntensity(&source,&destination,channel,&composite);
break;
}
case LightenIntensityCompositeOp:
{
CompositeLightenIntensity(&source,&destination,channel,&composite);
break;
}
case MathematicsCompositeOp:
{
CompositeMathematics(&source,&destination,channel,&geometry_info,
&composite);
break;
}
/* Lighting Compositions */
case ColorDodgeCompositeOp:
{
CompositeColorDodge(&source,&destination,&composite);
break;
}
case ColorBurnCompositeOp:
{
CompositeColorBurn(&source,&destination,&composite);
break;
}
case LinearDodgeCompositeOp:
{
CompositeLinearDodge(&source,&destination,&composite);
break;
}
case LinearBurnCompositeOp:
{
CompositeLinearBurn(&source,&destination,&composite);
break;
}
case HardLightCompositeOp:
{
CompositeHardLight(&source,&destination,&composite);
break;
}
case OverlayCompositeOp:
{
/* Overlay = Reversed HardLight. */
CompositeHardLight(&destination,&source,&composite);
break;
}
case SoftLightCompositeOp:
{
CompositeSoftLight(&source,&destination,&composite);
break;
}
case LinearLightCompositeOp:
{
CompositeLinearLight(&source,&destination,&composite);
break;
}
case PegtopLightCompositeOp:
{
CompositePegtopLight(&source,&destination,&composite);
break;
}
case VividLightCompositeOp:
{
CompositeVividLight(&source,&destination,&composite);
break;
}
case PinLightCompositeOp:
{
CompositePinLight(&source,&destination,&composite);
break;
}
/* Other Composition */
case ChangeMaskCompositeOp:
{
if ((composite.opacity > ((MagickRealType) QuantumRange/2.0)) ||
(IsMagickColorSimilar(&source,&destination) != MagickFalse))
composite.opacity=(MagickRealType) TransparentOpacity;
else
composite.opacity=(MagickRealType) OpaqueOpacity;
break;
}
case BumpmapCompositeOp:
{
if (source.opacity == TransparentOpacity)
break;
CompositeBumpmap(&source,&destination,&composite);
break;
}
case DissolveCompositeOp:
{
MagickPixelCompositeOver(&source,(MagickRealType) (QuantumRange-
source_dissolve*(QuantumRange-source.opacity)),&destination,
(MagickRealType) (QuantumRange-destination_dissolve*(QuantumRange-
destination.opacity)),&composite);
break;
}
case BlendCompositeOp:
{
MagickPixelCompositeBlend(&source,source_dissolve,&destination,
destination_dissolve,&composite);
break;
}
case ThresholdCompositeOp:
{
CompositeThreshold(&source,&destination,threshold,amount,&composite);
break;
}
case ModulateCompositeOp:
{
ssize_t
offset;
if (source.opacity == TransparentOpacity)
break;
offset=(ssize_t) (MagickPixelIntensityToQuantum(&source)-midpoint);
if (offset == 0)
break;
CompositeHCL(destination.red,destination.green,destination.blue,&hue,
&chroma,&luma);
luma+=(0.01*percent_luma*offset)/midpoint;
chroma*=0.01*percent_chroma;
HCLComposite(hue,chroma,luma,&composite.red,
&composite.green,&composite.blue);
break;
}
case HueCompositeOp:
{
if (source.opacity == TransparentOpacity)
break;
if (destination.opacity == TransparentOpacity)
{
composite=source;
break;
}
CompositeHCL(destination.red,destination.green,destination.blue,&hue,
&chroma,&luma);
CompositeHCL(source.red,source.green,source.blue,&hue,&sans,&sans);
HCLComposite(hue,chroma,luma,&composite.red,
&composite.green,&composite.blue);
if (source.opacity < destination.opacity)
composite.opacity=source.opacity;
break;
}
case SaturateCompositeOp:
{
if (source.opacity == TransparentOpacity)
break;
if (destination.opacity == TransparentOpacity)
{
composite=source;
break;
}
CompositeHCL(destination.red,destination.green,destination.blue,&hue,
&chroma,&luma);
CompositeHCL(source.red,source.green,source.blue,&sans,&chroma,
&sans);
HCLComposite(hue,chroma,luma,&composite.red,
&composite.green,&composite.blue);
if (source.opacity < destination.opacity)
composite.opacity=source.opacity;
break;
}
case LuminizeCompositeOp:
{
if (source.opacity == TransparentOpacity)
break;
if (destination.opacity == TransparentOpacity)
{
composite=source;
break;
}
CompositeHCL(destination.red,destination.green,destination.blue,&hue,
&chroma,&luma);
CompositeHCL(source.red,source.green,source.blue,&sans,&sans,
&luma);
HCLComposite(hue,chroma,luma,&composite.red,
&composite.green,&composite.blue);
if (source.opacity < destination.opacity)
composite.opacity=source.opacity;
break;
}
case ColorizeCompositeOp:
{
if (source.opacity == TransparentOpacity)
break;
if (destination.opacity == TransparentOpacity)
{
composite=source;
break;
}
CompositeHCL(destination.red,destination.green,destination.blue,&sans,
&sans,&luma);
CompositeHCL(source.red,source.green,source.blue,&hue,&chroma,
&sans);
HCLComposite(hue,chroma,luma,&composite.red,
&composite.green,&composite.blue);
if (source.opacity < destination.opacity)
composite.opacity=source.opacity;
break;
}
case CopyRedCompositeOp:
case CopyCyanCompositeOp:
{
composite.red=source.red;
break;
}
case CopyGreenCompositeOp:
case CopyMagentaCompositeOp:
{
composite.green=source.green;
break;
}
case CopyBlueCompositeOp:
case CopyYellowCompositeOp:
{
composite.blue=source.blue;
break;
}
case CopyOpacityCompositeOp:
{
if (source.matte == MagickFalse)
{
composite.opacity=(MagickRealType) (QuantumRange-
MagickPixelIntensityToQuantum(&source));
break;
}
composite.opacity=source.opacity;
break;
}
case CopyBlackCompositeOp:
{
if (source.colorspace != CMYKColorspace)
ConvertRGBToCMYK(&source);
composite.index=source.index;
break;
}
/* compose methods that are already handled */
case BlurCompositeOp:
case DisplaceCompositeOp:
case DistortCompositeOp:
{
composite=source;
break;
}
default:
break;
}
if (image->colorspace == CMYKColorspace)
{
composite.red=(MagickRealType) QuantumRange-composite.red;
composite.green=(MagickRealType) QuantumRange-composite.green;
composite.blue=(MagickRealType) QuantumRange-composite.blue;
composite.index=(MagickRealType) QuantumRange-composite.index;
}
SetPixelRed(q,ClampToQuantum(composite.red));
SetPixelGreen(q,ClampToQuantum(composite.green));
SetPixelBlue(q,ClampToQuantum(composite.blue));
SetPixelOpacity(q,ClampToQuantum(composite.opacity));
if (image->colorspace == CMYKColorspace)
SetPixelIndex(indexes+x,ClampToQuantum(composite.index));
p++;
if (p >= (pixels+composite_image->columns))
p=pixels;
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_CompositeImageChannel)
#endif
proceed=SetImageProgress(image,CompositeImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
composite_view=DestroyCacheView(composite_view);
image_view=DestroyCacheView(image_view);
if (destination_image != (Image * ) NULL)
destination_image=DestroyImage(destination_image);
else
composite_image=DestroyImage(composite_image);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T e x t u r e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TextureImage() repeatedly tiles the texture image across and down the image
% canvas.
%
% The format of the TextureImage method is:
%
% MagickBooleanType TextureImage(Image *image,const Image *texture)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o texture: This image is the texture to layer on the background.
%
*/
MagickExport MagickBooleanType TextureImage(Image *image,const Image *texture)
{
#define TextureImageTag "Texture/Image"
CacheView
*image_view,
*texture_view;
ExceptionInfo
*exception;
Image
*texture_image;
MagickBooleanType
status;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickSignature);
if (texture == (const Image *) NULL)
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
exception=(&image->exception);
texture_image=CloneImage(texture,0,0,MagickTrue,exception);
if (texture_image == (const Image *) NULL)
return(MagickFalse);
(void) TransformImageColorspace(texture_image,image->colorspace);
(void) SetImageVirtualPixelMethod(texture_image,TileVirtualPixelMethod);
status=MagickTrue;
if ((image->compose != CopyCompositeOp) &&
((image->compose != OverCompositeOp) || (image->matte != MagickFalse) ||
(texture_image->matte != MagickFalse)))
{
/*
Tile texture onto the image background.
*/
for (y=0; y < (ssize_t) image->rows; y+=(ssize_t) texture_image->rows)
{
register ssize_t
x;
if (status == MagickFalse)
continue;
for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) texture_image->columns)
{
MagickBooleanType
thread_status;
thread_status=CompositeImage(image,image->compose,texture_image,x+
texture_image->tile_offset.x,y+texture_image->tile_offset.y);
if (thread_status == MagickFalse)
{
status=thread_status;
break;
}
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,TextureImageTag,(MagickOffsetType)
y,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
(void) SetImageProgress(image,TextureImageTag,(MagickOffsetType)
image->rows,image->rows);
texture_image=DestroyImage(texture_image);
return(status);
}
/*
Tile texture onto the image background (optimized).
*/
status=MagickTrue;
texture_view=AcquireVirtualCacheView(texture_image,exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,texture_image,1,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register const IndexPacket
*texture_indexes;
register const PixelPacket
*p;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
size_t
width;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(texture_view,texture_image->tile_offset.x,(y+
texture_image->tile_offset.y) % texture_image->rows,
texture_image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
texture_indexes=GetCacheViewVirtualIndexQueue(texture_view);
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) texture_image->columns)
{
width=texture_image->columns;
if ((x+(ssize_t) width) > (ssize_t) image->columns)
width=image->columns-x;
(void) CopyMagickMemory(q,p,width*sizeof(*p));
if ((image->colorspace == CMYKColorspace) &&
(texture_image->colorspace == CMYKColorspace))
{
(void) CopyMagickMemory(indexes,texture_indexes,width*
sizeof(*indexes));
indexes+=width;
}
q+=width;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_TextureImage)
#endif
proceed=SetImageProgress(image,TextureImageTag,(MagickOffsetType) y,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
texture_view=DestroyCacheView(texture_view);
image_view=DestroyCacheView(image_view);
texture_image=DestroyImage(texture_image);
return(status);
}
|
pmv-openMP-a.c | // Compilar con -O2 y -fopenmp
#include <stdlib.h>
#include <stdio.h>
#include <omp.h>
int main(int argc, char** argv){
int i, j;
double t1, t2, total;
//Leer argumento de entrada (no de componentes del vector)
if (argc<2){
printf("Falta tamaño de matriz y vector\n");
exit(-1);
}
unsigned int N = atoi(argv[1]); // Máximo N =2^32-1=4294967295 (sizeof(unsigned int) = 4 B)
double *v1, *v2, **M;
v1 = (double*) malloc(N*sizeof(double));// malloc necesita el tamaño en bytes
v2 = (double*) malloc(N*sizeof(double)); //si no hay espacio suficiente malloc devuelve NULL
M = (double**) malloc(N*sizeof(double *));
if ( (v1==NULL) || (v2==NULL) || (M==NULL) ){
printf("Error en la reserva de espacio para los vectores\n");
exit(-2);
}
for (i=0; i<N; i++){
M[i] = (double*) malloc(N*sizeof(double));
if ( M[i]==NULL ){
printf("Error en la reserva de espacio para los vectores\n");
exit(-2);
}
}
//A partir de aqui se pueden acceder las componentes de la matriz como M[i][j]
#pragma omp parallel
{
//Inicializar matriz y vectores
#pragma omp for private(j)
for(i = 0; i< N; i++)
{
v1[i] = 2;
v2[i] = 0;
for(j = 0; j < N; j++ )
{
M[i][j] = 2;
}
}
//Medida de tiempo
#pragma omp single
{
t1 = omp_get_wtime();
}
//Calcular producto de matriz por vector v2 = M · v1
#pragma omp for private(j)
for(i = 0; i<N;i++)
{
for(j=0; j<N;j++)
{
v2[i] += M[i][j] * v1[j];
}
}
//Medida de tiempo
#pragma omp single
{
t2 = omp_get_wtime();
}
}
total = t2 - t1;
//Imprimir el resultado y el tiempo de ejecución
printf("Tiempo(seg.):%11.9f\t / Tamaño:%u\t/ V2[0]=%8.6f V2[%d]=%8.6f\n", total,N,v2[0],N-1,v2[N-1]);
free(v1); // libera el espacio reservado para v1
free(v2); // libera el espacio reservado para v2
for (i=0; i<N; i++)
free(M[i]);
free(M);
return 0;
}
|
simulate_blif.c | /*
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "simulate_blif.h"
#ifndef max
#define max(a,b) (((a) > (b))? (a) : (b))
#define min(a,b) ((a) > (b)? (b) : (a))
#endif
/*
* Performs simulation.
*/
void simulate_netlist(netlist_t *netlist)
{
printf("Beginning simulation.\n"); fflush(stdout);
// Create and verify the lines.
lines_t *input_lines = create_lines(netlist, INPUT);
if (!verify_lines(input_lines))
error_message(SIMULATION_ERROR, 0, -1, "Input lines could not be assigned.");
lines_t *output_lines = create_lines(netlist, OUTPUT);
if (!verify_lines(output_lines))
error_message(SIMULATION_ERROR, 0, -1, "Output lines could not be assigned.");
// Open the output vector file.
FILE *out = fopen(OUTPUT_VECTOR_FILE_NAME, "w");
if (!out)
error_message(SIMULATION_ERROR, 0, -1, "Could not open output vector file.");
// Open the input vector file.
FILE *in_out = fopen( INPUT_VECTOR_FILE_NAME, "w");
if (!in_out)
error_message(SIMULATION_ERROR, 0, -1, "Could not open input vector file.");
// Open the modelsim vector file.
FILE *modelsim_out = fopen("test.do", "w");
if (!modelsim_out)
error_message(SIMULATION_ERROR, 0, -1, "Could not open modelsim output file.");
FILE *in = NULL;
int num_vectors;
// Passed via the -t option.
char *input_vector_file = global_args.sim_vector_input_file;
// Input vectors can either come from a file or be randomly generated.
if (input_vector_file)
{
in = fopen(input_vector_file, "r");
if (!in)
error_message(SIMULATION_ERROR, 0, -1, "Could not open vector input file: %s", input_vector_file);
num_vectors = count_test_vectors(in);
// Read the vector headers and check to make sure they match the lines.
if (!verify_test_vector_headers(in, input_lines))
error_message(SIMULATION_ERROR, 0, -1, "Invalid vector header format in %s.", input_vector_file);
printf("Simulating %d existing vectors from \"%s\".\n", num_vectors, input_vector_file); fflush(stdout);
}
else
{
// Passed via the -g option.
num_vectors = global_args.sim_num_test_vectors;
printf("Simulating %d new vectors.\n", num_vectors); fflush(stdout);
}
// Determine which edge(s) we are outputting.
int output_edge;
if (global_args.sim_output_both_edges ) output_edge = -1; // Both edges
else if (global_args.sim_output_rising_edge) output_edge = 1; // Rising edge only
else output_edge = 0; // Falling edge only
if (!num_vectors)
{
error_message(SIMULATION_ERROR, 0, -1, "No vectors to simulate.");
}
else
{
printf("\n");
int progress_bar_position = -1;
const int progress_bar_length = 50;
double total_time = 0; // Includes I/O
double simulation_time = 0; // Does not include I/O
stages *stages = 0;
// Parse -L and -H options containing lists of pins to hold high or low during random vector generation.
pin_names *hold_high = parse_pin_name_list(global_args.sim_hold_high);
pin_names *hold_low = parse_pin_name_list(global_args.sim_hold_low);
hashtable_t *hold_high_index = index_pin_name_list(hold_high);
hashtable_t *hold_low_index = index_pin_name_list(hold_low);
/*
* Simulation is done in "waves" of SIM_WAVE_LENGTH cycles at a time.
* Every second cycle gets a input new vector.
*/
int num_cycles = num_vectors * 2;
int num_waves = ceil(num_cycles / (double)SIM_WAVE_LENGTH);
int wave;
test_vector *v = 0;
for (wave = 0; wave < num_waves; wave++)
{
double wave_start_time = wall_time();
int cycle_offset = SIM_WAVE_LENGTH * wave;
int wave_length = (wave < (num_waves-1))?SIM_WAVE_LENGTH:(num_cycles - cycle_offset);
// Assign vectors to lines, either by reading or generating them.
// Every second cycle gets a new vector.
int cycle;
for (cycle = cycle_offset; cycle < cycle_offset + wave_length; cycle++)
{
if (is_even_cycle(cycle))
{
if (input_vector_file)
{
char buffer[BUFFER_MAX_SIZE];
if (!get_next_vector(in, buffer))
error_message(SIMULATION_ERROR, 0, -1, "Could not read next vector.");
v = parse_test_vector(buffer);
}
else
{
v = generate_random_test_vector(input_lines, cycle, hold_high_index, hold_low_index);
}
}
add_test_vector_to_lines(v, input_lines, cycle);
if (!is_even_cycle(cycle))
free_test_vector(v);
}
// Record the input vectors we are using.
write_wave_to_file(input_lines, in_out, cycle_offset, wave_length, 1);
// Write ModelSim script.
write_wave_to_modelsim_file(netlist, input_lines, modelsim_out, cycle_offset, wave_length);
double simulation_start_time = wall_time();
// Perform simulation
for (cycle = cycle_offset; cycle < cycle_offset + wave_length; cycle++)
{
//original_simulate_cycle(netlist, cycle);
if (cycle)
{
simulate_cycle(cycle, stages);
}
else
{
// The first cycle produces the stages, and adds additional
// lines as specified by the -p option.
pin_names *p = parse_pin_name_list(global_args.sim_additional_pins);
stages = simulate_first_cycle(netlist, cycle, p, output_lines);
free_pin_name_list(p);
// Make sure the output lines are still OK after adding custom lines.
if (!verify_lines(output_lines))
error_message(SIMULATION_ERROR, 0, -1,
"Problem detected with the output lines after the first cycle.");
}
}
simulation_time += wall_time() - simulation_start_time;
// Write the result of this wave to the output vector file.
write_wave_to_file(output_lines, out, cycle_offset, wave_length, output_edge);
total_time += wall_time() - wave_start_time;
// Print netlist-specific statistics.
if (!cycle_offset)
print_netlist_stats(stages, num_vectors);
// Delay drawing of the progress bar until the second wave to improve the accuracy of the ETA.
if ((num_waves == 1) || cycle_offset)
progress_bar_position = print_progress_bar(
cycle/(double)num_cycles, progress_bar_position, progress_bar_length, total_time);
}
free_pin_name_list(hold_high);
free_pin_name_list(hold_low);
hold_high_index->destroy_free_items(hold_high_index);
hold_low_index ->destroy_free_items(hold_low_index);
fflush(out);
fprintf(modelsim_out, "run %d\n", num_vectors*100);
printf("\n");
// If a second output vector file was given via the -T option, verify that it matches.
char *output_vector_file = global_args.sim_vector_output_file;
if (output_vector_file)
{
if (verify_output_vectors(output_vector_file, num_vectors))
printf("Vector file \"%s\" matches output\n", output_vector_file);
else
error_message(SIMULATION_ERROR, 0, -1, "Vector files differ.");
printf("\n");
}
// Print statistics.
print_simulation_stats(stages, num_vectors, total_time, simulation_time);
free_stages(stages);
}
free_lines(output_lines);
free_lines(input_lines);
fclose(modelsim_out);
fclose(in_out);
if (input_vector_file)
fclose(in);
fclose(out);
}
/*
* This simulates a single cycle using the stages generated
* during the first cycle. Simulates in parallel if OpenMP is enabled.
*
* OpenMP simulation computes a small number of cycles sequentially and
* a small number in parallel. The minimum parallel and sequential time is
* taken for each stage, and that stage is computed in parallel for all subsequent
* cycles if speedup is observed.
*/
void simulate_cycle(int cycle, stages *s)
{
#ifdef _OPENMP
// -1 for cycle 0, -1 for the last cycle in the wave.
const int test_cycles = SIM_WAVE_LENGTH - 2;
const int st_length = test_cycles/2;
const int st_start = 1;
const int st_end = st_start + (st_length-1);
const int pt_length = test_cycles - st_length;
const int pt_start = st_end + 1;
const int pt_end = pt_start + (pt_length-1);
if (test_cycles < 2)
error_message(SIMULATION_ERROR, -1, -1, "SIM_WAVE_LENGTH is too small.");
// Range of cycles over which to test the sequential run times of each stage.
char sequential_test = (cycle >= st_start && cycle <= st_end);
// Range of cycles over which to test the parallel run times of each stage.
char parallel_test = (cycle >= pt_start && cycle <= pt_end);
#endif
int i;
for(i = 0; i < s->count; i++)
{
int j;
#ifdef _OPENMP
double time = 0.0;
if (sequential_test || parallel_test)
time = wall_time();
// Compute in parallel if we are profiling or if this stage is known to be faster in parallel.
char compute_in_parallel = parallel_test
|| (!sequential_test && !parallel_test && s->sequential_times[i] > s->parallel_times[i]);
if (compute_in_parallel)
{ // Compute the stage in parallel.
#pragma omp parallel for schedule(static)
for (j = 0; j < s->counts[i]; j++)
compute_and_store_value(s->stages[i][j], cycle);
}
else
{
#endif
// Compute the stage sequentially.
for (j = 0; j < s->counts[i]; j++)
compute_and_store_value(s->stages[i][j], cycle);
#ifdef _OPENMP
}
if (sequential_test)
{
// Take the minimum sequential time.
time = wall_time() - time;
if (s->sequential_times[i] == 0 || time < s->sequential_times[i])
s->sequential_times[i] = time;
}
else if (parallel_test)
{
// Take the minimum parallel time.
time = wall_time() - time;
if (s->parallel_times[i] == 0 || time < s->parallel_times[i])
s->parallel_times[i] = time;
}
if (cycle == pt_end + 1)
{
//printf("%.10f\t %.10f\t %.10f\t %d\t %d\t %f\n", s->sequential_times[i], s->parallel_times[i], s->sequential_times[i]/s->parallel_times[i], s->counts[i], compute_in_parallel, s->num_children[i]/(double)s->counts[i]);
//printf("%d %d %d %d %d %d\n", st_length, pt_length, st_start, st_end, pt_start, pt_end);
// Record the number of nodes in parallelizable stages.
if (compute_in_parallel)
s->num_parallel_nodes += s->counts[i];
}
#endif
}
}
/*
* Simulates the first cycle by traversing the netlist and returns
* the nodes organised into parallelizable stages. Also adds lines to
* custom pins and nodes as requested via the -p option.
*/
stages *simulate_first_cycle(netlist_t *netlist, int cycle, pin_names *p, lines_t *l)
{
queue_t *queue = create_queue();
// Enqueue top input nodes
int i;
for (i = 0; i < netlist->num_top_input_nodes; i++)
enqueue_node_if_ready(queue,netlist->top_input_nodes[i],cycle);
// Enqueue constant nodes.
nnode_t *constant_nodes[] = {netlist->gnd_node, netlist->vcc_node, netlist->pad_node};
int num_constant_nodes = 3;
for (i = 0; i < num_constant_nodes; i++)
enqueue_node_if_ready(queue,constant_nodes[i],cycle);
nnode_t **ordered_nodes = 0;
int num_ordered_nodes = 0;
nnode_t *node;
while ((node = queue->remove(queue)))
{
compute_and_store_value(node, cycle);
// Match node for items passed via -p and add to lines if there's a match.
add_additional_items_to_lines(node, p, l);
// Enqueue child nodes which are ready, not already queued, and not already complete.
int num_children = 0;
nnode_t **children = get_children_of(node, &num_children);
for (i = 0; i < num_children; i++)
{
nnode_t* node = children[i];
if (!node->in_queue && is_node_ready(node, cycle) && !is_node_complete(node, cycle))
{
node->in_queue = TRUE;
queue->add(queue,node);
}
}
free(children);
node->in_queue = FALSE;
// Add the node to the ordered nodes array.
ordered_nodes = realloc(ordered_nodes, sizeof(nnode_t *) * (num_ordered_nodes + 1));
ordered_nodes[num_ordered_nodes++] = node;
}
queue->destroy(queue);
// Reorganise the ordered nodes into stages for parallel computation.
stages *s = stage_ordered_nodes(ordered_nodes, num_ordered_nodes);
free(ordered_nodes);
return s;
}
/*
* Puts the ordered nodes in stages, each of which can be computed in parallel.
*/
stages *stage_ordered_nodes(nnode_t **ordered_nodes, int num_ordered_nodes) {
stages *s = malloc(sizeof(stages));
s->stages = calloc(1,sizeof(nnode_t**));
s->counts = calloc(1,sizeof(int));
s->num_children = calloc(1,sizeof(int));
s->count = 1;
s->num_connections = 0;
s->num_nodes = num_ordered_nodes;
s->num_parallel_nodes = 0;
const int index_table_size = (num_ordered_nodes/100)+10;
// Hash tables index the nodes in the current stage, as well as their children.
hashtable_t *stage_children = create_hashtable(index_table_size);
hashtable_t *stage_nodes = create_hashtable(index_table_size);
int i;
for (i = 0; i < num_ordered_nodes; i++)
{
nnode_t* node = ordered_nodes[i];
int stage = s->count-1;
// Get the node's children for dependency checks.
int num_children;
nnode_t **children = get_children_of(node, &num_children);
// Determine if the node is a child of any node in the current stage.
int is_child_of_stage = stage_children->get(stage_children, node, sizeof(nnode_t*))?1:0;
// Determine if any node in the current stage is a child of this node.
int is_stage_child_of = FALSE;
int j;
if (!is_child_of_stage)
for (j = 0; j < num_children; j++)
if ((is_stage_child_of = stage_nodes->get(stage_nodes, children[j], sizeof(nnode_t*))?1:0))
break;
// Start a new stage if this node is related to any node in the current stage.
if (is_child_of_stage || is_stage_child_of)
{
s->stages = realloc(s->stages, sizeof(nnode_t**) * (s->count+1));
s->counts = realloc(s->counts, sizeof(int) * (s->count+1));
s->num_children = realloc(s->num_children, sizeof(int) * (s->count+1));
stage = s->count++;
s->stages[stage] = 0;
s->counts[stage] = 0;
s->num_children[stage] = 0;
stage_children->destroy(stage_children);
stage_nodes ->destroy(stage_nodes);
stage_children = create_hashtable(index_table_size);
stage_nodes = create_hashtable(index_table_size);
}
// Add the node to the current stage.
s->stages[stage] = realloc(s->stages[stage],sizeof(nnode_t*) * (s->counts[stage]+1));
s->stages[stage][s->counts[stage]++] = node;
// Index the node.
stage_nodes->add(stage_nodes, node, sizeof(nnode_t*), node);
// Index its children.
for (j = 0; j < num_children; j++)
stage_children->add(stage_children, children[j], sizeof(nnode_t*), children[j]);
// Record the number of children for computing the degree.
s->num_connections += num_children;
s->num_children[stage] += num_children;
free(children);
}
stage_children->destroy(stage_children);
stage_nodes ->destroy(stage_nodes);
s->sequential_times = calloc(s->count, sizeof(double));
s->parallel_times = calloc(s->count, sizeof(double));
return s;
}
/*
* Given a node, this function will simulate that node's new outputs,
* and updates those pins.
*/
void compute_and_store_value(nnode_t *node, int cycle)
{
update_undriven_input_pins(node,cycle);
operation_list type = is_clock_node(node)?CLOCK_NODE:node->type;
switch(type)
{
case MUX_2:
compute_mux_2_node(node, cycle);
break;
case FF_NODE:
compute_flipflop_node(node, cycle);
break;
case MEMORY:
compute_memory_node(node, cycle);
break;
case MULTIPLY:
compute_multiply_node(node, cycle);
break;
case LOGICAL_AND: // &&
{
oassert(node->num_output_pins == 1);
char unknown = FALSE;
char zero = FALSE;
int i;
for (i = 0; i < node->num_input_pins; i++)
{
signed char pin = get_pin_value(node->input_pins[i], cycle);
if (pin < 0) { unknown = TRUE; }
else if (pin == 0) { zero = TRUE; break; }
}
if (zero) update_pin_value(node->output_pins[0], 0, cycle);
else if (unknown) update_pin_value(node->output_pins[0], -1, cycle);
else update_pin_value(node->output_pins[0], 1, cycle);
break;
}
case LOGICAL_OR:
{ // ||
oassert(node->num_output_pins == 1);
char unknown = FALSE;
char one = FALSE;
int i;
for (i = 0; i < node->num_input_pins; i++)
{
signed char pin = get_pin_value(node->input_pins[i], cycle);
if (pin < 0) { unknown = TRUE; }
else if (pin == 1) { one = TRUE; break; }
}
if (one) update_pin_value(node->output_pins[0], 1, cycle);
else if (unknown) update_pin_value(node->output_pins[0], -1, cycle);
else update_pin_value(node->output_pins[0], 0, cycle);
break;
}
case LOGICAL_NAND:
{ // !&&
oassert(node->num_output_pins == 1);
char unknown = FALSE;
char one = FALSE;
int i;
for (i = 0; i < node->num_input_pins; i++)
{
signed char pin = get_pin_value(node->input_pins[i], cycle);
if (pin < 0) { unknown = TRUE; }
else if (pin == 0) { one = TRUE; break; }
}
if (one) update_pin_value(node->output_pins[0], 1, cycle);
else if (unknown) update_pin_value(node->output_pins[0], -1, cycle);
else update_pin_value(node->output_pins[0], 0, cycle);
break;
}
case LOGICAL_NOT: // !
case LOGICAL_NOR: // !|
{
oassert(node->num_output_pins == 1);
char unknown = FALSE;
char zero = FALSE;
int i;
for (i = 0; i < node->num_input_pins; i++)
{
signed char pin = get_pin_value(node->input_pins[i], cycle);
if (pin < 0) { unknown = TRUE; }
else if (pin == 1) { zero = TRUE; break; }
}
if (zero) update_pin_value(node->output_pins[0], 0, cycle);
else if (unknown) update_pin_value(node->output_pins[0], -1, cycle);
else update_pin_value(node->output_pins[0], 1, cycle);
break;
}
case LT: // < 010 1
{
oassert(node->num_input_port_sizes == 3);
oassert(node->num_output_port_sizes == 1);
signed char pin0 = get_pin_value(node->input_pins[0],cycle);
signed char pin1 = get_pin_value(node->input_pins[1],cycle);
signed char pin2 = get_pin_value(node->input_pins[2],cycle);
if (pin0 < 0 || pin1 < 0 || pin2 < 0)
update_pin_value(node->output_pins[0], -1, cycle);
else if (pin0 == 0 && pin1 == 1 && pin2 == 0)
update_pin_value(node->output_pins[0], 1, cycle);
else
update_pin_value(node->output_pins[0], 0, cycle);
break;
}
case GT: // > 100 1
{
oassert(node->num_input_port_sizes == 3);
oassert(node->num_output_port_sizes == 1);
signed char pin0 = get_pin_value(node->input_pins[0],cycle);
signed char pin1 = get_pin_value(node->input_pins[1],cycle);
signed char pin2 = get_pin_value(node->input_pins[2],cycle);
if (pin0 < 0 || pin1 < 0 || pin2 < 0)
update_pin_value(node->output_pins[0], -1, cycle);
else if (pin0 == 1 && pin1 == 0 && pin2 == 0)
update_pin_value(node->output_pins[0], 1, cycle);
else
update_pin_value(node->output_pins[0], 0, cycle);
break;
}
case ADDER_FUNC: // 001 1\n010 1\n100 1\n111 1
{
oassert(node->num_input_port_sizes == 3);
oassert(node->num_output_port_sizes == 1);
signed char pin0 = get_pin_value(node->input_pins[0],cycle);
signed char pin1 = get_pin_value(node->input_pins[1],cycle);
signed char pin2 = get_pin_value(node->input_pins[2],cycle);
if (pin0 < 0 || pin1 < 0 || pin2 < 0)
update_pin_value(node->output_pins[0], -1, cycle);
else if (
(pin0 == 0 && pin1 == 0 && pin2 == 1)
|| (pin0 == 0 && pin1 == 1 && pin2 == 0)
|| (pin0 == 1 && pin1 == 0 && pin2 == 0)
|| (pin0 == 1 && pin1 == 1 && pin2 == 1)
)
update_pin_value(node->output_pins[0], 1, cycle);
else
update_pin_value(node->output_pins[0], 0, cycle);
break;
}
case CARRY_FUNC: // 011 1\n100 1\n110 1\n111 1
{
oassert(node->num_input_port_sizes == 3);
oassert(node->num_output_port_sizes == 1);
signed char pin0 = get_pin_value(node->input_pins[0],cycle);
signed char pin1 = get_pin_value(node->input_pins[1],cycle);
signed char pin2 = get_pin_value(node->input_pins[2],cycle);
if (pin0 < 0 || pin1 < 0 || pin2 < 0)
update_pin_value(node->output_pins[0], -1, cycle);
else if (
(pin0 == 1 && (pin1 == 1 || pin2 == 1))
|| (pin1 == 1 && pin2 == 1)
)
update_pin_value(node->output_pins[0], 1, cycle);
else
update_pin_value(node->output_pins[0], 0, cycle);
break;
}
case NOT_EQUAL: // !=
case LOGICAL_XOR: // ^
{
oassert(node->num_output_pins == 1);
char unknown = FALSE;
int ones = 0;
int i;
for (i = 0; i < node->num_input_pins; i++)
{
signed char pin = get_pin_value(node->input_pins[i], cycle);
if (pin < 0) { unknown = TRUE; break; }
else if (pin == 1) { ones++; }
}
if (unknown) update_pin_value(node->output_pins[0], -1, cycle);
else if ((ones % 2) == 1) update_pin_value(node->output_pins[0], 1, cycle);
else update_pin_value(node->output_pins[0], 0, cycle);
break;
}
case LOGICAL_EQUAL: // ==
case LOGICAL_XNOR: // !^
{
oassert(node->num_output_pins == 1);
char unknown = FALSE;
int ones = 0;
int i;
for (i = 0; i < node->num_input_pins; i++)
{
signed char pin = get_pin_value(node->input_pins[i], cycle);
if (pin < 0) { unknown = TRUE; break; }
if (pin == 1) { ones++; }
}
if (unknown) update_pin_value(node->output_pins[0], -1, cycle);
else if ((ones % 2) == 1) update_pin_value(node->output_pins[0], 0, cycle);
else update_pin_value(node->output_pins[0], 1, cycle);
break;
}
case BITWISE_NOT:
{
oassert(node->num_input_pins == 1);
oassert(node->num_output_pins == 1);
signed char pin = get_pin_value(node->input_pins[0], cycle);
if (pin < 0) update_pin_value(node->output_pins[0], -1, cycle);
else if (pin == 1) update_pin_value(node->output_pins[0], 0, cycle);
else update_pin_value(node->output_pins[0], 1, cycle);
break;
}
case CLOCK_NODE:
{
int i;
for (i = 0; i < node->num_output_pins; i++)
update_pin_value(node->output_pins[i], is_even_cycle(cycle)?0:1, cycle);
break;
}
case GND_NODE:
oassert(node->num_output_pins == 1);
update_pin_value(node->output_pins[0], 0, cycle);
break;
case VCC_NODE:
oassert(node->num_output_pins == 1);
update_pin_value(node->output_pins[0], 1, cycle);
break;
case PAD_NODE:
oassert(node->num_output_pins == 1);
update_pin_value(node->output_pins[0], 0, cycle);
break;
case INPUT_NODE:
break;
case OUTPUT_NODE:
oassert(node->num_output_pins == 1);
oassert(node->num_input_pins == 1);
update_pin_value(node->output_pins[0], get_pin_value(node->input_pins[0],cycle), cycle);
break;
case HARD_IP:
compute_hard_ip_node(node,cycle);
break;
case GENERIC :
compute_generic_node(node,cycle);
break;
//case FULLADDER:
case ADD:
compute_add_node(node, cycle, 0);
break;
case MINUS:
if(node->num_input_port_sizes == 3)
compute_add_node(node, cycle, 1);
else
compute_unary_sub_node(node, cycle);
break;
/* These should have already been converted to softer versions. */
case BITWISE_AND:
case BITWISE_NAND:
case BITWISE_NOR:
case BITWISE_XNOR:
case BITWISE_XOR:
case BITWISE_OR:
case BUF_NODE:
case MULTI_PORT_MUX:
case SL:
case SR:
case CASE_EQUAL:
case CASE_NOT_EQUAL:
case DIVIDE:
case MODULO:
case GTE:
case LTE:
//case ADD:
//case MINUS:
default:
error_message(SIMULATION_ERROR, 0, -1, "Node should have been converted to softer version: %s", node->name);
break;
}
// Record coverage on any output pins that have changed.
{
int i;
for (i = 0; i < node->num_output_pins; i++)
if(get_pin_value(node->output_pins[i],cycle-1) != get_pin_value(node->output_pins[i],cycle))
node->output_pins[i]->coverage++;
}
}
/*
* Updates all pins which have been flagged as undriven
* to -1 for the given cycle.
*
* Also checks that other pins have been updated
* by cycle 3 and throws an error if they haven't been.
*
* This function is called when each node is updated as a
* safeguard.
*/
void update_undriven_input_pins(nnode_t *node, int cycle)
{
int i;
for (i = 0; i < node->num_undriven_pins; i++)
{
npin_t *pin = node->undriven_pins[i];
update_pin_value(pin, -1, cycle);
}
// By the third cycle everything in the netlist should have been updated.
if (cycle == 3)
{
for (i = 0; i < node->num_input_pins; i++)
{
npin_t *pin = node->input_pins[i];
if (get_pin_cycle(pin) < cycle-1)
#ifdef _OPENMP
// Can't have multiple threads trying to error out at the same time.
#pragma omp critical
#endif
{
char *node_name = node->name;
char *pin_name = pin->name;
// Print the trace.
nnode_t *root = print_update_trace(node, cycle);
// Throw an error.
error_message(SIMULATION_ERROR,0,-1,"Odin has detected that an input pin attached to %s isn't being updated.\n"
"\tPin name: %s\n"
"\tRoot node: %s\n"
"\tSee the trace immediately above this message for details.\n",
node_name, pin_name, root?root->name:"N/A"
);
}
}
}
}
/*
* Flags any inputs pins which are undriven and have
* not already been flagged.
*/
void flag_undriven_input_pins(nnode_t *node)
{
int i;
for (i = 0; i < node->num_input_pins; i++)
{
npin_t *pin = node->input_pins[i];
if (!pin->net || !pin->net->driver_pin || !pin->net->driver_pin->node)
{
int already_flagged = FALSE;
int j;
for (j = 0; j < node->num_undriven_pins; j++)
{
if (node->undriven_pins[j] == pin)
already_flagged = TRUE;
}
if (!already_flagged)
{
node->undriven_pins = realloc(node->undriven_pins, sizeof(npin_t *) * (node->num_undriven_pins + 1));
node->undriven_pins[node->num_undriven_pins++] = pin;
warning_message(SIMULATION_ERROR,0,-1,"A node (%s) has an undriven input pin.", node->name);
}
}
}
}
/*
* Gets the number of nodes whose output pins have been sufficiently covered.
*/
int get_num_covered_nodes(stages *s)
{
int covered_nodes = 0;
int i;
for(i = 0; i < s->count; i++)
{
int j;
for (j = 0; j < s->counts[i]; j++)
{ /*
* To count as being covered, every pin should resolve, and
* make at least one transition from one binary value to another
* and back. (That's three transitions total.)
*/
nnode_t *node = s->stages[i][j];
int k;
int covered = TRUE;
for (k = 0; k < node->num_output_pins; k++)
{
if (node->output_pins[k]->coverage < 3)
{
covered = FALSE;
break;
}
}
if (covered)
covered_nodes++;
}
}
return covered_nodes;
}
/*
* Enqueues the node in the given queue if is_node_ready returns TRUE.
*/
int enqueue_node_if_ready(queue_t* queue, nnode_t* node, int cycle)
{
if (is_node_ready(node, cycle))
{
node->in_queue = TRUE;
queue->add(queue, node);
return TRUE;
}
else
{
return FALSE;
}
}
/*
* Determines if the given node has been simulated for the given cycle.
*/
int is_node_complete(nnode_t* node, int cycle)
{
int i;
for (i = 0; i < node->num_output_pins; i++)
if (node->output_pins[i] && (get_pin_cycle(node->output_pins[i]) < cycle))
return FALSE;
return TRUE;
}
/*
* Checks to see if the node is ready to be simulated for the given cycle.
*/
int is_node_ready(nnode_t* node, int cycle)
{
if (!cycle)
{
flag_undriven_input_pins(node);
update_undriven_input_pins(node, cycle);
}
if (node->type == FF_NODE)
{
npin_t *D_pin = node->input_pins[0];
npin_t *clock_pin = node->input_pins[1];
// Flip-flops depend on the D input from the previous cycle and the clock from this cycle.
if
(
(get_pin_cycle(D_pin ) < cycle-1)
|| (get_pin_cycle(clock_pin) < cycle )
)
return FALSE;
}
else if (node->type == MEMORY)
{
int i;
for (i = 0; i < node->num_input_pins; i++)
{
npin_t *pin = node->input_pins[i];
// The data and write enable inputs rely on the values from the previous cycle.
if (
!strcmp(pin->mapping, "data") || !strcmp(pin->mapping, "data1") || !strcmp(pin->mapping, "data2")
|| !strcmp(pin->mapping, "we") || !strcmp(pin->mapping, "we1") || !strcmp(pin->mapping, "we2")
)
{
if (get_pin_cycle(pin) < cycle-1)
return FALSE;
}
else
{
if (get_pin_cycle(pin) < cycle)
return FALSE;
}
}
}
else
{
int i;
for (i = 0; i < node->num_input_pins; i++)
if (get_pin_cycle(node->input_pins[i]) < cycle)
return FALSE;
}
return TRUE;
}
/*
* Gets the children of the given node. Returns the number of
* children via the num_children parameter. Throws warnings
* or errors if invalid connection patterns are detected.
*/
nnode_t **get_children_of(nnode_t *node, int *num_children)
{
nnode_t **children = 0;
int count = 0;
int i;
for (i = 0; i < node->num_output_pins; i++)
{
npin_t *pin = node->output_pins[i];
nnet_t *net = pin->net;
if (net)
{
/*
* Detects a net that may be being driven by two
* or more pins or has an incorrect driver pin assignment.
*/
if (net->driver_pin != pin && global_args.all_warnings)
{
char *pin_name = get_pin_name(pin->name);
char *node_name = get_pin_name(node->name);
char *net_name = get_pin_name(net->name);
warning_message(SIMULATION_ERROR, -1, -1,
"Found output pin \"%s\" (%ld) on node \"%s\" (%ld)\n"
" which is mapped to a net \"%s\" (%ld) whose driver pin is \"%s\" (%ld) \n",
pin_name,
pin->unique_id,
node_name,
node->unique_id,
net_name,
net->unique_id,
net->driver_pin->name,
net->driver_pin->unique_id
);
free(net_name);
free(pin_name);
free(node_name);
}
int j;
for (j = 0; j < net->num_fanout_pins; j++)
{
npin_t *fanout_pin = net->fanout_pins[j];
if (fanout_pin && fanout_pin->type == INPUT && fanout_pin->node)
{
nnode_t *child_node = fanout_pin->node;
// Check linkage for inconsistencies.
if (fanout_pin->net != net)
{
print_ancestry(child_node, 0);
error_message(SIMULATION_ERROR, -1, -1, "Found mismapped node %s", node->name);
}
else if (fanout_pin->net->driver_pin->net != net)
{
print_ancestry(child_node, 0);
error_message(SIMULATION_ERROR, -1, -1, "Found mismapped node %s", node->name);
}
else if (fanout_pin->net->driver_pin->node != node)
{
print_ancestry(child_node, 0);
error_message(SIMULATION_ERROR, -1, -1, "Found mismapped node %s", node->name);
}
else
{
// Add child.
children = realloc(children, sizeof(nnode_t*) * (count + 1));
children[count++] = child_node;
}
}
}
}
}
*num_children = count;
return children;
}
/*
* Gets the children of a specific output pin of the given node. Returns the number of
* children via the num_children parameter. Throws warnings
* or errors if invalid connection patterns are detected.
*/
nnode_t **get_children_of_nodepin(nnode_t *node, int *num_children, int output_pin)
{
nnode_t **children = 0;
int count = 0;
int output_pin_number = node->num_output_pins;
if(output_pin < 0 || output_pin > output_pin_number)
{
error_message(SIMULATION_ERROR, -1, -1, "Requested pin not available");
return children;
}
npin_t *pin = node->output_pins[output_pin];
nnet_t *net = pin->net;
if (net)
{
/*
* Detects a net that may be being driven by two
* or more pins or has an incorrect driver pin assignment.
*/
if (net->driver_pin != pin && global_args.all_warnings)
{
char *pin_name = get_pin_name(pin->name);
char *node_name = get_pin_name(node->name);
char *net_name = get_pin_name(net->name);
warning_message(SIMULATION_ERROR, -1, -1,
"Found output pin \"%s\" (%ld) on node \"%s\" (%ld)\n"
" which is mapped to a net \"%s\" (%ld) whose driver pin is \"%s\" (%ld) \n",
pin_name,
pin->unique_id,
node_name,
node->unique_id,
net_name,
net->unique_id,
net->driver_pin->name,
net->driver_pin->unique_id
);
free(net_name);
free(pin_name);
free(node_name);
}
int j;
for (j = 0; j < net->num_fanout_pins; j++)
{
npin_t *fanout_pin = net->fanout_pins[j];
if (fanout_pin && fanout_pin->type == INPUT && fanout_pin->node)
{
nnode_t *child_node = fanout_pin->node;
// Check linkage for inconsistencies.
if (fanout_pin->net != net)
{
print_ancestry(child_node, 0);
error_message(SIMULATION_ERROR, -1, -1, "Found mismapped node %s", node->name);
}
else if (fanout_pin->net->driver_pin->net != net)
{
print_ancestry(child_node, 0);
error_message(SIMULATION_ERROR, -1, -1, "Found mismapped node %s", node->name);
}
else if (fanout_pin->net->driver_pin->node != node)
{
print_ancestry(child_node, 0);
error_message(SIMULATION_ERROR, -1, -1, "Found mismapped node %s", node->name);
}
else
{
// Add child.
children = realloc(children, sizeof(nnode_t*) * (count + 1));
children[count++] = child_node;
}
}
}
}
*num_children = count;
return children;
}
/*
* Updates the value of a pin and its cycle. Pins should be updated using
* only this function.
*
* Initializes the pin if need be.
*/
void update_pin_value(npin_t *pin, signed char value, int cycle)
{
if (!pin->values)
initialize_pin(pin);
pin->values[get_values_offset(cycle)] = value;
set_pin_cycle(pin, cycle);
}
/*
* Gets the value of a pin. Pins should be checked using this function only.
*/
signed char get_pin_value(npin_t *pin, int cycle)
{
if (!pin->values || cycle < 0)
return -1;
return pin->values[get_values_offset(cycle)];
}
/*
* Calculates the index in the values array for the given cycle.
*/
inline int get_values_offset(int cycle)
{
return (((cycle) + (SIM_WAVE_LENGTH)) % (SIM_WAVE_LENGTH));
}
/*
* Gets the cycle of the given pin
*/
inline int get_pin_cycle(npin_t *pin)
{
if (!pin->cycle)
return -1;
else
return *(pin->cycle);
}
/*
* Sets the cycle of the given pin.
*
* Only called from update_pin_value.
*/
inline void set_pin_cycle(npin_t *pin, int cycle)
{
*(pin->cycle) = cycle;
}
/*
* Returns FALSE if the cycle is odd.
*/
int is_even_cycle(int cycle)
{
return !((cycle + 2) % 2);
}
/*
* Allocates memory for the pin's value and cycle.
*
* Checks to see if this pin's net has a different driver, and
* initialises that pin too.
*
* Fanout pins will share the same memory locations for cycle
* and values so that the values don't have to be propagated
* through the net.
*/
void initialize_pin(npin_t *pin)
{
// Initialise the driver pin if this pin is not the driver.
if (pin->net && pin->net->driver_pin && pin->net->driver_pin != pin)
initialize_pin(pin->net->driver_pin);
// If initialising the driver initialised this pin, we're OK to return.
if (pin->cycle || pin->values)
return;
if (pin->net)
{
pin->values = pin->net->values;
pin->cycle = &(pin->net->cycle);
int i;
for (i = 0; i < pin->net->num_fanout_pins; i++)
{
npin_t *fanout_pin = pin->net->fanout_pins[i];
if (fanout_pin)
{
fanout_pin->values = pin->net->values;
fanout_pin->cycle = &(pin->net->cycle);
}
}
}
else
{
pin->values = malloc(SIM_WAVE_LENGTH * sizeof(signed char));
pin->cycle = malloc(sizeof(int));
}
int i;
for (i = 0; i < SIM_WAVE_LENGTH; i++)
pin->values[i] = -1;
set_pin_cycle(pin, -1);
}
/*
* Returns FALSE if the node is not a clock.
*/
inline int is_clock_node(nnode_t *node)
{
return (
(node->type == CLOCK_NODE)
|| !strcmp(node->name,"top^clk") // Strictly for memories.
);
}
/*
* Returns TRUE if the pin's value for this
* cycle is 1 and the value for the previous cycle
* was not 1. Otherwise returns FALSE.
*/
int is_posedge(npin_t *pin, int cycle)
{
if (get_pin_value(pin,cycle) == 1 && get_pin_value(pin,cycle-1) != 1)
return TRUE;
else
return FALSE;
}
/*
* Computes a node of type FF_NODE for the given cycle.
*/
void compute_flipflop_node(nnode_t *node, int cycle)
{
oassert(node->num_output_pins == 1);
oassert(node->num_input_pins == 2);
npin_t *D_pin = node->input_pins[0];
npin_t *clock_pin = node->input_pins[1];
npin_t *output_pin = node->output_pins[0];
// Rising edge: update the flip-flop from the input value of the previous cycle.
if (is_posedge(clock_pin, cycle))
update_pin_value(output_pin, get_pin_value(D_pin, cycle-1), cycle);
// Falling edge: maintain the flip-flop value.
else
update_pin_value(output_pin, get_pin_value(output_pin,cycle-1), cycle);
}
/*
* Computes a node of type MUX_2 for the given cycle.
*/
void compute_mux_2_node(nnode_t *node, int cycle)
{
oassert(node->num_output_pins == 1);
oassert(node->num_input_port_sizes >= 2);
oassert(node->input_port_sizes[0] == node->input_port_sizes[1]);
ast_node_t *ast_node = node->related_ast_node;
// Figure out which pin is being selected.
char unknown = FALSE;
int select = -1;
int default_select = -1;
int i;
for (i = 0; i < node->input_port_sizes[0]; i++)
{
npin_t *pin = node->input_pins[i];
signed char value = get_pin_value(pin, cycle);
if (value < 0)
unknown = TRUE;
else if (value == 1 && select == -1) // Take the first selection only.
select = i;
/*
* If the pin comes from an "else" condition or a case "default" condition,
* we favour it in the case where there are unknowns.
*/
if (ast_node && pin->is_default && (ast_node->type == IF || ast_node->type == CASE))
default_select = i;
}
// If there are unknowns and there is a default clause, select it.
if (unknown && default_select >= 0)
{
unknown = FALSE;
select = default_select;
}
npin_t *output_pin = node->output_pins[0];
// If any select pin is unknown (and we don't have a default), we take the value from the previous cycle.
if (unknown)
{
/*
* Conform to ModelSim's behaviour where in-line ifs are concerned. If the
* condition is unknown, the inline if's output is unknown.
*/
if (ast_node && ast_node->type == IF_Q)
update_pin_value(output_pin, -1, cycle);
else
update_pin_value(output_pin, get_pin_value(output_pin, cycle-1), cycle);
}
// If no selection is made (all 0) we output x.
else if (select < 0)
{
update_pin_value(output_pin, -1, cycle);
}
else
{
npin_t *pin = node->input_pins[select + node->input_port_sizes[0]];
signed char value = get_pin_value(pin,cycle);
// Drive implied drivers to unknown value.
/*if (pin->is_implied && ast_node && (ast_node->type == CASE))
update_pin_value(output_pin, -1, cycle);
else*/
update_pin_value(output_pin, value, cycle);
}
}
// TODO: Needs to be verified.
void compute_hard_ip_node(nnode_t *node, int cycle)
{
oassert(node->input_port_sizes[0] > 0);
oassert(node->output_port_sizes[0] > 0);
int *input_pins = malloc(sizeof(int)*node->num_input_pins);
int *output_pins = malloc(sizeof(int)*node->num_output_pins);
if (!node->simulate_block_cycle)
{
char *filename = malloc(sizeof(char)*strlen(node->name));
if (!index(node->name, '.'))
error_message(SIMULATION_ERROR, 0, -1,
"Couldn't extract the name of a shared library for hard-block simulation");
snprintf(filename, sizeof(char)*strlen(node->name), "%s.so", index(node->name, '.')+1);
void *handle = dlopen(filename, RTLD_LAZY);
if (!handle)
error_message(SIMULATION_ERROR, 0, -1,
"Couldn't open a shared library for hard-block simulation: %s", dlerror());
dlerror();
void (*func_pointer)(int, int, int*, int, int*) =
(void(*)(int, int, int*, int, int*))dlsym(handle, "simulate_block_cycle");
char *error = dlerror();
if (error)
error_message(SIMULATION_ERROR, 0, -1,
"Couldn't load a shared library method for hard-block simulation: %s", error);
node->simulate_block_cycle = func_pointer;
free(filename);
}
int i;
for (i = 0; i < node->num_input_pins; i++)
input_pins[i] = get_pin_value(node->input_pins[i],cycle);
(node->simulate_block_cycle)
(cycle, node->num_input_pins, input_pins, node->num_output_pins, output_pins);
for (i = 0; i < node->num_output_pins; i++)
update_pin_value(node->output_pins[i], output_pins[i], cycle);
free(input_pins);
free(output_pins);
}
/*
* Computes the given multiply node for the given cycle.
*/
void compute_multiply_node(nnode_t *node, int cycle)
{
oassert(node->num_input_port_sizes == 2);
oassert(node->num_output_port_sizes == 1);
int i;
char unknown = FALSE;
for (i = 0; i < node->input_port_sizes[0] + node->input_port_sizes[1]; i++)
{
signed char pin = get_pin_value(node->input_pins[i],cycle);
if (pin < 0)
{
unknown = TRUE;
break;
}
}
if (unknown)
{
for (i = 0; i < node->num_output_pins; i++)
update_pin_value(node->output_pins[i], -1, cycle);
}
else
{
int *a = malloc(sizeof(int)*node->input_port_sizes[0]);
int *b = malloc(sizeof(int)*node->input_port_sizes[1]);
for (i = 0; i < node->input_port_sizes[0]; i++)
a[i] = get_pin_value(node->input_pins[i],cycle);
for (i = 0; i < node->input_port_sizes[1]; i++)
b[i] = get_pin_value(node->input_pins[node->input_port_sizes[0] + i],cycle);
int *result = multiply_arrays(a, node->input_port_sizes[0], b, node->input_port_sizes[1]);
for (i = 0; i < node->num_output_pins; i++)
update_pin_value(node->output_pins[i], result[i], cycle);
free(result);
free(a);
free(b);
}
}
// TODO: Needs to be verified.
void compute_generic_node(nnode_t *node, int cycle)
{
int line_count_bitmap = node->bit_map_line_count;
char **bit_map = node->bit_map;
int lut_size = 0;
while (bit_map[0][lut_size] != 0)
lut_size++;
int found = 0;
int i;
for (i = 0; i < line_count_bitmap && (!found); i++)
{
int j;
for (j = 0; j < lut_size; j++)
{
if (get_pin_value(node->input_pins[j],cycle) < 0)
{
update_pin_value(node->output_pins[0], -1, cycle);
return;
}
if ((bit_map[i][j] != '-') && (bit_map[i][j]-'0' != get_pin_value(node->input_pins[j],cycle)))
break;
}
if (j == lut_size) found = TRUE;
}
if (found) update_pin_value(node->output_pins[0], 1, cycle);
else update_pin_value(node->output_pins[0], 0, cycle);
}
/*
* Takes two arrays of integers (1's and 0's) and returns an array
* of integers (1's and 0's) that represent their product. The
* length of the returned array is twice that of the two parameters.
*
* This array will need to be freed later!
*/
int *multiply_arrays(int *a, int a_length, int *b, int b_length)
{
int result_size = a_length + b_length;
int *result = calloc(sizeof(int), result_size);
int i;
for (i = 0; i < a_length; i++)
{
if (a[i] == 1)
{
int j;
for (j = 0; j < b_length; j++)
result[i+j] += b[j];
}
}
for (i = 0; i < result_size; i++)
{
while (result[i] > 1)
{
result[i] -= 2;
result[i+1]++;
}
}
return result;
}
/*
* Computes the given add node for the given cycle.
* add by Sen
*/
void compute_add_node(nnode_t *node, int cycle, int type)
{
oassert(node->num_input_port_sizes == 3);
oassert(node->num_output_port_sizes == 2);
int i, num;
int flag = 0;
int *a = malloc(sizeof(int)*node->input_port_sizes[0]);
int *b = malloc(sizeof(int)*node->input_port_sizes[1]);
int *c = malloc(sizeof(int)*node->input_port_sizes[2]);
num = node->input_port_sizes[0]+ node->input_port_sizes[1];
//if cin connect to unconn(PAD_NODE), a[0] connect to ground(GND_NODE) and b[0] connect to ground, flag = 0 the initial adder for addition
//if cin connect to unconn(PAD_NODE), a[0] connect to ground(GND_NODE) and b[0] connect to vcc, flag = 1 the initial adder for subtraction
if(node->input_pins[num]->net->driver_pin->node->type == PAD_NODE)
{
if(node->input_pins[0]->net->driver_pin->node->type == GND_NODE && node->input_pins[node->input_port_sizes[0]]->net->driver_pin->node->type == GND_NODE)
flag = 0;
else if(node->input_pins[0]->net->driver_pin->node->type == GND_NODE && node->input_pins[node->input_port_sizes[0]]->net->driver_pin->node->type == VCC_NODE)
flag = 1;
}
else
flag = 2;
for (i = 0; i < node->input_port_sizes[0]; i++)
a[i] = get_pin_value(node->input_pins[i],cycle);
for (i = 0; i < node->input_port_sizes[1]; i++)
b[i] = get_pin_value(node->input_pins[node->input_port_sizes[0] + i],cycle);
for (i = 0; i < node->input_port_sizes[2]; i++)
//the initial cin of carry chain subtractor should be 1
if(flag == 1)
c[i] = 1;
//the initial cin of carry chain adder should be 0
else if(flag == 0)
c[i] = 0;
else
c[i] = get_pin_value(node->input_pins[node->input_port_sizes[0]+ node->input_port_sizes[1] + i],cycle);
int *result = add_arrays(a, node->input_port_sizes[0], b, node->input_port_sizes[1], c, node->input_port_sizes[2],type);
//update the pin value of output
for (i = 1; i < node->num_output_pins; i++)
update_pin_value(node->output_pins[i], result[(i - 1)], cycle);
update_pin_value(node->output_pins[0], result[(node->num_output_pins - 1)], cycle);
free(result);
free(a);
free(b);
free(c);
}
/*
* Takes two arrays of integers (1's and 0's) and returns an array
* of integers (1's and 0's) that represent their sum. The
* length of the returned array is the maximum of the two parameters plus one.
* add by Sen
* This array will need to be freed later!
*/
int *add_arrays(int *a, int a_length, int *b, int b_length, int *c, int c_length, int flag)
{
int result_size = max(a_length , b_length) + 1;
int *result = calloc(sizeof(int), result_size);
int i;
int temp_carry_in;
//least significant bit would use the input carryIn, the other bits would use the compute value
//if one of the number is unknown, then the answer should be unknown(same as ModelSim)
if(a[0] == -1 || b[0] == -1 || c[0] == -1)
{
result[0] = -1;
result[1] = -1;
}
else
{
result[0] = a[0] ^ b[0] ^ c[0];
result[1] = (a[0] & b[0]) | (c[0] & b[0]) | (a[0] & c[0]);
}
temp_carry_in = result[1];
if(result_size > 2){
for(i = 1; i < min(a_length,b_length); i++)
{
if(a[i] == -1 || b[i] == -1 || temp_carry_in == -1)
{
result[i] = -1;
result[i+1] = -1;
}
else
{
result[i] = a[i] ^ b[i] ^ temp_carry_in;
result[i+1] = (a[i] & b[i]) | (a[i] & temp_carry_in) | (temp_carry_in & b[i]);
}
temp_carry_in = result[i+1];
}
if(a_length >= b_length)
{
for(i = b_length; i < a_length; i++)
{
if(a[i] == -1 || temp_carry_in == -1)
{
result[i] = -1;
result[i+1] = -1;
}
else
{
result[i] = a[i] ^ temp_carry_in;
result[i+1] = a[i] & temp_carry_in;
}
temp_carry_in = result[i+1];
}
}
else
{
for(i = a_length; i < b_length; i++)
{
if(b[i] == -1 || temp_carry_in == -1)
{
result[i] = -1;
result[i+1] = -1;
}else
{
result[i] = b[i] ^ temp_carry_in;
result[i+1] = b[i] & temp_carry_in;
}
temp_carry_in = result[i+1];
}
}
}
return result;
}
/*
* Computes the given add node for the given cycle.
* add by Sen
*/
void compute_unary_sub_node(nnode_t *node, int cycle)
{
oassert(node->num_input_port_sizes == 2);
oassert(node->num_output_port_sizes == 2);
int i;
char unknown = FALSE;
for (i = 0; i < (node->input_port_sizes[0] + node->input_port_sizes[1]); i++)
{
signed char pin = get_pin_value(node->input_pins[i],cycle);
if (pin < 0)
{
unknown = TRUE;
break;
}
}
if (unknown)
{
for (i = 0; i < (node->output_port_sizes[0] + node->output_port_sizes[1]); i++)
update_pin_value(node->output_pins[i], -1, cycle);
}
else
{
int *a = malloc(sizeof(int)*node->input_port_sizes[0]);
int *c = malloc(sizeof(int)*node->input_port_sizes[1]);
for (i = 0; i < node->input_port_sizes[0]; i++)
a[i] = get_pin_value(node->input_pins[i],cycle);
for (i = 0; i < node->input_port_sizes[1]; i++)
if((node->input_pins[node->input_port_sizes[0]+ node->input_port_sizes[1] + i]->net->driver_pin->node->type == PAD_NODE))
c[i] = 1;
else
c[i] = get_pin_value(node->input_pins[node->input_port_sizes[0] + i],cycle);
int *result = unary_sub_arrays(a, node->input_port_sizes[0], c, node->input_port_sizes[1]);
for (i = 1; i < node->num_output_pins; i++)
update_pin_value(node->output_pins[i], result[(i - 1)], cycle);
update_pin_value(node->output_pins[0], result[(node->num_output_pins - 1)], cycle);
free(result);
free(a);
free(c);
}
}
/*
* Takes two arrays of integers (1's and 0's) and returns an array
* of integers (1's and 0's) that represent their sum. The
* length of the returned array is the maximum of the two parameters plus one.
* add by Sen
* This array will need to be freed later!
*/
int *unary_sub_arrays(int *a, int a_length, int *c, int c_length)
{
int result_size = a_length + 1;
int *result = calloc(sizeof(int), result_size);
int i;
int temp_carry_in;
c[0] = 1;
result[0] = (!a[0]) ^ c[0] ^ 0;
result[1] = ((!a[0]) & 0) | (c[0] & 0) | ((!a[0]) & c[0]);
temp_carry_in = result[1];
if(result_size > 2){
for(i = 1; i < a_length; i++)
{
result[i] = (!a[i]) ^ 0 ^ temp_carry_in;
result[i+1] = ((!a[i]) & 0) | ((!a[i]) & temp_carry_in) | (temp_carry_in & 0);
temp_carry_in = result[i+1];
}
}
return result;
}
/*
* Computes the given memory node.
*/
void compute_memory_node(nnode_t *node, int cycle)
{
if (is_sp_ram(node))
compute_single_port_memory(node, cycle);
else if (is_dp_ram(node))
compute_dual_port_memory(node, cycle);
else
error_message(SIMULATION_ERROR, 0, -1,
"Could not resolve memory hard block %s to a valid type.", node->name);
}
/*
* Computes single port memory.
*/
void compute_single_port_memory(nnode_t *node, int cycle)
{
sp_ram_signals *signals = get_sp_ram_signals(node);
int posedge = is_posedge(signals->clk, cycle);
if (!node->memory_data)
instantiate_memory(node, signals->data->count, signals->addr->count);
// On the rising edge, write the memory.
if (posedge)
{
int we = get_pin_value(signals->we, cycle - 1);
long address = compute_memory_address(signals->addr, cycle - 1);
char address_ok = (address != -1)?1:0;
int i;
for (i = 0; i < signals->data->count; i++)
{
// Compute which bit we are addressing.
long bit_address = address_ok?(i + (address * signals->data->count)):-1;
// If write is enabled, copy the input to memory.
if (address_ok && we)
node->memory_data[bit_address] = get_pin_value(signals->data->pins[i],cycle-1);
}
}
// Read data from the memory.
{
long address = compute_memory_address(signals->addr, cycle);
char address_ok = (address != -1)?1:0;
int i;
for (i = 0; i < signals->data->count; i++)
{
// Compute which bit we are addressing.
long bit_address = address_ok?(i + (address * signals->data->count)):-1;
// Update the output.
if (address_ok)
update_pin_value(signals->out->pins[i], node->memory_data[bit_address], cycle);
else
update_pin_value(signals->out->pins[i], -1, cycle);
}
}
free_sp_ram_signals(signals);
}
/*
* Computes dual port memory.
*/
void compute_dual_port_memory(nnode_t *node, int cycle)
{
dp_ram_signals *signals = get_dp_ram_signals(node);
int posedge = is_posedge(signals->clk, cycle);
if (!node->memory_data)
instantiate_memory(node, signals->data2->count, signals->addr2->count);
// On the rising edge, we write the memory.
if (posedge)
{
int we1 = get_pin_value(signals->we1, cycle - 1);
int we2 = get_pin_value(signals->we2, cycle - 1);
long address1 = compute_memory_address(signals->addr1, cycle - 1);
long address2 = compute_memory_address(signals->addr2, cycle - 1);
char address1_ok = (address1 != -1)?1:0;
char address2_ok = (address2 != -1)?1:0;
int i;
for (i = 0; i < signals->data1->count; i++)
{
// Compute which bit we are addressing.
long bit_address1 = address1_ok?(i + (address1 * signals->data1->count)):-1;
long bit_address2 = address2_ok?(i + (address2 * signals->data2->count)):-1;
// Write to the memory
if (address1_ok && we1)
node->memory_data[bit_address1] = get_pin_value(signals->data1->pins[i], cycle-1);
if (address2_ok && we2)
node->memory_data[bit_address2] = get_pin_value(signals->data2->pins[i], cycle-1);
}
}
// Read data from memory.
{
long address1 = compute_memory_address(signals->addr1, cycle);
long address2 = compute_memory_address(signals->addr2, cycle);
char address1_ok = (address1 != -1)?1:0;
char address2_ok = (address2 != -1)?1:0;
int i;
for (i = 0; i < signals->data1->count; i++)
{
// Compute which bit we are addressing.
long bit_address1 = address1_ok?(i + (address1 * signals->data1->count)):-1;
long bit_address2 = address2_ok?(i + (address2 * signals->data2->count)):-1;
// Read the memory bit
if (address1_ok)
update_pin_value(signals->out1->pins[i], node->memory_data[bit_address1], cycle);
else
update_pin_value(signals->out1->pins[i], -1, cycle);
if (address2_ok)
update_pin_value(signals->out2->pins[i], node->memory_data[bit_address2], cycle);
else
update_pin_value(signals->out2->pins[i], -1, cycle);
}
}
free_dp_ram_signals(signals);
}
/*
* Calculates the memory address. Returns -1 if the address is unknown.
*/
long compute_memory_address(signal_list_t *addr, int cycle)
{
long address = 0;
int i;
for (i = 0; i < addr->count; i++)
{
// If any address pins are x's, write x's we return -1.
if (get_pin_value(addr->pins[i],cycle) < 0)
return -1;
address += get_pin_value(addr->pins[i],cycle) << (i);
}
return address;
}
/*
* Initialises memory using a memory information file (mif). If not
* file is found, it is initialised to x's.
*/
void instantiate_memory(nnode_t *node, int data_width, int addr_width)
{
long max_address = 1 << addr_width;
node->memory_data = malloc(sizeof(signed char) * max_address * data_width);
// Initialise the memory to -1.
int i;
for (i = 0; i < max_address * data_width; i++)
node->memory_data[i] = -1;
char *filename = get_mif_filename(node);
FILE *mif = fopen(filename, "r");
if (!mif)
{
printf("MIF %s (%dx%d) not found. \n", filename, data_width, addr_width);
}
else
{
assign_memory_from_mif_file(mif, filename, data_width, addr_width, node->memory_data);
fclose(mif);
}
free(filename);
}
/*
* Removes white space (except new lines) and comments from
* the given mif file and returns the resulting temporary file.
*/
FILE *preprocess_mif_file(FILE *source)
{
FILE *destination = tmpfile();
destination = freopen(NULL, "r+", destination);
rewind(source);
char line[BUFFER_MAX_SIZE];
int in_multiline_comment = FALSE;
while (fgets(line, BUFFER_MAX_SIZE, source))
{
int i;
for (i = 0; i < strlen(line); i++)
{
if (!in_multiline_comment)
{
// For a single line comment, skip the rest of the line.
if (line[i] == '-' && line[i+1] == '-')
break;
// Start of a multiline comment
else if (line[i] == '%')
in_multiline_comment = TRUE;
// Don't copy any white space over.
else if (line[i] != '\n' && line[i] != ' ' && line[i] != '\r' && line[i] != '\t' )
fputc(line[i], destination);
}
else
{
// If we're in a multi-line comment, search for the %
if (line[i] == '%')
in_multiline_comment = FALSE;
}
}
fputc('\n', destination);
}
rewind(destination);
return destination;
}
int parse_mif_radix(char *radix)
{
if (radix)
{
if (!strcmp(radix, "HEX"))
return 16;
else if (!strcmp(radix, "DEC"))
return 10;
else if (!strcmp(radix, "OCT"))
return 8;
else if (!strcmp(radix, "BIN"))
return 2;
else
return 0;
}
else
{
return 0;
}
}
void assign_memory_from_mif_file(FILE *mif, char *filename, int width, long depth, signed char *memory)
{
FILE *file = preprocess_mif_file(mif);
rewind(file);
hashtable_t *symbols = create_hashtable(100000);
char buffer[BUFFER_MAX_SIZE];
int in_content = FALSE;
char *last_line = NULL;
int line_number = 0;
int addr_radix = 0;
int data_radix = 0;
while (fgets(buffer, BUFFER_MAX_SIZE, file))
{
line_number++;
// Remove the newline.
trim_string(buffer, "\n");
// Only process lines which are not empty.
if (strlen(buffer))
{
char *line = strdup(buffer);
// MIF files are case insensitive
string_to_upper(line);
// The content section of the file contains address:value; assignments.
if (in_content)
{
// Parse at the :
char *token = strtok(line, ":");
if (strlen(token))
{
// END; signifies the end of the file.
if(!strcmp(buffer, "END;"))
break;
// The part before the : is the address.
char *address_string = token;
token = strtok(NULL, ";");
// The reset (before the ;) is the data_value.
char *data_string = token;
if (token)
{
// Make sure the address and value are valid strings of the specified radix.
if (!is_string_of_radix(address_string, addr_radix))
error_message(SIMULATION_ERROR, line_number, -1, "%s: address %s is not a base %d string.", filename, address_string, addr_radix);
if (!is_string_of_radix(data_string, data_radix))
error_message(SIMULATION_ERROR, line_number, -1, "%s: data string %s is not a base %d string.", filename, data_string, data_radix);
char *binary_data = convert_string_of_radix_to_bit_string(data_string, data_radix, width);
long long address = convert_string_of_radix_to_long_long(address_string, addr_radix);
if (address >= depth)
error_message(SIMULATION_ERROR, line_number, -1, "%s: address %s is out of range.", filename, address_string);
// Calculate the offset of this memory location in bits.
long long offset = address * width;
// Write the parsed value string to the memory location.
long long i;
for (i = offset; i < offset + width; i++)
memory[i] = binary_data[i - offset] - '0';
}
else
{
error_message(SIMULATION_ERROR, line_number, -1,
"%s: MIF syntax error.", filename);
}
}
}
// The header section of the file contains parameters given as PARAMETER=value;
else
{
// Grab the bit before the = sign.
char *token = strtok(line, "=");
if (strlen(token))
{
char *symbol = token;
token = strtok(NULL, ";");
// If is something after the equals sign and before the semicolon, add the symbol=value association to the symbol table.
if (token)
symbols->add(symbols, symbol, sizeof(char) * strlen(symbol), strdup(token));
else if(!strcmp(buffer, "CONTENT")) {}
// We found "CONTENT" followed on the next line by "BEGIN". That means we're at the end of the parameters.
else if(!strcmp(buffer, "BEGIN") && !strcmp(last_line, "CONTENT"))
{
// Sanity check parameters to make sure we have what we need.
// Verify the width parameter.
char *width_string = symbols->get(symbols, "WIDTH", sizeof(char) * 5);
int mif_width = atoi(width_string);
if (!width_string) error_message(SIMULATION_ERROR, -1, -1, "%s: MIF WIDTH parameter unspecified.", filename);
if (mif_width != width)
error_message(SIMULATION_ERROR, -1, -1,
"%s: MIF width mismatch: must be %d but %d was given", filename, width, mif_width);
// Verify the depth parameter.
char *depth_string = symbols->get(symbols, "DEPTH", sizeof(char) * 5);
int mif_depth = atoi(depth_string);
if (!depth_string) error_message(SIMULATION_ERROR, -1, -1, "%s: MIF DEPTH parameter unspecified.", filename);
if (mif_depth != depth)
error_message(SIMULATION_ERROR, -1, -1,
"%s: MIF depth mismatch: must be %d but %d was given", filename, depth, mif_depth);
// Parse the radix specifications and make sure they're OK.
addr_radix = parse_mif_radix(symbols->get(symbols, "ADDRESS_RADIX", sizeof(char) * 13));
data_radix = parse_mif_radix(symbols->get(symbols, "DATA_RADIX", sizeof(char) * 10));
if (!addr_radix)
error_message(SIMULATION_ERROR, -1, -1,
"%s: invalid or missing ADDRESS_RADIX: must specify DEC, HEX, OCT, or BIN", filename);
if (!data_radix)
error_message(SIMULATION_ERROR, -1, -1,
"%s: invalid or missing DATA_RADIX: must specify DEC, HEX, OCT, or BIN", filename);
// If everything checks out, start reading the values.
in_content = TRUE;
}
else
{
error_message(SIMULATION_ERROR, line_number, -1, "%s: MIF syntax error: %s", filename, line);
}
}
else
{
error_message(SIMULATION_ERROR, line_number, -1, "%s: MIF syntax error: %s", filename, line);
}
free(line);
}
if (last_line)
free(last_line);
last_line = strdup(buffer);
}
}
if (last_line)
free(last_line);
symbols->destroy_free_items(symbols);
fclose(file);
}
/*
* Assigns the given node to its corresponding line in the given array of line.
* Assumes the line has already been created.
*/
void assign_node_to_line(nnode_t *node, lines_t *l, int type, int single_pin)
{
// Make sure the node has an output pin.
if (!node->num_output_pins)
{
npin_t *pin = allocate_npin();
allocate_more_output_pins(node, 1);
add_output_pin_to_node(node, pin, 0);
}
// Parse the node name into a pin number and a port name.
int pin_number = get_pin_number(node->name);
char *port_name;
if (pin_number != -1 && !single_pin) {
port_name = get_port_name(node->name);
}
else {
port_name = get_pin_name(node->name);
single_pin = TRUE;
}
// Search the lines for the port name.
int j = find_portname_in_lines(port_name, l);
free(port_name);
if (single_pin)
{
if (j == -1)
{
warning_message(SIMULATION_ERROR, 0, -1,
"Could not map single-bit node '%s' line", node->name);
}
else
{
pin_number = (pin_number == -1)?0:pin_number;
int already_added = l->lines[j]->number_of_pins >= 1;
if (!already_added)
insert_pin_into_line(node->output_pins[0], pin_number, l->lines[j], type);
}
}
else
{
if (j == -1)
warning_message(SIMULATION_ERROR, 0, -1,
"Could not map multi-bit node '%s' to line", node->name);
else
insert_pin_into_line(node->output_pins[0], pin_number, l->lines[j], type);
}
}
/*
* Inserts the given pin according to its pin number into the given line.
*/
void insert_pin_into_line(npin_t *pin, int pin_number, line_t *line, int type)
{
// Allocate memory for the new pin.
line->pins = realloc(line->pins, sizeof(npin_t*) * (line->number_of_pins + 1));
line->pin_numbers = realloc(line->pin_numbers, sizeof(npin_t*) * (line->number_of_pins + 1));
// Find the proper place to insert this pin, and make room for it.
int i;
for (i = 0; i < line->number_of_pins; i++)
{
if (line->pin_numbers[i] > pin_number)
{
// Move other pins to the right to make room.
int j;
for (j = line->number_of_pins; j > i; j--)
{
line->pins[j] = line->pins[j-1];
line->pin_numbers[j] = line->pin_numbers[j-1];
}
break;
}
}
// Add the new pin.
line->pins[i] = pin;
line->pin_numbers[i] = pin_number;
line->type = type;
line->number_of_pins++;
}
/*
* Given a netlist, this function maps the top_input_nodes
* or top_output_nodes depending on the value of type
* (INPUT or OUTPUT) to a line_t each. It stores them in a
* lines_t struct and returns a pointer to it.
*/
lines_t *create_lines(netlist_t *netlist, int type)
{
lines_t *l = malloc(sizeof(lines_t));
l->lines = 0;
l->count = 0;
int num_nodes = (type == INPUT)?netlist->num_top_input_nodes:netlist->num_top_output_nodes;
nnode_t **nodes = (type == INPUT)?netlist->top_input_nodes :netlist->top_output_nodes;
int i;
for (i = 0; i < num_nodes; i++)
{
nnode_t *node = nodes[i];
char *port_name = get_port_name(node->name);
if (type == OUTPUT || !is_clock_node(node))
{
if (find_portname_in_lines(port_name, l) == -1)
{
line_t *line = create_line(port_name);
l->lines = realloc(l->lines, sizeof(line_t *)*(l->count + 1));
l->lines[l->count++] = line;
}
assign_node_to_line(node, l, type, 0);
}
free(port_name);
}
return l;
}
/*
* Creates a vector file header from the given lines,
* and writes it to the given file.
*/
void write_vector_headers(FILE *file, lines_t *l)
{
char* headers = generate_vector_header(l);
fprintf(file, "%s", headers);
free(headers);
fflush(file);
}
/*
* Parses the first line of the given file and compares it to the
* given lines for identity. If there is any difference, a warning is printed,
* and FALSE is returned. If there are no differences, the file pointer is left
* at the start of the second line, and TRUE is returned.
*/
int verify_test_vector_headers(FILE *in, lines_t *l)
{
int current_line = 0;
int buffer_length = 0;
// Read the header from the vector file.
char read_buffer [BUFFER_MAX_SIZE];
rewind(in);
if (!get_next_vector(in, read_buffer))
error_message(SIMULATION_ERROR, 0, -1, "Failed to read vector headers.");
// Parse the header, checking each entity against the corresponding line.
char buffer [BUFFER_MAX_SIZE];
buffer[0] = '\0';
int i;
for (i = 0; i < strlen(read_buffer) && i < BUFFER_MAX_SIZE; i++)
{
char next = read_buffer[i];
if (next == EOF)
{
warning_message(SIMULATION_ERROR, 0, -1, "Hit end of file.");
return FALSE;
}
else if (next == ' ' || next == '\t' || next == '\n')
{
if (buffer_length)
{
if(strcmp(l->lines[current_line]->name,buffer))
{
char *expected_header = generate_vector_header(l);
warning_message(SIMULATION_ERROR, 0, -1,
"Vector header mismatch: \n "
" Found: %s "
" Expected: %s", read_buffer, expected_header);
free(expected_header);
return FALSE;
}
else
{
buffer_length = 0;
current_line++;
}
}
if (next == '\n')
break;
}
else
{
buffer[buffer_length++] = next;
buffer[buffer_length] = '\0';
}
}
return TRUE;
}
/*
* Verifies that no lines have null pins.
*/
int verify_lines (lines_t *l)
{
int i;
for (i = 0; i < l->count; i++)
{
int j;
for (j = 0; j < l->lines[i]->number_of_pins; j++)
{
if (!l->lines[i]->pins[j])
{
warning_message(SIMULATION_ERROR, 0, -1, "A line %d:(%s) has a NULL pin. ", j, l->lines[i]->name);
return FALSE;
}
}
}
return TRUE;
}
/*
* Searches for a line with the given name in the lines. Returns the index
* or -1 if no such line was found.
*/
int find_portname_in_lines(char* port_name, lines_t *l)
{
int j;
for (j = 0; j < l->count; j++)
if (!strcmp(l->lines[j]->name, port_name))
return j;
return -1;
}
/*
* allocates memory for and initialises a line_t struct
*/
line_t *create_line(char *name)
{
line_t *line = malloc(sizeof(line_t));
line->number_of_pins = 0;
line->pins = 0;
line->pin_numbers = 0;
line->type = -1;
line->name = malloc(sizeof(char)*(strlen(name)+1));
strcpy(line->name, name);
return line;
}
/*
* Generates the appropriate vector headers based on the given lines.
*/
char *generate_vector_header(lines_t *l)
{
char *header = calloc(BUFFER_MAX_SIZE, sizeof(char));
if (l->count)
{
int j;
for (j = 0; j < l->count; j++)
{
// "+ 2" for null and newline/space.
if ((strlen(header) + strlen(l->lines[j]->name) + 2) > BUFFER_MAX_SIZE)
error_message(SIMULATION_ERROR, 0, -1, "Buffer overflow anticipated while generating vector header.");
strcat(header,l->lines[j]->name);
strcat(header," ");
}
header[strlen(header)-1] = '\n';
}
else
{
header[0] = '\n';
}
header = realloc(header, sizeof(char)*(strlen(header)+1));
return header;
}
/*
* Stores the given test vector in the given lines, with some sanity checking to ensure that it
* has a compatible geometry.
*/
void add_test_vector_to_lines(test_vector *v, lines_t *l, int cycle)
{
if (l->count < v->count)
error_message(SIMULATION_ERROR, 0, -1, "Fewer lines (%d) than values (%d).", l->count, v->count);
if (l->count > v->count)
error_message(SIMULATION_ERROR, 0, -1, "More lines (%d) than values (%d).", l->count, v->count);
int i;
for (i = 0; i < v->count; i++)
{
line_t *line = l->lines[i];
if (line->number_of_pins < 1)
error_message(SIMULATION_ERROR, 0, -1, "Found a line '%s' with no pins.", line->name);
int j;
for (j = 0; j < line->number_of_pins; j++)
{
if (j < v->counts[i]) update_pin_value(line->pins[j], v->values[i][j], cycle);
else update_pin_value(line->pins[j], 0, cycle);
}
}
}
/*
* Compares two test vectors for numerical and geometric identity. Returns FALSE if
* they are found to be different, and TRUE otherwise.
*/
int compare_test_vectors(test_vector *v1, test_vector *v2)
{
if (v1->count != v2->count)
{
warning_message(SIMULATION_ERROR, 0, -1, "Vector lengths differ.");
return FALSE;
}
int l;
for (l = 0; l < v1->count; l++)
{ // Compare bit by bit.
int i;
for (i = 0; i < v1->counts[l] && i < v2->counts[l]; i++)
if (v1->values[l][i] != v2->values[l][i])
return FALSE;
/*
* If one value has more bits than the other, they are still
* equivalent as long as the higher order bits of the longer
* one are zero.
*/
if (v1->counts[l] != v2->counts[l])
{
test_vector *v = v1->counts[l] < v2->counts[l] ? v2 : v1;
int j;
for (j = i; j < v->counts[l]; j++)
if (v->values[l][j] != 0)
return FALSE;
}
}
return TRUE;
}
/*
* Parses the given line from a test vector file into a
* test_vector data structure.
*/
test_vector *parse_test_vector(char *buffer)
{
buffer = strdup(buffer);
test_vector *v = malloc(sizeof(test_vector));
v->values = 0;
v->counts = 0;
v->count = 0;
trim_string(buffer,"\r\n");
const char *delim = " \t";
char *token = strtok(buffer, delim);
while (token)
{
v->values = realloc(v->values, sizeof(signed char *) * (v->count + 1));
v->counts = realloc(v->counts, sizeof(int) * (v->count + 1));
v->values[v->count] = 0;
v->counts[v->count] = 0;
if (token[0] == '0' && (token[1] == 'x' || token[1] == 'X'))
{ // Value is hex.
token += 2;
int token_length = strlen(token);
reverse_string(token, token_length);
int i;
for (i = 0; i < token_length; i++)
{
char temp[] = {token[i],'\0'};
int value = strtol(temp, NULL, 16);
int k;
for (k = 0; k < 4; k++)
{
signed char bit = 0;
if (value > 0)
{
bit = value % 2;
value /= 2;
}
v->values[v->count] = realloc(v->values[v->count], sizeof(signed char) * (v->counts[v->count] + 1));
v->values[v->count][v->counts[v->count]++] = bit;
}
}
}
else
{ // Value is binary.
int i;
for (i = strlen(token) - 1; i >= 0; i--)
{
signed char value = -1;
if (token[i] == '0') value = 0;
else if (token[i] == '1') value = 1;
v->values[v->count] = realloc(v->values[v->count], sizeof(signed char) * (v->counts[v->count] + 1));
v->values[v->count][v->counts[v->count]++] = value;
}
}
v->count++;
token = strtok(NULL, delim);
}
free(buffer);
return v;
}
/*
* Generates a "random" test_vector structure based on the geometry of the given lines.
*
* If you want better randomness, call srand at some point.
*/
test_vector *generate_random_test_vector(lines_t *l, int cycle, hashtable_t *hold_high_index, hashtable_t *hold_low_index)
{
test_vector *v = malloc(sizeof(test_vector));
v->values = 0;
v->counts = 0;
v->count = 0;
int i;
for (i = 0; i < l->count; i++)
{
v->values = realloc(v->values, sizeof(signed char *) * (v->count + 1));
v->counts = realloc(v->counts, sizeof(int) * (v->count + 1));
v->values[v->count] = 0;
v->counts[v->count] = 0;
int j;
for (j = 0; j < l->lines[i]->number_of_pins; j++)
{
char *name = l->lines[i]->name;
signed char value;
if (hold_high_index->count && hold_high_index->get(hold_high_index,name,sizeof(char)*strlen(name)))
{
if (!cycle) value = 0;
else value = 1;
}
else if (hold_low_index->count && hold_low_index->get(hold_low_index,name,sizeof(char)*strlen(name)))
{
if (!cycle) value = 1;
else value = 0;
}
else
{
// Passed via the -3 option.
if (global_args.sim_generate_three_valued_logic)
value = (rand() % 3) - 1;
else
value = (rand() % 2);
}
v->values[v->count] = realloc(v->values[v->count], sizeof(signed char) * (v->counts[v->count] + 1));
v->values[v->count][v->counts[v->count]++] = value;
}
v->count++;
}
return v;
}
/*
* Writes a wave of vectors to the given file. Writes the headers
* prior to cycle 0.
*
* When edge is -1, both edges of the clock are written. When edge is 0,
* the falling edge is written. When edge is 1, the rising edge is written.
*/
void write_wave_to_file(lines_t *l, FILE* file, int cycle_offset, int wave_length, int edge)
{
if (!cycle_offset)
write_vector_headers(file, l);
int cycle;
for (cycle = cycle_offset; cycle < (cycle_offset + wave_length); cycle++)
{
if (edge == -1 || (edge == 0 && is_even_cycle(cycle)) || (edge == 1 && !is_even_cycle(cycle)))
write_vector_to_file(l, file, cycle);
}
}
/*
* Writes all values in the given lines to a line in the given file
* for the given cycle.
*/
void write_vector_to_file(lines_t *l, FILE *file, int cycle)
{
char buffer[BUFFER_MAX_SIZE];
int i;
for (i = 0; i < l->count; i++)
{
line_t *line = l->lines[i];
int num_pins = line->number_of_pins;
if (line_has_unknown_pin(line, cycle) || num_pins == 1)
{
if ((num_pins + 1) > BUFFER_MAX_SIZE)
error_message(SIMULATION_ERROR, 0, -1, "Buffer overflow anticipated while writing vector for line %s.", line->name);
buffer[0] = 0;
int j;
int known_values = 0;
for (j = num_pins - 1; j >= 0 ; j--)
{
signed char value = get_line_pin_value(line, j, cycle);
if (value > 1)
error_message(SIMULATION_ERROR, 0, -1, "Invalid logic value of %d read from line %s.", value, line->name);
if (value < 0)
{
strcat(buffer, "x");
}
else
{ known_values++;
sprintf(buffer, "%s%d", buffer, value);
}
}
// If there are no known values, print a single capital X.
// (Only for testing. Breaks machine readability.)
//if (!known_values && num_pins > 1)
// sprintf(buffer, "X");
}
else
{
// +1 for ceiling, +1 for null, +2 for "OX"
if ((num_pins/4 + 1 + 1 + 2) > BUFFER_MAX_SIZE)
error_message(SIMULATION_ERROR, 0, -1, "Buffer overflow anticipated while writing vector for line %s.", line->name);
sprintf(buffer, "0X");
int hex_digit = 0;
int j;
for (j = num_pins - 1; j >= 0; j--)
{
signed char value = get_line_pin_value(line,j,cycle);
if (value > 1)
error_message(SIMULATION_ERROR, 0, -1, "Invalid logic value of %d read from line %s.", value, line->name);
hex_digit += value << j % 4;
if (!(j % 4))
{
sprintf(buffer, "%s%X", buffer, hex_digit);
hex_digit = 0;
}
}
}
// Expand the value to fill to space under the header. (Gets ugly sometimes.)
//while (strlen(buffer) < strlen(l->lines[i]->name))
// strcat(buffer," ");
fprintf(file,"%s ",buffer);
}
fprintf(file, "\n");
}
/*
* Writes a wave of vectors to the given modelsim out file.
*/
void write_wave_to_modelsim_file(netlist_t *netlist, lines_t *l, FILE* modelsim_out, int cycle_offset, int wave_length)
{
if (!cycle_offset)
{
fprintf(modelsim_out, "add wave *\n");
// Add clocks to the output file.
int i;
for (i = 0; i < netlist->num_top_input_nodes; i++)
{
nnode_t *node = netlist->top_input_nodes[i];
if (is_clock_node(node))
{
char *port_name = get_port_name(node->name);
fprintf(modelsim_out, "force %s 0 0, 1 50 -repeat 100\n", port_name);
free(port_name);
}
}
}
int cycle;
for (cycle = cycle_offset; cycle < (cycle_offset + wave_length); cycle ++)
{
if (!is_even_cycle(cycle))
write_vector_to_modelsim_file(l, modelsim_out, cycle);
}
}
/*
* Writes a vector to the given modelsim out file.
*/
void write_vector_to_modelsim_file(lines_t *l, FILE *modelsim_out, int cycle)
{
int i;
for (i = 0; i < l->count; i++)
{
if (line_has_unknown_pin(l->lines[i], cycle) || l->lines[i]->number_of_pins == 1)
{
fprintf(modelsim_out, "force %s ",l->lines[i]->name);
int j;
for (j = l->lines[i]->number_of_pins - 1; j >= 0 ; j--)
{
int value = get_line_pin_value(l->lines[i],j,cycle);
if (value < 0) fprintf(modelsim_out, "%s", "x");
else fprintf(modelsim_out, "%d", value);
}
fprintf(modelsim_out, " %d\n", cycle/2 * 100);
}
else
{
int value = 0;
fprintf(modelsim_out, "force %s 16#", l->lines[i]->name);
int j;
for (j = l->lines[i]->number_of_pins - 1; j >= 0; j--)
{
if (get_line_pin_value(l->lines[i],j,cycle) > 0)
value += my_power(2, j % 4);
if (j % 4 == 0)
{
fprintf(modelsim_out, "%X", value);
value = 0;
}
}
fprintf(modelsim_out, " %d\n", cycle/2 * 100);
}
}
}
/*
* Verify that the given output vector file is identical (numerically)
* to the one written by the current simulation. This is done by parsing each
* file vector by vector and comparing them. Also verifies that the headers are identical.
*
* Prints appropriate warning messages when differences are found.
*
* Returns false if the files differ and true if they are identical, with the exception of
* number format.
*/
int verify_output_vectors(char* output_vector_file, int num_vectors)
{
if (global_args.sim_output_both_edges)
num_vectors *= 2;
int error = FALSE;
// The filename cannot be the same as our default output file.
if (!strcmp(output_vector_file,OUTPUT_VECTOR_FILE_NAME))
{
error = TRUE;
warning_message(SIMULATION_ERROR,0,-1,
"Vector file \"%s\" given for verification "
"is the same as the default output file \"%s\". "
"Ignoring.", output_vector_file, OUTPUT_VECTOR_FILE_NAME);
}
else
{
// The file being verified against.
FILE *existing_out = fopen(output_vector_file, "r");
if (!existing_out) error_message(SIMULATION_ERROR, 0, -1, "Could not open vector output file: %s", output_vector_file);
// Our current output vectors. (Just produced.)
FILE *current_out = fopen(OUTPUT_VECTOR_FILE_NAME, "r");
if (!current_out) error_message(SIMULATION_ERROR, 0, -1, "Could not open output vector file.");
int cycle;
char buffer1[BUFFER_MAX_SIZE];
char buffer2[BUFFER_MAX_SIZE];
// Start at cycle -1 to check the headers.
for (cycle = -1; cycle < num_vectors; cycle++)
{
if (!get_next_vector(existing_out, buffer1))
{
error = TRUE;
warning_message(SIMULATION_ERROR, 0, -1,"Too few vectors in %s \n", output_vector_file);
break;
}
else if (!get_next_vector(current_out, buffer2))
{
error = TRUE;
warning_message(SIMULATION_ERROR, 0, -1,"Simulation produced fewer than %d vectors. \n", num_vectors);
break;
}
// The headers differ.
else if ((cycle == -1) && strcmp(buffer1,buffer2))
{
error = TRUE;
warning_message(SIMULATION_ERROR, 0, -1, "Vector headers do not match: \n"
"\t%s"
"in %s does not match\n"
"\t%s"
"in %s.\n\n",
buffer2, OUTPUT_VECTOR_FILE_NAME, buffer1, output_vector_file
);
break;
}
else
{
// Parse both vectors.
test_vector *v1 = parse_test_vector(buffer1);
test_vector *v2 = parse_test_vector(buffer2);
// Compare them and print an appropriate message if they differ.
if (!compare_test_vectors(v1,v2))
{
trim_string(buffer1, "\n\t");
trim_string(buffer2, "\n\t");
error = TRUE;
warning_message(SIMULATION_ERROR, 0, -1, "Vector %d mismatch:\n"
"\t%s in %s\n"
"\t%s in %s\n",
cycle, buffer2, OUTPUT_VECTOR_FILE_NAME, buffer1, output_vector_file
);
}
free_test_vector(v1);
free_test_vector(v2);
}
}
// If the file we're checking against is longer than the current output, print an appropriate warning.
if (!error && get_next_vector(existing_out, buffer1))
{
error = TRUE;
warning_message(SIMULATION_ERROR, 0, -1,"%s contains more than %d vectors.\n", output_vector_file, num_vectors);
}
fclose(existing_out);
fclose(current_out);
}
return !error;
}
/*
* Creates a hastable_t index of the given pin names list
* of the form pin name hashes to pin name array index.
*/
hashtable_t *index_pin_name_list(pin_names *list)
{
hashtable_t *index = create_hashtable(list->count * 2+1);
int i;
for (i = 0; i < list->count; i++)
{
int *id = malloc(sizeof(int));
*id = i;
index->add(index, list->pins[i], sizeof(char)*strlen(list->pins[i]), id);
}
return index;
}
/*
* Parses the given comma separated list into a
* pin_names struct. If the list is empty or null
* an empty struct is returned.
*/
pin_names *parse_pin_name_list(char *list)
{
pin_names *p = malloc(sizeof(pin_names));
p->pins = 0;
p->count = 0;
// Parse the list of additional pins passed via the -p option.
if (list)
{
char *pin_list = strdup(list);
char *token = strtok(pin_list, ",");
while (token)
{
p->pins = realloc(p->pins, sizeof(char *) * (p->count + 1));
p->pins[p->count++] = strdup(token);
token = strtok(NULL, ",");
}
free(pin_list);
}
return p;
}
/*
* If the given node matches one of the additional names (passed via -p),
* it's added to the lines. (Matches on output pin names, net names, and node names).
*/
void add_additional_items_to_lines(nnode_t *node, pin_names *p, lines_t *l)
{
if (p->count)
{
int add = FALSE;
int j, k = 0;
// Search the output pin names for each user-defined item.
for (j = 0; j < node->num_output_pins; j++)
{
npin_t *pin = node->output_pins[j];
if (pin->name)
{
for (k = 0; k < p->count; k++)
{
if (strstr(pin->name, p->pins[k]))
{
add = TRUE;
break;
}
}
if (add) break;
}
if (pin->net && pin->net->name)
{
for (k = 0; k < p->count; k++)
{
if (strstr(pin->net->name, p->pins[k]))
{
add = TRUE;
break;
}
}
if (add) break;
}
}
// Search the node name for each user defined item.
if (!add && node->name && strlen(node->name) && strchr(node->name, '^'))
{
for (k = 0; k < p->count; k++)
{
if (strstr(node->name, p->pins[k]))
{
add = TRUE;
break;
}
}
}
if (add)
{
int single_pin = strchr(p->pins[k], '~')?1:0;
if (strchr(node->name, '^'))
{
char *port_name;
if (single_pin)
port_name = get_pin_name(node->name);
else
port_name = get_port_name(node->name);
if (find_portname_in_lines(port_name, l) == -1)
{
line_t *line = create_line(port_name);
l->lines = realloc(l->lines, sizeof(line_t *)*((l->count)+1));
l->lines[l->count++] = line;
}
assign_node_to_line(node, l, OUTPUT, single_pin);
free(port_name);
}
}
}
}
/*
* Parses the given (memory) node name into a corresponding
* mif file name.
*/
char *get_mif_filename(nnode_t *node)
{
char buffer[BUFFER_MAX_SIZE];
buffer[0] = 0;
strcat(buffer, node->name);
char *filename = strrchr(buffer, '+');
if (filename) filename += 1;
else filename = buffer;
strcat(filename, ".mif");
filename = strdup(filename);
return filename;
}
/*
* Trims characters in the given "chars" string
* from the end of the given string.
*/
void trim_string(char* string, char *chars)
{
if (string)
{
int length;
while((length = strlen(string)))
{ int trimmed = FALSE;
int i;
for (i = 0; i < strlen(chars); i++)
{
if (string[length-1] == chars[i])
{
trimmed = TRUE;
string[length-1] = '\0';
break;
}
}
if (!trimmed)
break;
}
}
}
/*
* Returns TRUE if the given line has a pin for
* the given cycle whose value is -1.
*/
int line_has_unknown_pin(line_t *line, int cycle)
{
int unknown = FALSE;
int j;
for (j = line->number_of_pins - 1; j >= 0; j--)
{
if (get_line_pin_value(line, j, cycle) < 0)
{
unknown = TRUE;
break;
}
}
return unknown;
}
/*
* Gets the value of the pin given pin within the given line
* for the given cycle.
*/
signed char get_line_pin_value(line_t *line, int pin_num, int cycle)
{
return get_pin_value(line->pins[pin_num],cycle);
}
/*
* Returns a value from a test_vectors struct in hex. Works
* for the values arrays in pins as well.
*/
char *vector_value_to_hex(signed char *value, int length)
{
char *tmp;
char *string = calloc((length + 1),sizeof(char));
int j;
for (j = 0; j < length; j++)
string[j] = value[j] + '0';
reverse_string(string,strlen(string));
char *hex_string = malloc(sizeof(char) * ((length/4 + 1) + 1));
sprintf(hex_string, "%X ", (unsigned int)strtol(string, &tmp, 2));
free(string);
return hex_string;
}
/*
* Counts the number of vectors in the given file.
*/
int count_test_vectors(FILE *in)
{
rewind(in);
int count = 0;
char buffer[BUFFER_MAX_SIZE];
while (get_next_vector(in, buffer))
count++;
if (count) // Don't count the headers.
count--;
rewind(in);
return count;
}
/*
* A given line is a vector if it contains one or more
* non-whitespace characters and does not being with a #.
*/
int is_vector(char *buffer)
{
char *line = strdup(buffer);
trim_string(line," \t\r\n");
if (line[0] != '#' && strlen(line))
{
free(line);
return TRUE;
}
else
{
free(line);
return FALSE;
}
}
/*
* Gets the next line from the given file that
* passes the is_vector() test and places it in
* the buffer. Returns TRUE if a vector was found,
* and FALSE if no vector was found.
*/
int get_next_vector(FILE *file, char *buffer)
{
while (fgets(buffer, BUFFER_MAX_SIZE, file))
if (is_vector(buffer))
return TRUE;
return FALSE;
}
/*
* Free each element in lines[] and the array itself
*/
void free_lines(lines_t *l)
{
int i;
for (i = 0; i < l->count; i++)
{
free(l->lines[i]->name);
free(l->lines[i]->pins);
free(l->lines[i]);
}
free(l->lines);
free(l);
}
/*
* Free stages.
*/
void free_stages(stages *s)
{
while (s->count--)
free(s->stages[s->count]);
free(s->stages);
free(s->counts);
free(s);
}
/*
* Free the given test_vector.
*/
void free_test_vector(test_vector* v)
{
while (v->count--)
free(v->values[v->count]);
free(v->values);
free(v->counts);
free(v);
}
/*
* Frees pin_names struct.
*/
void free_pin_name_list(pin_names *p)
{
while (p->count--)
free(p->pins[p->count]);
free(p->pins);
free(p);
}
/*
* Prints/updates an ASCII progress bar of length "length" to position length * completion
* from previous position "position". Updates ETA based on the elapsed time "time".
* Returns the new position. If the position is unchanged the bar is not redrawn.
*
* Call with position = -1 to draw for the first time. Returns the new
* position, calculated based on completion.
*/
int print_progress_bar(double completion, int position, int length, double time)
{
if (position == -1 || ((int)(completion * length)) > position)
{
printf("%3.0f%%|", completion * (double)100);
position = completion * length;
int i;
for (i = 0; i < position; i++)
printf("=");
printf(">");
for (; i < length; i++)
printf("-");
if (completion < 1.0)
{
printf("| Remaining: ");
double remaining_time = time/(double)completion - time;
print_time(remaining_time);
}
else
{
printf("| Total time: ");
print_time(time);
}
printf(" \r");
if (position == length)
printf("\n");
fflush(stdout);
}
return position;
}
/*
* Prints information about the netlist we are simulating.
*/
void print_netlist_stats(stages *stages, int num_vectors)
{
printf("%s:\n", get_circuit_filename());
printf(" Nodes: %d\n", stages->num_nodes);
printf(" Connections: %d\n", stages->num_connections);
printf(" Degree: %3.2f\n", stages->num_connections/(float)stages->num_nodes);
printf(" Stages: %d\n", stages->count);
#ifdef _OPENMP
printf(" Parallel nodes: %d (%4.1f%%)\n", stages->num_parallel_nodes, (stages->num_parallel_nodes/(double)stages->num_nodes) * 100);
#endif
printf("\n");
}
/*
* Prints statistics. (Coverage and times.)
*/
void print_simulation_stats(stages *stages, int num_vectors, double total_time, double simulation_time)
{
int covered_nodes = get_num_covered_nodes(stages);
printf("Simulation time: ");
print_time(simulation_time);
printf("\n");
printf("Elapsed time: ");
print_time(total_time);
printf("\n");
printf("Coverage: "
"%d (%4.1f%%)\n", covered_nodes, (covered_nodes/(double)stages->num_nodes) * 100);
}
/*
* Prints the time in appropriate units.
*/
void print_time(double time)
{
if (time > 24*3600) printf("%.1fd", time/(24*3600.0));
else if (time > 3600) printf("%.1fh", time/3600.0);
else if (time > 60) printf("%.1fm", time/60.0);
else if (time > 1) printf("%.1fs", time);
else printf("%.1fms", time*1000);
}
/*
* Prints n ancestors of the given node, complete
* with their parents, ids, etc.
*/
void print_ancestry(nnode_t *bottom_node, int n)
{
if (!n) n = 10;
queue_t *queue = create_queue();
queue->add(queue, bottom_node);
nnode_t *node;
printf( " ------------\n");
printf( " BACKTRACE\n");
printf( " ------------\n");
while (n-- && (node = queue->remove(queue)))
{
char *name = get_pin_name(node->name);
printf(" %s (%ld):\n", name, node->unique_id);
free(name);
int i;
for (i = 0; i < node->num_input_pins; i++)
{
npin_t *pin = node->input_pins[i];
nnet_t *net = pin->net;
nnode_t *node = net->driver_pin->node;
queue->add(queue, node);
char *name = get_pin_name(node->name);
printf("\t%s %s (%ld)\n", pin->mapping, name, node->unique_id);fflush(stdout);
free(name);
}
/*int count = 0;
{
printf( " ------------\n");
printf( " CHILDREN \n");
printf( " ------------\n");
printf( " O: %d\n", node->num_output_pins);fflush(stdout);
for (i = 0; i < node->num_output_pins; i++)
{
npin_t *pin = node->output_pins[i];
if (pin)
{
nnet_t *net = pin->net;
if (net)
{
int j;
for (j = 0; j < net->num_fanout_pins; j++)
{
npin_t *pin = net->fanout_pins[j];
if (pin)
{
nnode_t *node = pin->node;
if (node)
{
char *name = get_pin_name(node->name);
printf("\t%s %s (%ld)\n", pin->mapping, name, node->unique_id);fflush(stdout);
free(name);
}
else
{
printf(" Null node %d\n", ++count);fflush(stdout);
}
}
else
{
printf(" Null fanout pin\n");fflush(stdout);
}
}
}
else
{
printf(" Null net\n");fflush(stdout);
}
}
}
}*/
printf( " ------------\n");
}
queue->destroy(queue);
printf( " END OF TRACE\n");
printf( " ------------\n");
}
/*
* Traces an node which is failing to update back to parent of
* the earliest node in the net list with an unupdated pin.
* (Pin whose cycle is less than cycle-1). Prints all nodes
* traversed during the trace with the original node printed
* first, and the root of the issue printed last.
*
* Returns the root node for inspection.
*/
nnode_t *print_update_trace(nnode_t *bottom_node, int cycle)
{
// Limit the length of the trace. 0 for unlimited.
const int max_depth = 0;
printf(
" --------------------------------------------------------------------------\n"
" --------------------------------------------------------------------------\n"
" BACKTRACE:\n"
"\tFormat: Each node is listed followed by its parents. The parent \n"
"\twhich is not updating is indicated with an astrisk. (*)\n"
"\tEach node is listed in the form:\n"
"\t\t(<mapping>) <Name> (<Unique ID>) <# of Parents> <# of Children> \n"
" --------------------------------------------------------------------------\n"
);
nnode_t *root_node = NULL;
// Used to detect cycles. Based table size of max depth. If unlimited, set to something big.
hashtable_t *index = create_hashtable(max_depth?(max_depth * 2):100000);
queue_t *queue = create_queue();
queue->add(queue, bottom_node);
nnode_t *node;
int depth = 0;
// Traverse the netlist in reverse, starting with our current location.
while ((node = queue->remove(queue)))
{
int found_undriven_pin = FALSE;
int is_duplicate = index->get(index, &node->unique_id, sizeof(long))?1:0;
if (!is_duplicate)
{
depth++;
index->add(index, &node->unique_id, sizeof(long), (void *)1);
char *name = get_pin_name(node->name);
printf(" %s (%ld) %d %d\n", name, node->unique_id, node->num_input_pins, node->num_output_pins);
free(name);
int i;
for (i = 0; i < node->num_input_pins; i++)
{
npin_t *pin = node->input_pins[i];
nnet_t *net = pin->net;
nnode_t *node = net->driver_pin->node;
// If an input is found which hasn't been updated since before cycle-1, traverse it.
int is_undriven = FALSE;
if (get_pin_cycle(pin) < cycle-1)
{
// Only add each node for traversal once.
if (!found_undriven_pin)
{
found_undriven_pin = TRUE;
queue->add(queue, node);
}
is_undriven = TRUE;
}
char *name = get_pin_name(node->name);
printf("\t(%s) %s (%ld) %d %d %s \n", pin->mapping, name, node->unique_id, node->num_input_pins, node->num_output_pins, is_undriven?"*":"");
free(name);
}
printf(" ------------\n");
}
else {
printf(" CYCLE DETECTED AFTER %d NODES.\n", depth);
printf(" ------------\n");
break;
}
if (!found_undriven_pin)
{
printf(" TOP OF TRACE\n");
printf(" ------------\n");
root_node = node;
break;
}
else if (max_depth && depth >=max_depth)
{
printf(" TRACE TRUNCATED AT %d NODES.\n", max_depth);
printf(" ------------\n");
break;
}
}
index->destroy(index);
queue->destroy(queue);
return root_node;
}
/*
* Gets the current time in seconds.
*/
inline double wall_time()
{
struct timeval tv;
gettimeofday(&tv, 0);
return (1000000*tv.tv_sec+tv.tv_usec)/1.0e6;
}
/*
* Gets the name of the file we are simulating as passed by the -b or -V option.
*/
char *get_circuit_filename()
{
return global_args.verilog_file?global_args.verilog_file:global_args.blif_file;
}
|
GB_unaryop__minv_uint16_int16.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__minv_uint16_int16
// op(A') function: GB_tran__minv_uint16_int16
// C type: uint16_t
// A type: int16_t
// cast: uint16_t cij = (uint16_t) aij
// unaryop: cij = GB_IMINV_UNSIGNED (aij, 16)
#define GB_ATYPE \
int16_t
#define GB_CTYPE \
uint16_t
// 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 = GB_IMINV_UNSIGNED (x, 16) ;
// casting
#define GB_CASTING(z, x) \
uint16_t z = (uint16_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_MINV || GxB_NO_UINT16 || GxB_NO_INT16)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__minv_uint16_int16
(
uint16_t *restrict Cx,
const int16_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__minv_uint16_int16
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t **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_fp32_bool.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_fp32_bool)
// op(A') function: GB (_unop_tran__identity_fp32_bool)
// C type: float
// A type: bool
// cast: float cij = (float) aij
// unaryop: cij = aij
#define GB_ATYPE \
bool
#define GB_CTYPE \
float
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
bool aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
float z = (float) aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
bool aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
float z = (float) aij ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_FP32 || GxB_NO_BOOL)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_fp32_bool)
(
float *Cx, // Cx and Ax may be aliased
const bool *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++)
{
bool aij = Ax [p] ;
float z = (float) aij ;
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 ;
bool aij = Ax [p] ;
float z = (float) aij ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__identity_fp32_bool)
(
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
|
GB_binop__div_fc32.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 GBCUDA_DEV
#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__div_fc32)
// A.*B function (eWiseMult): GB (_AemultB_08__div_fc32)
// A.*B function (eWiseMult): GB (_AemultB_02__div_fc32)
// A.*B function (eWiseMult): GB (_AemultB_04__div_fc32)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__div_fc32)
// A*D function (colscale): GB (_AxD__div_fc32)
// D*A function (rowscale): GB (_DxB__div_fc32)
// C+=B function (dense accum): GB (_Cdense_accumB__div_fc32)
// C+=b function (dense accum): GB (_Cdense_accumb__div_fc32)
// C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__div_fc32)
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__div_fc32)
// C=scalar+B GB (_bind1st__div_fc32)
// C=scalar+B' GB (_bind1st_tran__div_fc32)
// C=A+scalar GB (_bind2nd__div_fc32)
// C=A'+scalar GB (_bind2nd_tran__div_fc32)
// C type: GxB_FC32_t
// A type: GxB_FC32_t
// A pattern? 0
// B type: GxB_FC32_t
// B pattern? 0
// BinaryOp: cij = GB_FC32_div (aij, bij)
#define GB_ATYPE \
GxB_FC32_t
#define GB_BTYPE \
GxB_FC32_t
#define GB_CTYPE \
GxB_FC32_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) \
GxB_FC32_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) \
GxB_FC32_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) \
GxB_FC32_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_FC32_div (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_DIV || GxB_NO_FC32 || GxB_NO_DIV_FC32)
//------------------------------------------------------------------------------
// 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__div_fc32)
(
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
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__div_fc32)
(
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__div_fc32)
(
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__div_fc32)
(
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 GxB_FC32_t
GxB_FC32_t bwork = (*((GxB_FC32_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__div_fc32)
(
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
GxB_FC32_t *restrict Cx = (GxB_FC32_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__div_fc32)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GxB_FC32_t *restrict Cx = (GxB_FC32_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__div_fc32)
(
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) ;
GxB_FC32_t alpha_scalar ;
GxB_FC32_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((GxB_FC32_t *) alpha_scalar_in)) ;
beta_scalar = (*((GxB_FC32_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__div_fc32)
(
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__div_fc32)
(
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__div_fc32)
(
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__div_fc32)
(
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__div_fc32)
(
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
GxB_FC32_t *Cx = (GxB_FC32_t *) Cx_output ;
GxB_FC32_t x = (*((GxB_FC32_t *) x_input)) ;
GxB_FC32_t *Bx = (GxB_FC32_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 ;
GxB_FC32_t bij = GBX (Bx, p, false) ;
Cx [p] = GB_FC32_div (x, bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__div_fc32)
(
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 ;
GxB_FC32_t *Cx = (GxB_FC32_t *) Cx_output ;
GxB_FC32_t *Ax = (GxB_FC32_t *) Ax_input ;
GxB_FC32_t y = (*((GxB_FC32_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
GxB_FC32_t aij = GBX (Ax, p, false) ;
Cx [p] = GB_FC32_div (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) \
{ \
GxB_FC32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_FC32_div (x, aij) ; \
}
GrB_Info GB (_bind1st_tran__div_fc32)
(
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 \
GxB_FC32_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GxB_FC32_t x = (*((const GxB_FC32_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
GxB_FC32_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) \
{ \
GxB_FC32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_FC32_div (aij, y) ; \
}
GrB_Info GB (_bind2nd_tran__div_fc32)
(
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
GxB_FC32_t y = (*((const GxB_FC32_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
22_set_threads_in_directive.c | #include <stdio.h>
#include <omp.h>
int main()
{
printf("Hello world from the main program\n");
int nthreads = 6;
#pragma omp parallel num_threads(nthreads)
{
printf("Hello world! I am processor %i\n", omp_get_thread_num());
}
return 0;
}
|
einspline_allocator.c | /////////////////////////////////////////////////////////////////////////////
// einspline: a library for creating and evaluating B-splines //
// Copyright (C) 2007 Kenneth P. Esler, Jr. //
// //
// 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 //
// along with this program; if not, write to the Free Software //
// Foundation, Inc., 51 Franklin Street, Fifth Floor, //
// Boston, MA 02110-1301 USA //
/////////////////////////////////////////////////////////////////////////////
/** @file einspline_allocator.c
*
* Gather only 3d_d/3d_s allocation routines.
* Original implementations are einspline/ *_create.c
*/
#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>
#include "config.h"
#include "einspline/bspline.h"
#include "spline2/einspline_allocator.h"
//forward declaration of the functions
void find_coefs_1d_d (Ugrid grid, BCtype_d bc, double *data, intptr_t dstride,
double *coefs, intptr_t cstride);
void solve_deriv_interp_1d_s (float bands[], float coefs[], int M, int
cstride);
void solve_antiperiodic_interp_1d_s (float bands[], float coefs[], int M, int
cstride);
void find_coefs_1d_s (Ugrid grid, BCtype_s bc, float *data, intptr_t dstride,
float *coefs, intptr_t cstride);
#if defined(HAVE_POSIX_MEMALIGN)
int posix_memalign(void **memptr, size_t alignment, size_t size);
inline void *
einspline_alloc (size_t size, size_t alignment)
{
void *ptr;
posix_memalign (&ptr, alignment, size);
return ptr;
}
inline void
einspline_free (void *ptr)
{
free (ptr);
}
#else
inline void *
einspline_alloc (size_t size, size_t alignment)
{
size += (alignment-1)+sizeof(void*);
void *ptr = malloc (size);
if (ptr == NULL)
return NULL;
else
{
void *shifted = (char *)ptr + sizeof(void*); // make room to save original pointer
size_t offset = alignment - (size_t)shifted%(size_t)alignment;
void *aligned = (char *)shifted + offset;
*((void**)aligned-1) = ptr;
return aligned;
}
}
inline void
einspline_free (void *aligned)
{
void *ptr = *((void**)aligned-1);
free (ptr);
}
#endif
multi_UBspline_3d_s*
einspline_create_multi_UBspline_3d_s (Ugrid x_grid, Ugrid y_grid, Ugrid z_grid,
BCtype_s xBC, BCtype_s yBC, BCtype_s zBC,
int num_splines)
{
// Create new spline
multi_UBspline_3d_s* restrict spline = malloc (sizeof(multi_UBspline_3d_s));
if (!spline) {
fprintf (stderr, "Out of memory allocating spline in create_multi_UBspline_3d_s.\n");
abort();
}
spline->spcode = MULTI_U3D;
spline->tcode = SINGLE_REAL;
spline->xBC = xBC;
spline->yBC = yBC;
spline->zBC = zBC;
spline->num_splines = num_splines;
// Setup internal variables
int Mx = x_grid.num; int My = y_grid.num; int Mz = z_grid.num;
int Nx, Ny, Nz;
if (xBC.lCode == PERIODIC || xBC.lCode == ANTIPERIODIC)
Nx = Mx+3;
else
Nx = Mx+2;
x_grid.delta = (x_grid.end - x_grid.start)/(double)(Nx-3);
x_grid.delta_inv = 1.0/x_grid.delta;
spline->x_grid = x_grid;
if (yBC.lCode == PERIODIC || yBC.lCode == ANTIPERIODIC)
Ny = My+3;
else
Ny = My+2;
y_grid.delta = (y_grid.end - y_grid.start)/(double)(Ny-3);
y_grid.delta_inv = 1.0/y_grid.delta;
spline->y_grid = y_grid;
if (zBC.lCode == PERIODIC || zBC.lCode == ANTIPERIODIC)
Nz = Mz+3;
else
Nz = Mz+2;
z_grid.delta = (z_grid.end - z_grid.start)/(double)(Nz-3);
z_grid.delta_inv = 1.0/z_grid.delta;
spline->z_grid = z_grid;
const int ND=QMC_CLINE/sizeof(float);
const size_t N=((num_splines+ND-1)/ND)*ND;
//int N= (num_splines%ND) ? (num_splines+ND-num_splines%ND) : num_splines;
spline->x_stride = (size_t)Ny*(size_t)Nz*(size_t)N;
spline->y_stride = (size_t)Nz*N;
spline->z_stride = N;
spline->coefs_size=(size_t)Nx*spline->x_stride;
spline->coefs = (float*)einspline_alloc(sizeof(float)*spline->coefs_size,QMC_CLINE);
//printf("Einepline allocator %d %d %d %zd (%d) %zu %d\n",Nx,Ny,Nz,N,num_splines,spline->coefs_size,QMC_CLINE);
if (!spline->coefs) {
fprintf (stderr, "Out of memory allocating spline coefficients in create_multi_UBspline_3d_s.\n");
abort();
}
#if 0
//test first-touch later
const size_t xs = spline->x_stride;
const size_t ys = spline->y_stride;
const size_t zs = spline->z_stride;
const float czero=0;
#pragma omp parallel for collapse(3)
for(size_t i=0; i<Nx; ++i)
for(size_t j=0; j<Ny; ++j)
for(size_t k=0; k<Nz; ++k)
{
float* restrict coefs = spline->coefs + i*xs + j*ys + k*zs;
for(size_t s=0; s<N; ++s)
coefs[s]=czero;
}
#endif
return spline;
}
multi_UBspline_3d_d*
einspline_create_multi_UBspline_3d_d (Ugrid x_grid, Ugrid y_grid, Ugrid z_grid,
BCtype_d xBC, BCtype_d yBC, BCtype_d zBC,
int num_splines)
{
// Create new spline
multi_UBspline_3d_d* restrict spline = malloc (sizeof(multi_UBspline_3d_d));
if (!spline) {
fprintf (stderr, "Out of memory allocating spline in create_multi_UBspline_3d_d.\n");
abort();
}
spline->spcode = MULTI_U3D;
spline->tcode = DOUBLE_REAL;
spline->xBC = xBC;
spline->yBC = yBC;
spline->zBC = zBC;
spline->num_splines = num_splines;
// Setup internal variables
int Mx = x_grid.num; int My = y_grid.num; int Mz = z_grid.num;
int Nx, Ny, Nz;
if (xBC.lCode == PERIODIC || xBC.lCode == ANTIPERIODIC)
Nx = Mx+3;
else
Nx = Mx+2;
x_grid.delta = (x_grid.end - x_grid.start)/(double)(Nx-3);
x_grid.delta_inv = 1.0/x_grid.delta;
spline->x_grid = x_grid;
if (yBC.lCode == PERIODIC || yBC.lCode == ANTIPERIODIC)
Ny = My+3;
else
Ny = My+2;
y_grid.delta = (y_grid.end - y_grid.start)/(double)(Ny-3);
y_grid.delta_inv = 1.0/y_grid.delta;
spline->y_grid = y_grid;
if (zBC.lCode == PERIODIC || zBC.lCode == ANTIPERIODIC)
Nz = Mz+3;
else
Nz = Mz+2;
z_grid.delta = (z_grid.end - z_grid.start)/(double)(Nz-3);
z_grid.delta_inv = 1.0/z_grid.delta;
spline->z_grid = z_grid;
const int ND=QMC_CLINE/sizeof(double);
int N= (num_splines%ND) ? (num_splines+ND-num_splines%ND) : num_splines;
spline->x_stride = (size_t)Ny*(size_t)Nz*(size_t)N;
spline->y_stride = Nz*N;
spline->z_stride = N;
spline->coefs_size=(size_t)Nx*spline->x_stride;
spline->coefs=(double*)einspline_alloc(sizeof(double)*spline->coefs_size,QMC_CLINE);
if (!spline->coefs) {
fprintf (stderr, "Out of memory allocating spline coefficients in create_multi_UBspline_3d_d.\n");
abort();
}
return spline;
}
UBspline_3d_d*
einspline_create_UBspline_3d_d (Ugrid x_grid, Ugrid y_grid, Ugrid z_grid,
BCtype_d xBC, BCtype_d yBC, BCtype_d zBC,
double *data)
{
// Create new spline
UBspline_3d_d* restrict spline = malloc (sizeof(UBspline_3d_d));
spline->spcode = U3D;
spline->tcode = DOUBLE_REAL;
spline->xBC = xBC;
spline->yBC = yBC;
spline->zBC = zBC;
// Setup internal variables
int Mx = x_grid.num; int My = y_grid.num; int Mz = z_grid.num;
int Nx, Ny, Nz;
if (xBC.lCode == PERIODIC || xBC.lCode == ANTIPERIODIC) Nx = Mx+3;
else Nx = Mx+2;
x_grid.delta = (x_grid.end - x_grid.start)/(double)(Nx-3);
x_grid.delta_inv = 1.0/x_grid.delta;
spline->x_grid = x_grid;
if (yBC.lCode == PERIODIC || yBC.lCode == ANTIPERIODIC) Ny = My+3;
else Ny = My+2;
y_grid.delta = (y_grid.end - y_grid.start)/(double)(Ny-3);
y_grid.delta_inv = 1.0/y_grid.delta;
spline->y_grid = y_grid;
if (zBC.lCode == PERIODIC || zBC.lCode == ANTIPERIODIC) Nz = Mz+3;
else Nz = Mz+2;
z_grid.delta = (z_grid.end - z_grid.start)/(double)(Nz-3);
z_grid.delta_inv = 1.0/z_grid.delta;
spline->z_grid = z_grid;
spline->x_stride = Ny*Nz;
spline->y_stride = Nz;
spline->coefs_size=(size_t)Nx*(size_t)Ny*(size_t)Nz;
spline->coefs= (double*)einspline_alloc (sizeof(double)*spline->coefs_size,QMC_CLINE);
if(data != NULL) // only data is provided
{
// First, solve in the X-direction
#pragma omp parallel for
for (int iy=0; iy<My; iy++)
for (int iz=0; iz<Mz; iz++) {
intptr_t doffset = iy*Mz+iz;
intptr_t coffset = iy*Nz+iz;
find_coefs_1d_d (spline->x_grid, xBC, data+doffset, My*Mz,
spline->coefs+coffset, Ny*Nz);
}
// Now, solve in the Y-direction
#pragma omp parallel for
for (int ix=0; ix<Nx; ix++)
for (int iz=0; iz<Nz; iz++) {
intptr_t doffset = ix*Ny*Nz + iz;
intptr_t coffset = ix*Ny*Nz + iz;
find_coefs_1d_d (spline->y_grid, yBC, spline->coefs+doffset, Nz,
spline->coefs+coffset, Nz);
}
// Now, solve in the Z-direction
#pragma omp parallel for
for (int ix=0; ix<Nx; ix++)
for (int iy=0; iy<Ny; iy++) {
intptr_t doffset = (ix*Ny+iy)*Nz;
intptr_t coffset = (ix*Ny+iy)*Nz;
find_coefs_1d_d (spline->z_grid, zBC, spline->coefs+doffset, 1,
spline->coefs+coffset, 1);
}
}
return spline;
}
UBspline_3d_s*
einspline_create_UBspline_3d_s (Ugrid x_grid, Ugrid y_grid, Ugrid z_grid,
BCtype_s xBC, BCtype_s yBC, BCtype_s zBC,
float *data)
{
// Create new spline
UBspline_3d_s* spline = malloc (sizeof(UBspline_3d_s));
spline->spcode = U3D;
spline->tcode = SINGLE_REAL;
spline->xBC = xBC;
spline->yBC = yBC;
spline->zBC = zBC;
// Setup internal variables
int Mx = x_grid.num; int My = y_grid.num; int Mz = z_grid.num;
int Nx, Ny, Nz;
if (xBC.lCode == PERIODIC || xBC.lCode == ANTIPERIODIC) Nx = Mx+3;
else Nx = Mx+2;
x_grid.delta = (x_grid.end - x_grid.start)/(double)(Nx-3);
x_grid.delta_inv = 1.0/x_grid.delta;
spline->x_grid = x_grid;
if (yBC.lCode == PERIODIC || yBC.lCode == ANTIPERIODIC) Ny = My+3;
else Ny = My+2;
y_grid.delta = (y_grid.end - y_grid.start)/(double)(Ny-3);
y_grid.delta_inv = 1.0/y_grid.delta;
spline->y_grid = y_grid;
if (zBC.lCode == PERIODIC || zBC.lCode == ANTIPERIODIC) Nz = Mz+3;
else Nz = Mz+2;
z_grid.delta = (z_grid.end - z_grid.start)/(double)(Nz-3);
z_grid.delta_inv = 1.0/z_grid.delta;
spline->z_grid = z_grid;
spline->x_stride = Ny*Nz;
spline->y_stride = Nz;
spline->coefs_size=(size_t)Nx*(size_t)Ny*(size_t)Nz;
spline->coefs= (float*)einspline_alloc (sizeof(float)*spline->coefs_size,QMC_CLINE);
// First, solve in the X-direction
for (int iy=0; iy<My; iy++)
for (int iz=0; iz<Mz; iz++) {
intptr_t doffset = iy*Mz+iz;
intptr_t coffset = iy*Nz+iz;
find_coefs_1d_s (spline->x_grid, xBC, data+doffset, My*Mz,
spline->coefs+coffset, Ny*Nz);
}
// Now, solve in the Y-direction
for (int ix=0; ix<Nx; ix++)
for (int iz=0; iz<Nz; iz++) {
intptr_t doffset = ix*Ny*Nz + iz;
intptr_t coffset = ix*Ny*Nz + iz;
find_coefs_1d_s (spline->y_grid, yBC, spline->coefs+doffset, Nz,
spline->coefs+coffset, Nz);
}
// Now, solve in the Z-direction
for (int ix=0; ix<Nx; ix++)
for (int iy=0; iy<Ny; iy++) {
intptr_t doffset = (ix*Ny+iy)*Nz;
intptr_t coffset = (ix*Ny+iy)*Nz;
find_coefs_1d_s (spline->z_grid, zBC, spline->coefs+doffset, 1,
spline->coefs+coffset, 1);
}
return spline;
}
|
GB_unaryop__lnot_bool_fp32.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__lnot_bool_fp32
// op(A') function: GB_tran__lnot_bool_fp32
// C type: bool
// A type: float
// cast: bool cij = (bool) aij
// unaryop: cij = !aij
#define GB_ATYPE \
float
#define GB_CTYPE \
bool
// 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 = !x ;
// casting
#define GB_CASTING(z, aij) \
bool z = (bool) 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_LNOT || GxB_NO_BOOL || GxB_NO_FP32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__lnot_bool_fp32
(
bool *Cx, // Cx and Ax may be aliased
float *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__lnot_bool_fp32
(
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
|
algo.h | /**
* Copyright 2021 Huawei Technologies Co., Ltd
*
* 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 MINDQUANTUM_SPARSE_ALGO_H_
#define MINDQUANTUM_SPARSE_ALGO_H_
#include <memory>
#include "sparse/csrhdmatrix.h"
#include "sparse/paulimat.h"
#include "sparse/sparse_utils.h"
namespace mindquantum {
namespace sparse {
template <typename T>
std::shared_ptr<CsrHdMatrix<T>> TransposeCsrHdMatrix(std::shared_ptr<CsrHdMatrix<T>> a) {
auto &dim = a->dim_;
auto &nnz = a->nnz_;
auto &a_indices = a->indices_;
auto &a_indptr = a->indptr_;
auto &a_data = a->data_;
Index *indices = reinterpret_cast<Index *>(malloc(sizeof(Index) * nnz));
Index *indptr = reinterpret_cast<Index *>(malloc(sizeof(Index) * (dim + 1)));
CTP<T> data = reinterpret_cast<CTP<T>>(malloc(sizeof(CT<T>) * nnz));
std::fill(indptr, indptr + dim, 0);
for (Index n = 0; n < nnz; n++) {
indptr[a_indices[n]]++;
}
for (Index col = 0, sum = 0; col < dim; col++) {
Index t = indptr[col];
indptr[col] = sum;
sum += t;
}
indptr[dim] = nnz;
for (Index row = 0; row < dim; row++) {
for (Index jj = a_indptr[row]; jj < a_indptr[row + 1]; jj++) {
Index col = a_indices[jj];
Index dest = indptr[col];
indices[dest] = row;
data[dest] = std::conj(a_data[jj]);
indptr[col]++;
}
}
for (Index col = 0, last = 0; col <= dim; col++) {
Index t = indptr[col];
indptr[col] = last;
last = t;
}
auto c = std::make_shared<CsrHdMatrix<T>>(dim, nnz, indptr, indices, data);
return c;
}
template <typename T>
std::shared_ptr<CsrHdMatrix<T>> PauliMatToCsrHdMatrix(std::shared_ptr<PauliMat<T>> a) {
Index nnz = 0;
auto &col = a->col_;
auto &dim = a->dim_;
auto &coeff = a->coeff_;
auto &p = a->p_;
#pragma omp parallel for schedule(static) reduction(+ : nnz)
for (Index i = 0; i < dim; i++) {
if (i <= col[i]) {
nnz++;
}
}
Index *indptr = reinterpret_cast<Index *>(malloc(sizeof(Index) * (dim + 1)));
Index *indices = reinterpret_cast<Index *>(malloc(sizeof(Index) * nnz));
CTP<T> data = reinterpret_cast<CTP<T>>(malloc(sizeof(CT<T>) * nnz));
indptr[0] = 0;
for (Index i = 0, j = 0; i < dim; i++) {
if (i <= col[i]) {
indptr[i + 1] = indptr[i] + 1;
if (i == col[i]) {
data[j] = p * POLAR[coeff[i]] * (T) (0.5);
} else {
data[j] = p * POLAR[coeff[i]];
}
indices[j] = col[i];
j++;
} else {
indptr[i + 1] = indptr[i];
}
}
auto c = std::make_shared<CsrHdMatrix<T>>(dim, nnz, indptr, indices, data);
return c;
}
template <typename T>
std::shared_ptr<PauliMat<T>> GetPauliMat(const PauliTerm<T> &pt, Index n_qubits) {
auto c = std::make_shared<PauliMat<T>>(pt, n_qubits);
return c;
}
template <typename T>
std::shared_ptr<CsrHdMatrix<T>> Csr_Plus_Csr(std::shared_ptr<CsrHdMatrix<T>> a, std::shared_ptr<CsrHdMatrix<T>> b) {
auto a_nnz = a->nnz_;
auto b_nnz = b->nnz_;
auto dim = a->dim_;
auto maxnnz = a_nnz + b_nnz;
CTP<T> data = reinterpret_cast<CTP<T>>(malloc(sizeof(CT<T>) * maxnnz));
Index *indices = reinterpret_cast<Index *>(malloc(sizeof(Index) * maxnnz));
Index *indptr = reinterpret_cast<Index *>(malloc(sizeof(Index) * (dim + 1)));
csr_plus_csr(dim, a->indptr_, a->indices_, a->data_, b->indptr_, b->indices_, b->data_, indptr, indices, data);
auto nnz = indptr[dim];
auto c = std::make_shared<CsrHdMatrix<T>>(dim, nnz, indptr, indices, data);
return c;
}
template <typename T>
std::shared_ptr<CsrHdMatrix<T>> SparseHamiltonian(const VT<PauliTerm<T>> &hams, Index n_qubits) {
VT<std::shared_ptr<CsrHdMatrix<T>>> sp_hams(hams.size());
#pragma omp parallel for schedule(static)
for (Index i = 0; i < static_cast<Index>(hams.size()); i++) {
auto pm = GetPauliMat(hams[i], n_qubits);
sp_hams[i] = PauliMatToCsrHdMatrix(pm);
pm->Reset();
}
Index tot = static_cast<Index>(hams.size());
while (tot > 1) {
Index half = tot / 2 + tot % 2;
#pragma omp parallel for schedule(static) num_threads(half)
for (Index i = half; i < tot; i++) {
sp_hams[i - half] = Csr_Plus_Csr(sp_hams[i - half], sp_hams[i]);
sp_hams[i]->Reset();
}
tot = half;
}
return sp_hams[0];
}
template <typename T, typename T2>
T2 *Csr_Dot_Vec(std::shared_ptr<CsrHdMatrix<T>> a, T2 *vec) {
auto dim = a->dim_;
auto c_vec = reinterpret_cast<CTP<T2>>(vec);
auto new_vec = reinterpret_cast<CTP<T2>>(malloc(sizeof(CT<T2>) * dim));
// auto nnz = a->nnz_;
auto data = a->data_;
auto indptr = a->indptr_;
auto indices = a->indices_;
#pragma omp parallel for schedule(static)
for (Index i = 0; i < dim; i++) {
CT<T2> sum = {0.0, 0.0};
for (Index j = indptr[i]; j < indptr[i + 1]; j++) {
sum += data[j] * c_vec[indices[j]];
}
new_vec[i] = sum;
}
free(vec);
return reinterpret_cast<T2 *>(new_vec);
}
template <typename T, typename T2>
T2 *Csr_Dot_Vec(std::shared_ptr<CsrHdMatrix<T>> a, std::shared_ptr<CsrHdMatrix<T>> b, T2 *vec) {
auto dim = a->dim_;
auto c_vec = reinterpret_cast<CTP<T2>>(vec);
auto new_vec = reinterpret_cast<CTP<T2>>(malloc(sizeof(CT<T2>) * dim));
// auto nnz = a->nnz_;
auto data = a->data_;
auto indptr = a->indptr_;
auto indices = a->indices_;
auto data_b = b->data_;
auto indptr_b = b->indptr_;
auto indices_b = b->indices_;
#pragma omp parallel for schedule(static)
for (Index i = 0; i < dim; i++) {
CT<T2> sum = {0.0, 0.0};
for (Index j = indptr[i]; j < indptr[i + 1]; j++) {
sum += data[j] * c_vec[indices[j]];
}
for (Index j = indptr_b[i]; j < indptr_b[i + 1]; j++) {
sum += data_b[j] * c_vec[indices_b[j]];
}
new_vec[i] = sum;
}
free(vec);
return reinterpret_cast<T2 *>(new_vec);
}
} // namespace sparse
} // namespace mindquantum
#endif // MINDQUANTUM_SPARSE_ALGO_H_
|
com4.c | #include <mpi.h>
extern int local_cell_blocks;
extern int local_edge_blocks;
#include "grid.h"
#include "memory.h"
#include "component.h"
#include "io.h"
#include <stdint.h>
void com4_init(GRID * g);
void com4_compute(GRID * g);
void com4_io(GRID * g);
double com4_flops(GRID * g);
double com4_memory(GRID * g);
uint64_t com4_checksum(GRID *);
void com4_cleanup(GRID * g);
void grad(GRID * g);
void O6precIndxDb(GRID * g);
void O7precIndxNb(GRID * g);
void O8ind(GRID * g);
GVAL *restrict * restrict * restrict gv_precInd;
int *restrict t6Blk;
int *restrict t6Ver;
int *restrict t6Ind;
int *restrict t7Blk;
int *restrict t7Ind;
struct {
char *name;
int loc;
int dim;
union {
GVAL *restrict * restrict p2;
GVAL *restrict * restrict * restrict p3;
} data_pointer;
} *gv_o8param[3];
struct {
char *name;
int loc;
int dim;
union {
GVAL *restrict * restrict p2;
GVAL *restrict * restrict * restrict p3;
} data_pointer;
} *gv_o8par2;
struct {
char *name;
int loc;
int dim;
union {
GVAL *restrict * restrict p2;
GVAL *restrict * restrict * restrict p3;
} data_pointer;
} *gv_o8var;
io_var_t io_gv_precInd;
io_var_t io_gv_o8var;
MODEL_COMPONENT com4 = { 0, com4_init, com4_compute, com4_io, com4_flops, com4_memory, com4_checksum, com4_cleanup };
void init_opO6(GRID * g)
{
t6Blk = malloc((g->eBlkCnt * g->height * g->blkSize) * sizeof(int));
t6Ver = malloc((g->eBlkCnt * g->height * g->blkSize) * sizeof(int));
t6Ind = malloc((g->eBlkCnt * g->height * g->blkSize) * sizeof(int));
{
size_t min_block = g->mpi_rank == (0) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? 0 % (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : 0;
size_t max_block = g->mpi_rank < (0) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) || g->mpi_rank > (g->eBlkCnt - 1) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? 0 : g->mpi_rank == (g->eBlkCnt - 1) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? g->eBlkCnt % (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? g->eBlkCnt % (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size);
#pragma omp parallel for
for (size_t block_index = (min_block); block_index < (max_block); block_index++) {
for (size_t height_index = (0); height_index < (g->height); height_index++) {
for (size_t edge_index = (0); edge_index < (g->blkSize); edge_index++) {
t6Blk[block_index * g->height * g->blkSize + height_index * g->blkSize + edge_index] = block_index;
t6Ver[block_index * g->height * g->blkSize + height_index * g->blkSize + edge_index] = height_index;
t6Ind[block_index * g->height * g->blkSize + height_index * g->blkSize + edge_index] = edge_index;
}
}
}
}
int eb, ee;
#pragma omp parallel for
for (int b = 0; b < g->eBlkCnt; b++) {
get_indices_e(g, b, &eb, &ee);
for (int k = 0; k < g->height; k++) {
for (int e = eb; e < ee; e++) {
t6Blk[b * g->height * g->blkSize + k * ee + e] = b;
t6Ver[b * g->height * g->blkSize + k * ee + e] = k;
t6Ind[b * g->height * g->blkSize + k * ee + e] = e;
}
}
}
}
void init_opO7(GRID * g)
{
t7Blk = malloc((g->edgeCount) * sizeof(int));
t7Ind = malloc((g->edgeCount) * sizeof(int));
{
size_t min_block = g->mpi_rank == (0) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? 0 % (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : 0;
size_t max_block = g->mpi_rank < (0) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) || g->mpi_rank > (g->eBlkCnt - 1) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? 0 : g->mpi_rank == (g->eBlkCnt - 1) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? g->eBlkCnt % (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? g->eBlkCnt % (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size);
#pragma omp parallel for
for (size_t block_index = (min_block); block_index < (max_block); block_index++) {
for (size_t edge_index = (0); edge_index < (g->blkSize); edge_index++) {
t7Blk[block_index * g->blkSize + edge_index] = block_index;
t7Ind[block_index * g->blkSize + edge_index] = edge_index;
}
}
}
}
extern MODEL_COMPONENT com1;
void com4_init(GRID * g)
{
com4.loaded = 1;
if (!com1.loaded)
com1.init(g);
gv_precInd = (GVAL * restrict * restrict * restrict) allocate_variable(g, GRID_POS_EDGE, GRID_DIM_3D, sizeof(GVAL));
init_opO6(g);
init_opO7(g);
for (int i = 0; i < 3; i++) {
int num_blocks = local_cell_blocks ? local_cell_blocks : (((g->cBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size);
gv_o8param[i] = malloc(24);
gv_o8param[i]->name = "gv_o8param[ i]";
gv_o8param[i]->loc = 0;
gv_o8param[i]->dim = 2;
gv_o8param[i]->data_pointer.p2 = malloc((num_blocks * g->blkSize) * sizeof(GVAL) + (num_blocks) * sizeof(char *));
char *pos = (char *) gv_o8param[i]->data_pointer.p2 + num_blocks * sizeof(char *);
for (int b = 0; b < num_blocks; b++) {
gv_o8param[i]->data_pointer.p2[b] = (GVAL *) pos;
pos += g->blkSize * sizeof(GVAL);
for (int c = 0; c < g->blkSize; c++) {
gv_o8param[i]->data_pointer.p2[b][c] = (GVAL) 0;
}
}
}
{
int num_blocks = local_cell_blocks ? local_cell_blocks : (((g->cBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size);
gv_o8par2 = malloc(24);
gv_o8par2->name = "gv_o8par2";
gv_o8par2->loc = 0;
gv_o8par2->dim = 3;
gv_o8par2->data_pointer.p3 = malloc((num_blocks * g->height * g->blkSize) * sizeof(GVAL) + (num_blocks * g->height) * sizeof(char *) + (num_blocks) * sizeof(char *));
char *pos = (char *) gv_o8par2->data_pointer.p3 + num_blocks * sizeof(char *);
char *pos2 = (char *) gv_o8par2->data_pointer.p3 + num_blocks * sizeof(char *) + num_blocks * g->height * sizeof(char *);
for (int b = 0; b < num_blocks; b++) {
gv_o8par2->data_pointer.p3[b] = (GVAL * *)pos;
pos += g->height * sizeof(char *);
for (int k = 0; k < g->height; k++) {
gv_o8par2->data_pointer.p3[b][k] = (GVAL *) pos2;
pos2 += g->blkSize * sizeof(GVAL);
for (int c = 0; c < g->blkSize; c++) {
gv_o8par2->data_pointer.p3[b][k][c] = (GVAL) 0;
}
}
}
}
{
int num_blocks = local_cell_blocks ? local_cell_blocks : (((g->cBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size);
gv_o8var = malloc(24);
gv_o8var->name = "gv_o8var";
gv_o8var->loc = 0;
gv_o8var->dim = 3;
gv_o8var->data_pointer.p3 = malloc((num_blocks * g->height * g->blkSize) * sizeof(GVAL) + (num_blocks * g->height) * sizeof(char *) + (num_blocks) * sizeof(char *));
char *pos = (char *) gv_o8var->data_pointer.p3 + num_blocks * sizeof(char *);
char *pos2 = (char *) gv_o8var->data_pointer.p3 + num_blocks * sizeof(char *) + num_blocks * g->height * sizeof(char *);
for (int b = 0; b < num_blocks; b++) {
gv_o8var->data_pointer.p3[b] = (GVAL * *)pos;
pos += g->height * sizeof(char *);
for (int k = 0; k < g->height; k++) {
gv_o8var->data_pointer.p3[b][k] = (GVAL *) pos2;
pos2 += g->blkSize * sizeof(GVAL);
for (int c = 0; c < g->blkSize; c++) {
gv_o8var->data_pointer.p3[b][k][c] = (GVAL) 0;
}
}
}
}
io_read_register(g, "gv_o8param0", (GVAL *) gv_o8param[0], FLOAT32, FLOAT32, GRID_POS_CELL, GRID_DIM_2D);
io_read_register(g, "gv_o8param1", (GVAL *) gv_o8param[1], FLOAT32, FLOAT32, GRID_POS_CELL, GRID_DIM_2D);
io_read_register(g, "gv_o8param2", (GVAL *) gv_o8param[2], FLOAT32, FLOAT32, GRID_POS_CELL, GRID_DIM_2D);
io_read_register(g, "gv_o8par2", (GVAL *) gv_o8par2, FLOAT32, FLOAT32, GRID_POS_CELL, GRID_DIM_3D);
io_write_define(g, "gv_precInd", (GVAL *) gv_precInd, FLOAT32, GRID_POS_EDGE, GRID_DIM_3D, &io_gv_precInd);
io_write_define(g, "gv_o8var", (GVAL *) gv_o8var, FLOAT32, GRID_POS_CELL, GRID_DIM_3D, &io_gv_o8var);
}
void com4_compute(GRID * g)
{
grad(g);
O6precIndxDb(g);
O7precIndxNb(g);
O8ind(g);
}
void com4_io(GRID * g)
{
io_write_announce(g, &io_gv_precInd);
io_write_announce(g, &io_gv_o8var);
}
double com4_flops(GRID * g)
{
double flop = (double) g->edgeCount * (double) g->height + (double) g->edgeCount * (double) g->height + (double) g->edgeCount * (double) g->height + 14.0 * (double) g->cellCount * (double) (g->height - 1) + 20.0 * (double) g->cellCount;
return flop;
}
double com4_memory(GRID * g)
{
double mem = ((double) g->edgeCount * (double) g->height + 3.0 * (double) g->cellCount + (double) g->cellCount * (double) g->height + (double) g->cellCount * (double) g->height) * (double) sizeof(GVAL) + (3.0 * (double) g->eBlkCnt * (double) g->height * (double) g->blkSize + 2.0 * (double) g->edgeCount) * (double) sizeof(int);
return mem / (1024 * 1024);
}
uint64_t com4_checksum(GRID * g)
{
uint64_t ret = 0;
{
size_t min_block = g->mpi_rank == (0) / (((g->cBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? 0 % (((g->cBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : 0;
size_t max_block = g->mpi_rank < (0) / (((g->cBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) || g->mpi_rank > (g->cBlkCnt - 1) / (((g->cBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? 0 : g->mpi_rank == (g->cBlkCnt - 1) / (((g->cBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? g->cBlkCnt % (((g->cBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? g->cBlkCnt % (((g->cBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : (((g->cBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : (((g->cBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size);
#pragma omp parallel for
for (size_t block_index = (min_block); block_index < (max_block); block_index++) {
for (size_t height_index = (0); height_index < (g->height); height_index++) {
for (size_t cell_index = (0); cell_index < (g->blkSize); cell_index++) {
ret += (uint64_t) gv_o8var->data_pointer.p3[(block_index)][(height_index)][(cell_index)];
}
}
}
}
return ret;
}
void com4_cleanup(GRID * g)
{
com4.loaded = 0;
deallocate_variable((void *) gv_precInd, g, GRID_POS_EDGE, GRID_DIM_3D, sizeof(GVAL));
free((void *) t6Blk);
free((void *) t6Ver);
free((void *) t6Ind);
free((void *) t7Blk);
free((void *) t7Ind);
for (int i = 0; i < 3; i++)
free((void *) gv_o8param[i]->data_pointer.p2);
free((void *) gv_o8par2->data_pointer.p3);
free((void *) gv_o8var->data_pointer.p3);
}
|
collinear-list_gpu.c | /*
This program checks the collinearity of points.
It receives an input a vector with points and returns the mathematical
functions that pass these points. It have a list to store answers.
This program create a csv file with the time execution results for each
function(CPU,GPU) in this format: size of vector, cpu with list time, gpu
with list time.
Author: Gleison Souza Diniz Mendon?a
Date: 04-05-2015
version 2.0
Run:
folder_ipmacc/ipmacc folder_archive/colinear_v2.c
./a.out
*/
#include "BenchmarksUtil.h"
#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
#ifdef RUN_TEST
#define SIZE 1024
#elif RUN_BENCHMARK
#define SIZE 1024 * 16
#else
#define SIZE 1024
#endif
#define PERCENT_DIFF_ERROR_THRESHOLD 0.05
typedef struct point {
int x;
int y;
} point;
point *points;
void generate_points() {
int i;
for (i = 0; i < SIZE; i++) {
points[i].x = (i * 777) % 11;
points[i].y = (i * 777) % 13;
}
}
/// colinear list algorithm GPU
/// N = size of vector
int colinear_list_points_GPU() {
int val = 0;
int *parallel_lines = (int *)malloc(sizeof(int) * SIZE);
for (int i = 0; i < SIZE; i++) {
parallel_lines[i] = 0;
}
#pragma omp target map(to : points[ : SIZE]) \
map(tofrom : parallel_lines[ : SIZE]) device(DEVICE_ID)
{
#pragma omp parallel for collapse(1)
for (int i = 0; i < SIZE; ++i) {
for (int j = 0; j < SIZE; j++) {
for (int k = 0; k < SIZE; k++) {
/// to understand if is colinear points
int slope_coefficient, linear_coefficient;
int ret;
ret = 0;
slope_coefficient = points[j].y - points[i].y;
if ((points[j].x - points[i].x) != 0) {
slope_coefficient = slope_coefficient / (points[j].x - points[i].x);
linear_coefficient =
points[i].y - (points[i].x * slope_coefficient);
if (slope_coefficient != 0 && linear_coefficient != 0 &&
points[k].y ==
(points[k].x * slope_coefficient) + linear_coefficient) {
ret = 1;
}
}
if (ret == 1) {
parallel_lines[(i & (SIZE - 1))] = 1;
}
}
}
}
}
val = 0;
for (int i = 0; i < SIZE; i++) {
if (parallel_lines[i] == 1) {
val = 1;
break;
}
}
free(parallel_lines);
return val;
}
int colinear_list_points_CPU() {
int i, j, k, val;
val = 0;
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
for (k = 0; k < SIZE; k++) {
/// to understand if is colinear points
int slope_coefficient, linear_coefficient;
int ret;
ret = 0;
slope_coefficient = points[j].y - points[i].y;
if ((points[j].x - points[i].x) != 0) {
slope_coefficient = slope_coefficient / (points[j].x - points[i].x);
linear_coefficient = points[i].y - (points[i].x * slope_coefficient);
if (slope_coefficient != 0 && linear_coefficient != 0 &&
points[k].y ==
(points[k].x * slope_coefficient) + linear_coefficient) {
ret = 1;
}
}
/// to list add
if (ret == 1) {
val = 1;
}
}
}
}
return val;
}
int compareResults(int A, int A_outputFromGpu) {
int i, j, fail;
fail = 0;
if (A != A_outputFromGpu)
fail = 1;
// Print results
printf("Non-Matching CPU-GPU Outputs Beyond Error Threshold of %4.2f "
"Percent: %d\n",
PERCENT_DIFF_ERROR_THRESHOLD, fail);
return fail;
}
int main(int argc, char *argv[]) {
double t_start, t_end;
int fail = 0;
int result_CPU, result_GPU;
fprintf(stdout, "<< Collinear List >>\n");
points = (point *)malloc(sizeof(points) * SIZE);
generate_points();
t_start = rtclock();
result_GPU = colinear_list_points_GPU();
t_end = rtclock();
fprintf(stdout, "GPU Runtime: %0.6lfs\n", t_end - t_start);
#ifdef RUN_TEST
t_start = rtclock();
result_CPU = colinear_list_points_CPU();
t_end = rtclock();
fprintf(stdout, "CPU Runtime: %0.6lfs\n", t_end - t_start);
fail = compareResults(result_GPU, result_CPU);
#endif
free(points);
return fail;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.