source
stringlengths 3
92
| c
stringlengths 26
2.25M
|
|---|---|
GrB_Descriptor_wait.c
|
//------------------------------------------------------------------------------
// GrB_Descriptor_wait: wait for a user-defined GrB_Descriptor to complete
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// In SuiteSparse:GraphBLAS, a user-defined GrB_Descriptor has no pending
// operations to wait for. All this method does is verify that the descriptor
// is properly initialized, and then it does an OpenMP flush. Note that unlike
// other methods, passing in a NULL pointer, or a pointer to a NULL descriptor
// is valid, since a NULL descriptor results in default settings.
#include "GB.h"
GrB_Info GrB_Descriptor_wait // no work, just check if GrB_Descriptor is valid
(
GrB_Descriptor desc,
GrB_WaitMode waitmode
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
GB_WHERE1 ("GrB_Descriptor_wait (desc, waitmode)") ;
if (desc != NULL) GB_RETURN_IF_FAULTY (desc) ;
//--------------------------------------------------------------------------
// return result
//--------------------------------------------------------------------------
#pragma omp flush
return (GrB_SUCCESS) ;
}
|
GB_binop__rminus_fc64.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__rminus_fc64)
// A.*B function (eWiseMult): GB (_AemultB_08__rminus_fc64)
// A.*B function (eWiseMult): GB (_AemultB_02__rminus_fc64)
// A.*B function (eWiseMult): GB (_AemultB_04__rminus_fc64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__rminus_fc64)
// A*D function (colscale): GB (_AxD__rminus_fc64)
// D*A function (rowscale): GB (_DxB__rminus_fc64)
// C+=B function (dense accum): GB (_Cdense_accumB__rminus_fc64)
// C+=b function (dense accum): GB (_Cdense_accumb__rminus_fc64)
// C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__rminus_fc64)
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__rminus_fc64)
// C=scalar+B GB (_bind1st__rminus_fc64)
// C=scalar+B' GB (_bind1st_tran__rminus_fc64)
// C=A+scalar GB (_bind2nd__rminus_fc64)
// C=A'+scalar GB (_bind2nd_tran__rminus_fc64)
// C type: GxB_FC64_t
// A type: GxB_FC64_t
// A pattern? 0
// B type: GxB_FC64_t
// B pattern? 0
// BinaryOp: cij = GB_FC64_minus (bij, aij)
#define GB_ATYPE \
GxB_FC64_t
#define GB_BTYPE \
GxB_FC64_t
#define GB_CTYPE \
GxB_FC64_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_FC64_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_FC64_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_FC64_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_FC64_minus (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_RMINUS || GxB_NO_FC64 || GxB_NO_RMINUS_FC64)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB (_Cdense_ewise3_accum__rminus_fc64)
(
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__rminus_fc64)
(
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__rminus_fc64)
(
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__rminus_fc64)
(
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_FC64_t
GxB_FC64_t bwork = (*((GxB_FC64_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__rminus_fc64)
(
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_FC64_t *restrict Cx = (GxB_FC64_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__rminus_fc64)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GxB_FC64_t *restrict Cx = (GxB_FC64_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__rminus_fc64)
(
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_FC64_t alpha_scalar ;
GxB_FC64_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((GxB_FC64_t *) alpha_scalar_in)) ;
beta_scalar = (*((GxB_FC64_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__rminus_fc64)
(
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__rminus_fc64)
(
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__rminus_fc64)
(
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__rminus_fc64)
(
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__rminus_fc64)
(
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_FC64_t *Cx = (GxB_FC64_t *) Cx_output ;
GxB_FC64_t x = (*((GxB_FC64_t *) x_input)) ;
GxB_FC64_t *Bx = (GxB_FC64_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_FC64_t bij = GBX (Bx, p, false) ;
Cx [p] = GB_FC64_minus (bij, x) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__rminus_fc64)
(
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_FC64_t *Cx = (GxB_FC64_t *) Cx_output ;
GxB_FC64_t *Ax = (GxB_FC64_t *) Ax_input ;
GxB_FC64_t y = (*((GxB_FC64_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
GxB_FC64_t aij = GBX (Ax, p, false) ;
Cx [p] = GB_FC64_minus (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_FC64_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_FC64_minus (aij, x) ; \
}
GrB_Info GB (_bind1st_tran__rminus_fc64)
(
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_FC64_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GxB_FC64_t x = (*((const GxB_FC64_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
GxB_FC64_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_FC64_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_FC64_minus (y, aij) ; \
}
GrB_Info GB (_bind2nd_tran__rminus_fc64)
(
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_FC64_t y = (*((const GxB_FC64_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
NonlocalMarching_Inpaint_core.c
|
/*
* This work is part of the Core Imaging Library developed by
* Visual Analytics and Imaging System Group of the Science Technology
* Facilities Council, STFC
*
* Copyright 2017 Daniil Kazantsev
* Copyright 2017 Srikanth Nagella, Edoardo Pasca
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "NonlocalMarching_Inpaint_core.h"
#include "utils.h"
/* C-OMP implementation of Nonlocal Vertical Marching inpainting method (2D case)
* The method is heuristic but computationally efficent (especially for larger images).
* It developed specifically to smoothly inpaint horizontal or inclined missing data regions in sinograms
* The method WILL not work satisfactory if you have lengthy vertical stripes of missing data
*
* Input:
* 1. 2D image or sinogram with horizontal or inclined regions of missing data
* 2. Mask of the same size as A in 'unsigned char' format (ones mark the region to inpaint, zeros belong to the data)
* 3. Linear increment to increase searching window size in iterations, values from 1-3 is a good choice
*
* Output:
* 1. Inpainted image or a sinogram
* 2. updated mask
*
* Reference: D. Kazantsev (paper in preparation)
*/
float NonlocalMarching_Inpaint_main(float *Input, unsigned char *M, float *Output, unsigned char *M_upd, int SW_increment, int iterationsNumb, int trigger, int dimX, int dimY, int dimZ)
{
int i, j, i_m, j_m, counter, iter, iterations_number, W_fullsize, switchmask, switchcurr, counterElements;
float *Gauss_weights;
/* copying M to M_upd */
copyIm_unchar(M, M_upd, dimX, dimY, 1);
/* Copying the image */
copyIm(Input, Output, dimX, dimY, 1);
/* Find how many inpainting iterations (equal to the number of ones) required based on a mask */
if (iterationsNumb == 0) {
iterations_number = 0;
for (i=0; i<dimY*dimX; i++) {
if (M[i] == 1) iterations_number++;
}
if ((int)(iterations_number/dimY) > dimX) iterations_number = dimX;
}
else iterations_number = iterationsNumb;
if (iterations_number == 0) printf("%s \n", "Nothing to inpaint, zero mask!");
else {
printf("%s %i \n", "Max iteration number equals to:", iterations_number);
/* Inpainting iterations run here*/
int W_halfsize = 1;
for(iter=0; iter < iterations_number; iter++) {
//if (mod (iter, 2) == 0) {W_halfsize += 1;}
// printf("%i \n", W_halfsize);
/* pre-calculation of Gaussian distance weights */
W_fullsize = (int)(2*W_halfsize + 1); /*full size of similarity window */
Gauss_weights = (float*)calloc(W_fullsize*W_fullsize,sizeof(float ));
counter = 0;
for(i_m=-W_halfsize; i_m<=W_halfsize; i_m++) {
for(j_m=-W_halfsize; j_m<=W_halfsize; j_m++) {
Gauss_weights[counter] = exp(-(pow((i_m), 2) + pow((j_m), 2))/(2*W_halfsize*W_halfsize));
counter++;
}
}
if (trigger == 0) {
/*Matlab*/
#pragma omp parallel for shared(Output, M_upd, Gauss_weights) private(i, j, switchmask, switchcurr)
for(j=0; j<dimY; j++) {
switchmask = 0;
for(i=0; i<dimX; i++) {
switchcurr = 0;
if ((M_upd[j*dimX + i] == 1) && (switchmask == 0)) {
/* perform inpainting of the current pixel */
inpaint_func(Output, M_upd, Gauss_weights, i, j, dimX, dimY, W_halfsize, W_fullsize);
/* add value to the mask*/
M_upd[j*dimX + i] = 0;
switchmask = 1; switchcurr = 1;
}
if ((M_upd[j*dimX + i] == 0) && (switchmask == 1) && (switchcurr == 0)) {
/* perform inpainting of the previous (i-1) pixel */
inpaint_func(Output, M_upd, Gauss_weights, i-1, j, dimX, dimY, W_halfsize, W_fullsize);
/* add value to the mask*/
M_upd[(j)*dimX + i-1] = 0;
switchmask = 0;
}
}
}
}
else {
/*Python*/
/* find a point in the mask to inpaint */
#pragma omp parallel for shared(Output, M_upd, Gauss_weights) private(i, j, switchmask, switchcurr)
for(i=0; i<dimX; i++) {
switchmask = 0;
for(j=0; j<dimY; j++) {
switchcurr = 0;
if ((M_upd[j*dimX + i] == 1) && (switchmask == 0)) {
/* perform inpainting of the current pixel */
inpaint_func(Output, M_upd, Gauss_weights, i, j, dimX, dimY, W_halfsize, W_fullsize);
/* add value to the mask*/
M_upd[j*dimX + i] = 0;
switchmask = 1; switchcurr = 1;
}
if ((M_upd[j*dimX + i] == 0) && (switchmask == 1) && (switchcurr == 0)) {
/* perform inpainting of the previous (j-1) pixel */
inpaint_func(Output, M_upd, Gauss_weights, i, j-1, dimX, dimY, W_halfsize, W_fullsize);
/* add value to the mask*/
M_upd[(j-1)*dimX + i] = 0;
switchmask = 0;
}
}
}
}
free(Gauss_weights);
/* check if possible to terminate iterations earlier */
counterElements = 0;
for(i=0; i<dimX*dimY; i++) if (M_upd[i] == 0) counterElements++;
if (counterElements == dimX*dimY) {
printf("%s \n", "Padding completed!");
break;
}
W_halfsize += SW_increment;
}
printf("%s %i \n", "Iterations stopped at:", iter);
}
return *Output;
}
float inpaint_func(float *U, unsigned char *M_upd, float *Gauss_weights, int i, int j, int dimX, int dimY, int W_halfsize, int W_fullsize)
{
int i1, j1, i_m, j_m, counter;
float sum_val, sumweight;
/*method 1: inpainting based on Euclidian weights */
sumweight = 0.0f;
counter = 0; sum_val = 0.0f;
for(i_m=-W_halfsize; i_m<=W_halfsize; i_m++) {
i1 = i+i_m;
for(j_m=-W_halfsize; j_m<=W_halfsize; j_m++) {
j1 = j+j_m;
if (((i1 >= 0) && (i1 < dimX)) && ((j1 >= 0) && (j1 < dimY))) {
if (M_upd[j1*dimX + i1] == 0) {
sumweight += Gauss_weights[counter];
}
}
counter++;
}
}
counter = 0; sum_val = 0.0f;
for(i_m=-W_halfsize; i_m<=W_halfsize; i_m++) {
i1 = i+i_m;
for(j_m=-W_halfsize; j_m<=W_halfsize; j_m++) {
j1 = j+j_m;
if (((i1 >= 0) && (i1 < dimX)) && ((j1 >= 0) && (j1 < dimY))) {
if ((M_upd[j1*dimX + i1] == 0) && (sumweight != 0.0f)) {
/* we have data so add it with Euc weight */
sum_val += (Gauss_weights[counter]/sumweight)*U[j1*dimX + i1];
}
}
counter++;
}
}
U[j*dimX + i] = sum_val;
return *U;
}
|
conversions.h
|
#ifndef CONVERSIONS_H
#define CONVERSIONS_H
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include "omp.h"
#include "loewner_declaration.h"
#include "morph_color_matrix.h"
/*
*============================================================================================================================================
* Class that contains methods for performing conversions between different image formats.
* Algorithms for conversions are following the paper An approach to color-morphology based on Einstein addition and Loewner order by
* Bernhard Burgeth and Andreas Kleefeld.
*
* Current version is implemented to perform conversions in parallel using OpenMP, with the number of threads predefined by user.
*
* version: 1.0
* author: Filip Srnec
*============================================================================================================================================
*/
#ifndef PI
#define PI 3.141592653589793
#endif
#ifndef KAPPA
#define KAPPA 0.707106781186547
#endif
#ifndef RGB_MAX
#define RGB_MAX 255.0
#endif
#ifndef INTENSITY_ALPHA
#define INTENSITY_ALPHA 10
#endif
#ifndef INTENSITY_FACTOR
#define INTENSITY_FACTOR ((T) RGB_MAX / INTENSITY_ALPHA)
#endif
#ifndef HUE_TRESHOLD
#define HUE_TRESHOLD 0.5
#endif
class LoewnerMorphology::Conversions {
private:
// Helper method for finding a minimum among 3 values. T must have operator <.
template<typename T>
static T min3(T a, T b, T c);
// Helper method for finding a maximum among 3 values. T must have operator >.
template<typename T>
static T max3(T a, T b, T c);
// Helper method that converts hue values to rgb values
template<typename T>
static T hueToRgb(T p, T q, T t);
public:
/*
* Performs a conversion from RGB-value image to M-HCL-value image. RGB values should be stored
* on memory locations r, g and b respectively. Result will be stored on locations h, c and l.
* All memory should be previously allocated. Argument size is the size of the initial image (width * height).
*/
template<typename T>
static void rgb2mhcl(const T *r, const T *g, const T *b, T *h, T *c, T *l, int size);
/*
* Performs a conversion from M-HCL-value image to RGB-value image. H, C and L values should be stored on memory locations
* r, g and b respectively. Result will be stored on locations r, g and b. All memory should be previously allocated.
* Argument size is the size of the initial image (width * height).
*/
template<typename T>
static void mhcl2rgb(const T *h, const T *c, const T *l, T *r, T *g, T *b, int size);
/*
* Converts the image vector containing M-HCL values to the vector containing
* MorphColorMatrix objects. Memory for the new vector needs to be allocated and passed
* as a vector argument. It should be array of MorphColorMatrix values which size is equal
* as the size of the image. Pointers h, c and l are the pointers to the values
* of the hue, chroma and luminance.
*/
template<typename T>
static void mhcl2matrix(const T *h, const T *c, const T *l, LoewnerMorphology::MorphColorMatrix *vector, int size);
/*
* Converts the vector containing MorphColorMatrix objects to M-HCL values. Memory for the new vectors needs
* to be allocated and passed as a h,c and l arguments. Size of each destination pointer must be equal
* to the size of the image. Pointers h, c and l are the pointers to the values of the hue, chroma and
* lightness for the given image.
*/
template<typename T>
static void matrix2mhcl(const LoewnerMorphology::MorphColorMatrix *vector, T *h, T *c, T *l, int size);
/*
* Converts image array of values of type T to the image array of double values. It is assumed that conversion is legal. Memory for both arrays must be allocated
* before entering the method.
*/
template<typename T>
static void type2double(const T *imgType, double *imgDouble, int size);
/*
* Converts image array of double values to the image array of values of type T. It is assumed that conversion is legal. Memory for both arrays should be allocated
* before entering the method.
*/
template<typename T>
static void double2type(const double *imgDouble, T *imgType, int size);
};
// IMPLEMENTATION
template<typename T>
T LoewnerMorphology::Conversions::min3(T a, T b, T c) {
if (a < b) {
if (a < c) {
return a;
} else {
return (b < c) ? b : c;
}
} else {
if (b < c) {
return b;
} else {
return (a < c) ? a : c;
}
}
}
template<typename T>
T LoewnerMorphology::Conversions::max3(T a, T b, T c) {
if (a > b) {
if (a > c) {
return a;
} else {
return (b > c) ? b : c;
}
} else {
if (b > c) {
return b;
} else {
return (a > c) ? a : c;
}
}
}
template<typename T>
void LoewnerMorphology::Conversions::rgb2mhcl(const T *r, const T *g, const T *b, T *h, T *c, T *l, int size) {
#pragma omp parallel for
for (int i = 0; i < size; i++) {
T r1 = r[i] / RGB_MAX;
T g1 = g[i] / RGB_MAX;
T b1 = b[i] / RGB_MAX;
T cMax = max3(r1, g1, b1);
T cMin = min3(r1, g1, b1);
T delta = cMax - cMin;
if (delta == 0) {
h[i] = 0;
} else if (cMax == r1) {
h[i] = ((g1 - b1) / delta) + (g1 < b1 ? 6.0 : 0.0);
} else if (cMax == g1) {
h[i] = (2 + ((b1 - r1) / delta));
} else {
h[i] = (4 + ((r1 - g1) / delta));
}
if (h[i] < 0) {
h[i] += 1;
}
h[i] /= 6.0;
c[i] = delta;
l[i] = cMin + cMax - 1;
}
}
template<typename T>
T LoewnerMorphology::Conversions::hueToRgb(T p, T q, T t) {
if (t < 0)
t += 1;
if (t > 1)
t -= 1;
if (t < (T) 1 / 6)
return p + (q - p) * 6 * t;
if (t < (T) 1 / 2)
return q;
if (t < (T) 2 / 3)
return p + (q - p) * ((T) 2 / 3 - t) * 6;
return p;
}
template<typename T>
void LoewnerMorphology::Conversions::mhcl2rgb(const T *h, const T *c, const T *l, T *r, T *g, T *b, int size) {
#pragma omp parallel for
for (int i = 0; i < size; i++) {
T delta = c[i];
T l_val = (l[i] + 1) / 2;
T s_val = (delta < 1e-4) ? 0 : delta / (1 - abs(l[i]));
T q = (l_val < 0.5) ? (l_val * (1 + s_val)) : (l_val + s_val - (l_val * s_val));
T p = 2 * l_val - q;
r[i] = round(hueToRgb(p, q, h[i] + (T) 1 / 3) * RGB_MAX);
g[i] = round(hueToRgb(p, q, h[i]) * RGB_MAX);
b[i] = round(hueToRgb(p, q, h[i] - (T) 1 / 3) * RGB_MAX);
}
}
template<typename T>
void LoewnerMorphology::Conversions::mhcl2matrix(const T *h, const T *c, const T *l, LoewnerMorphology::MorphColorMatrix *vector, int size) {
#pragma omp parallel for
for (int i = 0; i < size; i++) {
T hv = h[i];
T cv = c[i];
T z = l[i];
T value = 2 * PI * hv;
T x = cv * cos(value);
T y = cv * sin(value);
LoewnerMorphology::MorphColorMatrix temp;
temp.a = KAPPA * (z - y);
temp.b = KAPPA * x;
temp.c = KAPPA * (z + y);
vector[i] = temp;
}
}
template<typename T>
void LoewnerMorphology::Conversions::matrix2mhcl(const LoewnerMorphology::MorphColorMatrix *vector, T *h, T *c, T *l, int size) {
#pragma omp parallel for
for (int i = 0; i < size; i++) {
LoewnerMorphology::MorphColorMatrix temp = vector[i];
T x = 2 * KAPPA * temp.b;
T y = KAPPA * (temp.c - temp.a);
T z = KAPPA * (temp.c + temp.a);
T at = atan2(y, x);
if (at < 0) {
at = at + 2 * PI;
}
h[i] = at / (2 * PI);
c[i] = sqrt(x * x + y * y);
l[i] = z;
}
}
template<typename T>
void LoewnerMorphology::Conversions::type2double(const T *imgOriginal, double *imgDouble, int size) {
#pragma omp parallel for
for (int i = 0; i < size; i++) {
imgDouble[i] = (double)imgOriginal[i];
}
}
template<typename T>
void LoewnerMorphology::Conversions::double2type(const double *imgDouble, T *imgType, int size) {
#pragma omp parallel for
for (int i = 0; i < size; i++) {
imgType[i] = (T)imgDouble[i];
}
}
#endif
|
GB_unop__identity_int16_int64.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_int16_int64
// op(A') function: GB_unop_tran__identity_int16_int64
// C type: int16_t
// A type: int64_t
// cast: int16_t cij = (int16_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
int64_t
#define GB_CTYPE \
int16_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
int16_t z = (int16_t) aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
int64_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
int16_t z = (int16_t) 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_INT16 || GxB_NO_INT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__identity_int16_int64
(
int16_t *Cx, // Cx and Ax may be aliased
const int64_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 (int64_t), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
int64_t aij = Ax [p] ;
int16_t z = (int16_t) 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 ;
int64_t aij = Ax [p] ;
int16_t z = (int16_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_int16_int64
(
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
|
sections-3.c
|
// { dg-do compile }
extern void bar (void);
int main (void)
{
#pragma omp parallel sections nowait /* { dg-error "'nowait'" } */
{
#pragma omp section
{ bar(); }
#pragma omp section
{ bar(); }
}
}
|
GB_unaryop__minv_uint8_fp32.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_uint8_fp32
// op(A') function: GB_tran__minv_uint8_fp32
// C type: uint8_t
// A type: float
// cast: uint8_t cij ; GB_CAST_UNSIGNED(cij,aij,8)
// unaryop: cij = GB_IMINV_UNSIGNED (aij, 8)
#define GB_ATYPE \
float
#define GB_CTYPE \
uint8_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
float aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = GB_IMINV_UNSIGNED (x, 8) ;
// casting
#define GB_CASTING(z, x) \
uint8_t z ; GB_CAST_UNSIGNED(z,x,8) ;
// 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_UINT8 || GxB_NO_FP32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__minv_uint8_fp32
(
uint8_t *restrict Cx,
const float *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_uint8_fp32
(
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_binop__plus_int16.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__plus_int16)
// A.*B function (eWiseMult): GB (_AemultB_08__plus_int16)
// A.*B function (eWiseMult): GB (_AemultB_02__plus_int16)
// A.*B function (eWiseMult): GB (_AemultB_04__plus_int16)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__plus_int16)
// A*D function (colscale): GB (_AxD__plus_int16)
// D*A function (rowscale): GB (_DxB__plus_int16)
// C+=B function (dense accum): GB (_Cdense_accumB__plus_int16)
// C+=b function (dense accum): GB (_Cdense_accumb__plus_int16)
// C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__plus_int16)
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__plus_int16)
// C=scalar+B GB (_bind1st__plus_int16)
// C=scalar+B' GB (_bind1st_tran__plus_int16)
// C=A+scalar GB (_bind2nd__plus_int16)
// C=A'+scalar GB (_bind2nd_tran__plus_int16)
// C type: int16_t
// A type: int16_t
// A pattern? 0
// B type: int16_t
// B pattern? 0
// BinaryOp: cij = (aij + bij)
#define GB_ATYPE \
int16_t
#define GB_BTYPE \
int16_t
#define GB_CTYPE \
int16_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
int16_t aij = GBX (Ax, pA, A_iso)
// 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) \
int16_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) \
int16_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = (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_PLUS || GxB_NO_INT16 || GxB_NO_PLUS_INT16)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB (_Cdense_ewise3_accum__plus_int16)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__plus_int16)
(
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__plus_int16)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__plus_int16)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type int16_t
int16_t bwork = (*((int16_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__plus_int16)
(
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
int16_t *restrict Cx = (int16_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__plus_int16)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t *restrict Cx = (int16_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__plus_int16)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool 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) ;
int16_t alpha_scalar ;
int16_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((int16_t *) alpha_scalar_in)) ;
beta_scalar = (*((int16_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__plus_int16)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_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__plus_int16)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__plus_int16)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_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__plus_int16)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__plus_int16)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t *Cx = (int16_t *) Cx_output ;
int16_t x = (*((int16_t *) x_input)) ;
int16_t *Bx = (int16_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
int16_t bij = GBX (Bx, p, false) ;
Cx [p] = (x + bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__plus_int16)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
int16_t *Cx = (int16_t *) Cx_output ;
int16_t *Ax = (int16_t *) Ax_input ;
int16_t y = (*((int16_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
int16_t aij = GBX (Ax, p, false) ;
Cx [p] = (aij + y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int16_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x + aij) ; \
}
GrB_Info GB (_bind1st_tran__plus_int16)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
int16_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t x = (*((const int16_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
int16_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int16_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij + y) ; \
}
GrB_Info GB (_bind2nd_tran__plus_int16)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t y = (*((const int16_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
protocol.h
|
#ifndef __PROTOCOL_H_
#define __PROTOCOL_H_
#include "gwasiter.h"
#include "mpc.h"
#include "util.h"
#include <vector>
#include <NTL/mat_ZZ_p.h>
#include <NTL/mat_ZZ.h>
#include <NTL/ZZ.h>
#include <NTL/BasicThreadPool.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <chrono>
using namespace NTL;
using namespace std;
using msec = chrono::milliseconds;
using get_time = chrono::steady_clock;
#define ABS(a) (((a)<0)?-(a):(a))
auto clock_start = get_time::now();
auto clock_start2 = get_time::now();
void tic() {
clock_start = get_time::now();
}
void tick() {
clock_start2 = get_time::now();
}
int toc() {
auto clock_end = get_time::now();
int duration = chrono::duration_cast<msec>(clock_end - clock_start).count();
cout << "Elapsed time is " << duration / 1000.0 << " secs" << endl;
return duration;
}
int tock() {
auto clock_end2 = get_time::now();
int duration = chrono::duration_cast<msec>(clock_end2 - clock_start2).count();
cout << "Elapsed time is " << duration / 1000.0 << " secs" << endl;
return duration;
}
bool DecrComp(const pair<int, double> &a, const pair<int, double> &b) {
return a.second > b.second;
}
string cache(int pid, string desc) {
ostringstream oss;
oss << Param::CACHE_FILE_PREFIX[Param::CUR_ROUND] << "_" << desc << ".bin";
return oss.str();
}
string cache(int pid, int index, string desc) {
ostringstream oss;
oss << Param::CACHE_FILE_PREFIX[index] << "_" << desc << ".bin";
return oss.str();
}
string cache(int pid, int index, int chunk_id, string desc) {
ostringstream oss;
oss << Param::CACHE_FILE_PREFIX[index] << "_" << chunk_id << "_" << desc << ".bin";
return oss.str();
}
string cache(int pid, int index) {
ostringstream oss;
oss << Param::CACHE_FILE_PREFIX[Param::CUR_ROUND] << "_" << index << ".bin";
return oss.str();
}
string outname(string desc) {
ostringstream oss;
oss << Param::OUTPUT_FILE_PREFIX << "_" << desc << ".txt";
return oss.str();
}
bool logireg_protocol(MPCEnv& mpc, int pid) {
SetNumThreads(Param::NUM_THREADS);
cout << AvailableThreads() << " threads created" << endl;
int ntop = 100;
// need to update logireg_protocol function to be compatible with multiple input datasets
int n0 = Param::NUM_INDS[Param::CUR_ROUND];
int m0 = Param::NUM_SNPS;
int k = Param::NUM_DIM_TO_REMOVE;
cout << "n0: " << n0 << ", " << "m0: " << m0 << endl;
// Shared variables
string s;
fstream fs;
ofstream ofs;
ifstream ifs;
streampos strpos;
int ind;
Vec<ZZ_p> tmp_vec;
Mat<ZZ_p> tmp_mat;
//mpc.ProfilerPushState("main");
ZZ_p fp_one = DoubleToFP(1, Param::NBIT_K, Param::NBIT_F);
Vec<ZZ_p> pheno;
Init(pheno, n0);
Mat<ZZ_p> cov;
Init(cov, n0, Param::NUM_COVS);
if (!exists(cache(pid, "input_geno")) || !exists(cache(pid, "input_pheno_cov"))) {
cout << "Initial data sharing results not found:" << endl;
cout << "\t" << cache(pid, "input_geno") << endl;
cout << "\t" << cache(pid, "input_pheno_cov") << endl;
return false;
}
cout << "Initial data sharing results found" << endl;
ifs.open(cache(pid, "input_pheno_cov").c_str(), ios::binary);
mpc.ReadFromFile(pheno, ifs, n0);
mpc.ReadFromFile(cov, ifs, n0, Param::NUM_COVS);
ifs.close();
cout << "Phenotypes and covariates loaded" << endl;
Vec<ZZ_p> gkeep1;
Init(gkeep1, m0);
cout << "Using locus missing rate filter from a previous run" << endl;
if (pid == 2) {
ifs.open(outname("gkeep1").c_str());
for (int i = 0; i < m0; i++) {
ifs >> gkeep1[i];
}
ifs.close();
mpc.SendVec(gkeep1, 0);
mpc.SendVec(gkeep1, 1);
} else {
mpc.ReceiveVec(gkeep1, 2, m0);
}
uint m1 = conv<uint>(Sum(gkeep1));
cout << "n0: " << n0 << ", " << "m1: " << m1 << endl;
Vec<ZZ_p> ikeep;
Init(ikeep, n0);
cout << "Using individual missing rate/het rate filters from a previous run" << endl;
if (pid == 2) {
ifs.open(outname("ikeep").c_str());
for (int i = 0; i < n0; i++) {
ifs >> ikeep[i];
}
ifs.close();
mpc.SendVec(ikeep, 0);
mpc.SendVec(ikeep, 1);
} else {
mpc.ReceiveVec(ikeep, 2, n0);
}
uint n1 = conv<uint>(Sum(ikeep));
cout << "n1: " << n1 << ", " << "m1: " << m1 << endl;
cout << "Filtering phenotypes and covariates" << endl;
mpc.Filter(pheno, ikeep, n1);
mpc.FilterRows(cov, ikeep, n1);
Vec<ZZ_p> gkeep2;
Init(gkeep2, m1);
cout << "Using MAF/HWE filters from a previous run" << endl;
if (pid == 2) {
ifs.open(outname("gkeep2").c_str());
for (int i = 0; i < m1; i++) {
ifs >> gkeep2[i];
}
ifs.close();
mpc.SendVec(gkeep2, 0);
mpc.SendVec(gkeep2, 1);
} else {
mpc.ReceiveVec(gkeep2, 2, m1);
}
uint m2 = conv<uint>(Sum(gkeep2));
cout << "n1: " << n1 << ", " << "m2: " << m2 << endl;
cout << "Using CA statistics from a previous run" << endl;
Vec<ZZ_p> gkeep3;
Init(gkeep3, m2);
if (pid == 2) {
vector<pair<int, double> > cavec(m2);
ifs.open(outname("assoc").c_str());
double val;
for (int i = 0; i < m2; i++) {
ifs >> val;
cavec[i] = make_pair(i, val * val);
}
ifs.close();
sort(cavec.begin(), cavec.end(), DecrComp);
cout << "Selected top " << ntop << " candidates" << endl;
cout << "Top 5 CA stats: " << cavec[0].second;
for (int i = 1; i < 5; i++) {
cout << ", " << cavec[i].second;
}
cout << endl;
for (int i = 0; i < ntop; i++) {
gkeep3[cavec[i].first] = 1;
}
mpc.SendVec(gkeep3, 0);
mpc.SendVec(gkeep3, 1);
} else {
mpc.ReceiveVec(gkeep3, 2, m2);
}
Mat<ZZ_p> V;
Init(V, k, n1);
cout << "Using eigenvectors from a previous run" << endl;
ifs.open(cache(pid, "eigen").c_str(), ios::binary);
mpc.ReadFromFile(V, ifs, k, n1);
ifs.close();
// Concatenate covariate matrix and jointly orthogonalize
mpc.Transpose(cov);
V.SetDims(k + Param::NUM_COVS, n1);
if (pid > 0) {
for (int i = 0; i < Param::NUM_COVS; i++) {
V[k + i] = cov[i] * fp_one;
}
}
cov.kill();
mpc.OrthonormalBasis(V, V);
Vec<ZZ_p> V_mean;
Init(V_mean, V.NumRows());
ZZ_p fp_denom = DoubleToFP(1 / ((double) V.NumCols()), Param::NBIT_K, Param::NBIT_F);
for (int i = 0; i < V_mean.length(); i++) {
V_mean[i] = Sum(V[i]) * fp_denom;
}
mpc.Trunc(V_mean);
for (int i = 0; i < V_mean.length(); i++) {
AddScalar(V[i], -V_mean[i]);
}
Vec<ZZ_p> V_var;
mpc.InnerProd(V_var, V);
mpc.Trunc(V_var);
V_var *= fp_denom;
mpc.Trunc(V_var);
Vec<ZZ_p> V_stdinv, dummy_vec;
mpc.FPSqrt(dummy_vec, V_stdinv, V_var);
for (int i = 0; i < V_mean.length(); i++) {
mpc.MultMat(V[i], V[i], V_stdinv[i]);
}
mpc.Trunc(V);
Vec<bool> gkeep;
gkeep.SetLength(m0);
for (int j = 0; j < m0; j++) {
gkeep[j] = gkeep1[j] == 1;
}
ind = 0;
for (int j = 0; j < m0; j++) {
if (gkeep[j]) {
gkeep[j] = gkeep2[ind] == 1;
ind++;
}
}
ind = 0;
for (int j = 0; j < m0; j++) {
if (gkeep[j]) {
gkeep[j] = gkeep3[ind] == 1;
ind++;
}
}
Mat<ZZ_p> X, X_mask;
if (exists(cache(pid, "logi_input"))) {
cout << "logi_input cache found" << endl;
ifs.open(cache(pid, "logi_input").c_str(), ios::in | ios::binary);
mpc.BeaverReadFromFile(X, X_mask, ifs, ntop, n1);
ifs.close();
} else {
X.SetDims(n1, ntop);
X_mask.SetDims(n1, ntop);
ifs.open(cache(pid, "input_geno").c_str(), ios::binary);
if (pid > 0) {
mpc.ImportSeed(10, ifs);
} else {
for (int p = 1; p <= 2; p++) {
mpc.ImportSeed(10 + p, ifs);
}
}
cout << "Collecting genotypes for top candidates" << endl;
ind = -1;
int batch_size = n1 / 10;
tic();
for (int cur = 0; cur < n1; cur++) {
ind++;
if ((cur + 1) % batch_size == 0 || cur == n1 - 1) {
cout << cur + 1 << "/" << n1 << ", "; toc();
tic();
}
Mat<ZZ_p> g0, g0_mask;
Vec<ZZ_p> miss0, miss0_mask;
while (ikeep[ind] != 1) {
if (pid > 0) {
mpc.SkipData(ifs, 3, m0); // g
mpc.SkipData(ifs, m0); // miss
mpc.SwitchSeed(10);
mpc.RandMat(g0_mask, 3, m0);
mpc.RandVec(miss0_mask, m0);
mpc.RestoreSeed();
} else {
for (int p = 1; p <= 2; p++) {
mpc.SwitchSeed(10 + p);
mpc.RandMat(g0_mask, 3, m0);
mpc.RandVec(miss0_mask, m0);
mpc.RestoreSeed();
}
}
ind++;
}
if (pid > 0) {
mpc.ReadFromFile(g0, ifs, 3, m0); // g
mpc.ReadFromFile(miss0, ifs, m0); // miss
mpc.SwitchSeed(10);
mpc.RandMat(g0_mask, 3, m0);
mpc.RandVec(miss0_mask, m0);
mpc.RestoreSeed();
} else {
Init(g0, 3, m0);
Init(g0_mask, 3, m0);
Init(miss0, m0);
Init(miss0_mask, m0);
for (int p = 1; p <= 2; p++) {
mpc.SwitchSeed(10 + p);
mpc.RandMat(tmp_mat, 3, m0);
mpc.RandVec(tmp_vec, m0);
mpc.RestoreSeed();
g0_mask += tmp_mat;
miss0_mask += tmp_vec;
}
}
Mat<ZZ_p> g, g_mask;
Vec<ZZ_p> miss, miss_mask;
g.SetDims(3, ntop);
miss.SetLength(ntop);
g_mask.SetDims(3, ntop);
miss_mask.SetLength(ntop);
int ind2 = 0;
for (int j = 0; j < m0; j++) {
if (gkeep[j]) {
for (int k = 0; k < 3; k++) {
g[k][ind2] = g0[k][j];
g_mask[k][ind2] = g0_mask[k][j];
}
miss[ind2] = miss0[j];
miss_mask[ind2] = miss0_mask[j];
ind2++;
}
}
X[cur] = g[1] + 2 * g[2];
X_mask[cur] = g_mask[1] + 2 * g_mask[2];
}
mpc.Transpose(X); // ntop-by-n1
transpose(X_mask, X_mask);
fs.open(cache(pid, "logi_input").c_str(), ios::out | ios::binary);
mpc.BeaverWriteToFile(X, X_mask, fs);
fs.close();
}
// Shuffle
Mat<ZZ_p> xrt, xmt;
transpose(xrt, X);
transpose(xmt, X_mask);
transpose(V, V);
Vec<long> indices;
indices.SetLength(n1);
for (int i = 0; i < n1; i++) {
indices[i] = i + 1;
}
mpc.SwitchSeed(-1);
for (int i = 0; i < n1-1; i++) {
long chosen = mpc.RandBnd(n1-i);
Vec<ZZ_p> tmp;
if (chosen > 0) {
tmp = xrt[i];
xrt[i] = xrt[i + chosen];
xrt[i + chosen] = tmp;
tmp = xmt[i];
xmt[i] = xmt[i + chosen];
xmt[i + chosen] = tmp;
tmp = V[i];
V[i] = V[i + chosen];
V[i + chosen] = tmp;
ZZ_p tmpy;
tmpy = pheno[i];
pheno[i] = pheno[i + chosen];
pheno[i + chosen] = tmpy;
long t = indices[i];
indices[i] = indices[i + chosen];
indices[i + chosen] = t;
}
}
mpc.RestoreSeed();
transpose(X, xrt);
transpose(X_mask, xmt);
transpose(V, V);
xrt.kill();
xmt.kill();
Mat<ZZ_p> V_mask;
mpc.BeaverPartition(V_mask, V);
Vec<ZZ_p> pheno_mask;
mpc.BeaverPartition(pheno_mask, pheno);
Vec<ZZ_p> b0;
Mat<ZZ_p> bv;
Vec<ZZ_p> bx;
mpc.ParallelLogisticRegression(b0, bv, bx, X, X_mask, V, V_mask, pheno, pheno_mask, 500);
fs.open(cache(pid, "logireg_final_coeff").c_str(), ios::out | ios::binary);
if (pid > 0) {
mpc.WriteToFile(b0, fs);
mpc.WriteToFile(bv, fs);
mpc.WriteToFile(bx, fs);
}
fs.close();
mpc.RevealSym(bx);
if (pid == 2) {
Vec<double> bx_double;
FPToDouble(bx_double, bx, Param::NBIT_K, Param::NBIT_F);
ofs.open(outname("logi_coeff").c_str(), ios::out);
for (int i = 0; i < bx_double.length(); i++) {
ofs << bx_double[i] << endl;
}
ofs.close();
cout << "Result written to " << outname("logi_coeff") << endl;
}
return true;
}
bool data_sharing_protocol(MPCEnv& mpc, int pid, int n, int chunk_id) {
cout << "n: " << n << endl;
fstream fs;
Vec<ZZ_p> pheno;
Init(pheno, n);
Mat<ZZ_p> cov;
Init(cov, n, Param::NUM_COVS);
fs.open(cache(pid, Param::CUR_ROUND, chunk_id, "input_geno").c_str(), ios::out | ios::binary);
if (pid > 0) {
mpc.ExportSeed(fs, 0);
} else {
for (int p = 1; p <= 2; p++) {
mpc.ExportSeed(fs, p);
}
}
GwasIterator git(mpc, pid);
git.Init(true, true);
long bsize = n / 10;
cout << "Begin processing:" << endl;
tic();
for (int i = 0; i < n; i++) {
Mat<ZZ_p> g;
Vec<ZZ_p> miss, p;
git.GetNextGMP(g, miss, p);
if (pid > 0) {
pheno[i] = p[0];
for (int j = 0; j < Param::NUM_COVS; j++) {
cov[i][j] = p[1 + j];
}
}
// In practice this would be done in one batch
Mat<ZZ_p> g_mask;
Vec<ZZ_p> miss_mask;
mpc.BeaverPartition(g_mask, g);
mpc.BeaverPartition(miss_mask, miss);
if (pid > 0) {
// Note: g_mask and miss_mask can be recovered from PRG and
// need not be written
mpc.WriteToFile(g, fs);
mpc.WriteToFile(miss, fs);
}
if ((i + 1) % bsize == 0 || i == n - 1) {
cout << "\t" << i+1 << " / " << n << ", "; toc(); tic();
}
}
git.Terminate();
fs.close();
cout << "Finished writing Beaver partitioned genotype data" << endl;
if (Param::DEBUG) {
cout << "pheno" << endl;
mpc.Print(pheno, 5);
cout << "cov" << endl;
mpc.Print(cov[0], 5);
}
fs.open(cache(pid, Param::CUR_ROUND, chunk_id, "input_pheno_cov").c_str(), ios::out | ios::binary);
mpc.WriteToFile(pheno, fs);
mpc.WriteToFile(cov, fs);
fs.close();
cout << "Finished writing phenotype and covariate data" << endl;
return true;
}
bool gwas_protocol(MPCEnv& mpc, int pid) {
if (Param::NUM_THREADS > 1) {
SetNumThreads(Param::NTL_NUM_THREADS);
cout << AvailableThreads() << " threads created for NTL" << endl;
}
int n0 = 0; // total number of individuals across datasets
for (int i = 0; i < Param::NUM_INDS.size(); i++) {
n0 += Param::NUM_INDS[i];
}
int m0 = Param::NUM_SNPS;
int k = Param::NUM_DIM_TO_REMOVE;
int kp = k + Param::NUM_OVERSAMPLE;
cout << "n0: " << n0 << ", " << "m0: " << m0 << endl;
// Shared variables
string s;
fstream fs;
ofstream ofs;
ifstream ifs;
streampos strpos;
int ind;
Vec<ZZ_p> tmp_vec;
Mat<ZZ_p> tmp_mat;
int num_datasets = Param::NUM_INDS.size();
int num_threads = Param::NUM_THREADS;
mpc.ProfilerPushState("main");
// Read in SNP list
Vec<ZZ> snp_pos;
Init(snp_pos, m0);
ifs.open(Param::SNP_POS_FILE.c_str());
if (!ifs.is_open()) {
cout << "Could not open SNP_POS_FILE: " << Param::SNP_POS_FILE << endl;
return false;
}
for (int i = 0; i < m0; i++) {
long chrom, pos;
ifs >> chrom >> pos;
snp_pos[i] = ZZ(chrom) * 1e9 + ZZ(pos);
}
ifs.close();
/* Useful constants */
ZZ_p two(2), twoinv;
inv(twoinv, two);
ZZ_p fp_one = DoubleToFP(1, Param::NBIT_K, Param::NBIT_F);
Vec<ZZ_p> pheno;
Init(pheno, n0);
Mat<ZZ_p> cov;
Init(cov, n0, Param::NUM_COVS);
// check that values for every chunk of data exists in the cache
for (int i = 0; i < num_datasets; i++) {
if (!exists(cache(pid, i, "input_geno")) || !exists(cache(pid, i, "input_pheno_cov"))) {
cout << "Initial data sharing results not found:" << endl;
cout << "\t" << cache(pid, i, "input_geno") << endl;
cout << "\t" << cache(pid, i, "input_pheno_cov") << endl;
return false;
}
}
cout << "Initial data sharing results found" << endl;
// read phenotype and covariate data across chunks in parallel and consolidate into single vector/matrix
#pragma omp parallel for num_threads(num_threads)
for (int i = 0; i < num_datasets; i++) {
long offset = 0;
for (int j = 0; j < i; j++) {
offset += Param::NUM_INDS[j];
}
long inner_n0 = Param::NUM_INDS[i];
// avoid error by re-setting the modulus within each thread
ZZ base_p = conv<ZZ>(Param::BASE_P.c_str());
ZZ_p::init(base_p);
ifstream inner_ifs;
inner_ifs.open(cache(pid, i, "input_pheno_cov").c_str(), ios::binary);
Vec<ZZ_p> sub_pheno;
Init(sub_pheno, inner_n0);
mpc.ReadFromFile(sub_pheno, inner_ifs, inner_n0);
for (int j = 0; j < inner_n0; j++) {
pheno[offset + j] = sub_pheno[j];
}
Mat<ZZ_p> sub_cov;
Init(sub_cov, inner_n0, Param::NUM_COVS);
mpc.ReadFromFile(sub_cov, inner_ifs, inner_n0, Param::NUM_COVS);
for (int j = 0; j < inner_n0; j++) {
cov[offset + j] = sub_cov[j];
}
inner_ifs.close();
}
cout << "Phenotypes and covariates loaded" << endl;
if (Param::DEBUG) {
cout << "pheno" << endl;
mpc.Print(pheno, 5);
cout << "cov" << endl;
mpc.Print(cov[0], 5);
}
mpc.ProfilerPushState("qc");
mpc.ProfilerPushState("snp_miss");
Vec<ZZ_p> gkeep1;
Init(gkeep1, m0);
if (Param::SKIP_QC) {
for (int i = 0; i < m0; i++) {
gkeep1[i] = 1;
}
cout << "Locus missing rate filter skipped" << endl;
} else {
bool history;
if (pid == 2) {
history = exists(outname("gkeep1"));
mpc.SendBool(history, 0);
mpc.SendBool(history, 1);
} else {
// ask P2 if gkeep1 has been computed before
history = mpc.ReceiveBool(2);
}
if (history) {
cout << "Using locus missing rate filter from a previous run" << endl;
if (pid == 2) {
ifs.open(outname("gkeep1").c_str());
for (int i = 0; i < m0; i++) {
ifs >> gkeep1[i];
}
ifs.close();
mpc.SendVec(gkeep1, 0);
mpc.SendVec(gkeep1, 1);
} else {
mpc.ReceiveVec(gkeep1, 2, m0);
}
} else {
Vec<ZZ_p> gmiss;
Init(gmiss, m0);
if (exists(cache(pid, "gmiss"))) {
cout << "Locus missing rate cache found" << endl;
ifs.open(cache(pid, "gmiss").c_str(), ios::binary);
mpc.ReadFromFile(gmiss, ifs, m0);
ifs.close();
} else {
cout << "Taking a pass to calculate locus missing rates:" << endl; tick();
if (pid > 0) {
// Loop over all datasets/chunks to calculate missing rate across all individuals
#pragma omp parallel for num_threads(num_threads)
for (int i = 0; i < num_datasets; i++) {
long inner_n0 = Param::NUM_INDS[i];
// keep track of intermediate results to minimize number of (costly) atomic updates
Vec<ZZ_p> inner_gmiss;
Init(inner_gmiss, m0);
// avoid error by re-setting the modulus within each thread
ZZ base_p = conv<ZZ>(Param::BASE_P.c_str());
ZZ_p::init(base_p);
ifstream inner_ifs;
inner_ifs.open(cache(pid, i, "input_geno").c_str(), ios::binary);
mpc.ImportSeed(10, inner_ifs);
long bsize = inner_n0 / 10;
tic();
for (int j = 0; j < inner_n0; j++) {
Vec<ZZ_p> miss, miss_mask;
Mat<ZZ_p> skip_mat;
// Load stored Beaver partition
mpc.SwitchSeed(10);
mpc.RandMat(skip_mat, 3, m0); // g_mask
mpc.RandVec(miss_mask, m0);
mpc.RestoreSeed();
if (pid == 2) {
mpc.SkipData(inner_ifs, 3, m0);
mpc.ReadFromFile(miss, inner_ifs, m0);
}
// Recover secret shares from Beaver partition
if (pid == 1) {
miss = miss_mask;
} else {
miss += miss_mask;
}
inner_gmiss += miss;
if ((j + 1) % bsize == 0 || j == inner_n0 - 1) {
cout << "\t" << j+1 << " / " << inner_n0 << ", "; toc(); tic();
}
}
inner_ifs.close();
// Update global gmiss - this operation must be atomic
#pragma omp critical ( gmiss_update )
gmiss += inner_gmiss;
}
}
tock();
fs.open(cache(pid, "gmiss").c_str(), ios::out | ios::binary);
mpc.WriteToFile(gmiss, fs);
fs.close();
cout << "Wrote results to cache" << endl;
}
if (Param::DEBUG) {
cout << "gmiss" << endl;
mpc.Print(gmiss, 5);
}
cout << "Locus missing rate filter ... " << endl; tic();
ZZ_p gmiss_ub = ZZ_p((long) (n0 * Param::GMISS_UB));
mpc.LessThanPublic(gkeep1, gmiss, gmiss_ub);
cout << "done. "; toc();
mpc.RevealSym(gkeep1);
if (pid == 2) {
mpc.SendVec(gkeep1, 0);
} else if (pid == 0) {
mpc.ReceiveVec(gkeep1, 2, m0);
}
if (pid == 2) {
ofs.open(outname("gkeep1").c_str());
for (int i = 0; i < gkeep1.length(); i++) {
ofs << gkeep1[i] << endl;
}
ofs.close();
}
}
}
uint m1 = conv<uint>(Sum(gkeep1));
cout << "n0: " << n0 << ", " << "m1: " << m1 << endl;
cout << "Filtering SNP position vector ... " << endl; tic();
FilterVec(snp_pos, gkeep1);
cout << "done. "; toc();
mpc.ProfilerPopState(true); // snp_miss
mpc.ProfilerPushState("ind_miss/het");
Vec<ZZ_p> ikeep;
Init(ikeep, n0);
if (Param::SKIP_QC) {
for (int i = 0; i < n0; i++) {
ikeep[i] = 1;
}
cout << "Individual missing rate/het rate filters skipped" << endl;
} else {
bool history;
if (pid == 2) {
history = exists(outname("ikeep"));
mpc.SendBool(history, 0);
mpc.SendBool(history, 1);
} else {
// ask P2 if ikeep has been computed before
history = mpc.ReceiveBool(2);
}
if (history) {
cout << "Using individual missing rate/het rate filters from a previous run" << endl;
if (pid == 2) {
ifs.open(outname("ikeep").c_str());
for (int i = 0; i < n0; i++) {
ifs >> ikeep[i];
}
ifs.close();
mpc.SendVec(ikeep, 0);
mpc.SendVec(ikeep, 1);
} else {
mpc.ReceiveVec(ikeep, 2, n0);
}
} else {
Vec<ZZ_p> imiss, ihet;
Init(imiss, n0);
Init(ihet, n0);
if (exists(cache(pid, "imiss_ihet"))) {
cout << "Individual missing rate and het rate cache found" << endl;
ifs.open(cache(pid, "imiss_ihet").c_str(), ios::binary);
mpc.ReadFromFile(imiss, ifs, n0);
mpc.ReadFromFile(ihet, ifs, n0);
ifs.close();
} else {
cout << "Taking a pass to calculate individual missing rates and het rates:" << endl; tick();
mpc.ProfilerPushState("data_scan");
if (pid > 0) {
// Loop over all datasets/chunks to calculate individual missing/heterozygous rate for all individuals
#pragma omp parallel for num_threads(num_threads)
for (int i = 0; i < num_datasets; i++) {
long offset = 0;
for (int j = 0; j < i; j++) {
offset += Param::NUM_INDS[j];
}
long inner_n0 = Param::NUM_INDS[i];
// avoid error by re-setting the modulus within each thread
ZZ base_p = conv<ZZ>(Param::BASE_P.c_str());
ZZ_p::init(base_p);
ifstream inner_ifs;
inner_ifs.open(cache(pid, i, "input_geno").c_str(), ios::binary);
mpc.ImportSeed(10, inner_ifs);
long bsize = inner_n0 / 10;
tic();
for (int j = 0; j < inner_n0; j++) {
Mat<ZZ_p> g, g_mask;
Vec<ZZ_p> miss, miss_mask;
// Load stored Beaver partition
mpc.SwitchSeed(10);
mpc.RandMat(g_mask, 3, m0);
mpc.RandVec(miss_mask, m0);
mpc.RestoreSeed();
if (pid == 2) {
mpc.ReadFromFile(g, inner_ifs, 3, m0);
mpc.ReadFromFile(miss, inner_ifs, m0);
}
// Recover secret shares from Beaver partition
if (pid == 1) {
g = g_mask;
miss = miss_mask;
} else {
g += g_mask;
miss += miss_mask;
}
// Add to running sum
for (int k = 0; k < m0; k++) {
if (gkeep1[k] == 1) {
imiss[offset + j] += miss[k];
ihet[offset + j] += g[1][k];
}
}
if ((j + 1) % bsize == 0 || j == inner_n0 - 1) {
cout << "\t" << j+1 << " / " << inner_n0 << ", "; toc(); tic();
}
}
inner_ifs.close();
}
}
tock();
fs.open(cache(pid, "imiss_ihet").c_str(), ios::out | ios::binary);
mpc.WriteToFile(imiss, fs);
mpc.WriteToFile(ihet, fs);
fs.close();
cout << "Wrote results to cache" << endl;
mpc.ProfilerPopState(false); // data_scan
}
mpc.ProfilerPushState("miss_filt");
// Individual missingness filter
cout << "Individual missing rate filter ... "; tic();
ZZ_p imiss_ub = ZZ_p((long) (m1 * Param::IMISS_UB));
mpc.LessThanPublic(ikeep, imiss, imiss_ub);
cout << "done. "; toc();
mpc.ProfilerPopState(true); // miss_filt
mpc.ProfilerPushState("het_filt");
// Individual heterozygosity filter
cout << "Individual heterozygosity rate filter ... "; tic();
ZZ_p ihet_ub_frac = DoubleToFP(Param::HET_UB, Param::NBIT_K, Param::NBIT_F);
ZZ_p ihet_lb_frac = DoubleToFP(Param::HET_LB, Param::NBIT_K, Param::NBIT_F);
// Number of observed SNPs per individual
Vec<ZZ_p> m1_obs;
Init(m1_obs, n0);
if (pid > 0) {
for (int i = 0; i < n0; i++) {
m1_obs[i] = -imiss[i];
if (pid == 1) {
m1_obs[i] += m1;
}
}
}
Vec<ZZ_p> ihet_ub, ihet_lb;
Init(ihet_ub, n0);
Init(ihet_lb, n0);
if (pid > 0) {
for (int i = 0; i < n0; i++) {
ihet_ub[i] = m1_obs[i] * ihet_ub_frac;
ihet_lb[i] = m1_obs[i] * ihet_lb_frac;
ihet[i] *= fp_one;
}
}
Vec<ZZ_p> het_filt;
mpc.LessThan(het_filt, ihet, ihet_ub);
mpc.NotLessThan(tmp_vec, ihet, ihet_lb);
mpc.MultElem(het_filt, het_filt, tmp_vec);
mpc.MultElem(ikeep, ikeep, het_filt);
het_filt.kill();
cout << "done. "; toc();
mpc.ProfilerPopState(true); // het_filt
// Reveal samples to be filtered
mpc.RevealSym(ikeep);
if (pid == 2) {
mpc.SendVec(ikeep, 0);
} else if (pid == 0) {
mpc.ReceiveVec(ikeep, 2, n0);
}
if (pid == 2) {
ofs.open(outname("ikeep"));
for (int i = 0; i < ikeep.length(); i++) {
ofs << ikeep[i] << endl;
}
ofs.close();
}
}
}
mpc.ProfilerPopState(true); // ind_miss/het
uint n1 = conv<uint>(Sum(ikeep));
cout << "n1: " << n1 << ", " << "m1: " << m1 << endl;
// Now calculate the "sub" n1 values for each dataset - ie number of individuals kept after filtering for each dataset
vector<long> n1_vec;
long rolling_n0 = 0;
for (int i = 0; i < num_datasets; i++) {
n1_vec.push_back(0);
long sub_n0 = Param::NUM_INDS[i];
for (int j = 0; j < sub_n0; j++) {
if (ikeep[rolling_n0 + j] == 1) {
n1_vec[i] = n1_vec[i] + 1;
}
}
rolling_n0 += sub_n0;
}
cout << "Filtering phenotypes and covariates ... " << endl; tic();
mpc.Filter(pheno, ikeep, n1);
mpc.FilterRows(cov, ikeep, n1);
cout << "done. "; toc();
Vec<ZZ_p> ctrl;
mpc.FlipBit(ctrl, pheno);
Vec<ZZ_p> ctrl_mask;
mpc.BeaverPartition(ctrl_mask, ctrl);
Vec<ZZ_p> dosage_sum;
Vec<ZZ_p> gmiss, gmiss_ctrl, dosage_sum_ctrl;
Mat<ZZ_p> g_count_ctrl;
ZZ_p n1_ctrl(0);
Init(gmiss, m1);
Init(gmiss_ctrl, m1);
Init(dosage_sum, m1);
Init(dosage_sum_ctrl, m1);
Init(g_count_ctrl, 3, m1);
mpc.ProfilerPushState("data_scan");
if (exists(cache(pid, "geno_stats"))) {
cout << "Genotype statistics cache found" << endl;
ifs.open(cache(pid, "geno_stats").c_str(), ios::binary);
mpc.ReadFromFile(gmiss, ifs, m1);
mpc.ReadFromFile(gmiss_ctrl, ifs, m1);
mpc.ReadFromFile(dosage_sum, ifs, m1);
mpc.ReadFromFile(dosage_sum_ctrl, ifs, m1);
mpc.ReadFromFile(g_count_ctrl, ifs, 3, m1);
mpc.ReadFromFile(n1_ctrl, ifs);
ifs.close();
} else {
cout << "Taking a pass to calculate genotype statistics:" << endl; tick();
// reduce batch size to avoid memory issues because of the overhead
// in replicating dosage, g, miss, etc across all threads
long bsize = Param::PITER_BATCH_SIZE / num_threads;
long report_bsize = n1 / 10;
// Loop over all datasets/chunks to calculate genotype statistics over all individuals
#pragma omp parallel for num_threads(num_threads)
for (int dataset_idx = 0; dataset_idx < num_datasets; dataset_idx++) {
// Containers for batching the computation
Vec< Mat<ZZ_p> > g, g_mask;
Mat<ZZ_p> dosage, dosage_mask;
Mat<ZZ_p> miss, miss_mask;
Vec<ZZ_p> ctrl_vec, ctrl_mask_vec;
g.SetLength(3);
g_mask.SetLength(3);
dosage.SetDims(bsize, m1);
dosage_mask.SetDims(bsize, m1);
miss.SetDims(bsize, m1);
miss_mask.SetDims(bsize, m1);
for (int k = 0; k < 3; k++) {
g[k].SetDims(bsize, m1);
g_mask[k].SetDims(bsize, m1);
}
ctrl_vec.SetLength(bsize);
ctrl_mask_vec.SetLength(bsize);
// Containers to store intermediate results for batching (costly) global updates
Vec<ZZ_p> inner_gmiss, inner_gmiss_ctrl, inner_dosage_sum, inner_dosage_sum_ctrl;
Mat<ZZ_p> inner_g_count_ctrl;
ZZ_p inner_n1_ctrl(0);
Init(inner_gmiss, m1);
Init(inner_gmiss_ctrl, m1);
Init(inner_dosage_sum, m1);
Init(inner_dosage_sum_ctrl, m1);
Init(inner_g_count_ctrl, 3, m1);
tic();
ifstream inner_ifs;
inner_ifs.open(cache(pid, dataset_idx, "input_geno").c_str(), ios::binary);
if (pid > 0) {
mpc.ImportSeed(10, inner_ifs);
} else {
for (int p = 1; p <= 2; p++) {
mpc.ImportSeed(10 + p, inner_ifs);
}
}
// avoid error by re-setting the modulus within each thread
ZZ base_p = conv<ZZ>(Param::BASE_P.c_str());
ZZ_p::init(base_p);
// Iterate over this dataset, considering only those individuals who have not been filtered out
long offset = 0;
long inner_ind = -1;
for (int j = 0; j < dataset_idx; j++) {
offset += n1_vec[j];
inner_ind += Param::NUM_INDS[j];
}
long inner_n1 = n1_vec[dataset_idx];
for (int i = 0; i < inner_n1; i++) {
inner_ind++;
mpc.ProfilerPushState("file_io/rng");
Mat<ZZ_p> g0, g0_mask;
Vec<ZZ_p> miss0, miss0_mask;
while (ikeep[inner_ind] != 1) {
if (pid > 0) {
mpc.SkipData(inner_ifs, 3, m0); // g
mpc.SkipData(inner_ifs, m0); // miss
mpc.SwitchSeed(10);
mpc.RandMat(g0_mask, 3, m0);
mpc.RandVec(miss0_mask, m0);
mpc.RestoreSeed();
} else {
for (int p = 1; p <= 2; p++) {
mpc.SwitchSeed(10 + p);
mpc.RandMat(g0_mask, 3, m0);
mpc.RandVec(miss0_mask, m0);
mpc.RestoreSeed();
}
}
inner_ind++;
}
if (pid > 0) {
mpc.ReadFromFile(g0, inner_ifs, 3, m0); // g
mpc.ReadFromFile(miss0, inner_ifs, m0); // miss
mpc.SwitchSeed(10);
mpc.RandMat(g0_mask, 3, m0);
mpc.RandVec(miss0_mask, m0);
mpc.RestoreSeed();
} else {
Init(g0, 3, m0);
Init(g0_mask, 3, m0);
Init(miss0, m0);
Init(miss0_mask, m0);
Vec<ZZ_p> rand_vec;
Mat<ZZ_p> rand_mat;
for (int p = 1; p <= 2; p++) {
mpc.SwitchSeed(10 + p);
mpc.RandMat(rand_mat, 3, m0);
mpc.RandVec(rand_vec, m0);
mpc.RestoreSeed();
g0_mask += rand_mat;
miss0_mask += rand_vec;
}
}
mpc.ProfilerPopState(false); // file_io/rng
// Filter out loci that failed missing rate filter
int inner_ind2 = 0;
for (int j = 0; j < m0; j++) {
if (gkeep1[j] == 1) {
for (int k = 0; k < 3; k++) {
g[k][i % bsize][inner_ind2] = g0[k][j];
g_mask[k][i % bsize][inner_ind2] = g0_mask[k][j];
}
miss[i % bsize][inner_ind2] = miss0[j];
miss_mask[i % bsize][inner_ind2] = miss0_mask[j];
inner_ind2++;
}
}
dosage[i % bsize] = g[1][i % bsize] + 2 * g[2][i % bsize];
dosage_mask[i % bsize] = g_mask[1][i % bsize] + 2 * g_mask[2][i % bsize];
ctrl_vec[i % bsize] = ctrl[i + offset];
ctrl_mask_vec[i % bsize] = ctrl_mask[i + offset];
// Update running sums
if (pid > 0) {
inner_n1_ctrl += ctrl_mask_vec[i % bsize];
inner_gmiss += miss_mask[i % bsize];
inner_dosage_sum += dosage_mask[i % bsize];
if (pid == 1) {
inner_n1_ctrl += ctrl_vec[i % bsize];
inner_gmiss += miss[i % bsize];
inner_dosage_sum += dosage[i % bsize];
}
}
if (i % bsize == bsize - 1 || i == inner_n1 - 1) {
if (i % bsize < bsize - 1) {
int new_bsize = (i % bsize) + 1;
for (int k = 0; k < 3; k++) {
g[k].SetDims(new_bsize, m1);
g_mask[k].SetDims(new_bsize, m1);
}
dosage.SetDims(new_bsize, m1);
dosage_mask.SetDims(new_bsize, m1);
miss.SetDims(new_bsize, m1);
miss_mask.SetDims(new_bsize, m1);
ctrl_vec.SetLength(new_bsize);
ctrl_mask_vec.SetLength(new_bsize);
}
// Update running sums
Vec<ZZ_p> tmp_gmiss_ctrl, tmp_dosage_sum_ctrl;
Mat<ZZ_p> tmp_g_count_ctrl;
Init(tmp_gmiss_ctrl, m1);
Init(tmp_dosage_sum_ctrl, m1);
Init(tmp_g_count_ctrl, 3, m1);
mpc.BeaverMult(tmp_gmiss_ctrl, ctrl_vec, ctrl_mask_vec, miss, miss_mask);
inner_gmiss_ctrl += tmp_gmiss_ctrl;
mpc.BeaverMult(tmp_dosage_sum_ctrl, ctrl_vec, ctrl_mask_vec, dosage, dosage_mask);
inner_dosage_sum_ctrl += tmp_dosage_sum_ctrl;
for (int k = 0; k < 3; k++) {
mpc.BeaverMult(tmp_g_count_ctrl[k], ctrl_vec, ctrl_mask_vec, g[k], g_mask[k]);
inner_g_count_ctrl[k] += tmp_g_count_ctrl[k];
}
}
if (i % report_bsize == 0 || i == inner_n1 - 1) {
cout << "\t" << i << " / " << inner_n1 << ", "; toc(); tic();
}
}
// Update global values - these operations must be atomic
#pragma omp critical ( n1_ctrl_update )
n1_ctrl += inner_n1_ctrl;
#pragma omp critical ( gmiss_update )
gmiss += inner_gmiss;
#pragma omp critical ( dosage_sum_update )
dosage_sum += inner_dosage_sum;
#pragma omp critical ( gmiss_ctrl_update )
gmiss_ctrl += inner_gmiss_ctrl;
#pragma omp critical ( dosage_sum_ctrl_update )
dosage_sum_ctrl += inner_dosage_sum_ctrl;
#pragma omp critical ( g_count_ctrl_update )
g_count_ctrl += inner_g_count_ctrl;
inner_ifs.close();
}
mpc.BeaverReconstruct(gmiss_ctrl);
mpc.BeaverReconstruct(dosage_sum_ctrl);
mpc.BeaverReconstruct(g_count_ctrl);
tock();
// Write to cache
fs.open(cache(pid, "geno_stats").c_str(), ios::out | ios::binary);
mpc.WriteToFile(gmiss, fs);
mpc.WriteToFile(gmiss_ctrl, fs);
mpc.WriteToFile(dosage_sum, fs);
mpc.WriteToFile(dosage_sum_ctrl, fs);
mpc.WriteToFile(g_count_ctrl, fs);
mpc.WriteToFile(n1_ctrl, fs);
fs.close();
cout << "Wrote results to cache" << endl;
}
mpc.ProfilerPopState(true); // data_scan
mpc.ProfilerPushState("maf/hwe");
if (Param::DEBUG) {
cout << "gmiss" << endl;
mpc.Print(gmiss, 5);
cout << "gmiss_ctrl" << endl;
mpc.Print(gmiss_ctrl, 5);
cout << "dosage_sum" << endl;
mpc.Print(dosage_sum, 5);
cout << "dosage_sum_ctrl" << endl;
mpc.Print(dosage_sum_ctrl, 5);
cout << "g_count_ctrl" << endl;
for (int i = 0; i < 3; i++) {
mpc.Print(g_count_ctrl[i], 5);
}
}
mpc.ProfilerPushState("maf");
// SNP MAF filter
cout << "Locus minor allele frequency (MAF) filter ... " << endl; tic();
ZZ_p maf_lb = DoubleToFP(Param::MAF_LB, Param::NBIT_K, Param::NBIT_F);
ZZ_p maf_ub = DoubleToFP(Param::MAF_UB, Param::NBIT_K, Param::NBIT_F);
Vec<ZZ_p> dosage_tot, dosage_tot_ctrl;
if (pid > 0) {
dosage_tot = -gmiss;
dosage_tot_ctrl = -gmiss_ctrl;
mpc.AddPublic(dosage_tot, ZZ_p(n1));
mpc.Add(dosage_tot_ctrl, n1_ctrl);
dosage_tot *= 2;
dosage_tot_ctrl *= 2;
} else {
dosage_tot.SetLength(m1);
dosage_tot_ctrl.SetLength(m1);
}
cout << "done. "; toc();
cout << "Calculating MAFs ... " << endl; tic();
Vec<ZZ_p> maf, maf_ctrl;
if (exists(cache(pid, "maf"))) {
cout << "maf cache found" << endl;
ifs.open(cache(pid, "maf").c_str(), ios::binary);
mpc.ReadFromFile(maf, ifs, dosage_tot.length());
mpc.ReadFromFile(maf_ctrl, ifs, dosage_tot_ctrl.length());
ifs.close();
} else {
mpc.ProfilerPushState("div");
mpc.FPDivParallel(maf, dosage_sum, dosage_tot);
mpc.FPDivParallel(maf_ctrl, dosage_sum_ctrl, dosage_tot_ctrl);
mpc.ProfilerPopState(false); // div
fs.open(cache(pid, "maf").c_str(), ios::out | ios::binary);
mpc.WriteToFile(maf, fs);
mpc.WriteToFile(maf_ctrl, fs);
fs.close();
}
cout << "done. "; toc();
Vec<ZZ_p> Maf, Maf_ctrl; // MAJOR allele freq
if (pid > 0) {
Maf = -maf;
Maf_ctrl = -maf_ctrl;
mpc.AddPublic(Maf, fp_one);
mpc.AddPublic(Maf_ctrl, fp_one);
} else {
Maf.SetLength(m1);
Maf_ctrl.SetLength(m1);
}
// Variance based on Bernoulli distribution over each allele
Vec<ZZ_p> g_var_bern;
mpc.MultElem(g_var_bern, maf, Maf);
mpc.FastTrunc(g_var_bern);
mpc.ProfilerPopState(true); // maf
if (Param::DEBUG) {
cout << "maf" << endl;
mpc.PrintFP(maf, 5);
cout << "maf_ctrl" << endl;
mpc.PrintFP(maf_ctrl, 5);
}
Vec<ZZ_p> gkeep2;
Init(gkeep2, m1);
if (Param::SKIP_QC) {
for (int i = 0; i < m1; i++) {
gkeep2[i] = 1;
}
cout << "SNP MAF/HWE filters skipped" << endl;
} else {
bool history;
if (pid == 2) {
history = exists(outname("gkeep2"));
mpc.SendBool(history, 0);
mpc.SendBool(history, 1);
} else {
// ask P2 if gkeep2 has been computed before
history = mpc.ReceiveBool(2);
}
if (history) {
cout << "Using MAF/HWE filters from a previous run" << endl;
if (pid == 2) {
ifs.open(outname("gkeep2").c_str());
for (int i = 0; i < m1; i++) {
ifs >> gkeep2[i];
}
ifs.close();
mpc.SendVec(gkeep2, 0);
mpc.SendVec(gkeep2, 1);
} else {
mpc.ReceiveVec(gkeep2, 2, m1);
}
} else {
mpc.ProfilerPushState("maf_filt");
cout << "MAF Filter ... "; tic();
mpc.LessThanPublic(gkeep2, maf, maf_ub);
mpc.NotLessThanPublic(tmp_vec, maf, maf_lb);
mpc.MultElem(gkeep2, gkeep2, tmp_vec);
cout << "done. "; toc();
mpc.ProfilerPopState(true); // maf_filt
mpc.ProfilerPushState("hwe_filt");
cout << "Locus Hardy-Weinberg equilibrium (HWE) filter ... " << endl; tic();
ZZ_p hwe_ub = DoubleToFP(Param::HWE_UB, Param::NBIT_K, Param::NBIT_F); // p < 1e-7
// Calculate expected genotype distribution in control group
Mat<ZZ_p> g_exp_ctrl;
Init(g_exp_ctrl, 3, m1);
mpc.MultElem(g_exp_ctrl[0], Maf_ctrl, Maf_ctrl); // AA
mpc.MultElem(g_exp_ctrl[1], Maf_ctrl, maf_ctrl); // Aa
if (pid > 0) {
g_exp_ctrl[1] *= 2;
}
mpc.MultElem(g_exp_ctrl[2], maf_ctrl, maf_ctrl); // aa
for (int i = 0; i < 3; i++) {
mpc.MultElem(g_exp_ctrl[i], g_exp_ctrl[i], dosage_tot_ctrl);
}
g_exp_ctrl *= twoinv; // dosage_tot_ctrl is twice the # individuals we actually want
mpc.FastTrunc(g_exp_ctrl);
cout << "\tCalculated expected genotype counts, "; toc(); tic();
Vec<ZZ_p> hwe_chisq;
Init(hwe_chisq, m1);
if (exists(cache(pid, "hwe"))) {
cout << "HWE cache found" << endl;
ifs.open(cache(pid, "hwe").c_str(), ios::binary);
mpc.ReadFromFile(hwe_chisq, ifs, m1);
ifs.close();
} else {
for (int i = 0; i < 3; i++) {
Vec<ZZ_p> diff;
if (pid > 0) {
diff = fp_one * g_count_ctrl[i] - g_exp_ctrl[i];
} else {
diff.SetLength(m1);
}
mpc.MultElem(diff, diff, diff); // square
mpc.FastTrunc(diff);
mpc.ProfilerPushState("div");
mpc.FPDivParallel(tmp_vec, diff, g_exp_ctrl[i]);
mpc.ProfilerPopState(false); // div
hwe_chisq += tmp_vec;
cout << "\tChi-square test (" << i+1 << "/3), "; toc(); tic();
}
fs.open(cache(pid, "hwe").c_str(), ios::out | ios::binary);
mpc.WriteToFile(hwe_chisq, fs);
fs.close();
}
if (Param::DEBUG) {
cout << "hwe" << endl;
mpc.PrintFP(hwe_chisq, 5);
}
cout << "Applying hwe filter ... " << endl; tic();
Vec<ZZ_p> hwe_filt;
mpc.LessThanPublic(hwe_filt, hwe_chisq, hwe_ub);
mpc.MultElem(gkeep2, gkeep2, hwe_filt);
hwe_filt.kill();
cout << "done. "; toc();
// Reveal which SNPs to discard
mpc.RevealSym(gkeep2);
if (pid == 2) {
mpc.SendVec(gkeep2, 0);
} else if (pid == 0) {
mpc.ReceiveVec(gkeep2, 2, m1);
}
if (pid == 2) {
ofs.open(outname("gkeep2").c_str());
for (int i = 0; i < gkeep2.length(); i++) {
ofs << gkeep2[i] << endl;
}
ofs.close();
}
mpc.ProfilerPopState(true); // hwe_filt
}
}
uint m2 = conv<uint>(Sum(gkeep2));
cout << "n1: " << n1 << ", " << "m2: " << m2 << endl;
cout << "Filtering genotype statistics" << endl; tic();
mpc.Filter(g_var_bern, gkeep2, m2);
mpc.Filter(maf, gkeep2, m2);
FilterVec(snp_pos, gkeep2);
cout << "done. "; toc();
gmiss.kill();
gmiss_ctrl.kill();
dosage_sum.kill();
dosage_sum_ctrl.kill();
g_count_ctrl.kill();
mpc.ProfilerPopState(false); // maf/hwe
mpc.ProfilerPopState(true); // qc
mpc.ProfilerPushState("std_param");
Vec<ZZ_p> g_std_bern_inv;
if (exists(cache(pid, "stdinv_bern"))) {
cout << "Genotype standard deviation cache found" << endl;
ifs.open(cache(pid, "stdinv_bern").c_str(), ios::binary);
mpc.ReadFromFile(g_std_bern_inv, ifs, g_var_bern.length());
ifs.close();
} else {
cout << "Calculating genotype standard deviations (inverse)" << endl; tic();
mpc.ProfilerPushState("sqrt");
mpc.FPSqrtParallel(tmp_vec, g_std_bern_inv, g_var_bern);
mpc.ProfilerPopState(false); // sqrt
cout << "done. "; toc();
fs.open(cache(pid, "stdinv_bern").c_str(), ios::out | ios::binary);
mpc.WriteToFile(g_std_bern_inv, fs);
fs.close();
}
if (Param::DEBUG) {
cout << "g_std_bern_inv" << endl;
mpc.PrintFP(g_std_bern_inv, 5);
}
Vec<ZZ_p> g_mean;
if (pid > 0) {
g_mean = 2 * maf;
} else {
g_mean.SetLength(m2);
}
mpc.ProfilerPopState(true); // std_param
cout << "Starting population stratification analysis" << endl; tic();
mpc.ProfilerPushState("pop_strat");
mpc.ProfilerPushState("select_snp");
Vec<int8_t> selected; // 1 selected, 0 unselected, -1 TBD
Vec<bool> to_process;
selected.SetLength(m2);
to_process.SetLength(m2);
for (int i = 0; i < m2; i++) {
selected[i] = -1;
}
ZZ dist_thres(Param::LD_DIST_THRES);
ZZ prev(-1);
for (int i = 0; i < m2; i++) {
selected[i] = 0;
if (prev < 0 || snp_pos[i] - prev > dist_thres) {
selected[i] = 1;
prev = snp_pos[i];
}
}
// At this point "selected" contains the SNP filter for PCA, shared across all parties
uint32_t m3 = 0;
for (int i = 0; i < selected.length(); i++) {
if (selected[i] == 1) {
m3++;
}
}
cout << "SNP selection complete: " << m3 << " / " << m2 << " selected" << endl; toc();
mpc.ProfilerPopState(false); // select_snp
mpc.ProfilerPushState("reduce_file");
// Cache the reduced G for PCA
if (exists(cache(pid, "pca_input"))) {
cout << "pca_input cache found" << endl;
} else {
Vec<bool> gkeep3;
gkeep3.SetLength(m0);
for (int j = 0; j < m0; j++) {
gkeep3[j] = gkeep1[j] == 1;
}
ind = 0;
for (int j = 0; j < m0; j++) {
if (gkeep3[j]) {
gkeep3[j] = gkeep2[ind] == 1;
ind++;
}
}
ind = 0;
for (int j = 0; j < m0; j++) {
if (gkeep3[j]) {
gkeep3[j] = selected[ind] == 1;
ind++;
}
}
long bsize = n1 / 10;
cout << "Caching input data for PCA:" << endl; tick();
// Loop over all datasets/chunks
#pragma omp parallel for num_threads(num_threads)
for (int dataset_idx = 0; dataset_idx < num_datasets; dataset_idx++) {
tic();
ifstream inner_ifs;
inner_ifs.open(cache(pid, dataset_idx, "input_geno").c_str(), ios::binary);
if (pid > 0) {
mpc.ImportSeed(10, inner_ifs);
} else {
for (int p = 1; p <= 2; p++) {
mpc.ImportSeed(10 + p, inner_ifs);
}
}
// Improve performance by writing the pca data for each chunk to a separate cache file in parallel
fstream inner_fs;
inner_fs.open(cache(pid, dataset_idx, "pca_input").c_str(), ios::out | ios::binary);
// avoid error by re-setting the modulus within each thread
ZZ base_p = conv<ZZ>(Param::BASE_P.c_str());
ZZ_p::init(base_p);
// Iterate over this dataset, considering only those individuals who have not been filtered out
long offset = 0;
long inner_ind = -1;
for (int j = 0; j < dataset_idx; j++) {
offset += n1_vec[j];
inner_ind += Param::NUM_INDS[j];
}
long inner_n1 = n1_vec[dataset_idx];
for (int i = offset; i < offset + inner_n1; i++) {
inner_ind++;
mpc.ProfilerPushState("file_io/rng");
Mat<ZZ_p> g0, g0_mask;
Vec<ZZ_p> miss0, miss0_mask;
while (ikeep[inner_ind] != 1) {
if (pid > 0) {
mpc.SkipData(inner_ifs, 3, m0); // g
mpc.SkipData(inner_ifs, m0); // miss
mpc.SwitchSeed(10);
mpc.RandMat(g0_mask, 3, m0);
mpc.RandVec(miss0_mask, m0);
mpc.RestoreSeed();
} else {
for (int p = 1; p <= 2; p++) {
mpc.SwitchSeed(10 + p);
mpc.RandMat(g0_mask, 3, m0);
mpc.RandVec(miss0_mask, m0);
mpc.RestoreSeed();
}
}
inner_ind++;
}
if (pid > 0) {
mpc.ReadFromFile(g0, inner_ifs, 3, m0); // g
mpc.ReadFromFile(miss0, inner_ifs, m0); // miss
mpc.SwitchSeed(10);
mpc.RandMat(g0_mask, 3, m0);
mpc.RandVec(miss0_mask, m0);
mpc.RestoreSeed();
} else {
Init(g0, 3, m0);
Init(g0_mask, 3, m0);
Init(miss0, m0);
Init(miss0_mask, m0);
Vec<ZZ_p> rand_vec;
Mat<ZZ_p> rand_mat;
for (int p = 1; p <= 2; p++) {
mpc.SwitchSeed(10 + p);
mpc.RandMat(rand_mat, 3, m0);
mpc.RandVec(rand_vec, m0);
mpc.RestoreSeed();
g0_mask += rand_mat;
miss0_mask += rand_vec;
}
}
mpc.ProfilerPopState(false); // file_io/rng
// Filter out loci that failed missing rate filter
Mat<ZZ_p> g, g_mask;
Vec<ZZ_p> miss, miss_mask;
g.SetDims(3, m3);
g_mask.SetDims(3, m3);
miss.SetLength(m3);
miss_mask.SetLength(m3);
int ind2 = 0;
for (int j = 0; j < m0; j++) {
if (gkeep3[j]) {
for (int k = 0; k < 3; k++) {
g[k][ind2] = g0[k][j];
g_mask[k][ind2] = g0_mask[k][j];
}
miss[ind2] = miss0[j];
miss_mask[ind2] = miss0_mask[j];
ind2++;
}
}
Vec<ZZ_p> dosage, dosage_mask;
dosage = g[1] + 2 * g[2];
dosage_mask = g_mask[1] + 2 * g_mask[2];
mpc.BeaverWriteToFile(dosage, dosage_mask, inner_fs);
mpc.BeaverWriteToFile(miss, miss_mask, inner_fs);
if ((i - offset + 1) % bsize == 0 || (i - offset) == inner_n1 - 1) {
cout << "\t" << i+1 << " / " << n1 << ", "; toc(); tic();
}
}
inner_ifs.close();
inner_fs.close();
}
}
tock();
mpc.ProfilerPopState(false); // reduce_file
Vec<ZZ_p> g_mean_pca = g_mean;
mpc.Filter(g_mean_pca, selected, m3);
Vec<ZZ_p> g_stdinv_pca = g_std_bern_inv;
mpc.Filter(g_stdinv_pca, selected, m3);
Vec<ZZ_p> g_mean_pca_mask, g_stdinv_pca_mask;
mpc.BeaverPartition(g_mean_pca_mask, g_mean_pca);
mpc.BeaverPartition(g_stdinv_pca_mask, g_stdinv_pca);
/* Pass 2: Random sketch */
Mat<ZZ_p> Y_cur;
Init(Y_cur, kp, m3);
if (exists(cache(pid, "sketch"))) {
cout << "sketch cache found" << endl;
ifs.open(cache(pid, "sketch").c_str(), ios::in | ios::binary);
ifs >> kp;
mpc.ReadFromFile(Y_cur, ifs, kp, m3);
ifs.close();
} else {
mpc.ProfilerPushState("rand_proj");
cout << "Random Projection ..." << endl; tic();
Mat<ZZ_p> Y_cur_adj;
Init(Y_cur_adj, kp, m3);
Vec<int> bucket_count;
bucket_count.SetLength(kp);
for (int i = 0; i < kp; i++) {
bucket_count[i] = 0;
}
// Loop over all cached PCA datasets in parallel
#pragma omp parallel for num_threads(num_threads)
for (int dataset_idx = 0; dataset_idx < num_datasets; dataset_idx++) {
ifstream inner_ifs;
inner_ifs.open(cache(pid, dataset_idx, "pca_input").c_str(), ios::in | ios::binary);
// Containers to store intermediate results for batching (costly) global updates
Mat<ZZ_p> inner_Y_cur, inner_Y_cur_adj;
Init(inner_Y_cur, kp, m3);
Init(inner_Y_cur_adj, kp, m3);
Vec<int> inner_bucket_count;
inner_bucket_count.SetLength(kp);
for (int i = 0; i < kp; i++) {
inner_bucket_count[i] = 0;
}
long inner_n1 = n1_vec[dataset_idx];
for (int cur = 0; cur < inner_n1; cur++) {
// Count sketch (use global PRG)
mpc.SwitchSeed(-1);
long bucket_index = mpc.RandBnd(kp);
long rand_sign = mpc.RandBnd(2) * 2 - 1;
mpc.RestoreSeed();
Vec<ZZ_p> g, g_mask, miss, miss_mask;
mpc.BeaverReadFromFile(g, g_mask, inner_ifs, m3);
mpc.BeaverReadFromFile(miss, miss_mask, inner_ifs, m3);
// Flip miss bits so it points to places where g_mean should be subtracted
mpc.BeaverFlipBit(miss, miss_mask);
// Update running sum
if (pid > 0) {
inner_Y_cur[bucket_index] += rand_sign * g_mask;
if (pid == 1) {
inner_Y_cur[bucket_index] += rand_sign * g;
}
}
// Update adjustment factor
miss *= rand_sign;
miss_mask *= rand_sign;
mpc.BeaverMultElem(inner_Y_cur_adj[bucket_index], miss, miss_mask, g_mean_pca, g_mean_pca_mask);
inner_bucket_count[bucket_index]++;
}
inner_ifs.close();
// Update global values - these operations must be atomic
#pragma omp critical ( Y_cur_update )
Y_cur += inner_Y_cur;
#pragma omp critical ( Y_cur_adj_update )
Y_cur_adj += inner_Y_cur_adj;
#pragma omp critical ( bucket_count_update )
for (int i = 0; i < kp; i++) {
bucket_count[i] = bucket_count[i] + inner_bucket_count[i];
}
}
// Subtract the adjustment factor
mpc.BeaverReconstruct(Y_cur_adj);
if (pid > 0) {
Y_cur = fp_one * Y_cur - Y_cur_adj;
}
Y_cur_adj.kill();
cout << "done. "; toc();
if (Param::DEBUG) {
cout << "Y_cur" << endl;
mpc.PrintFP(Y_cur[0], 5);
cout << "g_mean_pca" << endl;
mpc.PrintBeaverFP(g_mean_pca, g_mean_pca_mask, 10);
cout << "g_stdinv_pca" << endl;
mpc.PrintBeaverFP(g_stdinv_pca, g_stdinv_pca_mask, 10);
}
// Get rid of empty buckets and normalize nonempty ones
int empty_slot = 0;
for (int i = 0; i < kp; i++) {
if (bucket_count[i] > 0) {
ZZ_p fp_count_inv = DoubleToFP(1 / ((double) bucket_count[i]), Param::NBIT_K, Param::NBIT_F);
Y_cur[empty_slot] = Y_cur[i] * fp_count_inv;
empty_slot++;
}
}
kp = empty_slot;
cout << "kp: " << kp << endl;
Y_cur.SetDims(kp, m3);
mpc.FastTrunc(Y_cur);
mpc.ProfilerPopState(true); // rand_proj
fs.open(cache(pid, "sketch").c_str(), ios::out | ios::binary);
fs << kp;
if (pid > 0) {
mpc.WriteToFile(Y_cur, fs);
}
fs.close();
}
mpc.ProfilerPushState("power_iter");
Mat<ZZ_p> Y_cur_mask;
mpc.BeaverPartition(Y_cur_mask, Y_cur);
cout << "Initial sketch obtained, starting power iteration (num iter = " << Param::NUM_POWER_ITER << ")" << endl;
tick();
Mat<ZZ_p> gQ;
if (exists(cache(pid, "piter"))) {
cout << "piter cache found" << endl;
ifs.open(cache(pid, "piter").c_str(), ios::in | ios::binary);
mpc.ReadFromFile(gQ, ifs, n1, kp);
ifs.close();
} else {
// Divide by standard deviation
Mat<ZZ_p> Y;
Init(Y, kp, m3);
for (int i = 0; i < kp; i++) {
mpc.BeaverMultElem(Y[i], Y_cur[i], Y_cur_mask[i], g_stdinv_pca, g_stdinv_pca_mask);
}
Y_cur.kill();
Y_cur_mask.kill();
mpc.BeaverReconstruct(Y);
mpc.FastTrunc(Y);
/* Calculate orthonormal bases of Y */
cout << "Initial orthonormal basis ... "; tic();
Mat<ZZ_p> Q;
mpc.ProfilerPushState("qr_m");
mpc.OrthonormalBasis(Q, Y);
mpc.ProfilerPopState(false); // qr_m
Y.kill();
cout << "done. "; toc();
Mat<ZZ_p> gQ_adj;
Mat<ZZ_p> Q_mask;
Mat<ZZ_p> Q_scaled, Q_scaled_mask;
Mat<ZZ_p> Q_scaled_gmean, Q_scaled_gmean_mask;
/* Power iteration */
for (int pit = 0; pit <= Param::NUM_POWER_ITER; pit++) {
/* This section is ran before each iteration AND once after all iterations */
mpc.BeaverPartition(Q_mask, Q);
// Normalize Q by standard deviations
Init(Q_scaled, kp, m3);
for (int i = 0; i < kp; i++) {
mpc.BeaverMultElem(Q_scaled[i], Q[i], Q_mask[i], g_stdinv_pca, g_stdinv_pca_mask);
}
mpc.BeaverReconstruct(Q_scaled);
mpc.FastTrunc(Q_scaled);
mpc.BeaverPartition(Q_scaled_mask, Q_scaled);
// Pre-multiply with g_mean to simplify calculation of centering matrix
Init(Q_scaled_gmean, kp, m3);
for (int i = 0; i < kp; i++) {
mpc.BeaverMultElem(Q_scaled_gmean[i], Q_scaled[i], Q_scaled_mask[i],
g_mean_pca, g_mean_pca_mask);
}
mpc.BeaverReconstruct(Q_scaled_gmean);
mpc.FastTrunc(Q_scaled_gmean);
mpc.Transpose(Q_scaled); // m3-by-kp
transpose(Q_scaled_mask, Q_scaled_mask); // m3-by-kp, unlike mpc.Transpose, P0 also transposes
mpc.Transpose(Q_scaled_gmean); // m3-by-kp
mpc.BeaverPartition(Q_scaled_gmean_mask, Q_scaled_gmean);
// reduce batch size to avoid memory issues when replicating variables across threads
long bsize = Param::PITER_BATCH_SIZE / num_threads;
/* Pass 1 */
Init(gQ, n1, kp);
Init(gQ_adj, n1, kp);
mpc.ProfilerPushState("data_scan0");
if (pit == 0) {
cout << "Iter 1: Data Scan 1 ... "; tic();
}
// Loop over all cached PCA datasets in parallel
#pragma omp parallel for num_threads(num_threads)
for (int dataset_idx = 0; dataset_idx < num_datasets; dataset_idx++) {
mpc.ProfilerPushState("file_io");
ifstream inner_ifs;
inner_ifs.open(cache(pid, dataset_idx, "pca_input").c_str(), ios::in | ios::binary);
Mat<ZZ_p> g, g_mask, miss, miss_mask;
Init(g, bsize, m3);
Init(g_mask, bsize, m3);
Init(miss, bsize, m3);
Init(miss_mask, bsize, m3);
long offset = 0;
for (int j = 0; j < dataset_idx; j++) {
offset += n1_vec[j];
}
long inner_n1 = n1_vec[dataset_idx];
for (int cur = 0; cur < inner_n1; cur++) {
mpc.BeaverReadFromFile(g[cur % bsize], g_mask[cur % bsize], inner_ifs, m3);
mpc.BeaverReadFromFile(miss[cur % bsize], miss_mask[cur % bsize], inner_ifs, m3);
mpc.BeaverFlipBit(miss[cur % bsize], miss_mask[cur % bsize]);
if (cur % bsize == bsize - 1 || cur == inner_n1 - 1) {
mpc.ProfilerPopState(false); // file_io
int new_bsize = bsize;
if (cur % bsize < bsize - 1) {
new_bsize = (cur % bsize) + 1;
g.SetDims(new_bsize, m3);
g_mask.SetDims(new_bsize, m3);
miss.SetDims(new_bsize, m3);
miss_mask.SetDims(new_bsize, m3);
}
Mat<ZZ_p> result;
Init(result, new_bsize, kp);
mpc.BeaverMult(result, g, g_mask, Q_scaled, Q_scaled_mask);
for (int i = 0; i < new_bsize; i++) {
gQ[(cur+offset)-(new_bsize-1)+i] = result[i];
}
Init(result, new_bsize, kp);
mpc.BeaverMult(result, miss, miss_mask, Q_scaled_gmean, Q_scaled_gmean_mask);
for (int i = 0; i < new_bsize; i++) {
gQ_adj[(cur+offset)-(new_bsize-1)+i] = result[i];
}
if (cur < inner_n1 - 1) mpc.ProfilerPushState("file_io");
}
}
ifs.close();
g.kill();
g_mask.kill();
miss.kill();
miss_mask.kill();
}
if (pit == 0) {
cout << "done. "; toc();
}
mpc.BeaverReconstruct(gQ);
mpc.BeaverReconstruct(gQ_adj);
if (pid > 0) {
gQ -= gQ_adj;
}
mpc.ProfilerPopState(false); // data_scan1
if (pit == Param::NUM_POWER_ITER) { // Quit if all iterations are performed
break;
}
if (pit == 0) {
cout << "Iter 1: OrthonormalBasis 1 ... "; tic();
}
mpc.Transpose(gQ); // kp-by-n1
mpc.ProfilerPushState("qr_n");
mpc.OrthonormalBasis(Q, gQ);
mpc.ProfilerPopState(false); // qr_n
mpc.Transpose(Q); // n1-by-kp
if (pit == 0) {
cout << "done. "; toc();
}
mpc.BeaverPartition(Q_mask, Q);
Init(gQ, kp, m3);
Init(gQ_adj, kp, m3);
mpc.ProfilerPushState("data_scan2");
// Pass 2
if (pit == 0) {
cout << "Iter 1: Data Scan 2 ... "; tic();
}
// Loop over all cached PCA datasets
#pragma omp parallel for num_threads(num_threads)
for (int dataset_idx = 0; dataset_idx < num_datasets; dataset_idx++) {
mpc.ProfilerPushState("file_io");
ifstream inner_ifs;
inner_ifs.open(cache(pid, dataset_idx, "pca_input").c_str(), ios::in | ios::binary);
Mat<ZZ_p> g, g_mask, miss, miss_mask, Qsub, Qsub_mask;;
Init(g, bsize, m3);
Init(g_mask, bsize, m3);
Init(miss, bsize, m3);
Init(miss_mask, bsize, m3);
Init(Qsub, bsize, kp);
Init(Qsub_mask, bsize, kp);
// Containers to store intermediate results for batching (costly) global updates
Mat<ZZ_p> inner_gQ, inner_gQ_adj;
Init(inner_gQ, kp, m3);
Init(inner_gQ_adj, kp, m3);
long offset = 0;
for (int j = 0; j < dataset_idx; j++) {
offset += n1_vec[j];
}
long inner_n1 = n1_vec[dataset_idx];
for (int cur = 0; cur < inner_n1; cur++) {
mpc.BeaverReadFromFile(g[cur % bsize], g_mask[cur % bsize], inner_ifs, m3);
mpc.BeaverReadFromFile(miss[cur % bsize], miss_mask[cur % bsize], inner_ifs, m3);
mpc.BeaverFlipBit(miss[cur % bsize], miss_mask[cur % bsize]);
Qsub[cur % bsize] = Q[cur + offset];
Qsub_mask[cur % bsize] = Q_mask[cur + offset];
if (cur % bsize == bsize - 1 || cur == inner_n1 - 1) {
mpc.ProfilerPopState(false); // file_io
int new_bsize = bsize;
if (cur % bsize < bsize - 1) {
new_bsize = (cur % bsize) + 1;
g.SetDims(new_bsize, m3);
g_mask.SetDims(new_bsize, m3);
miss.SetDims(new_bsize, m3);
miss_mask.SetDims(new_bsize, m3);
Qsub.SetDims(new_bsize, kp);
Qsub_mask.SetDims(new_bsize, kp);
}
mpc.Transpose(Qsub);
transpose(Qsub_mask, Qsub_mask);
mpc.BeaverMult(inner_gQ, Qsub, Qsub_mask, g, g_mask);
mpc.BeaverMult(inner_gQ_adj, Qsub, Qsub_mask, miss, miss_mask);
Qsub.SetDims(bsize, kp);
Qsub_mask.SetDims(bsize, kp);
if (cur < inner_n1 - 1) mpc.ProfilerPushState("file_io");
}
}
ifs.close();
// Update global values - these operations must be atomic
#pragma omp critical ( gQ_update )
gQ += inner_gQ;
#pragma omp critical ( gQ_adj_update )
gQ_adj += inner_gQ_adj;
g.kill();
g_mask.kill();
miss.kill();
miss_mask.kill();
Qsub.kill();
Qsub_mask.kill();
inner_gQ.kill();
inner_gQ_adj.kill();
}
if (pit == 0) {
cout << "done. "; toc();
}
mpc.BeaverReconstruct(gQ);
mpc.BeaverReconstruct(gQ_adj);
mpc.ProfilerPopState(false); // data_scan2
Mat<ZZ_p> gQ_adj_mask;
mpc.BeaverPartition(gQ_adj_mask, gQ_adj);
Mat<ZZ_p> gQ_adj_gmean;
Init(gQ_adj_gmean, kp, m3);
for (int i = 0; i < kp; i++) {
mpc.BeaverMultElem(gQ_adj_gmean[i], gQ_adj[i], gQ_adj_mask[i],
g_mean_pca, g_mean_pca_mask);
}
mpc.BeaverReconstruct(gQ_adj_gmean);
mpc.FastTrunc(gQ_adj_gmean);
if (pid > 0) {
gQ -= gQ_adj_gmean;
}
gQ_adj_gmean.kill();
Mat<ZZ_p> gQ_mask;
mpc.BeaverPartition(gQ_mask, gQ);
Mat<ZZ_p> gQ_scaled;
gQ_scaled.SetDims(kp, m3);
clear(gQ_scaled);
for (int i = 0; i < kp; i++) {
mpc.BeaverMultElem(gQ_scaled[i], gQ[i], gQ_mask[i], g_stdinv_pca, g_stdinv_pca_mask);
}
mpc.BeaverReconstruct(gQ_scaled);
mpc.FastTrunc(gQ_scaled);
mpc.ProfilerPushState("qr_m");
if (pit == 0) {
cout << "Iter 1: Orthonormal Basis 2 ... "; tic();
}
mpc.OrthonormalBasis(Q, gQ_scaled);
if (pit == 0) {
cout << "done. "; toc();
}
mpc.ProfilerPopState(false); // qr_m
if (pit != 0) {
cout << "Iter " << pit + 1 << " complete, "; toc();
}
tic();
}
fs.open(cache(pid, "piter").c_str(), ios::out | ios::binary);
if (pid > 0) {
mpc.WriteToFile(gQ, fs);
}
fs.close();
}
mpc.ProfilerPopState(true); // power_iter
cout << "Power iteration complete" << endl; tock();
Mat<ZZ_p> Z = gQ;
gQ.kill();
cout << "Data projected to subspace" << endl;
if (Param::DEBUG) {
cout << "Z" << endl;
mpc.PrintFP(Z[0], 5);
}
Mat<ZZ_p> V;
Init(V, k, n1);
/* Eigendecomposition */
if (exists(cache(pid, "eigen"))) {
cout << "eigen cache found" << endl;
ifs.open(cache(pid, "eigen").c_str(), ios::binary);
mpc.ReadFromFile(V, ifs, k, n1);
ifs.close();
} else {
ZZ_p fp_m2_inv = DoubleToFP(1 / ((double) m2), Param::NBIT_K, Param::NBIT_F);
Z *= fp_m2_inv;
mpc.FastTrunc(Z);
mpc.Transpose(Z); // kp-by-n1
Mat<ZZ_p> Z_mask;
mpc.BeaverPartition(Z_mask, Z);
/* Form covariance matrix */
Mat<ZZ_p> Z_gram;
Init(Z_gram, kp, kp);
for (int i = 0; i < kp; i++) {
mpc.BeaverMult(Z_gram[i], Z, Z_mask, Z[i], Z_mask[i]);
}
mpc.BeaverReconstruct(Z_gram);
mpc.FastTrunc(Z_gram);
cout << "Constructed reduced eigenvalue problem" << endl;
if (Param::DEBUG) {
cout << "Z_gram" << endl;
for (int i = 0; i < 3; i++) {
mpc.PrintFP(Z_gram[i], 5);
}
}
mpc.ProfilerPushState("eigen_solve");
Mat<ZZ_p> U;
Vec<ZZ_p> L;
cout << "Eigenvector decomposition ... " << endl; tic();
mpc.EigenDecomp(U, L, Z_gram);
cout << "done. "; toc();
Z_gram.kill();
// Select top eigenvectors and eigenvalues
U.SetDims(k, kp);
L.SetLength(k);
cout << "Selected K eigenvectors" << endl;
mpc.ProfilerPopState(false); // eigen_solve
if (Param::DEBUG) {
for (int i = 0; i < 3; i++) {
mpc.PrintFP(U[i], 5);
}
cout << "Eigenvalues" << endl;
mpc.PrintFP(L, 5);
}
// Recover singular vectors
Mat<ZZ_p> U_mask;
mpc.BeaverPartition(U_mask, U);
mpc.BeaverMultMat(V, U, U_mask, Z, Z_mask);
U.kill();
U_mask.kill();
Z_mask.kill();
mpc.BeaverReconstruct(V);
mpc.FastTrunc(V);
fs.open(cache(pid, "eigen").c_str(), ios::out | ios::binary);
if (pid > 0) {
mpc.WriteToFile(V, fs);
}
fs.close();
}
Z.kill();
mpc.ProfilerPopState(true); // pop_strat
mpc.ProfilerPushState("assoc_test");
mpc.ProfilerPushState("covar");
// Concatenate covariate matrix and jointly orthogonalize
mpc.Transpose(cov);
V.SetDims(k + Param::NUM_COVS, n1);
if (pid > 0) {
for (int i = 0; i < Param::NUM_COVS; i++) {
V[k + i] = cov[i] * fp_one;
}
}
cov.kill();
mpc.OrthonormalBasis(V, V);
Mat<ZZ_p> V_mask;
mpc.BeaverPartition(V_mask, V);
cout << "Bases for top singular vectors and covariates calculated" << endl;
mpc.ProfilerPopState(false); // covar
if (Param::DEBUG) {
mpc.PrintBeaverFP(V[0], V_mask[0], 5);
}
/* Pass 4: Calculate GWAS statistics */
Vec<ZZ_p> pheno_mask;
mpc.BeaverPartition(pheno_mask, pheno);
Vec<ZZ_p> Vp;
Init(Vp, k + Param::NUM_COVS);
mpc.BeaverMult(Vp, V, V_mask, pheno, pheno_mask);
mpc.BeaverReconstruct(Vp);
Vec<ZZ_p> Vp_mask;
mpc.BeaverPartition(Vp_mask, Vp);
Vec<ZZ_p> VVp;
Init(VVp, n1);
mpc.BeaverMult(VVp, Vp, Vp_mask, V, V_mask);
mpc.BeaverReconstruct(VVp);
mpc.FastTrunc(VVp);
Vec<ZZ_p> VVp_mask;
mpc.BeaverPartition(VVp_mask, VVp);
Vec<ZZ_p> p_hat, p_hat_mask;
p_hat = fp_one * pheno - VVp;
p_hat_mask = fp_one * pheno_mask - VVp_mask;
Vp.kill();
Vp_mask.kill();
VVp.kill();
VVp_mask.kill();
cout << "Phenotypes corrected" << endl;
Vec<ZZ_p> V_sum, V_sum_mask;
Init(V_sum, k + Param::NUM_COVS);
Init(V_sum_mask, k + Param::NUM_COVS);
for (int i = 0; i < k + Param::NUM_COVS; i++) {
for (int j = 0; j < n1; j++) {
V_sum[i] += V[i][j];
V_sum_mask[i] += V_mask[i][j];
}
}
Vec<ZZ_p> u;
Init(u, n1);
mpc.BeaverMult(u, V_sum, V_sum_mask, V, V_mask);
mpc.BeaverReconstruct(u);
mpc.FastTrunc(u);
if (pid > 0) {
u *= -1;
mpc.AddPublic(u, fp_one);
}
Vec<ZZ_p> u_mask;
mpc.BeaverPartition(u_mask, u);
if (Param::DEBUG) {
cout << "u" << endl;
mpc.PrintBeaverFP(u, u_mask, 10);
}
cout << "Allocating sx, sxx, sxp, B ... ";
Vec<ZZ_p> sx, sxx, sxp;
Mat<ZZ_p> B;
Init(sx, m2);
Init(sxx, m2);
Init(sxp, m2);
Init(B, k + Param::NUM_COVS, m2);
cout << "done." << endl;
mpc.ProfilerPushState("data_scan");
if (exists(cache(pid, "gwas_stats"))) {
cout << "GWAS statistics cache found" << endl;
ifs.open(cache(pid, "gwas_stats").c_str(), ios::binary);
mpc.ReadFromFile(sx, ifs, m2);
mpc.ReadFromFile(sxx, ifs, m2);
mpc.ReadFromFile(sxp, ifs, m2);
mpc.ReadFromFile(B, ifs, k + Param::NUM_COVS, m2);
ifs.close();
} else {
long bsize = Param::PITER_BATCH_SIZE / num_threads;
mpc.Transpose(V); // n1-by-(k + NUM_COVS)
transpose(V_mask, V_mask);
Vec<bool> gkeep3;
gkeep3.SetLength(m0);
for (int j = 0; j < m0; j++) {
gkeep3[j] = gkeep1[j] == 1;
}
ind = 0;
for (int j = 0; j < m0; j++) {
if (gkeep3[j]) {
gkeep3[j] = gkeep2[ind] == 1;
ind++;
}
}
tic();
mpc.ProfilerPushState("file_io/rng");
cout << "GWAS pass:" << endl; tick();
// Loop over all datasets/chunks in parallel
#pragma omp parallel for num_threads(num_threads)
for (int dataset_idx = 0; dataset_idx < Param::NUM_INDS.size(); dataset_idx++) {
Mat<ZZ_p> dosage, dosage_mask;
Init(dosage, bsize, m2);
Init(dosage_mask, bsize, m2);
Vec<ZZ_p> u_vec, u_mask_vec, p_hat_vec, p_hat_mask_vec;
Init(u_vec, bsize);
Init(u_mask_vec, bsize);
Init(p_hat_vec, bsize);
Init(p_hat_mask_vec, bsize);
Mat<ZZ_p> V_sub, V_mask_sub;
Init(V_sub, bsize, k + Param::NUM_COVS);
Init(V_mask_sub, bsize, k + Param::NUM_COVS);
Mat<ZZ_p> g, g_mask;
Vec<ZZ_p> miss, miss_mask;
g.SetDims(3, m2);
miss.SetLength(m2);
g_mask.SetDims(3, m2);
miss_mask.SetLength(m2);
Vec<ZZ_p> inner_sx, inner_sxx, inner_sxp;
Mat<ZZ_p> inner_B;
Init(inner_sx, m2);
Init(inner_sxx, m2);
Init(inner_sxp, m2);
Init(inner_B, k + Param::NUM_COVS, m2);
ifstream inner_ifs;
inner_ifs.open(cache(pid, dataset_idx, "input_geno").c_str(), ios::binary);
if (pid > 0) {
mpc.ImportSeed(10, inner_ifs);
} else {
for (int p = 1; p <= 2; p++) {
mpc.ImportSeed(10 + p, inner_ifs);
}
}
// avoid error by re-setting the modulus within each thread
ZZ base_p = conv<ZZ>(Param::BASE_P.c_str());
ZZ_p::init(base_p);
long offset = 0;
long inner_ind = -1;
for (int j = 0; j < dataset_idx; j++) {
offset += n1_vec[j];
inner_ind += Param::NUM_INDS[j];
}
long inner_n1 = n1_vec[dataset_idx];
for (int cur = 0; cur < inner_n1; cur++) {
inner_ind++;
Mat<ZZ_p> g0, g0_mask;
Vec<ZZ_p> miss0, miss0_mask;
while (ikeep[inner_ind] != 1) {
if (pid > 0) {
mpc.SkipData(inner_ifs, 3, m0); // g
mpc.SkipData(inner_ifs, m0); // miss
mpc.SwitchSeed(10);
mpc.RandMat(g0_mask, 3, m0);
mpc.RandVec(miss0_mask, m0);
mpc.RestoreSeed();
} else {
for (int p = 1; p <= 2; p++) {
mpc.SwitchSeed(10 + p);
mpc.RandMat(g0_mask, 3, m0);
mpc.RandVec(miss0_mask, m0);
mpc.RestoreSeed();
}
}
inner_ind++;
}
if (pid > 0) {
mpc.ReadFromFile(g0, inner_ifs, 3, m0); // g
mpc.ReadFromFile(miss0, inner_ifs, m0); // miss
mpc.SwitchSeed(10);
mpc.RandMat(g0_mask, 3, m0);
mpc.RandVec(miss0_mask, m0);
mpc.RestoreSeed();
} else {
Init(g0, 3, m0);
Init(g0_mask, 3, m0);
Init(miss0, m0);
Init(miss0_mask, m0);
Vec<ZZ_p> rand_vec;
Mat<ZZ_p> rand_mat;
for (int p = 1; p <= 2; p++) {
mpc.SwitchSeed(10 + p);
mpc.RandMat(rand_mat, 3, m0);
mpc.RandVec(rand_vec, m0);
mpc.RestoreSeed();
g0_mask += rand_mat;
miss0_mask += rand_vec;
}
}
int inner_ind2 = 0;
for (int j = 0; j < m0; j++) {
if (gkeep3[j]) {
for (int k = 0; k < 3; k++) {
g[k][inner_ind2] = g0[k][j];
g_mask[k][inner_ind2] = g0_mask[k][j];
}
miss[inner_ind2] = miss0[j];
miss_mask[inner_ind2] = miss0_mask[j];
inner_ind2++;
}
}
dosage[cur % bsize] = g[1] + 2 * g[2];
dosage_mask[cur % bsize] = g_mask[1] + 2 * g_mask[2];
u_vec[cur % bsize] = u[cur + offset];
u_mask_vec[cur % bsize] = u_mask[cur + offset];
p_hat_vec[cur % bsize] = p_hat[cur + offset];
p_hat_mask_vec[cur % bsize] = p_hat_mask[cur + offset];
V_sub[cur % bsize] = V[cur + offset];
V_mask_sub[cur % bsize] = V_mask[cur + offset];
long new_bsize = bsize;
if (cur % bsize == bsize - 1 || cur == inner_n1 - 1) {
if (cur % bsize < bsize - 1) {
new_bsize = inner_n1 % bsize;
dosage.SetDims(new_bsize, m2);
dosage_mask.SetDims(new_bsize, m2);
u_vec.SetLength(new_bsize);
u_mask_vec.SetLength(new_bsize);
p_hat_vec.SetLength(new_bsize);
p_hat_mask_vec.SetLength(new_bsize);
V_sub.SetDims(new_bsize, k + Param::NUM_COVS);
V_mask_sub.SetDims(new_bsize, k + Param::NUM_COVS);
}
mpc.ProfilerPopState(false); // file_io/rng
mpc.BeaverMult(inner_sx, u_vec, u_mask_vec, dosage, dosage_mask);
mpc.BeaverMult(inner_sxp, p_hat_vec, p_hat_mask_vec, dosage, dosage_mask);
Mat<ZZ_p> sxx_tmp;
Init(sxx_tmp, new_bsize, m2);
mpc.BeaverMultElem(sxx_tmp, dosage, dosage_mask, dosage, dosage_mask);
for (int b = 0; b < new_bsize; b++) {
inner_sxx += sxx_tmp[b];
}
sxx_tmp.kill();
mpc.Transpose(V_sub); // (k + NUM_COVS)-by-bsize
transpose(V_mask_sub, V_mask_sub);
mpc.BeaverMult(inner_B, V_sub, V_mask_sub, dosage, dosage_mask);
cout << "\t" << cur + 1 << " / " << inner_n1 << ", "; toc(); tic();
Init(dosage, bsize, m2);
Init(dosage_mask, bsize, m2);
Init(V_sub, bsize, k + Param::NUM_COVS);
Init(V_mask_sub, bsize, k + Param::NUM_COVS);
mpc.ProfilerPushState("file_io/rng");
}
}
inner_ifs.close();
// Add to running sums - each operation mutates shared data, and therefore must be atomic
#pragma omp critical ( sx_update )
sx += inner_sx;
#pragma omp critical ( sxp_update )
sxp += inner_sxp;
#pragma omp critical ( sxx_update )
sxx += inner_sxx;
#pragma omp critical ( B_update )
B += inner_B;
}
tock();
mpc.ProfilerPopState(false); // file_io/rng
mpc.BeaverReconstruct(sx);
mpc.BeaverReconstruct(sxp);
mpc.BeaverReconstruct(sxx);
mpc.BeaverReconstruct(B);
sxx *= fp_one;
fs.open(cache(pid, "gwas_stats").c_str(), ios::out | ios::binary);
mpc.WriteToFile(sx, fs);
mpc.WriteToFile(sxx, fs);
mpc.WriteToFile(sxp, fs);
mpc.WriteToFile(B, fs);
fs.close();
cout << "Wrote results to cache" << endl;
}
mpc.ProfilerPopState(true); // data_scan
if (Param::DEBUG) {
cout << "sx" << endl;
mpc.PrintFP(sx, 3);
cout << "sxp" << endl;
mpc.PrintFP(sxp, 3);
cout << "sxx" << endl;
mpc.PrintFP(sxx, 3);
cout << "B" << endl;
mpc.PrintFP(B, 3, 3);
}
mpc.Transpose(B); // m2-by-(k + Param::NUM_COVS)
Vec<ZZ_p> BB;
mpc.InnerProd(BB, B); // m2
mpc.FastTrunc(BB);
if (pid > 0) {
sxx -= BB;
}
ZZ_p sp(0);
if (pid > 0) {
for (int i = 0; i < n1; i++) {
sp += p_hat_mask[i];
if (pid == 1) {
sp += p_hat[i];
}
}
}
ZZ_p spp(0);
mpc.BeaverInnerProd(spp, p_hat, p_hat_mask);
mpc.BeaverReconstruct(spp);
ZZ_p fp_n1_inv = DoubleToFP(1 / ((double) n1), Param::NBIT_K, Param::NBIT_F);
sx *= fp_n1_inv;
sp *= fp_n1_inv;
mpc.FastTrunc(sx);
mpc.Trunc(sp);
mpc.Trunc(spp);
Vec<ZZ_p> sx_mask;
mpc.BeaverPartition(sx_mask, sx);
ZZ_p sp_mask;
mpc.BeaverPartition(sp_mask, sp);
Vec<ZZ_p> spsx, sx2;
ZZ_p sp2(0);
Init(spsx, m2);
Init(sx2, m2);
mpc.BeaverMult(spsx, sx, sx_mask, sp, sp_mask);
mpc.BeaverMult(sp2, sp, sp_mask, sp, sp_mask);
mpc.BeaverMultElem(sx2, sx, sx_mask, sx, sx_mask);
mpc.BeaverReconstruct(spsx);
mpc.BeaverReconstruct(sp2);
mpc.BeaverReconstruct(sx2);
spsx *= n1;
sp2 *= n1;
sx2 *= n1;
mpc.FastTrunc(spsx);
mpc.Trunc(sp2);
mpc.FastTrunc(sx2);
Vec<ZZ_p> numer, denom;
Init(numer, m2);
Init(denom, m2 + 1);
if (pid > 0) {
numer = sxp - spsx;
for (int i = 0; i < m2; i++) {
denom[i] = sxx[i] - sx2[i];
}
denom[m2] = spp - sp2;
}
Vec<ZZ_p> denom1_sqrt_inv;
if (exists(cache(pid, "denom_inv"))) {
cout << "denom_inv cache found" << endl;
ifs.open(cache(pid, "denom_inv").c_str(), ios::binary);
mpc.ReadFromFile(denom1_sqrt_inv, ifs, denom.length());
ifs.close();
} else {
cout << "Begin denom_inv calculation ... " << endl; tic();
mpc.ProfilerPushState("sqrt");
mpc.FPSqrtParallel(tmp_vec, denom1_sqrt_inv, denom);
mpc.ProfilerPopState(false); // sqrt
cout << "done. "; toc();
fs.open(cache(pid, "denom_inv").c_str(), ios::out | ios::binary);
if (pid > 0) {
mpc.WriteToFile(denom1_sqrt_inv, fs);
}
fs.close();
}
denom.kill();
tmp_vec.kill();
ZZ_p denom2_sqrt_inv = denom1_sqrt_inv[m2]; // p term
denom1_sqrt_inv.SetLength(m2); // truncate
Vec<ZZ_p> z;
mpc.MultElem(z, numer, denom1_sqrt_inv);
mpc.FastTrunc(z);
mpc.MultMat(z, z, denom2_sqrt_inv);
mpc.FastTrunc(z);
mpc.ProfilerPopState(false); // assoc_test
cout << "Association statistics calculated" << endl;
mpc.RevealSym(z);
if (pid == 2) {
Vec<double> z_double;
cout << "Converting association statistics to double ... "; tic();
FPToDouble(z_double, z, Param::NBIT_K, Param::NBIT_F);
cout << "done. "; toc();
ofs.open(outname("assoc").c_str(), ios::out);
for (int i = 0; i < z_double.length(); i++) {
ofs << z_double[i] << endl;
}
ofs.close();
cout << "Result written to " << outname("assoc") << endl;
}
mpc.ProfilerPopState(true); // main
return true;
}
#endif
|
cp-tree.h
|
/* Definitions for C++ parsing and type checking.
Copyright (C) 1987-2017 Free Software Foundation, Inc.
Contributed by Michael Tiemann ([email protected])
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
GCC 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 GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
#ifndef GCC_CP_TREE_H
#define GCC_CP_TREE_H
#include "tm.h"
#include "hard-reg-set.h"
#include "function.h"
/* In order for the format checking to accept the C++ front end
diagnostic framework extensions, you must include this file before
diagnostic-core.h, not after. We override the definition of GCC_DIAG_STYLE
in c-common.h. */
#undef GCC_DIAG_STYLE
#define GCC_DIAG_STYLE __gcc_cxxdiag__
#if defined(GCC_DIAGNOSTIC_CORE_H) || defined (GCC_C_COMMON_H)
#error \
In order for the format checking to accept the C++ front end diagnostic \
framework extensions, you must include this file before diagnostic-core.h and \
c-common.h, not after.
#endif
#include "c-family/c-common.h"
#include "diagnostic.h"
/* A tree node, together with a location, so that we can track locations
(and ranges) during parsing.
The location is redundant for node kinds that have locations,
but not all node kinds do (e.g. constants, and references to
params, locals, etc), so we stash a copy here. */
class cp_expr
{
public:
cp_expr () :
m_value (NULL), m_loc (UNKNOWN_LOCATION) {}
cp_expr (tree value) :
m_value (value), m_loc (EXPR_LOCATION (m_value)) {}
cp_expr (tree value, location_t loc):
m_value (value), m_loc (loc) {}
cp_expr (const cp_expr &other) :
m_value (other.m_value), m_loc (other.m_loc) {}
/* Implicit conversions to tree. */
operator tree () const { return m_value; }
tree & operator* () { return m_value; }
tree & operator-> () { return m_value; }
tree get_value () const { return m_value; }
location_t get_location () const { return m_loc; }
location_t get_start () const
{
source_range src_range = get_range_from_loc (line_table, m_loc);
return src_range.m_start;
}
location_t get_finish () const
{
source_range src_range = get_range_from_loc (line_table, m_loc);
return src_range.m_finish;
}
void set_location (location_t loc)
{
protected_set_expr_location (m_value, loc);
m_loc = loc;
}
void set_range (location_t start, location_t finish)
{
set_location (make_location (m_loc, start, finish));
}
private:
tree m_value;
location_t m_loc;
};
inline bool
operator == (const cp_expr &lhs, tree rhs)
{
return lhs.get_value () == rhs;
}
#include "name-lookup.h"
/* Usage of TREE_LANG_FLAG_?:
0: IDENTIFIER_MARKED (IDENTIFIER_NODEs)
NEW_EXPR_USE_GLOBAL (in NEW_EXPR).
COND_EXPR_IS_VEC_DELETE (in COND_EXPR).
DELETE_EXPR_USE_GLOBAL (in DELETE_EXPR).
COMPOUND_EXPR_OVERLOADED (in COMPOUND_EXPR).
CLEANUP_P (in TRY_BLOCK)
AGGR_INIT_VIA_CTOR_P (in AGGR_INIT_EXPR)
PTRMEM_OK_P (in ADDR_EXPR, OFFSET_REF, SCOPE_REF)
PAREN_STRING_LITERAL (in STRING_CST)
CP_DECL_THREAD_LOCAL_P (in VAR_DECL)
KOENIG_LOOKUP_P (in CALL_EXPR)
STATEMENT_LIST_NO_SCOPE (in STATEMENT_LIST).
EXPR_STMT_STMT_EXPR_RESULT (in EXPR_STMT)
STMT_EXPR_NO_SCOPE (in STMT_EXPR)
BIND_EXPR_TRY_BLOCK (in BIND_EXPR)
TYPENAME_IS_ENUM_P (in TYPENAME_TYPE)
OMP_FOR_GIMPLIFYING_P (in OMP_FOR, OMP_SIMD, OMP_DISTRIBUTE,
and OMP_TASKLOOP)
BASELINK_QUALIFIED_P (in BASELINK)
TARGET_EXPR_IMPLICIT_P (in TARGET_EXPR)
TEMPLATE_PARM_PARAMETER_PACK (in TEMPLATE_PARM_INDEX)
TREE_INDIRECT_USING (in a TREE_LIST of using-directives)
ATTR_IS_DEPENDENT (in the TREE_LIST for an attribute)
ABI_TAG_IMPLICIT (in the TREE_LIST for the argument of abi_tag)
CONSTRUCTOR_IS_DIRECT_INIT (in CONSTRUCTOR)
LAMBDA_EXPR_CAPTURES_THIS_P (in LAMBDA_EXPR)
DECLTYPE_FOR_LAMBDA_CAPTURE (in DECLTYPE_TYPE)
VEC_INIT_EXPR_IS_CONSTEXPR (in VEC_INIT_EXPR)
DECL_OVERRIDE_P (in FUNCTION_DECL)
IMPLICIT_CONV_EXPR_DIRECT_INIT (in IMPLICIT_CONV_EXPR)
TRANSACTION_EXPR_IS_STMT (in TRANSACTION_EXPR)
CONVERT_EXPR_VBASE_PATH (in CONVERT_EXPR)
OVL_ARG_DEPENDENT (in OVERLOAD)
PACK_EXPANSION_LOCAL_P (in *_PACK_EXPANSION)
TINFO_HAS_ACCESS_ERRORS (in TEMPLATE_INFO)
SIZEOF_EXPR_TYPE_P (in SIZEOF_EXPR)
COMPOUND_REQ_NOEXCEPT_P (in COMPOUND_REQ)
WILDCARD_PACK_P (in WILDCARD_DECL)
BLOCK_OUTER_CURLY_BRACE_P (in BLOCK)
FOLD_EXPR_MODOP_P (*_FOLD_EXPR)
IF_STMT_CONSTEXPR_P (IF_STMT)
TEMPLATE_TYPE_PARM_FOR_CLASS (TEMPLATE_TYPE_PARM)
1: IDENTIFIER_VIRTUAL_P (in IDENTIFIER_NODE)
TI_PENDING_TEMPLATE_FLAG.
TEMPLATE_PARMS_FOR_INLINE.
DELETE_EXPR_USE_VEC (in DELETE_EXPR).
(TREE_CALLS_NEW) (in _EXPR or _REF) (commented-out).
ICS_ELLIPSIS_FLAG (in _CONV)
DECL_INITIALIZED_P (in VAR_DECL)
TYPENAME_IS_CLASS_P (in TYPENAME_TYPE)
STMT_IS_FULL_EXPR_P (in _STMT)
TARGET_EXPR_LIST_INIT_P (in TARGET_EXPR)
LAMBDA_EXPR_MUTABLE_P (in LAMBDA_EXPR)
DECL_FINAL_P (in FUNCTION_DECL)
QUALIFIED_NAME_IS_TEMPLATE (in SCOPE_REF)
DECLTYPE_FOR_INIT_CAPTURE (in DECLTYPE_TYPE)
CONSTRUCTOR_NO_IMPLICIT_ZERO (in CONSTRUCTOR)
TINFO_USED_TEMPLATE_ID (in TEMPLATE_INFO)
PACK_EXPANSION_SIZEOF_P (in *_PACK_EXPANSION)
2: IDENTIFIER_OPNAME_P (in IDENTIFIER_NODE)
ICS_THIS_FLAG (in _CONV)
DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (in VAR_DECL)
STATEMENT_LIST_TRY_BLOCK (in STATEMENT_LIST)
TYPENAME_IS_RESOLVING_P (in TYPE_NAME_TYPE)
TARGET_EXPR_DIRECT_INIT_P (in TARGET_EXPR)
FNDECL_USED_AUTO (in FUNCTION_DECL)
DECLTYPE_FOR_LAMBDA_PROXY (in DECLTYPE_TYPE)
REF_PARENTHESIZED_P (in COMPONENT_REF, INDIRECT_REF, SCOPE_REF)
AGGR_INIT_ZERO_FIRST (in AGGR_INIT_EXPR)
CONSTRUCTOR_MUTABLE_POISON (in CONSTRUCTOR)
3: (TREE_REFERENCE_EXPR) (in NON_LVALUE_EXPR) (commented-out).
ICS_BAD_FLAG (in _CONV)
FN_TRY_BLOCK_P (in TRY_BLOCK)
IDENTIFIER_CTOR_OR_DTOR_P (in IDENTIFIER_NODE)
BIND_EXPR_BODY_BLOCK (in BIND_EXPR)
DECL_NON_TRIVIALLY_INITIALIZED_P (in VAR_DECL)
CALL_EXPR_ORDERED_ARGS (in CALL_EXPR, AGGR_INIT_EXPR)
DECLTYPE_FOR_REF_CAPTURE (in DECLTYPE_TYPE)
4: TREE_HAS_CONSTRUCTOR (in INDIRECT_REF, SAVE_EXPR, CONSTRUCTOR,
CALL_EXPR, or FIELD_DECL).
IDENTIFIER_TYPENAME_P (in IDENTIFIER_NODE)
DECL_TINFO_P (in VAR_DECL)
FUNCTION_REF_QUALIFIED (in FUNCTION_TYPE, METHOD_TYPE)
5: C_IS_RESERVED_WORD (in IDENTIFIER_NODE)
DECL_VTABLE_OR_VTT_P (in VAR_DECL)
FUNCTION_RVALUE_QUALIFIED (in FUNCTION_TYPE, METHOD_TYPE)
CALL_EXPR_REVERSE_ARGS (in CALL_EXPR, AGGR_INIT_EXPR)
6: IDENTIFIER_REPO_CHOSEN (in IDENTIFIER_NODE)
DECL_CONSTRUCTION_VTABLE_P (in VAR_DECL)
TYPE_MARKED_P (in _TYPE)
RANGE_FOR_IVDEP (in RANGE_FOR_STMT)
CALL_EXPR_OPERATOR_SYNTAX (in CALL_EXPR, AGGR_INIT_EXPR)
Usage of TYPE_LANG_FLAG_?:
0: TYPE_DEPENDENT_P
1: TYPE_HAS_USER_CONSTRUCTOR.
2: TYPE_HAS_LATE_RETURN_TYPE (in FUNCTION_TYPE, METHOD_TYPE)
TYPE_PTRMEMFUNC_FLAG (in RECORD_TYPE)
4: TYPE_HAS_NONTRIVIAL_DESTRUCTOR
5: CLASS_TYPE_P (in RECORD_TYPE and UNION_TYPE)
ENUM_FIXED_UNDERLYING_TYPE_P (in ENUMERAL_TYPE)
AUTO_IS_DECLTYPE (in TEMPLATE_TYPE_PARM)
REFERENCE_VLA_OK (in REFERENCE_TYPE)
6: TYPE_DEPENDENT_P_VALID
Usage of DECL_LANG_FLAG_?:
0: DECL_ERROR_REPORTED (in VAR_DECL).
DECL_TEMPLATE_PARM_P (in PARM_DECL, CONST_DECL, TYPE_DECL, or TEMPLATE_DECL)
DECL_LOCAL_FUNCTION_P (in FUNCTION_DECL)
DECL_MUTABLE_P (in FIELD_DECL)
DECL_DEPENDENT_P (in USING_DECL)
LABEL_DECL_BREAK (in LABEL_DECL)
1: C_TYPEDEF_EXPLICITLY_SIGNED (in TYPE_DECL).
DECL_TEMPLATE_INSTANTIATED (in a VAR_DECL or a FUNCTION_DECL)
DECL_MEMBER_TEMPLATE_P (in TEMPLATE_DECL)
USING_DECL_TYPENAME_P (in USING_DECL)
DECL_VLA_CAPTURE_P (in FIELD_DECL)
DECL_ARRAY_PARAMETER_P (in PARM_DECL)
LABEL_DECL_CONTINUE (in LABEL_DECL)
2: DECL_THIS_EXTERN (in VAR_DECL or FUNCTION_DECL).
DECL_IMPLICIT_TYPEDEF_P (in a TYPE_DECL)
DECL_CONSTRAINT_VAR_P (in a PARM_DECL)
TEMPLATE_DECL_COMPLEX_ALIAS_P (in TEMPLATE_DECL)
DECL_INSTANTIATING_NSDMI_P (in a FIELD_DECL)
3: DECL_IN_AGGR_P.
4: DECL_C_BIT_FIELD (in a FIELD_DECL)
DECL_ANON_UNION_VAR_P (in a VAR_DECL)
DECL_SELF_REFERENCE_P (in a TYPE_DECL)
DECL_INVALID_OVERRIDER_P (in a FUNCTION_DECL)
5: DECL_INTERFACE_KNOWN.
6: DECL_THIS_STATIC (in VAR_DECL or FUNCTION_DECL).
DECL_FIELD_IS_BASE (in FIELD_DECL)
TYPE_DECL_ALIAS_P (in TYPE_DECL)
7: DECL_DEAD_FOR_LOCAL (in VAR_DECL).
DECL_THUNK_P (in a member FUNCTION_DECL)
DECL_NORMAL_CAPTURE_P (in FIELD_DECL)
8: DECL_DECLARED_CONSTEXPR_P (in VAR_DECL, FUNCTION_DECL)
Usage of language-independent fields in a language-dependent manner:
TYPE_ALIAS_SET
This field is used by TYPENAME_TYPEs, TEMPLATE_TYPE_PARMs, and so
forth as a substitute for the mark bits provided in `lang_type'.
At present, only the six low-order bits are used.
TYPE_LANG_SLOT_1
For an ENUMERAL_TYPE, this is ENUM_TEMPLATE_INFO.
For a FUNCTION_TYPE or METHOD_TYPE, this is TYPE_RAISES_EXCEPTIONS
BINFO_VIRTUALS
For a binfo, this is a TREE_LIST. There is an entry for each
virtual function declared either in BINFO or its direct and
indirect primary bases.
The BV_DELTA of each node gives the amount by which to adjust the
`this' pointer when calling the function. If the method is an
overridden version of a base class method, then it is assumed
that, prior to adjustment, the this pointer points to an object
of the base class.
The BV_VCALL_INDEX of each node, if non-NULL, gives the vtable
index of the vcall offset for this entry.
The BV_FN is the declaration for the virtual function itself.
If BV_LOST_PRIMARY is set, it means that this entry is for a lost
primary virtual base and can be left null in the vtable.
BINFO_VTABLE
This is an expression with POINTER_TYPE that gives the value
to which the vptr should be initialized. Use get_vtbl_decl_for_binfo
to extract the VAR_DECL for the complete vtable.
DECL_VINDEX
This field is NULL for a non-virtual function. For a virtual
function, it is eventually set to an INTEGER_CST indicating the
index in the vtable at which this function can be found. When
a virtual function is declared, but before it is known what
function is overridden, this field is the error_mark_node.
Temporarily, it may be set to a TREE_LIST whose TREE_VALUE is
the virtual function this one overrides, and whose TREE_CHAIN is
the old DECL_VINDEX. */
/* Language-specific tree checkers. */
#define VAR_OR_FUNCTION_DECL_CHECK(NODE) \
TREE_CHECK2(NODE,VAR_DECL,FUNCTION_DECL)
#define TYPE_FUNCTION_OR_TEMPLATE_DECL_CHECK(NODE) \
TREE_CHECK3(NODE,TYPE_DECL,TEMPLATE_DECL,FUNCTION_DECL)
#define TYPE_FUNCTION_OR_TEMPLATE_DECL_P(NODE) \
(TREE_CODE (NODE) == TYPE_DECL || TREE_CODE (NODE) == TEMPLATE_DECL \
|| TREE_CODE (NODE) == FUNCTION_DECL)
#define VAR_FUNCTION_OR_PARM_DECL_CHECK(NODE) \
TREE_CHECK3(NODE,VAR_DECL,FUNCTION_DECL,PARM_DECL)
#define VAR_TEMPL_TYPE_OR_FUNCTION_DECL_CHECK(NODE) \
TREE_CHECK4(NODE,VAR_DECL,FUNCTION_DECL,TYPE_DECL,TEMPLATE_DECL)
#define VAR_TEMPL_TYPE_FIELD_OR_FUNCTION_DECL_CHECK(NODE) \
TREE_CHECK5(NODE,VAR_DECL,FIELD_DECL,FUNCTION_DECL,TYPE_DECL,TEMPLATE_DECL)
#define BOUND_TEMPLATE_TEMPLATE_PARM_TYPE_CHECK(NODE) \
TREE_CHECK(NODE,BOUND_TEMPLATE_TEMPLATE_PARM)
#if defined ENABLE_TREE_CHECKING && (GCC_VERSION >= 2007)
#define THUNK_FUNCTION_CHECK(NODE) __extension__ \
({ __typeof (NODE) const __t = (NODE); \
if (TREE_CODE (__t) != FUNCTION_DECL || !__t->decl_common.lang_specific \
|| !__t->decl_common.lang_specific->u.fn.thunk_p) \
tree_check_failed (__t, __FILE__, __LINE__, __FUNCTION__, 0); \
__t; })
#else
#define THUNK_FUNCTION_CHECK(NODE) (NODE)
#endif
/* Language-dependent contents of an identifier. */
struct GTY(()) lang_identifier {
struct c_common_identifier c_common;
cxx_binding *namespace_bindings;
cxx_binding *bindings;
tree class_template_info;
tree label_value;
};
/* Return a typed pointer version of T if it designates a
C++ front-end identifier. */
inline lang_identifier*
identifier_p (tree t)
{
if (TREE_CODE (t) == IDENTIFIER_NODE)
return (lang_identifier*) t;
return NULL;
}
/* In an IDENTIFIER_NODE, nonzero if this identifier is actually a
keyword. C_RID_CODE (node) is then the RID_* value of the keyword. */
#define C_IS_RESERVED_WORD(ID) TREE_LANG_FLAG_5 (ID)
#define LANG_IDENTIFIER_CAST(NODE) \
((struct lang_identifier*)IDENTIFIER_NODE_CHECK (NODE))
struct GTY(()) template_parm_index {
struct tree_common common;
int index;
int level;
int orig_level;
tree decl;
};
struct GTY(()) ptrmem_cst {
struct tree_common common;
tree member;
};
typedef struct ptrmem_cst * ptrmem_cst_t;
#define IDENTIFIER_GLOBAL_VALUE(NODE) \
namespace_binding ((NODE), global_namespace)
#define SET_IDENTIFIER_GLOBAL_VALUE(NODE, VAL) \
set_namespace_binding ((NODE), global_namespace, (VAL))
#define IDENTIFIER_NAMESPACE_VALUE(NODE) \
namespace_binding ((NODE), current_namespace)
#define SET_IDENTIFIER_NAMESPACE_VALUE(NODE, VAL) \
set_namespace_binding ((NODE), current_namespace, (VAL))
#define CLEANUP_P(NODE) TREE_LANG_FLAG_0 (TRY_BLOCK_CHECK (NODE))
#define BIND_EXPR_TRY_BLOCK(NODE) \
TREE_LANG_FLAG_0 (BIND_EXPR_CHECK (NODE))
/* Used to mark the block around the member initializers and cleanups. */
#define BIND_EXPR_BODY_BLOCK(NODE) \
TREE_LANG_FLAG_3 (BIND_EXPR_CHECK (NODE))
#define FUNCTION_NEEDS_BODY_BLOCK(NODE) \
(DECL_CONSTRUCTOR_P (NODE) || DECL_DESTRUCTOR_P (NODE) \
|| LAMBDA_FUNCTION_P (NODE))
#define STATEMENT_LIST_NO_SCOPE(NODE) \
TREE_LANG_FLAG_0 (STATEMENT_LIST_CHECK (NODE))
#define STATEMENT_LIST_TRY_BLOCK(NODE) \
TREE_LANG_FLAG_2 (STATEMENT_LIST_CHECK (NODE))
/* Mark the outer curly brace BLOCK. */
#define BLOCK_OUTER_CURLY_BRACE_P(NODE) TREE_LANG_FLAG_0 (BLOCK_CHECK (NODE))
/* Nonzero if this statement should be considered a full-expression,
i.e., if temporaries created during this statement should have
their destructors run at the end of this statement. */
#define STMT_IS_FULL_EXPR_P(NODE) TREE_LANG_FLAG_1 ((NODE))
/* Marks the result of a statement expression. */
#define EXPR_STMT_STMT_EXPR_RESULT(NODE) \
TREE_LANG_FLAG_0 (EXPR_STMT_CHECK (NODE))
/* Nonzero if this statement-expression does not have an associated scope. */
#define STMT_EXPR_NO_SCOPE(NODE) \
TREE_LANG_FLAG_0 (STMT_EXPR_CHECK (NODE))
#define COND_EXPR_IS_VEC_DELETE(NODE) \
TREE_LANG_FLAG_0 (COND_EXPR_CHECK (NODE))
/* Returns nonzero iff TYPE1 and TYPE2 are the same type, in the usual
sense of `same'. */
#define same_type_p(TYPE1, TYPE2) \
comptypes ((TYPE1), (TYPE2), COMPARE_STRICT)
/* Returns nonzero iff NODE is a declaration for the global function
`main'. */
#define DECL_MAIN_P(NODE) \
(DECL_EXTERN_C_FUNCTION_P (NODE) \
&& DECL_NAME (NODE) != NULL_TREE \
&& MAIN_NAME_P (DECL_NAME (NODE)) \
&& flag_hosted)
/* The overloaded FUNCTION_DECL. */
#define OVL_FUNCTION(NODE) \
(((struct tree_overload*)OVERLOAD_CHECK (NODE))->function)
#define OVL_CHAIN(NODE) TREE_CHAIN (NODE)
/* Polymorphic access to FUNCTION and CHAIN. */
#define OVL_CURRENT(NODE) \
((TREE_CODE (NODE) == OVERLOAD) ? OVL_FUNCTION (NODE) : (NODE))
#define OVL_NEXT(NODE) \
((TREE_CODE (NODE) == OVERLOAD) ? TREE_CHAIN (NODE) : NULL_TREE)
/* If set, this was imported in a using declaration.
This is not to confuse with being used somewhere, which
is not important for this node. */
#define OVL_USED(NODE) TREE_USED (OVERLOAD_CHECK (NODE))
/* If set, this OVERLOAD was created for argument-dependent lookup
and can be freed afterward. */
#define OVL_ARG_DEPENDENT(NODE) TREE_LANG_FLAG_0 (OVERLOAD_CHECK (NODE))
struct GTY(()) tree_overload {
struct tree_common common;
tree function;
};
struct GTY(()) tree_template_decl {
struct tree_decl_common common;
tree arguments;
tree result;
};
/* Returns true iff NODE is a BASELINK. */
#define BASELINK_P(NODE) \
(TREE_CODE (NODE) == BASELINK)
/* The BINFO indicating the base in which lookup found the
BASELINK_FUNCTIONS. */
#define BASELINK_BINFO(NODE) \
(((struct tree_baselink*) BASELINK_CHECK (NODE))->binfo)
/* The functions referred to by the BASELINK; either a FUNCTION_DECL,
a TEMPLATE_DECL, an OVERLOAD, or a TEMPLATE_ID_EXPR. */
#define BASELINK_FUNCTIONS(NODE) \
(((struct tree_baselink*) BASELINK_CHECK (NODE))->functions)
/* The BINFO in which the search for the functions indicated by this baselink
began. This base is used to determine the accessibility of functions
selected by overload resolution. */
#define BASELINK_ACCESS_BINFO(NODE) \
(((struct tree_baselink*) BASELINK_CHECK (NODE))->access_binfo)
/* For a type-conversion operator, the BASELINK_OPTYPE indicates the type
to which the conversion should occur. This value is important if
the BASELINK_FUNCTIONS include a template conversion operator --
the BASELINK_OPTYPE can be used to determine what type the user
requested. */
#define BASELINK_OPTYPE(NODE) \
(TREE_CHAIN (BASELINK_CHECK (NODE)))
/* Nonzero if this baselink was from a qualified lookup. */
#define BASELINK_QUALIFIED_P(NODE) \
TREE_LANG_FLAG_0 (BASELINK_CHECK (NODE))
struct GTY(()) tree_baselink {
struct tree_common common;
tree binfo;
tree functions;
tree access_binfo;
};
/* The different kinds of ids that we encounter. */
enum cp_id_kind
{
/* Not an id at all. */
CP_ID_KIND_NONE,
/* An unqualified-id that is not a template-id. */
CP_ID_KIND_UNQUALIFIED,
/* An unqualified-id that is a dependent name. */
CP_ID_KIND_UNQUALIFIED_DEPENDENT,
/* An unqualified template-id. */
CP_ID_KIND_TEMPLATE_ID,
/* A qualified-id. */
CP_ID_KIND_QUALIFIED
};
/* The various kinds of C++0x warnings we encounter. */
enum cpp0x_warn_str
{
/* extended initializer lists */
CPP0X_INITIALIZER_LISTS,
/* explicit conversion operators */
CPP0X_EXPLICIT_CONVERSION,
/* variadic templates */
CPP0X_VARIADIC_TEMPLATES,
/* lambda expressions */
CPP0X_LAMBDA_EXPR,
/* C++0x auto */
CPP0X_AUTO,
/* scoped enums */
CPP0X_SCOPED_ENUMS,
/* defaulted and deleted functions */
CPP0X_DEFAULTED_DELETED,
/* inline namespaces */
CPP0X_INLINE_NAMESPACES,
/* override controls, override/final */
CPP0X_OVERRIDE_CONTROLS,
/* non-static data member initializers */
CPP0X_NSDMI,
/* user defined literals */
CPP0X_USER_DEFINED_LITERALS,
/* delegating constructors */
CPP0X_DELEGATING_CTORS,
/* inheriting constructors */
CPP0X_INHERITING_CTORS,
/* C++11 attributes */
CPP0X_ATTRIBUTES,
/* ref-qualified member functions */
CPP0X_REF_QUALIFIER
};
/* The various kinds of operation used by composite_pointer_type. */
enum composite_pointer_operation
{
/* comparison */
CPO_COMPARISON,
/* conversion */
CPO_CONVERSION,
/* conditional expression */
CPO_CONDITIONAL_EXPR
};
/* Possible cases of expression list used by build_x_compound_expr_from_list. */
enum expr_list_kind {
ELK_INIT, /* initializer */
ELK_MEM_INIT, /* member initializer */
ELK_FUNC_CAST /* functional cast */
};
/* Possible cases of implicit bad rhs conversions. */
enum impl_conv_rhs {
ICR_DEFAULT_ARGUMENT, /* default argument */
ICR_CONVERTING, /* converting */
ICR_INIT, /* initialization */
ICR_ARGPASS, /* argument passing */
ICR_RETURN, /* return */
ICR_ASSIGN /* assignment */
};
/* Possible cases of implicit or explicit bad conversions to void. */
enum impl_conv_void {
ICV_CAST, /* (explicit) conversion to void */
ICV_SECOND_OF_COND, /* second operand of conditional expression */
ICV_THIRD_OF_COND, /* third operand of conditional expression */
ICV_RIGHT_OF_COMMA, /* right operand of comma operator */
ICV_LEFT_OF_COMMA, /* left operand of comma operator */
ICV_STATEMENT, /* statement */
ICV_THIRD_IN_FOR /* for increment expression */
};
/* Possible invalid uses of an abstract class that might not have a
specific associated declaration. */
enum GTY(()) abstract_class_use {
ACU_UNKNOWN, /* unknown or decl provided */
ACU_CAST, /* cast to abstract class */
ACU_NEW, /* new-expression of abstract class */
ACU_THROW, /* throw-expression of abstract class */
ACU_CATCH, /* catch-parameter of abstract class */
ACU_ARRAY, /* array of abstract class */
ACU_RETURN, /* return type of abstract class */
ACU_PARM /* parameter type of abstract class */
};
/* Macros for access to language-specific slots in an identifier. */
#define IDENTIFIER_NAMESPACE_BINDINGS(NODE) \
(LANG_IDENTIFIER_CAST (NODE)->namespace_bindings)
#define IDENTIFIER_TEMPLATE(NODE) \
(LANG_IDENTIFIER_CAST (NODE)->class_template_info)
/* The IDENTIFIER_BINDING is the innermost cxx_binding for the
identifier. It's PREVIOUS is the next outermost binding. Each
VALUE field is a DECL for the associated declaration. Thus,
name lookup consists simply of pulling off the node at the front
of the list (modulo oddities for looking up the names of types,
and such.) You can use SCOPE field to determine the scope
that bound the name. */
#define IDENTIFIER_BINDING(NODE) \
(LANG_IDENTIFIER_CAST (NODE)->bindings)
/* TREE_TYPE only indicates on local and class scope the current
type. For namespace scope, the presence of a type in any namespace
is indicated with global_type_node, and the real type behind must
be found through lookup. */
#define IDENTIFIER_TYPE_VALUE(NODE) identifier_type_value (NODE)
#define REAL_IDENTIFIER_TYPE_VALUE(NODE) TREE_TYPE (NODE)
#define SET_IDENTIFIER_TYPE_VALUE(NODE,TYPE) (TREE_TYPE (NODE) = (TYPE))
#define IDENTIFIER_HAS_TYPE_VALUE(NODE) (IDENTIFIER_TYPE_VALUE (NODE) ? 1 : 0)
#define IDENTIFIER_LABEL_VALUE(NODE) \
(LANG_IDENTIFIER_CAST (NODE)->label_value)
#define SET_IDENTIFIER_LABEL_VALUE(NODE, VALUE) \
IDENTIFIER_LABEL_VALUE (NODE) = (VALUE)
/* Nonzero if this identifier is used as a virtual function name somewhere
(optimizes searches). */
#define IDENTIFIER_VIRTUAL_P(NODE) TREE_LANG_FLAG_1 (NODE)
/* Nonzero if this identifier is the prefix for a mangled C++ operator
name. */
#define IDENTIFIER_OPNAME_P(NODE) TREE_LANG_FLAG_2 (NODE)
/* Nonzero if this identifier is the name of a type-conversion
operator. */
#define IDENTIFIER_TYPENAME_P(NODE) \
TREE_LANG_FLAG_4 (NODE)
/* Nonzero if this identifier is the name of a constructor or
destructor. */
#define IDENTIFIER_CTOR_OR_DTOR_P(NODE) \
TREE_LANG_FLAG_3 (NODE)
/* True iff NAME is the DECL_ASSEMBLER_NAME for an entity with vague
linkage which the prelinker has assigned to this translation
unit. */
#define IDENTIFIER_REPO_CHOSEN(NAME) \
(TREE_LANG_FLAG_6 (NAME))
/* In a RECORD_TYPE or UNION_TYPE, nonzero if any component is read-only. */
#define C_TYPE_FIELDS_READONLY(TYPE) \
(LANG_TYPE_CLASS_CHECK (TYPE)->fields_readonly)
/* The tokens stored in the default argument. */
#define DEFARG_TOKENS(NODE) \
(((struct tree_default_arg *)DEFAULT_ARG_CHECK (NODE))->tokens)
#define DEFARG_INSTANTIATIONS(NODE) \
(((struct tree_default_arg *)DEFAULT_ARG_CHECK (NODE))->instantiations)
struct GTY (()) tree_default_arg {
struct tree_common common;
struct cp_token_cache *tokens;
vec<tree, va_gc> *instantiations;
};
#define DEFERRED_NOEXCEPT_PATTERN(NODE) \
(((struct tree_deferred_noexcept *)DEFERRED_NOEXCEPT_CHECK (NODE))->pattern)
#define DEFERRED_NOEXCEPT_ARGS(NODE) \
(((struct tree_deferred_noexcept *)DEFERRED_NOEXCEPT_CHECK (NODE))->args)
#define DEFERRED_NOEXCEPT_SPEC_P(NODE) \
((NODE) && (TREE_PURPOSE (NODE)) \
&& (TREE_CODE (TREE_PURPOSE (NODE)) == DEFERRED_NOEXCEPT))
#define UNEVALUATED_NOEXCEPT_SPEC_P(NODE) \
(DEFERRED_NOEXCEPT_SPEC_P (NODE) \
&& DEFERRED_NOEXCEPT_PATTERN (TREE_PURPOSE (NODE)) == NULL_TREE)
struct GTY (()) tree_deferred_noexcept {
struct tree_base base;
tree pattern;
tree args;
};
/* The condition associated with the static assertion. This must be
an integral constant expression. */
#define STATIC_ASSERT_CONDITION(NODE) \
(((struct tree_static_assert *)STATIC_ASSERT_CHECK (NODE))->condition)
/* The message associated with the static assertion. This must be a
string constant, which will be emitted as an error message when the
static assert condition is false. */
#define STATIC_ASSERT_MESSAGE(NODE) \
(((struct tree_static_assert *)STATIC_ASSERT_CHECK (NODE))->message)
/* Source location information for a static assertion. */
#define STATIC_ASSERT_SOURCE_LOCATION(NODE) \
(((struct tree_static_assert *)STATIC_ASSERT_CHECK (NODE))->location)
struct GTY (()) tree_static_assert {
struct tree_common common;
tree condition;
tree message;
location_t location;
};
struct GTY (()) tree_argument_pack_select {
struct tree_common common;
tree argument_pack;
int index;
};
/* The different kinds of traits that we encounter. */
enum cp_trait_kind
{
CPTK_BASES,
CPTK_DIRECT_BASES,
CPTK_HAS_NOTHROW_ASSIGN,
CPTK_HAS_NOTHROW_CONSTRUCTOR,
CPTK_HAS_NOTHROW_COPY,
CPTK_HAS_TRIVIAL_ASSIGN,
CPTK_HAS_TRIVIAL_CONSTRUCTOR,
CPTK_HAS_TRIVIAL_COPY,
CPTK_HAS_TRIVIAL_DESTRUCTOR,
CPTK_HAS_UNIQUE_OBJ_REPRESENTATIONS,
CPTK_HAS_VIRTUAL_DESTRUCTOR,
CPTK_IS_ABSTRACT,
CPTK_IS_AGGREGATE,
CPTK_IS_BASE_OF,
CPTK_IS_CLASS,
CPTK_IS_EMPTY,
CPTK_IS_ENUM,
CPTK_IS_FINAL,
CPTK_IS_LITERAL_TYPE,
CPTK_IS_POD,
CPTK_IS_POLYMORPHIC,
CPTK_IS_SAME_AS,
CPTK_IS_STD_LAYOUT,
CPTK_IS_TRIVIAL,
CPTK_IS_TRIVIALLY_ASSIGNABLE,
CPTK_IS_TRIVIALLY_CONSTRUCTIBLE,
CPTK_IS_TRIVIALLY_COPYABLE,
CPTK_IS_UNION,
CPTK_UNDERLYING_TYPE
};
/* The types that we are processing. */
#define TRAIT_EXPR_TYPE1(NODE) \
(((struct tree_trait_expr *)TRAIT_EXPR_CHECK (NODE))->type1)
#define TRAIT_EXPR_TYPE2(NODE) \
(((struct tree_trait_expr *)TRAIT_EXPR_CHECK (NODE))->type2)
/* The specific trait that we are processing. */
#define TRAIT_EXPR_KIND(NODE) \
(((struct tree_trait_expr *)TRAIT_EXPR_CHECK (NODE))->kind)
struct GTY (()) tree_trait_expr {
struct tree_common common;
tree type1;
tree type2;
enum cp_trait_kind kind;
};
/* Based off of TYPE_UNNAMED_P. */
#define LAMBDA_TYPE_P(NODE) \
(CLASS_TYPE_P (NODE) && CLASSTYPE_LAMBDA_EXPR (NODE))
/* Test if FUNCTION_DECL is a lambda function. */
#define LAMBDA_FUNCTION_P(FNDECL) \
(DECL_OVERLOADED_OPERATOR_P (FNDECL) == CALL_EXPR \
&& LAMBDA_TYPE_P (CP_DECL_CONTEXT (FNDECL)))
enum cp_lambda_default_capture_mode_type {
CPLD_NONE,
CPLD_COPY,
CPLD_REFERENCE
};
/* The method of default capture, if any. */
#define LAMBDA_EXPR_DEFAULT_CAPTURE_MODE(NODE) \
(((struct tree_lambda_expr *)LAMBDA_EXPR_CHECK (NODE))->default_capture_mode)
/* The capture-list, including `this'. Each capture is stored as a FIELD_DECL
* so that the name, type, and field are all together, whether or not it has
* been added to the lambda's class type.
TREE_LIST:
TREE_PURPOSE: The FIELD_DECL for this capture.
TREE_VALUE: The initializer. This is part of a GNU extension. */
#define LAMBDA_EXPR_CAPTURE_LIST(NODE) \
(((struct tree_lambda_expr *)LAMBDA_EXPR_CHECK (NODE))->capture_list)
/* During parsing of the lambda-introducer, the node in the capture-list
that holds the 'this' capture. During parsing of the body, the
capture proxy for that node. */
#define LAMBDA_EXPR_THIS_CAPTURE(NODE) \
(((struct tree_lambda_expr *)LAMBDA_EXPR_CHECK (NODE))->this_capture)
/* Predicate tracking whether `this' is in the effective capture set. */
#define LAMBDA_EXPR_CAPTURES_THIS_P(NODE) \
LAMBDA_EXPR_THIS_CAPTURE(NODE)
/* Predicate tracking whether the lambda was declared 'mutable'. */
#define LAMBDA_EXPR_MUTABLE_P(NODE) \
TREE_LANG_FLAG_1 (LAMBDA_EXPR_CHECK (NODE))
/* The return type in the expression.
* NULL_TREE indicates that none was specified. */
#define LAMBDA_EXPR_RETURN_TYPE(NODE) \
(((struct tree_lambda_expr *)LAMBDA_EXPR_CHECK (NODE))->return_type)
/* The source location of the lambda. */
#define LAMBDA_EXPR_LOCATION(NODE) \
(((struct tree_lambda_expr *)LAMBDA_EXPR_CHECK (NODE))->locus)
/* The mangling scope for the lambda: FUNCTION_DECL, PARM_DECL, VAR_DECL,
FIELD_DECL or NULL_TREE. If this is NULL_TREE, we have no linkage. */
#define LAMBDA_EXPR_EXTRA_SCOPE(NODE) \
(((struct tree_lambda_expr *)LAMBDA_EXPR_CHECK (NODE))->extra_scope)
/* If EXTRA_SCOPE, this is the number of the lambda within that scope. */
#define LAMBDA_EXPR_DISCRIMINATOR(NODE) \
(((struct tree_lambda_expr *)LAMBDA_EXPR_CHECK (NODE))->discriminator)
/* During parsing of the lambda, a vector of capture proxies which need
to be pushed once we're done processing a nested lambda. */
#define LAMBDA_EXPR_PENDING_PROXIES(NODE) \
(((struct tree_lambda_expr *)LAMBDA_EXPR_CHECK (NODE))->pending_proxies)
/* The closure type of the lambda. Note that the TREE_TYPE of a
LAMBDA_EXPR is always NULL_TREE, because we need to instantiate the
LAMBDA_EXPR in order to instantiate the type. */
#define LAMBDA_EXPR_CLOSURE(NODE) \
(((struct tree_lambda_expr *)LAMBDA_EXPR_CHECK (NODE))->closure)
struct GTY (()) tree_lambda_expr
{
struct tree_typed typed;
tree capture_list;
tree this_capture;
tree return_type;
tree extra_scope;
tree closure;
vec<tree, va_gc> *pending_proxies;
location_t locus;
enum cp_lambda_default_capture_mode_type default_capture_mode;
int discriminator;
};
/* A (typedef,context,usage location) triplet.
It represents a typedef used through a
context at a given source location.
e.g.
struct foo {
typedef int myint;
};
struct bar {
foo::myint v; // #1<-- this location.
};
In bar, the triplet will be (myint, foo, #1).
*/
struct GTY(()) qualified_typedef_usage_s {
tree typedef_decl;
tree context;
location_t locus;
};
typedef struct qualified_typedef_usage_s qualified_typedef_usage_t;
/* Non-zero if this template specialization has access violations that
should be rechecked when the function is instantiated outside argument
deduction. */
#define TINFO_HAS_ACCESS_ERRORS(NODE) \
(TREE_LANG_FLAG_0 (TEMPLATE_INFO_CHECK (NODE)))
#define FNDECL_HAS_ACCESS_ERRORS(NODE) \
(TINFO_HAS_ACCESS_ERRORS (DECL_TEMPLATE_INFO (NODE)))
/* Non-zero if this variable template specialization was specified using a
template-id, so it's a partial or full specialization and not a definition
of the member template of a particular class specialization. */
#define TINFO_USED_TEMPLATE_ID(NODE) \
(TREE_LANG_FLAG_1 (TEMPLATE_INFO_CHECK (NODE)))
struct GTY(()) tree_template_info {
struct tree_common common;
vec<qualified_typedef_usage_t, va_gc> *typedefs_needing_access_checking;
};
// Constraint information for a C++ declaration. Constraint information is
// comprised of:
//
// - a constraint expression introduced by the template header
// - a constraint expression introduced by a function declarator
// - the associated constraints, which are the conjunction of those,
// and used for declaration matching
//
// The template and declarator requirements are kept to support pretty
// printing constrained declarations.
struct GTY(()) tree_constraint_info {
struct tree_base base;
tree template_reqs;
tree declarator_reqs;
tree associated_constr;
};
// Require that pointer P is non-null before returning.
template<typename T>
inline T*
check_nonnull (T* p)
{
gcc_assert (p);
return p;
}
// Returns true iff T is non-null and represents constraint info.
inline tree_constraint_info *
check_constraint_info (tree t)
{
if (t && TREE_CODE (t) == CONSTRAINT_INFO)
return (tree_constraint_info *)t;
return NULL;
}
// Access the expression describing the template constraints. This may be
// null if no constraints were introduced in the template parameter list,
// a requirements clause after the template parameter list, or constraints
// through a constrained-type-specifier.
#define CI_TEMPLATE_REQS(NODE) \
check_constraint_info (check_nonnull(NODE))->template_reqs
// Access the expression describing the trailing constraints. This is non-null
// for any implicit instantiation of a constrained declaration. For a
// templated declaration it is non-null only when a trailing requires-clause
// was specified.
#define CI_DECLARATOR_REQS(NODE) \
check_constraint_info (check_nonnull(NODE))->declarator_reqs
// The computed associated constraint expression for a declaration.
#define CI_ASSOCIATED_CONSTRAINTS(NODE) \
check_constraint_info (check_nonnull(NODE))->associated_constr
// Access the logical constraints on the template parameters introduced
// at a given template parameter list level indicated by NODE.
#define TEMPLATE_PARMS_CONSTRAINTS(NODE) \
TREE_TYPE (TREE_LIST_CHECK (NODE))
// Access the logical constraints on the template parameter declaration
// indicated by NODE.
#define TEMPLATE_PARM_CONSTRAINTS(NODE) \
TREE_TYPE (TREE_LIST_CHECK (NODE))
/* Non-zero if the noexcept is present in a compound requirement. */
#define COMPOUND_REQ_NOEXCEPT_P(NODE) \
TREE_LANG_FLAG_0 (TREE_CHECK (NODE, COMPOUND_REQ))
/* The constraints on an 'auto' placeholder type, used in an argument deduction
constraint. */
#define PLACEHOLDER_TYPE_CONSTRAINTS(NODE) \
DECL_SIZE_UNIT (TYPE_NAME (NODE))
/* The expression evaluated by the predicate constraint. */
#define PRED_CONSTR_EXPR(NODE) \
TREE_OPERAND (TREE_CHECK (NODE, PRED_CONSTR), 0)
/* The concept of a concept check. */
#define CHECK_CONSTR_CONCEPT(NODE) \
TREE_OPERAND (TREE_CHECK (NODE, CHECK_CONSTR), 0)
/* The template arguments of a concept check. */
#define CHECK_CONSTR_ARGS(NODE) \
TREE_OPERAND (TREE_CHECK (NODE, CHECK_CONSTR), 1)
/* The expression validated by the predicate constraint. */
#define EXPR_CONSTR_EXPR(NODE) \
TREE_OPERAND (TREE_CHECK (NODE, EXPR_CONSTR), 0)
/* The type validated by the predicate constraint. */
#define TYPE_CONSTR_TYPE(NODE) \
TREE_OPERAND (TREE_CHECK (NODE, TYPE_CONSTR), 0)
/* In an implicit conversion constraint, the source expression. */
#define ICONV_CONSTR_EXPR(NODE) \
TREE_OPERAND (TREE_CHECK (NODE, ICONV_CONSTR), 0)
/* In an implicit conversion constraint, the target type. */
#define ICONV_CONSTR_TYPE(NODE) \
TREE_OPERAND (TREE_CHECK (NODE, ICONV_CONSTR), 1)
/* In an argument deduction constraint, the source expression. */
#define DEDUCT_CONSTR_EXPR(NODE) \
TREE_OPERAND (TREE_CHECK (NODE, DEDUCT_CONSTR), 0)
/* In an argument deduction constraint, the target type pattern. */
#define DEDUCT_CONSTR_PATTERN(NODE) \
TREE_OPERAND (TREE_CHECK (NODE, DEDUCT_CONSTR), 1)
/* In an argument deduction constraint, the list of placeholder nodes. */
#define DEDUCT_CONSTR_PLACEHOLDER(NODE) \
TREE_OPERAND (TREE_CHECK (NODE, DEDUCT_CONSTR), 2)
/* The expression of an exception constraint. */
#define EXCEPT_CONSTR_EXPR(NODE) \
TREE_OPERAND (TREE_CHECK (NODE, EXCEPT_CONSTR), 0)
/* In a parameterized constraint, the local parameters. */
#define PARM_CONSTR_PARMS(NODE) \
TREE_OPERAND (TREE_CHECK (NODE, PARM_CONSTR), 0)
/* In a parameterized constraint, the operand. */
#define PARM_CONSTR_OPERAND(NODE) \
TREE_OPERAND (TREE_CHECK (NODE, PARM_CONSTR), 1)
/* Whether a PARM_DECL represents a local parameter in a
requires-expression. */
#define CONSTRAINT_VAR_P(NODE) \
DECL_LANG_FLAG_2 (TREE_CHECK (NODE, PARM_DECL))
/* The concept constraining this constrained template-parameter. */
#define CONSTRAINED_PARM_CONCEPT(NODE) \
DECL_SIZE_UNIT (TYPE_DECL_CHECK (NODE))
/* Any extra template arguments specified for a constrained
template-parameter. */
#define CONSTRAINED_PARM_EXTRA_ARGS(NODE) \
DECL_SIZE (TYPE_DECL_CHECK (NODE))
/* The first template parameter of CONSTRAINED_PARM_CONCEPT to be used as a
prototype for the constrained parameter in finish_shorthand_constraint,
attached for convenience. */
#define CONSTRAINED_PARM_PROTOTYPE(NODE) \
DECL_INITIAL (TYPE_DECL_CHECK (NODE))
enum cp_tree_node_structure_enum {
TS_CP_GENERIC,
TS_CP_IDENTIFIER,
TS_CP_TPI,
TS_CP_PTRMEM,
TS_CP_BINDING,
TS_CP_OVERLOAD,
TS_CP_BASELINK,
TS_CP_TEMPLATE_DECL,
TS_CP_WRAPPER,
TS_CP_DEFAULT_ARG,
TS_CP_DEFERRED_NOEXCEPT,
TS_CP_STATIC_ASSERT,
TS_CP_ARGUMENT_PACK_SELECT,
TS_CP_TRAIT_EXPR,
TS_CP_LAMBDA_EXPR,
TS_CP_TEMPLATE_INFO,
TS_CP_CONSTRAINT_INFO,
TS_CP_USERDEF_LITERAL,
LAST_TS_CP_ENUM
};
/* The resulting tree type. */
union GTY((desc ("cp_tree_node_structure (&%h)"),
chain_next ("(union lang_tree_node *) c_tree_chain_next (&%h.generic)"))) lang_tree_node {
union tree_node GTY ((tag ("TS_CP_GENERIC"),
desc ("tree_node_structure (&%h)"))) generic;
struct template_parm_index GTY ((tag ("TS_CP_TPI"))) tpi;
struct ptrmem_cst GTY ((tag ("TS_CP_PTRMEM"))) ptrmem;
struct tree_overload GTY ((tag ("TS_CP_OVERLOAD"))) overload;
struct tree_baselink GTY ((tag ("TS_CP_BASELINK"))) baselink;
struct tree_template_decl GTY ((tag ("TS_CP_TEMPLATE_DECL"))) template_decl;
struct tree_default_arg GTY ((tag ("TS_CP_DEFAULT_ARG"))) default_arg;
struct tree_deferred_noexcept GTY ((tag ("TS_CP_DEFERRED_NOEXCEPT"))) deferred_noexcept;
struct lang_identifier GTY ((tag ("TS_CP_IDENTIFIER"))) identifier;
struct tree_static_assert GTY ((tag ("TS_CP_STATIC_ASSERT")))
static_assertion;
struct tree_argument_pack_select GTY ((tag ("TS_CP_ARGUMENT_PACK_SELECT")))
argument_pack_select;
struct tree_trait_expr GTY ((tag ("TS_CP_TRAIT_EXPR")))
trait_expression;
struct tree_lambda_expr GTY ((tag ("TS_CP_LAMBDA_EXPR")))
lambda_expression;
struct tree_template_info GTY ((tag ("TS_CP_TEMPLATE_INFO")))
template_info;
struct tree_constraint_info GTY ((tag ("TS_CP_CONSTRAINT_INFO")))
constraint_info;
struct tree_userdef_literal GTY ((tag ("TS_CP_USERDEF_LITERAL")))
userdef_literal;
};
enum cp_tree_index
{
CPTI_WCHAR_DECL,
CPTI_VTABLE_ENTRY_TYPE,
CPTI_DELTA_TYPE,
CPTI_VTABLE_INDEX_TYPE,
CPTI_CLEANUP_TYPE,
CPTI_VTT_PARM_TYPE,
CPTI_CLASS_TYPE,
CPTI_UNKNOWN_TYPE,
CPTI_INIT_LIST_TYPE,
CPTI_VTBL_TYPE,
CPTI_VTBL_PTR_TYPE,
CPTI_STD,
CPTI_ABI,
CPTI_CONST_TYPE_INFO_TYPE,
CPTI_TYPE_INFO_PTR_TYPE,
CPTI_ABORT_FNDECL,
CPTI_AGGR_TAG,
CPTI_CTOR_IDENTIFIER,
CPTI_COMPLETE_CTOR_IDENTIFIER,
CPTI_BASE_CTOR_IDENTIFIER,
CPTI_DTOR_IDENTIFIER,
CPTI_COMPLETE_DTOR_IDENTIFIER,
CPTI_BASE_DTOR_IDENTIFIER,
CPTI_DELETING_DTOR_IDENTIFIER,
CPTI_DELTA_IDENTIFIER,
CPTI_IN_CHARGE_IDENTIFIER,
CPTI_VTT_PARM_IDENTIFIER,
CPTI_NELTS_IDENTIFIER,
CPTI_THIS_IDENTIFIER,
CPTI_PFN_IDENTIFIER,
CPTI_VPTR_IDENTIFIER,
CPTI_STD_IDENTIFIER,
CPTI_AUTO_IDENTIFIER,
CPTI_DECLTYPE_AUTO_IDENTIFIER,
CPTI_LANG_NAME_C,
CPTI_LANG_NAME_CPLUSPLUS,
CPTI_EMPTY_EXCEPT_SPEC,
CPTI_NOEXCEPT_TRUE_SPEC,
CPTI_NOEXCEPT_FALSE_SPEC,
CPTI_TERMINATE,
CPTI_CALL_UNEXPECTED,
CPTI_ATEXIT_FN_PTR_TYPE,
CPTI_ATEXIT,
CPTI_DSO_HANDLE,
CPTI_DCAST,
CPTI_KEYED_CLASSES,
CPTI_NULLPTR,
CPTI_NULLPTR_TYPE,
CPTI_ALIGN_TYPE,
CPTI_ANY_TARG,
CPTI_MAX
};
extern GTY(()) tree cp_global_trees[CPTI_MAX];
#define wchar_decl_node cp_global_trees[CPTI_WCHAR_DECL]
#define vtable_entry_type cp_global_trees[CPTI_VTABLE_ENTRY_TYPE]
/* The type used to represent an offset by which to adjust the `this'
pointer in pointer-to-member types. */
#define delta_type_node cp_global_trees[CPTI_DELTA_TYPE]
/* The type used to represent an index into the vtable. */
#define vtable_index_type cp_global_trees[CPTI_VTABLE_INDEX_TYPE]
#define class_type_node cp_global_trees[CPTI_CLASS_TYPE]
#define unknown_type_node cp_global_trees[CPTI_UNKNOWN_TYPE]
#define init_list_type_node cp_global_trees[CPTI_INIT_LIST_TYPE]
#define vtbl_type_node cp_global_trees[CPTI_VTBL_TYPE]
#define vtbl_ptr_type_node cp_global_trees[CPTI_VTBL_PTR_TYPE]
#define std_node cp_global_trees[CPTI_STD]
#define abi_node cp_global_trees[CPTI_ABI]
#define const_type_info_type_node cp_global_trees[CPTI_CONST_TYPE_INFO_TYPE]
#define type_info_ptr_type cp_global_trees[CPTI_TYPE_INFO_PTR_TYPE]
#define abort_fndecl cp_global_trees[CPTI_ABORT_FNDECL]
#define current_aggr cp_global_trees[CPTI_AGGR_TAG]
#define nullptr_node cp_global_trees[CPTI_NULLPTR]
#define nullptr_type_node cp_global_trees[CPTI_NULLPTR_TYPE]
/* std::align_val_t */
#define align_type_node cp_global_trees[CPTI_ALIGN_TYPE]
/* We cache these tree nodes so as to call get_identifier less
frequently. */
/* The name of a constructor that takes an in-charge parameter to
decide whether or not to construct virtual base classes. */
#define ctor_identifier cp_global_trees[CPTI_CTOR_IDENTIFIER]
/* The name of a constructor that constructs virtual base classes. */
#define complete_ctor_identifier cp_global_trees[CPTI_COMPLETE_CTOR_IDENTIFIER]
/* The name of a constructor that does not construct virtual base classes. */
#define base_ctor_identifier cp_global_trees[CPTI_BASE_CTOR_IDENTIFIER]
/* The name of a destructor that takes an in-charge parameter to
decide whether or not to destroy virtual base classes and whether
or not to delete the object. */
#define dtor_identifier cp_global_trees[CPTI_DTOR_IDENTIFIER]
/* The name of a destructor that destroys virtual base classes. */
#define complete_dtor_identifier cp_global_trees[CPTI_COMPLETE_DTOR_IDENTIFIER]
/* The name of a destructor that does not destroy virtual base
classes. */
#define base_dtor_identifier cp_global_trees[CPTI_BASE_DTOR_IDENTIFIER]
/* The name of a destructor that destroys virtual base classes, and
then deletes the entire object. */
#define deleting_dtor_identifier cp_global_trees[CPTI_DELETING_DTOR_IDENTIFIER]
#define delta_identifier cp_global_trees[CPTI_DELTA_IDENTIFIER]
#define in_charge_identifier cp_global_trees[CPTI_IN_CHARGE_IDENTIFIER]
/* The name of the parameter that contains a pointer to the VTT to use
for this subobject constructor or destructor. */
#define vtt_parm_identifier cp_global_trees[CPTI_VTT_PARM_IDENTIFIER]
#define nelts_identifier cp_global_trees[CPTI_NELTS_IDENTIFIER]
#define this_identifier cp_global_trees[CPTI_THIS_IDENTIFIER]
#define pfn_identifier cp_global_trees[CPTI_PFN_IDENTIFIER]
#define vptr_identifier cp_global_trees[CPTI_VPTR_IDENTIFIER]
/* The name of the std namespace. */
#define std_identifier cp_global_trees[CPTI_STD_IDENTIFIER]
/* auto and declspec(auto) identifiers. */
#define auto_identifier cp_global_trees[CPTI_AUTO_IDENTIFIER]
#define decltype_auto_identifier cp_global_trees[CPTI_DECLTYPE_AUTO_IDENTIFIER]
/* The name of a C++17 deduction guide. */
#define lang_name_c cp_global_trees[CPTI_LANG_NAME_C]
#define lang_name_cplusplus cp_global_trees[CPTI_LANG_NAME_CPLUSPLUS]
/* Exception specifiers used for throw(), noexcept(true) and
noexcept(false). We rely on these being uncloned. */
#define empty_except_spec cp_global_trees[CPTI_EMPTY_EXCEPT_SPEC]
#define noexcept_true_spec cp_global_trees[CPTI_NOEXCEPT_TRUE_SPEC]
#define noexcept_false_spec cp_global_trees[CPTI_NOEXCEPT_FALSE_SPEC]
/* The declaration for `std::terminate'. */
#define terminate_node cp_global_trees[CPTI_TERMINATE]
/* The declaration for "__cxa_call_unexpected". */
#define call_unexpected_node cp_global_trees[CPTI_CALL_UNEXPECTED]
/* The type of the function-pointer argument to "__cxa_atexit" (or
"std::atexit", if "__cxa_atexit" is not being used). */
#define atexit_fn_ptr_type_node cp_global_trees[CPTI_ATEXIT_FN_PTR_TYPE]
/* A pointer to `std::atexit'. */
#define atexit_node cp_global_trees[CPTI_ATEXIT]
/* A pointer to `__dso_handle'. */
#define dso_handle_node cp_global_trees[CPTI_DSO_HANDLE]
/* The declaration of the dynamic_cast runtime. */
#define dynamic_cast_node cp_global_trees[CPTI_DCAST]
/* The type of a destructor. */
#define cleanup_type cp_global_trees[CPTI_CLEANUP_TYPE]
/* The type of the vtt parameter passed to subobject constructors and
destructors. */
#define vtt_parm_type cp_global_trees[CPTI_VTT_PARM_TYPE]
/* A TREE_LIST of the dynamic classes whose vtables may have to be
emitted in this translation unit. */
#define keyed_classes cp_global_trees[CPTI_KEYED_CLASSES]
/* A node which matches any template argument. */
#define any_targ_node cp_global_trees[CPTI_ANY_TARG]
/* Node to indicate default access. This must be distinct from the
access nodes in tree.h. */
#define access_default_node null_node
/* Global state. */
struct GTY(()) saved_scope {
vec<cxx_saved_binding, va_gc> *old_bindings;
tree old_namespace;
vec<tree, va_gc> *decl_ns_list;
tree class_name;
tree class_type;
tree access_specifier;
tree function_decl;
vec<tree, va_gc> *lang_base;
tree lang_name;
tree template_parms;
cp_binding_level *x_previous_class_level;
tree x_saved_tree;
/* Only used for uses of this in trailing return type. */
tree x_current_class_ptr;
tree x_current_class_ref;
int x_processing_template_decl;
int x_processing_specialization;
BOOL_BITFIELD x_processing_explicit_instantiation : 1;
BOOL_BITFIELD need_pop_function_context : 1;
/* Nonzero if we are parsing the discarded statement of a constexpr
if-statement. */
BOOL_BITFIELD discarded_stmt : 1;
int unevaluated_operand;
int inhibit_evaluation_warnings;
int noexcept_operand;
/* If non-zero, implicit "omp declare target" attribute is added into the
attribute lists. */
int omp_declare_target_attribute;
struct stmt_tree_s x_stmt_tree;
cp_binding_level *class_bindings;
cp_binding_level *bindings;
hash_map<tree, tree> *GTY((skip)) x_local_specializations;
struct saved_scope *prev;
};
extern GTY(()) struct saved_scope *scope_chain;
/* The current open namespace. */
#define current_namespace scope_chain->old_namespace
/* The stack for namespaces of current declarations. */
#define decl_namespace_list scope_chain->decl_ns_list
/* IDENTIFIER_NODE: name of current class */
#define current_class_name scope_chain->class_name
/* _TYPE: the type of the current class */
#define current_class_type scope_chain->class_type
/* When parsing a class definition, the access specifier most recently
given by the user, or, if no access specifier was given, the
default value appropriate for the kind of class (i.e., struct,
class, or union). */
#define current_access_specifier scope_chain->access_specifier
/* Pointer to the top of the language name stack. */
#define current_lang_base scope_chain->lang_base
#define current_lang_name scope_chain->lang_name
/* When parsing a template declaration, a TREE_LIST represents the
active template parameters. Each node in the list represents one
level of template parameters. The innermost level is first in the
list. The depth of each level is stored as an INTEGER_CST in the
TREE_PURPOSE of each node. The parameters for that level are
stored in the TREE_VALUE. */
#define current_template_parms scope_chain->template_parms
#define processing_template_decl scope_chain->x_processing_template_decl
#define processing_specialization scope_chain->x_processing_specialization
#define processing_explicit_instantiation scope_chain->x_processing_explicit_instantiation
#define in_discarded_stmt scope_chain->discarded_stmt
/* RAII sentinel to handle clearing processing_template_decl and restoring
it when done. */
struct processing_template_decl_sentinel
{
int saved;
processing_template_decl_sentinel (bool reset = true)
: saved (processing_template_decl)
{
if (reset)
processing_template_decl = 0;
}
~processing_template_decl_sentinel()
{
processing_template_decl = saved;
}
};
/* RAII sentinel to disable certain warnings during template substitution
and elsewhere. */
struct warning_sentinel
{
int &flag;
int val;
warning_sentinel(int& flag, bool suppress=true)
: flag(flag), val(flag) { if (suppress) flag = 0; }
~warning_sentinel() { flag = val; }
};
/* The cached class binding level, from the most recently exited
class, or NULL if none. */
#define previous_class_level scope_chain->x_previous_class_level
/* A map from local variable declarations in the body of the template
presently being instantiated to the corresponding instantiated
local variables. */
#define local_specializations scope_chain->x_local_specializations
/* Nonzero if we are parsing the operand of a noexcept operator. */
#define cp_noexcept_operand scope_chain->noexcept_operand
/* A list of private types mentioned, for deferred access checking. */
struct GTY((for_user)) cxx_int_tree_map {
unsigned int uid;
tree to;
};
struct cxx_int_tree_map_hasher : ggc_ptr_hash<cxx_int_tree_map>
{
static hashval_t hash (cxx_int_tree_map *);
static bool equal (cxx_int_tree_map *, cxx_int_tree_map *);
};
struct named_label_entry;
struct named_label_hasher : ggc_ptr_hash<named_label_entry>
{
static hashval_t hash (named_label_entry *);
static bool equal (named_label_entry *, named_label_entry *);
};
/* Global state pertinent to the current function. */
struct GTY(()) language_function {
struct c_language_function base;
tree x_cdtor_label;
tree x_current_class_ptr;
tree x_current_class_ref;
tree x_eh_spec_block;
tree x_in_charge_parm;
tree x_vtt_parm;
tree x_return_value;
tree x_auto_return_pattern;
BOOL_BITFIELD returns_value : 1;
BOOL_BITFIELD returns_null : 1;
BOOL_BITFIELD returns_abnormally : 1;
BOOL_BITFIELD infinite_loop: 1;
BOOL_BITFIELD x_in_function_try_handler : 1;
BOOL_BITFIELD x_in_base_initializer : 1;
/* True if this function can throw an exception. */
BOOL_BITFIELD can_throw : 1;
BOOL_BITFIELD invalid_constexpr : 1;
hash_table<named_label_hasher> *x_named_labels;
cp_binding_level *bindings;
vec<tree, va_gc> *x_local_names;
/* Tracking possibly infinite loops. This is a vec<tree> only because
vec<bool> doesn't work with gtype. */
vec<tree, va_gc> *infinite_loops;
hash_table<cxx_int_tree_map_hasher> *extern_decl_map;
};
/* The current C++-specific per-function global variables. */
#define cp_function_chain (cfun->language)
/* In a constructor destructor, the point at which all derived class
destroying/construction has been done. I.e., just before a
constructor returns, or before any base class destroying will be done
in a destructor. */
#define cdtor_label cp_function_chain->x_cdtor_label
/* When we're processing a member function, current_class_ptr is the
PARM_DECL for the `this' pointer. The current_class_ref is an
expression for `*this'. */
#define current_class_ptr \
(*(cfun && cp_function_chain \
? &cp_function_chain->x_current_class_ptr \
: &scope_chain->x_current_class_ptr))
#define current_class_ref \
(*(cfun && cp_function_chain \
? &cp_function_chain->x_current_class_ref \
: &scope_chain->x_current_class_ref))
/* The EH_SPEC_BLOCK for the exception-specifiers for the current
function, if any. */
#define current_eh_spec_block cp_function_chain->x_eh_spec_block
/* The `__in_chrg' parameter for the current function. Only used for
constructors and destructors. */
#define current_in_charge_parm cp_function_chain->x_in_charge_parm
/* The `__vtt_parm' parameter for the current function. Only used for
constructors and destructors. */
#define current_vtt_parm cp_function_chain->x_vtt_parm
/* Set to 0 at beginning of a function definition, set to 1 if
a return statement that specifies a return value is seen. */
#define current_function_returns_value cp_function_chain->returns_value
/* Set to 0 at beginning of a function definition, set to 1 if
a return statement with no argument is seen. */
#define current_function_returns_null cp_function_chain->returns_null
/* Set to 0 at beginning of a function definition, set to 1 if
a call to a noreturn function is seen. */
#define current_function_returns_abnormally \
cp_function_chain->returns_abnormally
/* Set to 0 at beginning of a function definition, set to 1 if we see an
obvious infinite loop. This can have false positives and false
negatives, so it should only be used as a heuristic. */
#define current_function_infinite_loop cp_function_chain->infinite_loop
/* Nonzero if we are processing a base initializer. Zero elsewhere. */
#define in_base_initializer cp_function_chain->x_in_base_initializer
#define in_function_try_handler cp_function_chain->x_in_function_try_handler
/* Expression always returned from function, or error_mark_node
otherwise, for use by the automatic named return value optimization. */
#define current_function_return_value \
(cp_function_chain->x_return_value)
/* A type involving 'auto' to be used for return type deduction. */
#define current_function_auto_return_pattern \
(cp_function_chain->x_auto_return_pattern)
/* True if NAME is the IDENTIFIER_NODE for an overloaded "operator
new" or "operator delete". */
#define NEW_DELETE_OPNAME_P(NAME) \
((NAME) == cp_operator_id (NEW_EXPR) \
|| (NAME) == cp_operator_id (VEC_NEW_EXPR) \
|| (NAME) == cp_operator_id (DELETE_EXPR) \
|| (NAME) == cp_operator_id (VEC_DELETE_EXPR))
#define cp_operator_id(CODE) \
(operator_name_info[(int) (CODE)].identifier)
#define cp_assignment_operator_id(CODE) \
(assignment_operator_name_info[(int) (CODE)].identifier)
/* In parser.c. */
extern tree cp_literal_operator_id (const char *);
/* TRUE if a tree code represents a statement. */
extern bool statement_code_p[MAX_TREE_CODES];
#define STATEMENT_CODE_P(CODE) statement_code_p[(int) (CODE)]
enum languages { lang_c, lang_cplusplus };
/* Macros to make error reporting functions' lives easier. */
#define TYPE_LINKAGE_IDENTIFIER(NODE) \
(TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (NODE)))
#define TYPE_NAME_STRING(NODE) (IDENTIFIER_POINTER (TYPE_IDENTIFIER (NODE)))
#define TYPE_NAME_LENGTH(NODE) (IDENTIFIER_LENGTH (TYPE_IDENTIFIER (NODE)))
/* Nonzero if NODE has no name for linkage purposes. */
#define TYPE_UNNAMED_P(NODE) \
(OVERLOAD_TYPE_P (NODE) && anon_aggrname_p (TYPE_LINKAGE_IDENTIFIER (NODE)))
/* The _DECL for this _TYPE. */
#define TYPE_MAIN_DECL(NODE) (TYPE_STUB_DECL (TYPE_MAIN_VARIANT (NODE)))
/* Nonzero if T is a type that could resolve to any kind of concrete type
at instantiation time. */
#define WILDCARD_TYPE_P(T) \
(TREE_CODE (T) == TEMPLATE_TYPE_PARM \
|| TREE_CODE (T) == TYPENAME_TYPE \
|| TREE_CODE (T) == TYPEOF_TYPE \
|| TREE_CODE (T) == BOUND_TEMPLATE_TEMPLATE_PARM \
|| TREE_CODE (T) == DECLTYPE_TYPE)
/* Nonzero if T is a class (or struct or union) type. Also nonzero
for template type parameters, typename types, and instantiated
template template parameters. Keep these checks in ascending code
order. */
#define MAYBE_CLASS_TYPE_P(T) (WILDCARD_TYPE_P (T) || CLASS_TYPE_P (T))
/* Set CLASS_TYPE_P for T to VAL. T must be a class, struct, or
union type. */
#define SET_CLASS_TYPE_P(T, VAL) \
(TYPE_LANG_FLAG_5 (T) = (VAL))
/* Nonzero if T is a class type. Zero for template type parameters,
typename types, and so forth. */
#define CLASS_TYPE_P(T) \
(RECORD_OR_UNION_CODE_P (TREE_CODE (T)) && TYPE_LANG_FLAG_5 (T))
/* Nonzero if T is a class type but not an union. */
#define NON_UNION_CLASS_TYPE_P(T) \
(CLASS_TYPE_P (T) && TREE_CODE (T) != UNION_TYPE)
/* Keep these checks in ascending code order. */
#define RECORD_OR_UNION_CODE_P(T) \
((T) == RECORD_TYPE || (T) == UNION_TYPE)
#define OVERLOAD_TYPE_P(T) \
(CLASS_TYPE_P (T) || TREE_CODE (T) == ENUMERAL_TYPE)
/* True if this type is dependent. This predicate is only valid if
TYPE_DEPENDENT_P_VALID is true. */
#define TYPE_DEPENDENT_P(NODE) TYPE_LANG_FLAG_0 (NODE)
/* True if dependent_type_p has been called for this type, with the
result that TYPE_DEPENDENT_P is valid. */
#define TYPE_DEPENDENT_P_VALID(NODE) TYPE_LANG_FLAG_6(NODE)
/* Nonzero if this type is const-qualified. */
#define CP_TYPE_CONST_P(NODE) \
((cp_type_quals (NODE) & TYPE_QUAL_CONST) != 0)
/* Nonzero if this type is volatile-qualified. */
#define CP_TYPE_VOLATILE_P(NODE) \
((cp_type_quals (NODE) & TYPE_QUAL_VOLATILE) != 0)
/* Nonzero if this type is restrict-qualified. */
#define CP_TYPE_RESTRICT_P(NODE) \
((cp_type_quals (NODE) & TYPE_QUAL_RESTRICT) != 0)
/* Nonzero if this type is const-qualified, but not
volatile-qualified. Other qualifiers are ignored. This macro is
used to test whether or not it is OK to bind an rvalue to a
reference. */
#define CP_TYPE_CONST_NON_VOLATILE_P(NODE) \
((cp_type_quals (NODE) & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)) \
== TYPE_QUAL_CONST)
#define FUNCTION_ARG_CHAIN(NODE) \
TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (NODE)))
/* Given a FUNCTION_DECL, returns the first TREE_LIST out of TYPE_ARG_TYPES
which refers to a user-written parameter. */
#define FUNCTION_FIRST_USER_PARMTYPE(NODE) \
skip_artificial_parms_for ((NODE), TYPE_ARG_TYPES (TREE_TYPE (NODE)))
/* Similarly, but for DECL_ARGUMENTS. */
#define FUNCTION_FIRST_USER_PARM(NODE) \
skip_artificial_parms_for ((NODE), DECL_ARGUMENTS (NODE))
/* Nonzero iff TYPE is derived from PARENT. Ignores accessibility and
ambiguity issues. */
#define DERIVED_FROM_P(PARENT, TYPE) \
(lookup_base ((TYPE), (PARENT), ba_any, NULL, tf_none) != NULL_TREE)
/* Gives the visibility specification for a class type. */
#define CLASSTYPE_VISIBILITY(TYPE) \
DECL_VISIBILITY (TYPE_MAIN_DECL (TYPE))
#define CLASSTYPE_VISIBILITY_SPECIFIED(TYPE) \
DECL_VISIBILITY_SPECIFIED (TYPE_MAIN_DECL (TYPE))
struct GTY (()) tree_pair_s {
tree purpose;
tree value;
};
typedef tree_pair_s *tree_pair_p;
/* This is a few header flags for 'struct lang_type'. Actually,
all but the first are used only for lang_type_class; they
are put in this structure to save space. */
struct GTY(()) lang_type_header {
BOOL_BITFIELD is_lang_type_class : 1;
BOOL_BITFIELD has_type_conversion : 1;
BOOL_BITFIELD has_copy_ctor : 1;
BOOL_BITFIELD has_default_ctor : 1;
BOOL_BITFIELD const_needs_init : 1;
BOOL_BITFIELD ref_needs_init : 1;
BOOL_BITFIELD has_const_copy_assign : 1;
BOOL_BITFIELD spare : 1;
};
/* This structure provides additional information above and beyond
what is provide in the ordinary tree_type. In the past, we used it
for the types of class types, template parameters types, typename
types, and so forth. However, there can be many (tens to hundreds
of thousands) of template parameter types in a compilation, and
there's no need for this additional information in that case.
Therefore, we now use this data structure only for class types.
In the past, it was thought that there would be relatively few
class types. However, in the presence of heavy use of templates,
many (i.e., thousands) of classes can easily be generated.
Therefore, we should endeavor to keep the size of this structure to
a minimum. */
struct GTY(()) lang_type_class {
struct lang_type_header h;
unsigned char align;
unsigned has_mutable : 1;
unsigned com_interface : 1;
unsigned non_pod_class : 1;
unsigned nearly_empty_p : 1;
unsigned user_align : 1;
unsigned has_copy_assign : 1;
unsigned has_new : 1;
unsigned has_array_new : 1;
unsigned gets_delete : 2;
unsigned interface_only : 1;
unsigned interface_unknown : 1;
unsigned contains_empty_class_p : 1;
unsigned anon_aggr : 1;
unsigned non_zero_init : 1;
unsigned empty_p : 1;
unsigned vec_new_uses_cookie : 1;
unsigned declared_class : 1;
unsigned diamond_shaped : 1;
unsigned repeated_base : 1;
unsigned being_defined : 1;
unsigned debug_requested : 1;
unsigned fields_readonly : 1;
unsigned ptrmemfunc_flag : 1;
unsigned use_template : 2;
unsigned was_anonymous : 1;
unsigned lazy_default_ctor : 1;
unsigned lazy_copy_ctor : 1;
unsigned lazy_copy_assign : 1;
unsigned lazy_destructor : 1;
unsigned has_const_copy_ctor : 1;
unsigned has_complex_copy_ctor : 1;
unsigned has_complex_copy_assign : 1;
unsigned non_aggregate : 1;
unsigned has_complex_dflt : 1;
unsigned has_list_ctor : 1;
unsigned non_std_layout : 1;
unsigned is_literal : 1;
unsigned lazy_move_ctor : 1;
unsigned lazy_move_assign : 1;
unsigned has_complex_move_ctor : 1;
unsigned has_complex_move_assign : 1;
unsigned has_constexpr_ctor : 1;
unsigned unique_obj_representations : 1;
unsigned unique_obj_representations_set : 1;
/* When adding a flag here, consider whether or not it ought to
apply to a template instance if it applies to the template. If
so, make sure to copy it in instantiate_class_template! */
/* There are some bits left to fill out a 32-bit word. Keep track
of this by updating the size of this bitfield whenever you add or
remove a flag. */
unsigned dummy : 2;
tree primary_base;
vec<tree_pair_s, va_gc> *vcall_indices;
tree vtables;
tree typeinfo_var;
vec<tree, va_gc> *vbases;
binding_table nested_udts;
tree as_base;
vec<tree, va_gc> *pure_virtuals;
tree friend_classes;
vec<tree, va_gc> * GTY((reorder ("resort_type_method_vec"))) methods;
tree key_method;
tree decl_list;
tree template_info;
tree befriending_classes;
/* In a RECORD_TYPE, information specific to Objective-C++, such
as a list of adopted protocols or a pointer to a corresponding
@interface. See objc/objc-act.h for details. */
tree objc_info;
/* sorted_fields is sorted based on a pointer, so we need to be able
to resort it if pointers get rearranged. */
struct sorted_fields_type * GTY ((reorder ("resort_sorted_fields")))
sorted_fields;
/* FIXME reuse another field? */
tree lambda_expr;
};
struct GTY(()) lang_type_ptrmem {
struct lang_type_header h;
tree record;
};
struct GTY(()) lang_type {
union lang_type_u
{
struct lang_type_header GTY((skip (""))) h;
struct lang_type_class GTY((tag ("1"))) c;
struct lang_type_ptrmem GTY((tag ("0"))) ptrmem;
} GTY((desc ("%h.h.is_lang_type_class"))) u;
};
#if defined ENABLE_TREE_CHECKING && (GCC_VERSION >= 2007)
#define LANG_TYPE_CLASS_CHECK(NODE) __extension__ \
({ struct lang_type *lt = TYPE_LANG_SPECIFIC (NODE); \
if (! lt->u.h.is_lang_type_class) \
lang_check_failed (__FILE__, __LINE__, __FUNCTION__); \
<->u.c; })
#define LANG_TYPE_PTRMEM_CHECK(NODE) __extension__ \
({ struct lang_type *lt = TYPE_LANG_SPECIFIC (NODE); \
if (lt->u.h.is_lang_type_class) \
lang_check_failed (__FILE__, __LINE__, __FUNCTION__); \
<->u.ptrmem; })
#else
#define LANG_TYPE_CLASS_CHECK(NODE) (&TYPE_LANG_SPECIFIC (NODE)->u.c)
#define LANG_TYPE_PTRMEM_CHECK(NODE) (&TYPE_LANG_SPECIFIC (NODE)->u.ptrmem)
#endif /* ENABLE_TREE_CHECKING */
/* Nonzero for _CLASSTYPE means that operator delete is defined. */
#define TYPE_GETS_DELETE(NODE) (LANG_TYPE_CLASS_CHECK (NODE)->gets_delete)
#define TYPE_GETS_REG_DELETE(NODE) (TYPE_GETS_DELETE (NODE) & 1)
/* Nonzero if `new NODE[x]' should cause the allocation of extra
storage to indicate how many array elements are in use. */
#define TYPE_VEC_NEW_USES_COOKIE(NODE) \
(CLASS_TYPE_P (NODE) \
&& LANG_TYPE_CLASS_CHECK (NODE)->vec_new_uses_cookie)
/* Nonzero means that this _CLASSTYPE node defines ways of converting
itself to other types. */
#define TYPE_HAS_CONVERSION(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->h.has_type_conversion)
/* Nonzero means that NODE (a class type) has a default constructor --
but that it has not yet been declared. */
#define CLASSTYPE_LAZY_DEFAULT_CTOR(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->lazy_default_ctor)
/* Nonzero means that NODE (a class type) has a copy constructor --
but that it has not yet been declared. */
#define CLASSTYPE_LAZY_COPY_CTOR(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->lazy_copy_ctor)
/* Nonzero means that NODE (a class type) has a move constructor --
but that it has not yet been declared. */
#define CLASSTYPE_LAZY_MOVE_CTOR(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->lazy_move_ctor)
/* Nonzero means that NODE (a class type) has an assignment operator
-- but that it has not yet been declared. */
#define CLASSTYPE_LAZY_COPY_ASSIGN(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->lazy_copy_assign)
/* Nonzero means that NODE (a class type) has an assignment operator
-- but that it has not yet been declared. */
#define CLASSTYPE_LAZY_MOVE_ASSIGN(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->lazy_move_assign)
/* Nonzero means that NODE (a class type) has a destructor -- but that
it has not yet been declared. */
#define CLASSTYPE_LAZY_DESTRUCTOR(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->lazy_destructor)
/* Nonzero means that NODE (a class type) is final */
#define CLASSTYPE_FINAL(NODE) \
TYPE_FINAL_P (NODE)
/* Nonzero means that this _CLASSTYPE node overloads operator=(X&). */
#define TYPE_HAS_COPY_ASSIGN(NODE) (LANG_TYPE_CLASS_CHECK (NODE)->has_copy_assign)
/* True iff the class type NODE has an "operator =" whose parameter
has a parameter of type "const X&". */
#define TYPE_HAS_CONST_COPY_ASSIGN(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->h.has_const_copy_assign)
/* Nonzero means that this _CLASSTYPE node has an X(X&) constructor. */
#define TYPE_HAS_COPY_CTOR(NODE) (LANG_TYPE_CLASS_CHECK (NODE)->h.has_copy_ctor)
#define TYPE_HAS_CONST_COPY_CTOR(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->has_const_copy_ctor)
/* Nonzero if this class has an X(initializer_list<T>) constructor. */
#define TYPE_HAS_LIST_CTOR(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->has_list_ctor)
/* Nonzero if this class has a constexpr constructor other than a copy/move
constructor. Note that a class can have constexpr constructors for
static initialization even if it isn't a literal class. */
#define TYPE_HAS_CONSTEXPR_CTOR(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->has_constexpr_ctor)
/* Nonzero if this class defines an overloaded operator new. (An
operator new [] doesn't count.) */
#define TYPE_HAS_NEW_OPERATOR(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->has_new)
/* Nonzero if this class defines an overloaded operator new[]. */
#define TYPE_HAS_ARRAY_NEW_OPERATOR(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->has_array_new)
/* Nonzero means that this type is being defined. I.e., the left brace
starting the definition of this type has been seen. */
#define TYPE_BEING_DEFINED(NODE) (LANG_TYPE_CLASS_CHECK (NODE)->being_defined)
/* Nonzero means that this type is either complete or being defined, so we
can do lookup in it. */
#define COMPLETE_OR_OPEN_TYPE_P(NODE) \
(COMPLETE_TYPE_P (NODE) || (CLASS_TYPE_P (NODE) && TYPE_BEING_DEFINED (NODE)))
/* Mark bits for repeated base checks. */
#define TYPE_MARKED_P(NODE) TREE_LANG_FLAG_6 (TYPE_CHECK (NODE))
/* Nonzero if the class NODE has multiple paths to the same (virtual)
base object. */
#define CLASSTYPE_DIAMOND_SHAPED_P(NODE) \
(LANG_TYPE_CLASS_CHECK(NODE)->diamond_shaped)
/* Nonzero if the class NODE has multiple instances of the same base
type. */
#define CLASSTYPE_REPEATED_BASE_P(NODE) \
(LANG_TYPE_CLASS_CHECK(NODE)->repeated_base)
/* The member function with which the vtable will be emitted:
the first noninline non-pure-virtual member function. NULL_TREE
if there is no key function or if this is a class template */
#define CLASSTYPE_KEY_METHOD(NODE) (LANG_TYPE_CLASS_CHECK (NODE)->key_method)
/* Vector member functions defined in this class. Each element is
either a FUNCTION_DECL, a TEMPLATE_DECL, or an OVERLOAD. All
functions with the same name end up in the same slot. The first
two elements are for constructors, and destructors, respectively.
All template conversion operators to innermost template dependent
types are overloaded on the next slot, if they exist. Note, the
names for these functions will not all be the same. The
non-template conversion operators & templated conversions to
non-innermost template types are next, followed by ordinary member
functions. There may be empty entries at the end of the vector.
The conversion operators are unsorted. The ordinary member
functions are sorted, once the class is complete. */
#define CLASSTYPE_METHOD_VEC(NODE) (LANG_TYPE_CLASS_CHECK (NODE)->methods)
/* For class templates, this is a TREE_LIST of all member data,
functions, types, and friends in the order of declaration.
The TREE_PURPOSE of each TREE_LIST is NULL_TREE for a friend,
and the RECORD_TYPE for the class template otherwise. */
#define CLASSTYPE_DECL_LIST(NODE) (LANG_TYPE_CLASS_CHECK (NODE)->decl_list)
/* The slot in the CLASSTYPE_METHOD_VEC where constructors go. */
#define CLASSTYPE_CONSTRUCTOR_SLOT 0
/* The slot in the CLASSTYPE_METHOD_VEC where destructors go. */
#define CLASSTYPE_DESTRUCTOR_SLOT 1
/* The first slot in the CLASSTYPE_METHOD_VEC where conversion
operators can appear. */
#define CLASSTYPE_FIRST_CONVERSION_SLOT 2
/* A FUNCTION_DECL or OVERLOAD for the constructors for NODE. These
are the constructors that take an in-charge parameter. */
#define CLASSTYPE_CONSTRUCTORS(NODE) \
((*CLASSTYPE_METHOD_VEC (NODE))[CLASSTYPE_CONSTRUCTOR_SLOT])
/* A FUNCTION_DECL for the destructor for NODE. These are the
destructors that take an in-charge parameter. If
CLASSTYPE_LAZY_DESTRUCTOR is true, then this entry will be NULL
until the destructor is created with lazily_declare_fn. */
#define CLASSTYPE_DESTRUCTORS(NODE) \
(CLASSTYPE_METHOD_VEC (NODE) \
? (*CLASSTYPE_METHOD_VEC (NODE))[CLASSTYPE_DESTRUCTOR_SLOT] \
: NULL_TREE)
/* A dictionary of the nested user-defined-types (class-types, or enums)
found within this class. This table includes nested member class
templates. */
#define CLASSTYPE_NESTED_UTDS(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->nested_udts)
/* Nonzero if NODE has a primary base class, i.e., a base class with
which it shares the virtual function table pointer. */
#define CLASSTYPE_HAS_PRIMARY_BASE_P(NODE) \
(CLASSTYPE_PRIMARY_BINFO (NODE) != NULL_TREE)
/* If non-NULL, this is the binfo for the primary base class, i.e.,
the base class which contains the virtual function table pointer
for this class. */
#define CLASSTYPE_PRIMARY_BINFO(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->primary_base)
/* A vector of BINFOs for the direct and indirect virtual base classes
that this type uses in a post-order depth-first left-to-right
order. (In other words, these bases appear in the order that they
should be initialized.) */
#define CLASSTYPE_VBASECLASSES(NODE) (LANG_TYPE_CLASS_CHECK (NODE)->vbases)
/* The type corresponding to NODE when NODE is used as a base class,
i.e., NODE without virtual base classes or tail padding. */
#define CLASSTYPE_AS_BASE(NODE) (LANG_TYPE_CLASS_CHECK (NODE)->as_base)
/* True iff NODE is the CLASSTYPE_AS_BASE version of some type. */
#define IS_FAKE_BASE_TYPE(NODE) \
(TREE_CODE (NODE) == RECORD_TYPE \
&& TYPE_CONTEXT (NODE) && CLASS_TYPE_P (TYPE_CONTEXT (NODE)) \
&& CLASSTYPE_AS_BASE (TYPE_CONTEXT (NODE)) == (NODE))
/* These are the size and alignment of the type without its virtual
base classes, for when we use this type as a base itself. */
#define CLASSTYPE_SIZE(NODE) TYPE_SIZE (CLASSTYPE_AS_BASE (NODE))
#define CLASSTYPE_SIZE_UNIT(NODE) TYPE_SIZE_UNIT (CLASSTYPE_AS_BASE (NODE))
#define CLASSTYPE_ALIGN(NODE) TYPE_ALIGN (CLASSTYPE_AS_BASE (NODE))
#define CLASSTYPE_USER_ALIGN(NODE) TYPE_USER_ALIGN (CLASSTYPE_AS_BASE (NODE))
/* The alignment of NODE, without its virtual bases, in bytes. */
#define CLASSTYPE_ALIGN_UNIT(NODE) \
(CLASSTYPE_ALIGN (NODE) / BITS_PER_UNIT)
/* A vec<tree> of virtual functions which cannot be inherited by
derived classes. When deriving from this type, the derived
class must provide its own definition for each of these functions. */
#define CLASSTYPE_PURE_VIRTUALS(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->pure_virtuals)
/* Nonzero means that this type is an abstract class type. */
#define ABSTRACT_CLASS_TYPE_P(NODE) \
(CLASS_TYPE_P (NODE) && CLASSTYPE_PURE_VIRTUALS(NODE))
/* Nonzero means that this type has an X() constructor. */
#define TYPE_HAS_DEFAULT_CONSTRUCTOR(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->h.has_default_ctor)
/* Nonzero means that this type contains a mutable member. */
#define CLASSTYPE_HAS_MUTABLE(NODE) (LANG_TYPE_CLASS_CHECK (NODE)->has_mutable)
#define TYPE_HAS_MUTABLE_P(NODE) (cp_has_mutable_p (NODE))
/* Nonzero means that this class type is not POD for the purpose of layout
(as defined in the ABI). This is different from the language's POD. */
#define CLASSTYPE_NON_LAYOUT_POD_P(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->non_pod_class)
/* Nonzero means that this class type is a non-standard-layout class. */
#define CLASSTYPE_NON_STD_LAYOUT(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->non_std_layout)
/* Nonzero means that this class type does have unique object
representations. */
#define CLASSTYPE_UNIQUE_OBJ_REPRESENTATIONS(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->unique_obj_representations)
/* Nonzero means that this class type has
CLASSTYPE_UNIQUE_OBJ_REPRESENTATIONS computed. */
#define CLASSTYPE_UNIQUE_OBJ_REPRESENTATIONS_SET(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->unique_obj_representations_set)
/* Nonzero means that this class contains pod types whose default
initialization is not a zero initialization (namely, pointers to
data members). */
#define CLASSTYPE_NON_ZERO_INIT_P(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->non_zero_init)
/* Nonzero if this class is "empty" in the sense of the C++ ABI. */
#define CLASSTYPE_EMPTY_P(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->empty_p)
/* Nonzero if this class is "nearly empty", i.e., contains only a
virtual function table pointer. */
#define CLASSTYPE_NEARLY_EMPTY_P(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->nearly_empty_p)
/* Nonzero if this class contains an empty subobject. */
#define CLASSTYPE_CONTAINS_EMPTY_CLASS_P(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->contains_empty_class_p)
/* A list of class types of which this type is a friend. The
TREE_VALUE is normally a TYPE, but will be a TEMPLATE_DECL in the
case of a template friend. */
#define CLASSTYPE_FRIEND_CLASSES(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->friend_classes)
/* A list of the classes which grant friendship to this class. */
#define CLASSTYPE_BEFRIENDING_CLASSES(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->befriending_classes)
/* The associated LAMBDA_EXPR that made this class. */
#define CLASSTYPE_LAMBDA_EXPR(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->lambda_expr)
/* The extra mangling scope for this closure type. */
#define LAMBDA_TYPE_EXTRA_SCOPE(NODE) \
(LAMBDA_EXPR_EXTRA_SCOPE (CLASSTYPE_LAMBDA_EXPR (NODE)))
/* Say whether this node was declared as a "class" or a "struct". */
#define CLASSTYPE_DECLARED_CLASS(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->declared_class)
/* Nonzero if this class has const members
which have no specified initialization. */
#define CLASSTYPE_READONLY_FIELDS_NEED_INIT(NODE) \
(TYPE_LANG_SPECIFIC (NODE) \
? LANG_TYPE_CLASS_CHECK (NODE)->h.const_needs_init : 0)
#define SET_CLASSTYPE_READONLY_FIELDS_NEED_INIT(NODE, VALUE) \
(LANG_TYPE_CLASS_CHECK (NODE)->h.const_needs_init = (VALUE))
/* Nonzero if this class has ref members
which have no specified initialization. */
#define CLASSTYPE_REF_FIELDS_NEED_INIT(NODE) \
(TYPE_LANG_SPECIFIC (NODE) \
? LANG_TYPE_CLASS_CHECK (NODE)->h.ref_needs_init : 0)
#define SET_CLASSTYPE_REF_FIELDS_NEED_INIT(NODE, VALUE) \
(LANG_TYPE_CLASS_CHECK (NODE)->h.ref_needs_init = (VALUE))
/* Nonzero if this class is included from a header file which employs
`#pragma interface', and it is not included in its implementation file. */
#define CLASSTYPE_INTERFACE_ONLY(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->interface_only)
/* True if we have already determined whether or not vtables, VTTs,
typeinfo, and other similar per-class data should be emitted in
this translation unit. This flag does not indicate whether or not
these items should be emitted; it only indicates that we know one
way or the other. */
#define CLASSTYPE_INTERFACE_KNOWN(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->interface_unknown == 0)
/* The opposite of CLASSTYPE_INTERFACE_KNOWN. */
#define CLASSTYPE_INTERFACE_UNKNOWN(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->interface_unknown)
#define SET_CLASSTYPE_INTERFACE_UNKNOWN_X(NODE,X) \
(LANG_TYPE_CLASS_CHECK (NODE)->interface_unknown = !!(X))
#define SET_CLASSTYPE_INTERFACE_UNKNOWN(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->interface_unknown = 1)
#define SET_CLASSTYPE_INTERFACE_KNOWN(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->interface_unknown = 0)
/* Nonzero if a _DECL node requires us to output debug info for this class. */
#define CLASSTYPE_DEBUG_REQUESTED(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->debug_requested)
/* Additional macros for inheritance information. */
/* Nonzero means that this class is on a path leading to a new vtable. */
#define BINFO_VTABLE_PATH_MARKED(NODE) BINFO_FLAG_1 (NODE)
/* Nonzero means B (a BINFO) has its own vtable. Any copies will not
have this flag set. */
#define BINFO_NEW_VTABLE_MARKED(B) (BINFO_FLAG_2 (B))
/* Compare a BINFO_TYPE with another type for equality. For a binfo,
this is functionally equivalent to using same_type_p, but
measurably faster. At least one of the arguments must be a
BINFO_TYPE. The other can be a BINFO_TYPE or a regular type. If
BINFO_TYPE(T) ever stops being the main variant of the class the
binfo is for, this macro must change. */
#define SAME_BINFO_TYPE_P(A, B) ((A) == (B))
/* Any subobject that needs a new vtable must have a vptr and must not
be a non-virtual primary base (since it would then use the vtable from a
derived class and never become non-primary.) */
#define SET_BINFO_NEW_VTABLE_MARKED(B) \
(BINFO_NEW_VTABLE_MARKED (B) = 1, \
gcc_assert (!BINFO_PRIMARY_P (B) || BINFO_VIRTUAL_P (B)), \
gcc_assert (TYPE_VFIELD (BINFO_TYPE (B))))
/* Nonzero if this binfo is for a dependent base - one that should not
be searched. */
#define BINFO_DEPENDENT_BASE_P(NODE) BINFO_FLAG_3 (NODE)
/* Nonzero if this binfo has lost its primary base binfo (because that
is a nearly-empty virtual base that has been taken by some other
base in the complete hierarchy. */
#define BINFO_LOST_PRIMARY_P(NODE) BINFO_FLAG_4 (NODE)
/* Nonzero if this BINFO is a primary base class. */
#define BINFO_PRIMARY_P(NODE) BINFO_FLAG_5(NODE)
/* Used by various search routines. */
#define IDENTIFIER_MARKED(NODE) TREE_LANG_FLAG_0 (NODE)
/* A vec<tree_pair_s> of the vcall indices associated with the class
NODE. The PURPOSE of each element is a FUNCTION_DECL for a virtual
function. The VALUE is the index into the virtual table where the
vcall offset for that function is stored, when NODE is a virtual
base. */
#define CLASSTYPE_VCALL_INDICES(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->vcall_indices)
/* The various vtables for the class NODE. The primary vtable will be
first, followed by the construction vtables and VTT, if any. */
#define CLASSTYPE_VTABLES(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->vtables)
/* The std::type_info variable representing this class, or NULL if no
such variable has been created. This field is only set for the
TYPE_MAIN_VARIANT of the class. */
#define CLASSTYPE_TYPEINFO_VAR(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->typeinfo_var)
/* Accessor macros for the BINFO_VIRTUALS list. */
/* The number of bytes by which to adjust the `this' pointer when
calling this virtual function. Subtract this value from the this
pointer. Always non-NULL, might be constant zero though. */
#define BV_DELTA(NODE) (TREE_PURPOSE (NODE))
/* If non-NULL, the vtable index at which to find the vcall offset
when calling this virtual function. Add the value at that vtable
index to the this pointer. */
#define BV_VCALL_INDEX(NODE) (TREE_TYPE (NODE))
/* The function to call. */
#define BV_FN(NODE) (TREE_VALUE (NODE))
/* Whether or not this entry is for a lost primary virtual base. */
#define BV_LOST_PRIMARY(NODE) (TREE_LANG_FLAG_0 (NODE))
/* For FUNCTION_TYPE or METHOD_TYPE, a list of the exceptions that
this type can raise. Each TREE_VALUE is a _TYPE. The TREE_VALUE
will be NULL_TREE to indicate a throw specification of `()', or
no exceptions allowed. For a noexcept specification, TREE_VALUE
is NULL_TREE and TREE_PURPOSE is the constant-expression. For
a deferred noexcept-specification, TREE_PURPOSE is a DEFERRED_NOEXCEPT
(for templates) or an OVERLOAD list of functions (for implicitly
declared functions). */
#define TYPE_RAISES_EXCEPTIONS(NODE) \
TYPE_LANG_SLOT_1 (FUNC_OR_METHOD_CHECK (NODE))
/* For FUNCTION_TYPE or METHOD_TYPE, return 1 iff it is declared `throw()'
or noexcept(true). */
#define TYPE_NOTHROW_P(NODE) nothrow_spec_p (TYPE_RAISES_EXCEPTIONS (NODE))
/* For FUNCTION_TYPE or METHOD_TYPE, true if NODE is noexcept. This is the
case for things declared noexcept(true) and, with -fnothrow-opt, for
throw() functions. */
#define TYPE_NOEXCEPT_P(NODE) type_noexcept_p (NODE)
/* The binding level associated with the namespace. */
#define NAMESPACE_LEVEL(NODE) \
(LANG_DECL_NS_CHECK (NODE)->level)
/* Flags shared by all forms of DECL_LANG_SPECIFIC.
Some of the flags live here only to make lang_decl_min/fn smaller. Do
not make this struct larger than 32 bits; instead, make sel smaller. */
struct GTY(()) lang_decl_base {
unsigned selector : 16; /* Larger than necessary for faster access. */
ENUM_BITFIELD(languages) language : 1;
unsigned use_template : 2;
unsigned not_really_extern : 1; /* var or fn */
unsigned initialized_in_class : 1; /* var or fn */
unsigned repo_available_p : 1; /* var or fn */
unsigned threadprivate_or_deleted_p : 1; /* var or fn */
unsigned anticipated_p : 1; /* fn, type or template */
/* anticipated_p reused as DECL_OMP_PRIVATIZED_MEMBER in var */
unsigned friend_or_tls : 1; /* var, fn, type or template */
unsigned template_conv_p : 1; /* var or template */
unsigned odr_used : 1; /* var or fn */
unsigned u2sel : 1;
unsigned concept_p : 1; /* applies to vars and functions */
unsigned var_declared_inline_p : 1; /* var */
unsigned decomposition_p : 1; /* var */
/* 1 spare bit */
};
/* True for DECL codes which have template info and access. */
#define LANG_DECL_HAS_MIN(NODE) \
(VAR_OR_FUNCTION_DECL_P (NODE) \
|| TREE_CODE (NODE) == FIELD_DECL \
|| TREE_CODE (NODE) == CONST_DECL \
|| TREE_CODE (NODE) == TYPE_DECL \
|| TREE_CODE (NODE) == TEMPLATE_DECL \
|| TREE_CODE (NODE) == USING_DECL)
/* DECL_LANG_SPECIFIC for the above codes. */
struct GTY(()) lang_decl_min {
struct lang_decl_base base;
/* In a FUNCTION_DECL for which DECL_THUNK_P holds, this is
THUNK_ALIAS.
In a FUNCTION_DECL for which DECL_THUNK_P does not hold,
VAR_DECL, TYPE_DECL, or TEMPLATE_DECL, this is
DECL_TEMPLATE_INFO. */
tree template_info;
union lang_decl_u2 {
/* In a FUNCTION_DECL for which DECL_THUNK_P holds, this is
THUNK_VIRTUAL_OFFSET.
Otherwise this is DECL_ACCESS. */
tree GTY ((tag ("0"))) access;
/* For VAR_DECL in function, this is DECL_DISCRIMINATOR. */
int GTY ((tag ("1"))) discriminator;
} GTY ((desc ("%0.u.base.u2sel"))) u2;
};
/* Additional DECL_LANG_SPECIFIC information for functions. */
struct GTY(()) lang_decl_fn {
struct lang_decl_min min;
/* In an overloaded operator, this is the value of
DECL_OVERLOADED_OPERATOR_P. */
ENUM_BITFIELD (tree_code) operator_code : 16;
unsigned global_ctor_p : 1;
unsigned global_dtor_p : 1;
unsigned assignment_operator_p : 1;
unsigned static_function : 1;
unsigned pure_virtual : 1;
unsigned defaulted_p : 1;
unsigned has_in_charge_parm_p : 1;
unsigned has_vtt_parm_p : 1;
unsigned pending_inline_p : 1;
unsigned nonconverting : 1;
unsigned thunk_p : 1;
unsigned this_thunk_p : 1;
unsigned hidden_friend_p : 1;
unsigned omp_declare_reduction_p : 1;
/* 2 spare bits on 32-bit hosts, 34 on 64-bit hosts. */
/* For a non-thunk function decl, this is a tree list of
friendly classes. For a thunk function decl, it is the
thunked to function decl. */
tree befriending_classes;
/* For a non-virtual FUNCTION_DECL, this is
DECL_FRIEND_CONTEXT. For a virtual FUNCTION_DECL for which
DECL_THIS_THUNK_P does not hold, this is DECL_THUNKS. Both
this pointer and result pointer adjusting thunks are
chained here. This pointer thunks to return pointer thunks
will be chained on the return pointer thunk. */
tree context;
union lang_decl_u5
{
/* In a non-thunk FUNCTION_DECL or TEMPLATE_DECL, this is
DECL_CLONED_FUNCTION. */
tree GTY ((tag ("0"))) cloned_function;
/* In a FUNCTION_DECL for which THUNK_P holds this is the
THUNK_FIXED_OFFSET. */
HOST_WIDE_INT GTY ((tag ("1"))) fixed_offset;
} GTY ((desc ("%1.thunk_p"))) u5;
union lang_decl_u3
{
struct cp_token_cache * GTY ((tag ("1"))) pending_inline_info;
struct language_function * GTY ((tag ("0")))
saved_language_function;
} GTY ((desc ("%1.pending_inline_p"))) u;
};
/* DECL_LANG_SPECIFIC for namespaces. */
struct GTY(()) lang_decl_ns {
struct lang_decl_base base;
cp_binding_level *level;
tree ns_using;
tree ns_users;
};
/* DECL_LANG_SPECIFIC for parameters. */
struct GTY(()) lang_decl_parm {
struct lang_decl_base base;
int level;
int index;
};
/* DECL_LANG_SPECIFIC for all types. It would be nice to just make this a
union rather than a struct containing a union as its only field, but
tree.h declares it as a struct. */
struct GTY(()) lang_decl {
union GTY((desc ("%h.base.selector"))) lang_decl_u {
struct lang_decl_base GTY ((default)) base;
struct lang_decl_min GTY((tag ("0"))) min;
struct lang_decl_fn GTY ((tag ("1"))) fn;
struct lang_decl_ns GTY((tag ("2"))) ns;
struct lang_decl_parm GTY((tag ("3"))) parm;
} u;
};
/* Looks through a template (if present) to find what it declares. */
#define STRIP_TEMPLATE(NODE) \
(TREE_CODE (NODE) == TEMPLATE_DECL ? DECL_TEMPLATE_RESULT (NODE) : NODE)
#if defined ENABLE_TREE_CHECKING && (GCC_VERSION >= 2007)
#define LANG_DECL_MIN_CHECK(NODE) __extension__ \
({ struct lang_decl *lt = DECL_LANG_SPECIFIC (NODE); \
if (!LANG_DECL_HAS_MIN (NODE)) \
lang_check_failed (__FILE__, __LINE__, __FUNCTION__); \
<->u.min; })
/* We want to be able to check DECL_CONSTRUCTOR_P and such on a function
template, not just on a FUNCTION_DECL. So when looking for things in
lang_decl_fn, look down through a TEMPLATE_DECL into its result. */
#define LANG_DECL_FN_CHECK(NODE) __extension__ \
({ struct lang_decl *lt = DECL_LANG_SPECIFIC (STRIP_TEMPLATE (NODE)); \
if (!DECL_DECLARES_FUNCTION_P (NODE) || lt->u.base.selector != 1) \
lang_check_failed (__FILE__, __LINE__, __FUNCTION__); \
<->u.fn; })
#define LANG_DECL_NS_CHECK(NODE) __extension__ \
({ struct lang_decl *lt = DECL_LANG_SPECIFIC (NODE); \
if (TREE_CODE (NODE) != NAMESPACE_DECL || lt->u.base.selector != 2) \
lang_check_failed (__FILE__, __LINE__, __FUNCTION__); \
<->u.ns; })
#define LANG_DECL_PARM_CHECK(NODE) __extension__ \
({ struct lang_decl *lt = DECL_LANG_SPECIFIC (NODE); \
if (TREE_CODE (NODE) != PARM_DECL) \
lang_check_failed (__FILE__, __LINE__, __FUNCTION__); \
<->u.parm; })
#define LANG_DECL_U2_CHECK(NODE, TF) __extension__ \
({ struct lang_decl *lt = DECL_LANG_SPECIFIC (NODE); \
if (!LANG_DECL_HAS_MIN (NODE) || lt->u.base.u2sel != TF) \
lang_check_failed (__FILE__, __LINE__, __FUNCTION__); \
<->u.min.u2; })
#else
#define LANG_DECL_MIN_CHECK(NODE) \
(&DECL_LANG_SPECIFIC (NODE)->u.min)
#define LANG_DECL_FN_CHECK(NODE) \
(&DECL_LANG_SPECIFIC (STRIP_TEMPLATE (NODE))->u.fn)
#define LANG_DECL_NS_CHECK(NODE) \
(&DECL_LANG_SPECIFIC (NODE)->u.ns)
#define LANG_DECL_PARM_CHECK(NODE) \
(&DECL_LANG_SPECIFIC (NODE)->u.parm)
#define LANG_DECL_U2_CHECK(NODE, TF) \
(&DECL_LANG_SPECIFIC (NODE)->u.min.u2)
#endif /* ENABLE_TREE_CHECKING */
/* For a FUNCTION_DECL or a VAR_DECL, the language linkage for the
declaration. Some entities (like a member function in a local
class, or a local variable) do not have linkage at all, and this
macro should not be used in those cases.
Implementation note: A FUNCTION_DECL without DECL_LANG_SPECIFIC was
created by language-independent code, and has C linkage. Most
VAR_DECLs have C++ linkage, and do not have DECL_LANG_SPECIFIC, but
we do create DECL_LANG_SPECIFIC for variables with non-C++ linkage. */
#define DECL_LANGUAGE(NODE) \
(DECL_LANG_SPECIFIC (NODE) \
? DECL_LANG_SPECIFIC (NODE)->u.base.language \
: (TREE_CODE (NODE) == FUNCTION_DECL \
? lang_c : lang_cplusplus))
/* Set the language linkage for NODE to LANGUAGE. */
#define SET_DECL_LANGUAGE(NODE, LANGUAGE) \
(DECL_LANG_SPECIFIC (NODE)->u.base.language = (LANGUAGE))
/* For FUNCTION_DECLs and TEMPLATE_DECLs: nonzero means that this function
is a constructor. */
#define DECL_CONSTRUCTOR_P(NODE) \
DECL_CXX_CONSTRUCTOR_P (STRIP_TEMPLATE (NODE))
/* Nonzero if NODE (a FUNCTION_DECL) is a constructor for a complete
object. */
#define DECL_COMPLETE_CONSTRUCTOR_P(NODE) \
(DECL_CONSTRUCTOR_P (NODE) \
&& DECL_NAME (NODE) == complete_ctor_identifier)
/* Nonzero if NODE (a FUNCTION_DECL) is a constructor for a base
object. */
#define DECL_BASE_CONSTRUCTOR_P(NODE) \
(DECL_CONSTRUCTOR_P (NODE) \
&& DECL_NAME (NODE) == base_ctor_identifier)
/* Nonzero if NODE (a FUNCTION_DECL) is a constructor, but not either the
specialized in-charge constructor or the specialized not-in-charge
constructor. */
#define DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P(NODE) \
(DECL_DECLARES_FUNCTION_P (NODE) && DECL_CONSTRUCTOR_P (NODE) \
&& !DECL_CLONED_FUNCTION_P (NODE))
/* Nonzero if NODE (a FUNCTION_DECL) is a copy constructor. */
#define DECL_COPY_CONSTRUCTOR_P(NODE) \
(DECL_CONSTRUCTOR_P (NODE) && copy_fn_p (NODE) > 0)
/* Nonzero if NODE (a FUNCTION_DECL) is a move constructor. */
#define DECL_MOVE_CONSTRUCTOR_P(NODE) \
(DECL_CONSTRUCTOR_P (NODE) && move_fn_p (NODE))
/* Nonzero if NODE (a FUNCTION_DECL or TEMPLATE_DECL)
is a destructor. */
#define DECL_DESTRUCTOR_P(NODE) \
DECL_CXX_DESTRUCTOR_P (STRIP_TEMPLATE (NODE))
/* Nonzero if NODE (a FUNCTION_DECL) is a destructor, but not the
specialized in-charge constructor, in-charge deleting constructor,
or the base destructor. */
#define DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P(NODE) \
(DECL_DECLARES_FUNCTION_P (NODE) && DECL_DESTRUCTOR_P (NODE) \
&& !DECL_CLONED_FUNCTION_P (NODE))
/* Nonzero if NODE (a FUNCTION_DECL) is a destructor for a complete
object. */
#define DECL_COMPLETE_DESTRUCTOR_P(NODE) \
(DECL_DESTRUCTOR_P (NODE) \
&& DECL_NAME (NODE) == complete_dtor_identifier)
/* Nonzero if NODE (a FUNCTION_DECL) is a destructor for a base
object. */
#define DECL_BASE_DESTRUCTOR_P(NODE) \
(DECL_DESTRUCTOR_P (NODE) \
&& DECL_NAME (NODE) == base_dtor_identifier)
/* Nonzero if NODE (a FUNCTION_DECL) is a destructor for a complete
object that deletes the object after it has been destroyed. */
#define DECL_DELETING_DESTRUCTOR_P(NODE) \
(DECL_DESTRUCTOR_P (NODE) \
&& DECL_NAME (NODE) == deleting_dtor_identifier)
/* Nonzero if NODE (a FUNCTION_DECL) is a cloned constructor or
destructor. */
#define DECL_CLONED_FUNCTION_P(NODE) (!!decl_cloned_function_p (NODE, true))
/* If DECL_CLONED_FUNCTION_P holds, this is the function that was
cloned. */
#define DECL_CLONED_FUNCTION(NODE) (*decl_cloned_function_p (NODE, false))
/* Perform an action for each clone of FN, if FN is a function with
clones. This macro should be used like:
FOR_EACH_CLONE (clone, fn)
{ ... }
*/
#define FOR_EACH_CLONE(CLONE, FN) \
if (!(TREE_CODE (FN) == FUNCTION_DECL \
&& (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (FN) \
|| DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P (FN))))\
; \
else \
for (CLONE = DECL_CHAIN (FN); \
CLONE && DECL_CLONED_FUNCTION_P (CLONE); \
CLONE = DECL_CHAIN (CLONE))
/* Nonzero if NODE has DECL_DISCRIMINATOR and not DECL_ACCESS. */
#define DECL_DISCRIMINATOR_P(NODE) \
(VAR_P (NODE) && DECL_FUNCTION_SCOPE_P (NODE))
/* Discriminator for name mangling. */
#define DECL_DISCRIMINATOR(NODE) (LANG_DECL_U2_CHECK (NODE, 1)->discriminator)
/* True iff DECL_DISCRIMINATOR is set for a DECL_DISCRIMINATOR_P decl. */
#define DECL_DISCRIMINATOR_SET_P(NODE) \
(DECL_LANG_SPECIFIC (NODE) && DECL_LANG_SPECIFIC (NODE)->u.base.u2sel == 1)
/* The index of a user-declared parameter in its function, starting at 1.
All artificial parameters will have index 0. */
#define DECL_PARM_INDEX(NODE) \
(LANG_DECL_PARM_CHECK (NODE)->index)
/* The level of a user-declared parameter in its function, starting at 1.
A parameter of the function will have level 1; a parameter of the first
nested function declarator (i.e. t in void f (void (*p)(T t))) will have
level 2. */
#define DECL_PARM_LEVEL(NODE) \
(LANG_DECL_PARM_CHECK (NODE)->level)
/* Nonzero if the VTT parm has been added to NODE. */
#define DECL_HAS_VTT_PARM_P(NODE) \
(LANG_DECL_FN_CHECK (NODE)->has_vtt_parm_p)
/* Nonzero if NODE is a FUNCTION_DECL for which a VTT parameter is
required. */
#define DECL_NEEDS_VTT_PARM_P(NODE) \
(CLASSTYPE_VBASECLASSES (DECL_CONTEXT (NODE)) \
&& (DECL_BASE_CONSTRUCTOR_P (NODE) \
|| DECL_BASE_DESTRUCTOR_P (NODE)))
/* Nonzero if NODE is a user-defined conversion operator. */
#define DECL_CONV_FN_P(NODE) \
(DECL_NAME (NODE) && IDENTIFIER_TYPENAME_P (DECL_NAME (NODE)))
/* If FN is a conversion operator, the type to which it converts.
Otherwise, NULL_TREE. */
#define DECL_CONV_FN_TYPE(FN) \
(DECL_CONV_FN_P (FN) ? TREE_TYPE (DECL_NAME (FN)) : NULL_TREE)
/* Nonzero if NODE, which is a TEMPLATE_DECL, is a template
conversion operator to a type dependent on the innermost template
args. */
#define DECL_TEMPLATE_CONV_FN_P(NODE) \
(DECL_LANG_SPECIFIC (TEMPLATE_DECL_CHECK (NODE))->u.base.template_conv_p)
/* Nonzero if NODE, a static data member, was declared in its class as an
array of unknown bound. */
#define VAR_HAD_UNKNOWN_BOUND(NODE) \
(DECL_LANG_SPECIFIC (VAR_DECL_CHECK (NODE)) \
? DECL_LANG_SPECIFIC (NODE)->u.base.template_conv_p \
: false)
#define SET_VAR_HAD_UNKNOWN_BOUND(NODE) \
(DECL_LANG_SPECIFIC (VAR_DECL_CHECK (NODE))->u.base.template_conv_p = true)
/* Set the overloaded operator code for NODE to CODE. */
#define SET_OVERLOADED_OPERATOR_CODE(NODE, CODE) \
(LANG_DECL_FN_CHECK (NODE)->operator_code = (CODE))
/* If NODE is an overloaded operator, then this returns the TREE_CODE
associated with the overloaded operator.
DECL_ASSIGNMENT_OPERATOR_P must also be checked to determine
whether or not NODE is an assignment operator. If NODE is not an
overloaded operator, ERROR_MARK is returned. Since the numerical
value of ERROR_MARK is zero, this macro can be used as a predicate
to test whether or not NODE is an overloaded operator. */
#define DECL_OVERLOADED_OPERATOR_P(NODE) \
(IDENTIFIER_OPNAME_P (DECL_NAME (NODE)) \
? LANG_DECL_FN_CHECK (NODE)->operator_code : ERROR_MARK)
/* Nonzero if NODE is an assignment operator (including += and such). */
#define DECL_ASSIGNMENT_OPERATOR_P(NODE) \
(LANG_DECL_FN_CHECK (NODE)->assignment_operator_p)
/* For FUNCTION_DECLs: nonzero means that this function is a
constructor or a destructor with an extra in-charge parameter to
control whether or not virtual bases are constructed. */
#define DECL_HAS_IN_CHARGE_PARM_P(NODE) \
(LANG_DECL_FN_CHECK (NODE)->has_in_charge_parm_p)
/* Nonzero if DECL is a declaration of __builtin_constant_p. */
#define DECL_IS_BUILTIN_CONSTANT_P(NODE) \
(TREE_CODE (NODE) == FUNCTION_DECL \
&& DECL_BUILT_IN_CLASS (NODE) == BUILT_IN_NORMAL \
&& DECL_FUNCTION_CODE (NODE) == BUILT_IN_CONSTANT_P)
/* Nonzero for _DECL means that this decl appears in (or will appear
in) as a member in a RECORD_TYPE or UNION_TYPE node. It is also for
detecting circularity in case members are multiply defined. In the
case of a VAR_DECL, it is also used to determine how program storage
should be allocated. */
#define DECL_IN_AGGR_P(NODE) (DECL_LANG_FLAG_3 (NODE))
/* Nonzero for a VAR_DECL means that the variable's initialization (if
any) has been processed. (In general, DECL_INITIALIZED_P is
!DECL_EXTERNAL, but static data members may be initialized even if
not defined.) */
#define DECL_INITIALIZED_P(NODE) \
(TREE_LANG_FLAG_1 (VAR_DECL_CHECK (NODE)))
/* Nonzero for a VAR_DECL iff an explicit initializer was provided
or a non-trivial constructor is called. */
#define DECL_NONTRIVIALLY_INITIALIZED_P(NODE) \
(TREE_LANG_FLAG_3 (VAR_DECL_CHECK (NODE)))
/* Nonzero for a VAR_DECL that was initialized with a
constant-expression. */
#define DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P(NODE) \
(TREE_LANG_FLAG_2 (VAR_DECL_CHECK (NODE)))
/* Nonzero if the DECL was initialized in the class definition itself,
rather than outside the class. This is used for both static member
VAR_DECLS, and FUNCTION_DECLS that are defined in the class. */
#define DECL_INITIALIZED_IN_CLASS_P(DECL) \
(DECL_LANG_SPECIFIC (VAR_OR_FUNCTION_DECL_CHECK (DECL)) \
->u.base.initialized_in_class)
/* Nonzero if the DECL is used in the sense of 3.2 [basic.def.odr].
Only available for decls with DECL_LANG_SPECIFIC. */
#define DECL_ODR_USED(DECL) \
(DECL_LANG_SPECIFIC (VAR_OR_FUNCTION_DECL_CHECK (DECL)) \
->u.base.odr_used)
/* Nonzero for DECL means that this decl is just a friend declaration,
and should not be added to the list of members for this class. */
#define DECL_FRIEND_P(NODE) \
(DECL_LANG_SPECIFIC (TYPE_FUNCTION_OR_TEMPLATE_DECL_CHECK (NODE)) \
->u.base.friend_or_tls)
/* Nonzero if the thread-local variable was declared with __thread as
opposed to thread_local. */
#define DECL_GNU_TLS_P(NODE) \
(DECL_LANG_SPECIFIC (VAR_DECL_CHECK (NODE)) \
&& DECL_LANG_SPECIFIC (NODE)->u.base.friend_or_tls)
#define SET_DECL_GNU_TLS_P(NODE) \
(retrofit_lang_decl (VAR_DECL_CHECK (NODE)), \
DECL_LANG_SPECIFIC (NODE)->u.base.friend_or_tls = true)
/* A TREE_LIST of the types which have befriended this FUNCTION_DECL. */
#define DECL_BEFRIENDING_CLASSES(NODE) \
(LANG_DECL_FN_CHECK (NODE)->befriending_classes)
/* Nonzero for FUNCTION_DECL means that this decl is a static
member function. */
#define DECL_STATIC_FUNCTION_P(NODE) \
(LANG_DECL_FN_CHECK (NODE)->static_function)
/* Nonzero for FUNCTION_DECL means that this decl is a non-static
member function. */
#define DECL_NONSTATIC_MEMBER_FUNCTION_P(NODE) \
(TREE_CODE (TREE_TYPE (NODE)) == METHOD_TYPE)
/* Nonzero for FUNCTION_DECL means that this decl is a member function
(static or non-static). */
#define DECL_FUNCTION_MEMBER_P(NODE) \
(DECL_NONSTATIC_MEMBER_FUNCTION_P (NODE) || DECL_STATIC_FUNCTION_P (NODE))
/* Nonzero for FUNCTION_DECL means that this member function
has `this' as const X *const. */
#define DECL_CONST_MEMFUNC_P(NODE) \
(DECL_NONSTATIC_MEMBER_FUNCTION_P (NODE) \
&& CP_TYPE_CONST_P (TREE_TYPE (TREE_VALUE \
(TYPE_ARG_TYPES (TREE_TYPE (NODE))))))
/* Nonzero for FUNCTION_DECL means that this member function
has `this' as volatile X *const. */
#define DECL_VOLATILE_MEMFUNC_P(NODE) \
(DECL_NONSTATIC_MEMBER_FUNCTION_P (NODE) \
&& CP_TYPE_VOLATILE_P (TREE_TYPE (TREE_VALUE \
(TYPE_ARG_TYPES (TREE_TYPE (NODE))))))
/* Nonzero for a DECL means that this member is a non-static member. */
#define DECL_NONSTATIC_MEMBER_P(NODE) \
(DECL_NONSTATIC_MEMBER_FUNCTION_P (NODE) \
|| TREE_CODE (NODE) == FIELD_DECL)
/* Nonzero for _DECL means that this member object type
is mutable. */
#define DECL_MUTABLE_P(NODE) (DECL_LANG_FLAG_0 (NODE))
/* Nonzero for _DECL means that this constructor or conversion function is
non-converting. */
#define DECL_NONCONVERTING_P(NODE) \
(LANG_DECL_FN_CHECK (NODE)->nonconverting)
/* Nonzero for FUNCTION_DECL means that this member function is a pure
virtual function. */
#define DECL_PURE_VIRTUAL_P(NODE) \
(LANG_DECL_FN_CHECK (NODE)->pure_virtual)
/* True (in a FUNCTION_DECL) if NODE is a virtual function that is an
invalid overrider for a function from a base class. Once we have
complained about an invalid overrider we avoid complaining about it
again. */
#define DECL_INVALID_OVERRIDER_P(NODE) \
(DECL_LANG_FLAG_4 (NODE))
/* True (in a FUNCTION_DECL) if NODE is a function declared with
an override virt-specifier */
#define DECL_OVERRIDE_P(NODE) (TREE_LANG_FLAG_0 (NODE))
/* The thunks associated with NODE, a FUNCTION_DECL. */
#define DECL_THUNKS(NODE) \
(DECL_VIRTUAL_P (NODE) ? LANG_DECL_FN_CHECK (NODE)->context : NULL_TREE)
/* Set DECL_THUNKS. */
#define SET_DECL_THUNKS(NODE,THUNKS) \
(LANG_DECL_FN_CHECK (NODE)->context = (THUNKS))
/* If NODE, a FUNCTION_DECL, is a C++11 inheriting constructor, then this
is the constructor it inherits from. */
#define DECL_INHERITED_CTOR(NODE) \
(DECL_DECLARES_FUNCTION_P (NODE) && DECL_CONSTRUCTOR_P (NODE) \
? LANG_DECL_FN_CHECK (NODE)->context : NULL_TREE)
/* And this is the base that constructor comes from. */
#define DECL_INHERITED_CTOR_BASE(NODE) \
(DECL_INHERITED_CTOR (NODE) \
? DECL_CONTEXT (flag_new_inheriting_ctors \
? strip_inheriting_ctors (NODE) \
: DECL_INHERITED_CTOR (NODE)) \
: NULL_TREE)
/* Set the inherited base. */
#define SET_DECL_INHERITED_CTOR(NODE,INH) \
(LANG_DECL_FN_CHECK (NODE)->context = (INH))
/* Nonzero if NODE is a thunk, rather than an ordinary function. */
#define DECL_THUNK_P(NODE) \
(TREE_CODE (NODE) == FUNCTION_DECL \
&& DECL_LANG_SPECIFIC (NODE) \
&& LANG_DECL_FN_CHECK (NODE)->thunk_p)
/* Set DECL_THUNK_P for node. */
#define SET_DECL_THUNK_P(NODE, THIS_ADJUSTING) \
(LANG_DECL_FN_CHECK (NODE)->thunk_p = 1, \
LANG_DECL_FN_CHECK (NODE)->this_thunk_p = (THIS_ADJUSTING))
/* Nonzero if NODE is a this pointer adjusting thunk. */
#define DECL_THIS_THUNK_P(NODE) \
(DECL_THUNK_P (NODE) && LANG_DECL_FN_CHECK (NODE)->this_thunk_p)
/* Nonzero if NODE is a result pointer adjusting thunk. */
#define DECL_RESULT_THUNK_P(NODE) \
(DECL_THUNK_P (NODE) && !LANG_DECL_FN_CHECK (NODE)->this_thunk_p)
/* Nonzero if NODE is a FUNCTION_DECL, but not a thunk. */
#define DECL_NON_THUNK_FUNCTION_P(NODE) \
(TREE_CODE (NODE) == FUNCTION_DECL && !DECL_THUNK_P (NODE))
/* Nonzero if NODE is `extern "C"'. */
#define DECL_EXTERN_C_P(NODE) \
(DECL_LANGUAGE (NODE) == lang_c)
/* Nonzero if NODE is an `extern "C"' function. */
#define DECL_EXTERN_C_FUNCTION_P(NODE) \
(DECL_NON_THUNK_FUNCTION_P (NODE) && DECL_EXTERN_C_P (NODE))
/* True iff DECL is an entity with vague linkage whose definition is
available in this translation unit. */
#define DECL_REPO_AVAILABLE_P(NODE) \
(DECL_LANG_SPECIFIC (NODE)->u.base.repo_available_p)
/* True if DECL is declared 'constexpr'. */
#define DECL_DECLARED_CONSTEXPR_P(DECL) \
DECL_LANG_FLAG_8 (VAR_OR_FUNCTION_DECL_CHECK (STRIP_TEMPLATE (DECL)))
// True if NODE was declared as 'concept'. The flag implies that the
// declaration is constexpr, that the declaration cannot be specialized or
// refined, and that the result type must be convertible to bool.
#define DECL_DECLARED_CONCEPT_P(NODE) \
(DECL_LANG_SPECIFIC (NODE)->u.base.concept_p)
/* Nonzero if this DECL is the __PRETTY_FUNCTION__ variable in a
template function. */
#define DECL_PRETTY_FUNCTION_P(NODE) \
(DECL_NAME (NODE) \
&& !strcmp (IDENTIFIER_POINTER (DECL_NAME (NODE)), "__PRETTY_FUNCTION__"))
/* Nonzero if the variable was declared to be thread-local.
We need a special C++ version of this test because the middle-end
DECL_THREAD_LOCAL_P uses the symtab, so we can't use it for
templates. */
#define CP_DECL_THREAD_LOCAL_P(NODE) \
(TREE_LANG_FLAG_0 (VAR_DECL_CHECK (NODE)))
/* The _TYPE context in which this _DECL appears. This field holds the
class where a virtual function instance is actually defined. */
#define DECL_CLASS_CONTEXT(NODE) \
(DECL_CLASS_SCOPE_P (NODE) ? DECL_CONTEXT (NODE) : NULL_TREE)
/* For a non-member friend function, the class (if any) in which this
friend was defined. For example, given:
struct S { friend void f (); };
the DECL_FRIEND_CONTEXT for `f' will be `S'. */
#define DECL_FRIEND_CONTEXT(NODE) \
((DECL_DECLARES_FUNCTION_P (NODE) \
&& DECL_FRIEND_P (NODE) && !DECL_FUNCTION_MEMBER_P (NODE)) \
? LANG_DECL_FN_CHECK (NODE)->context \
: NULL_TREE)
/* Set the DECL_FRIEND_CONTEXT for NODE to CONTEXT. */
#define SET_DECL_FRIEND_CONTEXT(NODE, CONTEXT) \
(LANG_DECL_FN_CHECK (NODE)->context = (CONTEXT))
#define CP_DECL_CONTEXT(NODE) \
(!DECL_FILE_SCOPE_P (NODE) ? DECL_CONTEXT (NODE) : global_namespace)
#define CP_TYPE_CONTEXT(NODE) \
(!TYPE_FILE_SCOPE_P (NODE) ? TYPE_CONTEXT (NODE) : global_namespace)
#define FROB_CONTEXT(NODE) \
((NODE) == global_namespace ? DECL_CONTEXT (NODE) : (NODE))
/* 1 iff NODE has namespace scope, including the global namespace. */
#define DECL_NAMESPACE_SCOPE_P(NODE) \
(!DECL_TEMPLATE_PARM_P (NODE) \
&& TREE_CODE (CP_DECL_CONTEXT (NODE)) == NAMESPACE_DECL)
#define TYPE_NAMESPACE_SCOPE_P(NODE) \
(TREE_CODE (CP_TYPE_CONTEXT (NODE)) == NAMESPACE_DECL)
#define NAMESPACE_SCOPE_P(NODE) \
((DECL_P (NODE) && DECL_NAMESPACE_SCOPE_P (NODE)) \
|| (TYPE_P (NODE) && TYPE_NAMESPACE_SCOPE_P (NODE)))
/* 1 iff NODE is a class member. */
#define DECL_CLASS_SCOPE_P(NODE) \
(DECL_CONTEXT (NODE) && TYPE_P (DECL_CONTEXT (NODE)))
#define TYPE_CLASS_SCOPE_P(NODE) \
(TYPE_CONTEXT (NODE) && TYPE_P (TYPE_CONTEXT (NODE)))
/* 1 iff NODE is function-local. */
#define DECL_FUNCTION_SCOPE_P(NODE) \
(DECL_CONTEXT (NODE) \
&& TREE_CODE (DECL_CONTEXT (NODE)) == FUNCTION_DECL)
#define TYPE_FUNCTION_SCOPE_P(NODE) \
(TYPE_CONTEXT (NODE) && TREE_CODE (TYPE_CONTEXT (NODE)) == FUNCTION_DECL)
/* 1 iff VAR_DECL node NODE is a type-info decl. This flag is set for
both the primary typeinfo object and the associated NTBS name. */
#define DECL_TINFO_P(NODE) TREE_LANG_FLAG_4 (VAR_DECL_CHECK (NODE))
/* 1 iff VAR_DECL node NODE is virtual table or VTT. */
#define DECL_VTABLE_OR_VTT_P(NODE) TREE_LANG_FLAG_5 (VAR_DECL_CHECK (NODE))
/* 1 iff FUNCTION_TYPE or METHOD_TYPE has a ref-qualifier (either & or &&). */
#define FUNCTION_REF_QUALIFIED(NODE) \
TREE_LANG_FLAG_4 (FUNC_OR_METHOD_CHECK (NODE))
/* 1 iff FUNCTION_TYPE or METHOD_TYPE has &&-ref-qualifier. */
#define FUNCTION_RVALUE_QUALIFIED(NODE) \
TREE_LANG_FLAG_5 (FUNC_OR_METHOD_CHECK (NODE))
/* Returns 1 iff VAR_DECL is a construction virtual table.
DECL_VTABLE_OR_VTT_P will be true in this case and must be checked
before using this macro. */
#define DECL_CONSTRUCTION_VTABLE_P(NODE) \
TREE_LANG_FLAG_6 (VAR_DECL_CHECK (NODE))
/* 1 iff NODE is function-local, but for types. */
#define LOCAL_CLASS_P(NODE) \
(decl_function_context (TYPE_MAIN_DECL (NODE)) != NULL_TREE)
/* For a NAMESPACE_DECL: the list of using namespace directives
The PURPOSE is the used namespace, the value is the namespace
that is the common ancestor. */
#define DECL_NAMESPACE_USING(NODE) (LANG_DECL_NS_CHECK (NODE)->ns_using)
/* In a NAMESPACE_DECL, the DECL_INITIAL is used to record all users
of a namespace, to record the transitive closure of using namespace. */
#define DECL_NAMESPACE_USERS(NODE) (LANG_DECL_NS_CHECK (NODE)->ns_users)
/* In a NAMESPACE_DECL, the list of namespaces which have associated
themselves with this one. */
#define DECL_NAMESPACE_ASSOCIATIONS(NODE) \
DECL_INITIAL (NAMESPACE_DECL_CHECK (NODE))
/* In a NAMESPACE_DECL, points to the original namespace if this is
a namespace alias. */
#define DECL_NAMESPACE_ALIAS(NODE) \
DECL_ABSTRACT_ORIGIN (NAMESPACE_DECL_CHECK (NODE))
#define ORIGINAL_NAMESPACE(NODE) \
(DECL_NAMESPACE_ALIAS (NODE) ? DECL_NAMESPACE_ALIAS (NODE) : (NODE))
/* Nonzero if NODE is the std namespace. */
#define DECL_NAMESPACE_STD_P(NODE) \
(TREE_CODE (NODE) == NAMESPACE_DECL \
&& CP_DECL_CONTEXT (NODE) == global_namespace \
&& DECL_NAME (NODE) == std_identifier)
/* In a TREE_LIST concatenating using directives, indicate indirect
directives */
#define TREE_INDIRECT_USING(NODE) TREE_LANG_FLAG_0 (TREE_LIST_CHECK (NODE))
/* In a TREE_LIST in an attribute list, indicates that the attribute
must be applied at instantiation time. */
#define ATTR_IS_DEPENDENT(NODE) TREE_LANG_FLAG_0 (TREE_LIST_CHECK (NODE))
/* In a TREE_LIST in the argument of attribute abi_tag, indicates that the tag
was inherited from a template parameter, not explicitly indicated. */
#define ABI_TAG_IMPLICIT(NODE) TREE_LANG_FLAG_0 (TREE_LIST_CHECK (NODE))
extern tree decl_shadowed_for_var_lookup (tree);
extern void decl_shadowed_for_var_insert (tree, tree);
/* Non zero if this is a using decl for a dependent scope. */
#define DECL_DEPENDENT_P(NODE) DECL_LANG_FLAG_0 (USING_DECL_CHECK (NODE))
/* The scope named in a using decl. */
#define USING_DECL_SCOPE(NODE) TREE_TYPE (USING_DECL_CHECK (NODE))
/* The decls named by a using decl. */
#define USING_DECL_DECLS(NODE) DECL_INITIAL (USING_DECL_CHECK (NODE))
/* Non zero if the using decl refers to a dependent type. */
#define USING_DECL_TYPENAME_P(NODE) DECL_LANG_FLAG_1 (USING_DECL_CHECK (NODE))
/* In a VAR_DECL, true if we have a shadowed local variable
in the shadowed var table for this VAR_DECL. */
#define DECL_HAS_SHADOWED_FOR_VAR_P(NODE) \
(VAR_DECL_CHECK (NODE)->decl_with_vis.shadowed_for_var_p)
/* In a VAR_DECL for a variable declared in a for statement,
this is the shadowed (local) variable. */
#define DECL_SHADOWED_FOR_VAR(NODE) \
(DECL_HAS_SHADOWED_FOR_VAR_P(NODE) ? decl_shadowed_for_var_lookup (NODE) : NULL)
#define SET_DECL_SHADOWED_FOR_VAR(NODE, VAL) \
(decl_shadowed_for_var_insert (NODE, VAL))
/* In a FUNCTION_DECL, this is nonzero if this function was defined in
the class definition. We have saved away the text of the function,
but have not yet processed it. */
#define DECL_PENDING_INLINE_P(NODE) \
(LANG_DECL_FN_CHECK (NODE)->pending_inline_p)
/* If DECL_PENDING_INLINE_P holds, this is the saved text of the
function. */
#define DECL_PENDING_INLINE_INFO(NODE) \
(LANG_DECL_FN_CHECK (NODE)->u.pending_inline_info)
/* Nonzero for TYPE_DECL means that it was written 'using name = type'. */
#define TYPE_DECL_ALIAS_P(NODE) \
DECL_LANG_FLAG_6 (TYPE_DECL_CHECK (NODE))
/* Nonzero for TEMPLATE_DECL means that it is a 'complex' alias template. */
#define TEMPLATE_DECL_COMPLEX_ALIAS_P(NODE) \
DECL_LANG_FLAG_2 (TEMPLATE_DECL_CHECK (NODE))
/* Nonzero for a type which is an alias for another type; i.e, a type
which declaration was written 'using name-of-type =
another-type'. */
#define TYPE_ALIAS_P(NODE) \
(TYPE_P (NODE) \
&& TYPE_NAME (NODE) \
&& TREE_CODE (TYPE_NAME (NODE)) == TYPE_DECL \
&& TYPE_DECL_ALIAS_P (TYPE_NAME (NODE)))
/* For a class type: if this structure has many fields, we'll sort them
and put them into a TREE_VEC. */
#define CLASSTYPE_SORTED_FIELDS(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->sorted_fields)
/* If non-NULL for a VAR_DECL, FUNCTION_DECL, TYPE_DECL or
TEMPLATE_DECL, the entity is either a template specialization (if
DECL_USE_TEMPLATE is nonzero) or the abstract instance of the
template itself.
In either case, DECL_TEMPLATE_INFO is a TREE_LIST, whose
TREE_PURPOSE is the TEMPLATE_DECL of which this entity is a
specialization or abstract instance. The TREE_VALUE is the
template arguments used to specialize the template.
Consider:
template <typename T> struct S { friend void f(T) {} };
In this case, S<int>::f is, from the point of view of the compiler,
an instantiation of a template -- but, from the point of view of
the language, each instantiation of S results in a wholly unrelated
global function f. In this case, DECL_TEMPLATE_INFO for S<int>::f
will be non-NULL, but DECL_USE_TEMPLATE will be zero. */
#define DECL_TEMPLATE_INFO(NODE) \
(DECL_LANG_SPECIFIC (VAR_TEMPL_TYPE_FIELD_OR_FUNCTION_DECL_CHECK (NODE)) \
->u.min.template_info)
/* For a VAR_DECL, indicates that the variable is actually a
non-static data member of anonymous union that has been promoted to
variable status. */
#define DECL_ANON_UNION_VAR_P(NODE) \
(DECL_LANG_FLAG_4 (VAR_DECL_CHECK (NODE)))
/* Template information for a RECORD_TYPE or UNION_TYPE. */
#define CLASSTYPE_TEMPLATE_INFO(NODE) \
(LANG_TYPE_CLASS_CHECK (RECORD_OR_UNION_CHECK (NODE))->template_info)
/* Template information for an ENUMERAL_TYPE. Although an enumeration may
not be a primary template, it may be declared within the scope of a
primary template and the enumeration constants may depend on
non-type template parameters. */
#define ENUM_TEMPLATE_INFO(NODE) \
(TYPE_LANG_SLOT_1 (ENUMERAL_TYPE_CHECK (NODE)))
/* Template information for a template template parameter. */
#define TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO(NODE) \
(LANG_TYPE_CLASS_CHECK (BOUND_TEMPLATE_TEMPLATE_PARM_TYPE_CHECK (NODE)) \
->template_info)
/* Template information for an ENUMERAL_, RECORD_, UNION_TYPE, or
BOUND_TEMPLATE_TEMPLATE_PARM type. This ignores any alias
templateness of NODE. */
#define TYPE_TEMPLATE_INFO(NODE) \
(TREE_CODE (NODE) == ENUMERAL_TYPE \
? ENUM_TEMPLATE_INFO (NODE) \
: (TREE_CODE (NODE) == BOUND_TEMPLATE_TEMPLATE_PARM \
? TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (NODE) \
: (CLASS_TYPE_P (NODE) \
? CLASSTYPE_TEMPLATE_INFO (NODE) \
: NULL_TREE)))
/* Template information (if any) for an alias type. */
#define TYPE_ALIAS_TEMPLATE_INFO(NODE) \
(DECL_LANG_SPECIFIC (TYPE_NAME (NODE)) \
? DECL_TEMPLATE_INFO (TYPE_NAME (NODE)) \
: NULL_TREE)
/* If NODE is a type alias, this accessor returns the template info
for the alias template (if any). Otherwise behave as
TYPE_TEMPLATE_INFO. */
#define TYPE_TEMPLATE_INFO_MAYBE_ALIAS(NODE) \
(TYPE_ALIAS_P (NODE) \
? TYPE_ALIAS_TEMPLATE_INFO (NODE) \
: TYPE_TEMPLATE_INFO (NODE))
/* Set the template information for an ENUMERAL_, RECORD_, or
UNION_TYPE to VAL. */
#define SET_TYPE_TEMPLATE_INFO(NODE, VAL) \
(TREE_CODE (NODE) == ENUMERAL_TYPE \
? (ENUM_TEMPLATE_INFO (NODE) = (VAL)) \
: ((CLASS_TYPE_P (NODE) && !TYPE_ALIAS_P (NODE)) \
? (CLASSTYPE_TEMPLATE_INFO (NODE) = (VAL)) \
: (DECL_TEMPLATE_INFO (TYPE_NAME (NODE)) = (VAL))))
#define TI_TEMPLATE(NODE) TREE_TYPE (TEMPLATE_INFO_CHECK (NODE))
#define TI_ARGS(NODE) TREE_CHAIN (TEMPLATE_INFO_CHECK (NODE))
#define TI_PENDING_TEMPLATE_FLAG(NODE) TREE_LANG_FLAG_1 (NODE)
/* For a given TREE_VEC containing a template argument list,
this property contains the number of arguments that are not
defaulted. */
#define NON_DEFAULT_TEMPLATE_ARGS_COUNT(NODE) TREE_CHAIN (TREE_VEC_CHECK (NODE))
/* Below are the setter and getter of the NON_DEFAULT_TEMPLATE_ARGS_COUNT
property. */
#define SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT(NODE, INT_VALUE) \
NON_DEFAULT_TEMPLATE_ARGS_COUNT(NODE) = build_int_cst (NULL_TREE, INT_VALUE)
#if CHECKING_P
#define GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT(NODE) \
int_cst_value (NON_DEFAULT_TEMPLATE_ARGS_COUNT (NODE))
#else
#define GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT(NODE) \
NON_DEFAULT_TEMPLATE_ARGS_COUNT (NODE) \
? int_cst_value (NON_DEFAULT_TEMPLATE_ARGS_COUNT (NODE)) \
: TREE_VEC_LENGTH (INNERMOST_TEMPLATE_ARGS (NODE))
#endif
/* The list of typedefs - used in the template - that need
access checking at template instantiation time.
FIXME this should be associated with the TEMPLATE_DECL, not the
TEMPLATE_INFO. */
#define TI_TYPEDEFS_NEEDING_ACCESS_CHECKING(NODE) \
((struct tree_template_info*)TEMPLATE_INFO_CHECK \
(NODE))->typedefs_needing_access_checking
/* We use TREE_VECs to hold template arguments. If there is only one
level of template arguments, then the TREE_VEC contains the
arguments directly. If there is more than one level of template
arguments, then each entry in the TREE_VEC is itself a TREE_VEC,
containing the template arguments for a single level. The first
entry in the outer TREE_VEC is the outermost level of template
parameters; the last is the innermost.
It is incorrect to ever form a template argument vector containing
only one level of arguments, but which is a TREE_VEC containing as
its only entry the TREE_VEC for that level.
For each TREE_VEC containing the template arguments for a single
level, it's possible to get or set the number of non defaulted
template arguments by using the accessor macros
GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT or
SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT. */
/* Nonzero if the template arguments is actually a vector of vectors,
rather than just a vector. */
#define TMPL_ARGS_HAVE_MULTIPLE_LEVELS(NODE) \
(NODE && TREE_VEC_LENGTH (NODE) && TREE_VEC_ELT (NODE, 0) \
&& TREE_CODE (TREE_VEC_ELT (NODE, 0)) == TREE_VEC)
/* The depth of a template argument vector. When called directly by
the parser, we use a TREE_LIST rather than a TREE_VEC to represent
template arguments. In fact, we may even see NULL_TREE if there
are no template arguments. In both of those cases, there is only
one level of template arguments. */
#define TMPL_ARGS_DEPTH(NODE) \
(TMPL_ARGS_HAVE_MULTIPLE_LEVELS (NODE) ? TREE_VEC_LENGTH (NODE) : 1)
/* The LEVELth level of the template ARGS. The outermost level of
args is level 1, not level 0. */
#define TMPL_ARGS_LEVEL(ARGS, LEVEL) \
(TMPL_ARGS_HAVE_MULTIPLE_LEVELS (ARGS) \
? TREE_VEC_ELT (ARGS, (LEVEL) - 1) : (ARGS))
/* Set the LEVELth level of the template ARGS to VAL. This macro does
not work with single-level argument vectors. */
#define SET_TMPL_ARGS_LEVEL(ARGS, LEVEL, VAL) \
(TREE_VEC_ELT (ARGS, (LEVEL) - 1) = (VAL))
/* Accesses the IDXth parameter in the LEVELth level of the ARGS. */
#define TMPL_ARG(ARGS, LEVEL, IDX) \
(TREE_VEC_ELT (TMPL_ARGS_LEVEL (ARGS, LEVEL), IDX))
/* Given a single level of template arguments in NODE, return the
number of arguments. */
#define NUM_TMPL_ARGS(NODE) \
(TREE_VEC_LENGTH (NODE))
/* Returns the innermost level of template arguments in ARGS. */
#define INNERMOST_TEMPLATE_ARGS(NODE) \
(get_innermost_template_args ((NODE), 1))
/* The number of levels of template parameters given by NODE. */
#define TMPL_PARMS_DEPTH(NODE) \
((HOST_WIDE_INT) TREE_INT_CST_LOW (TREE_PURPOSE (NODE)))
/* The TEMPLATE_DECL instantiated or specialized by NODE. This
TEMPLATE_DECL will be the immediate parent, not the most general
template. For example, in:
template <class T> struct S { template <class U> void f(U); }
the FUNCTION_DECL for S<int>::f<double> will have, as its
DECL_TI_TEMPLATE, `template <class U> S<int>::f<U>'.
As a special case, for a member friend template of a template
class, this value will not be a TEMPLATE_DECL, but rather an
IDENTIFIER_NODE or OVERLOAD indicating the name of the template and
any explicit template arguments provided. For example, in:
template <class T> struct S { friend void f<int>(int, double); }
the DECL_TI_TEMPLATE will be an IDENTIFIER_NODE for `f' and the
DECL_TI_ARGS will be {int}.
For a FIELD_DECL with a non-static data member initializer, this value
is the FIELD_DECL it was instantiated from. */
#define DECL_TI_TEMPLATE(NODE) TI_TEMPLATE (DECL_TEMPLATE_INFO (NODE))
/* The template arguments used to obtain this decl from the most
general form of DECL_TI_TEMPLATE. For the example given for
DECL_TI_TEMPLATE, the DECL_TI_ARGS will be {int, double}. These
are always the full set of arguments required to instantiate this
declaration from the most general template specialized here. */
#define DECL_TI_ARGS(NODE) TI_ARGS (DECL_TEMPLATE_INFO (NODE))
/* The TEMPLATE_DECL associated with NODE, a class type. Even if NODE
will be generated from a partial specialization, the TEMPLATE_DECL
referred to here will be the original template. For example,
given:
template <typename T> struct S {};
template <typename T> struct S<T*> {};
the CLASSTPYE_TI_TEMPLATE for S<int*> will be S, not the S<T*>. */
#define CLASSTYPE_TI_TEMPLATE(NODE) TI_TEMPLATE (CLASSTYPE_TEMPLATE_INFO (NODE))
#define CLASSTYPE_TI_ARGS(NODE) TI_ARGS (CLASSTYPE_TEMPLATE_INFO (NODE))
/* For a template instantiation TYPE, returns the TYPE corresponding
to the primary template. Otherwise returns TYPE itself. */
#define CLASSTYPE_PRIMARY_TEMPLATE_TYPE(TYPE) \
((CLASSTYPE_USE_TEMPLATE ((TYPE)) \
&& !CLASSTYPE_TEMPLATE_SPECIALIZATION ((TYPE))) \
? TREE_TYPE (DECL_TEMPLATE_RESULT (DECL_PRIMARY_TEMPLATE \
(CLASSTYPE_TI_TEMPLATE ((TYPE))))) \
: (TYPE))
/* Like CLASS_TI_TEMPLATE, but also works for ENUMERAL_TYPEs. */
#define TYPE_TI_TEMPLATE(NODE) \
(TI_TEMPLATE (TYPE_TEMPLATE_INFO (NODE)))
/* Like DECL_TI_ARGS, but for an ENUMERAL_, RECORD_, or UNION_TYPE. */
#define TYPE_TI_ARGS(NODE) \
(TI_ARGS (TYPE_TEMPLATE_INFO (NODE)))
#define INNERMOST_TEMPLATE_PARMS(NODE) TREE_VALUE (NODE)
/* Nonzero if NODE (a TEMPLATE_DECL) is a member template, in the
sense of [temp.mem]. */
#define DECL_MEMBER_TEMPLATE_P(NODE) \
(DECL_LANG_FLAG_1 (TEMPLATE_DECL_CHECK (NODE)))
/* Nonzero if the NODE corresponds to the template parameters for a
member template, whose inline definition is being processed after
the class definition is complete. */
#define TEMPLATE_PARMS_FOR_INLINE(NODE) TREE_LANG_FLAG_1 (NODE)
/* Determine if a declaration (PARM_DECL or FIELD_DECL) is a pack. */
#define DECL_PACK_P(NODE) \
(DECL_P (NODE) && PACK_EXPANSION_P (TREE_TYPE (NODE)))
/* Determines if NODE is an expansion of one or more parameter packs,
e.g., a TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION. */
#define PACK_EXPANSION_P(NODE) \
(TREE_CODE (NODE) == TYPE_PACK_EXPANSION \
|| TREE_CODE (NODE) == EXPR_PACK_EXPANSION)
/* Extracts the type or expression pattern from a TYPE_PACK_EXPANSION or
EXPR_PACK_EXPANSION. */
#define PACK_EXPANSION_PATTERN(NODE) \
(TREE_CODE (NODE) == TYPE_PACK_EXPANSION? TREE_TYPE (NODE) \
: TREE_OPERAND (NODE, 0))
/* Sets the type or expression pattern for a TYPE_PACK_EXPANSION or
EXPR_PACK_EXPANSION. */
#define SET_PACK_EXPANSION_PATTERN(NODE,VALUE) \
if (TREE_CODE (NODE) == TYPE_PACK_EXPANSION) \
TREE_TYPE (NODE) = VALUE; \
else \
TREE_OPERAND (NODE, 0) = VALUE
/* The list of parameter packs used in the PACK_EXPANSION_* node. The
TREE_VALUE of each TREE_LIST contains the parameter packs. */
#define PACK_EXPANSION_PARAMETER_PACKS(NODE) \
*(TREE_CODE (NODE) == EXPR_PACK_EXPANSION \
? &TREE_OPERAND (NODE, 1) \
: &TYPE_MINVAL (TYPE_PACK_EXPANSION_CHECK (NODE)))
/* Any additional template args to be applied when substituting into
the pattern, set by tsubst_pack_expansion for partial instantiations. */
#define PACK_EXPANSION_EXTRA_ARGS(NODE) \
*(TREE_CODE (NODE) == TYPE_PACK_EXPANSION \
? &TYPE_MAXVAL (NODE) \
: &TREE_OPERAND ((NODE), 2))
/* True iff this pack expansion is within a function context. */
#define PACK_EXPANSION_LOCAL_P(NODE) TREE_LANG_FLAG_0 (NODE)
/* True iff this pack expansion is for sizeof.... */
#define PACK_EXPANSION_SIZEOF_P(NODE) TREE_LANG_FLAG_1 (NODE)
/* True iff the wildcard can match a template parameter pack. */
#define WILDCARD_PACK_P(NODE) TREE_LANG_FLAG_0 (NODE)
/* Determine if this is an argument pack. */
#define ARGUMENT_PACK_P(NODE) \
(TREE_CODE (NODE) == TYPE_ARGUMENT_PACK \
|| TREE_CODE (NODE) == NONTYPE_ARGUMENT_PACK)
/* The arguments stored in an argument pack. Arguments are stored in a
TREE_VEC, which may have length zero. */
#define ARGUMENT_PACK_ARGS(NODE) \
(TREE_CODE (NODE) == TYPE_ARGUMENT_PACK? TREE_TYPE (NODE) \
: TREE_OPERAND (NODE, 0))
/* Set the arguments stored in an argument pack. VALUE must be a
TREE_VEC. */
#define SET_ARGUMENT_PACK_ARGS(NODE,VALUE) \
if (TREE_CODE (NODE) == TYPE_ARGUMENT_PACK) \
TREE_TYPE (NODE) = VALUE; \
else \
TREE_OPERAND (NODE, 0) = VALUE
/* Whether the argument pack is "incomplete", meaning that more
arguments can still be deduced. Incomplete argument packs are only
used when the user has provided an explicit template argument list
for a variadic function template. Some of the explicit template
arguments will be placed into the beginning of the argument pack,
but additional arguments might still be deduced. */
#define ARGUMENT_PACK_INCOMPLETE_P(NODE) \
TREE_ADDRESSABLE (ARGUMENT_PACK_ARGS (NODE))
/* When ARGUMENT_PACK_INCOMPLETE_P, stores the explicit template
arguments used to fill this pack. */
#define ARGUMENT_PACK_EXPLICIT_ARGS(NODE) \
TREE_TYPE (ARGUMENT_PACK_ARGS (NODE))
/* In an ARGUMENT_PACK_SELECT, the argument pack from which an
argument will be selected. */
#define ARGUMENT_PACK_SELECT_FROM_PACK(NODE) \
(((struct tree_argument_pack_select *)ARGUMENT_PACK_SELECT_CHECK (NODE))->argument_pack)
/* In an ARGUMENT_PACK_SELECT, the index of the argument we want to
select. */
#define ARGUMENT_PACK_SELECT_INDEX(NODE) \
(((struct tree_argument_pack_select *)ARGUMENT_PACK_SELECT_CHECK (NODE))->index)
/* In an ARGUMENT_PACK_SELECT, the actual underlying argument that the
ARGUMENT_PACK_SELECT represents. */
#define ARGUMENT_PACK_SELECT_ARG(NODE) \
TREE_VEC_ELT (ARGUMENT_PACK_ARGS (ARGUMENT_PACK_SELECT_FROM_PACK (NODE)), \
ARGUMENT_PACK_SELECT_INDEX (NODE))
#define FOLD_EXPR_CHECK(NODE) \
TREE_CHECK4 (NODE, UNARY_LEFT_FOLD_EXPR, UNARY_RIGHT_FOLD_EXPR, \
BINARY_LEFT_FOLD_EXPR, BINARY_RIGHT_FOLD_EXPR)
#define BINARY_FOLD_EXPR_CHECK(NODE) \
TREE_CHECK2 (NODE, BINARY_LEFT_FOLD_EXPR, BINARY_RIGHT_FOLD_EXPR)
/* True if NODE is UNARY_FOLD_EXPR or a BINARY_FOLD_EXPR */
#define FOLD_EXPR_P(NODE) \
(TREE_CODE (NODE) == UNARY_LEFT_FOLD_EXPR \
|| TREE_CODE (NODE) == UNARY_RIGHT_FOLD_EXPR \
|| TREE_CODE (NODE) == BINARY_LEFT_FOLD_EXPR \
|| TREE_CODE (NODE) == BINARY_RIGHT_FOLD_EXPR)
/* True when NODE is a fold over a compound assignment operator. */
#define FOLD_EXPR_MODIFY_P(NODE) \
TREE_LANG_FLAG_0 (FOLD_EXPR_CHECK (NODE))
/* An INTEGER_CST containing the tree code of the folded operator. */
#define FOLD_EXPR_OP(NODE) \
TREE_OPERAND (FOLD_EXPR_CHECK (NODE), 0)
/* The expression containing an unexpanded parameter pack. */
#define FOLD_EXPR_PACK(NODE) \
TREE_OPERAND (FOLD_EXPR_CHECK (NODE), 1)
/* In a binary fold expression, the argument with no unexpanded
parameter packs. */
#define FOLD_EXPR_INIT(NODE) \
TREE_OPERAND (BINARY_FOLD_EXPR_CHECK (NODE), 2)
/* In a FUNCTION_DECL, the saved language-specific per-function data. */
#define DECL_SAVED_FUNCTION_DATA(NODE) \
(LANG_DECL_FN_CHECK (FUNCTION_DECL_CHECK (NODE)) \
->u.saved_language_function)
/* True if NODE is an implicit INDIRECT_EXPR from convert_from_reference. */
#define REFERENCE_REF_P(NODE) \
(INDIRECT_REF_P (NODE) \
&& TREE_TYPE (TREE_OPERAND (NODE, 0)) \
&& (TREE_CODE (TREE_TYPE (TREE_OPERAND ((NODE), 0))) \
== REFERENCE_TYPE))
/* True if NODE is a REFERENCE_TYPE which is OK to instantiate to be a
reference to VLA type, because it's used for VLA capture. */
#define REFERENCE_VLA_OK(NODE) \
(TYPE_LANG_FLAG_5 (REFERENCE_TYPE_CHECK (NODE)))
#define NEW_EXPR_USE_GLOBAL(NODE) \
TREE_LANG_FLAG_0 (NEW_EXPR_CHECK (NODE))
#define DELETE_EXPR_USE_GLOBAL(NODE) \
TREE_LANG_FLAG_0 (DELETE_EXPR_CHECK (NODE))
#define DELETE_EXPR_USE_VEC(NODE) \
TREE_LANG_FLAG_1 (DELETE_EXPR_CHECK (NODE))
#define CALL_OR_AGGR_INIT_CHECK(NODE) \
TREE_CHECK2 ((NODE), CALL_EXPR, AGGR_INIT_EXPR)
/* Indicates that this is a non-dependent COMPOUND_EXPR which will
resolve to a function call. */
#define COMPOUND_EXPR_OVERLOADED(NODE) \
TREE_LANG_FLAG_0 (COMPOUND_EXPR_CHECK (NODE))
/* In a CALL_EXPR appearing in a template, true if Koenig lookup
should be performed at instantiation time. */
#define KOENIG_LOOKUP_P(NODE) TREE_LANG_FLAG_0 (CALL_EXPR_CHECK (NODE))
/* True if the arguments to NODE should be evaluated in left-to-right
order regardless of PUSH_ARGS_REVERSED. */
#define CALL_EXPR_ORDERED_ARGS(NODE) \
TREE_LANG_FLAG_3 (CALL_OR_AGGR_INIT_CHECK (NODE))
/* True if the arguments to NODE should be evaluated in right-to-left
order regardless of PUSH_ARGS_REVERSED. */
#define CALL_EXPR_REVERSE_ARGS(NODE) \
TREE_LANG_FLAG_5 (CALL_OR_AGGR_INIT_CHECK (NODE))
/* True if CALL_EXPR was written as an operator expression, not a function
call. */
#define CALL_EXPR_OPERATOR_SYNTAX(NODE) \
TREE_LANG_FLAG_6 (CALL_OR_AGGR_INIT_CHECK (NODE))
/* Indicates whether a string literal has been parenthesized. Such
usages are disallowed in certain circumstances. */
#define PAREN_STRING_LITERAL_P(NODE) \
TREE_LANG_FLAG_0 (STRING_CST_CHECK (NODE))
/* Indicates whether a COMPONENT_REF or a SCOPE_REF has been parenthesized, or
an INDIRECT_REF comes from parenthesizing a _DECL. Currently only set some
of the time in C++14 mode. */
#define REF_PARENTHESIZED_P(NODE) \
TREE_LANG_FLAG_2 (TREE_CHECK3 ((NODE), COMPONENT_REF, INDIRECT_REF, SCOPE_REF))
/* Nonzero if this AGGR_INIT_EXPR provides for initialization via a
constructor call, rather than an ordinary function call. */
#define AGGR_INIT_VIA_CTOR_P(NODE) \
TREE_LANG_FLAG_0 (AGGR_INIT_EXPR_CHECK (NODE))
/* Nonzero if expanding this AGGR_INIT_EXPR should first zero-initialize
the object. */
#define AGGR_INIT_ZERO_FIRST(NODE) \
TREE_LANG_FLAG_2 (AGGR_INIT_EXPR_CHECK (NODE))
/* Nonzero means that the call is the jump from a thunk to the
thunked-to function. */
#define AGGR_INIT_FROM_THUNK_P(NODE) \
(AGGR_INIT_EXPR_CHECK (NODE)->base.protected_flag)
/* AGGR_INIT_EXPR accessors. These are equivalent to the CALL_EXPR
accessors, except for AGGR_INIT_EXPR_SLOT (which takes the place of
CALL_EXPR_STATIC_CHAIN). */
#define AGGR_INIT_EXPR_FN(NODE) TREE_OPERAND (AGGR_INIT_EXPR_CHECK (NODE), 1)
#define AGGR_INIT_EXPR_SLOT(NODE) \
TREE_OPERAND (AGGR_INIT_EXPR_CHECK (NODE), 2)
#define AGGR_INIT_EXPR_ARG(NODE, I) \
TREE_OPERAND (AGGR_INIT_EXPR_CHECK (NODE), (I) + 3)
#define aggr_init_expr_nargs(NODE) (VL_EXP_OPERAND_LENGTH(NODE) - 3)
/* AGGR_INIT_EXPR_ARGP returns a pointer to the argument vector for NODE.
We can't use &AGGR_INIT_EXPR_ARG (NODE, 0) because that will complain if
the argument count is zero when checking is enabled. Instead, do
the pointer arithmetic to advance past the 3 fixed operands in a
AGGR_INIT_EXPR. That produces a valid pointer to just past the end of
the operand array, even if it's not valid to dereference it. */
#define AGGR_INIT_EXPR_ARGP(NODE) \
(&(TREE_OPERAND (AGGR_INIT_EXPR_CHECK (NODE), 0)) + 3)
/* Abstract iterators for AGGR_INIT_EXPRs. */
/* Structure containing iterator state. */
struct aggr_init_expr_arg_iterator {
tree t; /* the aggr_init_expr */
int n; /* argument count */
int i; /* next argument index */
};
/* Initialize the abstract argument list iterator object ITER with the
arguments from AGGR_INIT_EXPR node EXP. */
inline void
init_aggr_init_expr_arg_iterator (tree exp,
aggr_init_expr_arg_iterator *iter)
{
iter->t = exp;
iter->n = aggr_init_expr_nargs (exp);
iter->i = 0;
}
/* Return the next argument from abstract argument list iterator object ITER,
and advance its state. Return NULL_TREE if there are no more arguments. */
inline tree
next_aggr_init_expr_arg (aggr_init_expr_arg_iterator *iter)
{
tree result;
if (iter->i >= iter->n)
return NULL_TREE;
result = AGGR_INIT_EXPR_ARG (iter->t, iter->i);
iter->i++;
return result;
}
/* Initialize the abstract argument list iterator object ITER, then advance
past and return the first argument. Useful in for expressions, e.g.
for (arg = first_aggr_init_expr_arg (exp, &iter); arg;
arg = next_aggr_init_expr_arg (&iter)) */
inline tree
first_aggr_init_expr_arg (tree exp, aggr_init_expr_arg_iterator *iter)
{
init_aggr_init_expr_arg_iterator (exp, iter);
return next_aggr_init_expr_arg (iter);
}
/* Test whether there are more arguments in abstract argument list iterator
ITER, without changing its state. */
inline bool
more_aggr_init_expr_args_p (const aggr_init_expr_arg_iterator *iter)
{
return (iter->i < iter->n);
}
/* Iterate through each argument ARG of AGGR_INIT_EXPR CALL, using variable
ITER (of type aggr_init_expr_arg_iterator) to hold the iteration state. */
#define FOR_EACH_AGGR_INIT_EXPR_ARG(arg, iter, call) \
for ((arg) = first_aggr_init_expr_arg ((call), &(iter)); (arg); \
(arg) = next_aggr_init_expr_arg (&(iter)))
/* VEC_INIT_EXPR accessors. */
#define VEC_INIT_EXPR_SLOT(NODE) TREE_OPERAND (VEC_INIT_EXPR_CHECK (NODE), 0)
#define VEC_INIT_EXPR_INIT(NODE) TREE_OPERAND (VEC_INIT_EXPR_CHECK (NODE), 1)
/* Indicates that a VEC_INIT_EXPR is a potential constant expression.
Only set when the current function is constexpr. */
#define VEC_INIT_EXPR_IS_CONSTEXPR(NODE) \
TREE_LANG_FLAG_0 (VEC_INIT_EXPR_CHECK (NODE))
/* Indicates that a VEC_INIT_EXPR is expressing value-initialization. */
#define VEC_INIT_EXPR_VALUE_INIT(NODE) \
TREE_LANG_FLAG_1 (VEC_INIT_EXPR_CHECK (NODE))
/* The condition under which this MUST_NOT_THROW_EXPR actually blocks
exceptions. NULL_TREE means 'true'. */
#define MUST_NOT_THROW_COND(NODE) \
TREE_OPERAND (MUST_NOT_THROW_EXPR_CHECK (NODE), 1)
/* The TYPE_MAIN_DECL for a class template type is a TYPE_DECL, not a
TEMPLATE_DECL. This macro determines whether or not a given class
type is really a template type, as opposed to an instantiation or
specialization of one. */
#define CLASSTYPE_IS_TEMPLATE(NODE) \
(CLASSTYPE_TEMPLATE_INFO (NODE) \
&& !CLASSTYPE_USE_TEMPLATE (NODE) \
&& PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (NODE)))
/* The name used by the user to name the typename type. Typically,
this is an IDENTIFIER_NODE, and the same as the DECL_NAME on the
corresponding TYPE_DECL. However, this may also be a
TEMPLATE_ID_EXPR if we had something like `typename X::Y<T>'. */
#define TYPENAME_TYPE_FULLNAME(NODE) \
(TYPE_VALUES_RAW (TYPENAME_TYPE_CHECK (NODE)))
/* True if a TYPENAME_TYPE was declared as an "enum". */
#define TYPENAME_IS_ENUM_P(NODE) \
(TREE_LANG_FLAG_0 (TYPENAME_TYPE_CHECK (NODE)))
/* True if a TYPENAME_TYPE was declared as a "class", "struct", or
"union". */
#define TYPENAME_IS_CLASS_P(NODE) \
(TREE_LANG_FLAG_1 (TYPENAME_TYPE_CHECK (NODE)))
/* True if a TYPENAME_TYPE is in the process of being resolved. */
#define TYPENAME_IS_RESOLVING_P(NODE) \
(TREE_LANG_FLAG_2 (TYPENAME_TYPE_CHECK (NODE)))
/* [class.virtual]
A class that declares or inherits a virtual function is called a
polymorphic class. */
#define TYPE_POLYMORPHIC_P(NODE) (TREE_LANG_FLAG_2 (NODE))
/* Nonzero if this class has a virtual function table pointer. */
#define TYPE_CONTAINS_VPTR_P(NODE) \
(TYPE_POLYMORPHIC_P (NODE) || CLASSTYPE_VBASECLASSES (NODE))
/* This flag is true of a local VAR_DECL if it was declared in a for
statement, but we are no longer in the scope of the for. */
#define DECL_DEAD_FOR_LOCAL(NODE) DECL_LANG_FLAG_7 (VAR_DECL_CHECK (NODE))
/* This flag is set on a VAR_DECL that is a DECL_DEAD_FOR_LOCAL
if we already emitted a warning about using it. */
#define DECL_ERROR_REPORTED(NODE) DECL_LANG_FLAG_0 (VAR_DECL_CHECK (NODE))
/* Nonzero if NODE is a FUNCTION_DECL (for a function with global
scope) declared in a local scope. */
#define DECL_LOCAL_FUNCTION_P(NODE) \
DECL_LANG_FLAG_0 (FUNCTION_DECL_CHECK (NODE))
/* Nonzero if NODE is the target for genericization of 'break' stmts. */
#define LABEL_DECL_BREAK(NODE) \
DECL_LANG_FLAG_0 (LABEL_DECL_CHECK (NODE))
/* Nonzero if NODE is the target for genericization of 'continue' stmts. */
#define LABEL_DECL_CONTINUE(NODE) \
DECL_LANG_FLAG_1 (LABEL_DECL_CHECK (NODE))
/* True if NODE was declared with auto in its return type, but it has
started compilation and so the return type might have been changed by
return type deduction; its declared return type should be found in
DECL_STRUCT_FUNCTION(NODE)->language->x_auto_return_pattern. */
#define FNDECL_USED_AUTO(NODE) \
TREE_LANG_FLAG_2 (FUNCTION_DECL_CHECK (NODE))
/* Nonzero if NODE is a DECL which we know about but which has not
been explicitly declared, such as a built-in function or a friend
declared inside a class. In the latter case DECL_HIDDEN_FRIEND_P
will be set. */
#define DECL_ANTICIPATED(NODE) \
(DECL_LANG_SPECIFIC (TYPE_FUNCTION_OR_TEMPLATE_DECL_CHECK (NODE)) \
->u.base.anticipated_p)
/* True for artificial decls added for OpenMP privatized non-static
data members. */
#define DECL_OMP_PRIVATIZED_MEMBER(NODE) \
(DECL_LANG_SPECIFIC (VAR_DECL_CHECK (NODE))->u.base.anticipated_p)
/* Nonzero if NODE is a FUNCTION_DECL which was declared as a friend
within a class but has not been declared in the surrounding scope.
The function is invisible except via argument dependent lookup. */
#define DECL_HIDDEN_FRIEND_P(NODE) \
(LANG_DECL_FN_CHECK (DECL_COMMON_CHECK (NODE))->hidden_friend_p)
/* Nonzero if NODE is an artificial FUNCTION_DECL for
#pragma omp declare reduction. */
#define DECL_OMP_DECLARE_REDUCTION_P(NODE) \
(LANG_DECL_FN_CHECK (DECL_COMMON_CHECK (NODE))->omp_declare_reduction_p)
/* Nonzero if DECL has been declared threadprivate by
#pragma omp threadprivate. */
#define CP_DECL_THREADPRIVATE_P(DECL) \
(DECL_LANG_SPECIFIC (VAR_DECL_CHECK (DECL))->u.base.threadprivate_or_deleted_p)
/* Nonzero if NODE is a VAR_DECL which has been declared inline. */
#define DECL_VAR_DECLARED_INLINE_P(NODE) \
(DECL_LANG_SPECIFIC (VAR_DECL_CHECK (NODE)) \
? DECL_LANG_SPECIFIC (NODE)->u.base.var_declared_inline_p \
: false)
#define SET_DECL_VAR_DECLARED_INLINE_P(NODE) \
(DECL_LANG_SPECIFIC (VAR_DECL_CHECK (NODE))->u.base.var_declared_inline_p \
= true)
/* Nonzero if NODE is an artificial VAR_DECL for a C++17 decomposition
declaration. */
#define DECL_DECOMPOSITION_P(NODE) \
(VAR_P (NODE) && DECL_LANG_SPECIFIC (NODE) \
? DECL_LANG_SPECIFIC (NODE)->u.base.decomposition_p \
: false)
#define SET_DECL_DECOMPOSITION_P(NODE) \
(DECL_LANG_SPECIFIC (VAR_DECL_CHECK (NODE))->u.base.decomposition_p \
= true)
/* Nonzero if NODE is an inline VAR_DECL. In C++17, static data members
declared with constexpr specifier are implicitly inline variables. */
#define DECL_INLINE_VAR_P(NODE) \
(DECL_VAR_DECLARED_INLINE_P (NODE) \
|| (cxx_dialect >= cxx1z \
&& DECL_DECLARED_CONSTEXPR_P (NODE) \
&& DECL_CLASS_SCOPE_P (NODE)))
/* Nonzero if DECL was declared with '= delete'. */
#define DECL_DELETED_FN(DECL) \
(LANG_DECL_FN_CHECK (DECL)->min.base.threadprivate_or_deleted_p)
/* Nonzero if DECL was declared with '= default' (maybe implicitly). */
#define DECL_DEFAULTED_FN(DECL) \
(LANG_DECL_FN_CHECK (DECL)->defaulted_p)
/* Nonzero if DECL is explicitly defaulted in the class body. */
#define DECL_DEFAULTED_IN_CLASS_P(DECL) \
(DECL_DEFAULTED_FN (DECL) && DECL_INITIALIZED_IN_CLASS_P (DECL))
/* Nonzero if DECL was defaulted outside the class body. */
#define DECL_DEFAULTED_OUTSIDE_CLASS_P(DECL) \
(DECL_DEFAULTED_FN (DECL) \
&& !(DECL_ARTIFICIAL (DECL) || DECL_INITIALIZED_IN_CLASS_P (DECL)))
/* Record whether a typedef for type `int' was actually `signed int'. */
#define C_TYPEDEF_EXPLICITLY_SIGNED(EXP) DECL_LANG_FLAG_1 (EXP)
/* Returns nonzero if DECL has external linkage, as specified by the
language standard. (This predicate may hold even when the
corresponding entity is not actually given external linkage in the
object file; see decl_linkage for details.) */
#define DECL_EXTERNAL_LINKAGE_P(DECL) \
(decl_linkage (DECL) == lk_external)
/* Keep these codes in ascending code order. */
#define INTEGRAL_CODE_P(CODE) \
((CODE) == ENUMERAL_TYPE \
|| (CODE) == BOOLEAN_TYPE \
|| (CODE) == INTEGER_TYPE)
/* [basic.fundamental]
Types bool, char, wchar_t, and the signed and unsigned integer types
are collectively called integral types.
Note that INTEGRAL_TYPE_P, as defined in tree.h, allows enumeration
types as well, which is incorrect in C++. Keep these checks in
ascending code order. */
#define CP_INTEGRAL_TYPE_P(TYPE) \
(TREE_CODE (TYPE) == BOOLEAN_TYPE \
|| TREE_CODE (TYPE) == INTEGER_TYPE)
/* Returns true if TYPE is an integral or enumeration name. Keep
these checks in ascending code order. */
#define INTEGRAL_OR_ENUMERATION_TYPE_P(TYPE) \
(TREE_CODE (TYPE) == ENUMERAL_TYPE || CP_INTEGRAL_TYPE_P (TYPE))
/* Returns true if TYPE is an integral or unscoped enumeration type. */
#define INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P(TYPE) \
(UNSCOPED_ENUM_P (TYPE) || CP_INTEGRAL_TYPE_P (TYPE))
/* True if the class type TYPE is a literal type. */
#define CLASSTYPE_LITERAL_P(TYPE) \
(LANG_TYPE_CLASS_CHECK (TYPE)->is_literal)
/* [basic.fundamental]
Integral and floating types are collectively called arithmetic
types.
As a GNU extension, we also accept complex types.
Keep these checks in ascending code order. */
#define ARITHMETIC_TYPE_P(TYPE) \
(CP_INTEGRAL_TYPE_P (TYPE) \
|| TREE_CODE (TYPE) == REAL_TYPE \
|| TREE_CODE (TYPE) == COMPLEX_TYPE)
/* True iff TYPE is cv decltype(nullptr). */
#define NULLPTR_TYPE_P(TYPE) (TREE_CODE (TYPE) == NULLPTR_TYPE)
/* [basic.types]
Arithmetic types, enumeration types, pointer types,
pointer-to-member types, and std::nullptr_t are collectively called
scalar types.
Keep these checks in ascending code order. */
#define SCALAR_TYPE_P(TYPE) \
(TYPE_PTRDATAMEM_P (TYPE) \
|| TREE_CODE (TYPE) == ENUMERAL_TYPE \
|| ARITHMETIC_TYPE_P (TYPE) \
|| TYPE_PTR_P (TYPE) \
|| TYPE_PTRMEMFUNC_P (TYPE) \
|| NULLPTR_TYPE_P (TYPE))
/* Determines whether this type is a C++0x scoped enumeration
type. Scoped enumerations types are introduced via "enum class" or
"enum struct", e.g.,
enum class Color {
Red, Green, Blue
};
Scoped enumeration types are different from normal (unscoped)
enumeration types in several ways:
- The enumerators of a scoped enumeration type are only available
within the scope of the enumeration type and not in the
enclosing scope. For example, the Red color can be referred to
with "Color::Red" but not "Red".
- Scoped enumerators and enumerations do not implicitly convert
to integers or 'bool'.
- The underlying type of the enum is well-defined. */
#define SCOPED_ENUM_P(TYPE) \
(TREE_CODE (TYPE) == ENUMERAL_TYPE && ENUM_IS_SCOPED (TYPE))
/* Determine whether this is an unscoped enumeration type. */
#define UNSCOPED_ENUM_P(TYPE) \
(TREE_CODE (TYPE) == ENUMERAL_TYPE && !ENUM_IS_SCOPED (TYPE))
/* Set the flag indicating whether an ENUMERAL_TYPE is a C++0x scoped
enumeration type (1) or a normal (unscoped) enumeration type
(0). */
#define SET_SCOPED_ENUM_P(TYPE, VAL) \
(ENUM_IS_SCOPED (TYPE) = (VAL))
#define SET_OPAQUE_ENUM_P(TYPE, VAL) \
(ENUM_IS_OPAQUE (TYPE) = (VAL))
#define OPAQUE_ENUM_P(TYPE) \
(TREE_CODE (TYPE) == ENUMERAL_TYPE && ENUM_IS_OPAQUE (TYPE))
/* Determines whether an ENUMERAL_TYPE has an explicit
underlying type. */
#define ENUM_FIXED_UNDERLYING_TYPE_P(NODE) (TYPE_LANG_FLAG_5 (NODE))
/* Returns the underlying type of the given enumeration type. The
underlying type is determined in different ways, depending on the
properties of the enum:
- In C++0x, the underlying type can be explicitly specified, e.g.,
enum E1 : char { ... } // underlying type is char
- In a C++0x scoped enumeration, the underlying type is int
unless otherwises specified:
enum class E2 { ... } // underlying type is int
- Otherwise, the underlying type is determined based on the
values of the enumerators. In this case, the
ENUM_UNDERLYING_TYPE will not be set until after the definition
of the enumeration is completed by finish_enum. */
#define ENUM_UNDERLYING_TYPE(TYPE) \
TREE_TYPE (ENUMERAL_TYPE_CHECK (TYPE))
/* [dcl.init.aggr]
An aggregate is an array or a class with no user-provided
constructors, no brace-or-equal-initializers for non-static data
members, no private or protected non-static data members, no
base classes, and no virtual functions.
As an extension, we also treat vectors as aggregates. Keep these
checks in ascending code order. */
#define CP_AGGREGATE_TYPE_P(TYPE) \
(TREE_CODE (TYPE) == VECTOR_TYPE \
||TREE_CODE (TYPE) == ARRAY_TYPE \
|| (CLASS_TYPE_P (TYPE) && !CLASSTYPE_NON_AGGREGATE (TYPE)))
/* Nonzero for a class type means that the class type has a
user-declared constructor. */
#define TYPE_HAS_USER_CONSTRUCTOR(NODE) (TYPE_LANG_FLAG_1 (NODE))
/* Nonzero means that the FUNCTION_TYPE or METHOD_TYPE has a
late-specified return type. */
#define TYPE_HAS_LATE_RETURN_TYPE(NODE) \
(TYPE_LANG_FLAG_2 (FUNC_OR_METHOD_CHECK (NODE)))
/* When appearing in an INDIRECT_REF, it means that the tree structure
underneath is actually a call to a constructor. This is needed
when the constructor must initialize local storage (which can
be automatically destroyed), rather than allowing it to allocate
space from the heap.
When appearing in a SAVE_EXPR, it means that underneath
is a call to a constructor.
When appearing in a CONSTRUCTOR, the expression is a
compound literal.
When appearing in a FIELD_DECL, it means that this field
has been duly initialized in its constructor. */
#define TREE_HAS_CONSTRUCTOR(NODE) (TREE_LANG_FLAG_4 (NODE))
/* True if NODE is a brace-enclosed initializer. */
#define BRACE_ENCLOSED_INITIALIZER_P(NODE) \
(TREE_CODE (NODE) == CONSTRUCTOR && TREE_TYPE (NODE) == init_list_type_node)
/* True if NODE is a compound-literal, i.e., a brace-enclosed
initializer cast to a particular type. */
#define COMPOUND_LITERAL_P(NODE) \
(TREE_CODE (NODE) == CONSTRUCTOR && TREE_HAS_CONSTRUCTOR (NODE))
#define EMPTY_CONSTRUCTOR_P(NODE) (TREE_CODE (NODE) == CONSTRUCTOR \
&& vec_safe_is_empty(CONSTRUCTOR_ELTS(NODE))\
&& !TREE_HAS_CONSTRUCTOR (NODE))
/* True if NODE is a init-list used as a direct-initializer, i.e.
B b{1,2}, not B b({1,2}) or B b = {1,2}. */
#define CONSTRUCTOR_IS_DIRECT_INIT(NODE) (TREE_LANG_FLAG_0 (CONSTRUCTOR_CHECK (NODE)))
/* True if an uninitialized element in NODE should not be treated as
implicitly value-initialized. Only used in constexpr evaluation. */
#define CONSTRUCTOR_NO_IMPLICIT_ZERO(NODE) \
(TREE_LANG_FLAG_1 (CONSTRUCTOR_CHECK (NODE)))
/* True if this CONSTRUCTOR should not be used as a variable initializer
because it was loaded from a constexpr variable with mutable fields. */
#define CONSTRUCTOR_MUTABLE_POISON(NODE) \
(TREE_LANG_FLAG_2 (CONSTRUCTOR_CHECK (NODE)))
#define DIRECT_LIST_INIT_P(NODE) \
(BRACE_ENCLOSED_INITIALIZER_P (NODE) && CONSTRUCTOR_IS_DIRECT_INIT (NODE))
/* True if NODE represents a conversion for direct-initialization in a
template. Set by perform_implicit_conversion_flags. */
#define IMPLICIT_CONV_EXPR_DIRECT_INIT(NODE) \
(TREE_LANG_FLAG_0 (IMPLICIT_CONV_EXPR_CHECK (NODE)))
/* Nonzero means that an object of this type can not be initialized using
an initializer list. */
#define CLASSTYPE_NON_AGGREGATE(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->non_aggregate)
#define TYPE_NON_AGGREGATE_CLASS(NODE) \
(CLASS_TYPE_P (NODE) && CLASSTYPE_NON_AGGREGATE (NODE))
/* Nonzero if there is a non-trivial X::op=(cv X&) for this class. */
#define TYPE_HAS_COMPLEX_COPY_ASSIGN(NODE) (LANG_TYPE_CLASS_CHECK (NODE)->has_complex_copy_assign)
/* Nonzero if there is a non-trivial X::X(cv X&) for this class. */
#define TYPE_HAS_COMPLEX_COPY_CTOR(NODE) (LANG_TYPE_CLASS_CHECK (NODE)->has_complex_copy_ctor)
/* Nonzero if there is a non-trivial X::op=(X&&) for this class. */
#define TYPE_HAS_COMPLEX_MOVE_ASSIGN(NODE) (LANG_TYPE_CLASS_CHECK (NODE)->has_complex_move_assign)
/* Nonzero if there is a non-trivial X::X(X&&) for this class. */
#define TYPE_HAS_COMPLEX_MOVE_CTOR(NODE) (LANG_TYPE_CLASS_CHECK (NODE)->has_complex_move_ctor)
/* Nonzero if there is no trivial default constructor for this class. */
#define TYPE_HAS_COMPLEX_DFLT(NODE) (LANG_TYPE_CLASS_CHECK (NODE)->has_complex_dflt)
/* Nonzero if TYPE has a trivial destructor. From [class.dtor]:
A destructor is trivial if it is an implicitly declared
destructor and if:
- all of the direct base classes of its class have trivial
destructors,
- for all of the non-static data members of its class that are
of class type (or array thereof), each such class has a
trivial destructor. */
#define TYPE_HAS_TRIVIAL_DESTRUCTOR(NODE) \
(!TYPE_HAS_NONTRIVIAL_DESTRUCTOR (NODE))
/* Nonzero for _TYPE node means that this type does not have a trivial
destructor. Therefore, destroying an object of this type will
involve a call to a destructor. This can apply to objects of
ARRAY_TYPE is the type of the elements needs a destructor. */
#define TYPE_HAS_NONTRIVIAL_DESTRUCTOR(NODE) \
(TYPE_LANG_FLAG_4 (NODE))
/* Nonzero for class type means that the default constructor is trivial. */
#define TYPE_HAS_TRIVIAL_DFLT(NODE) \
(TYPE_HAS_DEFAULT_CONSTRUCTOR (NODE) && ! TYPE_HAS_COMPLEX_DFLT (NODE))
/* Nonzero for class type means that copy initialization of this type can use
a bitwise copy. */
#define TYPE_HAS_TRIVIAL_COPY_CTOR(NODE) \
(TYPE_HAS_COPY_CTOR (NODE) && ! TYPE_HAS_COMPLEX_COPY_CTOR (NODE))
/* Nonzero for class type means that assignment of this type can use
a bitwise copy. */
#define TYPE_HAS_TRIVIAL_COPY_ASSIGN(NODE) \
(TYPE_HAS_COPY_ASSIGN (NODE) && ! TYPE_HAS_COMPLEX_COPY_ASSIGN (NODE))
/* Returns true if NODE is a pointer-to-data-member. */
#define TYPE_PTRDATAMEM_P(NODE) \
(TREE_CODE (NODE) == OFFSET_TYPE)
/* Returns true if NODE is a pointer. */
#define TYPE_PTR_P(NODE) \
(TREE_CODE (NODE) == POINTER_TYPE)
/* Returns true if NODE is an object type:
[basic.types]
An object type is a (possibly cv-qualified) type that is not a
function type, not a reference type, and not a void type.
Keep these checks in ascending order, for speed. */
#define TYPE_OBJ_P(NODE) \
(TREE_CODE (NODE) != REFERENCE_TYPE \
&& !VOID_TYPE_P (NODE) \
&& TREE_CODE (NODE) != FUNCTION_TYPE \
&& TREE_CODE (NODE) != METHOD_TYPE)
/* Returns true if NODE is a pointer to an object. Keep these checks
in ascending tree code order. */
#define TYPE_PTROB_P(NODE) \
(TYPE_PTR_P (NODE) && TYPE_OBJ_P (TREE_TYPE (NODE)))
/* Returns true if NODE is a reference to an object. Keep these checks
in ascending tree code order. */
#define TYPE_REF_OBJ_P(NODE) \
(TREE_CODE (NODE) == REFERENCE_TYPE && TYPE_OBJ_P (TREE_TYPE (NODE)))
/* Returns true if NODE is a pointer to an object, or a pointer to
void. Keep these checks in ascending tree code order. */
#define TYPE_PTROBV_P(NODE) \
(TYPE_PTR_P (NODE) \
&& !(TREE_CODE (TREE_TYPE (NODE)) == FUNCTION_TYPE \
|| TREE_CODE (TREE_TYPE (NODE)) == METHOD_TYPE))
/* Returns true if NODE is a pointer to function type. */
#define TYPE_PTRFN_P(NODE) \
(TYPE_PTR_P (NODE) \
&& TREE_CODE (TREE_TYPE (NODE)) == FUNCTION_TYPE)
/* Returns true if NODE is a reference to function type. */
#define TYPE_REFFN_P(NODE) \
(TREE_CODE (NODE) == REFERENCE_TYPE \
&& TREE_CODE (TREE_TYPE (NODE)) == FUNCTION_TYPE)
/* Returns true if NODE is a pointer to member function type. */
#define TYPE_PTRMEMFUNC_P(NODE) \
(TREE_CODE (NODE) == RECORD_TYPE \
&& TYPE_PTRMEMFUNC_FLAG (NODE))
#define TYPE_PTRMEMFUNC_FLAG(NODE) \
(TYPE_LANG_FLAG_2 (RECORD_TYPE_CHECK (NODE)))
/* Returns true if NODE is a pointer-to-member. */
#define TYPE_PTRMEM_P(NODE) \
(TYPE_PTRDATAMEM_P (NODE) || TYPE_PTRMEMFUNC_P (NODE))
/* Returns true if NODE is a pointer or a pointer-to-member. */
#define TYPE_PTR_OR_PTRMEM_P(NODE) \
(TYPE_PTR_P (NODE) || TYPE_PTRMEM_P (NODE))
/* Indicates when overload resolution may resolve to a pointer to
member function. [expr.unary.op]/3 */
#define PTRMEM_OK_P(NODE) \
TREE_LANG_FLAG_0 (TREE_CHECK3 ((NODE), ADDR_EXPR, OFFSET_REF, SCOPE_REF))
/* Get the POINTER_TYPE to the METHOD_TYPE associated with this
pointer to member function. TYPE_PTRMEMFUNC_P _must_ be true,
before using this macro. */
#define TYPE_PTRMEMFUNC_FN_TYPE(NODE) \
(cp_build_qualified_type (TREE_TYPE (TYPE_FIELDS (NODE)),\
cp_type_quals (NODE)))
/* As above, but can be used in places that want an lvalue at the expense
of not necessarily having the correct cv-qualifiers. */
#define TYPE_PTRMEMFUNC_FN_TYPE_RAW(NODE) \
(TREE_TYPE (TYPE_FIELDS (NODE)))
/* Returns `A' for a type like `int (A::*)(double)' */
#define TYPE_PTRMEMFUNC_OBJECT_TYPE(NODE) \
TYPE_METHOD_BASETYPE (TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (NODE)))
/* These are use to manipulate the canonical RECORD_TYPE from the
hashed POINTER_TYPE, and can only be used on the POINTER_TYPE. */
#define TYPE_GET_PTRMEMFUNC_TYPE(NODE) \
(TYPE_LANG_SPECIFIC (NODE) ? LANG_TYPE_PTRMEM_CHECK (NODE)->record : NULL)
#define TYPE_SET_PTRMEMFUNC_TYPE(NODE, VALUE) \
do { \
if (TYPE_LANG_SPECIFIC (NODE) == NULL) \
{ \
TYPE_LANG_SPECIFIC (NODE) \
= (struct lang_type *) ggc_internal_cleared_alloc \
(sizeof (struct lang_type_ptrmem)); \
TYPE_LANG_SPECIFIC (NODE)->u.ptrmem.h.is_lang_type_class = 0; \
} \
TYPE_LANG_SPECIFIC (NODE)->u.ptrmem.record = (VALUE); \
} while (0)
/* For a pointer-to-member type of the form `T X::*', this is `X'.
For a type like `void (X::*)() const', this type is `X', not `const
X'. To get at the `const X' you have to look at the
TYPE_PTRMEM_POINTED_TO_TYPE; there, the first parameter will have
type `const X*'. */
#define TYPE_PTRMEM_CLASS_TYPE(NODE) \
(TYPE_PTRDATAMEM_P (NODE) \
? TYPE_OFFSET_BASETYPE (NODE) \
: TYPE_PTRMEMFUNC_OBJECT_TYPE (NODE))
/* For a pointer-to-member type of the form `T X::*', this is `T'. */
#define TYPE_PTRMEM_POINTED_TO_TYPE(NODE) \
(TYPE_PTRDATAMEM_P (NODE) \
? TREE_TYPE (NODE) \
: TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (NODE)))
/* For a pointer-to-member constant `X::Y' this is the RECORD_TYPE for
`X'. */
#define PTRMEM_CST_CLASS(NODE) \
TYPE_PTRMEM_CLASS_TYPE (TREE_TYPE (PTRMEM_CST_CHECK (NODE)))
/* For a pointer-to-member constant `X::Y' this is the _DECL for
`Y'. */
#define PTRMEM_CST_MEMBER(NODE) (((ptrmem_cst_t)PTRMEM_CST_CHECK (NODE))->member)
/* The expression in question for a TYPEOF_TYPE. */
#define TYPEOF_TYPE_EXPR(NODE) (TYPE_VALUES_RAW (TYPEOF_TYPE_CHECK (NODE)))
/* The type in question for an UNDERLYING_TYPE. */
#define UNDERLYING_TYPE_TYPE(NODE) \
(TYPE_VALUES_RAW (UNDERLYING_TYPE_CHECK (NODE)))
/* The type in question for BASES. */
#define BASES_TYPE(NODE) \
(TYPE_VALUES_RAW (BASES_CHECK (NODE)))
#define BASES_DIRECT(NODE) \
TREE_LANG_FLAG_0 (BASES_CHECK (NODE))
/* The expression in question for a DECLTYPE_TYPE. */
#define DECLTYPE_TYPE_EXPR(NODE) (TYPE_VALUES_RAW (DECLTYPE_TYPE_CHECK (NODE)))
/* Whether the DECLTYPE_TYPE_EXPR of NODE was originally parsed as an
id-expression or a member-access expression. When false, it was
parsed as a full expression. */
#define DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P(NODE) \
(DECLTYPE_TYPE_CHECK (NODE))->type_common.string_flag
/* These flags indicate that we want different semantics from normal
decltype: lambda capture just drops references, init capture
uses auto semantics, lambda proxies look through implicit dereference. */
#define DECLTYPE_FOR_LAMBDA_CAPTURE(NODE) \
TREE_LANG_FLAG_0 (DECLTYPE_TYPE_CHECK (NODE))
#define DECLTYPE_FOR_INIT_CAPTURE(NODE) \
TREE_LANG_FLAG_1 (DECLTYPE_TYPE_CHECK (NODE))
#define DECLTYPE_FOR_LAMBDA_PROXY(NODE) \
TREE_LANG_FLAG_2 (DECLTYPE_TYPE_CHECK (NODE))
#define DECLTYPE_FOR_REF_CAPTURE(NODE) \
TREE_LANG_FLAG_3 (DECLTYPE_TYPE_CHECK (NODE))
/* Nonzero for VAR_DECL and FUNCTION_DECL node means that `extern' was
specified in its declaration. This can also be set for an
erroneously declared PARM_DECL. */
#define DECL_THIS_EXTERN(NODE) \
DECL_LANG_FLAG_2 (VAR_FUNCTION_OR_PARM_DECL_CHECK (NODE))
/* Nonzero for VAR_DECL and FUNCTION_DECL node means that `static' was
specified in its declaration. This can also be set for an
erroneously declared PARM_DECL. */
#define DECL_THIS_STATIC(NODE) \
DECL_LANG_FLAG_6 (VAR_FUNCTION_OR_PARM_DECL_CHECK (NODE))
/* Nonzero for FIELD_DECL node means that this field is a lambda capture
field for an array of runtime bound. */
#define DECL_VLA_CAPTURE_P(NODE) \
DECL_LANG_FLAG_1 (FIELD_DECL_CHECK (NODE))
/* Nonzero for PARM_DECL node means that this is an array function
parameter, i.e, a[] rather than *a. */
#define DECL_ARRAY_PARAMETER_P(NODE) \
DECL_LANG_FLAG_1 (PARM_DECL_CHECK (NODE))
/* Nonzero for a FIELD_DECL who's NSMDI is currently being
instantiated. */
#define DECL_INSTANTIATING_NSDMI_P(NODE) \
DECL_LANG_FLAG_2 (FIELD_DECL_CHECK (NODE))
/* Nonzero for FIELD_DECL node means that this field is a base class
of the parent object, as opposed to a member field. */
#define DECL_FIELD_IS_BASE(NODE) \
DECL_LANG_FLAG_6 (FIELD_DECL_CHECK (NODE))
/* Nonzero for FIELD_DECL node means that this field is a simple (no
explicit initializer) lambda capture field, making it invisible to
name lookup in unevaluated contexts. */
#define DECL_NORMAL_CAPTURE_P(NODE) \
DECL_LANG_FLAG_7 (FIELD_DECL_CHECK (NODE))
/* Nonzero if TYPE is an anonymous union or struct type. We have to use a
flag for this because "A union for which objects or pointers are
declared is not an anonymous union" [class.union]. */
#define ANON_AGGR_TYPE_P(NODE) \
(CLASS_TYPE_P (NODE) && LANG_TYPE_CLASS_CHECK (NODE)->anon_aggr)
#define SET_ANON_AGGR_TYPE_P(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->anon_aggr = 1)
/* Nonzero if TYPE is an anonymous union type. */
#define ANON_UNION_TYPE_P(NODE) \
(TREE_CODE (NODE) == UNION_TYPE && ANON_AGGR_TYPE_P (NODE))
/* Define fields and accessors for nodes representing declared names. */
/* Nonzero if TYPE is an unnamed class with a typedef for linkage purposes. */
#define TYPE_WAS_UNNAMED(NODE) (LANG_TYPE_CLASS_CHECK (NODE)->was_anonymous)
/* C++: all of these are overloaded! These apply only to TYPE_DECLs. */
/* The format of each node in the DECL_FRIENDLIST is as follows:
The TREE_PURPOSE will be the name of a function, i.e., an
IDENTIFIER_NODE. The TREE_VALUE will be itself a TREE_LIST, whose
TREE_VALUEs are friends with the given name. */
#define DECL_FRIENDLIST(NODE) (DECL_INITIAL (NODE))
#define FRIEND_NAME(LIST) (TREE_PURPOSE (LIST))
#define FRIEND_DECLS(LIST) (TREE_VALUE (LIST))
/* The DECL_ACCESS, if non-NULL, is a TREE_LIST. The TREE_PURPOSE of
each node is a type; the TREE_VALUE is the access granted for this
DECL in that type. The DECL_ACCESS is set by access declarations.
For example, if a member that would normally be public in a
derived class is made protected, then the derived class and the
protected_access_node will appear in the DECL_ACCESS for the node. */
#define DECL_ACCESS(NODE) (LANG_DECL_U2_CHECK (NODE, 0)->access)
/* Nonzero if the FUNCTION_DECL is a global constructor. */
#define DECL_GLOBAL_CTOR_P(NODE) \
(LANG_DECL_FN_CHECK (NODE)->global_ctor_p)
/* Nonzero if the FUNCTION_DECL is a global destructor. */
#define DECL_GLOBAL_DTOR_P(NODE) \
(LANG_DECL_FN_CHECK (NODE)->global_dtor_p)
/* Accessor macros for C++ template decl nodes. */
/* The DECL_TEMPLATE_PARMS are a list. The TREE_PURPOSE of each node
is a INT_CST whose TREE_INT_CST_LOW indicates the level of the
template parameters, with 1 being the outermost set of template
parameters. The TREE_VALUE is a vector, whose elements are the
template parameters at each level. Each element in the vector is a
TREE_LIST, whose TREE_VALUE is a PARM_DECL (if the parameter is a
non-type parameter), or a TYPE_DECL (if the parameter is a type
parameter). The TREE_PURPOSE is the default value, if any. The
TEMPLATE_PARM_INDEX for the parameter is available as the
DECL_INITIAL (for a PARM_DECL) or as the TREE_TYPE (for a
TYPE_DECL).
FIXME: CONST_CAST_TREE is a hack that hopefully will go away after
tree is converted to C++ class hiearchy. */
#define DECL_TEMPLATE_PARMS(NODE) \
((struct tree_template_decl *)CONST_CAST_TREE (TEMPLATE_DECL_CHECK (NODE)))->arguments
#define DECL_INNERMOST_TEMPLATE_PARMS(NODE) \
INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (NODE))
#define DECL_NTPARMS(NODE) \
TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (NODE))
/* For function, method, class-data templates.
FIXME: CONST_CAST_TREE is a hack that hopefully will go away after
tree is converted to C++ class hiearchy. */
#define DECL_TEMPLATE_RESULT(NODE) \
((struct tree_template_decl *)CONST_CAST_TREE(TEMPLATE_DECL_CHECK (NODE)))->result
/* For a function template at namespace scope, DECL_TEMPLATE_INSTANTIATIONS
lists all instantiations and specializations of the function so that
tsubst_friend_function can reassign them to another template if we find
that the namespace-scope template is really a partial instantiation of a
friend template.
For a class template the DECL_TEMPLATE_INSTANTIATIONS lists holds
all instantiations and specializations of the class type, including
partial instantiations and partial specializations, so that if we
explicitly specialize a partial instantiation we can walk the list
in maybe_process_partial_specialization and reassign them or complain
as appropriate.
In both cases, the TREE_PURPOSE of each node contains the arguments
used; the TREE_VALUE contains the generated variable. The template
arguments are always complete. For example, given:
template <class T> struct S1 {
template <class U> struct S2 {};
template <class U> struct S2<U*> {};
};
the record for the partial specialization will contain, as its
argument list, { {T}, {U*} }, and will be on the
DECL_TEMPLATE_INSTANTIATIONS list for `template <class T> template
<class U> struct S1<T>::S2'.
This list is not used for other templates. */
#define DECL_TEMPLATE_INSTANTIATIONS(NODE) \
DECL_SIZE_UNIT (TEMPLATE_DECL_CHECK (NODE))
/* For a class template, this list contains the partial
specializations of this template. (Full specializations are not
recorded on this list.) The TREE_PURPOSE holds the arguments used
in the partial specialization (e.g., for `template <class T> struct
S<T*, int>' this will be `T*, int'.) The arguments will also include
any outer template arguments. The TREE_VALUE holds the TEMPLATE_DECL
for the partial specialization. The TREE_TYPE is the _TYPE node for
the partial specialization.
This list is not used for other templates. */
#define DECL_TEMPLATE_SPECIALIZATIONS(NODE) \
DECL_SIZE (TEMPLATE_DECL_CHECK (NODE))
/* Nonzero for a DECL which is actually a template parameter. Keep
these checks in ascending tree code order. */
#define DECL_TEMPLATE_PARM_P(NODE) \
(DECL_LANG_FLAG_0 (NODE) \
&& (TREE_CODE (NODE) == CONST_DECL \
|| TREE_CODE (NODE) == PARM_DECL \
|| TREE_CODE (NODE) == TYPE_DECL \
|| TREE_CODE (NODE) == TEMPLATE_DECL))
/* Mark NODE as a template parameter. */
#define SET_DECL_TEMPLATE_PARM_P(NODE) \
(DECL_LANG_FLAG_0 (NODE) = 1)
/* Nonzero if NODE is a template template parameter. */
#define DECL_TEMPLATE_TEMPLATE_PARM_P(NODE) \
(TREE_CODE (NODE) == TEMPLATE_DECL && DECL_TEMPLATE_PARM_P (NODE))
/* Nonzero for a DECL that represents a function template. */
#define DECL_FUNCTION_TEMPLATE_P(NODE) \
(TREE_CODE (NODE) == TEMPLATE_DECL \
&& DECL_TEMPLATE_RESULT (NODE) != NULL_TREE \
&& TREE_CODE (DECL_TEMPLATE_RESULT (NODE)) == FUNCTION_DECL)
/* Nonzero for a DECL that represents a class template or alias
template. */
#define DECL_TYPE_TEMPLATE_P(NODE) \
(TREE_CODE (NODE) == TEMPLATE_DECL \
&& DECL_TEMPLATE_RESULT (NODE) != NULL_TREE \
&& TREE_CODE (DECL_TEMPLATE_RESULT (NODE)) == TYPE_DECL)
/* Nonzero for a DECL that represents a class template. */
#define DECL_CLASS_TEMPLATE_P(NODE) \
(DECL_TYPE_TEMPLATE_P (NODE) \
&& DECL_IMPLICIT_TYPEDEF_P (DECL_TEMPLATE_RESULT (NODE)))
/* Nonzero for a TEMPLATE_DECL that represents an alias template. */
#define DECL_ALIAS_TEMPLATE_P(NODE) \
(DECL_TYPE_TEMPLATE_P (NODE) \
&& !DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (NODE)))
/* Nonzero for a NODE which declares a type. */
#define DECL_DECLARES_TYPE_P(NODE) \
(TREE_CODE (NODE) == TYPE_DECL || DECL_TYPE_TEMPLATE_P (NODE))
/* Nonzero if NODE declares a function. */
#define DECL_DECLARES_FUNCTION_P(NODE) \
(TREE_CODE (NODE) == FUNCTION_DECL || DECL_FUNCTION_TEMPLATE_P (NODE))
/* Nonzero if NODE is the typedef implicitly generated for a type when
the type is declared. In C++, `struct S {};' is roughly
equivalent to `struct S {}; typedef struct S S;' in C.
DECL_IMPLICIT_TYPEDEF_P will hold for the typedef indicated in this
example. In C++, there is a second implicit typedef for each
class, called the injected-class-name, in the scope of `S' itself, so that
you can say `S::S'. DECL_SELF_REFERENCE_P will hold for that typedef. */
#define DECL_IMPLICIT_TYPEDEF_P(NODE) \
(TREE_CODE (NODE) == TYPE_DECL && DECL_LANG_FLAG_2 (NODE))
#define SET_DECL_IMPLICIT_TYPEDEF_P(NODE) \
(DECL_LANG_FLAG_2 (NODE) = 1)
#define DECL_SELF_REFERENCE_P(NODE) \
(TREE_CODE (NODE) == TYPE_DECL && DECL_LANG_FLAG_4 (NODE))
#define SET_DECL_SELF_REFERENCE_P(NODE) \
(DECL_LANG_FLAG_4 (NODE) = 1)
/* A `primary' template is one that has its own template header and is not
a partial specialization. A member function of a class template is a
template, but not primary. A member template is primary. Friend
templates are primary, too. */
/* Returns the primary template corresponding to these parameters. */
#define DECL_PRIMARY_TEMPLATE(NODE) \
(TREE_TYPE (DECL_INNERMOST_TEMPLATE_PARMS (NODE)))
/* Returns nonzero if NODE is a primary template. */
#define PRIMARY_TEMPLATE_P(NODE) (DECL_PRIMARY_TEMPLATE (NODE) == (NODE))
/* Nonzero iff NODE is a specialization of a template. The value
indicates the type of specializations:
1=implicit instantiation
2=partial or explicit specialization, e.g.:
template <> int min<int> (int, int),
3=explicit instantiation, e.g.:
template int min<int> (int, int);
Note that NODE will be marked as a specialization even if the
template it is instantiating is not a primary template. For
example, given:
template <typename T> struct O {
void f();
struct I {};
};
both O<int>::f and O<int>::I will be marked as instantiations.
If DECL_USE_TEMPLATE is nonzero, then DECL_TEMPLATE_INFO will also
be non-NULL. */
#define DECL_USE_TEMPLATE(NODE) (DECL_LANG_SPECIFIC (NODE)->u.base.use_template)
/* Like DECL_USE_TEMPLATE, but for class types. */
#define CLASSTYPE_USE_TEMPLATE(NODE) \
(LANG_TYPE_CLASS_CHECK (NODE)->use_template)
/* True if NODE is a specialization of a primary template. */
#define CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P(NODE) \
(CLASS_TYPE_P (NODE) \
&& CLASSTYPE_USE_TEMPLATE (NODE) \
&& PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (NODE)))
#define DECL_TEMPLATE_INSTANTIATION(NODE) (DECL_USE_TEMPLATE (NODE) & 1)
#define CLASSTYPE_TEMPLATE_INSTANTIATION(NODE) \
(CLASSTYPE_USE_TEMPLATE (NODE) & 1)
#define DECL_TEMPLATE_SPECIALIZATION(NODE) (DECL_USE_TEMPLATE (NODE) == 2)
#define SET_DECL_TEMPLATE_SPECIALIZATION(NODE) (DECL_USE_TEMPLATE (NODE) = 2)
/* Returns true for an explicit or partial specialization of a class
template. */
#define CLASSTYPE_TEMPLATE_SPECIALIZATION(NODE) \
(CLASSTYPE_USE_TEMPLATE (NODE) == 2)
#define SET_CLASSTYPE_TEMPLATE_SPECIALIZATION(NODE) \
(CLASSTYPE_USE_TEMPLATE (NODE) = 2)
#define DECL_IMPLICIT_INSTANTIATION(NODE) (DECL_USE_TEMPLATE (NODE) == 1)
#define SET_DECL_IMPLICIT_INSTANTIATION(NODE) (DECL_USE_TEMPLATE (NODE) = 1)
#define CLASSTYPE_IMPLICIT_INSTANTIATION(NODE) \
(CLASSTYPE_USE_TEMPLATE (NODE) == 1)
#define SET_CLASSTYPE_IMPLICIT_INSTANTIATION(NODE) \
(CLASSTYPE_USE_TEMPLATE (NODE) = 1)
#define DECL_EXPLICIT_INSTANTIATION(NODE) (DECL_USE_TEMPLATE (NODE) == 3)
#define SET_DECL_EXPLICIT_INSTANTIATION(NODE) (DECL_USE_TEMPLATE (NODE) = 3)
#define CLASSTYPE_EXPLICIT_INSTANTIATION(NODE) \
(CLASSTYPE_USE_TEMPLATE (NODE) == 3)
#define SET_CLASSTYPE_EXPLICIT_INSTANTIATION(NODE) \
(CLASSTYPE_USE_TEMPLATE (NODE) = 3)
/* Nonzero if DECL is a friend function which is an instantiation
from the point of view of the compiler, but not from the point of
view of the language. For example given:
template <class T> struct S { friend void f(T) {}; };
the declaration of `void f(int)' generated when S<int> is
instantiated will not be a DECL_TEMPLATE_INSTANTIATION, but will be
a DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION. */
#define DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION(DECL) \
(DECL_LANG_SPECIFIC (DECL) && DECL_TEMPLATE_INFO (DECL) \
&& !DECL_USE_TEMPLATE (DECL))
/* Nonzero if DECL is a function generated from a function 'temploid',
i.e. template, member of class template, or dependent friend. */
#define DECL_TEMPLOID_INSTANTIATION(DECL) \
(DECL_TEMPLATE_INSTANTIATION (DECL) \
|| DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (DECL))
/* Nonzero if DECL is either defined implicitly by the compiler or
generated from a temploid. */
#define DECL_GENERATED_P(DECL) \
(DECL_TEMPLOID_INSTANTIATION (DECL) || DECL_DEFAULTED_FN (DECL))
/* Nonzero iff we are currently processing a declaration for an
entity with its own template parameter list, and which is not a
full specialization. */
#define PROCESSING_REAL_TEMPLATE_DECL_P() \
(processing_template_decl > template_class_depth (current_scope ()))
/* Nonzero if this VAR_DECL or FUNCTION_DECL has already been
instantiated, i.e. its definition has been generated from the
pattern given in the template. */
#define DECL_TEMPLATE_INSTANTIATED(NODE) \
DECL_LANG_FLAG_1 (VAR_OR_FUNCTION_DECL_CHECK (NODE))
/* We know what we're doing with this decl now. */
#define DECL_INTERFACE_KNOWN(NODE) DECL_LANG_FLAG_5 (NODE)
/* DECL_EXTERNAL must be set on a decl until the decl is actually emitted,
so that assemble_external will work properly. So we have this flag to
tell us whether the decl is really not external.
This flag does not indicate whether or not the decl is defined in the
current translation unit; it indicates whether or not we should emit the
decl at the end of compilation if it is defined and needed. */
#define DECL_NOT_REALLY_EXTERN(NODE) \
(DECL_LANG_SPECIFIC (NODE)->u.base.not_really_extern)
#define DECL_REALLY_EXTERN(NODE) \
(DECL_EXTERNAL (NODE) \
&& (!DECL_LANG_SPECIFIC (NODE) || !DECL_NOT_REALLY_EXTERN (NODE)))
/* A thunk is a stub function.
A thunk is an alternate entry point for an ordinary FUNCTION_DECL.
The address of the ordinary FUNCTION_DECL is given by the
DECL_INITIAL, which is always an ADDR_EXPR whose operand is a
FUNCTION_DECL. The job of the thunk is to either adjust the this
pointer before transferring control to the FUNCTION_DECL, or call
FUNCTION_DECL and then adjust the result value. Note, the result
pointer adjusting thunk must perform a call to the thunked
function, (or be implemented via passing some invisible parameter
to the thunked function, which is modified to perform the
adjustment just before returning).
A thunk may perform either, or both, of the following operations:
o Adjust the this or result pointer by a constant offset.
o Adjust the this or result pointer by looking up a vcall or vbase offset
in the vtable.
A this pointer adjusting thunk converts from a base to a derived
class, and hence adds the offsets. A result pointer adjusting thunk
converts from a derived class to a base, and hence subtracts the
offsets. If both operations are performed, then the constant
adjustment is performed first for this pointer adjustment and last
for the result pointer adjustment.
The constant adjustment is given by THUNK_FIXED_OFFSET. If the
vcall or vbase offset is required, THUNK_VIRTUAL_OFFSET is
used. For this pointer adjusting thunks, it is the vcall offset
into the vtable. For result pointer adjusting thunks it is the
binfo of the virtual base to convert to. Use that binfo's vbase
offset.
It is possible to have equivalent covariant thunks. These are
distinct virtual covariant thunks whose vbase offsets happen to
have the same value. THUNK_ALIAS is used to pick one as the
canonical thunk, which will get all the this pointer adjusting
thunks attached to it. */
/* An integer indicating how many bytes should be subtracted from the
this or result pointer when this function is called. */
#define THUNK_FIXED_OFFSET(DECL) \
(DECL_LANG_SPECIFIC (THUNK_FUNCTION_CHECK (DECL))->u.fn.u5.fixed_offset)
/* A tree indicating how to perform the virtual adjustment. For a this
adjusting thunk it is the number of bytes to be added to the vtable
to find the vcall offset. For a result adjusting thunk, it is the
binfo of the relevant virtual base. If NULL, then there is no
virtual adjust. (The vptr is always located at offset zero from
the this or result pointer.) (If the covariant type is within the
class hierarchy being laid out, the vbase index is not yet known
at the point we need to create the thunks, hence the need to use
binfos.) */
#define THUNK_VIRTUAL_OFFSET(DECL) \
(LANG_DECL_U2_CHECK (FUNCTION_DECL_CHECK (DECL), 0)->access)
/* A thunk which is equivalent to another thunk. */
#define THUNK_ALIAS(DECL) \
(DECL_LANG_SPECIFIC (FUNCTION_DECL_CHECK (DECL))->u.min.template_info)
/* For thunk NODE, this is the FUNCTION_DECL thunked to. It is
possible for the target to be a thunk too. */
#define THUNK_TARGET(NODE) \
(LANG_DECL_FN_CHECK (NODE)->befriending_classes)
/* True for a SCOPE_REF iff the "template" keyword was used to
indicate that the qualified name denotes a template. */
#define QUALIFIED_NAME_IS_TEMPLATE(NODE) \
(TREE_LANG_FLAG_1 (SCOPE_REF_CHECK (NODE)))
/* True for an OMP_ATOMIC that has dependent parameters. These are stored
as an expr in operand 1, and integer_zero_node in operand 0. */
#define OMP_ATOMIC_DEPENDENT_P(NODE) \
(TREE_CODE (TREE_OPERAND (OMP_ATOMIC_CHECK (NODE), 0)) == INTEGER_CST)
/* Used while gimplifying continue statements bound to OMP_FOR nodes. */
#define OMP_FOR_GIMPLIFYING_P(NODE) \
(TREE_LANG_FLAG_0 (OMP_LOOP_CHECK (NODE)))
/* A language-specific token attached to the OpenMP data clauses to
hold code (or code fragments) related to ctors, dtors, and op=.
See semantics.c for details. */
#define CP_OMP_CLAUSE_INFO(NODE) \
TREE_TYPE (OMP_CLAUSE_RANGE_CHECK (NODE, OMP_CLAUSE_PRIVATE, \
OMP_CLAUSE_LINEAR))
/* Nonzero if this transaction expression's body contains statements. */
#define TRANSACTION_EXPR_IS_STMT(NODE) \
TREE_LANG_FLAG_0 (TRANSACTION_EXPR_CHECK (NODE))
/* These macros provide convenient access to the various _STMT nodes
created when parsing template declarations. */
#define TRY_STMTS(NODE) TREE_OPERAND (TRY_BLOCK_CHECK (NODE), 0)
#define TRY_HANDLERS(NODE) TREE_OPERAND (TRY_BLOCK_CHECK (NODE), 1)
#define EH_SPEC_STMTS(NODE) TREE_OPERAND (EH_SPEC_BLOCK_CHECK (NODE), 0)
#define EH_SPEC_RAISES(NODE) TREE_OPERAND (EH_SPEC_BLOCK_CHECK (NODE), 1)
#define USING_STMT_NAMESPACE(NODE) TREE_OPERAND (USING_STMT_CHECK (NODE), 0)
/* Nonzero if this try block is a function try block. */
#define FN_TRY_BLOCK_P(NODE) TREE_LANG_FLAG_3 (TRY_BLOCK_CHECK (NODE))
#define HANDLER_PARMS(NODE) TREE_OPERAND (HANDLER_CHECK (NODE), 0)
#define HANDLER_BODY(NODE) TREE_OPERAND (HANDLER_CHECK (NODE), 1)
#define HANDLER_TYPE(NODE) TREE_TYPE (HANDLER_CHECK (NODE))
/* CLEANUP_STMT accessors. The statement(s) covered, the cleanup to run
and the VAR_DECL for which this cleanup exists. */
#define CLEANUP_BODY(NODE) TREE_OPERAND (CLEANUP_STMT_CHECK (NODE), 0)
#define CLEANUP_EXPR(NODE) TREE_OPERAND (CLEANUP_STMT_CHECK (NODE), 1)
#define CLEANUP_DECL(NODE) TREE_OPERAND (CLEANUP_STMT_CHECK (NODE), 2)
/* IF_STMT accessors. These give access to the condition of the if
statement, the then block of the if statement, and the else block
of the if statement if it exists. */
#define IF_COND(NODE) TREE_OPERAND (IF_STMT_CHECK (NODE), 0)
#define THEN_CLAUSE(NODE) TREE_OPERAND (IF_STMT_CHECK (NODE), 1)
#define ELSE_CLAUSE(NODE) TREE_OPERAND (IF_STMT_CHECK (NODE), 2)
#define IF_SCOPE(NODE) TREE_OPERAND (IF_STMT_CHECK (NODE), 3)
#define IF_STMT_CONSTEXPR_P(NODE) TREE_LANG_FLAG_0 (IF_STMT_CHECK (NODE))
/* WHILE_STMT accessors. These give access to the condition of the
while statement and the body of the while statement, respectively. */
#define WHILE_COND(NODE) TREE_OPERAND (WHILE_STMT_CHECK (NODE), 0)
#define WHILE_BODY(NODE) TREE_OPERAND (WHILE_STMT_CHECK (NODE), 1)
/* DO_STMT accessors. These give access to the condition of the do
statement and the body of the do statement, respectively. */
#define DO_COND(NODE) TREE_OPERAND (DO_STMT_CHECK (NODE), 0)
#define DO_BODY(NODE) TREE_OPERAND (DO_STMT_CHECK (NODE), 1)
/* FOR_STMT accessors. These give access to the init statement,
condition, update expression, and body of the for statement,
respectively. */
#define FOR_INIT_STMT(NODE) TREE_OPERAND (FOR_STMT_CHECK (NODE), 0)
#define FOR_COND(NODE) TREE_OPERAND (FOR_STMT_CHECK (NODE), 1)
#define FOR_EXPR(NODE) TREE_OPERAND (FOR_STMT_CHECK (NODE), 2)
#define FOR_BODY(NODE) TREE_OPERAND (FOR_STMT_CHECK (NODE), 3)
#define FOR_SCOPE(NODE) TREE_OPERAND (FOR_STMT_CHECK (NODE), 4)
/* RANGE_FOR_STMT accessors. These give access to the declarator,
expression, body, and scope of the statement, respectively. */
#define RANGE_FOR_DECL(NODE) TREE_OPERAND (RANGE_FOR_STMT_CHECK (NODE), 0)
#define RANGE_FOR_EXPR(NODE) TREE_OPERAND (RANGE_FOR_STMT_CHECK (NODE), 1)
#define RANGE_FOR_BODY(NODE) TREE_OPERAND (RANGE_FOR_STMT_CHECK (NODE), 2)
#define RANGE_FOR_SCOPE(NODE) TREE_OPERAND (RANGE_FOR_STMT_CHECK (NODE), 3)
#define RANGE_FOR_IVDEP(NODE) TREE_LANG_FLAG_6 (RANGE_FOR_STMT_CHECK (NODE))
#define SWITCH_STMT_COND(NODE) TREE_OPERAND (SWITCH_STMT_CHECK (NODE), 0)
#define SWITCH_STMT_BODY(NODE) TREE_OPERAND (SWITCH_STMT_CHECK (NODE), 1)
#define SWITCH_STMT_TYPE(NODE) TREE_OPERAND (SWITCH_STMT_CHECK (NODE), 2)
#define SWITCH_STMT_SCOPE(NODE) TREE_OPERAND (SWITCH_STMT_CHECK (NODE), 3)
/* STMT_EXPR accessor. */
#define STMT_EXPR_STMT(NODE) TREE_OPERAND (STMT_EXPR_CHECK (NODE), 0)
/* EXPR_STMT accessor. This gives the expression associated with an
expression statement. */
#define EXPR_STMT_EXPR(NODE) TREE_OPERAND (EXPR_STMT_CHECK (NODE), 0)
/* True if this TARGET_EXPR was created by build_cplus_new, and so we can
discard it if it isn't useful. */
#define TARGET_EXPR_IMPLICIT_P(NODE) \
TREE_LANG_FLAG_0 (TARGET_EXPR_CHECK (NODE))
/* True if this TARGET_EXPR is the result of list-initialization of a
temporary. */
#define TARGET_EXPR_LIST_INIT_P(NODE) \
TREE_LANG_FLAG_1 (TARGET_EXPR_CHECK (NODE))
/* True if this TARGET_EXPR expresses direct-initialization of an object
to be named later. */
#define TARGET_EXPR_DIRECT_INIT_P(NODE) \
TREE_LANG_FLAG_2 (TARGET_EXPR_CHECK (NODE))
/* True if NODE is a TARGET_EXPR that just expresses a copy of its INITIAL; if
the initializer has void type, it's doing something more complicated. */
#define SIMPLE_TARGET_EXPR_P(NODE) \
(TREE_CODE (NODE) == TARGET_EXPR \
&& !VOID_TYPE_P (TREE_TYPE (TARGET_EXPR_INITIAL (NODE))))
/* True if EXPR expresses direct-initialization of a TYPE. */
#define DIRECT_INIT_EXPR_P(TYPE,EXPR) \
(TREE_CODE (EXPR) == TARGET_EXPR && TREE_LANG_FLAG_2 (EXPR) \
&& same_type_ignoring_top_level_qualifiers_p (TYPE, TREE_TYPE (EXPR)))
/* True if this CONVERT_EXPR is for a conversion to virtual base in
an NSDMI, and should be re-evaluated when used in a constructor. */
#define CONVERT_EXPR_VBASE_PATH(NODE) \
TREE_LANG_FLAG_0 (CONVERT_EXPR_CHECK (NODE))
/* True if SIZEOF_EXPR argument is type. */
#define SIZEOF_EXPR_TYPE_P(NODE) \
TREE_LANG_FLAG_0 (SIZEOF_EXPR_CHECK (NODE))
/* An enumeration of the kind of tags that C++ accepts. */
enum tag_types {
none_type = 0, /* Not a tag type. */
record_type, /* "struct" types. */
class_type, /* "class" types. */
union_type, /* "union" types. */
enum_type, /* "enum" types. */
typename_type, /* "typename" types. */
scope_type /* namespace or tagged type name followed by :: */
};
/* The various kinds of lvalues we distinguish. */
enum cp_lvalue_kind_flags {
clk_none = 0, /* Things that are not an lvalue. */
clk_ordinary = 1, /* An ordinary lvalue. */
clk_rvalueref = 2,/* An xvalue (rvalue formed using an rvalue reference) */
clk_class = 4, /* A prvalue of class or array type. */
clk_bitfield = 8, /* An lvalue for a bit-field. */
clk_packed = 16 /* An lvalue for a packed field. */
};
/* This type is used for parameters and variables which hold
combinations of the flags in enum cp_lvalue_kind_flags. */
typedef int cp_lvalue_kind;
/* Various kinds of template specialization, instantiation, etc. */
enum tmpl_spec_kind {
tsk_none, /* Not a template at all. */
tsk_invalid_member_spec, /* An explicit member template
specialization, but the enclosing
classes have not all been explicitly
specialized. */
tsk_invalid_expl_inst, /* An explicit instantiation containing
template parameter lists. */
tsk_excessive_parms, /* A template declaration with too many
template parameter lists. */
tsk_insufficient_parms, /* A template declaration with too few
parameter lists. */
tsk_template, /* A template declaration. */
tsk_expl_spec, /* An explicit specialization. */
tsk_expl_inst /* An explicit instantiation. */
};
/* The various kinds of access. BINFO_ACCESS depends on these being
two bit quantities. The numerical values are important; they are
used to initialize RTTI data structures, so changing them changes
the ABI. */
enum access_kind {
ak_none = 0, /* Inaccessible. */
ak_public = 1, /* Accessible, as a `public' thing. */
ak_protected = 2, /* Accessible, as a `protected' thing. */
ak_private = 3 /* Accessible, as a `private' thing. */
};
/* The various kinds of special functions. If you add to this list,
you should update special_function_p as well. */
enum special_function_kind {
sfk_none = 0, /* Not a special function. This enumeral
must have value zero; see
special_function_p. */
sfk_constructor, /* A constructor. */
sfk_copy_constructor, /* A copy constructor. */
sfk_move_constructor, /* A move constructor. */
sfk_copy_assignment, /* A copy assignment operator. */
sfk_move_assignment, /* A move assignment operator. */
sfk_destructor, /* A destructor. */
sfk_complete_destructor, /* A destructor for complete objects. */
sfk_base_destructor, /* A destructor for base subobjects. */
sfk_deleting_destructor, /* A destructor for complete objects that
deletes the object after it has been
destroyed. */
sfk_conversion, /* A conversion operator. */
sfk_deduction_guide, /* A class template deduction guide. */
sfk_inheriting_constructor /* An inheriting constructor */
};
/* The various kinds of linkage. From [basic.link],
A name is said to have linkage when it might denote the same
object, reference, function, type, template, namespace or value
as a name introduced in another scope:
-- When a name has external linkage, the entity it denotes can
be referred to from scopes of other translation units or from
other scopes of the same translation unit.
-- When a name has internal linkage, the entity it denotes can
be referred to by names from other scopes in the same
translation unit.
-- When a name has no linkage, the entity it denotes cannot be
referred to by names from other scopes. */
enum linkage_kind {
lk_none, /* No linkage. */
lk_internal, /* Internal linkage. */
lk_external /* External linkage. */
};
enum duration_kind {
dk_static,
dk_thread,
dk_auto,
dk_dynamic
};
/* Bitmask flags to control type substitution. */
enum tsubst_flags {
tf_none = 0, /* nothing special */
tf_error = 1 << 0, /* give error messages */
tf_warning = 1 << 1, /* give warnings too */
tf_ignore_bad_quals = 1 << 2, /* ignore bad cvr qualifiers */
tf_keep_type_decl = 1 << 3, /* retain typedef type decls
(make_typename_type use) */
tf_ptrmem_ok = 1 << 4, /* pointers to member ok (internal
instantiate_type use) */
tf_user = 1 << 5, /* found template must be a user template
(lookup_template_class use) */
tf_conv = 1 << 6, /* We are determining what kind of
conversion might be permissible,
not actually performing the
conversion. */
tf_decltype = 1 << 7, /* We are the operand of decltype.
Used to implement the special rules
for calls in decltype (5.2.2/11). */
tf_partial = 1 << 8, /* Doing initial explicit argument
substitution in fn_type_unification. */
tf_fndecl_type = 1 << 9, /* Substituting the type of a function
declaration. */
tf_no_cleanup = 1 << 10, /* Do not build a cleanup
(build_target_expr and friends) */
/* Convenient substitution flags combinations. */
tf_warning_or_error = tf_warning | tf_error
};
/* This type is used for parameters and variables which hold
combinations of the flags in enum tsubst_flags. */
typedef int tsubst_flags_t;
/* The kind of checking we can do looking in a class hierarchy. */
enum base_access_flags {
ba_any = 0, /* Do not check access, allow an ambiguous base,
prefer a non-virtual base */
ba_unique = 1 << 0, /* Must be a unique base. */
ba_check_bit = 1 << 1, /* Check access. */
ba_check = ba_unique | ba_check_bit,
ba_ignore_scope = 1 << 2 /* Ignore access allowed by local scope. */
};
/* This type is used for parameters and variables which hold
combinations of the flags in enum base_access_flags. */
typedef int base_access;
/* The various kinds of access check during parsing. */
enum deferring_kind {
dk_no_deferred = 0, /* Check access immediately */
dk_deferred = 1, /* Deferred check */
dk_no_check = 2 /* No access check */
};
/* The kind of base we can find, looking in a class hierarchy.
Values <0 indicate we failed. */
enum base_kind {
bk_inaccessible = -3, /* The base is inaccessible */
bk_ambig = -2, /* The base is ambiguous */
bk_not_base = -1, /* It is not a base */
bk_same_type = 0, /* It is the same type */
bk_proper_base = 1, /* It is a proper base */
bk_via_virtual = 2 /* It is a proper base, but via a virtual
path. This might not be the canonical
binfo. */
};
/* Node for "pointer to (virtual) function".
This may be distinct from ptr_type_node so gdb can distinguish them. */
#define vfunc_ptr_type_node vtable_entry_type
/* For building calls to `delete'. */
extern GTY(()) tree integer_two_node;
/* The number of function bodies which we are currently processing.
(Zero if we are at namespace scope, one inside the body of a
function, two inside the body of a function in a local class, etc.) */
extern int function_depth;
/* Nonzero if we are inside eq_specializations, which affects comparison of
PARM_DECLs in cp_tree_equal. */
extern int comparing_specializations;
/* In parser.c. */
/* Nonzero if we are parsing an unevaluated operand: an operand to
sizeof, typeof, or alignof. This is a count since operands to
sizeof can be nested. */
extern int cp_unevaluated_operand;
/* RAII class used to inhibit the evaluation of operands during parsing
and template instantiation. Evaluation warnings are also inhibited. */
struct cp_unevaluated
{
cp_unevaluated ();
~cp_unevaluated ();
};
/* in pt.c */
/* These values are used for the `STRICT' parameter to type_unification and
fn_type_unification. Their meanings are described with the
documentation for fn_type_unification. */
enum unification_kind_t {
DEDUCE_CALL,
DEDUCE_CONV,
DEDUCE_EXACT
};
// An RAII class used to create a new pointer map for local
// specializations. When the stack goes out of scope, the
// previous pointer map is restored.
struct local_specialization_stack
{
local_specialization_stack ();
~local_specialization_stack ();
hash_map<tree, tree> *saved;
};
/* in class.c */
extern int current_class_depth;
/* An array of all local classes present in this translation unit, in
declaration order. */
extern GTY(()) vec<tree, va_gc> *local_classes;
/* Here's where we control how name mangling takes place. */
/* Cannot use '$' up front, because this confuses gdb
(names beginning with '$' are gdb-local identifiers).
Note that all forms in which the '$' is significant are long enough
for direct indexing (meaning that if we know there is a '$'
at a particular location, we can index into the string at
any other location that provides distinguishing characters). */
/* Define NO_DOT_IN_LABEL in your favorite tm file if your assembler
doesn't allow '.' in symbol names. */
#ifndef NO_DOT_IN_LABEL
#define JOINER '.'
#define AUTO_TEMP_NAME "_.tmp_"
#define VFIELD_BASE ".vf"
#define VFIELD_NAME "_vptr."
#define VFIELD_NAME_FORMAT "_vptr.%s"
#else /* NO_DOT_IN_LABEL */
#ifndef NO_DOLLAR_IN_LABEL
#define JOINER '$'
#define AUTO_TEMP_NAME "_$tmp_"
#define VFIELD_BASE "$vf"
#define VFIELD_NAME "_vptr$"
#define VFIELD_NAME_FORMAT "_vptr$%s"
#else /* NO_DOLLAR_IN_LABEL */
#define AUTO_TEMP_NAME "__tmp_"
#define TEMP_NAME_P(ID_NODE) \
(!strncmp (IDENTIFIER_POINTER (ID_NODE), AUTO_TEMP_NAME, \
sizeof (AUTO_TEMP_NAME) - 1))
#define VTABLE_NAME "__vt_"
#define VTABLE_NAME_P(ID_NODE) \
(!strncmp (IDENTIFIER_POINTER (ID_NODE), VTABLE_NAME, \
sizeof (VTABLE_NAME) - 1))
#define VFIELD_BASE "__vfb"
#define VFIELD_NAME "__vptr_"
#define VFIELD_NAME_P(ID_NODE) \
(!strncmp (IDENTIFIER_POINTER (ID_NODE), VFIELD_NAME, \
sizeof (VFIELD_NAME) - 1))
#define VFIELD_NAME_FORMAT "__vptr_%s"
#endif /* NO_DOLLAR_IN_LABEL */
#endif /* NO_DOT_IN_LABEL */
#define THIS_NAME "this"
#define IN_CHARGE_NAME "__in_chrg"
#define VTBL_PTR_TYPE "__vtbl_ptr_type"
#define VTABLE_DELTA_NAME "__delta"
#define VTABLE_PFN_NAME "__pfn"
#define LAMBDANAME_PREFIX "__lambda"
#define LAMBDANAME_FORMAT LAMBDANAME_PREFIX "%d"
#define UDLIT_OP_ANSI_PREFIX "operator\"\""
#define UDLIT_OP_ANSI_FORMAT UDLIT_OP_ANSI_PREFIX "%s"
#define UDLIT_OP_MANGLED_PREFIX "li"
#define UDLIT_OP_MANGLED_FORMAT UDLIT_OP_MANGLED_PREFIX "%s"
#define UDLIT_OPER_P(ID_NODE) \
(!strncmp (IDENTIFIER_POINTER (ID_NODE), \
UDLIT_OP_ANSI_PREFIX, \
sizeof (UDLIT_OP_ANSI_PREFIX) - 1))
#define UDLIT_OP_SUFFIX(ID_NODE) \
(IDENTIFIER_POINTER (ID_NODE) + sizeof (UDLIT_OP_ANSI_PREFIX) - 1)
#if !defined(NO_DOLLAR_IN_LABEL) || !defined(NO_DOT_IN_LABEL)
#define VTABLE_NAME_P(ID_NODE) (IDENTIFIER_POINTER (ID_NODE)[1] == 'v' \
&& IDENTIFIER_POINTER (ID_NODE)[2] == 't' \
&& IDENTIFIER_POINTER (ID_NODE)[3] == JOINER)
#define TEMP_NAME_P(ID_NODE) \
(!strncmp (IDENTIFIER_POINTER (ID_NODE), AUTO_TEMP_NAME, sizeof (AUTO_TEMP_NAME)-1))
#define VFIELD_NAME_P(ID_NODE) \
(!strncmp (IDENTIFIER_POINTER (ID_NODE), VFIELD_NAME, sizeof(VFIELD_NAME)-1))
#endif /* !defined(NO_DOLLAR_IN_LABEL) || !defined(NO_DOT_IN_LABEL) */
/* Nonzero if we're done parsing and into end-of-file activities.
Two if we're done with front-end processing. */
extern int at_eof;
/* True if note_mangling_alias should enqueue mangling aliases for
later generation, rather than emitting them right away. */
extern bool defer_mangling_aliases;
/* True if noexcept is part of the type (i.e. in C++17). */
extern bool flag_noexcept_type;
/* A list of namespace-scope objects which have constructors or
destructors which reside in the global scope. The decl is stored
in the TREE_VALUE slot and the initializer is stored in the
TREE_PURPOSE slot. */
extern GTY(()) tree static_aggregates;
/* Likewise, for thread local storage. */
extern GTY(()) tree tls_aggregates;
enum overload_flags { NO_SPECIAL = 0, DTOR_FLAG, TYPENAME_FLAG };
/* These are uses as bits in flags passed to various functions to
control their behavior. Despite the LOOKUP_ prefix, many of these
do not control name lookup. ??? Functions using these flags should
probably be modified to accept explicit boolean flags for the
behaviors relevant to them. */
/* Check for access violations. */
#define LOOKUP_PROTECT (1 << 0)
#define LOOKUP_NORMAL (LOOKUP_PROTECT)
/* Even if the function found by lookup is a virtual function, it
should be called directly. */
#define LOOKUP_NONVIRTUAL (1 << 1)
/* Non-converting (i.e., "explicit") constructors are not tried. This flag
indicates that we are not performing direct-initialization. */
#define LOOKUP_ONLYCONVERTING (1 << 2)
#define LOOKUP_IMPLICIT (LOOKUP_NORMAL | LOOKUP_ONLYCONVERTING)
/* If a temporary is created, it should be created so that it lives
as long as the current variable bindings; otherwise it only lives
until the end of the complete-expression. It also forces
direct-initialization in cases where other parts of the compiler
have already generated a temporary, such as reference
initialization and the catch parameter. */
#define DIRECT_BIND (1 << 3)
/* We're performing a user-defined conversion, so more user-defined
conversions are not permitted (only built-in conversions). */
#define LOOKUP_NO_CONVERSION (1 << 4)
/* The user has explicitly called a destructor. (Therefore, we do
not need to check that the object is non-NULL before calling the
destructor.) */
#define LOOKUP_DESTRUCTOR (1 << 5)
/* Do not permit references to bind to temporaries. */
#define LOOKUP_NO_TEMP_BIND (1 << 6)
/* Do not accept objects, and possibly namespaces. */
#define LOOKUP_PREFER_TYPES (1 << 7)
/* Do not accept objects, and possibly types. */
#define LOOKUP_PREFER_NAMESPACES (1 << 8)
/* Accept types or namespaces. */
#define LOOKUP_PREFER_BOTH (LOOKUP_PREFER_TYPES | LOOKUP_PREFER_NAMESPACES)
/* Return friend declarations and un-declared builtin functions.
(Normally, these entities are registered in the symbol table, but
not found by lookup.) */
#define LOOKUP_HIDDEN (LOOKUP_PREFER_NAMESPACES << 1)
/* Prefer that the lvalue be treated as an rvalue. */
#define LOOKUP_PREFER_RVALUE (LOOKUP_HIDDEN << 1)
/* We're inside an init-list, so narrowing conversions are ill-formed. */
#define LOOKUP_NO_NARROWING (LOOKUP_PREFER_RVALUE << 1)
/* We're looking up a constructor for list-initialization. */
#define LOOKUP_LIST_INIT_CTOR (LOOKUP_NO_NARROWING << 1)
/* This is the first parameter of a copy constructor. */
#define LOOKUP_COPY_PARM (LOOKUP_LIST_INIT_CTOR << 1)
/* We only want to consider list constructors. */
#define LOOKUP_LIST_ONLY (LOOKUP_COPY_PARM << 1)
/* Return after determining which function to call and checking access.
Used by sythesized_method_walk to determine which functions will
be called to initialize subobjects, in order to determine exception
specification and possible implicit delete.
This is kind of a hack, but exiting early avoids problems with trying
to perform argument conversions when the class isn't complete yet. */
#define LOOKUP_SPECULATIVE (LOOKUP_LIST_ONLY << 1)
/* Used by calls from defaulted functions to limit the overload set to avoid
cycles trying to declare them (core issue 1092). */
#define LOOKUP_DEFAULTED (LOOKUP_SPECULATIVE << 1)
/* Used in calls to store_init_value to suppress its usual call to
digest_init. */
#define LOOKUP_ALREADY_DIGESTED (LOOKUP_DEFAULTED << 1)
/* An instantiation with explicit template arguments. */
#define LOOKUP_EXPLICIT_TMPL_ARGS (LOOKUP_ALREADY_DIGESTED << 1)
/* Like LOOKUP_NO_TEMP_BIND, but also prevent binding to xvalues. */
#define LOOKUP_NO_RVAL_BIND (LOOKUP_EXPLICIT_TMPL_ARGS << 1)
/* Used by case_conversion to disregard non-integral conversions. */
#define LOOKUP_NO_NON_INTEGRAL (LOOKUP_NO_RVAL_BIND << 1)
/* Used for delegating constructors in order to diagnose self-delegation. */
#define LOOKUP_DELEGATING_CONS (LOOKUP_NO_NON_INTEGRAL << 1)
#define LOOKUP_NAMESPACES_ONLY(F) \
(((F) & LOOKUP_PREFER_NAMESPACES) && !((F) & LOOKUP_PREFER_TYPES))
#define LOOKUP_TYPES_ONLY(F) \
(!((F) & LOOKUP_PREFER_NAMESPACES) && ((F) & LOOKUP_PREFER_TYPES))
#define LOOKUP_QUALIFIERS_ONLY(F) ((F) & LOOKUP_PREFER_BOTH)
/* These flags are used by the conversion code.
CONV_IMPLICIT : Perform implicit conversions (standard and user-defined).
CONV_STATIC : Perform the explicit conversions for static_cast.
CONV_CONST : Perform the explicit conversions for const_cast.
CONV_REINTERPRET: Perform the explicit conversions for reinterpret_cast.
CONV_PRIVATE : Perform upcasts to private bases.
CONV_FORCE_TEMP : Require a new temporary when converting to the same
aggregate type. */
#define CONV_IMPLICIT 1
#define CONV_STATIC 2
#define CONV_CONST 4
#define CONV_REINTERPRET 8
#define CONV_PRIVATE 16
/* #define CONV_NONCONVERTING 32 */
#define CONV_FORCE_TEMP 64
#define CONV_FOLD 128
#define CONV_OLD_CONVERT (CONV_IMPLICIT | CONV_STATIC | CONV_CONST \
| CONV_REINTERPRET)
#define CONV_C_CAST (CONV_IMPLICIT | CONV_STATIC | CONV_CONST \
| CONV_REINTERPRET | CONV_PRIVATE | CONV_FORCE_TEMP)
#define CONV_BACKEND_CONVERT (CONV_OLD_CONVERT | CONV_FOLD)
/* Used by build_expr_type_conversion to indicate which types are
acceptable as arguments to the expression under consideration. */
#define WANT_INT 1 /* integer types, including bool */
#define WANT_FLOAT 2 /* floating point types */
#define WANT_ENUM 4 /* enumerated types */
#define WANT_POINTER 8 /* pointer types */
#define WANT_NULL 16 /* null pointer constant */
#define WANT_VECTOR_OR_COMPLEX 32 /* vector or complex types */
#define WANT_ARITH (WANT_INT | WANT_FLOAT | WANT_VECTOR_OR_COMPLEX)
/* Used with comptypes, and related functions, to guide type
comparison. */
#define COMPARE_STRICT 0 /* Just check if the types are the
same. */
#define COMPARE_BASE 1 /* Check to see if the second type is
derived from the first. */
#define COMPARE_DERIVED 2 /* Like COMPARE_BASE, but in
reverse. */
#define COMPARE_REDECLARATION 4 /* The comparison is being done when
another declaration of an existing
entity is seen. */
#define COMPARE_STRUCTURAL 8 /* The comparison is intended to be
structural. The actual comparison
will be identical to
COMPARE_STRICT. */
/* Used with push_overloaded_decl. */
#define PUSH_GLOBAL 0 /* Push the DECL into namespace scope,
regardless of the current scope. */
#define PUSH_LOCAL 1 /* Push the DECL into the current
scope. */
#define PUSH_USING 2 /* We are pushing this DECL as the
result of a using declaration. */
/* Used with start function. */
#define SF_DEFAULT 0 /* No flags. */
#define SF_PRE_PARSED 1 /* The function declaration has
already been parsed. */
#define SF_INCLASS_INLINE 2 /* The function is an inline, defined
in the class body. */
/* Used with start_decl's initialized parameter. */
#define SD_UNINITIALIZED 0
#define SD_INITIALIZED 1
#define SD_DEFAULTED 2
#define SD_DELETED 3
/* Returns nonzero iff TYPE1 and TYPE2 are the same type, or if TYPE2
is derived from TYPE1, or if TYPE2 is a pointer (reference) to a
class derived from the type pointed to (referred to) by TYPE1. */
#define same_or_base_type_p(TYPE1, TYPE2) \
comptypes ((TYPE1), (TYPE2), COMPARE_BASE)
/* These macros are used to access a TEMPLATE_PARM_INDEX. */
#define TEMPLATE_PARM_INDEX_CAST(NODE) \
((template_parm_index*)TEMPLATE_PARM_INDEX_CHECK (NODE))
#define TEMPLATE_PARM_IDX(NODE) (TEMPLATE_PARM_INDEX_CAST (NODE)->index)
#define TEMPLATE_PARM_LEVEL(NODE) (TEMPLATE_PARM_INDEX_CAST (NODE)->level)
#define TEMPLATE_PARM_DESCENDANTS(NODE) (TREE_CHAIN (NODE))
#define TEMPLATE_PARM_ORIG_LEVEL(NODE) (TEMPLATE_PARM_INDEX_CAST (NODE)->orig_level)
#define TEMPLATE_PARM_DECL(NODE) (TEMPLATE_PARM_INDEX_CAST (NODE)->decl)
#define TEMPLATE_PARM_PARAMETER_PACK(NODE) \
(TREE_LANG_FLAG_0 (TEMPLATE_PARM_INDEX_CHECK (NODE)))
/* These macros are for accessing the fields of TEMPLATE_TYPE_PARM,
TEMPLATE_TEMPLATE_PARM and BOUND_TEMPLATE_TEMPLATE_PARM nodes. */
#define TEMPLATE_TYPE_PARM_INDEX(NODE) \
(TYPE_VALUES_RAW (TREE_CHECK3 ((NODE), TEMPLATE_TYPE_PARM, \
TEMPLATE_TEMPLATE_PARM, \
BOUND_TEMPLATE_TEMPLATE_PARM)))
#define TEMPLATE_TYPE_IDX(NODE) \
(TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (NODE)))
#define TEMPLATE_TYPE_LEVEL(NODE) \
(TEMPLATE_PARM_LEVEL (TEMPLATE_TYPE_PARM_INDEX (NODE)))
#define TEMPLATE_TYPE_ORIG_LEVEL(NODE) \
(TEMPLATE_PARM_ORIG_LEVEL (TEMPLATE_TYPE_PARM_INDEX (NODE)))
#define TEMPLATE_TYPE_DECL(NODE) \
(TEMPLATE_PARM_DECL (TEMPLATE_TYPE_PARM_INDEX (NODE)))
#define TEMPLATE_TYPE_PARAMETER_PACK(NODE) \
(TEMPLATE_PARM_PARAMETER_PACK (TEMPLATE_TYPE_PARM_INDEX (NODE)))
/* For a C++17 class deduction placeholder, the template it represents. */
#define CLASS_PLACEHOLDER_TEMPLATE(NODE) \
(DECL_INITIAL (TYPE_NAME (TEMPLATE_TYPE_PARM_CHECK (NODE))))
/* Contexts in which auto deduction occurs. These flags are
used to control diagnostics in do_auto_deduction. */
enum auto_deduction_context
{
adc_unspecified, /* Not given */
adc_variable_type, /* Variable initializer deduction */
adc_return_type, /* Return type deduction */
adc_unify, /* Template argument deduction */
adc_requirement, /* Argument deduction constraint */
adc_decomp_type /* Decomposition declaration initializer deduction */
};
/* True if this type-parameter belongs to a class template, used by C++17
class template argument deduction. */
#define TEMPLATE_TYPE_PARM_FOR_CLASS(NODE) \
(TREE_LANG_FLAG_0 (TEMPLATE_TYPE_PARM_CHECK (NODE)))
/* True iff this TEMPLATE_TYPE_PARM represents decltype(auto). */
#define AUTO_IS_DECLTYPE(NODE) \
(TYPE_LANG_FLAG_5 (TEMPLATE_TYPE_PARM_CHECK (NODE)))
/* These constants can used as bit flags in the process of tree formatting.
TFF_PLAIN_IDENTIFIER: unqualified part of a name.
TFF_SCOPE: include the class and namespace scope of the name.
TFF_CHASE_TYPEDEF: print the original type-id instead of the typedef-name.
TFF_DECL_SPECIFIERS: print decl-specifiers.
TFF_CLASS_KEY_OR_ENUM: precede a class-type name (resp. enum name) with
a class-key (resp. `enum').
TFF_RETURN_TYPE: include function return type.
TFF_FUNCTION_DEFAULT_ARGUMENTS: include function default parameter values.
TFF_EXCEPTION_SPECIFICATION: show function exception specification.
TFF_TEMPLATE_HEADER: show the template<...> header in a
template-declaration.
TFF_TEMPLATE_NAME: show only template-name.
TFF_EXPR_IN_PARENS: parenthesize expressions.
TFF_NO_FUNCTION_ARGUMENTS: don't show function arguments.
TFF_UNQUALIFIED_NAME: do not print the qualifying scope of the
top-level entity.
TFF_NO_OMIT_DEFAULT_TEMPLATE_ARGUMENTS: do not omit template arguments
identical to their defaults.
TFF_NO_TEMPLATE_BINDINGS: do not print information about the template
arguments for a function template specialization.
TFF_POINTER: we are printing a pointer type. */
#define TFF_PLAIN_IDENTIFIER (0)
#define TFF_SCOPE (1)
#define TFF_CHASE_TYPEDEF (1 << 1)
#define TFF_DECL_SPECIFIERS (1 << 2)
#define TFF_CLASS_KEY_OR_ENUM (1 << 3)
#define TFF_RETURN_TYPE (1 << 4)
#define TFF_FUNCTION_DEFAULT_ARGUMENTS (1 << 5)
#define TFF_EXCEPTION_SPECIFICATION (1 << 6)
#define TFF_TEMPLATE_HEADER (1 << 7)
#define TFF_TEMPLATE_NAME (1 << 8)
#define TFF_EXPR_IN_PARENS (1 << 9)
#define TFF_NO_FUNCTION_ARGUMENTS (1 << 10)
#define TFF_UNQUALIFIED_NAME (1 << 11)
#define TFF_NO_OMIT_DEFAULT_TEMPLATE_ARGUMENTS (1 << 12)
#define TFF_NO_TEMPLATE_BINDINGS (1 << 13)
#define TFF_POINTER (1 << 14)
/* Returns the TEMPLATE_DECL associated to a TEMPLATE_TEMPLATE_PARM
node. */
#define TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL(NODE) \
((TREE_CODE (NODE) == BOUND_TEMPLATE_TEMPLATE_PARM) \
? TYPE_TI_TEMPLATE (NODE) \
: TYPE_NAME (NODE))
/* in lex.c */
extern void init_reswords (void);
typedef struct GTY(()) operator_name_info_t {
/* The IDENTIFIER_NODE for the operator. */
tree identifier;
/* The name of the operator. */
const char *name;
/* The mangled name of the operator. */
const char *mangled_name;
/* The arity of the operator. */
int arity;
} operator_name_info_t;
/* A mapping from tree codes to operator name information. */
extern GTY(()) operator_name_info_t operator_name_info
[(int) MAX_TREE_CODES];
/* Similar, but for assignment operators. */
extern GTY(()) operator_name_info_t assignment_operator_name_info
[(int) MAX_TREE_CODES];
/* A type-qualifier, or bitmask therefore, using the TYPE_QUAL
constants. */
typedef int cp_cv_quals;
/* Non-static member functions have an optional virt-specifier-seq.
There is a VIRT_SPEC value for each virt-specifier.
They can be combined by bitwise-or to form the complete set of
virt-specifiers for a member function. */
enum virt_specifier
{
VIRT_SPEC_UNSPECIFIED = 0x0,
VIRT_SPEC_FINAL = 0x1,
VIRT_SPEC_OVERRIDE = 0x2
};
/* A type-qualifier, or bitmask therefore, using the VIRT_SPEC
constants. */
typedef int cp_virt_specifiers;
/* Wherever there is a function-cv-qual, there could also be a ref-qualifier:
[dcl.fct]
The return type, the parameter-type-list, the ref-qualifier, and
the cv-qualifier-seq, but not the default arguments or the exception
specification, are part of the function type.
REF_QUAL_NONE Ordinary member function with no ref-qualifier
REF_QUAL_LVALUE Member function with the &-ref-qualifier
REF_QUAL_RVALUE Member function with the &&-ref-qualifier */
enum cp_ref_qualifier {
REF_QUAL_NONE = 0,
REF_QUAL_LVALUE = 1,
REF_QUAL_RVALUE = 2
};
/* A storage class. */
enum cp_storage_class {
/* sc_none must be zero so that zeroing a cp_decl_specifier_seq
sets the storage_class field to sc_none. */
sc_none = 0,
sc_auto,
sc_register,
sc_static,
sc_extern,
sc_mutable
};
/* An individual decl-specifier. This is used to index the array of
locations for the declspecs in struct cp_decl_specifier_seq
below. */
enum cp_decl_spec {
ds_first,
ds_signed = ds_first,
ds_unsigned,
ds_short,
ds_long,
ds_const,
ds_volatile,
ds_restrict,
ds_inline,
ds_virtual,
ds_explicit,
ds_friend,
ds_typedef,
ds_alias,
ds_constexpr,
ds_complex,
ds_thread,
ds_type_spec,
ds_redefined_builtin_type_spec,
ds_attribute,
ds_std_attribute,
ds_storage_class,
ds_long_long,
ds_concept,
ds_last /* This enumerator must always be the last one. */
};
/* A decl-specifier-seq. */
struct cp_decl_specifier_seq {
/* An array of locations for the declaration sepecifiers, indexed by
enum cp_decl_spec_word. */
source_location locations[ds_last];
/* The primary type, if any, given by the decl-specifier-seq.
Modifiers, like "short", "const", and "unsigned" are not
reflected here. This field will be a TYPE, unless a typedef-name
was used, in which case it will be a TYPE_DECL. */
tree type;
/* The attributes, if any, provided with the specifier sequence. */
tree attributes;
/* The c++11 attributes that follows the type specifier. */
tree std_attributes;
/* If non-NULL, a built-in type that the user attempted to redefine
to some other type. */
tree redefined_builtin_type;
/* The storage class specified -- or sc_none if no storage class was
explicitly specified. */
cp_storage_class storage_class;
/* For the __intN declspec, this stores the index into the int_n_* arrays. */
int int_n_idx;
/* True iff TYPE_SPEC defines a class or enum. */
BOOL_BITFIELD type_definition_p : 1;
/* True iff multiple types were (erroneously) specified for this
decl-specifier-seq. */
BOOL_BITFIELD multiple_types_p : 1;
/* True iff multiple storage classes were (erroneously) specified
for this decl-specifier-seq or a combination of a storage class
with a typedef specifier. */
BOOL_BITFIELD conflicting_specifiers_p : 1;
/* True iff at least one decl-specifier was found. */
BOOL_BITFIELD any_specifiers_p : 1;
/* True iff at least one type-specifier was found. */
BOOL_BITFIELD any_type_specifiers_p : 1;
/* True iff "int" was explicitly provided. */
BOOL_BITFIELD explicit_int_p : 1;
/* True iff "__intN" was explicitly provided. */
BOOL_BITFIELD explicit_intN_p : 1;
/* True iff "char" was explicitly provided. */
BOOL_BITFIELD explicit_char_p : 1;
/* True iff ds_thread is set for __thread, not thread_local. */
BOOL_BITFIELD gnu_thread_keyword_p : 1;
/* True iff the type is a decltype. */
BOOL_BITFIELD decltype_p : 1;
};
/* The various kinds of declarators. */
enum cp_declarator_kind {
cdk_id,
cdk_function,
cdk_array,
cdk_pointer,
cdk_reference,
cdk_ptrmem,
cdk_decomp,
cdk_error
};
/* A declarator. */
typedef struct cp_declarator cp_declarator;
typedef struct cp_parameter_declarator cp_parameter_declarator;
/* A parameter, before it has been semantically analyzed. */
struct cp_parameter_declarator {
/* The next parameter, or NULL_TREE if none. */
cp_parameter_declarator *next;
/* The decl-specifiers-seq for the parameter. */
cp_decl_specifier_seq decl_specifiers;
/* The declarator for the parameter. */
cp_declarator *declarator;
/* The default-argument expression, or NULL_TREE, if none. */
tree default_argument;
/* True iff this is a template parameter pack. */
bool template_parameter_pack_p;
};
/* A declarator. */
struct cp_declarator {
/* The kind of declarator. */
ENUM_BITFIELD (cp_declarator_kind) kind : 4;
/* Whether we parsed an ellipsis (`...') just before the declarator,
to indicate this is a parameter pack. */
BOOL_BITFIELD parameter_pack_p : 1;
location_t id_loc; /* Currently only set for cdk_id, cdk_decomp and
cdk_function. */
/* GNU Attributes that apply to this declarator. If the declarator
is a pointer or a reference, these attribute apply to the type
pointed to. */
tree attributes;
/* Standard C++11 attributes that apply to this declarator. If the
declarator is a pointer or a reference, these attributes apply
to the pointer, rather than to the type pointed to. */
tree std_attributes;
/* For all but cdk_id, cdk_decomp and cdk_error, the contained declarator.
For cdk_id, cdk_decomp and cdk_error, guaranteed to be NULL. */
cp_declarator *declarator;
union {
/* For identifiers. */
struct {
/* If non-NULL, the qualifying scope (a NAMESPACE_DECL or
*_TYPE) for this identifier. */
tree qualifying_scope;
/* The unqualified name of the entity -- an IDENTIFIER_NODE,
BIT_NOT_EXPR, or TEMPLATE_ID_EXPR. */
tree unqualified_name;
/* If this is the name of a function, what kind of special
function (if any). */
special_function_kind sfk;
} id;
/* For functions. */
struct {
/* The parameters to the function as a TREE_LIST of decl/default. */
tree parameters;
/* The cv-qualifiers for the function. */
cp_cv_quals qualifiers;
/* The virt-specifiers for the function. */
cp_virt_specifiers virt_specifiers;
/* The ref-qualifier for the function. */
cp_ref_qualifier ref_qualifier;
/* The transaction-safety qualifier for the function. */
tree tx_qualifier;
/* The exception-specification for the function. */
tree exception_specification;
/* The late-specified return type, if any. */
tree late_return_type;
/* The trailing requires-clause, if any. */
tree requires_clause;
} function;
/* For arrays. */
struct {
/* The bounds to the array. */
tree bounds;
} array;
/* For cdk_pointer and cdk_ptrmem. */
struct {
/* The cv-qualifiers for the pointer. */
cp_cv_quals qualifiers;
/* For cdk_ptrmem, the class type containing the member. */
tree class_type;
} pointer;
/* For cdk_reference */
struct {
/* The cv-qualifiers for the reference. These qualifiers are
only used to diagnose ill-formed code. */
cp_cv_quals qualifiers;
/* Whether this is an rvalue reference */
bool rvalue_ref;
} reference;
} u;
};
/* A level of template instantiation. */
struct GTY((chain_next ("%h.next"))) tinst_level {
/* The immediately deeper level in the chain. */
struct tinst_level *next;
/* The original node. Can be either a DECL (for a function or static
data member) or a TYPE (for a class), depending on what we were
asked to instantiate. */
tree decl;
/* The location where the template is instantiated. */
location_t locus;
/* errorcount+sorrycount when we pushed this level. */
int errors;
/* True if the location is in a system header. */
bool in_system_header_p;
};
bool decl_spec_seq_has_spec_p (const cp_decl_specifier_seq *, cp_decl_spec);
/* Return the type of the `this' parameter of FNTYPE. */
inline tree
type_of_this_parm (const_tree fntype)
{
function_args_iterator iter;
gcc_assert (TREE_CODE (fntype) == METHOD_TYPE);
function_args_iter_init (&iter, fntype);
return function_args_iter_cond (&iter);
}
/* Return the class of the `this' parameter of FNTYPE. */
inline tree
class_of_this_parm (const_tree fntype)
{
return TREE_TYPE (type_of_this_parm (fntype));
}
/* True iff T is a variable template declaration. */
inline bool
variable_template_p (tree t)
{
if (TREE_CODE (t) != TEMPLATE_DECL)
return false;
if (!PRIMARY_TEMPLATE_P (t))
return false;
if (tree r = DECL_TEMPLATE_RESULT (t))
return VAR_P (r);
return false;
}
/* True iff T is a variable concept definition. That is, T is
a variable template declared with the concept specifier. */
inline bool
variable_concept_p (tree t)
{
if (TREE_CODE (t) != TEMPLATE_DECL)
return false;
if (tree r = DECL_TEMPLATE_RESULT (t))
return VAR_P (r) && DECL_DECLARED_CONCEPT_P (r);
return false;
}
/* True iff T is a concept definition. That is, T is a variable or function
template declared with the concept specifier. */
inline bool
concept_template_p (tree t)
{
if (TREE_CODE (t) != TEMPLATE_DECL)
return false;
if (tree r = DECL_TEMPLATE_RESULT (t))
return VAR_OR_FUNCTION_DECL_P (r) && DECL_DECLARED_CONCEPT_P (r);
return false;
}
/* A parameter list indicating for a function with no parameters,
e.g "int f(void)". */
extern cp_parameter_declarator *no_parameters;
/* in call.c */
extern bool check_dtor_name (tree, tree);
int magic_varargs_p (tree);
extern tree build_conditional_expr (location_t, tree, tree, tree,
tsubst_flags_t);
extern tree build_addr_func (tree, tsubst_flags_t);
extern void set_flags_from_callee (tree);
extern tree build_call_a (tree, int, tree*);
extern tree build_call_n (tree, int, ...);
extern bool null_ptr_cst_p (tree);
extern bool null_member_pointer_value_p (tree);
extern bool sufficient_parms_p (const_tree);
extern tree type_decays_to (tree);
extern tree extract_call_expr (tree);
extern tree build_user_type_conversion (tree, tree, int,
tsubst_flags_t);
extern tree build_new_function_call (tree, vec<tree, va_gc> **, bool,
tsubst_flags_t);
extern tree build_operator_new_call (tree, vec<tree, va_gc> **, tree *,
tree *, tree, tree, tree *,
tsubst_flags_t);
extern tree build_new_method_call (tree, tree, vec<tree, va_gc> **,
tree, int, tree *,
tsubst_flags_t);
extern tree build_special_member_call (tree, tree, vec<tree, va_gc> **,
tree, int, tsubst_flags_t);
extern tree build_new_op (location_t, enum tree_code,
int, tree, tree, tree, tree *,
tsubst_flags_t);
extern tree build_op_call (tree, vec<tree, va_gc> **,
tsubst_flags_t);
extern bool aligned_allocation_fn_p (tree);
extern bool usual_deallocation_fn_p (tree);
extern tree build_op_delete_call (enum tree_code, tree, tree,
bool, tree, tree,
tsubst_flags_t);
extern bool can_convert (tree, tree, tsubst_flags_t);
extern bool can_convert_standard (tree, tree, tsubst_flags_t);
extern bool can_convert_arg (tree, tree, tree, int,
tsubst_flags_t);
extern bool can_convert_arg_bad (tree, tree, tree, int,
tsubst_flags_t);
extern bool enforce_access (tree, tree, tree,
tsubst_flags_t);
extern void push_defarg_context (tree);
extern void pop_defarg_context (void);
extern tree convert_default_arg (tree, tree, tree, int,
tsubst_flags_t);
extern tree convert_arg_to_ellipsis (tree, tsubst_flags_t);
extern tree build_x_va_arg (source_location, tree, tree);
extern tree cxx_type_promotes_to (tree);
extern tree type_passed_as (tree);
extern tree convert_for_arg_passing (tree, tree, tsubst_flags_t);
extern bool is_properly_derived_from (tree, tree);
extern tree initialize_reference (tree, tree, int,
tsubst_flags_t);
extern tree extend_ref_init_temps (tree, tree, vec<tree, va_gc>**);
extern tree make_temporary_var_for_ref_to_temp (tree, tree);
extern bool type_has_extended_temps (tree);
extern tree strip_top_quals (tree);
extern bool reference_related_p (tree, tree);
extern int remaining_arguments (tree);
extern tree perform_implicit_conversion (tree, tree, tsubst_flags_t);
extern tree perform_implicit_conversion_flags (tree, tree, tsubst_flags_t, int);
extern tree build_integral_nontype_arg_conv (tree, tree, tsubst_flags_t);
extern tree perform_direct_initialization_if_possible (tree, tree, bool,
tsubst_flags_t);
extern tree in_charge_arg_for_name (tree);
extern tree build_cxx_call (tree, int, tree *,
tsubst_flags_t);
extern bool is_std_init_list (tree);
extern bool is_list_ctor (tree);
extern void validate_conversion_obstack (void);
extern void mark_versions_used (tree);
extern tree get_function_version_dispatcher (tree);
/* in class.c */
extern tree build_vfield_ref (tree, tree);
extern tree build_if_in_charge (tree true_stmt, tree false_stmt = void_node);
extern tree build_base_path (enum tree_code, tree,
tree, int, tsubst_flags_t);
extern tree convert_to_base (tree, tree, bool, bool,
tsubst_flags_t);
extern tree convert_to_base_statically (tree, tree);
extern tree build_vtbl_ref (tree, tree);
extern tree build_vfn_ref (tree, tree);
extern tree get_vtable_decl (tree, int);
extern void resort_type_method_vec (void *, void *,
gt_pointer_operator, void *);
extern bool add_method (tree, tree, tree);
extern tree declared_access (tree);
extern tree currently_open_class (tree);
extern tree currently_open_derived_class (tree);
extern tree outermost_open_class (void);
extern tree current_nonlambda_class_type (void);
extern tree finish_struct (tree, tree);
extern void finish_struct_1 (tree);
extern int resolves_to_fixed_type_p (tree, int *);
extern void init_class_processing (void);
extern int is_empty_class (tree);
extern bool is_really_empty_class (tree);
extern void pushclass (tree);
extern void popclass (void);
extern void push_nested_class (tree);
extern void pop_nested_class (void);
extern int current_lang_depth (void);
extern void push_lang_context (tree);
extern void pop_lang_context (void);
extern tree instantiate_type (tree, tree, tsubst_flags_t);
extern void print_class_statistics (void);
extern void build_self_reference (void);
extern int same_signature_p (const_tree, const_tree);
extern void maybe_add_class_template_decl_list (tree, tree, int);
extern void unreverse_member_declarations (tree);
extern void invalidate_class_lookup_cache (void);
extern void maybe_note_name_used_in_class (tree, tree);
extern void note_name_declared_in_class (tree, tree);
extern tree get_vtbl_decl_for_binfo (tree);
extern bool vptr_via_virtual_p (tree);
extern void debug_class (tree);
extern void debug_thunks (tree);
extern void set_linkage_according_to_type (tree, tree);
extern void determine_key_method (tree);
extern void check_for_override (tree, tree);
extern void push_class_stack (void);
extern void pop_class_stack (void);
extern bool default_ctor_p (tree);
extern bool type_has_user_nondefault_constructor (tree);
extern tree in_class_defaulted_default_constructor (tree);
extern bool user_provided_p (tree);
extern bool type_has_user_provided_constructor (tree);
extern bool type_has_non_user_provided_default_constructor (tree);
extern bool vbase_has_user_provided_move_assign (tree);
extern tree default_init_uninitialized_part (tree);
extern bool trivial_default_constructor_is_constexpr (tree);
extern bool type_has_constexpr_default_constructor (tree);
extern bool type_has_virtual_destructor (tree);
extern bool type_has_move_constructor (tree);
extern bool type_has_move_assign (tree);
extern bool type_has_user_declared_move_constructor (tree);
extern bool type_has_user_declared_move_assign(tree);
extern bool type_build_ctor_call (tree);
extern bool type_build_dtor_call (tree);
extern void explain_non_literal_class (tree);
extern void inherit_targ_abi_tags (tree);
extern void defaulted_late_check (tree);
extern bool defaultable_fn_check (tree);
extern void check_abi_tags (tree);
extern tree missing_abi_tags (tree);
extern void fixup_type_variants (tree);
extern void fixup_attribute_variants (tree);
extern tree* decl_cloned_function_p (const_tree, bool);
extern void clone_function_decl (tree, int);
extern void adjust_clone_args (tree);
extern void deduce_noexcept_on_destructor (tree);
extern void insert_late_enum_def_into_classtype_sorted_fields (tree, tree);
extern bool uniquely_derived_from_p (tree, tree);
extern bool publicly_uniquely_derived_p (tree, tree);
extern tree common_enclosing_class (tree, tree);
/* in cvt.c */
extern tree convert_to_reference (tree, tree, int, int, tree,
tsubst_flags_t);
extern tree convert_from_reference (tree);
extern tree force_rvalue (tree, tsubst_flags_t);
extern tree ocp_convert (tree, tree, int, int,
tsubst_flags_t);
extern tree cp_convert (tree, tree, tsubst_flags_t);
extern tree cp_convert_and_check (tree, tree, tsubst_flags_t);
extern tree cp_fold_convert (tree, tree);
extern tree cp_get_callee (tree);
extern tree cp_get_callee_fndecl (tree);
extern tree cp_get_fndecl_from_callee (tree);
extern tree convert_to_void (tree, impl_conv_void,
tsubst_flags_t);
extern tree convert_force (tree, tree, int,
tsubst_flags_t);
extern tree build_expr_type_conversion (int, tree, bool);
extern tree type_promotes_to (tree);
extern tree perform_qualification_conversions (tree, tree);
extern bool tx_safe_fn_type_p (tree);
extern tree tx_unsafe_fn_variant (tree);
extern bool fnptr_conv_p (tree, tree);
extern tree strip_fnptr_conv (tree);
/* in name-lookup.c */
extern tree pushdecl (tree);
extern tree pushdecl_maybe_friend (tree, bool);
extern void maybe_push_cleanup_level (tree);
extern tree pushtag (tree, tree, tag_scope);
extern tree make_anon_name (void);
extern tree pushdecl_top_level_maybe_friend (tree, bool);
extern tree pushdecl_top_level_and_finish (tree, tree);
extern tree check_for_out_of_scope_variable (tree);
extern void dump (cp_binding_level &ref);
extern void dump (cp_binding_level *ptr);
extern void print_other_binding_stack (cp_binding_level *);
extern tree maybe_push_decl (tree);
extern tree current_decl_namespace (void);
/* decl.c */
extern tree poplevel (int, int, int);
extern void cxx_init_decl_processing (void);
enum cp_tree_node_structure_enum cp_tree_node_structure
(union lang_tree_node *);
extern void finish_scope (void);
extern void push_switch (tree);
extern void pop_switch (void);
extern tree make_lambda_name (void);
extern int decls_match (tree, tree);
extern tree duplicate_decls (tree, tree, bool);
extern tree declare_local_label (tree);
extern tree define_label (location_t, tree);
extern void check_goto (tree);
extern bool check_omp_return (void);
extern tree make_typename_type (tree, tree, enum tag_types, tsubst_flags_t);
extern tree make_unbound_class_template (tree, tree, tree, tsubst_flags_t);
extern tree build_library_fn_ptr (const char *, tree, int);
extern tree build_cp_library_fn_ptr (const char *, tree, int);
extern tree push_library_fn (tree, tree, tree, int);
extern tree push_void_library_fn (tree, tree, int);
extern tree push_throw_library_fn (tree, tree);
extern void warn_misplaced_attr_for_class_type (source_location location,
tree class_type);
extern tree check_tag_decl (cp_decl_specifier_seq *, bool);
extern tree shadow_tag (cp_decl_specifier_seq *);
extern tree groktypename (cp_decl_specifier_seq *, const cp_declarator *, bool);
extern tree start_decl (const cp_declarator *, cp_decl_specifier_seq *, int, tree, tree, tree *);
extern void start_decl_1 (tree, bool);
extern bool check_array_initializer (tree, tree, tree);
extern void cp_finish_decl (tree, tree, bool, tree, int);
extern tree lookup_decomp_type (tree);
extern void cp_finish_decomp (tree, tree, unsigned int);
extern int cp_complete_array_type (tree *, tree, bool);
extern int cp_complete_array_type_or_error (tree *, tree, bool, tsubst_flags_t);
extern tree build_ptrmemfunc_type (tree);
extern tree build_ptrmem_type (tree, tree);
/* the grokdeclarator prototype is in decl.h */
extern tree build_this_parm (tree, cp_cv_quals);
extern tree grokparms (tree, tree *);
extern int copy_fn_p (const_tree);
extern bool move_fn_p (const_tree);
extern bool move_signature_fn_p (const_tree);
extern tree get_scope_of_declarator (const cp_declarator *);
extern void grok_special_member_properties (tree);
extern int grok_ctor_properties (const_tree, const_tree);
extern bool grok_op_properties (tree, bool);
extern tree xref_tag (enum tag_types, tree, tag_scope, bool);
extern tree xref_tag_from_type (tree, tree, tag_scope);
extern void xref_basetypes (tree, tree);
extern tree start_enum (tree, tree, tree, tree, bool, bool *);
extern void finish_enum_value_list (tree);
extern void finish_enum (tree);
extern void build_enumerator (tree, tree, tree, tree, location_t);
extern tree lookup_enumerator (tree, tree);
extern bool start_preparsed_function (tree, tree, int);
extern bool start_function (cp_decl_specifier_seq *,
const cp_declarator *, tree);
extern tree begin_function_body (void);
extern void finish_function_body (tree);
extern tree outer_curly_brace_block (tree);
extern tree finish_function (int);
extern tree grokmethod (cp_decl_specifier_seq *, const cp_declarator *, tree);
extern void maybe_register_incomplete_var (tree);
extern void maybe_commonize_var (tree);
extern void complete_vars (tree);
extern tree static_fn_type (tree);
extern void revert_static_member_fn (tree);
extern void fixup_anonymous_aggr (tree);
extern tree compute_array_index_type (tree, tree, tsubst_flags_t);
extern tree check_default_argument (tree, tree, tsubst_flags_t);
typedef int (*walk_namespaces_fn) (tree, void *);
extern int walk_namespaces (walk_namespaces_fn,
void *);
extern int wrapup_globals_for_namespace (tree, void *);
extern int diagnose_inline_vars_for_namespace (tree, void *);
extern tree create_implicit_typedef (tree, tree);
extern int local_variable_p (const_tree);
extern tree register_dtor_fn (tree);
extern tmpl_spec_kind current_tmpl_spec_kind (int);
extern tree cp_fname_init (const char *, tree *);
extern tree cxx_builtin_function (tree decl);
extern tree cxx_builtin_function_ext_scope (tree decl);
extern tree check_elaborated_type_specifier (enum tag_types, tree, bool);
extern void warn_extern_redeclared_static (tree, tree);
extern tree cxx_comdat_group (tree);
extern bool cp_missing_noreturn_ok_p (tree);
extern bool is_direct_enum_init (tree, tree);
extern void initialize_artificial_var (tree, vec<constructor_elt, va_gc> *);
extern tree check_var_type (tree, tree);
extern tree reshape_init (tree, tree, tsubst_flags_t);
extern tree next_initializable_field (tree);
extern tree fndecl_declared_return_type (tree);
extern bool undeduced_auto_decl (tree);
extern bool require_deduced_type (tree, tsubst_flags_t = tf_warning_or_error);
extern tree finish_case_label (location_t, tree, tree);
extern tree cxx_maybe_build_cleanup (tree, tsubst_flags_t);
/* in decl2.c */
extern void note_mangling_alias (tree, tree);
extern void generate_mangling_aliases (void);
extern tree build_memfn_type (tree, tree, cp_cv_quals, cp_ref_qualifier);
extern tree build_pointer_ptrmemfn_type (tree);
extern tree change_return_type (tree, tree);
extern void maybe_retrofit_in_chrg (tree);
extern void maybe_make_one_only (tree);
extern bool vague_linkage_p (tree);
extern void grokclassfn (tree, tree,
enum overload_flags);
extern tree grok_array_decl (location_t, tree, tree, bool);
extern tree delete_sanity (tree, tree, bool, int, tsubst_flags_t);
extern tree check_classfn (tree, tree, tree);
extern void check_member_template (tree);
extern tree grokfield (const cp_declarator *, cp_decl_specifier_seq *,
tree, bool, tree, tree);
extern tree grokbitfield (const cp_declarator *, cp_decl_specifier_seq *,
tree, tree);
extern bool any_dependent_type_attributes_p (tree);
extern tree cp_reconstruct_complex_type (tree, tree);
extern bool attributes_naming_typedef_ok (tree);
extern void cplus_decl_attributes (tree *, tree, int);
extern void finish_anon_union (tree);
extern void cxx_post_compilation_parsing_cleanups (void);
extern tree coerce_new_type (tree);
extern tree coerce_delete_type (tree);
extern void comdat_linkage (tree);
extern void determine_visibility (tree);
extern void constrain_class_visibility (tree);
extern void reset_type_linkage (tree);
extern void tentative_decl_linkage (tree);
extern void import_export_decl (tree);
extern tree build_cleanup (tree);
extern tree build_offset_ref_call_from_tree (tree, vec<tree, va_gc> **,
tsubst_flags_t);
extern bool decl_defined_p (tree);
extern bool decl_constant_var_p (tree);
extern bool decl_maybe_constant_var_p (tree);
extern void no_linkage_error (tree);
extern void check_default_args (tree);
extern bool mark_used (tree);
extern bool mark_used (tree, tsubst_flags_t);
extern void finish_static_data_member_decl (tree, tree, bool, tree, int);
extern tree cp_build_parm_decl (tree, tree);
extern tree get_guard (tree);
extern tree get_guard_cond (tree, bool);
extern tree set_guard (tree);
extern tree get_tls_wrapper_fn (tree);
extern void mark_needed (tree);
extern bool decl_needed_p (tree);
extern void note_vague_linkage_fn (tree);
extern void note_variable_template_instantiation (tree);
extern tree build_artificial_parm (tree, tree);
extern bool possibly_inlined_p (tree);
extern int parm_index (tree);
extern tree vtv_start_verification_constructor_init_function (void);
extern tree vtv_finish_verification_constructor_init_function (tree);
extern bool cp_omp_mappable_type (tree);
/* in error.c */
extern const char *type_as_string (tree, int);
extern const char *type_as_string_translate (tree, int);
extern const char *decl_as_string (tree, int);
extern const char *decl_as_string_translate (tree, int);
extern const char *decl_as_dwarf_string (tree, int);
extern const char *expr_as_string (tree, int);
extern const char *lang_decl_name (tree, int, bool);
extern const char *lang_decl_dwarf_name (tree, int, bool);
extern const char *language_to_string (enum languages);
extern const char *class_key_or_enum_as_string (tree);
extern void maybe_warn_variadic_templates (void);
extern void maybe_warn_cpp0x (cpp0x_warn_str str);
extern bool pedwarn_cxx98 (location_t, int, const char *, ...) ATTRIBUTE_GCC_DIAG(3,4);
extern location_t location_of (tree);
extern void qualified_name_lookup_error (tree, tree, tree,
location_t);
/* in except.c */
extern void init_exception_processing (void);
extern tree expand_start_catch_block (tree);
extern void expand_end_catch_block (void);
extern tree build_exc_ptr (void);
extern tree build_throw (tree);
extern int nothrow_libfn_p (const_tree);
extern void check_handlers (tree);
extern tree finish_noexcept_expr (tree, tsubst_flags_t);
extern bool expr_noexcept_p (tree, tsubst_flags_t);
extern void perform_deferred_noexcept_checks (void);
extern bool nothrow_spec_p (const_tree);
extern bool type_noexcept_p (const_tree);
extern bool type_throw_all_p (const_tree);
extern tree build_noexcept_spec (tree, int);
extern void choose_personality_routine (enum languages);
extern tree build_must_not_throw_expr (tree,tree);
extern tree eh_type_info (tree);
extern tree begin_eh_spec_block (void);
extern void finish_eh_spec_block (tree, tree);
extern tree build_eh_type_type (tree);
extern tree cp_protect_cleanup_actions (void);
extern tree create_try_catch_expr (tree, tree);
/* in expr.c */
extern tree cplus_expand_constant (tree);
extern tree mark_rvalue_use (tree,
location_t = UNKNOWN_LOCATION,
bool = true);
extern tree mark_lvalue_use (tree);
extern tree mark_type_use (tree);
extern void mark_exp_read (tree);
/* friend.c */
extern int is_friend (tree, tree);
extern void make_friend_class (tree, tree, bool);
extern void add_friend (tree, tree, bool);
extern tree do_friend (tree, tree, tree, tree, enum overload_flags, bool);
extern void set_global_friend (tree);
extern bool is_global_friend (tree);
/* in init.c */
extern tree expand_member_init (tree);
extern void emit_mem_initializers (tree);
extern tree build_aggr_init (tree, tree, int,
tsubst_flags_t);
extern int is_class_type (tree, int);
extern tree get_type_value (tree);
extern tree build_zero_init (tree, tree, bool);
extern tree build_value_init (tree, tsubst_flags_t);
extern tree build_value_init_noctor (tree, tsubst_flags_t);
extern tree get_nsdmi (tree, bool);
extern tree build_offset_ref (tree, tree, bool,
tsubst_flags_t);
extern tree throw_bad_array_new_length (void);
extern bool type_has_new_extended_alignment (tree);
extern unsigned malloc_alignment (void);
extern tree build_new (vec<tree, va_gc> **, tree, tree,
vec<tree, va_gc> **, int,
tsubst_flags_t);
extern tree get_temp_regvar (tree, tree);
extern tree build_vec_init (tree, tree, tree, bool, int,
tsubst_flags_t);
extern tree build_delete (tree, tree,
special_function_kind,
int, int, tsubst_flags_t);
extern void push_base_cleanups (void);
extern tree build_vec_delete (tree, tree,
special_function_kind, int,
tsubst_flags_t);
extern tree create_temporary_var (tree);
extern void initialize_vtbl_ptrs (tree);
extern tree scalar_constant_value (tree);
extern tree decl_really_constant_value (tree);
extern int diagnose_uninitialized_cst_or_ref_member (tree, bool, bool);
extern tree build_vtbl_address (tree);
extern bool maybe_reject_flexarray_init (tree, tree);
/* in lex.c */
extern void cxx_dup_lang_specific_decl (tree);
extern void yyungetc (int, int);
extern tree unqualified_name_lookup_error (tree,
location_t = UNKNOWN_LOCATION);
extern tree unqualified_fn_lookup_error (cp_expr);
extern tree build_lang_decl (enum tree_code, tree, tree);
extern tree build_lang_decl_loc (location_t, enum tree_code, tree, tree);
extern void retrofit_lang_decl (tree);
extern tree copy_decl (tree);
extern tree copy_type (tree);
extern tree cxx_make_type (enum tree_code);
extern tree make_class_type (enum tree_code);
extern bool cxx_init (void);
extern void cxx_finish (void);
extern bool in_main_input_context (void);
/* in method.c */
extern void init_method (void);
extern tree make_thunk (tree, bool, tree, tree);
extern void finish_thunk (tree);
extern void use_thunk (tree, bool);
extern bool trivial_fn_p (tree);
extern tree forward_parm (tree);
extern bool is_trivially_xible (enum tree_code, tree, tree);
extern tree get_defaulted_eh_spec (tree);
extern tree unevaluated_noexcept_spec (void);
extern void after_nsdmi_defaulted_late_checks (tree);
extern bool maybe_explain_implicit_delete (tree);
extern void explain_implicit_non_constexpr (tree);
extern void deduce_inheriting_ctor (tree);
extern void synthesize_method (tree);
extern tree lazily_declare_fn (special_function_kind,
tree);
extern tree skip_artificial_parms_for (const_tree, tree);
extern int num_artificial_parms_for (const_tree);
extern tree make_alias_for (tree, tree);
extern tree get_copy_ctor (tree, tsubst_flags_t);
extern tree get_copy_assign (tree);
extern tree get_default_ctor (tree);
extern tree get_dtor (tree, tsubst_flags_t);
extern tree strip_inheriting_ctors (tree);
extern tree inherited_ctor_binfo (tree);
extern bool ctor_omit_inherited_parms (tree);
extern tree locate_ctor (tree);
extern tree implicitly_declare_fn (special_function_kind, tree,
bool, tree, tree);
/* In optimize.c */
extern bool maybe_clone_body (tree);
/* In parser.c */
extern tree cp_convert_range_for (tree, tree, tree, tree, unsigned int, bool);
extern bool parsing_nsdmi (void);
extern bool parsing_default_capturing_generic_lambda_in_template (void);
extern void inject_this_parameter (tree, cp_cv_quals);
/* in pt.c */
extern bool check_template_shadow (tree);
extern tree get_innermost_template_args (tree, int);
extern void maybe_begin_member_template_processing (tree);
extern void maybe_end_member_template_processing (void);
extern tree finish_member_template_decl (tree);
extern void begin_template_parm_list (void);
extern bool begin_specialization (void);
extern void reset_specialization (void);
extern void end_specialization (void);
extern void begin_explicit_instantiation (void);
extern void end_explicit_instantiation (void);
extern void check_unqualified_spec_or_inst (tree, location_t);
extern tree check_explicit_specialization (tree, tree, int, int);
extern int num_template_headers_for_class (tree);
extern void check_template_variable (tree);
extern tree make_auto (void);
extern tree make_decltype_auto (void);
extern tree make_template_placeholder (tree);
extern bool template_placeholder_p (tree);
extern tree do_auto_deduction (tree, tree, tree);
extern tree do_auto_deduction (tree, tree, tree,
tsubst_flags_t,
auto_deduction_context,
tree = NULL_TREE,
int = LOOKUP_NORMAL);
extern tree type_uses_auto (tree);
extern tree type_uses_auto_or_concept (tree);
extern void append_type_to_template_for_access_check (tree, tree, tree,
location_t);
extern tree convert_generic_types_to_packs (tree, int, int);
extern tree splice_late_return_type (tree, tree);
extern bool is_auto (const_tree);
extern bool is_auto_or_concept (const_tree);
extern tree process_template_parm (tree, location_t, tree,
bool, bool);
extern tree end_template_parm_list (tree);
extern void end_template_parm_list (void);
extern void end_template_decl (void);
extern tree maybe_update_decl_type (tree, tree);
extern bool check_default_tmpl_args (tree, tree, bool, bool, int);
extern tree push_template_decl (tree);
extern tree push_template_decl_real (tree, bool);
extern tree add_inherited_template_parms (tree, tree);
extern bool redeclare_class_template (tree, tree, tree);
extern tree lookup_template_class (tree, tree, tree, tree,
int, tsubst_flags_t);
extern tree lookup_template_function (tree, tree);
extern tree lookup_template_variable (tree, tree);
extern int uses_template_parms (tree);
extern bool uses_template_parms_level (tree, int);
extern bool in_template_function (void);
extern tree instantiate_class_template (tree);
extern tree instantiate_template (tree, tree, tsubst_flags_t);
extern tree fn_type_unification (tree, tree, tree,
const tree *, unsigned int,
tree, unification_kind_t, int,
bool, bool);
extern void mark_decl_instantiated (tree, int);
extern int more_specialized_fn (tree, tree, int);
extern void do_decl_instantiation (tree, tree);
extern void do_type_instantiation (tree, tree, tsubst_flags_t);
extern bool always_instantiate_p (tree);
extern void maybe_instantiate_noexcept (tree);
extern tree instantiate_decl (tree, bool, bool);
extern int comp_template_parms (const_tree, const_tree);
extern bool uses_parameter_packs (tree);
extern bool template_parameter_pack_p (const_tree);
extern bool function_parameter_pack_p (const_tree);
extern bool function_parameter_expanded_from_pack_p (tree, tree);
extern tree make_pack_expansion (tree);
extern bool check_for_bare_parameter_packs (tree);
extern tree build_template_info (tree, tree);
extern tree get_template_info (const_tree);
extern vec<qualified_typedef_usage_t, va_gc> *get_types_needing_access_check (tree);
extern int template_class_depth (tree);
extern int is_specialization_of (tree, tree);
extern bool is_specialization_of_friend (tree, tree);
extern tree get_pattern_parm (tree, tree);
extern int comp_template_args (tree, tree, tree * = NULL,
tree * = NULL, bool = false);
extern int template_args_equal (tree, tree, bool = false);
extern tree maybe_process_partial_specialization (tree);
extern tree most_specialized_instantiation (tree);
extern void print_candidates (tree);
extern void instantiate_pending_templates (int);
extern tree tsubst_default_argument (tree, tree, tree,
tsubst_flags_t);
extern tree tsubst (tree, tree, tsubst_flags_t, tree);
extern tree tsubst_copy_and_build (tree, tree, tsubst_flags_t,
tree, bool, bool);
extern tree tsubst_expr (tree, tree, tsubst_flags_t,
tree, bool);
extern tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
extern tree most_general_template (tree);
extern tree get_mostly_instantiated_function_type (tree);
extern bool problematic_instantiation_changed (void);
extern void record_last_problematic_instantiation (void);
extern struct tinst_level *current_instantiation(void);
extern bool instantiating_current_function_p (void);
extern tree maybe_get_template_decl_from_type_decl (tree);
extern int processing_template_parmlist;
extern bool dependent_type_p (tree);
extern bool dependent_scope_p (tree);
extern bool any_dependent_template_arguments_p (const_tree);
extern bool dependent_template_p (tree);
extern bool dependent_template_id_p (tree, tree);
extern bool type_dependent_expression_p (tree);
extern bool type_dependent_object_expression_p (tree);
extern bool any_type_dependent_arguments_p (const vec<tree, va_gc> *);
extern bool any_type_dependent_elements_p (const_tree);
extern bool type_dependent_expression_p_push (tree);
extern bool value_dependent_expression_p (tree);
extern bool instantiation_dependent_expression_p (tree);
extern bool instantiation_dependent_uneval_expression_p (tree);
extern bool any_value_dependent_elements_p (const_tree);
extern bool dependent_omp_for_p (tree, tree, tree, tree);
extern tree resolve_typename_type (tree, bool);
extern tree template_for_substitution (tree);
extern tree build_non_dependent_expr (tree);
extern void make_args_non_dependent (vec<tree, va_gc> *);
extern bool reregister_specialization (tree, tree, tree);
extern tree instantiate_non_dependent_expr (tree);
extern tree instantiate_non_dependent_expr_sfinae (tree, tsubst_flags_t);
extern tree instantiate_non_dependent_expr_internal (tree, tsubst_flags_t);
extern tree instantiate_non_dependent_or_null (tree);
extern bool variable_template_specialization_p (tree);
extern bool alias_type_or_template_p (tree);
extern bool alias_template_specialization_p (const_tree);
extern bool dependent_alias_template_spec_p (const_tree);
extern bool explicit_class_specialization_p (tree);
extern bool push_tinst_level (tree);
extern bool push_tinst_level_loc (tree, location_t);
extern void pop_tinst_level (void);
extern struct tinst_level *outermost_tinst_level(void);
extern void init_template_processing (void);
extern void print_template_statistics (void);
bool template_template_parameter_p (const_tree);
bool template_type_parameter_p (const_tree);
extern bool primary_template_instantiation_p (const_tree);
extern tree get_primary_template_innermost_parameters (const_tree);
extern tree get_template_parms_at_level (tree, int);
extern tree get_template_innermost_arguments (const_tree);
extern tree get_template_argument_pack_elems (const_tree);
extern tree get_function_template_decl (const_tree);
extern tree resolve_nondeduced_context (tree, tsubst_flags_t);
extern hashval_t iterative_hash_template_arg (tree arg, hashval_t val);
extern tree coerce_template_parms (tree, tree, tree);
extern tree coerce_template_parms (tree, tree, tree, tsubst_flags_t);
extern void register_local_specialization (tree, tree);
extern tree retrieve_local_specialization (tree);
extern tree extract_fnparm_pack (tree, tree *);
extern tree template_parm_to_arg (tree);
extern tree dguide_name (tree);
extern bool dguide_name_p (tree);
extern bool deduction_guide_p (const_tree);
extern bool copy_guide_p (const_tree);
extern bool template_guide_p (const_tree);
/* in repo.c */
extern void init_repo (void);
extern int repo_emit_p (tree);
extern bool repo_export_class_p (const_tree);
extern void finish_repo (void);
/* in rtti.c */
/* A vector of all tinfo decls that haven't been emitted yet. */
extern GTY(()) vec<tree, va_gc> *unemitted_tinfo_decls;
extern void init_rtti_processing (void);
extern tree build_typeid (tree, tsubst_flags_t);
extern tree get_tinfo_decl (tree);
extern tree get_typeid (tree, tsubst_flags_t);
extern tree build_headof (tree);
extern tree build_dynamic_cast (tree, tree, tsubst_flags_t);
extern void emit_support_tinfos (void);
extern bool emit_tinfo_decl (tree);
/* in search.c */
extern bool accessible_base_p (tree, tree, bool);
extern tree lookup_base (tree, tree, base_access,
base_kind *, tsubst_flags_t);
extern tree dcast_base_hint (tree, tree);
extern int accessible_p (tree, tree, bool);
extern int accessible_in_template_p (tree, tree);
extern tree lookup_field_1 (tree, tree, bool);
extern tree lookup_field (tree, tree, int, bool);
extern int lookup_fnfields_1 (tree, tree);
extern tree lookup_fnfields_slot (tree, tree);
extern tree lookup_fnfields_slot_nolazy (tree, tree);
extern int class_method_index_for_fn (tree, tree);
extern tree lookup_fnfields (tree, tree, int);
extern tree lookup_member (tree, tree, int, bool,
tsubst_flags_t);
extern tree lookup_member_fuzzy (tree, tree, bool);
extern int look_for_overrides (tree, tree);
extern void get_pure_virtuals (tree);
extern void maybe_suppress_debug_info (tree);
extern void note_debug_info_needed (tree);
extern void print_search_statistics (void);
extern void reinit_search_statistics (void);
extern tree current_scope (void);
extern int at_function_scope_p (void);
extern bool at_class_scope_p (void);
extern bool at_namespace_scope_p (void);
extern tree context_for_name_lookup (tree);
extern tree lookup_conversions (tree);
extern tree binfo_from_vbase (tree);
extern tree binfo_for_vbase (tree, tree);
extern tree look_for_overrides_here (tree, tree);
#define dfs_skip_bases ((tree)1)
extern tree dfs_walk_all (tree, tree (*) (tree, void *),
tree (*) (tree, void *), void *);
extern tree dfs_walk_once (tree, tree (*) (tree, void *),
tree (*) (tree, void *), void *);
extern tree binfo_via_virtual (tree, tree);
extern bool binfo_direct_p (tree);
extern tree build_baselink (tree, tree, tree, tree);
extern tree adjust_result_of_qualified_name_lookup
(tree, tree, tree);
extern tree copied_binfo (tree, tree);
extern tree original_binfo (tree, tree);
extern int shared_member_p (tree);
extern bool any_dependent_bases_p (tree = current_nonlambda_class_type ());
/* The representation of a deferred access check. */
struct GTY(()) deferred_access_check {
/* The base class in which the declaration is referenced. */
tree binfo;
/* The declaration whose access must be checked. */
tree decl;
/* The declaration that should be used in the error message. */
tree diag_decl;
/* The location of this access. */
location_t loc;
};
/* in semantics.c */
extern void push_deferring_access_checks (deferring_kind);
extern void resume_deferring_access_checks (void);
extern void stop_deferring_access_checks (void);
extern void pop_deferring_access_checks (void);
extern vec<deferred_access_check, va_gc> *get_deferred_access_checks (void);
extern void reopen_deferring_access_checks (vec<deferred_access_check, va_gc> *);
extern void pop_to_parent_deferring_access_checks (void);
extern bool perform_access_checks (vec<deferred_access_check, va_gc> *,
tsubst_flags_t);
extern bool perform_deferred_access_checks (tsubst_flags_t);
extern bool perform_or_defer_access_check (tree, tree, tree,
tsubst_flags_t);
/* RAII sentinel to ensures that deferred access checks are popped before
a function returns. */
struct deferring_access_check_sentinel
{
deferring_access_check_sentinel ()
{
push_deferring_access_checks (dk_deferred);
}
~deferring_access_check_sentinel ()
{
pop_deferring_access_checks ();
}
};
extern int stmts_are_full_exprs_p (void);
extern void init_cp_semantics (void);
extern tree do_poplevel (tree);
extern void break_maybe_infinite_loop (void);
extern void add_decl_expr (tree);
extern tree maybe_cleanup_point_expr_void (tree);
extern tree finish_expr_stmt (tree);
extern tree begin_if_stmt (void);
extern tree finish_if_stmt_cond (tree, tree);
extern tree finish_then_clause (tree);
extern void begin_else_clause (tree);
extern void finish_else_clause (tree);
extern void finish_if_stmt (tree);
extern tree begin_while_stmt (void);
extern void finish_while_stmt_cond (tree, tree, bool);
extern void finish_while_stmt (tree);
extern tree begin_do_stmt (void);
extern void finish_do_body (tree);
extern void finish_do_stmt (tree, tree, bool);
extern tree finish_return_stmt (tree);
extern tree begin_for_scope (tree *);
extern tree begin_for_stmt (tree, tree);
extern void finish_init_stmt (tree);
extern void finish_for_cond (tree, tree, bool);
extern void finish_for_expr (tree, tree);
extern void finish_for_stmt (tree);
extern tree begin_range_for_stmt (tree, tree);
extern void finish_range_for_decl (tree, tree, tree);
extern void finish_range_for_stmt (tree);
extern tree finish_break_stmt (void);
extern tree finish_continue_stmt (void);
extern tree begin_switch_stmt (void);
extern void finish_switch_cond (tree, tree);
extern void finish_switch_stmt (tree);
extern tree finish_goto_stmt (tree);
extern tree begin_try_block (void);
extern void finish_try_block (tree);
extern void finish_handler_sequence (tree);
extern tree begin_function_try_block (tree *);
extern void finish_function_try_block (tree);
extern void finish_function_handler_sequence (tree, tree);
extern void finish_cleanup_try_block (tree);
extern tree begin_handler (void);
extern void finish_handler_parms (tree, tree);
extern void finish_handler (tree);
extern void finish_cleanup (tree, tree);
extern bool is_this_parameter (tree);
enum {
BCS_NORMAL = 0,
BCS_NO_SCOPE = 1,
BCS_TRY_BLOCK = 2,
BCS_FN_BODY = 4,
BCS_TRANSACTION = 8
};
extern tree begin_compound_stmt (unsigned int);
extern void finish_compound_stmt (tree);
extern tree finish_asm_stmt (int, tree, tree, tree, tree,
tree);
extern tree finish_label_stmt (tree);
extern void finish_label_decl (tree);
extern cp_expr finish_parenthesized_expr (cp_expr);
extern tree force_paren_expr (tree);
extern tree maybe_undo_parenthesized_ref (tree);
extern tree finish_non_static_data_member (tree, tree, tree);
extern tree begin_stmt_expr (void);
extern tree finish_stmt_expr_expr (tree, tree);
extern tree finish_stmt_expr (tree, bool);
extern tree stmt_expr_value_expr (tree);
bool empty_expr_stmt_p (tree);
extern cp_expr perform_koenig_lookup (cp_expr, vec<tree, va_gc> *,
tsubst_flags_t);
extern tree finish_call_expr (tree, vec<tree, va_gc> **, bool,
bool, tsubst_flags_t);
extern tree lookup_and_finish_template_variable (tree, tree, tsubst_flags_t = tf_warning_or_error);
extern tree finish_template_variable (tree, tsubst_flags_t = tf_warning_or_error);
extern cp_expr finish_increment_expr (cp_expr, enum tree_code);
extern tree finish_this_expr (void);
extern tree finish_pseudo_destructor_expr (tree, tree, tree, location_t);
extern cp_expr finish_unary_op_expr (location_t, enum tree_code, cp_expr,
tsubst_flags_t);
extern tree finish_compound_literal (tree, tree, tsubst_flags_t);
extern tree finish_fname (tree);
extern void finish_translation_unit (void);
extern tree finish_template_type_parm (tree, tree);
extern tree finish_template_template_parm (tree, tree);
extern tree begin_class_definition (tree);
extern void finish_template_decl (tree);
extern tree finish_template_type (tree, tree, int);
extern tree finish_base_specifier (tree, tree, bool);
extern void finish_member_declaration (tree);
extern bool outer_automatic_var_p (tree);
extern tree process_outer_var_ref (tree, tsubst_flags_t);
extern cp_expr finish_id_expression (tree, tree, tree,
cp_id_kind *,
bool, bool, bool *,
bool, bool, bool, bool,
const char **,
location_t);
extern tree finish_typeof (tree);
extern tree finish_underlying_type (tree);
extern tree calculate_bases (tree);
extern tree finish_bases (tree, bool);
extern tree calculate_direct_bases (tree);
extern tree finish_offsetof (tree, tree, location_t);
extern void finish_decl_cleanup (tree, tree);
extern void finish_eh_cleanup (tree);
extern void emit_associated_thunks (tree);
extern void finish_mem_initializers (tree);
extern tree check_template_template_default_arg (tree);
extern bool expand_or_defer_fn_1 (tree);
extern void expand_or_defer_fn (tree);
extern void add_typedef_to_current_template_for_access_check (tree, tree,
location_t);
extern void check_accessibility_of_qualified_id (tree, tree, tree);
extern tree finish_qualified_id_expr (tree, tree, bool, bool,
bool, bool, tsubst_flags_t);
extern void simplify_aggr_init_expr (tree *);
extern void finalize_nrv (tree *, tree, tree);
extern tree omp_reduction_id (enum tree_code, tree, tree);
extern tree cp_remove_omp_priv_cleanup_stmt (tree *, int *, void *);
extern void cp_check_omp_declare_reduction (tree);
extern void finish_omp_declare_simd_methods (tree);
extern tree finish_omp_clauses (tree, enum c_omp_region_type);
extern tree push_omp_privatization_clauses (bool);
extern void pop_omp_privatization_clauses (tree);
extern void save_omp_privatization_clauses (vec<tree> &);
extern void restore_omp_privatization_clauses (vec<tree> &);
extern void finish_omp_threadprivate (tree);
extern tree begin_omp_structured_block (void);
extern tree finish_omp_structured_block (tree);
extern tree finish_oacc_data (tree, tree);
extern tree finish_oacc_host_data (tree, tree);
extern tree finish_omp_construct (enum tree_code, tree, tree);
extern tree begin_omp_parallel (void);
extern tree finish_omp_parallel (tree, tree);
extern tree begin_omp_task (void);
extern tree finish_omp_task (tree, tree);
extern tree finish_omp_for (location_t, enum tree_code,
tree, tree, tree, tree, tree,
tree, tree, vec<tree> *, tree);
extern void finish_omp_atomic (enum tree_code, enum tree_code,
tree, tree, tree, tree, tree,
bool);
extern void finish_omp_barrier (void);
extern void finish_omp_flush (void);
extern void finish_omp_taskwait (void);
extern void finish_omp_taskyield (void);
extern void finish_omp_cancel (tree);
extern void finish_omp_cancellation_point (tree);
extern tree omp_privatize_field (tree, bool);
extern tree begin_transaction_stmt (location_t, tree *, int);
extern void finish_transaction_stmt (tree, tree, int, tree);
extern tree build_transaction_expr (location_t, tree, int, tree);
extern bool cxx_omp_create_clause_info (tree, tree, bool, bool,
bool, bool);
extern tree baselink_for_fns (tree);
extern void finish_static_assert (tree, tree, location_t,
bool);
extern tree finish_decltype_type (tree, bool, tsubst_flags_t);
extern tree finish_trait_expr (enum cp_trait_kind, tree, tree);
extern tree build_lambda_expr (void);
extern tree build_lambda_object (tree);
extern tree begin_lambda_type (tree);
extern tree lambda_capture_field_type (tree, bool, bool);
extern tree lambda_return_type (tree);
extern tree lambda_proxy_type (tree);
extern tree lambda_function (tree);
extern void apply_deduced_return_type (tree, tree);
extern tree add_capture (tree, tree, tree, bool, bool);
extern tree add_default_capture (tree, tree, tree);
extern tree build_capture_proxy (tree);
extern void insert_capture_proxy (tree);
extern void insert_pending_capture_proxies (void);
extern bool is_capture_proxy (tree);
extern bool is_normal_capture_proxy (tree);
extern void register_capture_members (tree);
extern tree lambda_expr_this_capture (tree, bool);
extern void maybe_generic_this_capture (tree, tree);
extern tree maybe_resolve_dummy (tree, bool);
extern tree current_nonlambda_function (void);
extern tree nonlambda_method_basetype (void);
extern tree current_nonlambda_scope (void);
extern bool generic_lambda_fn_p (tree);
extern void maybe_add_lambda_conv_op (tree);
extern bool is_lambda_ignored_entity (tree);
extern bool lambda_static_thunk_p (tree);
extern tree finish_builtin_launder (location_t, tree,
tsubst_flags_t);
/* in tree.c */
extern int cp_tree_operand_length (const_tree);
extern int cp_tree_code_length (enum tree_code);
void cp_free_lang_data (tree t);
extern tree force_target_expr (tree, tree, tsubst_flags_t);
extern tree build_target_expr_with_type (tree, tree, tsubst_flags_t);
extern void lang_check_failed (const char *, int,
const char *) ATTRIBUTE_NORETURN;
extern tree stabilize_expr (tree, tree *);
extern void stabilize_call (tree, tree *);
extern bool stabilize_init (tree, tree *);
extern tree add_stmt_to_compound (tree, tree);
extern void init_tree (void);
extern bool pod_type_p (const_tree);
extern bool layout_pod_type_p (const_tree);
extern bool std_layout_type_p (const_tree);
extern bool trivial_type_p (const_tree);
extern bool trivially_copyable_p (const_tree);
extern bool type_has_unique_obj_representations (const_tree);
extern bool scalarish_type_p (const_tree);
extern bool type_has_nontrivial_default_init (const_tree);
extern bool type_has_nontrivial_copy_init (const_tree);
extern bool class_tmpl_impl_spec_p (const_tree);
extern int zero_init_p (const_tree);
extern bool check_abi_tag_redeclaration (const_tree, const_tree, const_tree);
extern bool check_abi_tag_args (tree, tree);
extern tree strip_typedefs (tree, bool * = NULL);
extern tree strip_typedefs_expr (tree, bool * = NULL);
extern tree copy_binfo (tree, tree, tree,
tree *, int);
extern int member_p (const_tree);
extern cp_lvalue_kind real_lvalue_p (const_tree);
extern cp_lvalue_kind lvalue_kind (const_tree);
extern bool glvalue_p (const_tree);
extern bool obvalue_p (const_tree);
extern bool xvalue_p (const_tree);
extern bool bitfield_p (const_tree);
extern tree cp_stabilize_reference (tree);
extern bool builtin_valid_in_constant_expr_p (const_tree);
extern tree build_min (enum tree_code, tree, ...);
extern tree build_min_nt_loc (location_t, enum tree_code,
...);
extern tree build_min_non_dep (enum tree_code, tree, ...);
extern tree build_min_non_dep_op_overload (enum tree_code, tree, tree, ...);
extern tree build_min_non_dep_call_vec (tree, tree, vec<tree, va_gc> *);
extern vec<tree, va_gc>* vec_copy_and_insert (vec<tree, va_gc>*, tree, unsigned);
extern tree build_cplus_new (tree, tree, tsubst_flags_t);
extern tree build_aggr_init_expr (tree, tree);
extern tree get_target_expr (tree);
extern tree get_target_expr_sfinae (tree, tsubst_flags_t);
extern tree build_cplus_array_type (tree, tree);
extern tree build_array_of_n_type (tree, int);
extern bool array_of_runtime_bound_p (tree);
extern tree build_array_copy (tree);
extern tree build_vec_init_expr (tree, tree, tsubst_flags_t);
extern void diagnose_non_constexpr_vec_init (tree);
extern tree hash_tree_cons (tree, tree, tree);
extern tree hash_tree_chain (tree, tree);
extern tree build_qualified_name (tree, tree, tree, bool);
extern tree build_ref_qualified_type (tree, cp_ref_qualifier);
extern int is_overloaded_fn (tree);
extern tree dependent_name (tree);
extern tree get_fns (tree);
extern tree get_first_fn (tree);
extern tree ovl_cons (tree, tree);
extern tree build_overload (tree, tree);
extern tree ovl_scope (tree);
extern const char *cxx_printable_name (tree, int);
extern const char *cxx_printable_name_translate (tree, int);
extern tree canonical_eh_spec (tree);
extern tree build_exception_variant (tree, tree);
extern tree bind_template_template_parm (tree, tree);
extern tree array_type_nelts_total (tree);
extern tree array_type_nelts_top (tree);
extern tree break_out_target_exprs (tree);
extern tree build_ctor_subob_ref (tree, tree, tree);
extern tree replace_placeholders (tree, tree, bool * = NULL);
extern tree get_type_decl (tree);
extern tree decl_namespace_context (tree);
extern bool decl_anon_ns_mem_p (const_tree);
extern tree lvalue_type (tree);
extern tree error_type (tree);
extern int varargs_function_p (const_tree);
extern bool really_overloaded_fn (tree);
extern bool cp_tree_equal (tree, tree);
extern tree no_linkage_check (tree, bool);
extern void debug_binfo (tree);
extern tree build_dummy_object (tree);
extern tree maybe_dummy_object (tree, tree *);
extern int is_dummy_object (const_tree);
extern const struct attribute_spec cxx_attribute_table[];
extern tree make_ptrmem_cst (tree, tree);
extern tree cp_build_type_attribute_variant (tree, tree);
extern tree cp_build_reference_type (tree, bool);
extern tree move (tree);
extern tree cp_build_qualified_type_real (tree, int, tsubst_flags_t);
#define cp_build_qualified_type(TYPE, QUALS) \
cp_build_qualified_type_real ((TYPE), (QUALS), tf_warning_or_error)
extern bool cv_qualified_p (const_tree);
extern tree cv_unqualified (tree);
extern special_function_kind special_function_p (const_tree);
extern int count_trees (tree);
extern int char_type_p (tree);
extern void verify_stmt_tree (tree);
extern linkage_kind decl_linkage (tree);
extern duration_kind decl_storage_duration (tree);
extern tree cp_walk_subtrees (tree*, int*, walk_tree_fn,
void*, hash_set<tree> *);
#define cp_walk_tree(tp,func,data,pset) \
walk_tree_1 (tp, func, data, pset, cp_walk_subtrees)
#define cp_walk_tree_without_duplicates(tp,func,data) \
walk_tree_without_duplicates_1 (tp, func, data, cp_walk_subtrees)
extern tree rvalue (tree);
extern tree convert_bitfield_to_declared_type (tree);
extern tree cp_save_expr (tree);
extern bool cast_valid_in_integral_constant_expression_p (tree);
extern bool cxx_type_hash_eq (const_tree, const_tree);
extern void cxx_print_statistics (void);
extern bool maybe_warn_zero_as_null_pointer_constant (tree, location_t);
/* in ptree.c */
extern void cxx_print_xnode (FILE *, tree, int);
extern void cxx_print_decl (FILE *, tree, int);
extern void cxx_print_type (FILE *, tree, int);
extern void cxx_print_identifier (FILE *, tree, int);
extern void cxx_print_error_function (diagnostic_context *,
const char *,
struct diagnostic_info *);
/* in typeck.c */
extern bool cxx_mark_addressable (tree, bool = false);
extern int string_conv_p (const_tree, const_tree, int);
extern tree cp_truthvalue_conversion (tree);
extern tree condition_conversion (tree);
extern tree require_complete_type (tree);
extern tree require_complete_type_sfinae (tree, tsubst_flags_t);
extern tree complete_type (tree);
extern tree complete_type_or_else (tree, tree);
extern tree complete_type_or_maybe_complain (tree, tree, tsubst_flags_t);
extern int type_unknown_p (const_tree);
enum { ce_derived, ce_type, ce_normal, ce_exact };
extern bool comp_except_specs (const_tree, const_tree, int);
extern bool comptypes (tree, tree, int);
extern bool same_type_ignoring_top_level_qualifiers_p (tree, tree);
extern bool compparms (const_tree, const_tree);
extern int comp_cv_qualification (const_tree, const_tree);
extern int comp_cv_qualification (int, int);
extern int comp_cv_qual_signature (tree, tree);
extern tree cxx_sizeof_or_alignof_expr (tree, enum tree_code, bool);
extern tree cxx_sizeof_or_alignof_type (tree, enum tree_code, bool);
extern tree cxx_alignas_expr (tree);
extern tree cxx_sizeof_nowarn (tree);
extern tree is_bitfield_expr_with_lowered_type (const_tree);
extern tree unlowered_expr_type (const_tree);
extern tree decay_conversion (tree,
tsubst_flags_t,
bool = true);
extern tree build_class_member_access_expr (cp_expr, tree, tree, bool,
tsubst_flags_t);
extern tree finish_class_member_access_expr (cp_expr, tree, bool,
tsubst_flags_t);
extern tree build_x_indirect_ref (location_t, tree,
ref_operator, tsubst_flags_t);
extern tree cp_build_indirect_ref (tree, ref_operator,
tsubst_flags_t);
extern tree build_array_ref (location_t, tree, tree);
extern tree cp_build_array_ref (location_t, tree, tree,
tsubst_flags_t);
extern tree get_member_function_from_ptrfunc (tree *, tree, tsubst_flags_t);
extern tree cp_build_function_call_nary (tree, tsubst_flags_t, ...)
ATTRIBUTE_SENTINEL;
extern tree cp_build_function_call_vec (tree, vec<tree, va_gc> **,
tsubst_flags_t);
extern tree build_x_binary_op (location_t,
enum tree_code, tree,
enum tree_code, tree,
enum tree_code, tree *,
tsubst_flags_t);
extern tree build_x_array_ref (location_t, tree, tree,
tsubst_flags_t);
extern tree build_x_unary_op (location_t,
enum tree_code, cp_expr,
tsubst_flags_t);
extern tree cp_build_addressof (location_t, tree,
tsubst_flags_t);
extern tree cp_build_addr_expr (tree, tsubst_flags_t);
extern tree cp_build_unary_op (enum tree_code, tree, bool,
tsubst_flags_t);
extern tree unary_complex_lvalue (enum tree_code, tree);
extern tree build_x_conditional_expr (location_t, tree, tree, tree,
tsubst_flags_t);
extern tree build_x_compound_expr_from_list (tree, expr_list_kind,
tsubst_flags_t);
extern tree build_x_compound_expr_from_vec (vec<tree, va_gc> *,
const char *, tsubst_flags_t);
extern tree build_x_compound_expr (location_t, tree, tree,
tsubst_flags_t);
extern tree build_compound_expr (location_t, tree, tree);
extern tree cp_build_compound_expr (tree, tree, tsubst_flags_t);
extern tree build_static_cast (tree, tree, tsubst_flags_t);
extern tree build_reinterpret_cast (tree, tree, tsubst_flags_t);
extern tree build_const_cast (tree, tree, tsubst_flags_t);
extern tree build_c_cast (location_t, tree, tree);
extern cp_expr build_c_cast (location_t loc, tree type,
cp_expr expr);
extern tree cp_build_c_cast (tree, tree, tsubst_flags_t);
extern cp_expr build_x_modify_expr (location_t, tree,
enum tree_code, tree,
tsubst_flags_t);
extern tree cp_build_modify_expr (location_t, tree,
enum tree_code, tree,
tsubst_flags_t);
extern tree convert_for_initialization (tree, tree, tree, int,
impl_conv_rhs, tree, int,
tsubst_flags_t);
extern int comp_ptr_ttypes (tree, tree);
extern bool comp_ptr_ttypes_const (tree, tree);
extern bool error_type_p (const_tree);
extern bool ptr_reasonably_similar (const_tree, const_tree);
extern tree build_ptrmemfunc (tree, tree, int, bool,
tsubst_flags_t);
extern int cp_type_quals (const_tree);
extern int type_memfn_quals (const_tree);
extern cp_ref_qualifier type_memfn_rqual (const_tree);
extern tree apply_memfn_quals (tree, cp_cv_quals, cp_ref_qualifier);
extern bool cp_has_mutable_p (const_tree);
extern bool at_least_as_qualified_p (const_tree, const_tree);
extern void cp_apply_type_quals_to_decl (int, tree);
extern tree build_ptrmemfunc1 (tree, tree, tree);
extern void expand_ptrmemfunc_cst (tree, tree *, tree *);
extern tree type_after_usual_arithmetic_conversions (tree, tree);
extern tree common_pointer_type (tree, tree);
extern tree composite_pointer_type (tree, tree, tree, tree,
composite_pointer_operation,
tsubst_flags_t);
extern tree merge_types (tree, tree);
extern tree strip_array_domain (tree);
extern tree check_return_expr (tree, bool *);
extern tree cp_build_binary_op (location_t,
enum tree_code, tree, tree,
tsubst_flags_t);
extern tree build_x_vec_perm_expr (location_t,
tree, tree, tree,
tsubst_flags_t);
#define cxx_sizeof(T) cxx_sizeof_or_alignof_type (T, SIZEOF_EXPR, true)
extern tree build_simple_component_ref (tree, tree);
extern tree build_ptrmemfunc_access_expr (tree, tree);
extern tree build_address (tree);
extern tree build_nop (tree, tree);
extern tree non_reference (tree);
extern tree lookup_anon_field (tree, tree);
extern bool invalid_nonstatic_memfn_p (location_t, tree,
tsubst_flags_t);
extern tree convert_member_func_to_ptr (tree, tree, tsubst_flags_t);
extern tree convert_ptrmem (tree, tree, bool, bool,
tsubst_flags_t);
extern int lvalue_or_else (tree, enum lvalue_use,
tsubst_flags_t);
extern void check_template_keyword (tree);
extern bool check_raw_literal_operator (const_tree decl);
extern bool check_literal_operator_args (const_tree, bool *, bool *);
extern void maybe_warn_about_useless_cast (tree, tree, tsubst_flags_t);
extern tree cp_perform_integral_promotions (tree, tsubst_flags_t);
extern tree finish_left_unary_fold_expr (tree, int);
extern tree finish_right_unary_fold_expr (tree, int);
extern tree finish_binary_fold_expr (tree, tree, int);
/* in typeck2.c */
extern void require_complete_eh_spec_types (tree, tree);
extern void cxx_incomplete_type_diagnostic (location_t, const_tree,
const_tree, diagnostic_t);
inline void
cxx_incomplete_type_diagnostic (const_tree value, const_tree type,
diagnostic_t diag_kind)
{
cxx_incomplete_type_diagnostic (EXPR_LOC_OR_LOC (value, input_location),
value, type, diag_kind);
}
extern void cxx_incomplete_type_error (location_t, const_tree,
const_tree);
inline void
cxx_incomplete_type_error (const_tree value, const_tree type)
{
cxx_incomplete_type_diagnostic (value, type, DK_ERROR);
}
extern void cxx_incomplete_type_inform (const_tree);
extern tree error_not_base_type (tree, tree);
extern tree binfo_or_else (tree, tree);
extern void cxx_readonly_error (tree, enum lvalue_use);
extern void complete_type_check_abstract (tree);
extern int abstract_virtuals_error (tree, tree);
extern int abstract_virtuals_error (abstract_class_use, tree);
extern int abstract_virtuals_error_sfinae (tree, tree, tsubst_flags_t);
extern int abstract_virtuals_error_sfinae (abstract_class_use, tree, tsubst_flags_t);
extern tree store_init_value (tree, tree, vec<tree, va_gc>**, int);
extern tree split_nonconstant_init (tree, tree);
extern bool check_narrowing (tree, tree, tsubst_flags_t);
extern tree digest_init (tree, tree, tsubst_flags_t);
extern tree digest_init_flags (tree, tree, int, tsubst_flags_t);
extern tree digest_nsdmi_init (tree, tree);
extern tree build_scoped_ref (tree, tree, tree *);
extern tree build_x_arrow (location_t, tree,
tsubst_flags_t);
extern tree build_m_component_ref (tree, tree, tsubst_flags_t);
extern tree build_functional_cast (tree, tree, tsubst_flags_t);
extern tree add_exception_specifier (tree, tree, int);
extern tree merge_exception_specifiers (tree, tree);
/* in mangle.c */
extern bool maybe_remove_implicit_alias (tree);
extern void init_mangle (void);
extern void mangle_decl (tree);
extern const char *mangle_type_string (tree);
extern tree mangle_typeinfo_for_type (tree);
extern tree mangle_typeinfo_string_for_type (tree);
extern tree mangle_vtbl_for_type (tree);
extern tree mangle_vtt_for_type (tree);
extern tree mangle_ctor_vtbl_for_type (tree, tree);
extern tree mangle_thunk (tree, int, tree, tree, tree);
extern tree mangle_conv_op_name_for_type (tree);
extern tree mangle_guard_variable (tree);
extern tree mangle_tls_init_fn (tree);
extern tree mangle_tls_wrapper_fn (tree);
extern bool decl_tls_wrapper_p (tree);
extern tree mangle_ref_init_variable (tree);
extern char * get_mangled_vtable_map_var_name (tree);
extern bool mangle_return_type_p (tree);
extern tree mangle_decomp (tree, vec<tree> &);
/* in dump.c */
extern bool cp_dump_tree (void *, tree);
/* In cp/cp-objcp-common.c. */
extern alias_set_type cxx_get_alias_set (tree);
extern bool cxx_warn_unused_global_decl (const_tree);
extern size_t cp_tree_size (enum tree_code);
extern bool cp_var_mod_type_p (tree, tree);
extern void cxx_initialize_diagnostics (diagnostic_context *);
extern int cxx_types_compatible_p (tree, tree);
extern void init_shadowed_var_for_decl (void);
extern bool cxx_block_may_fallthru (const_tree);
/* in cp-gimplify.c */
extern int cp_gimplify_expr (tree *, gimple_seq *,
gimple_seq *);
extern void cp_genericize (tree);
extern bool cxx_omp_const_qual_no_mutable (tree);
extern enum omp_clause_default_kind cxx_omp_predetermined_sharing (tree);
extern tree cxx_omp_clause_default_ctor (tree, tree, tree);
extern tree cxx_omp_clause_copy_ctor (tree, tree, tree);
extern tree cxx_omp_clause_assign_op (tree, tree, tree);
extern tree cxx_omp_clause_dtor (tree, tree);
extern void cxx_omp_finish_clause (tree, gimple_seq *);
extern bool cxx_omp_privatize_by_reference (const_tree);
extern bool cxx_omp_disregard_value_expr (tree, bool);
extern void cp_fold_function (tree);
extern tree cp_fully_fold (tree);
extern void clear_fold_cache (void);
/* in name-lookup.c */
extern void suggest_alternatives_for (location_t, tree, bool);
extern bool suggest_alternative_in_explicit_scope (location_t, tree, tree);
extern tree strip_using_decl (tree);
/* Tell the binding oracle what kind of binding we are looking for. */
enum cp_oracle_request
{
CP_ORACLE_IDENTIFIER
};
/* If this is non-NULL, then it is a "binding oracle" which can lazily
create bindings when needed by the C compiler. The oracle is told
the name and type of the binding to create. It can call pushdecl
or the like to ensure the binding is visible; or do nothing,
leaving the binding untouched. c-decl.c takes note of when the
oracle has been called and will not call it again if it fails to
create a given binding. */
typedef void cp_binding_oracle_function (enum cp_oracle_request, tree identifier);
extern cp_binding_oracle_function *cp_binding_oracle;
/* in constraint.cc */
extern void init_constraint_processing ();
extern bool constraint_p (tree);
extern tree conjoin_constraints (tree, tree);
extern tree conjoin_constraints (tree);
extern tree get_constraints (tree);
extern void set_constraints (tree, tree);
extern void remove_constraints (tree);
extern tree current_template_constraints (void);
extern tree associate_classtype_constraints (tree);
extern tree build_constraints (tree, tree);
extern tree get_shorthand_constraints (tree);
extern tree build_concept_check (tree, tree, tree = NULL_TREE);
extern tree build_constrained_parameter (tree, tree, tree = NULL_TREE);
extern tree make_constrained_auto (tree, tree);
extern void placeholder_extract_concept_and_args (tree, tree&, tree&);
extern bool equivalent_placeholder_constraints (tree, tree);
extern hashval_t hash_placeholder_constraint (tree);
extern bool deduce_constrained_parameter (tree, tree&, tree&);
extern tree resolve_constraint_check (tree);
extern tree check_function_concept (tree);
extern tree finish_template_introduction (tree, tree);
extern bool valid_requirements_p (tree);
extern tree finish_concept_name (tree);
extern tree finish_shorthand_constraint (tree, tree);
extern tree finish_requires_expr (tree, tree);
extern tree finish_simple_requirement (tree);
extern tree finish_type_requirement (tree);
extern tree finish_compound_requirement (tree, tree, bool);
extern tree finish_nested_requirement (tree);
extern void check_constrained_friend (tree, tree);
extern tree tsubst_requires_expr (tree, tree, tsubst_flags_t, tree);
extern tree tsubst_constraint (tree, tree, tsubst_flags_t, tree);
extern tree tsubst_constraint_info (tree, tree, tsubst_flags_t, tree);
extern bool function_concept_check_p (tree);
extern tree normalize_expression (tree);
extern tree expand_concept (tree, tree);
extern bool expanding_concept ();
extern tree evaluate_constraints (tree, tree);
extern tree evaluate_function_concept (tree, tree);
extern tree evaluate_variable_concept (tree, tree);
extern tree evaluate_constraint_expression (tree, tree);
extern bool constraints_satisfied_p (tree);
extern bool constraints_satisfied_p (tree, tree);
extern tree lookup_constraint_satisfaction (tree, tree);
extern tree memoize_constraint_satisfaction (tree, tree, tree);
extern tree lookup_concept_satisfaction (tree, tree);
extern tree memoize_concept_satisfaction (tree, tree, tree);
extern tree get_concept_expansion (tree, tree);
extern tree save_concept_expansion (tree, tree, tree);
extern bool* lookup_subsumption_result (tree, tree);
extern bool save_subsumption_result (tree, tree, bool);
extern bool equivalent_constraints (tree, tree);
extern bool equivalently_constrained (tree, tree);
extern bool subsumes_constraints (tree, tree);
extern bool strictly_subsumes (tree, tree);
extern int more_constrained (tree, tree);
extern void diagnose_constraints (location_t, tree, tree);
/* in logic.cc */
extern tree decompose_conclusions (tree);
extern bool subsumes (tree, tree);
/* In class.c */
extern void cp_finish_injected_record_type (tree);
/* in vtable-class-hierarchy.c */
extern void vtv_compute_class_hierarchy_transitive_closure (void);
extern void vtv_generate_init_routine (void);
extern void vtv_save_class_info (tree);
extern void vtv_recover_class_info (void);
extern void vtv_build_vtable_verify_fndecl (void);
/* In cp/cp-array-notations.c */
extern tree expand_array_notation_exprs (tree);
bool cilkplus_an_triplet_types_ok_p (location_t, tree, tree, tree,
tree);
/* In constexpr.c */
extern void fini_constexpr (void);
extern bool literal_type_p (tree);
extern tree register_constexpr_fundef (tree, tree);
extern bool is_valid_constexpr_fn (tree, bool);
extern bool check_constexpr_ctor_body (tree, tree, bool);
extern tree ensure_literal_type_for_constexpr_object (tree);
extern bool potential_constant_expression (tree);
extern bool potential_nondependent_constant_expression (tree);
extern bool potential_nondependent_static_init_expression (tree);
extern bool potential_static_init_expression (tree);
extern bool potential_rvalue_constant_expression (tree);
extern bool require_potential_constant_expression (tree);
extern bool require_potential_rvalue_constant_expression (tree);
extern tree cxx_constant_value (tree, tree = NULL_TREE);
extern tree maybe_constant_value (tree, tree = NULL_TREE);
extern tree maybe_constant_init (tree, tree = NULL_TREE);
extern tree fold_non_dependent_expr (tree);
extern tree fold_simple (tree);
extern bool is_sub_constant_expr (tree);
extern bool reduced_constant_expression_p (tree);
extern bool is_instantiation_of_constexpr (tree);
extern bool var_in_constexpr_fn (tree);
extern bool var_in_maybe_constexpr_fn (tree);
extern void explain_invalid_constexpr_fn (tree);
extern vec<tree> cx_error_context (void);
extern tree fold_sizeof_expr (tree);
extern void clear_cv_and_fold_caches (void);
/* In c-family/cilk.c */
extern bool cilk_valid_spawn (tree);
/* In cp-ubsan.c */
extern void cp_ubsan_maybe_instrument_member_call (tree);
extern void cp_ubsan_instrument_member_accesses (tree *);
extern tree cp_ubsan_maybe_instrument_downcast (location_t, tree, tree, tree);
extern tree cp_ubsan_maybe_instrument_cast_to_vbase (location_t, tree, tree);
extern void cp_ubsan_maybe_initialize_vtbl_ptrs (tree);
/* -- end of C++ */
#endif /* ! GCC_CP_TREE_H */
|
c-tree.h
|
/* Definitions for C parsing and type checking.
Copyright (C) 1987-2014 Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 3, or (at your option) any later
version.
GCC 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 GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
#ifndef GCC_C_TREE_H
#define GCC_C_TREE_H
#include "c-family/c-common.h"
#include "diagnostic.h"
/* struct lang_identifier is private to c-decl.c, but langhooks.c needs to
know how big it is. This is sanity-checked in c-decl.c. */
#define C_SIZEOF_STRUCT_LANG_IDENTIFIER \
(sizeof (struct c_common_identifier) + 3 * sizeof (void *))
/* In a RECORD_TYPE or UNION_TYPE, nonzero if any component is read-only. */
#define C_TYPE_FIELDS_READONLY(TYPE) TREE_LANG_FLAG_1 (TYPE)
/* In a RECORD_TYPE or UNION_TYPE, nonzero if any component is volatile. */
#define C_TYPE_FIELDS_VOLATILE(TYPE) TREE_LANG_FLAG_2 (TYPE)
/* In a RECORD_TYPE or UNION_TYPE or ENUMERAL_TYPE
nonzero if the definition of the type has already started. */
#define C_TYPE_BEING_DEFINED(TYPE) TYPE_LANG_FLAG_0 (TYPE)
/* In an incomplete RECORD_TYPE or UNION_TYPE, a list of variable
declarations whose type would be completed by completing that type. */
#define C_TYPE_INCOMPLETE_VARS(TYPE) TYPE_VFIELD (TYPE)
/* In an IDENTIFIER_NODE, nonzero if this identifier is actually a
keyword. C_RID_CODE (node) is then the RID_* value of the keyword,
and C_RID_YYCODE is the token number wanted by Yacc. */
#define C_IS_RESERVED_WORD(ID) TREE_LANG_FLAG_0 (ID)
/* Record whether a type or decl was written with nonconstant size.
Note that TYPE_SIZE may have simplified to a constant. */
#define C_TYPE_VARIABLE_SIZE(TYPE) TYPE_LANG_FLAG_1 (TYPE)
#define C_DECL_VARIABLE_SIZE(TYPE) DECL_LANG_FLAG_0 (TYPE)
/* Record whether a type is defined inside a struct or union type.
This is used for -Wc++-compat. */
#define C_TYPE_DEFINED_IN_STRUCT(TYPE) TYPE_LANG_FLAG_2 (TYPE)
/* Record whether a typedef for type `int' was actually `signed int'. */
#define C_TYPEDEF_EXPLICITLY_SIGNED(EXP) DECL_LANG_FLAG_1 (EXP)
/* For a FUNCTION_DECL, nonzero if it was defined without an explicit
return type. */
#define C_FUNCTION_IMPLICIT_INT(EXP) DECL_LANG_FLAG_1 (EXP)
/* For a FUNCTION_DECL, nonzero if it was an implicit declaration. */
#define C_DECL_IMPLICIT(EXP) DECL_LANG_FLAG_2 (EXP)
/* For FUNCTION_DECLs, evaluates true if the decl is built-in but has
been declared. */
#define C_DECL_DECLARED_BUILTIN(EXP) \
DECL_LANG_FLAG_3 (FUNCTION_DECL_CHECK (EXP))
/* For FUNCTION_DECLs, evaluates true if the decl is built-in, has a
built-in prototype and does not have a non-built-in prototype. */
#define C_DECL_BUILTIN_PROTOTYPE(EXP) \
DECL_LANG_FLAG_6 (FUNCTION_DECL_CHECK (EXP))
/* Record whether a decl was declared register. This is strictly a
front-end flag, whereas DECL_REGISTER is used for code generation;
they may differ for structures with volatile fields. */
#define C_DECL_REGISTER(EXP) DECL_LANG_FLAG_4 (EXP)
/* Record whether a decl was used in an expression anywhere except an
unevaluated operand of sizeof / typeof / alignof. This is only
used for functions declared static but not defined, though outside
sizeof and typeof it is set for other function decls as well. */
#define C_DECL_USED(EXP) DECL_LANG_FLAG_5 (FUNCTION_DECL_CHECK (EXP))
/* Record whether a variable has been declared threadprivate by
#pragma omp threadprivate. */
#define C_DECL_THREADPRIVATE_P(DECL) DECL_LANG_FLAG_3 (VAR_DECL_CHECK (DECL))
/* Nonzero for a decl which either doesn't exist or isn't a prototype.
N.B. Could be simplified if all built-in decls had complete prototypes
(but this is presently difficult because some of them need FILE*). */
#define C_DECL_ISNT_PROTOTYPE(EXP) \
(EXP == 0 \
|| (!prototype_p (TREE_TYPE (EXP)) \
&& !DECL_BUILT_IN (EXP)))
/* For FUNCTION_TYPE, a hidden list of types of arguments. The same as
TYPE_ARG_TYPES for functions with prototypes, but created for functions
without prototypes. */
#define TYPE_ACTUAL_ARG_TYPES(NODE) TYPE_LANG_SLOT_1 (NODE)
/* For a CONSTRUCTOR, whether some initializer contains a
subexpression meaning it is not a constant expression. */
#define CONSTRUCTOR_NON_CONST(EXPR) TREE_LANG_FLAG_1 (CONSTRUCTOR_CHECK (EXPR))
/* Record parser information about an expression that is irrelevant
for code generation alongside a tree representing its value. */
struct c_expr
{
/* The value of the expression. */
tree value;
/* Record the original unary/binary operator of an expression, which may
have been changed by fold, STRING_CST for unparenthesized string
constants, C_MAYBE_CONST_EXPR for __builtin_constant_p calls
(even if parenthesized), for subexpressions, and for non-constant
initializers, or ERROR_MARK for other expressions (including
parenthesized expressions). */
enum tree_code original_code;
/* If not NULL, the original type of an expression. This will
differ from the type of the value field for an enum constant.
The type of an enum constant is a plain integer type, but this
field will be the enum type. */
tree original_type;
};
/* Type alias for struct c_expr. This allows to use the structure
inside the VEC types. */
typedef struct c_expr c_expr_t;
/* A kind of type specifier. Note that this information is currently
only used to distinguish tag definitions, tag references and typeof
uses. */
enum c_typespec_kind {
/* No typespec. This appears only in struct c_declspec. */
ctsk_none,
/* A reserved keyword type specifier. */
ctsk_resword,
/* A reference to a tag, previously declared, such as "struct foo".
This includes where the previous declaration was as a different
kind of tag, in which case this is only valid if shadowing that
tag in an inner scope. */
ctsk_tagref,
/* A reference to a tag, not previously declared in a visible
scope. */
ctsk_tagfirstref,
/* A definition of a tag such as "struct foo { int a; }". */
ctsk_tagdef,
/* A typedef name. */
ctsk_typedef,
/* An ObjC-specific kind of type specifier. */
ctsk_objc,
/* A typeof specifier, or _Atomic ( type-name ). */
ctsk_typeof
};
/* A type specifier: this structure is created in the parser and
passed to declspecs_add_type only. */
struct c_typespec {
/* What kind of type specifier this is. */
enum c_typespec_kind kind;
/* Whether the expression has operands suitable for use in constant
expressions. */
bool expr_const_operands;
/* The specifier itself. */
tree spec;
/* An expression to be evaluated before the type specifier, in the
case of typeof specifiers, or NULL otherwise or if no such
expression is required for a particular typeof specifier. In
particular, when typeof is applied to an expression of variably
modified type, that expression must be evaluated in order to
determine array sizes that form part of the type, but the
expression itself (as opposed to the array sizes) forms no part
of the type and so needs to be recorded separately. */
tree expr;
};
/* A storage class specifier. */
enum c_storage_class {
csc_none,
csc_auto,
csc_extern,
csc_register,
csc_static,
csc_typedef
};
/* A type specifier keyword "void", "_Bool", "char", "int", "float",
"double", "_Decimal32", "_Decimal64", "_Decimal128", "_Fract", "_Accum",
or none of these. */
enum c_typespec_keyword {
cts_none,
cts_void,
cts_bool,
cts_char,
cts_int,
cts_float,
cts_int128,
cts_double,
cts_dfloat32,
cts_dfloat64,
cts_dfloat128,
cts_fract,
cts_accum,
cts_auto_type
};
/* This enum lists all the possible declarator specifiers, storage
class or attribute that a user can write. There is at least one
enumerator per possible declarator specifier in the struct
c_declspecs below.
It is used to index the array of declspec locations in struct
c_declspecs. */
enum c_declspec_word {
cdw_typespec /* A catch-all for a typespec. */,
cdw_storage_class /* A catch-all for a storage class */,
cdw_attributes,
cdw_typedef,
cdw_explicit_signed,
cdw_deprecated,
cdw_default_int,
cdw_long,
cdw_long_long,
cdw_short,
cdw_signed,
cdw_unsigned,
cdw_complex,
cdw_inline,
cdw_noreturn,
cdw_thread,
cdw_const,
cdw_volatile,
cdw_restrict,
cdw_saturating,
cdw_alignas,
cdw_address_space,
cdw_number_of_elements /* This one must always be the last
enumerator. */
};
/* A sequence of declaration specifiers in C. When a new declaration
specifier is added, please update the enum c_declspec_word above
accordingly. */
struct c_declspecs {
source_location locations[cdw_number_of_elements];
/* The type specified, if a single type specifier such as a struct,
union or enum specifier, typedef name or typeof specifies the
whole type, or NULL_TREE if none or a keyword such as "void" or
"char" is used. Does not include qualifiers. */
tree type;
/* Any expression to be evaluated before the type, from a typeof
specifier. */
tree expr;
/* The attributes from a typedef decl. */
tree decl_attr;
/* When parsing, the attributes. Outside the parser, this will be
NULL; attributes (possibly from multiple lists) will be passed
separately. */
tree attrs;
/* The base-2 log of the greatest alignment required by an _Alignas
specifier, in bytes, or -1 if no such specifiers with nonzero
alignment. */
int align_log;
/* The storage class specifier, or csc_none if none. */
enum c_storage_class storage_class;
/* Any type specifier keyword used such as "int", not reflecting
modifiers such as "short", or cts_none if none. */
ENUM_BITFIELD (c_typespec_keyword) typespec_word : 8;
/* The kind of type specifier if one has been seen, ctsk_none
otherwise. */
ENUM_BITFIELD (c_typespec_kind) typespec_kind : 3;
/* Whether any expressions in typeof specifiers may appear in
constant expressions. */
BOOL_BITFIELD expr_const_operands : 1;
/* Whether any declaration specifiers have been seen at all. */
BOOL_BITFIELD declspecs_seen_p : 1;
/* Whether something other than a storage class specifier or
attribute has been seen. This is used to warn for the
obsolescent usage of storage class specifiers other than at the
start of the list. (Doing this properly would require function
specifiers to be handled separately from storage class
specifiers.) */
BOOL_BITFIELD non_sc_seen_p : 1;
/* Whether the type is specified by a typedef or typeof name. */
BOOL_BITFIELD typedef_p : 1;
/* Whether the type is explicitly "signed" or specified by a typedef
whose type is explicitly "signed". */
BOOL_BITFIELD explicit_signed_p : 1;
/* Whether the specifiers include a deprecated typedef. */
BOOL_BITFIELD deprecated_p : 1;
/* Whether the type defaulted to "int" because there were no type
specifiers. */
BOOL_BITFIELD default_int_p : 1;
/* Whether "long" was specified. */
BOOL_BITFIELD long_p : 1;
/* Whether "long" was specified more than once. */
BOOL_BITFIELD long_long_p : 1;
/* Whether "short" was specified. */
BOOL_BITFIELD short_p : 1;
/* Whether "signed" was specified. */
BOOL_BITFIELD signed_p : 1;
/* Whether "unsigned" was specified. */
BOOL_BITFIELD unsigned_p : 1;
/* Whether "complex" was specified. */
BOOL_BITFIELD complex_p : 1;
/* Whether "inline" was specified. */
BOOL_BITFIELD inline_p : 1;
/* Whether "_Noreturn" was speciied. */
BOOL_BITFIELD noreturn_p : 1;
/* Whether "__thread" or "_Thread_local" was specified. */
BOOL_BITFIELD thread_p : 1;
/* Whether "__thread" rather than "_Thread_local" was specified. */
BOOL_BITFIELD thread_gnu_p : 1;
/* Whether "const" was specified. */
BOOL_BITFIELD const_p : 1;
/* Whether "volatile" was specified. */
BOOL_BITFIELD volatile_p : 1;
/* Whether "restrict" was specified. */
BOOL_BITFIELD restrict_p : 1;
/* Whether "_Atomic" was specified. */
BOOL_BITFIELD atomic_p : 1;
/* Whether "_Sat" was specified. */
BOOL_BITFIELD saturating_p : 1;
/* Whether any alignment specifier (even with zero alignment) was
specified. */
BOOL_BITFIELD alignas_p : 1;
/* The address space that the declaration belongs to. */
addr_space_t address_space;
};
/* The various kinds of declarators in C. */
enum c_declarator_kind {
/* An identifier. */
cdk_id,
/* A function. */
cdk_function,
/* An array. */
cdk_array,
/* A pointer. */
cdk_pointer,
/* Parenthesized declarator with nested attributes. */
cdk_attrs
};
typedef struct c_arg_tag_d {
/* The argument name. */
tree id;
/* The type of the argument. */
tree type;
} c_arg_tag;
/* Information about the parameters in a function declarator. */
struct c_arg_info {
/* A list of parameter decls. */
tree parms;
/* A list of structure, union and enum tags defined. */
vec<c_arg_tag, va_gc> *tags;
/* A list of argument types to go in the FUNCTION_TYPE. */
tree types;
/* A list of non-parameter decls (notably enumeration constants)
defined with the parameters. */
tree others;
/* A compound expression of VLA sizes from the parameters, or NULL.
In a function definition, these are used to ensure that
side-effects in sizes of arrays converted to pointers (such as a
parameter int i[n++]) take place; otherwise, they are
ignored. */
tree pending_sizes;
/* True when these arguments had [*]. */
BOOL_BITFIELD had_vla_unspec : 1;
};
/* A declarator. */
struct c_declarator {
/* The kind of declarator. */
enum c_declarator_kind kind;
location_t id_loc; /* Currently only set for cdk_id, cdk_array. */
/* Except for cdk_id, the contained declarator. For cdk_id, NULL. */
struct c_declarator *declarator;
union {
/* For identifiers, an IDENTIFIER_NODE or NULL_TREE if an abstract
declarator. */
tree id;
/* For functions. */
struct c_arg_info *arg_info;
/* For arrays. */
struct {
/* The array dimension, or NULL for [] and [*]. */
tree dimen;
/* The qualifiers inside []. */
int quals;
/* The attributes (currently ignored) inside []. */
tree attrs;
/* Whether [static] was used. */
BOOL_BITFIELD static_p : 1;
/* Whether [*] was used. */
BOOL_BITFIELD vla_unspec_p : 1;
} array;
/* For pointers, the qualifiers on the pointer type. */
int pointer_quals;
/* For attributes. */
tree attrs;
} u;
};
/* A type name. */
struct c_type_name {
/* The declaration specifiers. */
struct c_declspecs *specs;
/* The declarator. */
struct c_declarator *declarator;
};
/* A parameter. */
struct c_parm {
/* The declaration specifiers, minus any prefix attributes. */
struct c_declspecs *specs;
/* The attributes. */
tree attrs;
/* The declarator. */
struct c_declarator *declarator;
};
/* Used when parsing an enum. Initialized by start_enum. */
struct c_enum_contents
{
/* While defining an enum type, this is 1 plus the last enumerator
constant value. */
tree enum_next_value;
/* Nonzero means that there was overflow computing enum_next_value. */
int enum_overflow;
};
/* A type of reference to a static identifier in an inline
function. */
enum c_inline_static_type {
/* Identifier with internal linkage used in function that may be an
inline definition (i.e., file-scope static). */
csi_internal,
/* Modifiable object with static storage duration defined in
function that may be an inline definition (i.e., local
static). */
csi_modifiable
};
/* in c-parser.c */
extern void c_parse_init (void);
/* in c-aux-info.c */
extern void gen_aux_info_record (tree, int, int, int);
/* in c-decl.c */
struct c_spot_bindings;
struct c_struct_parse_info;
extern struct obstack parser_obstack;
extern tree c_break_label;
extern tree c_cont_label;
extern bool global_bindings_p (void);
extern void push_scope (void);
extern tree pop_scope (void);
extern void c_bindings_start_stmt_expr (struct c_spot_bindings *);
extern void c_bindings_end_stmt_expr (struct c_spot_bindings *);
extern void record_inline_static (location_t, tree, tree,
enum c_inline_static_type);
extern void c_init_decl_processing (void);
extern void c_print_identifier (FILE *, tree, int);
extern int quals_from_declspecs (const struct c_declspecs *);
extern struct c_declarator *build_array_declarator (location_t, tree,
struct c_declspecs *,
bool, bool);
extern tree build_enumerator (location_t, location_t, struct c_enum_contents *,
tree, tree);
extern tree check_for_loop_decls (location_t, bool);
extern void mark_forward_parm_decls (void);
extern void declare_parm_level (void);
extern void undeclared_variable (location_t, tree);
extern tree lookup_label_for_goto (location_t, tree);
extern tree declare_label (tree);
extern tree define_label (location_t, tree);
extern struct c_spot_bindings *c_get_switch_bindings (void);
extern void c_release_switch_bindings (struct c_spot_bindings *);
extern bool c_check_switch_jump_warnings (struct c_spot_bindings *,
location_t, location_t);
extern void finish_decl (tree, location_t, tree, tree, tree);
extern tree finish_enum (tree, tree, tree);
extern void finish_function (void);
extern tree finish_struct (location_t, tree, tree, tree,
struct c_struct_parse_info *);
extern struct c_arg_info *build_arg_info (void);
extern struct c_arg_info *get_parm_info (bool, tree);
extern tree grokfield (location_t, struct c_declarator *,
struct c_declspecs *, tree, tree *);
extern tree groktypename (struct c_type_name *, tree *, bool *);
extern tree grokparm (const struct c_parm *, tree *);
extern tree implicitly_declare (location_t, tree);
extern void keep_next_level (void);
extern void pending_xref_error (void);
extern void c_push_function_context (void);
extern void c_pop_function_context (void);
extern void push_parm_decl (const struct c_parm *, tree *);
extern struct c_declarator *set_array_declarator_inner (struct c_declarator *,
struct c_declarator *);
extern tree c_builtin_function (tree);
extern tree c_builtin_function_ext_scope (tree);
extern void shadow_tag (const struct c_declspecs *);
extern void shadow_tag_warned (const struct c_declspecs *, int);
extern tree start_enum (location_t, struct c_enum_contents *, tree);
extern int start_function (struct c_declspecs *, struct c_declarator *, tree);
extern tree start_decl (struct c_declarator *, struct c_declspecs *, bool,
tree);
extern tree start_struct (location_t, enum tree_code, tree,
struct c_struct_parse_info **);
extern void store_parm_decls (void);
extern void store_parm_decls_from (struct c_arg_info *);
extern void temp_store_parm_decls (tree, tree);
extern void temp_pop_parm_decls (void);
extern tree xref_tag (enum tree_code, tree);
extern struct c_typespec parser_xref_tag (location_t, enum tree_code, tree);
extern struct c_parm *build_c_parm (struct c_declspecs *, tree,
struct c_declarator *);
extern struct c_declarator *build_attrs_declarator (tree,
struct c_declarator *);
extern struct c_declarator *build_function_declarator (struct c_arg_info *,
struct c_declarator *);
extern struct c_declarator *build_id_declarator (tree);
extern struct c_declarator *make_pointer_declarator (struct c_declspecs *,
struct c_declarator *);
extern struct c_declspecs *build_null_declspecs (void);
extern struct c_declspecs *declspecs_add_qual (source_location,
struct c_declspecs *, tree);
extern struct c_declspecs *declspecs_add_type (location_t,
struct c_declspecs *,
struct c_typespec);
extern struct c_declspecs *declspecs_add_scspec (source_location,
struct c_declspecs *, tree);
extern struct c_declspecs *declspecs_add_attrs (source_location,
struct c_declspecs *, tree);
extern struct c_declspecs *declspecs_add_addrspace (source_location,
struct c_declspecs *,
addr_space_t);
extern struct c_declspecs *declspecs_add_alignas (source_location,
struct c_declspecs *, tree);
extern struct c_declspecs *finish_declspecs (struct c_declspecs *);
/* in c-objc-common.c */
extern bool c_objc_common_init (void);
extern bool c_missing_noreturn_ok_p (tree);
extern bool c_warn_unused_global_decl (const_tree);
extern void c_initialize_diagnostics (diagnostic_context *);
extern bool c_vla_unspec_p (tree x, tree fn);
/* in c-typeck.c */
extern int in_alignof;
extern int in_sizeof;
extern int in_typeof;
extern tree c_last_sizeof_arg;
extern struct c_switch *c_switch_stack;
extern tree c_objc_common_truthvalue_conversion (location_t, tree);
extern tree require_complete_type (tree);
extern int same_translation_unit_p (const_tree, const_tree);
extern int comptypes (tree, tree);
extern int comptypes_check_different_types (tree, tree, bool *);
extern bool c_vla_type_p (const_tree);
extern bool c_mark_addressable (tree);
extern void c_incomplete_type_error (const_tree, const_tree);
extern tree c_type_promotes_to (tree);
extern struct c_expr default_function_array_conversion (location_t,
struct c_expr);
extern struct c_expr default_function_array_read_conversion (location_t,
struct c_expr);
extern struct c_expr convert_lvalue_to_rvalue (location_t, struct c_expr,
bool, bool);
extern void mark_exp_read (tree);
extern tree composite_type (tree, tree);
extern tree build_component_ref (location_t, tree, tree);
extern tree build_array_ref (location_t, tree, tree);
extern tree build_external_ref (location_t, tree, int, tree *);
extern void pop_maybe_used (bool);
extern struct c_expr c_expr_sizeof_expr (location_t, struct c_expr);
extern struct c_expr c_expr_sizeof_type (location_t, struct c_type_name *);
extern struct c_expr parser_build_unary_op (location_t, enum tree_code,
struct c_expr);
extern struct c_expr parser_build_binary_op (location_t,
enum tree_code, struct c_expr,
struct c_expr);
extern tree build_conditional_expr (location_t, tree, bool, tree, tree,
tree, tree);
extern tree build_compound_expr (location_t, tree, tree);
extern tree c_cast_expr (location_t, struct c_type_name *, tree);
extern tree build_c_cast (location_t, tree, tree);
extern void store_init_value (location_t, tree, tree, tree);
extern void error_init (const char *);
extern void pedwarn_init (location_t, int opt, const char *);
extern void maybe_warn_string_init (tree, struct c_expr);
extern void start_init (tree, tree, int);
extern void finish_init (void);
extern void really_start_incremental_init (tree);
extern void push_init_level (int, struct obstack *);
extern struct c_expr pop_init_level (int, struct obstack *);
extern void set_init_index (tree, tree, struct obstack *);
extern void set_init_label (tree, struct obstack *);
extern void process_init_element (location_t, struct c_expr, bool,
struct obstack *);
extern tree build_compound_literal (location_t, tree, tree, bool);
extern void check_compound_literal_type (location_t, struct c_type_name *);
extern tree c_start_case (location_t, location_t, tree);
extern void c_finish_case (tree);
extern tree build_asm_expr (location_t, tree, tree, tree, tree, tree, bool);
extern tree build_asm_stmt (tree, tree);
extern int c_types_compatible_p (tree, tree);
extern tree c_begin_compound_stmt (bool);
extern tree c_end_compound_stmt (location_t, tree, bool);
extern void c_finish_if_stmt (location_t, tree, tree, tree, bool);
extern void c_finish_loop (location_t, tree, tree, tree, tree, tree, bool);
extern tree c_begin_stmt_expr (void);
extern tree c_finish_stmt_expr (location_t, tree);
extern tree c_process_expr_stmt (location_t, tree);
extern tree c_finish_expr_stmt (location_t, tree);
extern tree c_finish_return (location_t, tree, tree);
extern tree c_finish_bc_stmt (location_t, tree *, bool);
extern tree c_finish_goto_label (location_t, tree);
extern tree c_finish_goto_ptr (location_t, tree);
extern tree c_expr_to_decl (tree, bool *, bool *);
extern tree c_begin_omp_parallel (void);
extern tree c_finish_omp_parallel (location_t, tree, tree);
extern tree c_begin_omp_task (void);
extern tree c_finish_omp_task (location_t, tree, tree);
extern void c_finish_omp_cancel (location_t, tree);
extern void c_finish_omp_cancellation_point (location_t, tree);
extern tree c_finish_omp_clauses (tree);
extern tree c_build_va_arg (location_t, tree, tree);
extern tree c_finish_transaction (location_t, tree, int);
extern bool c_tree_equal (tree, tree);
extern tree c_build_function_call_vec (location_t, vec<location_t>, tree,
vec<tree, va_gc> *, vec<tree, va_gc> *);
/* Set to 0 at beginning of a function definition, set to 1 if
a return statement that specifies a return value is seen. */
extern int current_function_returns_value;
/* Set to 0 at beginning of a function definition, set to 1 if
a return statement with no argument is seen. */
extern int current_function_returns_null;
/* Set to 0 at beginning of a function definition, set to 1 if
a call to a noreturn function is seen. */
extern int current_function_returns_abnormally;
/* Mode used to build pointers (VOIDmode means ptr_mode). */
extern enum machine_mode c_default_pointer_mode;
/* In c-decl.c */
extern void c_finish_incomplete_decl (tree);
extern void c_write_global_declarations (void);
extern tree c_omp_reduction_id (enum tree_code, tree);
extern tree c_omp_reduction_decl (tree);
extern tree c_omp_reduction_lookup (tree, tree);
extern tree c_check_omp_declare_reduction_r (tree *, int *, void *);
/* In c-errors.c */
extern void pedwarn_c90 (location_t, int opt, const char *, ...) ATTRIBUTE_GCC_DIAG(3,4);
extern void pedwarn_c99 (location_t, int opt, const char *, ...) ATTRIBUTE_GCC_DIAG(3,4);
#endif /* ! GCC_C_TREE_H */
|
HashFactory.c
|
/* Copyright (C) 1991-2012 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. */
/* We do support the IEC 559 math functionality, real and complex. */
/* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) /
Unicode 6.0. */
/* We do not support C11 <threads.h>. */
/* Copyright 2013-14. Los Alamos National Security, LLC. This material was produced
* under U.S. Government contract DE-AC52-06NA25396 for Los Alamos National
* Laboratory (LANL), which is operated by Los Alamos National Security, LLC
* for the U.S. Department of Energy. The U.S. Government has rights to use,
* reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR LOS
* ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR
* ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified
* to produce derivative works, such modified software should be clearly marked,
* so as not to confuse it with the version available from LANL.
*
* 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.
*
* Under this license, it is required to include a reference to this work. We
* request that each derivative work contain a reference to LANL Copyright
* Disclosure C14043/LA-CC-14-003 so that this work's impact can be roughly
* measured. In addition, it is requested that a modifier is included as in
* the following example:
*
* //<Uses | improves on | modified from> LANL Copyright Disclosure C14043/LA-CC-14-003
*
* This is LANL Copyright Disclosure C14043/LA-CC-14-003
*/
/**
* @file HashFactory.c
* @author Peter Ahrens
* @date Thu Jun 6 2013
*/
//
#ifdef _OPENMP
#include <omp.h>
#endif
#include "HashFactory.h"
#ifdef HAVE_OPENCL
#ifdef __APPLE_CC__
#include <OpenCL/OpenCL.h>
#else
#include <CL/cl.h>
#endif
#else
typedef int cl_kernel;
#define CL_CONTEXT_DEVICES 0
#define CL_MEM_READ_WRITE 0
#define CL_TRUE 1
#define CL_MEM_READ_ONLY 0
#define CL_MEM_COPY_HOST_PTR 0
#define CL_MEM_WRITE_ONLY 0
#define CL_KERNEL_WORK_GROUP_SIZE 128
int clRetainContext(int context) {
return context;
}
int clRetainCommandQueue(int command_queue) {
return command_queue;
}
int clGetContextInfo(int context, int param, size_t size, void *value,
size_t * size_ret) {
return 0;
}
int clReleaseContext(int context) {
return context;
}
int clReleaseCommandQueue(int command_queue) {
return command_queue;
}
int clReleaseProgram(int program) {
return program;
}
int clRetainKernel(int kernel) {
return kernel;
}
int clRetainProgram(int program) {
return program;
}
cl_mem clCreateBuffer(int context, int flags, size_t size, void *value,
int *size_ret) {
return 0;
}
int clEnqueueWriteBuffer(int command_queue, void *buffer, int blocking_write,
size_t offset, size_t cb, const void *ptr,
uint nevents, const int *wait_list, int *event) {
return 0;
}
int clEnqueueReadBuffer(int command_queue, void *buffer, int blocking_write,
size_t offset, size_t cb, const void *ptr, uint nevents,
const int *wait_list, int *event) {
return 0;
}
int clCreateKernel(int program, const char *kernel_name, int *errcode_ret) {
return 0;
}
int clReleaseKernel(int kernel) {
return kernel;
}
int clReleaseMemObject(void *memobj) {
return 0;
}
int clSetKernelArg(int kernel, uint arg_index, size_t arg_size,
const void *arg_value) {
return 0;
}
int clGetKernelWorkGroupInfo(int kernel, int device, int param_name,
size_t size, void *value, size_t * size_ret) {
return 0;
}
int clEnqueueNDRangeKernel(int command_queue, int kernel, uint work_dim,
const size_t * offset, const size_t * size,
const size_t * local_size, uint nevents,
const int *wait_list, int *event) {
return 0;
}
int clFinish(int command_queue) {
return 0;
}
#endif
#define PRIME_NUM_CHECKS 20
#include <math.h>
/* Copyright 2013-14. Los Alamos National Security, LLC. This material was produced
* under U.S. Government contract DE-AC52-06NA25396 for Los Alamos National
* Laboratory (LANL), which is operated by Los Alamos National Security, LLC
* for the U.S. Department of Energy. The U.S. Government has rights to use,
* reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR LOS
* ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR
* ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified
* to produce derivative works, such modified software should be clearly marked,
* so as not to confuse it with the version available from LANL.
*
* 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.
*
* Under this license, it is required to include a reference to this work. We
* request that each derivative work contain a reference to LANL Copyright
* Disclosure C14043/LA-CC-14-003 so that this work's impact can be roughly
* measured. In addition, it is requested that a modifier is included as in
* the following example:
*
* //<Uses | improves on | modified from> LANL Copyright Disclosure C14043/LA-CC-14-003
*
* This is LANL Copyright Disclosure C14043/LA-CC-14-003
*/
/* Copyright 2013-14. Los Alamos National Security, LLC. This material was produced
* under U.S. Government contract DE-AC52-06NA25396 for Los Alamos National
* Laboratory (LANL), which is operated by Los Alamos National Security, LLC
* for the U.S. Department of Energy. The U.S. Government has rights to use,
* reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR LOS
* ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR
* ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified
* to produce derivative works, such modified software should be clearly marked,
* so as not to confuse it with the version available from LANL.
*
* 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.
*
* Under this license, it is required to include a reference to this work. We
* request that each derivative work contain a reference to LANL Copyright
* Disclosure C14043/LA-CC-14-003 so that this work's impact can be roughly
* measured. In addition, it is requested that a modifier is included as in
* the following example:
*
* //<Uses | improves on | modified from> LANL Copyright Disclosure C14043/LA-CC-14-003
*
* This is LANL Copyright Disclosure C14043/LA-CC-14-003
*/
/* Copyright 2013-14. Los Alamos National Security, LLC. This material was produced
* under U.S. Government contract DE-AC52-06NA25396 for Los Alamos National
* Laboratory (LANL), which is operated by Los Alamos National Security, LLC
* for the U.S. Department of Energy. The U.S. Government has rights to use,
* reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR LOS
* ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR
* ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified
* to produce derivative works, such modified software should be clearly marked,
* so as not to confuse it with the version available from LANL.
*
* 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.
*
* Under this license, it is required to include a reference to this work. We
* request that each derivative work contain a reference to LANL Copyright
* Disclosure C14043/LA-CC-14-003 so that this work's impact can be roughly
* measured. In addition, it is requested that a modifier is included as in
* the following example:
*
* //<Uses | improves on | modified from> LANL Copyright Disclosure C14043/LA-CC-14-003
*
* This is LANL Copyright Disclosure C14043/LA-CC-14-003
*/
/* Copyright 2013-14. Los Alamos National Security, LLC. This material was produced
* under U.S. Government contract DE-AC52-06NA25396 for Los Alamos National
* Laboratory (LANL), which is operated by Los Alamos National Security, LLC
* for the U.S. Department of Energy. The U.S. Government has rights to use,
* reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR LOS
* ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR
* ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified
* to produce derivative works, such modified software should be clearly marked,
* so as not to confuse it with the version available from LANL.
*
* 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.
*
* Under this license, it is required to include a reference to this work. We
* request that each derivative work contain a reference to LANL Copyright
* Disclosure C14043/LA-CC-14-003 so that this work's impact can be roughly
* measured. In addition, it is requested that a modifier is included as in
* the following example:
*
* //<Uses | improves on | modified from> LANL Copyright Disclosure C14043/LA-CC-14-003
*
* This is LANL Copyright Disclosure C14043/LA-CC-14-003
*/
/* Copyright 2013-14. Los Alamos National Security, LLC. This material was produced
* under U.S. Government contract DE-AC52-06NA25396 for Los Alamos National
* Laboratory (LANL), which is operated by Los Alamos National Security, LLC
* for the U.S. Department of Energy. The U.S. Government has rights to use,
* reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR LOS
* ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR
* ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified
* to produce derivative works, such modified software should be clearly marked,
* so as not to confuse it with the version available from LANL.
*
* 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.
*
* Under this license, it is required to include a reference to this work. We
* request that each derivative work contain a reference to LANL Copyright
* Disclosure C14043/LA-CC-14-003 so that this work's impact can be roughly
* measured. In addition, it is requested that a modifier is included as in
* the following example:
*
* //<Uses | improves on | modified from> LANL Copyright Disclosure C14043/LA-CC-14-003
*
* This is LANL Copyright Disclosure C14043/LA-CC-14-003
*/
/* Copyright 2013-14. Los Alamos National Security, LLC. This material was produced
* under U.S. Government contract DE-AC52-06NA25396 for Los Alamos National
* Laboratory (LANL), which is operated by Los Alamos National Security, LLC
* for the U.S. Department of Energy. The U.S. Government has rights to use,
* reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR LOS
* ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR
* ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified
* to produce derivative works, such modified software should be clearly marked,
* so as not to confuse it with the version available from LANL.
*
* 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.
*
* Under this license, it is required to include a reference to this work. We
* request that each derivative work contain a reference to LANL Copyright
* Disclosure C14043/LA-CC-14-003 so that this work's impact can be roughly
* measured. In addition, it is requested that a modifier is included as in
* the following example:
*
* //<Uses | improves on | modified from> LANL Copyright Disclosure C14043/LA-CC-14-003
*
* This is LANL Copyright Disclosure C14043/LA-CC-14-003
*/
/* Copyright 2013-14. Los Alamos National Security, LLC. This material was produced
* under U.S. Government contract DE-AC52-06NA25396 for Los Alamos National
* Laboratory (LANL), which is operated by Los Alamos National Security, LLC
* for the U.S. Department of Energy. The U.S. Government has rights to use,
* reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR LOS
* ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR
* ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified
* to produce derivative works, such modified software should be clearly marked,
* so as not to confuse it with the version available from LANL.
*
* 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.
*
* Under this license, it is required to include a reference to this work. We
* request that each derivative work contain a reference to LANL Copyright
* Disclosure C14043/LA-CC-14-003 so that this work's impact can be roughly
* measured. In addition, it is requested that a modifier is included as in
* the following example:
*
* //<Uses | improves on | modified from> LANL Copyright Disclosure C14043/LA-CC-14-003
*
* This is LANL Copyright Disclosure C14043/LA-CC-14-003
*/
/* Copyright 2013-14. Los Alamos National Security, LLC. This material was produced
* under U.S. Government contract DE-AC52-06NA25396 for Los Alamos National
* Laboratory (LANL), which is operated by Los Alamos National Security, LLC
* for the U.S. Department of Energy. The U.S. Government has rights to use,
* reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR LOS
* ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR
* ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified
* to produce derivative works, such modified software should be clearly marked,
* so as not to confuse it with the version available from LANL.
*
* 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.
*
* Under this license, it is required to include a reference to this work. We
* request that each derivative work contain a reference to LANL Copyright
* Disclosure C14043/LA-CC-14-003 so that this work's impact can be roughly
* measured. In addition, it is requested that a modifier is included as in
* the following example:
*
* //<Uses | improves on | modified from> LANL Copyright Disclosure C14043/LA-CC-14-003
*
* This is LANL Copyright Disclosure C14043/LA-CC-14-003
*/
/* Copyright 2013-14. Los Alamos National Security, LLC. This material was produced
* under U.S. Government contract DE-AC52-06NA25396 for Los Alamos National
* Laboratory (LANL), which is operated by Los Alamos National Security, LLC
* for the U.S. Department of Energy. The U.S. Government has rights to use,
* reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR LOS
* ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR
* ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified
* to produce derivative works, such modified software should be clearly marked,
* so as not to confuse it with the version available from LANL.
*
* 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.
*
* Under this license, it is required to include a reference to this work. We
* request that each derivative work contain a reference to LANL Copyright
* Disclosure C14043/LA-CC-14-003 so that this work's impact can be roughly
* measured. In addition, it is requested that a modifier is included as in
* the following example:
*
* //<Uses | improves on | modified from> LANL Copyright Disclosure C14043/LA-CC-14-003
*
* This is LANL Copyright Disclosure C14043/LA-CC-14-003
*/
/* Copyright 2013-14. Los Alamos National Security, LLC. This material was produced
* under U.S. Government contract DE-AC52-06NA25396 for Los Alamos National
* Laboratory (LANL), which is operated by Los Alamos National Security, LLC
* for the U.S. Department of Energy. The U.S. Government has rights to use,
* reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR LOS
* ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR
* ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified
* to produce derivative works, such modified software should be clearly marked,
* so as not to confuse it with the version available from LANL.
*
* 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.
*
* Under this license, it is required to include a reference to this work. We
* request that each derivative work contain a reference to LANL Copyright
* Disclosure C14043/LA-CC-14-003 so that this work's impact can be roughly
* measured. In addition, it is requested that a modifier is included as in
* the following example:
*
* //<Uses | improves on | modified from> LANL Copyright Disclosure C14043/LA-CC-14-003
*
* This is LANL Copyright Disclosure C14043/LA-CC-14-003
*/
static int reportLevel = 0;
const char *HashFactory_source;
const char *Hash_GetKernelSourceString() {
return HashFactory_source;
}
size_t roundUpToNearest(size_t x, size_t r) {
return (((x - 1) / r) + 1) * r;
}
int modularPow(int base, int exponent, int modulus) {
int result = 1;
while (exponent) {
if (exponent & 1)
result = ((long long int)result * base) % modulus;
exponent >>= 1;
base = ((long long int)base * base) % modulus;
}
return result;
}
int largestProthPrimeUnder(int N) {
if (N < 4) {
return N;
}
//determine the nearest proth number
int n;
int m;
frexp((double)N, &n);
n /= 2;
int s = 1 << n;
int p = s * ((N - 1) / s) + 1;
int i;
int a;
srand(p);
while (p > 3) {
//check if a proth number is prime
for (i = 0; i < PRIME_NUM_CHECKS; i++) {
a = rand();
if (modularPow(a, (p - 1) / 2, p) == p - 1) {
return p;
}
}
//determine the next proth number
if (p - 1 == s * s / 4) {
s /= 2;
}
p -= s;
}
return 3;
}
int smallestProthPrimeAbove(int N) {
if (N < 4) {
return N;
}
//determine the nearest proth number
int n;
int m;
frexp((double)N, &n);
n /= 2;
int s = 1 << n;
int p = s * ((N - 1) / s) + 1;
int i;
int a;
srand(p);
while (1) {
//determine the next proth number
if (p - 1 == s * s) {
s *= 2;
}
p += s;
//check if a proth number is prime
for (i = 0; i < PRIME_NUM_CHECKS; i++) {
a = rand();
if (modularPow(a, (p - 1) / 2, p) == p - 1) {
return p;
}
}
}
return 3;
}
int intLog2(int n) {
int result = 0;
while (n >>= 1) {
result++;
}
return result;
}
void Hash_SetReportLevel(int level) {
reportLevel = level;
}
int Hash_GetReportLevel() {
return reportLevel;
}
char *Hash_ExitCodeString(int exitCode) {
switch (exitCode) {
case HASH_EXIT_CODE_NORMAL:
return "Normal";
case HASH_EXIT_CODE_ERROR:
return "Error";
case HASH_EXIT_CODE_OVERWRITE:
return "Overwrite";
case HASH_EXIT_CODE_KEY_DNE:
return "Key Does Not Exist";
case HASH_EXIT_CODE_CYCLE:
return "Cycle";
case HASH_EXIT_CODE_MAX_ENTRIES_EXCEEDED:
return "Maximum Number Of Entries Exceeded";
default:
return "Unknown";
}
}
void Hash_ExitCodeDebug(int exitCode) {
if (exitCode != HASH_EXIT_CODE_NORMAL) {
printf("HashExitCode: %s\n", Hash_ExitCodeString(exitCode));
}
}
struct intintHash_Table_ {
char *tableData;
cl_mem tableDataBuffer;
int (*destroyFunc) (intintHash_Table *);
int (*setupFunc) (intintHash_Table *);
int (*emptyFunc) (intintHash_Table *);
int (*queryFunc) (intintHash_Table *, size_t, int *, int *);
int (*querySingleFunc) (intintHash_Table *, int, int *);
int (*insertFunc) (intintHash_Table *, size_t, int *, int *);
int (*insertSingleFunc) (intintHash_Table *, int, int);
int (*insertNoOverwriteFunc) (intintHash_Table *, size_t, int *, int *);
int (*insertSingleNoOverwriteFunc) (intintHash_Table *, int, int);
int (*bufferQueryFunc) (intintHash_Table *, size_t, cl_mem, cl_mem);
int (*bufferInsertFunc) (intintHash_Table *, size_t, cl_mem, cl_mem);
int (*bufferInsertNoOverwriteFunc) (intintHash_Table *, size_t, cl_mem,
cl_mem);
cl_context context;
cl_command_queue queue;
cl_program utilProgram;
cl_kernel emptyKernel;
size_t emptyKernelLocalWorkSize;
cl_program program;
cl_kernel querySingleKernel;
cl_kernel insertSingleKernel;
cl_kernel insertSingleNoOverwriteKernel;
size_t localWorkSize;
};
struct intintHash_Factory_ {
cl_context context;
cl_program program;
cl_command_queue queue;
int hashTypesAvailable;
cl_program utilProgram[HASH_NUM_CL_HASHES];
cl_kernel emptyKernel[HASH_NUM_CL_HASHES];
size_t emptyKernelLocalWorkSize[HASH_NUM_CL_HASHES];
cl_kernel querySingleKernel[HASH_NUM_CL_HASHES];
cl_kernel insertSingleKernel[HASH_NUM_CL_HASHES];
cl_kernel insertSingleNoOverwriteKernel[HASH_NUM_CL_HASHES];
int emptyValue;
size_t localWorkSize;
intintHash_Table *(*createFunc[HASH_NUM_HASHES]) (intintHash_Factory *,
int hashIndex,
size_t keyRange,
size_t numEntries,
float loadFactor);
int (*destroyFunc[HASH_NUM_HASHES]) (intintHash_Factory *,
int hashIndex);
};
intintHash_Factory *intintHash_CreateFactory(int hashTypes, int *emptyValue,
size_t localWorkSize,
cl_context * context,
cl_command_queue * queue) {
if (hashTypes == 0) {
hashTypes = HASH_ALL_C_HASHES;
}
if (!(hashTypes & HASH_ALL_HASHES)) {
printf("Please specify a valid hash type to create.\n");
exit(1);
}
hashTypes &= HASH_ALL_HASHES;
if ((hashTypes & HASH_SENTINEL_PERFECT_HASHES) == hashTypes
&& emptyValue == NULL) {
printf
("emptyValue must be valid if a sentinel perfect hash is the only option available.\n");
exit(1);
}
intintHash_Factory *factory =
(intintHash_Factory *) malloc(sizeof(intintHash_Factory));
if (emptyValue == NULL) {
hashTypes &= !HASH_SENTINEL_PERFECT_HASHES;
} else {
factory->emptyValue = *emptyValue;
}
factory->hashTypesAvailable = hashTypes;
if (hashTypes & HASH_ALL_CL_HASHES) {
if (localWorkSize == 0) {
factory->localWorkSize = HASH_DEFAULT_LOCAL_WORK_SIZE;
} else {
factory->localWorkSize = 1 << intLog2(localWorkSize);
}
if (context == NULL) {
CLHash_Utilities_CreateContext(&factory->context,
&factory->queue);
} else {
factory->context = *context;
clRetainContext(*context);
if (queue == NULL) {
printf
("Please specify a command queue for your context.\n");
exit(-1);
}
factory->queue = *queue;
clRetainCommandQueue(*queue);
}
cl_int error;
cl_device_id device;
error =
clGetContextInfo(factory->context, CL_CONTEXT_DEVICES,
sizeof(device), &device, NULL);
CLHash_Utilities_HandleError(error, "intintHash_CreateFactory",
"clGetContextInfo");
factory->program =
CLHash_Utilities_BuildProgramString(factory->context,
device,
Hash_GetKernelSourceString
());
}
int hashType = 1;
for (int hashIndex = 0; hashIndex < HASH_NUM_HASHES; hashIndex++) {
hashType = 1 << hashIndex;
switch (hashType & hashTypes) {
case IDENTITY_PERFECT_HASH_ID:
intintIdentityPerfectHash_CreateFactory(factory,
hashIndex);
break;
case IDENTITY_PERFECT_CL_HASH_ID:
intintIdentityPerfectCLHash_CreateFactory(factory,
hashIndex);
break;
case IDENTITY_PERFECT_OPENMP_HASH_ID:
intintIdentityPerfectOpenMPHash_CreateFactory(factory,
hashIndex);
break;
case IDENTITY_SENTINEL_PERFECT_HASH_ID:
intintIdentitySentinelPerfectHash_CreateFactory(factory,
hashIndex);
break;
case IDENTITY_SENTINEL_PERFECT_CL_HASH_ID:
intintIdentitySentinelPerfectCLHash_CreateFactory
(factory, hashIndex);
break;
case IDENTITY_SENTINEL_PERFECT_OPENMP_HASH_ID:
intintIdentitySentinelPerfectOpenMPHash_CreateFactory
(factory, hashIndex);
break;
case LCG_LINEAR_OPEN_COMPACT_HASH_ID:
intintLCGLinearOpenCompactHash_CreateFactory(factory,
hashIndex);
break;
case LCG_LINEAR_OPEN_COMPACT_CL_HASH_ID:
intintLCGLinearOpenCompactCLHash_CreateFactory(factory,
hashIndex);
break;
case LCG_LINEAR_OPEN_COMPACT_OPENMP_HASH_ID:
intintLCGLinearOpenCompactOpenMPHash_CreateFactory
(factory, hashIndex);
break;
case LCG_QUADRATIC_OPEN_COMPACT_HASH_ID:
intintLCGQuadraticOpenCompactHash_CreateFactory(factory,
hashIndex);
break;
case LCG_QUADRATIC_OPEN_COMPACT_CL_HASH_ID:
intintLCGQuadraticOpenCompactCLHash_CreateFactory
(factory, hashIndex);
break;
case LCG_QUADRATIC_OPEN_COMPACT_OPENMP_HASH_ID:
intintLCGQuadraticOpenCompactOpenMPHash_CreateFactory
(factory, hashIndex);
break;
}
}
return factory;
}
int intintHash_DestroyFactory(intintHash_Factory * factory) {
int hashType = 1;
for (int hashIndex = 0; hashIndex < HASH_NUM_HASHES; hashIndex++) {
hashType = 1 << hashIndex;
switch (hashType & factory->hashTypesAvailable) {
case IDENTITY_PERFECT_HASH_ID:
intintIdentityPerfectHash_DestroyFactory(factory,
hashIndex);
break;
case IDENTITY_PERFECT_CL_HASH_ID:
intintIdentityPerfectCLHash_DestroyFactory(factory,
hashIndex);
break;
case IDENTITY_PERFECT_OPENMP_HASH_ID:
intintIdentityPerfectOpenMPHash_DestroyFactory(factory,
hashIndex);
break;
case IDENTITY_SENTINEL_PERFECT_HASH_ID:
intintIdentitySentinelPerfectHash_DestroyFactory
(factory, hashIndex);
break;
case IDENTITY_SENTINEL_PERFECT_CL_HASH_ID:
intintIdentitySentinelPerfectCLHash_DestroyFactory
(factory, hashIndex);
break;
case IDENTITY_SENTINEL_PERFECT_OPENMP_HASH_ID:
intintIdentitySentinelPerfectOpenMPHash_DestroyFactory
(factory, hashIndex);
break;
case LCG_LINEAR_OPEN_COMPACT_HASH_ID:
intintLCGLinearOpenCompactHash_DestroyFactory(factory,
hashIndex);
break;
case LCG_LINEAR_OPEN_COMPACT_CL_HASH_ID:
intintLCGLinearOpenCompactCLHash_DestroyFactory(factory,
hashIndex);
break;
case LCG_LINEAR_OPEN_COMPACT_OPENMP_HASH_ID:
intintLCGLinearOpenCompactOpenMPHash_DestroyFactory
(factory, hashIndex);
break;
case LCG_QUADRATIC_OPEN_COMPACT_HASH_ID:
intintLCGQuadraticOpenCompactHash_DestroyFactory
(factory, hashIndex);
break;
case LCG_QUADRATIC_OPEN_COMPACT_CL_HASH_ID:
intintLCGQuadraticOpenCompactCLHash_DestroyFactory
(factory, hashIndex);
break;
case LCG_QUADRATIC_OPEN_COMPACT_OPENMP_HASH_ID:
intintLCGQuadraticOpenCompactOpenMPHash_DestroyFactory
(factory, hashIndex);
break;
}
hashIndex++;
}
if (factory->hashTypesAvailable & HASH_ALL_CL_HASHES) {
clReleaseContext(factory->context);
clReleaseCommandQueue(factory->queue);
clReleaseProgram(factory->program);
}
free(factory);
return (0);
}
intintHash_Table *intintHash_CreateTable(intintHash_Factory * factory,
int hashTypes, size_t keyRange,
size_t numEntries, float loadFactor) {
if (loadFactor > 1.0 || loadFactor < HASH_MIN_LOAD_FACTOR) {
loadFactor = HASH_DEFAULT_LOAD_FACTOR;
}
if (hashTypes == 0) {
hashTypes = factory->hashTypesAvailable;
if ((hashTypes & HASH_ALL_CL_HASHES)
&& (hashTypes & HASH_ALL_OPENMP_HASHES)
&& (hashTypes & HASH_ALL_C_HASHES)) {
hashTypes &= HASH_ALL_C_HASHES;
}
}
if (!(hashTypes & factory->hashTypesAvailable)) {
printf
("None of the selected hash types are supported by this factory.\n");
exit(1);
}
hashTypes &= factory->hashTypesAvailable;
if ((hashTypes & HASH_ALL_CL_HASHES)
&& (hashTypes & HASH_ALL_OPENMP_HASHES)
&& (hashTypes & HASH_ALL_C_HASHES)) {
printf("Please decide between OpenCL, OpenMP or C hash.\n");
exit(1);
}
if ((hashTypes & HASH_PERFECT_HASHES) == hashTypes && keyRange == 0) {
printf
("keyRange must be set if a perfect hash is the only option available.\n");
exit(1);
}
if ((hashTypes & HASH_COMPACT_HASHES) == hashTypes && numEntries == 0) {
printf
("numEntries must be set if a compact hash is the only option available.\n");
exit(1);
}
if (numEntries == 0 && keyRange == 0) {
printf("either numEntries or keyRange must be set.\n");
exit(1);
}
size_t perfectNumBuckets = keyRange;
size_t compactNumBuckets = (size_t) (numEntries / loadFactor);
int hashIndex;
if ((hashTypes & HASH_SENTINEL_PERFECT_HASHES)
&& ((hashTypes == (hashTypes & HASH_SENTINEL_PERFECT_HASHES))
|| (compactNumBuckets == 0
|| (perfectNumBuckets / compactNumBuckets <
HASH_PERFECT_COMPACT_SWITCH_FACTOR)))) {
hashIndex = intLog2(hashTypes & HASH_SENTINEL_PERFECT_HASHES);
} else if ((hashTypes & HASH_NOSENTINEL_PERFECT_HASHES)
&& ((hashTypes == (hashTypes & HASH_PERFECT_HASHES))
|| (compactNumBuckets == 0
|| (perfectNumBuckets / compactNumBuckets <
HASH_PERFECT_COMPACT_SWITCH_FACTOR)))) {
hashIndex = intLog2(hashTypes & HASH_NOSENTINEL_PERFECT_HASHES);
} else if ((hashTypes & HASH_LINEAR_COMPACT_HASHES)
&&
((hashTypes ==
(hashTypes &
(HASH_PERFECT_HASHES | HASH_LINEAR_COMPACT_HASHES)))
||
((hashTypes & HASH_COMPACT_HASHES &
HASH_LINEAR_COMPACT_HASHES) ==
(hashTypes & HASH_COMPACT_HASHES) || loadFactor > 0.5))) {
hashIndex = intLog2(hashTypes & HASH_LINEAR_COMPACT_HASHES);
} else {
hashIndex = intLog2(hashTypes & HASH_QUADRATIC_COMPACT_HASHES);
}
intintHash_Table *table =
factory->createFunc[hashIndex] (factory, hashIndex, keyRange,
numEntries, loadFactor);
return table;
}
int intintHash_SetupTable(intintHash_Table * table) {
table->setupFunc(table);
return (0);
}
int intintHash_EmptyTable(intintHash_Table * table) {
table->emptyFunc(table);
return (0);
}
int intintHash_DestroyTable(intintHash_Table * table) {
table->destroyFunc(table);
return (0);
}
cl_mem intintHash_GetTableDataBuffer(intintHash_Table * table) {
return table->tableDataBuffer;
}
cl_mem *intintHash_GetTableDataBufferPtr(intintHash_Table * table) {
return &table->tableDataBuffer;
}
int intintHash_GetTableType(intintHash_Table * table) {
return ((int *)table->tableData)[0];
} int intintHash_Query(intintHash_Table * table, size_t numKeys, int *keys,
int *valuesOutput) {
table->queryFunc(table, numKeys, keys, valuesOutput);
return (0);
}
int intintHash_QuerySingle(intintHash_Table * table, int key, int *valueOutput) {
table->querySingleFunc(table, key, valueOutput);
return (0);
}
int intintHash_Insert(intintHash_Table * table, size_t numEntries, int *keys,
int *values) {
table->insertFunc(table, numEntries, keys, values);
return (0);
}
int intintHash_InsertSingle(intintHash_Table * table, int key, int value) {
table->insertSingleFunc(table, key, value);
return (0);
}
int intintHash_InsertNoOverwrite(intintHash_Table * table, size_t numEntries,
int *keys, int *values) {
table->insertNoOverwriteFunc(table, numEntries, keys, values);
return (0);
}
int intintHash_InsertSingleNoOverwrite(intintHash_Table * table, int key,
int value) {
table->insertSingleNoOverwriteFunc(table, key, value);
return (0);
}
int intintHash_BufferQuery(intintHash_Table * table, size_t numKeys,
cl_mem keys, cl_mem valuesOutput) {
table->bufferQueryFunc(table, numKeys, keys, valuesOutput);
return (0);
}
int intintHash_BufferInsert(intintHash_Table * table, size_t numEntries,
cl_mem keys, cl_mem values) {
table->bufferInsertFunc(table, numEntries, keys, values);
return (0);
}
int intintHash_BufferInsertNoOverwrite(intintHash_Table * table,
size_t numEntries, cl_mem keys,
cl_mem values) {
table->bufferInsertNoOverwriteFunc(table, numEntries, keys, values);
return (0);
}
typedef struct intintIdentityPerfectHash_TableData {
int hashID;
unsigned int numBuckets;
char compressFuncData;
} intintIdentityPerfectHash_TableData;
typedef struct intintIdentityPerfectHash_Bucket {
int key;
int value;
} intintIdentityPerfectHash_Bucket;
intintHash_Table *intintIdentityPerfectHash_CreateTable(intintHash_Factory *
factory, int hashIndex,
size_t keyRange,
size_t numEntries,
float loadFactor) {
intintHash_Table *table =
(intintHash_Table *) malloc(sizeof(intintHash_Table));
table->destroyFunc = &intintIdentityPerfectHash_DestroyTable;
table->setupFunc = &intintIdentityPerfectHash_SetupTable;
table->emptyFunc = &intintIdentityPerfectHash_EmptyTable;
table->queryFunc = &intintIdentityPerfectHash_Query;
table->querySingleFunc = &intintIdentityPerfectHash_QuerySingle;
table->insertFunc = &intintIdentityPerfectHash_Insert;
table->insertSingleFunc = &intintIdentityPerfectHash_InsertSingle;
table->insertNoOverwriteFunc =
&intintIdentityPerfectHash_InsertNoOverwrite;
table->insertSingleNoOverwriteFunc =
&intintIdentityPerfectHash_InsertSingleNoOverwrite;
table->tableData =
(char *)malloc(sizeof(intintIdentityPerfectHash_TableData));
((intintIdentityPerfectHash_TableData *) table->tableData)->hashID =
IDENTITY_PERFECT_HASH_ID;
((intintIdentityPerfectHash_TableData *) table->tableData)->numBuckets =
keyRange + 1;
char *tempHashData =
(char *)malloc(sizeof(intintIdentityPerfectHash_TableData) +
((intintIdentityPerfectHash_TableData *) table->
tableData)->numBuckets *
sizeof(intintIdentityPerfectHash_Bucket));
memcpy(tempHashData, table->tableData,
sizeof(intintIdentityPerfectHash_TableData));
free(table->tableData);
table->tableData = tempHashData;
return table;
}
int intintIdentityPerfectHash_CreateFactory(intintHash_Factory * factory,
int hashIndex) {
factory->createFunc[hashIndex] = &intintIdentityPerfectHash_CreateTable;
factory->destroyFunc[hashIndex] =
&intintIdentityPerfectHash_DestroyFactory;;
return HASH_EXIT_CODE_NORMAL;
}
int intintIdentityPerfectHash_DestroyFactory(intintHash_Factory * factory,
int hashIndex) {;
return HASH_EXIT_CODE_NORMAL;
}
int intintIdentityPerfectHash_DestroyTable(intintHash_Table * table) {
int exitCode = 0;
free(table->tableData);
free(table);
return exitCode;
}
int intintIdentityPerfectHash_SetupTable(intintHash_Table * table) {
int exitCode = 0;
intintIdentityPerfectHash_Bucket *buckets =
(intintIdentityPerfectHash_Bucket *) & table->
tableData[sizeof(intintIdentityPerfectHash_TableData)];
if (intintHash_GetTableType(table) & ~HASH_SENTINEL_PERFECT_HASHES) {
for (int index = 0;
index <
((intintIdentityPerfectHash_TableData *) table->
tableData)->numBuckets; index++) {
buckets[index].key = HASH_BUCKET_STATUS_EMPTY;
}}
exitCode = HASH_EXIT_CODE_NORMAL;
return exitCode;
}
int intintIdentityPerfectHash_EmptyTable(intintHash_Table * table) {
int exitCode = 0;
intintIdentityPerfectHash_Bucket *buckets =
(intintIdentityPerfectHash_Bucket *) & table->
tableData[sizeof(intintIdentityPerfectHash_TableData)];
for (int index = 0;
index <
((intintIdentityPerfectHash_TableData *) table->tableData)->
numBuckets; index++) {
buckets[index].key = HASH_BUCKET_STATUS_EMPTY;
} exitCode = HASH_EXIT_CODE_NORMAL;
return exitCode;
}
int intintIdentityPerfectHash_InnerQuerySingle(char *tableData, int key,
int *valueOutput) {
intintIdentityPerfectHash_Bucket *buckets =
(intintIdentityPerfectHash_Bucket *) &
tableData[sizeof(intintIdentityPerfectHash_TableData)];
int index;
int exitCode;
index =
intintHash_CompressIdentity(((intintIdentityPerfectHash_TableData *)
tableData)->compressFuncData, key);
if ((buckets[index].key) != HASH_BUCKET_STATUS_EMPTY) {
if (key == buckets[index].key) {
exitCode = HASH_SEARCH_CODE_MATCH;
} else {
exitCode = HASH_SEARCH_CODE_MISMATCH;
}
} else {
exitCode = HASH_SEARCH_CODE_EMPTY;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
*valueOutput = buckets[index].value;
return HASH_EXIT_CODE_NORMAL;
case HASH_SEARCH_CODE_MISMATCH:
case HASH_SEARCH_CODE_EMPTY:
return HASH_EXIT_CODE_KEY_DNE;
default:
return exitCode;
}
}
int intintIdentityPerfectHash_InnerQuery(char *tableData, unsigned int numKeys,
int *keys, int *valuesOutput) {
intintIdentityPerfectHash_Bucket *buckets =
(intintIdentityPerfectHash_Bucket *) &
tableData[sizeof(intintIdentityPerfectHash_TableData)];
int key;
int *valueOutput;
int index;
int exitCode;
uint i;
int resultExitCode = HASH_EXIT_CODE_NORMAL;
for (i = 0; i < numKeys; i++) {
key = keys[i];
valueOutput = &valuesOutput[i];
index =
intintHash_CompressIdentity(((intintIdentityPerfectHash_TableData *) tableData)->compressFuncData, key);
if ((buckets[index].key) != HASH_BUCKET_STATUS_EMPTY) {
if (key == buckets[index].key) {
exitCode = HASH_SEARCH_CODE_MATCH;
} else {
exitCode = HASH_SEARCH_CODE_MISMATCH;
}
} else {
exitCode = HASH_SEARCH_CODE_EMPTY;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
*valueOutput = buckets[index].value;
break;
case HASH_SEARCH_CODE_MISMATCH:
case HASH_SEARCH_CODE_EMPTY:
resultExitCode = HASH_EXIT_CODE_KEY_DNE;
break;
default:
return exitCode;
}
}
return resultExitCode;
}
int intintIdentityPerfectHash_InnerInsertSingle(char *tableData, int key,
int value) {
intintIdentityPerfectHash_Bucket *buckets =
(intintIdentityPerfectHash_Bucket *) &
tableData[sizeof(intintIdentityPerfectHash_TableData)];
int index;
int exitCode;
index =
intintHash_CompressIdentity(((intintIdentityPerfectHash_TableData *)
tableData)->compressFuncData, key);
if (((buckets[index].key ==
HASH_BUCKET_STATUS_EMPTY) ? (buckets[index].key =
key,
HASH_BUCKET_STATUS_EMPTY) :
buckets[index].key) != HASH_BUCKET_STATUS_EMPTY) {
if (key == buckets[index].key) {
exitCode = HASH_SEARCH_CODE_MATCH;
} else {
exitCode = HASH_SEARCH_CODE_MISMATCH;
}
} else {
exitCode = HASH_SEARCH_CODE_EMPTY;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
buckets[index].value = value;
return HASH_EXIT_CODE_OVERWRITE;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = value;
return HASH_EXIT_CODE_NORMAL;
default:
return exitCode;
}
}
int intintIdentityPerfectHash_InnerInsert(char *tableData,
unsigned int numEntries, int *keys,
int *values) {
intintIdentityPerfectHash_Bucket *buckets =
(intintIdentityPerfectHash_Bucket *) &
tableData[sizeof(intintIdentityPerfectHash_TableData)];
int resultExitCode = HASH_EXIT_CODE_NORMAL;
int key;
int index;
int exitCode;
uint i;;
for (i = 0; i < numEntries; i++) {
key = keys[i];
index =
intintHash_CompressIdentity(((intintIdentityPerfectHash_TableData *) tableData)->compressFuncData, key);
if (((buckets[index].key ==
HASH_BUCKET_STATUS_EMPTY) ? (buckets[index].key =
key,
HASH_BUCKET_STATUS_EMPTY) :
buckets[index].key) != HASH_BUCKET_STATUS_EMPTY) {
if (key == buckets[index].key) {
exitCode = HASH_SEARCH_CODE_MATCH;
} else {
exitCode = HASH_SEARCH_CODE_MISMATCH;
}
} else {
exitCode = HASH_SEARCH_CODE_EMPTY;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
resultExitCode = HASH_EXIT_CODE_OVERWRITE;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = values[i];
break;
default:
resultExitCode = exitCode;
}
}
return resultExitCode;
}
int intintIdentityPerfectHash_InnerInsertSingleNoOverwrite(char *tableData,
int key, int value) {
intintIdentityPerfectHash_Bucket *buckets =
(intintIdentityPerfectHash_Bucket *) &
tableData[sizeof(intintIdentityPerfectHash_TableData)];
int index;
int exitCode;
index =
intintHash_CompressIdentity(((intintIdentityPerfectHash_TableData *)
tableData)->compressFuncData, key);
if (((buckets[index].key ==
HASH_BUCKET_STATUS_EMPTY) ? (buckets[index].key =
key,
HASH_BUCKET_STATUS_EMPTY) :
buckets[index].key) != HASH_BUCKET_STATUS_EMPTY) {
if (key == buckets[index].key) {
exitCode = HASH_SEARCH_CODE_MATCH;
} else {
exitCode = HASH_SEARCH_CODE_MISMATCH;
}
} else {
exitCode = HASH_SEARCH_CODE_EMPTY;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
return HASH_EXIT_CODE_OVERWRITE;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = value;
return HASH_EXIT_CODE_NORMAL;
default:
return exitCode;
}
}
int intintIdentityPerfectHash_InnerInsertNoOverwrite(char *tableData,
unsigned int numEntries,
int *keys, int *values) {
intintIdentityPerfectHash_Bucket *buckets =
(intintIdentityPerfectHash_Bucket *) &
tableData[sizeof(intintIdentityPerfectHash_TableData)];
int resultExitCode = HASH_EXIT_CODE_NORMAL;
int key;
int index;
int exitCode;
uint i;;
for (i = 0; i < numEntries; i++) {
key = keys[i];
index =
intintHash_CompressIdentity(((intintIdentityPerfectHash_TableData *) tableData)->compressFuncData, key);
if (((buckets[index].key ==
HASH_BUCKET_STATUS_EMPTY) ? (buckets[index].key =
key,
HASH_BUCKET_STATUS_EMPTY) :
buckets[index].key) != HASH_BUCKET_STATUS_EMPTY) {
if (key == buckets[index].key) {
exitCode = HASH_SEARCH_CODE_MATCH;
} else {
exitCode = HASH_SEARCH_CODE_MISMATCH;
}
} else {
exitCode = HASH_SEARCH_CODE_EMPTY;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
resultExitCode = HASH_EXIT_CODE_OVERWRITE;
break;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = values[i];
break;
default:
resultExitCode = exitCode;
}
}
return resultExitCode;
}
int intintIdentityPerfectHash_QuerySingle(intintHash_Table * table, int key,
int *valueOutput) {
return intintIdentityPerfectHash_InnerQuerySingle(table->tableData, key,
valueOutput);
}
int intintIdentityPerfectHash_Query(intintHash_Table * table, size_t numKeys,
int *keys, int *valuesOutput) {
return intintIdentityPerfectHash_InnerQuery(table->tableData, numKeys,
keys, valuesOutput);
}
int intintIdentityPerfectHash_InsertSingle(intintHash_Table * table, int key,
int value) {
return intintIdentityPerfectHash_InnerInsertSingle(table->tableData,
key, value);
}
int intintIdentityPerfectHash_Insert(intintHash_Table * table,
size_t numEntries, int *keys,
int *values) {
return intintIdentityPerfectHash_InnerInsert(table->tableData,
numEntries, keys, values);
}
int intintIdentityPerfectHash_InsertSingleNoOverwrite(intintHash_Table * table,
int key, int value) {
return intintIdentityPerfectHash_InnerInsertSingleNoOverwrite(table->
tableData,
key,
value);
}
int intintIdentityPerfectHash_InsertNoOverwrite(intintHash_Table * table,
size_t numEntries, int *keys,
int *values) {
return intintIdentityPerfectHash_InnerInsertNoOverwrite(table->
tableData,
numEntries,
keys, values);
}
typedef struct intintIdentityPerfectCLHash_TableData {
int hashID;
unsigned int numBuckets;
char compressFuncData;
} intintIdentityPerfectCLHash_TableData;
typedef struct intintIdentityPerfectCLHash_Bucket {
int key;
int value;
} intintIdentityPerfectCLHash_Bucket;
intintHash_Table *intintIdentityPerfectCLHash_CreateTable(intintHash_Factory *
factory,
int hashIndex,
size_t keyRange,
size_t numEntries,
float loadFactor) {
intintHash_Table *table =
(intintHash_Table *) malloc(sizeof(intintHash_Table));
table->destroyFunc = &intintIdentityPerfectCLHash_DestroyTable;
table->setupFunc = &intintIdentityPerfectCLHash_SetupTable;
table->emptyFunc = &intintIdentityPerfectCLHash_EmptyTable;
table->queryFunc = &intintIdentityPerfectCLHash_Query;
table->querySingleFunc = &intintIdentityPerfectCLHash_QuerySingle;
table->insertFunc = &intintIdentityPerfectCLHash_Insert;
table->insertSingleFunc = &intintIdentityPerfectCLHash_InsertSingle;
table->insertNoOverwriteFunc =
&intintIdentityPerfectCLHash_InsertNoOverwrite;
table->insertSingleNoOverwriteFunc =
&intintIdentityPerfectCLHash_InsertSingleNoOverwrite;
table->tableData =
(char *)malloc(sizeof(intintIdentityPerfectCLHash_TableData));
((intintIdentityPerfectCLHash_TableData *) table->tableData)->hashID =
IDENTITY_PERFECT_CL_HASH_ID;
table->context = factory->context;
table->queue = factory->queue;
table->program = factory->program;
table->localWorkSize = factory->localWorkSize;
table->utilProgram = factory->utilProgram[hashIndex];
table->emptyKernel = factory->emptyKernel[hashIndex];
table->emptyKernelLocalWorkSize =
factory->emptyKernelLocalWorkSize[hashIndex];
table->querySingleKernel = factory->querySingleKernel[hashIndex];
table->insertSingleKernel = factory->insertSingleKernel[hashIndex];
table->insertSingleNoOverwriteKernel =
factory->insertSingleNoOverwriteKernel[hashIndex];
clRetainContext(table->context);
clRetainCommandQueue(table->queue);
clRetainProgram(table->program);
clRetainProgram(table->utilProgram);
clRetainKernel(table->emptyKernel);
clRetainKernel(table->querySingleKernel);
clRetainKernel(table->insertSingleKernel);
clRetainKernel(table->insertSingleNoOverwriteKernel);;
((intintIdentityPerfectCLHash_TableData *) table->tableData)->
numBuckets = keyRange + 1;
char *tempHashData =
(char *)malloc(sizeof(intintIdentityPerfectCLHash_TableData) +
((intintIdentityPerfectCLHash_TableData *) table->
tableData)->numBuckets *
sizeof(intintIdentityPerfectCLHash_Bucket));
memcpy(tempHashData, table->tableData,
sizeof(intintIdentityPerfectCLHash_TableData));
free(table->tableData);
table->tableData = tempHashData;
cl_int err;
table->tableDataBuffer =
clCreateBuffer(table->context, CL_MEM_READ_WRITE,
sizeof(intintIdentityPerfectHash_TableData) +
((intintIdentityPerfectHash_TableData *) table->
tableData)->numBuckets *
sizeof(intintIdentityPerfectHash_Bucket), NULL,
&err);
CLHash_Utilities_HandleError(err,
"intintIdentityPerfectCLHash_InitTable",
"clCreateBuffer");
err =
clEnqueueWriteBuffer(table->queue, table->tableDataBuffer, CL_TRUE,
0, sizeof(intintIdentityPerfectHash_TableData),
table->tableData, 0, NULL, NULL);
CLHash_Utilities_HandleError(err,
"intintIdentityPerfectCLHash_InitTable",
"clEnqueueWriteBuffer");
return table;
}
int intintIdentityPerfectCLHash_CreateFactory(intintHash_Factory * factory,
int hashIndex) {
factory->createFunc[hashIndex] =
&intintIdentityPerfectCLHash_CreateTable;
factory->destroyFunc[hashIndex] =
&intintIdentityPerfectCLHash_DestroyFactory;
cl_int error;
cl_device_id device;
error =
clGetContextInfo(factory->context, CL_CONTEXT_DEVICES,
sizeof(device), &device, NULL);
CLHash_Utilities_HandleError(error, "intintHash_CreateFactory",
"clGetContextInfo");
factory->querySingleKernel[hashIndex] =
clCreateKernel(factory->program,
"intintIdentityPerfectCLHash_RangeQuerySingle",
&error);
CLHash_Utilities_HandleError(error,
"intintIdentityPerfectCLHash_CreateFactory",
"clCreateKernel");
factory->insertSingleKernel[hashIndex] =
clCreateKernel(factory->program,
"intintIdentityPerfectCLHash_RangeInsertSingle",
&error);
CLHash_Utilities_HandleError(error,
"intintIdentityPerfectCLHash_CreateFactory",
"clCreateKernel");
factory->insertSingleNoOverwriteKernel[hashIndex] =
clCreateKernel(factory->program,
"intintIdentityPerfectCLHash_RangeInsertSingleNoOverwrite",
&error);
CLHash_Utilities_HandleError(error,
"intintIdentityPerfectCLHash_CreateFactory",
"clCreateKernel");
factory->utilProgram[hashIndex] =
CLHash_Utilities_BuildProgramString(factory->context, device,
"static inline unsigned int intintHash_CompressIdentity(char data, int hashCode){ return hashCode; } typedef struct intintHash_CompressLCGData{ long unsigned int a; long unsigned int c; unsigned int m; unsigned int n; }intintHash_CompressLCGData; static inline unsigned int intintHash_CompressLCG(intintHash_CompressLCGData compressLCGData, int hashCode){ return ((compressLCGData.a * hashCode + compressLCGData.c) % compressLCGData.m) % compressLCGData.n; } typedef struct intintIdentityPerfectCLHash_TableData{ int hashID; unsigned int numBuckets; char compressFuncData; }intintIdentityPerfectCLHash_TableData; typedef struct intintIdentityPerfectCLHash_Bucket{ int key; int value; }intintIdentityPerfectCLHash_Bucket; __kernel void intintIdentityPerfectCLHash_Empty(__global char *tableData){ int index = get_global_id(0); if(index >= ((__global intintIdentityPerfectCLHash_TableData*)tableData)->numBuckets){ return; } __global intintIdentityPerfectCLHash_Bucket *buckets = (__global intintIdentityPerfectCLHash_Bucket*)&tableData[sizeof(intintIdentityPerfectCLHash_TableData)]; buckets[index].key = -1;/*HASH_BUCKET_STATUS_EMPTY*/ }");
factory->emptyKernel[hashIndex] =
clCreateKernel(factory->utilProgram[hashIndex],
"intintIdentityPerfectCLHash_Empty", &error);
CLHash_Utilities_HandleError(error,
"intintIdentityPerfectCLHash_CreateFactory",
"clCreateKernel");
error =
clGetKernelWorkGroupInfo(factory->emptyKernel[hashIndex], device,
CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t),
&factory->
emptyKernelLocalWorkSize[hashIndex], NULL);
CLHash_Utilities_HandleError(error,
"intintIdentityPerfectCLHash_CreateFactory",
"clGetKernelWorkGroupInfo");;;
return HASH_EXIT_CODE_NORMAL;
}
int intintIdentityPerfectCLHash_DestroyFactory(intintHash_Factory * factory,
int hashIndex) {;
clReleaseKernel(factory->emptyKernel[hashIndex]);
clReleaseProgram(factory->utilProgram[hashIndex]);
clReleaseKernel(factory->querySingleKernel[hashIndex]);
clReleaseKernel(factory->insertSingleKernel[hashIndex]);
clReleaseKernel(factory->insertSingleNoOverwriteKernel[hashIndex]);;
return HASH_EXIT_CODE_NORMAL;
}
int intintIdentityPerfectCLHash_DestroyTable(intintHash_Table * table) {
int exitCode = 0;
clReleaseMemObject(table->tableDataBuffer);
clReleaseContext(table->context);
clReleaseCommandQueue(table->queue);
clReleaseProgram(table->utilProgram);
clReleaseKernel(table->emptyKernel);
clReleaseProgram(table->program);
clReleaseKernel(table->querySingleKernel);
clReleaseKernel(table->insertSingleKernel);
clReleaseKernel(table->insertSingleNoOverwriteKernel);
free(table->tableData);
free(table);
return exitCode;
}
int intintIdentityPerfectCLHash_SetupTable(intintHash_Table * table) {
int exitCode = 0;
cl_int err;
err =
clSetKernelArg(table->emptyKernel, 0, sizeof(cl_mem),
&table->tableDataBuffer);
CLHash_Utilities_HandleError(err,
"intintIdentityPerfectCLHash_EmptyTable",
"clSetKernelArg");
const size_t groupWorkSize =
roundUpToNearest(((intintIdentityPerfectHash_TableData *) table->
tableData)->numBuckets,
table->emptyKernelLocalWorkSize);
err =
clEnqueueNDRangeKernel(table->queue, table->emptyKernel, 1, 0,
&groupWorkSize,
(const size_t *)&table->
emptyKernelLocalWorkSize, 0, NULL, NULL);
CLHash_Utilities_HandleError(err,
"intintIdentityPerfectCLHash_EmptyTable",
"clEnqueueNDRangeKernel");
exitCode = HASH_EXIT_CODE_NORMAL;;
return exitCode;
}
int intintIdentityPerfectCLHash_EmptyTable(intintHash_Table * table) {
int exitCode = 0;
cl_int err;
err =
clSetKernelArg(table->emptyKernel, 0, sizeof(cl_mem),
&table->tableDataBuffer);
CLHash_Utilities_HandleError(err,
"intintIdentityPerfectCLHash_EmptyTable",
"clSetKernelArg");
const size_t groupWorkSize =
roundUpToNearest(((intintIdentityPerfectHash_TableData *) table->
tableData)->numBuckets,
table->emptyKernelLocalWorkSize);
err =
clEnqueueNDRangeKernel(table->queue, table->emptyKernel, 1, 0,
&groupWorkSize,
(const size_t *)&table->
emptyKernelLocalWorkSize, 0, NULL, NULL);
CLHash_Utilities_HandleError(err,
"intintIdentityPerfectCLHash_EmptyTable",
"clEnqueueNDRangeKernel");
exitCode = HASH_EXIT_CODE_NORMAL;;
return exitCode;
}
int intintIdentityPerfectCLHash_QuerySingle(intintHash_Table * table, int key,
int *valueOutput) {
return intintIdentityPerfectCLHash_Query(table, 1, &key, valueOutput);
}
int intintIdentityPerfectCLHash_Query(intintHash_Table * table, size_t numKeys,
int *keys, int *valuesOutput) {
cl_int err;
cl_mem keysBuffer =
clCreateBuffer(table->context,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(int) * numKeys, keys, &err);
CLHash_Utilities_HandleError(err, "intintIdentityPerfectCLHash_Query",
"clCreateBuffer");
cl_mem valuesOutputBuffer =
clCreateBuffer(table->context, CL_MEM_WRITE_ONLY,
sizeof(int) * numKeys, NULL, &err);
CLHash_Utilities_HandleError(err, "intintIdentityPerfectCLHash_Query",
"clCreateBuffer");
intintIdentityPerfectCLHash_BufferQuery(table, numKeys, keysBuffer,
valuesOutputBuffer);
err =
clEnqueueReadBuffer(table->queue, valuesOutputBuffer, CL_TRUE, 0,
sizeof(int) * numKeys, valuesOutput, 0, NULL,
NULL);
CLHash_Utilities_HandleError(err, "intintIdentityPerfectCLHash_Query",
"clEnqueueReadBuffer");
clReleaseMemObject(keysBuffer);
clReleaseMemObject(valuesOutputBuffer);
return HASH_EXIT_CODE_NORMAL;
}
int intintIdentityPerfectCLHash_BufferQuery(intintHash_Table * table,
size_t numKeys, cl_mem keysBuffer,
cl_mem valuesOutputBuffer) {
cl_int err;
err =
clSetKernelArg(table->querySingleKernel, 0, sizeof(cl_mem),
&table->tableDataBuffer);
CLHash_Utilities_HandleError(err,
"intintIdentityPerfectCLHash_BufferQuery",
"clSetKernelArg");
err =
clSetKernelArg(table->querySingleKernel, 1, sizeof(unsigned int),
&numKeys);
CLHash_Utilities_HandleError(err,
"intintIdentityPerfectCLHash_BufferQuery",
"clSetKernelArg");
err =
clSetKernelArg(table->querySingleKernel, 2, sizeof(cl_mem),
&keysBuffer);
CLHash_Utilities_HandleError(err,
"intintIdentityPerfectCLHash_BufferQuery",
"clSetKernelArg");
err =
clSetKernelArg(table->querySingleKernel, 3, sizeof(cl_mem),
&valuesOutputBuffer);
CLHash_Utilities_HandleError(err,
"intintIdentityPerfectCLHash_BufferQuery",
"clSetKernelArg");
const size_t groupWorkSize =
roundUpToNearest(numKeys, table->localWorkSize);
err =
clEnqueueNDRangeKernel(table->queue, table->querySingleKernel, 1, 0,
&groupWorkSize,
(const size_t *)&table->localWorkSize, 0,
NULL, NULL);
CLHash_Utilities_HandleError(err,
"intintIdentityPerfectCLHash_BufferQuery",
"clEnqueueNDRangeKernel");
clFinish(table->queue);
return HASH_EXIT_CODE_NORMAL;
}
int intintIdentityPerfectCLHash_InsertSingle(intintHash_Table * table, int key,
int value) {
return intintIdentityPerfectCLHash_Insert(table, 1, &key, &value);
}
int intintIdentityPerfectCLHash_Insert(intintHash_Table * table,
size_t numEntries, int *keys,
int *values) {
cl_int err;
cl_mem keysBuffer =
clCreateBuffer(table->context,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(int) * numEntries, keys, &err);
CLHash_Utilities_HandleError(err, "intintIdentityPerfectCLHash_Insert",
"clCreateBuffer");
cl_mem valuesBuffer =
clCreateBuffer(table->context,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(int) * numEntries, values, &err);
CLHash_Utilities_HandleError(err, "intintIdentityPerfectCLHash_Insert",
"clCreateBuffer");
intintIdentityPerfectCLHash_BufferInsert(table, numEntries, keysBuffer,
valuesBuffer);
clReleaseMemObject(keysBuffer);
clReleaseMemObject(valuesBuffer);
return HASH_EXIT_CODE_NORMAL;
}
int intintIdentityPerfectCLHash_BufferInsert(intintHash_Table * table,
size_t numEntries,
cl_mem keysBuffer,
cl_mem valuesBuffer) {
cl_int err;
err =
clSetKernelArg(table->insertSingleKernel, 0, sizeof(cl_mem),
&table->tableDataBuffer);
CLHash_Utilities_HandleError(err,
"intintIdentityPerfectCLHash_BufferInsert",
"clSetKernelArg");
err =
clSetKernelArg(table->insertSingleKernel, 1, sizeof(unsigned int),
&numEntries);
CLHash_Utilities_HandleError(err,
"intintIdentityPerfectCLHash_BufferInsert",
"clSetKernelArg");
err =
clSetKernelArg(table->insertSingleKernel, 2, sizeof(cl_mem),
&keysBuffer);
CLHash_Utilities_HandleError(err,
"intintIdentityPerfectCLHash_BufferInsert",
"clSetKernelArg");
err =
clSetKernelArg(table->insertSingleKernel, 3, sizeof(cl_mem),
&valuesBuffer);
CLHash_Utilities_HandleError(err,
"intintIdentityPerfectCLHash_BufferInsert",
"clSetKernelArg");
const size_t groupWorkSize =
roundUpToNearest(numEntries, table->localWorkSize);
err =
clEnqueueNDRangeKernel(table->queue, table->insertSingleKernel, 1,
0, &groupWorkSize,
(const size_t *)&table->localWorkSize, 0,
NULL, NULL);
CLHash_Utilities_HandleError(err, NULL, "clEnqueueNDRangeKernel");
return (0);
}
int intintIdentityPerfectCLHash_InsertSingleNoOverwrite(intintHash_Table *
table, int key,
int value) {
return intintIdentityPerfectCLHash_InsertNoOverwrite(table, 1, &key,
&value);
}
int intintIdentityPerfectCLHash_InsertNoOverwrite(intintHash_Table * table,
size_t numEntries, int *keys,
int *values) {
cl_int err;
cl_mem keysBuffer =
clCreateBuffer(table->context,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(int) * numEntries, keys, &err);
CLHash_Utilities_HandleError(err,
"intintIdentityPerfectCLHash_InsertNoOverwrite",
"clCreateBuffer");
cl_mem valuesBuffer =
clCreateBuffer(table->context,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(int) * numEntries, values, &err);
CLHash_Utilities_HandleError(err,
"intintIdentityPerfectCLHash_InsertNoOverwrite",
"clCreateBuffer");
intintIdentityPerfectCLHash_BufferInsertNoOverwrite(table, numEntries,
keysBuffer,
valuesBuffer);
clReleaseMemObject(keysBuffer);
clReleaseMemObject(valuesBuffer);
return HASH_EXIT_CODE_NORMAL;
}
int intintIdentityPerfectCLHash_BufferInsertNoOverwrite(intintHash_Table *
table,
size_t numEntries,
cl_mem keysBuffer,
cl_mem valuesBuffer) {
cl_int err;
err =
clSetKernelArg(table->insertSingleNoOverwriteKernel, 0,
sizeof(cl_mem), &table->tableDataBuffer);
CLHash_Utilities_HandleError(err,
"intintIdentityPerfectCLHash_BufferInsertNoOverwrite",
"clSetKernelArg");
err =
clSetKernelArg(table->insertSingleNoOverwriteKernel, 1,
sizeof(unsigned int), &numEntries);
CLHash_Utilities_HandleError(err,
"intintIdentityPerfectCLHash_BufferInsertNoOverwrite",
"ClSetKernelArg");
err =
clSetKernelArg(table->insertSingleNoOverwriteKernel, 2,
sizeof(cl_mem), &keysBuffer);
CLHash_Utilities_HandleError(err,
"intintIdentityPerfectCLHash_BufferInsertNoOverwrite",
"clSetKernelArg");
err =
clSetKernelArg(table->insertSingleNoOverwriteKernel, 3,
sizeof(cl_mem), &valuesBuffer);
CLHash_Utilities_HandleError(err,
"intintIdentityPerfectCLHash_BufferInsertNoOverwrite",
"clSetKernelArg");
const size_t groupWorkSize =
roundUpToNearest(numEntries, table->localWorkSize);
err =
clEnqueueNDRangeKernel(table->queue,
table->insertSingleNoOverwriteKernel, 1, 0,
&groupWorkSize,
(const size_t *)&table->localWorkSize, 0,
NULL, NULL);
CLHash_Utilities_HandleError(err,
"intintIdentityPerfectCLHash_BufferInsertNoOverwrite",
"clEnqueueNDRangeKernel");
return (0);
}
typedef struct intintIdentityPerfectOpenMPHash_TableData {
int hashID;
unsigned int numBuckets;
char compressFuncData;
} intintIdentityPerfectOpenMPHash_TableData;
typedef struct intintIdentityPerfectOpenMPHash_Bucket {
int key;
int value;
} intintIdentityPerfectOpenMPHash_Bucket;
intintHash_Table *intintIdentityPerfectOpenMPHash_CreateTable(intintHash_Factory
* factory,
int hashIndex,
size_t keyRange,
size_t numEntries,
float loadFactor)
{
intintHash_Table *table =
(intintHash_Table *) malloc(sizeof(intintHash_Table));
table->destroyFunc = &intintIdentityPerfectOpenMPHash_DestroyTable;
table->setupFunc = &intintIdentityPerfectOpenMPHash_SetupTable;
table->emptyFunc = &intintIdentityPerfectOpenMPHash_EmptyTable;
table->queryFunc = &intintIdentityPerfectOpenMPHash_Query;
table->querySingleFunc = &intintIdentityPerfectOpenMPHash_QuerySingle;
table->insertFunc = &intintIdentityPerfectOpenMPHash_Insert;
table->insertSingleFunc = &intintIdentityPerfectOpenMPHash_InsertSingle;
table->insertNoOverwriteFunc =
&intintIdentityPerfectOpenMPHash_InsertNoOverwrite;
table->insertSingleNoOverwriteFunc =
&intintIdentityPerfectOpenMPHash_InsertSingleNoOverwrite;
table->tableData =
(char *)malloc(sizeof(intintIdentityPerfectOpenMPHash_TableData));
((intintIdentityPerfectOpenMPHash_TableData *) table->tableData)->
hashID = IDENTITY_PERFECT_OPENMP_HASH_ID;
((intintIdentityPerfectOpenMPHash_TableData *) table->tableData)->
numBuckets = keyRange + 1;
char *tempHashData =
(char *)malloc(sizeof(intintIdentityPerfectOpenMPHash_TableData) +
((intintIdentityPerfectOpenMPHash_TableData *)
table->tableData)->numBuckets *
sizeof(intintIdentityPerfectOpenMPHash_Bucket));
memcpy(tempHashData, table->tableData,
sizeof(intintIdentityPerfectOpenMPHash_TableData));
free(table->tableData);
table->tableData = tempHashData;
return table;
}
int intintIdentityPerfectOpenMPHash_CreateFactory(intintHash_Factory * factory,
int hashIndex) {
factory->createFunc[hashIndex] =
&intintIdentityPerfectOpenMPHash_CreateTable;
factory->destroyFunc[hashIndex] =
&intintIdentityPerfectOpenMPHash_DestroyFactory;;
return HASH_EXIT_CODE_NORMAL;
}
int intintIdentityPerfectOpenMPHash_DestroyFactory(intintHash_Factory * factory,
int hashIndex) {;
return HASH_EXIT_CODE_NORMAL;
}
int intintIdentityPerfectOpenMPHash_DestroyTable(intintHash_Table * table) {
int exitCode = 0;
free(table->tableData);
free(table);
return exitCode;
}
int intintIdentityPerfectOpenMPHash_SetupTable(intintHash_Table * table) {
int exitCode = 0;
intintIdentityPerfectOpenMPHash_Bucket *buckets =
(intintIdentityPerfectOpenMPHash_Bucket *) & table->
tableData[sizeof(intintIdentityPerfectOpenMPHash_TableData)];
if (intintHash_GetTableType(table) & ~HASH_SENTINEL_PERFECT_HASHES) {
#pragma omp parallel for
for (int index = 0;
index <
((intintIdentityPerfectOpenMPHash_TableData *) table->
tableData)->numBuckets; index++) {
buckets[index].key = HASH_BUCKET_STATUS_EMPTY;
}}
exitCode = HASH_EXIT_CODE_NORMAL;
return exitCode;
}
int intintIdentityPerfectOpenMPHash_EmptyTable(intintHash_Table * table) {
int exitCode = 0;
intintIdentityPerfectOpenMPHash_Bucket *buckets =
(intintIdentityPerfectOpenMPHash_Bucket *) & table->
tableData[sizeof(intintIdentityPerfectOpenMPHash_TableData)];
#pragma omp parallel for
for (int index = 0;
index <
((intintIdentityPerfectOpenMPHash_TableData *) table->tableData)->
numBuckets; index++) {
buckets[index].key = HASH_BUCKET_STATUS_EMPTY;
} exitCode = HASH_EXIT_CODE_NORMAL;
return exitCode;
}
int intintIdentityPerfectOpenMPHash_InnerQuerySingle(char *tableData, int key,
int *valueOutput) {
intintIdentityPerfectOpenMPHash_Bucket *buckets =
(intintIdentityPerfectOpenMPHash_Bucket *) &
tableData[sizeof(intintIdentityPerfectOpenMPHash_TableData)];
int index;
int exitCode;
index =
intintHash_CompressIdentity(((intintIdentityPerfectOpenMPHash_TableData *) tableData)->compressFuncData, key);
if ((buckets[index].key) != HASH_BUCKET_STATUS_EMPTY) {
if (key == buckets[index].key) {
exitCode = HASH_SEARCH_CODE_MATCH;
} else {
exitCode = HASH_SEARCH_CODE_MISMATCH;
}
} else {
exitCode = HASH_SEARCH_CODE_EMPTY;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
*valueOutput = buckets[index].value;
return HASH_EXIT_CODE_NORMAL;
case HASH_SEARCH_CODE_MISMATCH:
case HASH_SEARCH_CODE_EMPTY:
return HASH_EXIT_CODE_KEY_DNE;
default:
return exitCode;
}
}
int intintIdentityPerfectOpenMPHash_InnerQuery(char *tableData,
unsigned int numKeys, int *keys,
int *valuesOutput) {
intintIdentityPerfectOpenMPHash_Bucket *buckets =
(intintIdentityPerfectOpenMPHash_Bucket *) &
tableData[sizeof(intintIdentityPerfectOpenMPHash_TableData)];
int key;
int *valueOutput;
int index;
int exitCode;
uint i;
int resultExitCode = HASH_EXIT_CODE_NORMAL;
for (i = 0; i < numKeys; i++) {
key = keys[i];
valueOutput = &valuesOutput[i];
index =
intintHash_CompressIdentity(((intintIdentityPerfectOpenMPHash_TableData *) tableData)->compressFuncData, key);
if ((buckets[index].key) != HASH_BUCKET_STATUS_EMPTY) {
if (key == buckets[index].key) {
exitCode = HASH_SEARCH_CODE_MATCH;
} else {
exitCode = HASH_SEARCH_CODE_MISMATCH;
}
} else {
exitCode = HASH_SEARCH_CODE_EMPTY;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
*valueOutput = buckets[index].value;
break;
case HASH_SEARCH_CODE_MISMATCH:
case HASH_SEARCH_CODE_EMPTY:
resultExitCode = HASH_EXIT_CODE_KEY_DNE;
break;
default:
return exitCode;
}
}
return resultExitCode;
}
int intintIdentityPerfectOpenMPHash_InnerInsertSingle(char *tableData, int key,
int value) {
intintIdentityPerfectOpenMPHash_Bucket *buckets =
(intintIdentityPerfectOpenMPHash_Bucket *) &
tableData[sizeof(intintIdentityPerfectOpenMPHash_TableData)];
int index;
int exitCode;
index =
intintHash_CompressIdentity(((intintIdentityPerfectOpenMPHash_TableData *) tableData)->compressFuncData, key);
if (((buckets[index].key ==
HASH_BUCKET_STATUS_EMPTY) ? (buckets[index].key =
key,
HASH_BUCKET_STATUS_EMPTY) :
buckets[index].key) != HASH_BUCKET_STATUS_EMPTY) {
if (key == buckets[index].key) {
exitCode = HASH_SEARCH_CODE_MATCH;
} else {
exitCode = HASH_SEARCH_CODE_MISMATCH;
}
} else {
exitCode = HASH_SEARCH_CODE_EMPTY;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
buckets[index].value = value;
return HASH_EXIT_CODE_OVERWRITE;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = value;
return HASH_EXIT_CODE_NORMAL;
default:
return exitCode;
}
}
int intintIdentityPerfectOpenMPHash_InnerInsert(char *tableData,
unsigned int numEntries,
int *keys, int *values) {
intintIdentityPerfectOpenMPHash_Bucket *buckets =
(intintIdentityPerfectOpenMPHash_Bucket *) &
tableData[sizeof(intintIdentityPerfectOpenMPHash_TableData)];
int resultExitCode = HASH_EXIT_CODE_NORMAL;
int key;
int index;
int exitCode;
uint i;
#pragma omp parallel for
for (i = 0; i < numEntries; i++) {
key = keys[i];
index =
intintHash_CompressIdentity(((intintIdentityPerfectOpenMPHash_TableData *) tableData)->compressFuncData, key);
if (((buckets[index].key ==
HASH_BUCKET_STATUS_EMPTY) ? (buckets[index].key =
key,
HASH_BUCKET_STATUS_EMPTY) :
buckets[index].key) != HASH_BUCKET_STATUS_EMPTY) {
if (key == buckets[index].key) {
exitCode = HASH_SEARCH_CODE_MATCH;
} else {
exitCode = HASH_SEARCH_CODE_MISMATCH;
}
} else {
exitCode = HASH_SEARCH_CODE_EMPTY;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
resultExitCode = HASH_EXIT_CODE_OVERWRITE;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = values[i];
break;
default:
resultExitCode = exitCode;
}
}
return resultExitCode;
}
int intintIdentityPerfectOpenMPHash_InnerInsertSingleNoOverwrite(char
*tableData,
int key,
int value) {
intintIdentityPerfectOpenMPHash_Bucket *buckets =
(intintIdentityPerfectOpenMPHash_Bucket *) &
tableData[sizeof(intintIdentityPerfectOpenMPHash_TableData)];
int index;
int exitCode;
index =
intintHash_CompressIdentity(((intintIdentityPerfectOpenMPHash_TableData *) tableData)->compressFuncData, key);
if (((buckets[index].key ==
HASH_BUCKET_STATUS_EMPTY) ? (buckets[index].key =
key,
HASH_BUCKET_STATUS_EMPTY) :
buckets[index].key) != HASH_BUCKET_STATUS_EMPTY) {
if (key == buckets[index].key) {
exitCode = HASH_SEARCH_CODE_MATCH;
} else {
exitCode = HASH_SEARCH_CODE_MISMATCH;
}
} else {
exitCode = HASH_SEARCH_CODE_EMPTY;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
return HASH_EXIT_CODE_OVERWRITE;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = value;
return HASH_EXIT_CODE_NORMAL;
default:
return exitCode;
}
}
int intintIdentityPerfectOpenMPHash_InnerInsertNoOverwrite(char *tableData,
unsigned int
numEntries,
int *keys,
int *values) {
intintIdentityPerfectOpenMPHash_Bucket *buckets =
(intintIdentityPerfectOpenMPHash_Bucket *) &
tableData[sizeof(intintIdentityPerfectOpenMPHash_TableData)];
int resultExitCode = HASH_EXIT_CODE_NORMAL;
int key;
int index;
int exitCode;
uint i;
#pragma omp parallel for
for (i = 0; i < numEntries; i++) {
key = keys[i];
index =
intintHash_CompressIdentity(((intintIdentityPerfectOpenMPHash_TableData *) tableData)->compressFuncData, key);
if (((buckets[index].key ==
HASH_BUCKET_STATUS_EMPTY) ? (buckets[index].key =
key,
HASH_BUCKET_STATUS_EMPTY) :
buckets[index].key) != HASH_BUCKET_STATUS_EMPTY) {
if (key == buckets[index].key) {
exitCode = HASH_SEARCH_CODE_MATCH;
} else {
exitCode = HASH_SEARCH_CODE_MISMATCH;
}
} else {
exitCode = HASH_SEARCH_CODE_EMPTY;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
resultExitCode = HASH_EXIT_CODE_OVERWRITE;
break;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = values[i];
break;
default:
resultExitCode = exitCode;
}
}
return resultExitCode;
}
int intintIdentityPerfectOpenMPHash_QuerySingle(intintHash_Table * table,
int key, int *valueOutput) {
return intintIdentityPerfectOpenMPHash_InnerQuerySingle(table->
tableData, key,
valueOutput);
}
int intintIdentityPerfectOpenMPHash_Query(intintHash_Table * table,
size_t numKeys, int *keys,
int *valuesOutput) {
return intintIdentityPerfectOpenMPHash_InnerQuery(table->tableData,
numKeys, keys,
valuesOutput);
}
int intintIdentityPerfectOpenMPHash_InsertSingle(intintHash_Table * table,
int key, int value) {
return intintIdentityPerfectOpenMPHash_InnerInsertSingle(table->
tableData, key,
value);
}
int intintIdentityPerfectOpenMPHash_Insert(intintHash_Table * table,
size_t numEntries, int *keys,
int *values) {
return intintIdentityPerfectOpenMPHash_InnerInsert(table->tableData,
numEntries, keys,
values);
}
int intintIdentityPerfectOpenMPHash_InsertSingleNoOverwrite(intintHash_Table *
table, int key,
int value) {
return
intintIdentityPerfectOpenMPHash_InnerInsertSingleNoOverwrite(table->
tableData,
key,
value);
}
int intintIdentityPerfectOpenMPHash_InsertNoOverwrite(intintHash_Table * table,
size_t numEntries,
int *keys, int *values) {
return intintIdentityPerfectOpenMPHash_InnerInsertNoOverwrite(table->
tableData,
numEntries,
keys,
values);
}
typedef struct intintIdentitySentinelPerfectHash_TableData {
int hashID;
unsigned int numBuckets;
char compressFuncData;
int emptyValue;
} intintIdentitySentinelPerfectHash_TableData;
typedef struct intintIdentitySentinelPerfectHash_Bucket {
int value;
} intintIdentitySentinelPerfectHash_Bucket;
intintHash_Table
*intintIdentitySentinelPerfectHash_CreateTable(intintHash_Factory * factory,
int hashIndex,
size_t keyRange,
size_t numEntries,
float loadFactor) {
intintHash_Table *table =
(intintHash_Table *) malloc(sizeof(intintHash_Table));
table->destroyFunc = &intintIdentitySentinelPerfectHash_DestroyTable;
table->setupFunc = &intintIdentitySentinelPerfectHash_SetupTable;
table->emptyFunc = &intintIdentitySentinelPerfectHash_EmptyTable;
table->queryFunc = &intintIdentitySentinelPerfectHash_Query;
table->querySingleFunc = &intintIdentitySentinelPerfectHash_QuerySingle;
table->insertFunc = &intintIdentitySentinelPerfectHash_Insert;
table->insertSingleFunc =
&intintIdentitySentinelPerfectHash_InsertSingle;
table->insertNoOverwriteFunc =
&intintIdentitySentinelPerfectHash_InsertNoOverwrite;
table->insertSingleNoOverwriteFunc =
&intintIdentitySentinelPerfectHash_InsertSingleNoOverwrite;
table->tableData =
(char *)malloc(sizeof(intintIdentitySentinelPerfectHash_TableData));
((intintIdentitySentinelPerfectHash_TableData *) table->tableData)->
hashID = IDENTITY_SENTINEL_PERFECT_HASH_ID;
((intintIdentitySentinelPerfectHash_TableData *) table->tableData)->
emptyValue = factory->emptyValue;
((intintIdentitySentinelPerfectHash_TableData *) table->tableData)->
numBuckets = keyRange + 1;
char *tempHashData =
(char *)malloc(sizeof(intintIdentitySentinelPerfectHash_TableData) +
((intintIdentitySentinelPerfectHash_TableData *)
table->tableData)->numBuckets *
sizeof(intintIdentitySentinelPerfectHash_Bucket));
memcpy(tempHashData, table->tableData,
sizeof(intintIdentitySentinelPerfectHash_TableData));
free(table->tableData);
table->tableData = tempHashData;
return table;
}
int intintIdentitySentinelPerfectHash_CreateFactory(intintHash_Factory *
factory, int hashIndex) {
factory->createFunc[hashIndex] =
&intintIdentitySentinelPerfectHash_CreateTable;
factory->destroyFunc[hashIndex] =
&intintIdentitySentinelPerfectHash_DestroyFactory;;
return HASH_EXIT_CODE_NORMAL;
}
int intintIdentitySentinelPerfectHash_DestroyFactory(intintHash_Factory *
factory, int hashIndex) {;
return HASH_EXIT_CODE_NORMAL;
}
int intintIdentitySentinelPerfectHash_DestroyTable(intintHash_Table * table) {
int exitCode = 0;
free(table->tableData);
free(table);
return exitCode;
}
int intintIdentitySentinelPerfectHash_SetupTable(intintHash_Table * table) {
int exitCode = 0;
intintIdentitySentinelPerfectHash_Bucket *buckets =
(intintIdentitySentinelPerfectHash_Bucket *) & table->
tableData[sizeof(intintIdentitySentinelPerfectHash_TableData)];
if (intintHash_GetTableType(table) & ~HASH_SENTINEL_PERFECT_HASHES) {
for (int index = 0;
index <
((intintIdentitySentinelPerfectHash_TableData *) table->
tableData)->numBuckets; index++) {
buckets[index].value =
((intintIdentitySentinelPerfectHash_TableData *)
table->tableData)->emptyValue;
}}
exitCode = HASH_EXIT_CODE_NORMAL;
return exitCode;
}
int intintIdentitySentinelPerfectHash_EmptyTable(intintHash_Table * table) {
int exitCode = 0;
intintIdentitySentinelPerfectHash_Bucket *buckets =
(intintIdentitySentinelPerfectHash_Bucket *) & table->
tableData[sizeof(intintIdentitySentinelPerfectHash_TableData)];
for (int index = 0;
index <
((intintIdentitySentinelPerfectHash_TableData *) table->
tableData)->numBuckets; index++) {
buckets[index].value =
((intintIdentitySentinelPerfectHash_TableData *) table->
tableData)->emptyValue;
} exitCode = HASH_EXIT_CODE_NORMAL;
return exitCode;
}
int intintIdentitySentinelPerfectHash_InnerQuerySingle(char *tableData, int key,
int *valueOutput) {
intintIdentitySentinelPerfectHash_Bucket *buckets =
(intintIdentitySentinelPerfectHash_Bucket *) &
tableData[sizeof(intintIdentitySentinelPerfectHash_TableData)];
int index;
int exitCode;
index =
intintHash_CompressIdentity(((intintIdentitySentinelPerfectHash_TableData *) tableData)->compressFuncData, key);
if (buckets[index].value !=
((intintIdentitySentinelPerfectHash_TableData *) tableData)->
emptyValue) {
exitCode = HASH_SEARCH_CODE_MATCH;
} else {
exitCode = HASH_SEARCH_CODE_EMPTY;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
*valueOutput = buckets[index].value;
return HASH_EXIT_CODE_NORMAL;
case HASH_SEARCH_CODE_MISMATCH:
case HASH_SEARCH_CODE_EMPTY:
return HASH_EXIT_CODE_KEY_DNE;
default:
return exitCode;
}
}
int intintIdentitySentinelPerfectHash_InnerQuery(char *tableData,
unsigned int numKeys,
int *keys, int *valuesOutput) {
intintIdentitySentinelPerfectHash_Bucket *buckets =
(intintIdentitySentinelPerfectHash_Bucket *) &
tableData[sizeof(intintIdentitySentinelPerfectHash_TableData)];
int key;
int *valueOutput;
int index;
int exitCode;
uint i;
int resultExitCode = HASH_EXIT_CODE_NORMAL;
for (i = 0; i < numKeys; i++) {
key = keys[i];
valueOutput = &valuesOutput[i];
index =
intintHash_CompressIdentity(((intintIdentitySentinelPerfectHash_TableData *) tableData)->compressFuncData, key);
if (buckets[index].value !=
((intintIdentitySentinelPerfectHash_TableData *)
tableData)->emptyValue) {
exitCode = HASH_SEARCH_CODE_MATCH;
} else {
exitCode = HASH_SEARCH_CODE_EMPTY;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
*valueOutput = buckets[index].value;
break;
case HASH_SEARCH_CODE_MISMATCH:
case HASH_SEARCH_CODE_EMPTY:
resultExitCode = HASH_EXIT_CODE_KEY_DNE;
break;
default:
return exitCode;
}
}
return resultExitCode;
}
int intintIdentitySentinelPerfectHash_InnerInsertSingle(char *tableData,
int key, int value) {
intintIdentitySentinelPerfectHash_Bucket *buckets =
(intintIdentitySentinelPerfectHash_Bucket *) &
tableData[sizeof(intintIdentitySentinelPerfectHash_TableData)];
int index;
int exitCode;
index =
intintHash_CompressIdentity(((intintIdentitySentinelPerfectHash_TableData *) tableData)->compressFuncData, key);
if (buckets[index].value !=
((intintIdentitySentinelPerfectHash_TableData *) tableData)->
emptyValue) {
exitCode = HASH_SEARCH_CODE_MATCH;
} else {
exitCode = HASH_SEARCH_CODE_EMPTY;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
buckets[index].value = value;
return HASH_EXIT_CODE_OVERWRITE;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = value;
return HASH_EXIT_CODE_NORMAL;
default:
return exitCode;
}
}
int intintIdentitySentinelPerfectHash_InnerInsert(char *tableData,
unsigned int numEntries,
int *keys, int *values) {
intintIdentitySentinelPerfectHash_Bucket *buckets =
(intintIdentitySentinelPerfectHash_Bucket *) &
tableData[sizeof(intintIdentitySentinelPerfectHash_TableData)];
int resultExitCode = HASH_EXIT_CODE_NORMAL;
int key;
int index;
int exitCode;
uint i;;
for (i = 0; i < numEntries; i++) {
key = keys[i];
index =
intintHash_CompressIdentity(((intintIdentitySentinelPerfectHash_TableData *) tableData)->compressFuncData, key);
if (buckets[index].value !=
((intintIdentitySentinelPerfectHash_TableData *)
tableData)->emptyValue) {
exitCode = HASH_SEARCH_CODE_MATCH;
} else {
exitCode = HASH_SEARCH_CODE_EMPTY;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
resultExitCode = HASH_EXIT_CODE_OVERWRITE;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = values[i];
break;
default:
resultExitCode = exitCode;
}
}
return resultExitCode;
}
int intintIdentitySentinelPerfectHash_InnerInsertSingleNoOverwrite(char
*tableData,
int key,
int value) {
intintIdentitySentinelPerfectHash_Bucket *buckets =
(intintIdentitySentinelPerfectHash_Bucket *) &
tableData[sizeof(intintIdentitySentinelPerfectHash_TableData)];
int index;
int exitCode;
index =
intintHash_CompressIdentity(((intintIdentitySentinelPerfectHash_TableData *) tableData)->compressFuncData, key);
if (buckets[index].value !=
((intintIdentitySentinelPerfectHash_TableData *) tableData)->
emptyValue) {
exitCode = HASH_SEARCH_CODE_MATCH;
} else {
exitCode = HASH_SEARCH_CODE_EMPTY;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
return HASH_EXIT_CODE_OVERWRITE;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = value;
return HASH_EXIT_CODE_NORMAL;
default:
return exitCode;
}
}
int intintIdentitySentinelPerfectHash_InnerInsertNoOverwrite(char *tableData,
unsigned int
numEntries,
int *keys,
int *values) {
intintIdentitySentinelPerfectHash_Bucket *buckets =
(intintIdentitySentinelPerfectHash_Bucket *) &
tableData[sizeof(intintIdentitySentinelPerfectHash_TableData)];
int resultExitCode = HASH_EXIT_CODE_NORMAL;
int key;
int index;
int exitCode;
uint i;;
for (i = 0; i < numEntries; i++) {
key = keys[i];
index =
intintHash_CompressIdentity(((intintIdentitySentinelPerfectHash_TableData *) tableData)->compressFuncData, key);
if (buckets[index].value !=
((intintIdentitySentinelPerfectHash_TableData *)
tableData)->emptyValue) {
exitCode = HASH_SEARCH_CODE_MATCH;
} else {
exitCode = HASH_SEARCH_CODE_EMPTY;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
resultExitCode = HASH_EXIT_CODE_OVERWRITE;
break;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = values[i];
break;
default:
resultExitCode = exitCode;
}
}
return resultExitCode;
}
int intintIdentitySentinelPerfectHash_QuerySingle(intintHash_Table * table,
int key, int *valueOutput) {
return intintIdentitySentinelPerfectHash_InnerQuerySingle(table->
tableData,
key,
valueOutput);
}
int intintIdentitySentinelPerfectHash_Query(intintHash_Table * table,
size_t numKeys, int *keys,
int *valuesOutput) {
return intintIdentitySentinelPerfectHash_InnerQuery(table->tableData,
numKeys, keys,
valuesOutput);
}
int intintIdentitySentinelPerfectHash_InsertSingle(intintHash_Table * table,
int key, int value) {
return intintIdentitySentinelPerfectHash_InnerInsertSingle(table->
tableData,
key, value);
}
int intintIdentitySentinelPerfectHash_Insert(intintHash_Table * table,
size_t numEntries, int *keys,
int *values) {
return intintIdentitySentinelPerfectHash_InnerInsert(table->tableData,
numEntries, keys,
values);
}
int intintIdentitySentinelPerfectHash_InsertSingleNoOverwrite(intintHash_Table *
table, int key,
int value) {
return
intintIdentitySentinelPerfectHash_InnerInsertSingleNoOverwrite
(table->tableData, key, value);
}
int intintIdentitySentinelPerfectHash_InsertNoOverwrite(intintHash_Table *
table,
size_t numEntries,
int *keys,
int *values) {
return intintIdentitySentinelPerfectHash_InnerInsertNoOverwrite(table->
tableData,
numEntries,
keys,
values);
}
typedef struct intintIdentitySentinelPerfectCLHash_TableData {
int hashID;
unsigned int numBuckets;
char compressFuncData;
int emptyValue;
} intintIdentitySentinelPerfectCLHash_TableData;
typedef struct intintIdentitySentinelPerfectCLHash_Bucket {
int value;
} intintIdentitySentinelPerfectCLHash_Bucket;
intintHash_Table
*intintIdentitySentinelPerfectCLHash_CreateTable(intintHash_Factory *
factory, int hashIndex,
size_t keyRange,
size_t numEntries,
float loadFactor) {
intintHash_Table *table =
(intintHash_Table *) malloc(sizeof(intintHash_Table));
table->destroyFunc = &intintIdentitySentinelPerfectCLHash_DestroyTable;
table->setupFunc = &intintIdentitySentinelPerfectCLHash_SetupTable;
table->emptyFunc = &intintIdentitySentinelPerfectCLHash_EmptyTable;
table->queryFunc = &intintIdentitySentinelPerfectCLHash_Query;
table->querySingleFunc =
&intintIdentitySentinelPerfectCLHash_QuerySingle;
table->insertFunc = &intintIdentitySentinelPerfectCLHash_Insert;
table->insertSingleFunc =
&intintIdentitySentinelPerfectCLHash_InsertSingle;
table->insertNoOverwriteFunc =
&intintIdentitySentinelPerfectCLHash_InsertNoOverwrite;
table->insertSingleNoOverwriteFunc =
&intintIdentitySentinelPerfectCLHash_InsertSingleNoOverwrite;
table->tableData =
(char *)
malloc(sizeof(intintIdentitySentinelPerfectCLHash_TableData));
((intintIdentitySentinelPerfectCLHash_TableData *) table->tableData)->
hashID = IDENTITY_SENTINEL_PERFECT_CL_HASH_ID;
table->context = factory->context;
table->queue = factory->queue;
table->program = factory->program;
table->localWorkSize = factory->localWorkSize;
table->utilProgram = factory->utilProgram[hashIndex];
table->emptyKernel = factory->emptyKernel[hashIndex];
table->emptyKernelLocalWorkSize =
factory->emptyKernelLocalWorkSize[hashIndex];
table->querySingleKernel = factory->querySingleKernel[hashIndex];
table->insertSingleKernel = factory->insertSingleKernel[hashIndex];
table->insertSingleNoOverwriteKernel =
factory->insertSingleNoOverwriteKernel[hashIndex];
clRetainContext(table->context);
clRetainCommandQueue(table->queue);
clRetainProgram(table->program);
clRetainProgram(table->utilProgram);
clRetainKernel(table->emptyKernel);
clRetainKernel(table->querySingleKernel);
clRetainKernel(table->insertSingleKernel);
clRetainKernel(table->insertSingleNoOverwriteKernel);;
((intintIdentitySentinelPerfectCLHash_TableData *) table->tableData)->
emptyValue = factory->emptyValue;
((intintIdentitySentinelPerfectCLHash_TableData *) table->tableData)->
numBuckets = keyRange + 1;
char *tempHashData =
(char *)malloc(sizeof(intintIdentitySentinelPerfectCLHash_TableData)
+
((intintIdentitySentinelPerfectCLHash_TableData *)
table->tableData)->numBuckets *
sizeof(intintIdentitySentinelPerfectCLHash_Bucket));
memcpy(tempHashData, table->tableData,
sizeof(intintIdentitySentinelPerfectCLHash_TableData));
free(table->tableData);
table->tableData = tempHashData;
cl_int err;
table->tableDataBuffer =
clCreateBuffer(table->context, CL_MEM_READ_WRITE,
sizeof(intintIdentitySentinelPerfectHash_TableData) +
((intintIdentitySentinelPerfectHash_TableData *)
table->tableData)->numBuckets *
sizeof(intintIdentitySentinelPerfectHash_Bucket),
NULL, &err);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_InitTable",
"clCreateBuffer");
err =
clEnqueueWriteBuffer(table->queue, table->tableDataBuffer, CL_TRUE,
0,
sizeof
(intintIdentitySentinelPerfectHash_TableData),
table->tableData, 0, NULL, NULL);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_InitTable",
"clEnqueueWriteBuffer");
return table;
}
int intintIdentitySentinelPerfectCLHash_CreateFactory(intintHash_Factory *
factory, int hashIndex) {
factory->createFunc[hashIndex] =
&intintIdentitySentinelPerfectCLHash_CreateTable;
factory->destroyFunc[hashIndex] =
&intintIdentitySentinelPerfectCLHash_DestroyFactory;
cl_int error;
cl_device_id device;
error =
clGetContextInfo(factory->context, CL_CONTEXT_DEVICES,
sizeof(device), &device, NULL);
CLHash_Utilities_HandleError(error, "intintHash_CreateFactory",
"clGetContextInfo");
factory->querySingleKernel[hashIndex] =
clCreateKernel(factory->program,
"intintIdentitySentinelPerfectCLHash_RangeQuerySingle",
&error);
CLHash_Utilities_HandleError(error,
"intintIdentitySentinelPerfectCLHash_CreateFactory",
"clCreateKernel");
factory->insertSingleKernel[hashIndex] =
clCreateKernel(factory->program,
"intintIdentitySentinelPerfectCLHash_RangeInsertSingle",
&error);
CLHash_Utilities_HandleError(error,
"intintIdentitySentinelPerfectCLHash_CreateFactory",
"clCreateKernel");
factory->insertSingleNoOverwriteKernel[hashIndex] =
clCreateKernel(factory->program,
"intintIdentitySentinelPerfectCLHash_RangeInsertSingleNoOverwrite",
&error);
CLHash_Utilities_HandleError(error,
"intintIdentitySentinelPerfectCLHash_CreateFactory",
"clCreateKernel");
factory->utilProgram[hashIndex] =
CLHash_Utilities_BuildProgramString(factory->context, device,
"static inline unsigned int intintHash_CompressIdentity(char data, int hashCode){ return hashCode; } typedef struct intintHash_CompressLCGData{ long unsigned int a; long unsigned int c; unsigned int m; unsigned int n; }intintHash_CompressLCGData; static inline unsigned int intintHash_CompressLCG(intintHash_CompressLCGData compressLCGData, int hashCode){ return ((compressLCGData.a * hashCode + compressLCGData.c) % compressLCGData.m) % compressLCGData.n; } typedef struct intintIdentitySentinelPerfectCLHash_TableData{ int hashID; unsigned int numBuckets; char compressFuncData; int emptyValue; }intintIdentitySentinelPerfectCLHash_TableData; typedef struct intintIdentitySentinelPerfectCLHash_Bucket{ int value; }intintIdentitySentinelPerfectCLHash_Bucket; __kernel void intintIdentitySentinelPerfectCLHash_Empty(__global char *tableData){ int index = get_global_id(0); if(index >= ((__global intintIdentitySentinelPerfectCLHash_TableData*)tableData)->numBuckets){ return; } __global intintIdentitySentinelPerfectCLHash_Bucket *buckets = (__global intintIdentitySentinelPerfectCLHash_Bucket*)&tableData[sizeof(intintIdentitySentinelPerfectCLHash_TableData)]; buckets[index].value = ((__global intintIdentitySentinelPerfectCLHash_TableData*)tableData)->emptyValue; }");
factory->emptyKernel[hashIndex] =
clCreateKernel(factory->utilProgram[hashIndex],
"intintIdentitySentinelPerfectCLHash_Empty", &error);
CLHash_Utilities_HandleError(error,
"intintIdentitySentinelPerfectCLHash_CreateFactory",
"clCreateKernel");
error =
clGetKernelWorkGroupInfo(factory->emptyKernel[hashIndex], device,
CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t),
&factory->
emptyKernelLocalWorkSize[hashIndex], NULL);
CLHash_Utilities_HandleError(error,
"intintIdentitySentinelPerfectCLHash_CreateFactory",
"clGetKernelWorkGroupInfo");;;
return HASH_EXIT_CODE_NORMAL;
}
int intintIdentitySentinelPerfectCLHash_DestroyFactory(intintHash_Factory *
factory,
int hashIndex) {;
clReleaseKernel(factory->emptyKernel[hashIndex]);
clReleaseProgram(factory->utilProgram[hashIndex]);
clReleaseKernel(factory->querySingleKernel[hashIndex]);
clReleaseKernel(factory->insertSingleKernel[hashIndex]);
clReleaseKernel(factory->insertSingleNoOverwriteKernel[hashIndex]);;
return HASH_EXIT_CODE_NORMAL;
}
int intintIdentitySentinelPerfectCLHash_DestroyTable(intintHash_Table * table) {
int exitCode = 0;
clReleaseMemObject(table->tableDataBuffer);
clReleaseContext(table->context);
clReleaseCommandQueue(table->queue);
clReleaseProgram(table->utilProgram);
clReleaseKernel(table->emptyKernel);
clReleaseProgram(table->program);
clReleaseKernel(table->querySingleKernel);
clReleaseKernel(table->insertSingleKernel);
clReleaseKernel(table->insertSingleNoOverwriteKernel);
free(table->tableData);
free(table);
return exitCode;
}
int intintIdentitySentinelPerfectCLHash_SetupTable(intintHash_Table * table) {
int exitCode = 0;
cl_int err;
err =
clSetKernelArg(table->emptyKernel, 0, sizeof(cl_mem),
&table->tableDataBuffer);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_EmptyTable",
"clSetKernelArg");
const size_t groupWorkSize =
roundUpToNearest(((intintIdentitySentinelPerfectHash_TableData *)
table->tableData)->numBuckets,
table->emptyKernelLocalWorkSize);
err =
clEnqueueNDRangeKernel(table->queue, table->emptyKernel, 1, 0,
&groupWorkSize,
(const size_t *)&table->
emptyKernelLocalWorkSize, 0, NULL, NULL);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_EmptyTable",
"clEnqueueNDRangeKernel");
exitCode = HASH_EXIT_CODE_NORMAL;;
return exitCode;
}
int intintIdentitySentinelPerfectCLHash_EmptyTable(intintHash_Table * table) {
int exitCode = 0;
cl_int err;
err =
clSetKernelArg(table->emptyKernel, 0, sizeof(cl_mem),
&table->tableDataBuffer);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_EmptyTable",
"clSetKernelArg");
const size_t groupWorkSize =
roundUpToNearest(((intintIdentitySentinelPerfectHash_TableData *)
table->tableData)->numBuckets,
table->emptyKernelLocalWorkSize);
err =
clEnqueueNDRangeKernel(table->queue, table->emptyKernel, 1, 0,
&groupWorkSize,
(const size_t *)&table->
emptyKernelLocalWorkSize, 0, NULL, NULL);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_EmptyTable",
"clEnqueueNDRangeKernel");
exitCode = HASH_EXIT_CODE_NORMAL;;
return exitCode;
}
int intintIdentitySentinelPerfectCLHash_QuerySingle(intintHash_Table * table,
int key, int *valueOutput) {
return intintIdentitySentinelPerfectCLHash_Query(table, 1, &key,
valueOutput);
}
int intintIdentitySentinelPerfectCLHash_Query(intintHash_Table * table,
size_t numKeys, int *keys,
int *valuesOutput) {
cl_int err;
cl_mem keysBuffer =
clCreateBuffer(table->context,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(int) * numKeys, keys, &err);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_Query",
"clCreateBuffer");
cl_mem valuesOutputBuffer =
clCreateBuffer(table->context, CL_MEM_WRITE_ONLY,
sizeof(int) * numKeys, NULL, &err);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_Query",
"clCreateBuffer");
intintIdentitySentinelPerfectCLHash_BufferQuery(table, numKeys,
keysBuffer,
valuesOutputBuffer);
err =
clEnqueueReadBuffer(table->queue, valuesOutputBuffer, CL_TRUE, 0,
sizeof(int) * numKeys, valuesOutput, 0, NULL,
NULL);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_Query",
"clEnqueueReadBuffer");
clReleaseMemObject(keysBuffer);
clReleaseMemObject(valuesOutputBuffer);
return HASH_EXIT_CODE_NORMAL;
}
int intintIdentitySentinelPerfectCLHash_BufferQuery(intintHash_Table * table,
size_t numKeys,
cl_mem keysBuffer,
cl_mem valuesOutputBuffer) {
cl_int err;
err =
clSetKernelArg(table->querySingleKernel, 0, sizeof(cl_mem),
&table->tableDataBuffer);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_BufferQuery",
"clSetKernelArg");
err =
clSetKernelArg(table->querySingleKernel, 1, sizeof(unsigned int),
&numKeys);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_BufferQuery",
"clSetKernelArg");
err =
clSetKernelArg(table->querySingleKernel, 2, sizeof(cl_mem),
&keysBuffer);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_BufferQuery",
"clSetKernelArg");
err =
clSetKernelArg(table->querySingleKernel, 3, sizeof(cl_mem),
&valuesOutputBuffer);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_BufferQuery",
"clSetKernelArg");
const size_t groupWorkSize =
roundUpToNearest(numKeys, table->localWorkSize);
err =
clEnqueueNDRangeKernel(table->queue, table->querySingleKernel, 1, 0,
&groupWorkSize,
(const size_t *)&table->localWorkSize, 0,
NULL, NULL);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_BufferQuery",
"clEnqueueNDRangeKernel");
clFinish(table->queue);
return HASH_EXIT_CODE_NORMAL;
}
int intintIdentitySentinelPerfectCLHash_InsertSingle(intintHash_Table * table,
int key, int value) {
return intintIdentitySentinelPerfectCLHash_Insert(table, 1, &key,
&value);
}
int intintIdentitySentinelPerfectCLHash_Insert(intintHash_Table * table,
size_t numEntries, int *keys,
int *values) {
cl_int err;
cl_mem keysBuffer =
clCreateBuffer(table->context,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(int) * numEntries, keys, &err);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_Insert",
"clCreateBuffer");
cl_mem valuesBuffer =
clCreateBuffer(table->context,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(int) * numEntries, values, &err);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_Insert",
"clCreateBuffer");
intintIdentitySentinelPerfectCLHash_BufferInsert(table, numEntries,
keysBuffer,
valuesBuffer);
clReleaseMemObject(keysBuffer);
clReleaseMemObject(valuesBuffer);
return HASH_EXIT_CODE_NORMAL;
}
int intintIdentitySentinelPerfectCLHash_BufferInsert(intintHash_Table * table,
size_t numEntries,
cl_mem keysBuffer,
cl_mem valuesBuffer) {
cl_int err;
err =
clSetKernelArg(table->insertSingleKernel, 0, sizeof(cl_mem),
&table->tableDataBuffer);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_BufferInsert",
"clSetKernelArg");
err =
clSetKernelArg(table->insertSingleKernel, 1, sizeof(unsigned int),
&numEntries);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_BufferInsert",
"clSetKernelArg");
err =
clSetKernelArg(table->insertSingleKernel, 2, sizeof(cl_mem),
&keysBuffer);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_BufferInsert",
"clSetKernelArg");
err =
clSetKernelArg(table->insertSingleKernel, 3, sizeof(cl_mem),
&valuesBuffer);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_BufferInsert",
"clSetKernelArg");
const size_t groupWorkSize =
roundUpToNearest(numEntries, table->localWorkSize);
err =
clEnqueueNDRangeKernel(table->queue, table->insertSingleKernel, 1,
0, &groupWorkSize,
(const size_t *)&table->localWorkSize, 0,
NULL, NULL);
CLHash_Utilities_HandleError(err, NULL, "clEnqueueNDRangeKernel");
return (0);
}
int intintIdentitySentinelPerfectCLHash_InsertSingleNoOverwrite(intintHash_Table
* table,
int key,
int value) {
return intintIdentitySentinelPerfectCLHash_InsertNoOverwrite(table, 1,
&key,
&value);
}
int intintIdentitySentinelPerfectCLHash_InsertNoOverwrite(intintHash_Table *
table,
size_t numEntries,
int *keys,
int *values) {
cl_int err;
cl_mem keysBuffer =
clCreateBuffer(table->context,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(int) * numEntries, keys, &err);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_InsertNoOverwrite",
"clCreateBuffer");
cl_mem valuesBuffer =
clCreateBuffer(table->context,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(int) * numEntries, values, &err);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_InsertNoOverwrite",
"clCreateBuffer");
intintIdentitySentinelPerfectCLHash_BufferInsertNoOverwrite(table,
numEntries,
keysBuffer,
valuesBuffer);
clReleaseMemObject(keysBuffer);
clReleaseMemObject(valuesBuffer);
return HASH_EXIT_CODE_NORMAL;
}
int intintIdentitySentinelPerfectCLHash_BufferInsertNoOverwrite(intintHash_Table
* table,
size_t
numEntries,
cl_mem
keysBuffer,
cl_mem
valuesBuffer) {
cl_int err;
err =
clSetKernelArg(table->insertSingleNoOverwriteKernel, 0,
sizeof(cl_mem), &table->tableDataBuffer);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_BufferInsertNoOverwrite",
"clSetKernelArg");
err =
clSetKernelArg(table->insertSingleNoOverwriteKernel, 1,
sizeof(unsigned int), &numEntries);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_BufferInsertNoOverwrite",
"ClSetKernelArg");
err =
clSetKernelArg(table->insertSingleNoOverwriteKernel, 2,
sizeof(cl_mem), &keysBuffer);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_BufferInsertNoOverwrite",
"clSetKernelArg");
err =
clSetKernelArg(table->insertSingleNoOverwriteKernel, 3,
sizeof(cl_mem), &valuesBuffer);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_BufferInsertNoOverwrite",
"clSetKernelArg");
const size_t groupWorkSize =
roundUpToNearest(numEntries, table->localWorkSize);
err =
clEnqueueNDRangeKernel(table->queue,
table->insertSingleNoOverwriteKernel, 1, 0,
&groupWorkSize,
(const size_t *)&table->localWorkSize, 0,
NULL, NULL);
CLHash_Utilities_HandleError(err,
"intintIdentitySentinelPerfectCLHash_BufferInsertNoOverwrite",
"clEnqueueNDRangeKernel");
return (0);
}
typedef struct intintIdentitySentinelPerfectOpenMPHash_TableData {
int hashID;
unsigned int numBuckets;
char compressFuncData;
int emptyValue;
} intintIdentitySentinelPerfectOpenMPHash_TableData;
typedef struct intintIdentitySentinelPerfectOpenMPHash_Bucket {
int value;
} intintIdentitySentinelPerfectOpenMPHash_Bucket;
intintHash_Table
*intintIdentitySentinelPerfectOpenMPHash_CreateTable(intintHash_Factory *
factory, int hashIndex,
size_t keyRange,
size_t numEntries,
float loadFactor) {
intintHash_Table *table =
(intintHash_Table *) malloc(sizeof(intintHash_Table));
table->destroyFunc =
&intintIdentitySentinelPerfectOpenMPHash_DestroyTable;
table->setupFunc = &intintIdentitySentinelPerfectOpenMPHash_SetupTable;
table->emptyFunc = &intintIdentitySentinelPerfectOpenMPHash_EmptyTable;
table->queryFunc = &intintIdentitySentinelPerfectOpenMPHash_Query;
table->querySingleFunc =
&intintIdentitySentinelPerfectOpenMPHash_QuerySingle;
table->insertFunc = &intintIdentitySentinelPerfectOpenMPHash_Insert;
table->insertSingleFunc =
&intintIdentitySentinelPerfectOpenMPHash_InsertSingle;
table->insertNoOverwriteFunc =
&intintIdentitySentinelPerfectOpenMPHash_InsertNoOverwrite;
table->insertSingleNoOverwriteFunc =
&intintIdentitySentinelPerfectOpenMPHash_InsertSingleNoOverwrite;
table->tableData =
(char *)
malloc(sizeof(intintIdentitySentinelPerfectOpenMPHash_TableData));
((intintIdentitySentinelPerfectOpenMPHash_TableData *) table->
tableData)->hashID = IDENTITY_SENTINEL_PERFECT_OPENMP_HASH_ID;
((intintIdentitySentinelPerfectOpenMPHash_TableData *) table->
tableData)->emptyValue = factory->emptyValue;
((intintIdentitySentinelPerfectOpenMPHash_TableData *) table->
tableData)->numBuckets = keyRange + 1;
char *tempHashData =
(char *)
malloc(sizeof(intintIdentitySentinelPerfectOpenMPHash_TableData) +
((intintIdentitySentinelPerfectOpenMPHash_TableData *)
table->tableData)->numBuckets *
sizeof(intintIdentitySentinelPerfectOpenMPHash_Bucket));
memcpy(tempHashData, table->tableData,
sizeof(intintIdentitySentinelPerfectOpenMPHash_TableData));
free(table->tableData);
table->tableData = tempHashData;
return table;
}
int intintIdentitySentinelPerfectOpenMPHash_CreateFactory(intintHash_Factory *
factory,
int hashIndex) {
factory->createFunc[hashIndex] =
&intintIdentitySentinelPerfectOpenMPHash_CreateTable;
factory->destroyFunc[hashIndex] =
&intintIdentitySentinelPerfectOpenMPHash_DestroyFactory;;
return HASH_EXIT_CODE_NORMAL;
}
int intintIdentitySentinelPerfectOpenMPHash_DestroyFactory(intintHash_Factory *
factory,
int hashIndex) {;
return HASH_EXIT_CODE_NORMAL;
}
int intintIdentitySentinelPerfectOpenMPHash_DestroyTable(intintHash_Table *
table) {
int exitCode = 0;
free(table->tableData);
free(table);
return exitCode;
}
int intintIdentitySentinelPerfectOpenMPHash_SetupTable(intintHash_Table * table) {
int exitCode = 0;
intintIdentitySentinelPerfectOpenMPHash_Bucket *buckets =
(intintIdentitySentinelPerfectOpenMPHash_Bucket *) & table->
tableData[sizeof
(intintIdentitySentinelPerfectOpenMPHash_TableData)];
if (intintHash_GetTableType(table) & ~HASH_SENTINEL_PERFECT_HASHES) {
#pragma omp parallel for
for (int index = 0;
index <
((intintIdentitySentinelPerfectOpenMPHash_TableData *)
table->tableData)->numBuckets; index++) {
buckets[index].value =
((intintIdentitySentinelPerfectOpenMPHash_TableData
*) table->tableData)->emptyValue;
}}
exitCode = HASH_EXIT_CODE_NORMAL;
return exitCode;
}
int intintIdentitySentinelPerfectOpenMPHash_EmptyTable(intintHash_Table * table) {
int exitCode = 0;
intintIdentitySentinelPerfectOpenMPHash_Bucket *buckets =
(intintIdentitySentinelPerfectOpenMPHash_Bucket *) & table->
tableData[sizeof
(intintIdentitySentinelPerfectOpenMPHash_TableData)];
#pragma omp parallel for
for (int index = 0;
index <
((intintIdentitySentinelPerfectOpenMPHash_TableData *) table->
tableData)->numBuckets; index++) {
buckets[index].value =
((intintIdentitySentinelPerfectOpenMPHash_TableData *)
table->tableData)->emptyValue;
} exitCode = HASH_EXIT_CODE_NORMAL;
return exitCode;
}
int intintIdentitySentinelPerfectOpenMPHash_InnerQuerySingle(char *tableData,
int key,
int *valueOutput) {
intintIdentitySentinelPerfectOpenMPHash_Bucket *buckets =
(intintIdentitySentinelPerfectOpenMPHash_Bucket *) &
tableData[sizeof
(intintIdentitySentinelPerfectOpenMPHash_TableData)];
int index;
int exitCode;
index =
intintHash_CompressIdentity(((intintIdentitySentinelPerfectOpenMPHash_TableData *) tableData)->compressFuncData, key);
if (buckets[index].value !=
((intintIdentitySentinelPerfectOpenMPHash_TableData *) tableData)->
emptyValue) {
exitCode = HASH_SEARCH_CODE_MATCH;
} else {
exitCode = HASH_SEARCH_CODE_EMPTY;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
*valueOutput = buckets[index].value;
return HASH_EXIT_CODE_NORMAL;
case HASH_SEARCH_CODE_MISMATCH:
case HASH_SEARCH_CODE_EMPTY:
return HASH_EXIT_CODE_KEY_DNE;
default:
return exitCode;
}
}
int intintIdentitySentinelPerfectOpenMPHash_InnerQuery(char *tableData,
unsigned int numKeys,
int *keys,
int *valuesOutput) {
intintIdentitySentinelPerfectOpenMPHash_Bucket *buckets =
(intintIdentitySentinelPerfectOpenMPHash_Bucket *) &
tableData[sizeof
(intintIdentitySentinelPerfectOpenMPHash_TableData)];
int key;
int *valueOutput;
int index;
int exitCode;
uint i;
int resultExitCode = HASH_EXIT_CODE_NORMAL;
for (i = 0; i < numKeys; i++) {
key = keys[i];
valueOutput = &valuesOutput[i];
index =
intintHash_CompressIdentity(((intintIdentitySentinelPerfectOpenMPHash_TableData *) tableData)->compressFuncData, key);
if (buckets[index].value !=
((intintIdentitySentinelPerfectOpenMPHash_TableData *)
tableData)->emptyValue) {
exitCode = HASH_SEARCH_CODE_MATCH;
} else {
exitCode = HASH_SEARCH_CODE_EMPTY;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
*valueOutput = buckets[index].value;
break;
case HASH_SEARCH_CODE_MISMATCH:
case HASH_SEARCH_CODE_EMPTY:
resultExitCode = HASH_EXIT_CODE_KEY_DNE;
break;
default:
return exitCode;
}
}
return resultExitCode;
}
int intintIdentitySentinelPerfectOpenMPHash_InnerInsertSingle(char *tableData,
int key,
int value) {
intintIdentitySentinelPerfectOpenMPHash_Bucket *buckets =
(intintIdentitySentinelPerfectOpenMPHash_Bucket *) &
tableData[sizeof
(intintIdentitySentinelPerfectOpenMPHash_TableData)];
int index;
int exitCode;
index =
intintHash_CompressIdentity(((intintIdentitySentinelPerfectOpenMPHash_TableData *) tableData)->compressFuncData, key);
if (buckets[index].value !=
((intintIdentitySentinelPerfectOpenMPHash_TableData *) tableData)->
emptyValue) {
exitCode = HASH_SEARCH_CODE_MATCH;
} else {
exitCode = HASH_SEARCH_CODE_EMPTY;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
buckets[index].value = value;
return HASH_EXIT_CODE_OVERWRITE;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = value;
return HASH_EXIT_CODE_NORMAL;
default:
return exitCode;
}
}
int intintIdentitySentinelPerfectOpenMPHash_InnerInsert(char *tableData,
unsigned int numEntries,
int *keys,
int *values) {
intintIdentitySentinelPerfectOpenMPHash_Bucket *buckets =
(intintIdentitySentinelPerfectOpenMPHash_Bucket *) &
tableData[sizeof
(intintIdentitySentinelPerfectOpenMPHash_TableData)];
int resultExitCode = HASH_EXIT_CODE_NORMAL;
int key;
int index;
int exitCode;
uint i;
#pragma omp parallel for
for (i = 0; i < numEntries; i++) {
key = keys[i];
index =
intintHash_CompressIdentity(((intintIdentitySentinelPerfectOpenMPHash_TableData *) tableData)->compressFuncData, key);
if (buckets[index].value !=
((intintIdentitySentinelPerfectOpenMPHash_TableData *)
tableData)->emptyValue) {
exitCode = HASH_SEARCH_CODE_MATCH;
} else {
exitCode = HASH_SEARCH_CODE_EMPTY;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
resultExitCode = HASH_EXIT_CODE_OVERWRITE;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = values[i];
break;
default:
resultExitCode = exitCode;
}
}
return resultExitCode;
}
int intintIdentitySentinelPerfectOpenMPHash_InnerInsertSingleNoOverwrite(char
*tableData,
int
key,
int
value)
{
intintIdentitySentinelPerfectOpenMPHash_Bucket *buckets =
(intintIdentitySentinelPerfectOpenMPHash_Bucket *) &
tableData[sizeof
(intintIdentitySentinelPerfectOpenMPHash_TableData)];
int index;
int exitCode;
index =
intintHash_CompressIdentity(((intintIdentitySentinelPerfectOpenMPHash_TableData *) tableData)->compressFuncData, key);
if (buckets[index].value !=
((intintIdentitySentinelPerfectOpenMPHash_TableData *) tableData)->
emptyValue) {
exitCode = HASH_SEARCH_CODE_MATCH;
} else {
exitCode = HASH_SEARCH_CODE_EMPTY;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
return HASH_EXIT_CODE_OVERWRITE;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = value;
return HASH_EXIT_CODE_NORMAL;
default:
return exitCode;
}
}
int intintIdentitySentinelPerfectOpenMPHash_InnerInsertNoOverwrite(char
*tableData,
unsigned int
numEntries,
int *keys,
int *values)
{
intintIdentitySentinelPerfectOpenMPHash_Bucket *buckets =
(intintIdentitySentinelPerfectOpenMPHash_Bucket *) &
tableData[sizeof
(intintIdentitySentinelPerfectOpenMPHash_TableData)];
int resultExitCode = HASH_EXIT_CODE_NORMAL;
int key;
int index;
int exitCode;
uint i;
#pragma omp parallel for
for (i = 0; i < numEntries; i++) {
key = keys[i];
index =
intintHash_CompressIdentity(((intintIdentitySentinelPerfectOpenMPHash_TableData *) tableData)->compressFuncData, key);
if (buckets[index].value !=
((intintIdentitySentinelPerfectOpenMPHash_TableData *)
tableData)->emptyValue) {
exitCode = HASH_SEARCH_CODE_MATCH;
} else {
exitCode = HASH_SEARCH_CODE_EMPTY;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
resultExitCode = HASH_EXIT_CODE_OVERWRITE;
break;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = values[i];
break;
default:
resultExitCode = exitCode;
}
}
return resultExitCode;
}
int intintIdentitySentinelPerfectOpenMPHash_QuerySingle(intintHash_Table *
table, int key,
int *valueOutput) {
return intintIdentitySentinelPerfectOpenMPHash_InnerQuerySingle(table->
tableData,
key,
valueOutput);
}
int intintIdentitySentinelPerfectOpenMPHash_Query(intintHash_Table * table,
size_t numKeys, int *keys,
int *valuesOutput) {
return intintIdentitySentinelPerfectOpenMPHash_InnerQuery(table->
tableData,
numKeys, keys,
valuesOutput);
}
int intintIdentitySentinelPerfectOpenMPHash_InsertSingle(intintHash_Table *
table, int key,
int value) {
return intintIdentitySentinelPerfectOpenMPHash_InnerInsertSingle(table->
tableData,
key,
value);
}
int intintIdentitySentinelPerfectOpenMPHash_Insert(intintHash_Table * table,
size_t numEntries, int *keys,
int *values) {
return intintIdentitySentinelPerfectOpenMPHash_InnerInsert(table->
tableData,
numEntries,
keys,
values);
}
int
intintIdentitySentinelPerfectOpenMPHash_InsertSingleNoOverwrite(intintHash_Table
* table,
int key,
int value) {
return
intintIdentitySentinelPerfectOpenMPHash_InnerInsertSingleNoOverwrite
(table->tableData, key, value);
}
int intintIdentitySentinelPerfectOpenMPHash_InsertNoOverwrite(intintHash_Table *
table,
size_t numEntries,
int *keys,
int *values) {
return
intintIdentitySentinelPerfectOpenMPHash_InnerInsertNoOverwrite
(table->tableData, numEntries, keys, values);
}
typedef struct intintLCGLinearOpenCompactHash_TableData {
int hashID;
unsigned int numBuckets;
intintHash_CompressLCGData compressFuncData;
} intintLCGLinearOpenCompactHash_TableData;
typedef struct intintLCGLinearOpenCompactHash_Bucket {
int key;
int value;
} intintLCGLinearOpenCompactHash_Bucket;
intintHash_Table *intintLCGLinearOpenCompactHash_CreateTable(intintHash_Factory
* factory,
int hashIndex,
size_t keyRange,
size_t numEntries,
float loadFactor) {
intintHash_Table *table =
(intintHash_Table *) malloc(sizeof(intintHash_Table));
table->destroyFunc = &intintLCGLinearOpenCompactHash_DestroyTable;
table->setupFunc = &intintLCGLinearOpenCompactHash_SetupTable;
table->emptyFunc = &intintLCGLinearOpenCompactHash_EmptyTable;
table->queryFunc = &intintLCGLinearOpenCompactHash_Query;
table->querySingleFunc = &intintLCGLinearOpenCompactHash_QuerySingle;
table->insertFunc = &intintLCGLinearOpenCompactHash_Insert;
table->insertSingleFunc = &intintLCGLinearOpenCompactHash_InsertSingle;
table->insertNoOverwriteFunc =
&intintLCGLinearOpenCompactHash_InsertNoOverwrite;
table->insertSingleNoOverwriteFunc =
&intintLCGLinearOpenCompactHash_InsertSingleNoOverwrite;
table->tableData =
(char *)malloc(sizeof(intintLCGLinearOpenCompactHash_TableData));
((intintLCGLinearOpenCompactHash_TableData *) table->tableData)->
hashID = LCG_LINEAR_OPEN_COMPACT_HASH_ID;
((intintLCGLinearOpenCompactHash_TableData *) table->tableData)->
numBuckets = (unsigned int)((double)numEntries / loadFactor);
((intintLCGLinearOpenCompactHash_TableData *) table->tableData)->
compressFuncData.a = HASH_LCG_A;
((intintLCGLinearOpenCompactHash_TableData *) table->tableData)->
compressFuncData.c = HASH_LCG_C;
((intintLCGLinearOpenCompactHash_TableData *) table->tableData)->
compressFuncData.m = HASH_LCG_M;
((intintLCGLinearOpenCompactHash_TableData *) table->tableData)->
compressFuncData.n =
((intintLCGLinearOpenCompactHash_TableData *) table->tableData)->
numBuckets;
char *tempHashData =
(char *)malloc(sizeof(intintLCGLinearOpenCompactHash_TableData) +
((intintLCGLinearOpenCompactHash_TableData *) table->
tableData)->numBuckets *
sizeof(intintLCGLinearOpenCompactHash_Bucket));
memcpy(tempHashData, table->tableData,
sizeof(intintLCGLinearOpenCompactHash_TableData));
free(table->tableData);
table->tableData = tempHashData;
return table;
}
int intintLCGLinearOpenCompactHash_CreateFactory(intintHash_Factory * factory,
int hashIndex) {
factory->createFunc[hashIndex] =
&intintLCGLinearOpenCompactHash_CreateTable;
factory->destroyFunc[hashIndex] =
&intintLCGLinearOpenCompactHash_DestroyFactory;;
return HASH_EXIT_CODE_NORMAL;
}
int intintLCGLinearOpenCompactHash_DestroyFactory(intintHash_Factory * factory,
int hashIndex) {;
return HASH_EXIT_CODE_NORMAL;
}
int intintLCGLinearOpenCompactHash_DestroyTable(intintHash_Table * table) {
int exitCode = 0;
free(table->tableData);
free(table);
return exitCode;
}
int intintLCGLinearOpenCompactHash_SetupTable(intintHash_Table * table) {
int exitCode = 0;
intintLCGLinearOpenCompactHash_Bucket *buckets =
(intintLCGLinearOpenCompactHash_Bucket *) & table->
tableData[sizeof(intintLCGLinearOpenCompactHash_TableData)];
if (intintHash_GetTableType(table) & ~HASH_SENTINEL_PERFECT_HASHES) {
for (int index = 0;
index <
((intintLCGLinearOpenCompactHash_TableData *) table->
tableData)->numBuckets; index++) {
buckets[index].key = HASH_BUCKET_STATUS_EMPTY;
}}
exitCode = HASH_EXIT_CODE_NORMAL;
return exitCode;
}
int intintLCGLinearOpenCompactHash_EmptyTable(intintHash_Table * table) {
int exitCode = 0;
intintLCGLinearOpenCompactHash_Bucket *buckets =
(intintLCGLinearOpenCompactHash_Bucket *) & table->
tableData[sizeof(intintLCGLinearOpenCompactHash_TableData)];
for (int index = 0;
index <
((intintLCGLinearOpenCompactHash_TableData *) table->tableData)->
numBuckets; index++) {
buckets[index].key = HASH_BUCKET_STATUS_EMPTY;
} exitCode = HASH_EXIT_CODE_NORMAL;
return exitCode;
}
int intintLCGLinearOpenCompactHash_InnerQuerySingle(char *tableData, int key,
int *valueOutput) {
intintLCGLinearOpenCompactHash_Bucket *buckets =
(intintLCGLinearOpenCompactHash_Bucket *) &
tableData[sizeof(intintLCGLinearOpenCompactHash_TableData)];
int index;
int exitCode;
intintLCGLinearOpenCompactHash_TableData *mytableData =
(intintLCGLinearOpenCompactHash_TableData *) tableData;
intintHash_CompressLCGData compressFuncData =
mytableData->compressFuncData;
unsigned int c = intintHash_CompressLCG(compressFuncData, key);
unsigned long int iteration = 0;
for (;;) {
index =
((1 * iteration +
c) %
((intintLCGLinearOpenCompactHash_TableData *) tableData)->
numBuckets);
if ((buckets[index].key) == HASH_BUCKET_STATUS_EMPTY) {
exitCode = HASH_SEARCH_CODE_EMPTY;
break;
} else if (key == buckets[index].key) {
exitCode = HASH_SEARCH_CODE_MATCH;
break;
} else if ((index == c && iteration > 0)) {
exitCode = HASH_EXIT_CODE_CYCLE;
break;
}
iteration++;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
*valueOutput = buckets[index].value;
return HASH_EXIT_CODE_NORMAL;
case HASH_SEARCH_CODE_MISMATCH:
case HASH_SEARCH_CODE_EMPTY:
return HASH_EXIT_CODE_KEY_DNE;
default:
return exitCode;
}
}
int intintLCGLinearOpenCompactHash_InnerQuery(char *tableData,
unsigned int numKeys, int *keys,
int *valuesOutput) {
intintLCGLinearOpenCompactHash_Bucket *buckets =
(intintLCGLinearOpenCompactHash_Bucket *) &
tableData[sizeof(intintLCGLinearOpenCompactHash_TableData)];
int key;
int *valueOutput;
int index;
int exitCode;
uint i;
int resultExitCode = HASH_EXIT_CODE_NORMAL;
for (i = 0; i < numKeys; i++) {
key = keys[i];
valueOutput = &valuesOutput[i];
intintLCGLinearOpenCompactHash_TableData *mytableData =
(intintLCGLinearOpenCompactHash_TableData *) tableData;
intintHash_CompressLCGData compressFuncData =
mytableData->compressFuncData;
unsigned int c = intintHash_CompressLCG(compressFuncData, key);
unsigned long int iteration = 0;
for (;;) {
index =
((1 * iteration +
c) %
((intintLCGLinearOpenCompactHash_TableData *)
tableData)->numBuckets);
if ((buckets[index].key) == HASH_BUCKET_STATUS_EMPTY) {
exitCode = HASH_SEARCH_CODE_EMPTY;
break;
} else if (key == buckets[index].key) {
exitCode = HASH_SEARCH_CODE_MATCH;
break;
} else if ((index == c && iteration > 0)) {
exitCode = HASH_EXIT_CODE_CYCLE;
break;
}
iteration++;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
*valueOutput = buckets[index].value;
break;
case HASH_SEARCH_CODE_MISMATCH:
case HASH_SEARCH_CODE_EMPTY:
resultExitCode = HASH_EXIT_CODE_KEY_DNE;
break;
default:
return exitCode;
}
}
return resultExitCode;
}
int intintLCGLinearOpenCompactHash_InnerInsertSingle(char *tableData, int key,
int value) {
intintLCGLinearOpenCompactHash_Bucket *buckets =
(intintLCGLinearOpenCompactHash_Bucket *) &
tableData[sizeof(intintLCGLinearOpenCompactHash_TableData)];
int index;
int exitCode;
intintLCGLinearOpenCompactHash_TableData *mytableData =
(intintLCGLinearOpenCompactHash_TableData *) tableData;
intintHash_CompressLCGData compressFuncData =
mytableData->compressFuncData;
unsigned int c = intintHash_CompressLCG(compressFuncData, key);
unsigned long int iteration = 0;
for (;;) {
index =
((1 * iteration +
c) %
((intintLCGLinearOpenCompactHash_TableData *) tableData)->
numBuckets);
if (((buckets[index].key ==
HASH_BUCKET_STATUS_EMPTY) ? (buckets[index].key =
key,
HASH_BUCKET_STATUS_EMPTY) :
buckets[index].key) == HASH_BUCKET_STATUS_EMPTY) {
exitCode = HASH_SEARCH_CODE_EMPTY;
break;
} else if (key == buckets[index].key) {
exitCode = HASH_SEARCH_CODE_MATCH;
break;
} else if ((index == c && iteration > 0)) {
exitCode = HASH_EXIT_CODE_CYCLE;
break;
}
iteration++;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
buckets[index].value = value;
return HASH_EXIT_CODE_OVERWRITE;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = value;
return HASH_EXIT_CODE_NORMAL;
default:
return exitCode;
}
}
int intintLCGLinearOpenCompactHash_InnerInsert(char *tableData,
unsigned int numEntries,
int *keys, int *values) {
intintLCGLinearOpenCompactHash_Bucket *buckets =
(intintLCGLinearOpenCompactHash_Bucket *) &
tableData[sizeof(intintLCGLinearOpenCompactHash_TableData)];
int resultExitCode = HASH_EXIT_CODE_NORMAL;
int key;
int index;
int exitCode;
uint i;;
for (i = 0; i < numEntries; i++) {
key = keys[i];
intintLCGLinearOpenCompactHash_TableData *mytableData =
(intintLCGLinearOpenCompactHash_TableData *) tableData;
intintHash_CompressLCGData compressFuncData =
mytableData->compressFuncData;
unsigned int c = intintHash_CompressLCG(compressFuncData, key);
unsigned long int iteration = 0;
for (;;) {
index =
((1 * iteration +
c) %
((intintLCGLinearOpenCompactHash_TableData *)
tableData)->numBuckets);
if (((buckets[index].key ==
HASH_BUCKET_STATUS_EMPTY) ? (buckets[index].key =
key,
HASH_BUCKET_STATUS_EMPTY)
: buckets[index].key) ==
HASH_BUCKET_STATUS_EMPTY) {
exitCode = HASH_SEARCH_CODE_EMPTY;
break;
} else if (key == buckets[index].key) {
exitCode = HASH_SEARCH_CODE_MATCH;
break;
} else if ((index == c && iteration > 0)) {
exitCode = HASH_EXIT_CODE_CYCLE;
break;
}
iteration++;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
resultExitCode = HASH_EXIT_CODE_OVERWRITE;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = values[i];
break;
default:
resultExitCode = exitCode;
}
}
return resultExitCode;
}
int intintLCGLinearOpenCompactHash_InnerInsertSingleNoOverwrite(char *tableData,
int key,
int value) {
intintLCGLinearOpenCompactHash_Bucket *buckets =
(intintLCGLinearOpenCompactHash_Bucket *) &
tableData[sizeof(intintLCGLinearOpenCompactHash_TableData)];
int index;
int exitCode;
intintLCGLinearOpenCompactHash_TableData *mytableData =
(intintLCGLinearOpenCompactHash_TableData *) tableData;
intintHash_CompressLCGData compressFuncData =
mytableData->compressFuncData;
unsigned int c = intintHash_CompressLCG(compressFuncData, key);
unsigned long int iteration = 0;
for (;;) {
index =
((1 * iteration +
c) %
((intintLCGLinearOpenCompactHash_TableData *) tableData)->
numBuckets);
if (((buckets[index].key ==
HASH_BUCKET_STATUS_EMPTY) ? (buckets[index].key =
key,
HASH_BUCKET_STATUS_EMPTY) :
buckets[index].key) == HASH_BUCKET_STATUS_EMPTY) {
exitCode = HASH_SEARCH_CODE_EMPTY;
break;
} else if (key == buckets[index].key) {
exitCode = HASH_SEARCH_CODE_MATCH;
break;
} else if ((index == c && iteration > 0)) {
exitCode = HASH_EXIT_CODE_CYCLE;
break;
}
iteration++;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
return HASH_EXIT_CODE_OVERWRITE;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = value;
return HASH_EXIT_CODE_NORMAL;
default:
return exitCode;
}
}
int intintLCGLinearOpenCompactHash_InnerInsertNoOverwrite(char *tableData,
unsigned int
numEntries, int *keys,
int *values) {
intintLCGLinearOpenCompactHash_Bucket *buckets =
(intintLCGLinearOpenCompactHash_Bucket *) &
tableData[sizeof(intintLCGLinearOpenCompactHash_TableData)];
int resultExitCode = HASH_EXIT_CODE_NORMAL;
int key;
int index;
int exitCode;
uint i;;
for (i = 0; i < numEntries; i++) {
key = keys[i];
intintLCGLinearOpenCompactHash_TableData *mytableData =
(intintLCGLinearOpenCompactHash_TableData *) tableData;
intintHash_CompressLCGData compressFuncData =
mytableData->compressFuncData;
unsigned int c = intintHash_CompressLCG(compressFuncData, key);
unsigned long int iteration = 0;
for (;;) {
index =
((1 * iteration +
c) %
((intintLCGLinearOpenCompactHash_TableData *)
tableData)->numBuckets);
if (((buckets[index].key ==
HASH_BUCKET_STATUS_EMPTY) ? (buckets[index].key =
key,
HASH_BUCKET_STATUS_EMPTY)
: buckets[index].key) ==
HASH_BUCKET_STATUS_EMPTY) {
exitCode = HASH_SEARCH_CODE_EMPTY;
break;
} else if (key == buckets[index].key) {
exitCode = HASH_SEARCH_CODE_MATCH;
break;
} else if ((index == c && iteration > 0)) {
exitCode = HASH_EXIT_CODE_CYCLE;
break;
}
iteration++;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
resultExitCode = HASH_EXIT_CODE_OVERWRITE;
break;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = values[i];
break;
default:
resultExitCode = exitCode;
}
}
return resultExitCode;
}
int intintLCGLinearOpenCompactHash_QuerySingle(intintHash_Table * table,
int key, int *valueOutput) {
return intintLCGLinearOpenCompactHash_InnerQuerySingle(table->tableData,
key,
valueOutput);
}
int intintLCGLinearOpenCompactHash_Query(intintHash_Table * table,
size_t numKeys, int *keys,
int *valuesOutput) {
return intintLCGLinearOpenCompactHash_InnerQuery(table->tableData,
numKeys, keys,
valuesOutput);
}
int intintLCGLinearOpenCompactHash_InsertSingle(intintHash_Table * table,
int key, int value) {
return intintLCGLinearOpenCompactHash_InnerInsertSingle(table->
tableData, key,
value);
}
int intintLCGLinearOpenCompactHash_Insert(intintHash_Table * table,
size_t numEntries, int *keys,
int *values) {
return intintLCGLinearOpenCompactHash_InnerInsert(table->tableData,
numEntries, keys,
values);
}
int intintLCGLinearOpenCompactHash_InsertSingleNoOverwrite(intintHash_Table *
table, int key,
int value) {
return
intintLCGLinearOpenCompactHash_InnerInsertSingleNoOverwrite(table->
tableData,
key,
value);
}
int intintLCGLinearOpenCompactHash_InsertNoOverwrite(intintHash_Table * table,
size_t numEntries,
int *keys, int *values) {
return intintLCGLinearOpenCompactHash_InnerInsertNoOverwrite(table->
tableData,
numEntries,
keys,
values);
}
typedef struct intintLCGLinearOpenCompactCLHash_TableData {
int hashID;
unsigned int numBuckets;
intintHash_CompressLCGData compressFuncData;
} intintLCGLinearOpenCompactCLHash_TableData;
typedef struct intintLCGLinearOpenCompactCLHash_Bucket {
int key;
int value;
} intintLCGLinearOpenCompactCLHash_Bucket;
intintHash_Table
*intintLCGLinearOpenCompactCLHash_CreateTable(intintHash_Factory * factory,
int hashIndex,
size_t keyRange,
size_t numEntries,
float loadFactor) {
intintHash_Table *table =
(intintHash_Table *) malloc(sizeof(intintHash_Table));
table->destroyFunc = &intintLCGLinearOpenCompactCLHash_DestroyTable;
table->setupFunc = &intintLCGLinearOpenCompactCLHash_SetupTable;
table->emptyFunc = &intintLCGLinearOpenCompactCLHash_EmptyTable;
table->queryFunc = &intintLCGLinearOpenCompactCLHash_Query;
table->querySingleFunc = &intintLCGLinearOpenCompactCLHash_QuerySingle;
table->insertFunc = &intintLCGLinearOpenCompactCLHash_Insert;
table->insertSingleFunc =
&intintLCGLinearOpenCompactCLHash_InsertSingle;
table->insertNoOverwriteFunc =
&intintLCGLinearOpenCompactCLHash_InsertNoOverwrite;
table->insertSingleNoOverwriteFunc =
&intintLCGLinearOpenCompactCLHash_InsertSingleNoOverwrite;
table->tableData =
(char *)malloc(sizeof(intintLCGLinearOpenCompactCLHash_TableData));
((intintLCGLinearOpenCompactCLHash_TableData *) table->tableData)->
hashID = LCG_LINEAR_OPEN_COMPACT_CL_HASH_ID;
table->context = factory->context;
table->queue = factory->queue;
table->program = factory->program;
table->localWorkSize = factory->localWorkSize;
table->utilProgram = factory->utilProgram[hashIndex];
table->emptyKernel = factory->emptyKernel[hashIndex];
table->emptyKernelLocalWorkSize =
factory->emptyKernelLocalWorkSize[hashIndex];
table->querySingleKernel = factory->querySingleKernel[hashIndex];
table->insertSingleKernel = factory->insertSingleKernel[hashIndex];
table->insertSingleNoOverwriteKernel =
factory->insertSingleNoOverwriteKernel[hashIndex];
clRetainContext(table->context);
clRetainCommandQueue(table->queue);
clRetainProgram(table->program);
clRetainProgram(table->utilProgram);
clRetainKernel(table->emptyKernel);
clRetainKernel(table->querySingleKernel);
clRetainKernel(table->insertSingleKernel);
clRetainKernel(table->insertSingleNoOverwriteKernel);;
((intintLCGLinearOpenCompactCLHash_TableData *) table->tableData)->
numBuckets = (unsigned int)((double)numEntries / loadFactor);
((intintLCGLinearOpenCompactCLHash_TableData *) table->tableData)->
compressFuncData.a = HASH_LCG_A;
((intintLCGLinearOpenCompactCLHash_TableData *) table->tableData)->
compressFuncData.c = HASH_LCG_C;
((intintLCGLinearOpenCompactCLHash_TableData *) table->tableData)->
compressFuncData.m = HASH_LCG_M;
((intintLCGLinearOpenCompactCLHash_TableData *) table->tableData)->
compressFuncData.n =
((intintLCGLinearOpenCompactCLHash_TableData *) table->tableData)->
numBuckets;
char *tempHashData =
(char *)malloc(sizeof(intintLCGLinearOpenCompactCLHash_TableData) +
((intintLCGLinearOpenCompactCLHash_TableData *)
table->tableData)->numBuckets *
sizeof(intintLCGLinearOpenCompactCLHash_Bucket));
memcpy(tempHashData, table->tableData,
sizeof(intintLCGLinearOpenCompactCLHash_TableData));
free(table->tableData);
table->tableData = tempHashData;
cl_int err;
table->tableDataBuffer =
clCreateBuffer(table->context, CL_MEM_READ_WRITE,
sizeof(intintLCGLinearOpenCompactHash_TableData) +
((intintLCGLinearOpenCompactHash_TableData *) table->
tableData)->numBuckets *
sizeof(intintLCGLinearOpenCompactHash_Bucket), NULL,
&err);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_InitTable",
"clCreateBuffer");
err =
clEnqueueWriteBuffer(table->queue, table->tableDataBuffer, CL_TRUE,
0,
sizeof
(intintLCGLinearOpenCompactHash_TableData),
table->tableData, 0, NULL, NULL);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_InitTable",
"clEnqueueWriteBuffer");
return table;
}
int intintLCGLinearOpenCompactCLHash_CreateFactory(intintHash_Factory * factory,
int hashIndex) {
factory->createFunc[hashIndex] =
&intintLCGLinearOpenCompactCLHash_CreateTable;
factory->destroyFunc[hashIndex] =
&intintLCGLinearOpenCompactCLHash_DestroyFactory;
cl_int error;
cl_device_id device;
error =
clGetContextInfo(factory->context, CL_CONTEXT_DEVICES,
sizeof(device), &device, NULL);
CLHash_Utilities_HandleError(error, "intintHash_CreateFactory",
"clGetContextInfo");
factory->querySingleKernel[hashIndex] =
clCreateKernel(factory->program,
"intintLCGLinearOpenCompactCLHash_RangeQuerySingle",
&error);
CLHash_Utilities_HandleError(error,
"intintLCGLinearOpenCompactCLHash_CreateFactory",
"clCreateKernel");
factory->insertSingleKernel[hashIndex] =
clCreateKernel(factory->program,
"intintLCGLinearOpenCompactCLHash_RangeInsertSingle",
&error);
CLHash_Utilities_HandleError(error,
"intintLCGLinearOpenCompactCLHash_CreateFactory",
"clCreateKernel");
factory->insertSingleNoOverwriteKernel[hashIndex] =
clCreateKernel(factory->program,
"intintLCGLinearOpenCompactCLHash_RangeInsertSingleNoOverwrite",
&error);
CLHash_Utilities_HandleError(error,
"intintLCGLinearOpenCompactCLHash_CreateFactory",
"clCreateKernel");
factory->utilProgram[hashIndex] =
CLHash_Utilities_BuildProgramString(factory->context, device,
"static inline unsigned int intintHash_CompressIdentity(char data, int hashCode){ return hashCode; } typedef struct intintHash_CompressLCGData{ long unsigned int a; long unsigned int c; unsigned int m; unsigned int n; }intintHash_CompressLCGData; static inline unsigned int intintHash_CompressLCG(intintHash_CompressLCGData compressLCGData, int hashCode){ return ((compressLCGData.a * hashCode + compressLCGData.c) % compressLCGData.m) % compressLCGData.n; } typedef struct intintLCGLinearOpenCompactCLHash_TableData{ int hashID; unsigned int numBuckets; intintHash_CompressLCGData compressFuncData; }intintLCGLinearOpenCompactCLHash_TableData; typedef struct intintLCGLinearOpenCompactCLHash_Bucket{ int key; int value; }intintLCGLinearOpenCompactCLHash_Bucket; __kernel void intintLCGLinearOpenCompactCLHash_Empty(__global char *tableData){ int index = get_global_id(0); if(index >= ((__global intintLCGLinearOpenCompactCLHash_TableData*)tableData)->numBuckets){ return; } __global intintLCGLinearOpenCompactCLHash_Bucket *buckets = (__global intintLCGLinearOpenCompactCLHash_Bucket*)&tableData[sizeof(intintLCGLinearOpenCompactCLHash_TableData)]; buckets[index].key = -1;/*HASH_BUCKET_STATUS_EMPTY*/ }");
factory->emptyKernel[hashIndex] =
clCreateKernel(factory->utilProgram[hashIndex],
"intintLCGLinearOpenCompactCLHash_Empty", &error);
CLHash_Utilities_HandleError(error,
"intintLCGLinearOpenCompactCLHash_CreateFactory",
"clCreateKernel");
error =
clGetKernelWorkGroupInfo(factory->emptyKernel[hashIndex], device,
CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t),
&factory->
emptyKernelLocalWorkSize[hashIndex], NULL);
CLHash_Utilities_HandleError(error,
"intintLCGLinearOpenCompactCLHash_CreateFactory",
"clGetKernelWorkGroupInfo");;;
return HASH_EXIT_CODE_NORMAL;
}
int intintLCGLinearOpenCompactCLHash_DestroyFactory(intintHash_Factory *
factory, int hashIndex) {;
clReleaseKernel(factory->emptyKernel[hashIndex]);
clReleaseProgram(factory->utilProgram[hashIndex]);
clReleaseKernel(factory->querySingleKernel[hashIndex]);
clReleaseKernel(factory->insertSingleKernel[hashIndex]);
clReleaseKernel(factory->insertSingleNoOverwriteKernel[hashIndex]);;
return HASH_EXIT_CODE_NORMAL;
}
int intintLCGLinearOpenCompactCLHash_DestroyTable(intintHash_Table * table) {
int exitCode = 0;
clReleaseMemObject(table->tableDataBuffer);
clReleaseContext(table->context);
clReleaseCommandQueue(table->queue);
clReleaseProgram(table->utilProgram);
clReleaseKernel(table->emptyKernel);
clReleaseProgram(table->program);
clReleaseKernel(table->querySingleKernel);
clReleaseKernel(table->insertSingleKernel);
clReleaseKernel(table->insertSingleNoOverwriteKernel);
free(table->tableData);
free(table);
return exitCode;
}
int intintLCGLinearOpenCompactCLHash_SetupTable(intintHash_Table * table) {
int exitCode = 0;
cl_int err;
err =
clSetKernelArg(table->emptyKernel, 0, sizeof(cl_mem),
&table->tableDataBuffer);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_EmptyTable",
"clSetKernelArg");
const size_t groupWorkSize =
roundUpToNearest(((intintLCGLinearOpenCompactHash_TableData *)
table->tableData)->numBuckets,
table->emptyKernelLocalWorkSize);
err =
clEnqueueNDRangeKernel(table->queue, table->emptyKernel, 1, 0,
&groupWorkSize,
(const size_t *)&table->
emptyKernelLocalWorkSize, 0, NULL, NULL);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_EmptyTable",
"clEnqueueNDRangeKernel");
exitCode = HASH_EXIT_CODE_NORMAL;;
return exitCode;
}
int intintLCGLinearOpenCompactCLHash_EmptyTable(intintHash_Table * table) {
int exitCode = 0;
cl_int err;
err =
clSetKernelArg(table->emptyKernel, 0, sizeof(cl_mem),
&table->tableDataBuffer);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_EmptyTable",
"clSetKernelArg");
const size_t groupWorkSize =
roundUpToNearest(((intintLCGLinearOpenCompactHash_TableData *)
table->tableData)->numBuckets,
table->emptyKernelLocalWorkSize);
err =
clEnqueueNDRangeKernel(table->queue, table->emptyKernel, 1, 0,
&groupWorkSize,
(const size_t *)&table->
emptyKernelLocalWorkSize, 0, NULL, NULL);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_EmptyTable",
"clEnqueueNDRangeKernel");
exitCode = HASH_EXIT_CODE_NORMAL;;
return exitCode;
}
int intintLCGLinearOpenCompactCLHash_QuerySingle(intintHash_Table * table,
int key, int *valueOutput) {
return intintLCGLinearOpenCompactCLHash_Query(table, 1, &key,
valueOutput);
}
int intintLCGLinearOpenCompactCLHash_Query(intintHash_Table * table,
size_t numKeys, int *keys,
int *valuesOutput) {
cl_int err;
cl_mem keysBuffer =
clCreateBuffer(table->context,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(int) * numKeys, keys, &err);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_Query",
"clCreateBuffer");
cl_mem valuesOutputBuffer =
clCreateBuffer(table->context, CL_MEM_WRITE_ONLY,
sizeof(int) * numKeys, NULL, &err);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_Query",
"clCreateBuffer");
intintLCGLinearOpenCompactCLHash_BufferQuery(table, numKeys, keysBuffer,
valuesOutputBuffer);
err =
clEnqueueReadBuffer(table->queue, valuesOutputBuffer, CL_TRUE, 0,
sizeof(int) * numKeys, valuesOutput, 0, NULL,
NULL);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_Query",
"clEnqueueReadBuffer");
clReleaseMemObject(keysBuffer);
clReleaseMemObject(valuesOutputBuffer);
return HASH_EXIT_CODE_NORMAL;
}
int intintLCGLinearOpenCompactCLHash_BufferQuery(intintHash_Table * table,
size_t numKeys,
cl_mem keysBuffer,
cl_mem valuesOutputBuffer) {
cl_int err;
err =
clSetKernelArg(table->querySingleKernel, 0, sizeof(cl_mem),
&table->tableDataBuffer);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_BufferQuery",
"clSetKernelArg");
err =
clSetKernelArg(table->querySingleKernel, 1, sizeof(unsigned int),
&numKeys);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_BufferQuery",
"clSetKernelArg");
err =
clSetKernelArg(table->querySingleKernel, 2, sizeof(cl_mem),
&keysBuffer);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_BufferQuery",
"clSetKernelArg");
err =
clSetKernelArg(table->querySingleKernel, 3, sizeof(cl_mem),
&valuesOutputBuffer);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_BufferQuery",
"clSetKernelArg");
const size_t groupWorkSize =
roundUpToNearest(numKeys, table->localWorkSize);
err =
clEnqueueNDRangeKernel(table->queue, table->querySingleKernel, 1, 0,
&groupWorkSize,
(const size_t *)&table->localWorkSize, 0,
NULL, NULL);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_BufferQuery",
"clEnqueueNDRangeKernel");
clFinish(table->queue);
return HASH_EXIT_CODE_NORMAL;
}
int intintLCGLinearOpenCompactCLHash_InsertSingle(intintHash_Table * table,
int key, int value) {
return intintLCGLinearOpenCompactCLHash_Insert(table, 1, &key, &value);
}
int intintLCGLinearOpenCompactCLHash_Insert(intintHash_Table * table,
size_t numEntries, int *keys,
int *values) {
cl_int err;
cl_mem keysBuffer =
clCreateBuffer(table->context,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(int) * numEntries, keys, &err);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_Insert",
"clCreateBuffer");
cl_mem valuesBuffer =
clCreateBuffer(table->context,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(int) * numEntries, values, &err);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_Insert",
"clCreateBuffer");
intintLCGLinearOpenCompactCLHash_BufferInsert(table, numEntries,
keysBuffer, valuesBuffer);
clReleaseMemObject(keysBuffer);
clReleaseMemObject(valuesBuffer);
return HASH_EXIT_CODE_NORMAL;
}
int intintLCGLinearOpenCompactCLHash_BufferInsert(intintHash_Table * table,
size_t numEntries,
cl_mem keysBuffer,
cl_mem valuesBuffer) {
cl_int err;
err =
clSetKernelArg(table->insertSingleKernel, 0, sizeof(cl_mem),
&table->tableDataBuffer);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_BufferInsert",
"clSetKernelArg");
err =
clSetKernelArg(table->insertSingleKernel, 1, sizeof(unsigned int),
&numEntries);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_BufferInsert",
"clSetKernelArg");
err =
clSetKernelArg(table->insertSingleKernel, 2, sizeof(cl_mem),
&keysBuffer);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_BufferInsert",
"clSetKernelArg");
err =
clSetKernelArg(table->insertSingleKernel, 3, sizeof(cl_mem),
&valuesBuffer);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_BufferInsert",
"clSetKernelArg");
const size_t groupWorkSize =
roundUpToNearest(numEntries, table->localWorkSize);
err =
clEnqueueNDRangeKernel(table->queue, table->insertSingleKernel, 1,
0, &groupWorkSize,
(const size_t *)&table->localWorkSize, 0,
NULL, NULL);
CLHash_Utilities_HandleError(err, NULL, "clEnqueueNDRangeKernel");
return (0);
}
int intintLCGLinearOpenCompactCLHash_InsertSingleNoOverwrite(intintHash_Table *
table, int key,
int value) {
return intintLCGLinearOpenCompactCLHash_InsertNoOverwrite(table, 1,
&key, &value);
}
int intintLCGLinearOpenCompactCLHash_InsertNoOverwrite(intintHash_Table * table,
size_t numEntries,
int *keys, int *values) {
cl_int err;
cl_mem keysBuffer =
clCreateBuffer(table->context,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(int) * numEntries, keys, &err);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_InsertNoOverwrite",
"clCreateBuffer");
cl_mem valuesBuffer =
clCreateBuffer(table->context,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(int) * numEntries, values, &err);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_InsertNoOverwrite",
"clCreateBuffer");
intintLCGLinearOpenCompactCLHash_BufferInsertNoOverwrite(table,
numEntries,
keysBuffer,
valuesBuffer);
clReleaseMemObject(keysBuffer);
clReleaseMemObject(valuesBuffer);
return HASH_EXIT_CODE_NORMAL;
}
int intintLCGLinearOpenCompactCLHash_BufferInsertNoOverwrite(intintHash_Table *
table,
size_t numEntries,
cl_mem keysBuffer,
cl_mem
valuesBuffer) {
cl_int err;
err =
clSetKernelArg(table->insertSingleNoOverwriteKernel, 0,
sizeof(cl_mem), &table->tableDataBuffer);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_BufferInsertNoOverwrite",
"clSetKernelArg");
err =
clSetKernelArg(table->insertSingleNoOverwriteKernel, 1,
sizeof(unsigned int), &numEntries);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_BufferInsertNoOverwrite",
"ClSetKernelArg");
err =
clSetKernelArg(table->insertSingleNoOverwriteKernel, 2,
sizeof(cl_mem), &keysBuffer);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_BufferInsertNoOverwrite",
"clSetKernelArg");
err =
clSetKernelArg(table->insertSingleNoOverwriteKernel, 3,
sizeof(cl_mem), &valuesBuffer);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_BufferInsertNoOverwrite",
"clSetKernelArg");
const size_t groupWorkSize =
roundUpToNearest(numEntries, table->localWorkSize);
err =
clEnqueueNDRangeKernel(table->queue,
table->insertSingleNoOverwriteKernel, 1, 0,
&groupWorkSize,
(const size_t *)&table->localWorkSize, 0,
NULL, NULL);
CLHash_Utilities_HandleError(err,
"intintLCGLinearOpenCompactCLHash_BufferInsertNoOverwrite",
"clEnqueueNDRangeKernel");
return (0);
}
typedef struct intintLCGLinearOpenCompactOpenMPHash_TableData {
int hashID;
unsigned int numBuckets;
intintHash_CompressLCGData compressFuncData;
} intintLCGLinearOpenCompactOpenMPHash_TableData;
typedef struct intintLCGLinearOpenCompactOpenMPHash_Bucket {
int key;
int value;
} intintLCGLinearOpenCompactOpenMPHash_Bucket;
intintHash_Table
*intintLCGLinearOpenCompactOpenMPHash_CreateTable(intintHash_Factory *
factory, int hashIndex,
size_t keyRange,
size_t numEntries,
float loadFactor) {
intintHash_Table *table =
(intintHash_Table *) malloc(sizeof(intintHash_Table));
table->destroyFunc = &intintLCGLinearOpenCompactOpenMPHash_DestroyTable;
table->setupFunc = &intintLCGLinearOpenCompactOpenMPHash_SetupTable;
table->emptyFunc = &intintLCGLinearOpenCompactOpenMPHash_EmptyTable;
table->queryFunc = &intintLCGLinearOpenCompactOpenMPHash_Query;
table->querySingleFunc =
&intintLCGLinearOpenCompactOpenMPHash_QuerySingle;
table->insertFunc = &intintLCGLinearOpenCompactOpenMPHash_Insert;
table->insertSingleFunc =
&intintLCGLinearOpenCompactOpenMPHash_InsertSingle;
table->insertNoOverwriteFunc =
&intintLCGLinearOpenCompactOpenMPHash_InsertNoOverwrite;
table->insertSingleNoOverwriteFunc =
&intintLCGLinearOpenCompactOpenMPHash_InsertSingleNoOverwrite;
table->tableData =
(char *)
malloc(sizeof(intintLCGLinearOpenCompactOpenMPHash_TableData));
((intintLCGLinearOpenCompactOpenMPHash_TableData *) table->tableData)->
hashID = LCG_LINEAR_OPEN_COMPACT_OPENMP_HASH_ID;
((intintLCGLinearOpenCompactOpenMPHash_TableData *) table->tableData)->
numBuckets = (unsigned int)((double)numEntries / loadFactor);
((intintLCGLinearOpenCompactOpenMPHash_TableData *) table->tableData)->
compressFuncData.a = HASH_LCG_A;
((intintLCGLinearOpenCompactOpenMPHash_TableData *) table->tableData)->
compressFuncData.c = HASH_LCG_C;
((intintLCGLinearOpenCompactOpenMPHash_TableData *) table->tableData)->
compressFuncData.m = HASH_LCG_M;
((intintLCGLinearOpenCompactOpenMPHash_TableData *) table->tableData)->
compressFuncData.n =
((intintLCGLinearOpenCompactOpenMPHash_TableData *) table->
tableData)->numBuckets;
char *tempHashData =
(char *)
malloc(sizeof(intintLCGLinearOpenCompactOpenMPHash_TableData) +
((intintLCGLinearOpenCompactOpenMPHash_TableData *) table->
tableData)->numBuckets *
sizeof(intintLCGLinearOpenCompactOpenMPHash_Bucket));
memcpy(tempHashData, table->tableData,
sizeof(intintLCGLinearOpenCompactOpenMPHash_TableData));
free(table->tableData);
table->tableData = tempHashData;
return table;
}
int intintLCGLinearOpenCompactOpenMPHash_CreateFactory(intintHash_Factory *
factory, int hashIndex) {
factory->createFunc[hashIndex] =
&intintLCGLinearOpenCompactOpenMPHash_CreateTable;
factory->destroyFunc[hashIndex] =
&intintLCGLinearOpenCompactOpenMPHash_DestroyFactory;;
return HASH_EXIT_CODE_NORMAL;
}
int intintLCGLinearOpenCompactOpenMPHash_DestroyFactory(intintHash_Factory *
factory,
int hashIndex) {;
return HASH_EXIT_CODE_NORMAL;
}
int intintLCGLinearOpenCompactOpenMPHash_DestroyTable(intintHash_Table * table) {
int exitCode = 0;
free(table->tableData);
free(table);
return exitCode;
}
int intintLCGLinearOpenCompactOpenMPHash_SetupTable(intintHash_Table * table) {
int exitCode = 0;
intintLCGLinearOpenCompactOpenMPHash_Bucket *buckets =
(intintLCGLinearOpenCompactOpenMPHash_Bucket *) & table->
tableData[sizeof(intintLCGLinearOpenCompactOpenMPHash_TableData)];
if (intintHash_GetTableType(table) & ~HASH_SENTINEL_PERFECT_HASHES) {
#pragma omp parallel for
for (int index = 0;
index <
((intintLCGLinearOpenCompactOpenMPHash_TableData *) table->
tableData)->numBuckets; index++) {
buckets[index].key = HASH_BUCKET_STATUS_EMPTY;
}}
exitCode = HASH_EXIT_CODE_NORMAL;
return exitCode;
}
int intintLCGLinearOpenCompactOpenMPHash_EmptyTable(intintHash_Table * table) {
int exitCode = 0;
intintLCGLinearOpenCompactOpenMPHash_Bucket *buckets =
(intintLCGLinearOpenCompactOpenMPHash_Bucket *) & table->
tableData[sizeof(intintLCGLinearOpenCompactOpenMPHash_TableData)];
#pragma omp parallel for
for (int index = 0;
index <
((intintLCGLinearOpenCompactOpenMPHash_TableData *) table->
tableData)->numBuckets; index++) {
buckets[index].key = HASH_BUCKET_STATUS_EMPTY;
} exitCode = HASH_EXIT_CODE_NORMAL;
return exitCode;
}
int intintLCGLinearOpenCompactOpenMPHash_InnerQuerySingle(char *tableData,
int key,
int *valueOutput) {
intintLCGLinearOpenCompactOpenMPHash_Bucket *buckets =
(intintLCGLinearOpenCompactOpenMPHash_Bucket *) &
tableData[sizeof(intintLCGLinearOpenCompactOpenMPHash_TableData)];
int index;
int exitCode;
intintLCGLinearOpenCompactOpenMPHash_TableData *mytableData =
(intintLCGLinearOpenCompactOpenMPHash_TableData *) tableData;
intintHash_CompressLCGData compressFuncData =
mytableData->compressFuncData;
unsigned int c = intintHash_CompressLCG(compressFuncData, key);
unsigned long int iteration = 0;
for (;;) {
index =
((1 * iteration +
c) %
((intintLCGLinearOpenCompactOpenMPHash_TableData *)
tableData)->numBuckets);
int old_key =
__sync_val_compare_and_swap(&buckets[index].key, -1, key);
if (old_key == HASH_BUCKET_STATUS_EMPTY) {
exitCode = HASH_SEARCH_CODE_EMPTY;
break;
} else if (old_key == key) {
exitCode = HASH_SEARCH_CODE_MATCH;
break;
} else if ((index == c && iteration > 0)) {
exitCode = HASH_EXIT_CODE_CYCLE;
break;
}
iteration++;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
*valueOutput = buckets[index].value;
return HASH_EXIT_CODE_NORMAL;
case HASH_SEARCH_CODE_MISMATCH:
case HASH_SEARCH_CODE_EMPTY:
return HASH_EXIT_CODE_KEY_DNE;
default:
return exitCode;
}
}
int intintLCGLinearOpenCompactOpenMPHash_InnerQuery(char *tableData,
unsigned int numKeys,
int *keys,
int *valuesOutput) {
intintLCGLinearOpenCompactOpenMPHash_Bucket *buckets =
(intintLCGLinearOpenCompactOpenMPHash_Bucket *) &
tableData[sizeof(intintLCGLinearOpenCompactOpenMPHash_TableData)];
int key;
int *valueOutput;
int index;
int exitCode;
uint i;
int resultExitCode = HASH_EXIT_CODE_NORMAL;
for (i = 0; i < numKeys; i++) {
key = keys[i];
valueOutput = &valuesOutput[i];
intintLCGLinearOpenCompactOpenMPHash_TableData *mytableData =
(intintLCGLinearOpenCompactOpenMPHash_TableData *)
tableData;
intintHash_CompressLCGData compressFuncData =
mytableData->compressFuncData;
unsigned int c = intintHash_CompressLCG(compressFuncData, key);
unsigned long int iteration = 0;
for (;;) {
index =
((1 * iteration +
c) %
((intintLCGLinearOpenCompactOpenMPHash_TableData *)
tableData)->numBuckets);
int old_key =
__sync_val_compare_and_swap(&buckets[index].key, -1,
key);
if (old_key == HASH_BUCKET_STATUS_EMPTY) {
exitCode = HASH_SEARCH_CODE_EMPTY;
break;
} else if (old_key == key) {
exitCode = HASH_SEARCH_CODE_MATCH;
break;
} else if ((index == c && iteration > 0)) {
exitCode = HASH_EXIT_CODE_CYCLE;
break;
}
iteration++;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
*valueOutput = buckets[index].value;
break;
case HASH_SEARCH_CODE_MISMATCH:
case HASH_SEARCH_CODE_EMPTY:
resultExitCode = HASH_EXIT_CODE_KEY_DNE;
break;
default:
return exitCode;
}
}
return resultExitCode;
}
int intintLCGLinearOpenCompactOpenMPHash_InnerInsertSingle(char *tableData,
int key, int value) {
intintLCGLinearOpenCompactOpenMPHash_Bucket *buckets =
(intintLCGLinearOpenCompactOpenMPHash_Bucket *) &
tableData[sizeof(intintLCGLinearOpenCompactOpenMPHash_TableData)];
int index;
int exitCode;
intintLCGLinearOpenCompactOpenMPHash_TableData *mytableData =
(intintLCGLinearOpenCompactOpenMPHash_TableData *) tableData;
intintHash_CompressLCGData compressFuncData =
mytableData->compressFuncData;
unsigned int c = intintHash_CompressLCG(compressFuncData, key);
unsigned long int iteration = 0;
for (;;) {
index =
((1 * iteration +
c) %
((intintLCGLinearOpenCompactOpenMPHash_TableData *)
tableData)->numBuckets);
int old_key =
__sync_val_compare_and_swap(&buckets[index].key, -1, key);
if (old_key == HASH_BUCKET_STATUS_EMPTY) {
exitCode = HASH_SEARCH_CODE_EMPTY;
break;
} else if (old_key == key) {
exitCode = HASH_SEARCH_CODE_MATCH;
break;
} else if ((index == c && iteration > 0)) {
exitCode = HASH_EXIT_CODE_CYCLE;
break;
}
iteration++;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
buckets[index].value = value;
return HASH_EXIT_CODE_OVERWRITE;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = value;
return HASH_EXIT_CODE_NORMAL;
default:
return exitCode;
}
}
int intintLCGLinearOpenCompactOpenMPHash_InnerInsert(char *tableData,
unsigned int numEntries,
int *keys, int *values) {
intintLCGLinearOpenCompactOpenMPHash_Bucket *buckets =
(intintLCGLinearOpenCompactOpenMPHash_Bucket *) &
tableData[sizeof(intintLCGLinearOpenCompactOpenMPHash_TableData)];
int resultExitCode = HASH_EXIT_CODE_NORMAL;
int key;
int index;
int exitCode;
uint i;
#pragma omp parallel for
for (i = 0; i < numEntries; i++) {
key = keys[i];
intintLCGLinearOpenCompactOpenMPHash_TableData *mytableData =
(intintLCGLinearOpenCompactOpenMPHash_TableData *)
tableData;
intintHash_CompressLCGData compressFuncData =
mytableData->compressFuncData;
unsigned int c = intintHash_CompressLCG(compressFuncData, key);
unsigned long int iteration = 0;
for (;;) {
index =
((1 * iteration +
c) %
((intintLCGLinearOpenCompactOpenMPHash_TableData *)
tableData)->numBuckets);
int old_key =
__sync_val_compare_and_swap(&buckets[index].key, -1,
key);
if (old_key == HASH_BUCKET_STATUS_EMPTY) {
exitCode = HASH_SEARCH_CODE_EMPTY;
break;
} else if (old_key == key) {
exitCode = HASH_SEARCH_CODE_MATCH;
break;
} else if ((index == c && iteration > 0)) {
exitCode = HASH_EXIT_CODE_CYCLE;
break;
}
iteration++;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
resultExitCode = HASH_EXIT_CODE_OVERWRITE;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = values[i];
break;
default:
resultExitCode = exitCode;
}
}
return resultExitCode;
}
int intintLCGLinearOpenCompactOpenMPHash_InnerInsertSingleNoOverwrite(char
*tableData,
int key,
int
value) {
intintLCGLinearOpenCompactOpenMPHash_Bucket *buckets =
(intintLCGLinearOpenCompactOpenMPHash_Bucket *) &
tableData[sizeof(intintLCGLinearOpenCompactOpenMPHash_TableData)];
int index;
int exitCode;
intintLCGLinearOpenCompactOpenMPHash_TableData *mytableData =
(intintLCGLinearOpenCompactOpenMPHash_TableData *) tableData;
intintHash_CompressLCGData compressFuncData =
mytableData->compressFuncData;
unsigned int c = intintHash_CompressLCG(compressFuncData, key);
unsigned long int iteration = 0;
for (;;) {
index =
((1 * iteration +
c) %
((intintLCGLinearOpenCompactOpenMPHash_TableData *)
tableData)->numBuckets);
int old_key =
__sync_val_compare_and_swap(&buckets[index].key, -1, key);
if (old_key == HASH_BUCKET_STATUS_EMPTY) {
exitCode = HASH_SEARCH_CODE_EMPTY;
break;
} else if (old_key == key) {
exitCode = HASH_SEARCH_CODE_MATCH;
break;
} else if ((index == c && iteration > 0)) {
exitCode = HASH_EXIT_CODE_CYCLE;
break;
}
iteration++;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
return HASH_EXIT_CODE_OVERWRITE;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = value;
return HASH_EXIT_CODE_NORMAL;
default:
return exitCode;
}
}
int intintLCGLinearOpenCompactOpenMPHash_InnerInsertNoOverwrite(char *tableData,
unsigned int
numEntries,
int *keys,
int *values) {
intintLCGLinearOpenCompactOpenMPHash_Bucket *buckets =
(intintLCGLinearOpenCompactOpenMPHash_Bucket *) &
tableData[sizeof(intintLCGLinearOpenCompactOpenMPHash_TableData)];
int resultExitCode = HASH_EXIT_CODE_NORMAL;
int key;
int index;
int exitCode;
uint i;
#pragma omp parallel for
for (i = 0; i < numEntries; i++) {
key = keys[i];
intintLCGLinearOpenCompactOpenMPHash_TableData *mytableData =
(intintLCGLinearOpenCompactOpenMPHash_TableData *)
tableData;
intintHash_CompressLCGData compressFuncData =
mytableData->compressFuncData;
unsigned int c = intintHash_CompressLCG(compressFuncData, key);
unsigned long int iteration = 0;
for (;;) {
index =
((1 * iteration +
c) %
((intintLCGLinearOpenCompactOpenMPHash_TableData *)
tableData)->numBuckets);
int old_key =
__sync_val_compare_and_swap(&buckets[index].key, -1,
key);
if (old_key == HASH_BUCKET_STATUS_EMPTY) {
exitCode = HASH_SEARCH_CODE_EMPTY;
break;
} else if (old_key == key) {
exitCode = HASH_SEARCH_CODE_MATCH;
break;
} else if ((index == c && iteration > 0)) {
exitCode = HASH_EXIT_CODE_CYCLE;
break;
}
iteration++;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
resultExitCode = HASH_EXIT_CODE_OVERWRITE;
break;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = values[i];
break;
default:
resultExitCode = exitCode;
}
}
return resultExitCode;
}
int intintLCGLinearOpenCompactOpenMPHash_QuerySingle(intintHash_Table * table,
int key,
int *valueOutput) {
return intintLCGLinearOpenCompactOpenMPHash_InnerQuerySingle(table->
tableData,
key,
valueOutput);
}
int intintLCGLinearOpenCompactOpenMPHash_Query(intintHash_Table * table,
size_t numKeys, int *keys,
int *valuesOutput) {
return intintLCGLinearOpenCompactOpenMPHash_InnerQuery(table->tableData,
numKeys, keys,
valuesOutput);
}
int intintLCGLinearOpenCompactOpenMPHash_InsertSingle(intintHash_Table * table,
int key, int value) {
return intintLCGLinearOpenCompactOpenMPHash_InnerInsertSingle(table->
tableData,
key,
value);
}
int intintLCGLinearOpenCompactOpenMPHash_Insert(intintHash_Table * table,
size_t numEntries, int *keys,
int *values) {
return intintLCGLinearOpenCompactOpenMPHash_InnerInsert(table->
tableData,
numEntries,
keys, values);
}
int
intintLCGLinearOpenCompactOpenMPHash_InsertSingleNoOverwrite(intintHash_Table *
table, int key,
int value) {
return
intintLCGLinearOpenCompactOpenMPHash_InnerInsertSingleNoOverwrite
(table->tableData, key, value);
}
int intintLCGLinearOpenCompactOpenMPHash_InsertNoOverwrite(intintHash_Table *
table,
size_t numEntries,
int *keys,
int *values) {
return
intintLCGLinearOpenCompactOpenMPHash_InnerInsertNoOverwrite(table->
tableData,
numEntries,
keys,
values);
}
typedef struct intintLCGQuadraticOpenCompactHash_TableData {
int hashID;
unsigned int numBuckets;
intintHash_CompressLCGData compressFuncData;
} intintLCGQuadraticOpenCompactHash_TableData;
typedef struct intintLCGQuadraticOpenCompactHash_Bucket {
int key;
int value;
} intintLCGQuadraticOpenCompactHash_Bucket;
intintHash_Table
*intintLCGQuadraticOpenCompactHash_CreateTable(intintHash_Factory * factory,
int hashIndex,
size_t keyRange,
size_t numEntries,
float loadFactor) {
intintHash_Table *table =
(intintHash_Table *) malloc(sizeof(intintHash_Table));
table->destroyFunc = &intintLCGQuadraticOpenCompactHash_DestroyTable;
table->setupFunc = &intintLCGQuadraticOpenCompactHash_SetupTable;
table->emptyFunc = &intintLCGQuadraticOpenCompactHash_EmptyTable;
table->queryFunc = &intintLCGQuadraticOpenCompactHash_Query;
table->querySingleFunc = &intintLCGQuadraticOpenCompactHash_QuerySingle;
table->insertFunc = &intintLCGQuadraticOpenCompactHash_Insert;
table->insertSingleFunc =
&intintLCGQuadraticOpenCompactHash_InsertSingle;
table->insertNoOverwriteFunc =
&intintLCGQuadraticOpenCompactHash_InsertNoOverwrite;
table->insertSingleNoOverwriteFunc =
&intintLCGQuadraticOpenCompactHash_InsertSingleNoOverwrite;
table->tableData =
(char *)malloc(sizeof(intintLCGQuadraticOpenCompactHash_TableData));
((intintLCGQuadraticOpenCompactHash_TableData *) table->tableData)->
hashID = LCG_QUADRATIC_OPEN_COMPACT_HASH_ID;
((intintLCGQuadraticOpenCompactHash_TableData *) table->tableData)->
numBuckets = (unsigned int)((double)numEntries / loadFactor);
((intintLCGQuadraticOpenCompactHash_TableData *) table->tableData)->
compressFuncData.a = HASH_LCG_A;
((intintLCGQuadraticOpenCompactHash_TableData *) table->tableData)->
compressFuncData.c = HASH_LCG_C;
((intintLCGQuadraticOpenCompactHash_TableData *) table->tableData)->
compressFuncData.m = HASH_LCG_M;
((intintLCGQuadraticOpenCompactHash_TableData *) table->tableData)->
compressFuncData.n =
((intintLCGQuadraticOpenCompactHash_TableData *) table->tableData)->
numBuckets;
((intintLCGQuadraticOpenCompactHash_TableData *) table->tableData)->
numBuckets =
largestProthPrimeUnder(((intintLCGQuadraticOpenCompactHash_TableData
*) table->tableData)->numBuckets);
char *tempHashData =
(char *)malloc(sizeof(intintLCGQuadraticOpenCompactHash_TableData) +
((intintLCGQuadraticOpenCompactHash_TableData *)
table->tableData)->numBuckets *
sizeof(intintLCGQuadraticOpenCompactHash_Bucket));
memcpy(tempHashData, table->tableData,
sizeof(intintLCGQuadraticOpenCompactHash_TableData));
free(table->tableData);
table->tableData = tempHashData;
return table;
}
int intintLCGQuadraticOpenCompactHash_CreateFactory(intintHash_Factory *
factory, int hashIndex) {
factory->createFunc[hashIndex] =
&intintLCGQuadraticOpenCompactHash_CreateTable;
factory->destroyFunc[hashIndex] =
&intintLCGQuadraticOpenCompactHash_DestroyFactory;;
return HASH_EXIT_CODE_NORMAL;
}
int intintLCGQuadraticOpenCompactHash_DestroyFactory(intintHash_Factory *
factory, int hashIndex) {;
return HASH_EXIT_CODE_NORMAL;
}
int intintLCGQuadraticOpenCompactHash_DestroyTable(intintHash_Table * table) {
int exitCode = 0;
free(table->tableData);
free(table);
return exitCode;
}
int intintLCGQuadraticOpenCompactHash_SetupTable(intintHash_Table * table) {
int exitCode = 0;
intintLCGQuadraticOpenCompactHash_Bucket *buckets =
(intintLCGQuadraticOpenCompactHash_Bucket *) & table->
tableData[sizeof(intintLCGQuadraticOpenCompactHash_TableData)];
if (intintHash_GetTableType(table) & ~HASH_SENTINEL_PERFECT_HASHES) {
for (int index = 0;
index <
((intintLCGQuadraticOpenCompactHash_TableData *) table->
tableData)->numBuckets; index++) {
buckets[index].key = HASH_BUCKET_STATUS_EMPTY;
}}
exitCode = HASH_EXIT_CODE_NORMAL;
return exitCode;
}
int intintLCGQuadraticOpenCompactHash_EmptyTable(intintHash_Table * table) {
int exitCode = 0;
intintLCGQuadraticOpenCompactHash_Bucket *buckets =
(intintLCGQuadraticOpenCompactHash_Bucket *) & table->
tableData[sizeof(intintLCGQuadraticOpenCompactHash_TableData)];
for (int index = 0;
index <
((intintLCGQuadraticOpenCompactHash_TableData *) table->
tableData)->numBuckets; index++) {
buckets[index].key = HASH_BUCKET_STATUS_EMPTY;
} exitCode = HASH_EXIT_CODE_NORMAL;
return exitCode;
}
int intintLCGQuadraticOpenCompactHash_InnerQuerySingle(char *tableData, int key,
int *valueOutput) {
intintLCGQuadraticOpenCompactHash_Bucket *buckets =
(intintLCGQuadraticOpenCompactHash_Bucket *) &
tableData[sizeof(intintLCGQuadraticOpenCompactHash_TableData)];
int index;
int exitCode;
intintLCGQuadraticOpenCompactHash_TableData *mytableData =
(intintLCGQuadraticOpenCompactHash_TableData *) tableData;
intintHash_CompressLCGData compressFuncData =
mytableData->compressFuncData;
unsigned int c = intintHash_CompressLCG(compressFuncData, key);
unsigned long int iteration = 0;
for (;;) {
index =
((1 * iteration * iteration + 0 * iteration +
c) %
((intintLCGQuadraticOpenCompactHash_TableData *)
tableData)->numBuckets);
if ((buckets[index].key) == HASH_BUCKET_STATUS_EMPTY) {
exitCode = HASH_SEARCH_CODE_EMPTY;
break;
} else if (key == buckets[index].key) {
exitCode = HASH_SEARCH_CODE_MATCH;
break;
} else
if ((iteration >
((intintLCGQuadraticOpenCompactHash_TableData *)
tableData)->numBuckets)) {
exitCode = HASH_EXIT_CODE_CYCLE;
break;
}
iteration++;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
*valueOutput = buckets[index].value;
return HASH_EXIT_CODE_NORMAL;
case HASH_SEARCH_CODE_MISMATCH:
case HASH_SEARCH_CODE_EMPTY:
return HASH_EXIT_CODE_KEY_DNE;
default:
return exitCode;
}
}
int intintLCGQuadraticOpenCompactHash_InnerQuery(char *tableData,
unsigned int numKeys,
int *keys, int *valuesOutput) {
intintLCGQuadraticOpenCompactHash_Bucket *buckets =
(intintLCGQuadraticOpenCompactHash_Bucket *) &
tableData[sizeof(intintLCGQuadraticOpenCompactHash_TableData)];
int key;
int *valueOutput;
int index;
int exitCode;
uint i;
int resultExitCode = HASH_EXIT_CODE_NORMAL;
for (i = 0; i < numKeys; i++) {
key = keys[i];
valueOutput = &valuesOutput[i];
intintLCGQuadraticOpenCompactHash_TableData *mytableData =
(intintLCGQuadraticOpenCompactHash_TableData *) tableData;
intintHash_CompressLCGData compressFuncData =
mytableData->compressFuncData;
unsigned int c = intintHash_CompressLCG(compressFuncData, key);
unsigned long int iteration = 0;
for (;;) {
index =
((1 * iteration * iteration + 0 * iteration +
c) %
((intintLCGQuadraticOpenCompactHash_TableData *)
tableData)->numBuckets);
if ((buckets[index].key) == HASH_BUCKET_STATUS_EMPTY) {
exitCode = HASH_SEARCH_CODE_EMPTY;
break;
} else if (key == buckets[index].key) {
exitCode = HASH_SEARCH_CODE_MATCH;
break;
} else
if ((iteration >
((intintLCGQuadraticOpenCompactHash_TableData
*) tableData)->numBuckets)) {
exitCode = HASH_EXIT_CODE_CYCLE;
break;
}
iteration++;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
*valueOutput = buckets[index].value;
break;
case HASH_SEARCH_CODE_MISMATCH:
case HASH_SEARCH_CODE_EMPTY:
resultExitCode = HASH_EXIT_CODE_KEY_DNE;
break;
default:
return exitCode;
}
}
return resultExitCode;
}
int intintLCGQuadraticOpenCompactHash_InnerInsertSingle(char *tableData,
int key, int value) {
intintLCGQuadraticOpenCompactHash_Bucket *buckets =
(intintLCGQuadraticOpenCompactHash_Bucket *) &
tableData[sizeof(intintLCGQuadraticOpenCompactHash_TableData)];
int index;
int exitCode;
intintLCGQuadraticOpenCompactHash_TableData *mytableData =
(intintLCGQuadraticOpenCompactHash_TableData *) tableData;
intintHash_CompressLCGData compressFuncData =
mytableData->compressFuncData;
unsigned int c = intintHash_CompressLCG(compressFuncData, key);
unsigned long int iteration = 0;
for (;;) {
index =
((1 * iteration * iteration + 0 * iteration +
c) %
((intintLCGQuadraticOpenCompactHash_TableData *)
tableData)->numBuckets);
if (((buckets[index].key ==
HASH_BUCKET_STATUS_EMPTY) ? (buckets[index].key =
key,
HASH_BUCKET_STATUS_EMPTY) :
buckets[index].key) == HASH_BUCKET_STATUS_EMPTY) {
exitCode = HASH_SEARCH_CODE_EMPTY;
break;
} else if (key == buckets[index].key) {
exitCode = HASH_SEARCH_CODE_MATCH;
break;
} else
if ((iteration >
((intintLCGQuadraticOpenCompactHash_TableData *)
tableData)->numBuckets)) {
exitCode = HASH_EXIT_CODE_CYCLE;
break;
}
iteration++;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
buckets[index].value = value;
return HASH_EXIT_CODE_OVERWRITE;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = value;
return HASH_EXIT_CODE_NORMAL;
default:
return exitCode;
}
}
int intintLCGQuadraticOpenCompactHash_InnerInsert(char *tableData,
unsigned int numEntries,
int *keys, int *values) {
intintLCGQuadraticOpenCompactHash_Bucket *buckets =
(intintLCGQuadraticOpenCompactHash_Bucket *) &
tableData[sizeof(intintLCGQuadraticOpenCompactHash_TableData)];
int resultExitCode = HASH_EXIT_CODE_NORMAL;
int key;
int index;
int exitCode;
uint i;;
for (i = 0; i < numEntries; i++) {
key = keys[i];
intintLCGQuadraticOpenCompactHash_TableData *mytableData =
(intintLCGQuadraticOpenCompactHash_TableData *) tableData;
intintHash_CompressLCGData compressFuncData =
mytableData->compressFuncData;
unsigned int c = intintHash_CompressLCG(compressFuncData, key);
unsigned long int iteration = 0;
for (;;) {
index =
((1 * iteration * iteration + 0 * iteration +
c) %
((intintLCGQuadraticOpenCompactHash_TableData *)
tableData)->numBuckets);
if (((buckets[index].key ==
HASH_BUCKET_STATUS_EMPTY) ? (buckets[index].key =
key,
HASH_BUCKET_STATUS_EMPTY)
: buckets[index].key) ==
HASH_BUCKET_STATUS_EMPTY) {
exitCode = HASH_SEARCH_CODE_EMPTY;
break;
} else if (key == buckets[index].key) {
exitCode = HASH_SEARCH_CODE_MATCH;
break;
} else
if ((iteration >
((intintLCGQuadraticOpenCompactHash_TableData
*) tableData)->numBuckets)) {
exitCode = HASH_EXIT_CODE_CYCLE;
break;
}
iteration++;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
resultExitCode = HASH_EXIT_CODE_OVERWRITE;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = values[i];
break;
default:
resultExitCode = exitCode;
}
}
return resultExitCode;
}
int intintLCGQuadraticOpenCompactHash_InnerInsertSingleNoOverwrite(char
*tableData,
int key,
int value) {
intintLCGQuadraticOpenCompactHash_Bucket *buckets =
(intintLCGQuadraticOpenCompactHash_Bucket *) &
tableData[sizeof(intintLCGQuadraticOpenCompactHash_TableData)];
int index;
int exitCode;
intintLCGQuadraticOpenCompactHash_TableData *mytableData =
(intintLCGQuadraticOpenCompactHash_TableData *) tableData;
intintHash_CompressLCGData compressFuncData =
mytableData->compressFuncData;
unsigned int c = intintHash_CompressLCG(compressFuncData, key);
unsigned long int iteration = 0;
for (;;) {
index =
((1 * iteration * iteration + 0 * iteration +
c) %
((intintLCGQuadraticOpenCompactHash_TableData *)
tableData)->numBuckets);
if (((buckets[index].key ==
HASH_BUCKET_STATUS_EMPTY) ? (buckets[index].key =
key,
HASH_BUCKET_STATUS_EMPTY) :
buckets[index].key) == HASH_BUCKET_STATUS_EMPTY) {
exitCode = HASH_SEARCH_CODE_EMPTY;
break;
} else if (key == buckets[index].key) {
exitCode = HASH_SEARCH_CODE_MATCH;
break;
} else
if ((iteration >
((intintLCGQuadraticOpenCompactHash_TableData *)
tableData)->numBuckets)) {
exitCode = HASH_EXIT_CODE_CYCLE;
break;
}
iteration++;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
return HASH_EXIT_CODE_OVERWRITE;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = value;
return HASH_EXIT_CODE_NORMAL;
default:
return exitCode;
}
}
int intintLCGQuadraticOpenCompactHash_InnerInsertNoOverwrite(char *tableData,
unsigned int
numEntries,
int *keys,
int *values) {
intintLCGQuadraticOpenCompactHash_Bucket *buckets =
(intintLCGQuadraticOpenCompactHash_Bucket *) &
tableData[sizeof(intintLCGQuadraticOpenCompactHash_TableData)];
int resultExitCode = HASH_EXIT_CODE_NORMAL;
int key;
int index;
int exitCode;
uint i;;
for (i = 0; i < numEntries; i++) {
key = keys[i];
intintLCGQuadraticOpenCompactHash_TableData *mytableData =
(intintLCGQuadraticOpenCompactHash_TableData *) tableData;
intintHash_CompressLCGData compressFuncData =
mytableData->compressFuncData;
unsigned int c = intintHash_CompressLCG(compressFuncData, key);
unsigned long int iteration = 0;
for (;;) {
index =
((1 * iteration * iteration + 0 * iteration +
c) %
((intintLCGQuadraticOpenCompactHash_TableData *)
tableData)->numBuckets);
if (((buckets[index].key ==
HASH_BUCKET_STATUS_EMPTY) ? (buckets[index].key =
key,
HASH_BUCKET_STATUS_EMPTY)
: buckets[index].key) ==
HASH_BUCKET_STATUS_EMPTY) {
exitCode = HASH_SEARCH_CODE_EMPTY;
break;
} else if (key == buckets[index].key) {
exitCode = HASH_SEARCH_CODE_MATCH;
break;
} else
if ((iteration >
((intintLCGQuadraticOpenCompactHash_TableData
*) tableData)->numBuckets)) {
exitCode = HASH_EXIT_CODE_CYCLE;
break;
}
iteration++;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
resultExitCode = HASH_EXIT_CODE_OVERWRITE;
break;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = values[i];
break;
default:
resultExitCode = exitCode;
}
}
return resultExitCode;
}
int intintLCGQuadraticOpenCompactHash_QuerySingle(intintHash_Table * table,
int key, int *valueOutput) {
return intintLCGQuadraticOpenCompactHash_InnerQuerySingle(table->
tableData,
key,
valueOutput);
}
int intintLCGQuadraticOpenCompactHash_Query(intintHash_Table * table,
size_t numKeys, int *keys,
int *valuesOutput) {
return intintLCGQuadraticOpenCompactHash_InnerQuery(table->tableData,
numKeys, keys,
valuesOutput);
}
int intintLCGQuadraticOpenCompactHash_InsertSingle(intintHash_Table * table,
int key, int value) {
return intintLCGQuadraticOpenCompactHash_InnerInsertSingle(table->
tableData,
key, value);
}
int intintLCGQuadraticOpenCompactHash_Insert(intintHash_Table * table,
size_t numEntries, int *keys,
int *values) {
return intintLCGQuadraticOpenCompactHash_InnerInsert(table->tableData,
numEntries, keys,
values);
}
int intintLCGQuadraticOpenCompactHash_InsertSingleNoOverwrite(intintHash_Table *
table, int key,
int value) {
return
intintLCGQuadraticOpenCompactHash_InnerInsertSingleNoOverwrite
(table->tableData, key, value);
}
int intintLCGQuadraticOpenCompactHash_InsertNoOverwrite(intintHash_Table *
table,
size_t numEntries,
int *keys,
int *values) {
return intintLCGQuadraticOpenCompactHash_InnerInsertNoOverwrite(table->
tableData,
numEntries,
keys,
values);
}
typedef struct intintLCGQuadraticOpenCompactCLHash_TableData {
int hashID;
unsigned int numBuckets;
intintHash_CompressLCGData compressFuncData;
} intintLCGQuadraticOpenCompactCLHash_TableData;
typedef struct intintLCGQuadraticOpenCompactCLHash_Bucket {
int key;
int value;
} intintLCGQuadraticOpenCompactCLHash_Bucket;
intintHash_Table
*intintLCGQuadraticOpenCompactCLHash_CreateTable(intintHash_Factory *
factory, int hashIndex,
size_t keyRange,
size_t numEntries,
float loadFactor) {
intintHash_Table *table =
(intintHash_Table *) malloc(sizeof(intintHash_Table));
table->destroyFunc = &intintLCGQuadraticOpenCompactCLHash_DestroyTable;
table->setupFunc = &intintLCGQuadraticOpenCompactCLHash_SetupTable;
table->emptyFunc = &intintLCGQuadraticOpenCompactCLHash_EmptyTable;
table->queryFunc = &intintLCGQuadraticOpenCompactCLHash_Query;
table->querySingleFunc =
&intintLCGQuadraticOpenCompactCLHash_QuerySingle;
table->insertFunc = &intintLCGQuadraticOpenCompactCLHash_Insert;
table->insertSingleFunc =
&intintLCGQuadraticOpenCompactCLHash_InsertSingle;
table->insertNoOverwriteFunc =
&intintLCGQuadraticOpenCompactCLHash_InsertNoOverwrite;
table->insertSingleNoOverwriteFunc =
&intintLCGQuadraticOpenCompactCLHash_InsertSingleNoOverwrite;
table->tableData =
(char *)
malloc(sizeof(intintLCGQuadraticOpenCompactCLHash_TableData));
((intintLCGQuadraticOpenCompactCLHash_TableData *) table->tableData)->
hashID = LCG_QUADRATIC_OPEN_COMPACT_CL_HASH_ID;
table->context = factory->context;
table->queue = factory->queue;
table->program = factory->program;
table->localWorkSize = factory->localWorkSize;
table->utilProgram = factory->utilProgram[hashIndex];
table->emptyKernel = factory->emptyKernel[hashIndex];
table->emptyKernelLocalWorkSize =
factory->emptyKernelLocalWorkSize[hashIndex];
table->querySingleKernel = factory->querySingleKernel[hashIndex];
table->insertSingleKernel = factory->insertSingleKernel[hashIndex];
table->insertSingleNoOverwriteKernel =
factory->insertSingleNoOverwriteKernel[hashIndex];
clRetainContext(table->context);
clRetainCommandQueue(table->queue);
clRetainProgram(table->program);
clRetainProgram(table->utilProgram);
clRetainKernel(table->emptyKernel);
clRetainKernel(table->querySingleKernel);
clRetainKernel(table->insertSingleKernel);
clRetainKernel(table->insertSingleNoOverwriteKernel);;
((intintLCGQuadraticOpenCompactCLHash_TableData *) table->tableData)->
numBuckets = (unsigned int)((double)numEntries / loadFactor);
((intintLCGQuadraticOpenCompactCLHash_TableData *) table->tableData)->
compressFuncData.a = HASH_LCG_A;
((intintLCGQuadraticOpenCompactCLHash_TableData *) table->tableData)->
compressFuncData.c = HASH_LCG_C;
((intintLCGQuadraticOpenCompactCLHash_TableData *) table->tableData)->
compressFuncData.m = HASH_LCG_M;
((intintLCGQuadraticOpenCompactCLHash_TableData *) table->tableData)->
compressFuncData.n =
((intintLCGQuadraticOpenCompactCLHash_TableData *) table->
tableData)->numBuckets;
((intintLCGQuadraticOpenCompactCLHash_TableData *) table->tableData)->
numBuckets =
largestProthPrimeUnder(((intintLCGQuadraticOpenCompactCLHash_TableData *) table->tableData)->numBuckets);
char *tempHashData =
(char *)malloc(sizeof(intintLCGQuadraticOpenCompactCLHash_TableData)
+
((intintLCGQuadraticOpenCompactCLHash_TableData *)
table->tableData)->numBuckets *
sizeof(intintLCGQuadraticOpenCompactCLHash_Bucket));
memcpy(tempHashData, table->tableData,
sizeof(intintLCGQuadraticOpenCompactCLHash_TableData));
free(table->tableData);
table->tableData = tempHashData;
cl_int err;
table->tableDataBuffer =
clCreateBuffer(table->context, CL_MEM_READ_WRITE,
sizeof(intintLCGQuadraticOpenCompactHash_TableData) +
((intintLCGQuadraticOpenCompactHash_TableData *)
table->tableData)->numBuckets *
sizeof(intintLCGQuadraticOpenCompactHash_Bucket),
NULL, &err);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_InitTable",
"clCreateBuffer");
err =
clEnqueueWriteBuffer(table->queue, table->tableDataBuffer, CL_TRUE,
0,
sizeof
(intintLCGQuadraticOpenCompactHash_TableData),
table->tableData, 0, NULL, NULL);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_InitTable",
"clEnqueueWriteBuffer");
return table;
}
int intintLCGQuadraticOpenCompactCLHash_CreateFactory(intintHash_Factory *
factory, int hashIndex) {
factory->createFunc[hashIndex] =
&intintLCGQuadraticOpenCompactCLHash_CreateTable;
factory->destroyFunc[hashIndex] =
&intintLCGQuadraticOpenCompactCLHash_DestroyFactory;
cl_int error;
cl_device_id device;
error =
clGetContextInfo(factory->context, CL_CONTEXT_DEVICES,
sizeof(device), &device, NULL);
CLHash_Utilities_HandleError(error, "intintHash_CreateFactory",
"clGetContextInfo");
factory->querySingleKernel[hashIndex] =
clCreateKernel(factory->program,
"intintLCGQuadraticOpenCompactCLHash_RangeQuerySingle",
&error);
CLHash_Utilities_HandleError(error,
"intintLCGQuadraticOpenCompactCLHash_CreateFactory",
"clCreateKernel");
factory->insertSingleKernel[hashIndex] =
clCreateKernel(factory->program,
"intintLCGQuadraticOpenCompactCLHash_RangeInsertSingle",
&error);
CLHash_Utilities_HandleError(error,
"intintLCGQuadraticOpenCompactCLHash_CreateFactory",
"clCreateKernel");
factory->insertSingleNoOverwriteKernel[hashIndex] =
clCreateKernel(factory->program,
"intintLCGQuadraticOpenCompactCLHash_RangeInsertSingleNoOverwrite",
&error);
CLHash_Utilities_HandleError(error,
"intintLCGQuadraticOpenCompactCLHash_CreateFactory",
"clCreateKernel");
factory->utilProgram[hashIndex] =
CLHash_Utilities_BuildProgramString(factory->context, device,
"static inline unsigned int intintHash_CompressIdentity(char data, int hashCode){ return hashCode; } typedef struct intintHash_CompressLCGData{ long unsigned int a; long unsigned int c; unsigned int m; unsigned int n; }intintHash_CompressLCGData; static inline unsigned int intintHash_CompressLCG(intintHash_CompressLCGData compressLCGData, int hashCode){ return ((compressLCGData.a * hashCode + compressLCGData.c) % compressLCGData.m) % compressLCGData.n; } typedef struct intintLCGQuadraticOpenCompactCLHash_TableData{ int hashID; unsigned int numBuckets; intintHash_CompressLCGData compressFuncData; }intintLCGQuadraticOpenCompactCLHash_TableData; typedef struct intintLCGQuadraticOpenCompactCLHash_Bucket{ int key; int value; }intintLCGQuadraticOpenCompactCLHash_Bucket; __kernel void intintLCGQuadraticOpenCompactCLHash_Empty(__global char *tableData){ int index = get_global_id(0); if(index >= ((__global intintLCGQuadraticOpenCompactCLHash_TableData*)tableData)->numBuckets){ return; } __global intintLCGQuadraticOpenCompactCLHash_Bucket *buckets = (__global intintLCGQuadraticOpenCompactCLHash_Bucket*)&tableData[sizeof(intintLCGQuadraticOpenCompactCLHash_TableData)]; buckets[index].key = -1;/*HASH_BUCKET_STATUS_EMPTY*/ }");
factory->emptyKernel[hashIndex] =
clCreateKernel(factory->utilProgram[hashIndex],
"intintLCGQuadraticOpenCompactCLHash_Empty", &error);
CLHash_Utilities_HandleError(error,
"intintLCGQuadraticOpenCompactCLHash_CreateFactory",
"clCreateKernel");
error =
clGetKernelWorkGroupInfo(factory->emptyKernel[hashIndex], device,
CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t),
&factory->
emptyKernelLocalWorkSize[hashIndex], NULL);
CLHash_Utilities_HandleError(error,
"intintLCGQuadraticOpenCompactCLHash_CreateFactory",
"clGetKernelWorkGroupInfo");;;
return HASH_EXIT_CODE_NORMAL;
}
int intintLCGQuadraticOpenCompactCLHash_DestroyFactory(intintHash_Factory *
factory,
int hashIndex) {;
clReleaseKernel(factory->emptyKernel[hashIndex]);
clReleaseProgram(factory->utilProgram[hashIndex]);
clReleaseKernel(factory->querySingleKernel[hashIndex]);
clReleaseKernel(factory->insertSingleKernel[hashIndex]);
clReleaseKernel(factory->insertSingleNoOverwriteKernel[hashIndex]);;
return HASH_EXIT_CODE_NORMAL;
}
int intintLCGQuadraticOpenCompactCLHash_DestroyTable(intintHash_Table * table) {
int exitCode = 0;
clReleaseMemObject(table->tableDataBuffer);
clReleaseContext(table->context);
clReleaseCommandQueue(table->queue);
clReleaseProgram(table->utilProgram);
clReleaseKernel(table->emptyKernel);
clReleaseProgram(table->program);
clReleaseKernel(table->querySingleKernel);
clReleaseKernel(table->insertSingleKernel);
clReleaseKernel(table->insertSingleNoOverwriteKernel);
free(table->tableData);
free(table);
return exitCode;
}
int intintLCGQuadraticOpenCompactCLHash_SetupTable(intintHash_Table * table) {
int exitCode = 0;
cl_int err;
err =
clSetKernelArg(table->emptyKernel, 0, sizeof(cl_mem),
&table->tableDataBuffer);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_EmptyTable",
"clSetKernelArg");
const size_t groupWorkSize =
roundUpToNearest(((intintLCGQuadraticOpenCompactHash_TableData *)
table->tableData)->numBuckets,
table->emptyKernelLocalWorkSize);
err =
clEnqueueNDRangeKernel(table->queue, table->emptyKernel, 1, 0,
&groupWorkSize,
(const size_t *)&table->
emptyKernelLocalWorkSize, 0, NULL, NULL);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_EmptyTable",
"clEnqueueNDRangeKernel");
exitCode = HASH_EXIT_CODE_NORMAL;;
return exitCode;
}
int intintLCGQuadraticOpenCompactCLHash_EmptyTable(intintHash_Table * table) {
int exitCode = 0;
cl_int err;
err =
clSetKernelArg(table->emptyKernel, 0, sizeof(cl_mem),
&table->tableDataBuffer);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_EmptyTable",
"clSetKernelArg");
const size_t groupWorkSize =
roundUpToNearest(((intintLCGQuadraticOpenCompactHash_TableData *)
table->tableData)->numBuckets,
table->emptyKernelLocalWorkSize);
err =
clEnqueueNDRangeKernel(table->queue, table->emptyKernel, 1, 0,
&groupWorkSize,
(const size_t *)&table->
emptyKernelLocalWorkSize, 0, NULL, NULL);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_EmptyTable",
"clEnqueueNDRangeKernel");
exitCode = HASH_EXIT_CODE_NORMAL;;
return exitCode;
}
int intintLCGQuadraticOpenCompactCLHash_QuerySingle(intintHash_Table * table,
int key, int *valueOutput) {
return intintLCGQuadraticOpenCompactCLHash_Query(table, 1, &key,
valueOutput);
}
int intintLCGQuadraticOpenCompactCLHash_Query(intintHash_Table * table,
size_t numKeys, int *keys,
int *valuesOutput) {
cl_int err;
cl_mem keysBuffer =
clCreateBuffer(table->context,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(int) * numKeys, keys, &err);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_Query",
"clCreateBuffer");
cl_mem valuesOutputBuffer =
clCreateBuffer(table->context, CL_MEM_WRITE_ONLY,
sizeof(int) * numKeys, NULL, &err);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_Query",
"clCreateBuffer");
intintLCGQuadraticOpenCompactCLHash_BufferQuery(table, numKeys,
keysBuffer,
valuesOutputBuffer);
err =
clEnqueueReadBuffer(table->queue, valuesOutputBuffer, CL_TRUE, 0,
sizeof(int) * numKeys, valuesOutput, 0, NULL,
NULL);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_Query",
"clEnqueueReadBuffer");
clReleaseMemObject(keysBuffer);
clReleaseMemObject(valuesOutputBuffer);
return HASH_EXIT_CODE_NORMAL;
}
int intintLCGQuadraticOpenCompactCLHash_BufferQuery(intintHash_Table * table,
size_t numKeys,
cl_mem keysBuffer,
cl_mem valuesOutputBuffer) {
cl_int err;
err =
clSetKernelArg(table->querySingleKernel, 0, sizeof(cl_mem),
&table->tableDataBuffer);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_BufferQuery",
"clSetKernelArg");
err =
clSetKernelArg(table->querySingleKernel, 1, sizeof(unsigned int),
&numKeys);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_BufferQuery",
"clSetKernelArg");
err =
clSetKernelArg(table->querySingleKernel, 2, sizeof(cl_mem),
&keysBuffer);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_BufferQuery",
"clSetKernelArg");
err =
clSetKernelArg(table->querySingleKernel, 3, sizeof(cl_mem),
&valuesOutputBuffer);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_BufferQuery",
"clSetKernelArg");
const size_t groupWorkSize =
roundUpToNearest(numKeys, table->localWorkSize);
err =
clEnqueueNDRangeKernel(table->queue, table->querySingleKernel, 1, 0,
&groupWorkSize,
(const size_t *)&table->localWorkSize, 0,
NULL, NULL);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_BufferQuery",
"clEnqueueNDRangeKernel");
clFinish(table->queue);
return HASH_EXIT_CODE_NORMAL;
}
int intintLCGQuadraticOpenCompactCLHash_InsertSingle(intintHash_Table * table,
int key, int value) {
return intintLCGQuadraticOpenCompactCLHash_Insert(table, 1, &key,
&value);
}
int intintLCGQuadraticOpenCompactCLHash_Insert(intintHash_Table * table,
size_t numEntries, int *keys,
int *values) {
cl_int err;
cl_mem keysBuffer =
clCreateBuffer(table->context,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(int) * numEntries, keys, &err);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_Insert",
"clCreateBuffer");
cl_mem valuesBuffer =
clCreateBuffer(table->context,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(int) * numEntries, values, &err);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_Insert",
"clCreateBuffer");
intintLCGQuadraticOpenCompactCLHash_BufferInsert(table, numEntries,
keysBuffer,
valuesBuffer);
clReleaseMemObject(keysBuffer);
clReleaseMemObject(valuesBuffer);
return HASH_EXIT_CODE_NORMAL;
}
int intintLCGQuadraticOpenCompactCLHash_BufferInsert(intintHash_Table * table,
size_t numEntries,
cl_mem keysBuffer,
cl_mem valuesBuffer) {
cl_int err;
err =
clSetKernelArg(table->insertSingleKernel, 0, sizeof(cl_mem),
&table->tableDataBuffer);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_BufferInsert",
"clSetKernelArg");
err =
clSetKernelArg(table->insertSingleKernel, 1, sizeof(unsigned int),
&numEntries);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_BufferInsert",
"clSetKernelArg");
err =
clSetKernelArg(table->insertSingleKernel, 2, sizeof(cl_mem),
&keysBuffer);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_BufferInsert",
"clSetKernelArg");
err =
clSetKernelArg(table->insertSingleKernel, 3, sizeof(cl_mem),
&valuesBuffer);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_BufferInsert",
"clSetKernelArg");
const size_t groupWorkSize =
roundUpToNearest(numEntries, table->localWorkSize);
err =
clEnqueueNDRangeKernel(table->queue, table->insertSingleKernel, 1,
0, &groupWorkSize,
(const size_t *)&table->localWorkSize, 0,
NULL, NULL);
CLHash_Utilities_HandleError(err, NULL, "clEnqueueNDRangeKernel");
return (0);
}
int intintLCGQuadraticOpenCompactCLHash_InsertSingleNoOverwrite(intintHash_Table
* table,
int key,
int value) {
return intintLCGQuadraticOpenCompactCLHash_InsertNoOverwrite(table, 1,
&key,
&value);
}
int intintLCGQuadraticOpenCompactCLHash_InsertNoOverwrite(intintHash_Table *
table,
size_t numEntries,
int *keys,
int *values) {
cl_int err;
cl_mem keysBuffer =
clCreateBuffer(table->context,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(int) * numEntries, keys, &err);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_InsertNoOverwrite",
"clCreateBuffer");
cl_mem valuesBuffer =
clCreateBuffer(table->context,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(int) * numEntries, values, &err);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_InsertNoOverwrite",
"clCreateBuffer");
intintLCGQuadraticOpenCompactCLHash_BufferInsertNoOverwrite(table,
numEntries,
keysBuffer,
valuesBuffer);
clReleaseMemObject(keysBuffer);
clReleaseMemObject(valuesBuffer);
return HASH_EXIT_CODE_NORMAL;
}
int intintLCGQuadraticOpenCompactCLHash_BufferInsertNoOverwrite(intintHash_Table
* table,
size_t
numEntries,
cl_mem
keysBuffer,
cl_mem
valuesBuffer) {
cl_int err;
err =
clSetKernelArg(table->insertSingleNoOverwriteKernel, 0,
sizeof(cl_mem), &table->tableDataBuffer);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_BufferInsertNoOverwrite",
"clSetKernelArg");
err =
clSetKernelArg(table->insertSingleNoOverwriteKernel, 1,
sizeof(unsigned int), &numEntries);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_BufferInsertNoOverwrite",
"ClSetKernelArg");
err =
clSetKernelArg(table->insertSingleNoOverwriteKernel, 2,
sizeof(cl_mem), &keysBuffer);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_BufferInsertNoOverwrite",
"clSetKernelArg");
err =
clSetKernelArg(table->insertSingleNoOverwriteKernel, 3,
sizeof(cl_mem), &valuesBuffer);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_BufferInsertNoOverwrite",
"clSetKernelArg");
const size_t groupWorkSize =
roundUpToNearest(numEntries, table->localWorkSize);
err =
clEnqueueNDRangeKernel(table->queue,
table->insertSingleNoOverwriteKernel, 1, 0,
&groupWorkSize,
(const size_t *)&table->localWorkSize, 0,
NULL, NULL);
CLHash_Utilities_HandleError(err,
"intintLCGQuadraticOpenCompactCLHash_BufferInsertNoOverwrite",
"clEnqueueNDRangeKernel");
return (0);
}
typedef struct intintLCGQuadraticOpenCompactOpenMPHash_TableData {
int hashID;
unsigned int numBuckets;
intintHash_CompressLCGData compressFuncData;
} intintLCGQuadraticOpenCompactOpenMPHash_TableData;
typedef struct intintLCGQuadraticOpenCompactOpenMPHash_Bucket {
int key;
int value;
} intintLCGQuadraticOpenCompactOpenMPHash_Bucket;
intintHash_Table
*intintLCGQuadraticOpenCompactOpenMPHash_CreateTable(intintHash_Factory *
factory, int hashIndex,
size_t keyRange,
size_t numEntries,
float loadFactor) {
intintHash_Table *table =
(intintHash_Table *) malloc(sizeof(intintHash_Table));
table->destroyFunc =
&intintLCGQuadraticOpenCompactOpenMPHash_DestroyTable;
table->setupFunc = &intintLCGQuadraticOpenCompactOpenMPHash_SetupTable;
table->emptyFunc = &intintLCGQuadraticOpenCompactOpenMPHash_EmptyTable;
table->queryFunc = &intintLCGQuadraticOpenCompactOpenMPHash_Query;
table->querySingleFunc =
&intintLCGQuadraticOpenCompactOpenMPHash_QuerySingle;
table->insertFunc = &intintLCGQuadraticOpenCompactOpenMPHash_Insert;
table->insertSingleFunc =
&intintLCGQuadraticOpenCompactOpenMPHash_InsertSingle;
table->insertNoOverwriteFunc =
&intintLCGQuadraticOpenCompactOpenMPHash_InsertNoOverwrite;
table->insertSingleNoOverwriteFunc =
&intintLCGQuadraticOpenCompactOpenMPHash_InsertSingleNoOverwrite;
table->tableData =
(char *)
malloc(sizeof(intintLCGQuadraticOpenCompactOpenMPHash_TableData));
((intintLCGQuadraticOpenCompactOpenMPHash_TableData *) table->
tableData)->hashID = LCG_QUADRATIC_OPEN_COMPACT_OPENMP_HASH_ID;
((intintLCGQuadraticOpenCompactOpenMPHash_TableData *) table->
tableData)->numBuckets =
(unsigned int)((double)numEntries / loadFactor);
((intintLCGQuadraticOpenCompactOpenMPHash_TableData *) table->
tableData)->compressFuncData.a = HASH_LCG_A;
((intintLCGQuadraticOpenCompactOpenMPHash_TableData *) table->
tableData)->compressFuncData.c = HASH_LCG_C;
((intintLCGQuadraticOpenCompactOpenMPHash_TableData *) table->
tableData)->compressFuncData.m = HASH_LCG_M;
((intintLCGQuadraticOpenCompactOpenMPHash_TableData *) table->
tableData)->compressFuncData.n =
((intintLCGQuadraticOpenCompactOpenMPHash_TableData *) table->tableData)->numBuckets;
((intintLCGQuadraticOpenCompactOpenMPHash_TableData *) table->
tableData)->numBuckets =
largestProthPrimeUnder(((intintLCGQuadraticOpenCompactOpenMPHash_TableData *) table->tableData)->numBuckets);
char *tempHashData =
(char *)
malloc(sizeof(intintLCGQuadraticOpenCompactOpenMPHash_TableData) +
((intintLCGQuadraticOpenCompactOpenMPHash_TableData *)
table->tableData)->numBuckets *
sizeof(intintLCGQuadraticOpenCompactOpenMPHash_Bucket));
memcpy(tempHashData, table->tableData,
sizeof(intintLCGQuadraticOpenCompactOpenMPHash_TableData));
free(table->tableData);
table->tableData = tempHashData;
return table;
}
int intintLCGQuadraticOpenCompactOpenMPHash_CreateFactory(intintHash_Factory *
factory,
int hashIndex) {
factory->createFunc[hashIndex] =
&intintLCGQuadraticOpenCompactOpenMPHash_CreateTable;
factory->destroyFunc[hashIndex] =
&intintLCGQuadraticOpenCompactOpenMPHash_DestroyFactory;;
return HASH_EXIT_CODE_NORMAL;
}
int intintLCGQuadraticOpenCompactOpenMPHash_DestroyFactory(intintHash_Factory *
factory,
int hashIndex) {;
return HASH_EXIT_CODE_NORMAL;
}
int intintLCGQuadraticOpenCompactOpenMPHash_DestroyTable(intintHash_Table *
table) {
int exitCode = 0;
free(table->tableData);
free(table);
return exitCode;
}
int intintLCGQuadraticOpenCompactOpenMPHash_SetupTable(intintHash_Table * table) {
int exitCode = 0;
intintLCGQuadraticOpenCompactOpenMPHash_Bucket *buckets =
(intintLCGQuadraticOpenCompactOpenMPHash_Bucket *) & table->
tableData[sizeof
(intintLCGQuadraticOpenCompactOpenMPHash_TableData)];
if (intintHash_GetTableType(table) & ~HASH_SENTINEL_PERFECT_HASHES) {
#pragma omp parallel for
for (int index = 0;
index <
((intintLCGQuadraticOpenCompactOpenMPHash_TableData *)
table->tableData)->numBuckets; index++) {
buckets[index].key = HASH_BUCKET_STATUS_EMPTY;
}}
exitCode = HASH_EXIT_CODE_NORMAL;
return exitCode;
}
int intintLCGQuadraticOpenCompactOpenMPHash_EmptyTable(intintHash_Table * table) {
int exitCode = 0;
intintLCGQuadraticOpenCompactOpenMPHash_Bucket *buckets =
(intintLCGQuadraticOpenCompactOpenMPHash_Bucket *) & table->
tableData[sizeof
(intintLCGQuadraticOpenCompactOpenMPHash_TableData)];
#pragma omp parallel for
for (int index = 0;
index <
((intintLCGQuadraticOpenCompactOpenMPHash_TableData *) table->
tableData)->numBuckets; index++) {
buckets[index].key = HASH_BUCKET_STATUS_EMPTY;
} exitCode = HASH_EXIT_CODE_NORMAL;
return exitCode;
}
int intintLCGQuadraticOpenCompactOpenMPHash_InnerQuerySingle(char *tableData,
int key,
int *valueOutput) {
intintLCGQuadraticOpenCompactOpenMPHash_Bucket *buckets =
(intintLCGQuadraticOpenCompactOpenMPHash_Bucket *) &
tableData[sizeof
(intintLCGQuadraticOpenCompactOpenMPHash_TableData)];
int index;
int exitCode;
intintLCGQuadraticOpenCompactOpenMPHash_TableData *mytableData =
(intintLCGQuadraticOpenCompactOpenMPHash_TableData *) tableData;
intintHash_CompressLCGData compressFuncData =
mytableData->compressFuncData;
unsigned int c = intintHash_CompressLCG(compressFuncData, key);
unsigned long int iteration = 0;
for (;;) {
index =
((1 * iteration * iteration + 0 * iteration +
c) %
((intintLCGQuadraticOpenCompactOpenMPHash_TableData *)
tableData)->numBuckets);
int old_key =
__sync_val_compare_and_swap(&buckets[index].key, -1, key);
if (old_key == HASH_BUCKET_STATUS_EMPTY) {
exitCode = HASH_SEARCH_CODE_EMPTY;
break;
} else if (old_key == key) {
exitCode = HASH_SEARCH_CODE_MATCH;
break;
} else
if ((iteration >
((intintLCGQuadraticOpenCompactOpenMPHash_TableData *)
tableData)->numBuckets)) {
exitCode = HASH_EXIT_CODE_CYCLE;
break;
}
iteration++;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
*valueOutput = buckets[index].value;
return HASH_EXIT_CODE_NORMAL;
case HASH_SEARCH_CODE_MISMATCH:
case HASH_SEARCH_CODE_EMPTY:
return HASH_EXIT_CODE_KEY_DNE;
default:
return exitCode;
}
}
int intintLCGQuadraticOpenCompactOpenMPHash_InnerQuery(char *tableData,
unsigned int numKeys,
int *keys,
int *valuesOutput) {
intintLCGQuadraticOpenCompactOpenMPHash_Bucket *buckets =
(intintLCGQuadraticOpenCompactOpenMPHash_Bucket *) &
tableData[sizeof
(intintLCGQuadraticOpenCompactOpenMPHash_TableData)];
int key;
int *valueOutput;
int index;
int exitCode;
uint i;
int resultExitCode = HASH_EXIT_CODE_NORMAL;
for (i = 0; i < numKeys; i++) {
key = keys[i];
valueOutput = &valuesOutput[i];
intintLCGQuadraticOpenCompactOpenMPHash_TableData *mytableData =
(intintLCGQuadraticOpenCompactOpenMPHash_TableData *)
tableData;
intintHash_CompressLCGData compressFuncData =
mytableData->compressFuncData;
unsigned int c = intintHash_CompressLCG(compressFuncData, key);
unsigned long int iteration = 0;
for (;;) {
index =
((1 * iteration * iteration + 0 * iteration +
c) %
((intintLCGQuadraticOpenCompactOpenMPHash_TableData
*) tableData)->numBuckets);
int old_key =
__sync_val_compare_and_swap(&buckets[index].key, -1,
key);
if (old_key == HASH_BUCKET_STATUS_EMPTY) {
exitCode = HASH_SEARCH_CODE_EMPTY;
break;
} else if (old_key == key) {
exitCode = HASH_SEARCH_CODE_MATCH;
break;
} else
if ((iteration >
((intintLCGQuadraticOpenCompactOpenMPHash_TableData *) tableData)->numBuckets)) {
exitCode = HASH_EXIT_CODE_CYCLE;
break;
}
iteration++;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
*valueOutput = buckets[index].value;
break;
case HASH_SEARCH_CODE_MISMATCH:
case HASH_SEARCH_CODE_EMPTY:
resultExitCode = HASH_EXIT_CODE_KEY_DNE;
break;
default:
return exitCode;
}
}
return resultExitCode;
}
int intintLCGQuadraticOpenCompactOpenMPHash_InnerInsertSingle(char *tableData,
int key,
int value) {
intintLCGQuadraticOpenCompactOpenMPHash_Bucket *buckets =
(intintLCGQuadraticOpenCompactOpenMPHash_Bucket *) &
tableData[sizeof
(intintLCGQuadraticOpenCompactOpenMPHash_TableData)];
int index;
int exitCode;
intintLCGQuadraticOpenCompactOpenMPHash_TableData *mytableData =
(intintLCGQuadraticOpenCompactOpenMPHash_TableData *) tableData;
intintHash_CompressLCGData compressFuncData =
mytableData->compressFuncData;
unsigned int c = intintHash_CompressLCG(compressFuncData, key);
unsigned long int iteration = 0;
for (;;) {
index =
((1 * iteration * iteration + 0 * iteration +
c) %
((intintLCGQuadraticOpenCompactOpenMPHash_TableData *)
tableData)->numBuckets);
int old_key =
__sync_val_compare_and_swap(&buckets[index].key, -1, key);
if (old_key == HASH_BUCKET_STATUS_EMPTY) {
exitCode = HASH_SEARCH_CODE_EMPTY;
break;
} else if (old_key == key) {
exitCode = HASH_SEARCH_CODE_MATCH;
break;
} else
if ((iteration >
((intintLCGQuadraticOpenCompactOpenMPHash_TableData *)
tableData)->numBuckets)) {
exitCode = HASH_EXIT_CODE_CYCLE;
break;
}
iteration++;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
buckets[index].value = value;
return HASH_EXIT_CODE_OVERWRITE;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = value;
return HASH_EXIT_CODE_NORMAL;
default:
return exitCode;
}
}
int intintLCGQuadraticOpenCompactOpenMPHash_InnerInsert(char *tableData,
unsigned int numEntries,
int *keys,
int *values) {
intintLCGQuadraticOpenCompactOpenMPHash_Bucket *buckets =
(intintLCGQuadraticOpenCompactOpenMPHash_Bucket *) &
tableData[sizeof
(intintLCGQuadraticOpenCompactOpenMPHash_TableData)];
int resultExitCode = HASH_EXIT_CODE_NORMAL;
int key;
int index;
int exitCode;
uint i;
#pragma omp parallel for
for (i = 0; i < numEntries; i++) {
key = keys[i];
intintLCGQuadraticOpenCompactOpenMPHash_TableData *mytableData =
(intintLCGQuadraticOpenCompactOpenMPHash_TableData *)
tableData;
intintHash_CompressLCGData compressFuncData =
mytableData->compressFuncData;
unsigned int c = intintHash_CompressLCG(compressFuncData, key);
unsigned long int iteration = 0;
for (;;) {
index =
((1 * iteration * iteration + 0 * iteration +
c) %
((intintLCGQuadraticOpenCompactOpenMPHash_TableData
*) tableData)->numBuckets);
int old_key =
__sync_val_compare_and_swap(&buckets[index].key, -1,
key);
if (old_key == HASH_BUCKET_STATUS_EMPTY) {
exitCode = HASH_SEARCH_CODE_EMPTY;
break;
} else if (old_key == key) {
exitCode = HASH_SEARCH_CODE_MATCH;
break;
} else
if ((iteration >
((intintLCGQuadraticOpenCompactOpenMPHash_TableData *) tableData)->numBuckets)) {
exitCode = HASH_EXIT_CODE_CYCLE;
break;
}
iteration++;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
resultExitCode = HASH_EXIT_CODE_OVERWRITE;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = values[i];
break;
default:
resultExitCode = exitCode;
}
}
return resultExitCode;
}
int intintLCGQuadraticOpenCompactOpenMPHash_InnerInsertSingleNoOverwrite(char
*tableData,
int
key,
int
value)
{
intintLCGQuadraticOpenCompactOpenMPHash_Bucket *buckets =
(intintLCGQuadraticOpenCompactOpenMPHash_Bucket *) &
tableData[sizeof
(intintLCGQuadraticOpenCompactOpenMPHash_TableData)];
int index;
int exitCode;
intintLCGQuadraticOpenCompactOpenMPHash_TableData *mytableData =
(intintLCGQuadraticOpenCompactOpenMPHash_TableData *) tableData;
intintHash_CompressLCGData compressFuncData =
mytableData->compressFuncData;
unsigned int c = intintHash_CompressLCG(compressFuncData, key);
unsigned long int iteration = 0;
for (;;) {
index =
((1 * iteration * iteration + 0 * iteration +
c) %
((intintLCGQuadraticOpenCompactOpenMPHash_TableData *)
tableData)->numBuckets);
int old_key =
__sync_val_compare_and_swap(&buckets[index].key, -1, key);
if (old_key == HASH_BUCKET_STATUS_EMPTY) {
exitCode = HASH_SEARCH_CODE_EMPTY;
break;
} else if (old_key == key) {
exitCode = HASH_SEARCH_CODE_MATCH;
break;
} else
if ((iteration >
((intintLCGQuadraticOpenCompactOpenMPHash_TableData *)
tableData)->numBuckets)) {
exitCode = HASH_EXIT_CODE_CYCLE;
break;
}
iteration++;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
return HASH_EXIT_CODE_OVERWRITE;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = value;
return HASH_EXIT_CODE_NORMAL;
default:
return exitCode;
}
}
int intintLCGQuadraticOpenCompactOpenMPHash_InnerInsertNoOverwrite(char
*tableData,
unsigned int
numEntries,
int *keys,
int *values)
{
intintLCGQuadraticOpenCompactOpenMPHash_Bucket *buckets =
(intintLCGQuadraticOpenCompactOpenMPHash_Bucket *) &
tableData[sizeof
(intintLCGQuadraticOpenCompactOpenMPHash_TableData)];
int resultExitCode = HASH_EXIT_CODE_NORMAL;
int key;
int index;
int exitCode;
uint i;
#pragma omp parallel for
for (i = 0; i < numEntries; i++) {
key = keys[i];
intintLCGQuadraticOpenCompactOpenMPHash_TableData *mytableData =
(intintLCGQuadraticOpenCompactOpenMPHash_TableData *)
tableData;
intintHash_CompressLCGData compressFuncData =
mytableData->compressFuncData;
unsigned int c = intintHash_CompressLCG(compressFuncData, key);
unsigned long int iteration = 0;
for (;;) {
index =
((1 * iteration * iteration + 0 * iteration +
c) %
((intintLCGQuadraticOpenCompactOpenMPHash_TableData
*) tableData)->numBuckets);
int old_key =
__sync_val_compare_and_swap(&buckets[index].key, -1,
key);
if (old_key == HASH_BUCKET_STATUS_EMPTY) {
exitCode = HASH_SEARCH_CODE_EMPTY;
break;
} else if (old_key == key) {
exitCode = HASH_SEARCH_CODE_MATCH;
break;
} else
if ((iteration >
((intintLCGQuadraticOpenCompactOpenMPHash_TableData *) tableData)->numBuckets)) {
exitCode = HASH_EXIT_CODE_CYCLE;
break;
}
iteration++;
}
switch (exitCode) {
case HASH_SEARCH_CODE_MATCH:
case HASH_SEARCH_CODE_MISMATCH:
resultExitCode = HASH_EXIT_CODE_OVERWRITE;
break;
case HASH_SEARCH_CODE_EMPTY:
buckets[index].value = values[i];
break;
default:
resultExitCode = exitCode;
}
}
return resultExitCode;
}
int intintLCGQuadraticOpenCompactOpenMPHash_QuerySingle(intintHash_Table *
table, int key,
int *valueOutput) {
return intintLCGQuadraticOpenCompactOpenMPHash_InnerQuerySingle(table->
tableData,
key,
valueOutput);
}
int intintLCGQuadraticOpenCompactOpenMPHash_Query(intintHash_Table * table,
size_t numKeys, int *keys,
int *valuesOutput) {
return intintLCGQuadraticOpenCompactOpenMPHash_InnerQuery(table->
tableData,
numKeys, keys,
valuesOutput);
}
int intintLCGQuadraticOpenCompactOpenMPHash_InsertSingle(intintHash_Table *
table, int key,
int value) {
return intintLCGQuadraticOpenCompactOpenMPHash_InnerInsertSingle(table->
tableData,
key,
value);
}
int intintLCGQuadraticOpenCompactOpenMPHash_Insert(intintHash_Table * table,
size_t numEntries, int *keys,
int *values) {
return intintLCGQuadraticOpenCompactOpenMPHash_InnerInsert(table->
tableData,
numEntries,
keys,
values);
}
int
intintLCGQuadraticOpenCompactOpenMPHash_InsertSingleNoOverwrite(intintHash_Table
* table,
int key,
int value) {
return
intintLCGQuadraticOpenCompactOpenMPHash_InnerInsertSingleNoOverwrite
(table->tableData, key, value);
}
int intintLCGQuadraticOpenCompactOpenMPHash_InsertNoOverwrite(intintHash_Table *
table,
size_t numEntries,
int *keys,
int *values) {
return
intintLCGQuadraticOpenCompactOpenMPHash_InnerInsertNoOverwrite
(table->tableData, numEntries, keys, values);
}
const char *HashFactory_source =
"\n"
"/* Copyright (C) 1991-2012 Free Software Foundation, Inc.\n"
" This file is part of the GNU C Library.\n"
"\n"
" The GNU C Library is free software; you can redistribute it and/or\n"
" modify it under the terms of the GNU Lesser General Public\n"
" License as published by the Free Software Foundation; either\n"
" version 2.1 of the License, or (at your option) any later version.\n"
"\n"
" The GNU C Library is distributed in the hope that it will be useful,\n"
" but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
" Lesser General Public License for more details.\n"
"\n"
" You should have received a copy of the GNU Lesser General Public\n"
" License along with the GNU C Library; if not, see\n"
" <http://www.gnu.org/licenses/>. */\n"
"/* This header is separate from features.h so that the compiler can\n"
" include it implicitly at the start of every compilation. It must\n"
" not itself include <features.h> or any other header that includes\n"
" <features.h> because the implicit include comes before any feature\n"
" test macros that may be defined in a source file before it first\n"
" explicitly includes a system header. GCC knows the name of this\n"
" header in order to preinclude it. */\n"
"/* We do support the IEC 559 math functionality, real and complex. */\n"
"/* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) /\n"
" Unicode 6.0. */\n"
"/* We do not support C11 <threads.h>. */\n"
"/* Copyright 2013-14. Los Alamos National Security, LLC. This material was produced\n"
" * under U.S. Government contract DE-AC52-06NA25396 for Los Alamos National \n"
" * Laboratory (LANL), which is operated by Los Alamos National Security, LLC\n"
" * for the U.S. Department of Energy. The U.S. Government has rights to use,\n"
" * reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR LOS\n"
" * ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR\n"
" * ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified\n"
" * to produce derivative works, such modified software should be clearly marked,\n"
" * so as not to confuse it with the version available from LANL. \n"
" *\n"
" * Licensed under the Apache License, Version 2.0 (the ""License""); you may not\n"
" * use this file except in compliance with the License. You may obtain a copy\n"
" * of the License at \n"
" *\n"
" * http://www.apache.org/licenses/LICENSE-2.0\n"
" *\n"
" * Unless required by applicable law or agreed to in writing, software distributed\n"
" * under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR\n"
" * CONDITIONS OF ANY KIND, either express or implied. See the License for the\n"
" * specific language governing permissions and limitations under the License.\n"
" *\n"
" * Under this license, it is required to include a reference to this work. We\n"
" * request that each derivative work contain a reference to LANL Copyright \n"
" * Disclosure C14043/LA-CC-14-003 so that this work's impact can be roughly\n"
" * measured. In addition, it is requested that a modifier is included as in\n"
" * the following example:\n"
" *\n"
" * //<Uses | improves on | modified from> LANL Copyright Disclosure C14043/LA-CC-14-003\n"
" *\n"
" * This is LANL Copyright Disclosure C14043/LA-CC-14-003\n"
" */\n"
"int intintIdentityPerfectCLHash_InsertSingle(__global char *tableData,\n"
" int key, int value);\n"
"int intintIdentityPerfectCLHash_InnerInsertSingle(__global char *tableData,\n"
" int key, int value);\n"
"int intintHash_InsertSingle(__global char *tableData, int key, int value);\n"
"int intintIdentityPerfectCLHash_InnerQuery(__global char *tableData,\n"
" unsigned int numKeys,\n"
" __global int *keys,\n"
" __global int *valuesOutput);\n"
"int intintIdentityPerfectCLHash_InnerQuerySingle(__global char *tableData,\n"
" int key,\n"
" __global int *valueOutput);\n"
"int intintIdentityPerfectCLHash_InnerInsert(__global char *tableData,\n"
" unsigned int numEntries,\n"
" __global int *keys,\n"
" __global int *values);\n"
"int intintIdentityPerfectCLHash_InnerInsertSingleNoOverwrite(__global char\n"
" *tableData,\n"
" int key,\n"
" int value);\n"
"int intintIdentityPerfectCLHash_InnerInsertNoOverwrite(__global char *tableData,\n"
" unsigned int numEntries,\n"
" __global int *keys,\n"
" __global int *values);\n"
"int intintIdentityPerfectCLHash_QuerySingle(__global char *tableData, int key,\n"
" __global int *valueOutput);\n"
"int intintIdentityPerfectCLHash_QuerySingle(__global char *tableData, int key,\n"
" __global int *valueOutput);\n"
"int intintIdentityPerfectCLHash_Query(__global char *tableData, size_t numKeys,\n"
" __global int *keys,\n"
" __global int *valuesOutput);\n"
"int intintIdentityPerfectCLHash_Insert(__global char *tableData,\n"
" size_t numEntries, __global int *keys,\n"
" __global int *values);\n"
"int intintIdentityPerfectCLHash_InsertSingleNoOverwrite(__global char\n"
" *tableData, int key,\n"
" int value);\n"
"int intintIdentityPerfectCLHash_InsertNoOverwrite(__global char *tableData,\n"
" size_t numEntries,\n"
" __global int *keys,\n"
" __global int *values);\n"
"int intintIdentitySentinelPerfectCLHash_InnerInsertNoOverwrite(__global char\n"
" *tableData,\n"
" unsigned int\n"
" numEntries,\n"
" __global int\n"
" *keys,\n"
" __global int\n"
" *values);\n"
"int intintIdentitySentinelPerfectCLHash_InnerQuerySingle(__global char\n"
" *tableData, int key,\n"
" __global int\n"
" *valueOutput);\n"
"int intintIdentitySentinelPerfectCLHash_InnerQuery(__global char *tableData,\n"
" unsigned int numKeys,\n"
" __global int *keys,\n"
" __global int *valuesOutput);\n"
"int intintIdentitySentinelPerfectCLHash_InnerInsertSingle(__global char\n"
" *tableData, int key,\n"
" int value);\n"
"int intintIdentitySentinelPerfectCLHash_InnerInsert(__global char *tableData,\n"
" unsigned int numEntries,\n"
" __global int *keys,\n"
" __global int *values);\n"
"int intintIdentitySentinelPerfectCLHash_InnerInsertSingleNoOverwrite(__global\n"
" char\n"
" *tableData,\n"
" int key,\n"
" int value);\n"
"int intintIdentitySentinelPerfectCLHash_QuerySingle(__global char *tableData,\n"
" int key,\n"
" __global int *valueOutput);\n"
"int intintIdentitySentinelPerfectCLHash_Query(__global char *tableData,\n"
" size_t numKeys,\n"
" __global int *keys,\n"
" __global int *valuesOutput);\n"
"int intintIdentitySentinelPerfectCLHash_InsertSingle(__global char *tableData,\n"
" int key, int value);\n"
"int intintIdentitySentinelPerfectCLHash_Insert(__global char *tableData,\n"
" size_t numEntries,\n"
" __global int *keys,\n"
" __global int *values);\n"
"int intintIdentitySentinelPerfectCLHash_InsertSingleNoOverwrite(__global char\n"
" *tableData,\n"
" int key,\n"
" int value);\n"
"int intintIdentitySentinelPerfectCLHash_InsertNoOverwrite(__global char\n"
" *tableData,\n"
" size_t numEntries,\n"
" __global int *keys,\n"
" __global int *values);\n"
"int intintLCGLinearOpenCompactCLHash_InnerQuerySingle(__global char *tableData,\n"
" int key,\n"
" __global int\n"
" *valueOutput);\n"
"int intintLCGLinearOpenCompactCLHash_QuerySingle(__global char *tableData,\n"
" int key,\n"
" __global int *valueOutput);\n"
"int intintLCGLinearOpenCompactCLHash_Query(__global char *tableData,\n"
" size_t numKeys, __global int *keys,\n"
" __global int *valuesOutput);\n"
"int intintLCGLinearOpenCompactCLHash_InsertSingle(__global char *tableData,\n"
" int key, int value);\n"
"int intintLCGLinearOpenCompactCLHash_Insert(__global char *tableData,\n"
" size_t numEntries,\n"
" __global int *keys,\n"
" __global int *values);\n"
"int intintLCGLinearOpenCompactCLHash_InsertSingleNoOverwrite(__global char\n"
" *tableData,\n"
" int key,\n"
" int value);\n"
"int intintLCGLinearOpenCompactCLHash_InsertNoOverwrite(__global char *tableData,\n"
" size_t numEntries,\n"
" __global int *keys,\n"
" __global int *values);\n"
"int intintLCGLinearOpenCompactCLHash_InnerQuery(__global char *tableData,\n"
" unsigned int numKeys,\n"
" __global int *keys,\n"
" __global int *valuesOutput);\n"
"int intintLCGLinearOpenCompactCLHash_InnerInsertNoOverwrite(__global char\n"
" *tableData,\n"
" unsigned int\n"
" numEntries,\n"
" __global int *keys,\n"
" __global int\n"
" *values);\n"
"int intintLCGLinearOpenCompactCLHash_InnerInsertSingle(__global char *tableData,\n"
" int key, int value);\n"
"int intintLCGLinearOpenCompactCLHash_InnerInsertSingleNoOverwrite(__global char\n"
" *tableData,\n"
" int key,\n"
" int value);\n"
"int intintLCGLinearOpenCompactCLHash_InnerInsert(__global char *tableData,\n"
" unsigned int numEntries,\n"
" __global int *keys,\n"
" __global int *values);\n"
"int intintLCGQuadraticOpenCompactCLHash_InnerQuerySingle(__global char\n"
" *tableData, int key,\n"
" __global int\n"
" *valueOutput);\n"
"int intintLCGQuadraticOpenCompactCLHash_InnerQuery(__global char *tableData,\n"
" unsigned int numKeys,\n"
" __global int *keys,\n"
" __global int *valuesOutput);\n"
"int intintLCGQuadraticOpenCompactCLHash_InnerInsertSingle(__global char\n"
" *tableData, int key,\n"
" int value);\n"
"int intintLCGQuadraticOpenCompactCLHash_InnerInsert(__global char *tableData,\n"
" unsigned int numEntries,\n"
" __global int *keys,\n"
" __global int *values);\n"
"int intintLCGQuadraticOpenCompactCLHash_InnerInsertSingleNoOverwrite(__global\n"
" char\n"
" *tableData,\n"
" int key,\n"
" int value);\n"
"int intintLCGQuadraticOpenCompactCLHash_InnerInsertNoOverwrite(__global char\n"
" *tableData,\n"
" unsigned int\n"
" numEntries,\n"
" __global int\n"
" *keys,\n"
" __global int\n"
" *values);\n"
"int intintLCGQuadraticOpenCompactCLHash_QuerySingle(__global char *tableData,\n"
" int key,\n"
" __global int *valueOutput);\n"
"int intintLCGQuadraticOpenCompactCLHash_Query(__global char *tableData,\n"
" size_t numKeys,\n"
" __global int *keys,\n"
" __global int *valuesOutput);\n"
"int intintLCGQuadraticOpenCompactCLHash_InsertSingle(__global char *tableData,\n"
" int key, int value);\n"
"int intintLCGQuadraticOpenCompactCLHash_Insert(__global char *tableData,\n"
" size_t numEntries,\n"
" __global int *keys,\n"
" __global int *values);\n"
"int intintLCGQuadraticOpenCompactCLHash_InsertSingleNoOverwrite(__global char\n"
" *tableData,\n"
" int key,\n"
" int value);\n"
"int intintLCGQuadraticOpenCompactCLHash_InsertNoOverwrite(__global char\n"
" *tableData,\n"
" size_t numEntries,\n"
" __global int *keys,\n"
" __global int *values);\n"
"int intintHash_Query(__global char *tableData, unsigned int numKeys,\n"
" __global int *keys, __global int *valuesOutput);\n"
"int intintHash_QuerySingle(__global char *tableData, int key,\n"
" __global int *valueOutput);\n"
"int intintHash_Insert(__global char *tableData, unsigned int numEntries,\n"
" __global int *keys, __global int *values);\n"
"int intintHash_InsertNoOverwrite(__global char *tableData,\n"
" unsigned int numEntries, __global int *keys,\n"
" __global int *values);\n"
"int intintHash_InsertSingleNoOverwrite(__global char *tableData, int key,\n"
" int value);\n"
"#define HASH_REPORT_NEVER /**/ 0\n"
"#define HASH_REPORT_CYCLE /**/ 1\n"
"#define HASH_REPORT_END /****/ 2\n"
"//\n"
"#define HASH_EXIT_CODE_NORMAL /****************/ -1\n"
"#define HASH_EXIT_CODE_ERROR /*****************/ -2\n"
"#define HASH_EXIT_CODE_OVERWRITE /*************/ -3\n"
"#define HASH_EXIT_CODE_KEY_DNE /***************/ -4\n"
"#define HASH_EXIT_CODE_CYCLE /*****************/ -5\n"
"#define HASH_EXIT_CODE_MAX_ENTRIES_EXCEEDED /**/ -6\n"
"#define HASH_EXIT_CODE_BUCKET_INDEX_OOB /******/ -7\n"
"//\n"
"#define HASH_SEARCH_CODE_MATCH /*****/ 0\n"
"#define HASH_SEARCH_CODE_MISMATCH /**/ 1\n"
"#define HASH_SEARCH_CODE_EMPTY /*****/ 2\n"
"//\n"
"#define IDENTITY_PERFECT_CL_HASH_ID /****************/ 16\n"
"#define IDENTITY_SENTINEL_PERFECT_CL_HASH_ID /*******/ 32\n"
"#define LCG_LINEAR_OPEN_COMPACT_CL_HASH_ID /*********/ 64\n"
"#define LCG_QUADRATIC_OPEN_COMPACT_CL_HASH_ID /******/ 128\n"
"//\n"
"#define HASH_BUCKET_STATUS_EMPTY /**/ -1\n"
"#define HASH_BUCKET_STATUS_FULL /***/ -2\n"
"#define HASH_BUCKET_STATUS_LOCK /***/ -3\n"
"static inline unsigned int intintHash_CompressIdentity(char data, int hashCode) {\n"
" return hashCode;\n"
"}\n"
"\n"
"typedef struct intintHash_CompressLCGData {\n"
" long unsigned int a;\n"
" long unsigned int c;\n"
" unsigned int m;\n"
" unsigned int n;\n"
"} intintHash_CompressLCGData;\n"
"static inline unsigned int intintHash_CompressLCG(intintHash_CompressLCGData\n"
" compressLCGData,\n"
" int hashCode) {\n"
" return ((compressLCGData.a * hashCode +\n"
" compressLCGData.c) % compressLCGData.m) % compressLCGData.n;\n"
"}\n"
"\n"
"typedef struct intintIdentityPerfectCLHash_TableData {\n"
" int hashID;\n"
" unsigned int numBuckets;\n"
" char compressFuncData;\n"
"} intintIdentityPerfectCLHash_TableData;\n"
"typedef struct intintIdentityPerfectCLHash_Bucket {\n"
" int key;\n"
" int value;\n"
"} intintIdentityPerfectCLHash_Bucket;\n"
"int intintIdentityPerfectCLHash_InnerQuerySingle(__global char *tableData,\n"
" int key,\n"
" __global int *valueOutput) {\n"
" __global intintIdentityPerfectCLHash_Bucket *buckets =\n"
" (__global intintIdentityPerfectCLHash_Bucket *) &\n"
" tableData[sizeof(intintIdentityPerfectCLHash_TableData)];\n"
" int index;\n"
" int exitCode;\n"
" index =\n"
" intintHash_CompressIdentity(((__global\n"
" intintIdentityPerfectCLHash_TableData\n"
" *) tableData)->compressFuncData, key);\n"
" if ((buckets[index].key) != HASH_BUCKET_STATUS_EMPTY) {\n"
" if (key == buckets[index].key) {\n"
" exitCode = HASH_SEARCH_CODE_MATCH;\n"
" } else {\n"
" exitCode = HASH_SEARCH_CODE_MISMATCH;\n"
" }\n"
" } else {\n"
" exitCode = HASH_SEARCH_CODE_EMPTY;\n"
" }\n"
" switch (exitCode) {\n"
" case HASH_SEARCH_CODE_MATCH:\n"
" *valueOutput = buckets[index].value;\n"
" return HASH_EXIT_CODE_NORMAL;\n"
" case HASH_SEARCH_CODE_MISMATCH:\n"
" case HASH_SEARCH_CODE_EMPTY:\n"
" return HASH_EXIT_CODE_KEY_DNE;\n"
" default:\n"
" return exitCode;\n"
" }\n"
"}\n"
"int intintIdentityPerfectCLHash_InnerQuery(__global char *tableData,\n"
" unsigned int numKeys,\n"
" __global int *keys,\n"
" __global int *valuesOutput) {\n"
" __global intintIdentityPerfectCLHash_Bucket *buckets =\n"
" (__global intintIdentityPerfectCLHash_Bucket *) &\n"
" tableData[sizeof(intintIdentityPerfectCLHash_TableData)];\n"
" int key;\n"
" __global int *valueOutput;\n"
" int index;\n"
" int exitCode;\n"
" uint i;\n"
" int resultExitCode = HASH_EXIT_CODE_NORMAL;\n"
" for (i = 0; i < numKeys; i++) {\n"
" key = keys[i];\n"
" valueOutput = &valuesOutput[i];\n"
" index =\n"
" intintHash_CompressIdentity(((__global\n"
" intintIdentityPerfectCLHash_TableData\n"
" *) tableData)->\n"
" compressFuncData, key);\n"
" if ((buckets[index].key) != HASH_BUCKET_STATUS_EMPTY) {\n"
" if (key == buckets[index].key) {\n"
" exitCode = HASH_SEARCH_CODE_MATCH;\n"
" } else {\n"
" exitCode = HASH_SEARCH_CODE_MISMATCH;\n"
" }\n"
" } else {\n"
" exitCode = HASH_SEARCH_CODE_EMPTY;\n"
" }\n"
" switch (exitCode) {\n"
" case HASH_SEARCH_CODE_MATCH:\n"
" *valueOutput = buckets[index].value;\n"
" break;\n"
" case HASH_SEARCH_CODE_MISMATCH:\n"
" case HASH_SEARCH_CODE_EMPTY:\n"
" resultExitCode = HASH_EXIT_CODE_KEY_DNE;\n"
" break;\n"
" default:\n"
" return exitCode;\n"
" }\n"
" }\n"
" return resultExitCode;\n"
"}\n"
"int intintIdentityPerfectCLHash_InnerInsertSingle(__global char *tableData,\n"
" int key, int value) {\n"
" __global intintIdentityPerfectCLHash_Bucket *buckets =\n"
" (__global intintIdentityPerfectCLHash_Bucket *) &\n"
" tableData[sizeof(intintIdentityPerfectCLHash_TableData)];\n"
" int index;\n"
" int exitCode;\n"
" index =\n"
" intintHash_CompressIdentity(((__global\n"
" intintIdentityPerfectCLHash_TableData\n"
" *) tableData)->compressFuncData, key);\n"
" if (((buckets[index].key ==\n"
" HASH_BUCKET_STATUS_EMPTY) ? (buckets[index].key =\n"
" key,\n"
" HASH_BUCKET_STATUS_EMPTY) :\n"
" buckets[index].key) != HASH_BUCKET_STATUS_EMPTY) {\n"
" if (key == buckets[index].key) {\n"
" exitCode = HASH_SEARCH_CODE_MATCH;\n"
" } else {\n"
" exitCode = HASH_SEARCH_CODE_MISMATCH;\n"
" }\n"
" } else {\n"
" exitCode = HASH_SEARCH_CODE_EMPTY;\n"
" }\n"
" switch (exitCode) {\n"
" case HASH_SEARCH_CODE_MATCH:\n"
" case HASH_SEARCH_CODE_MISMATCH:\n"
" buckets[index].value = value;\n"
" return HASH_EXIT_CODE_OVERWRITE;\n"
" case HASH_SEARCH_CODE_EMPTY:\n"
" buckets[index].value = value;\n"
" return HASH_EXIT_CODE_NORMAL;\n"
" default:\n"
" return exitCode;\n"
" }\n"
"}\n"
"int intintIdentityPerfectCLHash_InnerInsert(__global char *tableData,\n"
" unsigned int numEntries,\n"
" __global int *keys,\n"
" __global int *values) {\n"
" __global intintIdentityPerfectCLHash_Bucket *buckets =\n"
" (__global intintIdentityPerfectCLHash_Bucket *) &\n"
" tableData[sizeof(intintIdentityPerfectCLHash_TableData)];\n"
" int resultExitCode = HASH_EXIT_CODE_NORMAL;\n"
" int key;\n"
" int index;\n"
" int exitCode;\n"
" uint i;;\n"
" for (i = 0; i < numEntries; i++) {\n"
" key = keys[i];\n"
" index =\n"
" intintHash_CompressIdentity(((__global\n"
" intintIdentityPerfectCLHash_TableData\n"
" *) tableData)->\n"
" compressFuncData, key);\n"
" if (((buckets[index].key ==\n"
" HASH_BUCKET_STATUS_EMPTY) ? (buckets[index].key =\n"
" key,\n"
" HASH_BUCKET_STATUS_EMPTY) :\n"
" buckets[index].key) != HASH_BUCKET_STATUS_EMPTY) {\n"
" if (key == buckets[index].key) {\n"
" exitCode = HASH_SEARCH_CODE_MATCH;\n"
" } else {\n"
" exitCode = HASH_SEARCH_CODE_MISMATCH;\n"
" }\n"
" } else {\n"
" exitCode = HASH_SEARCH_CODE_EMPTY;\n"
" }\n"
" switch (exitCode) {\n"
" case HASH_SEARCH_CODE_MATCH:\n"
" case HASH_SEARCH_CODE_MISMATCH:\n"
" resultExitCode = HASH_EXIT_CODE_OVERWRITE;\n"
" case HASH_SEARCH_CODE_EMPTY:\n"
" buckets[index].value = values[i];\n"
" break;\n"
" default:\n"
" resultExitCode = exitCode;\n"
" }\n"
" }\n"
" return resultExitCode;\n"
"}\n"
"int intintIdentityPerfectCLHash_InnerInsertSingleNoOverwrite(__global char\n"
" *tableData,\n"
" int key,\n"
" int value) {\n"
" __global intintIdentityPerfectCLHash_Bucket *buckets =\n"
" (__global intintIdentityPerfectCLHash_Bucket *) &\n"
" tableData[sizeof(intintIdentityPerfectCLHash_TableData)];\n"
" int index;\n"
" int exitCode;\n"
" index =\n"
" intintHash_CompressIdentity(((__global\n"
" intintIdentityPerfectCLHash_TableData\n"
" *) tableData)->compressFuncData, key);\n"
" if (((buckets[index].key ==\n"
" HASH_BUCKET_STATUS_EMPTY) ? (buckets[index].key =\n"
" key,\n"
" HASH_BUCKET_STATUS_EMPTY) :\n"
" buckets[index].key) != HASH_BUCKET_STATUS_EMPTY) {\n"
" if (key == buckets[index].key) {\n"
" exitCode = HASH_SEARCH_CODE_MATCH;\n"
" } else {\n"
" exitCode = HASH_SEARCH_CODE_MISMATCH;\n"
" }\n"
" } else {\n"
" exitCode = HASH_SEARCH_CODE_EMPTY;\n"
" }\n"
" switch (exitCode) {\n"
" case HASH_SEARCH_CODE_MATCH:\n"
" case HASH_SEARCH_CODE_MISMATCH:\n"
" return HASH_EXIT_CODE_OVERWRITE;\n"
" case HASH_SEARCH_CODE_EMPTY:\n"
" buckets[index].value = value;\n"
" return HASH_EXIT_CODE_NORMAL;\n"
" default:\n"
" return exitCode;\n"
" }\n"
"}\n"
"int intintIdentityPerfectCLHash_InnerInsertNoOverwrite(__global char *tableData,\n"
" unsigned int numEntries,\n"
" __global int *keys,\n"
" __global int *values) {\n"
" __global intintIdentityPerfectCLHash_Bucket *buckets =\n"
" (__global intintIdentityPerfectCLHash_Bucket *) &\n"
" tableData[sizeof(intintIdentityPerfectCLHash_TableData)];\n"
" int resultExitCode = HASH_EXIT_CODE_NORMAL;\n"
" int key;\n"
" int index;\n"
" int exitCode;\n"
" uint i;;\n"
" for (i = 0; i < numEntries; i++) {\n"
" key = keys[i];\n"
" index =\n"
" intintHash_CompressIdentity(((__global\n"
" intintIdentityPerfectCLHash_TableData\n"
" *) tableData)->\n"
" compressFuncData, key);\n"
" if (((buckets[index].key ==\n"
" HASH_BUCKET_STATUS_EMPTY) ? (buckets[index].key =\n"
" key,\n"
" HASH_BUCKET_STATUS_EMPTY) :\n"
" buckets[index].key) != HASH_BUCKET_STATUS_EMPTY) {\n"
" if (key == buckets[index].key) {\n"
" exitCode = HASH_SEARCH_CODE_MATCH;\n"
" } else {\n"
" exitCode = HASH_SEARCH_CODE_MISMATCH;\n"
" }\n"
" } else {\n"
" exitCode = HASH_SEARCH_CODE_EMPTY;\n"
" }\n"
" switch (exitCode) {\n"
" case HASH_SEARCH_CODE_MATCH:\n"
" case HASH_SEARCH_CODE_MISMATCH:\n"
" resultExitCode = HASH_EXIT_CODE_OVERWRITE;\n"
" break;\n"
" case HASH_SEARCH_CODE_EMPTY:\n"
" buckets[index].value = values[i];\n"
" break;\n"
" default:\n"
" resultExitCode = exitCode;\n"
" }\n"
" }\n"
" return resultExitCode;\n"
"}\n"
"int intintIdentityPerfectCLHash_QuerySingle(__global char *tableData, int key,\n"
" __global int *valueOutput) {\n"
" return intintIdentityPerfectCLHash_InnerQuerySingle(tableData, key,\n"
" valueOutput);\n"
"}\n"
"int intintIdentityPerfectCLHash_Query(__global char *tableData, size_t numKeys,\n"
" __global int *keys,\n"
" __global int *valuesOutput) {\n"
" return intintIdentityPerfectCLHash_InnerQuery(tableData, numKeys, keys,\n"
" valuesOutput);\n"
"}\n"
"int intintIdentityPerfectCLHash_InsertSingle(__global char *tableData, int key,\n"
" int value) {\n"
" return intintIdentityPerfectCLHash_InnerInsertSingle(tableData, key,\n"
" value);\n"
"}\n"
"int intintIdentityPerfectCLHash_Insert(__global char *tableData,\n"
" size_t numEntries, __global int *keys,\n"
" __global int *values) {\n"
" return intintIdentityPerfectCLHash_InnerInsert(tableData, numEntries,\n"
" keys, values);\n"
"}\n"
"int intintIdentityPerfectCLHash_InsertSingleNoOverwrite(__global char\n"
" *tableData, int key,\n"
" int value) {\n"
" return\n"
" intintIdentityPerfectCLHash_InnerInsertSingleNoOverwrite(tableData,\n"
" key,\n"
" value);\n"
"}\n"
"int intintIdentityPerfectCLHash_InsertNoOverwrite(__global char *tableData,\n"
" size_t numEntries,\n"
" __global int *keys,\n"
" __global int *values) {\n"
" return intintIdentityPerfectCLHash_InnerInsertNoOverwrite(tableData,\n"
" numEntries,\n"
" keys, values);\n"
"}\n"
"__kernel void intintIdentityPerfectCLHash_RangeQuerySingle(__global char\n"
" *tableData,\n"
" unsigned int\n"
" numQueries,\n"
" __global int *keys,\n"
" __global int\n"
" *valuesOutput) {\n"
" uint i = get_global_id(0);\n"
" if (i >= numQueries) {\n"
" return;\n"
" }\n"
" intintIdentityPerfectCLHash_InnerQuerySingle(tableData, keys[i],\n"
" valuesOutput + i);\n"
"}\n"
"__kernel void intintIdentityPerfectCLHash_RangeQuery(__global char *tableData,\n"
" unsigned int numQueries,\n"
" unsigned int numKeys,\n"
" __global int *keys,\n"
" __global int\n"
" *valuesOutput) {\n"
" uint i = get_global_id(0);\n"
" if (i >= numQueries) {\n"
" return;\n"
" }\n"
" intintIdentityPerfectCLHash_InnerQuery(tableData, numKeys,\n"
" keys + (i * numKeys),\n"
" valuesOutput + (i * numKeys));\n"
"}\n"
"__kernel void intintIdentityPerfectCLHash_RangeInsertSingle(__global char\n"
" *tableData,\n"
" unsigned int\n"
" numInsertions,\n"
" __global int *keys,\n"
" __global int\n"
" *values) {\n"
" uint i = get_global_id(0);\n"
" if (i >= numInsertions) {\n"
" return;\n"
" }\n"
" intintIdentityPerfectCLHash_InnerInsertSingle(tableData, keys[i],\n"
" values[i]);\n"
"}\n"
"__kernel void intintIdentityPerfectCLHash_RangeInsert(__global char *tableData,\n"
" unsigned int\n"
" numInsertions,\n"
" unsigned int numEntries,\n"
" __global int *keys,\n"
" __global int *values) {\n"
" uint i = get_global_id(0);\n"
" if (i >= numInsertions) {\n"
" return;\n"
" }\n"
" intintIdentityPerfectCLHash_InnerInsert(tableData, numEntries,\n"
" keys + (i * numEntries),\n"
" values + (i * numEntries));\n"
"}\n"
"__kernel void intintIdentityPerfectCLHash_RangeInsertSingleNoOverwrite(__global\n"
" char\n"
" *tableData,\n"
" unsigned\n"
" int\n"
" numInsertions,\n"
" __global\n"
" int\n"
" *keys,\n"
" __global\n"
" int\n"
" *values) \n"
"{\n"
" uint i = get_global_id(0);\n"
" if (i >= numInsertions) {\n"
" return;\n"
" }\n"
" intintIdentityPerfectCLHash_InnerInsertSingleNoOverwrite(tableData,\n"
" keys[i],\n"
" values[i]);\n"
"}\n"
"__kernel void intintIdentityPerfectCLHash_RangeInsertNoOverwrite(__global char\n"
" *tableData,\n"
" unsigned int\n"
" numInsertions,\n"
" unsigned int\n"
" numEntries,\n"
" __global int\n"
" *keys,\n"
" __global int\n"
" *values) {\n"
" uint i = get_global_id(0);\n"
" if (i >= numInsertions) {\n"
" return;\n"
" }\n"
" intintIdentityPerfectCLHash_InnerInsertNoOverwrite(tableData,\n"
" numEntries,\n"
" keys +\n"
" (i * numEntries),\n"
" values +\n"
" (i * numEntries));\n"
"}\n"
"\n"
"typedef struct intintIdentitySentinelPerfectCLHash_TableData {\n"
" int hashID;\n"
" unsigned int numBuckets;\n"
" char compressFuncData;\n"
" int emptyValue;\n"
"} intintIdentitySentinelPerfectCLHash_TableData;\n"
"typedef struct intintIdentitySentinelPerfectCLHash_Bucket {\n"
" int value;\n"
"} intintIdentitySentinelPerfectCLHash_Bucket;\n"
"int intintIdentitySentinelPerfectCLHash_InnerQuerySingle(__global char\n"
" *tableData, int key,\n"
" __global int\n"
" *valueOutput) {\n"
" __global intintIdentitySentinelPerfectCLHash_Bucket *buckets =\n"
" (__global intintIdentitySentinelPerfectCLHash_Bucket *) &\n"
" tableData[sizeof(intintIdentitySentinelPerfectCLHash_TableData)];\n"
" int index;\n"
" int exitCode;\n"
" index =\n"
" intintHash_CompressIdentity(((__global\n"
" intintIdentitySentinelPerfectCLHash_TableData\n"
" *) tableData)->compressFuncData, key);\n"
" if (buckets[index].value !=\n"
" ((__global intintIdentitySentinelPerfectCLHash_TableData *)\n"
" tableData)->emptyValue) {\n"
" exitCode = HASH_SEARCH_CODE_MATCH;\n"
" } else {\n"
" exitCode = HASH_SEARCH_CODE_EMPTY;\n"
" }\n"
" switch (exitCode) {\n"
" case HASH_SEARCH_CODE_MATCH:\n"
" *valueOutput = buckets[index].value;\n"
" return HASH_EXIT_CODE_NORMAL;\n"
" case HASH_SEARCH_CODE_MISMATCH:\n"
" case HASH_SEARCH_CODE_EMPTY:\n"
" return HASH_EXIT_CODE_KEY_DNE;\n"
" default:\n"
" return exitCode;\n"
" }\n"
"}\n"
"int intintIdentitySentinelPerfectCLHash_InnerQuery(__global char *tableData,\n"
" unsigned int numKeys,\n"
" __global int *keys,\n"
" __global int *valuesOutput) {\n"
" __global intintIdentitySentinelPerfectCLHash_Bucket *buckets =\n"
" (__global intintIdentitySentinelPerfectCLHash_Bucket *) &\n"
" tableData[sizeof(intintIdentitySentinelPerfectCLHash_TableData)];\n"
" int key;\n"
" __global int *valueOutput;\n"
" int index;\n"
" int exitCode;\n"
" uint i;\n"
" int resultExitCode = HASH_EXIT_CODE_NORMAL;\n"
" for (i = 0; i < numKeys; i++) {\n"
" key = keys[i];\n"
" valueOutput = &valuesOutput[i];\n"
" index =\n"
" intintHash_CompressIdentity(((__global\n"
" intintIdentitySentinelPerfectCLHash_TableData\n"
" *) tableData)->\n"
" compressFuncData, key);\n"
" if (buckets[index].value !=\n"
" ((__global intintIdentitySentinelPerfectCLHash_TableData *)\n"
" tableData)->emptyValue) {\n"
" exitCode = HASH_SEARCH_CODE_MATCH;\n"
" } else {\n"
" exitCode = HASH_SEARCH_CODE_EMPTY;\n"
" }\n"
" switch (exitCode) {\n"
" case HASH_SEARCH_CODE_MATCH:\n"
" *valueOutput = buckets[index].value;\n"
" break;\n"
" case HASH_SEARCH_CODE_MISMATCH:\n"
" case HASH_SEARCH_CODE_EMPTY:\n"
" resultExitCode = HASH_EXIT_CODE_KEY_DNE;\n"
" break;\n"
" default:\n"
" return exitCode;\n"
" }\n"
" }\n"
" return resultExitCode;\n"
"}\n"
"int intintIdentitySentinelPerfectCLHash_InnerInsertSingle(__global char\n"
" *tableData, int key,\n"
" int value) {\n"
" __global intintIdentitySentinelPerfectCLHash_Bucket *buckets =\n"
" (__global intintIdentitySentinelPerfectCLHash_Bucket *) &\n"
" tableData[sizeof(intintIdentitySentinelPerfectCLHash_TableData)];\n"
" int index;\n"
" int exitCode;\n"
" index =\n"
" intintHash_CompressIdentity(((__global\n"
" intintIdentitySentinelPerfectCLHash_TableData\n"
" *) tableData)->compressFuncData, key);\n"
" if (buckets[index].value !=\n"
" ((__global intintIdentitySentinelPerfectCLHash_TableData *)\n"
" tableData)->emptyValue) {\n"
" exitCode = HASH_SEARCH_CODE_MATCH;\n"
" } else {\n"
" exitCode = HASH_SEARCH_CODE_EMPTY;\n"
" }\n"
" switch (exitCode) {\n"
" case HASH_SEARCH_CODE_MATCH:\n"
" case HASH_SEARCH_CODE_MISMATCH:\n"
" buckets[index].value = value;\n"
" return HASH_EXIT_CODE_OVERWRITE;\n"
" case HASH_SEARCH_CODE_EMPTY:\n"
" buckets[index].value = value;\n"
" return HASH_EXIT_CODE_NORMAL;\n"
" default:\n"
" return exitCode;\n"
" }\n"
"}\n"
"int intintIdentitySentinelPerfectCLHash_InnerInsert(__global char *tableData,\n"
" unsigned int numEntries,\n"
" __global int *keys,\n"
" __global int *values) {\n"
" __global intintIdentitySentinelPerfectCLHash_Bucket *buckets =\n"
" (__global intintIdentitySentinelPerfectCLHash_Bucket *) &\n"
" tableData[sizeof(intintIdentitySentinelPerfectCLHash_TableData)];\n"
" int resultExitCode = HASH_EXIT_CODE_NORMAL;\n"
" int key;\n"
" int index;\n"
" int exitCode;\n"
" uint i;;\n"
" for (i = 0; i < numEntries; i++) {\n"
" key = keys[i];\n"
" index =\n"
" intintHash_CompressIdentity(((__global\n"
" intintIdentitySentinelPerfectCLHash_TableData\n"
" *) tableData)->\n"
" compressFuncData, key);\n"
" if (buckets[index].value !=\n"
" ((__global intintIdentitySentinelPerfectCLHash_TableData *)\n"
" tableData)->emptyValue) {\n"
" exitCode = HASH_SEARCH_CODE_MATCH;\n"
" } else {\n"
" exitCode = HASH_SEARCH_CODE_EMPTY;\n"
" }\n"
" switch (exitCode) {\n"
" case HASH_SEARCH_CODE_MATCH:\n"
" case HASH_SEARCH_CODE_MISMATCH:\n"
" resultExitCode = HASH_EXIT_CODE_OVERWRITE;\n"
" case HASH_SEARCH_CODE_EMPTY:\n"
" buckets[index].value = values[i];\n"
" break;\n"
" default:\n"
" resultExitCode = exitCode;\n"
" }\n"
" }\n"
" return resultExitCode;\n"
"}\n"
"int intintIdentitySentinelPerfectCLHash_InnerInsertSingleNoOverwrite(__global\n"
" char\n"
" *tableData,\n"
" int key,\n"
" int value) \n"
"{\n"
" __global intintIdentitySentinelPerfectCLHash_Bucket *buckets =\n"
" (__global intintIdentitySentinelPerfectCLHash_Bucket *) &\n"
" tableData[sizeof(intintIdentitySentinelPerfectCLHash_TableData)];\n"
" int index;\n"
" int exitCode;\n"
" index =\n"
" intintHash_CompressIdentity(((__global\n"
" intintIdentitySentinelPerfectCLHash_TableData\n"
" *) tableData)->compressFuncData, key);\n"
" if (buckets[index].value !=\n"
" ((__global intintIdentitySentinelPerfectCLHash_TableData *)\n"
" tableData)->emptyValue) {\n"
" exitCode = HASH_SEARCH_CODE_MATCH;\n"
" } else {\n"
" exitCode = HASH_SEARCH_CODE_EMPTY;\n"
" }\n"
" switch (exitCode) {\n"
" case HASH_SEARCH_CODE_MATCH:\n"
" case HASH_SEARCH_CODE_MISMATCH:\n"
" return HASH_EXIT_CODE_OVERWRITE;\n"
" case HASH_SEARCH_CODE_EMPTY:\n"
" buckets[index].value = value;\n"
" return HASH_EXIT_CODE_NORMAL;\n"
" default:\n"
" return exitCode;\n"
" }\n"
"}\n"
"int intintIdentitySentinelPerfectCLHash_InnerInsertNoOverwrite(__global char\n"
" *tableData,\n"
" unsigned int\n"
" numEntries,\n"
" __global int\n"
" *keys,\n"
" __global int\n"
" *values) {\n"
" __global intintIdentitySentinelPerfectCLHash_Bucket *buckets =\n"
" (__global intintIdentitySentinelPerfectCLHash_Bucket *) &\n"
" tableData[sizeof(intintIdentitySentinelPerfectCLHash_TableData)];\n"
" int resultExitCode = HASH_EXIT_CODE_NORMAL;\n"
" int key;\n"
" int index;\n"
" int exitCode;\n"
" uint i;;\n"
" for (i = 0; i < numEntries; i++) {\n"
" key = keys[i];\n"
" index =\n"
" intintHash_CompressIdentity(((__global\n"
" intintIdentitySentinelPerfectCLHash_TableData\n"
" *) tableData)->\n"
" compressFuncData, key);\n"
" if (buckets[index].value !=\n"
" ((__global intintIdentitySentinelPerfectCLHash_TableData *)\n"
" tableData)->emptyValue) {\n"
" exitCode = HASH_SEARCH_CODE_MATCH;\n"
" } else {\n"
" exitCode = HASH_SEARCH_CODE_EMPTY;\n"
" }\n"
" switch (exitCode) {\n"
" case HASH_SEARCH_CODE_MATCH:\n"
" case HASH_SEARCH_CODE_MISMATCH:\n"
" resultExitCode = HASH_EXIT_CODE_OVERWRITE;\n"
" break;\n"
" case HASH_SEARCH_CODE_EMPTY:\n"
" buckets[index].value = values[i];\n"
" break;\n"
" default:\n"
" resultExitCode = exitCode;\n"
" }\n"
" }\n"
" return resultExitCode;\n"
"}\n"
"int intintIdentitySentinelPerfectCLHash_QuerySingle(__global char *tableData,\n"
" int key,\n"
" __global int *valueOutput) {\n"
" return intintIdentitySentinelPerfectCLHash_InnerQuerySingle(tableData,\n"
" key,\n"
" valueOutput);\n"
"}\n"
"int intintIdentitySentinelPerfectCLHash_Query(__global char *tableData,\n"
" size_t numKeys,\n"
" __global int *keys,\n"
" __global int *valuesOutput) {\n"
" return intintIdentitySentinelPerfectCLHash_InnerQuery(tableData,\n"
" numKeys, keys,\n"
" valuesOutput);\n"
"}\n"
"int intintIdentitySentinelPerfectCLHash_InsertSingle(__global char *tableData,\n"
" int key, int value) {\n"
" return intintIdentitySentinelPerfectCLHash_InnerInsertSingle(tableData,\n"
" key,\n"
" value);\n"
"}\n"
"int intintIdentitySentinelPerfectCLHash_Insert(__global char *tableData,\n"
" size_t numEntries,\n"
" __global int *keys,\n"
" __global int *values) {\n"
" return intintIdentitySentinelPerfectCLHash_InnerInsert(tableData,\n"
" numEntries, keys,\n"
" values);\n"
"}\n"
"int intintIdentitySentinelPerfectCLHash_InsertSingleNoOverwrite(__global char\n"
" *tableData,\n"
" int key,\n"
" int value) {\n"
" return\n"
" intintIdentitySentinelPerfectCLHash_InnerInsertSingleNoOverwrite\n"
" (tableData, key, value);\n"
"}\n"
"int intintIdentitySentinelPerfectCLHash_InsertNoOverwrite(__global char\n"
" *tableData,\n"
" size_t numEntries,\n"
" __global int *keys,\n"
" __global int *values) \n"
"{\n"
" return\n"
" intintIdentitySentinelPerfectCLHash_InnerInsertNoOverwrite\n"
" (tableData, numEntries, keys, values);\n"
"}\n"
"__kernel void intintIdentitySentinelPerfectCLHash_RangeQuerySingle(__global char\n"
" *tableData,\n"
" unsigned int\n"
" numQueries,\n"
" __global int\n"
" *keys,\n"
" __global int\n"
" *valuesOutput) \n"
"{\n"
" uint i = get_global_id(0);\n"
" if (i >= numQueries) {\n"
" return;\n"
" }\n"
" intintIdentitySentinelPerfectCLHash_InnerQuerySingle(tableData, keys[i],\n"
" valuesOutput + i);\n"
"}\n"
"__kernel void intintIdentitySentinelPerfectCLHash_RangeQuery(__global char\n"
" *tableData,\n"
" unsigned int\n"
" numQueries,\n"
" unsigned int\n"
" numKeys,\n"
" __global int *keys,\n"
" __global int\n"
" *valuesOutput) {\n"
" uint i = get_global_id(0);\n"
" if (i >= numQueries) {\n"
" return;\n"
" }\n"
" intintIdentitySentinelPerfectCLHash_InnerQuery(tableData, numKeys,\n"
" keys + (i * numKeys),\n"
" valuesOutput +\n"
" (i * numKeys));\n"
"}\n"
"__kernel void intintIdentitySentinelPerfectCLHash_RangeInsertSingle(__global\n"
" char\n"
" *tableData,\n"
" unsigned int\n"
" numInsertions,\n"
" __global int\n"
" *keys,\n"
" __global int\n"
" *values) {\n"
" uint i = get_global_id(0);\n"
" if (i >= numInsertions) {\n"
" return;\n"
" }\n"
" intintIdentitySentinelPerfectCLHash_InnerInsertSingle(tableData,\n"
" keys[i],\n"
" values[i]);\n"
"}\n"
"__kernel void intintIdentitySentinelPerfectCLHash_RangeInsert(__global char\n"
" *tableData,\n"
" unsigned int\n"
" numInsertions,\n"
" unsigned int\n"
" numEntries,\n"
" __global int\n"
" *keys,\n"
" __global int\n"
" *values) {\n"
" uint i = get_global_id(0);\n"
" if (i >= numInsertions) {\n"
" return;\n"
" }\n"
" intintIdentitySentinelPerfectCLHash_InnerInsert(tableData, numEntries,\n"
" keys + (i * numEntries),\n"
" values +\n"
" (i * numEntries));\n"
"}\n"
"__kernel void\n"
"intintIdentitySentinelPerfectCLHash_RangeInsertSingleNoOverwrite(__global char\n"
" *tableData,\n"
" unsigned int\n"
" numInsertions,\n"
" __global int\n"
" *keys,\n"
" __global int\n"
" *values) {\n"
" uint i = get_global_id(0);\n"
" if (i >= numInsertions) {\n"
" return;\n"
" }\n"
" intintIdentitySentinelPerfectCLHash_InnerInsertSingleNoOverwrite\n"
" (tableData, keys[i], values[i]);\n"
"}\n"
"__kernel void\n"
"intintIdentitySentinelPerfectCLHash_RangeInsertNoOverwrite(__global char\n"
" *tableData,\n"
" unsigned int\n"
" numInsertions,\n"
" unsigned int\n"
" numEntries,\n"
" __global int *keys,\n"
" __global int\n"
" *values) {\n"
" uint i = get_global_id(0);\n"
" if (i >= numInsertions) {\n"
" return;\n"
" }\n"
" intintIdentitySentinelPerfectCLHash_InnerInsertNoOverwrite(tableData,\n"
" numEntries,\n"
" keys +\n"
" (i *\n"
" numEntries),\n"
" values +\n"
" (i *\n"
" numEntries));\n"
"}\n"
"\n"
"typedef struct intintLCGLinearOpenCompactCLHash_TableData {\n"
" int hashID;\n"
" unsigned int numBuckets;\n"
" intintHash_CompressLCGData compressFuncData;\n"
"} intintLCGLinearOpenCompactCLHash_TableData;\n"
"typedef struct intintLCGLinearOpenCompactCLHash_Bucket {\n"
" int key;\n"
" int value;\n"
"} intintLCGLinearOpenCompactCLHash_Bucket;\n"
"int intintLCGLinearOpenCompactCLHash_InnerQuerySingle(__global char *tableData,\n"
" int key,\n"
" __global int\n"
" *valueOutput) {\n"
" __global intintLCGLinearOpenCompactCLHash_Bucket *buckets =\n"
" (__global intintLCGLinearOpenCompactCLHash_Bucket *) &\n"
" tableData[sizeof(intintLCGLinearOpenCompactCLHash_TableData)];\n"
" int index;\n"
" int exitCode;\n"
" __global intintLCGLinearOpenCompactCLHash_TableData *mytableData =\n"
" (__global intintLCGLinearOpenCompactCLHash_TableData *) tableData;\n"
" intintHash_CompressLCGData compressFuncData =\n"
" mytableData->compressFuncData;\n"
" unsigned int c = intintHash_CompressLCG(compressFuncData, key);\n"
" unsigned long int iteration = 0;\n"
" for (;;) {\n"
" index =\n"
" ((1 * iteration +\n"
" c) %\n"
" ((__global intintLCGLinearOpenCompactCLHash_TableData *)\n"
" tableData)->numBuckets);\n"
" if ((buckets[index].key) == HASH_BUCKET_STATUS_EMPTY) {\n"
" exitCode = HASH_SEARCH_CODE_EMPTY;\n"
" break;\n"
" } else if (key == buckets[index].key) {\n"
" exitCode = HASH_SEARCH_CODE_MATCH;\n"
" break;\n"
" } else if ((index == c && iteration > 0)) {\n"
" exitCode = HASH_EXIT_CODE_CYCLE;\n"
" break;\n"
" }\n"
" iteration++;\n"
" }\n"
" switch (exitCode) {\n"
" case HASH_SEARCH_CODE_MATCH:\n"
" *valueOutput = buckets[index].value;\n"
" return HASH_EXIT_CODE_NORMAL;\n"
" case HASH_SEARCH_CODE_MISMATCH:\n"
" case HASH_SEARCH_CODE_EMPTY:\n"
" return HASH_EXIT_CODE_KEY_DNE;\n"
" default:\n"
" return exitCode;\n"
" }\n"
"}\n"
"int intintLCGLinearOpenCompactCLHash_InnerQuery(__global char *tableData,\n"
" unsigned int numKeys,\n"
" __global int *keys,\n"
" __global int *valuesOutput) {\n"
" __global intintLCGLinearOpenCompactCLHash_Bucket *buckets =\n"
" (__global intintLCGLinearOpenCompactCLHash_Bucket *) &\n"
" tableData[sizeof(intintLCGLinearOpenCompactCLHash_TableData)];\n"
" int key;\n"
" __global int *valueOutput;\n"
" int index;\n"
" int exitCode;\n"
" uint i;\n"
" int resultExitCode = HASH_EXIT_CODE_NORMAL;\n"
" for (i = 0; i < numKeys; i++) {\n"
" key = keys[i];\n"
" valueOutput = &valuesOutput[i];\n"
" __global intintLCGLinearOpenCompactCLHash_TableData *mytableData\n"
" =\n"
" (__global intintLCGLinearOpenCompactCLHash_TableData *)\n"
" tableData;\n"
" intintHash_CompressLCGData compressFuncData =\n"
" mytableData->compressFuncData;\n"
" unsigned int c = intintHash_CompressLCG(compressFuncData, key);\n"
" unsigned long int iteration = 0;\n"
" for (;;) {\n"
" index =\n"
" ((1 * iteration +\n"
" c) %\n"
" ((__global\n"
" intintLCGLinearOpenCompactCLHash_TableData *)\n"
" tableData)->numBuckets);\n"
" if ((buckets[index].key) == HASH_BUCKET_STATUS_EMPTY) {\n"
" exitCode = HASH_SEARCH_CODE_EMPTY;\n"
" break;\n"
" } else if (key == buckets[index].key) {\n"
" exitCode = HASH_SEARCH_CODE_MATCH;\n"
" break;\n"
" } else if ((index == c && iteration > 0)) {\n"
" exitCode = HASH_EXIT_CODE_CYCLE;\n"
" break;\n"
" }\n"
" iteration++;\n"
" }\n"
" switch (exitCode) {\n"
" case HASH_SEARCH_CODE_MATCH:\n"
" *valueOutput = buckets[index].value;\n"
" break;\n"
" case HASH_SEARCH_CODE_MISMATCH:\n"
" case HASH_SEARCH_CODE_EMPTY:\n"
" resultExitCode = HASH_EXIT_CODE_KEY_DNE;\n"
" break;\n"
" default:\n"
" return exitCode;\n"
" }\n"
" }\n"
" return resultExitCode;\n"
"}\n"
"int intintLCGLinearOpenCompactCLHash_InnerInsertSingle(__global char *tableData,\n"
" int key, int value) {\n"
" __global intintLCGLinearOpenCompactCLHash_Bucket *buckets =\n"
" (__global intintLCGLinearOpenCompactCLHash_Bucket *) &\n"
" tableData[sizeof(intintLCGLinearOpenCompactCLHash_TableData)];\n"
" int index;\n"
" int exitCode;\n"
" __global intintLCGLinearOpenCompactCLHash_TableData *mytableData =\n"
" (__global intintLCGLinearOpenCompactCLHash_TableData *) tableData;\n"
" intintHash_CompressLCGData compressFuncData =\n"
" mytableData->compressFuncData;\n"
" unsigned int c = intintHash_CompressLCG(compressFuncData, key);\n"
" unsigned long int iteration = 0;\n"
" for (;;) {\n"
" index =\n"
" ((1 * iteration +\n"
" c) %\n"
" ((__global intintLCGLinearOpenCompactCLHash_TableData *)\n"
" tableData)->numBuckets);\n"
" if ((atomic_cmpxchg\n"
" (&(buckets[index].key), HASH_BUCKET_STATUS_EMPTY,\n"
" key)) == HASH_BUCKET_STATUS_EMPTY) {\n"
" exitCode = HASH_SEARCH_CODE_EMPTY;\n"
" break;\n"
" } else if (key == buckets[index].key) {\n"
" exitCode = HASH_SEARCH_CODE_MATCH;\n"
" break;\n"
" } else if ((index == c && iteration > 0)) {\n"
" exitCode = HASH_EXIT_CODE_CYCLE;\n"
" break;\n"
" }\n"
" iteration++;\n"
" }\n"
" switch (exitCode) {\n"
" case HASH_SEARCH_CODE_MATCH:\n"
" case HASH_SEARCH_CODE_MISMATCH:\n"
" buckets[index].value = value;\n"
" return HASH_EXIT_CODE_OVERWRITE;\n"
" case HASH_SEARCH_CODE_EMPTY:\n"
" buckets[index].value = value;\n"
" return HASH_EXIT_CODE_NORMAL;\n"
" default:\n"
" return exitCode;\n"
" }\n"
"}\n"
"int intintLCGLinearOpenCompactCLHash_InnerInsert(__global char *tableData,\n"
" unsigned int numEntries,\n"
" __global int *keys,\n"
" __global int *values) {\n"
" __global intintLCGLinearOpenCompactCLHash_Bucket *buckets =\n"
" (__global intintLCGLinearOpenCompactCLHash_Bucket *) &\n"
" tableData[sizeof(intintLCGLinearOpenCompactCLHash_TableData)];\n"
" int resultExitCode = HASH_EXIT_CODE_NORMAL;\n"
" int key;\n"
" int index;\n"
" int exitCode;\n"
" uint i;;\n"
" for (i = 0; i < numEntries; i++) {\n"
" key = keys[i];\n"
" __global intintLCGLinearOpenCompactCLHash_TableData *mytableData\n"
" =\n"
" (__global intintLCGLinearOpenCompactCLHash_TableData *)\n"
" tableData;\n"
" intintHash_CompressLCGData compressFuncData =\n"
" mytableData->compressFuncData;\n"
" unsigned int c = intintHash_CompressLCG(compressFuncData, key);\n"
" unsigned long int iteration = 0;\n"
" for (;;) {\n"
" index =\n"
" ((1 * iteration +\n"
" c) %\n"
" ((__global\n"
" intintLCGLinearOpenCompactCLHash_TableData *)\n"
" tableData)->numBuckets);\n"
" if ((atomic_cmpxchg\n"
" (&(buckets[index].key), HASH_BUCKET_STATUS_EMPTY,\n"
" key)) == HASH_BUCKET_STATUS_EMPTY) {\n"
" exitCode = HASH_SEARCH_CODE_EMPTY;\n"
" break;\n"
" } else if (key == buckets[index].key) {\n"
" exitCode = HASH_SEARCH_CODE_MATCH;\n"
" break;\n"
" } else if ((index == c && iteration > 0)) {\n"
" exitCode = HASH_EXIT_CODE_CYCLE;\n"
" break;\n"
" }\n"
" iteration++;\n"
" }\n"
" switch (exitCode) {\n"
" case HASH_SEARCH_CODE_MATCH:\n"
" case HASH_SEARCH_CODE_MISMATCH:\n"
" resultExitCode = HASH_EXIT_CODE_OVERWRITE;\n"
" case HASH_SEARCH_CODE_EMPTY:\n"
" buckets[index].value = values[i];\n"
" break;\n"
" default:\n"
" resultExitCode = exitCode;\n"
" }\n"
" }\n"
" return resultExitCode;\n"
"}\n"
"int intintLCGLinearOpenCompactCLHash_InnerInsertSingleNoOverwrite(__global char\n"
" *tableData,\n"
" int key,\n"
" int value) {\n"
" __global intintLCGLinearOpenCompactCLHash_Bucket *buckets =\n"
" (__global intintLCGLinearOpenCompactCLHash_Bucket *) &\n"
" tableData[sizeof(intintLCGLinearOpenCompactCLHash_TableData)];\n"
" int index;\n"
" int exitCode;\n"
" __global intintLCGLinearOpenCompactCLHash_TableData *mytableData =\n"
" (__global intintLCGLinearOpenCompactCLHash_TableData *) tableData;\n"
" intintHash_CompressLCGData compressFuncData =\n"
" mytableData->compressFuncData;\n"
" unsigned int c = intintHash_CompressLCG(compressFuncData, key);\n"
" unsigned long int iteration = 0;\n"
" for (;;) {\n"
" index =\n"
" ((1 * iteration +\n"
" c) %\n"
" ((__global intintLCGLinearOpenCompactCLHash_TableData *)\n"
" tableData)->numBuckets);\n"
" if ((atomic_cmpxchg\n"
" (&(buckets[index].key), HASH_BUCKET_STATUS_EMPTY,\n"
" key)) == HASH_BUCKET_STATUS_EMPTY) {\n"
" exitCode = HASH_SEARCH_CODE_EMPTY;\n"
" break;\n"
" } else if (key == buckets[index].key) {\n"
" exitCode = HASH_SEARCH_CODE_MATCH;\n"
" break;\n"
" } else if ((index == c && iteration > 0)) {\n"
" exitCode = HASH_EXIT_CODE_CYCLE;\n"
" break;\n"
" }\n"
" iteration++;\n"
" }\n"
" switch (exitCode) {\n"
" case HASH_SEARCH_CODE_MATCH:\n"
" case HASH_SEARCH_CODE_MISMATCH:\n"
" return HASH_EXIT_CODE_OVERWRITE;\n"
" case HASH_SEARCH_CODE_EMPTY:\n"
" buckets[index].value = value;\n"
" return HASH_EXIT_CODE_NORMAL;\n"
" default:\n"
" return exitCode;\n"
" }\n"
"}\n"
"int intintLCGLinearOpenCompactCLHash_InnerInsertNoOverwrite(__global char\n"
" *tableData,\n"
" unsigned int\n"
" numEntries,\n"
" __global int *keys,\n"
" __global int\n"
" *values) {\n"
" __global intintLCGLinearOpenCompactCLHash_Bucket *buckets =\n"
" (__global intintLCGLinearOpenCompactCLHash_Bucket *) &\n"
" tableData[sizeof(intintLCGLinearOpenCompactCLHash_TableData)];\n"
" int resultExitCode = HASH_EXIT_CODE_NORMAL;\n"
" int key;\n"
" int index;\n"
" int exitCode;\n"
" uint i;;\n"
" for (i = 0; i < numEntries; i++) {\n"
" key = keys[i];\n"
" __global intintLCGLinearOpenCompactCLHash_TableData *mytableData\n"
" =\n"
" (__global intintLCGLinearOpenCompactCLHash_TableData *)\n"
" tableData;\n"
" intintHash_CompressLCGData compressFuncData =\n"
" mytableData->compressFuncData;\n"
" unsigned int c = intintHash_CompressLCG(compressFuncData, key);\n"
" unsigned long int iteration = 0;\n"
" for (;;) {\n"
" index =\n"
" ((1 * iteration +\n"
" c) %\n"
" ((__global\n"
" intintLCGLinearOpenCompactCLHash_TableData *)\n"
" tableData)->numBuckets);\n"
" if ((atomic_cmpxchg\n"
" (&(buckets[index].key), HASH_BUCKET_STATUS_EMPTY,\n"
" key)) == HASH_BUCKET_STATUS_EMPTY) {\n"
" exitCode = HASH_SEARCH_CODE_EMPTY;\n"
" break;\n"
" } else if (key == buckets[index].key) {\n"
" exitCode = HASH_SEARCH_CODE_MATCH;\n"
" break;\n"
" } else if ((index == c && iteration > 0)) {\n"
" exitCode = HASH_EXIT_CODE_CYCLE;\n"
" break;\n"
" }\n"
" iteration++;\n"
" }\n"
" switch (exitCode) {\n"
" case HASH_SEARCH_CODE_MATCH:\n"
" case HASH_SEARCH_CODE_MISMATCH:\n"
" resultExitCode = HASH_EXIT_CODE_OVERWRITE;\n"
" break;\n"
" case HASH_SEARCH_CODE_EMPTY:\n"
" buckets[index].value = values[i];\n"
" break;\n"
" default:\n"
" resultExitCode = exitCode;\n"
" }\n"
" }\n"
" return resultExitCode;\n"
"}\n"
"int intintLCGLinearOpenCompactCLHash_QuerySingle(__global char *tableData,\n"
" int key,\n"
" __global int *valueOutput) {\n"
" return intintLCGLinearOpenCompactCLHash_InnerQuerySingle(tableData, key,\n"
" valueOutput);\n"
"}\n"
"int intintLCGLinearOpenCompactCLHash_Query(__global char *tableData,\n"
" size_t numKeys, __global int *keys,\n"
" __global int *valuesOutput) {\n"
" return intintLCGLinearOpenCompactCLHash_InnerQuery(tableData, numKeys,\n"
" keys, valuesOutput);\n"
"}\n"
"int intintLCGLinearOpenCompactCLHash_InsertSingle(__global char *tableData,\n"
" int key, int value) {\n"
" return intintLCGLinearOpenCompactCLHash_InnerInsertSingle(tableData,\n"
" key, value);\n"
"}\n"
"int intintLCGLinearOpenCompactCLHash_Insert(__global char *tableData,\n"
" size_t numEntries,\n"
" __global int *keys,\n"
" __global int *values) {\n"
" return intintLCGLinearOpenCompactCLHash_InnerInsert(tableData,\n"
" numEntries, keys,\n"
" values);\n"
"}\n"
"int intintLCGLinearOpenCompactCLHash_InsertSingleNoOverwrite(__global char\n"
" *tableData,\n"
" int key,\n"
" int value) {\n"
" return\n"
" intintLCGLinearOpenCompactCLHash_InnerInsertSingleNoOverwrite\n"
" (tableData, key, value);\n"
"}\n"
"int intintLCGLinearOpenCompactCLHash_InsertNoOverwrite(__global char *tableData,\n"
" size_t numEntries,\n"
" __global int *keys,\n"
" __global int *values) {\n"
" return\n"
" intintLCGLinearOpenCompactCLHash_InnerInsertNoOverwrite(tableData,\n"
" numEntries,\n"
" keys,\n"
" values);\n"
"}\n"
"__kernel void intintLCGLinearOpenCompactCLHash_RangeQuerySingle(__global char\n"
" *tableData,\n"
" unsigned int\n"
" numQueries,\n"
" __global int\n"
" *keys,\n"
" __global int\n"
" *valuesOutput) {\n"
" uint i = get_global_id(0);\n"
" if (i >= numQueries) {\n"
" return;\n"
" }\n"
" intintLCGLinearOpenCompactCLHash_InnerQuerySingle(tableData, keys[i],\n"
" valuesOutput + i);\n"
"}\n"
"__kernel void intintLCGLinearOpenCompactCLHash_RangeQuery(__global char\n"
" *tableData,\n"
" unsigned int\n"
" numQueries,\n"
" unsigned int numKeys,\n"
" __global int *keys,\n"
" __global int\n"
" *valuesOutput) {\n"
" uint i = get_global_id(0);\n"
" if (i >= numQueries) {\n"
" return;\n"
" }\n"
" intintLCGLinearOpenCompactCLHash_InnerQuery(tableData, numKeys,\n"
" keys + (i * numKeys),\n"
" valuesOutput +\n"
" (i * numKeys));\n"
"}\n"
"__kernel void intintLCGLinearOpenCompactCLHash_RangeInsertSingle(__global char\n"
" *tableData,\n"
" unsigned int\n"
" numInsertions,\n"
" __global int\n"
" *keys,\n"
" __global int\n"
" *values) {\n"
" uint i = get_global_id(0);\n"
" if (i >= numInsertions) {\n"
" return;\n"
" }\n"
" intintLCGLinearOpenCompactCLHash_InnerInsertSingle(tableData, keys[i],\n"
" values[i]);\n"
"}\n"
"__kernel void intintLCGLinearOpenCompactCLHash_RangeInsert(__global char\n"
" *tableData,\n"
" unsigned int\n"
" numInsertions,\n"
" unsigned int\n"
" numEntries,\n"
" __global int *keys,\n"
" __global int\n"
" *values) {\n"
" uint i = get_global_id(0);\n"
" if (i >= numInsertions) {\n"
" return;\n"
" }\n"
" intintLCGLinearOpenCompactCLHash_InnerInsert(tableData, numEntries,\n"
" keys + (i * numEntries),\n"
" values + (i * numEntries));\n"
"}\n"
"__kernel void\n"
"intintLCGLinearOpenCompactCLHash_RangeInsertSingleNoOverwrite(__global char\n"
" *tableData,\n"
" unsigned int\n"
" numInsertions,\n"
" __global int\n"
" *keys,\n"
" __global int\n"
" *values) {\n"
" uint i = get_global_id(0);\n"
" if (i >= numInsertions) {\n"
" return;\n"
" }\n"
" intintLCGLinearOpenCompactCLHash_InnerInsertSingleNoOverwrite(tableData,\n"
" keys[i],\n"
" values\n"
" [i]);\n"
"}\n"
"__kernel void intintLCGLinearOpenCompactCLHash_RangeInsertNoOverwrite(__global\n"
" char\n"
" *tableData,\n"
" unsigned\n"
" int\n"
" numInsertions,\n"
" unsigned\n"
" int\n"
" numEntries,\n"
" __global\n"
" int *keys,\n"
" __global\n"
" int\n"
" *values) {\n"
" uint i = get_global_id(0);\n"
" if (i >= numInsertions) {\n"
" return;\n"
" }\n"
" intintLCGLinearOpenCompactCLHash_InnerInsertNoOverwrite(tableData,\n"
" numEntries,\n"
" keys +\n"
" (i *\n"
" numEntries),\n"
" values +\n"
" (i *\n"
" numEntries));\n"
"}\n"
"\n"
"typedef struct intintLCGQuadraticOpenCompactCLHash_TableData {\n"
" int hashID;\n"
" unsigned int numBuckets;\n"
" intintHash_CompressLCGData compressFuncData;\n"
"} intintLCGQuadraticOpenCompactCLHash_TableData;\n"
"typedef struct intintLCGQuadraticOpenCompactCLHash_Bucket {\n"
" int key;\n"
" int value;\n"
"} intintLCGQuadraticOpenCompactCLHash_Bucket;\n"
"int intintLCGQuadraticOpenCompactCLHash_InnerQuerySingle(__global char\n"
" *tableData, int key,\n"
" __global int\n"
" *valueOutput) {\n"
" __global intintLCGQuadraticOpenCompactCLHash_Bucket *buckets =\n"
" (__global intintLCGQuadraticOpenCompactCLHash_Bucket *) &\n"
" tableData[sizeof(intintLCGQuadraticOpenCompactCLHash_TableData)];\n"
" int index;\n"
" int exitCode;\n"
" __global intintLCGQuadraticOpenCompactCLHash_TableData *mytableData =\n"
" (__global intintLCGQuadraticOpenCompactCLHash_TableData *)\n"
" tableData;\n"
" intintHash_CompressLCGData compressFuncData =\n"
" mytableData->compressFuncData;\n"
" unsigned int c = intintHash_CompressLCG(compressFuncData, key);\n"
" unsigned long int iteration = 0;\n"
" for (;;) {\n"
" index =\n"
" ((1 * iteration * iteration + 0 * iteration +\n"
" c) %\n"
" ((__global intintLCGQuadraticOpenCompactCLHash_TableData *)\n"
" tableData)->numBuckets);\n"
" if ((buckets[index].key) == HASH_BUCKET_STATUS_EMPTY) {\n"
" exitCode = HASH_SEARCH_CODE_EMPTY;\n"
" break;\n"
" } else if (key == buckets[index].key) {\n"
" exitCode = HASH_SEARCH_CODE_MATCH;\n"
" break;\n"
" } else\n"
" if ((iteration >\n"
" ((__global\n"
" intintLCGQuadraticOpenCompactCLHash_TableData *)\n"
" tableData)->numBuckets)) {\n"
" exitCode = HASH_EXIT_CODE_CYCLE;\n"
" break;\n"
" }\n"
" iteration++;\n"
" }\n"
" switch (exitCode) {\n"
" case HASH_SEARCH_CODE_MATCH:\n"
" *valueOutput = buckets[index].value;\n"
" return HASH_EXIT_CODE_NORMAL;\n"
" case HASH_SEARCH_CODE_MISMATCH:\n"
" case HASH_SEARCH_CODE_EMPTY:\n"
" return HASH_EXIT_CODE_KEY_DNE;\n"
" default:\n"
" return exitCode;\n"
" }\n"
"}\n"
"int intintLCGQuadraticOpenCompactCLHash_InnerQuery(__global char *tableData,\n"
" unsigned int numKeys,\n"
" __global int *keys,\n"
" __global int *valuesOutput) {\n"
" __global intintLCGQuadraticOpenCompactCLHash_Bucket *buckets =\n"
" (__global intintLCGQuadraticOpenCompactCLHash_Bucket *) &\n"
" tableData[sizeof(intintLCGQuadraticOpenCompactCLHash_TableData)];\n"
" int key;\n"
" __global int *valueOutput;\n"
" int index;\n"
" int exitCode;\n"
" uint i;\n"
" int resultExitCode = HASH_EXIT_CODE_NORMAL;\n"
" for (i = 0; i < numKeys; i++) {\n"
" key = keys[i];\n"
" valueOutput = &valuesOutput[i];\n"
" __global intintLCGQuadraticOpenCompactCLHash_TableData\n"
" *mytableData =\n"
" (__global intintLCGQuadraticOpenCompactCLHash_TableData *)\n"
" tableData;\n"
" intintHash_CompressLCGData compressFuncData =\n"
" mytableData->compressFuncData;\n"
" unsigned int c = intintHash_CompressLCG(compressFuncData, key);\n"
" unsigned long int iteration = 0;\n"
" for (;;) {\n"
" index =\n"
" ((1 * iteration * iteration + 0 * iteration +\n"
" c) %\n"
" ((__global\n"
" intintLCGQuadraticOpenCompactCLHash_TableData *)\n"
" tableData)->numBuckets);\n"
" if ((buckets[index].key) == HASH_BUCKET_STATUS_EMPTY) {\n"
" exitCode = HASH_SEARCH_CODE_EMPTY;\n"
" break;\n"
" } else if (key == buckets[index].key) {\n"
" exitCode = HASH_SEARCH_CODE_MATCH;\n"
" break;\n"
" } else\n"
" if ((iteration >\n"
" ((__global\n"
" intintLCGQuadraticOpenCompactCLHash_TableData\n"
" *) tableData)->numBuckets)) {\n"
" exitCode = HASH_EXIT_CODE_CYCLE;\n"
" break;\n"
" }\n"
" iteration++;\n"
" }\n"
" switch (exitCode) {\n"
" case HASH_SEARCH_CODE_MATCH:\n"
" *valueOutput = buckets[index].value;\n"
" break;\n"
" case HASH_SEARCH_CODE_MISMATCH:\n"
" case HASH_SEARCH_CODE_EMPTY:\n"
" resultExitCode = HASH_EXIT_CODE_KEY_DNE;\n"
" break;\n"
" default:\n"
" return exitCode;\n"
" }\n"
" }\n"
" return resultExitCode;\n"
"}\n"
"int intintLCGQuadraticOpenCompactCLHash_InnerInsertSingle(__global char\n"
" *tableData, int key,\n"
" int value) {\n"
" __global intintLCGQuadraticOpenCompactCLHash_Bucket *buckets =\n"
" (__global intintLCGQuadraticOpenCompactCLHash_Bucket *) &\n"
" tableData[sizeof(intintLCGQuadraticOpenCompactCLHash_TableData)];\n"
" int index;\n"
" int exitCode;\n"
" __global intintLCGQuadraticOpenCompactCLHash_TableData *mytableData =\n"
" (__global intintLCGQuadraticOpenCompactCLHash_TableData *)\n"
" tableData;\n"
" intintHash_CompressLCGData compressFuncData =\n"
" mytableData->compressFuncData;\n"
" unsigned int c = intintHash_CompressLCG(compressFuncData, key);\n"
" unsigned long int iteration = 0;\n"
" for (;;) {\n"
" index =\n"
" ((1 * iteration * iteration + 0 * iteration +\n"
" c) %\n"
" ((__global intintLCGQuadraticOpenCompactCLHash_TableData *)\n"
" tableData)->numBuckets);\n"
" if ((atomic_cmpxchg\n"
" (&(buckets[index].key), HASH_BUCKET_STATUS_EMPTY,\n"
" key)) == HASH_BUCKET_STATUS_EMPTY) {\n"
" exitCode = HASH_SEARCH_CODE_EMPTY;\n"
" break;\n"
" } else if (key == buckets[index].key) {\n"
" exitCode = HASH_SEARCH_CODE_MATCH;\n"
" break;\n"
" } else\n"
" if ((iteration >\n"
" ((__global\n"
" intintLCGQuadraticOpenCompactCLHash_TableData *)\n"
" tableData)->numBuckets)) {\n"
" exitCode = HASH_EXIT_CODE_CYCLE;\n"
" break;\n"
" }\n"
" iteration++;\n"
" }\n"
" switch (exitCode) {\n"
" case HASH_SEARCH_CODE_MATCH:\n"
" case HASH_SEARCH_CODE_MISMATCH:\n"
" buckets[index].value = value;\n"
" return HASH_EXIT_CODE_OVERWRITE;\n"
" case HASH_SEARCH_CODE_EMPTY:\n"
" buckets[index].value = value;\n"
" return HASH_EXIT_CODE_NORMAL;\n"
" default:\n"
" return exitCode;\n"
" }\n"
"}\n"
"int intintLCGQuadraticOpenCompactCLHash_InnerInsert(__global char *tableData,\n"
" unsigned int numEntries,\n"
" __global int *keys,\n"
" __global int *values) {\n"
" __global intintLCGQuadraticOpenCompactCLHash_Bucket *buckets =\n"
" (__global intintLCGQuadraticOpenCompactCLHash_Bucket *) &\n"
" tableData[sizeof(intintLCGQuadraticOpenCompactCLHash_TableData)];\n"
" int resultExitCode = HASH_EXIT_CODE_NORMAL;\n"
" int key;\n"
" int index;\n"
" int exitCode;\n"
" uint i;;\n"
" for (i = 0; i < numEntries; i++) {\n"
" key = keys[i];\n"
" __global intintLCGQuadraticOpenCompactCLHash_TableData\n"
" *mytableData =\n"
" (__global intintLCGQuadraticOpenCompactCLHash_TableData *)\n"
" tableData;\n"
" intintHash_CompressLCGData compressFuncData =\n"
" mytableData->compressFuncData;\n"
" unsigned int c = intintHash_CompressLCG(compressFuncData, key);\n"
" unsigned long int iteration = 0;\n"
" for (;;) {\n"
" index =\n"
" ((1 * iteration * iteration + 0 * iteration +\n"
" c) %\n"
" ((__global\n"
" intintLCGQuadraticOpenCompactCLHash_TableData *)\n"
" tableData)->numBuckets);\n"
" if ((atomic_cmpxchg\n"
" (&(buckets[index].key), HASH_BUCKET_STATUS_EMPTY,\n"
" key)) == HASH_BUCKET_STATUS_EMPTY) {\n"
" exitCode = HASH_SEARCH_CODE_EMPTY;\n"
" break;\n"
" } else if (key == buckets[index].key) {\n"
" exitCode = HASH_SEARCH_CODE_MATCH;\n"
" break;\n"
" } else\n"
" if ((iteration >\n"
" ((__global\n"
" intintLCGQuadraticOpenCompactCLHash_TableData\n"
" *) tableData)->numBuckets)) {\n"
" exitCode = HASH_EXIT_CODE_CYCLE;\n"
" break;\n"
" }\n"
" iteration++;\n"
" }\n"
" switch (exitCode) {\n"
" case HASH_SEARCH_CODE_MATCH:\n"
" case HASH_SEARCH_CODE_MISMATCH:\n"
" resultExitCode = HASH_EXIT_CODE_OVERWRITE;\n"
" case HASH_SEARCH_CODE_EMPTY:\n"
" buckets[index].value = values[i];\n"
" break;\n"
" default:\n"
" resultExitCode = exitCode;\n"
" }\n"
" }\n"
" return resultExitCode;\n"
"}\n"
"int intintLCGQuadraticOpenCompactCLHash_InnerInsertSingleNoOverwrite(__global\n"
" char\n"
" *tableData,\n"
" int key,\n"
" int value) \n"
"{\n"
" __global intintLCGQuadraticOpenCompactCLHash_Bucket *buckets =\n"
" (__global intintLCGQuadraticOpenCompactCLHash_Bucket *) &\n"
" tableData[sizeof(intintLCGQuadraticOpenCompactCLHash_TableData)];\n"
" int index;\n"
" int exitCode;\n"
" __global intintLCGQuadraticOpenCompactCLHash_TableData *mytableData =\n"
" (__global intintLCGQuadraticOpenCompactCLHash_TableData *)\n"
" tableData;\n"
" intintHash_CompressLCGData compressFuncData =\n"
" mytableData->compressFuncData;\n"
" unsigned int c = intintHash_CompressLCG(compressFuncData, key);\n"
" unsigned long int iteration = 0;\n"
" for (;;) {\n"
" index =\n"
" ((1 * iteration * iteration + 0 * iteration +\n"
" c) %\n"
" ((__global intintLCGQuadraticOpenCompactCLHash_TableData *)\n"
" tableData)->numBuckets);\n"
" if ((atomic_cmpxchg\n"
" (&(buckets[index].key), HASH_BUCKET_STATUS_EMPTY,\n"
" key)) == HASH_BUCKET_STATUS_EMPTY) {\n"
" exitCode = HASH_SEARCH_CODE_EMPTY;\n"
" break;\n"
" } else if (key == buckets[index].key) {\n"
" exitCode = HASH_SEARCH_CODE_MATCH;\n"
" break;\n"
" } else\n"
" if ((iteration >\n"
" ((__global\n"
" intintLCGQuadraticOpenCompactCLHash_TableData *)\n"
" tableData)->numBuckets)) {\n"
" exitCode = HASH_EXIT_CODE_CYCLE;\n"
" break;\n"
" }\n"
" iteration++;\n"
" }\n"
" switch (exitCode) {\n"
" case HASH_SEARCH_CODE_MATCH:\n"
" case HASH_SEARCH_CODE_MISMATCH:\n"
" return HASH_EXIT_CODE_OVERWRITE;\n"
" case HASH_SEARCH_CODE_EMPTY:\n"
" buckets[index].value = value;\n"
" return HASH_EXIT_CODE_NORMAL;\n"
" default:\n"
" return exitCode;\n"
" }\n"
"}\n"
"int intintLCGQuadraticOpenCompactCLHash_InnerInsertNoOverwrite(__global char\n"
" *tableData,\n"
" unsigned int\n"
" numEntries,\n"
" __global int\n"
" *keys,\n"
" __global int\n"
" *values) {\n"
" __global intintLCGQuadraticOpenCompactCLHash_Bucket *buckets =\n"
" (__global intintLCGQuadraticOpenCompactCLHash_Bucket *) &\n"
" tableData[sizeof(intintLCGQuadraticOpenCompactCLHash_TableData)];\n"
" int resultExitCode = HASH_EXIT_CODE_NORMAL;\n"
" int key;\n"
" int index;\n"
" int exitCode;\n"
" uint i;;\n"
" for (i = 0; i < numEntries; i++) {\n"
" key = keys[i];\n"
" __global intintLCGQuadraticOpenCompactCLHash_TableData\n"
" *mytableData =\n"
" (__global intintLCGQuadraticOpenCompactCLHash_TableData *)\n"
" tableData;\n"
" intintHash_CompressLCGData compressFuncData =\n"
" mytableData->compressFuncData;\n"
" unsigned int c = intintHash_CompressLCG(compressFuncData, key);\n"
" unsigned long int iteration = 0;\n"
" for (;;) {\n"
" index =\n"
" ((1 * iteration * iteration + 0 * iteration +\n"
" c) %\n"
" ((__global\n"
" intintLCGQuadraticOpenCompactCLHash_TableData *)\n"
" tableData)->numBuckets);\n"
" if ((atomic_cmpxchg\n"
" (&(buckets[index].key), HASH_BUCKET_STATUS_EMPTY,\n"
" key)) == HASH_BUCKET_STATUS_EMPTY) {\n"
" exitCode = HASH_SEARCH_CODE_EMPTY;\n"
" break;\n"
" } else if (key == buckets[index].key) {\n"
" exitCode = HASH_SEARCH_CODE_MATCH;\n"
" break;\n"
" } else\n"
" if ((iteration >\n"
" ((__global\n"
" intintLCGQuadraticOpenCompactCLHash_TableData\n"
" *) tableData)->numBuckets)) {\n"
" exitCode = HASH_EXIT_CODE_CYCLE;\n"
" break;\n"
" }\n"
" iteration++;\n"
" }\n"
" switch (exitCode) {\n"
" case HASH_SEARCH_CODE_MATCH:\n"
" case HASH_SEARCH_CODE_MISMATCH:\n"
" resultExitCode = HASH_EXIT_CODE_OVERWRITE;\n"
" break;\n"
" case HASH_SEARCH_CODE_EMPTY:\n"
" buckets[index].value = values[i];\n"
" break;\n"
" default:\n"
" resultExitCode = exitCode;\n"
" }\n"
" }\n"
" return resultExitCode;\n"
"}\n"
"int intintLCGQuadraticOpenCompactCLHash_QuerySingle(__global char *tableData,\n"
" int key,\n"
" __global int *valueOutput) {\n"
" return intintLCGQuadraticOpenCompactCLHash_InnerQuerySingle(tableData,\n"
" key,\n"
" valueOutput);\n"
"}\n"
"int intintLCGQuadraticOpenCompactCLHash_Query(__global char *tableData,\n"
" size_t numKeys,\n"
" __global int *keys,\n"
" __global int *valuesOutput) {\n"
" return intintLCGQuadraticOpenCompactCLHash_InnerQuery(tableData,\n"
" numKeys, keys,\n"
" valuesOutput);\n"
"}\n"
"int intintLCGQuadraticOpenCompactCLHash_InsertSingle(__global char *tableData,\n"
" int key, int value) {\n"
" return intintLCGQuadraticOpenCompactCLHash_InnerInsertSingle(tableData,\n"
" key,\n"
" value);\n"
"}\n"
"int intintLCGQuadraticOpenCompactCLHash_Insert(__global char *tableData,\n"
" size_t numEntries,\n"
" __global int *keys,\n"
" __global int *values) {\n"
" return intintLCGQuadraticOpenCompactCLHash_InnerInsert(tableData,\n"
" numEntries, keys,\n"
" values);\n"
"}\n"
"int intintLCGQuadraticOpenCompactCLHash_InsertSingleNoOverwrite(__global char\n"
" *tableData,\n"
" int key,\n"
" int value) {\n"
" return\n"
" intintLCGQuadraticOpenCompactCLHash_InnerInsertSingleNoOverwrite\n"
" (tableData, key, value);\n"
"}\n"
"int intintLCGQuadraticOpenCompactCLHash_InsertNoOverwrite(__global char\n"
" *tableData,\n"
" size_t numEntries,\n"
" __global int *keys,\n"
" __global int *values) \n"
"{\n"
" return\n"
" intintLCGQuadraticOpenCompactCLHash_InnerInsertNoOverwrite\n"
" (tableData, numEntries, keys, values);\n"
"}\n"
"__kernel void intintLCGQuadraticOpenCompactCLHash_RangeQuerySingle(__global char\n"
" *tableData,\n"
" unsigned int\n"
" numQueries,\n"
" __global int\n"
" *keys,\n"
" __global int\n"
" *valuesOutput) \n"
"{\n"
" uint i = get_global_id(0);\n"
" if (i >= numQueries) {\n"
" return;\n"
" }\n"
" intintLCGQuadraticOpenCompactCLHash_InnerQuerySingle(tableData, keys[i],\n"
" valuesOutput + i);\n"
"}\n"
"__kernel void intintLCGQuadraticOpenCompactCLHash_RangeQuery(__global char\n"
" *tableData,\n"
" unsigned int\n"
" numQueries,\n"
" unsigned int\n"
" numKeys,\n"
" __global int *keys,\n"
" __global int\n"
" *valuesOutput) {\n"
" uint i = get_global_id(0);\n"
" if (i >= numQueries) {\n"
" return;\n"
" }\n"
" intintLCGQuadraticOpenCompactCLHash_InnerQuery(tableData, numKeys,\n"
" keys + (i * numKeys),\n"
" valuesOutput +\n"
" (i * numKeys));\n"
"}\n"
"__kernel void intintLCGQuadraticOpenCompactCLHash_RangeInsertSingle(__global\n"
" char\n"
" *tableData,\n"
" unsigned int\n"
" numInsertions,\n"
" __global int\n"
" *keys,\n"
" __global int\n"
" *values) {\n"
" uint i = get_global_id(0);\n"
" if (i >= numInsertions) {\n"
" return;\n"
" }\n"
" intintLCGQuadraticOpenCompactCLHash_InnerInsertSingle(tableData,\n"
" keys[i],\n"
" values[i]);\n"
"}\n"
"__kernel void intintLCGQuadraticOpenCompactCLHash_RangeInsert(__global char\n"
" *tableData,\n"
" unsigned int\n"
" numInsertions,\n"
" unsigned int\n"
" numEntries,\n"
" __global int\n"
" *keys,\n"
" __global int\n"
" *values) {\n"
" uint i = get_global_id(0);\n"
" if (i >= numInsertions) {\n"
" return;\n"
" }\n"
" intintLCGQuadraticOpenCompactCLHash_InnerInsert(tableData, numEntries,\n"
" keys + (i * numEntries),\n"
" values +\n"
" (i * numEntries));\n"
"}\n"
"__kernel void\n"
"intintLCGQuadraticOpenCompactCLHash_RangeInsertSingleNoOverwrite(__global char\n"
" *tableData,\n"
" unsigned int\n"
" numInsertions,\n"
" __global int\n"
" *keys,\n"
" __global int\n"
" *values) {\n"
" uint i = get_global_id(0);\n"
" if (i >= numInsertions) {\n"
" return;\n"
" }\n"
" intintLCGQuadraticOpenCompactCLHash_InnerInsertSingleNoOverwrite\n"
" (tableData, keys[i], values[i]);\n"
"}\n"
"__kernel void\n"
"intintLCGQuadraticOpenCompactCLHash_RangeInsertNoOverwrite(__global char\n"
" *tableData,\n"
" unsigned int\n"
" numInsertions,\n"
" unsigned int\n"
" numEntries,\n"
" __global int *keys,\n"
" __global int\n"
" *values) {\n"
" uint i = get_global_id(0);\n"
" if (i >= numInsertions) {\n"
" return;\n"
" }\n"
" intintLCGQuadraticOpenCompactCLHash_InnerInsertNoOverwrite(tableData,\n"
" numEntries,\n"
" keys +\n"
" (i *\n"
" numEntries),\n"
" values +\n"
" (i *\n"
" numEntries));\n"
"}\n"
"__kernel void intintHash_RangeQuery(__global char *tableData,\n"
" unsigned int numQueries,\n"
" unsigned int numKeys, __global int *keys,\n"
" __global int *valuesOutput) {\n"
" switch (((__global int *)tableData)[0]) {\n"
" case IDENTITY_PERFECT_CL_HASH_ID:\n"
" return intintIdentityPerfectCLHash_RangeQuery(tableData,\n"
" numQueries,\n"
" numKeys, keys,\n"
" valuesOutput);\n"
" case IDENTITY_SENTINEL_PERFECT_CL_HASH_ID:\n"
" return intintIdentitySentinelPerfectCLHash_RangeQuery(tableData,\n"
" numQueries,\n"
" numKeys,\n"
" keys,\n"
" valuesOutput);\n"
" case LCG_LINEAR_OPEN_COMPACT_CL_HASH_ID:\n"
" return intintLCGLinearOpenCompactCLHash_RangeQuery(tableData,\n"
" numQueries,\n"
" numKeys,\n"
" keys,\n"
" valuesOutput);\n"
" case LCG_QUADRATIC_OPEN_COMPACT_CL_HASH_ID:\n"
" return intintLCGQuadraticOpenCompactCLHash_RangeQuery(tableData,\n"
" numQueries,\n"
" numKeys,\n"
" keys,\n"
" valuesOutput);\n"
" }\n"
"}\n"
"__kernel void intintHash_RangeQuerySingle(__global char *tableData,\n"
" unsigned int numQueries,\n"
" __global int *keys,\n"
" __global int *valueOutput) {\n"
" switch (((__global int *)tableData)[0]) {\n"
" case IDENTITY_PERFECT_CL_HASH_ID:\n"
" return intintIdentityPerfectCLHash_RangeQuerySingle(tableData,\n"
" numQueries,\n"
" keys,\n"
" valueOutput);\n"
" case IDENTITY_SENTINEL_PERFECT_CL_HASH_ID:\n"
" return\n"
" intintIdentitySentinelPerfectCLHash_RangeQuerySingle\n"
" (tableData, numQueries, keys, valueOutput);\n"
" case LCG_LINEAR_OPEN_COMPACT_CL_HASH_ID:\n"
" return\n"
" intintLCGLinearOpenCompactCLHash_RangeQuerySingle(tableData,\n"
" numQueries,\n"
" keys,\n"
" valueOutput);\n"
" case LCG_QUADRATIC_OPEN_COMPACT_CL_HASH_ID:\n"
" return\n"
" intintLCGQuadraticOpenCompactCLHash_RangeQuerySingle\n"
" (tableData, numQueries, keys, valueOutput);\n"
" }\n"
"}\n"
"__kernel void intintHash_RangeInsert(__global char *tableData,\n"
" unsigned int numInsertions,\n"
" unsigned int numEntries,\n"
" __global int *keys, __global int *values) {\n"
" switch (((__global int *)tableData)[0]) {\n"
" case IDENTITY_PERFECT_CL_HASH_ID:\n"
" return intintIdentityPerfectCLHash_RangeInsert(tableData,\n"
" numInsertions,\n"
" numEntries, keys,\n"
" values);\n"
" case IDENTITY_SENTINEL_PERFECT_CL_HASH_ID:\n"
" return\n"
" intintIdentitySentinelPerfectCLHash_RangeInsert(tableData,\n"
" numInsertions,\n"
" numEntries,\n"
" keys,\n"
" values);\n"
" case LCG_LINEAR_OPEN_COMPACT_CL_HASH_ID:\n"
" return intintLCGLinearOpenCompactCLHash_RangeInsert(tableData,\n"
" numInsertions,\n"
" numEntries,\n"
" keys,\n"
" values);\n"
" case LCG_QUADRATIC_OPEN_COMPACT_CL_HASH_ID:\n"
" return\n"
" intintLCGQuadraticOpenCompactCLHash_RangeInsert(tableData,\n"
" numInsertions,\n"
" numEntries,\n"
" keys,\n"
" values);\n"
" }\n"
"}\n"
"__kernel void intintHash_RangeInsertSingle(__global char *tableData,\n"
" unsigned int numInsertions,\n"
" __global int *keys,\n"
" __global int *values) {\n"
" switch (((__global int *)tableData)[0]) {\n"
" case IDENTITY_PERFECT_CL_HASH_ID:\n"
" return intintIdentityPerfectCLHash_RangeInsertSingle(tableData,\n"
" numInsertions,\n"
" keys,\n"
" values);\n"
" case IDENTITY_SENTINEL_PERFECT_CL_HASH_ID:\n"
" return\n"
" intintIdentitySentinelPerfectCLHash_RangeInsertSingle\n"
" (tableData, numInsertions, keys, values);\n"
" case LCG_LINEAR_OPEN_COMPACT_CL_HASH_ID:\n"
" return\n"
" intintLCGLinearOpenCompactCLHash_RangeInsertSingle\n"
" (tableData, numInsertions, keys, values);\n"
" case LCG_QUADRATIC_OPEN_COMPACT_CL_HASH_ID:\n"
" return\n"
" intintLCGQuadraticOpenCompactCLHash_RangeInsertSingle\n"
" (tableData, numInsertions, keys, values);\n"
" }\n"
"}\n"
"__kernel void intintHash_RangeInsertNoOverwrite(__global char *tableData,\n"
" unsigned int numInsertions,\n"
" unsigned int numEntries,\n"
" __global int *keys,\n"
" __global int *values) {\n"
" switch (((__global int *)tableData)[0]) {\n"
" case IDENTITY_PERFECT_CL_HASH_ID:\n"
" return\n"
" intintIdentityPerfectCLHash_RangeInsertNoOverwrite\n"
" (tableData, numInsertions, numEntries, keys, values);\n"
" case IDENTITY_SENTINEL_PERFECT_CL_HASH_ID:\n"
" return\n"
" intintIdentitySentinelPerfectCLHash_RangeInsertNoOverwrite\n"
" (tableData, numInsertions, numEntries, keys, values);\n"
" case LCG_LINEAR_OPEN_COMPACT_CL_HASH_ID:\n"
" return\n"
" intintLCGLinearOpenCompactCLHash_RangeInsertNoOverwrite\n"
" (tableData, numInsertions, numEntries, keys, values);\n"
" case LCG_QUADRATIC_OPEN_COMPACT_CL_HASH_ID:\n"
" return\n"
" intintLCGQuadraticOpenCompactCLHash_RangeInsertNoOverwrite\n"
" (tableData, numInsertions, numEntries, keys, values);\n"
" }\n"
"}\n"
"__kernel void intintHash_RangeInsertSingleNoOverwrite(__global char *tableData,\n"
" unsigned int\n"
" numInsertions,\n"
" __global int *keys,\n"
" __global int *values) {\n"
" switch (((__global int *)tableData)[0]) {\n"
" case IDENTITY_PERFECT_CL_HASH_ID:\n"
" return\n"
" intintIdentityPerfectCLHash_RangeInsertSingleNoOverwrite\n"
" (tableData, numInsertions, keys, values);\n"
" case IDENTITY_SENTINEL_PERFECT_CL_HASH_ID:\n"
" return\n"
" intintIdentitySentinelPerfectCLHash_RangeInsertSingleNoOverwrite\n"
" (tableData, numInsertions, keys, values);\n"
" case LCG_LINEAR_OPEN_COMPACT_CL_HASH_ID:\n"
" return\n"
" intintLCGLinearOpenCompactCLHash_RangeInsertSingleNoOverwrite\n"
" (tableData, numInsertions, keys, values);\n"
" case LCG_QUADRATIC_OPEN_COMPACT_CL_HASH_ID:\n"
" return\n"
" intintLCGQuadraticOpenCompactCLHash_RangeInsertSingleNoOverwrite\n"
" (tableData, numInsertions, keys, values);\n"
" }\n"
"}\n"
"int intintHash_Query(__global char *tableData, unsigned int numKeys,\n"
" __global int *keys, __global int *valuesOutput) {\n"
" switch (((__global int *)tableData)[0]) {\n"
" case IDENTITY_PERFECT_CL_HASH_ID:\n"
" return intintIdentityPerfectCLHash_Query(tableData, numKeys,\n"
" keys, valuesOutput);\n"
" case IDENTITY_SENTINEL_PERFECT_CL_HASH_ID:\n"
" return intintIdentitySentinelPerfectCLHash_Query(tableData,\n"
" numKeys, keys,\n"
" valuesOutput);\n"
" case LCG_LINEAR_OPEN_COMPACT_CL_HASH_ID:\n"
" return intintLCGLinearOpenCompactCLHash_Query(tableData,\n"
" numKeys, keys,\n"
" valuesOutput);\n"
" case LCG_QUADRATIC_OPEN_COMPACT_CL_HASH_ID:\n"
" return intintLCGQuadraticOpenCompactCLHash_Query(tableData,\n"
" numKeys, keys,\n"
" valuesOutput);\n"
" }\n"
" return HASH_EXIT_CODE_ERROR;\n"
"}\n"
"int intintHash_QuerySingle(__global char *tableData, int key,\n"
" __global int *valueOutput) {\n"
" switch (((__global int *)tableData)[0]) {\n"
" case IDENTITY_PERFECT_CL_HASH_ID:\n"
" return intintIdentityPerfectCLHash_QuerySingle(tableData, key,\n"
" valueOutput);\n"
" case IDENTITY_SENTINEL_PERFECT_CL_HASH_ID:\n"
" return\n"
" intintIdentitySentinelPerfectCLHash_QuerySingle(tableData,\n"
" key,\n"
" valueOutput);\n"
" case LCG_LINEAR_OPEN_COMPACT_CL_HASH_ID:\n"
" return intintLCGLinearOpenCompactCLHash_QuerySingle(tableData,\n"
" key,\n"
" valueOutput);\n"
" case LCG_QUADRATIC_OPEN_COMPACT_CL_HASH_ID:\n"
" return\n"
" intintLCGQuadraticOpenCompactCLHash_QuerySingle(tableData,\n"
" key,\n"
" valueOutput);\n"
" }\n"
" return HASH_EXIT_CODE_ERROR;\n"
"}\n"
"int intintHash_Insert(__global char *tableData, unsigned int numEntries,\n"
" __global int *keys, __global int *values) {\n"
" switch (((__global int *)tableData)[0]) {\n"
" case IDENTITY_PERFECT_CL_HASH_ID:\n"
" return intintIdentityPerfectCLHash_Insert(tableData, numEntries,\n"
" keys, values);\n"
" case IDENTITY_SENTINEL_PERFECT_CL_HASH_ID:\n"
" return intintIdentitySentinelPerfectCLHash_Insert(tableData,\n"
" numEntries,\n"
" keys, values);\n"
" case LCG_LINEAR_OPEN_COMPACT_CL_HASH_ID:\n"
" return intintLCGLinearOpenCompactCLHash_Insert(tableData,\n"
" numEntries, keys,\n"
" values);\n"
" case LCG_QUADRATIC_OPEN_COMPACT_CL_HASH_ID:\n"
" return intintLCGQuadraticOpenCompactCLHash_Insert(tableData,\n"
" numEntries,\n"
" keys, values);\n"
" }\n"
" return HASH_EXIT_CODE_ERROR;\n"
"}\n"
"int intintHash_InsertSingle(__global char *tableData, int key, int value) {\n"
" switch (((__global int *)tableData)[0]) {\n"
" case IDENTITY_PERFECT_CL_HASH_ID:\n"
" return intintIdentityPerfectCLHash_InsertSingle(tableData, key,\n"
" value);\n"
" case IDENTITY_SENTINEL_PERFECT_CL_HASH_ID:\n"
" return\n"
" intintIdentitySentinelPerfectCLHash_InsertSingle(tableData,\n"
" key,\n"
" value);\n"
" case LCG_LINEAR_OPEN_COMPACT_CL_HASH_ID:\n"
" return intintLCGLinearOpenCompactCLHash_InsertSingle(tableData,\n"
" key,\n"
" value);\n"
" case LCG_QUADRATIC_OPEN_COMPACT_CL_HASH_ID:\n"
" return\n"
" intintLCGQuadraticOpenCompactCLHash_InsertSingle(tableData,\n"
" key,\n"
" value);\n"
" }\n"
" return HASH_EXIT_CODE_ERROR;\n"
"}\n"
"int intintHash_InsertNoOverwrite(__global char *tableData,\n"
" unsigned int numEntries, __global int *keys,\n"
" __global int *values) {\n"
" switch (((__global int *)tableData)[0]) {\n"
" case IDENTITY_PERFECT_CL_HASH_ID:\n"
" return intintIdentityPerfectCLHash_InsertNoOverwrite(tableData,\n"
" numEntries,\n"
" keys,\n"
" values);\n"
" case IDENTITY_SENTINEL_PERFECT_CL_HASH_ID:\n"
" return\n"
" intintIdentitySentinelPerfectCLHash_InsertNoOverwrite\n"
" (tableData, numEntries, keys, values);\n"
" case LCG_LINEAR_OPEN_COMPACT_CL_HASH_ID:\n"
" return\n"
" intintLCGLinearOpenCompactCLHash_InsertNoOverwrite\n"
" (tableData, numEntries, keys, values);\n"
" case LCG_QUADRATIC_OPEN_COMPACT_CL_HASH_ID:\n"
" return\n"
" intintLCGQuadraticOpenCompactCLHash_InsertNoOverwrite\n"
" (tableData, numEntries, keys, values);\n"
" }\n"
" return HASH_EXIT_CODE_ERROR;\n"
"}\n"
"int intintHash_InsertSingleNoOverwrite(__global char *tableData, int key,\n"
" int value) {\n"
" switch (((__global int *)tableData)[0]) {\n"
" case IDENTITY_PERFECT_CL_HASH_ID:\n"
" return\n"
" intintIdentityPerfectCLHash_InsertSingleNoOverwrite\n"
" (tableData, key, value);\n"
" case IDENTITY_SENTINEL_PERFECT_CL_HASH_ID:\n"
" return\n"
" intintIdentitySentinelPerfectCLHash_InsertSingleNoOverwrite\n"
" (tableData, key, value);\n"
" case LCG_LINEAR_OPEN_COMPACT_CL_HASH_ID:\n"
" return\n"
" intintLCGLinearOpenCompactCLHash_InsertSingleNoOverwrite\n"
" (tableData, key, value);\n"
" case LCG_QUADRATIC_OPEN_COMPACT_CL_HASH_ID:\n"
" return\n"
" intintLCGQuadraticOpenCompactCLHash_InsertSingleNoOverwrite\n"
" (tableData, key, value);\n"
" }\n"
" return HASH_EXIT_CODE_ERROR;\n"
"}\n"
;
|
MD5_fmt.c
|
/*
* This file is part of John the Ripper password cracker,
* Copyright (c) 1996-2001,2008,2010-2012 by Solar Designer
*
* ...with changes in the jumbo patch, by bartavelle and magnum.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted.
*
* There's ABSOLUTELY NO WARRANTY, express or implied.
*/
#include <string.h>
#include "arch.h"
#include "misc.h"
#include "simd-intrinsics.h"
#include "MD5_std.h"
#include "common.h"
#include "formats.h"
#include "cryptmd5_common.h"
#if defined(_OPENMP) && defined(SIMD_PARA_MD5)
#ifndef OMP_SCALE
#define OMP_SCALE 4
#endif
#include <omp.h>
#endif
#include "memdbg.h"
#define FORMAT_LABEL "md5crypt"
#define FORMAT_NAME "crypt(3) $1$"
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH -1
#define PLAINTEXT_LENGTH 15
#define CIPHERTEXT_LENGTH 22
#ifdef SIMD_PARA_MD5
#define BINARY_SIZE 16
#else
#define BINARY_SIZE 4
#endif
#define BINARY_ALIGN 4
#define SALT_SIZE 9
#define SALT_ALIGN 1
#define MIN_KEYS_PER_CRYPT MD5_N
#define MAX_KEYS_PER_CRYPT MD5_N
static struct fmt_tests tests[] = {
{"$1$12345678$aIccj83HRDBo6ux1bVx7D1", "0123456789ABCDE"},
{"$apr1$Q6ZYh...$RV6ft2bZ8j.NGrxLYaJt9.", "test"},
{"$1$12345678$f8QoJuo0DpBRfQSD0vglc1", "12345678"},
{"$1$$qRPK7m23GJusamGpoGLby/", ""},
{"$apr1$a2Jqm...$grFrwEgiQleDr0zR4Jx1b.", "15 chars is max"},
{"$1$$AuJCr07mI7DSew03TmBIv/", "no salt"},
{"$1$`!@#%^&*$E6hD76/pKTS8qToBCkux30", "invalid salt"},
{"$1$12345678$xek.CpjQUVgdf/P2N9KQf/", ""},
{"$1$1234$BdIMOAWFOV2AQlLsrN/Sw.", "1234"},
{"$apr1$rBXqc...$NlXxN9myBOk95T0AyLAsJ0", "john"},
{"$apr1$Grpld/..$qp5GyjwM2dnA5Cdej9b411", "the"},
{"$apr1$GBx.D/..$yfVeeYFCIiEXInfRhBRpy/", "ripper"},
{"$1$bb$19smCEBG0Q1pVil0/HqK./", "aaaaa"},
{"$1$coin$rebm0t9KJ56mgGWJF5o5M0", "lapin"},
{"$1$pouet$/Ecz/vyk.zCYvrr6wB78h0", "canard"},
{"$1$test2$02MCIATVoxq3IhgK6XRkb1", "test1"},
{"$1$aussi$X67z3kXsWo92F15uChx1H1", "felicie"},
{"$1$boire$gf.YM2y3InYEu9.NbVr.v0", "manger"},
{"$1$bas$qvkmmWnVHRCSv/6LQ1doH/", "haut"},
{"$1$gauche$EPvd6LZlrgb0MMFPxUrJN1", "droite"},
/* following hashes are AIX non-standard smd5 hashes */
{"{smd5}s8/xSJ/v$uGam4GB8hOjTLQqvBfxJ2/", "password"},
{"{smd5}alRJaSLb$aKM3H1.h1ycXl5GEVDH1e1", "aixsucks?"},
{"{smd5}eLB0QWeS$Eg.YfWY8clZuCxF0xNrKg.", "0123456789ABCDE"},
/* following hashes are AIX standard smd5 hashes (with corrected tag)
* lpa_options = std_hash=true */
{"$1$JVDbGx8K$T9h8HK4LZxeLPMTAxCfpc1", "password"},
{"$1$1Cu6fEvv$42kuaJ5fMEqyVStPuFG040", "0123456789ABCDE"},
{"$1$ql5x.xXL$vYVDhExol2xUBBpERRWcn1", "jtr>hashcat"},
{"$1$27iyq7Ya$miN09fW1Scj0DHVNyewoU/", ""},
{"$1$84Othc1n$v1cuReaa5lRdGuHaOa76n0", "a"},
{"$1$4zq0BsCR$U2ua9WZtDEhzy4gFSiLxN1", "aa"},
{"$1$DKwjKWxp$PY6PdlPZsXjOppPDoFOz4.", "aaa"},
{"$1$OKDV6ppN$viTVmH48bSePiCrMvXT/./", "aaaa"},
{"$1$QEWsCY0O$xrTTMKTepiHMp7Oxgz0pX/", "aaaaa"},
{"$1$5dfdk2dF$XiJBPNrfKcCgdQ/kcoB40/", "aaaaaa"},
{"$1$Ps6A1Cy6$WsvLg9cQhm9JU0rXkLEtz.", "aaaaaaa"},
{"$1$9IK7nZ4M$4nx7Mdj05KGPJX/mZaDrh.", "aaaaaaaa"},
{"$1$l3pNTqwT$GAc.dcRaxCvC20CFGCjp4/", "aaaaaaaaa"},
{"$1$jSAARhJR$6daQ/ekjAL0MgOUgGJyp10", "aaaaaaaaaa"},
{"$1$wk3Xwqqg$2AtdiucwJvJgbaVT1jWpb0", "aaaaaaaaaaa"},
{"$1$G6Fn69Ei$d7AKJUOIdz/gO4Utc0TQP1", "aaaaaaaaaaaa"},
{"$1$A7XJ7lGK$W5jTnH/4lW4XwZ.6F7n1N.", "aaaaaaaaaaaaa"},
{"$1$Rcm46RfA$LfdIK/OP16yHzMYHSlx/B.", "aaaaaaaaaaaaaa"},
{"$1$4bCSSJMN$TcYKTsukD4SFJE1n4MwMZ/", "aaaaaaaaaaaaaaa"},
#if PLAINTEXT_LENGTH > 15
{"$1$mJxBkkl8$u7OHfWCPmNxvf0um7hH89.", "aaaaaaaaaaaaaaaa"},
{"$1$Ub1gBUt4$TNaLxU7Pq5mk/MiDEb60b/", "aaaaaaaaaaaaaaaaa"},
{"$1$8ot7QScR$x.p4vjIgdFxxS83x29PkJ0", "aaaaaaaaaaaaaaaaaa"},
{"$1$wRi4OjD3$eJjKD2AwLMWfOTRYA30zn.", "aaaaaaaaaaaaaaaaaaa"},
{"$1$lmektrsg$2KSRY4EUFzsYNMg80fG4/0", "aaaaaaaaaaaaaaaaaaaa"},
{"$1$tgVBKBmE$YRvzsi7qHP2MC1Atg8VCV.", "aaaaaaaaaaaaaaaaaaaaa"},
{"$1$oTsk88YC$Eh435T1BQzmjQekfqkHof/", "aaaaaaaaaaaaaaaaaaaaaa"},
{"$1$ykxSZEfP$hJrFeGOFk049L.94Mgggj/", "aaaaaaaaaaaaaaaaaaaaaaa"},
{"$1$LBK4p5tD$5/gAIx8/7hpTVwDC/.KQv/", "aaaaaaaaaaaaaaaaaaaaaaaa"},
{"$1$fkEasaUI$G7CelOWHkol2nVHN8XQP40", "aaaaaaaaaaaaaaaaaaaaaaaaa"},
{"$1$gRevVzeY$eMMQrsl5OHL5dP1p/ktJc/", "aaaaaaaaaaaaaaaaaaaaaaaaaa"},
{"$1$164TNEjj$ppoV6Ju6Vu63j1OlM4zit/", "aaaaaaaaaaaaaaaaaaaaaaaaaaa"},
{"$1$ErPmhjp2$lZZstb2M455Xhk50eeH4i/", "aaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
{"$1$NUssS5fT$QaS4Ywt0IwzxbE0FAGnXn0", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
{"$1$NxlTyiJ7$gxkXTEJdeTzY8P6tqKmcz.", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
{"$1$Cmy9x7gW$kamvHI42Kh1CH4Shy6g6S/", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
{"$1$IsuapfCX$4Yq0Adq5nNZgl0LwbSl5Y0", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
{"$1$rSZfNcKX$N4XPvGrfhKsyoEcRSaqmG0", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
#endif
{NULL}
};
static char (*saved_key)[PLAINTEXT_LENGTH + 1];
#ifdef SIMD_PARA_MD5
static unsigned char cursalt[SALT_SIZE];
static int CryptType;
static MD5_word (*sout);
static int omp_para = 1;
#endif
static void init(struct fmt_main *self)
{
MD5_std_init(self);
#if defined(_OPENMP) && defined(SIMD_PARA_MD5)
omp_para = omp_get_max_threads();
if (omp_para < 1)
omp_para = 1;
self->params.min_keys_per_crypt = MD5_N * omp_para;
omp_para *= OMP_SCALE;
self->params.max_keys_per_crypt = MD5_N * omp_para;
#elif MD5_std_mt
self->params.min_keys_per_crypt = MD5_std_min_kpc;
self->params.max_keys_per_crypt = MD5_std_max_kpc;
#endif
saved_key = mem_calloc_align(self->params.max_keys_per_crypt,
sizeof(*saved_key), MEM_ALIGN_CACHE);
#ifdef SIMD_PARA_MD5
sout = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*sout) * BINARY_SIZE);
#endif
}
static void done(void)
{
#ifdef SIMD_PARA_MD5
MEM_FREE(sout);
#endif
MEM_FREE(saved_key);
}
static int get_hash_0(int index)
{
#ifdef SIMD_PARA_MD5
unsigned int x,y;
x = index&(SIMD_COEF_32-1);
y = (unsigned int)index/SIMD_COEF_32;
return ((MD5_word *)sout)[x+y*SIMD_COEF_32*4] & PH_MASK_0;
#else
init_t();
return MD5_out[index][0] & PH_MASK_0;
#endif
}
static int get_hash_1(int index)
{
#ifdef SIMD_PARA_MD5
unsigned int x,y;
x = index&(SIMD_COEF_32-1);
y = (unsigned int)index/SIMD_COEF_32;
return ((MD5_word *)sout)[x+y*SIMD_COEF_32*4] & PH_MASK_1;
#else
init_t();
return MD5_out[index][0] & PH_MASK_1;
#endif
}
static int get_hash_2(int index)
{
#ifdef SIMD_PARA_MD5
unsigned int x,y;
x = index&(SIMD_COEF_32-1);
y = (unsigned int)index/SIMD_COEF_32;
return ((MD5_word *)sout)[x+y*SIMD_COEF_32*4] & PH_MASK_2;
#else
init_t();
return MD5_out[index][0] & PH_MASK_2;
#endif
}
static int get_hash_3(int index)
{
#ifdef SIMD_PARA_MD5
unsigned int x,y;
x = index&(SIMD_COEF_32-1);
y = (unsigned int)index/SIMD_COEF_32;
return ((MD5_word *)sout)[x+y*SIMD_COEF_32*4] & PH_MASK_3;
#else
init_t();
return MD5_out[index][0] & PH_MASK_3;
#endif
}
static int get_hash_4(int index)
{
#ifdef SIMD_PARA_MD5
unsigned int x,y;
x = index&(SIMD_COEF_32-1);
y = (unsigned int)index/SIMD_COEF_32;
return ((MD5_word *)sout)[x+y*SIMD_COEF_32*4] & PH_MASK_4;
#else
init_t();
return MD5_out[index][0] & PH_MASK_4;
#endif
}
static int get_hash_5(int index)
{
#ifdef SIMD_PARA_MD5
unsigned int x,y;
x = index&(SIMD_COEF_32-1);
y = (unsigned int)index/SIMD_COEF_32;
return ((MD5_word *)sout)[x+y*SIMD_COEF_32*4] & PH_MASK_5;
#else
init_t();
return MD5_out[index][0] & PH_MASK_5;
#endif
}
static int get_hash_6(int index)
{
#ifdef SIMD_PARA_MD5
unsigned int x,y;
x = index&(SIMD_COEF_32-1);
y = (unsigned int)index/SIMD_COEF_32;
return ((MD5_word *)sout)[x+y*SIMD_COEF_32*4] & PH_MASK_6;
#else
init_t();
return MD5_out[index][0] & PH_MASK_6;
#endif
}
static int salt_hash(void *salt)
{
unsigned int i, h, retval;
retval = 0;
for (i = 0; i <= 6; i += 2) {
h = (unsigned char)atoi64[ARCH_INDEX(((char *)salt)[i])];
h ^= ((unsigned char *)salt)[i + 1];
h <<= 6;
h ^= (unsigned char)atoi64[ARCH_INDEX(((char *)salt)[i + 1])];
h ^= ((unsigned char *)salt)[i];
retval += h;
}
retval ^= retval >> SALT_HASH_LOG;
retval &= SALT_HASH_SIZE - 1;
return retval;
}
static void set_key(char *key, int index)
{
#ifndef SIMD_PARA_MD5
MD5_std_set_key(key, index);
#endif
strnfcpy(saved_key[index], key, PLAINTEXT_LENGTH);
}
static char *get_key(int index)
{
saved_key[index][PLAINTEXT_LENGTH] = 0;
return saved_key[index];
}
static int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
#ifdef SIMD_PARA_MD5
#ifdef _OPENMP
int t;
#pragma omp parallel for
for (t = 0; t < omp_para; t++)
md5cryptsse((unsigned char *)(&saved_key[t*MD5_N]), cursalt, (char *)(&sout[t*MD5_N*BINARY_SIZE/sizeof(MD5_word)]), CryptType);
#else
md5cryptsse((unsigned char *)saved_key, cursalt, (char *)sout, CryptType);
#endif
#else
MD5_std_crypt(count);
#endif
return count;
}
static int cmp_all(void *binary, int count)
{
#ifdef SIMD_PARA_MD5
unsigned int x,y;
for(y=0;y<SIMD_PARA_MD5*omp_para;y++) for(x=0;x<SIMD_COEF_32;x++)
{
if( ((MD5_word *)binary)[0] == ((MD5_word *)sout)[x+y*SIMD_COEF_32*4] )
return 1;
}
return 0;
#else
#if MD5_std_mt
int t, n = (count + (MD5_N - 1)) / MD5_N;
#endif
for_each_t(n) {
#if MD5_X2
if (*(MD5_word *)binary == MD5_out[0][0] ||
*(MD5_word *)binary == MD5_out[1][0])
return 1;
#else
if (*(MD5_word *)binary == MD5_out[0][0])
return 1;
#endif
}
return 0;
#endif
}
static int cmp_one(void *binary, int index)
{
#ifdef SIMD_PARA_MD5
unsigned int x,y;
x = index&(SIMD_COEF_32-1);
y = (unsigned int)index/SIMD_COEF_32;
if(((unsigned int*)binary)[0] != ((unsigned int*)sout)[x+y*SIMD_COEF_32*4+0*SIMD_COEF_32])
return 0;
if(((unsigned int*)binary)[1] != ((unsigned int*)sout)[x+y*SIMD_COEF_32*4+1*SIMD_COEF_32])
return 0;
if(((unsigned int*)binary)[2] != ((unsigned int*)sout)[x+y*SIMD_COEF_32*4+2*SIMD_COEF_32])
return 0;
if(((unsigned int*)binary)[3] != ((unsigned int*)sout)[x+y*SIMD_COEF_32*4+3*SIMD_COEF_32])
return 0;
return 1;
#else
init_t();
return *(MD5_word *)binary == MD5_out[index][0];
#endif
}
static int cmp_exact(char *source, int index)
{
#ifdef SIMD_PARA_MD5
return 1;
#else
init_t();
return !memcmp(MD5_std_get_binary(source), MD5_out[index],
sizeof(MD5_binary));
#endif
}
static void set_salt(void *salt)
{
#ifdef SIMD_PARA_MD5
memcpy(cursalt, salt, SALT_SIZE);
CryptType = cursalt[8];
cursalt[8] = 0;
#endif
MD5_std_set_salt(salt);
}
static void *get_salt(char *ciphertext) {
return MD5_std_get_salt(ciphertext);
}
static void *get_binary(char *ciphertext) {
return MD5_std_get_binary(ciphertext);
}
struct fmt_main fmt_MD5 = {
{
FORMAT_LABEL,
FORMAT_NAME,
"MD5 " MD5_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 MD5_std_mt || defined(SIMD_PARA_MD5)
FMT_OMP |
#endif
FMT_CASE | FMT_8_BIT,
{ NULL },
tests
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
cryptmd5_common_valid,
fmt_default_split,
get_binary,
get_salt,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash_0,
fmt_default_binary_hash_1,
fmt_default_binary_hash_2,
fmt_default_binary_hash_3,
fmt_default_binary_hash_4,
fmt_default_binary_hash_5,
fmt_default_binary_hash_6
},
salt_hash,
NULL,
set_salt,
set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
get_hash_0,
get_hash_1,
get_hash_2,
get_hash_3,
get_hash_4,
get_hash_5,
get_hash_6
},
cmp_all,
cmp_one,
cmp_exact
}
};
|
DistanceTableData.h
|
//////////////////////////////////////////////////////////////////////////////////////
// This file is distributed under the University of Illinois/NCSA Open Source License.
// See LICENSE file in top directory for details.
//
// Copyright (c) 2016 Jeongnim Kim and QMCPACK developers.
//
// File developed by: Jeremy McMinnis, [email protected], University of Illinois at Urbana-Champaign
// Jeongnim Kim, [email protected], University of Illinois at Urbana-Champaign
// Jaron T. Krogel, [email protected], Oak Ridge National Laboratory
// Mark A. Berrill, [email protected], Oak Ridge National Laboratory
//
// File created by: Jeongnim Kim, [email protected], University of Illinois at Urbana-Champaign
//////////////////////////////////////////////////////////////////////////////////////
#ifndef QMCPLUSPLUS_DISTANCETABLEDATAIMPL_H
#define QMCPLUSPLUS_DISTANCETABLEDATAIMPL_H
#include "Particle/ParticleSet.h"
#include "OhmmsPETE/OhmmsVector.h"
#include "OhmmsPETE/OhmmsMatrix.h"
#include "CPU/SIMD/aligned_allocator.hpp"
#include "OhmmsSoA/VectorSoaContainer.h"
#include <limits>
#include <bitset>
namespace qmcplusplus
{
/** @ingroup nnlist
* @brief Abstract class to manage pair data between two ParticleSets.
*
* Each DistanceTableData object is fined by Source and Target of ParticleSet types.
*
*/
class DistanceTableData
{
public:
static constexpr unsigned DIM = OHMMS_DIM;
using IndexType = QMCTraits::IndexType;
using RealType = QMCTraits::RealType;
using PosType = QMCTraits::PosType;
using DistRow = Vector<RealType, aligned_allocator<RealType>>;
using DisplRow = VectorSoaContainer<RealType, DIM>;
protected:
const ParticleSet* Origin;
int N_sources;
int N_targets;
int N_walkers;
/**defgroup SoA data */
/*@{*/
/** distances_[i][j] , [N_targets][N_sources]
* Note: Derived classes decide if it is a memory view or the actual storage
* For derived AA, only the lower triangle (j<i) is defined and up-to-date after pbyp move.
* The upper triangle is symmetric to the lower one only when the full table is evaluated from scratch.
* Avoid using the upper triangle because we may change the code to only allocate the lower triangle part.
* For derived AB, the full table is up-to-date after pbyp move
*/
std::vector<DistRow> distances_;
/** displacements_[N_targets]x[3][N_sources]
* Note: Derived classes decide if it is a memory view or the actual storage
* displacements_[i][j] = r_A2[j] - r_A1[i], the opposite sign of AoS dr
* For derived AA, A1=A2=A, only the lower triangle (j<i) is defined.
* For derived AB, A1=A, A2=B, the full table is allocated.
*/
std::vector<DisplRow> displacements_;
/** temp_r */
DistRow temp_r_;
/** temp_dr */
DisplRow temp_dr_;
/*@}*/
/** whether full table needs to be ready at anytime or not
* Optimization can be implemented during forward PbyP move when the full table is not needed all the time.
* DT consumers should know if full table is needed or not and request via addTable.
*/
bool need_full_table_;
///name of the table
std::string Name;
public:
///constructor using source and target ParticleSet
DistanceTableData(const ParticleSet& source, const ParticleSet& target)
: Origin(&source), N_sources(0), N_targets(0), N_walkers(0), need_full_table_(false)
{}
///virutal destructor
virtual ~DistanceTableData() = default;
///get need_full_table_
inline bool getFullTableNeeds() const { return need_full_table_; }
///set need_full_table_
inline void setFullTableNeeds(bool is_needed) { need_full_table_ = is_needed; }
///return the name of table
inline const std::string& getName() const { return Name; }
///set the name of table
inline void setName(const std::string& tname) { Name = tname; }
///returns the reference the origin particleset
const ParticleSet& origin() const { return *Origin; }
///returns the number of centers
inline IndexType centers() const { return Origin->getTotalNum(); }
///returns the number of centers
inline IndexType targets() const { return N_targets; }
///returns the number of source particles
inline IndexType sources() const { return N_sources; }
/** return full table distances
*/
const std::vector<DistRow>& getDistances() const { return distances_; }
/** return full table displacements
*/
const std::vector<DisplRow>& getDisplacements() const { return displacements_; }
/** return a row of distances for a given target particle
*/
const DistRow& getDistRow(int iel) const { return distances_[iel]; }
/** return a row of displacements for a given target particle
*/
const DisplRow& getDisplRow(int iel) const { return displacements_[iel]; }
/** return old distances set up by move() for optimized distance table consumers
*/
virtual const DistRow& getOldDists() const
{
APP_ABORT("DistanceTableData::getOldDists is used incorrectly! Contact developers on github.");
return temp_r_; // dummy return to avoid compiler warning.
}
/** return old displacements set up by move() for optimized distance table consumers
*/
virtual const DisplRow& getOldDispls() const
{
APP_ABORT("DistanceTableData::getOldDispls is used incorrectly! Contact developers on github.");
return temp_dr_; // dummy return to avoid compiler warning.
}
/** return the temporary distances when a move is proposed
*/
const DistRow& getTempDists() const { return temp_r_; }
/** return the temporary displacements when a move is proposed
*/
const DisplRow& getTempDispls() const { return temp_dr_; }
/** evaluate the full Distance Table
* @param P the target particle set
*/
virtual void evaluate(ParticleSet& P) = 0;
virtual void mw_evaluate(const RefVector<DistanceTableData>& dt_list, const RefVector<ParticleSet>& p_list)
{
#pragma omp parallel for
for (int iw = 0; iw < dt_list.size(); iw++)
dt_list[iw].get().evaluate(p_list[iw]);
}
/** evaluate the temporary pair relations when a move is proposed
* @param P the target particle set
* @param rnew proposed new position
* @param iat the particle to be moved
* @param prepare_old if true, prepare (temporary) old distances and displacements for using getOldDists and getOldDispls functions in acceptMove.
*
* Note: some distance table consumers (WaveFunctionComponent) have optimized code paths which require prepare_old = true for accepting a move.
* Drivers/Hamiltonians know whether moves will be accepted or not and manage this flag when calling ParticleSet::makeMoveXXX functions.
*/
virtual void move(const ParticleSet& P, const PosType& rnew, const IndexType iat = 0, bool prepare_old = true) = 0;
/** update the distance table by the pair relations if a move is accepted
* @param iat the particle with an accepted move
* @param partial_update If true, rows after iat will not be updated. If false, upon accept a move, the full table should be up-to-date
*/
virtual void update(IndexType jat, bool partial_update = false) = 0;
/** build a compact list of a neighbor for the iat source
* @param iat source particle id
* @param rcut cutoff radius
* @param jid compressed index
* @param dist compressed distance
* @param displ compressed displacement
* @return number of target particles within rcut
*/
virtual size_t get_neighbors(int iat,
RealType rcut,
int* restrict jid,
RealType* restrict dist,
PosType* restrict displ) const
{
return 0;
}
/** find the first nearest neighbor
* @param iat source particle id
* @param r distance
* @param dr displacement
* @param newpos if true, use the data in temp_r_ and temp_dr_ for the proposed move.
* if false, use the data in distance_[iat] and displacements_[iat]
* @return the id of the nearest particle, -1 not found
*/
virtual int get_first_neighbor(IndexType iat, RealType& r, PosType& dr, bool newpos) const
{
APP_ABORT("DistanceTableData::get_first_neighbor is not implemented in calling base class");
return 0;
}
inline void print(std::ostream& os)
{
APP_ABORT("DistanceTableData::print is not supported")
//os << "Table " << Origin->getName() << std::endl;
//for (int i = 0; i < r_m.size(); i++)
// os << r_m[i] << " ";
//os << std::endl;
}
/**resize the storage
*@param npairs number of pairs which is evaluated by a derived class
*@param nw number of copies
*
* The data for the pair distances, displacements
*and the distance inverses are stored in a linear storage.
* The logical view of these storages is (ipair,iwalker),
* where 0 <= ipair < M[N[SourceIndex]] and 0 <= iwalker < N[WalkerIndex]
* This scheme can handle both dense and sparse distance tables,
* and full or half of the pairs.
* Note that this function is protected and the derived classes are
* responsible to call this function for memory allocation and any
* change in the indices N.
*/
void resize(int npairs, int nw) { N_walkers = nw; }
};
} // namespace qmcplusplus
#endif
|
rose_example2_refactored_OpenMP.c
|
#include <omp.h>
#include <stdio.h>
#include <sys/time.h>
#define N 30000
int main()
{
int i;
int j;
double x[30002UL][30002UL];
double y[30002UL][30002UL];
double tmp[30002UL][30002UL];
double sum = 0;
//for timing the code section
struct timeval start;
struct timeval end;
float delta;
for (i = 0; i <= 30000 + 1; i++) {
for (j = 0; j <= 30000 + 1; j++) {
x[i][j] = (((double )((i + j) % 3)) - 0.9999);
y[i][j] = (x[i][j] + 0.0001);
}
}
//start timer and calculation
gettimeofday(&start,0);
#pragma omp parallel default(none) shared(tmp,x,y) private(j,i)
{
#pragma omp for
for (j = 1; j < 30000 + 1; j++) {
for (i = 1; i < 30000 + 1; i++) {
tmp[i][j] = (0.167 * (((((x[i][j] + x[i - 1][j]) + x[i + 1][j]) + x[i][j - 1]) + x[i][j + 1]) + y[i + 1][j]));
}
}
}
#pragma omp parallel default(none) shared(sum,y,tmp) private(j,i)
{
#pragma omp for reduction ( + :sum)
for (j = 1; j < 30000 + 1; j++) {
for (i = 1; i < 30000 + 1; i++) {
y[i][j] = tmp[i][j];
sum = (sum + tmp[i][j]);
}
}
}
//stop timer and calculation
gettimeofday(&end,0);
delta = (((((end.tv_sec - start.tv_sec) * 1000000u) + end.tv_usec) - start.tv_usec) / 1.e6);
printf("\nThe total sum is: %lf\n",sum);
//print time to completion
printf("run time = %fs\n",delta);
return 0;
}
|
DRB060-matrixmultiply-orig-no.c
|
/*
Copyright (c) 2017, Lawrence Livermore National Security, LLC.
Produced at the Lawrence Livermore National Laboratory
Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund,
Markus Schordan, and Ian Karlin
(email: [email protected], [email protected], [email protected],
[email protected], [email protected])
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.
*/
/*
Classic i-k-j matrix multiplication
*/
#include <stdio.h>
#define N 100
#define M 100
#define K 100
#include <omp.h>
double a[100][100];
double b[100][100];
double c[100][100];
int init()
{
int i;
int j;
int k;
#pragma omp parallel for private (i,j)
for (i = 0; i <= 99; i += 1) {
#pragma omp parallel for private (j)
for (j = 0; j <= 99; j += 1) {
a[i][j] = ((double )i) * j;
b[i][j] = ((double )i) * j;
c[i][j] = ((double )i) * j;
}
}
return 0;
}
int mmm()
{
int i;
int j;
int k;
#pragma omp parallel for private (i,j,k)
for (i = 0; i <= 99; i += 1) {
for (k = 0; k <= 99; k += 1) {
#pragma omp parallel for private (j)
for (j = 0; j <= 99; j += 1) {
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
return 0;
}
int print()
{
int i;
int j;
int k;
for (i = 0; i <= 99; i += 1) {
for (j = 0; j <= 99; j += 1) {
printf("%lf %lf %lf\n",c[i][j],a[i][j],b[i][j]);
}
}
return 0;
}
int main()
{
init();
mmm();
print();
return 0;
}
|
cpu_solver.c
|
/** \file cpu_solver.c
* \brief Codice host degli algoritmo del solver.
*
*
*/
#ifndef MAX_THREADS
#define MAX_THREADS 16
#endif
#ifndef CHUNK_SIZE
#define CHUNK_SIZE 4
#endif
#include "cpu_solver.h"
#include <omp.h>
extern char* str;
extern int counter_nodi;
extern int counter_nodi0;
//extern int counter_nodi0_1;
//extern int counter_nodi0_2;
extern int num_nodi;
extern int num_archi;
extern int max_pesi;
extern int MG_pesi;
extern char *nodeFlags;
extern int *host_csrPtrInSuccLists;
extern int *host_csrSuccLists;
extern int *host_csrPesiArchi;
extern int *host_cscPtrInPredLists;
extern int *host_cscPredLists;
extern int *host_cscPesiArchiPred;
extern int numLowInDegree[4];
extern int numAllInDegree[LEN_DEGREEHIST];
extern int numAllOutDegree[LEN_DEGREEHIST];
extern int *host_ResNodeValues1;
extern int *host_ResNodeValues2;
extern int *host_ResNodeValuesAux;
extern int *host_csrDataArchiAux;
extern uint timeout_expired;
extern config configuration;
extern stat statistics;
void EG0_scpu_solver() {
int idx;
int idy;
int val;
long max_loop = configuration.max_loop_val;
long loop;
int *data1;
int *data2;
int *temp;
int tempval;
int flag1=0;
printf("Initializing cpu EG0 solver.\n");
max_loop = aggiorna_max_loop((long)num_archi, (long)num_nodi, (long)MG_pesi, max_loop);
data1 = host_ResNodeValues1;
data2 = host_ResNodeValues2;
for (idx=0; idx<counter_nodi; idx++) {
data1[idx] =0;
data2[idx] =0;
}
printf("Running EG0 on CPU. (MG_pesi=%d max_loop=%ld num nodes=%d num archi=%d max weight=%d\n", MG_pesi, max_loop, num_nodi, num_archi, max_pesi); fflush(stdout);
for (loop=1; loop<=max_loop; loop++) {
flag1=0;
for (idx=0; idx<counter_nodi; idx++) {
tempval = OMINUS(data1[host_csrSuccLists[host_csrPtrInSuccLists[idx]]] , host_csrPesiArchi[host_csrPtrInSuccLists[idx]]);
for (idy=(host_csrPtrInSuccLists[idx])+1; idy < host_csrPtrInSuccLists[idx+1]; idy++) {
val = OMINUS(data1[host_csrSuccLists[idy]] , host_csrPesiArchi[idy]);
if ((idx<counter_nodi0) && (tempval > val)) {
tempval = val;
}
if ((idx>=counter_nodi0) && (tempval < val)) {
tempval = val;
}
}
if (data2[idx] < tempval) {
flag1=1;
data2[idx] = tempval;
}
}
temp = data1; data1 = data2; data2 = temp; //swap ruoli degli array
if (flag1 == 0) {break;}
if (timeout_expired == 1) {break;}
}
if ((max_loop%2) != 0) { //se numero loop e' dispari, il risultato e' nell'array host_ResNodeValues2[]. Lo metto in host_ResNodeValues1[]
temp = host_ResNodeValues1;
host_ResNodeValues1 = host_ResNodeValues2;
host_ResNodeValues2 = temp;
}
printf("End EG0 on CPU after %ld loops (each loop involves all nodes) (flag1=%d)\n", loop-1, flag1);
statistics.processedNodes = ((long)(loop-1))*((long)num_nodi);
}
void EG0_cpu_solver() {
int idx;
int idy;
long max_loop = configuration.max_loop_val;
long loop;
int *data1;
int *data2;
int *temp;
// Varaible for OpenMP thread management
int flag_per_thread[MAX_THREADS];
static int tid;
static int nthx=1;
int c=0;
for (c = 0; c < MAX_THREADS ; c++) flag_per_thread[c] = 0;
#pragma omp threadprivate(tid)
#pragma omp parallel
{
tid = omp_get_thread_num();
nthx = omp_get_num_threads();
nthx = (nthx < MAX_THREADS) ? nthx : MAX_THREADS;
}
printf("Initializing cpu EG0 solver using (%d Mthreads).\n", nthx);
max_loop = aggiorna_max_loop((long)num_archi, (long)num_nodi, (long)MG_pesi, max_loop);
data1 = host_ResNodeValues1;
data2 = host_ResNodeValues2;
for (idx=0; idx<counter_nodi; idx++) {
data1[idx] =0;
data2[idx] =0;
}
//printf("Running EG0 on CPU. (MG_pesi=%d max_loop=%ld num nodes=%d num archi=%d max weight=%d\n", MG_pesi, max_loop, num_nodi, num_archi, max_pesi); fflush(stdout);
for (loop=1; loop<=max_loop; loop++) {
for (c = 0; c < nthx; c++) flag_per_thread[c] = 0;
#pragma omp parallel for schedule(guided, CHUNK_SIZE)
for (idx=0; idx<counter_nodi; idx++) {
int tempval = OMINUS(data1[host_csrSuccLists[host_csrPtrInSuccLists[idx]]] , host_csrPesiArchi[host_csrPtrInSuccLists[idx]]);
for (idy=(host_csrPtrInSuccLists[idx])+1; idy < host_csrPtrInSuccLists[idx+1]; idy++) {
int val = OMINUS(data1[host_csrSuccLists[idy]] , host_csrPesiArchi[idy]);
if ((idx<counter_nodi0) && (tempval > val)) {
tempval = val;
}
if ((idx>=counter_nodi0) && (tempval < val)) {
tempval = val;
}
}
if (data2[idx] < tempval) {
flag_per_thread[tid]=1;
data2[idx] = tempval;
}
}
int check = 0;
temp = data1; data1 = data2; data2 = temp; //swap ruoli degli array
for (c = 0; c < nthx; c++){
if (flag_per_thread[c] == 0){
check += flag_per_thread[c];
}
else {
check += flag_per_thread[c];
break;
}
}
if (check == 0) {break;}
if (timeout_expired == 1) {break;}
}
if ((max_loop%2) != 0) { //se numero loop e' dispari, il risultato e' nell'array host_ResNodeValues2[]. Lo metto in host_ResNodeValues1[]
temp = host_ResNodeValues1;
host_ResNodeValues1 = host_ResNodeValues2;
host_ResNodeValues2 = temp;
}
printf("End EG0 on CPU after %ld loops (each loop involves all nodes)\n", loop-1);
statistics.processedNodes = ((long)(loop-1))*((long)num_nodi);
}
void EG_cpu_solver() {
int idx;
int idy;
int val;
long max_loop = configuration.max_loop_val;
long loop;
int *data1 = host_ResNodeValues1; // vettore dei risultati (f(v)) inizialmente gia' azzerato
int temp;
int flag1=0;
int *stackL = host_csrDataArchiAux; //uso spazio host_csrDataArchiAux[] per memorizzare l'insieme L dei nodi con (potenziali) "inconsistenze"
//inoltre uso il vettore di flags nodeFlags[] come bitmap per evitare di inserire doppi in stackL[]
// N.B:: dato che ogni nodo ha in-degree e out-degree non nulli si ha num_archi>=num_nodi
int top_stackL = 0; // altezza dello stackL //SCEGLIENDO questa si usa L come stack
//int *queueL = stackL; // invece di stack uso queue //SCEGLIENDO questa si usa L come queue
int in_queueL = 0;
int out_queueL = 0;
int len_queueL = 0;
// Ora usa L come queue, le linee di codice per usare L come stack sono commentate.
// Sperimentalmente, sembra che queue si comporti in media meglio di stack (per le istanze viste)
printf("Initializing cpu EG solver.\n");
max_loop = aggiorna_max_loop((long)num_archi, (long)num_nodi, (long)MG_pesi, max_loop);
// inizializza flags e stackL[] (= i nodi "inconsistenti")
for (idx=0; idx<counter_nodi0; idx++) {
temp=1; // finora sono tutti negativi
idy=(host_csrPtrInSuccLists[idx]);
while ((temp==1) && (idy < host_csrPtrInSuccLists[idx+1])) {
if (host_csrPesiArchi[idy] >= 0) {
temp = 0;
}
idy++;
}
if (temp==1) { // tutti outedges negativi
nodeFlags[idx]=1;
stackL[top_stackL++] = idx;
}
}
for (idx=counter_nodi0; idx<counter_nodi; idx++) {
temp=1; // finora sono nessun negativo
idy=(host_csrPtrInSuccLists[idx]);
while ((temp==1) && (idy < host_csrPtrInSuccLists[idx+1])) {
if (host_csrPesiArchi[idy] < 0) {
temp = 0;
}
idy++;
}
if (temp==0) { // almeno un outedge negativo
nodeFlags[idx]=1;
stackL[top_stackL++] = idx;
}
}
in_queueL = top_stackL;
out_queueL = 0;
len_queueL = in_queueL-out_queueL;
host_csr2csc(num_nodi, num_nodi, num_archi, host_csrPesiArchi, host_csrSuccLists, host_csrPtrInSuccLists, host_cscPesiArchiPred, host_cscPredLists, host_cscPtrInPredLists);
/* Calcolo gli in-degree */
{ int i,d;
for (i=0; i<num_nodi; i++) {
d = host_cscPtrInPredLists[i+1] - host_cscPtrInPredLists[i];
if (d<(LEN_DEGREEHIST-1)) { (numAllInDegree[d])++;
} else { (numAllInDegree[LEN_DEGREEHIST-1])++; }
if (d<4) { (numLowInDegree[d])++; }
}
printf("\tLow in-degree: 0: %d \t1: %d \t2: %d \t3: %d\n", numLowInDegree[0], numLowInDegree[1], numLowInDegree[2], numLowInDegree[3]);fflush(stdout);
}
if (configuration.print_degree_hist == YES_PRINT_DEGREEHIST) {
int hist;
printf("In degrees:,%s,", (configuration.stdinputsource == 1)?"stdin":configuration.filename);
for (hist=0; hist<(LEN_DEGREEHIST-1); hist++) {
printf("%d,", numAllInDegree[hist]);
}
printf("%d\n", numAllInDegree[LEN_DEGREEHIST-1]);
printf("Out degrees:,%s,", (configuration.stdinputsource == 1)?"stdin":configuration.filename);
for (hist=0; hist<(LEN_DEGREEHIST-1); hist++) {
printf("%d,", numAllOutDegree[hist]);
}
printf("%d\n", numAllOutDegree[LEN_DEGREEHIST-1]);
}
// Loop di calcolo dell'initial credit problem:
printf("Running EG on CPU. (MG_pesi=%d max_loop=%ld num nodes=%d num archi=%d max weight=%d\n", MG_pesi, max_loop, num_nodi, num_archi, max_pesi); fflush(stdout);
loop=1;
//while ((top_stackL>0) && (loop<=max_loop)) {
while ((len_queueL>0) && (loop<=max_loop)) {
// DUE modi (a seconda che L sia usato come stack o queue) per non selezionare gli elementi di L in ordine, ma pseudo-casualmente:
//int r = rand()%top_stackL; int tt = stackL[r]; stackL[r] = stackL[top_stackL]; stackL[top_stackL] = tt;
//int r = rand()%len_queueL; int tt = stackL[(out_queueL+r)%num_nodi]; stackL[(out_queueL+r)%num_nodi] = stackL[out_queueL]; stackL[out_queueL] = tt;
// Solo per sperimentare. Ora DISATTIVATI.
loop++;
flag1=0;
//idx = stackL[--top_stackL]; //preleva uno dei nodi da processare usando L come stack
idx = stackL[out_queueL]; out_queueL=(out_queueL+1)%num_nodi; //preleva uno dei nodi da processare usando L come queue
len_queueL--;
nodeFlags[idx]=0; //riazzero per il ciclo successivo
temp = OMINUS(data1[host_csrSuccLists[host_csrPtrInSuccLists[idx]]] , host_csrPesiArchi[host_csrPtrInSuccLists[idx]]);
for (idy=(host_csrPtrInSuccLists[idx])+1; idy < host_csrPtrInSuccLists[idx+1]; idy++) {
val = OMINUS(data1[host_csrSuccLists[idy]] , host_csrPesiArchi[idy]);
if ((idx<counter_nodi0) && (temp > val)) {
temp = val;
}
if ((idx>=counter_nodi0) && (temp < val)) {
temp = val;
}
}
// aggiunge predecessori del nodo aggiornato
if (data1[idx] < temp) { // il valore aumenta
//printf(" %d : %d --> %d)\n",idx,data1[idx],temp);
data1[idx] = temp;
flag1=1;
// aggiugi PREDs in stackL GREZZO: aggiunge sempre!!! non usa counter come nell'articolo di Raffaella&C.
int idz;
for (idz=host_cscPtrInPredLists[idx]; idz<host_cscPtrInPredLists[idx+1]; idz++) {
if (nodeFlags[host_cscPredLists[idz]] == 0) {
//stackL[top_stackL++] = host_cscPredLists[idz]; // L come stack
stackL[in_queueL] = host_cscPredLists[idz]; in_queueL=(in_queueL+1)%num_nodi; // L come queue
nodeFlags[host_cscPredLists[idz]]=1;
len_queueL++; // L come queue
}
}
}
//if ((flag1 == 0) && (top_stackL==0)) {break;} // L come stack
if ((flag1 == 0) && (len_queueL==0)) {break;} // L come queue
if (timeout_expired == 1) {break;}
}
printf("End EG on CPU after %ld loops (each loop involves one node only) (flag1=%d)\n", loop-1, flag1);
statistics.processedNodes = ((long)(loop-1));
}
void cpu_solver() {
struct timeb tp;
double deltacpusoltime;
ftime(&tp);
deltacpusoltime = ((double)((long int)tp.time));
deltacpusoltime += ((double)tp.millitm)/1000;
switch (configuration.algoritmo) {
case ALGOR_EG0: // versione di EG naive (presa da master per facilitare multithread)
EG0_cpu_solver();
break;
case ALGOR_EG:
EG_cpu_solver();
break;
default:
EG_cpu_solver();
break;
}
ftime(&tp);
statistics.solvingtime = ((((double)((long int)tp.time)) + (((double)tp.millitm)/1000)) - deltacpusoltime);
}
|
omp_task.c
|
/* OpenMP TASK Construct Example */
#include <stdio.h>
#include <omp.h>
int main () {
#pragma omp parallel
{
#pragma omp single
{
printf("A ");
#pragma omp task
{printf("race ");}
#pragma omp task
{printf("car ");}
}
} // End of parallel region
printf("\n");
return 0;
}
|
GB_binop__lt_fp32.c
|
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__lt_fp32)
// A.*B function (eWiseMult): GB (_AemultB)
// A.*B function (eWiseMult): GB (_AemultB_02__lt_fp32)
// A.*B function (eWiseMult): GB (_AemultB_03__lt_fp32)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__lt_fp32)
// A*D function (colscale): GB (_AxD__lt_fp32)
// D*A function (rowscale): GB (_DxB__lt_fp32)
// C+=B function (dense accum): GB (_Cdense_accumB__lt_fp32)
// C+=b function (dense accum): GB (_Cdense_accumb__lt_fp32)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__lt_fp32)
// C=scalar+B GB (_bind1st__lt_fp32)
// C=scalar+B' GB (_bind1st_tran__lt_fp32)
// C=A+scalar GB (_bind2nd__lt_fp32)
// C=A'+scalar GB (_bind2nd_tran__lt_fp32)
// C type: bool
// A type: float
// B,b type: float
// BinaryOp: cij = (aij < bij)
#define GB_ATYPE \
float
#define GB_BTYPE \
float
#define GB_CTYPE \
bool
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
0
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
0
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
float aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
float bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
bool 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) ;
// 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_LT || GxB_NO_FP32 || GxB_NO_LT_FP32)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_ewise3_noaccum__lt_fp32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_dense_ewise3_noaccum_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__lt_fp32)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if 0
{
#include "GB_dense_subassign_23_template.c"
}
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__lt_fp32)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if 0
{
// get the scalar b for C += b, of type float
float bwork = (*((float *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__lt_fp32)
(
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
bool *restrict Cx = (bool *) 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__lt_fp32)
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool *restrict Cx = (bool *) C->x ;
#include "GB_AxB_rowscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__lt_fp32)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
#include "GB_add_template.c"
GB_FREE_WORK ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C = A.*B or C<M> = A.*B
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_01__lt_fp32)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_01_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__lt_fp32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_03__lt_fp32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_03_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__lt_fp32)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__lt_fp32)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool *Cx = (bool *) Cx_output ;
float x = (*((float *) x_input)) ;
float *Bx = (float *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Bb, p)) continue ;
float bij = Bx [p] ;
Cx [p] = (x < bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__lt_fp32)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
bool *Cx = (bool *) Cx_output ;
float *Ax = (float *) Ax_input ;
float y = (*((float *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
float aij = Ax [p] ;
Cx [p] = (aij < y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
float aij = Ax [pA] ; \
Cx [pC] = (x < aij) ; \
}
GrB_Info GB (_bind1st_tran__lt_fp32)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
float
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
float x = (*((const float *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
float
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
float aij = Ax [pA] ; \
Cx [pC] = (aij < y) ; \
}
GrB_Info GB (_bind2nd_tran__lt_fp32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
float y = (*((const float *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
DRB010-lastprivatemissing-var-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: [email protected], [email protected], [email protected],
[email protected], [email protected])
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 loop has loop-carried output-dependence due to x=... at line 63.
The problem can be solved by using lastprivate(x) .
Data race pair: x@63:5 vs. x@63:5
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
int i,x;
int len = 10000;
if (argc>1)
len = atoi(argv[1]);
#pragma omp parallel for private (i)
for (i=0;i<len;i++)
x=i;
printf("x=%d",x);
return 0;
}
|
IPB2_fmt_plug.c
|
/*
* IPB2_fmt.c (version 4)
*
* Invision Power Board 2.x salted MD5 module for Solar Designer's JtR
* Uses Solar Designer's MD5 implementation.
* regenrecht at o2.pl, Jan 2006
*
* Hashes list should have form of username:$IPB2$salt$hash
* Values to be taken from IPB database, where:
* salt = bin2hex(ibf_members_converge.converge_pass_salt)
* hash = ibf_members_converge.converge_pass_hash
*/
#if FMT_EXTERNS_H
extern struct fmt_main fmt_IPB2;
#elif FMT_REGISTERS_H
john_register_one(&fmt_IPB2);
#else
#include <string.h>
#include "arch.h"
#include "misc.h"
#include "md5.h"
#include "common.h"
#include "formats.h"
#include "simd-intrinsics.h"
#if defined(_OPENMP)
#include <omp.h>
static unsigned int omp_t = 1;
#ifdef SIMD_COEF_32
#ifndef OMP_SCALE
#define OMP_SCALE 512 // Tuned K8-dual HT
#endif
#else
#ifndef OMP_SCALE
#define OMP_SCALE 256
#endif
#endif
#else
#define omp_t 1
#endif
#include "memdbg.h"
#define FORMAT_LABEL "ipb2"
#define FORMAT_NAME "Invision Power Board 2.x"
#define ALGORITHM_NAME "MD5 " MD5_ALGORITHM_NAME
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH 0
#define BINARY_ALIGN 4
#define BINARY_SIZE 16
#define MD5_HEX_SIZE (BINARY_SIZE * 2)
#define SALT_SIZE MD5_HEX_SIZE
#define SALT_ALIGN 4
#define SALT_LENGTH 5
#define PLAINTEXT_LENGTH 31
#define CIPHERTEXT_LENGTH (1 + 4 + 1 + SALT_LENGTH * 2 + 1 + MD5_HEX_SIZE)
#ifdef SIMD_COEF_32
#define NBKEYS (SIMD_COEF_32 * SIMD_PARA_MD5)
#define MIN_KEYS_PER_CRYPT NBKEYS
#define MAX_KEYS_PER_CRYPT NBKEYS
#define GETPOS(i, index) ( (index&(SIMD_COEF_32-1))*4 + ((i)&60)*SIMD_COEF_32 + ((i)&3) + (unsigned int)index/SIMD_COEF_32*64*SIMD_COEF_32 )
#define GETOUTPOS(i, index) ( (index&(SIMD_COEF_32-1))*4 + ((i)&12)*SIMD_COEF_32 + ((i)&3) + (unsigned int)index/SIMD_COEF_32*16*SIMD_COEF_32 )
#else
#define NBKEYS 1
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
#endif
static struct fmt_tests tests[] = {
{"$IPB2$2e75504633$d891f03a7327639bc632d62a7f302604", "welcome"},
{"$IPB2$735a213a4e$4f23de7bb115139660db5e953153f28a", "enter"},
{"$IPB2$5d75343455$de98ba8ca7bb16f43af05e9e4fb8afee", "matrix"},
{"$IPB2$556c576c39$16d4f29c71b05bd75e61d0254800bfa3", "123456"},
{NULL}
};
static const char itoa16_shr_04[] =
"0000000000000000"
"1111111111111111"
"2222222222222222"
"3333333333333333"
"4444444444444444"
"5555555555555555"
"6666666666666666"
"7777777777777777"
"8888888888888888"
"9999999999999999"
"aaaaaaaaaaaaaaaa"
"bbbbbbbbbbbbbbbb"
"cccccccccccccccc"
"dddddddddddddddd"
"eeeeeeeeeeeeeeee"
"ffffffffffffffff";
static const char itoa16_and_0f[] =
"0123456789abcdef"
"0123456789abcdef"
"0123456789abcdef"
"0123456789abcdef"
"0123456789abcdef"
"0123456789abcdef"
"0123456789abcdef"
"0123456789abcdef"
"0123456789abcdef"
"0123456789abcdef"
"0123456789abcdef"
"0123456789abcdef"
"0123456789abcdef"
"0123456789abcdef"
"0123456789abcdef"
"0123456789abcdef";
static char (*saved_plain)[PLAINTEXT_LENGTH + 1];
#if SIMD_COEF_32
static unsigned char *saved_key;
static unsigned char *key_buf;
static unsigned char *empty_key;
static unsigned char *crypt_key;
static ARCH_WORD_32 *cur_salt;
static int new_salt;
static int new_key;
#else
static char (*saved_key)[2*MD5_HEX_SIZE];
static ARCH_WORD_32 (*crypt_key)[BINARY_SIZE / sizeof(ARCH_WORD_32)];
#endif
static void init(struct fmt_main *self)
{
#if SIMD_COEF_32
unsigned int i;
#endif
#if defined (_OPENMP)
omp_t = omp_get_max_threads();
self->params.min_keys_per_crypt *= omp_t;
omp_t *= OMP_SCALE;
// these 2 lines of change, allows the format to work with
// [Options] FormatBlockScaleTuneMultiplier= without other format change
omp_t *= self->params.max_keys_per_crypt;
omp_t /= NBKEYS;
self->params.max_keys_per_crypt = (omp_t*NBKEYS);
#endif
#if SIMD_COEF_32
key_buf = mem_calloc_align(self->params.max_keys_per_crypt,
64, MEM_ALIGN_SIMD);
empty_key = mem_calloc_align(64 * NBKEYS,
sizeof(empty_key), MEM_ALIGN_SIMD);
for (i = 0; i < NBKEYS; ++i) {
empty_key[GETPOS(0, i)] = 0x80;
((unsigned int*)empty_key)[14*SIMD_COEF_32 + (i&(SIMD_COEF_32-1)) + i/SIMD_COEF_32*16*SIMD_COEF_32] = (2 * MD5_HEX_SIZE)<<3;
}
crypt_key = mem_calloc_align(self->params.max_keys_per_crypt,
BINARY_SIZE, MEM_ALIGN_SIMD);
saved_key = mem_calloc_align(self->params.max_keys_per_crypt,
64, MEM_ALIGN_SIMD);
#else
crypt_key = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*crypt_key));
saved_key = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*saved_key));
#endif
saved_plain = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*saved_plain));
}
static void done(void)
{
MEM_FREE(saved_plain);
MEM_FREE(saved_key);
MEM_FREE(crypt_key);
#if SIMD_COEF_32
MEM_FREE(empty_key);
MEM_FREE(key_buf);
#endif
}
static int valid(char *ciphertext, struct fmt_main *self)
{
if (strncmp(ciphertext, "$IPB2$", 6) != 0)
return 0;
if (strlen(ciphertext) != CIPHERTEXT_LENGTH)
return 0;
if (ciphertext[16] != '$')
return 0;
if (strspn(ciphertext+6, HEXCHARS_lc) != SALT_LENGTH*2)
return 0;
if (strspn(ciphertext+17, HEXCHARS_lc) != MD5_HEX_SIZE)
return 0;
return 1;
}
static void *get_binary(char *ciphertext)
{
static ARCH_WORD_32 out[BINARY_SIZE/4];
unsigned char *binary_cipher = (unsigned char*)out;
int i;
ciphertext += 17;
for (i = 0; i < BINARY_SIZE; ++i)
binary_cipher[i] =
(atoi16[ARCH_INDEX(ciphertext[i*2])] << 4)
+ atoi16[ARCH_INDEX(ciphertext[i*2+1])];
return (void*)out;
}
static void *get_salt(char *ciphertext)
{
static ARCH_WORD_32 hex_salt[MD5_HEX_SIZE/4];
unsigned char binary_salt[SALT_LENGTH];
unsigned char salt_hash[BINARY_SIZE];
static MD5_CTX ctx;
int i;
ciphertext += 6;
for (i = 0; i < SALT_LENGTH; ++i)
binary_salt[i] =
(atoi16[ARCH_INDEX(ciphertext[i*2])] << 4)
+ atoi16[ARCH_INDEX(ciphertext[i*2+1])];
MD5_Init(&ctx);
MD5_Update(&ctx, binary_salt, SALT_LENGTH);
MD5_Final(salt_hash, &ctx);
for (i = 0; i < BINARY_SIZE; ++i) {
((char*)hex_salt)[i*2] = itoa16[ARCH_INDEX(salt_hash[i] >> 4)];
((char*)hex_salt)[i*2+1] = itoa16[ARCH_INDEX(salt_hash[i] & 0x0f)];
}
return (void*)hex_salt;
}
static void set_salt(void *salt)
{
#ifdef SIMD_COEF_32
cur_salt = salt;
new_salt = 1;
#else
int index;
for (index = 0; index < omp_t * MAX_KEYS_PER_CRYPT; index++)
memcpy(saved_key[index], salt, MD5_HEX_SIZE);
#endif
}
#ifndef SIMD_COEF_32
static inline int strnfcpy_count(char *dst, char *src, int size)
{
char *dptr = dst, *sptr = src;
int count = size;
while (count--)
if (!(*dptr++ = *sptr++)) break;
return size-count-1;
}
#endif
static void set_key(char *key, int index)
{
#ifdef SIMD_COEF_32
strcpy(saved_plain[index], key);
new_key = 1;
#else
unsigned char key_hash[BINARY_SIZE];
unsigned char *kh = key_hash;
unsigned char *key_ptr = (unsigned char*)saved_key[index] + MD5_HEX_SIZE;
unsigned char v;
int i, len;
MD5_CTX ctx;
len = strnfcpy_count(saved_plain[index], key, PLAINTEXT_LENGTH);
MD5_Init(&ctx);
MD5_Update(&ctx, key, len);
MD5_Final(key_hash, &ctx);
for (i = 0; i < BINARY_SIZE; ++i) {
v = *kh++;
*key_ptr++ = itoa16_shr_04[ARCH_INDEX(v)];
*key_ptr++ = itoa16_and_0f[ARCH_INDEX(v)];
}
#endif
}
static char *get_key(int index)
{
return saved_plain[index];
}
static int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
#ifdef SIMD_COEF_32
#if defined(_OPENMP)
int t;
#pragma omp parallel for
for (t = 0; t < omp_t; t++)
#define ti (t*NBKEYS+index)
#else
#define t 0
#define ti index
#endif
{
unsigned int index, i;
if (new_salt)
for (index = 0; index < NBKEYS; index++) {
const ARCH_WORD_32 *sp = cur_salt;
ARCH_WORD_32 *kb = (ARCH_WORD_32*)&saved_key[GETPOS(0, ti)];
for (i = 0; i < MD5_HEX_SIZE / 4; i++, kb += SIMD_COEF_32)
*kb = *sp++;
}
if (new_key)
for (index = 0; index < NBKEYS; index++) {
const ARCH_WORD_32 *key = (ARCH_WORD_32*)saved_plain[ti];
ARCH_WORD_32 *kb = (ARCH_WORD_32*)&key_buf[GETPOS(0, ti)];
ARCH_WORD_32 *keybuffer = kb;
int len, temp;
len = 0;
while((unsigned char)(temp = *key++)) {
if (!(temp & 0xff00)) {
*kb = (unsigned char)temp | (0x80 << 8);
len++;
goto key_cleaning;
}
if (!(temp & 0xff0000)) {
*kb = (unsigned short)temp | (0x80 << 16);
len+=2;
goto key_cleaning;
}
if (!(temp & 0xff000000)) {
*kb = temp | (0x80U << 24);
len+=3;
goto key_cleaning;
}
*kb = temp;
len += 4;
kb += SIMD_COEF_32;
}
*kb = 0x00000080;
key_cleaning:
kb += SIMD_COEF_32;
while(*kb) {
*kb = 0;
kb += SIMD_COEF_32;
}
keybuffer[14*SIMD_COEF_32] = len << 3;
}
SIMDmd5body(&key_buf[t*NBKEYS*64], (unsigned int*)&crypt_key[t*NBKEYS*16], NULL, SSEi_MIXED_IN);
for (index = 0; index < NBKEYS; index++) {
// Somehow when I optimised this it got faster in Valgrind but slower IRL
for (i = 0; i < BINARY_SIZE; i++) {
unsigned char v = crypt_key[GETOUTPOS(i, ti)];
saved_key[GETPOS(MD5_HEX_SIZE + 2 * i, ti)] = itoa16_shr_04[ARCH_INDEX(v)];
saved_key[GETPOS(MD5_HEX_SIZE + 2 * i + 1, ti)] = itoa16_and_0f[ARCH_INDEX(v)];
}
}
SIMDmd5body(&saved_key[t*NBKEYS*64], (unsigned int*)&crypt_key[t*NBKEYS*16], NULL, SSEi_MIXED_IN);
SIMDmd5body(empty_key, (unsigned int*)&crypt_key[t*NBKEYS*16], (unsigned int*)&crypt_key[t*NBKEYS*16], SSEi_RELOAD|SSEi_MIXED_IN);
}
//dump_stuff_mmx_msg("\nfinal ", saved_key, 64, count-1);
//dump_out_mmx_msg("result", crypt_key, 16, count-1);
new_salt = new_key = 0;
#else
#ifdef _OPENMP
int index;
#pragma omp parallel for
for (index = 0; index < count; index++)
#else
#define index 0
#endif
{
MD5_CTX ctx;
MD5_Init(&ctx);
MD5_Update(&ctx, saved_key[index], MD5_HEX_SIZE * 2);
MD5_Final((unsigned char*)crypt_key[index], &ctx);
}
#undef index
#endif
return count;
}
static int cmp_all(void *binary, int count) {
#ifdef SIMD_COEF_32
unsigned int x,y=0;
#ifdef _OPENMP
for(;y<SIMD_PARA_MD5*omp_t;y++)
#else
for(;y<SIMD_PARA_MD5;y++)
#endif
for(x = 0; x < SIMD_COEF_32; x++)
{
if( ((ARCH_WORD_32*)binary)[0] == ((ARCH_WORD_32*)crypt_key)[y*SIMD_COEF_32*4+x] )
return 1;
}
return 0;
#else
int index;
for (index = 0; index < count; index++)
if (!memcmp(binary, crypt_key[index], BINARY_SIZE))
return 1;
return 0;
#endif
}
static int cmp_exact(char *source, int index)
{
return 1;
}
static int cmp_one(void * binary, int index)
{
#ifdef SIMD_COEF_32
unsigned int i,x,y;
x = index&(SIMD_COEF_32-1);
y = (unsigned int)index/SIMD_COEF_32;
for(i=0;i<(BINARY_SIZE/4);i++)
if ( ((ARCH_WORD_32*)binary)[i] != ((ARCH_WORD_32*)crypt_key)[y*SIMD_COEF_32*4+i*SIMD_COEF_32+x] )
return 0;
return 1;
#else
return !memcmp(binary, crypt_key[index], BINARY_SIZE);
#endif
}
#ifdef SIMD_COEF_32
#define HASH_OFFSET (index&(SIMD_COEF_32-1))+((unsigned int)index/SIMD_COEF_32)*SIMD_COEF_32*4
static int get_hash_0(int index) { return ((ARCH_WORD_32 *)crypt_key)[HASH_OFFSET] & PH_MASK_0; }
static int get_hash_1(int index) { return ((ARCH_WORD_32 *)crypt_key)[HASH_OFFSET] & PH_MASK_1; }
static int get_hash_2(int index) { return ((ARCH_WORD_32 *)crypt_key)[HASH_OFFSET] & PH_MASK_2; }
static int get_hash_3(int index) { return ((ARCH_WORD_32 *)crypt_key)[HASH_OFFSET] & PH_MASK_3; }
static int get_hash_4(int index) { return ((ARCH_WORD_32 *)crypt_key)[HASH_OFFSET] & PH_MASK_4; }
static int get_hash_5(int index) { return ((ARCH_WORD_32 *)crypt_key)[HASH_OFFSET] & PH_MASK_5; }
static int get_hash_6(int index) { return ((ARCH_WORD_32 *)crypt_key)[HASH_OFFSET] & PH_MASK_6; }
#else
static int get_hash_0(int index) { return *(ARCH_WORD_32*)crypt_key[index] & PH_MASK_0; }
static int get_hash_1(int index) { return *(ARCH_WORD_32*)crypt_key[index] & PH_MASK_1; }
static int get_hash_2(int index) { return *(ARCH_WORD_32*)crypt_key[index] & PH_MASK_2; }
static int get_hash_3(int index) { return *(ARCH_WORD_32*)crypt_key[index] & PH_MASK_3; }
static int get_hash_4(int index) { return *(ARCH_WORD_32*)crypt_key[index] & PH_MASK_4; }
static int get_hash_5(int index) { return *(ARCH_WORD_32*)crypt_key[index] & PH_MASK_5; }
static int get_hash_6(int index) { return *(ARCH_WORD_32*)crypt_key[index] & PH_MASK_6; }
#endif
static int salt_hash(void *salt)
{
return *(ARCH_WORD_32*)salt & (SALT_HASH_SIZE - 1);
}
struct fmt_main fmt_IPB2 = {
{
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,
FMT_CASE | FMT_8_BIT | FMT_OMP,
{ NULL },
tests
},
{
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid,
fmt_default_split,
get_binary,
get_salt,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash_0,
fmt_default_binary_hash_1,
fmt_default_binary_hash_2,
fmt_default_binary_hash_3,
fmt_default_binary_hash_4,
fmt_default_binary_hash_5,
fmt_default_binary_hash_6
},
salt_hash,
NULL,
set_salt,
set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
get_hash_0,
get_hash_1,
get_hash_2,
get_hash_3,
get_hash_4,
get_hash_5,
get_hash_6
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
|
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] = 24;
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
#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;
}
|
gm_dfs_template.h
|
#ifndef GM_DFS_TEMPLATE_H
#define GM_DFS_TEMPLATE_H
#include <omp.h>
#include <string.h>
#include <set>
#include <vector>
#include "gm_graph.h"
//-----------------------------------------------
// template for DFS
// Note that recursion-base DFS will surely crash due to
// stack overflow, when applied to small-world graphs.
// (It will visit O(N) nodes before ever pop up)
// Thus, here we implement DFS withour recursion.
//-----------------------------------------------
struct _dfs_state
{
_dfs_state(node_t N, edge_t I, edge_t E) :
node(N), idx(I), end(E) {
}
node_t node; // node
edge_t idx; // edge idx
edge_t end; //
};
template<bool has_pre_visit, bool has_post_visit, bool has_navigator, bool use_reverse_edge>
class gm_dfs_template
{
protected:
virtual void visit_pre(node_t t)=0;
virtual void visit_post(node_t t)=0;
virtual bool check_navigator(node_t t, edge_t idx)=0;
public:
gm_dfs_template(gm_graph& _G) :
G(_G) {
visited_bitmap = NULL; // bitmap
}
virtual ~gm_dfs_template() {
delete visited_bitmap;
}
void prepare(node_t root_node) {
root = root_node;
cnt = 0;
visited_small.clear();
is_small = true;
curr_node = INVALID_NODE;
curr_idx = 0;
curr_end = 0;
THRESHOLD_LARGE = std::max((int)(G.num_nodes()*0.1), 4096);
}
void do_dfs() {
enter_node(root);
main_loop();
}
private:
void prepare_large() {
delete[] visited_bitmap;
visited_bitmap = new unsigned char[(G.num_nodes() + 7) / 8];
#pragma omp parallel for
for (int i = 0; i < (G.num_nodes() + 7) / 8; i++)
visited_bitmap[i] = 0;
std::set<node_t>::iterator I;
for (I = visited_small.begin(); I != visited_small.end(); I++) {
node_t u = *I;
_gm_set_bit(visited_bitmap, u);
}
is_small = false;
stack.reserve(G.num_nodes());
}
void enter_node(node_t n) {
// push current node
_dfs_state S(curr_node, curr_idx, curr_end);
stack.push_back(S);
curr_node = n;
curr_idx = (use_reverse_edge) ? G.r_begin[n] : G.begin[n];
curr_end = (use_reverse_edge) ? G.r_begin[n + 1] : G.begin[n + 1];
// mark visited
add_visited(n);
cnt++;
if (cnt == THRESHOLD_LARGE) // if go over threshold, it will probably visit all the nodes
{
prepare_large();
}
if (has_pre_visit) visit_pre(n);
}
void exit_node(node_t n) {
if (has_post_visit) visit_post(n);
_dfs_state S = stack.back();
stack.pop_back();
curr_node = S.node;
curr_idx = S.idx;
curr_end = S.end;
}
void main_loop() {
//----------------------------------
// Repeat until stack is empty
//----------------------------------
while (curr_node != INVALID_NODE) {
//----------------------------------
// Every neighbor has been visited
//----------------------------------
if (curr_idx == curr_end) {
exit_node(curr_node);
continue;
}
else {
//----------------------------------
// check every non-visited neighbor
//----------------------------------
node_t z;
if (use_reverse_edge) {
z = G.r_node_idx[curr_idx];
} else {
z = G.node_idx[curr_idx];
}
if (has_visited(z)) {
curr_idx++;
continue;
}
if (has_navigator) {
if (check_navigator(z, curr_idx) == false) {
curr_idx++;
continue;
}
}
curr_idx++;
enter_node(z);
continue;
}
}
}
void add_visited(node_t n) {
if (is_small)
visited_small.insert(n);
else
_gm_set_bit(visited_bitmap, n);
}
bool has_visited(node_t n) {
if (is_small) {
return (visited_small.find(n) != visited_small.end());
} else {
return _gm_get_bit(visited_bitmap, n);
}
}
protected:
node_t root;
gm_graph& G;
// stack implementation
node_t stack_ptr;
std::vector<_dfs_state> stack;
node_t curr_node;
edge_t curr_idx;
edge_t curr_end;
// visited set implementation
node_t cnt;
unsigned char* visited_bitmap;
std::set<node_t> visited_small;
bool is_small;
int THRESHOLD_LARGE;
static const node_t INVALID_NODE = -1;
};
#endif
|
diagsm_x_csr_n_col.c
|
#include "alphasparse/kernel.h"
#include "alphasparse/util.h"
#include "alphasparse/opt.h"
#include <memory.h>
alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_CSR *A, const ALPHA_Number *x, const ALPHA_INT columns, const ALPHA_INT ldx, ALPHA_Number *y, const ALPHA_INT ldy)
{
ALPHA_Number diag[A->rows];
memset(diag, '\0', A->rows * sizeof(ALPHA_Number));
int num_thread = alpha_get_thread_num();
#ifdef _OPENMP
#pragma omp parallel for num_threads(num_thread)
#endif
for (ALPHA_INT r = 0; r < A->rows; r++)
{
for (ALPHA_INT ai = A->rows_start[r]; ai < A->rows_end[r]; ai++)
{
ALPHA_INT ac = A->col_indx[ai];
if (ac == r)
{
diag[r] = A->values[ai];
}
}
}
#ifdef _OPENMP
#pragma omp parallel for num_threads(num_thread)
#endif
for (ALPHA_INT c = 0; c < columns; ++c)
{
for (ALPHA_INT r = 0; r < A->rows; ++r)
{
ALPHA_Number t;
alpha_setzero(t);
alpha_mul(t, alpha, x[index2(c, r, ldx)]);
alpha_div(y[index2(c, r, ldy)], t, diag[r]);
}
}
return ALPHA_SPARSE_STATUS_SUCCESS;
}
|
CPhotoconsistencyOdometryBiObjective.h
|
/*
* Photoconsistency-Visual-Odometry
* Multiscale Photoconsistency Visual Odometry from RGBD Images
* Copyright (c) 2012-2013, Miguel Algaba Borrego
*
* http://code.google.com/p/photoconsistency-visual-odometry/
*
* 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 holder(s) 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef _CPHOTOCONSISTENCY_ODOMETRY_BIOBJECTIVE_
#define _CPHOTOCONSISTENCY_ODOMETRY_BIOBJECTIVE_
#define ENABLE_GAUSSIAN_BLUR 1
#define ENABLE_BOX_FILTER_BLUR 0
#define ENABLE_OPENMP_MULTITHREADING 0
#define ENABLE_PRINT_CONSOLE_OPTIMIZATION_PROGRESS 0
#include "CPhotoconsistencyOdometry.h"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/contrib/contrib.hpp" //TickMeter
#include <iostream>
namespace phovo
{
namespace Analytic
{
/*!This class computes the rigid (6DoF) transformation that best aligns a pair of RGBD frames using a photoconsistency maximization approach.
To estimate the rigid transformation, this class implements a coarse to fine approach minimizing the photometric and depth error simultaneously. Thus, the algorithm starts finding a first pose approximation at
a low resolution level and uses the estimate to initialize the optimization at greater image scales. Both the residuals and jacobians are computed analytically.*/
template< class TPixel, class TCoordinate >
class CPhotoconsistencyOdometryBiObjective :
public CPhotoconsistencyOdometry< TPixel, TCoordinate >
{
public:
typedef CPhotoconsistencyOdometry< TPixel, TCoordinate > Superclass;
typedef typename Superclass::CoordinateType CoordinateType;
typedef typename Superclass::IntensityImageType IntensityImageType;
typedef typename Superclass::DepthImageType DepthImageType;
typedef typename Superclass::Matrix33Type Matrix33Type;
typedef typename Superclass::Matrix44Type Matrix44Type;
typedef typename Superclass::Vector6Type Vector6Type;
typedef typename Superclass::Vector4Type Vector4Type;
private:
typedef DepthImageType InternalIntensityImageType;
typedef std::vector< InternalIntensityImageType > InternalIntensityImageContainerType;
typedef std::vector< DepthImageType > DepthImageContainerType;
typedef std::vector< CoordinateType > CoordinateContainerType;
typedef std::vector< int > IntegerContainerType;
/*!Intensity (gray), depth and gradient image pyramids. Each pyramid has 'numOptimizationLevels' levels.*/
InternalIntensityImageContainerType m_IntensityPyramid0;
InternalIntensityImageContainerType m_IntensityPyramid1;
DepthImageContainerType m_DepthPyramid0;
DepthImageContainerType m_DepthPyramid1;
InternalIntensityImageContainerType m_IntensityGradientXPyramid1;
InternalIntensityImageContainerType m_IntensityGradientYPyramid1;
DepthImageContainerType m_DepthGradientXPyramid1;
DepthImageContainerType m_DepthGradientYPyramid1;
/*!Camera matrix (intrinsic parameters).*/
Matrix33Type m_IntrinsicMatrix;
/*!Current optimization level. Level 0 corresponds to the higher image resolution.*/
int m_OptimizationLevel;
/*!Number of optimization levels.*/
int m_NumOptimizationLevels;
/*!Scaling factor to update the state vector (at each level).*/
CoordinateContainerType m_LambdaOptimizationSteps;
/*!Size (in pixels) of the blur filter (at each level).*/
IntegerContainerType m_BlurFilterSizes;
/*!Scaling factor applied to the image gradients (at each level).*/
CoordinateContainerType m_ImageGradientsScalingFactors;
/*!Maximum number of iterations for the Gauss-Newton algorithm (at each level).*/
IntegerContainerType m_MaxNumIterations;
/*!Minimum gradient norm of the jacobian (at each level).*/
CoordinateContainerType m_MinGradientNorms;
/*!Enable the visualization of the optimization process (only for debug).*/
bool m_VisualizeIterations;
/*!State vector.*/
Vector6Type m_StateVector; //Parameter vector (x y z yaw pitch roll)
/*!Gradient of the error function.*/
Vector6Type m_Gradients;
/*!Current iteration at the current optimization level.*/
int m_Iteration;
/*!Minimum allowed depth to consider a depth pixel valid.*/
CoordinateType m_MinDepth;
/*!Maximum allowed depth to consider a depth pixel valid.*/
CoordinateType m_MaxDepth;
/*!Depth component gain. This variable is used to scale the depth values so that depth components are similar to intensity values.*/
CoordinateType m_DepthComponentGain;
template< class TImage >
void BuildPyramid( const TImage & img,
std::vector< TImage > & pyramid,
const int levels, const bool applyBlur )
{
typedef TImage ImageType;
//Create space for all the images
pyramid.resize( levels );
double factor = 1.;
for( int level=0; level<levels; level++ )
{
//Create an auxiliar image of factor times the size of the original image
ImageType imgAux;
if( level!=0 )
{
cv::resize( img, imgAux, cv::Size(0,0), factor, factor );
}
else
{
imgAux = img;
}
//Blur the resized image with different filter size depending on the current pyramid level
if( applyBlur )
{
int blurFilterSize = m_BlurFilterSizes[level];
#if ENABLE_GAUSSIAN_BLUR
if( blurFilterSize>0 )
{
cv::GaussianBlur( imgAux, imgAux, cv::Size( blurFilterSize, blurFilterSize ), 3 );
cv::GaussianBlur( imgAux, imgAux, cv::Size( blurFilterSize, blurFilterSize ), 3 );
}
#elif ENABLE_BOX_FILTER_BLUR
if( blurFilterSize>0 )
{
cv::blur( imgAux, imgAux, cv::Size( blurFilterSize, blurFilterSize ) );
cv::blur( imgAux, imgAux, cv::Size( blurFilterSize, blurFilterSize ) );
}
#endif
}
//Assign the resized image to the current level of the pyramid
pyramid[level] = imgAux;
factor = factor/2;
}
}
void BuildIntensityDerivativesPyramids( InternalIntensityImageContainerType & imagePyramid,
InternalIntensityImageContainerType & derXPyramid,
InternalIntensityImageContainerType & derYPyramid)
{
//Compute image gradients
double delta = 0.0;
int ddepth = m_IntensityPyramid0[0].type();
//Create space for all the derivatives images
derXPyramid.resize(imagePyramid.size());
derYPyramid.resize(imagePyramid.size());
for( size_t level=0; level<imagePyramid.size(); level++ )
{
// Compute the gradient in x
InternalIntensityImageType imgGray1_grad_x;
cv::Scharr( imagePyramid[level], derXPyramid[level], ddepth, 1, 0,
m_ImageGradientsScalingFactors[level], delta, cv::BORDER_DEFAULT );
// Compute the gradient in y
InternalIntensityImageType imgGray1_grad_y;
cv::Scharr( imagePyramid[level], derYPyramid[level],ddepth, 0, 1,
m_ImageGradientsScalingFactors[level], delta, cv::BORDER_DEFAULT );
}
}
CoordinateType MaxDepthValue( const DepthImageType & image ) const
{
CoordinateType maxDepth = 0;
for( int r=0; r<image.rows; r++ )
{
for( int c=0; c<image.cols; c++ )
{
if( image( r, c ) > maxDepth )
{
maxDepth = image( r, c );
}
}
}
return maxDepth;
}
void BuildDepthDerivativesPyramids( DepthImageContainerType & imagePyramid,
DepthImageContainerType & derXPyramid,
DepthImageContainerType & derYPyramid)
{
//Compute image gradients
double delta = 0.0;
int ddepth = m_DepthPyramid0[0].type();
//Create space for all the derivatives images
derXPyramid.resize(imagePyramid.size());
derYPyramid.resize(imagePyramid.size());
for( size_t level=0; level<imagePyramid.size(); level++ )
{
DepthImageType imgNormalizedDepth;
imagePyramid[level].convertTo( imgNormalizedDepth, ddepth, 1./m_MaxDepth );
// Compute the gradient in x
cv::Scharr( imgNormalizedDepth, derXPyramid[level], ddepth, 1, 0,
m_ImageGradientsScalingFactors[level], delta, cv::BORDER_DEFAULT );
// Compute the gradient in y
DepthImageType imgGray1_grad_y;
cv::Scharr( imgNormalizedDepth, derYPyramid[level],ddepth, 0, 1,
m_ImageGradientsScalingFactors[level], delta, cv::BORDER_DEFAULT );
}
}
//Separated jacobians
void ComputeResidualsAndJacobians( const InternalIntensityImageType & source_grayImg,
const DepthImageType & source_depthImg,
const InternalIntensityImageType & target_grayImg,
const InternalIntensityImageType & target_depthImg,
const InternalIntensityImageType & target_intensityGradXImg,
const InternalIntensityImageType & target_intensityGradYImg,
const DepthImageType & target_depthGradXImg,
const DepthImageType & target_depthGradYImg,
Numeric::RowDynamicMatrixColMajor< CoordinateType, 1 > & residuals,
Numeric::RowDynamicMatrixColMajor< CoordinateType, 6 > & jacobians,
InternalIntensityImageType & warped_source_grayImage)
{
int nRows = source_grayImg.rows;
int nCols = source_grayImg.cols;
CoordinateType scaleFactor = 1.0/pow(2,m_OptimizationLevel);
CoordinateType fx = m_IntrinsicMatrix(0,0)*scaleFactor;
CoordinateType fy = m_IntrinsicMatrix(1,1)*scaleFactor;
CoordinateType ox = m_IntrinsicMatrix(0,2)*scaleFactor;
CoordinateType oy = m_IntrinsicMatrix(1,2)*scaleFactor;
CoordinateType inv_fx = 1.f/fx;
CoordinateType inv_fy = 1.f/fy;
CoordinateType x = m_StateVector(0);
CoordinateType y = m_StateVector(1);
CoordinateType z = m_StateVector(2);
CoordinateType yaw = m_StateVector(3);
CoordinateType pitch = m_StateVector(4);
CoordinateType roll = m_StateVector(5);
//Compute the rigid transformation matrix from the parameters
Matrix44Type Rt = Matrix44Type::Identity();
CoordinateType sin_yaw = sin(yaw);
CoordinateType cos_yaw = cos(yaw);
CoordinateType sin_pitch = sin(pitch);
CoordinateType cos_pitch = cos(pitch);
CoordinateType sin_roll = sin(roll);
CoordinateType cos_roll = cos(roll);
Rt(0,0) = cos_yaw * cos_pitch;
Rt(0,1) = cos_yaw * sin_pitch * sin_roll - sin_yaw * cos_roll;
Rt(0,2) = cos_yaw * sin_pitch * cos_roll + sin_yaw * sin_roll;
Rt(0,3) = x;
Rt(1,0) = sin_yaw * cos_pitch;
Rt(1,1) = sin_yaw * sin_pitch * sin_roll + cos_yaw * cos_roll;
Rt(1,2) = sin_yaw * sin_pitch * cos_roll - cos_yaw * sin_roll;
Rt(1,3) = y;
Rt(2,0) = -sin_pitch;
Rt(2,1) = cos_pitch * sin_roll;
Rt(2,2) = cos_pitch * cos_roll;
Rt(2,3) = z;
Rt(3,0) = 0.0;
Rt(3,1) = 0.0;
Rt(3,2) = 0.0;
Rt(3,3) = 1.0;
m_DepthComponentGain = cv::mean( target_grayImg ).val[0] / cv::mean( target_depthImg ).val[0];
#if ENABLE_OPENMP_MULTITHREADING
#pragma omp parallel for
#endif
for (int r=0;r<nRows;r++)
{
for (int c=0;c<nCols;c++)
{
int i = nCols*r+c; //vector index
//Compute the 3D coordinates of the pij of the source frame
Vector4Type point3D;
point3D(2) = source_depthImg( r, c );
if( m_MinDepth < point3D(2) && point3D(2) < m_MaxDepth) //Compute the jacobian only for the valid points
{
point3D(0) = (c - ox) * point3D(2) * inv_fx;
point3D(1) = (r - oy) * point3D(2) * inv_fy;
point3D(3) = 1.0;
CoordinateType px = point3D(0);
CoordinateType py = point3D(1);
CoordinateType pz = point3D(2);
//Transform the 3D point using the transformation matrix Rt
Vector4Type transformedPoint3D = Rt*point3D;
//Project the 3D point to the 2D plane
CoordinateType inv_transformedPz = 1.0 / transformedPoint3D(2);
CoordinateType transformed_c = (transformedPoint3D(0) * fx) * inv_transformedPz + ox; //transformed x (2D)
CoordinateType transformed_r = (transformedPoint3D(1) * fy) * inv_transformedPz + oy; //transformed y (2D)
int transformed_r_int = static_cast< int >( round( transformed_r ) );
int transformed_c_int = static_cast< int >( round( transformed_c ) );
//Asign the intensity value to the warped image and compute the difference between the transformed
//pixel of frame 1 and the corresponding pixel of frame 2. Compute the error function
if( ( transformed_r_int >= 0 && transformed_r_int < nRows ) &
( transformed_c_int >= 0 && transformed_c_int < nCols ) )
{
//Obtain the pixel values that will be used to compute the intensity residual
CoordinateType intensity1; //Intensity value of the pixel(r,c) of the warped frame 1
CoordinateType intensity2; //Intensity value of the pixel(r,c) of frame 2
intensity1 = source_grayImg( r, c );
intensity2 = target_grayImg( transformed_r_int, transformed_c_int );
//Obtain the depth values that will be used to the compute the depth residual
CoordinateType depth1; //Depth value of the pixel(r,c) of the warped frame 1
CoordinateType depth2; //Depth value of the pixel(r,c) of frame 2
depth1 = source_depthImg( r, c );
depth2 = target_depthImg( transformed_r_int, transformed_c_int );
//Compute the rigid transformation jacobian
Numeric::FixedMatrixRowMajor< CoordinateType, 3, 6 > jacobianRt;
//Derivative with respect to x
jacobianRt(0,0) = 1.;
jacobianRt(1,0) = 0.;
jacobianRt(2,0) = 0.;
//Derivative with respect to y
jacobianRt(0,1) = 0.;
jacobianRt(1,1) = 1.;
jacobianRt(2,1) = 0.;
//Derivative with respect to z
jacobianRt(0,2) = 0.;
jacobianRt(1,2) = 0.;
jacobianRt(2,2) = 1.;
//Derivative with respect to yaw
jacobianRt(0,3) = py*(-sin(pitch)*sin(roll)*sin(yaw)-cos(roll)*cos(yaw))+pz*(sin(roll)*cos(yaw)-sin(pitch)*cos(roll)*sin(yaw))-cos(pitch)*px*sin(yaw);
jacobianRt(1,3) = pz*(sin(roll)*sin(yaw)+sin(pitch)*cos(roll)*cos(yaw))+py*(sin(pitch)*sin(roll)*cos(yaw)-cos(roll)*sin(yaw))+cos(pitch)*px*cos(yaw);
jacobianRt(2,3) = 0.;
//Derivative with respect to pitch
jacobianRt(0,4) = cos(pitch)*py*sin(roll)*cos(yaw)+cos(pitch)*pz*cos(roll)*cos(yaw)-sin(pitch)*px*cos(yaw);
jacobianRt(1,4) = cos(pitch)*py*sin(roll)*sin(yaw)+cos(pitch)*pz*cos(roll)*sin(yaw)-sin(pitch)*px*sin(yaw);
jacobianRt(2,4) = -sin(pitch)*py*sin(roll)-sin(pitch)*pz*cos(roll)-cos(pitch)*px;
//Derivative with respect to roll
jacobianRt(0,5) = py*(sin(roll)*sin(yaw)+sin(pitch)*cos(roll)*cos(yaw))+pz*(cos(roll)*sin(yaw)-sin(pitch)*sin(roll)*cos(yaw));
jacobianRt(1,5) = pz*(-sin(pitch)*sin(roll)*sin(yaw)-cos(roll)*cos(yaw))+py*(sin(pitch)*cos(roll)*sin(yaw)-sin(roll)*cos(yaw));
jacobianRt(2,5) = cos(pitch)*py*cos(roll)-cos(pitch)*pz*sin(roll);
//Compute the proyective transformation jacobian
Numeric::FixedMatrixRowMajor< CoordinateType, 2, 3 > jacobianProy;
//Derivative with respect to x
jacobianProy(0,0) = fx*inv_transformedPz;
jacobianProy(1,0) = 0.;
//Derivative with respect to y
jacobianProy(0,1) = 0.;
jacobianProy(1,1) = fy*inv_transformedPz;
//Derivative with respect to z
jacobianProy(0,2) = -(fx*transformedPoint3D(0))*inv_transformedPz*inv_transformedPz;
jacobianProy(1,2) = -(fy*transformedPoint3D(1))*inv_transformedPz*inv_transformedPz;
//Intensity jacobian:
//Apply the chain rule to compound the intensity gradients with the projective+RigidTransform jacobians
Numeric::FixedRowVector< CoordinateType, 2 > target_intensityGradient;
target_intensityGradient(0,0) = target_intensityGradXImg(i);
target_intensityGradient(0,1) = target_intensityGradYImg(i);
Numeric::FixedRowVector< CoordinateType, 6 > jacobianItensity = target_intensityGradient*jacobianProy*jacobianRt;
//Depth jacobian:
//Apply the chain rule to compound the depth gradients with the projective+RigidTransform jacobians
Numeric::FixedRowVector< CoordinateType, 2 > target_depthGradient;
target_depthGradient(0,0) = target_depthGradXImg(i);
target_depthGradient(0,1) = target_depthGradYImg(i);
Numeric::FixedRowVector< CoordinateType, 6 > jacobianRt_z;
jacobianRt_z(0,0) = jacobianRt(2,0);
jacobianRt_z(0,1) = jacobianRt(2,1);
jacobianRt_z(0,2) = jacobianRt(2,2);
jacobianRt_z(0,3) = jacobianRt(2,3);
jacobianRt_z(0,4) = jacobianRt(2,4);
jacobianRt_z(0,5) = jacobianRt(2,5);
Numeric::FixedRowVector< CoordinateType, 6 > jacobianDepth =
m_DepthComponentGain * ( target_depthGradient * jacobianProy * jacobianRt - jacobianRt_z );
//Assign the pixel residual and jacobian to its corresponding row
//Assign intensity jacobians
jacobians(i,0) = jacobianItensity(0,0);
jacobians(i,1) = jacobianItensity(0,1);
jacobians(i,2) = jacobianItensity(0,2);
jacobians(i,3) = jacobianItensity(0,3);
jacobians(i,4) = jacobianItensity(0,4);
jacobians(i,5) = jacobianItensity(0,5);
//Assign intensity residuals
residuals( nCols * transformed_r_int + transformed_c_int , 0 ) = intensity2 - intensity1;
//Assign depth jacobians
jacobians( 2*i, 0 ) = jacobianDepth(0,0);
jacobians( 2*i, 1 ) = jacobianDepth(0,1);
jacobians( 2*i, 2 ) = jacobianDepth(0,2);
jacobians( 2*i, 3 ) = jacobianDepth(0,3);
jacobians( 2*i, 4 ) = jacobianDepth(0,4);
jacobians( 2*i, 5 ) = jacobianDepth(0,5);
//Assign depth residuals
residuals (nCols * 2 * transformed_r_int + 2 * transformed_c_int, 0 ) =
m_DepthComponentGain * ( depth2 - depth1 );
if( m_VisualizeIterations )
{
warped_source_grayImage( transformed_r_int, transformed_c_int ) = intensity1;
}
}
}
}
}
}
enum TerminationCriteriaType
{
NonTerminated = -1,
MaxIterationsReached = 0,
GradientNormLowerThanThreshold = 1
};
bool TestTerminationCriteria() const
{
bool optimizationFinished = false;
CoordinateType gradientNorm = m_Gradients.norm();
TerminationCriteriaType terminationCriteria = NonTerminated;
if( m_Iteration >= m_MaxNumIterations[ m_OptimizationLevel ] )
{
terminationCriteria = MaxIterationsReached;
optimizationFinished = true;
}
else if( gradientNorm < m_MinGradientNorms[ m_OptimizationLevel ] )
{
terminationCriteria = GradientNormLowerThanThreshold;
optimizationFinished = true;
}
if( optimizationFinished )
{
#if ENABLE_PRINT_CONSOLE_OPTIMIZATION_PROGRESS
std::cout << "----------------------------------------" << std::endl;
std::cout << "Optimization level: " << m_OptimizationLevel << std::endl;
std::cout << "Termination criteria: ";
#endif
switch( terminationCriteria )
{
case MaxIterationsReached:
#if ENABLE_PRINT_CONSOLE_OPTIMIZATION_PROGRESS
std::cout << " Max number of iterations reached (" << m_MaxNumIterations[ m_OptimizationLevel ] << ")" << std::endl;;
#endif
break;
case GradientNormLowerThanThreshold:
#if ENABLE_PRINT_CONSOLE_OPTIMIZATION_PROGRESS
std::cout << " Gradient norm is lower than threshold (" << m_MinGradientNorms[ m_OptimizationLevel ] << ")" << std::endl;
#endif
break;
default :
break;
}
#if ENABLE_PRINT_CONSOLE_OPTIMIZATION_PROGRESS
std::cout << "Number iterations: " << m_Iteration << std::endl;
std::cout << "gradient norm: " << gradientNorm << std::endl;
std::cout << "----------------------------------------" << std::endl;
#endif
}
return optimizationFinished;
}
public:
CPhotoconsistencyOdometryBiObjective() : m_MinDepth( 0.3 ), m_MaxDepth( 5.0 )
{
m_StateVector.setZero();
m_NumOptimizationLevels = 5;
m_BlurFilterSizes.resize( m_NumOptimizationLevels, 0 );
m_ImageGradientsScalingFactors.resize( m_NumOptimizationLevels, 0.0625 );
m_LambdaOptimizationSteps.resize( m_NumOptimizationLevels, 1. );
m_MaxNumIterations.resize( m_NumOptimizationLevels, 0 );
m_MaxNumIterations[ 2 ] = 5;
m_MaxNumIterations[ 3 ] = 20;
m_MaxNumIterations[ 4 ] = 50;
m_MinGradientNorms.resize( m_NumOptimizationLevels, 300. );
m_VisualizeIterations = false;
}
~CPhotoconsistencyOdometryBiObjective(){};
/*!Sets the minimum depth distance (m) to consider a certain pixel valid.*/
void SetMinDepth( const CoordinateType minD )
{
m_MinDepth = minD;
}
/*!Sets the maximum depth distance (m) to consider a certain pixel valid.*/
void SetMaxDepth( const CoordinateType maxD )
{
m_MaxDepth = maxD;
}
/*!Sets the 3x3 intrinsic camera matrix*/
void SetIntrinsicMatrix( const Matrix33Type & intrinsicMatrix )
{
m_IntrinsicMatrix = intrinsicMatrix;
}
/*!Sets the source (Intensity+Depth) frame.*/
void SetSourceFrame( const IntensityImageType & intensityImage,
const DepthImageType & depthImage )
{
//Create an auxialiary image from the imput image
InternalIntensityImageType intensityImageAux;
intensityImage.convertTo( intensityImageAux, depthImage.type(), 1./255 );
//Compute image pyramids for the grayscale and depth images
BuildPyramid( intensityImageAux, m_IntensityPyramid0, m_NumOptimizationLevels, true );
BuildPyramid( depthImage, m_DepthPyramid0, m_NumOptimizationLevels, false ); //TODO: Do not apply low-pass filtering to depth image
}
/*!Sets the source (Intensity+Depth) frame. Depth image is ignored*/
void SetTargetFrame( const IntensityImageType & intensityImage,
const DepthImageType & depthImage )
{
//Create an auxialiary image from the imput image
InternalIntensityImageType intensityImageAux;
intensityImage.convertTo( intensityImageAux, depthImage.type(), 1./255 );
//Compute image pyramids for the grayscale and depth images
BuildPyramid( intensityImageAux, m_IntensityPyramid1, m_NumOptimizationLevels, true );
BuildPyramid( depthImage, m_DepthPyramid1, m_NumOptimizationLevels, false ); //TODO: Do not apply low-pass filtering to depth image
//Compute image pyramids for the gradients images
BuildIntensityDerivativesPyramids( m_IntensityPyramid1, m_IntensityGradientXPyramid1, m_IntensityGradientYPyramid1 );
BuildDepthDerivativesPyramids( m_DepthPyramid1, m_DepthGradientXPyramid1, m_DepthGradientYPyramid1 );
}
/*!Initializes the state vector to a certain value. The optimization process uses the initial state vector as the initial estimate.*/
void SetInitialStateVector( const Vector6Type & initialStateVector )
{
m_StateVector = initialStateVector;
}
/*!Launches the least-squares optimization process to find the configuration of the state vector parameters that maximizes the photoconsistency between the source and target frame.*/
void Optimize()
{
for( m_OptimizationLevel = m_NumOptimizationLevels-1;
m_OptimizationLevel >= 0; m_OptimizationLevel-- )
{
int nRows = m_IntensityPyramid0[ m_OptimizationLevel ].rows;
int nCols = m_IntensityPyramid0[ m_OptimizationLevel ].cols;
int nPoints = nRows * nCols;
m_Iteration = 0;
while(true)
{
#if ENABLE_PRINT_CONSOLE_OPTIMIZATION_PROGRESS
cv::TickMeter tm;tm.start();
#endif
InternalIntensityImageType warpedSourceIntensityImage;
if( m_VisualizeIterations )
warpedSourceIntensityImage = InternalIntensityImageType::zeros( nRows, nCols );
Numeric::RowDynamicMatrixColMajor< CoordinateType, 1 > residuals;
residuals.resize( 2*nPoints, Eigen::NoChange );
residuals.setZero();
Numeric::RowDynamicMatrixColMajor< CoordinateType, 6 > jacobians;
jacobians.resize( 2*nPoints, Eigen::NoChange );
jacobians.setZero();
if( m_MaxNumIterations[ m_OptimizationLevel] > 0 ) //compute only if the number of maximum iterations are greater than 0
{
ComputeResidualsAndJacobians(
m_IntensityPyramid0[ m_OptimizationLevel ],
m_DepthPyramid0[ m_OptimizationLevel ],
m_IntensityPyramid1[ m_OptimizationLevel ],
m_DepthPyramid1[ m_OptimizationLevel ],
m_IntensityGradientXPyramid1[ m_OptimizationLevel ],
m_IntensityGradientYPyramid1[ m_OptimizationLevel ],
m_DepthGradientXPyramid1[ m_OptimizationLevel ],
m_DepthGradientYPyramid1[ m_OptimizationLevel ],
residuals,
jacobians,
warpedSourceIntensityImage );
m_Gradients = jacobians.transpose()*residuals;
m_StateVector = m_StateVector - m_LambdaOptimizationSteps[ m_OptimizationLevel ] *
((jacobians.transpose()*jacobians).inverse() * m_Gradients );
#if ENABLE_PRINT_CONSOLE_OPTIMIZATION_PROGRESS
tm.stop(); std::cout << "Iteration time = " << tm.getTimeSec() << " sec." << std::endl;
#endif
}
m_Iteration++;
if( TestTerminationCriteria() ){break;}
if( m_VisualizeIterations )
{
InternalIntensityImageType imgDiff = InternalIntensityImageType::zeros( nRows, nCols );
cv::absdiff( m_IntensityPyramid1[ m_OptimizationLevel ], warpedSourceIntensityImage, imgDiff );
cv::imshow("optimize::imgDiff",imgDiff);
cv::waitKey(0);
}
}
}
//After all the optimization process the optimization level is 0
m_OptimizationLevel = 0;
}
/*!Returns the optimal state vector. This method has to be called after calling the Optimize() method.*/
Vector6Type GetOptimalStateVector() const
{
return m_StateVector;
}
/*!Returns the optimal 4x4 rigid transformation matrix between the source and target frame. This method has to be called after calling the Optimize() method.*/
Matrix44Type GetOptimalRigidTransformationMatrix() const
{
Matrix44Type Rt;
eigenPose( m_StateVector(0), m_StateVector(1), m_StateVector(2),
m_StateVector(3), m_StateVector(4), m_StateVector(5), Rt );
return Rt;
}
/*!Reads the configuration parameters from a .yml file.*/
void ReadConfigurationFile( const std::string & fileName )
{
cv::FileStorage fs( fileName, cv::FileStorage::READ );
//Read the number of optimization levels
fs["numOptimizationLevels"] >> m_NumOptimizationLevels;
#if ENABLE_GAUSSIAN_BLUR || ENABLE_BOX_FILTER_BLUR
//Read the blur filter size at every pyramid level
fs["blurFilterSize (at each level)"] >> m_BlurFilterSizes;
#endif
//Read the scaling factor for each gradient image at each level
fs["imageGradientsScalingFactor (at each level)"] >> m_ImageGradientsScalingFactors;
//Read the lambda factor to change the optimization step
fs["lambda_optimization_step (at each level)"] >> m_LambdaOptimizationSteps;
//Read the number of Levenberg-Marquardt iterations at each optimization level
fs["max_num_iterations (at each level)"] >> m_MaxNumIterations;
//Read optimizer minimum gradient norm at each level
fs["min_gradient_norm (at each level)"] >> m_MinGradientNorms;
//Read the boolean value to determine if visualize the progress images or not
fs["visualizeIterations"] >> m_VisualizeIterations;
}
};
} //end namespace Analytic
} //end namespace phovo
#endif
|
viter.c
|
#include "libimagequant.h"
#include "pam.h"
#include "viter.h"
#include "nearest.h"
#include <stdlib.h>
#include <string.h>
#ifdef _OPENMP
#include <omp.h>
#else
#define omp_get_max_threads() 1
#define omp_get_thread_num() 0
#endif
/*
* Voronoi iteration: new palette color is computed from weighted average of colors that map to that palette entry.
*/
LIQ_PRIVATE void viter_init(const colormap *map, const unsigned int max_threads, viter_state average_color[])
{
memset(average_color, 0, sizeof(average_color[0])*(VITER_CACHE_LINE_GAP+map->colors)*max_threads);
}
LIQ_PRIVATE void viter_update_color(const f_pixel acolor, const float value, const colormap *map, unsigned int match, const unsigned int thread, viter_state average_color[])
{
match += thread * (VITER_CACHE_LINE_GAP+map->colors);
average_color[match].a += acolor.a * value;
average_color[match].r += acolor.r * value;
average_color[match].g += acolor.g * value;
average_color[match].b += acolor.b * value;
average_color[match].total += value;
}
LIQ_PRIVATE void viter_finalize(colormap *map, const unsigned int max_threads, const viter_state average_color[])
{
for (unsigned int i=0; i < map->colors; i++) {
double a=0, r=0, g=0, b=0, total=0;
// Aggregate results from all threads
for(unsigned int t=0; t < max_threads; t++) {
const unsigned int offset = (VITER_CACHE_LINE_GAP+map->colors) * t + i;
a += average_color[offset].a;
r += average_color[offset].r;
g += average_color[offset].g;
b += average_color[offset].b;
total += average_color[offset].total;
}
if (total && !map->palette[i].fixed) {
map->palette[i].acolor = (f_pixel){
.a = a / total,
.r = r / total,
.g = g / total,
.b = b / total,
};
} else {
total = i/1024.0;
}
map->palette[i].popularity = total;
}
}
LIQ_PRIVATE double viter_do_iteration(histogram *hist, colormap *const map, const float min_opaque_val, viter_callback callback, const bool fast_palette)
{
const unsigned int max_threads = omp_get_max_threads();
viter_state average_color[(VITER_CACHE_LINE_GAP+map->colors) * max_threads];
viter_init(map, max_threads, average_color);
struct nearest_map *const n = nearest_init(map, fast_palette);
hist_item *const achv = hist->achv;
const int hist_size = hist->size;
double total_diff=0;
#if __GNUC__ >= 9
#pragma omp parallel for if (hist_size > 3000) \
schedule(static) default(none) shared(map,min_opaque_val,callback,average_color,n,achv,hist_size) reduction(+:total_diff)
#endif
for(int j=0; j < hist_size; j++) {
float diff;
unsigned int match = nearest_search(n, achv[j].acolor, achv[j].tmp.likely_colormap_index, min_opaque_val, &diff);
achv[j].tmp.likely_colormap_index = match;
total_diff += diff * achv[j].perceptual_weight;
viter_update_color(achv[j].acolor, achv[j].perceptual_weight, map, match, omp_get_thread_num(), average_color);
if (callback) callback(&achv[j], diff);
}
nearest_free(n);
viter_finalize(map, max_threads, average_color);
return total_diff / hist->total_perceptual_weight;
}
|
kmp_taskloop.c
|
// RUN: %libomp-compile-and-run
// RUN: %libomp-compile && env KMP_TASKLOOP_MIN_TASKS=1 %libomp-run
// REQUIRES: openmp-4.5
#include <stdio.h>
#include <omp.h>
#include "omp_my_sleep.h"
#define N 4
#define GRAIN 10
#define STRIDE 3
// globals
int th_counter[N];
int counter;
// Compiler-generated code (emulation)
typedef struct ident {
void* dummy;
} ident_t;
typedef struct shar {
int(*pth_counter)[N];
int *pcounter;
int *pj;
} *pshareds;
typedef struct task {
pshareds shareds;
int(* routine)(int,struct task*);
int part_id;
// privates:
unsigned long long lb; // library always uses ULONG
unsigned long long ub;
int st;
int last;
int i;
int j;
int th;
} *ptask, kmp_task_t;
typedef int(* task_entry_t)( int, ptask );
void
__task_dup_entry(ptask task_dst, ptask task_src, int lastpriv)
{
// setup lastprivate flag
task_dst->last = lastpriv;
// could be constructor calls here...
}
// OpenMP RTL interfaces
typedef unsigned long long kmp_uint64;
typedef long long kmp_int64;
#ifdef __cplusplus
extern "C" {
#endif
void
__kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int if_val,
kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st,
int nogroup, int sched, kmp_int64 grainsize, void *task_dup );
ptask
__kmpc_omp_task_alloc( ident_t *loc, int gtid, int flags,
size_t sizeof_kmp_task_t, size_t sizeof_shareds,
task_entry_t task_entry );
void __kmpc_atomic_fixed4_add(void *id_ref, int gtid, int * lhs, int rhs);
int __kmpc_global_thread_num(void *id_ref);
#ifdef __cplusplus
}
#endif
// User's code
int task_entry(int gtid, ptask task)
{
pshareds pshar = task->shareds;
for( task->i = task->lb; task->i <= (int)task->ub; task->i += task->st ) {
task->th = omp_get_thread_num();
__kmpc_atomic_fixed4_add(NULL,gtid,pshar->pcounter,1);
__kmpc_atomic_fixed4_add(NULL,gtid,&((*pshar->pth_counter)[task->th]),1);
task->j = task->i;
}
my_sleep( 0.1 ); // sleep 100 ms in order to allow other threads to steal tasks
if( task->last ) {
*(pshar->pj) = task->j; // lastprivate
}
return 0;
}
int main()
{
int i, j, gtid = __kmpc_global_thread_num(NULL);
ptask task;
pshareds psh;
omp_set_dynamic(0);
counter = 0;
for( i=0; i<N; ++i )
th_counter[i] = 0;
#pragma omp parallel num_threads(N)
{
#pragma omp master
{
int gtid = __kmpc_global_thread_num(NULL);
/*
* This is what the OpenMP runtime calls correspond to:
#pragma omp taskloop num_tasks(N) lastprivate(j)
for( i=0; i<N*GRAIN*STRIDE-1; i+=STRIDE )
{
int th = omp_get_thread_num();
#pragma omp atomic
counter++;
#pragma omp atomic
th_counter[th]++;
j = i;
}
*/
task = __kmpc_omp_task_alloc(NULL,gtid,1,sizeof(struct task),sizeof(struct shar),&task_entry);
psh = task->shareds;
psh->pth_counter = &th_counter;
psh->pcounter = &counter;
psh->pj = &j;
task->lb = 0;
task->ub = N*GRAIN*STRIDE-2;
task->st = STRIDE;
__kmpc_taskloop(
NULL, // location
gtid, // gtid
task, // task structure
1, // if clause value
&task->lb, // lower bound
&task->ub, // upper bound
STRIDE, // loop increment
0, // 1 if nogroup specified
2, // schedule type: 0-none, 1-grainsize, 2-num_tasks
N, // schedule value (ignored for type 0)
(void*)&__task_dup_entry // tasks duplication routine
);
} // end master
} // end parallel
// check results
if( j != N*GRAIN*STRIDE-STRIDE ) {
printf("Error in lastprivate, %d != %d\n",j,N*GRAIN*STRIDE-STRIDE);
return 1;
}
if( counter != N*GRAIN ) {
printf("Error, counter %d != %d\n",counter,N*GRAIN);
return 1;
}
for( i=0; i<N; ++i ) {
if( th_counter[i] % GRAIN ) {
printf("Error, th_counter[%d] = %d\n",i,th_counter[i]);
return 1;
}
}
printf("passed\n");
return 0;
}
|
column_matrix.h
|
/*!
* Copyright 2017 by Contributors
* \file column_matrix.h
* \brief Utility for fast column-wise access
* \author Philip Cho
*/
#ifndef XGBOOST_COMMON_COLUMN_MATRIX_H_
#define XGBOOST_COMMON_COLUMN_MATRIX_H_
#include <dmlc/timer.h>
#include <limits>
#include <vector>
#include "hist_util.h"
namespace xgboost {
namespace common {
/*! \brief column type */
enum ColumnType {
kDenseColumn,
kSparseColumn
};
/*! \brief a column storage, to be used with ApplySplit. Note that each
bin id is stored as index[i] + index_base. */
class Column {
public:
Column(ColumnType type, const uint32_t* index, uint32_t index_base,
const size_t* row_ind, size_t len)
: type_(type),
index_(index),
index_base_(index_base),
row_ind_(row_ind),
len_(len) {}
size_t Size() const { return len_; }
uint32_t GetGlobalBinIdx(size_t idx) const { return index_base_ + index_[idx]; }
uint32_t GetFeatureBinIdx(size_t idx) const { return index_[idx]; }
// column.GetFeatureBinIdx(idx) + column.GetBaseIdx(idx) ==
// column.GetGlobalBinIdx(idx)
uint32_t GetBaseIdx() const { return index_base_; }
ColumnType GetType() const { return type_; }
size_t GetRowIdx(size_t idx) const {
// clang-tidy worries that row_ind_ might be a nullptr, which is possible,
// but low level structure is not safe anyway.
return type_ == ColumnType::kDenseColumn ? idx : row_ind_[idx]; // NOLINT
}
bool IsMissing(size_t idx) const {
return index_[idx] == std::numeric_limits<uint32_t>::max();
}
const size_t* GetRowData() const { return row_ind_; }
const uint32_t* GetIndex() const {
return index_;
}
private:
ColumnType type_;
const uint32_t* index_;
uint32_t index_base_;
const size_t* row_ind_;
const size_t len_;
};
/*! \brief a collection of columns, with support for construction from
GHistIndexMatrix. */
class ColumnMatrix {
public:
// get number of features
inline bst_uint GetNumFeature() const {
return static_cast<bst_uint>(type_.size());
}
// construct column matrix from GHistIndexMatrix
inline void Init(const GHistIndexMatrix& gmat,
double sparse_threshold) {
const int32_t nfeature = static_cast<int32_t>(gmat.cut.row_ptr.size() - 1);
const size_t nrow = gmat.row_ptr.size() - 1;
// identify type of each column
feature_counts_.resize(nfeature);
type_.resize(nfeature);
std::fill(feature_counts_.begin(), feature_counts_.end(), 0);
uint32_t max_val = std::numeric_limits<uint32_t>::max();
for (int32_t fid = 0; fid < nfeature; ++fid) {
CHECK_LE(gmat.cut.row_ptr[fid + 1] - gmat.cut.row_ptr[fid], max_val);
}
gmat.GetFeatureCounts(&feature_counts_[0]);
// classify features
for (int32_t fid = 0; fid < nfeature; ++fid) {
if (static_cast<double>(feature_counts_[fid])
< sparse_threshold * nrow) {
type_[fid] = kSparseColumn;
} else {
type_[fid] = kDenseColumn;
}
}
// want to compute storage boundary for each feature
// using variants of prefix sum scan
boundary_.resize(nfeature);
size_t accum_index_ = 0;
size_t accum_row_ind_ = 0;
for (int32_t fid = 0; fid < nfeature; ++fid) {
boundary_[fid].index_begin = accum_index_;
boundary_[fid].row_ind_begin = accum_row_ind_;
if (type_[fid] == kDenseColumn) {
accum_index_ += static_cast<size_t>(nrow);
accum_row_ind_ += static_cast<size_t>(nrow);
} else {
accum_index_ += feature_counts_[fid];
accum_row_ind_ += feature_counts_[fid];
}
boundary_[fid].index_end = accum_index_;
boundary_[fid].row_ind_end = accum_row_ind_;
}
index_.resize(boundary_[nfeature - 1].index_end);
row_ind_.resize(boundary_[nfeature - 1].row_ind_end);
// store least bin id for each feature
index_base_.resize(nfeature);
for (int32_t fid = 0; fid < nfeature; ++fid) {
index_base_[fid] = gmat.cut.row_ptr[fid];
}
// pre-fill index_ for dense columns
#pragma omp parallel for
for (int32_t fid = 0; fid < nfeature; ++fid) {
if (type_[fid] == kDenseColumn) {
const size_t ibegin = boundary_[fid].index_begin;
uint32_t* begin = &index_[ibegin];
uint32_t* end = begin + nrow;
std::fill(begin, end, std::numeric_limits<uint32_t>::max());
// max() indicates missing values
}
}
// loop over all rows and fill column entries
// num_nonzeros[fid] = how many nonzeros have this feature accumulated so far?
std::vector<size_t> num_nonzeros;
num_nonzeros.resize(nfeature);
std::fill(num_nonzeros.begin(), num_nonzeros.end(), 0);
for (size_t rid = 0; rid < nrow; ++rid) {
const size_t ibegin = gmat.row_ptr[rid];
const size_t iend = gmat.row_ptr[rid + 1];
size_t fid = 0;
for (size_t i = ibegin; i < iend; ++i) {
const uint32_t bin_id = gmat.index[i];
while (bin_id >= gmat.cut.row_ptr[fid + 1]) {
++fid;
}
if (type_[fid] == kDenseColumn) {
uint32_t* begin = &index_[boundary_[fid].index_begin];
begin[rid] = bin_id - index_base_[fid];
} else {
uint32_t* begin = &index_[boundary_[fid].index_begin];
begin[num_nonzeros[fid]] = bin_id - index_base_[fid];
row_ind_[boundary_[fid].row_ind_begin + num_nonzeros[fid]] = rid;
++num_nonzeros[fid];
}
}
}
}
/* Fetch an individual column. This code should be used with XGBOOST_TYPE_SWITCH
to determine type of bin id's */
inline Column GetColumn(unsigned fid) const {
Column c(type_[fid], &index_[boundary_[fid].index_begin], index_base_[fid],
(type_[fid] == ColumnType::kSparseColumn ?
&row_ind_[boundary_[fid].row_ind_begin] : nullptr),
boundary_[fid].index_end - boundary_[fid].index_begin);
return c;
}
private:
struct ColumnBoundary {
// indicate where each column's index and row_ind is stored.
// index_begin and index_end are logical offsets, so they should be converted to
// actual offsets by scaling with packing_factor_
size_t index_begin;
size_t index_end;
size_t row_ind_begin;
size_t row_ind_end;
};
std::vector<size_t> feature_counts_;
std::vector<ColumnType> type_;
SimpleArray<uint32_t> index_; // index_: may store smaller integers; needs padding
SimpleArray<size_t> row_ind_;
std::vector<ColumnBoundary> boundary_;
// index_base_[fid]: least bin id for feature fid
std::vector<uint32_t> index_base_;
};
} // namespace common
} // namespace xgboost
#endif // XGBOOST_COMMON_COLUMN_MATRIX_H_
|
bd_fast.c
|
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h> // access
#include <math.h>
#include <assert.h>
#include "timer.h"
#include "bd.h"
#include <omp.h>
#define NTHREADS 36
#define M_PI 3.14159265358979323846
#define my_EPS 0.000000001
void get_indices(int index, int *i, int *j, int *k, int b){
int ib, ib2;
ib = index%(b); ib2 = index%(b*b);
*k = ib;
*i = (index-ib2)/(b*b);
*j = (ib2-*k)/b;
return;
}
struct box
{
int head;
};
// it is possible to use smaller boxes and more complex neighbor patterns
#define NUM_BOX_NEIGHBORS 14
int box_neighbors[NUM_BOX_NEIGHBORS][3] =
{
{-1,-1,-1},
{-1,-1, 0},
{-1,-1,+1},
{-1, 0,-1},
{-1, 0, 0},
{-1, 0,+1},
{-1,+1,-1},
{-1,+1, 0},
{-1,+1,+1},
{ 0,-1,-1},
{ 0,-1, 0},
{ 0,-1,+1},
{ 0, 0,-1},
{ 0, 0, 0} // will calculate within the box interactions
};
int bd(int npos, double * restrict pos_orig, double * restrict buf, const int *types, double L, double * restrict pos, int* restrict next, double* restrict forces, double f_const)
{
// Initialisations required for INTERACTION FUNCTION******** NOTE: Can take input to bd itself!!!
double krepul = 100, a=1, a_sq, phi=0.2, f;
a_sq = a*a;
int boxdim;// boxdim is number of cells in L
double cutoff2; int numpairs_p;
cutoff2 = 4;// cutoff < L/boxdim
boxdim =(int)(L/cutoff2)*a;//(int)(L/cutoff2*0.8);
printf("L = %lf cutoff2 = %lf boxdim = %d\n", L, cutoff2, boxdim);
struct box b[boxdim][boxdim][boxdim];
struct box *bp;
struct box *neigh_bp;
// box indices
int idx, idy, idz, index, box2, ib2;
int neigh_idx, neigh_idy, neigh_idz;
// allocate implied linked list
int p1, p2, j, i;
double d2, dx, dy, dz, s;
box2 = boxdim*boxdim;
//*****************************************END initialisations***********************************
if (boxdim < 4 || cutoff2 > (L/boxdim)*(L/boxdim))
{
printf("interactions: bad input parameters\n");
// return 1;
}
double t0, t_init_cells = 0, t_assign_to_cells=0, t_update_pos=0, t_force=0;
for (int step=0; step<INTERVAL_LEN; step++)
{
// Calculation of interaction per time step
t0 = time_in_seconds();
// allocate memory for particles in each box
// #pragma omp parallel for schedule(static) private(idx, idy, idz, ib2) shared(b, boxdim, box2)
// for (index=0; index<boxdim*box2; index++){
// idz = index%(boxdim);
// ib2 = index%(box2);
// idx = (index-ib2)/(box2);
// idy = (ib2-idz)/boxdim;
// b[idx][idy][idz].head=-1;
// }
for (idx=0; idx<boxdim; idx++){
for (idy=0; idy<boxdim; idy++){
for (idz=0; idz<boxdim; idz++){
b[idx][idy][idz].head=-1;
}
}
}
t_init_cells += time_in_seconds()-t0;
t0 = time_in_seconds();
// traverse all particles and assign to boxes
#pragma omp parallel for schedule(static) private(i, idx, idy, idz, bp) shared(b, next) num_threads(NTHREADS)
for (i=0; i<npos; i++)
{
if (pos_orig[3*i] >= 0){pos[3*i]= fmod(pos_orig[3*i], L);}// OR SINCE PARTICLES moving slowly.. change to -L
else {// pos_orig[i] is negative
pos[3*i] = L-fmod(-1*pos_orig[3*i], L);
}
if (pos_orig[3*i+1] >= 0){pos[3*i+1]= fmod(pos_orig[3*i+1], L);}// OR SINCE PARTICLES moving slowly.. change to -L
else {// pos_orig[i] is negative
pos[3*i+1] = L-fmod(-1*pos_orig[3*i+1], L);
}
if (pos_orig[3*i+2] >= 0){pos[3*i+2]= fmod(pos_orig[3*i+2], L);}// OR SINCE PARTICLES moving slowly.. change to -L
else {// pos_orig[i] is negative
pos[3*i+2] = L-fmod(-1*pos_orig[3*i+2], L);
}
if (pos[3*i]<0){printf("pos_orig = %lf pos defect = %lf and i = %d and L =%lf\n", pos_orig[3*i], pos[3*i], i, L);}
// initialize entry of implied linked list
next[i] = -1;
forces[3*i+0] = 0; forces[3*i+1] = 0; forces[3*i+2] = 0; // re-initialising interaction forces at each time step
// which box does the particle belong to?
// assumes particles have positions within [0,L]^3
idx = (int)(pos[3*i ]/L*boxdim);
idy = (int)(pos[3*i+1]/L*boxdim);
idz = (int)(pos[3*i+2]/L*boxdim);
// add to beginning of implied linked list
bp = &b[idx][idy][idz];
// next[i] = bp->head; // next = previous (my notation)
// #pragma omp critical
// {
next[i] = bp->head; // next = previous (my notation)
bp->head = i; // head = latest (my notation)
// }
}
t_assign_to_cells += time_in_seconds()-t0;
t0 = time_in_seconds();
#pragma omp parallel for schedule(static) private(j, neigh_idx, neigh_idy, neigh_idz, neigh_bp, p1, p2, dx, dy, dz, d2, s, f, idx, idy, idz, ib2, bp) shared(b, box_neighbors, boxdim, L, pos, forces, krepul, a, a_sq, next, box2) num_threads(NTHREADS)
for (index=0; index<boxdim*box2; index++){
idz = index%(boxdim);
ib2 = index%(box2);
idx = (index-ib2)/(box2);
idy = (ib2-idz)/boxdim;
bp = &b[idx][idy][idz];
// interactions within and other boxes
#pragma omp parallel for schedule(static) private(j, neigh_idx, neigh_idy, neigh_idz, neigh_bp, p1, p2, dx, dy, dz, d2, s, f) shared(bp, b, box_neighbors, boxdim, L, pos, forces, krepul, a, a_sq, next, idx, idy, idz)// num_threads(NTHREADS)
for (j=0; j<NUM_BOX_NEIGHBORS; j++)
{
neigh_idx = (idx + box_neighbors[j][0] + boxdim) % boxdim;
neigh_idy = (idy + box_neighbors[j][1] + boxdim) % boxdim;
neigh_idz = (idz + box_neighbors[j][2] + boxdim) % boxdim;
neigh_bp = &b[neigh_idx][neigh_idy][neigh_idz];
// when using boxes, the minimum image computation is
// known beforehand, thus we can compute position offsets
// to compensate for wraparound when computing distances
double xoffset = 0.;
double yoffset = 0.;
double zoffset = 0.;
if (idx + box_neighbors[j][0] == -1) xoffset = -L;
if (idy + box_neighbors[j][1] == -1) yoffset = -L;
if (idz + box_neighbors[j][2] == -1) zoffset = -L;
if (idx + box_neighbors[j][0] == boxdim) xoffset = L;
if (idy + box_neighbors[j][1] == boxdim) yoffset = L;
if (idz + box_neighbors[j][2] == boxdim) zoffset = L;
// NOTE: modifying the function to update the forces
p1 = neigh_bp->head;
while (p1 != -1)
{
p2 = bp->head;
while (p2 != -1)
{
// compute distance vector
dx = pos[3*p1+0] - pos[3*p2+0] + xoffset;
dy = pos[3*p1+1] - pos[3*p2+1] + yoffset;
dz = pos[3*p1+2] - pos[3*p2+2] + zoffset;
d2 = dx*dx+dy*dy+dz*dz+my_EPS;
if ( d2<4.0*a_sq)
{
s = sqrt(d2);
f = krepul*(2*a-s);
#pragma omp atomic
forces[3*p1+0] += f*dx/s;
#pragma omp atomic
forces[3*p1+1] += f*dy/s;
#pragma omp atomic
forces[3*p1+2] += f*dz/s;
#pragma omp atomic
forces[3*p2+0] -= f*dx/s;
#pragma omp atomic
forces[3*p2+1] -= f*dy/s;
#pragma omp atomic
forces[3*p2+2] -= f*dz/s;
}
p2 = next[p2];
}
p1 = next[p1];
}
}
}
t_force += time_in_seconds() - t0;
t0 = time_in_seconds();
// generate random values from standard normal distribution
// note: this MKL function is sequential but vectorized
vdRngGaussian(VSL_RNG_METHOD_GAUSSIAN_BOXMULLER, stream, 3*npos, buf, 0., 1.);
// update positions with Brownian displacements
#pragma omp parallel for schedule(static) shared(pos_orig) private(i) num_threads(NTHREADS)
for (int i=0; i<3*npos; i++)
{
pos_orig[i] += forces[i]*DELTAT+f_const*buf[i];
}
t_update_pos += time_in_seconds() - t0;
}
printf("--------------------------------------------------------\n");
printf("Time: %f for initiating the cell head \n", t_init_cells);
printf("Time: %f for assigning particles to cells \n", t_assign_to_cells);
printf("Time: %f for force calculations \n", t_force);
printf("Time: %f for pos update \n", t_update_pos);
printf("--------------------------------------------------------\n");
return 0;
}
|
space.h
|
#ifndef MATH_SPACE_H
#define MATH_SPACE_H
namespace math {
namespace space {
inline
arma::uword
indices_to_index(const arma::uvec & indices, const arma::uvec & table) {
assert(indices.n_elem == table.n_elem);
const arma::uword dims = table.n_elem;
arma::uword index = 0;
for (arma::uword i = 0; i < dims; i++) {
index += table(i) * indices(i);
}
return index;
}
inline
arma::uvec index_to_indices(const arma::uword index, const arma::uvec & table) {
const arma::uword dims = table.n_elem;
arma::uvec indices = arma::uvec(dims, arma::fill::zeros);
arma::uword i = 0;
arma::uword downgraded_index = index;
for (i = 0; i < dims - 1; i++) {
if (index < table(i)) break;
}
for (arma::uword j = i; j > 0; j--) {
indices(j) = downgraded_index / table(j);
downgraded_index = downgraded_index % table(j);
}
indices(0) = downgraded_index / table(0);
return indices;
}
inline
arma::uvec grids_to_table(const arma::uvec & grids) {
const arma::uword dims = grids.n_elem;
arma::uword table_index = 1;
arma::uvec table = arma::uvec(dims);
for (arma::uword i = 0; i < dims; i++) {
table(i) = table_index;
table_index *= grids(i);
}
return table;
}
inline
arma::umat auto_iteration_over_dims(const arma::uvec & grid) {
const arma::uvec table = grids_to_table(grid);
const auto n_elem = arma::prod(grid);
const auto dim = grid.n_elem;
arma::umat result = arma::umat(dim, n_elem);
#pragma omp parallel for
for (arma::uword i = 0; i < n_elem; i++) {
result.col(i) = index_to_indices(i, table);
}
return result;
}
inline
arma::mat points_generate(const arma::uvec & grids,
const arma::mat & begin_end_list) {
const arma::vec begin_list = begin_end_list.col(0);
const arma::vec end_list = begin_end_list.col(1);
const arma::vec diff = end_list - begin_list;
assert(grids.n_elem == begin_end_list.n_rows);
const arma::vec steps = diff / (grids - arma::ones(grids.n_elem));
const auto iterations = space::auto_iteration_over_dims(grids);
arma::mat centers = arma::mat(arma::size(iterations));
#pragma omp parallel for
for (arma::uword i = 0; i < iterations.n_cols; i++) {
centers.col(i) = iterations.col(i) % steps + begin_list;
}
return centers;
}
}
}
#endif //MATH_SPACE_H
|
reduce3.h
|
/*
* reduce3.h
*
* Created on: Dec 28, 2015
* Author: agibsonccc
*/
#ifndef REDUCE3_H_
#define REDUCE3_H_
#define EXTRA_PARAMS_LENGTH 10
#include <templatemath.h>
#include <helper_cuda.h>
#include <helpers/sharedmem.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#include <pairwise_util.h>
#include <dll.h>
#include <helpers/shape.h>
#include <ops/ops.h>
#include <op_boilerplate.h>
#ifdef __CUDACC__
#include <cuda.h>
#include <cuda_runtime.h>
#endif
#ifndef _OPENMP
#define omp_get_thread_num() 0
#define omp_get_max_threads() 1
#endif
#include "legacy_ops.h"
namespace functions {
namespace reduce3 {
/**
* Reduce involving
* 2 arrays
*/
template<typename T>
class Reduce3 {
public:
#ifdef __CUDACC__
virtual __device__
inline T opAtomic(T d1, T d2, T *extraParamsRef) = 0;
#endif
#ifdef __CUDACC__
/**
* Aggregate shared memory
* @param sPartialsRef
* @param tid
* @param extraParams
*/
template<typename OpType>
static __inline__ __device__ void aggregatePartials(T **sPartialsRef, int tid, int numItems, T *extraParamsRef) {
// start the shared memory loop on the next power of 2 less
// than the block size. If block size is not a power of 2,
// accumulate the intermediate sums in the remainder range.
T *sPartials = *sPartialsRef;
int floorPow2 = numItems;
if (floorPow2 & (floorPow2 - 1)) {
while (floorPow2 & (floorPow2 - 1)) {
floorPow2 &= floorPow2 - 1;
}
if (tid >= floorPow2) {
sPartials[tid - floorPow2] = OpType::update(sPartials[tid - floorPow2], sPartials[tid], extraParamsRef);
}
__syncthreads();
}
for (int activeThreads = floorPow2 >> 1; activeThreads; activeThreads >>= 1) {
if (tid < activeThreads) {
sPartials[tid] = OpType::update(sPartials[tid], sPartials[tid + activeThreads], extraParamsRef);
}
__syncthreads();
}
}
/**
Perform a reduction
@param n the number of elements
@param xOffset the starting offset
@param dx the data to perform the reduction on
@param incx the increment on which to perform the reduction
@param extraParams extra parameters used for calculations
@param result where to store the result of the reduction
*/
virtual __inline__ __device__ void transformNoElementWiseStride(
T *dx,
int *xShapeInfo,
T *dy,
int *yShapeInfo,
T *extraParams,
T *result,
int *resultShapeInfo,
int postProcessOrNot, int *allocationPointer, UnifiedSharedMemory *manager, int *tadOnlyShapeInfo) {
Nd4jIndex n = shape::length(xShapeInfo);
int rank = shape::rank(xShapeInfo);
T *sPartials = (T *) manager->getSharedReductionBuffer(); //val.getPointer();
T startingVal = this->startingValue(dx);
// FIXME: this ugly fast fix.
__shared__ T extraZ[2];
if (threadIdx.x == 0) {
extraZ[0] = (T) 0.0;
extraZ[1] = (T) 0.0;
}
sPartials[threadIdx.x] = startingVal;
__syncthreads();
int idx[MAX_RANK];
for(Nd4jIndex i = blockIdx.x * gridDim.x + threadIdx.x; i < n; i += gridDim.x * blockDim.x) {
shape::ind2subC(rank,shape::shapeOf(xShapeInfo),i, idx);
Nd4jIndex offset = shape::getOffset(0,shape::shapeOf(xShapeInfo),shape::stride(xShapeInfo),idx,rank);
Nd4jIndex yOffset = shape::getOffset(0,shape::shapeOf(yShapeInfo),shape::stride(yShapeInfo),idx,rank);
sPartials[threadIdx.x] = update(sPartials[threadIdx.x], this->opAtomic(dx[offset], dy[yOffset], extraZ), extraZ);
}
T **sPartialsRef = (T **) &sPartials;
aggregatePartials(sPartialsRef, threadIdx.x, nd4j::math::nd4j_min<int>(blockDim.x, n), extraZ);
/**
* Look at something that uses the extra params
* and aggregates the extra values propelry.
*This will be used in summary stats too.
*/
// write result for this block to global mem
if (threadIdx.x == 0) {
if (postProcessOrNot) {
result[blockIdx.x] = postProcess(sPartials[0], n, extraZ);
}
else {
result[blockIdx.x] = sPartials[0];
}
}
}
/**
*
*/
template<typename OpType>
static inline __device__ void execScalarCuda(
T *dx,
int *xShapeInfo,
T *dy,
int *yShapeInfo,
T *extraParams,
T *result,
int *resultShapeInfo, int *allocationPointer, T *reductionBuffer, UnifiedSharedMemory *manager, int *tadOnlyShapeInfo) {
// SharedMemory <T> val;
T *sPartials = (T *) manager->getSharedReductionBuffer(); // val.getPointer();
// FIXME: this ugly fast fix.
__shared__ T extraZ[3];
if (threadIdx.x == 0) {
extraZ[0] = (T) 0.0f;
extraZ[1] = (T) 0.0f;
if (extraParams != NULL) {
extraZ[2] = extraParams[0];
} else extraZ[2] = (T) 0.0f;
}
__syncthreads();
T startingVal = OpType::startingValue(dx);
Nd4jIndex length = shape::length(xShapeInfo);
int xElementWiseStride = shape::elementWiseStride(xShapeInfo);
int yElementWiseStride = shape::elementWiseStride(yShapeInfo);
int tid = blockIdx.x * blockDim.x + threadIdx.x;
char xOrder = shape::order(xShapeInfo);
char yOrder = shape::order(yShapeInfo);
if(xOrder == yOrder && (xElementWiseStride > 0 && yElementWiseStride > 0) && shape::strideDescendingCAscendingF(xShapeInfo) && shape::strideDescendingCAscendingF(yShapeInfo)) {
if (xElementWiseStride == 1 && yElementWiseStride == 1) {
for(Nd4jIndex i = tid; i < length; i+= gridDim.x * blockDim.x) {
startingVal = OpType::update(startingVal, OpType::opAtomic(dx[i], dy[i], extraZ), extraZ);
}
}
else {
for(Nd4jIndex i = tid; i < length; i+= gridDim.x * blockDim.x) {
startingVal = OpType::update(startingVal, OpType::opAtomic(dx[i * xElementWiseStride], dy[i * yElementWiseStride], extraZ), extraZ);
}
}
sPartials[threadIdx.x] = startingVal;
} else {
__shared__ int *xShape;
__shared__ int *yShape;
__shared__ int *xStride;
__shared__ int *yStride;
__shared__ int rank;
if (threadIdx.x == 0) {
xShape = shape::shapeOf(xShapeInfo);
yShape = shape::shapeOf(yShapeInfo);
xStride = shape::stride(xShapeInfo);
yStride = shape::stride(yShapeInfo);
rank = shape::rank(xShapeInfo);
}
__syncthreads();
T startingVal = OpType::startingValue(dx);
T *sPartials = (T *) manager->getSharedReductionBuffer();
int xCoords[MAX_RANK];
int yCoords[MAX_RANK];
sPartials[threadIdx.x] = startingVal;
for(unsigned int i = tid ;i < length; i += gridDim.x * blockDim.x) {
shape::ind2subC(rank,xShape,i,xCoords);
shape::ind2subC(rank,yShape,i,yCoords);
Nd4jIndex offset = shape::getOffset(0, xShape, xStride, xCoords,rank);
Nd4jIndex yOffset = shape::getOffset(0,yShape, yStride, yCoords,rank);
sPartials[threadIdx.x] = OpType::update(sPartials[threadIdx.x], OpType::opAtomic(dx[offset], dy[yOffset], extraZ), extraZ);
}
}
__syncthreads();
T **sPartialsRef = (T **) &sPartials;
aggregatePartials<OpType>(sPartialsRef, threadIdx.x, nd4j::math::nd4j_min<int>(blockDim.x, length), extraZ);
__syncthreads();
if (gridDim.x > 1) {
unsigned int *tc = (unsigned int *)reductionBuffer;
__shared__ bool amLast;
int rank = shape::rank(xShapeInfo);
tid = threadIdx.x;
T *extraBuffer = (T *) allocationPointer;
if (threadIdx.x == 0) {
reductionBuffer[blockIdx.x] = sPartials[0];
extraBuffer[blockIdx.x] = extraZ[0];
extraBuffer[gridDim.x + blockIdx.x] = extraZ[1];
}
__threadfence();
__syncthreads();
if (threadIdx.x == 0) {
unsigned int ticket = atomicInc(&tc[16384], gridDim.x);
amLast = (ticket == gridDim.x - 1);
}
sPartials[tid] = startingVal;
__syncthreads();
if (amLast) {
tc[16384] = 0;
sPartials[threadIdx.x] = OpType::startingValue(dx);
// TODO: later probably replace this. Right now we need extraZ sync for CosineSimilarity ONLY
if (tid == 0 && extraZ[0] != (T) 0.0 && extraZ[1] != (T) 0.0) {
extraZ[0] = 0.0;
extraZ[1] = 0.0;
for (int i = 0; i < gridDim.x; i++) {
extraZ[0] += extraBuffer[i];
extraZ[1] += extraBuffer[gridDim.x + i];
}
}
for (Nd4jIndex i = threadIdx.x; i < gridDim.x; i += blockDim.x) {
sPartials[threadIdx.x] = OpType::update(sPartials[threadIdx.x], reductionBuffer[i], extraZ);
}
__syncthreads();
aggregatePartials<OpType>(sPartialsRef, threadIdx.x, nd4j::math::nd4j_min<int>(gridDim.x, blockDim.x), extraZ);
__syncthreads();
if (threadIdx.x == 0) {
result[0] = OpType::postProcess(sPartials[0], length, extraZ);
}
}
} else {
if (tid == 0) {
unsigned int *tc = (unsigned *)reductionBuffer;
tc[16384] = 0;
result[0] = OpType::postProcess(sPartials[0], length, extraZ);
}
}
}
template<typename OpType>
__device__
static inline void transformAll(
T *dx,
int *xShapeInfo,
T *dy,
int *yShapeInfo,
T *extraParams,
T *result,
int *resultShapeInfo,
int *dimension,
int dimensionLength,
int postProcessOrNot,
int *allocationPointer,
UnifiedSharedMemory *manager,
int *xTadShapeInfo,
Nd4jIndex *xOffsets,
int *yTadShapeInfo,
Nd4jIndex *yOffsets) {
// initialize partials first
T *sPartials = (T *) manager->getSharedReductionBuffer();
T startingVal = OpType::startingValue(dx);
sPartials[threadIdx.x] = startingVal;
T *tempX = sPartials + blockDim.x;
const int maxBlock = blockDim.x;
__shared__ T extraZ[OpType::extraParamsLen > 0 ? OpType::extraParamsLen : 1];
__shared__ int xTadLength;
__shared__ int yTadLength;
__shared__ int xTads;
__shared__ int yTads;
__shared__ int *xShape;
__shared__ int *xStride;
__shared__ int xRank;
__shared__ int *yShape;
__shared__ int *yStride;
__shared__ int yRank;
//reading initial data
if (threadIdx.x == 0) {
xTadLength = shape::tadLength(xShapeInfo, dimension, dimensionLength);
yTadLength = shape::tadLength(yShapeInfo, dimension, dimensionLength);
xTads = shape::length(xShapeInfo) / xTadLength;
yTads = shape::length(yShapeInfo) / yTadLength;
xShape = shape::shapeOf(xTadShapeInfo);
xStride = shape::stride(xTadShapeInfo);
xRank = shape::rank(xTadShapeInfo);
yShape = shape::shapeOf(yTadShapeInfo);
yStride = shape::stride(yTadShapeInfo);
yRank = shape::rank(yTadShapeInfo);
}
__syncthreads();
int xCoord[MAX_RANK];
int yCoord[MAX_RANK];
int limit = xTadLength / maxBlock;
if (xTadLength % maxBlock > 0)
limit++;
for (int r = blockIdx.x; r < xTads; r += blockDim.x * gridDim.x) {
T *x = dx + xOffsets[r];
if (threadIdx.x < xTadLength && threadIdx.x < maxBlock) {
if (shape::order(xTadShapeInfo) == 'c') {
shape::ind2subC(xRank, xShape, threadIdx.x, xCoord);
} else {
shape::ind2sub(xRank, xShape, threadIdx.x, xCoord);
}
Nd4jIndex xO = shape::getOffset(0, xShape, xStride, xCoord, xRank);
tempX[threadIdx.x] = x[xO];
}
for (int g = 0; g < yTads; g++) {
T *y = dy + yOffsets[g];
int ri = (r * yTads) + g;
sPartials[threadIdx.x] = startingVal;
if (OpType::extraParamsLen > 0 && threadIdx.x < OpType::extraParamsLen) {
extraZ[threadIdx.x] = (T) startingVal;
}
__syncthreads();
// we might have data too large for single cache block, rendering cache useless though :(
for (int t = 0; t < limit; t++) {
// we reset tempX IF we have >1 tiles
if (t >= 1 || (limit > 1 && g > 0))
if (threadIdx.x + (t * maxBlock) < xTadLength) {
if (shape::order(xTadShapeInfo) == 'c') {
shape::ind2subC(xRank, xShape, threadIdx.x + (t * maxBlock), xCoord);
} else {
shape::ind2sub(xRank, xShape, threadIdx.x + (t * maxBlock), xCoord);
}
Nd4jIndex xO = shape::getOffset(0, xShape, xStride, xCoord, xRank);
tempX[threadIdx.x] = x[xO];
// tempX[threadIdx.x] = x[threadIdx.x + (t * maxBlock)];
}
for (int f = threadIdx.x + (t * maxBlock); f < xTadLength && f < threadIdx.x + ((t + 1) * maxBlock); f += blockDim.x * gridDim.x) {
if (shape::order(yTadShapeInfo) == 'c') {
shape::ind2subC(yRank, yShape, f, yCoord);
} else {
shape::ind2sub(yRank, yShape, f, yCoord);
}
Nd4jIndex yO = shape::getOffset(0, yShape, yStride, yCoord, yRank);
sPartials[threadIdx.x] = OpType::update(sPartials[threadIdx.x], OpType::opAtomic(tempX[threadIdx.x], y[yO], extraZ), extraZ);
}
// we MUST step through this block altogether
__syncthreads();
}
T **sPartialsRef = (T **) &sPartials;
aggregatePartials<OpType>(sPartialsRef, threadIdx.x, nd4j::math::nd4j_min<int>(blockDim.x, xTadLength), extraZ);
__syncthreads();
if (threadIdx.x == 0) {
result[ri] = OpType::postProcess(sPartials[threadIdx.x],xTadLength, extraZ);
}
__syncthreads();
}
}
}
/**
Perform a reduction
@param n the number of elements
@param xOffset the starting offset
@param dx the data to perform the reduction on
@param incx the increment on which to perform the reduction
@param extraParams extra parameters used for calculations
@param result where to store the result of the reduction
*/
template<typename OpType>
__device__
static inline void transform(
T *dx,
int *xShapeInfo,
T *dy,
int *yShapeInfo,
T *extraParams,
T *result,
int *resultShapeInfo,
int *dimension,
int dimensionLength,
int postProcessOrNot,
int *allocationPointer,
UnifiedSharedMemory *manager,
int *tadOnlyShapeInfo,
Nd4jIndex *tadOffsets,
int *yTadOnlyShapeInfo,
Nd4jIndex *yTadOffsets) {
/**
* Gpu information for the problem
*/
int tid = threadIdx.x + blockIdx.x * blockDim.x;
__shared__ int resultScalar;
__shared__ int xElementWiseStride;
__shared__ int yElementWiseStride;
//shared memory space for storing intermediate results
//SharedMemory <T> val;
T *sPartials = (T *) manager->getSharedReductionBuffer(); //val.getPointer();
T init = OpType::startingValue(dx);
sPartials[threadIdx.x] = init;
__shared__ T extraZ[OpType::extraParamsLen > 0 ? OpType::extraParamsLen : 1];
//length for the tad
__shared__ Nd4jIndex resultLength;
__shared__ int tadLength;
__shared__ int yLength;
__shared__ int tadElementWiseStride;
__shared__ int yTadElementWiseStride;
T startingVal = OpType::startingValue(dx);
T reduction = OpType::startingValue(dx);
if (threadIdx.x == 0) {
if (resultShapeInfo != nullptr)
resultLength = shape::length(resultShapeInfo);
else resultLength = 1;
if (dimensionLength == 1) {
if (dimension == nullptr || dimension[0] == MAX_DIMENSION)
resultScalar = 1;
else
resultScalar = 0;
}
else
resultScalar = 0;
if (resultLength == 1)
resultScalar = 1;
int *xStride = shape::stride(xShapeInfo);
char xOrder = shape::order(xShapeInfo);
tadLength = shape::tadLength(xShapeInfo, dimension, dimensionLength);
tadElementWiseStride = shape::elementWiseStride(tadOnlyShapeInfo);
yLength = shape::length(yShapeInfo);
if (yTadOnlyShapeInfo != nullptr)
yTadElementWiseStride = shape::elementWiseStride(yTadOnlyShapeInfo);
}
__syncthreads();
// code branch for TAD vs full array
if (tadLength == yLength) {
int xCoord[MAX_RANK];
int yCoord[MAX_RANK];
int *yShape = shape::shapeOf(yShapeInfo);
int *yStride = shape::stride(yShapeInfo);
int *xShape = shape::shapeOf(tadOnlyShapeInfo);
int *xStride = shape::stride(tadOnlyShapeInfo);
int yRank = shape::rank(yShapeInfo);
int xRank = shape::rank(tadOnlyShapeInfo);
for(int i = blockIdx.x; i < resultLength; i+= gridDim.x) {
int xOffsetForTad = tadOffsets[i];
if (OpType::extraParamsLen > 0 && threadIdx.x < OpType::extraParamsLen) {
extraZ[threadIdx.x] = (T) startingVal;
}
__syncthreads();
for(int j = threadIdx.x; j < tadLength; j += blockDim.x) {
shape::ind2subC(xRank,xShape, j, xCoord);
shape::ind2subC(yRank,yShape, j, yCoord);
Nd4jIndex xOffset = shape::getOffset(xOffsetForTad, xShape, xStride, xCoord, xRank);
Nd4jIndex yOffset = shape::getOffset(0, yShape, yStride, yCoord, yRank);
sPartials[threadIdx.x] = j < blockDim.x ? OpType::opAtomic(dx[xOffset],dy[yOffset], extraZ) : OpType::update(sPartials[threadIdx.x], OpType::opAtomic(dx[xOffset],dy[yOffset], extraZ), extraZ);
}
__syncthreads();
T **sPartialsRef = (T **) &sPartials;
aggregatePartials<OpType>(sPartialsRef, threadIdx.x, nd4j::math::nd4j_min<int>(blockDim.x, tadLength), extraZ);
__syncthreads();
if (threadIdx.x == 0)
result[i] = OpType::postProcess(sPartials[threadIdx.x],tadLength, extraZ);
__syncthreads();
}
} else if (!resultScalar) {
if(tadElementWiseStride >= 1 && yTadElementWiseStride) {
for(int i = blockIdx.x; i < resultLength; i+= gridDim.x) {
int xOffsetForTad = tadOffsets[i];
int yOffsetForTad = yTadOffsets[i];
if (OpType::extraParamsLen > 0 && threadIdx.x < OpType::extraParamsLen) {
extraZ[threadIdx.x] = (T) startingVal;
}
__syncthreads();
if (threadIdx.x < tadLength)
sPartials[threadIdx.x] = OpType::op(dx[xOffsetForTad + tadElementWiseStride * threadIdx.x],dy[yOffsetForTad + yTadElementWiseStride * threadIdx.x], extraZ);
for(int j = threadIdx.x + blockDim.x; j < tadLength; j += blockDim.x) {
sPartials[threadIdx.x] = OpType::update(sPartials[threadIdx.x], OpType::op(dx[xOffsetForTad + tadElementWiseStride * j],dy[yOffsetForTad + yTadElementWiseStride * j], extraZ), extraZ);
}
__syncthreads();
T **sPartialsRef = (T **) &sPartials;
aggregatePartials<OpType>(sPartialsRef, threadIdx.x, nd4j::math::nd4j_min<int>(blockDim.x, tadLength), extraZ);
__syncthreads();
if (threadIdx.x == 0)
result[i] = OpType::postProcess(sPartials[threadIdx.x],tadLength, extraZ);
__syncthreads();
}
}
else {
/*
// DO NOT REMOVE THIS COMMENTED BLOCK PLEASE
for (int r = blockIdx.x; r < tad->numTads; r += gridDim.x) {
if (threadIdx.x == 0)
tad->createOffsetForBlock(r);
__syncthreads();
int tadOffsetForBlock = tad->tadOffsetForBlock;
T *xVal = dx + tadOffsetForBlock;
sPartials[threadIdx.x] = this->startingValue(xVal);
for(int i = threadIdx.x; i < tad->tadLength; i+= blockDim.x) {
int xOffsetForTad = shape::tadOffset(i, xShapeInfo, dimension, dimensionLength, nullptr);
int yOffsetForTad = shape::tadOffset(i, yShapeInfo, dimension, dimensionLength, nullptr);
sPartials[threadIdx.x] = this->update(sPartials[threadIdx.x],dx[tadOffsetForBlock + i * tad->tadElementWiseStride], extraParams);
}
__syncthreads();
// aggregate. do NOT reduce for elements > tadLength
T **sPartialsRef = (T **) &sPartials;
aggregatePartials(sPartialsRef, threadIdx.x, nd4j::math::nd4j_min<int>(blockDim.x, tad->tadLength), extraParams);
__syncthreads();
if (threadIdx.x == 0)
result[r] = this->postProcess(sPartials[threadIdx.x], tad->tadLength, extraParams);
}
*/
int xCoord[MAX_RANK];
int yCoord[MAX_RANK];
int *yShape = shape::shapeOf(yTadOnlyShapeInfo);
int *yStride = shape::stride(yTadOnlyShapeInfo);
int *xShape = shape::shapeOf(tadOnlyShapeInfo);
int *xStride = shape::stride(tadOnlyShapeInfo);
int yRank = shape::rank(yTadOnlyShapeInfo);
int xRank = shape::rank(tadOnlyShapeInfo);
for(int i = blockIdx.x; i < resultLength; i+= gridDim.x) {
int xOffsetForTad = tadOffsets[i];
int yOffsetForTad = yTadOffsets[i];
if (OpType::extraParamsLen > 0 && threadIdx.x < OpType::extraParamsLen) {
extraZ[threadIdx.x] = (T) startingVal;
}
__syncthreads();
for(int j = threadIdx.x; j < tadLength; j += blockDim.x) {
shape::ind2subC(xRank,xShape, j, xCoord);
shape::ind2subC(yRank,yShape, j, yCoord);
Nd4jIndex xOffset = shape::getOffset(xOffsetForTad, xShape, xStride, xCoord, xRank);
Nd4jIndex yOffset = shape::getOffset(yOffsetForTad, yShape, yStride, yCoord, yRank);
sPartials[threadIdx.x] = j < blockDim.x ? OpType::opAtomic(dx[xOffset],dy[yOffset], extraZ) : OpType::update(sPartials[threadIdx.x], OpType::opAtomic(dx[xOffset],dy[yOffset], extraZ), extraZ);
}
__syncthreads();
T **sPartialsRef = (T **) &sPartials;
aggregatePartials<OpType>(sPartialsRef, threadIdx.x, nd4j::math::nd4j_min<int>(blockDim.x, tadLength), extraZ);
__syncthreads();
if (threadIdx.x == 0)
result[i] = OpType::postProcess(sPartials[threadIdx.x],tadLength, extraZ);
__syncthreads();
}
}
}
}
#endif
#ifdef __CUDACC__
__device__
static inline void exec(
const int opNum,
T *dx,
int *xShapeInfo,
T *dy,
int *yShapeInfo,
T *extraParams,
T *result,
int *resultShapeInfo,
int *dimension,
int dimensionLength,
int postProcessOrNot,
int *allocationPointer,
UnifiedSharedMemory *manager,
int *tadOnlyShapeInfo,
Nd4jIndex *tadOffsets,
int *yTadOnlyShapeInfo,
Nd4jIndex *yTadOffsets) {
DISPATCH_BY_OPNUM(transform, PARAMS(dx, xShapeInfo, dy, yShapeInfo, extraParams, result, resultShapeInfo, dimension, dimensionLength, postProcessOrNot, allocationPointer, manager, tadOnlyShapeInfo, tadOffsets, yTadOnlyShapeInfo, yTadOffsets), REDUCE3_OPS);
}
__device__
static inline void execAllCuda(
const int opNum,
T *dx,
int *xShapeInfo,
T *dy,
int *yShapeInfo,
T *extraParams,
T *result,
int *resultShapeInfo,
int *dimension,
int dimensionLength,
int postProcessOrNot,
int *allocationPointer,
UnifiedSharedMemory *manager,
int *tadOnlyShapeInfo,
Nd4jIndex *tadOffsets,
int *yTadOnlyShapeInfo,
Nd4jIndex *yTadOffsets) {
DISPATCH_BY_OPNUM(transformAll, PARAMS(dx, xShapeInfo, dy, yShapeInfo, extraParams, result, resultShapeInfo, dimension, dimensionLength, postProcessOrNot, allocationPointer, manager, tadOnlyShapeInfo, tadOffsets, yTadOnlyShapeInfo, yTadOffsets), REDUCE3_OPS);
}
__device__
static inline void execScalarCuda(
const int opNum,
T *dx,
int *xShapeInfo,
T *dy,
int *yShapeInfo,
T *extraParams,
T *result,
int *resultShapeInfo,
int * allocationPointer,
T *reductionBuffer,
UnifiedSharedMemory *manager,
int *tadOnlyShapeInfo) {
DISPATCH_BY_OPNUM(execScalarCuda, PARAMS(dx, xShapeInfo, dy, yShapeInfo, extraParams, result, resultShapeInfo, allocationPointer, reductionBuffer, manager, tadOnlyShapeInfo), REDUCE3_OPS);
}
#endif
#ifdef __CUDACC__
__host__
#endif
static T execScalar(
const int opNum,
T *x,
int *xShapeInfo,
T *extraParamsVals,
T *y,
int *yShapeInfo) {
RETURNING_DISPATCH_BY_OPNUM(execScalar, PARAMS(x,
xShapeInfo,
extraParamsVals,
y,
yShapeInfo), REDUCE3_OPS);
}
static void exec( const int opNum,
T *x, int *xShapeInfo,
T *extraParamsVals,
T *y,
int *yShapeInfo,
T *result,
int *resultShapeInfoBuffer,
int *dimension,
int dimensionLength) {
DISPATCH_BY_OPNUM(exec, PARAMS(x,
xShapeInfo,
extraParamsVals,
y, yShapeInfo,
result,
resultShapeInfoBuffer,
dimension,
dimensionLength), REDUCE3_OPS);
}
static void exec( const int opNum,
T *x, int *xShapeInfo,
T *extraParamsVals,
T *y,
int *yShapeInfo,
T *result,
int *resultShapeInfoBuffer,
int *dimension,
int dimensionLength, int *tadShapeInfo, Nd4jIndex *tadOffsets) {
DISPATCH_BY_OPNUM(exec, PARAMS(x,
xShapeInfo,
extraParamsVals,
y, yShapeInfo,
result,
resultShapeInfoBuffer,
dimension,
dimensionLength, tadShapeInfo, tadOffsets), REDUCE3_OPS);
}
static void execAll( const int opNum,
T *x,
int *xShapeInfo,
T *extraParamsVals,
T *y,
int *yShapeInfo,
T *result,
int *resultShapeInfoBuffer,
int *dimension,
int dimensionLength,
int *xTadShapeInfo, Nd4jIndex *xOffsets,
int *yTadShapeInfo, Nd4jIndex *yOffsets) {
DISPATCH_BY_OPNUM(execAll, PARAMS(x,
xShapeInfo,
extraParamsVals,
y, yShapeInfo,
result,
resultShapeInfoBuffer,
dimension,
dimensionLength, xTadShapeInfo, xOffsets, yTadShapeInfo, yOffsets), REDUCE3_OPS);
}
template<typename OpType>
#ifdef __CUDACC__
__host__
#endif
static T execScalar(
T *x,
int *xShapeInfo,
T *extraParams,
T *y,
int *yShapeInfo) {
T startingVal = OpType::startingValue(x);
Nd4jIndex length = shape::length(xShapeInfo);
int xElementWiseStride = shape::elementWiseStride(xShapeInfo);
int yElementWiseStride = shape::elementWiseStride(yShapeInfo);
T extraParamsVals[3] = {(T) 0.0, (T) 0.0, (T) 0.0};
// it's possible case for EqualsWithEps op
if (extraParams != nullptr) {
extraParamsVals[2] = extraParams[0];
}
char xOrder = shape::order(xShapeInfo);
char yOrder = shape::order(yShapeInfo);
if(xOrder == yOrder && (xElementWiseStride >=1 && yElementWiseStride >= 1) && shape::strideDescendingCAscendingF(xShapeInfo) && shape::strideDescendingCAscendingF(yShapeInfo)) {
if (xElementWiseStride == 1 && yElementWiseStride == 1) {
// TODO:: proper reduction required here
for(int i = 0; i < length; i++) {
startingVal = OpType::update(startingVal,
OpType::op(x[i],y[i],
extraParamsVals),
extraParamsVals);
}
return OpType::postProcess(startingVal, length, extraParamsVals);
}
else {
// TODO:: proper reduction required here
for(Nd4jIndex i = 0; i < length; i++) {
startingVal = OpType::update(startingVal, OpType::op(x[i * xElementWiseStride],y[i * yElementWiseStride], extraParamsVals), extraParamsVals);
}
return OpType::postProcess(startingVal, length, extraParamsVals);
}
}
else {
int xCoords[MAX_RANK];
int yCoords[MAX_RANK];
int xRank = shape::rank(xShapeInfo);
int yRank = shape::rank(yShapeInfo);
int *xShape = shape::shapeOf(xShapeInfo);
int *xStride = shape::stride(xShapeInfo);
int *yShape = shape::shapeOf(yShapeInfo);
int *yStride = shape::stride(yShapeInfo);
for(unsigned int i = 0 ;i < length; i++) {
shape::ind2subC(xRank, xShape, i, xCoords);
shape::ind2subC(yRank, yShape, i, yCoords);
Nd4jIndex offset = shape::getOffset(0, xShape, xStride, xCoords, xRank);
Nd4jIndex yOffset = shape::getOffset(0, yShape, yStride, yCoords, yRank);
startingVal = OpType::update(startingVal, OpType::op(x[offset], y[yOffset], extraParamsVals), extraParamsVals);
}
}
return OpType::postProcess(startingVal, length, extraParamsVals);;
}
template<typename OpType>
static void execAll(
T *x,
int *xShapeInfo,
T *extraParams,
T *y,
int *yShapeInfo,
T *result,
int *resultShapeInfoBuffer,
int *dimension,
int dimensionLength, int *xTadShapeInfo, Nd4jIndex *xOffsets, int *yTadShapeInfo, Nd4jIndex *yOffsets) {
int xTadLength = shape::tadLength(xShapeInfo, dimension, dimensionLength);
int yTadLength = shape::tadLength(yShapeInfo, dimension, dimensionLength);
int xTads = shape::length(xShapeInfo) / xTadLength;
int yTads = shape::length(yShapeInfo) / yTadLength;
int *xShape = shape::shapeOf(xTadShapeInfo);
int *xStride = shape::stride(xTadShapeInfo);
int xRank = shape::rank(xTadShapeInfo);
int *yShape = shape::shapeOf(yTadShapeInfo);
int *yStride = shape::stride(yTadShapeInfo);
int yRank = shape::rank(yTadShapeInfo);
int xCoord[MAX_RANK];
int yCoord[MAX_RANK];
T startingVal = OpType::startingValue(x);
#pragma omp parallel for proc_bind(AFFINITY) default(shared) private(xCoord, yCoord)
for (int r = 0; r < xTads; r++) {
Nd4jIndex xOffset = xOffsets[r];
T *lX = x + xOffset;
for (int g = 0; g < yTads; g++) {
int yOffset = yOffsets[g];
T *lY = y + yOffset;
int ri = (r * yTads) + g;
T *localExtraParams = nullptr;
if (OpType::extraParamsLen > 0)
localExtraParams = new T[OpType::extraParamsLen];
for (int extraParamsIdx = 0; extraParamsIdx < OpType::extraParamsLen; extraParamsIdx++) {
localExtraParams[extraParamsIdx] = startingVal;
}
for (int f = 0; f < xTadLength; f++) {
if (shape::order(yTadShapeInfo) == 'c') {
shape::ind2subC(yRank, yShape, f, yCoord);
} else {
shape::ind2sub(yRank, yShape, f, yCoord);
}
if (shape::order(xTadShapeInfo) == 'c') {
shape::ind2subC(xRank, xShape, f, xCoord);
} else {
shape::ind2sub(xRank, xShape, f, xCoord);
}
Nd4jIndex xO = shape::getOffset(0, xShape, xStride, xCoord, xRank);
Nd4jIndex yO = shape::getOffset(0, yShape, yStride, yCoord, yRank);
result[ri] = OpType::update(result[ri], OpType::op(lX[xO], lY[yO], localExtraParams), localExtraParams);
}
result[ri] = OpType::postProcess(result[ri], xTadLength, localExtraParams);
if (localExtraParams != nullptr)
delete[] localExtraParams;
}
}
}
template<typename OpType>
static void exec(
T *x,
int *xShapeInfo,
T *extraParams,
T *y,
int *yShapeInfo,
T *result,
int *resultShapeInfoBuffer,
int *dimension,
int dimensionLength, int *tadShapeInfo, Nd4jIndex *tadOffsets) {
T startingVal = OpType::startingValue(x);
int tadLength = shape::tadLength(xShapeInfo, dimension, dimensionLength);
int tads = shape::length(xShapeInfo) / tadLength;
int *xShape = shape::shapeOf(tadShapeInfo);
int *xStride = shape::stride(tadShapeInfo);
int xRank = shape::rank(tadShapeInfo);
int *yShape = shape::shapeOf(yShapeInfo);
int *yStride = shape::stride(yShapeInfo);
int yRank = shape::rank(yShapeInfo);
int xCoord[MAX_RANK];
int yCoord[MAX_RANK];
#pragma omp parallel for proc_bind(AFFINITY) default(shared) private(xCoord, yCoord)
for (int r = 0; r < tads; r++) {
Nd4jIndex offset = tadOffsets[r];
T *localExtraParams = nullptr;
if (OpType::extraParamsLen > 0)
localExtraParams = new T[OpType::extraParamsLen];
for (int extraParamsIdx = 0; extraParamsIdx < OpType::extraParamsLen; extraParamsIdx++) {
localExtraParams[extraParamsIdx] = startingVal;
}
for (int f = 0; f < tadLength; f++) {
if (shape::order(tadShapeInfo) == 'c') {
shape::ind2subC(xRank, xShape, f, xCoord);
shape::ind2subC(yRank, yShape, f, yCoord);
} else {
shape::ind2sub(xRank, xShape, f, xCoord);
shape::ind2sub(yRank, yShape, f, yCoord);
}
Nd4jIndex xOffset = shape::getOffset(offset, xShape, xStride, xCoord, xRank);
Nd4jIndex yOffset = shape::getOffset(0, yShape, yStride, yCoord, yRank);
result[r] = OpType::update(result[r], OpType::op(x[xOffset], y[yOffset], localExtraParams), localExtraParams);
}
result[r] = OpType::postProcess(result[r], tadLength, localExtraParams);
if (localExtraParams != nullptr)
delete[] localExtraParams;
}
}
template<typename OpType>
static void exec(
T *x,
int *xShapeInfo,
T *extraParams,
T *y,
int *yShapeInfo,
T *result,
int *resultShapeInfoBuffer,
int *dimension,
int dimensionLength) {
T extraParamsVals[2] = {(T) 0.0, (T) 0.0};
if(shape::isScalar(resultShapeInfoBuffer)) {
result[0] = execScalar<OpType>(
x,
xShapeInfo,
extraParamsVals,
y,
yShapeInfo);
return;
}
char xOrder = shape::order(xShapeInfo);
char yOrder = shape::order(yShapeInfo);
if(xOrder != yOrder) {
int shapeIter[MAX_RANK];
int coord[MAX_RANK];
int dim;
int xStridesIter[MAX_RANK];
int yStridesIter[MAX_RANK];
int *xShape = shape::shapeOf(xShapeInfo);
int *xStride = shape::stride(xShapeInfo);
int *yStride = shape::stride(yShapeInfo);
int rank = shape::rank(xShapeInfo);
if(PrepareTwoRawArrayIter<T>(rank,
xShape,
x,
xStride,
y,
yStride,
&rank,
shapeIter,
&x,
xStridesIter,
&y,
yStridesIter) >= 0) {
Nd4jIndex resultLength = shape::length(resultShapeInfoBuffer);
Nd4jIndex tadLength = shape::tadLength(xShapeInfo,dimension,dimensionLength);
ND4J_RAW_ITER_START(dim, rank, coord, shapeIter); {
Nd4jIndex xOffset = shape::getOffset(0,xShape,xStride,coord,rank);
int reductionIndex = xOffset / resultLength;
result[reductionIndex] = OpType::update(result[reductionIndex], OpType::op(x[0],y[0], extraParamsVals), extraParamsVals);
} ND4J_RAW_ITER_TWO_NEXT(dim,
rank,
coord,
shapeIter,
x,
xStridesIter,
y,
yStridesIter);
#pragma omp parallel for proc_bind(AFFINITY) default(shared)
for(Nd4jIndex i = 0; i < resultLength ;i++) {
result[i] = OpType::postProcess(result[i],tadLength, extraParamsVals);
}
}
else {
printf("Unable to prepare array\n");
}
}
else {
T startingVal = OpType::startingValue(x);
Nd4jIndex resultLength = shape::length(resultShapeInfoBuffer);
shape::TAD xTad(xShapeInfo, dimension, dimensionLength);
xTad.createTadOnlyShapeInfo();
xTad.createOffsets();
shape::TAD yTad(yShapeInfo, dimension, dimensionLength);
yTad.createTadOnlyShapeInfo();
yTad.createOffsets();
/**
* The element wise stride belong longs to a reduction index.
* When used out of order, we can get rid of the data
* dependencies and rely on using the max dimension
* specified for stride instead.
* Say we take the sum(0,1) along long arr
* we can use arr.stride(1) as a representation
* along long which to iterate.
*/
int tadElementWiseStride = shape::elementWiseStride(xTad.tadOnlyShapeInfo);
int yElementWiseStride = shape::elementWiseStride(yTad.tadOnlyShapeInfo);
int tadLength = shape::length(xTad.tadOnlyShapeInfo);
if (tadElementWiseStride >= 1 && yElementWiseStride >= 1) {
#pragma omp parallel for proc_bind(AFFINITY) default(shared)
for (Nd4jIndex i = 0; i < resultLength; i++) {
T *localExtraParams = nullptr;
if (OpType::extraParamsLen > 0)
localExtraParams = new T[OpType::extraParamsLen];
for (int extraParamsIdx = 0; extraParamsIdx < OpType::extraParamsLen; extraParamsIdx++) {
localExtraParams[extraParamsIdx] = startingVal;
}
Nd4jIndex offset = xTad.tadOffsets[i];
Nd4jIndex yOffset = yTad.tadOffsets[i];
result[i] = OpType::op(x[offset], y[yOffset], localExtraParams);
for (int j = 1; j < tadLength; j++) {
result[i] = OpType::update(result[i], OpType::op(x[offset + tadElementWiseStride * j],
y[yOffset + yElementWiseStride * j],
localExtraParams), localExtraParams);
}
result[i] = OpType::postProcess(result[i], tadLength, localExtraParams);
if (localExtraParams != nullptr)
delete[] localExtraParams;
}
} else {
shape::TAD xTad(xShapeInfo, dimension, dimensionLength);
xTad.createTadOnlyShapeInfo();
xTad.createOffsets();
shape::TAD yTad(yShapeInfo, dimension, dimensionLength);
yTad.createTadOnlyShapeInfo();
yTad.createOffsets();
int tadsPerThread = resultLength / TAD_THRESHOLD;
int num_threads = nd4j::math::nd4j_max<int>(1, tadsPerThread);
num_threads = nd4j::math::nd4j_min<int>(num_threads, omp_get_max_threads());
#pragma omp parallel for schedule(guided) num_threads(num_threads) if (num_threads > 1) proc_bind(AFFINITY) default(shared)
for (int i = 0; i < resultLength; i++) {
Nd4jIndex xOffset = xTad.tadOffsets[i];
Nd4jIndex yOffset = yTad.tadOffsets[i];
int coord[MAX_RANK];
T start = OpType::startingValue(x + xOffset);
for (int j = 0; j < shape::length(xTad.tadOnlyShapeInfo); j++) {
shape::ind2subC(shape::rank(xTad.tadOnlyShapeInfo), shape::shapeOf(xTad.tadOnlyShapeInfo), j, coord);
int xOffset2 = shape::getOffset(xOffset,shape::shapeOf(xTad.tadOnlyShapeInfo),shape::stride(xTad.tadOnlyShapeInfo),coord,shape::rank(xTad.tadOnlyShapeInfo));
int yOffset2 = shape::getOffset(yOffset,shape::shapeOf(yTad.tadOnlyShapeInfo),shape::stride(yTad.tadOnlyShapeInfo),coord,shape::rank(yTad.tadOnlyShapeInfo));
start = OpType::update(start, OpType::op(x[xOffset2], y[yOffset2],extraParams), extraParams);
}
result[i] = OpType::postProcess(start, shape::length(xTad.tadOnlyShapeInfo), extraParams);
}
}
}
}
};
}
}
#ifdef __CUDACC__
/**
* The driver api
* @param opNum the number
* @param n the length of the reduce
* @param dx the input data
* @param xShapeInfo the shape information
* @param dy the pair wise reduce
* @param yShapeInfo the shape information for y
* @param extraParams the extra parameters in the operation
* @param result where to store the result
* @param resultShapeInfo the shape information
* @param gpuInformation the gpu information
* @param dimension the dimension to reduce along long
* @param dimensionLength the dimension length
* @param postProcessOrNot whether to post
*/
template <typename T>
__device__ void reduce3Generic(
const int opNum,
T *dx,
int *xShapeInfo,
T *dy,
int *yShapeInfo,
T *extraParams,
T *result,
int *resultShapeInfo,
int *dimension,
int dimensionLength,
int postProcessOrNot, int *allocationPointer, int *tadOnlyShapeInfo, Nd4jIndex *tadOffsets, int *yTadOnlyShapeInfo, Nd4jIndex *yTadOffsets) {
__shared__ UnifiedSharedMemory *manager;
if (threadIdx.x == 0) {
extern __shared__ unsigned char shmem[];
manager = new(shmem) UnifiedSharedMemory((int *) shmem);
manager->init(sizeof(UnifiedSharedMemory), 0, sizeof(functions::reduce3::Reduce3<T>), sizeof(shape::TAD), shape::rank(xShapeInfo));
}
__syncthreads();
functions::reduce3::Reduce3<T>::exec(
opNum,
dx,
xShapeInfo,
dy,
yShapeInfo,
extraParams,
result,
resultShapeInfo,
dimension,
dimensionLength,
postProcessOrNot,
allocationPointer,
manager,
tadOnlyShapeInfo,
tadOffsets,
yTadOnlyShapeInfo,
yTadOffsets);
}
template <typename T>
__device__ void reduce3AllGeneric(
const int opNum,
T *dx,
int *xShapeInfo,
T *dy,
int *yShapeInfo,
T *extraParams,
T *result,
int *resultShapeInfo,
int *dimension,
int dimensionLength,
int postProcessOrNot,
int *allocationPointer,
int *tadOnlyShapeInfo,
Nd4jIndex *tadOffsets,
int *yTadOnlyShapeInfo,
Nd4jIndex *yTadOffsets) {
__shared__ UnifiedSharedMemory *manager;
if (threadIdx.x == 0) {
extern __shared__ unsigned char shmem[];
manager = new(shmem) UnifiedSharedMemory((int *) shmem);
manager->init(sizeof(UnifiedSharedMemory), 0, sizeof(functions::reduce3::Reduce3<T>), sizeof(shape::TAD), shape::rank(xShapeInfo));
}
__syncthreads();
functions::reduce3::Reduce3<T>::execAllCuda(
opNum,
dx,
xShapeInfo,
dy,
yShapeInfo,
extraParams,
result,
resultShapeInfo,
dimension,
dimensionLength,
postProcessOrNot,
allocationPointer,
manager,
tadOnlyShapeInfo,
tadOffsets,
yTadOnlyShapeInfo,
yTadOffsets);
}
template <typename T>
__device__ void reduce3ScalarGeneric(
int opNum,
T *dx,
int *xShapeInfo,
T *dy,
int *yShapeInfo,
T *extraParams,
T *result,
int *resultShapeInfo, int *allocationPointer,
T *reductionBuffer, int *tadOnlyShapeInfo, Nd4jIndex *tadOffsets, int *yTadOnlyShapeInfo, Nd4jIndex *yTadOffsets) {
__shared__ UnifiedSharedMemory *manager;
if (threadIdx.x == 0) {
extern __shared__ unsigned char shmem[];
manager = new(shmem) UnifiedSharedMemory((int *) shmem);
manager->init(sizeof(UnifiedSharedMemory), 0, sizeof(functions::reduce3::Reduce3<T>), sizeof(shape::TAD), shape::rank(xShapeInfo));
}
__syncthreads();
functions::reduce3::Reduce3<T>::execScalarCuda(
opNum,
dx,
xShapeInfo,
dy,
yShapeInfo,
extraParams,
result,
resultShapeInfo,
allocationPointer,
reductionBuffer,
manager,
tadOnlyShapeInfo);
}
/**
* The driver api
* @param opNum the number
* @param n the length of the reduce
* @param dx the input data
* @param xShapeInfo the shape information
* @param dy the pair wise reduce
* @param yShapeInfo the shape information for y
* @param extraParams the extra parameters in the operation
* @param result where to store the result
* @param resultShapeInfo the shape information
* @param dimension the dimension to reduce along long
* @param dimensionLength the dimension length
* @param postProcessOrNot whether to post [
*/
extern "C"
__global__ void reduce3Double(
int opNum,
double *dx,
int *xShapeInfo,
double *dy,
int *yShapeInfo,
double *extraParams,
double *result,
int *resultShapeInfo,
int *dimension,
int dimensionLength,
int postProcessOrNot, int *allocationPointer, int *tadOnlyShapeInfo, Nd4jIndex *tadOffsets, int *yTadOnlyShapeInfo, Nd4jIndex *yTadOffsets) {
reduce3Generic<double>(
opNum,
dx,
xShapeInfo,
dy,
yShapeInfo,
extraParams,
result,
resultShapeInfo,
dimension,
dimensionLength,
postProcessOrNot, allocationPointer, tadOnlyShapeInfo, tadOffsets, yTadOnlyShapeInfo, yTadOffsets);
}
extern "C"
__global__ void reduce3AllDouble(
int opNum,
double *dx,
int *xShapeInfo,
double *dy,
int *yShapeInfo,
double *extraParams,
double *result,
int *resultShapeInfo,
int *dimension,
int dimensionLength,
int postProcessOrNot, int *allocationPointer, int *tadOnlyShapeInfo, Nd4jIndex *tadOffsets, int *yTadOnlyShapeInfo, Nd4jIndex *yTadOffsets) {
reduce3AllGeneric<double>(
opNum,
dx,
xShapeInfo,
dy,
yShapeInfo,
extraParams,
result,
resultShapeInfo,
dimension,
dimensionLength,
postProcessOrNot, allocationPointer, tadOnlyShapeInfo, tadOffsets, yTadOnlyShapeInfo, yTadOffsets);
}
/**
* The driver api
* @param opNum the number
* @param n the length of the reduce
* @param dx the input data
* @param xShapeInfo the shape information
* @param dy the pair wise reduce
* @param yShapeInfo the shape information for y
* @param extraParams the extra parameters in the operation
* @param result where to store the result
* @param resultShapeInfo the shape information
* @param gpuInformation the gpu information
* @param dimension the dimension to reduce along long
* @param dimensionLength the dimension length
* @param postProcessOrNot whether to post [
*/
extern "C"
__global__ void reduce3Float(
int opNum,
float *dx,
int *xShapeInfo,
float *dy,
int *yShapeInfo,
float *extraParams,
float *result,
int *resultShapeInfo,
int *dimension,
int dimensionLength,
int postProcessOrNot, int *allocationPointer, int *tadOnlyShapeInfo, Nd4jIndex *tadOffsets, int *yTadOnlyShapeInfo, Nd4jIndex *yTadOffsets) {
reduce3Generic<float>(
opNum,
dx,
xShapeInfo,
dy,
yShapeInfo,
extraParams,
result,
resultShapeInfo,
dimension,
dimensionLength,
postProcessOrNot, allocationPointer, tadOnlyShapeInfo, tadOffsets, yTadOnlyShapeInfo, yTadOffsets);
}
extern "C"
__global__ void reduce3AllFloat(
int opNum,
float *dx,
int *xShapeInfo,
float *dy,
int *yShapeInfo,
float *extraParams,
float *result,
int *resultShapeInfo,
int *dimension,
int dimensionLength,
int postProcessOrNot, int *allocationPointer, int *tadOnlyShapeInfo, Nd4jIndex *tadOffsets, int *yTadOnlyShapeInfo, Nd4jIndex *yTadOffsets) {
reduce3AllGeneric<float>(
opNum,
dx,
xShapeInfo,
dy,
yShapeInfo,
extraParams,
result,
resultShapeInfo,
dimension,
dimensionLength,
postProcessOrNot, allocationPointer, tadOnlyShapeInfo, tadOffsets, yTadOnlyShapeInfo, yTadOffsets);
}
extern "C"
__global__ void reduce3Half(
int opNum,
float16 *dx,
int *xShapeInfo,
float16 *dy,
int *yShapeInfo,
float16 *extraParams,
float16 *result,
int *resultShapeInfo,
int *dimension,
int dimensionLength,
int postProcessOrNot, int *allocationPointer, int *tadOnlyShapeInfo, Nd4jIndex *tadOffsets, int *yTadOnlyShapeInfo, Nd4jIndex *yTadOffsets) {
reduce3Generic<float16>(
opNum,
dx,
xShapeInfo,
dy,
yShapeInfo,
extraParams,
result,
resultShapeInfo,
dimension,
dimensionLength,
postProcessOrNot, allocationPointer, tadOnlyShapeInfo, tadOffsets, yTadOnlyShapeInfo, yTadOffsets);
}
extern "C"
__global__ void reduce3AllHalf(
int opNum,
float16 *dx,
int *xShapeInfo,
float16 *dy,
int *yShapeInfo,
float16 *extraParams,
float16 *result,
int *resultShapeInfo,
int *dimension,
int dimensionLength,
int postProcessOrNot, int *allocationPointer, int *tadOnlyShapeInfo, Nd4jIndex *tadOffsets, int *yTadOnlyShapeInfo, Nd4jIndex *yTadOffsets) {
reduce3AllGeneric<float16>(
opNum,
dx,
xShapeInfo,
dy,
yShapeInfo,
extraParams,
result,
resultShapeInfo,
dimension,
dimensionLength,
postProcessOrNot, allocationPointer, tadOnlyShapeInfo, tadOffsets, yTadOnlyShapeInfo, yTadOffsets);
}
extern "C"
__global__ void reduce3ScalarFloat(
int opNum,
float *dx,
int *xShapeInfo,
float *dy,
int *yShapeInfo,
float *extraParams,
float *result,
int *resultShapeInfo,
int *dimension,
int dimensionLength,
int postProcessOrNot, int *allocationPointer, float *reductionBuffer, int *tadOnlyShapeInfo, Nd4jIndex *tadOffsets, int *yTadOnlyShapeInfo, Nd4jIndex *yTadOffsets) {
reduce3ScalarGeneric<float>(
opNum,
dx,
xShapeInfo,
dy,
yShapeInfo,
extraParams,
result,
resultShapeInfo, allocationPointer,
reductionBuffer, tadOnlyShapeInfo, tadOffsets, yTadOnlyShapeInfo, yTadOffsets);
}
extern "C" __global__ void reduce3ScalarHalf(
int opNum,
float16 *dx,
int *xShapeInfo,
float16 *dy,
int *yShapeInfo,
float16 *extraParams,
float16 *result,
int *resultShapeInfo,
int *dimension,
int dimensionLength,
int postProcessOrNot, int *allocationPointer, float16 *reductionBuffer, int *tadOnlyShapeInfo, Nd4jIndex *tadOffsets, int *yTadOnlyShapeInfo, Nd4jIndex *yTadOffsets) {
reduce3ScalarGeneric<float16>(
opNum,
dx,
xShapeInfo,
dy,
yShapeInfo,
extraParams,
result,
resultShapeInfo, allocationPointer,
reductionBuffer, tadOnlyShapeInfo, tadOffsets, yTadOnlyShapeInfo, yTadOffsets);
}
extern "C"
__global__ void reduce3ScalarDouble(
int opNum,
double *dx,
int *xShapeInfo,
double *dy,
int *yShapeInfo,
double *extraParams,
double *result,
int *resultShapeInfo,
int *dimension,
int dimensionLength,
int postProcessOrNot, int *allocationPointer, double *reductionBuffer, int *tadOnlyShapeInfo, Nd4jIndex *tadOffsets, int *yTadOnlyShapeInfo, Nd4jIndex *yTadOffsets) {
reduce3ScalarGeneric<double>(
opNum,
dx,
xShapeInfo,
dy,
yShapeInfo,
extraParams,
result,
resultShapeInfo, allocationPointer,
reductionBuffer, tadOnlyShapeInfo, tadOffsets, yTadOnlyShapeInfo, yTadOffsets);
}
#endif
#endif /* REDUCE3_H_ */
|
GB_binop__times_uint32.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__times_uint32)
// A.*B function (eWiseMult): GB (_AemultB_08__times_uint32)
// A.*B function (eWiseMult): GB (_AemultB_02__times_uint32)
// A.*B function (eWiseMult): GB (_AemultB_04__times_uint32)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__times_uint32)
// A*D function (colscale): GB (_AxD__times_uint32)
// D*A function (rowscale): GB (_DxB__times_uint32)
// C+=B function (dense accum): GB (_Cdense_accumB__times_uint32)
// C+=b function (dense accum): GB (_Cdense_accumb__times_uint32)
// C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__times_uint32)
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__times_uint32)
// C=scalar+B GB (_bind1st__times_uint32)
// C=scalar+B' GB (_bind1st_tran__times_uint32)
// C=A+scalar GB (_bind2nd__times_uint32)
// C=A'+scalar GB (_bind2nd_tran__times_uint32)
// C type: uint32_t
// A type: uint32_t
// A pattern? 0
// B type: uint32_t
// B pattern? 0
// BinaryOp: cij = (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,A_iso) \
uint32_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) \
uint32_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) \
uint32_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_TIMES || GxB_NO_UINT32 || GxB_NO_TIMES_UINT32)
//------------------------------------------------------------------------------
// 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__times_uint32)
(
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__times_uint32)
(
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__times_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__times_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
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__times_uint32)
(
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
uint32_t *restrict Cx = (uint32_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__times_uint32)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t *restrict Cx = (uint32_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__times_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 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) ;
uint32_t alpha_scalar ;
uint32_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((uint32_t *) alpha_scalar_in)) ;
beta_scalar = (*((uint32_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__times_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_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__times_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_04__times_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_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__times_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__times_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 bnz,
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 < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
uint32_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__times_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 = 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) \
{ \
uint32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x * aij) ; \
}
GrB_Info GB (_bind1st_tran__times_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 = GBX (Ax, pA, false) ; \
Cx [pC] = (aij * y) ; \
}
GrB_Info GB (_bind2nd_tran__times_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
|
SizeField.h
|
#pragma once
#include <ScalarField/ScalarField.h>
#include "MeshHeader.h"
#include "HelperFunctions.h"
#include <nanoflann.hpp>
class SizeField
{
struct MeshPointsNN
{
using kd_tree_t = nanoflann::KDTreeSingleIndexAdaptor<nanoflann::L2_Simple_Adaptor<float, MeshPointsNN >, MeshPointsNN, 3>;
std::unique_ptr<kd_tree_t> kdTree_;
std::vector<TriMesh::Point> points_;
MeshPointsNN( TriMesh& mesh ) {
points_.reserve( mesh.n_vertices() );
for( const auto& vh : mesh.vertices() ) {
points_.push_back( mesh.point( vh ) );
}
for( auto& p : points_ ) {
p[2] = 0;
}
// init kd tree
kdTree_ = std::make_unique<kd_tree_t>( 3, *this );
kdTree_->buildIndex();
}
std::vector<size_t> findNearestNeighbor( const TriMesh::Point& p, int k ) const {
std::vector<size_t> ret_indexes( k );
std::vector<float> out_dists_sqr( k );
nanoflann::KNNResultSet<float> resultSet( k );
resultSet.init( &ret_indexes[0], &out_dists_sqr[0] );
kdTree_->findNeighbors( resultSet, &p[0], nanoflann::SearchParams() );
return ret_indexes;
}
/*----- nanoflann functions -----*/
// Must return the number of data points
inline size_t kdtree_get_point_count() const { return points_.size(); }
// Returns the dim'th component of the idx'th point in the class
inline float kdtree_get_pt( const size_t idx, const size_t dim ) const {
return points_[idx][dim];
}
template <class BBOX>
bool kdtree_get_bbox( BBOX& ) const { return false; }
};
ScalarField::ScalarField field_;
public:
SizeField( const std::experimental::filesystem::path& filename ) : field_(filename) {}
SizeField( const ScalarField::ScalarField& field ) : field_( field ) {}
SizeField( TriMesh& mesh, const size_t& Nx, const size_t& Ny, const bool useInterpolation = true )
: field_( useInterpolation ? computeAabbLecacy( mesh ) : computeAabbLecacy( mesh ), Nx, Ny )
{
if( useInterpolation ) {
fillGrid( mesh );
} else {
fillGridFromNearestNeighbors( mesh );
}
}
const auto& field() const { return field_; }
private:
void gaussSeidelStep( ScalarField::ScalarField& sf, int i, int j, float* v, float* vNew ) {
int n = 0;
float val = 0;
if( i > 0 && v[sf.lex( i - 1, j )] != -FLT_MAX ) {
val += v[sf.lex( i - 1, j )];
++n;
}
if( i < sf.Nx() - 1 && v[sf.lex( i + 1, j )] != -FLT_MAX ) {
val += v[sf.lex( i + 1, j )];
++n;
}
if( j > 0 && v[sf.lex( i, j - 1 )] != -FLT_MAX ) {
val += v[sf.lex( i, j - 1 )];
++n;
}
if( j < sf.Ny() - 1 && v[sf.lex( i, j + 1 )] != -FLT_MAX ) {
val += v[sf.lex( i, j + 1 )];
++n;
}
if( n != 0 )
vNew[sf.lex( i, j )] = val / n;
}
void gaussSeidelStepInterior( ScalarField::ScalarField& sf, int i, int j, float* v, float* vNew ) {
vNew[sf.lex( i, j )] = 0.25f * (
v[sf.lex( i - 1, j )] +
v[sf.lex( i + 1, j )] +
v[sf.lex( i, j - 1 )] +
v[sf.lex( i, j + 1 )] );
}
void fillGrid( TriMesh& mesh ) {
// fill scalar field
std::vector<float> vertexAvg( mesh.n_vertices() );
std::vector<bool> isDomain( field_.scalars().size(), false );
for( const auto& v : mesh.vertices() ) {
float avg{ 0.f };
auto nEdges{ 0 };
for( const auto& voh : v.outgoing_halfedges() ) {
++nEdges;
auto p1 = mesh.point( voh.from() );
auto p2 = mesh.point( voh.to() );
p1[2] = 0;
p2[2] = 0;
avg += ( p1 - p2 ).length();
}
vertexAvg[v.idx()] = avg / (float)nEdges;
}
for( const auto& fh : mesh.faces() ) {
std::vector<TriMesh::Point> triangle; // points of the triangle
for( const auto& v : fh.vertices() ) {
TriMesh::Point p{ mesh.point( v )[0], mesh.point( v )[1], vertexAvg[v.idx()] };
triangle.push_back( p );
}
// get the rectangle of grid points that surrounds the triangle
float x_t_max = std::fmaxf( std::max( triangle[0][0], triangle[1][0] ), triangle[2][0] );
float x_t_min = std::fminf( std::min( triangle[0][0], triangle[1][0] ), triangle[2][0] );
float y_t_max = std::fmaxf( std::max( triangle[0][1], triangle[1][1] ), triangle[2][1] );
float y_t_min = std::fminf( std::min( triangle[0][1], triangle[1][1] ), triangle[2][1] );
size_t i_min = field_.x2col( x_t_min );
size_t i_max = field_.x2col( x_t_max ) + 1;
size_t j_min = field_.y2row( y_t_min );
size_t j_max = field_.y2row( y_t_max ) + 1;
// check for all inner points of rectangle if they are inside the triangle. If yes, calculate the depth
for( size_t i = i_min + 1; i < i_max; ++i ) {
const float xv = field_.x( i );
for( size_t j = j_min + 1; j < j_max; ++j ) {
const float yv = field_.y( j );
const auto [a, b, c] = HelperFunctions::barycentricCoordinates( { triangle[0], triangle[1], triangle[2] }, { xv,yv,0 } );
if( HelperFunctions::isInsideTriangle( a, b, c ) ) {
// calculate average edge length
field_( i, j ) = HelperFunctions::barycentricInterpolation( triangle, a, b, c );
isDomain[field_.lex( i, j )] = true;
}
}
}
}
auto v2 = field_.scalars();
auto vDiff = decltype( v2 )( v2.size(), 0 );
float* pv1 = field_.scalars().data();
float* pv2 = v2.data();
const auto& v1Size = field_.scalars().size();
std::vector<std::array<int, 2>> warmUpRed;
std::vector<std::array<int, 2>> warmUpBlack;
for( int i = 0; i < field_.Nx(); ++i ) {
for( int j = 0; j < field_.Ny(); ++j ) {
if( isDomain[field_.lex( i, j )] ) continue;
if( ( i + j ) % 2 == 0 )
warmUpRed.push_back( { i,j } );
else
warmUpBlack.push_back( { i,j } );
}
}
const auto warmUpRedSize = warmUpRed.size();
const auto warmUpBlackSize = warmUpBlack.size();
// warm-up phase (spread reasonable values fast)
for( long k = 0; k < 1e6; ++k ) {
#pragma omp parallel for
for( int idx = 0; idx < warmUpRedSize; ++idx ) {
const int i = warmUpRed[idx][0];
const int j = warmUpRed[idx][1];
gaussSeidelStep( field_, i, j, pv1, pv2 );
}
#pragma omp parallel for
for( int idx = 0; idx < warmUpBlackSize; ++idx ) {
const int i = warmUpBlack[idx][0];
const int j = warmUpBlack[idx][1];
gaussSeidelStep( field_, i, j, pv2, pv2 );
}
std::swap( pv1, pv2 );
auto minIt = std::min_element( field_.scalars().begin(), field_.scalars().end() );
if( *minIt != -FLT_MAX ) {
break;
}
}
std::vector<std::array<int, 2>> interiorRed;
std::vector<std::array<int, 2>> interiorBlack;
for( int i = 1; i < field_.Nx() - 1; ++i ) {
for( int j = 1; j < field_.Ny() - 1; ++j ) {
if( isDomain[field_.lex( i, j )] ) continue;
if( ( i + j ) % 2 == 0 )
interiorRed.push_back( { i,j } );
else
interiorBlack.push_back( { i,j } );
}
}
const auto interiorRedSize = interiorRed.size();
const auto interiorBlackSize = interiorBlack.size();
// main loop (after warm-up)
for( long k = 0; k < 1e6; ++k ) {
#pragma omp parallel for
for( int idx = 0; idx < interiorRedSize; ++idx ) {
const int i = interiorRed[idx][0];
const int j = interiorRed[idx][1];
gaussSeidelStepInterior( field_, i, j, pv1, pv2 );
}
// edges red
for( int i = 2; i < field_.Nx() - 1; i += 2 ) {
const int j = 0;
pv2[field_.lex( i, j )] = (
pv1[field_.lex( i - 1, j )] +
pv1[field_.lex( i + 1, j )] +
pv1[field_.lex( i, j + 1 )] ) / 3;
}
for( int j = 2; j < field_.Ny() - 1; j += 2 ) {
const int i = 0;
pv2[field_.lex( i, j )] = (
pv1[field_.lex( i + 1, j )] +
pv1[field_.lex( i, j - 1 )] +
pv1[field_.lex( i, j + 1 )] ) / 3;
}
for( int i = field_.Ny() % 2 == 0 ? 1 : 2; i < field_.Nx() - 1; i += 2 ) {
const int j = field_.Ny() - 1;
pv2[field_.lex( i, j )] = (
pv1[field_.lex( i - 1, j )] +
pv1[field_.lex( i + 1, j )] +
pv1[field_.lex( i, j - 1 )] ) / 3;
}
for( int j = field_.Nx() % 2 == 0 ? 1 : 2; j < field_.Ny() - 1; j += 2 ) {
const int i = field_.Nx() - 1;
pv2[field_.lex( i, j )] = (
pv1[field_.lex( i - 1, j )] +
pv1[field_.lex( i, j - 1 )] +
pv1[field_.lex( i, j + 1 )] ) / 3;
}
// corners red
pv2[field_.lex( 0, 0 )] = ( pv1[field_.lex( 0 + 1, 0 )] + pv1[field_.lex( 0, 0 + 1 )] ) / 2;
if( field_.Ny() % 2 == 1 )
pv2[field_.lex( field_.Nx() - 1, 0 )] = ( pv1[field_.lex( field_.Nx() - 1 - 1, 0 )] + pv1[field_.lex( field_.Nx() - 1, 0 + 1 )] ) / 2;
if( field_.Ny() % 2 == 1 )
pv2[field_.lex( 0, field_.Ny() - 1 )] = ( pv1[field_.lex( 0 + 1, field_.Ny() - 1 )] + pv1[field_.lex( 0, field_.Ny() - 1 - 1 )] ) / 2;
if( ( field_.Ny() + field_.Nx() ) % 2 == 0 )
pv2[field_.lex( field_.Nx() - 1, field_.Ny() - 1 )] = ( pv1[field_.lex( field_.Nx() - 1 - 1, field_.Ny() - 1 )] + pv1[field_.lex( field_.Nx() - 1, field_.Ny() - 1 - 1 )] ) / 2;
#pragma omp parallel for
for( int idx = 0; idx < interiorBlackSize; ++idx ) {
const int i = interiorBlack[idx][0];
const int j = interiorBlack[idx][1];
gaussSeidelStepInterior( field_, i, j, pv2, pv2 );
}
// edges black
for( int i = 1; i < field_.Nx() - 1; i += 2 ) {
const int j = 0;
pv2[field_.lex( i, j )] = (
pv2[field_.lex( i - 1, j )] +
pv2[field_.lex( i + 1, j )] +
pv2[field_.lex( i, j + 1 )] ) / 3;
}
for( int j = 1; j < field_.Ny() - 1; j += 2 ) {
const int i = 0;
pv2[field_.lex( i, j )] = (
pv2[field_.lex( i + 1, j )] +
pv2[field_.lex( i, j - 1 )] +
pv2[field_.lex( i, j + 1 )] ) / 3;
}
for( int i = field_.Ny() % 2 == 1 ? 1 : 2; i < field_.Nx() - 1; i += 2 ) {
const int j = field_.Ny() - 1;
pv2[field_.lex( i, j )] = (
pv2[field_.lex( i - 1, j )] +
pv2[field_.lex( i + 1, j )] +
pv2[field_.lex( i, j - 1 )] ) / 3;
}
for( int j = field_.Nx() % 2 == 1 ? 1 : 2; j < field_.Ny() - 1; j += 2 ) {
const int i = field_.Nx() - 1;
pv2[field_.lex( i, j )] = (
pv2[field_.lex( i - 1, j )] +
pv2[field_.lex( i, j - 1 )] +
pv2[field_.lex( i, j + 1 )] ) / 3;
}
// corners black
if( field_.Ny() % 2 == 0 )
pv2[field_.lex( field_.Nx() - 1, 0 )] = ( pv2[field_.lex( field_.Nx() - 1 - 1, 0 )] + pv2[field_.lex( field_.Nx() - 1, 0 + 1 )] ) / 2;
if( field_.Ny() % 2 == 0 )
pv2[field_.lex( 0, field_.Ny() - 1 )] = ( pv2[field_.lex( 0 + 1, field_.Ny() - 1 )] + pv2[field_.lex( 0, field_.Ny() - 1 - 1 )] ) / 2;
if( ( field_.Ny() + field_.Nx() ) % 2 == 1 )
pv2[field_.lex( field_.Nx() - 1, field_.Ny() - 1 )] = ( pv2[field_.lex( field_.Nx() - 1 - 1, field_.Ny() - 1 )] + pv2[field_.lex( field_.Nx() - 1, field_.Ny() - 1 - 1 )] ) / 2;
#pragma omp parallel for
for( int i = 0; i < v1Size; ++i ) {
vDiff[i] = std::fabs( pv2[i] - pv1[i] );
}
auto maxIt = std::max_element( vDiff.begin(), vDiff.end() );
std::swap( pv1, pv2 );
if( *maxIt <= 1e-5 * pv1[std::distance( vDiff.begin(), maxIt )] ) {
break;
}
}
}
void fillGridFromNearestNeighbors( TriMesh& mesh ) {
std::vector<float> vertexAvg( mesh.n_vertices() );
for( const auto& v : mesh.vertices() ) {
float avg{ 0.f };
auto nEdges{ 0 };
for( const auto& voh : v.outgoing_halfedges() ) {
++nEdges;
auto p1 = mesh.point( voh.from() );
auto p2 = mesh.point( voh.to() );
p1[2] = 0;
p2[2] = 0;
avg += ( p1 - p2 ).length();
}
vertexAvg[v.idx()] = avg / (float)nEdges;
}
MeshPointsNN knn( mesh );
for( int i = 0; i < field_.Nx(); ++i ) {
for( int j = 0; j < field_.Ny(); ++j ) {
const auto& pos = field_.pos( i, j );
TriMesh::Point p{ pos.x, pos.y, 0 };
const auto nnIdxs = knn.findNearestNeighbor( p, 5 );
float invDistSum = 0;
float avg = 0;
for( const auto& idx : nnIdxs ) {
const auto& pn = mesh.point( mesh.vertex_handle( idx ) );
auto dist = ( pn - p ).sqrnorm();
auto invDist = 1.f / ( dist + 0.0001f );
auto val = vertexAvg[idx];
avg += val * invDist;
invDistSum += invDist;
}
avg /= invDistSum;
field_( i, j ) = avg;
}
}
}
static ScalarField::AxisAlignedBoundingBox computeAabbLecacy( TriMesh& mesh ) {
const auto n_vertices = mesh.n_vertices();
auto xMax = -std::numeric_limits<float>::max();
auto yMax = -std::numeric_limits<float>::max();
auto xMin = std::numeric_limits<float>::max();
auto yMin = std::numeric_limits<float>::max();
for( unsigned int i = 0; i < n_vertices; ++i ) {
TriMesh::Point point = mesh.point( mesh.vertex_handle( i ) );
xMax = std::max( xMax, point[0] );
yMax = std::max( yMax, point[1] );
xMin = std::min( xMin, point[0] );
yMin = std::min( yMin, point[1] );
}
const float x_range_old = xMax - xMin;
const float y_range_old = yMax - yMin;
xMax += 0.1 * x_range_old;
xMin -= 0.1 * x_range_old;
yMax += 0.1 * y_range_old;
yMin -= 0.1 * y_range_old;
return { xMin, xMax, yMin, yMax };
}
static ScalarField::AxisAlignedBoundingBox computeAabb( TriMesh& mesh ) {
auto xMax = -std::numeric_limits<float>::max();
auto yMax = -std::numeric_limits<float>::max();
auto xMin = std::numeric_limits<float>::max();
auto yMin = std::numeric_limits<float>::max();
for( const auto& v : mesh.vertices() ) {
const auto& point = mesh.point( v );
xMax = std::max( xMax, point[0] );
yMax = std::max( yMax, point[1] );
xMin = std::min( xMin, point[0] );
yMin = std::min( yMin, point[1] );
}
return { xMin, xMax, yMin, yMax };
}
public:
// load size field if it already exists in cache, otherwise generate and store it.
static ScalarField::ScalarField load( TriMesh& mesh, const std::experimental::filesystem::path& cacheFolder, const std::experimental::filesystem::path& meshFile, const size_t& sizeGridSizeX, const size_t& sizeGridSizeY ) {
namespace fs = std::experimental::filesystem;
fs::path file = cacheFolder / ( meshFile.stem().string() + "_SizeField_" + std::to_string( sizeGridSizeX ) + "_" + std::to_string( sizeGridSizeY ) + ".bin" );
auto sfLoad = ScalarField::load( file, sizeGridSizeX, sizeGridSizeY );
//std::optional<ScalarField::ScalarField> sfLoad = {};
if( sfLoad ) {
return sfLoad.value();
} else {
LOG( INFO ) << "Generate SizeField";
SizeField sf( mesh, sizeGridSizeX, sizeGridSizeY, true );
LOG( INFO ) << "Store in cache file '" << file << "'";
sf.field().writeBinary( file.string() );
return sf.field();
}
}
};
|
dft.c
|
// Copyright Naoki Shibata and contributors 2010 - 2020.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <assert.h>
#include <signal.h>
#include <setjmp.h>
#include <math.h>
#include "sleef.h"
#include "misc.h"
#include "common.h"
#include "arraymap.h"
#include "dftcommon.h"
#ifdef _OPENMP
#include <omp.h>
#endif
#if BASETYPEID == 1
typedef double real;
typedef Sleef_double2 sc_t;
#define BASETYPESTRING "double"
#define MAGIC 0x27182818
#define MAGIC2D 0x17320508
#define INIT SleefDFT_double_init1d
#define EXECUTE SleefDFT_double_execute
#define INIT2D SleefDFT_double_init2d
#define CTBL ctbl_double
#define REALSUB0 realSub0_double
#define REALSUB1 realSub1_double
#define GETINT getInt_double
#define GETPTR getPtr_double
#define DFTF dftf_double
#define DFTB dftb_double
#define TBUTF tbutf_double
#define TBUTB tbutb_double
#define BUTF butf_double
#define BUTB butb_double
#define SINCOSPI Sleef_sincospi_u05
#include "dispatchdp.h"
#elif BASETYPEID == 2
typedef float real;
typedef Sleef_float2 sc_t;
#define BASETYPESTRING "float"
#define MAGIC 0x31415926
#define MAGIC2D 0x22360679
#define INIT SleefDFT_float_init1d
#define EXECUTE SleefDFT_float_execute
#define INIT2D SleefDFT_float_init2d
#define CTBL ctbl_float
#define REALSUB0 realSub0_float
#define REALSUB1 realSub1_float
#define GETINT getInt_float
#define GETPTR getPtr_float
#define DFTF dftf_float
#define DFTB dftb_float
#define TBUTF tbutf_float
#define TBUTB tbutb_float
#define BUTF butf_float
#define BUTB butb_float
#define SINCOSPI Sleef_sincospif_u05
#include "dispatchsp.h"
#elif BASETYPEID == 3
typedef long double real;
typedef Sleef_longdouble2 sc_t;
#define BASETYPESTRING "long double"
#define MAGIC 0x14142135
#define MAGIC2D 0x26457513
#define INIT SleefDFT_longdouble_init1d
#define EXECUTE SleefDFT_longdouble_execute
#define INIT2D SleefDFT_longdouble_init2d
#define CTBL ctbl_longdouble
#define REALSUB0 realSub0_longdouble
#define REALSUB1 realSub1_longdouble
#define GETINT getInt_longdouble
#define GETPTR getPtr_longdouble
#define DFTF dftf_longdouble
#define DFTB dftb_longdouble
#define TBUTF tbutf_longdouble
#define TBUTB tbutb_longdouble
#define BUTF butf_longdouble
#define BUTB butb_longdouble
#define SINCOSPI Sleef_sincospil_u05
#include "dispatchld.h"
#elif BASETYPEID == 4
typedef Sleef_quad real;
typedef Sleef_quad2 sc_t;
#define BASETYPESTRING "Sleef_quad"
#define MAGIC 0x33166247
#define MAGIC2D 0x36055512
#define INIT SleefDFT_quad_init1d
#define EXECUTE SleefDFT_quad_execute
#define INIT2D SleefDFT_quad_init2d
#define CTBL ctbl_Sleef_quad
#define REALSUB0 realSub0_Sleef_quad
#define REALSUB1 realSub1_Sleef_quad
#define GETINT getInt_Sleef_quad
#define GETPTR getPtr_Sleef_quad
#define DFTF dftf_Sleef_quad
#define DFTB dftb_Sleef_quad
#define TBUTF tbutf_Sleef_quad
#define TBUTB tbutb_Sleef_quad
#define BUTF butf_Sleef_quad
#define BUTB butb_Sleef_quad
#define SINCOSPI Sleef_sincospiq_u05
#include "dispatchqp.h"
#else
#error No BASETYPEID specified
#endif
#define IMPORT_IS_EXPORT
#include "sleefdft.h"
//
#if BASETYPEID == 4
real CTBL[] = {
0.7071067811865475243818940365159164684883Q, -0.7071067811865475243818940365159164684883Q,
0.9238795325112867561014214079495587839119Q, -0.382683432365089771723257530688933059082Q,
0.382683432365089771723257530688933059082Q, -0.9238795325112867561014214079495587839119Q,
#if MAXBUTWIDTH >= 5
0.9807852804032304491190993878113602022495Q, -0.1950903220161282678433729148581576851029Q,
0.5555702330196022247573058028269343822103Q, -0.8314696123025452370808655033762590846891Q,
0.8314696123025452370808655033762590846891Q, -0.5555702330196022247573058028269343822103Q,
0.1950903220161282678433729148581576851029Q, -0.9807852804032304491190993878113602022495Q,
#endif
#if MAXBUTWIDTH >= 6
0.9951847266721968862310254699821143731242Q, -0.09801714032956060199569840382660679267701Q,
0.6343932841636454982026105398063009488396Q, -0.7730104533627369607965383602188325085081Q,
0.881921264348355029715105513066220055407Q, -0.4713967368259976485449225247492677226546Q,
0.2902846772544623676448431737195932100803Q, -0.9569403357322088649310892760624369657307Q,
0.9569403357322088649310892760624369657307Q, -0.2902846772544623676448431737195932100803Q,
0.4713967368259976485449225247492677226546Q, -0.881921264348355029715105513066220055407Q,
0.7730104533627369607965383602188325085081Q, -0.6343932841636454982026105398063009488396Q,
0.09801714032956060199569840382660679267701Q, -0.9951847266721968862310254699821143731242Q,
#endif
#if MAXBUTWIDTH >= 7
0.9987954562051723927007702841240899260811Q, -0.04906767432741801425355085940205324135377Q,
0.6715589548470184006194634573905233310143Q, -0.7409511253549590911932944126139233276263Q,
0.9039892931234433315823215138173907234886Q, -0.427555093430282094315230886905077056781Q,
0.336889853392220050702686798271834334173Q, -0.9415440651830207783906830087961026265475Q,
0.9700312531945439926159106824865574481009Q, -0.2429801799032638899447731489766866275204Q,
0.5141027441932217266072797923204262815489Q, -0.8577286100002720698929313536407192941624Q,
0.8032075314806449097991200569701675249235Q, -0.5956993044924333434615715265891822127742Q,
0.1467304744553617516588479505190711904561Q, -0.9891765099647809734561415551112872890371Q,
0.9891765099647809734561415551112872890371Q, -0.1467304744553617516588479505190711904561Q,
0.5956993044924333434615715265891822127742Q, -0.8032075314806449097991200569701675249235Q,
0.8577286100002720698929313536407192941624Q, -0.5141027441932217266072797923204262815489Q,
0.2429801799032638899447731489766866275204Q, -0.9700312531945439926159106824865574481009Q,
0.9415440651830207783906830087961026265475Q, -0.336889853392220050702686798271834334173Q,
0.427555093430282094315230886905077056781Q, -0.9039892931234433315823215138173907234886Q,
0.7409511253549590911932944126139233276263Q, -0.6715589548470184006194634573905233310143Q,
0.04906767432741801425355085940205324135377Q, -0.9987954562051723927007702841240899260811Q,
#endif
};
#else
real CTBL[] = {
0.7071067811865475243818940365159164684883L, -0.7071067811865475243818940365159164684883L,
0.9238795325112867561014214079495587839119L, -0.382683432365089771723257530688933059082L,
0.382683432365089771723257530688933059082L, -0.9238795325112867561014214079495587839119L,
#if MAXBUTWIDTH >= 5
0.9807852804032304491190993878113602022495L, -0.1950903220161282678433729148581576851029L,
0.5555702330196022247573058028269343822103L, -0.8314696123025452370808655033762590846891L,
0.8314696123025452370808655033762590846891L, -0.5555702330196022247573058028269343822103L,
0.1950903220161282678433729148581576851029L, -0.9807852804032304491190993878113602022495L,
#endif
#if MAXBUTWIDTH >= 6
0.9951847266721968862310254699821143731242L, -0.09801714032956060199569840382660679267701L,
0.6343932841636454982026105398063009488396L, -0.7730104533627369607965383602188325085081L,
0.881921264348355029715105513066220055407L, -0.4713967368259976485449225247492677226546L,
0.2902846772544623676448431737195932100803L, -0.9569403357322088649310892760624369657307L,
0.9569403357322088649310892760624369657307L, -0.2902846772544623676448431737195932100803L,
0.4713967368259976485449225247492677226546L, -0.881921264348355029715105513066220055407L,
0.7730104533627369607965383602188325085081L, -0.6343932841636454982026105398063009488396L,
0.09801714032956060199569840382660679267701L, -0.9951847266721968862310254699821143731242L,
#endif
#if MAXBUTWIDTH >= 7
0.9987954562051723927007702841240899260811L, -0.04906767432741801425355085940205324135377L,
0.6715589548470184006194634573905233310143L, -0.7409511253549590911932944126139233276263L,
0.9039892931234433315823215138173907234886L, -0.427555093430282094315230886905077056781L,
0.336889853392220050702686798271834334173L, -0.9415440651830207783906830087961026265475L,
0.9700312531945439926159106824865574481009L, -0.2429801799032638899447731489766866275204L,
0.5141027441932217266072797923204262815489L, -0.8577286100002720698929313536407192941624L,
0.8032075314806449097991200569701675249235L, -0.5956993044924333434615715265891822127742L,
0.1467304744553617516588479505190711904561L, -0.9891765099647809734561415551112872890371L,
0.9891765099647809734561415551112872890371L, -0.1467304744553617516588479505190711904561L,
0.5956993044924333434615715265891822127742L, -0.8032075314806449097991200569701675249235L,
0.8577286100002720698929313536407192941624L, -0.5141027441932217266072797923204262815489L,
0.2429801799032638899447731489766866275204L, -0.9700312531945439926159106824865574481009L,
0.9415440651830207783906830087961026265475L, -0.336889853392220050702686798271834334173L,
0.427555093430282094315230886905077056781L, -0.9039892931234433315823215138173907234886L,
0.7409511253549590911932944126139233276263L, -0.6715589548470184006194634573905233310143L,
0.04906767432741801425355085940205324135377L, -0.9987954562051723927007702841240899260811L,
#endif
};
#endif
#ifndef ENABLE_STREAM
#error ENABLE_STREAM not defined
#endif
static const int constK[] = { 0, 2, 6, 14, 38, 94, 230, 542, 1254 };
extern const char *configStr[];
extern int planFilePathSet;
// Utility functions
static jmp_buf sigjmp;
static void sighandler(int signum) { longjmp(sigjmp, 1); }
static int checkISAAvailability(int isa) {
signal(SIGILL, sighandler);
if (setjmp(sigjmp) == 0) {
int ret = GETINT[isa] != NULL && (*GETINT[isa])(BASETYPEID);
signal(SIGILL, SIG_DFL);
return ret;
}
signal(SIGILL, SIG_DFL);
return 0;
}
#ifdef _OPENMP
static int omp_thread_count() {
int n = 0;
#pragma omp parallel reduction(+:n)
n += 1;
return n;
}
#endif
static void startAllThreads(const int nth) {
#ifdef _OPENMP
volatile int8_t *state = calloc(nth, 1);
int th;
#pragma omp parallel for
for(th=0;th<nth;th++) {
state[th] = 1;
for(;;) {
int i;
for(i=0;i<nth;i++) if (state[i] == 0) break;
if (i == nth) break;
}
}
free((void *)state);
#endif
}
// Dispatcher
static void dispatch(SleefDFT *p, const int N, real *d, const real *s, const int level, const int config) {
const int K = constK[N], log2len = p->log2len;
if (level == N) {
if ((p->mode & SLEEF_MODE_BACKWARD) == 0) {
void (*func)(real *, const real *, const int) = DFTF[config][p->isa][N];
(*func)(d, s, log2len-N);
} else {
void (*func)(real *, const real *, const int) = DFTB[config][p->isa][N];
(*func)(d, s, log2len-N);
}
} else if (level == log2len) {
assert(p->vecwidth <= (1 << N));
if ((p->mode & SLEEF_MODE_BACKWARD) == 0) {
void (*func)(real *, uint32_t *, const real *, const int, const real *, const int) = TBUTF[config][p->isa][N];
(*func)(d, p->perm[level], s, log2len-N, p->tbl[N][level], K);
} else {
void (*func)(real *, uint32_t *, const real *, const int, const real *, const int) = TBUTB[config][p->isa][N];
(*func)(d, p->perm[level], s, log2len-N, p->tbl[N][level], K);
}
} else {
if ((p->mode & SLEEF_MODE_BACKWARD) == 0) {
void (*func)(real *, uint32_t *, const int, const real *, const int, const real *, const int) = BUTF[config][p->isa][N];
(*func)(d, p->perm[level], log2len-level, s, log2len-N, p->tbl[N][level], K);
} else {
void (*func)(real *, uint32_t *, const int, const real *, const int, const real *, const int) = BUTB[config][p->isa][N];
(*func)(d, p->perm[level], log2len-level, s, log2len-N, p->tbl[N][level], K);
}
}
}
// Transposer
#if defined(__GNUC__) && __GNUC__ < 5
// This is another workaround of a bug in gcc-4
#define LOG2BS 3
#else
#define LOG2BS 4
#endif
#define BS (1 << LOG2BS)
#define TRANSPOSE_BLOCK(y2) do { \
for(int x2=y2+1;x2<BS;x2++) { \
element_t r = *(element_t *)&row[y2].r[x2*2+0]; \
*(element_t *)&row[y2].r[x2*2+0] = *(element_t *)&row[x2].r[y2*2+0]; \
*(element_t *)&row[x2].r[y2*2+0] = r; \
}} while(0)
static void transpose(real *RESTRICT ALIGNED(256) d, real *RESTRICT ALIGNED(256) s, const int log2n, const int log2m) {
if (log2n < LOG2BS || log2m < LOG2BS) {
for(int y=0;y<(1 << log2n);y++) {
for(int x=0;x<(1 << log2m);x++) {
real r0 = s[((y << log2m)+x)*2+0];
real r1 = s[((y << log2m)+x)*2+1];
d[((x << log2n)+y)*2+0] = r0;
d[((x << log2n)+y)*2+1] = r1;
}
}
} else {
#if defined(__GNUC__) && !defined(__clang__)
typedef struct { real __attribute__((vector_size(sizeof(real)*BS*2))) r; } row_t;
typedef struct { real __attribute__((vector_size(sizeof(real)*2))) r; } element_t;
#else
typedef struct { real r[BS*2]; } row_t;
typedef struct { real r0, r1; } element_t;
#endif
for(int y=0;y<(1 << log2n);y+=BS) {
for(int x=0;x<(1 << log2m);x+=BS) {
row_t row[BS];
for(int y2=0;y2<BS;y2++) {
row[y2] = *(row_t *)&s[(((y+y2) << log2m)+x)*2];
}
#if LOG2BS == 4
TRANSPOSE_BLOCK( 0); TRANSPOSE_BLOCK( 1);
TRANSPOSE_BLOCK( 2); TRANSPOSE_BLOCK( 3);
TRANSPOSE_BLOCK( 4); TRANSPOSE_BLOCK( 5);
TRANSPOSE_BLOCK( 6); TRANSPOSE_BLOCK( 7);
TRANSPOSE_BLOCK( 8); TRANSPOSE_BLOCK( 9);
TRANSPOSE_BLOCK(10); TRANSPOSE_BLOCK(11);
TRANSPOSE_BLOCK(12); TRANSPOSE_BLOCK(13);
TRANSPOSE_BLOCK(14); TRANSPOSE_BLOCK(15);
#else
for(int y2=0;y2<BS;y2++) {
for(int x2=y2+1;x2<BS;x2++) {
element_t r = *(element_t *)&row[y2].r[x2*2+0];
*(element_t *)&row[y2].r[x2*2+0] = *(element_t *)&row[x2].r[y2*2+0];
*(element_t *)&row[x2].r[y2*2+0] = r;
}
}
#endif
for(int y2=0;y2<BS;y2++) {
*(row_t *)&d[(((x+y2) << log2n)+y)*2] = row[y2];
}
}
}
}
}
#ifdef _OPENMP
static void transposeMT(real *RESTRICT ALIGNED(256) d, real *RESTRICT ALIGNED(256) s, int log2n, int log2m) {
if (log2n < LOG2BS || log2m < LOG2BS) {
for(int y=0;y<(1 << log2n);y++) {
for(int x=0;x<(1 << log2m);x++) {
real r0 = s[((y << log2m)+x)*2+0];
real r1 = s[((y << log2m)+x)*2+1];
d[((x << log2n)+y)*2+0] = r0;
d[((x << log2n)+y)*2+1] = r1;
}
}
} else {
#if defined(__GNUC__) && !defined(__clang__)
typedef struct { real __attribute__((vector_size(sizeof(real)*BS*2))) r; } row_t;
typedef struct { real __attribute__((vector_size(sizeof(real)*2))) r; } element_t;
#else
typedef struct { real r[BS*2]; } row_t;
typedef struct { real r0, r1; } element_t;
#endif
int y;
#pragma omp parallel for
for(y=0;y<(1 << log2n);y+=BS) {
for(int x=0;x<(1 << log2m);x+=BS) {
row_t row[BS];
for(int y2=0;y2<BS;y2++) {
row[y2] = *(row_t *)&s[(((y+y2) << log2m)+x)*2];
}
#if LOG2BS == 4
TRANSPOSE_BLOCK( 0); TRANSPOSE_BLOCK( 1);
TRANSPOSE_BLOCK( 2); TRANSPOSE_BLOCK( 3);
TRANSPOSE_BLOCK( 4); TRANSPOSE_BLOCK( 5);
TRANSPOSE_BLOCK( 6); TRANSPOSE_BLOCK( 7);
TRANSPOSE_BLOCK( 8); TRANSPOSE_BLOCK( 9);
TRANSPOSE_BLOCK(10); TRANSPOSE_BLOCK(11);
TRANSPOSE_BLOCK(12); TRANSPOSE_BLOCK(13);
TRANSPOSE_BLOCK(14); TRANSPOSE_BLOCK(15);
#else
for(int y2=0;y2<BS;y2++) {
for(int x2=y2+1;x2<BS;x2++) {
element_t r = *(element_t *)&row[y2].r[x2*2+0];
*(element_t *)&row[y2].r[x2*2+0] = *(element_t *)&row[x2].r[y2*2+0];
*(element_t *)&row[x2].r[y2*2+0] = r;
}
}
#endif
for(int y2=0;y2<BS;y2++) {
*(row_t *)&d[(((x+y2) << log2n)+y)*2] = row[y2];
}
}
}
}
}
#endif // #ifdef _OPENMP
// Table generator
static sc_t r2coefsc(int i, int log2len, int level) {
return SINCOSPI((i & ((-1 << (log2len - level)) & ~(-1 << log2len))) * ((real)1.0/(1 << (log2len-1))));
}
static sc_t srcoefsc(int i, int log2len, int level) {
return SINCOSPI(((3*(i & (-1 << (log2len - level)))) & ~(-1 << log2len)) * ((real)1.0/(1 << (log2len-1))));
}
static int makeTableRecurse(real *x, int *p, const int log2len, const int levelorg, const int levelinc, const int sign, const int top, const int bot, const int N, int cnt) {
if (levelinc >= N-1) return cnt;
const int level = levelorg - levelinc;
if (bot - top > 4) {
const int bl = 1 << (N - levelinc);
const int w = bl/4;
for(int j=0;j<(bot-top)/bl;j++) {
for(int i=0;i<w;i++) {
int a = sign*(p[(levelinc << N) + top+bl*j+i] & (-1 << (log2len - level)));
sc_t sc;
sc = r2coefsc(a, log2len, level);
x[cnt++] = -sc.x; x[cnt++] = -sc.y;
sc = srcoefsc(a, log2len, level);
x[cnt++] = -sc.x; x[cnt++] = -sc.y;
}
cnt = makeTableRecurse(x, p, log2len, levelorg, levelinc+1, sign, top+bl*j , top+bl*j + bl/2, N, cnt);
cnt = makeTableRecurse(x, p, log2len, levelorg, levelinc+2, sign, top+bl*j + bl/2, top+bl*j + bl , N, cnt);
}
} else if (bot - top == 4) {
int a = sign*(p[(levelinc << N) + top] & (-1 << (log2len - level)));
sc_t sc;
sc = r2coefsc(a, log2len, level);
x[cnt++] = -sc.x; x[cnt++] = -sc.y;
sc = srcoefsc(a, log2len, level);
x[cnt++] = -sc.x; x[cnt++] = -sc.y;
}
return cnt;
}
static uint32_t perm(int nbits, uint32_t k, int s, int d) {
s = MIN(MAX(s, 0), nbits);
d = MIN(MAX(d, 0), nbits);
uint32_t r;
r = (((k & 0xaaaaaaaa) >> 1) | ((k & 0x55555555) << 1));
r = (((r & 0xcccccccc) >> 2) | ((r & 0x33333333) << 2));
r = (((r & 0xf0f0f0f0) >> 4) | ((r & 0x0f0f0f0f) << 4));
r = (((r & 0xff00ff00) >> 8) | ((r & 0x00ff00ff) << 8));
r = ((r >> 16) | (r << 16)) >> (32-nbits);
return (((r << s) | (k & ~(-1 << s))) & ~(-1 << d)) |
((((k >> s) | (r & (-1 << (nbits-s)))) << d) & ~(-1 << nbits));
}
static real **makeTable(int sign, int vecwidth, int log2len, const int N, const int K) {
if (log2len < N) return NULL;
int *p = (int *)malloc(sizeof(int)*((N+1)<<N));
real **tbl = (real **)calloc(sizeof(real *), (log2len+1));
for(int level=N;level<=log2len;level++) {
if (level == log2len && (1 << (log2len-N)) < vecwidth) { tbl[level] = NULL; continue; }
int tblOffset = 0;
tbl[level] = (real *)Sleef_malloc(sizeof(real) * (K << (level-N)));
for(int i0=0;i0 < (1 << (log2len-N));i0+=(1 << (log2len - level))) {
for(int j=0;j<N+1;j++) {
for(int i=0;i<(1 << N);i++) {
p[(j << N) + i] = perm(log2len, i0 + (i << (log2len-N)), log2len-level, log2len-(level-j));
}
}
int a = -sign*(p[((N-1) << N) + 0] & (-1 << (log2len - level)));
sc_t sc = r2coefsc(a, log2len, level-N+1);
tbl[level][tblOffset++] = sc.y; tbl[level][tblOffset++] = sc.x;
tblOffset = makeTableRecurse(tbl[level], p, log2len, level, 0, sign, 0, 1 << N, N, tblOffset);
}
if (level == log2len) {
real *atbl = (real *)Sleef_malloc(sizeof(real)*(K << (log2len-N))*2);
tblOffset = 0;
while(tblOffset < (K << (log2len-N))) {
for(int k=0;k < K;k++) {
for(int v = 0;v < vecwidth;v++) {
assert((tblOffset + k * vecwidth + v)*2 + 1 < (K << (log2len-N))*2);
atbl[(tblOffset + k * vecwidth + v)*2 + 0] = tbl[log2len][tblOffset + v * K + k];
atbl[(tblOffset + k * vecwidth + v)*2 + 1] = tbl[log2len][tblOffset + v * K + k];
}
}
tblOffset += K * vecwidth;
}
Sleef_free(tbl[log2len]);
tbl[log2len] = atbl;
}
}
free(p);
return tbl;
}
// Random planner (for debugging)
static int searchForRandomPathRecurse(SleefDFT *p, int level, int *path, int *pathConfig, uint64_t tm, int nTrial) {
if (level == 0) {
p->bestTime = tm;
for(uint32_t j = 0;j < p->log2len+1;j++) {
p->bestPathConfig[j] = pathConfig[j];
p->bestPath[j] = path[j];
}
return nTrial;
}
if (level < 1) return nTrial-1;
for(int i=0;i<10;i++) {
int N;
do {
N = 1 + rand() % MAXBUTWIDTH;
} while(p->tm[0][level*(MAXBUTWIDTH+1)+N] >= 1ULL << 60);
if (p->vecwidth > (1 << N) || N == p->log2len) continue;
path[level] = N;
for(;;) {
pathConfig[level] = rand() % CONFIGMAX;
#if ENABLE_STREAM == 0
pathConfig[level] &= ~1;
#endif
if ((p->mode2 & SLEEF_MODE2_MT1D) == 0 && (pathConfig[level] & CONFIG_MT) != 0) continue;
break;
}
for(int j = level-1;j >= 0;j--) path[j] = 0;
nTrial = searchForRandomPathRecurse(p, level - N, path, pathConfig, 0, nTrial);
if (nTrial <= 0) break;
if (p->bestTime < 1ULL << 60) break;
}
return nTrial - 1;
}
// Planner
#define NSHORTESTPATHS 15
#define MAXPATHLEN (MAXLOG2LEN+1)
#define POSMAX (CONFIGMAX * MAXLOG2LEN * (MAXBUTWIDTH+1))
static int cln2pos(int config, int level, int N) { return (config * MAXLOG2LEN + level) * MAXBUTWIDTH + N; }
static int pos2config(int pos) { return pos == -1 ? -1 : ((pos - 1) / (MAXBUTWIDTH * MAXLOG2LEN)); }
static int pos2level(int pos) { return pos == -1 ? -1 : (((pos - 1) / MAXBUTWIDTH) % MAXLOG2LEN); }
static int pos2N(int pos) { return pos == -1 ? -1 : ((pos - 1) % MAXBUTWIDTH + 1); }
typedef struct {
SleefDFT *p;
int countu[POSMAX];
int path[NSHORTESTPATHS][MAXPATHLEN];
int pathLen[NSHORTESTPATHS];
uint64_t cost[NSHORTESTPATHS];
int nPaths;
int *heap;
int *heapLen;
uint64_t *heapCost;
int heapSize, nPathsInHeap;
} ks_t;
static ks_t *ksInit(SleefDFT *p) {
ks_t *q = calloc(1, sizeof(ks_t));
q->p = p;
q->heapSize = 10;
q->heap = calloc(q->heapSize, sizeof(int)*MAXPATHLEN);
q->heapCost = calloc(q->heapSize, sizeof(uint64_t));
q->heapLen = calloc(q->heapSize, sizeof(int));
return q;
}
static void ksDispose(ks_t *q) {
free(q->heapCost);
free(q->heapLen);
free(q->heap);
free(q);
}
// returns the number of paths in the heap
static int ksSize(ks_t *q) { return q->nPathsInHeap; }
// adds a path to the heap
static void ksAddPath(ks_t *q, int *path, int pathLen, uint64_t cost) {
assert(pathLen <= MAXPATHLEN);
if (q->nPathsInHeap == q->heapSize) {
q->heapSize *= 2;
q->heap = realloc(q->heap, q->heapSize * sizeof(int)*MAXPATHLEN);
q->heapCost = realloc(q->heapCost, q->heapSize * sizeof(uint64_t));
q->heapLen = realloc(q->heapLen, q->heapSize * sizeof(int));
}
for(int i=0;i<pathLen;i++) q->heap[q->nPathsInHeap * MAXPATHLEN + i] = path[i];
q->heapLen[q->nPathsInHeap] = pathLen;
q->heapCost[q->nPathsInHeap] = cost;
q->nPathsInHeap++;
}
// returns the cost of n-th paths in the heap
static uint64_t ksCost(ks_t *q, int n) {
assert(0 <= n && n < q->nPathsInHeap);
return q->heapCost[n];
}
// copies the n-th paths in the heap to path, returns its length
static int ksGetPath(ks_t *q, int *path, int n) {
assert(0 <= n && n < q->nPathsInHeap);
int len = q->heapLen[n];
for(int i=0;i<len;i++) path[i] = q->heap[n * MAXPATHLEN + i];
return len;
}
// removes the n-th paths in the heap
static void ksRemove(ks_t *q, int n) {
assert(0 <= n && n < q->nPathsInHeap);
for(int i=n;i<q->nPathsInHeap-1;i++) {
int len = q->heapLen[i+1];
assert(len < MAXPATHLEN);
for(int j=0;j<len;j++) q->heap[i * MAXPATHLEN + j] = q->heap[(i+1) * MAXPATHLEN + j];
q->heapLen[i] = q->heapLen[i+1];
q->heapCost[i] = q->heapCost[i+1];
}
q->nPathsInHeap--;
}
// returns the countu value at pos
static int ksCountu(ks_t *q, int pos) {
assert(0 <= pos && pos < POSMAX);
return q->countu[pos];
}
// set the countu value at pos to n
static void ksSetCountu(ks_t *q, int pos, int n) {
assert(0 <= pos && pos < POSMAX);
q->countu[pos] = n;
}
// adds a path as one of the best k paths, returns the number best paths
static int ksAddBestPath(ks_t *q, int *path, int pathLen, uint64_t cost) {
assert(pathLen <= MAXPATHLEN);
assert(q->nPaths < NSHORTESTPATHS);
for(int i=0;i<pathLen;i++) q->path[q->nPaths][i] = path[i];
q->pathLen[q->nPaths] = pathLen;
q->cost[q->nPaths] = cost;
q->nPaths++;
return q->nPaths;
}
// returns if pos is a destination
static int ksIsDest(ks_t *q, int pos) { return pos2level(pos) == 0; }
// returns n-th adjacent nodes at pos.
static int ksAdjacent(ks_t *q, int pos, int n) {
if (pos != -1 && pos2level(pos) == 0) return -1;
int NMAX = MIN(MIN(q->p->log2len, MAXBUTWIDTH+1), q->p->log2len - q->p->log2vecwidth + 1);
if (pos == -1) {
int N = n / 2 + MAX(q->p->log2vecwidth, 1);
if (N >= NMAX) return -1;
return cln2pos((n & 1) * CONFIG_MT, q->p->log2len, N);
}
int config = (pos2config(pos) & CONFIG_MT);
int N = n + 1;
int level = pos2level(pos) - pos2N(pos);
if (level < 0 || N >= NMAX) return -1;
if (level == 0) return n == 0 ? cln2pos(0, 0, 0) : -1;
return cln2pos(config, level, N);
}
static uint64_t ksAdjacentCost(ks_t *q, int pos, int n) {
int nxpos = ksAdjacent(q, pos, n);
if (nxpos == -1) return 0;
int config = pos2config(nxpos), level = pos2level(nxpos), N = pos2N(nxpos);
uint64_t ret0 = q->p->tm[config | 0][level*(MAXBUTWIDTH+1) + N];
uint64_t ret1 = q->p->tm[config | 1][level*(MAXBUTWIDTH+1) + N];
return MIN(ret0, ret1);
}
static void searchForBestPath(SleefDFT *p) {
ks_t *q = ksInit(p);
for(int i=0;;i++) {
int v = ksAdjacent(q, -1, i);
if (v == -1) break;
uint64_t c = ksAdjacentCost(q, -1, i);
int path[1] = { v };
ksAddPath(q, path, 1, c);
}
while(ksSize(q) != 0) {
uint64_t bestCost = 1ULL << 60;
int bestPathNum = -1;
for(int i=0;i<ksSize(q);i++) {
if (ksCost(q, i) < bestCost) {
bestCost = ksCost(q, i);
bestPathNum = i;
}
}
if (bestPathNum == -1) break;
int path[MAXPATHLEN];
int pathLen = ksGetPath(q, path, bestPathNum);
uint64_t cost = ksCost(q, bestPathNum);
ksRemove(q, bestPathNum);
int lastPos = path[pathLen-1];
if (ksCountu(q, lastPos) >= NSHORTESTPATHS) continue;
ksSetCountu(q, lastPos, ksCountu(q, lastPos)+1);
if (ksIsDest(q, lastPos)) {
if (ksAddBestPath(q, path, pathLen, cost) >= NSHORTESTPATHS) break;
continue;
}
for(int i=0;;i++) {
int v = ksAdjacent(q, lastPos, i);
if (v == -1) break;
assert(0 <= pos2N(v) && pos2N(v) <= q->p->log2len);
uint64_t c = ksAdjacentCost(q, lastPos, i);
path[pathLen] = v;
ksAddPath(q, path, pathLen+1, cost + c);
}
}
for(int j = p->log2len;j >= 0;j--) p->bestPath[j] = 0;
if (((p->mode & SLEEF_MODE_MEASURE) != 0 || (planFilePathSet && (p->mode & SLEEF_MODE_MEASUREBITS) == 0))) {
uint64_t besttm = 1ULL << 62;
int bestPath = -1;
const int niter = 1 + 5000000 / ((1 << p->log2len) + 1);
real *s2 = NULL, *d2 = NULL;
const real *s = p->in == NULL ? (s2 = (real *)memset(Sleef_malloc((2 << p->log2len) * sizeof(real)), 0, sizeof(real) * (2 << p->log2len))) : p->in;
real *d = p->out == NULL ? (d2 = (real *)memset(Sleef_malloc((2 << p->log2len) * sizeof(real)), 0, sizeof(real) * (2 << p->log2len))) : p->out;
#ifdef _OPENMP
const int tn = omp_get_thread_num();
#else
const int tn = 0;
#endif
real *t[] = { p->x1[tn], p->x0[tn], d };
for(int mt=0;mt<2;mt++) {
for(int i=q->nPaths-1;i>=0;i--) {
if (((pos2config(q->path[i][0]) & CONFIG_MT) != 0) != mt) continue;
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) {
for(int j=0;j<q->pathLen[i];j++) {
int N = pos2N(q->path[i][j]);
int level = pos2level(q->path[i][j]);
int config = pos2config(q->path[i][j]) & ~1;
uint64_t t0 = q->p->tm[config | 0][level*(MAXBUTWIDTH+1) + N];
uint64_t t1 = q->p->tm[config | 1][level*(MAXBUTWIDTH+1) + N];
config = t0 < t1 ? config : (config | 1);
if (N != 0) printf("%d(%s) ", N, configStr[config]);
}
}
if (mt) startAllThreads(p->nThread);
uint64_t tm0 = Sleef_currentTimeMicros();
for(int k=0;k<niter;k++) {
int nb = 0;
const real *lb = s;
if ((p->pathLen & 1) == 1) nb = -1;
for(int level = p->log2len, j=0;level >= 1;j++) {
assert(pos2level(q->path[i][j]) == level);
int N = pos2N(q->path[i][j]);
int config = pos2config(q->path[i][j]) & ~1;
uint64_t t0 = q->p->tm[config | 0][level*(MAXBUTWIDTH+1) + N];
uint64_t t1 = q->p->tm[config | 1][level*(MAXBUTWIDTH+1) + N];
config = t0 < t1 ? config : (config | 1);
dispatch(p, N, t[nb+1], lb, level, config);
level -= N;
lb = t[nb+1];
nb = (nb + 1) & 1;
}
}
uint64_t tm1 = Sleef_currentTimeMicros();
for(int k=0;k<niter;k++) {
int nb = 0;
const real *lb = s;
if ((p->pathLen & 1) == 1) nb = -1;
for(int level = p->log2len, j=0;level >= 1;j++) {
assert(pos2level(q->path[i][j]) == level);
int N = pos2N(q->path[i][j]);
int config = pos2config(q->path[i][j]) & ~1;
uint64_t t0 = q->p->tm[config | 0][level*(MAXBUTWIDTH+1) + N];
uint64_t t1 = q->p->tm[config | 1][level*(MAXBUTWIDTH+1) + N];
config = t0 < t1 ? config : (config | 1);
dispatch(p, N, t[nb+1], lb, level, config);
level -= N;
lb = t[nb+1];
nb = (nb + 1) & 1;
}
}
uint64_t tm2 = Sleef_currentTimeMicros();
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) printf(" : %lld %lld\n", (long long int)(tm1 - tm0), (long long int)(tm2 - tm1));
if ((tm1 - tm0) < besttm) {
bestPath = i;
besttm = tm1 - tm0;
}
if ((tm2 - tm1) < besttm) {
bestPath = i;
besttm = tm2 - tm1;
}
}
}
for(int level = p->log2len, j=0;level >= 1;j++) {
assert(pos2level(q->path[bestPath][j]) == level);
int N = pos2N(q->path[bestPath][j]);
int config = pos2config(q->path[bestPath][j]) & ~1;
uint64_t t0 = q->p->tm[config | 0][level*(MAXBUTWIDTH+1) + N];
uint64_t t1 = q->p->tm[config | 1][level*(MAXBUTWIDTH+1) + N];
config = t0 < t1 ? config : (config | 1);
p->bestPath[level] = N;
p->bestPathConfig[level] = config;
level -= N;
}
if (d2 != NULL) Sleef_free(d2);
if (s2 != NULL) Sleef_free(s2);
} else {
for(int level = p->log2len, j=0;level >= 1;j++) {
int bestPath = 0;
assert(pos2level(q->path[bestPath][j]) == level);
int N = pos2N(q->path[bestPath][j]);
int config = pos2config(q->path[bestPath][j]);
p->bestPath[level] = N;
p->bestPathConfig[level] = config;
level -= N;
}
}
ksDispose(q);
}
//
static uint64_t estimate(int log2len, int level, int N, int config) {
uint64_t ret = N * 1000 + ABS(N-3) * 1000;
if (log2len >= 14 && (config & CONFIG_MT) != 0) ret /= 2;
return ret;
}
static void measureBut(SleefDFT *p) {
if (p->x0 == NULL) return;
//
#ifdef _OPENMP
const int tn = omp_get_thread_num();
#else
const int tn = 0;
#endif
real *s = (real *)memset(p->x0[tn], 0, sizeof(real) * (2 << p->log2len));
real *d = (real *)memset(p->x1[tn], 0, sizeof(real) * (2 << p->log2len));
const int niter = 1 + 100000 / ((1 << p->log2len) + 1);
#define MEASURE_REPEAT 4
for(int rep=1;rep<=MEASURE_REPEAT;rep++) {
for(int config=0;config<CONFIGMAX;config++) {
#if ENABLE_STREAM == 0
if ((config & 1) != 0) continue;
#endif
if ((p->mode2 & SLEEF_MODE2_MT1D) == 0 && (config & CONFIG_MT) != 0) continue;
for(uint32_t level = p->log2len;level >= 1;level--) {
for(uint32_t N=1;N<=MAXBUTWIDTH;N++) {
if (level < N || p->log2len <= N) continue;
if (level == N) {
if ((int)p->log2len - (int)level < p->log2vecwidth) continue;
uint64_t tm = Sleef_currentTimeMicros();
for(int i=0;i<niter*2;i++) {
dispatch(p, N, d, s, level, config);
}
tm = Sleef_currentTimeMicros() - tm + 1;
p->tm[config][level*(MAXBUTWIDTH+1)+N] = MIN(p->tm[config][level*(MAXBUTWIDTH+1)+N], tm);
} else if (level == p->log2len) {
if (p->tbl[N] == NULL || p->tbl[N][level] == NULL) continue;
if (p->vecwidth > (1 << N)) continue;
if ((config & CONFIG_MT) != 0) {
int i1;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for(i1=0;i1 < (1 << (p->log2len-N-p->log2vecwidth));i1++) {
int i0 = i1 << p->log2vecwidth;
p->perm[level][i1] = 2*perm(p->log2len, i0, p->log2len-level, p->log2len-(level-N));
}
} else {
for(int i0=0, i1=0;i0 < (1 << (p->log2len-N));i0+=p->vecwidth, i1++) {
p->perm[level][i1] = 2*perm(p->log2len, i0, p->log2len-level, p->log2len-(level-N));
}
}
uint64_t tm = Sleef_currentTimeMicros();
for(int i=0;i<niter;i++) {
dispatch(p, N, d, s, level, config);
dispatch(p, N, s, d, level, config);
}
tm = Sleef_currentTimeMicros() - tm + 1;
p->tm[config][level*(MAXBUTWIDTH+1)+N] = MIN(p->tm[config][level*(MAXBUTWIDTH+1)+N], tm);
} else {
if (p->tbl[N] == NULL || p->tbl[N][level] == NULL) continue;
if (p->vecwidth > 2 && p->log2len <= N+2) continue;
if ((int)p->log2len - (int)level < p->log2vecwidth) continue;
if ((config & CONFIG_MT) != 0) {
int i1;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for(i1=0;i1 < (1 << (p->log2len-N-p->log2vecwidth));i1++) {
int i0 = i1 << p->log2vecwidth;
p->perm[level][i1] = 2*perm(p->log2len, i0, p->log2len-level, p->log2len-(level-N));
}
} else {
for(int i0=0, i1=0;i0 < (1 << (p->log2len-N));i0+=p->vecwidth, i1++) {
p->perm[level][i1] = 2*perm(p->log2len, i0, p->log2len-level, p->log2len-(level-N));
}
}
uint64_t tm = Sleef_currentTimeMicros();
for(int i=0;i<niter;i++) {
dispatch(p, N, d, s, level, config);
dispatch(p, N, s, d, level, config);
}
tm = Sleef_currentTimeMicros() - tm + 1;
p->tm[config][level*(MAXBUTWIDTH+1)+N] = MIN(p->tm[config][level*(MAXBUTWIDTH+1)+N], tm);
}
}
}
}
}
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) {
for(uint32_t level = p->log2len;level >= 1;level--) {
for(uint32_t N=1;N<=MAXBUTWIDTH;N++) {
if (level < N || p->log2len <= N) continue;
if (level == N) {
if ((int)p->log2len - (int)level < p->log2vecwidth) continue;
printf("bot %d, %d, %d, ", p->log2len, level, N);
for(int config=0;config<CONFIGMAX;config++) {
if (p->tm[config][level*(MAXBUTWIDTH+1)+N] == 1ULL << 60) {
printf("N/A, ");
} else {
printf("%lld, ", (long long int)p->tm[config][level*(MAXBUTWIDTH+1)+N]);
}
}
printf("\n");
} else if (level == p->log2len) {
if (p->tbl[N] == NULL || p->tbl[N][level] == NULL) continue;
if (p->vecwidth > (1 << N)) continue;
printf("top %d, %d, %d, ", p->log2len, level, N);
for(int config=0;config<CONFIGMAX;config++) {
if (p->tm[config][level*(MAXBUTWIDTH+1)+N] == 1ULL << 60) {
printf("N/A, ");
} else {
printf("%lld, ", (long long int)p->tm[config][level*(MAXBUTWIDTH+1)+N]);
}
}
printf("\n");
} else {
if (p->tbl[N] == NULL || p->tbl[N][level] == NULL) continue;
if (p->vecwidth > 2 && p->log2len <= N+2) continue;
if ((int)p->log2len - (int)level < p->log2vecwidth) continue;
printf("mid %d, %d, %d, ", p->log2len, level, N);
for(int config=0;config<CONFIGMAX;config++) {
if (p->tm[config][level*(MAXBUTWIDTH+1)+N] == 1ULL << 60) {
printf("N/A, ");
} else {
printf("%lld, ", (long long int)p->tm[config][level*(MAXBUTWIDTH+1)+N]);
}
}
printf("\n");
}
}
}
}
}
static void estimateBut(SleefDFT *p) {
for(uint32_t level = p->log2len;level >= 1;level--) {
for(uint32_t N=1;N<=MAXBUTWIDTH;N++) {
if (level < N || p->log2len <= N) continue;
if (level == N) {
if ((int)p->log2len - (int)level < p->log2vecwidth) continue;
for(int config=0;config<CONFIGMAX;config++) {
#if ENABLE_STREAM == 0
if ((config & 1) != 0) continue;
#endif
p->tm[config][level*(MAXBUTWIDTH+1)+N] = estimate(p->log2len, level, N, config);
}
} else if (level == p->log2len) {
if (p->tbl[N] == NULL || p->tbl[N][level] == NULL) continue;
if (p->vecwidth > (1 << N)) continue;
for(int config=0;config<CONFIGMAX;config++) {
#if ENABLE_STREAM == 0
if ((config & 1) != 0) continue;
#endif
p->tm[config][level*(MAXBUTWIDTH+1)+N] = estimate(p->log2len, level, N, config);
}
} else {
if (p->tbl[N] == NULL || p->tbl[N][level] == NULL) continue;
if (p->vecwidth > 2 && p->log2len <= N+2) continue;
if ((int)p->log2len - (int)level < p->log2vecwidth) continue;
for(int config=0;config<CONFIGMAX;config++) {
#if ENABLE_STREAM == 0
if ((config & 1) != 0) continue;
#endif
p->tm[config][level*(MAXBUTWIDTH+1)+N] = estimate(p->log2len, level, N, config);
}
}
}
}
}
static int measure(SleefDFT *p, int randomize) {
if (p->log2len == 1) {
p->bestTime = 1ULL << 60;
p->pathLen = 1;
p->bestPath[1] = 1;
return 1;
}
if (PlanManager_loadMeasurementResultsP(p, (p->mode & SLEEF_MODE_NO_MT) != 0 ? 1 : 0)) {
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) {
printf("Path(loaded) : ");
for(int j = p->log2len;j >= 0;j--) if (p->bestPath[j] != 0) printf("%d(%s) ", p->bestPath[j], configStr[p->bestPathConfig[j]]);
printf("\n");
}
return 1;
}
int toBeSaved = 0;
for(uint32_t level = p->log2len;level >= 1;level--) {
for(uint32_t N=1;N<=MAXBUTWIDTH;N++) {
for(int config=0;config<CONFIGMAX;config++) {
p->tm[config][level*(MAXBUTWIDTH+1)+N] = 1ULL << 60;
}
}
}
if (((p->mode & SLEEF_MODE_MEASURE) != 0 || (planFilePathSet && (p->mode & SLEEF_MODE_MEASUREBITS) == 0)) && !randomize) {
measureBut(p);
toBeSaved = 1;
} else {
estimateBut(p);
}
int executable = 0;
for(int i=1;i<=MAXBUTWIDTH && !executable;i++) {
if (p->tm[0][p->log2len*(MAXBUTWIDTH+1)+i] < (1ULL << 60)) executable = 1;
}
if (!executable) return 0;
p->bestTime = 1ULL << 60;
p->bestPath[p->log2len] = 0;
if (!randomize) {
searchForBestPath(p);
} else {
int path[MAXLOG2LEN+1];
int pathConfig[MAXLOG2LEN+1];
for(int j = p->log2len;j >= 0;j--) path[j] = pathConfig[j] = 0;
int nTrial = 100000;
do {
nTrial = searchForRandomPathRecurse(p, p->log2len, path, pathConfig, 0, nTrial);
} while(p->bestTime == 1ULL << 60 && nTrial >= 0);
}
if (p->bestPath[p->log2len] == 0) return 0;
p->pathLen = 0;
for(int j = p->log2len;j >= 0;j--) if (p->bestPath[j] != 0) p->pathLen++;
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) {
printf("Path");
if (randomize) printf("(random) :");
else if (toBeSaved) printf("(measured) :");
else printf("(estimated) :");
for(int j = p->log2len;j >= 0;j--) if (p->bestPath[j] != 0) printf("%d(%s) ", p->bestPath[j], configStr[p->bestPathConfig[j]]);
printf("\n");
}
if (toBeSaved) {
PlanManager_saveMeasurementResultsP(p, (p->mode & SLEEF_MODE_NO_MT) != 0 ? 1 : 0);
}
return 1;
}
static void measureTranspose(SleefDFT *p) {
if (PlanManager_loadMeasurementResultsT(p)) {
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) printf("transpose NoMT(loaded): %lld\n", (long long int)p->tmNoMT);
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) printf("transpose MT(loaded): %lld\n", (long long int)p->tmMT);
return;
}
if ((p->mode & SLEEF_MODE_MEASURE) == 0 && (!planFilePathSet || (p->mode & SLEEF_MODE_MEASUREBITS) != 0)) {
if (p->log2hlen + p->log2vlen >= 14) {
p->tmNoMT = 20;
p->tmMT = 10;
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) printf("transpose : selected MT(estimated)\n");
} else {
p->tmNoMT = 10;
p->tmMT = 20;
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) printf("transpose : selected NoMT(estimated)\n");
}
return;
}
real *tBuf2 = (real *)Sleef_malloc(sizeof(real)*2*p->hlen*p->vlen);
const int niter = 1 + 5000000 / (p->hlen * p->vlen + 1);
uint64_t tm;
tm = Sleef_currentTimeMicros();
for(int i=0;i<niter;i++) {
transpose(tBuf2, p->tBuf, p->log2hlen, p->log2vlen);
transpose(tBuf2, p->tBuf, p->log2vlen, p->log2hlen);
}
p->tmNoMT = Sleef_currentTimeMicros() - tm + 1;
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) printf("transpose NoMT(measured): %lld\n", (long long int)p->tmNoMT);
#ifdef _OPENMP
tm = Sleef_currentTimeMicros();
for(int i=0;i<niter;i++) {
transposeMT(tBuf2, p->tBuf, p->log2hlen, p->log2vlen);
transposeMT(tBuf2, p->tBuf, p->log2vlen, p->log2hlen);
}
p->tmMT = Sleef_currentTimeMicros() - tm + 1;
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) printf("transpose MT(measured): %lld\n", (long long int)p->tmMT);
#else
p->tmMT = p->tmNoMT*2;
#endif
Sleef_free(tBuf2);
PlanManager_saveMeasurementResultsT(p);
}
// Implementation of SleefDFT_*_init1d
EXPORT SleefDFT *INIT(uint32_t n, const real *in, real *out, uint64_t mode) {
SleefDFT *p = (SleefDFT *)calloc(1, sizeof(SleefDFT));
p->magic = MAGIC;
p->baseTypeID = BASETYPEID;
p->in = (const void *)in;
p->out = (void *)out;
// Mode
p->mode = mode;
if ((p->mode & SLEEF_MODE_NO_MT) == 0) {
p->mode2 |= SLEEF_MODE2_MT1D;
}
if ((mode & SLEEF_MODE_REAL) != 0) n /= 2;
p->log2len = ilog2(n);
if (p->log2len <= 1) return p;
if ((mode & SLEEF_MODE_ALT) != 0) p->mode = mode = mode ^ SLEEF_MODE_BACKWARD;
#ifdef _OPENMP
p->nThread = omp_thread_count();
#else
p->nThread = 1;
p->mode2 &= ~SLEEF_MODE2_MT1D;
#endif
// ISA availability
int bestPriority = -1;
p->isa = -1;
for(int i=0;i<ISAMAX;i++) {
if (checkISAAvailability(i) && bestPriority < (*GETINT[i])(GETINT_DFTPRIORITY) && n >= (*GETINT[i])(GETINT_VECWIDTH) * (*GETINT[i])(GETINT_VECWIDTH)) {
bestPriority = (*GETINT[i])(GETINT_DFTPRIORITY);
p->isa = i;
}
}
if (p->isa == -1) {
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) printf("ISA not available\n");
p->magic = 0;
free(p);
return NULL;
}
// Tables
p->perm = (uint32_t **)calloc(sizeof(uint32_t *), p->log2len+1);
for(int level = p->log2len;level >= 1;level--) {
p->perm[level] = (uint32_t *)Sleef_malloc(sizeof(uint32_t) * ((1 << p->log2len) + 8));
}
p->x0 = malloc(sizeof(real *) * p->nThread);
p->x1 = malloc(sizeof(real *) * p->nThread);
for(int i=0;i<p->nThread;i++) {
p->x0[i] = (real *)Sleef_malloc(sizeof(real) * 2 * n);
p->x1[i] = (real *)Sleef_malloc(sizeof(real) * 2 * n);
}
if ((mode & SLEEF_MODE_REAL) != 0) {
p->rtCoef0 = (real *)Sleef_malloc(sizeof(real) * n);
p->rtCoef1 = (real *)Sleef_malloc(sizeof(real) * n);
if ((mode & SLEEF_MODE_BACKWARD) == 0) {
for(uint32_t i=0;i<n/2;i++) {
sc_t sc = SINCOSPI(i*((real)-1.0/n));
((real *)p->rtCoef0)[i*2+0] = ((real *)p->rtCoef0)[i*2+1] = (real)0.5 - (real)0.5 * sc.x;
((real *)p->rtCoef1)[i*2+0] = ((real *)p->rtCoef1)[i*2+1] = (real)0.5*sc.y;
}
} else {
for(uint32_t i=0;i<n/2;i++) {
sc_t sc = SINCOSPI(i*((real)-1.0/n));
((real *)p->rtCoef0)[i*2+0] = ((real *)p->rtCoef0)[i*2+1] = (real)0.5 + (real)0.5 * sc.x;
((real *)p->rtCoef1)[i*2+0] = ((real *)p->rtCoef1)[i*2+1] = (real)0.5*sc.y;
}
}
}
// Measure
int sign = (mode & SLEEF_MODE_BACKWARD) != 0 ? -1 : 1;
p->vecwidth = (*GETINT[p->isa])(GETINT_VECWIDTH);
p->log2vecwidth = ilog2(p->vecwidth);
for(int i=1;i<=MAXBUTWIDTH;i++) {
((real ***)p->tbl)[i] = makeTable(sign, p->vecwidth, p->log2len, i, constK[i]);
}
if (!measure(p, (mode & SLEEF_MODE_DEBUG))) {
// Fall back to the first ISA
freeTables(p);
p->isa = 0;
p->vecwidth = (*GETINT[p->isa])(GETINT_VECWIDTH);
p->log2vecwidth = ilog2(p->vecwidth);
for(int i=1;i<=MAXBUTWIDTH;i++) {
((real ***)p->tbl)[i] = makeTable(sign, p->vecwidth, p->log2len, i, constK[i]);
}
for(int level = p->log2len;level >= 1;) {
int N = ABS(p->bestPath[level]);
if (level == N) { level -= N; continue; }
int i1 = 0;
for(int i0=0;i0 < (1 << (p->log2len-N));i0+=p->vecwidth, i1++) {
p->perm[level][i1] = 2*perm(p->log2len, i0, p->log2len-level, p->log2len-(level-N));
}
for(;i1 < (1 << p->log2len) + 8;i1++) p->perm[level][i1] = 0;
level -= N;
}
if (!measure(p, (mode & SLEEF_MODE_DEBUG))) {
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) printf("Suitable ISA not found. This should not happen.\n");
return NULL;
}
}
for(int level = p->log2len;level >= 1;) {
int N = ABS(p->bestPath[level]);
if (level == N) { level -= N; continue; }
int i1 = 0;
for(int i0=0;i0 < (1 << (p->log2len-N));i0+=p->vecwidth, i1++) {
p->perm[level][i1] = 2*perm(p->log2len, i0, p->log2len-level, p->log2len-(level-N));
}
for(;i1 < (1 << p->log2len) + 8;i1++) p->perm[level][i1] = 0;
level -= N;
}
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) printf("ISA : %s %d bit %s\n", (char *)(*GETPTR[p->isa])(0), (int)(GETINT[p->isa](GETINT_VECWIDTH) * sizeof(real) * 16), BASETYPESTRING);
return p;
}
// Implementation of SleefDFT_*_init2d
EXPORT SleefDFT *INIT2D(uint32_t vlen, uint32_t hlen, const real *in, real *out, uint64_t mode) {
SleefDFT *p = (SleefDFT *)calloc(1, sizeof(SleefDFT));
p->magic = MAGIC2D;
p->mode = mode;
p->baseTypeID = BASETYPEID;
p->in = in;
p->out = out;
p->hlen = hlen;
p->log2hlen = ilog2(hlen);
p->vlen = vlen;
p->log2vlen = ilog2(vlen);
uint64_t mode1D = mode;
mode1D |= SLEEF_MODE_NO_MT;
if ((mode & SLEEF_MODE_NO_MT) == 0) p->mode3 |= SLEEF_MODE3_MT2D;
p->instH = p->instV = INIT(hlen, NULL, NULL, mode1D);
if (hlen != vlen) p->instV = INIT(vlen, NULL, NULL, mode1D);
p->tBuf = (void *)Sleef_malloc(sizeof(real)*2*hlen*vlen);
measureTranspose(p);
return p;
}
// Implementation of SleefDFT_*_execute
EXPORT void EXECUTE(SleefDFT *p, const real *s0, real *d0) {
assert(p != NULL && (p->magic == MAGIC || p->magic == MAGIC2D));
const real *s = s0 == NULL ? p->in : s0;
real *d = d0 == NULL ? p->out : d0;
if (p->magic == MAGIC2D) {
// S -> T -> D -> T -> D
real *tBuf = (real *)(p->tBuf);
#ifdef _OPENMP
if ((p->mode3 & SLEEF_MODE3_MT2D) != 0 &&
(((p->mode & SLEEF_MODE_DEBUG) == 0 && p->tmMT < p->tmNoMT) ||
((p->mode & SLEEF_MODE_DEBUG) != 0 && (rand() & 1))))
{
int y;
#pragma omp parallel for
for(y=0;y<p->vlen;y++) {
EXECUTE(p->instH, &s[p->hlen*2*y], &tBuf[p->hlen*2*y]);
}
transposeMT(d, tBuf, p->log2vlen, p->log2hlen);
#pragma omp parallel for
for(y=0;y<p->hlen;y++) {
EXECUTE(p->instV, &d[p->vlen*2*y], &tBuf[p->vlen*2*y]);
}
transposeMT(d, tBuf, p->log2hlen, p->log2vlen);
} else
#endif
{
for(int y=0;y<p->vlen;y++) {
EXECUTE(p->instH, &s[p->hlen*2*y], &tBuf[p->hlen*2*y]);
}
transpose(d, tBuf, p->log2vlen, p->log2hlen);
for(int y=0;y<p->hlen;y++) {
EXECUTE(p->instV, &d[p->vlen*2*y], &tBuf[p->vlen*2*y]);
}
transpose(d, tBuf, p->log2hlen, p->log2vlen);
}
return;
}
if (p->log2len <= 1) {
if ((p->mode & SLEEF_MODE_REAL) == 0) {
real r0 = s[0] + s[2];
real r1 = s[1] + s[3];
real r2 = s[0] - s[2];
real r3 = s[1] - s[3];
d[0] = r0; d[1] = r1; d[2] = r2; d[3] = r3;
} else {
if ((p->mode & SLEEF_MODE_ALT) == 0) {
if (p->log2len == 1) {
if ((p->mode & SLEEF_MODE_BACKWARD) == 0) {
real r0 = s[0] + s[2] + (s[1] + s[3]);
real r1 = s[0] + s[2] - (s[1] + s[3]);
real r2 = s[0] - s[2];
real r3 = s[3] - s[1];
d[0] = r0; d[1] = 0; d[2] = r2; d[3] = r3; d[4] = r1; d[5] = 0;
} else {
real r0 = (s[0] + s[4])*(real)0.5 + s[2];
real r1 = (s[0] - s[4])*(real)0.5 - s[3];
real r2 = (s[0] + s[4])*(real)0.5 - s[2];
real r3 = (s[0] - s[4])*(real)0.5 + s[3];
d[0] = r0*2; d[1] = r1*2; d[2] = r2*2; d[3] = r3*2;
}
} else {
if ((p->mode & SLEEF_MODE_BACKWARD) == 0) {
real r0 = s[0] + s[1];
real r1 = s[0] - s[1];
d[0] = r0; d[1] = 0; d[2] = r1; d[3] = 0;
} else {
real r0 = s[0] + s[2];
real r1 = s[0] - s[2];
d[0] = r0; d[1] = r1;
}
}
} else {
if (p->log2len == 1) {
if ((p->mode & SLEEF_MODE_BACKWARD) == 0) {
real r0 = s[0] + s[2] + (s[1] + s[3]);
real r1 = s[0] + s[2] - (s[1] + s[3]);
real r2 = s[0] - s[2];
real r3 = s[1] - s[3];
d[0] = r0; d[1] = r1; d[2] = r2; d[3] = r3;
} else {
real r0 = (s[0] + s[1])*(real)0.5 + s[2];
real r1 = (s[0] - s[1])*(real)0.5 + s[3];
real r2 = (s[0] + s[1])*(real)0.5 - s[2];
real r3 = (s[0] - s[1])*(real)0.5 - s[3];
d[0] = r0; d[1] = r1; d[2] = r2; d[3] = r3;
}
} else {
real c = ((p->mode & SLEEF_MODE_BACKWARD) != 0) ? (real)0.5 : (real)1.0;
real r0 = s[0] + s[1];
real r1 = s[0] - s[1];
d[0] = r0 * c; d[1] = r1 * c;
}
}
}
return;
}
//
#ifdef _OPENMP
const int tn = omp_get_thread_num();
real *t[] = { p->x1[tn], p->x0[tn], d };
#else
real *t[] = { p->x1[0], p->x0[0], d };
#endif
const real *lb = s;
int nb = 0;
if ((p->mode & SLEEF_MODE_REAL) != 0 && (p->pathLen & 1) == 0 &&
((p->mode & SLEEF_MODE_BACKWARD) != 0) != ((p->mode & SLEEF_MODE_ALT) != 0)) nb = -1;
if ((p->mode & SLEEF_MODE_REAL) == 0 && (p->pathLen & 1) == 1) nb = -1;
if ((p->mode & SLEEF_MODE_REAL) != 0 &&
((p->mode & SLEEF_MODE_BACKWARD) != 0) != ((p->mode & SLEEF_MODE_ALT) != 0)) {
(*REALSUB1[p->isa])(t[nb+1], s, p->log2len, p->rtCoef0, p->rtCoef1, (p->mode & SLEEF_MODE_ALT) == 0);
if ((p-> mode & SLEEF_MODE_ALT) == 0) t[nb+1][(1 << p->log2len)+1] = -s[(1 << p->log2len)+1] * 2;
lb = t[nb+1];
nb = (nb + 1) & 1;
}
for(int level = p->log2len;level >= 1;) {
int N = ABS(p->bestPath[level]), config = p->bestPathConfig[level];
dispatch(p, N, t[nb+1], lb, level, config);
level -= N;
lb = t[nb+1];
nb = (nb + 1) & 1;
}
if ((p->mode & SLEEF_MODE_REAL) != 0 &&
((p->mode & SLEEF_MODE_BACKWARD) == 0) != ((p->mode & SLEEF_MODE_ALT) != 0)) {
(*REALSUB0[p->isa])(d, lb, p->log2len, p->rtCoef0, p->rtCoef1);
if ((p->mode & SLEEF_MODE_ALT) == 0) {
d[(1 << p->log2len)+1] = -d[(1 << p->log2len)+1];
d[(2 << p->log2len)+0] = d[1];
d[(2 << p->log2len)+1] = 0;
d[1] = 0;
}
}
}
|
diagmm_x_bsr_n_col.c
|
#include "alphasparse/kernel.h"
#include "alphasparse/util.h"
#include <memory.h>
#include "alphasparse/opt.h"
#ifdef _OPENMP
#include <omp.h>
#endif
alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_BSR *mat, const ALPHA_Number *x, const ALPHA_INT columns, const ALPHA_INT ldx, const ALPHA_Number beta, ALPHA_Number *y, const ALPHA_INT ldy)
{
ALPHA_INT block_rowA = mat->rows;
ALPHA_INT rowA = mat->rows * mat->block_size;
ALPHA_Number diag[rowA];
memset(diag, '\0', sizeof(ALPHA_Number) * rowA);
ALPHA_INT bs = mat->block_size;
ALPHA_INT num_threads = alpha_get_thread_num();
#ifdef _OPENMP
#pragma omp parallel for num_threads(num_threads)
#endif
for (ALPHA_INT ar = 0; ar < block_rowA; ++ar)
{
for (ALPHA_INT ai = mat->rows_start[ar]; ai < mat->rows_end[ar]; ++ai)
{
if (mat->col_indx[ai] == ar)
{
for(ALPHA_INT block_i = 0; block_i < bs; block_i++)
{
diag[ar*bs+block_i] = mat->values[ai*bs*bs + block_i*bs + block_i];
}
}
}
}
#ifdef _OPENMP
#pragma omp parallel for num_threads(num_threads)
#endif
for (ALPHA_INT cc = 0; cc < columns; ++cc)
for (ALPHA_INT cr = 0; cr < rowA; ++cr)
{
ALPHA_Number t1, t2;
alpha_mul(t1, beta, y[index2(cc, cr, ldy)]);
alpha_mul(t2, alpha, diag[cr]);
alpha_mul(t2, t2, x[index2(cc, cr, ldx)]);
alpha_add(y[index2(cc, cr, ldy)], t1, t2);
}
return ALPHA_SPARSE_STATUS_SUCCESS;
}
|
gimplify.c
|
/* Tree lowering pass. This pass converts the GENERIC functions-as-trees
tree representation into the GIMPLE form.
Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
Free Software Foundation, Inc.
Major work done by Sebastian Pop <[email protected]>,
Diego Novillo <[email protected]> and Jason Merrill <[email protected]>.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 3, or (at your option) any later
version.
GCC 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 GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "tm.h"
#include "tree.h"
#include "rtl.h"
#include "varray.h"
#include "gimple.h"
#include "tree-iterator.h"
#include "tree-inline.h"
#include "diagnostic.h"
#include "langhooks.h"
#include "langhooks-def.h"
#include "tree-flow.h"
#include "cgraph.h"
#include "timevar.h"
#include "except.h"
#include "hashtab.h"
#include "flags.h"
#include "real.h"
#include "function.h"
#include "output.h"
#include "expr.h"
#include "ggc.h"
#include "toplev.h"
#include "target.h"
#include "optabs.h"
#include "pointer-set.h"
#include "splay-tree.h"
#include "vec.h"
#include "gimple.h"
enum gimplify_omp_var_data
{
GOVD_SEEN = 1,
GOVD_EXPLICIT = 2,
GOVD_SHARED = 4,
GOVD_PRIVATE = 8,
GOVD_FIRSTPRIVATE = 16,
GOVD_LASTPRIVATE = 32,
GOVD_REDUCTION = 64,
GOVD_LOCAL = 128,
GOVD_DEBUG_PRIVATE = 256,
GOVD_PRIVATE_OUTER_REF = 512,
GOVD_DATA_SHARE_CLASS = (GOVD_SHARED | GOVD_PRIVATE | GOVD_FIRSTPRIVATE
| GOVD_LASTPRIVATE | GOVD_REDUCTION | GOVD_LOCAL)
};
enum omp_region_type
{
ORT_WORKSHARE = 0,
ORT_PARALLEL = 2,
ORT_COMBINED_PARALLEL = 3,
ORT_TASK = 4,
ORT_UNTIED_TASK = 5
};
struct gimplify_omp_ctx
{
struct gimplify_omp_ctx *outer_context;
splay_tree variables;
struct pointer_set_t *privatized_types;
location_t location;
enum omp_clause_default_kind default_kind;
enum omp_region_type region_type;
};
static struct gimplify_ctx *gimplify_ctxp;
static struct gimplify_omp_ctx *gimplify_omp_ctxp;
/* Formal (expression) temporary table handling: Multiple occurrences of
the same scalar expression are evaluated into the same temporary. */
typedef struct gimple_temp_hash_elt
{
tree val; /* Key */
tree temp; /* Value */
} elt_t;
/* Forward declarations. */
static enum gimplify_status gimplify_compound_expr (tree *, gimple_seq *, bool);
/* Mark X addressable. Unlike the langhook we expect X to be in gimple
form and we don't do any syntax checking. */
static void
mark_addressable (tree x)
{
while (handled_component_p (x))
x = TREE_OPERAND (x, 0);
if (TREE_CODE (x) != VAR_DECL && TREE_CODE (x) != PARM_DECL)
return ;
TREE_ADDRESSABLE (x) = 1;
}
/* Return a hash value for a formal temporary table entry. */
static hashval_t
gimple_tree_hash (const void *p)
{
tree t = ((const elt_t *) p)->val;
return iterative_hash_expr (t, 0);
}
/* Compare two formal temporary table entries. */
static int
gimple_tree_eq (const void *p1, const void *p2)
{
tree t1 = ((const elt_t *) p1)->val;
tree t2 = ((const elt_t *) p2)->val;
enum tree_code code = TREE_CODE (t1);
if (TREE_CODE (t2) != code
|| TREE_TYPE (t1) != TREE_TYPE (t2))
return 0;
if (!operand_equal_p (t1, t2, 0))
return 0;
/* Only allow them to compare equal if they also hash equal; otherwise
results are nondeterminate, and we fail bootstrap comparison. */
gcc_assert (gimple_tree_hash (p1) == gimple_tree_hash (p2));
return 1;
}
/* Link gimple statement GS to the end of the sequence *SEQ_P. If
*SEQ_P is NULL, a new sequence is allocated. This function is
similar to gimple_seq_add_stmt, but does not scan the operands.
During gimplification, we need to manipulate statement sequences
before the def/use vectors have been constructed. */
static void
gimplify_seq_add_stmt (gimple_seq *seq_p, gimple gs)
{
gimple_stmt_iterator si;
if (gs == NULL)
return;
if (*seq_p == NULL)
*seq_p = gimple_seq_alloc ();
si = gsi_last (*seq_p);
gsi_insert_after_without_update (&si, gs, GSI_NEW_STMT);
}
/* Append sequence SRC to the end of sequence *DST_P. If *DST_P is
NULL, a new sequence is allocated. This function is
similar to gimple_seq_add_seq, but does not scan the operands.
During gimplification, we need to manipulate statement sequences
before the def/use vectors have been constructed. */
static void
gimplify_seq_add_seq (gimple_seq *dst_p, gimple_seq src)
{
gimple_stmt_iterator si;
if (src == NULL)
return;
if (*dst_p == NULL)
*dst_p = gimple_seq_alloc ();
si = gsi_last (*dst_p);
gsi_insert_seq_after_without_update (&si, src, GSI_NEW_STMT);
}
/* Set up a context for the gimplifier. */
void
push_gimplify_context (struct gimplify_ctx *c)
{
memset (c, '\0', sizeof (*c));
c->prev_context = gimplify_ctxp;
gimplify_ctxp = c;
}
/* Tear down a context for the gimplifier. If BODY is non-null, then
put the temporaries into the outer BIND_EXPR. Otherwise, put them
in the local_decls.
BODY is not a sequence, but the first tuple in a sequence. */
void
pop_gimplify_context (gimple body)
{
struct gimplify_ctx *c = gimplify_ctxp;
tree t;
gcc_assert (c && (c->bind_expr_stack == NULL
|| VEC_empty (gimple, c->bind_expr_stack)));
VEC_free (gimple, heap, c->bind_expr_stack);
gimplify_ctxp = c->prev_context;
for (t = c->temps; t ; t = TREE_CHAIN (t))
DECL_GIMPLE_FORMAL_TEMP_P (t) = 0;
if (body)
declare_vars (c->temps, body, false);
else
record_vars (c->temps);
if (c->temp_htab)
htab_delete (c->temp_htab);
}
static void
gimple_push_bind_expr (gimple gimple_bind)
{
if (gimplify_ctxp->bind_expr_stack == NULL)
gimplify_ctxp->bind_expr_stack = VEC_alloc (gimple, heap, 8);
VEC_safe_push (gimple, heap, gimplify_ctxp->bind_expr_stack, gimple_bind);
}
static void
gimple_pop_bind_expr (void)
{
VEC_pop (gimple, gimplify_ctxp->bind_expr_stack);
}
gimple
gimple_current_bind_expr (void)
{
return VEC_last (gimple, gimplify_ctxp->bind_expr_stack);
}
/* Return the stack GIMPLE_BINDs created during gimplification. */
VEC(gimple, heap) *
gimple_bind_expr_stack (void)
{
return gimplify_ctxp->bind_expr_stack;
}
/* Returns true iff there is a COND_EXPR between us and the innermost
CLEANUP_POINT_EXPR. This info is used by gimple_push_cleanup. */
static bool
gimple_conditional_context (void)
{
return gimplify_ctxp->conditions > 0;
}
/* Note that we've entered a COND_EXPR. */
static void
gimple_push_condition (void)
{
#ifdef ENABLE_GIMPLE_CHECKING
if (gimplify_ctxp->conditions == 0)
gcc_assert (gimple_seq_empty_p (gimplify_ctxp->conditional_cleanups));
#endif
++(gimplify_ctxp->conditions);
}
/* Note that we've left a COND_EXPR. If we're back at unconditional scope
now, add any conditional cleanups we've seen to the prequeue. */
static void
gimple_pop_condition (gimple_seq *pre_p)
{
int conds = --(gimplify_ctxp->conditions);
gcc_assert (conds >= 0);
if (conds == 0)
{
gimplify_seq_add_seq (pre_p, gimplify_ctxp->conditional_cleanups);
gimplify_ctxp->conditional_cleanups = NULL;
}
}
/* A stable comparison routine for use with splay trees and DECLs. */
static int
splay_tree_compare_decl_uid (splay_tree_key xa, splay_tree_key xb)
{
tree a = (tree) xa;
tree b = (tree) xb;
return DECL_UID (a) - DECL_UID (b);
}
/* Create a new omp construct that deals with variable remapping. */
static struct gimplify_omp_ctx *
new_omp_context (enum omp_region_type region_type)
{
struct gimplify_omp_ctx *c;
c = XCNEW (struct gimplify_omp_ctx);
c->outer_context = gimplify_omp_ctxp;
c->variables = splay_tree_new (splay_tree_compare_decl_uid, 0, 0);
c->privatized_types = pointer_set_create ();
c->location = input_location;
c->region_type = region_type;
if ((region_type & ORT_TASK) == 0)
c->default_kind = OMP_CLAUSE_DEFAULT_SHARED;
else
c->default_kind = OMP_CLAUSE_DEFAULT_UNSPECIFIED;
return c;
}
/* Destroy an omp construct that deals with variable remapping. */
static void
delete_omp_context (struct gimplify_omp_ctx *c)
{
splay_tree_delete (c->variables);
pointer_set_destroy (c->privatized_types);
XDELETE (c);
}
static void omp_add_variable (struct gimplify_omp_ctx *, tree, unsigned int);
static bool omp_notice_variable (struct gimplify_omp_ctx *, tree, bool);
/* A subroutine of append_to_statement_list{,_force}. T is not NULL. */
static void
append_to_statement_list_1 (tree t, tree *list_p)
{
tree list = *list_p;
tree_stmt_iterator i;
if (!list)
{
if (t && TREE_CODE (t) == STATEMENT_LIST)
{
*list_p = t;
return;
}
*list_p = list = alloc_stmt_list ();
}
i = tsi_last (list);
tsi_link_after (&i, t, TSI_CONTINUE_LINKING);
}
/* Add T to the end of the list container pointed to by LIST_P.
If T is an expression with no effects, it is ignored. */
void
append_to_statement_list (tree t, tree *list_p)
{
if (t && TREE_SIDE_EFFECTS (t))
append_to_statement_list_1 (t, list_p);
}
/* Similar, but the statement is always added, regardless of side effects. */
void
append_to_statement_list_force (tree t, tree *list_p)
{
if (t != NULL_TREE)
append_to_statement_list_1 (t, list_p);
}
/* Both gimplify the statement T and append it to *SEQ_P. This function
behaves exactly as gimplify_stmt, but you don't have to pass T as a
reference. */
void
gimplify_and_add (tree t, gimple_seq *seq_p)
{
gimplify_stmt (&t, seq_p);
}
/* Gimplify statement T into sequence *SEQ_P, and return the first
tuple in the sequence of generated tuples for this statement.
Return NULL if gimplifying T produced no tuples. */
static gimple
gimplify_and_return_first (tree t, gimple_seq *seq_p)
{
gimple_stmt_iterator last = gsi_last (*seq_p);
gimplify_and_add (t, seq_p);
if (!gsi_end_p (last))
{
gsi_next (&last);
return gsi_stmt (last);
}
else
return gimple_seq_first_stmt (*seq_p);
}
/* Strip off a legitimate source ending from the input string NAME of
length LEN. Rather than having to know the names used by all of
our front ends, we strip off an ending of a period followed by
up to five characters. (Java uses ".class".) */
static inline void
remove_suffix (char *name, int len)
{
int i;
for (i = 2; i < 8 && len > i; i++)
{
if (name[len - i] == '.')
{
name[len - i] = '\0';
break;
}
}
}
/* Subroutine for find_single_pointer_decl. */
static tree
find_single_pointer_decl_1 (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
void *data)
{
tree *pdecl = (tree *) data;
/* We are only looking for pointers at the same level as the
original tree; we must not look through any indirections.
Returning anything other than NULL_TREE will cause the caller to
not find a base. */
if (REFERENCE_CLASS_P (*tp))
return *tp;
if (DECL_P (*tp) && POINTER_TYPE_P (TREE_TYPE (*tp)))
{
if (*pdecl)
{
/* We already found a pointer decl; return anything other
than NULL_TREE to unwind from walk_tree signalling that
we have a duplicate. */
return *tp;
}
*pdecl = *tp;
}
return NULL_TREE;
}
/* Find the single DECL of pointer type in the tree T, used directly
rather than via an indirection, and return it. If there are zero
or more than one such DECLs, return NULL. */
static tree
find_single_pointer_decl (tree t)
{
tree decl = NULL_TREE;
if (walk_tree (&t, find_single_pointer_decl_1, &decl, NULL))
{
/* find_single_pointer_decl_1 returns a nonzero value, causing
walk_tree to return a nonzero value, to indicate that it
found more than one pointer DECL or that it found an
indirection. */
return NULL_TREE;
}
return decl;
}
/* Create a new temporary name with PREFIX. Returns an identifier. */
static GTY(()) unsigned int tmp_var_id_num;
tree
create_tmp_var_name (const char *prefix)
{
char *tmp_name;
if (prefix)
{
char *preftmp = ASTRDUP (prefix);
remove_suffix (preftmp, strlen (preftmp));
prefix = preftmp;
}
ASM_FORMAT_PRIVATE_NAME (tmp_name, prefix ? prefix : "T", tmp_var_id_num++);
return get_identifier (tmp_name);
}
/* Create a new temporary variable declaration of type TYPE.
Does NOT push it into the current binding. */
tree
create_tmp_var_raw (tree type, const char *prefix)
{
tree tmp_var;
tree new_type;
/* Make the type of the variable writable. */
new_type = build_type_variant (type, 0, 0);
TYPE_ATTRIBUTES (new_type) = TYPE_ATTRIBUTES (type);
tmp_var = build_decl (VAR_DECL, prefix ? create_tmp_var_name (prefix) : NULL,
type);
/* The variable was declared by the compiler. */
DECL_ARTIFICIAL (tmp_var) = 1;
/* And we don't want debug info for it. */
DECL_IGNORED_P (tmp_var) = 1;
/* Make the variable writable. */
TREE_READONLY (tmp_var) = 0;
DECL_EXTERNAL (tmp_var) = 0;
TREE_STATIC (tmp_var) = 0;
TREE_USED (tmp_var) = 1;
return tmp_var;
}
/* Create a new temporary variable declaration of type TYPE. DOES push the
variable into the current binding. Further, assume that this is called
only from gimplification or optimization, at which point the creation of
certain types are bugs. */
tree
create_tmp_var (tree type, const char *prefix)
{
tree tmp_var;
/* We don't allow types that are addressable (meaning we can't make copies),
or incomplete. We also used to reject every variable size objects here,
but now support those for which a constant upper bound can be obtained.
The processing for variable sizes is performed in gimple_add_tmp_var,
point at which it really matters and possibly reached via paths not going
through this function, e.g. after direct calls to create_tmp_var_raw. */
gcc_assert (!TREE_ADDRESSABLE (type) && COMPLETE_TYPE_P (type));
tmp_var = create_tmp_var_raw (type, prefix);
gimple_add_tmp_var (tmp_var);
return tmp_var;
}
/* Create a temporary with a name derived from VAL. Subroutine of
lookup_tmp_var; nobody else should call this function. */
static inline tree
create_tmp_from_val (tree val)
{
return create_tmp_var (TREE_TYPE (val), get_name (val));
}
/* Create a temporary to hold the value of VAL. If IS_FORMAL, try to reuse
an existing expression temporary. */
static tree
lookup_tmp_var (tree val, bool is_formal)
{
tree ret;
/* If not optimizing, never really reuse a temporary. local-alloc
won't allocate any variable that is used in more than one basic
block, which means it will go into memory, causing much extra
work in reload and final and poorer code generation, outweighing
the extra memory allocation here. */
if (!optimize || !is_formal || TREE_SIDE_EFFECTS (val))
ret = create_tmp_from_val (val);
else
{
elt_t elt, *elt_p;
void **slot;
elt.val = val;
if (gimplify_ctxp->temp_htab == NULL)
gimplify_ctxp->temp_htab
= htab_create (1000, gimple_tree_hash, gimple_tree_eq, free);
slot = htab_find_slot (gimplify_ctxp->temp_htab, (void *)&elt, INSERT);
if (*slot == NULL)
{
elt_p = XNEW (elt_t);
elt_p->val = val;
elt_p->temp = ret = create_tmp_from_val (val);
*slot = (void *) elt_p;
}
else
{
elt_p = (elt_t *) *slot;
ret = elt_p->temp;
}
}
if (is_formal)
DECL_GIMPLE_FORMAL_TEMP_P (ret) = 1;
return ret;
}
/* Return true if T is a CALL_EXPR or an expression that can be
assignmed to a temporary. Note that this predicate should only be
used during gimplification. See the rationale for this in
gimplify_modify_expr. */
static bool
is_gimple_formal_tmp_or_call_rhs (tree t)
{
return TREE_CODE (t) == CALL_EXPR || is_gimple_formal_tmp_rhs (t);
}
/* Returns true iff T is a valid RHS for an assignment to a renamed
user -- or front-end generated artificial -- variable. */
static bool
is_gimple_reg_or_call_rhs (tree t)
{
/* If the RHS of the MODIFY_EXPR may throw or make a nonlocal goto
and the LHS is a user variable, then we need to introduce a formal
temporary. This way the optimizers can determine that the user
variable is only modified if evaluation of the RHS does not throw.
Don't force a temp of a non-renamable type; the copy could be
arbitrarily expensive. Instead we will generate a VDEF for
the assignment. */
if (is_gimple_reg_type (TREE_TYPE (t))
&& ((TREE_CODE (t) == CALL_EXPR && TREE_SIDE_EFFECTS (t))
|| tree_could_throw_p (t)))
return false;
return is_gimple_formal_tmp_or_call_rhs (t);
}
/* Return true if T is a valid memory RHS or a CALL_EXPR. Note that
this predicate should only be used during gimplification. See the
rationale for this in gimplify_modify_expr. */
static bool
is_gimple_mem_or_call_rhs (tree t)
{
/* If we're dealing with a renamable type, either source or dest must be
a renamed variable. */
if (is_gimple_reg_type (TREE_TYPE (t)))
return is_gimple_val (t);
else
return is_gimple_formal_tmp_or_call_rhs (t);
}
/* Returns a formal temporary variable initialized with VAL. PRE_P is as
in gimplify_expr. Only use this function if:
1) The value of the unfactored expression represented by VAL will not
change between the initialization and use of the temporary, and
2) The temporary will not be otherwise modified.
For instance, #1 means that this is inappropriate for SAVE_EXPR temps,
and #2 means it is inappropriate for && temps.
For other cases, use get_initialized_tmp_var instead. */
static tree
internal_get_tmp_var (tree val, gimple_seq *pre_p, gimple_seq *post_p,
bool is_formal)
{
tree t, mod;
/* Notice that we explicitly allow VAL to be a CALL_EXPR so that we
can create an INIT_EXPR and convert it into a GIMPLE_CALL below. */
gimplify_expr (&val, pre_p, post_p, is_gimple_formal_tmp_or_call_rhs,
fb_rvalue);
t = lookup_tmp_var (val, is_formal);
if (is_formal)
{
tree u = find_single_pointer_decl (val);
if (u && TREE_CODE (u) == VAR_DECL && DECL_BASED_ON_RESTRICT_P (u))
u = DECL_GET_RESTRICT_BASE (u);
if (u && TYPE_RESTRICT (TREE_TYPE (u)))
{
if (DECL_BASED_ON_RESTRICT_P (t))
gcc_assert (u == DECL_GET_RESTRICT_BASE (t));
else
{
DECL_BASED_ON_RESTRICT_P (t) = 1;
SET_DECL_RESTRICT_BASE (t, u);
}
}
}
if (TREE_CODE (TREE_TYPE (t)) == COMPLEX_TYPE
|| TREE_CODE (TREE_TYPE (t)) == VECTOR_TYPE)
DECL_GIMPLE_REG_P (t) = 1;
mod = build2 (INIT_EXPR, TREE_TYPE (t), t, unshare_expr (val));
if (EXPR_HAS_LOCATION (val))
SET_EXPR_LOCUS (mod, EXPR_LOCUS (val));
else
SET_EXPR_LOCATION (mod, input_location);
/* gimplify_modify_expr might want to reduce this further. */
gimplify_and_add (mod, pre_p);
ggc_free (mod);
/* If we're gimplifying into ssa, gimplify_modify_expr will have
given our temporary an SSA name. Find and return it. */
if (gimplify_ctxp->into_ssa)
{
gimple last = gimple_seq_last_stmt (*pre_p);
t = gimple_get_lhs (last);
}
return t;
}
/* Returns a formal temporary variable initialized with VAL. PRE_P
points to a sequence where side-effects needed to compute VAL should be
stored. */
tree
get_formal_tmp_var (tree val, gimple_seq *pre_p)
{
return internal_get_tmp_var (val, pre_p, NULL, true);
}
/* Returns a temporary variable initialized with VAL. PRE_P and POST_P
are as in gimplify_expr. */
tree
get_initialized_tmp_var (tree val, gimple_seq *pre_p, gimple_seq *post_p)
{
return internal_get_tmp_var (val, pre_p, post_p, false);
}
/* Declares all the variables in VARS in SCOPE. If DEBUG_INFO is
true, generate debug info for them; otherwise don't. */
void
declare_vars (tree vars, gimple scope, bool debug_info)
{
tree last = vars;
if (last)
{
tree temps, block;
gcc_assert (gimple_code (scope) == GIMPLE_BIND);
temps = nreverse (last);
block = gimple_bind_block (scope);
gcc_assert (!block || TREE_CODE (block) == BLOCK);
if (!block || !debug_info)
{
TREE_CHAIN (last) = gimple_bind_vars (scope);
gimple_bind_set_vars (scope, temps);
}
else
{
/* We need to attach the nodes both to the BIND_EXPR and to its
associated BLOCK for debugging purposes. The key point here
is that the BLOCK_VARS of the BIND_EXPR_BLOCK of a BIND_EXPR
is a subchain of the BIND_EXPR_VARS of the BIND_EXPR. */
if (BLOCK_VARS (block))
BLOCK_VARS (block) = chainon (BLOCK_VARS (block), temps);
else
{
gimple_bind_set_vars (scope,
chainon (gimple_bind_vars (scope), temps));
BLOCK_VARS (block) = temps;
}
}
}
}
/* For VAR a VAR_DECL of variable size, try to find a constant upper bound
for the size and adjust DECL_SIZE/DECL_SIZE_UNIT accordingly. Abort if
no such upper bound can be obtained. */
static void
force_constant_size (tree var)
{
/* The only attempt we make is by querying the maximum size of objects
of the variable's type. */
HOST_WIDE_INT max_size;
gcc_assert (TREE_CODE (var) == VAR_DECL);
max_size = max_int_size_in_bytes (TREE_TYPE (var));
gcc_assert (max_size >= 0);
DECL_SIZE_UNIT (var)
= build_int_cst (TREE_TYPE (DECL_SIZE_UNIT (var)), max_size);
DECL_SIZE (var)
= build_int_cst (TREE_TYPE (DECL_SIZE (var)), max_size * BITS_PER_UNIT);
}
void
gimple_add_tmp_var (tree tmp)
{
gcc_assert (!TREE_CHAIN (tmp) && !DECL_SEEN_IN_BIND_EXPR_P (tmp));
/* Later processing assumes that the object size is constant, which might
not be true at this point. Force the use of a constant upper bound in
this case. */
if (!host_integerp (DECL_SIZE_UNIT (tmp), 1))
force_constant_size (tmp);
DECL_CONTEXT (tmp) = current_function_decl;
DECL_SEEN_IN_BIND_EXPR_P (tmp) = 1;
if (gimplify_ctxp)
{
TREE_CHAIN (tmp) = gimplify_ctxp->temps;
gimplify_ctxp->temps = tmp;
/* Mark temporaries local within the nearest enclosing parallel. */
if (gimplify_omp_ctxp)
{
struct gimplify_omp_ctx *ctx = gimplify_omp_ctxp;
while (ctx && ctx->region_type == ORT_WORKSHARE)
ctx = ctx->outer_context;
if (ctx)
omp_add_variable (ctx, tmp, GOVD_LOCAL | GOVD_SEEN);
}
}
else if (cfun)
record_vars (tmp);
else
{
gimple_seq body_seq;
/* This case is for nested functions. We need to expose the locals
they create. */
body_seq = gimple_body (current_function_decl);
declare_vars (tmp, gimple_seq_first_stmt (body_seq), false);
}
}
/* Determines whether to assign a location to the statement GS. */
static bool
should_carry_location_p (gimple gs)
{
/* Don't emit a line note for a label. We particularly don't want to
emit one for the break label, since it doesn't actually correspond
to the beginning of the loop/switch. */
if (gimple_code (gs) == GIMPLE_LABEL)
return false;
return true;
}
/* Same, but for a tree. */
static bool
tree_should_carry_location_p (const_tree stmt)
{
/* Don't emit a line note for a label. We particularly don't want to
emit one for the break label, since it doesn't actually correspond
to the beginning of the loop/switch. */
if (TREE_CODE (stmt) == LABEL_EXPR)
return false;
/* Do not annotate empty statements, since it confuses gcov. */
if (!TREE_SIDE_EFFECTS (stmt))
return false;
return true;
}
/* Return true if a location should not be emitted for this statement
by annotate_one_with_location. */
static inline bool
gimple_do_not_emit_location_p (gimple g)
{
return gimple_plf (g, GF_PLF_1);
}
/* Mark statement G so a location will not be emitted by
annotate_one_with_location. */
static inline void
gimple_set_do_not_emit_location (gimple g)
{
/* The PLF flags are initialized to 0 when a new tuple is created,
so no need to initialize it anywhere. */
gimple_set_plf (g, GF_PLF_1, true);
}
/* Set the location for gimple statement GS to LOCUS. */
static void
annotate_one_with_location (gimple gs, location_t location)
{
if (!gimple_has_location (gs)
&& !gimple_do_not_emit_location_p (gs)
&& should_carry_location_p (gs))
gimple_set_location (gs, location);
}
/* Same, but for tree T. */
static void
tree_annotate_one_with_location (tree t, location_t location)
{
if (CAN_HAVE_LOCATION_P (t)
&& ! EXPR_HAS_LOCATION (t) && tree_should_carry_location_p (t))
SET_EXPR_LOCATION (t, location);
}
/* Set LOCATION for all the statements after iterator GSI in sequence
SEQ. If GSI is pointing to the end of the sequence, start with the
first statement in SEQ. */
static void
annotate_all_with_location_after (gimple_seq seq, gimple_stmt_iterator gsi,
location_t location)
{
if (gsi_end_p (gsi))
gsi = gsi_start (seq);
else
gsi_next (&gsi);
for (; !gsi_end_p (gsi); gsi_next (&gsi))
annotate_one_with_location (gsi_stmt (gsi), location);
}
/* Set the location for all the statements in a sequence STMT_P to LOCUS. */
void
annotate_all_with_location (gimple_seq stmt_p, location_t location)
{
gimple_stmt_iterator i;
if (gimple_seq_empty_p (stmt_p))
return;
for (i = gsi_start (stmt_p); !gsi_end_p (i); gsi_next (&i))
{
gimple gs = gsi_stmt (i);
annotate_one_with_location (gs, location);
}
}
/* Same, but for statement or statement list in *STMT_P. */
void
tree_annotate_all_with_location (tree *stmt_p, location_t location)
{
tree_stmt_iterator i;
if (!*stmt_p)
return;
for (i = tsi_start (*stmt_p); !tsi_end_p (i); tsi_next (&i))
{
tree t = tsi_stmt (i);
/* Assuming we've already been gimplified, we shouldn't
see nested chaining constructs anymore. */
gcc_assert (TREE_CODE (t) != STATEMENT_LIST
&& TREE_CODE (t) != COMPOUND_EXPR);
tree_annotate_one_with_location (t, location);
}
}
/* Similar to copy_tree_r() but do not copy SAVE_EXPR or TARGET_EXPR nodes.
These nodes model computations that should only be done once. If we
were to unshare something like SAVE_EXPR(i++), the gimplification
process would create wrong code. */
static tree
mostly_copy_tree_r (tree *tp, int *walk_subtrees, void *data)
{
enum tree_code code = TREE_CODE (*tp);
/* Don't unshare types, decls, constants and SAVE_EXPR nodes. */
if (TREE_CODE_CLASS (code) == tcc_type
|| TREE_CODE_CLASS (code) == tcc_declaration
|| TREE_CODE_CLASS (code) == tcc_constant
|| code == SAVE_EXPR || code == TARGET_EXPR
/* We can't do anything sensible with a BLOCK used as an expression,
but we also can't just die when we see it because of non-expression
uses. So just avert our eyes and cross our fingers. Silly Java. */
|| code == BLOCK)
*walk_subtrees = 0;
else
{
gcc_assert (code != BIND_EXPR);
copy_tree_r (tp, walk_subtrees, data);
}
return NULL_TREE;
}
/* Callback for walk_tree to unshare most of the shared trees rooted at
*TP. If *TP has been visited already (i.e., TREE_VISITED (*TP) == 1),
then *TP is deep copied by calling copy_tree_r.
This unshares the same trees as copy_tree_r with the exception of
SAVE_EXPR nodes. These nodes model computations that should only be
done once. If we were to unshare something like SAVE_EXPR(i++), the
gimplification process would create wrong code. */
static tree
copy_if_shared_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
void *data ATTRIBUTE_UNUSED)
{
tree t = *tp;
enum tree_code code = TREE_CODE (t);
/* Skip types, decls, and constants. But we do want to look at their
types and the bounds of types. Mark them as visited so we properly
unmark their subtrees on the unmark pass. If we've already seen them,
don't look down further. */
if (TREE_CODE_CLASS (code) == tcc_type
|| TREE_CODE_CLASS (code) == tcc_declaration
|| TREE_CODE_CLASS (code) == tcc_constant)
{
if (TREE_VISITED (t))
*walk_subtrees = 0;
else
TREE_VISITED (t) = 1;
}
/* If this node has been visited already, unshare it and don't look
any deeper. */
else if (TREE_VISITED (t))
{
walk_tree (tp, mostly_copy_tree_r, NULL, NULL);
*walk_subtrees = 0;
}
/* Otherwise, mark the tree as visited and keep looking. */
else
TREE_VISITED (t) = 1;
return NULL_TREE;
}
static tree
unmark_visited_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
void *data ATTRIBUTE_UNUSED)
{
if (TREE_VISITED (*tp))
TREE_VISITED (*tp) = 0;
else
*walk_subtrees = 0;
return NULL_TREE;
}
/* Unshare all the trees in BODY_P, a pointer into the body of FNDECL, and the
bodies of any nested functions if we are unsharing the entire body of
FNDECL. */
static void
unshare_body (tree *body_p, tree fndecl)
{
struct cgraph_node *cgn = cgraph_node (fndecl);
walk_tree (body_p, copy_if_shared_r, NULL, NULL);
if (body_p == &DECL_SAVED_TREE (fndecl))
for (cgn = cgn->nested; cgn; cgn = cgn->next_nested)
unshare_body (&DECL_SAVED_TREE (cgn->decl), cgn->decl);
}
/* Likewise, but mark all trees as not visited. */
static void
unvisit_body (tree *body_p, tree fndecl)
{
struct cgraph_node *cgn = cgraph_node (fndecl);
walk_tree (body_p, unmark_visited_r, NULL, NULL);
if (body_p == &DECL_SAVED_TREE (fndecl))
for (cgn = cgn->nested; cgn; cgn = cgn->next_nested)
unvisit_body (&DECL_SAVED_TREE (cgn->decl), cgn->decl);
}
/* Unconditionally make an unshared copy of EXPR. This is used when using
stored expressions which span multiple functions, such as BINFO_VTABLE,
as the normal unsharing process can't tell that they're shared. */
tree
unshare_expr (tree expr)
{
walk_tree (&expr, mostly_copy_tree_r, NULL, NULL);
return expr;
}
/* WRAPPER is a code such as BIND_EXPR or CLEANUP_POINT_EXPR which can both
contain statements and have a value. Assign its value to a temporary
and give it void_type_node. Returns the temporary, or NULL_TREE if
WRAPPER was already void. */
tree
voidify_wrapper_expr (tree wrapper, tree temp)
{
tree type = TREE_TYPE (wrapper);
if (type && !VOID_TYPE_P (type))
{
tree *p;
/* Set p to point to the body of the wrapper. Loop until we find
something that isn't a wrapper. */
for (p = &wrapper; p && *p; )
{
switch (TREE_CODE (*p))
{
case BIND_EXPR:
TREE_SIDE_EFFECTS (*p) = 1;
TREE_TYPE (*p) = void_type_node;
/* For a BIND_EXPR, the body is operand 1. */
p = &BIND_EXPR_BODY (*p);
break;
case CLEANUP_POINT_EXPR:
case TRY_FINALLY_EXPR:
case TRY_CATCH_EXPR:
TREE_SIDE_EFFECTS (*p) = 1;
TREE_TYPE (*p) = void_type_node;
p = &TREE_OPERAND (*p, 0);
break;
case STATEMENT_LIST:
{
tree_stmt_iterator i = tsi_last (*p);
TREE_SIDE_EFFECTS (*p) = 1;
TREE_TYPE (*p) = void_type_node;
p = tsi_end_p (i) ? NULL : tsi_stmt_ptr (i);
}
break;
case COMPOUND_EXPR:
/* Advance to the last statement. Set all container types to void. */
for (; TREE_CODE (*p) == COMPOUND_EXPR; p = &TREE_OPERAND (*p, 1))
{
TREE_SIDE_EFFECTS (*p) = 1;
TREE_TYPE (*p) = void_type_node;
}
break;
default:
goto out;
}
}
out:
if (p == NULL || IS_EMPTY_STMT (*p))
temp = NULL_TREE;
else if (temp)
{
/* The wrapper is on the RHS of an assignment that we're pushing
down. */
gcc_assert (TREE_CODE (temp) == INIT_EXPR
|| TREE_CODE (temp) == MODIFY_EXPR);
TREE_OPERAND (temp, 1) = *p;
*p = temp;
}
else
{
temp = create_tmp_var (type, "retval");
*p = build2 (INIT_EXPR, type, temp, *p);
}
return temp;
}
return NULL_TREE;
}
/* Prepare calls to builtins to SAVE and RESTORE the stack as well as
a temporary through which they communicate. */
static void
build_stack_save_restore (gimple *save, gimple *restore)
{
tree tmp_var;
*save = gimple_build_call (implicit_built_in_decls[BUILT_IN_STACK_SAVE], 0);
tmp_var = create_tmp_var (ptr_type_node, "saved_stack");
gimple_call_set_lhs (*save, tmp_var);
*restore = gimple_build_call (implicit_built_in_decls[BUILT_IN_STACK_RESTORE],
1, tmp_var);
}
/* Gimplify a BIND_EXPR. Just voidify and recurse. */
static enum gimplify_status
gimplify_bind_expr (tree *expr_p, gimple_seq *pre_p)
{
tree bind_expr = *expr_p;
bool old_save_stack = gimplify_ctxp->save_stack;
tree t;
gimple gimple_bind;
gimple_seq body;
tree temp = voidify_wrapper_expr (bind_expr, NULL);
/* Mark variables seen in this bind expr. */
for (t = BIND_EXPR_VARS (bind_expr); t ; t = TREE_CHAIN (t))
{
if (TREE_CODE (t) == VAR_DECL)
{
struct gimplify_omp_ctx *ctx = gimplify_omp_ctxp;
/* Mark variable as local. */
if (ctx && !is_global_var (t)
&& (! DECL_SEEN_IN_BIND_EXPR_P (t)
|| splay_tree_lookup (ctx->variables,
(splay_tree_key) t) == NULL))
omp_add_variable (gimplify_omp_ctxp, t, GOVD_LOCAL | GOVD_SEEN);
DECL_SEEN_IN_BIND_EXPR_P (t) = 1;
if (DECL_HARD_REGISTER (t) && !is_global_var (t) && cfun)
cfun->has_local_explicit_reg_vars = true;
}
/* Preliminarily mark non-addressed complex variables as eligible
for promotion to gimple registers. We'll transform their uses
as we find them. */
if ((TREE_CODE (TREE_TYPE (t)) == COMPLEX_TYPE
|| TREE_CODE (TREE_TYPE (t)) == VECTOR_TYPE)
&& !TREE_THIS_VOLATILE (t)
&& (TREE_CODE (t) == VAR_DECL && !DECL_HARD_REGISTER (t))
&& !needs_to_live_in_memory (t))
DECL_GIMPLE_REG_P (t) = 1;
}
gimple_bind = gimple_build_bind (BIND_EXPR_VARS (bind_expr), NULL,
BIND_EXPR_BLOCK (bind_expr));
gimple_push_bind_expr (gimple_bind);
gimplify_ctxp->save_stack = false;
/* Gimplify the body into the GIMPLE_BIND tuple's body. */
body = NULL;
gimplify_stmt (&BIND_EXPR_BODY (bind_expr), &body);
gimple_bind_set_body (gimple_bind, body);
if (gimplify_ctxp->save_stack)
{
gimple stack_save, stack_restore, gs;
gimple_seq cleanup, new_body;
/* Save stack on entry and restore it on exit. Add a try_finally
block to achieve this. Note that mudflap depends on the
format of the emitted code: see mx_register_decls(). */
build_stack_save_restore (&stack_save, &stack_restore);
cleanup = new_body = NULL;
gimplify_seq_add_stmt (&cleanup, stack_restore);
gs = gimple_build_try (gimple_bind_body (gimple_bind), cleanup,
GIMPLE_TRY_FINALLY);
gimplify_seq_add_stmt (&new_body, stack_save);
gimplify_seq_add_stmt (&new_body, gs);
gimple_bind_set_body (gimple_bind, new_body);
}
gimplify_ctxp->save_stack = old_save_stack;
gimple_pop_bind_expr ();
gimplify_seq_add_stmt (pre_p, gimple_bind);
if (temp)
{
*expr_p = temp;
return GS_OK;
}
*expr_p = NULL_TREE;
return GS_ALL_DONE;
}
/* Gimplify a RETURN_EXPR. If the expression to be returned is not a
GIMPLE value, it is assigned to a new temporary and the statement is
re-written to return the temporary.
PRE_P points to the sequence where side effects that must happen before
STMT should be stored. */
static enum gimplify_status
gimplify_return_expr (tree stmt, gimple_seq *pre_p)
{
gimple ret;
tree ret_expr = TREE_OPERAND (stmt, 0);
tree result_decl, result;
if (ret_expr == error_mark_node)
return GS_ERROR;
if (!ret_expr
|| TREE_CODE (ret_expr) == RESULT_DECL
|| ret_expr == error_mark_node)
{
gimple ret = gimple_build_return (ret_expr);
gimple_set_no_warning (ret, TREE_NO_WARNING (stmt));
gimplify_seq_add_stmt (pre_p, ret);
return GS_ALL_DONE;
}
if (VOID_TYPE_P (TREE_TYPE (TREE_TYPE (current_function_decl))))
result_decl = NULL_TREE;
else
{
result_decl = TREE_OPERAND (ret_expr, 0);
/* See through a return by reference. */
if (TREE_CODE (result_decl) == INDIRECT_REF)
result_decl = TREE_OPERAND (result_decl, 0);
gcc_assert ((TREE_CODE (ret_expr) == MODIFY_EXPR
|| TREE_CODE (ret_expr) == INIT_EXPR)
&& TREE_CODE (result_decl) == RESULT_DECL);
}
/* If aggregate_value_p is true, then we can return the bare RESULT_DECL.
Recall that aggregate_value_p is FALSE for any aggregate type that is
returned in registers. If we're returning values in registers, then
we don't want to extend the lifetime of the RESULT_DECL, particularly
across another call. In addition, for those aggregates for which
hard_function_value generates a PARALLEL, we'll die during normal
expansion of structure assignments; there's special code in expand_return
to handle this case that does not exist in expand_expr. */
if (!result_decl
|| aggregate_value_p (result_decl, TREE_TYPE (current_function_decl)))
result = result_decl;
else if (gimplify_ctxp->return_temp)
result = gimplify_ctxp->return_temp;
else
{
result = create_tmp_var (TREE_TYPE (result_decl), NULL);
if (TREE_CODE (TREE_TYPE (result)) == COMPLEX_TYPE
|| TREE_CODE (TREE_TYPE (result)) == VECTOR_TYPE)
DECL_GIMPLE_REG_P (result) = 1;
/* ??? With complex control flow (usually involving abnormal edges),
we can wind up warning about an uninitialized value for this. Due
to how this variable is constructed and initialized, this is never
true. Give up and never warn. */
TREE_NO_WARNING (result) = 1;
gimplify_ctxp->return_temp = result;
}
/* Smash the lhs of the MODIFY_EXPR to the temporary we plan to use.
Then gimplify the whole thing. */
if (result != result_decl)
TREE_OPERAND (ret_expr, 0) = result;
gimplify_and_add (TREE_OPERAND (stmt, 0), pre_p);
ret = gimple_build_return (result);
gimple_set_no_warning (ret, TREE_NO_WARNING (stmt));
gimplify_seq_add_stmt (pre_p, ret);
return GS_ALL_DONE;
}
static void
gimplify_vla_decl (tree decl, gimple_seq *seq_p)
{
/* This is a variable-sized decl. Simplify its size and mark it
for deferred expansion. Note that mudflap depends on the format
of the emitted code: see mx_register_decls(). */
tree t, addr, ptr_type;
gimplify_one_sizepos (&DECL_SIZE (decl), seq_p);
gimplify_one_sizepos (&DECL_SIZE_UNIT (decl), seq_p);
/* All occurrences of this decl in final gimplified code will be
replaced by indirection. Setting DECL_VALUE_EXPR does two
things: First, it lets the rest of the gimplifier know what
replacement to use. Second, it lets the debug info know
where to find the value. */
ptr_type = build_pointer_type (TREE_TYPE (decl));
addr = create_tmp_var (ptr_type, get_name (decl));
DECL_IGNORED_P (addr) = 0;
t = build_fold_indirect_ref (addr);
SET_DECL_VALUE_EXPR (decl, t);
DECL_HAS_VALUE_EXPR_P (decl) = 1;
t = built_in_decls[BUILT_IN_ALLOCA];
t = build_call_expr (t, 1, DECL_SIZE_UNIT (decl));
t = fold_convert (ptr_type, t);
t = build2 (MODIFY_EXPR, TREE_TYPE (addr), addr, t);
gimplify_and_add (t, seq_p);
/* Indicate that we need to restore the stack level when the
enclosing BIND_EXPR is exited. */
gimplify_ctxp->save_stack = true;
}
/* Gimplifies a DECL_EXPR node *STMT_P by making any necessary allocation
and initialization explicit. */
static enum gimplify_status
gimplify_decl_expr (tree *stmt_p, gimple_seq *seq_p)
{
tree stmt = *stmt_p;
tree decl = DECL_EXPR_DECL (stmt);
*stmt_p = NULL_TREE;
if (TREE_TYPE (decl) == error_mark_node)
return GS_ERROR;
if ((TREE_CODE (decl) == TYPE_DECL
|| TREE_CODE (decl) == VAR_DECL)
&& !TYPE_SIZES_GIMPLIFIED (TREE_TYPE (decl)))
gimplify_type_sizes (TREE_TYPE (decl), seq_p);
if (TREE_CODE (decl) == VAR_DECL && !DECL_EXTERNAL (decl))
{
tree init = DECL_INITIAL (decl);
if (TREE_CODE (DECL_SIZE_UNIT (decl)) != INTEGER_CST
|| (!TREE_STATIC (decl)
&& flag_stack_check == GENERIC_STACK_CHECK
&& compare_tree_int (DECL_SIZE_UNIT (decl),
STACK_CHECK_MAX_VAR_SIZE) > 0))
gimplify_vla_decl (decl, seq_p);
if (init && init != error_mark_node)
{
if (!TREE_STATIC (decl))
{
DECL_INITIAL (decl) = NULL_TREE;
init = build2 (INIT_EXPR, void_type_node, decl, init);
gimplify_and_add (init, seq_p);
ggc_free (init);
}
else
/* We must still examine initializers for static variables
as they may contain a label address. */
walk_tree (&init, force_labels_r, NULL, NULL);
}
/* Some front ends do not explicitly declare all anonymous
artificial variables. We compensate here by declaring the
variables, though it would be better if the front ends would
explicitly declare them. */
if (!DECL_SEEN_IN_BIND_EXPR_P (decl)
&& DECL_ARTIFICIAL (decl) && DECL_NAME (decl) == NULL_TREE)
gimple_add_tmp_var (decl);
}
return GS_ALL_DONE;
}
/* Gimplify a LOOP_EXPR. Normally this just involves gimplifying the body
and replacing the LOOP_EXPR with goto, but if the loop contains an
EXIT_EXPR, we need to append a label for it to jump to. */
static enum gimplify_status
gimplify_loop_expr (tree *expr_p, gimple_seq *pre_p)
{
tree saved_label = gimplify_ctxp->exit_label;
tree start_label = create_artificial_label ();
gimplify_seq_add_stmt (pre_p, gimple_build_label (start_label));
gimplify_ctxp->exit_label = NULL_TREE;
gimplify_and_add (LOOP_EXPR_BODY (*expr_p), pre_p);
gimplify_seq_add_stmt (pre_p, gimple_build_goto (start_label));
if (gimplify_ctxp->exit_label)
gimplify_seq_add_stmt (pre_p, gimple_build_label (gimplify_ctxp->exit_label));
gimplify_ctxp->exit_label = saved_label;
*expr_p = NULL;
return GS_ALL_DONE;
}
/* Gimplifies a statement list onto a sequence. These may be created either
by an enlightened front-end, or by shortcut_cond_expr. */
static enum gimplify_status
gimplify_statement_list (tree *expr_p, gimple_seq *pre_p)
{
tree temp = voidify_wrapper_expr (*expr_p, NULL);
tree_stmt_iterator i = tsi_start (*expr_p);
while (!tsi_end_p (i))
{
gimplify_stmt (tsi_stmt_ptr (i), pre_p);
tsi_delink (&i);
}
if (temp)
{
*expr_p = temp;
return GS_OK;
}
return GS_ALL_DONE;
}
/* Compare two case labels. Because the front end should already have
made sure that case ranges do not overlap, it is enough to only compare
the CASE_LOW values of each case label. */
static int
compare_case_labels (const void *p1, const void *p2)
{
const_tree const case1 = *(const_tree const*)p1;
const_tree const case2 = *(const_tree const*)p2;
/* The 'default' case label always goes first. */
if (!CASE_LOW (case1))
return -1;
else if (!CASE_LOW (case2))
return 1;
else
return tree_int_cst_compare (CASE_LOW (case1), CASE_LOW (case2));
}
/* Sort the case labels in LABEL_VEC in place in ascending order. */
void
sort_case_labels (VEC(tree,heap)* label_vec)
{
size_t len = VEC_length (tree, label_vec);
qsort (VEC_address (tree, label_vec), len, sizeof (tree),
compare_case_labels);
}
/* Gimplify a SWITCH_EXPR, and collect a TREE_VEC of the labels it can
branch to. */
static enum gimplify_status
gimplify_switch_expr (tree *expr_p, gimple_seq *pre_p)
{
tree switch_expr = *expr_p;
gimple_seq switch_body_seq = NULL;
enum gimplify_status ret;
ret = gimplify_expr (&SWITCH_COND (switch_expr), pre_p, NULL, is_gimple_val,
fb_rvalue);
if (ret == GS_ERROR || ret == GS_UNHANDLED)
return ret;
if (SWITCH_BODY (switch_expr))
{
VEC (tree,heap) *labels;
VEC (tree,heap) *saved_labels;
tree default_case = NULL_TREE;
size_t i, len;
gimple gimple_switch;
/* If someone can be bothered to fill in the labels, they can
be bothered to null out the body too. */
gcc_assert (!SWITCH_LABELS (switch_expr));
/* save old labels, get new ones from body, then restore the old
labels. Save all the things from the switch body to append after. */
saved_labels = gimplify_ctxp->case_labels;
gimplify_ctxp->case_labels = VEC_alloc (tree, heap, 8);
gimplify_stmt (&SWITCH_BODY (switch_expr), &switch_body_seq);
labels = gimplify_ctxp->case_labels;
gimplify_ctxp->case_labels = saved_labels;
i = 0;
while (i < VEC_length (tree, labels))
{
tree elt = VEC_index (tree, labels, i);
tree low = CASE_LOW (elt);
bool remove_element = FALSE;
if (low)
{
/* Discard empty ranges. */
tree high = CASE_HIGH (elt);
if (high && tree_int_cst_lt (high, low))
remove_element = TRUE;
}
else
{
/* The default case must be the last label in the list. */
gcc_assert (!default_case);
default_case = elt;
remove_element = TRUE;
}
if (remove_element)
VEC_ordered_remove (tree, labels, i);
else
i++;
}
len = i;
if (!VEC_empty (tree, labels))
sort_case_labels (labels);
if (!default_case)
{
tree type = TREE_TYPE (switch_expr);
/* If the switch has no default label, add one, so that we jump
around the switch body. If the labels already cover the whole
range of type, add the default label pointing to one of the
existing labels. */
if (type == void_type_node)
type = TREE_TYPE (SWITCH_COND (switch_expr));
if (len
&& INTEGRAL_TYPE_P (type)
&& TYPE_MIN_VALUE (type)
&& TYPE_MAX_VALUE (type)
&& tree_int_cst_equal (CASE_LOW (VEC_index (tree, labels, 0)),
TYPE_MIN_VALUE (type)))
{
tree low, high = CASE_HIGH (VEC_index (tree, labels, len - 1));
if (!high)
high = CASE_LOW (VEC_index (tree, labels, len - 1));
if (tree_int_cst_equal (high, TYPE_MAX_VALUE (type)))
{
for (i = 1; i < len; i++)
{
high = CASE_LOW (VEC_index (tree, labels, i));
low = CASE_HIGH (VEC_index (tree, labels, i - 1));
if (!low)
low = CASE_LOW (VEC_index (tree, labels, i - 1));
if ((TREE_INT_CST_LOW (low) + 1
!= TREE_INT_CST_LOW (high))
|| (TREE_INT_CST_HIGH (low)
+ (TREE_INT_CST_LOW (high) == 0)
!= TREE_INT_CST_HIGH (high)))
break;
}
if (i == len)
default_case = build3 (CASE_LABEL_EXPR, void_type_node,
NULL_TREE, NULL_TREE,
CASE_LABEL (VEC_index (tree,
labels, 0)));
}
}
if (!default_case)
{
gimple new_default;
default_case = build3 (CASE_LABEL_EXPR, void_type_node,
NULL_TREE, NULL_TREE,
create_artificial_label ());
new_default = gimple_build_label (CASE_LABEL (default_case));
gimplify_seq_add_stmt (&switch_body_seq, new_default);
}
}
gimple_switch = gimple_build_switch_vec (SWITCH_COND (switch_expr),
default_case, labels);
gimplify_seq_add_stmt (pre_p, gimple_switch);
gimplify_seq_add_seq (pre_p, switch_body_seq);
VEC_free(tree, heap, labels);
}
else
gcc_assert (SWITCH_LABELS (switch_expr));
return GS_ALL_DONE;
}
static enum gimplify_status
gimplify_case_label_expr (tree *expr_p, gimple_seq *pre_p)
{
struct gimplify_ctx *ctxp;
gimple gimple_label;
/* Invalid OpenMP programs can play Duff's Device type games with
#pragma omp parallel. At least in the C front end, we don't
detect such invalid branches until after gimplification. */
for (ctxp = gimplify_ctxp; ; ctxp = ctxp->prev_context)
if (ctxp->case_labels)
break;
gimple_label = gimple_build_label (CASE_LABEL (*expr_p));
VEC_safe_push (tree, heap, ctxp->case_labels, *expr_p);
gimplify_seq_add_stmt (pre_p, gimple_label);
return GS_ALL_DONE;
}
/* Build a GOTO to the LABEL_DECL pointed to by LABEL_P, building it first
if necessary. */
tree
build_and_jump (tree *label_p)
{
if (label_p == NULL)
/* If there's nowhere to jump, just fall through. */
return NULL_TREE;
if (*label_p == NULL_TREE)
{
tree label = create_artificial_label ();
*label_p = label;
}
return build1 (GOTO_EXPR, void_type_node, *label_p);
}
/* Gimplify an EXIT_EXPR by converting to a GOTO_EXPR inside a COND_EXPR.
This also involves building a label to jump to and communicating it to
gimplify_loop_expr through gimplify_ctxp->exit_label. */
static enum gimplify_status
gimplify_exit_expr (tree *expr_p)
{
tree cond = TREE_OPERAND (*expr_p, 0);
tree expr;
expr = build_and_jump (&gimplify_ctxp->exit_label);
expr = build3 (COND_EXPR, void_type_node, cond, expr, NULL_TREE);
*expr_p = expr;
return GS_OK;
}
/* A helper function to be called via walk_tree. Mark all labels under *TP
as being forced. To be called for DECL_INITIAL of static variables. */
tree
force_labels_r (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED)
{
if (TYPE_P (*tp))
*walk_subtrees = 0;
if (TREE_CODE (*tp) == LABEL_DECL)
FORCED_LABEL (*tp) = 1;
return NULL_TREE;
}
/* *EXPR_P is a COMPONENT_REF being used as an rvalue. If its type is
different from its canonical type, wrap the whole thing inside a
NOP_EXPR and force the type of the COMPONENT_REF to be the canonical
type.
The canonical type of a COMPONENT_REF is the type of the field being
referenced--unless the field is a bit-field which can be read directly
in a smaller mode, in which case the canonical type is the
sign-appropriate type corresponding to that mode. */
static void
canonicalize_component_ref (tree *expr_p)
{
tree expr = *expr_p;
tree type;
gcc_assert (TREE_CODE (expr) == COMPONENT_REF);
if (INTEGRAL_TYPE_P (TREE_TYPE (expr)))
type = TREE_TYPE (get_unwidened (expr, NULL_TREE));
else
type = TREE_TYPE (TREE_OPERAND (expr, 1));
/* One could argue that all the stuff below is not necessary for
the non-bitfield case and declare it a FE error if type
adjustment would be needed. */
if (TREE_TYPE (expr) != type)
{
#ifdef ENABLE_TYPES_CHECKING
tree old_type = TREE_TYPE (expr);
#endif
int type_quals;
/* We need to preserve qualifiers and propagate them from
operand 0. */
type_quals = TYPE_QUALS (type)
| TYPE_QUALS (TREE_TYPE (TREE_OPERAND (expr, 0)));
if (TYPE_QUALS (type) != type_quals)
type = build_qualified_type (TYPE_MAIN_VARIANT (type), type_quals);
/* Set the type of the COMPONENT_REF to the underlying type. */
TREE_TYPE (expr) = type;
#ifdef ENABLE_TYPES_CHECKING
/* It is now a FE error, if the conversion from the canonical
type to the original expression type is not useless. */
gcc_assert (useless_type_conversion_p (old_type, type));
#endif
}
}
/* If a NOP conversion is changing a pointer to array of foo to a pointer
to foo, embed that change in the ADDR_EXPR by converting
T array[U];
(T *)&array
==>
&array[L]
where L is the lower bound. For simplicity, only do this for constant
lower bound.
The constraint is that the type of &array[L] is trivially convertible
to T *. */
static void
canonicalize_addr_expr (tree *expr_p)
{
tree expr = *expr_p;
tree addr_expr = TREE_OPERAND (expr, 0);
tree datype, ddatype, pddatype;
/* We simplify only conversions from an ADDR_EXPR to a pointer type. */
if (!POINTER_TYPE_P (TREE_TYPE (expr))
|| TREE_CODE (addr_expr) != ADDR_EXPR)
return;
/* The addr_expr type should be a pointer to an array. */
datype = TREE_TYPE (TREE_TYPE (addr_expr));
if (TREE_CODE (datype) != ARRAY_TYPE)
return;
/* The pointer to element type shall be trivially convertible to
the expression pointer type. */
ddatype = TREE_TYPE (datype);
pddatype = build_pointer_type (ddatype);
if (!useless_type_conversion_p (pddatype, ddatype))
return;
/* The lower bound and element sizes must be constant. */
if (!TYPE_SIZE_UNIT (ddatype)
|| TREE_CODE (TYPE_SIZE_UNIT (ddatype)) != INTEGER_CST
|| !TYPE_DOMAIN (datype) || !TYPE_MIN_VALUE (TYPE_DOMAIN (datype))
|| TREE_CODE (TYPE_MIN_VALUE (TYPE_DOMAIN (datype))) != INTEGER_CST)
return;
/* All checks succeeded. Build a new node to merge the cast. */
*expr_p = build4 (ARRAY_REF, ddatype, TREE_OPERAND (addr_expr, 0),
TYPE_MIN_VALUE (TYPE_DOMAIN (datype)),
NULL_TREE, NULL_TREE);
*expr_p = build1 (ADDR_EXPR, pddatype, *expr_p);
}
/* *EXPR_P is a NOP_EXPR or CONVERT_EXPR. Remove it and/or other conversions
underneath as appropriate. */
static enum gimplify_status
gimplify_conversion (tree *expr_p)
{
tree tem;
gcc_assert (CONVERT_EXPR_P (*expr_p));
/* Then strip away all but the outermost conversion. */
STRIP_SIGN_NOPS (TREE_OPERAND (*expr_p, 0));
/* And remove the outermost conversion if it's useless. */
if (tree_ssa_useless_type_conversion (*expr_p))
*expr_p = TREE_OPERAND (*expr_p, 0);
/* Attempt to avoid NOP_EXPR by producing reference to a subtype.
For example this fold (subclass *)&A into &A->subclass avoiding
a need for statement. */
if (CONVERT_EXPR_P (*expr_p)
&& POINTER_TYPE_P (TREE_TYPE (*expr_p))
&& POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (*expr_p, 0)))
&& (tem = maybe_fold_offset_to_address
(TREE_OPERAND (*expr_p, 0),
integer_zero_node, TREE_TYPE (*expr_p))) != NULL_TREE)
*expr_p = tem;
/* If we still have a conversion at the toplevel,
then canonicalize some constructs. */
if (CONVERT_EXPR_P (*expr_p))
{
tree sub = TREE_OPERAND (*expr_p, 0);
/* If a NOP conversion is changing the type of a COMPONENT_REF
expression, then canonicalize its type now in order to expose more
redundant conversions. */
if (TREE_CODE (sub) == COMPONENT_REF)
canonicalize_component_ref (&TREE_OPERAND (*expr_p, 0));
/* If a NOP conversion is changing a pointer to array of foo
to a pointer to foo, embed that change in the ADDR_EXPR. */
else if (TREE_CODE (sub) == ADDR_EXPR)
canonicalize_addr_expr (expr_p);
}
/* If we have a conversion to a non-register type force the
use of a VIEW_CONVERT_EXPR instead. */
if (CONVERT_EXPR_P (*expr_p) && !is_gimple_reg_type (TREE_TYPE (*expr_p)))
*expr_p = fold_build1 (VIEW_CONVERT_EXPR, TREE_TYPE (*expr_p),
TREE_OPERAND (*expr_p, 0));
return GS_OK;
}
/* Gimplify a VAR_DECL or PARM_DECL. Returns GS_OK if we expanded a
DECL_VALUE_EXPR, and it's worth re-examining things. */
static enum gimplify_status
gimplify_var_or_parm_decl (tree *expr_p)
{
tree decl = *expr_p;
/* ??? If this is a local variable, and it has not been seen in any
outer BIND_EXPR, then it's probably the result of a duplicate
declaration, for which we've already issued an error. It would
be really nice if the front end wouldn't leak these at all.
Currently the only known culprit is C++ destructors, as seen
in g++.old-deja/g++.jason/binding.C. */
if (TREE_CODE (decl) == VAR_DECL
&& !DECL_SEEN_IN_BIND_EXPR_P (decl)
&& !TREE_STATIC (decl) && !DECL_EXTERNAL (decl)
&& decl_function_context (decl) == current_function_decl)
{
gcc_assert (errorcount || sorrycount);
return GS_ERROR;
}
/* When within an OpenMP context, notice uses of variables. */
if (gimplify_omp_ctxp && omp_notice_variable (gimplify_omp_ctxp, decl, true))
return GS_ALL_DONE;
/* If the decl is an alias for another expression, substitute it now. */
if (DECL_HAS_VALUE_EXPR_P (decl))
{
*expr_p = unshare_expr (DECL_VALUE_EXPR (decl));
return GS_OK;
}
return GS_ALL_DONE;
}
/* Gimplify the COMPONENT_REF, ARRAY_REF, REALPART_EXPR or IMAGPART_EXPR
node *EXPR_P.
compound_lval
: min_lval '[' val ']'
| min_lval '.' ID
| compound_lval '[' val ']'
| compound_lval '.' ID
This is not part of the original SIMPLE definition, which separates
array and member references, but it seems reasonable to handle them
together. Also, this way we don't run into problems with union
aliasing; gcc requires that for accesses through a union to alias, the
union reference must be explicit, which was not always the case when we
were splitting up array and member refs.
PRE_P points to the sequence where side effects that must happen before
*EXPR_P should be stored.
POST_P points to the sequence where side effects that must happen after
*EXPR_P should be stored. */
static enum gimplify_status
gimplify_compound_lval (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p,
fallback_t fallback)
{
tree *p;
VEC(tree,heap) *stack;
enum gimplify_status ret = GS_OK, tret;
int i;
/* Create a stack of the subexpressions so later we can walk them in
order from inner to outer. */
stack = VEC_alloc (tree, heap, 10);
/* We can handle anything that get_inner_reference can deal with. */
for (p = expr_p; ; p = &TREE_OPERAND (*p, 0))
{
restart:
/* Fold INDIRECT_REFs now to turn them into ARRAY_REFs. */
if (TREE_CODE (*p) == INDIRECT_REF)
*p = fold_indirect_ref (*p);
if (handled_component_p (*p))
;
/* Expand DECL_VALUE_EXPR now. In some cases that may expose
additional COMPONENT_REFs. */
else if ((TREE_CODE (*p) == VAR_DECL || TREE_CODE (*p) == PARM_DECL)
&& gimplify_var_or_parm_decl (p) == GS_OK)
goto restart;
else
break;
VEC_safe_push (tree, heap, stack, *p);
}
gcc_assert (VEC_length (tree, stack));
/* Now STACK is a stack of pointers to all the refs we've walked through
and P points to the innermost expression.
Java requires that we elaborated nodes in source order. That
means we must gimplify the inner expression followed by each of
the indices, in order. But we can't gimplify the inner
expression until we deal with any variable bounds, sizes, or
positions in order to deal with PLACEHOLDER_EXPRs.
So we do this in three steps. First we deal with the annotations
for any variables in the components, then we gimplify the base,
then we gimplify any indices, from left to right. */
for (i = VEC_length (tree, stack) - 1; i >= 0; i--)
{
tree t = VEC_index (tree, stack, i);
if (TREE_CODE (t) == ARRAY_REF || TREE_CODE (t) == ARRAY_RANGE_REF)
{
/* Gimplify the low bound and element type size and put them into
the ARRAY_REF. If these values are set, they have already been
gimplified. */
if (TREE_OPERAND (t, 2) == NULL_TREE)
{
tree low = unshare_expr (array_ref_low_bound (t));
if (!is_gimple_min_invariant (low))
{
TREE_OPERAND (t, 2) = low;
tret = gimplify_expr (&TREE_OPERAND (t, 2), pre_p,
post_p, is_gimple_formal_tmp_reg,
fb_rvalue);
ret = MIN (ret, tret);
}
}
if (!TREE_OPERAND (t, 3))
{
tree elmt_type = TREE_TYPE (TREE_TYPE (TREE_OPERAND (t, 0)));
tree elmt_size = unshare_expr (array_ref_element_size (t));
tree factor = size_int (TYPE_ALIGN_UNIT (elmt_type));
/* Divide the element size by the alignment of the element
type (above). */
elmt_size = size_binop (EXACT_DIV_EXPR, elmt_size, factor);
if (!is_gimple_min_invariant (elmt_size))
{
TREE_OPERAND (t, 3) = elmt_size;
tret = gimplify_expr (&TREE_OPERAND (t, 3), pre_p,
post_p, is_gimple_formal_tmp_reg,
fb_rvalue);
ret = MIN (ret, tret);
}
}
}
else if (TREE_CODE (t) == COMPONENT_REF)
{
/* Set the field offset into T and gimplify it. */
if (!TREE_OPERAND (t, 2))
{
tree offset = unshare_expr (component_ref_field_offset (t));
tree field = TREE_OPERAND (t, 1);
tree factor
= size_int (DECL_OFFSET_ALIGN (field) / BITS_PER_UNIT);
/* Divide the offset by its alignment. */
offset = size_binop (EXACT_DIV_EXPR, offset, factor);
if (!is_gimple_min_invariant (offset))
{
TREE_OPERAND (t, 2) = offset;
tret = gimplify_expr (&TREE_OPERAND (t, 2), pre_p,
post_p, is_gimple_formal_tmp_reg,
fb_rvalue);
ret = MIN (ret, tret);
}
}
}
}
/* Step 2 is to gimplify the base expression. Make sure lvalue is set
so as to match the min_lval predicate. Failure to do so may result
in the creation of large aggregate temporaries. */
tret = gimplify_expr (p, pre_p, post_p, is_gimple_min_lval,
fallback | fb_lvalue);
ret = MIN (ret, tret);
/* And finally, the indices and operands to BIT_FIELD_REF. During this
loop we also remove any useless conversions. */
for (; VEC_length (tree, stack) > 0; )
{
tree t = VEC_pop (tree, stack);
if (TREE_CODE (t) == ARRAY_REF || TREE_CODE (t) == ARRAY_RANGE_REF)
{
/* Gimplify the dimension.
Temporary fix for gcc.c-torture/execute/20040313-1.c.
Gimplify non-constant array indices into a temporary
variable.
FIXME - The real fix is to gimplify post-modify
expressions into a minimal gimple lvalue. However, that
exposes bugs in alias analysis. The alias analyzer does
not handle &PTR->FIELD very well. Will fix after the
branch is merged into mainline (dnovillo 2004-05-03). */
if (!is_gimple_min_invariant (TREE_OPERAND (t, 1)))
{
tret = gimplify_expr (&TREE_OPERAND (t, 1), pre_p, post_p,
is_gimple_formal_tmp_reg, fb_rvalue);
ret = MIN (ret, tret);
}
}
else if (TREE_CODE (t) == BIT_FIELD_REF)
{
tret = gimplify_expr (&TREE_OPERAND (t, 1), pre_p, post_p,
is_gimple_val, fb_rvalue);
ret = MIN (ret, tret);
tret = gimplify_expr (&TREE_OPERAND (t, 2), pre_p, post_p,
is_gimple_val, fb_rvalue);
ret = MIN (ret, tret);
}
STRIP_USELESS_TYPE_CONVERSION (TREE_OPERAND (t, 0));
/* The innermost expression P may have originally had
TREE_SIDE_EFFECTS set which would have caused all the outer
expressions in *EXPR_P leading to P to also have had
TREE_SIDE_EFFECTS set. */
recalculate_side_effects (t);
}
/* If the outermost expression is a COMPONENT_REF, canonicalize its type. */
if ((fallback & fb_rvalue) && TREE_CODE (*expr_p) == COMPONENT_REF)
{
canonicalize_component_ref (expr_p);
ret = MIN (ret, GS_OK);
}
VEC_free (tree, heap, stack);
return ret;
}
/* Gimplify the self modifying expression pointed to by EXPR_P
(++, --, +=, -=).
PRE_P points to the list where side effects that must happen before
*EXPR_P should be stored.
POST_P points to the list where side effects that must happen after
*EXPR_P should be stored.
WANT_VALUE is nonzero iff we want to use the value of this expression
in another expression. */
static enum gimplify_status
gimplify_self_mod_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p,
bool want_value)
{
enum tree_code code;
tree lhs, lvalue, rhs, t1;
gimple_seq post = NULL, *orig_post_p = post_p;
bool postfix;
enum tree_code arith_code;
enum gimplify_status ret;
code = TREE_CODE (*expr_p);
gcc_assert (code == POSTINCREMENT_EXPR || code == POSTDECREMENT_EXPR
|| code == PREINCREMENT_EXPR || code == PREDECREMENT_EXPR);
/* Prefix or postfix? */
if (code == POSTINCREMENT_EXPR || code == POSTDECREMENT_EXPR)
/* Faster to treat as prefix if result is not used. */
postfix = want_value;
else
postfix = false;
/* For postfix, make sure the inner expression's post side effects
are executed after side effects from this expression. */
if (postfix)
post_p = &post;
/* Add or subtract? */
if (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR)
arith_code = PLUS_EXPR;
else
arith_code = MINUS_EXPR;
/* Gimplify the LHS into a GIMPLE lvalue. */
lvalue = TREE_OPERAND (*expr_p, 0);
ret = gimplify_expr (&lvalue, pre_p, post_p, is_gimple_lvalue, fb_lvalue);
if (ret == GS_ERROR)
return ret;
/* Extract the operands to the arithmetic operation. */
lhs = lvalue;
rhs = TREE_OPERAND (*expr_p, 1);
/* For postfix operator, we evaluate the LHS to an rvalue and then use
that as the result value and in the postqueue operation. */
if (postfix)
{
ret = gimplify_expr (&lhs, pre_p, post_p, is_gimple_val, fb_rvalue);
if (ret == GS_ERROR)
return ret;
}
/* For POINTERs increment, use POINTER_PLUS_EXPR. */
if (POINTER_TYPE_P (TREE_TYPE (lhs)))
{
rhs = fold_convert (sizetype, rhs);
if (arith_code == MINUS_EXPR)
rhs = fold_build1 (NEGATE_EXPR, TREE_TYPE (rhs), rhs);
arith_code = POINTER_PLUS_EXPR;
}
t1 = build2 (arith_code, TREE_TYPE (*expr_p), lhs, rhs);
if (postfix)
{
gimplify_assign (lvalue, t1, orig_post_p);
gimplify_seq_add_seq (orig_post_p, post);
*expr_p = lhs;
return GS_ALL_DONE;
}
else
{
*expr_p = build2 (MODIFY_EXPR, TREE_TYPE (lvalue), lvalue, t1);
return GS_OK;
}
}
/* If *EXPR_P has a variable sized type, wrap it in a WITH_SIZE_EXPR. */
static void
maybe_with_size_expr (tree *expr_p)
{
tree expr = *expr_p;
tree type = TREE_TYPE (expr);
tree size;
/* If we've already wrapped this or the type is error_mark_node, we can't do
anything. */
if (TREE_CODE (expr) == WITH_SIZE_EXPR
|| type == error_mark_node)
return;
/* If the size isn't known or is a constant, we have nothing to do. */
size = TYPE_SIZE_UNIT (type);
if (!size || TREE_CODE (size) == INTEGER_CST)
return;
/* Otherwise, make a WITH_SIZE_EXPR. */
size = unshare_expr (size);
size = SUBSTITUTE_PLACEHOLDER_IN_EXPR (size, expr);
*expr_p = build2 (WITH_SIZE_EXPR, type, expr, size);
}
/* Helper for gimplify_call_expr. Gimplify a single argument *ARG_P
Store any side-effects in PRE_P. CALL_LOCATION is the location of
the CALL_EXPR. */
static enum gimplify_status
gimplify_arg (tree *arg_p, gimple_seq *pre_p, location_t call_location)
{
bool (*test) (tree);
fallback_t fb;
/* In general, we allow lvalues for function arguments to avoid
extra overhead of copying large aggregates out of even larger
aggregates into temporaries only to copy the temporaries to
the argument list. Make optimizers happy by pulling out to
temporaries those types that fit in registers. */
if (is_gimple_reg_type (TREE_TYPE (*arg_p)))
test = is_gimple_val, fb = fb_rvalue;
else
test = is_gimple_lvalue, fb = fb_either;
/* If this is a variable sized type, we must remember the size. */
maybe_with_size_expr (arg_p);
/* Make sure arguments have the same location as the function call
itself. */
protected_set_expr_location (*arg_p, call_location);
/* There is a sequence point before a function call. Side effects in
the argument list must occur before the actual call. So, when
gimplifying arguments, force gimplify_expr to use an internal
post queue which is then appended to the end of PRE_P. */
return gimplify_expr (arg_p, pre_p, NULL, test, fb);
}
/* Gimplify the CALL_EXPR node *EXPR_P into the GIMPLE sequence PRE_P.
WANT_VALUE is true if the result of the call is desired. */
static enum gimplify_status
gimplify_call_expr (tree *expr_p, gimple_seq *pre_p, bool want_value)
{
tree fndecl, parms, p;
enum gimplify_status ret;
int i, nargs;
gimple call;
bool builtin_va_start_p = FALSE;
gcc_assert (TREE_CODE (*expr_p) == CALL_EXPR);
/* For reliable diagnostics during inlining, it is necessary that
every call_expr be annotated with file and line. */
if (! EXPR_HAS_LOCATION (*expr_p))
SET_EXPR_LOCATION (*expr_p, input_location);
/* This may be a call to a builtin function.
Builtin function calls may be transformed into different
(and more efficient) builtin function calls under certain
circumstances. Unfortunately, gimplification can muck things
up enough that the builtin expanders are not aware that certain
transformations are still valid.
So we attempt transformation/gimplification of the call before
we gimplify the CALL_EXPR. At this time we do not manage to
transform all calls in the same manner as the expanders do, but
we do transform most of them. */
fndecl = get_callee_fndecl (*expr_p);
if (fndecl && DECL_BUILT_IN (fndecl))
{
tree new_tree = fold_call_expr (*expr_p, !want_value);
if (new_tree && new_tree != *expr_p)
{
/* There was a transformation of this call which computes the
same value, but in a more efficient way. Return and try
again. */
*expr_p = new_tree;
return GS_OK;
}
if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
&& DECL_FUNCTION_CODE (fndecl) == BUILT_IN_VA_START)
{
builtin_va_start_p = TRUE;
if (call_expr_nargs (*expr_p) < 2)
{
error ("too few arguments to function %<va_start%>");
*expr_p = build_empty_stmt ();
return GS_OK;
}
if (fold_builtin_next_arg (*expr_p, true))
{
*expr_p = build_empty_stmt ();
return GS_OK;
}
}
}
/* There is a sequence point before the call, so any side effects in
the calling expression must occur before the actual call. Force
gimplify_expr to use an internal post queue. */
ret = gimplify_expr (&CALL_EXPR_FN (*expr_p), pre_p, NULL,
is_gimple_call_addr, fb_rvalue);
nargs = call_expr_nargs (*expr_p);
/* Get argument types for verification. */
fndecl = get_callee_fndecl (*expr_p);
parms = NULL_TREE;
if (fndecl)
parms = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
else if (POINTER_TYPE_P (TREE_TYPE (CALL_EXPR_FN (*expr_p))))
parms = TYPE_ARG_TYPES (TREE_TYPE (TREE_TYPE (CALL_EXPR_FN (*expr_p))));
if (fndecl && DECL_ARGUMENTS (fndecl))
p = DECL_ARGUMENTS (fndecl);
else if (parms)
p = parms;
else
p = NULL_TREE;
for (i = 0; i < nargs && p; i++, p = TREE_CHAIN (p))
;
/* If the last argument is __builtin_va_arg_pack () and it is not
passed as a named argument, decrease the number of CALL_EXPR
arguments and set instead the CALL_EXPR_VA_ARG_PACK flag. */
if (!p
&& i < nargs
&& TREE_CODE (CALL_EXPR_ARG (*expr_p, nargs - 1)) == CALL_EXPR)
{
tree last_arg = CALL_EXPR_ARG (*expr_p, nargs - 1);
tree last_arg_fndecl = get_callee_fndecl (last_arg);
if (last_arg_fndecl
&& TREE_CODE (last_arg_fndecl) == FUNCTION_DECL
&& DECL_BUILT_IN_CLASS (last_arg_fndecl) == BUILT_IN_NORMAL
&& DECL_FUNCTION_CODE (last_arg_fndecl) == BUILT_IN_VA_ARG_PACK)
{
tree call = *expr_p;
--nargs;
*expr_p = build_call_array (TREE_TYPE (call), CALL_EXPR_FN (call),
nargs, CALL_EXPR_ARGP (call));
/* Copy all CALL_EXPR flags, location and block, except
CALL_EXPR_VA_ARG_PACK flag. */
CALL_EXPR_STATIC_CHAIN (*expr_p) = CALL_EXPR_STATIC_CHAIN (call);
CALL_EXPR_TAILCALL (*expr_p) = CALL_EXPR_TAILCALL (call);
CALL_EXPR_RETURN_SLOT_OPT (*expr_p)
= CALL_EXPR_RETURN_SLOT_OPT (call);
CALL_FROM_THUNK_P (*expr_p) = CALL_FROM_THUNK_P (call);
CALL_CANNOT_INLINE_P (*expr_p) = CALL_CANNOT_INLINE_P (call);
SET_EXPR_LOCUS (*expr_p, EXPR_LOCUS (call));
TREE_BLOCK (*expr_p) = TREE_BLOCK (call);
/* Set CALL_EXPR_VA_ARG_PACK. */
CALL_EXPR_VA_ARG_PACK (*expr_p) = 1;
}
}
/* Finally, gimplify the function arguments. */
if (nargs > 0)
{
for (i = (PUSH_ARGS_REVERSED ? nargs - 1 : 0);
PUSH_ARGS_REVERSED ? i >= 0 : i < nargs;
PUSH_ARGS_REVERSED ? i-- : i++)
{
enum gimplify_status t;
/* Avoid gimplifying the second argument to va_start, which needs to
be the plain PARM_DECL. */
if ((i != 1) || !builtin_va_start_p)
{
t = gimplify_arg (&CALL_EXPR_ARG (*expr_p, i), pre_p,
EXPR_LOCATION (*expr_p));
if (t == GS_ERROR)
ret = GS_ERROR;
}
}
}
/* Try this again in case gimplification exposed something. */
if (ret != GS_ERROR)
{
tree new_tree = fold_call_expr (*expr_p, !want_value);
if (new_tree && new_tree != *expr_p)
{
/* There was a transformation of this call which computes the
same value, but in a more efficient way. Return and try
again. */
*expr_p = new_tree;
return GS_OK;
}
}
else
{
*expr_p = error_mark_node;
return GS_ERROR;
}
/* If the function is "const" or "pure", then clear TREE_SIDE_EFFECTS on its
decl. This allows us to eliminate redundant or useless
calls to "const" functions. */
if (TREE_CODE (*expr_p) == CALL_EXPR)
{
int flags = call_expr_flags (*expr_p);
if (flags & (ECF_CONST | ECF_PURE)
/* An infinite loop is considered a side effect. */
&& !(flags & (ECF_LOOPING_CONST_OR_PURE)))
TREE_SIDE_EFFECTS (*expr_p) = 0;
}
/* If the value is not needed by the caller, emit a new GIMPLE_CALL
and clear *EXPR_P. Otherwise, leave *EXPR_P in its gimplified
form and delegate the creation of a GIMPLE_CALL to
gimplify_modify_expr. This is always possible because when
WANT_VALUE is true, the caller wants the result of this call into
a temporary, which means that we will emit an INIT_EXPR in
internal_get_tmp_var which will then be handled by
gimplify_modify_expr. */
if (!want_value)
{
/* The CALL_EXPR in *EXPR_P is already in GIMPLE form, so all we
have to do is replicate it as a GIMPLE_CALL tuple. */
call = gimple_build_call_from_tree (*expr_p);
gimplify_seq_add_stmt (pre_p, call);
*expr_p = NULL_TREE;
}
return ret;
}
/* Handle shortcut semantics in the predicate operand of a COND_EXPR by
rewriting it into multiple COND_EXPRs, and possibly GOTO_EXPRs.
TRUE_LABEL_P and FALSE_LABEL_P point to the labels to jump to if the
condition is true or false, respectively. If null, we should generate
our own to skip over the evaluation of this specific expression.
This function is the tree equivalent of do_jump.
shortcut_cond_r should only be called by shortcut_cond_expr. */
static tree
shortcut_cond_r (tree pred, tree *true_label_p, tree *false_label_p)
{
tree local_label = NULL_TREE;
tree t, expr = NULL;
/* OK, it's not a simple case; we need to pull apart the COND_EXPR to
retain the shortcut semantics. Just insert the gotos here;
shortcut_cond_expr will append the real blocks later. */
if (TREE_CODE (pred) == TRUTH_ANDIF_EXPR)
{
/* Turn if (a && b) into
if (a); else goto no;
if (b) goto yes; else goto no;
(no:) */
if (false_label_p == NULL)
false_label_p = &local_label;
t = shortcut_cond_r (TREE_OPERAND (pred, 0), NULL, false_label_p);
append_to_statement_list (t, &expr);
t = shortcut_cond_r (TREE_OPERAND (pred, 1), true_label_p,
false_label_p);
append_to_statement_list (t, &expr);
}
else if (TREE_CODE (pred) == TRUTH_ORIF_EXPR)
{
/* Turn if (a || b) into
if (a) goto yes;
if (b) goto yes; else goto no;
(yes:) */
if (true_label_p == NULL)
true_label_p = &local_label;
t = shortcut_cond_r (TREE_OPERAND (pred, 0), true_label_p, NULL);
append_to_statement_list (t, &expr);
t = shortcut_cond_r (TREE_OPERAND (pred, 1), true_label_p,
false_label_p);
append_to_statement_list (t, &expr);
}
else if (TREE_CODE (pred) == COND_EXPR)
{
/* As long as we're messing with gotos, turn if (a ? b : c) into
if (a)
if (b) goto yes; else goto no;
else
if (c) goto yes; else goto no; */
expr = build3 (COND_EXPR, void_type_node, TREE_OPERAND (pred, 0),
shortcut_cond_r (TREE_OPERAND (pred, 1), true_label_p,
false_label_p),
shortcut_cond_r (TREE_OPERAND (pred, 2), true_label_p,
false_label_p));
}
else
{
expr = build3 (COND_EXPR, void_type_node, pred,
build_and_jump (true_label_p),
build_and_jump (false_label_p));
}
if (local_label)
{
t = build1 (LABEL_EXPR, void_type_node, local_label);
append_to_statement_list (t, &expr);
}
return expr;
}
/* Given a conditional expression EXPR with short-circuit boolean
predicates using TRUTH_ANDIF_EXPR or TRUTH_ORIF_EXPR, break the
predicate appart into the equivalent sequence of conditionals. */
static tree
shortcut_cond_expr (tree expr)
{
tree pred = TREE_OPERAND (expr, 0);
tree then_ = TREE_OPERAND (expr, 1);
tree else_ = TREE_OPERAND (expr, 2);
tree true_label, false_label, end_label, t;
tree *true_label_p;
tree *false_label_p;
bool emit_end, emit_false, jump_over_else;
bool then_se = then_ && TREE_SIDE_EFFECTS (then_);
bool else_se = else_ && TREE_SIDE_EFFECTS (else_);
/* First do simple transformations. */
if (!else_se)
{
/* If there is no 'else', turn (a && b) into if (a) if (b). */
while (TREE_CODE (pred) == TRUTH_ANDIF_EXPR)
{
TREE_OPERAND (expr, 0) = TREE_OPERAND (pred, 1);
then_ = shortcut_cond_expr (expr);
then_se = then_ && TREE_SIDE_EFFECTS (then_);
pred = TREE_OPERAND (pred, 0);
expr = build3 (COND_EXPR, void_type_node, pred, then_, NULL_TREE);
}
}
if (!then_se)
{
/* If there is no 'then', turn
if (a || b); else d
into
if (a); else if (b); else d. */
while (TREE_CODE (pred) == TRUTH_ORIF_EXPR)
{
TREE_OPERAND (expr, 0) = TREE_OPERAND (pred, 1);
else_ = shortcut_cond_expr (expr);
else_se = else_ && TREE_SIDE_EFFECTS (else_);
pred = TREE_OPERAND (pred, 0);
expr = build3 (COND_EXPR, void_type_node, pred, NULL_TREE, else_);
}
}
/* If we're done, great. */
if (TREE_CODE (pred) != TRUTH_ANDIF_EXPR
&& TREE_CODE (pred) != TRUTH_ORIF_EXPR)
return expr;
/* Otherwise we need to mess with gotos. Change
if (a) c; else d;
to
if (a); else goto no;
c; goto end;
no: d; end:
and recursively gimplify the condition. */
true_label = false_label = end_label = NULL_TREE;
/* If our arms just jump somewhere, hijack those labels so we don't
generate jumps to jumps. */
if (then_
&& TREE_CODE (then_) == GOTO_EXPR
&& TREE_CODE (GOTO_DESTINATION (then_)) == LABEL_DECL)
{
true_label = GOTO_DESTINATION (then_);
then_ = NULL;
then_se = false;
}
if (else_
&& TREE_CODE (else_) == GOTO_EXPR
&& TREE_CODE (GOTO_DESTINATION (else_)) == LABEL_DECL)
{
false_label = GOTO_DESTINATION (else_);
else_ = NULL;
else_se = false;
}
/* If we aren't hijacking a label for the 'then' branch, it falls through. */
if (true_label)
true_label_p = &true_label;
else
true_label_p = NULL;
/* The 'else' branch also needs a label if it contains interesting code. */
if (false_label || else_se)
false_label_p = &false_label;
else
false_label_p = NULL;
/* If there was nothing else in our arms, just forward the label(s). */
if (!then_se && !else_se)
return shortcut_cond_r (pred, true_label_p, false_label_p);
/* If our last subexpression already has a terminal label, reuse it. */
if (else_se)
expr = expr_last (else_);
else if (then_se)
expr = expr_last (then_);
else
expr = NULL;
if (expr && TREE_CODE (expr) == LABEL_EXPR)
end_label = LABEL_EXPR_LABEL (expr);
/* If we don't care about jumping to the 'else' branch, jump to the end
if the condition is false. */
if (!false_label_p)
false_label_p = &end_label;
/* We only want to emit these labels if we aren't hijacking them. */
emit_end = (end_label == NULL_TREE);
emit_false = (false_label == NULL_TREE);
/* We only emit the jump over the else clause if we have to--if the
then clause may fall through. Otherwise we can wind up with a
useless jump and a useless label at the end of gimplified code,
which will cause us to think that this conditional as a whole
falls through even if it doesn't. If we then inline a function
which ends with such a condition, that can cause us to issue an
inappropriate warning about control reaching the end of a
non-void function. */
jump_over_else = block_may_fallthru (then_);
pred = shortcut_cond_r (pred, true_label_p, false_label_p);
expr = NULL;
append_to_statement_list (pred, &expr);
append_to_statement_list (then_, &expr);
if (else_se)
{
if (jump_over_else)
{
t = build_and_jump (&end_label);
append_to_statement_list (t, &expr);
}
if (emit_false)
{
t = build1 (LABEL_EXPR, void_type_node, false_label);
append_to_statement_list (t, &expr);
}
append_to_statement_list (else_, &expr);
}
if (emit_end && end_label)
{
t = build1 (LABEL_EXPR, void_type_node, end_label);
append_to_statement_list (t, &expr);
}
return expr;
}
/* EXPR is used in a boolean context; make sure it has BOOLEAN_TYPE. */
tree
gimple_boolify (tree expr)
{
tree type = TREE_TYPE (expr);
if (TREE_CODE (expr) == NE_EXPR
&& TREE_CODE (TREE_OPERAND (expr, 0)) == CALL_EXPR
&& integer_zerop (TREE_OPERAND (expr, 1)))
{
tree call = TREE_OPERAND (expr, 0);
tree fn = get_callee_fndecl (call);
/* For __builtin_expect ((long) (x), y) recurse into x as well
if x is truth_value_p. */
if (fn
&& DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL
&& DECL_FUNCTION_CODE (fn) == BUILT_IN_EXPECT
&& call_expr_nargs (call) == 2)
{
tree arg = CALL_EXPR_ARG (call, 0);
if (arg)
{
if (TREE_CODE (arg) == NOP_EXPR
&& TREE_TYPE (arg) == TREE_TYPE (call))
arg = TREE_OPERAND (arg, 0);
if (truth_value_p (TREE_CODE (arg)))
{
arg = gimple_boolify (arg);
CALL_EXPR_ARG (call, 0)
= fold_convert (TREE_TYPE (call), arg);
}
}
}
}
if (TREE_CODE (type) == BOOLEAN_TYPE)
return expr;
switch (TREE_CODE (expr))
{
case TRUTH_AND_EXPR:
case TRUTH_OR_EXPR:
case TRUTH_XOR_EXPR:
case TRUTH_ANDIF_EXPR:
case TRUTH_ORIF_EXPR:
/* Also boolify the arguments of truth exprs. */
TREE_OPERAND (expr, 1) = gimple_boolify (TREE_OPERAND (expr, 1));
/* FALLTHRU */
case TRUTH_NOT_EXPR:
TREE_OPERAND (expr, 0) = gimple_boolify (TREE_OPERAND (expr, 0));
/* FALLTHRU */
case EQ_EXPR: case NE_EXPR:
case LE_EXPR: case GE_EXPR: case LT_EXPR: case GT_EXPR:
/* These expressions always produce boolean results. */
TREE_TYPE (expr) = boolean_type_node;
return expr;
default:
/* Other expressions that get here must have boolean values, but
might need to be converted to the appropriate mode. */
return fold_convert (boolean_type_node, expr);
}
}
/* Given a conditional expression *EXPR_P without side effects, gimplify
its operands. New statements are inserted to PRE_P. */
static enum gimplify_status
gimplify_pure_cond_expr (tree *expr_p, gimple_seq *pre_p)
{
tree expr = *expr_p, cond;
enum gimplify_status ret, tret;
enum tree_code code;
cond = gimple_boolify (COND_EXPR_COND (expr));
/* We need to handle && and || specially, as their gimplification
creates pure cond_expr, thus leading to an infinite cycle otherwise. */
code = TREE_CODE (cond);
if (code == TRUTH_ANDIF_EXPR)
TREE_SET_CODE (cond, TRUTH_AND_EXPR);
else if (code == TRUTH_ORIF_EXPR)
TREE_SET_CODE (cond, TRUTH_OR_EXPR);
ret = gimplify_expr (&cond, pre_p, NULL, is_gimple_condexpr, fb_rvalue);
COND_EXPR_COND (*expr_p) = cond;
tret = gimplify_expr (&COND_EXPR_THEN (expr), pre_p, NULL,
is_gimple_val, fb_rvalue);
ret = MIN (ret, tret);
tret = gimplify_expr (&COND_EXPR_ELSE (expr), pre_p, NULL,
is_gimple_val, fb_rvalue);
return MIN (ret, tret);
}
/* Returns true if evaluating EXPR could trap.
EXPR is GENERIC, while tree_could_trap_p can be called
only on GIMPLE. */
static bool
generic_expr_could_trap_p (tree expr)
{
unsigned i, n;
if (!expr || is_gimple_val (expr))
return false;
if (!EXPR_P (expr) || tree_could_trap_p (expr))
return true;
n = TREE_OPERAND_LENGTH (expr);
for (i = 0; i < n; i++)
if (generic_expr_could_trap_p (TREE_OPERAND (expr, i)))
return true;
return false;
}
/* Convert the conditional expression pointed to by EXPR_P '(p) ? a : b;'
into
if (p) if (p)
t1 = a; a;
else or else
t1 = b; b;
t1;
The second form is used when *EXPR_P is of type void.
PRE_P points to the list where side effects that must happen before
*EXPR_P should be stored. */
static enum gimplify_status
gimplify_cond_expr (tree *expr_p, gimple_seq *pre_p, fallback_t fallback)
{
tree expr = *expr_p;
tree tmp, type, arm1, arm2;
enum gimplify_status ret;
tree label_true, label_false, label_cont;
bool have_then_clause_p, have_else_clause_p;
gimple gimple_cond;
enum tree_code pred_code;
gimple_seq seq = NULL;
type = TREE_TYPE (expr);
/* If this COND_EXPR has a value, copy the values into a temporary within
the arms. */
if (! VOID_TYPE_P (type))
{
tree result;
/* If an rvalue is ok or we do not require an lvalue, avoid creating
an addressable temporary. */
if (((fallback & fb_rvalue)
|| !(fallback & fb_lvalue))
&& !TREE_ADDRESSABLE (type))
{
if (gimplify_ctxp->allow_rhs_cond_expr
/* If either branch has side effects or could trap, it can't be
evaluated unconditionally. */
&& !TREE_SIDE_EFFECTS (TREE_OPERAND (*expr_p, 1))
&& !generic_expr_could_trap_p (TREE_OPERAND (*expr_p, 1))
&& !TREE_SIDE_EFFECTS (TREE_OPERAND (*expr_p, 2))
&& !generic_expr_could_trap_p (TREE_OPERAND (*expr_p, 2)))
return gimplify_pure_cond_expr (expr_p, pre_p);
result = tmp = create_tmp_var (TREE_TYPE (expr), "iftmp");
ret = GS_ALL_DONE;
}
else
{
tree type = build_pointer_type (TREE_TYPE (expr));
if (TREE_TYPE (TREE_OPERAND (expr, 1)) != void_type_node)
TREE_OPERAND (expr, 1) =
build_fold_addr_expr (TREE_OPERAND (expr, 1));
if (TREE_TYPE (TREE_OPERAND (expr, 2)) != void_type_node)
TREE_OPERAND (expr, 2) =
build_fold_addr_expr (TREE_OPERAND (expr, 2));
tmp = create_tmp_var (type, "iftmp");
expr = build3 (COND_EXPR, void_type_node, TREE_OPERAND (expr, 0),
TREE_OPERAND (expr, 1), TREE_OPERAND (expr, 2));
result = build_fold_indirect_ref (tmp);
}
/* Build the then clause, 't1 = a;'. But don't build an assignment
if this branch is void; in C++ it can be, if it's a throw. */
if (TREE_TYPE (TREE_OPERAND (expr, 1)) != void_type_node)
TREE_OPERAND (expr, 1)
= build2 (MODIFY_EXPR, TREE_TYPE (tmp), tmp, TREE_OPERAND (expr, 1));
/* Build the else clause, 't1 = b;'. */
if (TREE_TYPE (TREE_OPERAND (expr, 2)) != void_type_node)
TREE_OPERAND (expr, 2)
= build2 (MODIFY_EXPR, TREE_TYPE (tmp), tmp, TREE_OPERAND (expr, 2));
TREE_TYPE (expr) = void_type_node;
recalculate_side_effects (expr);
/* Move the COND_EXPR to the prequeue. */
gimplify_stmt (&expr, pre_p);
*expr_p = result;
return GS_ALL_DONE;
}
/* Make sure the condition has BOOLEAN_TYPE. */
TREE_OPERAND (expr, 0) = gimple_boolify (TREE_OPERAND (expr, 0));
/* Break apart && and || conditions. */
if (TREE_CODE (TREE_OPERAND (expr, 0)) == TRUTH_ANDIF_EXPR
|| TREE_CODE (TREE_OPERAND (expr, 0)) == TRUTH_ORIF_EXPR)
{
expr = shortcut_cond_expr (expr);
if (expr != *expr_p)
{
*expr_p = expr;
/* We can't rely on gimplify_expr to re-gimplify the expanded
form properly, as cleanups might cause the target labels to be
wrapped in a TRY_FINALLY_EXPR. To prevent that, we need to
set up a conditional context. */
gimple_push_condition ();
gimplify_stmt (expr_p, &seq);
gimple_pop_condition (pre_p);
gimple_seq_add_seq (pre_p, seq);
return GS_ALL_DONE;
}
}
/* Now do the normal gimplification. */
/* Gimplify condition. */
ret = gimplify_expr (&TREE_OPERAND (expr, 0), pre_p, NULL, is_gimple_condexpr,
fb_rvalue);
if (ret == GS_ERROR)
return GS_ERROR;
gcc_assert (TREE_OPERAND (expr, 0) != NULL_TREE);
gimple_push_condition ();
have_then_clause_p = have_else_clause_p = false;
if (TREE_OPERAND (expr, 1) != NULL
&& TREE_CODE (TREE_OPERAND (expr, 1)) == GOTO_EXPR
&& TREE_CODE (GOTO_DESTINATION (TREE_OPERAND (expr, 1))) == LABEL_DECL
&& (DECL_CONTEXT (GOTO_DESTINATION (TREE_OPERAND (expr, 1)))
== current_function_decl)
/* For -O0 avoid this optimization if the COND_EXPR and GOTO_EXPR
have different locations, otherwise we end up with incorrect
location information on the branches. */
&& (optimize
|| !EXPR_HAS_LOCATION (expr)
|| !EXPR_HAS_LOCATION (TREE_OPERAND (expr, 1))
|| EXPR_LOCATION (expr) == EXPR_LOCATION (TREE_OPERAND (expr, 1))))
{
label_true = GOTO_DESTINATION (TREE_OPERAND (expr, 1));
have_then_clause_p = true;
}
else
label_true = create_artificial_label ();
if (TREE_OPERAND (expr, 2) != NULL
&& TREE_CODE (TREE_OPERAND (expr, 2)) == GOTO_EXPR
&& TREE_CODE (GOTO_DESTINATION (TREE_OPERAND (expr, 2))) == LABEL_DECL
&& (DECL_CONTEXT (GOTO_DESTINATION (TREE_OPERAND (expr, 2)))
== current_function_decl)
/* For -O0 avoid this optimization if the COND_EXPR and GOTO_EXPR
have different locations, otherwise we end up with incorrect
location information on the branches. */
&& (optimize
|| !EXPR_HAS_LOCATION (expr)
|| !EXPR_HAS_LOCATION (TREE_OPERAND (expr, 2))
|| EXPR_LOCATION (expr) == EXPR_LOCATION (TREE_OPERAND (expr, 2))))
{
label_false = GOTO_DESTINATION (TREE_OPERAND (expr, 2));
have_else_clause_p = true;
}
else
label_false = create_artificial_label ();
gimple_cond_get_ops_from_tree (COND_EXPR_COND (expr), &pred_code, &arm1,
&arm2);
gimple_cond = gimple_build_cond (pred_code, arm1, arm2, label_true,
label_false);
gimplify_seq_add_stmt (&seq, gimple_cond);
label_cont = NULL_TREE;
if (!have_then_clause_p)
{
/* For if (...) {} else { code; } put label_true after
the else block. */
if (TREE_OPERAND (expr, 1) == NULL_TREE
&& !have_else_clause_p
&& TREE_OPERAND (expr, 2) != NULL_TREE)
label_cont = label_true;
else
{
gimplify_seq_add_stmt (&seq, gimple_build_label (label_true));
have_then_clause_p = gimplify_stmt (&TREE_OPERAND (expr, 1), &seq);
/* For if (...) { code; } else {} or
if (...) { code; } else goto label; or
if (...) { code; return; } else { ... }
label_cont isn't needed. */
if (!have_else_clause_p
&& TREE_OPERAND (expr, 2) != NULL_TREE
&& gimple_seq_may_fallthru (seq))
{
gimple g;
label_cont = create_artificial_label ();
g = gimple_build_goto (label_cont);
/* GIMPLE_COND's are very low level; they have embedded
gotos. This particular embedded goto should not be marked
with the location of the original COND_EXPR, as it would
correspond to the COND_EXPR's condition, not the ELSE or the
THEN arms. To avoid marking it with the wrong location, flag
it as "no location". */
gimple_set_do_not_emit_location (g);
gimplify_seq_add_stmt (&seq, g);
}
}
}
if (!have_else_clause_p)
{
gimplify_seq_add_stmt (&seq, gimple_build_label (label_false));
have_else_clause_p = gimplify_stmt (&TREE_OPERAND (expr, 2), &seq);
}
if (label_cont)
gimplify_seq_add_stmt (&seq, gimple_build_label (label_cont));
gimple_pop_condition (pre_p);
gimple_seq_add_seq (pre_p, seq);
if (ret == GS_ERROR)
; /* Do nothing. */
else if (have_then_clause_p || have_else_clause_p)
ret = GS_ALL_DONE;
else
{
/* Both arms are empty; replace the COND_EXPR with its predicate. */
expr = TREE_OPERAND (expr, 0);
gimplify_stmt (&expr, pre_p);
}
*expr_p = NULL;
return ret;
}
/* A subroutine of gimplify_modify_expr. Replace a MODIFY_EXPR with
a call to __builtin_memcpy. */
static enum gimplify_status
gimplify_modify_expr_to_memcpy (tree *expr_p, tree size, bool want_value,
gimple_seq *seq_p)
{
tree t, to, to_ptr, from, from_ptr;
gimple gs;
to = TREE_OPERAND (*expr_p, 0);
from = TREE_OPERAND (*expr_p, 1);
from_ptr = build_fold_addr_expr (from);
gimplify_arg (&from_ptr, seq_p, EXPR_LOCATION (*expr_p));
to_ptr = build_fold_addr_expr (to);
gimplify_arg (&to_ptr, seq_p, EXPR_LOCATION (*expr_p));
t = implicit_built_in_decls[BUILT_IN_MEMCPY];
gs = gimple_build_call (t, 3, to_ptr, from_ptr, size);
if (want_value)
{
/* tmp = memcpy() */
t = create_tmp_var (TREE_TYPE (to_ptr), NULL);
gimple_call_set_lhs (gs, t);
gimplify_seq_add_stmt (seq_p, gs);
*expr_p = build1 (INDIRECT_REF, TREE_TYPE (to), t);
return GS_ALL_DONE;
}
gimplify_seq_add_stmt (seq_p, gs);
*expr_p = NULL;
return GS_ALL_DONE;
}
/* A subroutine of gimplify_modify_expr. Replace a MODIFY_EXPR with
a call to __builtin_memset. In this case we know that the RHS is
a CONSTRUCTOR with an empty element list. */
static enum gimplify_status
gimplify_modify_expr_to_memset (tree *expr_p, tree size, bool want_value,
gimple_seq *seq_p)
{
tree t, from, to, to_ptr;
gimple gs;
/* Assert our assumptions, to abort instead of producing wrong code
silently if they are not met. Beware that the RHS CONSTRUCTOR might
not be immediately exposed. */
from = TREE_OPERAND (*expr_p, 1);
if (TREE_CODE (from) == WITH_SIZE_EXPR)
from = TREE_OPERAND (from, 0);
gcc_assert (TREE_CODE (from) == CONSTRUCTOR
&& VEC_empty (constructor_elt, CONSTRUCTOR_ELTS (from)));
/* Now proceed. */
to = TREE_OPERAND (*expr_p, 0);
to_ptr = build_fold_addr_expr (to);
gimplify_arg (&to_ptr, seq_p, EXPR_LOCATION (*expr_p));
t = implicit_built_in_decls[BUILT_IN_MEMSET];
gs = gimple_build_call (t, 3, to_ptr, integer_zero_node, size);
if (want_value)
{
/* tmp = memset() */
t = create_tmp_var (TREE_TYPE (to_ptr), NULL);
gimple_call_set_lhs (gs, t);
gimplify_seq_add_stmt (seq_p, gs);
*expr_p = build1 (INDIRECT_REF, TREE_TYPE (to), t);
return GS_ALL_DONE;
}
gimplify_seq_add_stmt (seq_p, gs);
*expr_p = NULL;
return GS_ALL_DONE;
}
/* A subroutine of gimplify_init_ctor_preeval. Called via walk_tree,
determine, cautiously, if a CONSTRUCTOR overlaps the lhs of an
assignment. Returns non-null if we detect a potential overlap. */
struct gimplify_init_ctor_preeval_data
{
/* The base decl of the lhs object. May be NULL, in which case we
have to assume the lhs is indirect. */
tree lhs_base_decl;
/* The alias set of the lhs object. */
alias_set_type lhs_alias_set;
};
static tree
gimplify_init_ctor_preeval_1 (tree *tp, int *walk_subtrees, void *xdata)
{
struct gimplify_init_ctor_preeval_data *data
= (struct gimplify_init_ctor_preeval_data *) xdata;
tree t = *tp;
/* If we find the base object, obviously we have overlap. */
if (data->lhs_base_decl == t)
return t;
/* If the constructor component is indirect, determine if we have a
potential overlap with the lhs. The only bits of information we
have to go on at this point are addressability and alias sets. */
if (TREE_CODE (t) == INDIRECT_REF
&& (!data->lhs_base_decl || TREE_ADDRESSABLE (data->lhs_base_decl))
&& alias_sets_conflict_p (data->lhs_alias_set, get_alias_set (t)))
return t;
/* If the constructor component is a call, determine if it can hide a
potential overlap with the lhs through an INDIRECT_REF like above. */
if (TREE_CODE (t) == CALL_EXPR)
{
tree type, fntype = TREE_TYPE (TREE_TYPE (CALL_EXPR_FN (t)));
for (type = TYPE_ARG_TYPES (fntype); type; type = TREE_CHAIN (type))
if (POINTER_TYPE_P (TREE_VALUE (type))
&& (!data->lhs_base_decl || TREE_ADDRESSABLE (data->lhs_base_decl))
&& alias_sets_conflict_p (data->lhs_alias_set,
get_alias_set
(TREE_TYPE (TREE_VALUE (type)))))
return t;
}
if (IS_TYPE_OR_DECL_P (t))
*walk_subtrees = 0;
return NULL;
}
/* A subroutine of gimplify_init_constructor. Pre-evaluate EXPR,
force values that overlap with the lhs (as described by *DATA)
into temporaries. */
static void
gimplify_init_ctor_preeval (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p,
struct gimplify_init_ctor_preeval_data *data)
{
enum gimplify_status one;
/* If the value is constant, then there's nothing to pre-evaluate. */
if (TREE_CONSTANT (*expr_p))
{
/* Ensure it does not have side effects, it might contain a reference to
the object we're initializing. */
gcc_assert (!TREE_SIDE_EFFECTS (*expr_p));
return;
}
/* If the type has non-trivial constructors, we can't pre-evaluate. */
if (TREE_ADDRESSABLE (TREE_TYPE (*expr_p)))
return;
/* Recurse for nested constructors. */
if (TREE_CODE (*expr_p) == CONSTRUCTOR)
{
unsigned HOST_WIDE_INT ix;
constructor_elt *ce;
VEC(constructor_elt,gc) *v = CONSTRUCTOR_ELTS (*expr_p);
for (ix = 0; VEC_iterate (constructor_elt, v, ix, ce); ix++)
gimplify_init_ctor_preeval (&ce->value, pre_p, post_p, data);
return;
}
/* If this is a variable sized type, we must remember the size. */
maybe_with_size_expr (expr_p);
/* Gimplify the constructor element to something appropriate for the rhs
of a MODIFY_EXPR. Given that we know the LHS is an aggregate, we know
the gimplifier will consider this a store to memory. Doing this
gimplification now means that we won't have to deal with complicated
language-specific trees, nor trees like SAVE_EXPR that can induce
exponential search behavior. */
one = gimplify_expr (expr_p, pre_p, post_p, is_gimple_mem_rhs, fb_rvalue);
if (one == GS_ERROR)
{
*expr_p = NULL;
return;
}
/* If we gimplified to a bare decl, we can be sure that it doesn't overlap
with the lhs, since "a = { .x=a }" doesn't make sense. This will
always be true for all scalars, since is_gimple_mem_rhs insists on a
temporary variable for them. */
if (DECL_P (*expr_p))
return;
/* If this is of variable size, we have no choice but to assume it doesn't
overlap since we can't make a temporary for it. */
if (TREE_CODE (TYPE_SIZE (TREE_TYPE (*expr_p))) != INTEGER_CST)
return;
/* Otherwise, we must search for overlap ... */
if (!walk_tree (expr_p, gimplify_init_ctor_preeval_1, data, NULL))
return;
/* ... and if found, force the value into a temporary. */
*expr_p = get_formal_tmp_var (*expr_p, pre_p);
}
/* A subroutine of gimplify_init_ctor_eval. Create a loop for
a RANGE_EXPR in a CONSTRUCTOR for an array.
var = lower;
loop_entry:
object[var] = value;
if (var == upper)
goto loop_exit;
var = var + 1;
goto loop_entry;
loop_exit:
We increment var _after_ the loop exit check because we might otherwise
fail if upper == TYPE_MAX_VALUE (type for upper).
Note that we never have to deal with SAVE_EXPRs here, because this has
already been taken care of for us, in gimplify_init_ctor_preeval(). */
static void gimplify_init_ctor_eval (tree, VEC(constructor_elt,gc) *,
gimple_seq *, bool);
static void
gimplify_init_ctor_eval_range (tree object, tree lower, tree upper,
tree value, tree array_elt_type,
gimple_seq *pre_p, bool cleared)
{
tree loop_entry_label, loop_exit_label, fall_thru_label;
tree var, var_type, cref, tmp;
loop_entry_label = create_artificial_label ();
loop_exit_label = create_artificial_label ();
fall_thru_label = create_artificial_label ();
/* Create and initialize the index variable. */
var_type = TREE_TYPE (upper);
var = create_tmp_var (var_type, NULL);
gimplify_seq_add_stmt (pre_p, gimple_build_assign (var, lower));
/* Add the loop entry label. */
gimplify_seq_add_stmt (pre_p, gimple_build_label (loop_entry_label));
/* Build the reference. */
cref = build4 (ARRAY_REF, array_elt_type, unshare_expr (object),
var, NULL_TREE, NULL_TREE);
/* If we are a constructor, just call gimplify_init_ctor_eval to do
the store. Otherwise just assign value to the reference. */
if (TREE_CODE (value) == CONSTRUCTOR)
/* NB we might have to call ourself recursively through
gimplify_init_ctor_eval if the value is a constructor. */
gimplify_init_ctor_eval (cref, CONSTRUCTOR_ELTS (value),
pre_p, cleared);
else
gimplify_seq_add_stmt (pre_p, gimple_build_assign (cref, value));
/* We exit the loop when the index var is equal to the upper bound. */
gimplify_seq_add_stmt (pre_p,
gimple_build_cond (EQ_EXPR, var, upper,
loop_exit_label, fall_thru_label));
gimplify_seq_add_stmt (pre_p, gimple_build_label (fall_thru_label));
/* Otherwise, increment the index var... */
tmp = build2 (PLUS_EXPR, var_type, var,
fold_convert (var_type, integer_one_node));
gimplify_seq_add_stmt (pre_p, gimple_build_assign (var, tmp));
/* ...and jump back to the loop entry. */
gimplify_seq_add_stmt (pre_p, gimple_build_goto (loop_entry_label));
/* Add the loop exit label. */
gimplify_seq_add_stmt (pre_p, gimple_build_label (loop_exit_label));
}
/* Return true if FDECL is accessing a field that is zero sized. */
static bool
zero_sized_field_decl (const_tree fdecl)
{
if (TREE_CODE (fdecl) == FIELD_DECL && DECL_SIZE (fdecl)
&& integer_zerop (DECL_SIZE (fdecl)))
return true;
return false;
}
/* Return true if TYPE is zero sized. */
static bool
zero_sized_type (const_tree type)
{
if (AGGREGATE_TYPE_P (type) && TYPE_SIZE (type)
&& integer_zerop (TYPE_SIZE (type)))
return true;
return false;
}
/* A subroutine of gimplify_init_constructor. Generate individual
MODIFY_EXPRs for a CONSTRUCTOR. OBJECT is the LHS against which the
assignments should happen. ELTS is the CONSTRUCTOR_ELTS of the
CONSTRUCTOR. CLEARED is true if the entire LHS object has been
zeroed first. */
static void
gimplify_init_ctor_eval (tree object, VEC(constructor_elt,gc) *elts,
gimple_seq *pre_p, bool cleared)
{
tree array_elt_type = NULL;
unsigned HOST_WIDE_INT ix;
tree purpose, value;
if (TREE_CODE (TREE_TYPE (object)) == ARRAY_TYPE)
array_elt_type = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (object)));
FOR_EACH_CONSTRUCTOR_ELT (elts, ix, purpose, value)
{
tree cref;
/* NULL values are created above for gimplification errors. */
if (value == NULL)
continue;
if (cleared && initializer_zerop (value))
continue;
/* ??? Here's to hoping the front end fills in all of the indices,
so we don't have to figure out what's missing ourselves. */
gcc_assert (purpose);
/* Skip zero-sized fields, unless value has side-effects. This can
happen with calls to functions returning a zero-sized type, which
we shouldn't discard. As a number of downstream passes don't
expect sets of zero-sized fields, we rely on the gimplification of
the MODIFY_EXPR we make below to drop the assignment statement. */
if (! TREE_SIDE_EFFECTS (value) && zero_sized_field_decl (purpose))
continue;
/* If we have a RANGE_EXPR, we have to build a loop to assign the
whole range. */
if (TREE_CODE (purpose) == RANGE_EXPR)
{
tree lower = TREE_OPERAND (purpose, 0);
tree upper = TREE_OPERAND (purpose, 1);
/* If the lower bound is equal to upper, just treat it as if
upper was the index. */
if (simple_cst_equal (lower, upper))
purpose = upper;
else
{
gimplify_init_ctor_eval_range (object, lower, upper, value,
array_elt_type, pre_p, cleared);
continue;
}
}
if (array_elt_type)
{
/* Do not use bitsizetype for ARRAY_REF indices. */
if (TYPE_DOMAIN (TREE_TYPE (object)))
purpose = fold_convert (TREE_TYPE (TYPE_DOMAIN (TREE_TYPE (object))),
purpose);
cref = build4 (ARRAY_REF, array_elt_type, unshare_expr (object),
purpose, NULL_TREE, NULL_TREE);
}
else
{
gcc_assert (TREE_CODE (purpose) == FIELD_DECL);
cref = build3 (COMPONENT_REF, TREE_TYPE (purpose),
unshare_expr (object), purpose, NULL_TREE);
}
if (TREE_CODE (value) == CONSTRUCTOR
&& TREE_CODE (TREE_TYPE (value)) != VECTOR_TYPE)
gimplify_init_ctor_eval (cref, CONSTRUCTOR_ELTS (value),
pre_p, cleared);
else
{
tree init = build2 (INIT_EXPR, TREE_TYPE (cref), cref, value);
gimplify_and_add (init, pre_p);
ggc_free (init);
}
}
}
/* Returns the appropriate RHS predicate for this LHS. */
gimple_predicate
rhs_predicate_for (tree lhs)
{
if (is_gimple_formal_tmp_var (lhs))
return is_gimple_formal_tmp_or_call_rhs;
else if (is_gimple_reg (lhs))
return is_gimple_reg_or_call_rhs;
else
return is_gimple_mem_or_call_rhs;
}
/* A subroutine of gimplify_modify_expr. Break out elements of a
CONSTRUCTOR used as an initializer into separate MODIFY_EXPRs.
Note that we still need to clear any elements that don't have explicit
initializers, so if not all elements are initialized we keep the
original MODIFY_EXPR, we just remove all of the constructor elements.
If NOTIFY_TEMP_CREATION is true, do not gimplify, just return
GS_ERROR if we would have to create a temporary when gimplifying
this constructor. Otherwise, return GS_OK.
If NOTIFY_TEMP_CREATION is false, just do the gimplification. */
static enum gimplify_status
gimplify_init_constructor (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p,
bool want_value, bool notify_temp_creation)
{
tree object;
tree ctor = TREE_OPERAND (*expr_p, 1);
tree type = TREE_TYPE (ctor);
enum gimplify_status ret;
VEC(constructor_elt,gc) *elts;
if (TREE_CODE (ctor) != CONSTRUCTOR)
return GS_UNHANDLED;
if (!notify_temp_creation)
{
ret = gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p,
is_gimple_lvalue, fb_lvalue);
if (ret == GS_ERROR)
return ret;
}
object = TREE_OPERAND (*expr_p, 0);
elts = CONSTRUCTOR_ELTS (ctor);
ret = GS_ALL_DONE;
switch (TREE_CODE (type))
{
case RECORD_TYPE:
case UNION_TYPE:
case QUAL_UNION_TYPE:
case ARRAY_TYPE:
{
struct gimplify_init_ctor_preeval_data preeval_data;
HOST_WIDE_INT num_type_elements, num_ctor_elements;
HOST_WIDE_INT num_nonzero_elements;
bool cleared, valid_const_initializer;
/* Aggregate types must lower constructors to initialization of
individual elements. The exception is that a CONSTRUCTOR node
with no elements indicates zero-initialization of the whole. */
if (VEC_empty (constructor_elt, elts))
{
if (notify_temp_creation)
return GS_OK;
break;
}
/* Fetch information about the constructor to direct later processing.
We might want to make static versions of it in various cases, and
can only do so if it known to be a valid constant initializer. */
valid_const_initializer
= categorize_ctor_elements (ctor, &num_nonzero_elements,
&num_ctor_elements, &cleared);
/* If a const aggregate variable is being initialized, then it
should never be a lose to promote the variable to be static. */
if (valid_const_initializer
&& num_nonzero_elements > 1
&& TREE_READONLY (object)
&& TREE_CODE (object) == VAR_DECL
&& (flag_merge_constants >= 2 || !TREE_ADDRESSABLE (object)))
{
if (notify_temp_creation)
return GS_ERROR;
DECL_INITIAL (object) = ctor;
TREE_STATIC (object) = 1;
if (!DECL_NAME (object))
DECL_NAME (object) = create_tmp_var_name ("C");
walk_tree (&DECL_INITIAL (object), force_labels_r, NULL, NULL);
/* ??? C++ doesn't automatically append a .<number> to the
assembler name, and even when it does, it looks a FE private
data structures to figure out what that number should be,
which are not set for this variable. I suppose this is
important for local statics for inline functions, which aren't
"local" in the object file sense. So in order to get a unique
TU-local symbol, we must invoke the lhd version now. */
lhd_set_decl_assembler_name (object);
*expr_p = NULL_TREE;
break;
}
/* If there are "lots" of initialized elements, even discounting
those that are not address constants (and thus *must* be
computed at runtime), then partition the constructor into
constant and non-constant parts. Block copy the constant
parts in, then generate code for the non-constant parts. */
/* TODO. There's code in cp/typeck.c to do this. */
num_type_elements = count_type_elements (type, true);
/* If count_type_elements could not determine number of type elements
for a constant-sized object, assume clearing is needed.
Don't do this for variable-sized objects, as store_constructor
will ignore the clearing of variable-sized objects. */
if (num_type_elements < 0 && int_size_in_bytes (type) >= 0)
cleared = true;
/* If there are "lots" of zeros, then block clear the object first. */
else if (num_type_elements - num_nonzero_elements
> CLEAR_RATIO (optimize_function_for_speed_p (cfun))
&& num_nonzero_elements < num_type_elements/4)
cleared = true;
/* ??? This bit ought not be needed. For any element not present
in the initializer, we should simply set them to zero. Except
we'd need to *find* the elements that are not present, and that
requires trickery to avoid quadratic compile-time behavior in
large cases or excessive memory use in small cases. */
else if (num_ctor_elements < num_type_elements)
cleared = true;
/* If there are "lots" of initialized elements, and all of them
are valid address constants, then the entire initializer can
be dropped to memory, and then memcpy'd out. Don't do this
for sparse arrays, though, as it's more efficient to follow
the standard CONSTRUCTOR behavior of memset followed by
individual element initialization. Also don't do this for small
all-zero initializers (which aren't big enough to merit
clearing), and don't try to make bitwise copies of
TREE_ADDRESSABLE types. */
if (valid_const_initializer
&& !(cleared || num_nonzero_elements == 0)
&& !TREE_ADDRESSABLE (type))
{
HOST_WIDE_INT size = int_size_in_bytes (type);
unsigned int align;
/* ??? We can still get unbounded array types, at least
from the C++ front end. This seems wrong, but attempt
to work around it for now. */
if (size < 0)
{
size = int_size_in_bytes (TREE_TYPE (object));
if (size >= 0)
TREE_TYPE (ctor) = type = TREE_TYPE (object);
}
/* Find the maximum alignment we can assume for the object. */
/* ??? Make use of DECL_OFFSET_ALIGN. */
if (DECL_P (object))
align = DECL_ALIGN (object);
else
align = TYPE_ALIGN (type);
if (size > 0
&& num_nonzero_elements > 1
&& !can_move_by_pieces (size, align))
{
tree new_tree;
if (notify_temp_creation)
return GS_ERROR;
new_tree = create_tmp_var_raw (type, "C");
gimple_add_tmp_var (new_tree);
TREE_STATIC (new_tree) = 1;
TREE_READONLY (new_tree) = 1;
DECL_INITIAL (new_tree) = ctor;
if (align > DECL_ALIGN (new_tree))
{
DECL_ALIGN (new_tree) = align;
DECL_USER_ALIGN (new_tree) = 1;
}
walk_tree (&DECL_INITIAL (new_tree), force_labels_r, NULL, NULL);
TREE_OPERAND (*expr_p, 1) = new_tree;
/* This is no longer an assignment of a CONSTRUCTOR, but
we still may have processing to do on the LHS. So
pretend we didn't do anything here to let that happen. */
return GS_UNHANDLED;
}
}
/* If the target is volatile, we have non-zero elements and more than
one field to assign, initialize the target from a temporary. */
if (TREE_THIS_VOLATILE (object)
&& !TREE_ADDRESSABLE (type)
&& num_nonzero_elements > 0
&& VEC_length (constructor_elt, elts) > 1)
{
tree temp = create_tmp_var (TYPE_MAIN_VARIANT (type), NULL);
TREE_OPERAND (*expr_p, 0) = temp;
*expr_p = build2 (COMPOUND_EXPR, TREE_TYPE (*expr_p),
*expr_p,
build2 (MODIFY_EXPR, void_type_node,
object, temp));
return GS_OK;
}
if (notify_temp_creation)
return GS_OK;
/* If there are nonzero elements, pre-evaluate to capture elements
overlapping with the lhs into temporaries. We must do this before
clearing to fetch the values before they are zeroed-out. */
if (num_nonzero_elements > 0)
{
preeval_data.lhs_base_decl = get_base_address (object);
if (!DECL_P (preeval_data.lhs_base_decl))
preeval_data.lhs_base_decl = NULL;
preeval_data.lhs_alias_set = get_alias_set (object);
gimplify_init_ctor_preeval (&TREE_OPERAND (*expr_p, 1),
pre_p, post_p, &preeval_data);
}
if (cleared)
{
/* Zap the CONSTRUCTOR element list, which simplifies this case.
Note that we still have to gimplify, in order to handle the
case of variable sized types. Avoid shared tree structures. */
CONSTRUCTOR_ELTS (ctor) = NULL;
TREE_SIDE_EFFECTS (ctor) = 0;
object = unshare_expr (object);
gimplify_stmt (expr_p, pre_p);
}
/* If we have not block cleared the object, or if there are nonzero
elements in the constructor, add assignments to the individual
scalar fields of the object. */
if (!cleared || num_nonzero_elements > 0)
gimplify_init_ctor_eval (object, elts, pre_p, cleared);
*expr_p = NULL_TREE;
}
break;
case COMPLEX_TYPE:
{
tree r, i;
if (notify_temp_creation)
return GS_OK;
/* Extract the real and imaginary parts out of the ctor. */
gcc_assert (VEC_length (constructor_elt, elts) == 2);
r = VEC_index (constructor_elt, elts, 0)->value;
i = VEC_index (constructor_elt, elts, 1)->value;
if (r == NULL || i == NULL)
{
tree zero = fold_convert (TREE_TYPE (type), integer_zero_node);
if (r == NULL)
r = zero;
if (i == NULL)
i = zero;
}
/* Complex types have either COMPLEX_CST or COMPLEX_EXPR to
represent creation of a complex value. */
if (TREE_CONSTANT (r) && TREE_CONSTANT (i))
{
ctor = build_complex (type, r, i);
TREE_OPERAND (*expr_p, 1) = ctor;
}
else
{
ctor = build2 (COMPLEX_EXPR, type, r, i);
TREE_OPERAND (*expr_p, 1) = ctor;
ret = gimplify_expr (&TREE_OPERAND (*expr_p, 1),
pre_p,
post_p,
rhs_predicate_for (TREE_OPERAND (*expr_p, 0)),
fb_rvalue);
}
}
break;
case VECTOR_TYPE:
{
unsigned HOST_WIDE_INT ix;
constructor_elt *ce;
if (notify_temp_creation)
return GS_OK;
/* Go ahead and simplify constant constructors to VECTOR_CST. */
if (TREE_CONSTANT (ctor))
{
bool constant_p = true;
tree value;
/* Even when ctor is constant, it might contain non-*_CST
elements, such as addresses or trapping values like
1.0/0.0 - 1.0/0.0. Such expressions don't belong
in VECTOR_CST nodes. */
FOR_EACH_CONSTRUCTOR_VALUE (elts, ix, value)
if (!CONSTANT_CLASS_P (value))
{
constant_p = false;
break;
}
if (constant_p)
{
TREE_OPERAND (*expr_p, 1) = build_vector_from_ctor (type, elts);
break;
}
/* Don't reduce an initializer constant even if we can't
make a VECTOR_CST. It won't do anything for us, and it'll
prevent us from representing it as a single constant. */
if (initializer_constant_valid_p (ctor, type))
break;
TREE_CONSTANT (ctor) = 0;
}
/* Vector types use CONSTRUCTOR all the way through gimple
compilation as a general initializer. */
for (ix = 0; VEC_iterate (constructor_elt, elts, ix, ce); ix++)
{
enum gimplify_status tret;
tret = gimplify_expr (&ce->value, pre_p, post_p, is_gimple_val,
fb_rvalue);
if (tret == GS_ERROR)
ret = GS_ERROR;
}
if (!is_gimple_reg (TREE_OPERAND (*expr_p, 0)))
TREE_OPERAND (*expr_p, 1) = get_formal_tmp_var (ctor, pre_p);
}
break;
default:
/* So how did we get a CONSTRUCTOR for a scalar type? */
gcc_unreachable ();
}
if (ret == GS_ERROR)
return GS_ERROR;
else if (want_value)
{
*expr_p = object;
return GS_OK;
}
else
{
/* If we have gimplified both sides of the initializer but have
not emitted an assignment, do so now. */
if (*expr_p)
{
tree lhs = TREE_OPERAND (*expr_p, 0);
tree rhs = TREE_OPERAND (*expr_p, 1);
gimple init = gimple_build_assign (lhs, rhs);
gimplify_seq_add_stmt (pre_p, init);
*expr_p = NULL;
}
return GS_ALL_DONE;
}
}
/* Given a pointer value OP0, return a simplified version of an
indirection through OP0, or NULL_TREE if no simplification is
possible. Note that the resulting type may be different from
the type pointed to in the sense that it is still compatible
from the langhooks point of view. */
tree
gimple_fold_indirect_ref (tree t)
{
tree type = TREE_TYPE (TREE_TYPE (t));
tree sub = t;
tree subtype;
STRIP_USELESS_TYPE_CONVERSION (sub);
subtype = TREE_TYPE (sub);
if (!POINTER_TYPE_P (subtype))
return NULL_TREE;
if (TREE_CODE (sub) == ADDR_EXPR)
{
tree op = TREE_OPERAND (sub, 0);
tree optype = TREE_TYPE (op);
/* *&p => p */
if (useless_type_conversion_p (type, optype))
return op;
/* *(foo *)&fooarray => fooarray[0] */
if (TREE_CODE (optype) == ARRAY_TYPE
&& TREE_CODE (TYPE_SIZE (TREE_TYPE (optype))) == INTEGER_CST
&& useless_type_conversion_p (type, TREE_TYPE (optype)))
{
tree type_domain = TYPE_DOMAIN (optype);
tree min_val = size_zero_node;
if (type_domain && TYPE_MIN_VALUE (type_domain))
min_val = TYPE_MIN_VALUE (type_domain);
if (TREE_CODE (min_val) == INTEGER_CST)
return build4 (ARRAY_REF, type, op, min_val, NULL_TREE, NULL_TREE);
}
}
/* *(foo *)fooarrptr => (*fooarrptr)[0] */
if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
&& TREE_CODE (TYPE_SIZE (TREE_TYPE (TREE_TYPE (subtype)))) == INTEGER_CST
&& useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (subtype))))
{
tree type_domain;
tree min_val = size_zero_node;
tree osub = sub;
sub = gimple_fold_indirect_ref (sub);
if (! sub)
sub = build1 (INDIRECT_REF, TREE_TYPE (subtype), osub);
type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
if (type_domain && TYPE_MIN_VALUE (type_domain))
min_val = TYPE_MIN_VALUE (type_domain);
if (TREE_CODE (min_val) == INTEGER_CST)
return build4 (ARRAY_REF, type, sub, min_val, NULL_TREE, NULL_TREE);
}
return NULL_TREE;
}
/* Given a pointer value OP0, return a simplified version of an
indirection through OP0, or NULL_TREE if no simplification is
possible. This may only be applied to a rhs of an expression.
Note that the resulting type may be different from the type pointed
to in the sense that it is still compatible from the langhooks
point of view. */
static tree
gimple_fold_indirect_ref_rhs (tree t)
{
return gimple_fold_indirect_ref (t);
}
/* Subroutine of gimplify_modify_expr to do simplifications of
MODIFY_EXPRs based on the code of the RHS. We loop for as long as
something changes. */
static enum gimplify_status
gimplify_modify_expr_rhs (tree *expr_p, tree *from_p, tree *to_p,
gimple_seq *pre_p, gimple_seq *post_p,
bool want_value)
{
enum gimplify_status ret = GS_OK;
while (ret != GS_UNHANDLED)
switch (TREE_CODE (*from_p))
{
case VAR_DECL:
/* If we're assigning from a read-only variable initialized with
a constructor, do the direct assignment from the constructor,
but only if neither source nor target are volatile since this
latter assignment might end up being done on a per-field basis. */
if (DECL_INITIAL (*from_p)
&& TREE_READONLY (*from_p)
&& !TREE_THIS_VOLATILE (*from_p)
&& !TREE_THIS_VOLATILE (*to_p)
&& TREE_CODE (DECL_INITIAL (*from_p)) == CONSTRUCTOR)
{
tree old_from = *from_p;
/* Move the constructor into the RHS. */
*from_p = unshare_expr (DECL_INITIAL (*from_p));
/* Let's see if gimplify_init_constructor will need to put
it in memory. If so, revert the change. */
ret = gimplify_init_constructor (expr_p, NULL, NULL, false, true);
if (ret == GS_ERROR)
{
*from_p = old_from;
/* Fall through. */
}
else
{
ret = GS_OK;
break;
}
}
ret = GS_UNHANDLED;
break;
case INDIRECT_REF:
{
/* If we have code like
*(const A*)(A*)&x
where the type of "x" is a (possibly cv-qualified variant
of "A"), treat the entire expression as identical to "x".
This kind of code arises in C++ when an object is bound
to a const reference, and if "x" is a TARGET_EXPR we want
to take advantage of the optimization below. */
tree t = gimple_fold_indirect_ref_rhs (TREE_OPERAND (*from_p, 0));
if (t)
{
*from_p = t;
ret = GS_OK;
}
else
ret = GS_UNHANDLED;
break;
}
case TARGET_EXPR:
{
/* If we are initializing something from a TARGET_EXPR, strip the
TARGET_EXPR and initialize it directly, if possible. This can't
be done if the initializer is void, since that implies that the
temporary is set in some non-trivial way.
??? What about code that pulls out the temp and uses it
elsewhere? I think that such code never uses the TARGET_EXPR as
an initializer. If I'm wrong, we'll die because the temp won't
have any RTL. In that case, I guess we'll need to replace
references somehow. */
tree init = TARGET_EXPR_INITIAL (*from_p);
if (init
&& !VOID_TYPE_P (TREE_TYPE (init)))
{
*from_p = init;
ret = GS_OK;
}
else
ret = GS_UNHANDLED;
}
break;
case COMPOUND_EXPR:
/* Remove any COMPOUND_EXPR in the RHS so the following cases will be
caught. */
gimplify_compound_expr (from_p, pre_p, true);
ret = GS_OK;
break;
case CONSTRUCTOR:
/* If we're initializing from a CONSTRUCTOR, break this into
individual MODIFY_EXPRs. */
return gimplify_init_constructor (expr_p, pre_p, post_p, want_value,
false);
case COND_EXPR:
/* If we're assigning to a non-register type, push the assignment
down into the branches. This is mandatory for ADDRESSABLE types,
since we cannot generate temporaries for such, but it saves a
copy in other cases as well. */
if (!is_gimple_reg_type (TREE_TYPE (*from_p)))
{
/* This code should mirror the code in gimplify_cond_expr. */
enum tree_code code = TREE_CODE (*expr_p);
tree cond = *from_p;
tree result = *to_p;
ret = gimplify_expr (&result, pre_p, post_p,
is_gimple_lvalue, fb_lvalue);
if (ret != GS_ERROR)
ret = GS_OK;
if (TREE_TYPE (TREE_OPERAND (cond, 1)) != void_type_node)
TREE_OPERAND (cond, 1)
= build2 (code, void_type_node, result,
TREE_OPERAND (cond, 1));
if (TREE_TYPE (TREE_OPERAND (cond, 2)) != void_type_node)
TREE_OPERAND (cond, 2)
= build2 (code, void_type_node, unshare_expr (result),
TREE_OPERAND (cond, 2));
TREE_TYPE (cond) = void_type_node;
recalculate_side_effects (cond);
if (want_value)
{
gimplify_and_add (cond, pre_p);
*expr_p = unshare_expr (result);
}
else
*expr_p = cond;
return ret;
}
else
ret = GS_UNHANDLED;
break;
case CALL_EXPR:
/* For calls that return in memory, give *to_p as the CALL_EXPR's
return slot so that we don't generate a temporary. */
if (!CALL_EXPR_RETURN_SLOT_OPT (*from_p)
&& aggregate_value_p (*from_p, *from_p))
{
bool use_target;
if (!(rhs_predicate_for (*to_p))(*from_p))
/* If we need a temporary, *to_p isn't accurate. */
use_target = false;
else if (TREE_CODE (*to_p) == RESULT_DECL
&& DECL_NAME (*to_p) == NULL_TREE
&& needs_to_live_in_memory (*to_p))
/* It's OK to use the return slot directly unless it's an NRV. */
use_target = true;
else if (is_gimple_reg_type (TREE_TYPE (*to_p))
|| (DECL_P (*to_p) && DECL_REGISTER (*to_p)))
/* Don't force regs into memory. */
use_target = false;
else if (TREE_CODE (*to_p) == VAR_DECL
&& DECL_GIMPLE_FORMAL_TEMP_P (*to_p))
/* Don't use the original target if it's a formal temp; we
don't want to take their addresses. */
use_target = false;
else if (TREE_CODE (*expr_p) == INIT_EXPR)
/* It's OK to use the target directly if it's being
initialized. */
use_target = true;
else if (!is_gimple_non_addressable (*to_p))
/* Don't use the original target if it's already addressable;
if its address escapes, and the called function uses the
NRV optimization, a conforming program could see *to_p
change before the called function returns; see c++/19317.
When optimizing, the return_slot pass marks more functions
as safe after we have escape info. */
use_target = false;
else
use_target = true;
if (use_target)
{
CALL_EXPR_RETURN_SLOT_OPT (*from_p) = 1;
mark_addressable (*to_p);
}
}
ret = GS_UNHANDLED;
break;
/* If we're initializing from a container, push the initialization
inside it. */
case CLEANUP_POINT_EXPR:
case BIND_EXPR:
case STATEMENT_LIST:
{
tree wrap = *from_p;
tree t;
ret = gimplify_expr (to_p, pre_p, post_p, is_gimple_min_lval,
fb_lvalue);
if (ret != GS_ERROR)
ret = GS_OK;
t = voidify_wrapper_expr (wrap, *expr_p);
gcc_assert (t == *expr_p);
if (want_value)
{
gimplify_and_add (wrap, pre_p);
*expr_p = unshare_expr (*to_p);
}
else
*expr_p = wrap;
return GS_OK;
}
default:
ret = GS_UNHANDLED;
break;
}
return ret;
}
/* Promote partial stores to COMPLEX variables to total stores. *EXPR_P is
a MODIFY_EXPR with a lhs of a REAL/IMAGPART_EXPR of a variable with
DECL_GIMPLE_REG_P set.
IMPORTANT NOTE: This promotion is performed by introducing a load of the
other, unmodified part of the complex object just before the total store.
As a consequence, if the object is still uninitialized, an undefined value
will be loaded into a register, which may result in a spurious exception
if the register is floating-point and the value happens to be a signaling
NaN for example. Then the fully-fledged complex operations lowering pass
followed by a DCE pass are necessary in order to fix things up. */
static enum gimplify_status
gimplify_modify_expr_complex_part (tree *expr_p, gimple_seq *pre_p,
bool want_value)
{
enum tree_code code, ocode;
tree lhs, rhs, new_rhs, other, realpart, imagpart;
lhs = TREE_OPERAND (*expr_p, 0);
rhs = TREE_OPERAND (*expr_p, 1);
code = TREE_CODE (lhs);
lhs = TREE_OPERAND (lhs, 0);
ocode = code == REALPART_EXPR ? IMAGPART_EXPR : REALPART_EXPR;
other = build1 (ocode, TREE_TYPE (rhs), lhs);
other = get_formal_tmp_var (other, pre_p);
realpart = code == REALPART_EXPR ? rhs : other;
imagpart = code == REALPART_EXPR ? other : rhs;
if (TREE_CONSTANT (realpart) && TREE_CONSTANT (imagpart))
new_rhs = build_complex (TREE_TYPE (lhs), realpart, imagpart);
else
new_rhs = build2 (COMPLEX_EXPR, TREE_TYPE (lhs), realpart, imagpart);
gimplify_seq_add_stmt (pre_p, gimple_build_assign (lhs, new_rhs));
*expr_p = (want_value) ? rhs : NULL_TREE;
return GS_ALL_DONE;
}
/* Gimplify the MODIFY_EXPR node pointed to by EXPR_P.
modify_expr
: varname '=' rhs
| '*' ID '=' rhs
PRE_P points to the list where side effects that must happen before
*EXPR_P should be stored.
POST_P points to the list where side effects that must happen after
*EXPR_P should be stored.
WANT_VALUE is nonzero iff we want to use the value of this expression
in another expression. */
static enum gimplify_status
gimplify_modify_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p,
bool want_value)
{
tree *from_p = &TREE_OPERAND (*expr_p, 1);
tree *to_p = &TREE_OPERAND (*expr_p, 0);
enum gimplify_status ret = GS_UNHANDLED;
gimple assign;
gcc_assert (TREE_CODE (*expr_p) == MODIFY_EXPR
|| TREE_CODE (*expr_p) == INIT_EXPR);
/* Insert pointer conversions required by the middle-end that are not
required by the frontend. This fixes middle-end type checking for
for example gcc.dg/redecl-6.c. */
if (POINTER_TYPE_P (TREE_TYPE (*to_p))
&& lang_hooks.types_compatible_p (TREE_TYPE (*to_p), TREE_TYPE (*from_p)))
{
STRIP_USELESS_TYPE_CONVERSION (*from_p);
if (!useless_type_conversion_p (TREE_TYPE (*to_p), TREE_TYPE (*from_p)))
*from_p = fold_convert (TREE_TYPE (*to_p), *from_p);
}
/* See if any simplifications can be done based on what the RHS is. */
ret = gimplify_modify_expr_rhs (expr_p, from_p, to_p, pre_p, post_p,
want_value);
if (ret != GS_UNHANDLED)
return ret;
/* For zero sized types only gimplify the left hand side and right hand
side as statements and throw away the assignment. Do this after
gimplify_modify_expr_rhs so we handle TARGET_EXPRs of addressable
types properly. */
if (zero_sized_type (TREE_TYPE (*from_p)) && !want_value)
{
gimplify_stmt (from_p, pre_p);
gimplify_stmt (to_p, pre_p);
*expr_p = NULL_TREE;
return GS_ALL_DONE;
}
/* If the value being copied is of variable width, compute the length
of the copy into a WITH_SIZE_EXPR. Note that we need to do this
before gimplifying any of the operands so that we can resolve any
PLACEHOLDER_EXPRs in the size. Also note that the RTL expander uses
the size of the expression to be copied, not of the destination, so
that is what we must do here. */
maybe_with_size_expr (from_p);
ret = gimplify_expr (to_p, pre_p, post_p, is_gimple_lvalue, fb_lvalue);
if (ret == GS_ERROR)
return ret;
/* As a special case, we have to temporarily allow for assignments
with a CALL_EXPR on the RHS. Since in GIMPLE a function call is
a toplevel statement, when gimplifying the GENERIC expression
MODIFY_EXPR <a, CALL_EXPR <foo>>, we cannot create the tuple
GIMPLE_ASSIGN <a, GIMPLE_CALL <foo>>.
Instead, we need to create the tuple GIMPLE_CALL <a, foo>. To
prevent gimplify_expr from trying to create a new temporary for
foo's LHS, we tell it that it should only gimplify until it
reaches the CALL_EXPR. On return from gimplify_expr, the newly
created GIMPLE_CALL <foo> will be the last statement in *PRE_P
and all we need to do here is set 'a' to be its LHS. */
ret = gimplify_expr (from_p, pre_p, post_p, rhs_predicate_for (*to_p),
fb_rvalue);
if (ret == GS_ERROR)
return ret;
/* Now see if the above changed *from_p to something we handle specially. */
ret = gimplify_modify_expr_rhs (expr_p, from_p, to_p, pre_p, post_p,
want_value);
if (ret != GS_UNHANDLED)
return ret;
/* If we've got a variable sized assignment between two lvalues (i.e. does
not involve a call), then we can make things a bit more straightforward
by converting the assignment to memcpy or memset. */
if (TREE_CODE (*from_p) == WITH_SIZE_EXPR)
{
tree from = TREE_OPERAND (*from_p, 0);
tree size = TREE_OPERAND (*from_p, 1);
if (TREE_CODE (from) == CONSTRUCTOR)
return gimplify_modify_expr_to_memset (expr_p, size, want_value, pre_p);
if (is_gimple_addressable (from))
{
*from_p = from;
return gimplify_modify_expr_to_memcpy (expr_p, size, want_value,
pre_p);
}
}
/* Transform partial stores to non-addressable complex variables into
total stores. This allows us to use real instead of virtual operands
for these variables, which improves optimization. */
if ((TREE_CODE (*to_p) == REALPART_EXPR
|| TREE_CODE (*to_p) == IMAGPART_EXPR)
&& is_gimple_reg (TREE_OPERAND (*to_p, 0)))
return gimplify_modify_expr_complex_part (expr_p, pre_p, want_value);
/* Try to alleviate the effects of the gimplification creating artificial
temporaries (see for example is_gimple_reg_rhs) on the debug info. */
if (!gimplify_ctxp->into_ssa
&& DECL_P (*from_p)
&& DECL_IGNORED_P (*from_p)
&& DECL_P (*to_p)
&& !DECL_IGNORED_P (*to_p))
{
if (!DECL_NAME (*from_p) && DECL_NAME (*to_p))
DECL_NAME (*from_p)
= create_tmp_var_name (IDENTIFIER_POINTER (DECL_NAME (*to_p)));
DECL_DEBUG_EXPR_IS_FROM (*from_p) = 1;
SET_DECL_DEBUG_EXPR (*from_p, *to_p);
}
if (TREE_CODE (*from_p) == CALL_EXPR)
{
/* Since the RHS is a CALL_EXPR, we need to create a GIMPLE_CALL
instead of a GIMPLE_ASSIGN. */
assign = gimple_build_call_from_tree (*from_p);
gimple_call_set_lhs (assign, *to_p);
}
else
assign = gimple_build_assign (*to_p, *from_p);
gimplify_seq_add_stmt (pre_p, assign);
if (gimplify_ctxp->into_ssa && is_gimple_reg (*to_p))
{
/* If we've somehow already got an SSA_NAME on the LHS, then
we've probably modified it twice. Not good. */
gcc_assert (TREE_CODE (*to_p) != SSA_NAME);
*to_p = make_ssa_name (*to_p, assign);
gimple_set_lhs (assign, *to_p);
}
if (want_value)
{
*expr_p = unshare_expr (*to_p);
return GS_OK;
}
else
*expr_p = NULL;
return GS_ALL_DONE;
}
/* Gimplify a comparison between two variable-sized objects. Do this
with a call to BUILT_IN_MEMCMP. */
static enum gimplify_status
gimplify_variable_sized_compare (tree *expr_p)
{
tree op0 = TREE_OPERAND (*expr_p, 0);
tree op1 = TREE_OPERAND (*expr_p, 1);
tree t, arg, dest, src;
arg = TYPE_SIZE_UNIT (TREE_TYPE (op0));
arg = unshare_expr (arg);
arg = SUBSTITUTE_PLACEHOLDER_IN_EXPR (arg, op0);
src = build_fold_addr_expr (op1);
dest = build_fold_addr_expr (op0);
t = implicit_built_in_decls[BUILT_IN_MEMCMP];
t = build_call_expr (t, 3, dest, src, arg);
*expr_p
= build2 (TREE_CODE (*expr_p), TREE_TYPE (*expr_p), t, integer_zero_node);
return GS_OK;
}
/* Gimplify a comparison between two aggregate objects of integral scalar
mode as a comparison between the bitwise equivalent scalar values. */
static enum gimplify_status
gimplify_scalar_mode_aggregate_compare (tree *expr_p)
{
tree op0 = TREE_OPERAND (*expr_p, 0);
tree op1 = TREE_OPERAND (*expr_p, 1);
tree type = TREE_TYPE (op0);
tree scalar_type = lang_hooks.types.type_for_mode (TYPE_MODE (type), 1);
op0 = fold_build1 (VIEW_CONVERT_EXPR, scalar_type, op0);
op1 = fold_build1 (VIEW_CONVERT_EXPR, scalar_type, op1);
*expr_p
= fold_build2 (TREE_CODE (*expr_p), TREE_TYPE (*expr_p), op0, op1);
return GS_OK;
}
/* Gimplify TRUTH_ANDIF_EXPR and TRUTH_ORIF_EXPR expressions. EXPR_P
points to the expression to gimplify.
Expressions of the form 'a && b' are gimplified to:
a && b ? true : false
gimplify_cond_expr will do the rest.
PRE_P points to the list where side effects that must happen before
*EXPR_P should be stored. */
static enum gimplify_status
gimplify_boolean_expr (tree *expr_p)
{
/* Preserve the original type of the expression. */
tree type = TREE_TYPE (*expr_p);
*expr_p = build3 (COND_EXPR, type, *expr_p,
fold_convert (type, boolean_true_node),
fold_convert (type, boolean_false_node));
return GS_OK;
}
/* Gimplifies an expression sequence. This function gimplifies each
expression and re-writes the original expression with the last
expression of the sequence in GIMPLE form.
PRE_P points to the list where the side effects for all the
expressions in the sequence will be emitted.
WANT_VALUE is true when the result of the last COMPOUND_EXPR is used. */
static enum gimplify_status
gimplify_compound_expr (tree *expr_p, gimple_seq *pre_p, bool want_value)
{
tree t = *expr_p;
do
{
tree *sub_p = &TREE_OPERAND (t, 0);
if (TREE_CODE (*sub_p) == COMPOUND_EXPR)
gimplify_compound_expr (sub_p, pre_p, false);
else
gimplify_stmt (sub_p, pre_p);
t = TREE_OPERAND (t, 1);
}
while (TREE_CODE (t) == COMPOUND_EXPR);
*expr_p = t;
if (want_value)
return GS_OK;
else
{
gimplify_stmt (expr_p, pre_p);
return GS_ALL_DONE;
}
}
/* Gimplify a SAVE_EXPR node. EXPR_P points to the expression to
gimplify. After gimplification, EXPR_P will point to a new temporary
that holds the original value of the SAVE_EXPR node.
PRE_P points to the list where side effects that must happen before
*EXPR_P should be stored. */
static enum gimplify_status
gimplify_save_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p)
{
enum gimplify_status ret = GS_ALL_DONE;
tree val;
gcc_assert (TREE_CODE (*expr_p) == SAVE_EXPR);
val = TREE_OPERAND (*expr_p, 0);
/* If the SAVE_EXPR has not been resolved, then evaluate it once. */
if (!SAVE_EXPR_RESOLVED_P (*expr_p))
{
/* The operand may be a void-valued expression such as SAVE_EXPRs
generated by the Java frontend for class initialization. It is
being executed only for its side-effects. */
if (TREE_TYPE (val) == void_type_node)
{
ret = gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p,
is_gimple_stmt, fb_none);
val = NULL;
}
else
val = get_initialized_tmp_var (val, pre_p, post_p);
TREE_OPERAND (*expr_p, 0) = val;
SAVE_EXPR_RESOLVED_P (*expr_p) = 1;
}
*expr_p = val;
return ret;
}
/* Re-write the ADDR_EXPR node pointed to by EXPR_P
unary_expr
: ...
| '&' varname
...
PRE_P points to the list where side effects that must happen before
*EXPR_P should be stored.
POST_P points to the list where side effects that must happen after
*EXPR_P should be stored. */
static enum gimplify_status
gimplify_addr_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p)
{
tree expr = *expr_p;
tree op0 = TREE_OPERAND (expr, 0);
enum gimplify_status ret;
switch (TREE_CODE (op0))
{
case INDIRECT_REF:
case MISALIGNED_INDIRECT_REF:
do_indirect_ref:
/* Check if we are dealing with an expression of the form '&*ptr'.
While the front end folds away '&*ptr' into 'ptr', these
expressions may be generated internally by the compiler (e.g.,
builtins like __builtin_va_end). */
/* Caution: the silent array decomposition semantics we allow for
ADDR_EXPR means we can't always discard the pair. */
/* Gimplification of the ADDR_EXPR operand may drop
cv-qualification conversions, so make sure we add them if
needed. */
{
tree op00 = TREE_OPERAND (op0, 0);
tree t_expr = TREE_TYPE (expr);
tree t_op00 = TREE_TYPE (op00);
if (!useless_type_conversion_p (t_expr, t_op00))
op00 = fold_convert (TREE_TYPE (expr), op00);
*expr_p = op00;
ret = GS_OK;
}
break;
case VIEW_CONVERT_EXPR:
/* Take the address of our operand and then convert it to the type of
this ADDR_EXPR.
??? The interactions of VIEW_CONVERT_EXPR and aliasing is not at
all clear. The impact of this transformation is even less clear. */
/* If the operand is a useless conversion, look through it. Doing so
guarantees that the ADDR_EXPR and its operand will remain of the
same type. */
if (tree_ssa_useless_type_conversion (TREE_OPERAND (op0, 0)))
op0 = TREE_OPERAND (op0, 0);
*expr_p = fold_convert (TREE_TYPE (expr),
build_fold_addr_expr (TREE_OPERAND (op0, 0)));
ret = GS_OK;
break;
default:
/* We use fb_either here because the C frontend sometimes takes
the address of a call that returns a struct; see
gcc.dg/c99-array-lval-1.c. The gimplifier will correctly make
the implied temporary explicit. */
/* Mark the RHS addressable. */
ret = gimplify_expr (&TREE_OPERAND (expr, 0), pre_p, post_p,
is_gimple_addressable, fb_either);
if (ret == GS_ERROR)
break;
/* We cannot rely on making the RHS addressable if it is
a temporary created by gimplification. In this case create a
new temporary that is initialized by a copy (which will
become a store after we mark it addressable).
This mostly happens if the frontend passed us something that
it could not mark addressable yet, like a fortran
pass-by-reference parameter (int) floatvar. */
if (is_gimple_formal_tmp_var (TREE_OPERAND (expr, 0)))
TREE_OPERAND (expr, 0)
= get_initialized_tmp_var (TREE_OPERAND (expr, 0), pre_p, post_p);
op0 = TREE_OPERAND (expr, 0);
/* For various reasons, the gimplification of the expression
may have made a new INDIRECT_REF. */
if (TREE_CODE (op0) == INDIRECT_REF)
goto do_indirect_ref;
/* Make sure TREE_CONSTANT and TREE_SIDE_EFFECTS are set properly. */
recompute_tree_invariant_for_addr_expr (expr);
mark_addressable (TREE_OPERAND (expr, 0));
break;
}
return ret;
}
/* Gimplify the operands of an ASM_EXPR. Input operands should be a gimple
value; output operands should be a gimple lvalue. */
static enum gimplify_status
gimplify_asm_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p)
{
tree expr;
int noutputs;
const char **oconstraints;
int i;
tree link;
const char *constraint;
bool allows_mem, allows_reg, is_inout;
enum gimplify_status ret, tret;
gimple stmt;
VEC(tree, gc) *inputs;
VEC(tree, gc) *outputs;
VEC(tree, gc) *clobbers;
tree link_next;
expr = *expr_p;
noutputs = list_length (ASM_OUTPUTS (expr));
oconstraints = (const char **) alloca ((noutputs) * sizeof (const char *));
inputs = outputs = clobbers = NULL;
ret = GS_ALL_DONE;
link_next = NULL_TREE;
for (i = 0, link = ASM_OUTPUTS (expr); link; ++i, link = link_next)
{
bool ok;
size_t constraint_len;
link_next = TREE_CHAIN (link);
oconstraints[i]
= constraint
= TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
constraint_len = strlen (constraint);
if (constraint_len == 0)
continue;
ok = parse_output_constraint (&constraint, i, 0, 0,
&allows_mem, &allows_reg, &is_inout);
if (!ok)
{
ret = GS_ERROR;
is_inout = false;
}
if (!allows_reg && allows_mem)
mark_addressable (TREE_VALUE (link));
tret = gimplify_expr (&TREE_VALUE (link), pre_p, post_p,
is_inout ? is_gimple_min_lval : is_gimple_lvalue,
fb_lvalue | fb_mayfail);
if (tret == GS_ERROR)
{
error ("invalid lvalue in asm output %d", i);
ret = tret;
}
VEC_safe_push (tree, gc, outputs, link);
TREE_CHAIN (link) = NULL_TREE;
if (is_inout)
{
/* An input/output operand. To give the optimizers more
flexibility, split it into separate input and output
operands. */
tree input;
char buf[10];
/* Turn the in/out constraint into an output constraint. */
char *p = xstrdup (constraint);
p[0] = '=';
TREE_VALUE (TREE_PURPOSE (link)) = build_string (constraint_len, p);
/* And add a matching input constraint. */
if (allows_reg)
{
sprintf (buf, "%d", i);
/* If there are multiple alternatives in the constraint,
handle each of them individually. Those that allow register
will be replaced with operand number, the others will stay
unchanged. */
if (strchr (p, ',') != NULL)
{
size_t len = 0, buflen = strlen (buf);
char *beg, *end, *str, *dst;
for (beg = p + 1;;)
{
end = strchr (beg, ',');
if (end == NULL)
end = strchr (beg, '\0');
if ((size_t) (end - beg) < buflen)
len += buflen + 1;
else
len += end - beg + 1;
if (*end)
beg = end + 1;
else
break;
}
str = (char *) alloca (len);
for (beg = p + 1, dst = str;;)
{
const char *tem;
bool mem_p, reg_p, inout_p;
end = strchr (beg, ',');
if (end)
*end = '\0';
beg[-1] = '=';
tem = beg - 1;
parse_output_constraint (&tem, i, 0, 0,
&mem_p, ®_p, &inout_p);
if (dst != str)
*dst++ = ',';
if (reg_p)
{
memcpy (dst, buf, buflen);
dst += buflen;
}
else
{
if (end)
len = end - beg;
else
len = strlen (beg);
memcpy (dst, beg, len);
dst += len;
}
if (end)
beg = end + 1;
else
break;
}
*dst = '\0';
input = build_string (dst - str, str);
}
else
input = build_string (strlen (buf), buf);
}
else
input = build_string (constraint_len - 1, constraint + 1);
free (p);
input = build_tree_list (build_tree_list (NULL_TREE, input),
unshare_expr (TREE_VALUE (link)));
ASM_INPUTS (expr) = chainon (ASM_INPUTS (expr), input);
}
}
link_next = NULL_TREE;
for (link = ASM_INPUTS (expr); link; ++i, link = link_next)
{
link_next = TREE_CHAIN (link);
constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
parse_input_constraint (&constraint, 0, 0, noutputs, 0,
oconstraints, &allows_mem, &allows_reg);
/* If we can't make copies, we can only accept memory. */
if (TREE_ADDRESSABLE (TREE_TYPE (TREE_VALUE (link))))
{
if (allows_mem)
allows_reg = 0;
else
{
error ("impossible constraint in %<asm%>");
error ("non-memory input %d must stay in memory", i);
return GS_ERROR;
}
}
/* If the operand is a memory input, it should be an lvalue. */
if (!allows_reg && allows_mem)
{
tret = gimplify_expr (&TREE_VALUE (link), pre_p, post_p,
is_gimple_lvalue, fb_lvalue | fb_mayfail);
mark_addressable (TREE_VALUE (link));
if (tret == GS_ERROR)
{
if (EXPR_HAS_LOCATION (TREE_VALUE (link)))
input_location = EXPR_LOCATION (TREE_VALUE (link));
error ("memory input %d is not directly addressable", i);
ret = tret;
}
}
else
{
tret = gimplify_expr (&TREE_VALUE (link), pre_p, post_p,
is_gimple_asm_val, fb_rvalue);
if (tret == GS_ERROR)
ret = tret;
}
TREE_CHAIN (link) = NULL_TREE;
VEC_safe_push (tree, gc, inputs, link);
}
for (link = ASM_CLOBBERS (expr); link; ++i, link = TREE_CHAIN (link))
VEC_safe_push (tree, gc, clobbers, link);
stmt = gimple_build_asm_vec (TREE_STRING_POINTER (ASM_STRING (expr)),
inputs, outputs, clobbers);
gimple_asm_set_volatile (stmt, ASM_VOLATILE_P (expr));
gimple_asm_set_input (stmt, ASM_INPUT_P (expr));
gimplify_seq_add_stmt (pre_p, stmt);
return ret;
}
/* Gimplify a CLEANUP_POINT_EXPR. Currently this works by adding
GIMPLE_WITH_CLEANUP_EXPRs to the prequeue as we encounter cleanups while
gimplifying the body, and converting them to TRY_FINALLY_EXPRs when we
return to this function.
FIXME should we complexify the prequeue handling instead? Or use flags
for all the cleanups and let the optimizer tighten them up? The current
code seems pretty fragile; it will break on a cleanup within any
non-conditional nesting. But any such nesting would be broken, anyway;
we can't write a TRY_FINALLY_EXPR that starts inside a nesting construct
and continues out of it. We can do that at the RTL level, though, so
having an optimizer to tighten up try/finally regions would be a Good
Thing. */
static enum gimplify_status
gimplify_cleanup_point_expr (tree *expr_p, gimple_seq *pre_p)
{
gimple_stmt_iterator iter;
gimple_seq body_sequence = NULL;
tree temp = voidify_wrapper_expr (*expr_p, NULL);
/* We only care about the number of conditions between the innermost
CLEANUP_POINT_EXPR and the cleanup. So save and reset the count and
any cleanups collected outside the CLEANUP_POINT_EXPR. */
int old_conds = gimplify_ctxp->conditions;
gimple_seq old_cleanups = gimplify_ctxp->conditional_cleanups;
gimplify_ctxp->conditions = 0;
gimplify_ctxp->conditional_cleanups = NULL;
gimplify_stmt (&TREE_OPERAND (*expr_p, 0), &body_sequence);
gimplify_ctxp->conditions = old_conds;
gimplify_ctxp->conditional_cleanups = old_cleanups;
for (iter = gsi_start (body_sequence); !gsi_end_p (iter); )
{
gimple wce = gsi_stmt (iter);
if (gimple_code (wce) == GIMPLE_WITH_CLEANUP_EXPR)
{
if (gsi_one_before_end_p (iter))
{
/* Note that gsi_insert_seq_before and gsi_remove do not
scan operands, unlike some other sequence mutators. */
gsi_insert_seq_before_without_update (&iter,
gimple_wce_cleanup (wce),
GSI_SAME_STMT);
gsi_remove (&iter, true);
break;
}
else
{
gimple gtry;
gimple_seq seq;
enum gimple_try_flags kind;
if (gimple_wce_cleanup_eh_only (wce))
kind = GIMPLE_TRY_CATCH;
else
kind = GIMPLE_TRY_FINALLY;
seq = gsi_split_seq_after (iter);
gtry = gimple_build_try (seq, gimple_wce_cleanup (wce), kind);
/* Do not use gsi_replace here, as it may scan operands.
We want to do a simple structural modification only. */
*gsi_stmt_ptr (&iter) = gtry;
iter = gsi_start (seq);
}
}
else
gsi_next (&iter);
}
gimplify_seq_add_seq (pre_p, body_sequence);
if (temp)
{
*expr_p = temp;
return GS_OK;
}
else
{
*expr_p = NULL;
return GS_ALL_DONE;
}
}
/* Insert a cleanup marker for gimplify_cleanup_point_expr. CLEANUP
is the cleanup action required. EH_ONLY is true if the cleanup should
only be executed if an exception is thrown, not on normal exit. */
static void
gimple_push_cleanup (tree var, tree cleanup, bool eh_only, gimple_seq *pre_p)
{
gimple wce;
gimple_seq cleanup_stmts = NULL;
/* Errors can result in improperly nested cleanups. Which results in
confusion when trying to resolve the GIMPLE_WITH_CLEANUP_EXPR. */
if (errorcount || sorrycount)
return;
if (gimple_conditional_context ())
{
/* If we're in a conditional context, this is more complex. We only
want to run the cleanup if we actually ran the initialization that
necessitates it, but we want to run it after the end of the
conditional context. So we wrap the try/finally around the
condition and use a flag to determine whether or not to actually
run the destructor. Thus
test ? f(A()) : 0
becomes (approximately)
flag = 0;
try {
if (test) { A::A(temp); flag = 1; val = f(temp); }
else { val = 0; }
} finally {
if (flag) A::~A(temp);
}
val
*/
tree flag = create_tmp_var (boolean_type_node, "cleanup");
gimple ffalse = gimple_build_assign (flag, boolean_false_node);
gimple ftrue = gimple_build_assign (flag, boolean_true_node);
cleanup = build3 (COND_EXPR, void_type_node, flag, cleanup, NULL);
gimplify_stmt (&cleanup, &cleanup_stmts);
wce = gimple_build_wce (cleanup_stmts);
gimplify_seq_add_stmt (&gimplify_ctxp->conditional_cleanups, ffalse);
gimplify_seq_add_stmt (&gimplify_ctxp->conditional_cleanups, wce);
gimplify_seq_add_stmt (pre_p, ftrue);
/* Because of this manipulation, and the EH edges that jump
threading cannot redirect, the temporary (VAR) will appear
to be used uninitialized. Don't warn. */
TREE_NO_WARNING (var) = 1;
}
else
{
gimplify_stmt (&cleanup, &cleanup_stmts);
wce = gimple_build_wce (cleanup_stmts);
gimple_wce_set_cleanup_eh_only (wce, eh_only);
gimplify_seq_add_stmt (pre_p, wce);
}
}
/* Gimplify a TARGET_EXPR which doesn't appear on the rhs of an INIT_EXPR. */
static enum gimplify_status
gimplify_target_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p)
{
tree targ = *expr_p;
tree temp = TARGET_EXPR_SLOT (targ);
tree init = TARGET_EXPR_INITIAL (targ);
enum gimplify_status ret;
if (init)
{
/* TARGET_EXPR temps aren't part of the enclosing block, so add it
to the temps list. Handle also variable length TARGET_EXPRs. */
if (TREE_CODE (DECL_SIZE (temp)) != INTEGER_CST)
{
if (!TYPE_SIZES_GIMPLIFIED (TREE_TYPE (temp)))
gimplify_type_sizes (TREE_TYPE (temp), pre_p);
gimplify_vla_decl (temp, pre_p);
}
else
gimple_add_tmp_var (temp);
/* If TARGET_EXPR_INITIAL is void, then the mere evaluation of the
expression is supposed to initialize the slot. */
if (VOID_TYPE_P (TREE_TYPE (init)))
ret = gimplify_expr (&init, pre_p, post_p, is_gimple_stmt, fb_none);
else
{
tree init_expr = build2 (INIT_EXPR, void_type_node, temp, init);
init = init_expr;
ret = gimplify_expr (&init, pre_p, post_p, is_gimple_stmt, fb_none);
init = NULL;
ggc_free (init_expr);
}
if (ret == GS_ERROR)
{
/* PR c++/28266 Make sure this is expanded only once. */
TARGET_EXPR_INITIAL (targ) = NULL_TREE;
return GS_ERROR;
}
if (init)
gimplify_and_add (init, pre_p);
/* If needed, push the cleanup for the temp. */
if (TARGET_EXPR_CLEANUP (targ))
gimple_push_cleanup (temp, TARGET_EXPR_CLEANUP (targ),
CLEANUP_EH_ONLY (targ), pre_p);
/* Only expand this once. */
TREE_OPERAND (targ, 3) = init;
TARGET_EXPR_INITIAL (targ) = NULL_TREE;
}
else
/* We should have expanded this before. */
gcc_assert (DECL_SEEN_IN_BIND_EXPR_P (temp));
*expr_p = temp;
return GS_OK;
}
/* Gimplification of expression trees. */
/* Gimplify an expression which appears at statement context. The
corresponding GIMPLE statements are added to *SEQ_P. If *SEQ_P is
NULL, a new sequence is allocated.
Return true if we actually added a statement to the queue. */
bool
gimplify_stmt (tree *stmt_p, gimple_seq *seq_p)
{
gimple_seq_node last;
if (!*seq_p)
*seq_p = gimple_seq_alloc ();
last = gimple_seq_last (*seq_p);
gimplify_expr (stmt_p, seq_p, NULL, is_gimple_stmt, fb_none);
return last != gimple_seq_last (*seq_p);
}
/* Add FIRSTPRIVATE entries for DECL in the OpenMP the surrounding parallels
to CTX. If entries already exist, force them to be some flavor of private.
If there is no enclosing parallel, do nothing. */
void
omp_firstprivatize_variable (struct gimplify_omp_ctx *ctx, tree decl)
{
splay_tree_node n;
if (decl == NULL || !DECL_P (decl))
return;
do
{
n = splay_tree_lookup (ctx->variables, (splay_tree_key)decl);
if (n != NULL)
{
if (n->value & GOVD_SHARED)
n->value = GOVD_FIRSTPRIVATE | (n->value & GOVD_SEEN);
else
return;
}
else if (ctx->region_type != ORT_WORKSHARE)
omp_add_variable (ctx, decl, GOVD_FIRSTPRIVATE);
ctx = ctx->outer_context;
}
while (ctx);
}
/* Similarly for each of the type sizes of TYPE. */
static void
omp_firstprivatize_type_sizes (struct gimplify_omp_ctx *ctx, tree type)
{
if (type == NULL || type == error_mark_node)
return;
type = TYPE_MAIN_VARIANT (type);
if (pointer_set_insert (ctx->privatized_types, type))
return;
switch (TREE_CODE (type))
{
case INTEGER_TYPE:
case ENUMERAL_TYPE:
case BOOLEAN_TYPE:
case REAL_TYPE:
case FIXED_POINT_TYPE:
omp_firstprivatize_variable (ctx, TYPE_MIN_VALUE (type));
omp_firstprivatize_variable (ctx, TYPE_MAX_VALUE (type));
break;
case ARRAY_TYPE:
omp_firstprivatize_type_sizes (ctx, TREE_TYPE (type));
omp_firstprivatize_type_sizes (ctx, TYPE_DOMAIN (type));
break;
case RECORD_TYPE:
case UNION_TYPE:
case QUAL_UNION_TYPE:
{
tree field;
for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
if (TREE_CODE (field) == FIELD_DECL)
{
omp_firstprivatize_variable (ctx, DECL_FIELD_OFFSET (field));
omp_firstprivatize_type_sizes (ctx, TREE_TYPE (field));
}
}
break;
case POINTER_TYPE:
case REFERENCE_TYPE:
omp_firstprivatize_type_sizes (ctx, TREE_TYPE (type));
break;
default:
break;
}
omp_firstprivatize_variable (ctx, TYPE_SIZE (type));
omp_firstprivatize_variable (ctx, TYPE_SIZE_UNIT (type));
lang_hooks.types.omp_firstprivatize_type_sizes (ctx, type);
}
/* Add an entry for DECL in the OpenMP context CTX with FLAGS. */
static void
omp_add_variable (struct gimplify_omp_ctx *ctx, tree decl, unsigned int flags)
{
splay_tree_node n;
unsigned int nflags;
tree t;
if (decl == error_mark_node || TREE_TYPE (decl) == error_mark_node)
return;
/* Never elide decls whose type has TREE_ADDRESSABLE set. This means
there are constructors involved somewhere. */
if (TREE_ADDRESSABLE (TREE_TYPE (decl))
|| TYPE_NEEDS_CONSTRUCTING (TREE_TYPE (decl)))
flags |= GOVD_SEEN;
n = splay_tree_lookup (ctx->variables, (splay_tree_key)decl);
if (n != NULL)
{
/* We shouldn't be re-adding the decl with the same data
sharing class. */
gcc_assert ((n->value & GOVD_DATA_SHARE_CLASS & flags) == 0);
/* The only combination of data sharing classes we should see is
FIRSTPRIVATE and LASTPRIVATE. */
nflags = n->value | flags;
gcc_assert ((nflags & GOVD_DATA_SHARE_CLASS)
== (GOVD_FIRSTPRIVATE | GOVD_LASTPRIVATE));
n->value = nflags;
return;
}
/* When adding a variable-sized variable, we have to handle all sorts
of additional bits of data: the pointer replacement variable, and
the parameters of the type. */
if (DECL_SIZE (decl) && TREE_CODE (DECL_SIZE (decl)) != INTEGER_CST)
{
/* Add the pointer replacement variable as PRIVATE if the variable
replacement is private, else FIRSTPRIVATE since we'll need the
address of the original variable either for SHARED, or for the
copy into or out of the context. */
if (!(flags & GOVD_LOCAL))
{
nflags = flags & GOVD_PRIVATE ? GOVD_PRIVATE : GOVD_FIRSTPRIVATE;
nflags |= flags & GOVD_SEEN;
t = DECL_VALUE_EXPR (decl);
gcc_assert (TREE_CODE (t) == INDIRECT_REF);
t = TREE_OPERAND (t, 0);
gcc_assert (DECL_P (t));
omp_add_variable (ctx, t, nflags);
}
/* Add all of the variable and type parameters (which should have
been gimplified to a formal temporary) as FIRSTPRIVATE. */
omp_firstprivatize_variable (ctx, DECL_SIZE_UNIT (decl));
omp_firstprivatize_variable (ctx, DECL_SIZE (decl));
omp_firstprivatize_type_sizes (ctx, TREE_TYPE (decl));
/* The variable-sized variable itself is never SHARED, only some form
of PRIVATE. The sharing would take place via the pointer variable
which we remapped above. */
if (flags & GOVD_SHARED)
flags = GOVD_PRIVATE | GOVD_DEBUG_PRIVATE
| (flags & (GOVD_SEEN | GOVD_EXPLICIT));
/* We're going to make use of the TYPE_SIZE_UNIT at least in the
alloca statement we generate for the variable, so make sure it
is available. This isn't automatically needed for the SHARED
case, since we won't be allocating local storage then.
For local variables TYPE_SIZE_UNIT might not be gimplified yet,
in this case omp_notice_variable will be called later
on when it is gimplified. */
else if (! (flags & GOVD_LOCAL))
omp_notice_variable (ctx, TYPE_SIZE_UNIT (TREE_TYPE (decl)), true);
}
else if (lang_hooks.decls.omp_privatize_by_reference (decl))
{
gcc_assert ((flags & GOVD_LOCAL) == 0);
omp_firstprivatize_type_sizes (ctx, TREE_TYPE (decl));
/* Similar to the direct variable sized case above, we'll need the
size of references being privatized. */
if ((flags & GOVD_SHARED) == 0)
{
t = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (decl)));
if (TREE_CODE (t) != INTEGER_CST)
omp_notice_variable (ctx, t, true);
}
}
splay_tree_insert (ctx->variables, (splay_tree_key)decl, flags);
}
/* Notice a threadprivate variable DECL used in OpenMP context CTX.
This just prints out diagnostics about threadprivate variable uses
in untied tasks. If DECL2 is non-NULL, prevent this warning
on that variable. */
static bool
omp_notice_threadprivate_variable (struct gimplify_omp_ctx *ctx, tree decl,
tree decl2)
{
splay_tree_node n;
if (ctx->region_type != ORT_UNTIED_TASK)
return false;
n = splay_tree_lookup (ctx->variables, (splay_tree_key)decl);
if (n == NULL)
{
error ("threadprivate variable %qs used in untied task",
IDENTIFIER_POINTER (DECL_NAME (decl)));
error ("%Henclosing task", &ctx->location);
splay_tree_insert (ctx->variables, (splay_tree_key)decl, 0);
}
if (decl2)
splay_tree_insert (ctx->variables, (splay_tree_key)decl2, 0);
return false;
}
/* Record the fact that DECL was used within the OpenMP context CTX.
IN_CODE is true when real code uses DECL, and false when we should
merely emit default(none) errors. Return true if DECL is going to
be remapped and thus DECL shouldn't be gimplified into its
DECL_VALUE_EXPR (if any). */
static bool
omp_notice_variable (struct gimplify_omp_ctx *ctx, tree decl, bool in_code)
{
splay_tree_node n;
unsigned flags = in_code ? GOVD_SEEN : 0;
bool ret = false, shared;
if (decl == error_mark_node || TREE_TYPE (decl) == error_mark_node)
return false;
/* Threadprivate variables are predetermined. */
if (is_global_var (decl))
{
if (DECL_THREAD_LOCAL_P (decl))
return omp_notice_threadprivate_variable (ctx, decl, NULL_TREE);
if (DECL_HAS_VALUE_EXPR_P (decl))
{
tree value = get_base_address (DECL_VALUE_EXPR (decl));
if (value && DECL_P (value) && DECL_THREAD_LOCAL_P (value))
return omp_notice_threadprivate_variable (ctx, decl, value);
}
}
n = splay_tree_lookup (ctx->variables, (splay_tree_key)decl);
if (n == NULL)
{
enum omp_clause_default_kind default_kind, kind;
struct gimplify_omp_ctx *octx;
if (ctx->region_type == ORT_WORKSHARE)
goto do_outer;
/* ??? Some compiler-generated variables (like SAVE_EXPRs) could be
remapped firstprivate instead of shared. To some extent this is
addressed in omp_firstprivatize_type_sizes, but not effectively. */
default_kind = ctx->default_kind;
kind = lang_hooks.decls.omp_predetermined_sharing (decl);
if (kind != OMP_CLAUSE_DEFAULT_UNSPECIFIED)
default_kind = kind;
switch (default_kind)
{
case OMP_CLAUSE_DEFAULT_NONE:
error ("%qs not specified in enclosing parallel",
IDENTIFIER_POINTER (DECL_NAME
(lang_hooks.decls.omp_report_decl (decl))));
if ((ctx->region_type & ORT_TASK) != 0)
error ("%Henclosing task", &ctx->location);
else
error ("%Henclosing parallel", &ctx->location);
/* FALLTHRU */
case OMP_CLAUSE_DEFAULT_SHARED:
flags |= GOVD_SHARED;
break;
case OMP_CLAUSE_DEFAULT_PRIVATE:
flags |= GOVD_PRIVATE;
break;
case OMP_CLAUSE_DEFAULT_FIRSTPRIVATE:
flags |= GOVD_FIRSTPRIVATE;
break;
case OMP_CLAUSE_DEFAULT_UNSPECIFIED:
/* decl will be either GOVD_FIRSTPRIVATE or GOVD_SHARED. */
gcc_assert ((ctx->region_type & ORT_TASK) != 0);
if (ctx->outer_context)
omp_notice_variable (ctx->outer_context, decl, in_code);
for (octx = ctx->outer_context; octx; octx = octx->outer_context)
{
splay_tree_node n2;
n2 = splay_tree_lookup (octx->variables, (splay_tree_key) decl);
if (n2 && (n2->value & GOVD_DATA_SHARE_CLASS) != GOVD_SHARED)
{
flags |= GOVD_FIRSTPRIVATE;
break;
}
if ((octx->region_type & ORT_PARALLEL) != 0)
break;
}
if (flags & GOVD_FIRSTPRIVATE)
break;
if (octx == NULL
&& (TREE_CODE (decl) == PARM_DECL
|| (!is_global_var (decl)
&& DECL_CONTEXT (decl) == current_function_decl)))
{
flags |= GOVD_FIRSTPRIVATE;
break;
}
flags |= GOVD_SHARED;
break;
default:
gcc_unreachable ();
}
if ((flags & GOVD_PRIVATE)
&& lang_hooks.decls.omp_private_outer_ref (decl))
flags |= GOVD_PRIVATE_OUTER_REF;
omp_add_variable (ctx, decl, flags);
shared = (flags & GOVD_SHARED) != 0;
ret = lang_hooks.decls.omp_disregard_value_expr (decl, shared);
goto do_outer;
}
if ((n->value & (GOVD_SEEN | GOVD_LOCAL)) == 0
&& (flags & (GOVD_SEEN | GOVD_LOCAL)) == GOVD_SEEN
&& DECL_SIZE (decl)
&& TREE_CODE (DECL_SIZE (decl)) != INTEGER_CST)
{
splay_tree_node n2;
tree t = DECL_VALUE_EXPR (decl);
gcc_assert (TREE_CODE (t) == INDIRECT_REF);
t = TREE_OPERAND (t, 0);
gcc_assert (DECL_P (t));
n2 = splay_tree_lookup (ctx->variables, (splay_tree_key) t);
n2->value |= GOVD_SEEN;
}
shared = ((flags | n->value) & GOVD_SHARED) != 0;
ret = lang_hooks.decls.omp_disregard_value_expr (decl, shared);
/* If nothing changed, there's nothing left to do. */
if ((n->value & flags) == flags)
return ret;
flags |= n->value;
n->value = flags;
do_outer:
/* If the variable is private in the current context, then we don't
need to propagate anything to an outer context. */
if ((flags & GOVD_PRIVATE) && !(flags & GOVD_PRIVATE_OUTER_REF))
return ret;
if (ctx->outer_context
&& omp_notice_variable (ctx->outer_context, decl, in_code))
return true;
return ret;
}
/* Verify that DECL is private within CTX. If there's specific information
to the contrary in the innermost scope, generate an error. */
static bool
omp_is_private (struct gimplify_omp_ctx *ctx, tree decl)
{
splay_tree_node n;
n = splay_tree_lookup (ctx->variables, (splay_tree_key)decl);
if (n != NULL)
{
if (n->value & GOVD_SHARED)
{
if (ctx == gimplify_omp_ctxp)
{
error ("iteration variable %qs should be private",
IDENTIFIER_POINTER (DECL_NAME (decl)));
n->value = GOVD_PRIVATE;
return true;
}
else
return false;
}
else if ((n->value & GOVD_EXPLICIT) != 0
&& (ctx == gimplify_omp_ctxp
|| (ctx->region_type == ORT_COMBINED_PARALLEL
&& gimplify_omp_ctxp->outer_context == ctx)))
{
if ((n->value & GOVD_FIRSTPRIVATE) != 0)
error ("iteration variable %qs should not be firstprivate",
IDENTIFIER_POINTER (DECL_NAME (decl)));
else if ((n->value & GOVD_REDUCTION) != 0)
error ("iteration variable %qs should not be reduction",
IDENTIFIER_POINTER (DECL_NAME (decl)));
}
return (ctx == gimplify_omp_ctxp
|| (ctx->region_type == ORT_COMBINED_PARALLEL
&& gimplify_omp_ctxp->outer_context == ctx));
}
if (ctx->region_type != ORT_WORKSHARE)
return false;
else if (ctx->outer_context)
return omp_is_private (ctx->outer_context, decl);
return false;
}
/* Return true if DECL is private within a parallel region
that binds to the current construct's context or in parallel
region's REDUCTION clause. */
static bool
omp_check_private (struct gimplify_omp_ctx *ctx, tree decl)
{
splay_tree_node n;
do
{
ctx = ctx->outer_context;
if (ctx == NULL)
return !(is_global_var (decl)
/* References might be private, but might be shared too. */
|| lang_hooks.decls.omp_privatize_by_reference (decl));
n = splay_tree_lookup (ctx->variables, (splay_tree_key) decl);
if (n != NULL)
return (n->value & GOVD_SHARED) == 0;
}
while (ctx->region_type == ORT_WORKSHARE);
return false;
}
/* Scan the OpenMP clauses in *LIST_P, installing mappings into a new
and previous omp contexts. */
static void
gimplify_scan_omp_clauses (tree *list_p, gimple_seq *pre_p,
enum omp_region_type region_type)
{
struct gimplify_omp_ctx *ctx, *outer_ctx;
struct gimplify_ctx gctx;
tree c;
ctx = new_omp_context (region_type);
outer_ctx = ctx->outer_context;
while ((c = *list_p) != NULL)
{
bool remove = false;
bool notice_outer = true;
const char *check_non_private = NULL;
unsigned int flags;
tree decl;
switch (OMP_CLAUSE_CODE (c))
{
case OMP_CLAUSE_PRIVATE:
flags = GOVD_PRIVATE | GOVD_EXPLICIT;
if (lang_hooks.decls.omp_private_outer_ref (OMP_CLAUSE_DECL (c)))
{
flags |= GOVD_PRIVATE_OUTER_REF;
OMP_CLAUSE_PRIVATE_OUTER_REF (c) = 1;
}
else
notice_outer = false;
goto do_add;
case OMP_CLAUSE_SHARED:
flags = GOVD_SHARED | GOVD_EXPLICIT;
goto do_add;
case OMP_CLAUSE_FIRSTPRIVATE:
flags = GOVD_FIRSTPRIVATE | GOVD_EXPLICIT;
check_non_private = "firstprivate";
goto do_add;
case OMP_CLAUSE_LASTPRIVATE:
flags = GOVD_LASTPRIVATE | GOVD_SEEN | GOVD_EXPLICIT;
check_non_private = "lastprivate";
goto do_add;
case OMP_CLAUSE_REDUCTION:
flags = GOVD_REDUCTION | GOVD_SEEN | GOVD_EXPLICIT;
check_non_private = "reduction";
goto do_add;
do_add:
decl = OMP_CLAUSE_DECL (c);
if (decl == error_mark_node || TREE_TYPE (decl) == error_mark_node)
{
remove = true;
break;
}
omp_add_variable (ctx, decl, flags);
if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
&& OMP_CLAUSE_REDUCTION_PLACEHOLDER (c))
{
omp_add_variable (ctx, OMP_CLAUSE_REDUCTION_PLACEHOLDER (c),
GOVD_LOCAL | GOVD_SEEN);
gimplify_omp_ctxp = ctx;
push_gimplify_context (&gctx);
OMP_CLAUSE_REDUCTION_GIMPLE_INIT (c) = gimple_seq_alloc ();
OMP_CLAUSE_REDUCTION_GIMPLE_MERGE (c) = gimple_seq_alloc ();
gimplify_and_add (OMP_CLAUSE_REDUCTION_INIT (c),
&OMP_CLAUSE_REDUCTION_GIMPLE_INIT (c));
pop_gimplify_context
(gimple_seq_first_stmt (OMP_CLAUSE_REDUCTION_GIMPLE_INIT (c)));
push_gimplify_context (&gctx);
gimplify_and_add (OMP_CLAUSE_REDUCTION_MERGE (c),
&OMP_CLAUSE_REDUCTION_GIMPLE_MERGE (c));
pop_gimplify_context
(gimple_seq_first_stmt (OMP_CLAUSE_REDUCTION_GIMPLE_MERGE (c)));
OMP_CLAUSE_REDUCTION_INIT (c) = NULL_TREE;
OMP_CLAUSE_REDUCTION_MERGE (c) = NULL_TREE;
gimplify_omp_ctxp = outer_ctx;
}
else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE
&& OMP_CLAUSE_LASTPRIVATE_STMT (c))
{
gimplify_omp_ctxp = ctx;
push_gimplify_context (&gctx);
if (TREE_CODE (OMP_CLAUSE_LASTPRIVATE_STMT (c)) != BIND_EXPR)
{
tree bind = build3 (BIND_EXPR, void_type_node, NULL,
NULL, NULL);
TREE_SIDE_EFFECTS (bind) = 1;
BIND_EXPR_BODY (bind) = OMP_CLAUSE_LASTPRIVATE_STMT (c);
OMP_CLAUSE_LASTPRIVATE_STMT (c) = bind;
}
gimplify_and_add (OMP_CLAUSE_LASTPRIVATE_STMT (c),
&OMP_CLAUSE_LASTPRIVATE_GIMPLE_SEQ (c));
pop_gimplify_context
(gimple_seq_first_stmt (OMP_CLAUSE_LASTPRIVATE_GIMPLE_SEQ (c)));
OMP_CLAUSE_LASTPRIVATE_STMT (c) = NULL_TREE;
gimplify_omp_ctxp = outer_ctx;
}
if (notice_outer)
goto do_notice;
break;
case OMP_CLAUSE_COPYIN:
case OMP_CLAUSE_COPYPRIVATE:
decl = OMP_CLAUSE_DECL (c);
if (decl == error_mark_node || TREE_TYPE (decl) == error_mark_node)
{
remove = true;
break;
}
do_notice:
if (outer_ctx)
omp_notice_variable (outer_ctx, decl, true);
if (check_non_private
&& region_type == ORT_WORKSHARE
&& omp_check_private (ctx, decl))
{
error ("%s variable %qs is private in outer context",
check_non_private, IDENTIFIER_POINTER (DECL_NAME (decl)));
remove = true;
}
break;
case OMP_CLAUSE_IF:
OMP_CLAUSE_OPERAND (c, 0)
= gimple_boolify (OMP_CLAUSE_OPERAND (c, 0));
/* Fall through. */
case OMP_CLAUSE_SCHEDULE:
case OMP_CLAUSE_NUM_THREADS:
if (gimplify_expr (&OMP_CLAUSE_OPERAND (c, 0), pre_p, NULL,
is_gimple_val, fb_rvalue) == GS_ERROR)
remove = true;
break;
case OMP_CLAUSE_NOWAIT:
case OMP_CLAUSE_ORDERED:
case OMP_CLAUSE_UNTIED:
case OMP_CLAUSE_COLLAPSE:
break;
case OMP_CLAUSE_DEFAULT:
ctx->default_kind = OMP_CLAUSE_DEFAULT_KIND (c);
break;
default:
gcc_unreachable ();
}
if (remove)
*list_p = OMP_CLAUSE_CHAIN (c);
else
list_p = &OMP_CLAUSE_CHAIN (c);
}
gimplify_omp_ctxp = ctx;
}
/* For all variables that were not actually used within the context,
remove PRIVATE, SHARED, and FIRSTPRIVATE clauses. */
static int
gimplify_adjust_omp_clauses_1 (splay_tree_node n, void *data)
{
tree *list_p = (tree *) data;
tree decl = (tree) n->key;
unsigned flags = n->value;
enum omp_clause_code code;
tree clause;
bool private_debug;
if (flags & (GOVD_EXPLICIT | GOVD_LOCAL))
return 0;
if ((flags & GOVD_SEEN) == 0)
return 0;
if (flags & GOVD_DEBUG_PRIVATE)
{
gcc_assert ((flags & GOVD_DATA_SHARE_CLASS) == GOVD_PRIVATE);
private_debug = true;
}
else
private_debug
= lang_hooks.decls.omp_private_debug_clause (decl,
!!(flags & GOVD_SHARED));
if (private_debug)
code = OMP_CLAUSE_PRIVATE;
else if (flags & GOVD_SHARED)
{
if (is_global_var (decl))
{
struct gimplify_omp_ctx *ctx = gimplify_omp_ctxp->outer_context;
while (ctx != NULL)
{
splay_tree_node on
= splay_tree_lookup (ctx->variables, (splay_tree_key) decl);
if (on && (on->value & (GOVD_FIRSTPRIVATE | GOVD_LASTPRIVATE
| GOVD_PRIVATE | GOVD_REDUCTION)) != 0)
break;
ctx = ctx->outer_context;
}
if (ctx == NULL)
return 0;
}
code = OMP_CLAUSE_SHARED;
}
else if (flags & GOVD_PRIVATE)
code = OMP_CLAUSE_PRIVATE;
else if (flags & GOVD_FIRSTPRIVATE)
code = OMP_CLAUSE_FIRSTPRIVATE;
else
gcc_unreachable ();
clause = build_omp_clause (code);
OMP_CLAUSE_DECL (clause) = decl;
OMP_CLAUSE_CHAIN (clause) = *list_p;
if (private_debug)
OMP_CLAUSE_PRIVATE_DEBUG (clause) = 1;
else if (code == OMP_CLAUSE_PRIVATE && (flags & GOVD_PRIVATE_OUTER_REF))
OMP_CLAUSE_PRIVATE_OUTER_REF (clause) = 1;
*list_p = clause;
lang_hooks.decls.omp_finish_clause (clause);
return 0;
}
static void
gimplify_adjust_omp_clauses (tree *list_p)
{
struct gimplify_omp_ctx *ctx = gimplify_omp_ctxp;
tree c, decl;
while ((c = *list_p) != NULL)
{
splay_tree_node n;
bool remove = false;
switch (OMP_CLAUSE_CODE (c))
{
case OMP_CLAUSE_PRIVATE:
case OMP_CLAUSE_SHARED:
case OMP_CLAUSE_FIRSTPRIVATE:
decl = OMP_CLAUSE_DECL (c);
n = splay_tree_lookup (ctx->variables, (splay_tree_key) decl);
remove = !(n->value & GOVD_SEEN);
if (! remove)
{
bool shared = OMP_CLAUSE_CODE (c) == OMP_CLAUSE_SHARED;
if ((n->value & GOVD_DEBUG_PRIVATE)
|| lang_hooks.decls.omp_private_debug_clause (decl, shared))
{
gcc_assert ((n->value & GOVD_DEBUG_PRIVATE) == 0
|| ((n->value & GOVD_DATA_SHARE_CLASS)
== GOVD_PRIVATE));
OMP_CLAUSE_SET_CODE (c, OMP_CLAUSE_PRIVATE);
OMP_CLAUSE_PRIVATE_DEBUG (c) = 1;
}
}
break;
case OMP_CLAUSE_LASTPRIVATE:
/* Make sure OMP_CLAUSE_LASTPRIVATE_FIRSTPRIVATE is set to
accurately reflect the presence of a FIRSTPRIVATE clause. */
decl = OMP_CLAUSE_DECL (c);
n = splay_tree_lookup (ctx->variables, (splay_tree_key) decl);
OMP_CLAUSE_LASTPRIVATE_FIRSTPRIVATE (c)
= (n->value & GOVD_FIRSTPRIVATE) != 0;
break;
case OMP_CLAUSE_REDUCTION:
case OMP_CLAUSE_COPYIN:
case OMP_CLAUSE_COPYPRIVATE:
case OMP_CLAUSE_IF:
case OMP_CLAUSE_NUM_THREADS:
case OMP_CLAUSE_SCHEDULE:
case OMP_CLAUSE_NOWAIT:
case OMP_CLAUSE_ORDERED:
case OMP_CLAUSE_DEFAULT:
case OMP_CLAUSE_UNTIED:
case OMP_CLAUSE_COLLAPSE:
break;
default:
gcc_unreachable ();
}
if (remove)
*list_p = OMP_CLAUSE_CHAIN (c);
else
list_p = &OMP_CLAUSE_CHAIN (c);
}
/* Add in any implicit data sharing. */
splay_tree_foreach (ctx->variables, gimplify_adjust_omp_clauses_1, list_p);
gimplify_omp_ctxp = ctx->outer_context;
delete_omp_context (ctx);
}
/* Gimplify the contents of an OMP_PARALLEL statement. This involves
gimplification of the body, as well as scanning the body for used
variables. We need to do this scan now, because variable-sized
decls will be decomposed during gimplification. */
static void
gimplify_omp_parallel (tree *expr_p, gimple_seq *pre_p)
{
tree expr = *expr_p;
gimple g;
gimple_seq body = NULL;
struct gimplify_ctx gctx;
gimplify_scan_omp_clauses (&OMP_PARALLEL_CLAUSES (expr), pre_p,
OMP_PARALLEL_COMBINED (expr)
? ORT_COMBINED_PARALLEL
: ORT_PARALLEL);
push_gimplify_context (&gctx);
g = gimplify_and_return_first (OMP_PARALLEL_BODY (expr), &body);
if (gimple_code (g) == GIMPLE_BIND)
pop_gimplify_context (g);
else
pop_gimplify_context (NULL);
gimplify_adjust_omp_clauses (&OMP_PARALLEL_CLAUSES (expr));
g = gimple_build_omp_parallel (body,
OMP_PARALLEL_CLAUSES (expr),
NULL_TREE, NULL_TREE);
if (OMP_PARALLEL_COMBINED (expr))
gimple_omp_set_subcode (g, GF_OMP_PARALLEL_COMBINED);
gimplify_seq_add_stmt (pre_p, g);
*expr_p = NULL_TREE;
}
/* Gimplify the contents of an OMP_TASK statement. This involves
gimplification of the body, as well as scanning the body for used
variables. We need to do this scan now, because variable-sized
decls will be decomposed during gimplification. */
static void
gimplify_omp_task (tree *expr_p, gimple_seq *pre_p)
{
tree expr = *expr_p;
gimple g;
gimple_seq body = NULL;
struct gimplify_ctx gctx;
gimplify_scan_omp_clauses (&OMP_TASK_CLAUSES (expr), pre_p,
find_omp_clause (OMP_TASK_CLAUSES (expr),
OMP_CLAUSE_UNTIED)
? ORT_UNTIED_TASK : ORT_TASK);
push_gimplify_context (&gctx);
g = gimplify_and_return_first (OMP_TASK_BODY (expr), &body);
if (gimple_code (g) == GIMPLE_BIND)
pop_gimplify_context (g);
else
pop_gimplify_context (NULL);
gimplify_adjust_omp_clauses (&OMP_TASK_CLAUSES (expr));
g = gimple_build_omp_task (body,
OMP_TASK_CLAUSES (expr),
NULL_TREE, NULL_TREE,
NULL_TREE, NULL_TREE, NULL_TREE);
gimplify_seq_add_stmt (pre_p, g);
*expr_p = NULL_TREE;
}
/* Gimplify the gross structure of an OMP_FOR statement. */
static enum gimplify_status
gimplify_omp_for (tree *expr_p, gimple_seq *pre_p)
{
tree for_stmt, decl, var, t;
enum gimplify_status ret = GS_OK;
gimple gfor;
gimple_seq for_body, for_pre_body;
int i;
for_stmt = *expr_p;
gimplify_scan_omp_clauses (&OMP_FOR_CLAUSES (for_stmt), pre_p,
ORT_WORKSHARE);
/* Handle OMP_FOR_INIT. */
for_pre_body = NULL;
gimplify_and_add (OMP_FOR_PRE_BODY (for_stmt), &for_pre_body);
OMP_FOR_PRE_BODY (for_stmt) = NULL_TREE;
for_body = gimple_seq_alloc ();
gcc_assert (TREE_VEC_LENGTH (OMP_FOR_INIT (for_stmt))
== TREE_VEC_LENGTH (OMP_FOR_COND (for_stmt)));
gcc_assert (TREE_VEC_LENGTH (OMP_FOR_INIT (for_stmt))
== TREE_VEC_LENGTH (OMP_FOR_INCR (for_stmt)));
for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (for_stmt)); i++)
{
t = TREE_VEC_ELT (OMP_FOR_INIT (for_stmt), i);
gcc_assert (TREE_CODE (t) == MODIFY_EXPR);
decl = TREE_OPERAND (t, 0);
gcc_assert (DECL_P (decl));
gcc_assert (INTEGRAL_TYPE_P (TREE_TYPE (decl))
|| POINTER_TYPE_P (TREE_TYPE (decl)));
/* Make sure the iteration variable is private. */
if (omp_is_private (gimplify_omp_ctxp, decl))
omp_notice_variable (gimplify_omp_ctxp, decl, true);
else
omp_add_variable (gimplify_omp_ctxp, decl, GOVD_PRIVATE | GOVD_SEEN);
/* If DECL is not a gimple register, create a temporary variable to act
as an iteration counter. This is valid, since DECL cannot be
modified in the body of the loop. */
if (!is_gimple_reg (decl))
{
var = create_tmp_var (TREE_TYPE (decl), get_name (decl));
TREE_OPERAND (t, 0) = var;
gimplify_seq_add_stmt (&for_body, gimple_build_assign (decl, var));
omp_add_variable (gimplify_omp_ctxp, var, GOVD_PRIVATE | GOVD_SEEN);
}
else
var = decl;
ret |= gimplify_expr (&TREE_OPERAND (t, 1), &for_pre_body, NULL,
is_gimple_val, fb_rvalue);
if (ret == GS_ERROR)
return ret;
/* Handle OMP_FOR_COND. */
t = TREE_VEC_ELT (OMP_FOR_COND (for_stmt), i);
gcc_assert (COMPARISON_CLASS_P (t));
gcc_assert (TREE_OPERAND (t, 0) == decl);
ret |= gimplify_expr (&TREE_OPERAND (t, 1), &for_pre_body, NULL,
is_gimple_val, fb_rvalue);
/* Handle OMP_FOR_INCR. */
t = TREE_VEC_ELT (OMP_FOR_INCR (for_stmt), i);
switch (TREE_CODE (t))
{
case PREINCREMENT_EXPR:
case POSTINCREMENT_EXPR:
t = build_int_cst (TREE_TYPE (decl), 1);
t = build2 (PLUS_EXPR, TREE_TYPE (decl), var, t);
t = build2 (MODIFY_EXPR, TREE_TYPE (var), var, t);
TREE_VEC_ELT (OMP_FOR_INCR (for_stmt), i) = t;
break;
case PREDECREMENT_EXPR:
case POSTDECREMENT_EXPR:
t = build_int_cst (TREE_TYPE (decl), -1);
t = build2 (PLUS_EXPR, TREE_TYPE (decl), var, t);
t = build2 (MODIFY_EXPR, TREE_TYPE (var), var, t);
TREE_VEC_ELT (OMP_FOR_INCR (for_stmt), i) = t;
break;
case MODIFY_EXPR:
gcc_assert (TREE_OPERAND (t, 0) == decl);
TREE_OPERAND (t, 0) = var;
t = TREE_OPERAND (t, 1);
switch (TREE_CODE (t))
{
case PLUS_EXPR:
if (TREE_OPERAND (t, 1) == decl)
{
TREE_OPERAND (t, 1) = TREE_OPERAND (t, 0);
TREE_OPERAND (t, 0) = var;
break;
}
/* Fallthru. */
case MINUS_EXPR:
case POINTER_PLUS_EXPR:
gcc_assert (TREE_OPERAND (t, 0) == decl);
TREE_OPERAND (t, 0) = var;
break;
default:
gcc_unreachable ();
}
ret |= gimplify_expr (&TREE_OPERAND (t, 1), &for_pre_body, NULL,
is_gimple_val, fb_rvalue);
break;
default:
gcc_unreachable ();
}
if (var != decl || TREE_VEC_LENGTH (OMP_FOR_INIT (for_stmt)) > 1)
{
tree c;
for (c = OMP_FOR_CLAUSES (for_stmt); c ; c = OMP_CLAUSE_CHAIN (c))
if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE
&& OMP_CLAUSE_DECL (c) == decl
&& OMP_CLAUSE_LASTPRIVATE_GIMPLE_SEQ (c) == NULL)
{
t = TREE_VEC_ELT (OMP_FOR_INCR (for_stmt), i);
gcc_assert (TREE_CODE (t) == MODIFY_EXPR);
gcc_assert (TREE_OPERAND (t, 0) == var);
t = TREE_OPERAND (t, 1);
gcc_assert (TREE_CODE (t) == PLUS_EXPR
|| TREE_CODE (t) == MINUS_EXPR
|| TREE_CODE (t) == POINTER_PLUS_EXPR);
gcc_assert (TREE_OPERAND (t, 0) == var);
t = build2 (TREE_CODE (t), TREE_TYPE (decl), decl,
TREE_OPERAND (t, 1));
gimplify_assign (decl, t,
&OMP_CLAUSE_LASTPRIVATE_GIMPLE_SEQ (c));
}
}
}
gimplify_and_add (OMP_FOR_BODY (for_stmt), &for_body);
gimplify_adjust_omp_clauses (&OMP_FOR_CLAUSES (for_stmt));
gfor = gimple_build_omp_for (for_body, OMP_FOR_CLAUSES (for_stmt),
TREE_VEC_LENGTH (OMP_FOR_INIT (for_stmt)),
for_pre_body);
for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (for_stmt)); i++)
{
t = TREE_VEC_ELT (OMP_FOR_INIT (for_stmt), i);
gimple_omp_for_set_index (gfor, i, TREE_OPERAND (t, 0));
gimple_omp_for_set_initial (gfor, i, TREE_OPERAND (t, 1));
t = TREE_VEC_ELT (OMP_FOR_COND (for_stmt), i);
gimple_omp_for_set_cond (gfor, i, TREE_CODE (t));
gimple_omp_for_set_final (gfor, i, TREE_OPERAND (t, 1));
t = TREE_VEC_ELT (OMP_FOR_INCR (for_stmt), i);
gimple_omp_for_set_incr (gfor, i, TREE_OPERAND (t, 1));
}
gimplify_seq_add_stmt (pre_p, gfor);
return ret == GS_ALL_DONE ? GS_ALL_DONE : GS_ERROR;
}
/* Gimplify the gross structure of other OpenMP worksharing constructs.
In particular, OMP_SECTIONS and OMP_SINGLE. */
static void
gimplify_omp_workshare (tree *expr_p, gimple_seq *pre_p)
{
tree expr = *expr_p;
gimple stmt;
gimple_seq body = NULL;
gimplify_scan_omp_clauses (&OMP_CLAUSES (expr), pre_p, ORT_WORKSHARE);
gimplify_and_add (OMP_BODY (expr), &body);
gimplify_adjust_omp_clauses (&OMP_CLAUSES (expr));
if (TREE_CODE (expr) == OMP_SECTIONS)
stmt = gimple_build_omp_sections (body, OMP_CLAUSES (expr));
else if (TREE_CODE (expr) == OMP_SINGLE)
stmt = gimple_build_omp_single (body, OMP_CLAUSES (expr));
else
gcc_unreachable ();
gimplify_seq_add_stmt (pre_p, stmt);
}
/* A subroutine of gimplify_omp_atomic. The front end is supposed to have
stabilized the lhs of the atomic operation as *ADDR. Return true if
EXPR is this stabilized form. */
static bool
goa_lhs_expr_p (tree expr, tree addr)
{
/* Also include casts to other type variants. The C front end is fond
of adding these for e.g. volatile variables. This is like
STRIP_TYPE_NOPS but includes the main variant lookup. */
while ((CONVERT_EXPR_P (expr)
|| TREE_CODE (expr) == NON_LVALUE_EXPR)
&& TREE_OPERAND (expr, 0) != error_mark_node
&& (TYPE_MAIN_VARIANT (TREE_TYPE (expr))
== TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (expr, 0)))))
expr = TREE_OPERAND (expr, 0);
if (TREE_CODE (expr) == INDIRECT_REF)
{
expr = TREE_OPERAND (expr, 0);
while (expr != addr
&& (CONVERT_EXPR_P (expr)
|| TREE_CODE (expr) == NON_LVALUE_EXPR)
&& TREE_CODE (expr) == TREE_CODE (addr)
&& TYPE_MAIN_VARIANT (TREE_TYPE (expr))
== TYPE_MAIN_VARIANT (TREE_TYPE (addr)))
{
expr = TREE_OPERAND (expr, 0);
addr = TREE_OPERAND (addr, 0);
}
if (expr == addr)
return true;
return (TREE_CODE (addr) == ADDR_EXPR
&& TREE_CODE (expr) == ADDR_EXPR
&& TREE_OPERAND (addr, 0) == TREE_OPERAND (expr, 0));
}
if (TREE_CODE (addr) == ADDR_EXPR && expr == TREE_OPERAND (addr, 0))
return true;
return false;
}
/* Walk *EXPR_P and replace
appearances of *LHS_ADDR with LHS_VAR. If an expression does not involve
the lhs, evaluate it into a temporary. Return 1 if the lhs appeared as
a subexpression, 0 if it did not, or -1 if an error was encountered. */
static int
goa_stabilize_expr (tree *expr_p, gimple_seq *pre_p, tree lhs_addr,
tree lhs_var)
{
tree expr = *expr_p;
int saw_lhs;
if (goa_lhs_expr_p (expr, lhs_addr))
{
*expr_p = lhs_var;
return 1;
}
if (is_gimple_val (expr))
return 0;
saw_lhs = 0;
switch (TREE_CODE_CLASS (TREE_CODE (expr)))
{
case tcc_binary:
case tcc_comparison:
saw_lhs |= goa_stabilize_expr (&TREE_OPERAND (expr, 1), pre_p, lhs_addr,
lhs_var);
case tcc_unary:
saw_lhs |= goa_stabilize_expr (&TREE_OPERAND (expr, 0), pre_p, lhs_addr,
lhs_var);
break;
case tcc_expression:
switch (TREE_CODE (expr))
{
case TRUTH_ANDIF_EXPR:
case TRUTH_ORIF_EXPR:
case TRUTH_AND_EXPR:
case TRUTH_OR_EXPR:
case TRUTH_XOR_EXPR:
saw_lhs |= goa_stabilize_expr (&TREE_OPERAND (expr, 1), pre_p,
lhs_addr, lhs_var);
case TRUTH_NOT_EXPR:
saw_lhs |= goa_stabilize_expr (&TREE_OPERAND (expr, 0), pre_p,
lhs_addr, lhs_var);
break;
default:
break;
}
break;
default:
break;
}
if (saw_lhs == 0)
{
enum gimplify_status gs;
gs = gimplify_expr (expr_p, pre_p, NULL, is_gimple_val, fb_rvalue);
if (gs != GS_ALL_DONE)
saw_lhs = -1;
}
return saw_lhs;
}
/* Gimplify an OMP_ATOMIC statement. */
static enum gimplify_status
gimplify_omp_atomic (tree *expr_p, gimple_seq *pre_p)
{
tree addr = TREE_OPERAND (*expr_p, 0);
tree rhs = TREE_OPERAND (*expr_p, 1);
tree type = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (addr)));
tree tmp_load;
tmp_load = create_tmp_var (type, NULL);
if (TREE_CODE (type) == COMPLEX_TYPE || TREE_CODE (type) == VECTOR_TYPE)
DECL_GIMPLE_REG_P (tmp_load) = 1;
if (goa_stabilize_expr (&rhs, pre_p, addr, tmp_load) < 0)
return GS_ERROR;
if (gimplify_expr (&addr, pre_p, NULL, is_gimple_val, fb_rvalue)
!= GS_ALL_DONE)
return GS_ERROR;
gimplify_seq_add_stmt (pre_p, gimple_build_omp_atomic_load (tmp_load, addr));
if (gimplify_expr (&rhs, pre_p, NULL, is_gimple_val, fb_rvalue)
!= GS_ALL_DONE)
return GS_ERROR;
gimplify_seq_add_stmt (pre_p, gimple_build_omp_atomic_store (rhs));
*expr_p = NULL;
return GS_ALL_DONE;
}
/* Converts the GENERIC expression tree *EXPR_P to GIMPLE. If the
expression produces a value to be used as an operand inside a GIMPLE
statement, the value will be stored back in *EXPR_P. This value will
be a tree of class tcc_declaration, tcc_constant, tcc_reference or
an SSA_NAME. The corresponding sequence of GIMPLE statements is
emitted in PRE_P and POST_P.
Additionally, this process may overwrite parts of the input
expression during gimplification. Ideally, it should be
possible to do non-destructive gimplification.
EXPR_P points to the GENERIC expression to convert to GIMPLE. If
the expression needs to evaluate to a value to be used as
an operand in a GIMPLE statement, this value will be stored in
*EXPR_P on exit. This happens when the caller specifies one
of fb_lvalue or fb_rvalue fallback flags.
PRE_P will contain the sequence of GIMPLE statements corresponding
to the evaluation of EXPR and all the side-effects that must
be executed before the main expression. On exit, the last
statement of PRE_P is the core statement being gimplified. For
instance, when gimplifying 'if (++a)' the last statement in
PRE_P will be 'if (t.1)' where t.1 is the result of
pre-incrementing 'a'.
POST_P will contain the sequence of GIMPLE statements corresponding
to the evaluation of all the side-effects that must be executed
after the main expression. If this is NULL, the post
side-effects are stored at the end of PRE_P.
The reason why the output is split in two is to handle post
side-effects explicitly. In some cases, an expression may have
inner and outer post side-effects which need to be emitted in
an order different from the one given by the recursive
traversal. For instance, for the expression (*p--)++ the post
side-effects of '--' must actually occur *after* the post
side-effects of '++'. However, gimplification will first visit
the inner expression, so if a separate POST sequence was not
used, the resulting sequence would be:
1 t.1 = *p
2 p = p - 1
3 t.2 = t.1 + 1
4 *p = t.2
However, the post-decrement operation in line #2 must not be
evaluated until after the store to *p at line #4, so the
correct sequence should be:
1 t.1 = *p
2 t.2 = t.1 + 1
3 *p = t.2
4 p = p - 1
So, by specifying a separate post queue, it is possible
to emit the post side-effects in the correct order.
If POST_P is NULL, an internal queue will be used. Before
returning to the caller, the sequence POST_P is appended to
the main output sequence PRE_P.
GIMPLE_TEST_F points to a function that takes a tree T and
returns nonzero if T is in the GIMPLE form requested by the
caller. The GIMPLE predicates are in tree-gimple.c.
FALLBACK tells the function what sort of a temporary we want if
gimplification cannot produce an expression that complies with
GIMPLE_TEST_F.
fb_none means that no temporary should be generated
fb_rvalue means that an rvalue is OK to generate
fb_lvalue means that an lvalue is OK to generate
fb_either means that either is OK, but an lvalue is preferable.
fb_mayfail means that gimplification may fail (in which case
GS_ERROR will be returned)
The return value is either GS_ERROR or GS_ALL_DONE, since this
function iterates until EXPR is completely gimplified or an error
occurs. */
enum gimplify_status
gimplify_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p,
bool (*gimple_test_f) (tree), fallback_t fallback)
{
tree tmp;
gimple_seq internal_pre = NULL;
gimple_seq internal_post = NULL;
tree save_expr;
bool is_statement;
location_t saved_location;
enum gimplify_status ret;
gimple_stmt_iterator pre_last_gsi, post_last_gsi;
save_expr = *expr_p;
if (save_expr == NULL_TREE)
return GS_ALL_DONE;
/* If we are gimplifying a top-level statement, PRE_P must be valid. */
is_statement = gimple_test_f == is_gimple_stmt;
if (is_statement)
gcc_assert (pre_p);
/* Consistency checks. */
if (gimple_test_f == is_gimple_reg)
gcc_assert (fallback & (fb_rvalue | fb_lvalue));
else if (gimple_test_f == is_gimple_val
|| gimple_test_f == is_gimple_formal_tmp_rhs
|| gimple_test_f == is_gimple_formal_tmp_or_call_rhs
|| gimple_test_f == is_gimple_formal_tmp_reg
|| gimple_test_f == is_gimple_formal_tmp_var
|| gimple_test_f == is_gimple_call_addr
|| gimple_test_f == is_gimple_condexpr
|| gimple_test_f == is_gimple_mem_rhs
|| gimple_test_f == is_gimple_mem_or_call_rhs
|| gimple_test_f == is_gimple_reg_rhs
|| gimple_test_f == is_gimple_reg_or_call_rhs
|| gimple_test_f == is_gimple_asm_val)
gcc_assert (fallback & fb_rvalue);
else if (gimple_test_f == is_gimple_min_lval
|| gimple_test_f == is_gimple_lvalue)
gcc_assert (fallback & fb_lvalue);
else if (gimple_test_f == is_gimple_addressable)
gcc_assert (fallback & fb_either);
else if (gimple_test_f == is_gimple_stmt)
gcc_assert (fallback == fb_none);
else
{
/* We should have recognized the GIMPLE_TEST_F predicate to
know what kind of fallback to use in case a temporary is
needed to hold the value or address of *EXPR_P. */
gcc_unreachable ();
}
/* We used to check the predicate here and return immediately if it
succeeds. This is wrong; the design is for gimplification to be
idempotent, and for the predicates to only test for valid forms, not
whether they are fully simplified. */
if (pre_p == NULL)
pre_p = &internal_pre;
if (post_p == NULL)
post_p = &internal_post;
/* Remember the last statements added to PRE_P and POST_P. Every
new statement added by the gimplification helpers needs to be
annotated with location information. To centralize the
responsibility, we remember the last statement that had been
added to both queues before gimplifying *EXPR_P. If
gimplification produces new statements in PRE_P and POST_P, those
statements will be annotated with the same location information
as *EXPR_P. */
pre_last_gsi = gsi_last (*pre_p);
post_last_gsi = gsi_last (*post_p);
saved_location = input_location;
if (save_expr != error_mark_node
&& EXPR_HAS_LOCATION (*expr_p))
input_location = EXPR_LOCATION (*expr_p);
/* Loop over the specific gimplifiers until the toplevel node
remains the same. */
do
{
/* Strip away as many useless type conversions as possible
at the toplevel. */
STRIP_USELESS_TYPE_CONVERSION (*expr_p);
/* Remember the expr. */
save_expr = *expr_p;
/* Die, die, die, my darling. */
if (save_expr == error_mark_node
|| (TREE_TYPE (save_expr)
&& TREE_TYPE (save_expr) == error_mark_node))
{
ret = GS_ERROR;
break;
}
/* Do any language-specific gimplification. */
ret = lang_hooks.gimplify_expr (expr_p, pre_p, post_p);
if (ret == GS_OK)
{
if (*expr_p == NULL_TREE)
break;
if (*expr_p != save_expr)
continue;
}
else if (ret != GS_UNHANDLED)
break;
ret = GS_OK;
switch (TREE_CODE (*expr_p))
{
/* First deal with the special cases. */
case POSTINCREMENT_EXPR:
case POSTDECREMENT_EXPR:
case PREINCREMENT_EXPR:
case PREDECREMENT_EXPR:
ret = gimplify_self_mod_expr (expr_p, pre_p, post_p,
fallback != fb_none);
break;
case ARRAY_REF:
case ARRAY_RANGE_REF:
case REALPART_EXPR:
case IMAGPART_EXPR:
case COMPONENT_REF:
case VIEW_CONVERT_EXPR:
ret = gimplify_compound_lval (expr_p, pre_p, post_p,
fallback ? fallback : fb_rvalue);
break;
case COND_EXPR:
ret = gimplify_cond_expr (expr_p, pre_p, fallback);
/* C99 code may assign to an array in a structure value of a
conditional expression, and this has undefined behavior
only on execution, so create a temporary if an lvalue is
required. */
if (fallback == fb_lvalue)
{
*expr_p = get_initialized_tmp_var (*expr_p, pre_p, post_p);
mark_addressable (*expr_p);
}
break;
case CALL_EXPR:
ret = gimplify_call_expr (expr_p, pre_p, fallback != fb_none);
/* C99 code may assign to an array in a structure returned
from a function, and this has undefined behavior only on
execution, so create a temporary if an lvalue is
required. */
if (fallback == fb_lvalue)
{
*expr_p = get_initialized_tmp_var (*expr_p, pre_p, post_p);
mark_addressable (*expr_p);
}
break;
case TREE_LIST:
gcc_unreachable ();
case COMPOUND_EXPR:
ret = gimplify_compound_expr (expr_p, pre_p, fallback != fb_none);
break;
case MODIFY_EXPR:
case INIT_EXPR:
ret = gimplify_modify_expr (expr_p, pre_p, post_p,
fallback != fb_none);
break;
case TRUTH_ANDIF_EXPR:
case TRUTH_ORIF_EXPR:
ret = gimplify_boolean_expr (expr_p);
break;
case TRUTH_NOT_EXPR:
if (TREE_CODE (TREE_TYPE (*expr_p)) != BOOLEAN_TYPE)
{
tree type = TREE_TYPE (*expr_p);
*expr_p = fold_convert (type, gimple_boolify (*expr_p));
ret = GS_OK;
break;
}
ret = gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p,
is_gimple_val, fb_rvalue);
recalculate_side_effects (*expr_p);
break;
case ADDR_EXPR:
ret = gimplify_addr_expr (expr_p, pre_p, post_p);
break;
case VA_ARG_EXPR:
ret = gimplify_va_arg_expr (expr_p, pre_p, post_p);
break;
CASE_CONVERT:
if (IS_EMPTY_STMT (*expr_p))
{
ret = GS_ALL_DONE;
break;
}
if (VOID_TYPE_P (TREE_TYPE (*expr_p))
|| fallback == fb_none)
{
/* Just strip a conversion to void (or in void context) and
try again. */
*expr_p = TREE_OPERAND (*expr_p, 0);
break;
}
ret = gimplify_conversion (expr_p);
if (ret == GS_ERROR)
break;
if (*expr_p != save_expr)
break;
/* FALLTHRU */
case FIX_TRUNC_EXPR:
/* unary_expr: ... | '(' cast ')' val | ... */
ret = gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p,
is_gimple_val, fb_rvalue);
recalculate_side_effects (*expr_p);
break;
case INDIRECT_REF:
*expr_p = fold_indirect_ref (*expr_p);
if (*expr_p != save_expr)
break;
/* else fall through. */
case ALIGN_INDIRECT_REF:
case MISALIGNED_INDIRECT_REF:
ret = gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p,
is_gimple_reg, fb_rvalue);
recalculate_side_effects (*expr_p);
break;
/* Constants need not be gimplified. */
case INTEGER_CST:
case REAL_CST:
case FIXED_CST:
case STRING_CST:
case COMPLEX_CST:
case VECTOR_CST:
ret = GS_ALL_DONE;
break;
case CONST_DECL:
/* If we require an lvalue, such as for ADDR_EXPR, retain the
CONST_DECL node. Otherwise the decl is replaceable by its
value. */
/* ??? Should be == fb_lvalue, but ADDR_EXPR passes fb_either. */
if (fallback & fb_lvalue)
ret = GS_ALL_DONE;
else
*expr_p = DECL_INITIAL (*expr_p);
break;
case DECL_EXPR:
ret = gimplify_decl_expr (expr_p, pre_p);
break;
case EXC_PTR_EXPR:
/* FIXME make this a decl. */
ret = GS_ALL_DONE;
break;
case BIND_EXPR:
ret = gimplify_bind_expr (expr_p, pre_p);
break;
case LOOP_EXPR:
ret = gimplify_loop_expr (expr_p, pre_p);
break;
case SWITCH_EXPR:
ret = gimplify_switch_expr (expr_p, pre_p);
break;
case EXIT_EXPR:
ret = gimplify_exit_expr (expr_p);
break;
case GOTO_EXPR:
/* If the target is not LABEL, then it is a computed jump
and the target needs to be gimplified. */
if (TREE_CODE (GOTO_DESTINATION (*expr_p)) != LABEL_DECL)
{
ret = gimplify_expr (&GOTO_DESTINATION (*expr_p), pre_p,
NULL, is_gimple_val, fb_rvalue);
if (ret == GS_ERROR)
break;
}
gimplify_seq_add_stmt (pre_p,
gimple_build_goto (GOTO_DESTINATION (*expr_p)));
break;
case PREDICT_EXPR:
gimplify_seq_add_stmt (pre_p,
gimple_build_predict (PREDICT_EXPR_PREDICTOR (*expr_p),
PREDICT_EXPR_OUTCOME (*expr_p)));
ret = GS_ALL_DONE;
break;
case LABEL_EXPR:
ret = GS_ALL_DONE;
gcc_assert (decl_function_context (LABEL_EXPR_LABEL (*expr_p))
== current_function_decl);
gimplify_seq_add_stmt (pre_p,
gimple_build_label (LABEL_EXPR_LABEL (*expr_p)));
break;
case CASE_LABEL_EXPR:
ret = gimplify_case_label_expr (expr_p, pre_p);
break;
case RETURN_EXPR:
ret = gimplify_return_expr (*expr_p, pre_p);
break;
case CONSTRUCTOR:
/* Don't reduce this in place; let gimplify_init_constructor work its
magic. Buf if we're just elaborating this for side effects, just
gimplify any element that has side-effects. */
if (fallback == fb_none)
{
unsigned HOST_WIDE_INT ix;
constructor_elt *ce;
tree temp = NULL_TREE;
for (ix = 0;
VEC_iterate (constructor_elt, CONSTRUCTOR_ELTS (*expr_p),
ix, ce);
ix++)
if (TREE_SIDE_EFFECTS (ce->value))
append_to_statement_list (ce->value, &temp);
*expr_p = temp;
ret = GS_OK;
}
/* C99 code may assign to an array in a constructed
structure or union, and this has undefined behavior only
on execution, so create a temporary if an lvalue is
required. */
else if (fallback == fb_lvalue)
{
*expr_p = get_initialized_tmp_var (*expr_p, pre_p, post_p);
mark_addressable (*expr_p);
}
else
ret = GS_ALL_DONE;
break;
/* The following are special cases that are not handled by the
original GIMPLE grammar. */
/* SAVE_EXPR nodes are converted into a GIMPLE identifier and
eliminated. */
case SAVE_EXPR:
ret = gimplify_save_expr (expr_p, pre_p, post_p);
break;
case BIT_FIELD_REF:
{
enum gimplify_status r0, r1, r2;
r0 = gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p,
post_p, is_gimple_lvalue, fb_either);
r1 = gimplify_expr (&TREE_OPERAND (*expr_p, 1), pre_p,
post_p, is_gimple_val, fb_rvalue);
r2 = gimplify_expr (&TREE_OPERAND (*expr_p, 2), pre_p,
post_p, is_gimple_val, fb_rvalue);
recalculate_side_effects (*expr_p);
ret = MIN (r0, MIN (r1, r2));
}
break;
case NON_LVALUE_EXPR:
/* This should have been stripped above. */
gcc_unreachable ();
case ASM_EXPR:
ret = gimplify_asm_expr (expr_p, pre_p, post_p);
break;
case TRY_FINALLY_EXPR:
case TRY_CATCH_EXPR:
{
gimple_seq eval, cleanup;
gimple try_;
eval = cleanup = NULL;
gimplify_and_add (TREE_OPERAND (*expr_p, 0), &eval);
gimplify_and_add (TREE_OPERAND (*expr_p, 1), &cleanup);
/* Don't create bogus GIMPLE_TRY with empty cleanup. */
if (gimple_seq_empty_p (cleanup))
{
gimple_seq_add_seq (pre_p, eval);
ret = GS_ALL_DONE;
break;
}
try_ = gimple_build_try (eval, cleanup,
TREE_CODE (*expr_p) == TRY_FINALLY_EXPR
? GIMPLE_TRY_FINALLY
: GIMPLE_TRY_CATCH);
if (TREE_CODE (*expr_p) == TRY_CATCH_EXPR)
gimple_try_set_catch_is_cleanup (try_,
TRY_CATCH_IS_CLEANUP (*expr_p));
gimplify_seq_add_stmt (pre_p, try_);
ret = GS_ALL_DONE;
break;
}
case CLEANUP_POINT_EXPR:
ret = gimplify_cleanup_point_expr (expr_p, pre_p);
break;
case TARGET_EXPR:
ret = gimplify_target_expr (expr_p, pre_p, post_p);
break;
case CATCH_EXPR:
{
gimple c;
gimple_seq handler = NULL;
gimplify_and_add (CATCH_BODY (*expr_p), &handler);
c = gimple_build_catch (CATCH_TYPES (*expr_p), handler);
gimplify_seq_add_stmt (pre_p, c);
ret = GS_ALL_DONE;
break;
}
case EH_FILTER_EXPR:
{
gimple ehf;
gimple_seq failure = NULL;
gimplify_and_add (EH_FILTER_FAILURE (*expr_p), &failure);
ehf = gimple_build_eh_filter (EH_FILTER_TYPES (*expr_p), failure);
gimple_eh_filter_set_must_not_throw
(ehf, EH_FILTER_MUST_NOT_THROW (*expr_p));
gimplify_seq_add_stmt (pre_p, ehf);
ret = GS_ALL_DONE;
break;
}
case CHANGE_DYNAMIC_TYPE_EXPR:
{
gimple cdt;
ret = gimplify_expr (&CHANGE_DYNAMIC_TYPE_LOCATION (*expr_p),
pre_p, post_p, is_gimple_reg, fb_lvalue);
cdt = gimple_build_cdt (CHANGE_DYNAMIC_TYPE_NEW_TYPE (*expr_p),
CHANGE_DYNAMIC_TYPE_LOCATION (*expr_p));
gimplify_seq_add_stmt (pre_p, cdt);
ret = GS_ALL_DONE;
}
break;
case OBJ_TYPE_REF:
{
enum gimplify_status r0, r1;
r0 = gimplify_expr (&OBJ_TYPE_REF_OBJECT (*expr_p), pre_p,
post_p, is_gimple_val, fb_rvalue);
r1 = gimplify_expr (&OBJ_TYPE_REF_EXPR (*expr_p), pre_p,
post_p, is_gimple_val, fb_rvalue);
TREE_SIDE_EFFECTS (*expr_p) = 0;
ret = MIN (r0, r1);
}
break;
case LABEL_DECL:
/* We get here when taking the address of a label. We mark
the label as "forced"; meaning it can never be removed and
it is a potential target for any computed goto. */
FORCED_LABEL (*expr_p) = 1;
ret = GS_ALL_DONE;
break;
case STATEMENT_LIST:
ret = gimplify_statement_list (expr_p, pre_p);
break;
case WITH_SIZE_EXPR:
{
gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p,
post_p == &internal_post ? NULL : post_p,
gimple_test_f, fallback);
gimplify_expr (&TREE_OPERAND (*expr_p, 1), pre_p, post_p,
is_gimple_val, fb_rvalue);
}
break;
case VAR_DECL:
case PARM_DECL:
ret = gimplify_var_or_parm_decl (expr_p);
break;
case RESULT_DECL:
/* When within an OpenMP context, notice uses of variables. */
if (gimplify_omp_ctxp)
omp_notice_variable (gimplify_omp_ctxp, *expr_p, true);
ret = GS_ALL_DONE;
break;
case SSA_NAME:
/* Allow callbacks into the gimplifier during optimization. */
ret = GS_ALL_DONE;
break;
case OMP_PARALLEL:
gimplify_omp_parallel (expr_p, pre_p);
ret = GS_ALL_DONE;
break;
case OMP_TASK:
gimplify_omp_task (expr_p, pre_p);
ret = GS_ALL_DONE;
break;
case OMP_FOR:
ret = gimplify_omp_for (expr_p, pre_p);
break;
case OMP_SECTIONS:
case OMP_SINGLE:
gimplify_omp_workshare (expr_p, pre_p);
ret = GS_ALL_DONE;
break;
case OMP_SECTION:
case OMP_MASTER:
case OMP_ORDERED:
case OMP_CRITICAL:
{
gimple_seq body = NULL;
gimple g;
gimplify_and_add (OMP_BODY (*expr_p), &body);
switch (TREE_CODE (*expr_p))
{
case OMP_SECTION:
g = gimple_build_omp_section (body);
break;
case OMP_MASTER:
g = gimple_build_omp_master (body);
break;
case OMP_ORDERED:
g = gimple_build_omp_ordered (body);
break;
case OMP_CRITICAL:
g = gimple_build_omp_critical (body,
OMP_CRITICAL_NAME (*expr_p));
break;
default:
gcc_unreachable ();
}
gimplify_seq_add_stmt (pre_p, g);
ret = GS_ALL_DONE;
break;
}
case OMP_ATOMIC:
ret = gimplify_omp_atomic (expr_p, pre_p);
break;
case POINTER_PLUS_EXPR:
/* Convert ((type *)A)+offset into &A->field_of_type_and_offset.
The second is gimple immediate saving a need for extra statement.
*/
if (TREE_CODE (TREE_OPERAND (*expr_p, 1)) == INTEGER_CST
&& (tmp = maybe_fold_offset_to_address
(TREE_OPERAND (*expr_p, 0), TREE_OPERAND (*expr_p, 1),
TREE_TYPE (*expr_p))))
{
*expr_p = tmp;
break;
}
/* Convert (void *)&a + 4 into (void *)&a[1]. */
if (TREE_CODE (TREE_OPERAND (*expr_p, 0)) == NOP_EXPR
&& TREE_CODE (TREE_OPERAND (*expr_p, 1)) == INTEGER_CST
&& POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (TREE_OPERAND (*expr_p,
0),0)))
&& (tmp = maybe_fold_offset_to_address
(TREE_OPERAND (TREE_OPERAND (*expr_p, 0), 0),
TREE_OPERAND (*expr_p, 1),
TREE_TYPE (TREE_OPERAND (TREE_OPERAND (*expr_p, 0),
0)))))
{
*expr_p = fold_convert (TREE_TYPE (*expr_p), tmp);
break;
}
/* FALLTHRU */
default:
switch (TREE_CODE_CLASS (TREE_CODE (*expr_p)))
{
case tcc_comparison:
/* Handle comparison of objects of non scalar mode aggregates
with a call to memcmp. It would be nice to only have to do
this for variable-sized objects, but then we'd have to allow
the same nest of reference nodes we allow for MODIFY_EXPR and
that's too complex.
Compare scalar mode aggregates as scalar mode values. Using
memcmp for them would be very inefficient at best, and is
plain wrong if bitfields are involved. */
{
tree type = TREE_TYPE (TREE_OPERAND (*expr_p, 1));
if (!AGGREGATE_TYPE_P (type))
goto expr_2;
else if (TYPE_MODE (type) != BLKmode)
ret = gimplify_scalar_mode_aggregate_compare (expr_p);
else
ret = gimplify_variable_sized_compare (expr_p);
break;
}
/* If *EXPR_P does not need to be special-cased, handle it
according to its class. */
case tcc_unary:
ret = gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p,
post_p, is_gimple_val, fb_rvalue);
break;
case tcc_binary:
expr_2:
{
enum gimplify_status r0, r1;
r0 = gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p,
post_p, is_gimple_val, fb_rvalue);
r1 = gimplify_expr (&TREE_OPERAND (*expr_p, 1), pre_p,
post_p, is_gimple_val, fb_rvalue);
ret = MIN (r0, r1);
break;
}
case tcc_declaration:
case tcc_constant:
ret = GS_ALL_DONE;
goto dont_recalculate;
default:
gcc_assert (TREE_CODE (*expr_p) == TRUTH_AND_EXPR
|| TREE_CODE (*expr_p) == TRUTH_OR_EXPR
|| TREE_CODE (*expr_p) == TRUTH_XOR_EXPR);
goto expr_2;
}
recalculate_side_effects (*expr_p);
dont_recalculate:
break;
}
/* If we replaced *expr_p, gimplify again. */
if (ret == GS_OK && (*expr_p == NULL || *expr_p == save_expr))
ret = GS_ALL_DONE;
}
while (ret == GS_OK);
/* If we encountered an error_mark somewhere nested inside, either
stub out the statement or propagate the error back out. */
if (ret == GS_ERROR)
{
if (is_statement)
*expr_p = NULL;
goto out;
}
/* This was only valid as a return value from the langhook, which
we handled. Make sure it doesn't escape from any other context. */
gcc_assert (ret != GS_UNHANDLED);
if (fallback == fb_none && *expr_p && !is_gimple_stmt (*expr_p))
{
/* We aren't looking for a value, and we don't have a valid
statement. If it doesn't have side-effects, throw it away. */
if (!TREE_SIDE_EFFECTS (*expr_p))
*expr_p = NULL;
else if (!TREE_THIS_VOLATILE (*expr_p))
{
/* This is probably a _REF that contains something nested that
has side effects. Recurse through the operands to find it. */
enum tree_code code = TREE_CODE (*expr_p);
switch (code)
{
case COMPONENT_REF:
case REALPART_EXPR:
case IMAGPART_EXPR:
case VIEW_CONVERT_EXPR:
gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p,
gimple_test_f, fallback);
break;
case ARRAY_REF:
case ARRAY_RANGE_REF:
gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p, post_p,
gimple_test_f, fallback);
gimplify_expr (&TREE_OPERAND (*expr_p, 1), pre_p, post_p,
gimple_test_f, fallback);
break;
default:
/* Anything else with side-effects must be converted to
a valid statement before we get here. */
gcc_unreachable ();
}
*expr_p = NULL;
}
else if (COMPLETE_TYPE_P (TREE_TYPE (*expr_p))
&& TYPE_MODE (TREE_TYPE (*expr_p)) != BLKmode)
{
/* Historically, the compiler has treated a bare reference
to a non-BLKmode volatile lvalue as forcing a load. */
tree type = TYPE_MAIN_VARIANT (TREE_TYPE (*expr_p));
/* Normally, we do not want to create a temporary for a
TREE_ADDRESSABLE type because such a type should not be
copied by bitwise-assignment. However, we make an
exception here, as all we are doing here is ensuring that
we read the bytes that make up the type. We use
create_tmp_var_raw because create_tmp_var will abort when
given a TREE_ADDRESSABLE type. */
tree tmp = create_tmp_var_raw (type, "vol");
gimple_add_tmp_var (tmp);
gimplify_assign (tmp, *expr_p, pre_p);
*expr_p = NULL;
}
else
/* We can't do anything useful with a volatile reference to
an incomplete type, so just throw it away. Likewise for
a BLKmode type, since any implicit inner load should
already have been turned into an explicit one by the
gimplification process. */
*expr_p = NULL;
}
/* If we are gimplifying at the statement level, we're done. Tack
everything together and return. */
if (fallback == fb_none || is_statement)
{
/* Since *EXPR_P has been converted into a GIMPLE tuple, clear
it out for GC to reclaim it. */
*expr_p = NULL_TREE;
if (!gimple_seq_empty_p (internal_pre)
|| !gimple_seq_empty_p (internal_post))
{
gimplify_seq_add_seq (&internal_pre, internal_post);
gimplify_seq_add_seq (pre_p, internal_pre);
}
/* The result of gimplifying *EXPR_P is going to be the last few
statements in *PRE_P and *POST_P. Add location information
to all the statements that were added by the gimplification
helpers. */
if (!gimple_seq_empty_p (*pre_p))
annotate_all_with_location_after (*pre_p, pre_last_gsi, input_location);
if (!gimple_seq_empty_p (*post_p))
annotate_all_with_location_after (*post_p, post_last_gsi,
input_location);
goto out;
}
#ifdef ENABLE_GIMPLE_CHECKING
if (*expr_p)
{
enum tree_code code = TREE_CODE (*expr_p);
/* These expressions should already be in gimple IR form. */
gcc_assert (code != MODIFY_EXPR
&& code != ASM_EXPR
&& code != BIND_EXPR
&& code != CATCH_EXPR
&& (code != COND_EXPR || gimplify_ctxp->allow_rhs_cond_expr)
&& code != EH_FILTER_EXPR
&& code != GOTO_EXPR
&& code != LABEL_EXPR
&& code != LOOP_EXPR
&& code != RESX_EXPR
&& code != SWITCH_EXPR
&& code != TRY_FINALLY_EXPR
&& code != OMP_CRITICAL
&& code != OMP_FOR
&& code != OMP_MASTER
&& code != OMP_ORDERED
&& code != OMP_PARALLEL
&& code != OMP_SECTIONS
&& code != OMP_SECTION
&& code != OMP_SINGLE);
}
#endif
/* Otherwise we're gimplifying a subexpression, so the resulting
value is interesting. If it's a valid operand that matches
GIMPLE_TEST_F, we're done. Unless we are handling some
post-effects internally; if that's the case, we need to copy into
a temporary before adding the post-effects to POST_P. */
if (gimple_seq_empty_p (internal_post) && (*gimple_test_f) (*expr_p))
goto out;
/* Otherwise, we need to create a new temporary for the gimplified
expression. */
/* We can't return an lvalue if we have an internal postqueue. The
object the lvalue refers to would (probably) be modified by the
postqueue; we need to copy the value out first, which means an
rvalue. */
if ((fallback & fb_lvalue)
&& gimple_seq_empty_p (internal_post)
&& is_gimple_addressable (*expr_p))
{
/* An lvalue will do. Take the address of the expression, store it
in a temporary, and replace the expression with an INDIRECT_REF of
that temporary. */
tmp = build_fold_addr_expr (*expr_p);
gimplify_expr (&tmp, pre_p, post_p, is_gimple_reg, fb_rvalue);
*expr_p = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (tmp)), tmp);
}
else if ((fallback & fb_rvalue) && is_gimple_formal_tmp_or_call_rhs (*expr_p))
{
/* An rvalue will do. Assign the gimplified expression into a
new temporary TMP and replace the original expression with
TMP. First, make sure that the expression has a type so that
it can be assigned into a temporary. */
gcc_assert (!VOID_TYPE_P (TREE_TYPE (*expr_p)));
if (!gimple_seq_empty_p (internal_post) || (fallback & fb_lvalue))
/* The postqueue might change the value of the expression between
the initialization and use of the temporary, so we can't use a
formal temp. FIXME do we care? */
*expr_p = get_initialized_tmp_var (*expr_p, pre_p, post_p);
else
*expr_p = get_formal_tmp_var (*expr_p, pre_p);
if (TREE_CODE (*expr_p) != SSA_NAME)
DECL_GIMPLE_FORMAL_TEMP_P (*expr_p) = 1;
}
else
{
#ifdef ENABLE_GIMPLE_CHECKING
if (!(fallback & fb_mayfail))
{
fprintf (stderr, "gimplification failed:\n");
print_generic_expr (stderr, *expr_p, 0);
debug_tree (*expr_p);
internal_error ("gimplification failed");
}
#endif
gcc_assert (fallback & fb_mayfail);
/* If this is an asm statement, and the user asked for the
impossible, don't die. Fail and let gimplify_asm_expr
issue an error. */
ret = GS_ERROR;
goto out;
}
/* Make sure the temporary matches our predicate. */
gcc_assert ((*gimple_test_f) (*expr_p));
if (!gimple_seq_empty_p (internal_post))
{
annotate_all_with_location (internal_post, input_location);
gimplify_seq_add_seq (pre_p, internal_post);
}
out:
input_location = saved_location;
return ret;
}
/* Look through TYPE for variable-sized objects and gimplify each such
size that we find. Add to LIST_P any statements generated. */
void
gimplify_type_sizes (tree type, gimple_seq *list_p)
{
tree field, t;
if (type == NULL || type == error_mark_node)
return;
/* We first do the main variant, then copy into any other variants. */
type = TYPE_MAIN_VARIANT (type);
/* Avoid infinite recursion. */
if (TYPE_SIZES_GIMPLIFIED (type))
return;
TYPE_SIZES_GIMPLIFIED (type) = 1;
switch (TREE_CODE (type))
{
case INTEGER_TYPE:
case ENUMERAL_TYPE:
case BOOLEAN_TYPE:
case REAL_TYPE:
case FIXED_POINT_TYPE:
gimplify_one_sizepos (&TYPE_MIN_VALUE (type), list_p);
gimplify_one_sizepos (&TYPE_MAX_VALUE (type), list_p);
for (t = TYPE_NEXT_VARIANT (type); t; t = TYPE_NEXT_VARIANT (t))
{
TYPE_MIN_VALUE (t) = TYPE_MIN_VALUE (type);
TYPE_MAX_VALUE (t) = TYPE_MAX_VALUE (type);
}
break;
case ARRAY_TYPE:
/* These types may not have declarations, so handle them here. */
gimplify_type_sizes (TREE_TYPE (type), list_p);
gimplify_type_sizes (TYPE_DOMAIN (type), list_p);
/* When not optimizing, ensure VLA bounds aren't removed. */
if (!optimize
&& TYPE_DOMAIN (type)
&& INTEGRAL_TYPE_P (TYPE_DOMAIN (type)))
{
t = TYPE_MIN_VALUE (TYPE_DOMAIN (type));
if (t && TREE_CODE (t) == VAR_DECL && DECL_ARTIFICIAL (t))
DECL_IGNORED_P (t) = 0;
t = TYPE_MAX_VALUE (TYPE_DOMAIN (type));
if (t && TREE_CODE (t) == VAR_DECL && DECL_ARTIFICIAL (t))
DECL_IGNORED_P (t) = 0;
}
break;
case RECORD_TYPE:
case UNION_TYPE:
case QUAL_UNION_TYPE:
for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
if (TREE_CODE (field) == FIELD_DECL)
{
gimplify_one_sizepos (&DECL_FIELD_OFFSET (field), list_p);
gimplify_one_sizepos (&DECL_SIZE (field), list_p);
gimplify_one_sizepos (&DECL_SIZE_UNIT (field), list_p);
gimplify_type_sizes (TREE_TYPE (field), list_p);
}
break;
case POINTER_TYPE:
case REFERENCE_TYPE:
/* We used to recurse on the pointed-to type here, which turned out to
be incorrect because its definition might refer to variables not
yet initialized at this point if a forward declaration is involved.
It was actually useful for anonymous pointed-to types to ensure
that the sizes evaluation dominates every possible later use of the
values. Restricting to such types here would be safe since there
is no possible forward declaration around, but would introduce an
undesirable middle-end semantic to anonymity. We then defer to
front-ends the responsibility of ensuring that the sizes are
evaluated both early and late enough, e.g. by attaching artificial
type declarations to the tree. */
break;
default:
break;
}
gimplify_one_sizepos (&TYPE_SIZE (type), list_p);
gimplify_one_sizepos (&TYPE_SIZE_UNIT (type), list_p);
for (t = TYPE_NEXT_VARIANT (type); t; t = TYPE_NEXT_VARIANT (t))
{
TYPE_SIZE (t) = TYPE_SIZE (type);
TYPE_SIZE_UNIT (t) = TYPE_SIZE_UNIT (type);
TYPE_SIZES_GIMPLIFIED (t) = 1;
}
}
/* A subroutine of gimplify_type_sizes to make sure that *EXPR_P,
a size or position, has had all of its SAVE_EXPRs evaluated.
We add any required statements to *STMT_P. */
void
gimplify_one_sizepos (tree *expr_p, gimple_seq *stmt_p)
{
tree type, expr = *expr_p;
/* We don't do anything if the value isn't there, is constant, or contains
A PLACEHOLDER_EXPR. We also don't want to do anything if it's already
a VAR_DECL. If it's a VAR_DECL from another function, the gimplifier
will want to replace it with a new variable, but that will cause problems
if this type is from outside the function. It's OK to have that here. */
if (expr == NULL_TREE || TREE_CONSTANT (expr)
|| TREE_CODE (expr) == VAR_DECL
|| CONTAINS_PLACEHOLDER_P (expr))
return;
type = TREE_TYPE (expr);
*expr_p = unshare_expr (expr);
gimplify_expr (expr_p, stmt_p, NULL, is_gimple_val, fb_rvalue);
expr = *expr_p;
/* Verify that we've an exact type match with the original expression.
In particular, we do not wish to drop a "sizetype" in favour of a
type of similar dimensions. We don't want to pollute the generic
type-stripping code with this knowledge because it doesn't matter
for the bulk of GENERIC/GIMPLE. It only matters that TYPE_SIZE_UNIT
and friends retain their "sizetype-ness". */
if (TREE_TYPE (expr) != type
&& TREE_CODE (type) == INTEGER_TYPE
&& TYPE_IS_SIZETYPE (type))
{
tree tmp;
gimple stmt;
*expr_p = create_tmp_var (type, NULL);
tmp = build1 (NOP_EXPR, type, expr);
stmt = gimplify_assign (*expr_p, tmp, stmt_p);
if (EXPR_HAS_LOCATION (expr))
gimple_set_location (stmt, *EXPR_LOCUS (expr));
else
gimple_set_location (stmt, input_location);
}
}
/* Gimplify the body of statements pointed to by BODY_P and return a
GIMPLE_BIND containing the sequence of GIMPLE statements
corresponding to BODY_P. FNDECL is the function decl containing
*BODY_P. */
gimple
gimplify_body (tree *body_p, tree fndecl, bool do_parms)
{
location_t saved_location = input_location;
gimple_seq parm_stmts, seq;
gimple outer_bind;
struct gimplify_ctx gctx;
timevar_push (TV_TREE_GIMPLIFY);
/* Initialize for optimize_insn_for_s{ize,peed}_p possibly called during
gimplification. */
default_rtl_profile ();
gcc_assert (gimplify_ctxp == NULL);
push_gimplify_context (&gctx);
/* Unshare most shared trees in the body and in that of any nested functions.
It would seem we don't have to do this for nested functions because
they are supposed to be output and then the outer function gimplified
first, but the g++ front end doesn't always do it that way. */
unshare_body (body_p, fndecl);
unvisit_body (body_p, fndecl);
/* Make sure input_location isn't set to something weird. */
input_location = DECL_SOURCE_LOCATION (fndecl);
/* Resolve callee-copies. This has to be done before processing
the body so that DECL_VALUE_EXPR gets processed correctly. */
parm_stmts = (do_parms) ? gimplify_parameters () : NULL;
/* Gimplify the function's body. */
seq = NULL;
gimplify_stmt (body_p, &seq);
outer_bind = gimple_seq_first_stmt (seq);
if (!outer_bind)
{
outer_bind = gimple_build_nop ();
gimplify_seq_add_stmt (&seq, outer_bind);
}
/* The body must contain exactly one statement, a GIMPLE_BIND. If this is
not the case, wrap everything in a GIMPLE_BIND to make it so. */
if (gimple_code (outer_bind) == GIMPLE_BIND
&& gimple_seq_first (seq) == gimple_seq_last (seq))
;
else
outer_bind = gimple_build_bind (NULL_TREE, seq, NULL);
*body_p = NULL_TREE;
/* If we had callee-copies statements, insert them at the beginning
of the function. */
if (!gimple_seq_empty_p (parm_stmts))
{
gimplify_seq_add_seq (&parm_stmts, gimple_bind_body (outer_bind));
gimple_bind_set_body (outer_bind, parm_stmts);
}
pop_gimplify_context (outer_bind);
gcc_assert (gimplify_ctxp == NULL);
#ifdef ENABLE_TYPES_CHECKING
if (!errorcount && !sorrycount)
verify_types_in_gimple_seq (gimple_bind_body (outer_bind));
#endif
timevar_pop (TV_TREE_GIMPLIFY);
input_location = saved_location;
return outer_bind;
}
/* Entry point to the gimplification pass. FNDECL is the FUNCTION_DECL
node for the function we want to gimplify.
Returns the sequence of GIMPLE statements corresponding to the body
of FNDECL. */
void
gimplify_function_tree (tree fndecl)
{
tree oldfn, parm, ret;
gimple_seq seq;
gimple bind;
oldfn = current_function_decl;
current_function_decl = fndecl;
if (DECL_STRUCT_FUNCTION (fndecl))
push_cfun (DECL_STRUCT_FUNCTION (fndecl));
else
push_struct_function (fndecl);
for (parm = DECL_ARGUMENTS (fndecl); parm ; parm = TREE_CHAIN (parm))
{
/* Preliminarily mark non-addressed complex variables as eligible
for promotion to gimple registers. We'll transform their uses
as we find them. */
if ((TREE_CODE (TREE_TYPE (parm)) == COMPLEX_TYPE
|| TREE_CODE (TREE_TYPE (parm)) == VECTOR_TYPE)
&& !TREE_THIS_VOLATILE (parm)
&& !needs_to_live_in_memory (parm))
DECL_GIMPLE_REG_P (parm) = 1;
}
ret = DECL_RESULT (fndecl);
if ((TREE_CODE (TREE_TYPE (ret)) == COMPLEX_TYPE
|| TREE_CODE (TREE_TYPE (ret)) == VECTOR_TYPE)
&& !needs_to_live_in_memory (ret))
DECL_GIMPLE_REG_P (ret) = 1;
bind = gimplify_body (&DECL_SAVED_TREE (fndecl), fndecl, true);
/* The tree body of the function is no longer needed, replace it
with the new GIMPLE body. */
seq = gimple_seq_alloc ();
gimple_seq_add_stmt (&seq, bind);
gimple_set_body (fndecl, seq);
/* If we're instrumenting function entry/exit, then prepend the call to
the entry hook and wrap the whole function in a TRY_FINALLY_EXPR to
catch the exit hook. */
/* ??? Add some way to ignore exceptions for this TFE. */
if (flag_instrument_function_entry_exit
&& !DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (fndecl)
&& !flag_instrument_functions_exclude_p (fndecl))
{
tree x;
gimple new_bind;
gimple tf;
gimple_seq cleanup = NULL, body = NULL;
x = implicit_built_in_decls[BUILT_IN_PROFILE_FUNC_EXIT];
gimplify_seq_add_stmt (&cleanup, gimple_build_call (x, 0));
tf = gimple_build_try (seq, cleanup, GIMPLE_TRY_FINALLY);
x = implicit_built_in_decls[BUILT_IN_PROFILE_FUNC_ENTER];
gimplify_seq_add_stmt (&body, gimple_build_call (x, 0));
gimplify_seq_add_stmt (&body, tf);
new_bind = gimple_build_bind (NULL, body, gimple_bind_block (bind));
/* Clear the block for BIND, since it is no longer directly inside
the function, but within a try block. */
gimple_bind_set_block (bind, NULL);
/* Replace the current function body with the body
wrapped in the try/finally TF. */
seq = gimple_seq_alloc ();
gimple_seq_add_stmt (&seq, new_bind);
gimple_set_body (fndecl, seq);
}
DECL_SAVED_TREE (fndecl) = NULL_TREE;
current_function_decl = oldfn;
pop_cfun ();
}
/* Some transformations like inlining may invalidate the GIMPLE form
for operands. This function traverses all the operands in STMT and
gimplifies anything that is not a valid gimple operand. Any new
GIMPLE statements are inserted before *GSI_P. */
void
gimple_regimplify_operands (gimple stmt, gimple_stmt_iterator *gsi_p)
{
size_t i, num_ops;
tree orig_lhs = NULL_TREE, lhs, t;
gimple_seq pre = NULL;
gimple post_stmt = NULL;
struct gimplify_ctx gctx;
push_gimplify_context (&gctx);
gimplify_ctxp->into_ssa = gimple_in_ssa_p (cfun);
switch (gimple_code (stmt))
{
case GIMPLE_COND:
gimplify_expr (gimple_cond_lhs_ptr (stmt), &pre, NULL,
is_gimple_val, fb_rvalue);
gimplify_expr (gimple_cond_rhs_ptr (stmt), &pre, NULL,
is_gimple_val, fb_rvalue);
break;
case GIMPLE_SWITCH:
gimplify_expr (gimple_switch_index_ptr (stmt), &pre, NULL,
is_gimple_val, fb_rvalue);
break;
case GIMPLE_OMP_ATOMIC_LOAD:
gimplify_expr (gimple_omp_atomic_load_rhs_ptr (stmt), &pre, NULL,
is_gimple_val, fb_rvalue);
break;
case GIMPLE_ASM:
{
size_t i, noutputs = gimple_asm_noutputs (stmt);
const char *constraint, **oconstraints;
bool allows_mem, allows_reg, is_inout;
oconstraints
= (const char **) alloca ((noutputs) * sizeof (const char *));
for (i = 0; i < noutputs; i++)
{
tree op = gimple_asm_output_op (stmt, i);
constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (op)));
oconstraints[i] = constraint;
parse_output_constraint (&constraint, i, 0, 0, &allows_mem,
&allows_reg, &is_inout);
gimplify_expr (&TREE_VALUE (op), &pre, NULL,
is_inout ? is_gimple_min_lval : is_gimple_lvalue,
fb_lvalue | fb_mayfail);
}
for (i = 0; i < gimple_asm_ninputs (stmt); i++)
{
tree op = gimple_asm_input_op (stmt, i);
constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (op)));
parse_input_constraint (&constraint, 0, 0, noutputs, 0,
oconstraints, &allows_mem, &allows_reg);
if (TREE_ADDRESSABLE (TREE_TYPE (TREE_VALUE (op))) && allows_mem)
allows_reg = 0;
if (!allows_reg && allows_mem)
gimplify_expr (&TREE_VALUE (op), &pre, NULL,
is_gimple_lvalue, fb_lvalue | fb_mayfail);
else
gimplify_expr (&TREE_VALUE (op), &pre, NULL,
is_gimple_asm_val, fb_rvalue);
}
}
break;
default:
/* NOTE: We start gimplifying operands from last to first to
make sure that side-effects on the RHS of calls, assignments
and ASMs are executed before the LHS. The ordering is not
important for other statements. */
num_ops = gimple_num_ops (stmt);
orig_lhs = gimple_get_lhs (stmt);
for (i = num_ops; i > 0; i--)
{
tree op = gimple_op (stmt, i - 1);
if (op == NULL_TREE)
continue;
if (i == 1 && (is_gimple_call (stmt) || is_gimple_assign (stmt)))
gimplify_expr (&op, &pre, NULL, is_gimple_lvalue, fb_lvalue);
else if (i == 2
&& is_gimple_assign (stmt)
&& num_ops == 2
&& get_gimple_rhs_class (gimple_expr_code (stmt))
== GIMPLE_SINGLE_RHS)
gimplify_expr (&op, &pre, NULL,
rhs_predicate_for (gimple_assign_lhs (stmt)),
fb_rvalue);
else if (i == 2 && is_gimple_call (stmt))
{
if (TREE_CODE (op) == FUNCTION_DECL)
continue;
gimplify_expr (&op, &pre, NULL, is_gimple_call_addr, fb_rvalue);
}
else
gimplify_expr (&op, &pre, NULL, is_gimple_val, fb_rvalue);
gimple_set_op (stmt, i - 1, op);
}
lhs = gimple_get_lhs (stmt);
/* If the LHS changed it in a way that requires a simple RHS,
create temporary. */
if (lhs && !is_gimple_formal_tmp_var (lhs))
{
bool need_temp = false;
if (is_gimple_assign (stmt)
&& num_ops == 2
&& get_gimple_rhs_class (gimple_expr_code (stmt))
== GIMPLE_SINGLE_RHS)
gimplify_expr (gimple_assign_rhs1_ptr (stmt), &pre, NULL,
rhs_predicate_for (gimple_assign_lhs (stmt)),
fb_rvalue);
else if (is_gimple_reg (lhs))
{
if (is_gimple_reg_type (TREE_TYPE (lhs)))
{
if (is_gimple_call (stmt))
{
i = gimple_call_flags (stmt);
if ((i & ECF_LOOPING_CONST_OR_PURE)
|| !(i & (ECF_CONST | ECF_PURE)))
need_temp = true;
}
if (stmt_can_throw_internal (stmt))
need_temp = true;
}
}
else
{
if (is_gimple_reg_type (TREE_TYPE (lhs)))
need_temp = true;
else if (TYPE_MODE (TREE_TYPE (lhs)) != BLKmode)
{
if (is_gimple_call (stmt))
{
tree fndecl = gimple_call_fndecl (stmt);
if (!aggregate_value_p (TREE_TYPE (lhs), fndecl)
&& !(fndecl && DECL_RESULT (fndecl)
&& DECL_BY_REFERENCE (DECL_RESULT (fndecl))))
need_temp = true;
}
else
need_temp = true;
}
}
if (need_temp)
{
tree temp = create_tmp_var (TREE_TYPE (lhs), NULL);
DECL_GIMPLE_FORMAL_TEMP_P (temp) = 1;
if (TREE_CODE (TREE_TYPE (lhs)) == COMPLEX_TYPE
|| TREE_CODE (TREE_TYPE (lhs)) == VECTOR_TYPE)
DECL_GIMPLE_REG_P (temp) = 1;
if (TREE_CODE (orig_lhs) == SSA_NAME)
orig_lhs = SSA_NAME_VAR (orig_lhs);
if (TREE_CODE (orig_lhs) == VAR_DECL
&& DECL_BASED_ON_RESTRICT_P (orig_lhs))
{
DECL_BASED_ON_RESTRICT_P (temp) = 1;
SET_DECL_RESTRICT_BASE (temp,
DECL_GET_RESTRICT_BASE (orig_lhs));
}
if (gimple_in_ssa_p (cfun))
temp = make_ssa_name (temp, NULL);
gimple_set_lhs (stmt, temp);
post_stmt = gimple_build_assign (lhs, temp);
if (TREE_CODE (lhs) == SSA_NAME)
SSA_NAME_DEF_STMT (lhs) = post_stmt;
}
}
break;
}
if (gimple_referenced_vars (cfun))
for (t = gimplify_ctxp->temps; t ; t = TREE_CHAIN (t))
add_referenced_var (t);
if (!gimple_seq_empty_p (pre))
{
if (gimple_in_ssa_p (cfun))
{
gimple_stmt_iterator i;
for (i = gsi_start (pre); !gsi_end_p (i); gsi_next (&i))
mark_symbols_for_renaming (gsi_stmt (i));
}
gsi_insert_seq_before (gsi_p, pre, GSI_SAME_STMT);
}
if (post_stmt)
gsi_insert_after (gsi_p, post_stmt, GSI_NEW_STMT);
pop_gimplify_context (NULL);
}
/* Expands EXPR to list of gimple statements STMTS. If SIMPLE is true,
force the result to be either ssa_name or an invariant, otherwise
just force it to be a rhs expression. If VAR is not NULL, make the
base variable of the final destination be VAR if suitable. */
tree
force_gimple_operand (tree expr, gimple_seq *stmts, bool simple, tree var)
{
tree t;
enum gimplify_status ret;
gimple_predicate gimple_test_f;
struct gimplify_ctx gctx;
*stmts = NULL;
if (is_gimple_val (expr))
return expr;
gimple_test_f = simple ? is_gimple_val : is_gimple_reg_rhs;
push_gimplify_context (&gctx);
gimplify_ctxp->into_ssa = gimple_in_ssa_p (cfun);
gimplify_ctxp->allow_rhs_cond_expr = true;
if (var)
expr = build2 (MODIFY_EXPR, TREE_TYPE (var), var, expr);
if (TREE_CODE (expr) != MODIFY_EXPR
&& TREE_TYPE (expr) == void_type_node)
{
gimplify_and_add (expr, stmts);
expr = NULL_TREE;
}
else
{
ret = gimplify_expr (&expr, stmts, NULL, gimple_test_f, fb_rvalue);
gcc_assert (ret != GS_ERROR);
}
if (gimple_referenced_vars (cfun))
for (t = gimplify_ctxp->temps; t ; t = TREE_CHAIN (t))
add_referenced_var (t);
pop_gimplify_context (NULL);
return expr;
}
/* Invokes force_gimple_operand for EXPR with parameters SIMPLE_P and VAR. If
some statements are produced, emits them at GSI. If BEFORE is true.
the statements are appended before GSI, otherwise they are appended after
it. M specifies the way GSI moves after insertion (GSI_SAME_STMT or
GSI_CONTINUE_LINKING are the usual values). */
tree
force_gimple_operand_gsi (gimple_stmt_iterator *gsi, tree expr,
bool simple_p, tree var, bool before,
enum gsi_iterator_update m)
{
gimple_seq stmts;
expr = force_gimple_operand (expr, &stmts, simple_p, var);
if (!gimple_seq_empty_p (stmts))
{
if (gimple_in_ssa_p (cfun))
{
gimple_stmt_iterator i;
for (i = gsi_start (stmts); !gsi_end_p (i); gsi_next (&i))
mark_symbols_for_renaming (gsi_stmt (i));
}
if (before)
gsi_insert_seq_before (gsi, stmts, m);
else
gsi_insert_seq_after (gsi, stmts, m);
}
return expr;
}
#include "gt-gimplify.h"
|
draw.c
|
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% DDDD RRRR AAA W W %
% D D R R A A W W %
% D D RRRR AAAAA W W W %
% D D R RN A A WW WW %
% DDDD R R A A W W %
% %
% %
% MagickCore Image Drawing Methods %
% %
% %
% Software Design %
% Cristy %
% July 1998 %
% %
% %
% Copyright 1999-2017 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://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. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Bill Radcliffe of Corbis (www.corbis.com) contributed the polygon
% rendering code based on Paul Heckbert's "Concave Polygon Scan Conversion",
% Graphics Gems, 1990. Leonard Rosenthal and David Harr of Appligent
% (www.appligent.com) contributed the dash pattern, linecap stroking
% algorithm, and minor rendering improvements.
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/annotate.h"
#include "MagickCore/artifact.h"
#include "MagickCore/blob.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-private.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/channel.h"
#include "MagickCore/color.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/draw.h"
#include "MagickCore/draw-private.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/gem.h"
#include "MagickCore/geometry.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/paint.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel-private.h"
#include "MagickCore/property.h"
#include "MagickCore/resample.h"
#include "MagickCore/resample-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/token.h"
#include "MagickCore/transform-private.h"
#include "MagickCore/utility.h"
/*
Define declarations.
*/
#define BezierQuantum 200
#define DrawEpsilon (1.0e-10)
/*
Typedef declarations.
*/
typedef struct _EdgeInfo
{
SegmentInfo
bounds;
double
scanline;
PointInfo
*points;
size_t
number_points;
ssize_t
direction;
MagickBooleanType
ghostline;
size_t
highwater;
} EdgeInfo;
typedef struct _ElementInfo
{
double
cx,
cy,
major,
minor,
angle;
} ElementInfo;
typedef struct _PolygonInfo
{
EdgeInfo
*edges;
size_t
number_edges;
} PolygonInfo;
typedef enum
{
MoveToCode,
OpenCode,
GhostlineCode,
LineToCode,
EndCode
} PathInfoCode;
typedef struct _PathInfo
{
PointInfo
point;
PathInfoCode
code;
} PathInfo;
/*
Forward declarations.
*/
static MagickBooleanType
DrawStrokePolygon(Image *,const DrawInfo *,const PrimitiveInfo *,
ExceptionInfo *);
static PrimitiveInfo
*TraceStrokePolygon(const DrawInfo *,const PrimitiveInfo *);
static size_t
TracePath(PrimitiveInfo *,const char *);
static void
TraceArc(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo),
TraceArcPath(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo,
const double,const MagickBooleanType,const MagickBooleanType),
TraceBezier(PrimitiveInfo *,const size_t),
TraceCircle(PrimitiveInfo *,const PointInfo,const PointInfo),
TraceEllipse(PrimitiveInfo *,const PointInfo,const PointInfo,
const PointInfo),
TraceLine(PrimitiveInfo *,const PointInfo,const PointInfo),
TraceRectangle(PrimitiveInfo *,const PointInfo,const PointInfo),
TraceRoundRectangle(PrimitiveInfo *,const PointInfo,const PointInfo,
PointInfo),
TraceSquareLinecap(PrimitiveInfo *,const size_t,const double);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e D r a w I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireDrawInfo() returns a DrawInfo structure properly initialized.
%
% The format of the AcquireDrawInfo method is:
%
% DrawInfo *AcquireDrawInfo(void)
%
*/
MagickExport DrawInfo *AcquireDrawInfo(void)
{
DrawInfo
*draw_info;
draw_info=(DrawInfo *) AcquireMagickMemory(sizeof(*draw_info));
if (draw_info == (DrawInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
GetDrawInfo((ImageInfo *) NULL,draw_info);
return(draw_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e D r a w I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneDrawInfo() makes a copy of the given draw_info structure. If NULL
% is specified, a new DrawInfo structure is created initialized to default
% values.
%
% The format of the CloneDrawInfo method is:
%
% DrawInfo *CloneDrawInfo(const ImageInfo *image_info,
% const DrawInfo *draw_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o draw_info: the draw info.
%
*/
MagickExport DrawInfo *CloneDrawInfo(const ImageInfo *image_info,
const DrawInfo *draw_info)
{
DrawInfo
*clone_info;
ExceptionInfo
*exception;
clone_info=(DrawInfo *) AcquireMagickMemory(sizeof(*clone_info));
if (clone_info == (DrawInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
GetDrawInfo(image_info,clone_info);
if (draw_info == (DrawInfo *) NULL)
return(clone_info);
exception=AcquireExceptionInfo();
if (clone_info->primitive != (char *) NULL)
(void) CloneString(&clone_info->primitive,draw_info->primitive);
if (draw_info->geometry != (char *) NULL)
(void) CloneString(&clone_info->geometry,draw_info->geometry);
clone_info->viewbox=draw_info->viewbox;
clone_info->affine=draw_info->affine;
clone_info->gravity=draw_info->gravity;
clone_info->fill=draw_info->fill;
clone_info->stroke=draw_info->stroke;
clone_info->stroke_width=draw_info->stroke_width;
if (draw_info->fill_pattern != (Image *) NULL)
clone_info->fill_pattern=CloneImage(draw_info->fill_pattern,0,0,MagickTrue,
exception);
if (draw_info->stroke_pattern != (Image *) NULL)
clone_info->stroke_pattern=CloneImage(draw_info->stroke_pattern,0,0,
MagickTrue,exception);
clone_info->stroke_antialias=draw_info->stroke_antialias;
clone_info->text_antialias=draw_info->text_antialias;
clone_info->fill_rule=draw_info->fill_rule;
clone_info->linecap=draw_info->linecap;
clone_info->linejoin=draw_info->linejoin;
clone_info->miterlimit=draw_info->miterlimit;
clone_info->dash_offset=draw_info->dash_offset;
clone_info->decorate=draw_info->decorate;
clone_info->compose=draw_info->compose;
if (draw_info->text != (char *) NULL)
(void) CloneString(&clone_info->text,draw_info->text);
if (draw_info->font != (char *) NULL)
(void) CloneString(&clone_info->font,draw_info->font);
if (draw_info->metrics != (char *) NULL)
(void) CloneString(&clone_info->metrics,draw_info->metrics);
if (draw_info->family != (char *) NULL)
(void) CloneString(&clone_info->family,draw_info->family);
clone_info->style=draw_info->style;
clone_info->stretch=draw_info->stretch;
clone_info->weight=draw_info->weight;
if (draw_info->encoding != (char *) NULL)
(void) CloneString(&clone_info->encoding,draw_info->encoding);
clone_info->pointsize=draw_info->pointsize;
clone_info->kerning=draw_info->kerning;
clone_info->interline_spacing=draw_info->interline_spacing;
clone_info->interword_spacing=draw_info->interword_spacing;
clone_info->direction=draw_info->direction;
if (draw_info->density != (char *) NULL)
(void) CloneString(&clone_info->density,draw_info->density);
clone_info->align=draw_info->align;
clone_info->undercolor=draw_info->undercolor;
clone_info->border_color=draw_info->border_color;
if (draw_info->server_name != (char *) NULL)
(void) CloneString(&clone_info->server_name,draw_info->server_name);
if (draw_info->dash_pattern != (double *) NULL)
{
register ssize_t
x;
for (x=0; fabs(draw_info->dash_pattern[x]) >= DrawEpsilon; x++) ;
clone_info->dash_pattern=(double *) AcquireQuantumMemory((size_t) x+1UL,
sizeof(*clone_info->dash_pattern));
if (clone_info->dash_pattern == (double *) NULL)
ThrowFatalException(ResourceLimitFatalError,
"UnableToAllocateDashPattern");
(void) CopyMagickMemory(clone_info->dash_pattern,draw_info->dash_pattern,
(size_t) (x+1)*sizeof(*clone_info->dash_pattern));
}
clone_info->gradient=draw_info->gradient;
if (draw_info->gradient.stops != (StopInfo *) NULL)
{
size_t
number_stops;
number_stops=clone_info->gradient.number_stops;
clone_info->gradient.stops=(StopInfo *) AcquireQuantumMemory((size_t)
number_stops,sizeof(*clone_info->gradient.stops));
if (clone_info->gradient.stops == (StopInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,
"UnableToAllocateDashPattern");
(void) CopyMagickMemory(clone_info->gradient.stops,
draw_info->gradient.stops,(size_t) number_stops*
sizeof(*clone_info->gradient.stops));
}
if (draw_info->clip_mask != (char *) NULL)
(void) CloneString(&clone_info->clip_mask,draw_info->clip_mask);
clone_info->bounds=draw_info->bounds;
clone_info->clip_units=draw_info->clip_units;
clone_info->render=draw_info->render;
clone_info->fill_alpha=draw_info->fill_alpha;
clone_info->stroke_alpha=draw_info->stroke_alpha;
clone_info->element_reference=draw_info->element_reference;
clone_info->debug=IsEventLogging();
exception=DestroyExceptionInfo(exception);
return(clone_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C o n v e r t P a t h T o P o l y g o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ConvertPathToPolygon() converts a path to the more efficient sorted
% rendering form.
%
% The format of the ConvertPathToPolygon method is:
%
% PolygonInfo *ConvertPathToPolygon(const DrawInfo *draw_info,
% const PathInfo *path_info)
%
% A description of each parameter follows:
%
% o Method ConvertPathToPolygon returns the path in a more efficient sorted
% rendering form of type PolygonInfo.
%
% o draw_info: Specifies a pointer to an DrawInfo structure.
%
% o path_info: Specifies a pointer to an PathInfo structure.
%
%
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int CompareEdges(const void *x,const void *y)
{
register const EdgeInfo
*p,
*q;
/*
Compare two edges.
*/
p=(const EdgeInfo *) x;
q=(const EdgeInfo *) y;
if ((p->points[0].y-DrawEpsilon) > q->points[0].y)
return(1);
if ((p->points[0].y+DrawEpsilon) < q->points[0].y)
return(-1);
if ((p->points[0].x-DrawEpsilon) > q->points[0].x)
return(1);
if ((p->points[0].x+DrawEpsilon) < q->points[0].x)
return(-1);
if (((p->points[1].x-p->points[0].x)*(q->points[1].y-q->points[0].y)-
(p->points[1].y-p->points[0].y)*(q->points[1].x-q->points[0].x)) > 0.0)
return(1);
return(-1);
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static void LogPolygonInfo(const PolygonInfo *polygon_info)
{
register EdgeInfo
*p;
register ssize_t
i,
j;
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin active-edge");
p=polygon_info->edges;
for (i=0; i < (ssize_t) polygon_info->number_edges; i++)
{
(void) LogMagickEvent(DrawEvent,GetMagickModule()," edge %.20g:",
(double) i);
(void) LogMagickEvent(DrawEvent,GetMagickModule()," direction: %s",
p->direction != MagickFalse ? "down" : "up");
(void) LogMagickEvent(DrawEvent,GetMagickModule()," ghostline: %s",
p->ghostline != MagickFalse ? "transparent" : "opaque");
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" bounds: %g,%g - %g,%g",p->bounds.x1,p->bounds.y1,
p->bounds.x2,p->bounds.y2);
for (j=0; j < (ssize_t) p->number_points; j++)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," %g,%g",
p->points[j].x,p->points[j].y);
p++;
}
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end active-edge");
}
static void ReversePoints(PointInfo *points,const size_t number_points)
{
PointInfo
point;
register ssize_t
i;
for (i=0; i < (ssize_t) (number_points >> 1); i++)
{
point=points[i];
points[i]=points[number_points-(i+1)];
points[number_points-(i+1)]=point;
}
}
static PolygonInfo *ConvertPathToPolygon(const PathInfo *path_info)
{
long
direction,
next_direction;
PointInfo
point,
*points;
PolygonInfo
*polygon_info;
SegmentInfo
bounds;
register ssize_t
i,
n;
MagickBooleanType
ghostline;
size_t
edge,
number_edges,
number_points;
/*
Convert a path to the more efficient sorted rendering form.
*/
polygon_info=(PolygonInfo *) AcquireMagickMemory(sizeof(*polygon_info));
if (polygon_info == (PolygonInfo *) NULL)
return((PolygonInfo *) NULL);
number_edges=16;
polygon_info->edges=(EdgeInfo *) AcquireQuantumMemory(number_edges,
sizeof(*polygon_info->edges));
if (polygon_info->edges == (EdgeInfo *) NULL)
return((PolygonInfo *) NULL);
(void) ResetMagickMemory(polygon_info->edges,0,number_edges*
sizeof(*polygon_info->edges));
direction=0;
edge=0;
ghostline=MagickFalse;
n=0;
number_points=0;
points=(PointInfo *) NULL;
(void) ResetMagickMemory(&point,0,sizeof(point));
(void) ResetMagickMemory(&bounds,0,sizeof(bounds));
for (i=0; path_info[i].code != EndCode; i++)
{
if ((path_info[i].code == MoveToCode) || (path_info[i].code == OpenCode) ||
(path_info[i].code == GhostlineCode))
{
/*
Move to.
*/
if ((points != (PointInfo *) NULL) && (n >= 2))
{
if (edge == number_edges)
{
number_edges<<=1;
polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(
polygon_info->edges,(size_t) number_edges,
sizeof(*polygon_info->edges));
if (polygon_info->edges == (EdgeInfo *) NULL)
return((PolygonInfo *) NULL);
}
polygon_info->edges[edge].number_points=(size_t) n;
polygon_info->edges[edge].scanline=(-1.0);
polygon_info->edges[edge].highwater=0;
polygon_info->edges[edge].ghostline=ghostline;
polygon_info->edges[edge].direction=(ssize_t) (direction > 0);
if (direction < 0)
ReversePoints(points,(size_t) n);
polygon_info->edges[edge].points=points;
polygon_info->edges[edge].bounds=bounds;
polygon_info->edges[edge].bounds.y1=points[0].y;
polygon_info->edges[edge].bounds.y2=points[n-1].y;
points=(PointInfo *) NULL;
ghostline=MagickFalse;
edge++;
}
if (points == (PointInfo *) NULL)
{
number_points=16;
points=(PointInfo *) AcquireQuantumMemory((size_t) number_points,
sizeof(*points));
if (points == (PointInfo *) NULL)
return((PolygonInfo *) NULL);
}
ghostline=path_info[i].code == GhostlineCode ? MagickTrue : MagickFalse;
point=path_info[i].point;
points[0]=point;
bounds.x1=point.x;
bounds.x2=point.x;
direction=0;
n=1;
continue;
}
/*
Line to.
*/
next_direction=((path_info[i].point.y > point.y) ||
((fabs(path_info[i].point.y-point.y) < DrawEpsilon) &&
(path_info[i].point.x > point.x))) ? 1 : -1;
if ((points != (PointInfo *) NULL) && (direction != 0) &&
(direction != next_direction))
{
/*
New edge.
*/
point=points[n-1];
if (edge == number_edges)
{
number_edges<<=1;
polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(
polygon_info->edges,(size_t) number_edges,
sizeof(*polygon_info->edges));
if (polygon_info->edges == (EdgeInfo *) NULL)
return((PolygonInfo *) NULL);
}
polygon_info->edges[edge].number_points=(size_t) n;
polygon_info->edges[edge].scanline=(-1.0);
polygon_info->edges[edge].highwater=0;
polygon_info->edges[edge].ghostline=ghostline;
polygon_info->edges[edge].direction=(ssize_t) (direction > 0);
if (direction < 0)
ReversePoints(points,(size_t) n);
polygon_info->edges[edge].points=points;
polygon_info->edges[edge].bounds=bounds;
polygon_info->edges[edge].bounds.y1=points[0].y;
polygon_info->edges[edge].bounds.y2=points[n-1].y;
number_points=16;
points=(PointInfo *) AcquireQuantumMemory((size_t) number_points,
sizeof(*points));
if (points == (PointInfo *) NULL)
return((PolygonInfo *) NULL);
n=1;
ghostline=MagickFalse;
points[0]=point;
bounds.x1=point.x;
bounds.x2=point.x;
edge++;
}
direction=next_direction;
if (points == (PointInfo *) NULL)
continue;
if (n == (ssize_t) number_points)
{
number_points<<=1;
points=(PointInfo *) ResizeQuantumMemory(points,(size_t) number_points,
sizeof(*points));
if (points == (PointInfo *) NULL)
return((PolygonInfo *) NULL);
}
point=path_info[i].point;
points[n]=point;
if (point.x < bounds.x1)
bounds.x1=point.x;
if (point.x > bounds.x2)
bounds.x2=point.x;
n++;
}
if (points != (PointInfo *) NULL)
{
if (n < 2)
points=(PointInfo *) RelinquishMagickMemory(points);
else
{
if (edge == number_edges)
{
number_edges<<=1;
polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(
polygon_info->edges,(size_t) number_edges,
sizeof(*polygon_info->edges));
if (polygon_info->edges == (EdgeInfo *) NULL)
return((PolygonInfo *) NULL);
}
polygon_info->edges[edge].number_points=(size_t) n;
polygon_info->edges[edge].scanline=(-1.0);
polygon_info->edges[edge].highwater=0;
polygon_info->edges[edge].ghostline=ghostline;
polygon_info->edges[edge].direction=(ssize_t) (direction > 0);
if (direction < 0)
ReversePoints(points,(size_t) n);
polygon_info->edges[edge].points=points;
polygon_info->edges[edge].bounds=bounds;
polygon_info->edges[edge].bounds.y1=points[0].y;
polygon_info->edges[edge].bounds.y2=points[n-1].y;
ghostline=MagickFalse;
edge++;
}
}
polygon_info->number_edges=edge;
qsort(polygon_info->edges,(size_t) polygon_info->number_edges,
sizeof(*polygon_info->edges),CompareEdges);
if (IsEventLogging() != MagickFalse)
LogPolygonInfo(polygon_info);
return(polygon_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C o n v e r t P r i m i t i v e T o P a t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ConvertPrimitiveToPath() converts a PrimitiveInfo structure into a vector
% path structure.
%
% The format of the ConvertPrimitiveToPath method is:
%
% PathInfo *ConvertPrimitiveToPath(const DrawInfo *draw_info,
% const PrimitiveInfo *primitive_info)
%
% A description of each parameter follows:
%
% o Method ConvertPrimitiveToPath returns a vector path structure of type
% PathInfo.
%
% o draw_info: a structure of type DrawInfo.
%
% o primitive_info: Specifies a pointer to an PrimitiveInfo structure.
%
%
*/
static void LogPathInfo(const PathInfo *path_info)
{
register const PathInfo
*p;
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin vector-path");
for (p=path_info; p->code != EndCode; p++)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" %g,%g %s",p->point.x,p->point.y,p->code == GhostlineCode ?
"moveto ghostline" : p->code == OpenCode ? "moveto open" :
p->code == MoveToCode ? "moveto" : p->code == LineToCode ? "lineto" :
"?");
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end vector-path");
}
static PathInfo *ConvertPrimitiveToPath(const PrimitiveInfo *primitive_info)
{
PathInfo
*path_info;
PathInfoCode
code;
PointInfo
p,
q;
register ssize_t
i,
n;
ssize_t
coordinates,
start;
/*
Converts a PrimitiveInfo structure into a vector path structure.
*/
switch (primitive_info->primitive)
{
case AlphaPrimitive:
case ColorPrimitive:
case ImagePrimitive:
case PointPrimitive:
case TextPrimitive:
return((PathInfo *) NULL);
default:
break;
}
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;
path_info=(PathInfo *) AcquireQuantumMemory((size_t) (2UL*i+3UL),
sizeof(*path_info));
if (path_info == (PathInfo *) NULL)
return((PathInfo *) NULL);
coordinates=0;
n=0;
p.x=(-1.0);
p.y=(-1.0);
q.x=(-1.0);
q.y=(-1.0);
start=0;
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)
{
code=LineToCode;
if (coordinates <= 0)
{
coordinates=(ssize_t) primitive_info[i].coordinates;
p=primitive_info[i].point;
start=n;
code=MoveToCode;
}
coordinates--;
/*
Eliminate duplicate points.
*/
if ((i == 0) || (fabs(q.x-primitive_info[i].point.x) >= DrawEpsilon) ||
(fabs(q.y-primitive_info[i].point.y) >= DrawEpsilon))
{
path_info[n].code=code;
path_info[n].point=primitive_info[i].point;
q=primitive_info[i].point;
n++;
}
if (coordinates > 0)
continue;
if ((fabs(p.x-primitive_info[i].point.x) < DrawEpsilon) &&
(fabs(p.y-primitive_info[i].point.y) < DrawEpsilon))
continue;
/*
Mark the p point as open if it does not match the q.
*/
path_info[start].code=OpenCode;
path_info[n].code=GhostlineCode;
path_info[n].point=primitive_info[i].point;
n++;
path_info[n].code=LineToCode;
path_info[n].point=p;
n++;
}
path_info[n].code=EndCode;
path_info[n].point.x=0.0;
path_info[n].point.y=0.0;
if (IsEventLogging() != MagickFalse)
LogPathInfo(path_info);
return(path_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y D r a w I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyDrawInfo() deallocates memory associated with an DrawInfo
% structure.
%
% The format of the DestroyDrawInfo method is:
%
% DrawInfo *DestroyDrawInfo(DrawInfo *draw_info)
%
% A description of each parameter follows:
%
% o draw_info: the draw info.
%
*/
MagickExport DrawInfo *DestroyDrawInfo(DrawInfo *draw_info)
{
if (draw_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickCoreSignature);
if (draw_info->primitive != (char *) NULL)
draw_info->primitive=DestroyString(draw_info->primitive);
if (draw_info->text != (char *) NULL)
draw_info->text=DestroyString(draw_info->text);
if (draw_info->geometry != (char *) NULL)
draw_info->geometry=DestroyString(draw_info->geometry);
if (draw_info->fill_pattern != (Image *) NULL)
draw_info->fill_pattern=DestroyImage(draw_info->fill_pattern);
if (draw_info->stroke_pattern != (Image *) NULL)
draw_info->stroke_pattern=DestroyImage(draw_info->stroke_pattern);
if (draw_info->font != (char *) NULL)
draw_info->font=DestroyString(draw_info->font);
if (draw_info->metrics != (char *) NULL)
draw_info->metrics=DestroyString(draw_info->metrics);
if (draw_info->family != (char *) NULL)
draw_info->family=DestroyString(draw_info->family);
if (draw_info->encoding != (char *) NULL)
draw_info->encoding=DestroyString(draw_info->encoding);
if (draw_info->density != (char *) NULL)
draw_info->density=DestroyString(draw_info->density);
if (draw_info->server_name != (char *) NULL)
draw_info->server_name=(char *)
RelinquishMagickMemory(draw_info->server_name);
if (draw_info->dash_pattern != (double *) NULL)
draw_info->dash_pattern=(double *) RelinquishMagickMemory(
draw_info->dash_pattern);
if (draw_info->gradient.stops != (StopInfo *) NULL)
draw_info->gradient.stops=(StopInfo *) RelinquishMagickMemory(
draw_info->gradient.stops);
if (draw_info->clip_mask != (char *) NULL)
draw_info->clip_mask=DestroyString(draw_info->clip_mask);
draw_info->signature=(~MagickCoreSignature);
draw_info=(DrawInfo *) RelinquishMagickMemory(draw_info);
return(draw_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y E d g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyEdge() destroys the specified polygon edge.
%
% The format of the DestroyEdge method is:
%
% ssize_t DestroyEdge(PolygonInfo *polygon_info,const int edge)
%
% A description of each parameter follows:
%
% o polygon_info: Specifies a pointer to an PolygonInfo structure.
%
% o edge: the polygon edge number to destroy.
%
*/
static size_t DestroyEdge(PolygonInfo *polygon_info,
const size_t edge)
{
assert(edge < polygon_info->number_edges);
polygon_info->edges[edge].points=(PointInfo *) RelinquishMagickMemory(
polygon_info->edges[edge].points);
polygon_info->number_edges--;
if (edge < polygon_info->number_edges)
(void) CopyMagickMemory(polygon_info->edges+edge,polygon_info->edges+edge+1,
(size_t) (polygon_info->number_edges-edge)*sizeof(*polygon_info->edges));
return(polygon_info->number_edges);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y P o l y g o n I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyPolygonInfo() destroys the PolygonInfo data structure.
%
% The format of the DestroyPolygonInfo method is:
%
% PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info)
%
% A description of each parameter follows:
%
% o polygon_info: Specifies a pointer to an PolygonInfo structure.
%
*/
static PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info)
{
register ssize_t
i;
for (i=0; i < (ssize_t) polygon_info->number_edges; i++)
polygon_info->edges[i].points=(PointInfo *)
RelinquishMagickMemory(polygon_info->edges[i].points);
polygon_info->edges=(EdgeInfo *) RelinquishMagickMemory(polygon_info->edges);
return((PolygonInfo *) RelinquishMagickMemory(polygon_info));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w A f f i n e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawAffineImage() composites the source over the destination image as
% dictated by the affine transform.
%
% The format of the DrawAffineImage method is:
%
% MagickBooleanType DrawAffineImage(Image *image,const Image *source,
% const AffineMatrix *affine,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o source: the source image.
%
% o affine: the affine transform.
%
% o exception: return any errors or warnings in this structure.
%
*/
static SegmentInfo AffineEdge(const Image *image,const AffineMatrix *affine,
const double y,const SegmentInfo *edge)
{
double
intercept,
z;
register double
x;
SegmentInfo
inverse_edge;
/*
Determine left and right edges.
*/
inverse_edge.x1=edge->x1;
inverse_edge.y1=edge->y1;
inverse_edge.x2=edge->x2;
inverse_edge.y2=edge->y2;
z=affine->ry*y+affine->tx;
if (affine->sx >= DrawEpsilon)
{
intercept=(-z/affine->sx);
x=intercept;
if (x > inverse_edge.x1)
inverse_edge.x1=x;
intercept=(-z+(double) image->columns)/affine->sx;
x=intercept;
if (x < inverse_edge.x2)
inverse_edge.x2=x;
}
else
if (affine->sx < -DrawEpsilon)
{
intercept=(-z+(double) image->columns)/affine->sx;
x=intercept;
if (x > inverse_edge.x1)
inverse_edge.x1=x;
intercept=(-z/affine->sx);
x=intercept;
if (x < inverse_edge.x2)
inverse_edge.x2=x;
}
else
if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->columns))
{
inverse_edge.x2=edge->x1;
return(inverse_edge);
}
/*
Determine top and bottom edges.
*/
z=affine->sy*y+affine->ty;
if (affine->rx >= DrawEpsilon)
{
intercept=(-z/affine->rx);
x=intercept;
if (x > inverse_edge.x1)
inverse_edge.x1=x;
intercept=(-z+(double) image->rows)/affine->rx;
x=intercept;
if (x < inverse_edge.x2)
inverse_edge.x2=x;
}
else
if (affine->rx < -DrawEpsilon)
{
intercept=(-z+(double) image->rows)/affine->rx;
x=intercept;
if (x > inverse_edge.x1)
inverse_edge.x1=x;
intercept=(-z/affine->rx);
x=intercept;
if (x < inverse_edge.x2)
inverse_edge.x2=x;
}
else
if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->rows))
{
inverse_edge.x2=edge->x2;
return(inverse_edge);
}
return(inverse_edge);
}
static AffineMatrix InverseAffineMatrix(const AffineMatrix *affine)
{
AffineMatrix
inverse_affine;
double
determinant;
determinant=PerceptibleReciprocal(affine->sx*affine->sy-affine->rx*
affine->ry);
inverse_affine.sx=determinant*affine->sy;
inverse_affine.rx=determinant*(-affine->rx);
inverse_affine.ry=determinant*(-affine->ry);
inverse_affine.sy=determinant*affine->sx;
inverse_affine.tx=(-affine->tx)*inverse_affine.sx-affine->ty*
inverse_affine.ry;
inverse_affine.ty=(-affine->tx)*inverse_affine.rx-affine->ty*
inverse_affine.sy;
return(inverse_affine);
}
MagickExport MagickBooleanType DrawAffineImage(Image *image,
const Image *source,const AffineMatrix *affine,ExceptionInfo *exception)
{
AffineMatrix
inverse_affine;
CacheView
*image_view,
*source_view;
MagickBooleanType
status;
PixelInfo
zero;
PointInfo
extent[4],
min,
max;
register ssize_t
i;
SegmentInfo
edge;
ssize_t
start,
stop,
y;
/*
Determine bounding box.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(source != (const Image *) NULL);
assert(source->signature == MagickCoreSignature);
assert(affine != (AffineMatrix *) NULL);
extent[0].x=0.0;
extent[0].y=0.0;
extent[1].x=(double) source->columns-1.0;
extent[1].y=0.0;
extent[2].x=(double) source->columns-1.0;
extent[2].y=(double) source->rows-1.0;
extent[3].x=0.0;
extent[3].y=(double) source->rows-1.0;
for (i=0; i < 4; i++)
{
PointInfo
point;
point=extent[i];
extent[i].x=point.x*affine->sx+point.y*affine->ry+affine->tx;
extent[i].y=point.x*affine->rx+point.y*affine->sy+affine->ty;
}
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;
}
/*
Affine transform image.
*/
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
status=MagickTrue;
edge.x1=MagickMax(min.x,0.0);
edge.y1=MagickMax(min.y,0.0);
edge.x2=MagickMin(max.x,(double) image->columns-1.0);
edge.y2=MagickMin(max.y,(double) image->rows-1.0);
inverse_affine=InverseAffineMatrix(affine);
GetPixelInfo(image,&zero);
start=(ssize_t) ceil(edge.y1-0.5);
stop=(ssize_t) floor(edge.y2+0.5);
source_view=AcquireVirtualCacheView(source,exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(source,image,1,1)
#endif
for (y=start; y <= stop; y++)
{
PixelInfo
composite,
pixel;
PointInfo
point;
register ssize_t
x;
register Quantum
*magick_restrict q;
SegmentInfo
inverse_edge;
ssize_t
x_offset;
inverse_edge=AffineEdge(source,&inverse_affine,(double) y,&edge);
if (inverse_edge.x2 < inverse_edge.x1)
continue;
q=GetCacheViewAuthenticPixels(image_view,(ssize_t) ceil(inverse_edge.x1-
0.5),y,(size_t) (floor(inverse_edge.x2+0.5)-ceil(inverse_edge.x1-0.5)+1),
1,exception);
if (q == (Quantum *) NULL)
continue;
pixel=zero;
composite=zero;
x_offset=0;
for (x=(ssize_t) ceil(inverse_edge.x1-0.5); x <= (ssize_t) floor(inverse_edge.x2+0.5); x++)
{
point.x=(double) x*inverse_affine.sx+y*inverse_affine.ry+
inverse_affine.tx;
point.y=(double) x*inverse_affine.rx+y*inverse_affine.sy+
inverse_affine.ty;
(void) InterpolatePixelInfo(source,source_view,UndefinedInterpolatePixel,
point.x,point.y,&pixel,exception);
GetPixelInfoPixel(image,q,&composite);
CompositePixelInfoOver(&pixel,pixel.alpha,&composite,composite.alpha,
&composite);
SetPixelViaPixelInfo(image,&composite,q);
x_offset++;
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
source_view=DestroyCacheView(source_view);
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D r a w B o u n d i n g R e c t a n g l e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawBoundingRectangles() draws the bounding rectangles on the image. This
% is only useful for developers debugging the rendering algorithm.
%
% The format of the DrawBoundingRectangles method is:
%
% void DrawBoundingRectangles(Image *image,const DrawInfo *draw_info,
% PolygonInfo *polygon_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o polygon_info: Specifies a pointer to a PolygonInfo structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
static void DrawBoundingRectangles(Image *image,const DrawInfo *draw_info,
const PolygonInfo *polygon_info,ExceptionInfo *exception)
{
DrawInfo
*clone_info;
double
mid;
PointInfo
end,
resolution,
start;
PrimitiveInfo
primitive_info[6];
register ssize_t
i;
SegmentInfo
bounds;
ssize_t
coordinates;
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
(void) QueryColorCompliance("#000F",AllCompliance,&clone_info->fill,
exception);
resolution.x=96.0;
resolution.y=96.0;
if (clone_info->density != (char *) NULL)
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(clone_info->density,&geometry_info);
resolution.x=geometry_info.rho;
resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == MagickFalse)
resolution.y=resolution.x;
}
mid=(resolution.x/96.0)*ExpandAffine(&clone_info->affine)*
clone_info->stroke_width/2.0;
bounds.x1=0.0;
bounds.y1=0.0;
bounds.x2=0.0;
bounds.y2=0.0;
if (polygon_info != (PolygonInfo *) NULL)
{
bounds=polygon_info->edges[0].bounds;
for (i=1; i < (ssize_t) polygon_info->number_edges; i++)
{
if (polygon_info->edges[i].bounds.x1 < (double) bounds.x1)
bounds.x1=polygon_info->edges[i].bounds.x1;
if (polygon_info->edges[i].bounds.y1 < (double) bounds.y1)
bounds.y1=polygon_info->edges[i].bounds.y1;
if (polygon_info->edges[i].bounds.x2 > (double) bounds.x2)
bounds.x2=polygon_info->edges[i].bounds.x2;
if (polygon_info->edges[i].bounds.y2 > (double) bounds.y2)
bounds.y2=polygon_info->edges[i].bounds.y2;
}
bounds.x1-=mid;
bounds.x1=bounds.x1 < 0.0 ? 0.0 : bounds.x1 >= (double)
image->columns ? (double) image->columns-1 : bounds.x1;
bounds.y1-=mid;
bounds.y1=bounds.y1 < 0.0 ? 0.0 : bounds.y1 >= (double)
image->rows ? (double) image->rows-1 : bounds.y1;
bounds.x2+=mid;
bounds.x2=bounds.x2 < 0.0 ? 0.0 : bounds.x2 >= (double)
image->columns ? (double) image->columns-1 : bounds.x2;
bounds.y2+=mid;
bounds.y2=bounds.y2 < 0.0 ? 0.0 : bounds.y2 >= (double)
image->rows ? (double) image->rows-1 : bounds.y2;
for (i=0; i < (ssize_t) polygon_info->number_edges; i++)
{
if (polygon_info->edges[i].direction != 0)
(void) QueryColorCompliance("red",AllCompliance,&clone_info->stroke,
exception);
else
(void) QueryColorCompliance("green",AllCompliance,&clone_info->stroke,
exception);
start.x=(double) (polygon_info->edges[i].bounds.x1-mid);
start.y=(double) (polygon_info->edges[i].bounds.y1-mid);
end.x=(double) (polygon_info->edges[i].bounds.x2+mid);
end.y=(double) (polygon_info->edges[i].bounds.y2+mid);
primitive_info[0].primitive=RectanglePrimitive;
TraceRectangle(primitive_info,start,end);
primitive_info[0].method=ReplaceMethod;
coordinates=(ssize_t) primitive_info[0].coordinates;
primitive_info[coordinates].primitive=UndefinedPrimitive;
(void) DrawPrimitive(image,clone_info,primitive_info,exception);
}
}
(void) QueryColorCompliance("blue",AllCompliance,&clone_info->stroke,
exception);
start.x=(double) (bounds.x1-mid);
start.y=(double) (bounds.y1-mid);
end.x=(double) (bounds.x2+mid);
end.y=(double) (bounds.y2+mid);
primitive_info[0].primitive=RectanglePrimitive;
TraceRectangle(primitive_info,start,end);
primitive_info[0].method=ReplaceMethod;
coordinates=(ssize_t) primitive_info[0].coordinates;
primitive_info[coordinates].primitive=UndefinedPrimitive;
(void) DrawPrimitive(image,clone_info,primitive_info,exception);
clone_info=DestroyDrawInfo(clone_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w C l i p P a t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawClipPath() draws the clip path on the image mask.
%
% The format of the DrawClipPath method is:
%
% MagickBooleanType DrawClipPath(Image *image,const DrawInfo *draw_info,
% const char *name,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o name: the name of the clip path.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType DrawClipPath(Image *image,
const DrawInfo *draw_info,const char *name,ExceptionInfo *exception)
{
char
filename[MagickPathExtent];
Image
*clip_mask;
const char
*value;
DrawInfo
*clone_info;
MagickStatusType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (const DrawInfo *) NULL);
(void) FormatLocaleString(filename,MagickPathExtent,"%s",name);
value=GetImageArtifact(image,filename);
if (value == (const char *) NULL)
return(MagickFalse);
clip_mask=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
if (clip_mask == (Image *) NULL)
return(MagickFalse);
(void) QueryColorCompliance("#0000",AllCompliance,
&clip_mask->background_color,exception);
clip_mask->background_color.alpha=(MagickRealType) TransparentAlpha;
(void) SetImageBackgroundColor(clip_mask,exception);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"\nbegin clip-path %s",
draw_info->clip_mask);
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
(void) CloneString(&clone_info->primitive,value);
(void) QueryColorCompliance("#ffffff",AllCompliance,&clone_info->fill,
exception);
clone_info->clip_mask=(char *) NULL;
status=NegateImage(clip_mask,MagickFalse,exception);
(void) SetImageMask(image,ReadPixelMask,clip_mask,exception);
clip_mask=DestroyImage(clip_mask);
status&=DrawImage(image,clone_info,exception);
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"end clip-path");
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D r a w D a s h P o l y g o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawDashPolygon() draws a dashed polygon (line, rectangle, ellipse) on the
% image while respecting the dash offset and dash pattern attributes.
%
% The format of the DrawDashPolygon method is:
%
% MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info,
% const PrimitiveInfo *primitive_info,Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o draw_info: the draw info.
%
% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info,
const PrimitiveInfo *primitive_info,Image *image,ExceptionInfo *exception)
{
DrawInfo
*clone_info;
double
length,
maximum_length,
offset,
scale,
total_length;
MagickStatusType
status;
PrimitiveInfo
*dash_polygon;
register ssize_t
i;
register double
dx,
dy;
size_t
number_vertices;
ssize_t
j,
n;
assert(draw_info != (const DrawInfo *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-dash");
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;
number_vertices=(size_t) i;
dash_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t)
(2UL*number_vertices+1UL),sizeof(*dash_polygon));
if (dash_polygon == (PrimitiveInfo *) NULL)
return(MagickFalse);
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->miterlimit=0;
dash_polygon[0]=primitive_info[0];
scale=ExpandAffine(&draw_info->affine);
length=scale*(draw_info->dash_pattern[0]-0.5);
offset=fabs(draw_info->dash_offset) >= DrawEpsilon ?
scale*draw_info->dash_offset : 0.0;
j=1;
for (n=0; offset > 0.0; j=0)
{
if (draw_info->dash_pattern[n] <= 0.0)
break;
length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
if (offset > length)
{
offset-=length;
n++;
length=scale*(draw_info->dash_pattern[n]+0.5);
continue;
}
if (offset < length)
{
length-=offset;
offset=0.0;
break;
}
offset=0.0;
n++;
}
status=MagickTrue;
maximum_length=0.0;
total_length=0.0;
for (i=1; (i < (ssize_t) number_vertices) && (length >= 0.0); i++)
{
dx=primitive_info[i].point.x-primitive_info[i-1].point.x;
dy=primitive_info[i].point.y-primitive_info[i-1].point.y;
maximum_length=hypot((double) dx,dy);
if (fabs(length) < DrawEpsilon)
{
n++;
if (fabs(draw_info->dash_pattern[n]) < DrawEpsilon)
n=0;
length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
}
for (total_length=0.0; (length >= 0.0) && (maximum_length >= (total_length+length)); )
{
total_length+=length;
if ((n & 0x01) != 0)
{
dash_polygon[0]=primitive_info[0];
dash_polygon[0].point.x=(double) (primitive_info[i-1].point.x+dx*
total_length/maximum_length);
dash_polygon[0].point.y=(double) (primitive_info[i-1].point.y+dy*
total_length/maximum_length);
j=1;
}
else
{
if ((j+1) > (ssize_t) (2*number_vertices))
break;
dash_polygon[j]=primitive_info[i-1];
dash_polygon[j].point.x=(double) (primitive_info[i-1].point.x+dx*
total_length/maximum_length);
dash_polygon[j].point.y=(double) (primitive_info[i-1].point.y+dy*
total_length/maximum_length);
dash_polygon[j].coordinates=1;
j++;
dash_polygon[0].coordinates=(size_t) j;
dash_polygon[j].primitive=UndefinedPrimitive;
status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception);
}
n++;
if (fabs(draw_info->dash_pattern[n]) < DrawEpsilon)
n=0;
length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
}
length-=(maximum_length-total_length);
if ((n & 0x01) != 0)
continue;
dash_polygon[j]=primitive_info[i];
dash_polygon[j].coordinates=1;
j++;
}
if ((total_length <= maximum_length) && ((n & 0x01) == 0) && (j > 1))
{
dash_polygon[j]=primitive_info[i-1];
dash_polygon[j].point.x+=DrawEpsilon;
dash_polygon[j].point.y+=DrawEpsilon;
dash_polygon[j].coordinates=1;
j++;
dash_polygon[0].coordinates=(size_t) j;
dash_polygon[j].primitive=UndefinedPrimitive;
status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception);
}
dash_polygon=(PrimitiveInfo *) RelinquishMagickMemory(dash_polygon);
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-dash");
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawImage() draws a graphic primitive on your image. The primitive
% may be represented as a string or filename. Precede the filename with an
% "at" sign (@) and the contents of the file are drawn on the image. You
% can affect how text is drawn by setting one or more members of the draw
% info structure.
%
% The format of the DrawImage method is:
%
% MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline MagickBooleanType IsPoint(const char *point)
{
char
*p;
double
value;
value=StringToDouble(point,&p);
return((fabs(value) < DrawEpsilon) && (p == point) ? MagickFalse : MagickTrue);
}
static inline void TracePoint(PrimitiveInfo *primitive_info,
const PointInfo point)
{
primitive_info->coordinates=1;
primitive_info->point=point;
}
MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info,
ExceptionInfo *exception)
{
#define RenderImageTag "Render/Image"
AffineMatrix
affine,
current;
char
keyword[MagickPathExtent],
geometry[MagickPathExtent],
*next_token,
pattern[MagickPathExtent],
*primitive,
*token;
const char
*q;
double
angle,
factor,
primitive_extent;
DrawInfo
**graphic_context;
MagickBooleanType
proceed;
MagickSizeType
length,
number_points;
MagickStatusType
status;
PointInfo
point;
PrimitiveInfo
*primitive_info;
PrimitiveType
primitive_type;
register const char
*p;
register ssize_t
i,
x;
SegmentInfo
bounds;
size_t
extent,
number_stops;
ssize_t
j,
k,
n;
StopInfo
*stops;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
if ((draw_info->primitive == (char *) NULL) ||
(*draw_info->primitive == '\0'))
return(MagickFalse);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"begin draw-image");
if (*draw_info->primitive != '@')
primitive=AcquireString(draw_info->primitive);
else
primitive=FileToString(draw_info->primitive+1,~0UL,exception);
if (primitive == (char *) NULL)
return(MagickFalse);
primitive_extent=(double) strlen(primitive);
(void) SetImageArtifact(image,"MVG",primitive);
n=0;
number_stops=0;
stops=(StopInfo *) NULL;
/*
Allocate primitive info memory.
*/
graphic_context=(DrawInfo **) AcquireMagickMemory(sizeof(*graphic_context));
if (graphic_context == (DrawInfo **) NULL)
{
primitive=DestroyString(primitive);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
number_points=6553;
primitive_info=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_points,
sizeof(*primitive_info));
if (primitive_info == (PrimitiveInfo *) NULL)
{
primitive=DestroyString(primitive);
for ( ; n >= 0; n--)
graphic_context[n]=DestroyDrawInfo(graphic_context[n]);
graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL,draw_info);
graphic_context[n]->viewbox=image->page;
if ((image->page.width == 0) || (image->page.height == 0))
{
graphic_context[n]->viewbox.width=image->columns;
graphic_context[n]->viewbox.height=image->rows;
}
token=AcquireString(primitive);
extent=strlen(token)+MagickPathExtent;
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
status=MagickTrue;
for (q=primitive; *q != '\0'; )
{
/*
Interpret graphic primitive.
*/
GetNextToken(q,&q,MagickPathExtent,keyword);
if (*keyword == '\0')
break;
if (*keyword == '#')
{
/*
Comment.
*/
while ((*q != '\n') && (*q != '\0'))
q++;
continue;
}
p=q-strlen(keyword)-1;
primitive_type=UndefinedPrimitive;
current=graphic_context[n]->affine;
GetAffineMatrix(&affine);
switch (*keyword)
{
case ';':
break;
case 'a':
case 'A':
{
if (LocaleCompare("affine",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
affine.sx=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.rx=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.ry=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.sy=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.tx=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.ty=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
break;
}
if (LocaleCompare("alpha",keyword) == 0)
{
primitive_type=AlphaPrimitive;
break;
}
if (LocaleCompare("arc",keyword) == 0)
{
primitive_type=ArcPrimitive;
break;
}
status=MagickFalse;
break;
}
case 'b':
case 'B':
{
if (LocaleCompare("bezier",keyword) == 0)
{
primitive_type=BezierPrimitive;
break;
}
if (LocaleCompare("border-color",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) QueryColorCompliance(token,AllCompliance,
&graphic_context[n]->border_color,exception);
break;
}
status=MagickFalse;
break;
}
case 'c':
case 'C':
{
if (LocaleCompare("clip-path",keyword) == 0)
{
/*
Create clip mask.
*/
GetNextToken(q,&q,extent,token);
(void) CloneString(&graphic_context[n]->clip_mask,token);
(void) DrawClipPath(image,graphic_context[n],
graphic_context[n]->clip_mask,exception);
break;
}
if (LocaleCompare("clip-rule",keyword) == 0)
{
ssize_t
fill_rule;
GetNextToken(q,&q,extent,token);
fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse,
token);
if (fill_rule == -1)
status=MagickFalse;
else
graphic_context[n]->fill_rule=(FillRule) fill_rule;
break;
}
if (LocaleCompare("clip-units",keyword) == 0)
{
ssize_t
clip_units;
GetNextToken(q,&q,extent,token);
clip_units=ParseCommandOption(MagickClipPathOptions,MagickFalse,
token);
if (clip_units == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->clip_units=(ClipPathUnits) clip_units;
if (clip_units == ObjectBoundingBox)
{
GetAffineMatrix(¤t);
affine.sx=draw_info->bounds.x2;
affine.sy=draw_info->bounds.y2;
affine.tx=draw_info->bounds.x1;
affine.ty=draw_info->bounds.y1;
break;
}
break;
}
if (LocaleCompare("circle",keyword) == 0)
{
primitive_type=CirclePrimitive;
break;
}
if (LocaleCompare("color",keyword) == 0)
{
primitive_type=ColorPrimitive;
break;
}
status=MagickFalse;
break;
}
case 'd':
case 'D':
{
if (LocaleCompare("decorate",keyword) == 0)
{
ssize_t
decorate;
GetNextToken(q,&q,extent,token);
decorate=ParseCommandOption(MagickDecorateOptions,MagickFalse,
token);
if (decorate == -1)
status=MagickFalse;
else
graphic_context[n]->decorate=(DecorationType) decorate;
break;
}
if (LocaleCompare("density",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) CloneString(&graphic_context[n]->density,token);
break;
}
if (LocaleCompare("direction",keyword) == 0)
{
ssize_t
direction;
GetNextToken(q,&q,extent,token);
direction=ParseCommandOption(MagickDirectionOptions,MagickFalse,
token);
if (direction == -1)
status=MagickFalse;
else
graphic_context[n]->direction=(DirectionType) direction;
break;
}
status=MagickFalse;
break;
}
case 'e':
case 'E':
{
if (LocaleCompare("ellipse",keyword) == 0)
{
primitive_type=EllipsePrimitive;
break;
}
if (LocaleCompare("encoding",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) CloneString(&graphic_context[n]->encoding,token);
break;
}
status=MagickFalse;
break;
}
case 'f':
case 'F':
{
if (LocaleCompare("fill",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(pattern,MagickPathExtent,"%s",token);
if (GetImageArtifact(image,pattern) != (const char *) NULL)
(void) DrawPatternPath(image,draw_info,token,
&graphic_context[n]->fill_pattern,exception);
else
{
status&=QueryColorCompliance(token,AllCompliance,
&graphic_context[n]->fill,exception);
if (graphic_context[n]->fill_alpha != OpaqueAlpha)
graphic_context[n]->fill.alpha=graphic_context[n]->fill_alpha;
if (status == MagickFalse)
{
ImageInfo
*pattern_info;
pattern_info=AcquireImageInfo();
(void) CopyMagickString(pattern_info->filename,token,
MagickPathExtent);
graphic_context[n]->fill_pattern=ReadImage(pattern_info,
exception);
CatchException(exception);
pattern_info=DestroyImageInfo(pattern_info);
}
}
break;
}
if (LocaleCompare("fill-opacity",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;
graphic_context[n]->fill.alpha=QuantumRange-ClampToQuantum(
(MagickRealType) QuantumRange*(1.0-factor*StringToDouble(token,
&next_token)));
if (token == next_token)
status=MagickFalse;
break;
}
if (LocaleCompare("fill-rule",keyword) == 0)
{
ssize_t
fill_rule;
GetNextToken(q,&q,extent,token);
fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse,
token);
if (fill_rule == -1)
status=MagickFalse;
else
graphic_context[n]->fill_rule=(FillRule) fill_rule;
break;
}
if (LocaleCompare("font",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) CloneString(&graphic_context[n]->font,token);
if (LocaleCompare("none",token) == 0)
graphic_context[n]->font=(char *) RelinquishMagickMemory(
graphic_context[n]->font);
break;
}
if (LocaleCompare("font-family",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) CloneString(&graphic_context[n]->family,token);
break;
}
if (LocaleCompare("font-size",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->pointsize=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
break;
}
if (LocaleCompare("font-stretch",keyword) == 0)
{
ssize_t
stretch;
GetNextToken(q,&q,extent,token);
stretch=ParseCommandOption(MagickStretchOptions,MagickFalse,token);
if (stretch == -1)
status=MagickFalse;
else
graphic_context[n]->stretch=(StretchType) stretch;
break;
}
if (LocaleCompare("font-style",keyword) == 0)
{
ssize_t
style;
GetNextToken(q,&q,extent,token);
style=ParseCommandOption(MagickStyleOptions,MagickFalse,token);
if (style == -1)
status=MagickFalse;
else
graphic_context[n]->style=(StyleType) style;
break;
}
if (LocaleCompare("font-weight",keyword) == 0)
{
ssize_t
weight;
GetNextToken(q,&q,extent,token);
weight=ParseCommandOption(MagickWeightOptions,MagickFalse,token);
if (weight == -1)
weight=(ssize_t) StringToUnsignedLong(token);
graphic_context[n]->weight=(size_t) weight;
break;
}
status=MagickFalse;
break;
}
case 'g':
case 'G':
{
if (LocaleCompare("gradient-units",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("gravity",keyword) == 0)
{
ssize_t
gravity;
GetNextToken(q,&q,extent,token);
gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,token);
if (gravity == -1)
status=MagickFalse;
else
graphic_context[n]->gravity=(GravityType) gravity;
break;
}
status=MagickFalse;
break;
}
case 'i':
case 'I':
{
if (LocaleCompare("image",keyword) == 0)
{
ssize_t
compose;
primitive_type=ImagePrimitive;
GetNextToken(q,&q,extent,token);
compose=ParseCommandOption(MagickComposeOptions,MagickFalse,token);
if (compose == -1)
status=MagickFalse;
else
graphic_context[n]->compose=(CompositeOperator) compose;
break;
}
if (LocaleCompare("interline-spacing",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->interline_spacing=StringToDouble(token,
&next_token);
if (token == next_token)
status=MagickFalse;
break;
}
if (LocaleCompare("interword-spacing",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->interword_spacing=StringToDouble(token,
&next_token);
if (token == next_token)
status=MagickFalse;
break;
}
status=MagickFalse;
break;
}
case 'k':
case 'K':
{
if (LocaleCompare("kerning",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->kerning=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
break;
}
status=MagickFalse;
break;
}
case 'l':
case 'L':
{
if (LocaleCompare("line",keyword) == 0)
primitive_type=LinePrimitive;
else
status=MagickFalse;
break;
}
case 'o':
case 'O':
{
if (LocaleCompare("offset",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("opacity",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;
graphic_context[n]->alpha=QuantumRange*(1.0-(QuantumScale*
graphic_context[n]->alpha*(1.0-factor*StringToDouble(token,
&next_token))));
graphic_context[n]->fill_alpha=QuantumRange*(1.0-(QuantumScale*
graphic_context[n]->fill_alpha*(1.0-factor*StringToDouble(token,
&next_token))));
graphic_context[n]->stroke_alpha=QuantumRange*(1.0-(QuantumScale*
graphic_context[n]->stroke_alpha*(1.0-factor*StringToDouble(token,
&next_token))));
if (token == next_token)
status=MagickFalse;
break;
}
status=MagickFalse;
break;
}
case 'p':
case 'P':
{
if (LocaleCompare("path",keyword) == 0)
{
primitive_type=PathPrimitive;
break;
}
if (LocaleCompare("point",keyword) == 0)
{
primitive_type=PointPrimitive;
break;
}
if (LocaleCompare("polyline",keyword) == 0)
{
primitive_type=PolylinePrimitive;
break;
}
if (LocaleCompare("polygon",keyword) == 0)
{
primitive_type=PolygonPrimitive;
break;
}
if (LocaleCompare("pop",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
if (LocaleCompare("clip-path",token) == 0)
break;
if (LocaleCompare("defs",token) == 0)
break;
if (LocaleCompare("gradient",token) == 0)
break;
if (LocaleCompare("graphic-context",token) == 0)
{
if (n <= 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),
DrawError,"UnbalancedGraphicContextPushPop","`%s'",token);
status=MagickFalse;
n=0;
break;
}
if (graphic_context[n]->clip_mask != (char *) NULL)
if (LocaleCompare(graphic_context[n]->clip_mask,
graphic_context[n-1]->clip_mask) != 0)
(void) SetImageMask(image,ReadPixelMask,(Image *) NULL,
exception);
graphic_context[n]=DestroyDrawInfo(graphic_context[n]);
n--;
break;
}
if (LocaleCompare("pattern",token) == 0)
break;
status=MagickFalse;
break;
}
if (LocaleCompare("push",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
if (LocaleCompare("clip-path",token) == 0)
{
char
name[MagickPathExtent];
GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(name,MagickPathExtent,"%s",token);
for (p=q; *q != '\0'; )
{
GetNextToken(q,&q,extent,token);
if (LocaleCompare(token,"pop") != 0)
continue;
GetNextToken(q,(const char **) NULL,extent,token);
if (LocaleCompare(token,"clip-path") != 0)
continue;
break;
}
(void) CopyMagickString(token,p,(size_t) (q-p-4+1));
(void) SetImageArtifact(image,name,token);
GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("gradient",token) == 0)
{
char
key[2*MagickPathExtent],
name[MagickPathExtent],
type[MagickPathExtent];
SegmentInfo
segment;
GetNextToken(q,&q,extent,token);
(void) CopyMagickString(name,token,MagickPathExtent);
GetNextToken(q,&q,extent,token);
(void) CopyMagickString(type,token,MagickPathExtent);
GetNextToken(q,&q,extent,token);
segment.x1=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
segment.y1=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
segment.x2=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
segment.y2=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
if (LocaleCompare(type,"radial") == 0)
{
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
}
for (p=q; *q != '\0'; )
{
GetNextToken(q,&q,extent,token);
if (LocaleCompare(token,"pop") != 0)
continue;
GetNextToken(q,(const char **) NULL,extent,token);
if (LocaleCompare(token,"gradient") != 0)
continue;
break;
}
(void) CopyMagickString(token,p,(size_t) (q-p-4+1));
bounds.x1=graphic_context[n]->affine.sx*segment.x1+
graphic_context[n]->affine.ry*segment.y1+
graphic_context[n]->affine.tx;
bounds.y1=graphic_context[n]->affine.rx*segment.x1+
graphic_context[n]->affine.sy*segment.y1+
graphic_context[n]->affine.ty;
bounds.x2=graphic_context[n]->affine.sx*segment.x2+
graphic_context[n]->affine.ry*segment.y2+
graphic_context[n]->affine.tx;
bounds.y2=graphic_context[n]->affine.rx*segment.x2+
graphic_context[n]->affine.sy*segment.y2+
graphic_context[n]->affine.ty;
(void) FormatLocaleString(key,MagickPathExtent,"%s",name);
(void) SetImageArtifact(image,key,token);
(void) FormatLocaleString(key,MagickPathExtent,"%s-type",name);
(void) SetImageArtifact(image,key,type);
(void) FormatLocaleString(key,MagickPathExtent,"%s-geometry",
name);
(void) FormatLocaleString(geometry,MagickPathExtent,
"%gx%g%+.15g%+.15g",
MagickMax(fabs(bounds.x2-bounds.x1+1.0),1.0),
MagickMax(fabs(bounds.y2-bounds.y1+1.0),1.0),
bounds.x1,bounds.y1);
(void) SetImageArtifact(image,key,geometry);
GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("pattern",token) == 0)
{
char
key[2*MagickPathExtent],
name[MagickPathExtent];
RectangleInfo
pattern_bounds;
GetNextToken(q,&q,extent,token);
(void) CopyMagickString(name,token,MagickPathExtent);
GetNextToken(q,&q,extent,token);
pattern_bounds.x=(ssize_t) ceil(StringToDouble(token,
&next_token)-0.5);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
pattern_bounds.y=(ssize_t) ceil(StringToDouble(token,
&next_token)-0.5);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
pattern_bounds.width=(size_t) floor(StringToDouble(token,
&next_token)+0.5);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
pattern_bounds.height=(size_t) floor(StringToDouble(token,
&next_token)+0.5);
if (token == next_token)
status=MagickFalse;
for (p=q; *q != '\0'; )
{
GetNextToken(q,&q,extent,token);
if (LocaleCompare(token,"pop") != 0)
continue;
GetNextToken(q,(const char **) NULL,extent,token);
if (LocaleCompare(token,"pattern") != 0)
continue;
break;
}
(void) CopyMagickString(token,p,(size_t) (q-p-4+1));
(void) FormatLocaleString(key,MagickPathExtent,"%s",name);
(void) SetImageArtifact(image,key,token);
(void) FormatLocaleString(key,MagickPathExtent,"%s-geometry",
name);
(void) FormatLocaleString(geometry,MagickPathExtent,
"%.20gx%.20g%+.20g%+.20g",(double)pattern_bounds.width,
(double)pattern_bounds.height,(double)pattern_bounds.x,
(double)pattern_bounds.y);
(void) SetImageArtifact(image,key,geometry);
GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("graphic-context",token) == 0)
{
n++;
graphic_context=(DrawInfo **) ResizeQuantumMemory(
graphic_context,(size_t) (n+1),sizeof(*graphic_context));
if (graphic_context == (DrawInfo **) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
break;
}
graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL,
graphic_context[n-1]);
break;
}
if (LocaleCompare("defs",token) == 0)
break;
status=MagickFalse;
break;
}
status=MagickFalse;
break;
}
case 'r':
case 'R':
{
if (LocaleCompare("rectangle",keyword) == 0)
{
primitive_type=RectanglePrimitive;
break;
}
if (LocaleCompare("rotate",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
angle=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
affine.sx=cos(DegreesToRadians(fmod((double) angle,360.0)));
affine.rx=sin(DegreesToRadians(fmod((double) angle,360.0)));
affine.ry=(-sin(DegreesToRadians(fmod((double) angle,360.0))));
affine.sy=cos(DegreesToRadians(fmod((double) angle,360.0)));
break;
}
if (LocaleCompare("roundRectangle",keyword) == 0)
{
primitive_type=RoundRectanglePrimitive;
break;
}
status=MagickFalse;
break;
}
case 's':
case 'S':
{
if (LocaleCompare("scale",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
affine.sx=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.sy=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
break;
}
if (LocaleCompare("skewX",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
angle=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
affine.ry=sin(DegreesToRadians(angle));
break;
}
if (LocaleCompare("skewY",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
angle=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
affine.rx=(-tan(DegreesToRadians(angle)/2.0));
break;
}
if (LocaleCompare("stop-color",keyword) == 0)
{
PixelInfo
stop_color;
number_stops++;
if (number_stops == 1)
stops=(StopInfo *) AcquireQuantumMemory(2,sizeof(*stops));
else if (number_stops > 2)
stops=(StopInfo *) ResizeQuantumMemory(stops,number_stops,
sizeof(*stops));
if (stops == (StopInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
break;
}
GetNextToken(q,&q,extent,token);
(void) QueryColorCompliance(token,AllCompliance,&stop_color,
exception);
stops[number_stops-1].color=stop_color;
GetNextToken(q,&q,extent,token);
stops[number_stops-1].offset=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
break;
}
if (LocaleCompare("stroke",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) FormatLocaleString(pattern,MagickPathExtent,"%s",token);
if (GetImageArtifact(image,pattern) != (const char *) NULL)
(void) DrawPatternPath(image,draw_info,token,
&graphic_context[n]->stroke_pattern,exception);
else
{
status&=QueryColorCompliance(token,AllCompliance,
&graphic_context[n]->stroke,exception);
if (graphic_context[n]->stroke_alpha != OpaqueAlpha)
graphic_context[n]->stroke.alpha=
graphic_context[n]->stroke_alpha;
if (status == MagickFalse)
{
ImageInfo
*pattern_info;
pattern_info=AcquireImageInfo();
(void) CopyMagickString(pattern_info->filename,token,
MagickPathExtent);
graphic_context[n]->stroke_pattern=ReadImage(pattern_info,
exception);
CatchException(exception);
pattern_info=DestroyImageInfo(pattern_info);
}
}
break;
}
if (LocaleCompare("stroke-antialias",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->stroke_antialias=
StringToLong(token) != 0 ? MagickTrue : MagickFalse;
break;
}
if (LocaleCompare("stroke-dasharray",keyword) == 0)
{
if (graphic_context[n]->dash_pattern != (double *) NULL)
graphic_context[n]->dash_pattern=(double *)
RelinquishMagickMemory(graphic_context[n]->dash_pattern);
if (IsPoint(q) != MagickFalse)
{
const char
*r;
r=q;
GetNextToken(r,&r,extent,token);
if (*token == ',')
GetNextToken(r,&r,extent,token);
for (x=0; IsPoint(token) != MagickFalse; x++)
{
GetNextToken(r,&r,extent,token);
if (*token == ',')
GetNextToken(r,&r,extent,token);
}
graphic_context[n]->dash_pattern=(double *)
AcquireQuantumMemory((size_t) (2UL*x+1UL),
sizeof(*graphic_context[n]->dash_pattern));
if (graphic_context[n]->dash_pattern == (double *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
status=MagickFalse;
break;
}
for (j=0; j < x; j++)
{
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
graphic_context[n]->dash_pattern[j]=StringToDouble(token,
&next_token);
if (token == next_token)
status=MagickFalse;
if (graphic_context[n]->dash_pattern[j] < 0.0)
status=MagickFalse;
}
if ((x & 0x01) != 0)
for ( ; j < (2*x); j++)
graphic_context[n]->dash_pattern[j]=
graphic_context[n]->dash_pattern[j-x];
graphic_context[n]->dash_pattern[j]=0.0;
break;
}
GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("stroke-dashoffset",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->dash_offset=StringToDouble(token,
&next_token);
if (token == next_token)
status=MagickFalse;
break;
}
if (LocaleCompare("stroke-linecap",keyword) == 0)
{
ssize_t
linecap;
GetNextToken(q,&q,extent,token);
linecap=ParseCommandOption(MagickLineCapOptions,MagickFalse,token);
if (linecap == -1)
status=MagickFalse;
else
graphic_context[n]->linecap=(LineCap) linecap;
break;
}
if (LocaleCompare("stroke-linejoin",keyword) == 0)
{
ssize_t
linejoin;
GetNextToken(q,&q,extent,token);
linejoin=ParseCommandOption(MagickLineJoinOptions,MagickFalse,
token);
if (linejoin == -1)
status=MagickFalse;
else
graphic_context[n]->linejoin=(LineJoin) linejoin;
break;
}
if (LocaleCompare("stroke-miterlimit",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->miterlimit=StringToUnsignedLong(token);
break;
}
if (LocaleCompare("stroke-opacity",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;
graphic_context[n]->stroke.alpha=QuantumRange-ClampToQuantum(
(MagickRealType) QuantumRange*(1.0-factor*StringToDouble(token,
&next_token)));
if (token == next_token)
status=MagickFalse;
break;
}
if (LocaleCompare("stroke-width",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->stroke_width=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
break;
}
status=MagickFalse;
break;
}
case 't':
case 'T':
{
if (LocaleCompare("text",keyword) == 0)
{
primitive_type=TextPrimitive;
break;
}
if (LocaleCompare("text-align",keyword) == 0)
{
ssize_t
align;
GetNextToken(q,&q,extent,token);
align=ParseCommandOption(MagickAlignOptions,MagickFalse,token);
if (align == -1)
status=MagickFalse;
else
graphic_context[n]->align=(AlignType) align;
break;
}
if (LocaleCompare("text-anchor",keyword) == 0)
{
ssize_t
align;
GetNextToken(q,&q,extent,token);
align=ParseCommandOption(MagickAlignOptions,MagickFalse,token);
if (align == -1)
status=MagickFalse;
else
graphic_context[n]->align=(AlignType) align;
break;
}
if (LocaleCompare("text-antialias",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->text_antialias=StringToLong(token) != 0 ?
MagickTrue : MagickFalse;
break;
}
if (LocaleCompare("text-undercolor",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
(void) QueryColorCompliance(token,AllCompliance,
&graphic_context[n]->undercolor,exception);
break;
}
if (LocaleCompare("translate",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
affine.tx=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
affine.ty=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
break;
}
status=MagickFalse;
break;
}
case 'v':
case 'V':
{
if (LocaleCompare("viewbox",keyword) == 0)
{
GetNextToken(q,&q,extent,token);
graphic_context[n]->viewbox.x=(ssize_t) ceil(StringToDouble(token,
&next_token)-0.5);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
graphic_context[n]->viewbox.y=(ssize_t) ceil(StringToDouble(token,
&next_token)-0.5);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
graphic_context[n]->viewbox.width=(size_t) floor(StringToDouble(
token,&next_token)+0.5);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
graphic_context[n]->viewbox.height=(size_t) floor(StringToDouble(
token,&next_token)+0.5);
if (token == next_token)
status=MagickFalse;
break;
}
status=MagickFalse;
break;
}
default:
{
status=MagickFalse;
break;
}
}
if (status == MagickFalse)
break;
if ((fabs(affine.sx-1.0) >= DrawEpsilon) ||
(fabs(affine.rx) >= DrawEpsilon) || (fabs(affine.ry) >= DrawEpsilon) ||
(fabs(affine.sy-1.0) >= DrawEpsilon) ||
(fabs(affine.tx) >= DrawEpsilon) || (fabs(affine.ty) >= DrawEpsilon))
{
graphic_context[n]->affine.sx=current.sx*affine.sx+current.ry*affine.rx;
graphic_context[n]->affine.rx=current.rx*affine.sx+current.sy*affine.rx;
graphic_context[n]->affine.ry=current.sx*affine.ry+current.ry*affine.sy;
graphic_context[n]->affine.sy=current.rx*affine.ry+current.sy*affine.sy;
graphic_context[n]->affine.tx=current.sx*affine.tx+current.ry*affine.ty+
current.tx;
graphic_context[n]->affine.ty=current.rx*affine.tx+current.sy*affine.ty+
current.ty;
}
if (primitive_type == UndefinedPrimitive)
{
if (*q == '\0')
{
if (number_stops > 1)
{
GradientType
type;
type=LinearGradient;
if (draw_info->gradient.type == RadialGradient)
type=RadialGradient;
(void) GradientImage(image,type,PadSpread,stops,number_stops,
exception);
}
if (number_stops > 0)
stops=(StopInfo *) RelinquishMagickMemory(stops);
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",(int)
(q-p),p);
continue;
}
/*
Parse the primitive attributes.
*/
i=0;
j=0;
primitive_info[0].point.x=0.0;
primitive_info[0].point.y=0.0;
for (x=0; *q != '\0'; x++)
{
/*
Define points.
*/
if (IsPoint(q) == MagickFalse)
break;
GetNextToken(q,&q,extent,token);
point.x=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,&q,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
point.y=StringToDouble(token,&next_token);
if (token == next_token)
status=MagickFalse;
GetNextToken(q,(const char **) NULL,extent,token);
if (*token == ',')
GetNextToken(q,&q,extent,token);
primitive_info[i].primitive=primitive_type;
primitive_info[i].point=point;
primitive_info[i].coordinates=0;
primitive_info[i].method=FloodfillMethod;
i++;
if (i < (ssize_t) number_points)
continue;
number_points<<=1;
primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info,
(size_t) number_points,sizeof(*primitive_info));
if ((primitive_info == (PrimitiveInfo *) NULL) ||
(number_points != (MagickSizeType) ((size_t) number_points)))
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
primitive_info[j].primitive=primitive_type;
primitive_info[j].coordinates=(size_t) x;
primitive_info[j].method=FloodfillMethod;
primitive_info[j].text=(char *) NULL;
/*
Circumscribe primitive within a circle.
*/
bounds.x1=primitive_info[j].point.x;
bounds.y1=primitive_info[j].point.y;
bounds.x2=primitive_info[j].point.x;
bounds.y2=primitive_info[j].point.y;
for (k=1; k < (ssize_t) primitive_info[j].coordinates; k++)
{
point=primitive_info[j+k].point;
if (point.x < bounds.x1)
bounds.x1=point.x;
if (point.y < bounds.y1)
bounds.y1=point.y;
if (point.x > bounds.x2)
bounds.x2=point.x;
if (point.y > bounds.y2)
bounds.y2=point.y;
}
/*
Speculate how many points our primitive might consume.
*/
length=primitive_info[j].coordinates;
switch (primitive_type)
{
case RectanglePrimitive:
{
length*=5;
break;
}
case RoundRectanglePrimitive:
{
double
alpha,
beta,
radius;
alpha=bounds.x2-bounds.x1;
beta=bounds.y2-bounds.y1;
radius=hypot((double) alpha,(double) beta);
length*=5;
length+=2*((size_t) ceil((double) MagickPI*radius))+6*BezierQuantum+360;
break;
}
case BezierPrimitive:
{
if (primitive_info[j].coordinates > 107)
(void) ThrowMagickException(exception,GetMagickModule(),DrawError,
"TooManyBezierCoordinates","`%s'",token);
length=BezierQuantum*primitive_info[j].coordinates;
break;
}
case PathPrimitive:
{
char
*s,
*t;
GetNextToken(q,&q,extent,token);
length=1;
t=token;
for (s=token; *s != '\0'; s=t)
{
double
value;
value=StringToDouble(s,&t);
(void) value;
if (s == t)
{
t++;
continue;
}
length++;
}
length=length*BezierQuantum;
break;
}
case CirclePrimitive:
case ArcPrimitive:
case EllipsePrimitive:
{
double
alpha,
beta,
radius;
alpha=bounds.x2-bounds.x1;
beta=bounds.y2-bounds.y1;
radius=hypot((double) alpha,(double) beta);
length=2*((size_t) ceil((double) MagickPI*radius))+6*BezierQuantum+360;
break;
}
default:
break;
}
if ((i+length) >= number_points)
{
/*
Resize based on speculative points required by primitive.
*/
number_points+=length+1;
primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info,
(size_t) number_points,sizeof(*primitive_info));
if ((primitive_info == (PrimitiveInfo *) NULL) ||
(number_points != (MagickSizeType) ((size_t) number_points)))
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
break;
}
}
switch (primitive_type)
{
case PointPrimitive:
default:
{
if (primitive_info[j].coordinates != 1)
{
status=MagickFalse;
break;
}
TracePoint(primitive_info+j,primitive_info[j].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case LinePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
TraceLine(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case RectanglePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
TraceRectangle(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case RoundRectanglePrimitive:
{
if (primitive_info[j].coordinates != 3)
{
status=MagickFalse;
break;
}
TraceRoundRectangle(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point,primitive_info[j+2].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case ArcPrimitive:
{
if (primitive_info[j].coordinates != 3)
{
primitive_type=UndefinedPrimitive;
break;
}
TraceArc(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point,primitive_info[j+2].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case EllipsePrimitive:
{
if (primitive_info[j].coordinates != 3)
{
status=MagickFalse;
break;
}
TraceEllipse(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point,primitive_info[j+2].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case CirclePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
TraceCircle(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case PolylinePrimitive:
break;
case PolygonPrimitive:
{
primitive_info[i]=primitive_info[j];
primitive_info[i].coordinates=0;
primitive_info[j].coordinates++;
i++;
break;
}
case BezierPrimitive:
{
if (primitive_info[j].coordinates < 3)
{
status=MagickFalse;
break;
}
TraceBezier(primitive_info+j,primitive_info[j].coordinates);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case PathPrimitive:
{
i=(ssize_t) (j+TracePath(primitive_info+j,token));
break;
}
case AlphaPrimitive:
case ColorPrimitive:
{
ssize_t
method;
if (primitive_info[j].coordinates != 1)
{
status=MagickFalse;
break;
}
GetNextToken(q,&q,extent,token);
method=ParseCommandOption(MagickMethodOptions,MagickFalse,token);
if (method == -1)
status=MagickFalse;
else
primitive_info[j].method=(PaintMethod) method;
break;
}
case TextPrimitive:
{
if (primitive_info[j].coordinates != 1)
{
status=MagickFalse;
break;
}
if (*token != ',')
GetNextToken(q,&q,extent,token);
primitive_info[j].text=AcquireString(token);
break;
}
case ImagePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
GetNextToken(q,&q,extent,token);
primitive_info[j].text=AcquireString(token);
break;
}
}
if (primitive_info == (PrimitiveInfo *) NULL)
break;
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",(int) (q-p),p);
if (status == MagickFalse)
break;
primitive_info[i].primitive=UndefinedPrimitive;
if (i == 0)
continue;
/*
Transform points.
*/
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)
{
point=primitive_info[i].point;
primitive_info[i].point.x=graphic_context[n]->affine.sx*point.x+
graphic_context[n]->affine.ry*point.y+graphic_context[n]->affine.tx;
primitive_info[i].point.y=graphic_context[n]->affine.rx*point.x+
graphic_context[n]->affine.sy*point.y+graphic_context[n]->affine.ty;
point=primitive_info[i].point;
if (point.x < graphic_context[n]->bounds.x1)
graphic_context[n]->bounds.x1=point.x;
if (point.y < graphic_context[n]->bounds.y1)
graphic_context[n]->bounds.y1=point.y;
if (point.x > graphic_context[n]->bounds.x2)
graphic_context[n]->bounds.x2=point.x;
if (point.y > graphic_context[n]->bounds.y2)
graphic_context[n]->bounds.y2=point.y;
if (primitive_info[i].primitive == ImagePrimitive)
break;
if (i >= (ssize_t) number_points)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
}
if (graphic_context[n]->render != MagickFalse)
{
if ((n != 0) && (graphic_context[n]->clip_mask != (char *) NULL) &&
(LocaleCompare(graphic_context[n]->clip_mask,
graphic_context[n-1]->clip_mask) != 0))
status&=DrawClipPath(image,graphic_context[n],
graphic_context[n]->clip_mask,exception);
status&=DrawPrimitive(image,graphic_context[n],primitive_info,
exception);
}
if (primitive_info->text != (char *) NULL)
primitive_info->text=(char *) RelinquishMagickMemory(
primitive_info->text);
proceed=SetImageProgress(image,RenderImageTag,q-primitive,(MagickSizeType)
primitive_extent);
if (proceed == MagickFalse)
break;
if (status == 0)
break;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"end draw-image");
/*
Relinquish resources.
*/
token=DestroyString(token);
if (primitive_info != (PrimitiveInfo *) NULL)
primitive_info=(PrimitiveInfo *) RelinquishMagickMemory(primitive_info);
primitive=DestroyString(primitive);
for ( ; n >= 0; n--)
graphic_context[n]=DestroyDrawInfo(graphic_context[n]);
graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context);
if (status == MagickFalse)
ThrowBinaryException(DrawError,"NonconformingDrawingPrimitiveDefinition",
keyword);
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w G r a d i e n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawGradientImage() draws a linear gradient on the image.
%
% The format of the DrawGradientImage method is:
%
% MagickBooleanType DrawGradientImage(Image *image,
% const DrawInfo *draw_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline double GetStopColorOffset(const GradientInfo *gradient,
const ssize_t x,const ssize_t y)
{
switch (gradient->type)
{
case UndefinedGradient:
case LinearGradient:
{
double
gamma,
length,
offset,
scale;
PointInfo
p,
q;
const SegmentInfo
*gradient_vector;
gradient_vector=(&gradient->gradient_vector);
p.x=gradient_vector->x2-gradient_vector->x1;
p.y=gradient_vector->y2-gradient_vector->y1;
q.x=(double) x-gradient_vector->x1;
q.y=(double) y-gradient_vector->y1;
length=sqrt(q.x*q.x+q.y*q.y);
gamma=sqrt(p.x*p.x+p.y*p.y)*length;
gamma=PerceptibleReciprocal(gamma);
scale=p.x*q.x+p.y*q.y;
offset=gamma*scale*length;
return(offset);
}
case RadialGradient:
{
PointInfo
v;
if (gradient->spread == RepeatSpread)
{
v.x=(double) x-gradient->center.x;
v.y=(double) y-gradient->center.y;
return(sqrt(v.x*v.x+v.y*v.y));
}
v.x=(double) (((x-gradient->center.x)*cos(DegreesToRadians(
gradient->angle)))+((y-gradient->center.y)*sin(DegreesToRadians(
gradient->angle))))/gradient->radii.x;
v.y=(double) (((x-gradient->center.x)*sin(DegreesToRadians(
gradient->angle)))-((y-gradient->center.y)*cos(DegreesToRadians(
gradient->angle))))/gradient->radii.y;
return(sqrt(v.x*v.x+v.y*v.y));
}
}
return(0.0);
}
static int StopInfoCompare(const void *x,const void *y)
{
StopInfo
*stop_1,
*stop_2;
stop_1=(StopInfo *) x;
stop_2=(StopInfo *) y;
if (stop_1->offset > stop_2->offset)
return(1);
if (fabs(stop_1->offset-stop_2->offset) <= DrawEpsilon)
return(0);
return(-1);
}
MagickExport MagickBooleanType DrawGradientImage(Image *image,
const DrawInfo *draw_info,ExceptionInfo *exception)
{
CacheView
*image_view;
const GradientInfo
*gradient;
const SegmentInfo
*gradient_vector;
double
length;
MagickBooleanType
status;
PixelInfo
zero;
PointInfo
point;
RectangleInfo
bounding_box;
ssize_t
y;
/*
Draw linear or radial gradient on image.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (const DrawInfo *) NULL);
gradient=(&draw_info->gradient);
qsort(gradient->stops,gradient->number_stops,sizeof(StopInfo),
StopInfoCompare);
gradient_vector=(&gradient->gradient_vector);
point.x=gradient_vector->x2-gradient_vector->x1;
point.y=gradient_vector->y2-gradient_vector->y1;
length=sqrt(point.x*point.x+point.y*point.y);
bounding_box=gradient->bounding_box;
status=MagickTrue;
GetPixelInfo(image,&zero);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,1,1)
#endif
for (y=bounding_box.y; y < (ssize_t) bounding_box.height; y++)
{
PixelInfo
composite,
pixel;
double
alpha,
offset;
register Quantum
*magick_restrict q;
register ssize_t
i,
x;
ssize_t
j;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
pixel=zero;
composite=zero;
offset=GetStopColorOffset(gradient,0,y);
if (gradient->type != RadialGradient)
offset/=length;
for (x=bounding_box.x; x < (ssize_t) bounding_box.width; x++)
{
GetPixelInfoPixel(image,q,&pixel);
switch (gradient->spread)
{
case UndefinedSpread:
case PadSpread:
{
if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||
(y != (ssize_t) ceil(gradient_vector->y1-0.5)))
{
offset=GetStopColorOffset(gradient,x,y);
if (gradient->type != RadialGradient)
offset/=length;
}
for (i=0; i < (ssize_t) gradient->number_stops; i++)
if (offset < gradient->stops[i].offset)
break;
if ((offset < 0.0) || (i == 0))
composite=gradient->stops[0].color;
else
if ((offset > 1.0) || (i == (ssize_t) gradient->number_stops))
composite=gradient->stops[gradient->number_stops-1].color;
else
{
j=i;
i--;
alpha=(offset-gradient->stops[i].offset)/
(gradient->stops[j].offset-gradient->stops[i].offset);
CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha,
&gradient->stops[j].color,alpha,&composite);
}
break;
}
case ReflectSpread:
{
if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||
(y != (ssize_t) ceil(gradient_vector->y1-0.5)))
{
offset=GetStopColorOffset(gradient,x,y);
if (gradient->type != RadialGradient)
offset/=length;
}
if (offset < 0.0)
offset=(-offset);
if ((ssize_t) fmod(offset,2.0) == 0)
offset=fmod(offset,1.0);
else
offset=1.0-fmod(offset,1.0);
for (i=0; i < (ssize_t) gradient->number_stops; i++)
if (offset < gradient->stops[i].offset)
break;
if (i == 0)
composite=gradient->stops[0].color;
else
if (i == (ssize_t) gradient->number_stops)
composite=gradient->stops[gradient->number_stops-1].color;
else
{
j=i;
i--;
alpha=(offset-gradient->stops[i].offset)/
(gradient->stops[j].offset-gradient->stops[i].offset);
CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha,
&gradient->stops[j].color,alpha,&composite);
}
break;
}
case RepeatSpread:
{
MagickBooleanType
antialias;
double
repeat;
antialias=MagickFalse;
repeat=0.0;
if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||
(y != (ssize_t) ceil(gradient_vector->y1-0.5)))
{
offset=GetStopColorOffset(gradient,x,y);
if (gradient->type == LinearGradient)
{
repeat=fmod(offset,length);
if (repeat < 0.0)
repeat=length-fmod(-repeat,length);
else
repeat=fmod(offset,length);
antialias=(repeat < length) && ((repeat+1.0) > length) ?
MagickTrue : MagickFalse;
offset=repeat/length;
}
else
{
repeat=fmod(offset,gradient->radius);
if (repeat < 0.0)
repeat=gradient->radius-fmod(-repeat,gradient->radius);
else
repeat=fmod(offset,gradient->radius);
antialias=repeat+1.0 > gradient->radius ? MagickTrue :
MagickFalse;
offset=repeat/gradient->radius;
}
}
for (i=0; i < (ssize_t) gradient->number_stops; i++)
if (offset < gradient->stops[i].offset)
break;
if (i == 0)
composite=gradient->stops[0].color;
else
if (i == (ssize_t) gradient->number_stops)
composite=gradient->stops[gradient->number_stops-1].color;
else
{
j=i;
i--;
alpha=(offset-gradient->stops[i].offset)/
(gradient->stops[j].offset-gradient->stops[i].offset);
if (antialias != MagickFalse)
{
if (gradient->type == LinearGradient)
alpha=length-repeat;
else
alpha=gradient->radius-repeat;
i=0;
j=(ssize_t) gradient->number_stops-1L;
}
CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha,
&gradient->stops[j].color,alpha,&composite);
}
break;
}
}
CompositePixelInfoOver(&composite,composite.alpha,&pixel,pixel.alpha,
&pixel);
SetPixelViaPixelInfo(image,&pixel,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w P a t t e r n P a t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawPatternPath() draws a pattern.
%
% The format of the DrawPatternPath method is:
%
% MagickBooleanType DrawPatternPath(Image *image,const DrawInfo *draw_info,
% const char *name,Image **pattern,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o name: the pattern name.
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType DrawPatternPath(Image *image,
const DrawInfo *draw_info,const char *name,Image **pattern,
ExceptionInfo *exception)
{
char
property[MagickPathExtent];
const char
*geometry,
*path,
*type;
DrawInfo
*clone_info;
ImageInfo
*image_info;
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (const DrawInfo *) NULL);
assert(name != (const char *) NULL);
(void) FormatLocaleString(property,MagickPathExtent,"%s",name);
path=GetImageArtifact(image,property);
if (path == (const char *) NULL)
return(MagickFalse);
(void) FormatLocaleString(property,MagickPathExtent,"%s-geometry",name);
geometry=GetImageArtifact(image,property);
if (geometry == (const char *) NULL)
return(MagickFalse);
if ((*pattern) != (Image *) NULL)
*pattern=DestroyImage(*pattern);
image_info=AcquireImageInfo();
image_info->size=AcquireString(geometry);
*pattern=AcquireImage(image_info,exception);
image_info=DestroyImageInfo(image_info);
(void) QueryColorCompliance("#000000ff",AllCompliance,
&(*pattern)->background_color,exception);
(void) SetImageBackgroundColor(*pattern,exception);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"begin pattern-path %s %s",name,geometry);
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->fill_pattern=NewImageList();
clone_info->stroke_pattern=NewImageList();
(void) FormatLocaleString(property,MagickPathExtent,"%s-type",name);
type=GetImageArtifact(image,property);
if (type != (const char *) NULL)
clone_info->gradient.type=(GradientType) ParseCommandOption(
MagickGradientOptions,MagickFalse,type);
(void) CloneString(&clone_info->primitive,path);
status=DrawImage(*pattern,clone_info,exception);
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"end pattern-path");
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D r a w P o l y g o n P r i m i t i v e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawPolygonPrimitive() draws a polygon on the image.
%
% The format of the DrawPolygonPrimitive method is:
%
% MagickBooleanType DrawPolygonPrimitive(Image *image,
% const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
static PolygonInfo **DestroyPolygonThreadSet(PolygonInfo **polygon_info)
{
register ssize_t
i;
assert(polygon_info != (PolygonInfo **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (polygon_info[i] != (PolygonInfo *) NULL)
polygon_info[i]=DestroyPolygonInfo(polygon_info[i]);
polygon_info=(PolygonInfo **) RelinquishMagickMemory(polygon_info);
return(polygon_info);
}
static PolygonInfo **AcquirePolygonThreadSet(
const PrimitiveInfo *primitive_info)
{
PathInfo
*magick_restrict path_info;
PolygonInfo
**polygon_info;
register ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
polygon_info=(PolygonInfo **) AcquireQuantumMemory(number_threads,
sizeof(*polygon_info));
if (polygon_info == (PolygonInfo **) NULL)
return((PolygonInfo **) NULL);
(void) ResetMagickMemory(polygon_info,0,number_threads*sizeof(*polygon_info));
path_info=ConvertPrimitiveToPath(primitive_info);
if (path_info == (PathInfo *) NULL)
return(DestroyPolygonThreadSet(polygon_info));
for (i=0; i < (ssize_t) number_threads; i++)
{
polygon_info[i]=ConvertPathToPolygon(path_info);
if (polygon_info[i] == (PolygonInfo *) NULL)
return(DestroyPolygonThreadSet(polygon_info));
}
path_info=(PathInfo *) RelinquishMagickMemory(path_info);
return(polygon_info);
}
static double GetFillAlpha(PolygonInfo *polygon_info,const double mid,
const MagickBooleanType fill,const FillRule fill_rule,const ssize_t x,
const ssize_t y,double *stroke_alpha)
{
double
alpha,
beta,
distance,
subpath_alpha;
PointInfo
delta;
register const PointInfo
*q;
register EdgeInfo
*p;
register ssize_t
i;
ssize_t
j,
winding_number;
/*
Compute fill & stroke opacity for this (x,y) point.
*/
*stroke_alpha=0.0;
subpath_alpha=0.0;
p=polygon_info->edges;
for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++)
{
if ((double) y <= (p->bounds.y1-mid-0.5))
break;
if ((double) y > (p->bounds.y2+mid+0.5))
{
(void) DestroyEdge(polygon_info,(size_t) j);
continue;
}
if (((double) x <= (p->bounds.x1-mid-0.5)) ||
((double) x > (p->bounds.x2+mid+0.5)))
continue;
i=(ssize_t) MagickMax((double) p->highwater,1.0);
for ( ; i < (ssize_t) p->number_points; i++)
{
if ((double) y <= (p->points[i-1].y-mid-0.5))
break;
if ((double) y > (p->points[i].y+mid+0.5))
continue;
if (p->scanline != (double) y)
{
p->scanline=(double) y;
p->highwater=(size_t) i;
}
/*
Compute distance between a point and an edge.
*/
q=p->points+i-1;
delta.x=(q+1)->x-q->x;
delta.y=(q+1)->y-q->y;
beta=delta.x*(x-q->x)+delta.y*(y-q->y);
if (beta < 0.0)
{
delta.x=(double) x-q->x;
delta.y=(double) y-q->y;
distance=delta.x*delta.x+delta.y*delta.y;
}
else
{
alpha=delta.x*delta.x+delta.y*delta.y;
if (beta > alpha)
{
delta.x=(double) x-(q+1)->x;
delta.y=(double) y-(q+1)->y;
distance=delta.x*delta.x+delta.y*delta.y;
}
else
{
alpha=1.0/alpha;
beta=delta.x*(y-q->y)-delta.y*(x-q->x);
distance=alpha*beta*beta;
}
}
/*
Compute stroke & subpath opacity.
*/
beta=0.0;
if (p->ghostline == MagickFalse)
{
alpha=mid+0.5;
if ((*stroke_alpha < 1.0) &&
(distance <= ((alpha+0.25)*(alpha+0.25))))
{
alpha=mid-0.5;
if (distance <= ((alpha+0.25)*(alpha+0.25)))
*stroke_alpha=1.0;
else
{
beta=1.0;
if (fabs(distance-1.0) >= DrawEpsilon)
beta=sqrt((double) distance);
alpha=beta-mid-0.5;
if (*stroke_alpha < ((alpha-0.25)*(alpha-0.25)))
*stroke_alpha=(alpha-0.25)*(alpha-0.25);
}
}
}
if ((fill == MagickFalse) || (distance > 1.0) || (subpath_alpha >= 1.0))
continue;
if (distance <= 0.0)
{
subpath_alpha=1.0;
continue;
}
if (distance > 1.0)
continue;
if (fabs(beta) < DrawEpsilon)
{
beta=1.0;
if (fabs(distance-1.0) >= DrawEpsilon)
beta=sqrt(distance);
}
alpha=beta-1.0;
if (subpath_alpha < (alpha*alpha))
subpath_alpha=alpha*alpha;
}
}
/*
Compute fill opacity.
*/
if (fill == MagickFalse)
return(0.0);
if (subpath_alpha >= 1.0)
return(1.0);
/*
Determine winding number.
*/
winding_number=0;
p=polygon_info->edges;
for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++)
{
if ((double) y <= p->bounds.y1)
break;
if (((double) y > p->bounds.y2) || ((double) x <= p->bounds.x1))
continue;
if ((double) x > p->bounds.x2)
{
winding_number+=p->direction ? 1 : -1;
continue;
}
i=(ssize_t) MagickMax((double) p->highwater,1.0);
for ( ; i < (ssize_t) p->number_points; i++)
if ((double) y <= p->points[i].y)
break;
q=p->points+i-1;
if ((((q+1)->x-q->x)*(y-q->y)) <= (((q+1)->y-q->y)*(x-q->x)))
winding_number+=p->direction ? 1 : -1;
}
if (fill_rule != NonZeroRule)
{
if ((MagickAbsoluteValue(winding_number) & 0x01) != 0)
return(1.0);
}
else
if (MagickAbsoluteValue(winding_number) != 0)
return(1.0);
return(subpath_alpha);
}
static MagickBooleanType DrawPolygonPrimitive(Image *image,
const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
fill,
status;
double
mid;
PolygonInfo
**magick_restrict polygon_info;
register EdgeInfo
*p;
register ssize_t
i;
SegmentInfo
bounds;
ssize_t
start_y,
stop_y,
y;
/*
Compute bounding box.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickCoreSignature);
assert(primitive_info != (PrimitiveInfo *) NULL);
if (primitive_info->coordinates == 0)
return(MagickTrue);
polygon_info=AcquirePolygonThreadSet(primitive_info);
if (polygon_info == (PolygonInfo **) NULL)
return(MagickFalse);
DisableMSCWarning(4127)
if (0)
DrawBoundingRectangles(image,draw_info,polygon_info[0],exception);
RestoreMSCWarning
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-polygon");
fill=(primitive_info->method == FillToBorderMethod) ||
(primitive_info->method == FloodfillMethod) ? MagickTrue : MagickFalse;
mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;
bounds=polygon_info[0]->edges[0].bounds;
for (i=1; i < (ssize_t) polygon_info[0]->number_edges; i++)
{
p=polygon_info[0]->edges+i;
if (p->bounds.x1 < bounds.x1)
bounds.x1=p->bounds.x1;
if (p->bounds.y1 < bounds.y1)
bounds.y1=p->bounds.y1;
if (p->bounds.x2 > bounds.x2)
bounds.x2=p->bounds.x2;
if (p->bounds.y2 > bounds.y2)
bounds.y2=p->bounds.y2;
}
bounds.x1-=(mid+1.0);
bounds.x1=bounds.x1 < 0.0 ? 0.0 : (size_t) ceil(bounds.x1-0.5) >=
image->columns ? (double) image->columns-1 : bounds.x1;
bounds.y1-=(mid+1.0);
bounds.y1=bounds.y1 < 0.0 ? 0.0 : (size_t) ceil(bounds.y1-0.5) >=
image->rows ? (double) image->rows-1 : bounds.y1;
bounds.x2+=(mid+1.0);
bounds.x2=bounds.x2 < 0.0 ? 0.0 : (size_t) floor(bounds.x2+0.5) >=
image->columns ? (double) image->columns-1 : bounds.x2;
bounds.y2+=(mid+1.0);
bounds.y2=bounds.y2 < 0.0 ? 0.0 : (size_t) floor(bounds.y2+0.5) >=
image->rows ? (double) image->rows-1 : bounds.y2;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
if ((primitive_info->coordinates == 1) ||
(polygon_info[0]->number_edges == 0))
{
/*
Draw point.
*/
start_y=(ssize_t) ceil(bounds.y1-0.5);
stop_y=(ssize_t) floor(bounds.y2+0.5);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,1,1)
#endif
for (y=start_y; y <= stop_y; y++)
{
MagickBooleanType
sync;
PixelInfo
pixel;
register ssize_t
x;
register Quantum
*magick_restrict q;
ssize_t
start_x,
stop_x;
if (status == MagickFalse)
continue;
start_x=(ssize_t) ceil(bounds.x1-0.5);
stop_x=(ssize_t) floor(bounds.x2+0.5);
x=start_x;
q=GetCacheViewAuthenticPixels(image_view,x,y,(size_t) (stop_x-x+1),1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
GetPixelInfo(image,&pixel);
for ( ; x <= stop_x; x++)
{
if ((x == (ssize_t) ceil(primitive_info->point.x-0.5)) &&
(y == (ssize_t) ceil(primitive_info->point.y-0.5)))
{
GetFillColor(draw_info,x-start_x,y-start_y,&pixel,exception);
SetPixelViaPixelInfo(image,&pixel,q);
}
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
polygon_info=DestroyPolygonThreadSet(polygon_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" end draw-polygon");
return(status);
}
/*
Draw polygon or line.
*/
if (image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
start_y=(ssize_t) ceil(bounds.y1-0.5);
stop_y=(ssize_t) floor(bounds.y2+0.5);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,1,1)
#endif
for (y=start_y; y <= stop_y; y++)
{
const int
id = GetOpenMPThreadId();
double
fill_alpha,
stroke_alpha;
PixelInfo
fill_color,
stroke_color;
register Quantum
*magick_restrict q;
register ssize_t
x;
ssize_t
start_x,
stop_x;
if (status == MagickFalse)
continue;
start_x=(ssize_t) ceil(bounds.x1-0.5);
stop_x=(ssize_t) floor(bounds.x2+0.5);
q=GetCacheViewAuthenticPixels(image_view,start_x,y,(size_t) (stop_x-start_x+ 1),1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=start_x; x <= stop_x; x++)
{
/*
Fill and/or stroke.
*/
fill_alpha=GetFillAlpha(polygon_info[id],mid,fill,draw_info->fill_rule,
x,y,&stroke_alpha);
if (draw_info->stroke_antialias == MagickFalse)
{
fill_alpha=fill_alpha > 0.25 ? 1.0 : 0.0;
stroke_alpha=stroke_alpha > 0.25 ? 1.0 : 0.0;
}
GetFillColor(draw_info,x-start_x,y-start_y,&fill_color,exception);
fill_alpha=fill_alpha*fill_color.alpha;
CompositePixelOver(image,&fill_color,fill_alpha,q,(double)
GetPixelAlpha(image,q),q);
GetStrokeColor(draw_info,x-start_x,y-start_y,&stroke_color,exception);
stroke_alpha=stroke_alpha*stroke_color.alpha;
CompositePixelOver(image,&stroke_color,stroke_alpha,q,(double)
GetPixelAlpha(image,q),q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
polygon_info=DestroyPolygonThreadSet(polygon_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-polygon");
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w P r i m i t i v e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawPrimitive() draws a primitive (line, rectangle, ellipse) on the image.
%
% The format of the DrawPrimitive method is:
%
% MagickBooleanType DrawPrimitive(Image *image,const DrawInfo *draw_info,
% PrimitiveInfo *primitive_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
static void LogPrimitiveInfo(const PrimitiveInfo *primitive_info)
{
const char
*methods[] =
{
"point",
"replace",
"floodfill",
"filltoborder",
"reset",
"?"
};
PointInfo
p,
q,
point;
register ssize_t
i,
x;
ssize_t
coordinates,
y;
x=(ssize_t) ceil(primitive_info->point.x-0.5);
y=(ssize_t) ceil(primitive_info->point.y-0.5);
switch (primitive_info->primitive)
{
case AlphaPrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"AlphaPrimitive %.20g,%.20g %s",(double) x,(double) y,
methods[primitive_info->method]);
return;
}
case ColorPrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"ColorPrimitive %.20g,%.20g %s",(double) x,(double) y,
methods[primitive_info->method]);
return;
}
case ImagePrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"ImagePrimitive %.20g,%.20g",(double) x,(double) y);
return;
}
case PointPrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"PointPrimitive %.20g,%.20g %s",(double) x,(double) y,
methods[primitive_info->method]);
return;
}
case TextPrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"TextPrimitive %.20g,%.20g",(double) x,(double) y);
return;
}
default:
break;
}
coordinates=0;
p=primitive_info[0].point;
q.x=(-1.0);
q.y=(-1.0);
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)
{
point=primitive_info[i].point;
if (coordinates <= 0)
{
coordinates=(ssize_t) primitive_info[i].coordinates;
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" begin open (%.20g)",(double) coordinates);
p=point;
}
point=primitive_info[i].point;
if ((fabs(q.x-point.x) >= DrawEpsilon) ||
(fabs(q.y-point.y) >= DrawEpsilon))
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" %.20g: %.18g,%.18g",(double) coordinates,point.x,point.y);
else
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" %.20g: %g %g (duplicate)",(double) coordinates,point.x,point.y);
q=point;
coordinates--;
if (coordinates > 0)
continue;
if ((fabs(p.x-point.x) >= DrawEpsilon) ||
(fabs(p.y-point.y) >= DrawEpsilon))
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end last (%.20g)",
(double) coordinates);
else
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end open (%.20g)",
(double) coordinates);
}
}
MagickExport MagickBooleanType DrawPrimitive(Image *image,
const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickStatusType
status;
register ssize_t
i,
x;
ssize_t
y;
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" begin draw-primitive");
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" affine: %g,%g,%g,%g,%g,%g",draw_info->affine.sx,
draw_info->affine.rx,draw_info->affine.ry,draw_info->affine.sy,
draw_info->affine.tx,draw_info->affine.ty);
}
if ((IsGrayColorspace(image->colorspace) != MagickFalse) &&
((IsPixelInfoGray(&draw_info->fill) == MagickFalse) ||
(IsPixelInfoGray(&draw_info->stroke) == MagickFalse)))
(void) SetImageColorspace(image,sRGBColorspace,exception);
status=MagickTrue;
x=(ssize_t) ceil(primitive_info->point.x-0.5);
y=(ssize_t) ceil(primitive_info->point.y-0.5);
image_view=AcquireAuthenticCacheView(image,exception);
switch (primitive_info->primitive)
{
case AlphaPrimitive:
{
if (image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
switch (primitive_info->method)
{
case PointMethod:
default:
{
PixelInfo
pixel;
register Quantum
*q;
q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
if (q == (Quantum *) NULL)
break;
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
(void) SyncCacheViewAuthenticPixels(image_view,exception);
break;
}
case ReplaceMethod:
{
MagickBooleanType
sync;
PixelInfo
pixel,
target;
(void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target,
exception);
GetPixelInfo(image,&pixel);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetPixelInfoPixel(image,q,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse)
{
q+=GetPixelChannels(image);
continue;
}
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
case FloodfillMethod:
case FillToBorderMethod:
{
ChannelType
channel_mask;
PixelInfo
target;
(void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y,
&target,exception);
if (primitive_info->method == FillToBorderMethod)
{
target.red=(double) draw_info->border_color.red;
target.green=(double) draw_info->border_color.green;
target.blue=(double) draw_info->border_color.blue;
}
channel_mask=SetImageChannelMask(image,AlphaChannel);
status&=FloodfillPaintImage(image,draw_info,&target,x,y,
primitive_info->method == FloodfillMethod ? MagickFalse :
MagickTrue,exception);
(void) SetImageChannelMask(image,channel_mask);
break;
}
case ResetMethod:
{
MagickBooleanType
sync;
PixelInfo
pixel;
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
}
break;
}
case ColorPrimitive:
{
switch (primitive_info->method)
{
case PointMethod:
default:
{
PixelInfo
pixel;
register Quantum
*q;
q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
if (q == (Quantum *) NULL)
break;
GetPixelInfo(image,&pixel);
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelViaPixelInfo(image,&pixel,q);
(void) SyncCacheViewAuthenticPixels(image_view,exception);
break;
}
case ReplaceMethod:
{
MagickBooleanType
sync;
PixelInfo
pixel,
target;
(void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target,
exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetPixelInfoPixel(image,q,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse)
{
q+=GetPixelChannels(image);
continue;
}
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelViaPixelInfo(image,&pixel,q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
case FloodfillMethod:
case FillToBorderMethod:
{
PixelInfo
target;
(void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y,
&target,exception);
if (primitive_info->method == FillToBorderMethod)
{
target.red=(double) draw_info->border_color.red;
target.green=(double) draw_info->border_color.green;
target.blue=(double) draw_info->border_color.blue;
}
status&=FloodfillPaintImage(image,draw_info,&target,x,y,
primitive_info->method == FloodfillMethod ? MagickFalse :
MagickTrue,exception);
break;
}
case ResetMethod:
{
MagickBooleanType
sync;
PixelInfo
pixel;
GetPixelInfo(image,&pixel);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelViaPixelInfo(image,&pixel,q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
}
break;
}
case ImagePrimitive:
{
AffineMatrix
affine;
char
composite_geometry[MagickPathExtent];
Image
*composite_image;
ImageInfo
*clone_info;
RectangleInfo
geometry;
ssize_t
x1,
y1;
if (primitive_info->text == (char *) NULL)
break;
clone_info=AcquireImageInfo();
if (LocaleNCompare(primitive_info->text,"data:",5) == 0)
composite_image=ReadInlineImage(clone_info,primitive_info->text,
exception);
else
{
(void) CopyMagickString(clone_info->filename,primitive_info->text,
MagickPathExtent);
composite_image=ReadImage(clone_info,exception);
}
clone_info=DestroyImageInfo(clone_info);
if (composite_image == (Image *) NULL)
break;
(void) SetImageProgressMonitor(composite_image,(MagickProgressMonitor)
NULL,(void *) NULL);
x1=(ssize_t) ceil(primitive_info[1].point.x-0.5);
y1=(ssize_t) ceil(primitive_info[1].point.y-0.5);
if (((x1 != 0L) && (x1 != (ssize_t) composite_image->columns)) ||
((y1 != 0L) && (y1 != (ssize_t) composite_image->rows)))
{
/*
Resize image.
*/
(void) FormatLocaleString(composite_geometry,MagickPathExtent,
"%gx%g!",primitive_info[1].point.x,primitive_info[1].point.y);
composite_image->filter=image->filter;
(void) TransformImage(&composite_image,(char *) NULL,
composite_geometry,exception);
}
if (composite_image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(composite_image,OpaqueAlphaChannel,
exception);
if (draw_info->alpha != OpaqueAlpha)
(void) SetImageAlpha(composite_image,draw_info->alpha,exception);
SetGeometry(image,&geometry);
image->gravity=draw_info->gravity;
geometry.x=x;
geometry.y=y;
(void) FormatLocaleString(composite_geometry,MagickPathExtent,
"%.20gx%.20g%+.20g%+.20g",(double) composite_image->columns,(double)
composite_image->rows,(double) geometry.x,(double) geometry.y);
(void) ParseGravityGeometry(image,composite_geometry,&geometry,exception);
affine=draw_info->affine;
affine.tx=(double) geometry.x;
affine.ty=(double) geometry.y;
composite_image->interpolate=image->interpolate;
if (draw_info->compose == OverCompositeOp)
(void) DrawAffineImage(image,composite_image,&affine,exception);
else
(void) CompositeImage(image,composite_image,draw_info->compose,
MagickTrue,geometry.x,geometry.y,exception);
composite_image=DestroyImage(composite_image);
break;
}
case PointPrimitive:
{
PixelInfo
fill_color;
register Quantum
*q;
if ((y < 0) || (y >= (ssize_t) image->rows))
break;
if ((x < 0) || (x >= (ssize_t) image->columns))
break;
q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
if (q == (Quantum *) NULL)
break;
GetFillColor(draw_info,x,y,&fill_color,exception);
CompositePixelOver(image,&fill_color,(double) fill_color.alpha,q,
(double) GetPixelAlpha(image,q),q);
(void) SyncCacheViewAuthenticPixels(image_view,exception);
break;
}
case TextPrimitive:
{
char
geometry[MagickPathExtent];
DrawInfo
*clone_info;
if (primitive_info->text == (char *) NULL)
break;
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
(void) CloneString(&clone_info->text,primitive_info->text);
(void) FormatLocaleString(geometry,MagickPathExtent,"%+f%+f",
primitive_info->point.x,primitive_info->point.y);
(void) CloneString(&clone_info->geometry,geometry);
status&=AnnotateImage(image,clone_info,exception);
clone_info=DestroyDrawInfo(clone_info);
break;
}
default:
{
double
mid,
scale;
DrawInfo
*clone_info;
if (IsEventLogging() != MagickFalse)
LogPrimitiveInfo(primitive_info);
scale=ExpandAffine(&draw_info->affine);
if ((draw_info->dash_pattern != (double *) NULL) &&
(fabs(draw_info->dash_pattern[0]) >= DrawEpsilon) &&
(fabs(scale*draw_info->stroke_width) >= DrawEpsilon) &&
(draw_info->stroke.alpha != (Quantum) TransparentAlpha))
{
/*
Draw dash polygon.
*/
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->stroke_width=0.0;
clone_info->stroke.alpha=(MagickRealType) TransparentAlpha;
status&=DrawPolygonPrimitive(image,clone_info,primitive_info,
exception);
clone_info=DestroyDrawInfo(clone_info);
(void) DrawDashPolygon(draw_info,primitive_info,image,exception);
break;
}
mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;
if ((mid > 1.0) &&
((draw_info->stroke.alpha != (Quantum) TransparentAlpha) ||
(draw_info->stroke_pattern != (Image *) NULL)))
{
MagickBooleanType
closed_path;
/*
Draw strokes while respecting line cap/join attributes.
*/
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;
closed_path=
(fabs(primitive_info[i-1].point.x-primitive_info[0].point.x) < DrawEpsilon) &&
(fabs(primitive_info[i-1].point.y-primitive_info[0].point.y) < DrawEpsilon) ?
MagickTrue : MagickFalse;
i=(ssize_t) primitive_info[0].coordinates;
if ((((draw_info->linecap == RoundCap) ||
(closed_path != MagickFalse)) &&
(draw_info->linejoin == RoundJoin)) ||
(primitive_info[i].primitive != UndefinedPrimitive))
{
(void) DrawPolygonPrimitive(image,draw_info,primitive_info,
exception);
break;
}
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->stroke_width=0.0;
clone_info->stroke.alpha=(MagickRealType) TransparentAlpha;
status&=DrawPolygonPrimitive(image,clone_info,primitive_info,
exception);
clone_info=DestroyDrawInfo(clone_info);
status&=DrawStrokePolygon(image,draw_info,primitive_info,exception);
break;
}
status&=DrawPolygonPrimitive(image,draw_info,primitive_info,exception);
break;
}
}
image_view=DestroyCacheView(image_view);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-primitive");
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D r a w S t r o k e P o l y g o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawStrokePolygon() draws a stroked polygon (line, rectangle, ellipse) on
% the image while respecting the line cap and join attributes.
%
% The format of the DrawStrokePolygon method is:
%
% MagickBooleanType DrawStrokePolygon(Image *image,
% const DrawInfo *draw_info,const PrimitiveInfo *primitive_info)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
%
%
*/
static void DrawRoundLinecap(Image *image,const DrawInfo *draw_info,
const PrimitiveInfo *primitive_info,ExceptionInfo *exception)
{
PrimitiveInfo
linecap[5];
register ssize_t
i;
for (i=0; i < 4; i++)
linecap[i]=(*primitive_info);
linecap[0].coordinates=4;
linecap[1].point.x+=2.0*DrawEpsilon;
linecap[2].point.x+=2.0*DrawEpsilon;
linecap[2].point.y+=2.0*DrawEpsilon;
linecap[3].point.y+=2.0*DrawEpsilon;
linecap[4].primitive=UndefinedPrimitive;
(void) DrawPolygonPrimitive(image,draw_info,linecap,exception);
}
static MagickBooleanType DrawStrokePolygon(Image *image,
const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,
ExceptionInfo *exception)
{
DrawInfo
*clone_info;
MagickBooleanType
closed_path;
MagickStatusType
status;
PrimitiveInfo
*stroke_polygon;
register const PrimitiveInfo
*p,
*q;
/*
Draw stroked polygon.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" begin draw-stroke-polygon");
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->fill=draw_info->stroke;
if (clone_info->fill_pattern != (Image *) NULL)
clone_info->fill_pattern=DestroyImage(clone_info->fill_pattern);
if (clone_info->stroke_pattern != (Image *) NULL)
clone_info->fill_pattern=CloneImage(clone_info->stroke_pattern,0,0,
MagickTrue,exception);
clone_info->stroke.alpha=(MagickRealType) TransparentAlpha;
clone_info->stroke_width=0.0;
clone_info->fill_rule=NonZeroRule;
status=MagickTrue;
for (p=primitive_info; p->primitive != UndefinedPrimitive; p+=p->coordinates)
{
stroke_polygon=TraceStrokePolygon(draw_info,p);
status&=DrawPolygonPrimitive(image,clone_info,stroke_polygon,exception);
if (status == 0)
break;
stroke_polygon=(PrimitiveInfo *) RelinquishMagickMemory(stroke_polygon);
q=p+p->coordinates-1;
closed_path=(fabs(q->point.x-p->point.x) < DrawEpsilon) &&
(fabs(q->point.y-p->point.y) < DrawEpsilon) ? MagickTrue : MagickFalse;
if ((draw_info->linecap == RoundCap) && (closed_path == MagickFalse))
{
DrawRoundLinecap(image,draw_info,p,exception);
DrawRoundLinecap(image,draw_info,q,exception);
}
}
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" end draw-stroke-polygon");
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t A f f i n e M a t r i x %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetAffineMatrix() returns an AffineMatrix initialized to the identity
% matrix.
%
% The format of the GetAffineMatrix method is:
%
% void GetAffineMatrix(AffineMatrix *affine_matrix)
%
% A description of each parameter follows:
%
% o affine_matrix: the affine matrix.
%
*/
MagickExport void GetAffineMatrix(AffineMatrix *affine_matrix)
{
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(affine_matrix != (AffineMatrix *) NULL);
(void) ResetMagickMemory(affine_matrix,0,sizeof(*affine_matrix));
affine_matrix->sx=1.0;
affine_matrix->sy=1.0;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t D r a w I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetDrawInfo() initializes draw_info to default values from image_info.
%
% The format of the GetDrawInfo method is:
%
% void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info)
%
% A description of each parameter follows:
%
% o image_info: the image info..
%
% o draw_info: the draw info.
%
*/
MagickExport void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info)
{
char
*next_token;
const char
*option;
ExceptionInfo
*exception;
ImageInfo
*clone_info;
/*
Initialize draw attributes.
*/
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(draw_info != (DrawInfo *) NULL);
(void) ResetMagickMemory(draw_info,0,sizeof(*draw_info));
clone_info=CloneImageInfo(image_info);
GetAffineMatrix(&draw_info->affine);
exception=AcquireExceptionInfo();
(void) QueryColorCompliance("#000F",AllCompliance,&draw_info->fill,
exception);
(void) QueryColorCompliance("#0000",AllCompliance,&draw_info->stroke,
exception);
draw_info->stroke_width=1.0;
draw_info->fill_rule=EvenOddRule;
draw_info->alpha=OpaqueAlpha;
draw_info->fill_alpha=OpaqueAlpha;
draw_info->stroke_alpha=OpaqueAlpha;
draw_info->linecap=ButtCap;
draw_info->linejoin=MiterJoin;
draw_info->miterlimit=10;
draw_info->decorate=NoDecoration;
draw_info->pointsize=12.0;
draw_info->undercolor.alpha=(MagickRealType) TransparentAlpha;
draw_info->compose=OverCompositeOp;
draw_info->render=MagickTrue;
draw_info->debug=IsEventLogging();
draw_info->stroke_antialias=clone_info->antialias;
if (clone_info->font != (char *) NULL)
draw_info->font=AcquireString(clone_info->font);
if (clone_info->density != (char *) NULL)
draw_info->density=AcquireString(clone_info->density);
draw_info->text_antialias=clone_info->antialias;
if (fabs(clone_info->pointsize) >= DrawEpsilon)
draw_info->pointsize=clone_info->pointsize;
draw_info->border_color=clone_info->border_color;
if (clone_info->server_name != (char *) NULL)
draw_info->server_name=AcquireString(clone_info->server_name);
option=GetImageOption(clone_info,"direction");
if (option != (const char *) NULL)
draw_info->direction=(DirectionType) ParseCommandOption(
MagickDirectionOptions,MagickFalse,option);
else
draw_info->direction=UndefinedDirection;
option=GetImageOption(clone_info,"encoding");
if (option != (const char *) NULL)
(void) CloneString(&draw_info->encoding,option);
option=GetImageOption(clone_info,"family");
if (option != (const char *) NULL)
(void) CloneString(&draw_info->family,option);
option=GetImageOption(clone_info,"fill");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&draw_info->fill,
exception);
option=GetImageOption(clone_info,"gravity");
if (option != (const char *) NULL)
draw_info->gravity=(GravityType) ParseCommandOption(MagickGravityOptions,
MagickFalse,option);
option=GetImageOption(clone_info,"interline-spacing");
if (option != (const char *) NULL)
draw_info->interline_spacing=StringToDouble(option,&next_token);
option=GetImageOption(clone_info,"interword-spacing");
if (option != (const char *) NULL)
draw_info->interword_spacing=StringToDouble(option,&next_token);
option=GetImageOption(clone_info,"kerning");
if (option != (const char *) NULL)
draw_info->kerning=StringToDouble(option,&next_token);
option=GetImageOption(clone_info,"stroke");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&draw_info->stroke,
exception);
option=GetImageOption(clone_info,"strokewidth");
if (option != (const char *) NULL)
draw_info->stroke_width=StringToDouble(option,&next_token);
option=GetImageOption(clone_info,"style");
if (option != (const char *) NULL)
draw_info->style=(StyleType) ParseCommandOption(MagickStyleOptions,
MagickFalse,option);
option=GetImageOption(clone_info,"undercolor");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&draw_info->undercolor,
exception);
option=GetImageOption(clone_info,"weight");
if (option != (const char *) NULL)
{
ssize_t
weight;
weight=ParseCommandOption(MagickWeightOptions,MagickFalse,option);
if (weight == -1)
weight=(ssize_t) StringToUnsignedLong(option);
draw_info->weight=(size_t) weight;
}
exception=DestroyExceptionInfo(exception);
draw_info->signature=MagickCoreSignature;
clone_info=DestroyImageInfo(clone_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ P e r m u t a t e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Permutate() returns the permuation of the (n,k).
%
% The format of the Permutate method is:
%
% void Permutate(ssize_t n,ssize_t k)
%
% A description of each parameter follows:
%
% o n:
%
% o k:
%
%
*/
static inline double Permutate(const ssize_t n,const ssize_t k)
{
double
r;
register ssize_t
i;
r=1.0;
for (i=k+1; i <= n; i++)
r*=i;
for (i=1; i <= (n-k); i++)
r/=i;
return(r);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ T r a c e P r i m i t i v e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TracePrimitive is a collection of methods for generating graphic
% primitives such as arcs, ellipses, paths, etc.
%
*/
static void TraceArc(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo end,const PointInfo degrees)
{
PointInfo
center,
radii;
center.x=0.5*(end.x+start.x);
center.y=0.5*(end.y+start.y);
radii.x=fabs(center.x-start.x);
radii.y=fabs(center.y-start.y);
TraceEllipse(primitive_info,center,radii,degrees);
}
static void TraceArcPath(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo end,const PointInfo arc,const double angle,
const MagickBooleanType large_arc,const MagickBooleanType sweep)
{
double
alpha,
beta,
delta,
factor,
gamma,
theta;
PointInfo
center,
points[3],
radii;
register double
cosine,
sine;
register PrimitiveInfo
*p;
register ssize_t
i;
size_t
arc_segments;
if ((fabs(start.x-end.x) < DrawEpsilon) &&
(fabs(start.y-end.y) < DrawEpsilon))
{
TracePoint(primitive_info,end);
return;
}
radii.x=fabs(arc.x);
radii.y=fabs(arc.y);
if ((fabs(radii.x) < DrawEpsilon) || (fabs(radii.y) < DrawEpsilon))
{
TraceLine(primitive_info,start,end);
return;
}
cosine=cos(DegreesToRadians(fmod((double) angle,360.0)));
sine=sin(DegreesToRadians(fmod((double) angle,360.0)));
center.x=(double) (cosine*(end.x-start.x)/2+sine*(end.y-start.y)/2);
center.y=(double) (cosine*(end.y-start.y)/2-sine*(end.x-start.x)/2);
delta=(center.x*center.x)/(radii.x*radii.x)+(center.y*center.y)/
(radii.y*radii.y);
if (delta < DrawEpsilon)
{
TraceLine(primitive_info,start,end);
return;
}
if (delta > 1.0)
{
radii.x*=sqrt((double) delta);
radii.y*=sqrt((double) delta);
}
points[0].x=(double) (cosine*start.x/radii.x+sine*start.y/radii.x);
points[0].y=(double) (cosine*start.y/radii.y-sine*start.x/radii.y);
points[1].x=(double) (cosine*end.x/radii.x+sine*end.y/radii.x);
points[1].y=(double) (cosine*end.y/radii.y-sine*end.x/radii.y);
alpha=points[1].x-points[0].x;
beta=points[1].y-points[0].y;
factor=PerceptibleReciprocal(alpha*alpha+beta*beta)-0.25;
if (factor <= 0.0)
factor=0.0;
else
{
factor=sqrt((double) factor);
if (sweep == large_arc)
factor=(-factor);
}
center.x=(double) ((points[0].x+points[1].x)/2-factor*beta);
center.y=(double) ((points[0].y+points[1].y)/2+factor*alpha);
alpha=atan2(points[0].y-center.y,points[0].x-center.x);
theta=atan2(points[1].y-center.y,points[1].x-center.x)-alpha;
if ((theta < 0.0) && (sweep != MagickFalse))
theta+=2.0*MagickPI;
else
if ((theta > 0.0) && (sweep == MagickFalse))
theta-=2.0*MagickPI;
arc_segments=(size_t) ceil(fabs((double) (theta/(0.5*MagickPI+DrawEpsilon))));
p=primitive_info;
for (i=0; i < (ssize_t) arc_segments; i++)
{
beta=0.5*((alpha+(i+1)*theta/arc_segments)-(alpha+i*theta/arc_segments));
gamma=(8.0/3.0)*sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))*
sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))/
sin(fmod((double) beta,DegreesToRadians(360.0)));
points[0].x=(double) (center.x+cos(fmod((double) (alpha+(double) i*theta/
arc_segments),DegreesToRadians(360.0)))-gamma*sin(fmod((double) (alpha+
(double) i*theta/arc_segments),DegreesToRadians(360.0))));
points[0].y=(double) (center.y+sin(fmod((double) (alpha+(double) i*theta/
arc_segments),DegreesToRadians(360.0)))+gamma*cos(fmod((double) (alpha+
(double) i*theta/arc_segments),DegreesToRadians(360.0))));
points[2].x=(double) (center.x+cos(fmod((double) (alpha+(double) (i+1)*
theta/arc_segments),DegreesToRadians(360.0))));
points[2].y=(double) (center.y+sin(fmod((double) (alpha+(double) (i+1)*
theta/arc_segments),DegreesToRadians(360.0))));
points[1].x=(double) (points[2].x+gamma*sin(fmod((double) (alpha+(double)
(i+1)*theta/arc_segments),DegreesToRadians(360.0))));
points[1].y=(double) (points[2].y-gamma*cos(fmod((double) (alpha+(double)
(i+1)*theta/arc_segments),DegreesToRadians(360.0))));
p->point.x=(p == primitive_info) ? start.x : (p-1)->point.x;
p->point.y=(p == primitive_info) ? start.y : (p-1)->point.y;
(p+1)->point.x=(double) (cosine*radii.x*points[0].x-sine*radii.y*
points[0].y);
(p+1)->point.y=(double) (sine*radii.x*points[0].x+cosine*radii.y*
points[0].y);
(p+2)->point.x=(double) (cosine*radii.x*points[1].x-sine*radii.y*
points[1].y);
(p+2)->point.y=(double) (sine*radii.x*points[1].x+cosine*radii.y*
points[1].y);
(p+3)->point.x=(double) (cosine*radii.x*points[2].x-sine*radii.y*
points[2].y);
(p+3)->point.y=(double) (sine*radii.x*points[2].x+cosine*radii.y*
points[2].y);
if (i == (ssize_t) (arc_segments-1))
(p+3)->point=end;
TraceBezier(p,4);
p+=p->coordinates;
}
primitive_info->coordinates=(size_t) (p-primitive_info);
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
}
static void TraceBezier(PrimitiveInfo *primitive_info,
const size_t number_coordinates)
{
double
alpha,
*coefficients,
weight;
PointInfo
end,
point,
*points;
register PrimitiveInfo
*p;
register ssize_t
i,
j;
size_t
control_points,
quantum;
/*
Allocate coeficients.
*/
quantum=number_coordinates;
for (i=0; i < (ssize_t) number_coordinates; i++)
{
for (j=i+1; j < (ssize_t) number_coordinates; j++)
{
alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x);
if (alpha > (double) quantum)
quantum=(size_t) alpha;
alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y);
if (alpha > (double) quantum)
quantum=(size_t) alpha;
}
}
quantum=(size_t) MagickMin((double) quantum/number_coordinates,
(double) BezierQuantum);
control_points=quantum*number_coordinates;
coefficients=(double *) AcquireQuantumMemory((size_t)
number_coordinates,sizeof(*coefficients));
points=(PointInfo *) AcquireQuantumMemory((size_t) control_points,
sizeof(*points));
if ((coefficients == (double *) NULL) || (points == (PointInfo *) NULL))
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
/*
Compute bezier points.
*/
end=primitive_info[number_coordinates-1].point;
for (i=0; i < (ssize_t) number_coordinates; i++)
coefficients[i]=Permutate((ssize_t) number_coordinates-1,i);
weight=0.0;
for (i=0; i < (ssize_t) control_points; i++)
{
p=primitive_info;
point.x=0.0;
point.y=0.0;
alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0);
for (j=0; j < (ssize_t) number_coordinates; j++)
{
point.x+=alpha*coefficients[j]*p->point.x;
point.y+=alpha*coefficients[j]*p->point.y;
alpha*=weight/(1.0-weight);
p++;
}
points[i]=point;
weight+=1.0/control_points;
}
/*
Bezier curves are just short segmented polys.
*/
p=primitive_info;
for (i=0; i < (ssize_t) control_points; i++)
{
TracePoint(p,points[i]);
p+=p->coordinates;
}
TracePoint(p,end);
p+=p->coordinates;
primitive_info->coordinates=(size_t) (p-primitive_info);
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
points=(PointInfo *) RelinquishMagickMemory(points);
coefficients=(double *) RelinquishMagickMemory(coefficients);
}
static void TraceCircle(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo end)
{
double
alpha,
beta,
radius;
PointInfo
offset,
degrees;
alpha=end.x-start.x;
beta=end.y-start.y;
radius=hypot((double) alpha,(double) beta);
offset.x=(double) radius;
offset.y=(double) radius;
degrees.x=0.0;
degrees.y=360.0;
TraceEllipse(primitive_info,start,offset,degrees);
}
static void TraceEllipse(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo stop,const PointInfo degrees)
{
double
delta,
step,
y;
PointInfo
angle,
point;
register PrimitiveInfo
*p;
register ssize_t
i;
/*
Ellipses are just short segmented polys.
*/
if ((fabs(stop.x) < DrawEpsilon) && (fabs(stop.y) < DrawEpsilon))
{
TracePoint(primitive_info,start);
return;
}
delta=2.0/MagickMax(stop.x,stop.y);
step=MagickPI/8.0;
if ((delta >= 0.0) && (delta < (MagickPI/8.0)))
step=MagickPI/(4*(MagickPI/delta/2+0.5));
angle.x=DegreesToRadians(degrees.x);
y=degrees.y;
while (y < degrees.x)
y+=360.0;
angle.y=DegreesToRadians(y);
for (p=primitive_info; angle.x < angle.y; angle.x+=step)
{
point.x=cos(fmod(angle.x,DegreesToRadians(360.0)))*stop.x+start.x;
point.y=sin(fmod(angle.x,DegreesToRadians(360.0)))*stop.y+start.y;
TracePoint(p,point);
p+=p->coordinates;
}
point.x=cos(fmod(angle.y,DegreesToRadians(360.0)))*stop.x+start.x;
point.y=sin(fmod(angle.y,DegreesToRadians(360.0)))*stop.y+start.y;
TracePoint(p,point);
p+=p->coordinates;
primitive_info->coordinates=(size_t) (p-primitive_info);
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
}
static void TraceLine(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo end)
{
TracePoint(primitive_info,start);
if ((fabs(start.x-end.x) < DrawEpsilon) &&
(fabs(start.y-end.y) < DrawEpsilon))
{
primitive_info->primitive=PointPrimitive;
primitive_info->coordinates=1;
return;
}
TracePoint(primitive_info+1,end);
(primitive_info+1)->primitive=primitive_info->primitive;
primitive_info->coordinates=2;
}
static size_t TracePath(PrimitiveInfo *primitive_info,const char *path)
{
char
*next_token,
token[MagickPathExtent];
const char
*p;
double
x,
y;
int
attribute,
last_attribute;
PointInfo
end = {0.0, 0.0},
points[4] = { {0.0,0.0}, {0.0,0.0}, {0.0,0.0}, {0.0,0.0} },
point = {0.0, 0.0},
start = {0.0, 0.0};
PrimitiveType
primitive_type;
register PrimitiveInfo
*q;
register ssize_t
i;
size_t
number_coordinates,
z_count;
attribute=0;
number_coordinates=0;
z_count=0;
primitive_type=primitive_info->primitive;
q=primitive_info;
for (p=path; *p != '\0'; )
{
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == '\0')
break;
last_attribute=attribute;
attribute=(int) (*p++);
switch (attribute)
{
case 'a':
case 'A':
{
double
angle;
MagickBooleanType
large_arc,
sweep;
PointInfo
arc;
/*
Compute arc points.
*/
do
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
arc.x=StringToDouble(token,&next_token);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
arc.y=StringToDouble(token,&next_token);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
angle=StringToDouble(token,&next_token);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
large_arc=StringToLong(token) != 0 ? MagickTrue : MagickFalse;
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
sweep=StringToLong(token) != 0 ? MagickTrue : MagickFalse;
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,&next_token);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,&next_token);
end.x=(double) (attribute == (int) 'A' ? x : point.x+x);
end.y=(double) (attribute == (int) 'A' ? y : point.y+y);
TraceArcPath(q,point,end,arc,angle,large_arc,sweep);
q+=q->coordinates;
point=end;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == ',')
p++;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'c':
case 'C':
{
/*
Compute bezier points.
*/
do
{
points[0]=point;
for (i=1; i < 4; i++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,&next_token);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,&next_token);
end.x=(double) (attribute == (int) 'C' ? x : point.x+x);
end.y=(double) (attribute == (int) 'C' ? y : point.y+y);
points[i]=end;
}
for (i=0; i < 4; i++)
(q+i)->point=points[i];
TraceBezier(q,4);
q+=q->coordinates;
point=end;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'H':
case 'h':
{
do
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,&next_token);
point.x=(double) (attribute == (int) 'H' ? x: point.x+x);
TracePoint(q,point);
q+=q->coordinates;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'l':
case 'L':
{
do
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,&next_token);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,&next_token);
point.x=(double) (attribute == (int) 'L' ? x : point.x+x);
point.y=(double) (attribute == (int) 'L' ? y : point.y+y);
TracePoint(q,point);
q+=q->coordinates;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'M':
case 'm':
{
if (q != primitive_info)
{
primitive_info->coordinates=(size_t) (q-primitive_info);
number_coordinates+=primitive_info->coordinates;
primitive_info=q;
}
i=0;
do
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,&next_token);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,&next_token);
point.x=(double) (attribute == (int) 'M' ? x : point.x+x);
point.y=(double) (attribute == (int) 'M' ? y : point.y+y);
if (i == 0)
start=point;
i++;
TracePoint(q,point);
q+=q->coordinates;
if ((i != 0) && (attribute == (int) 'M'))
{
TracePoint(q,point);
q+=q->coordinates;
}
} while (IsPoint(p) != MagickFalse);
break;
}
case 'q':
case 'Q':
{
/*
Compute bezier points.
*/
do
{
points[0]=point;
for (i=1; i < 3; i++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,&next_token);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,&next_token);
if (*p == ',')
p++;
end.x=(double) (attribute == (int) 'Q' ? x : point.x+x);
end.y=(double) (attribute == (int) 'Q' ? y : point.y+y);
points[i]=end;
}
for (i=0; i < 3; i++)
(q+i)->point=points[i];
TraceBezier(q,3);
q+=q->coordinates;
point=end;
} while (IsPoint(p) != MagickFalse);
break;
}
case 's':
case 'S':
{
/*
Compute bezier points.
*/
do
{
points[0]=points[3];
points[1].x=2.0*points[3].x-points[2].x;
points[1].y=2.0*points[3].y-points[2].y;
for (i=2; i < 4; i++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,&next_token);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,&next_token);
if (*p == ',')
p++;
end.x=(double) (attribute == (int) 'S' ? x : point.x+x);
end.y=(double) (attribute == (int) 'S' ? y : point.y+y);
points[i]=end;
}
if (strchr("CcSs",last_attribute) == (char *) NULL)
{
points[0]=point;
points[1]=point;
}
for (i=0; i < 4; i++)
(q+i)->point=points[i];
TraceBezier(q,4);
q+=q->coordinates;
point=end;
} while (IsPoint(p) != MagickFalse);
break;
}
case 't':
case 'T':
{
/*
Compute bezier points.
*/
do
{
points[0]=points[2];
points[1].x=2.0*points[2].x-points[1].x;
points[1].y=2.0*points[2].y-points[1].y;
for (i=2; i < 3; i++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,&next_token);
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,&next_token);
end.x=(double) (attribute == (int) 'T' ? x : point.x+x);
end.y=(double) (attribute == (int) 'T' ? y : point.y+y);
points[i]=end;
}
if (strchr("QqTt",last_attribute) == (char *) NULL)
{
points[0]=point;
points[1]=point;
}
for (i=0; i < 3; i++)
(q+i)->point=points[i];
TraceBezier(q,3);
q+=q->coordinates;
point=end;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'v':
case 'V':
{
do
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,&next_token);
point.y=(double) (attribute == (int) 'V' ? y : point.y+y);
TracePoint(q,point);
q+=q->coordinates;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'z':
case 'Z':
{
point=start;
TracePoint(q,point);
q+=q->coordinates;
primitive_info->coordinates=(size_t) (q-primitive_info);
number_coordinates+=primitive_info->coordinates;
primitive_info=q;
z_count++;
break;
}
default:
{
if (isalpha((int) ((unsigned char) attribute)) != 0)
(void) FormatLocaleFile(stderr,"attribute not recognized: %c\n",
attribute);
break;
}
}
}
primitive_info->coordinates=(size_t) (q-primitive_info);
number_coordinates+=primitive_info->coordinates;
for (i=0; i < (ssize_t) number_coordinates; i++)
{
q--;
q->primitive=primitive_type;
if (z_count > 1)
q->method=FillToBorderMethod;
}
q=primitive_info;
return(number_coordinates);
}
static void TraceRectangle(PrimitiveInfo *primitive_info,const PointInfo start,
const PointInfo end)
{
PointInfo
point;
register PrimitiveInfo
*p;
register ssize_t
i;
p=primitive_info;
TracePoint(p,start);
p+=p->coordinates;
point.x=start.x;
point.y=end.y;
TracePoint(p,point);
p+=p->coordinates;
TracePoint(p,end);
p+=p->coordinates;
point.x=end.x;
point.y=start.y;
TracePoint(p,point);
p+=p->coordinates;
TracePoint(p,start);
p+=p->coordinates;
primitive_info->coordinates=(size_t) (p-primitive_info);
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
}
static void TraceRoundRectangle(PrimitiveInfo *primitive_info,
const PointInfo start,const PointInfo end,PointInfo arc)
{
PointInfo
degrees,
offset,
point;
register PrimitiveInfo
*p;
register ssize_t
i;
p=primitive_info;
offset.x=fabs(end.x-start.x);
offset.y=fabs(end.y-start.y);
if (arc.x > (0.5*offset.x))
arc.x=0.5*offset.x;
if (arc.y > (0.5*offset.y))
arc.y=0.5*offset.y;
point.x=start.x+offset.x-arc.x;
point.y=start.y+arc.y;
degrees.x=270.0;
degrees.y=360.0;
TraceEllipse(p,point,arc,degrees);
p+=p->coordinates;
point.x=start.x+offset.x-arc.x;
point.y=start.y+offset.y-arc.y;
degrees.x=0.0;
degrees.y=90.0;
TraceEllipse(p,point,arc,degrees);
p+=p->coordinates;
point.x=start.x+arc.x;
point.y=start.y+offset.y-arc.y;
degrees.x=90.0;
degrees.y=180.0;
TraceEllipse(p,point,arc,degrees);
p+=p->coordinates;
point.x=start.x+arc.x;
point.y=start.y+arc.y;
degrees.x=180.0;
degrees.y=270.0;
TraceEllipse(p,point,arc,degrees);
p+=p->coordinates;
TracePoint(p,primitive_info->point);
p+=p->coordinates;
primitive_info->coordinates=(size_t) (p-primitive_info);
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
}
static void TraceSquareLinecap(PrimitiveInfo *primitive_info,
const size_t number_vertices,const double offset)
{
double
distance;
register double
dx,
dy;
register ssize_t
i;
ssize_t
j;
dx=0.0;
dy=0.0;
for (i=1; i < (ssize_t) number_vertices; i++)
{
dx=primitive_info[0].point.x-primitive_info[i].point.x;
dy=primitive_info[0].point.y-primitive_info[i].point.y;
if ((fabs((double) dx) >= DrawEpsilon) ||
(fabs((double) dy) >= DrawEpsilon))
break;
}
if (i == (ssize_t) number_vertices)
i=(ssize_t) number_vertices-1L;
distance=hypot((double) dx,(double) dy);
primitive_info[0].point.x=(double) (primitive_info[i].point.x+
dx*(distance+offset)/distance);
primitive_info[0].point.y=(double) (primitive_info[i].point.y+
dy*(distance+offset)/distance);
for (j=(ssize_t) number_vertices-2; j >= 0; j--)
{
dx=primitive_info[number_vertices-1].point.x-primitive_info[j].point.x;
dy=primitive_info[number_vertices-1].point.y-primitive_info[j].point.y;
if ((fabs((double) dx) >= DrawEpsilon) ||
(fabs((double) dy) >= DrawEpsilon))
break;
}
distance=hypot((double) dx,(double) dy);
primitive_info[number_vertices-1].point.x=(double) (primitive_info[j].point.x+
dx*(distance+offset)/distance);
primitive_info[number_vertices-1].point.y=(double) (primitive_info[j].point.y+
dy*(distance+offset)/distance);
}
static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *draw_info,
const PrimitiveInfo *primitive_info)
{
typedef struct _LineSegment
{
double
p,
q;
} LineSegment;
double
delta_theta,
dot_product,
mid,
miterlimit;
LineSegment
dx,
dy,
inverse_slope,
slope,
theta;
MagickBooleanType
closed_path;
PointInfo
box_p[5],
box_q[5],
center,
offset,
*path_p,
*path_q;
PrimitiveInfo
*polygon_primitive,
*stroke_polygon;
register ssize_t
i;
size_t
arc_segments,
max_strokes,
number_vertices;
ssize_t
j,
n,
p,
q;
/*
Allocate paths.
*/
number_vertices=primitive_info->coordinates;
max_strokes=2*number_vertices+6*BezierQuantum+360;
path_p=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes,
sizeof(*path_p));
path_q=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes,
sizeof(*path_q));
polygon_primitive=(PrimitiveInfo *) AcquireQuantumMemory((size_t)
number_vertices+2UL,sizeof(*polygon_primitive));
if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL) ||
(polygon_primitive == (PrimitiveInfo *) NULL))
return((PrimitiveInfo *) NULL);
(void) CopyMagickMemory(polygon_primitive,primitive_info,(size_t)
number_vertices*sizeof(*polygon_primitive));
closed_path=
(fabs(primitive_info[number_vertices-1].point.x-primitive_info[0].point.x) < DrawEpsilon) &&
(fabs(primitive_info[number_vertices-1].point.y-primitive_info[0].point.y) < DrawEpsilon) ?
MagickTrue : MagickFalse;
if (((draw_info->linejoin == RoundJoin) ||
(draw_info->linejoin == MiterJoin)) && (closed_path != MagickFalse))
{
polygon_primitive[number_vertices]=primitive_info[1];
number_vertices++;
}
polygon_primitive[number_vertices].primitive=UndefinedPrimitive;
/*
Compute the slope for the first line segment, p.
*/
dx.p=0.0;
dy.p=0.0;
for (n=1; n < (ssize_t) number_vertices; n++)
{
dx.p=polygon_primitive[n].point.x-polygon_primitive[0].point.x;
dy.p=polygon_primitive[n].point.y-polygon_primitive[0].point.y;
if ((fabs(dx.p) >= DrawEpsilon) || (fabs(dy.p) >= DrawEpsilon))
break;
}
if (n == (ssize_t) number_vertices)
n=(ssize_t) number_vertices-1L;
slope.p=0.0;
inverse_slope.p=0.0;
if (fabs(dx.p) < DrawEpsilon)
{
if (dx.p >= 0.0)
slope.p=dy.p < 0.0 ? -1.0/DrawEpsilon : 1.0/DrawEpsilon;
else
slope.p=dy.p < 0.0 ? 1.0/DrawEpsilon : -1.0/DrawEpsilon;
}
else
if (fabs(dy.p) < DrawEpsilon)
{
if (dy.p >= 0.0)
inverse_slope.p=dx.p < 0.0 ? -1.0/DrawEpsilon : 1.0/DrawEpsilon;
else
inverse_slope.p=dx.p < 0.0 ? 1.0/DrawEpsilon : -1.0/DrawEpsilon;
}
else
{
slope.p=dy.p/dx.p;
inverse_slope.p=(-1.0/slope.p);
}
mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;
miterlimit=(double) (draw_info->miterlimit*draw_info->miterlimit*mid*mid);
if ((draw_info->linecap == SquareCap) && (closed_path == MagickFalse))
TraceSquareLinecap(polygon_primitive,number_vertices,mid);
offset.x=sqrt((double) (mid*mid/(inverse_slope.p*inverse_slope.p+1.0)));
offset.y=(double) (offset.x*inverse_slope.p);
if ((dy.p*offset.x-dx.p*offset.y) > 0.0)
{
box_p[0].x=polygon_primitive[0].point.x-offset.x;
box_p[0].y=polygon_primitive[0].point.y-offset.x*inverse_slope.p;
box_p[1].x=polygon_primitive[n].point.x-offset.x;
box_p[1].y=polygon_primitive[n].point.y-offset.x*inverse_slope.p;
box_q[0].x=polygon_primitive[0].point.x+offset.x;
box_q[0].y=polygon_primitive[0].point.y+offset.x*inverse_slope.p;
box_q[1].x=polygon_primitive[n].point.x+offset.x;
box_q[1].y=polygon_primitive[n].point.y+offset.x*inverse_slope.p;
}
else
{
box_p[0].x=polygon_primitive[0].point.x+offset.x;
box_p[0].y=polygon_primitive[0].point.y+offset.y;
box_p[1].x=polygon_primitive[n].point.x+offset.x;
box_p[1].y=polygon_primitive[n].point.y+offset.y;
box_q[0].x=polygon_primitive[0].point.x-offset.x;
box_q[0].y=polygon_primitive[0].point.y-offset.y;
box_q[1].x=polygon_primitive[n].point.x-offset.x;
box_q[1].y=polygon_primitive[n].point.y-offset.y;
}
/*
Create strokes for the line join attribute: bevel, miter, round.
*/
p=0;
q=0;
path_q[p++]=box_q[0];
path_p[q++]=box_p[0];
for (i=(ssize_t) n+1; i < (ssize_t) number_vertices; i++)
{
/*
Compute the slope for this line segment, q.
*/
dx.q=polygon_primitive[i].point.x-polygon_primitive[n].point.x;
dy.q=polygon_primitive[i].point.y-polygon_primitive[n].point.y;
dot_product=dx.q*dx.q+dy.q*dy.q;
if (dot_product < 0.25)
continue;
slope.q=0.0;
inverse_slope.q=0.0;
if (fabs(dx.q) < DrawEpsilon)
{
if (dx.q >= 0.0)
slope.q=dy.q < 0.0 ? -1.0/DrawEpsilon : 1.0/DrawEpsilon;
else
slope.q=dy.q < 0.0 ? 1.0/DrawEpsilon : -1.0/DrawEpsilon;
}
else
if (fabs(dy.q) < DrawEpsilon)
{
if (dy.q >= 0.0)
inverse_slope.q=dx.q < 0.0 ? -1.0/DrawEpsilon : 1.0/DrawEpsilon;
else
inverse_slope.q=dx.q < 0.0 ? 1.0/DrawEpsilon : -1.0/DrawEpsilon;
}
else
{
slope.q=dy.q/dx.q;
inverse_slope.q=(-1.0/slope.q);
}
offset.x=sqrt((double) (mid*mid/(inverse_slope.q*inverse_slope.q+1.0)));
offset.y=(double) (offset.x*inverse_slope.q);
dot_product=dy.q*offset.x-dx.q*offset.y;
if (dot_product > 0.0)
{
box_p[2].x=polygon_primitive[n].point.x-offset.x;
box_p[2].y=polygon_primitive[n].point.y-offset.y;
box_p[3].x=polygon_primitive[i].point.x-offset.x;
box_p[3].y=polygon_primitive[i].point.y-offset.y;
box_q[2].x=polygon_primitive[n].point.x+offset.x;
box_q[2].y=polygon_primitive[n].point.y+offset.y;
box_q[3].x=polygon_primitive[i].point.x+offset.x;
box_q[3].y=polygon_primitive[i].point.y+offset.y;
}
else
{
box_p[2].x=polygon_primitive[n].point.x+offset.x;
box_p[2].y=polygon_primitive[n].point.y+offset.y;
box_p[3].x=polygon_primitive[i].point.x+offset.x;
box_p[3].y=polygon_primitive[i].point.y+offset.y;
box_q[2].x=polygon_primitive[n].point.x-offset.x;
box_q[2].y=polygon_primitive[n].point.y-offset.y;
box_q[3].x=polygon_primitive[i].point.x-offset.x;
box_q[3].y=polygon_primitive[i].point.y-offset.y;
}
if (fabs((double) (slope.p-slope.q)) < DrawEpsilon)
{
box_p[4]=box_p[1];
box_q[4]=box_q[1];
}
else
{
box_p[4].x=(double) ((slope.p*box_p[0].x-box_p[0].y-slope.q*box_p[3].x+
box_p[3].y)/(slope.p-slope.q));
box_p[4].y=(double) (slope.p*(box_p[4].x-box_p[0].x)+box_p[0].y);
box_q[4].x=(double) ((slope.p*box_q[0].x-box_q[0].y-slope.q*box_q[3].x+
box_q[3].y)/(slope.p-slope.q));
box_q[4].y=(double) (slope.p*(box_q[4].x-box_q[0].x)+box_q[0].y);
}
if (q >= (ssize_t) (max_strokes-6*BezierQuantum-360))
{
if (~max_strokes < (6*BezierQuantum+360))
{
path_p=(PointInfo *) RelinquishMagickMemory(path_p);
path_q=(PointInfo *) RelinquishMagickMemory(path_q);
}
else
{
max_strokes+=6*BezierQuantum+360;
path_p=(PointInfo *) ResizeQuantumMemory(path_p,max_strokes,
sizeof(*path_p));
path_q=(PointInfo *) ResizeQuantumMemory(path_q,max_strokes,
sizeof(*path_q));
}
if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL))
{
if (path_p != (PointInfo *) NULL)
path_p=(PointInfo *) RelinquishMagickMemory(path_p);
if (path_q != (PointInfo *) NULL)
path_q=(PointInfo *) RelinquishMagickMemory(path_q);
polygon_primitive=(PrimitiveInfo *)
RelinquishMagickMemory(polygon_primitive);
return((PrimitiveInfo *) NULL);
}
}
dot_product=dx.q*dy.p-dx.p*dy.q;
if (dot_product <= 0.0)
switch (draw_info->linejoin)
{
case BevelJoin:
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
path_p[p++]=box_p[4];
else
{
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
}
break;
}
case MiterJoin:
{
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
{
path_q[q++]=box_q[4];
path_p[p++]=box_p[4];
}
else
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
}
break;
}
case RoundJoin:
{
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
path_p[p++]=box_p[4];
else
{
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
}
center=polygon_primitive[n].point;
theta.p=atan2(box_q[1].y-center.y,box_q[1].x-center.x);
theta.q=atan2(box_q[2].y-center.y,box_q[2].x-center.x);
if (theta.q < theta.p)
theta.q+=2.0*MagickPI;
arc_segments=(size_t) ceil((double) ((theta.q-theta.p)/
(2.0*sqrt((double) (1.0/mid)))));
path_q[q].x=box_q[1].x;
path_q[q].y=box_q[1].y;
q++;
for (j=1; j < (ssize_t) arc_segments; j++)
{
delta_theta=(double) (j*(theta.q-theta.p)/arc_segments);
path_q[q].x=(double) (center.x+mid*cos(fmod((double)
(theta.p+delta_theta),DegreesToRadians(360.0))));
path_q[q].y=(double) (center.y+mid*sin(fmod((double)
(theta.p+delta_theta),DegreesToRadians(360.0))));
q++;
}
path_q[q++]=box_q[2];
break;
}
default:
break;
}
else
switch (draw_info->linejoin)
{
case BevelJoin:
{
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
path_q[q++]=box_q[4];
else
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
}
break;
}
case MiterJoin:
{
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
{
path_q[q++]=box_q[4];
path_p[p++]=box_p[4];
}
else
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
}
break;
}
case RoundJoin:
{
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
path_q[q++]=box_q[4];
else
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
}
center=polygon_primitive[n].point;
theta.p=atan2(box_p[1].y-center.y,box_p[1].x-center.x);
theta.q=atan2(box_p[2].y-center.y,box_p[2].x-center.x);
if (theta.p < theta.q)
theta.p+=2.0*MagickPI;
arc_segments=(size_t) ceil((double) ((theta.p-theta.q)/
(2.0*sqrt((double) (1.0/mid)))));
path_p[p++]=box_p[1];
for (j=1; j < (ssize_t) arc_segments; j++)
{
delta_theta=(double) (j*(theta.q-theta.p)/arc_segments);
path_p[p].x=(double) (center.x+mid*cos(fmod((double)
(theta.p+delta_theta),DegreesToRadians(360.0))));
path_p[p].y=(double) (center.y+mid*sin(fmod((double)
(theta.p+delta_theta),DegreesToRadians(360.0))));
p++;
}
path_p[p++]=box_p[2];
break;
}
default:
break;
}
slope.p=slope.q;
inverse_slope.p=inverse_slope.q;
box_p[0]=box_p[2];
box_p[1]=box_p[3];
box_q[0]=box_q[2];
box_q[1]=box_q[3];
dx.p=dx.q;
dy.p=dy.q;
n=i;
}
path_p[p++]=box_p[1];
path_q[q++]=box_q[1];
/*
Trace stroked polygon.
*/
stroke_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t)
(p+q+2UL*closed_path+2UL),sizeof(*stroke_polygon));
if (stroke_polygon != (PrimitiveInfo *) NULL)
{
for (i=0; i < (ssize_t) p; i++)
{
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=path_p[i];
}
if (closed_path != MagickFalse)
{
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=stroke_polygon[0].point;
i++;
}
for ( ; i < (ssize_t) (p+q+closed_path); i++)
{
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=path_q[p+q+closed_path-(i+1)];
}
if (closed_path != MagickFalse)
{
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=stroke_polygon[p+closed_path].point;
i++;
}
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=stroke_polygon[0].point;
i++;
stroke_polygon[i].primitive=UndefinedPrimitive;
stroke_polygon[0].coordinates=(size_t) (p+q+2*closed_path+1);
}
path_p=(PointInfo *) RelinquishMagickMemory(path_p);
path_q=(PointInfo *) RelinquishMagickMemory(path_q);
polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive);
return(stroke_polygon);
}
|
kernel_parallel.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 <libxsmm.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
# if defined(__APPLE__) && defined(__arm64__)
#include <pthread.h>
# endif
# if defined(_OPENMP)
#include <omp.h>
#endif
int g_reps = 0;
#include "kernel_jit_exec.h"
LIBXSMM_INLINE void print_help(void) {
printf("\n\n");
printf("1. Usage (dense*dense=dense, correctness and performance):\n");
printf(" M\n");
printf(" N\n");
printf(" K\n");
printf(" LDA\n");
printf(" LDB\n");
printf(" LDC\n");
printf(" alpha: 1\n");
printf(" beta: 0 or 1\n");
printf(" 0: unaligned A, otherwise aligned\n");
printf(" 0: unaligned C, otherwise aligned\n");
printf(" 0: A normal, 1: A trans\n");
printf(" 0: B normal, 1: B trans\n");
printf(" PREFETCH: nopf (none), pfsigonly, BL2viaC, AL2, curAL2, AL2_BL2viaC, curAL2_BL2viaC\n");
printf(" PRECISION: SP, DP, I16I32, USI8I32, SUI8I32, SUI8UI8, BF16F32, BF16, BF1632_FLAT, BF16_FLAT\n");
printf(" BRGEMM: nobr, addrbr, offsbr, strdbr\n");
printf(" BRsize: 1 - N\n");
printf(" BRunroll: 0/1\n");
printf(" #repetitions\n");
printf(" tile configuration: 1 - external, 0 - internal\n");
printf("\n\n");
printf("2. Usage (dense*dense=dense, performance only option available):\n");
printf(" filename with space-sperated sizes (M N K LDA LDB LDC)\n");
printf(" alpha: 1\n");
printf(" beta: 0 or 1\n");
printf(" 0: unaligned A, otherwise aligned\n");
printf(" 0: unaligned C, otherwise aligned\n");
printf(" 0: A normal, 1: A trans\n");
printf(" 0: B normal, 1: B trans\n");
printf(" PRECISION: SP, DP, I16I32, USI8I32, SUI8I32, SUI8UI8, BF16F32, BF16, BF1632_FLAT, BF16_FLAT\n");
printf(" BRGEMM: nobr, addrbr, offsbr, strdbr\n");
printf(" BRsize: 1 - N\n");
printf(" BRunroll: 0/1\n");
printf(" #repetitions\n");
printf(" 0: no check, otherwise: run check - IGNORE IN THIS TESTER\n");
printf(" tile configuration: 1 - external, 0 - internal\n");
printf("\n\n");
}
int main(int argc, char* argv []) {
char* l_precision = NULL;
libxsmm_blasint l_lda = 0, l_ldb = 0, l_ldc = 0;
int l_m = 0, l_n = 0, l_k = 0;
int l_aligned_a = 0;
int l_aligned_c = 0;
int l_trans_a = 0;
int l_trans_b = 0;
double l_alpha = 0;
double l_beta = 0;
int l_br = 1;
int l_br_type = 0;
int l_br_unroll = 0;
libxsmm_gemm_prefetch_type l_prefetch = LIBXSMM_GEMM_PREFETCH_NONE;
gemm_def l_gemm_def;
double l_runtime_libxsmm = 0;
int l_file_input = 0;
char* l_file_name = NULL;
FILE *l_file_handle = NULL;
int l_run_check = 0;
int l_tc_config = 0;
int l_n_threads = 1;
# if defined(__APPLE__) && defined(__arm64__)
# if 1
pthread_set_qos_class_self_np( QOS_CLASS_USER_INTERACTIVE, 0 );
# else
pthread_set_qos_class_self_np( QOS_CLASS_BACKGROUND, 0 );
# endif
# endif
/* scaling factor */
float l_scf = 1.0;
/* check argument count for a valid range */
if ( argc == 20 || argc == 19 ) {
/* xgemm sizes */
l_m = atoi(argv[1]);
l_n = atoi(argv[2]);
l_k = atoi(argv[3]);
l_lda = atoi(argv[4]);
l_ldb = atoi(argv[5]);
l_ldc = atoi(argv[6]);
/* some sugar */
l_alpha = atof(argv[7]);
l_beta = atof(argv[8]);
l_aligned_a = atoi(argv[9]);
l_aligned_c = atoi(argv[10]);
l_trans_a = atoi(argv[11]);
l_trans_b = atoi(argv[12]);
/* arch specific stuff */
l_precision = argv[14];
l_br = atoi(argv[16]);
l_br_unroll = atoi(argv[17]);
g_reps = atoi(argv[18]);
if ( argc == 20 ) {
l_tc_config = atoi(argv[19]);
} else {
l_tc_config = 0;
}
/* set value of prefetch flag */
if (strcmp("nopf", argv[13]) == 0) {
l_prefetch = LIBXSMM_GEMM_PREFETCH_NONE;
}
else if (strcmp("pfsigonly", argv[13]) == 0) {
l_prefetch = LIBXSMM_GEMM_PREFETCH_SIGONLY;
}
else if (strcmp("BL2viaC", argv[13]) == 0) {
l_prefetch = LIBXSMM_GEMM_PREFETCH_BL2_VIA_C;
}
else if (strcmp("curAL2", argv[13]) == 0) {
l_prefetch = LIBXSMM_GEMM_PREFETCH_AL2_AHEAD;
}
else if (strcmp("curAL2_BL2viaC", argv[13]) == 0) {
l_prefetch = LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C_AHEAD;
}
else if (strcmp("AL2", argv[13]) == 0) {
l_prefetch = LIBXSMM_GEMM_PREFETCH_AL2;
}
else if (strcmp("AL2_BL2viaC", argv[13]) == 0) {
l_prefetch = LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C;
}
else {
print_help();
return EXIT_FAILURE;
}
if (strcmp("nobr", argv[15]) == 0) {
l_br_type = 0;
}
else if (strcmp("addrbr", argv[15]) == 0) {
l_br_type = 1;
}
else if (strcmp("offsbr", argv[15]) == 0) {
l_br_type = 2;
}
else if (strcmp("strdbr", argv[15]) == 0) {
l_br_type = 3;
}
else {
print_help();
return EXIT_FAILURE;
}
l_file_input = 0;
l_run_check = 1;
} else if ( argc == 15 || argc == 14 ) {
l_file_input = 1;
l_file_name = argv[1];
l_alpha = atof(argv[2]);
l_beta = atof(argv[3]);
l_aligned_a = atoi(argv[4]);
l_aligned_c = atoi(argv[5]);
l_trans_a = atoi(argv[6]);
l_trans_b = atoi(argv[7]);
l_precision = argv[8];
l_br = atoi(argv[10]);
l_br_unroll = atoi(argv[11]);
if ( argc == 15 ) {
l_tc_config = atoi(argv[14]);
} else {
l_tc_config = 0;
}
if (strcmp("nobr", argv[9]) == 0) {
l_br_type = 0;
}
else if (strcmp("addrbr", argv[9]) == 0) {
l_br_type = 1;
}
else if (strcmp("offsbr", argv[9]) == 0) {
l_br_type = 2;
}
else if (strcmp("strdbr", argv[9]) == 0) {
l_br_type = 3;
}
else {
print_help();
return EXIT_FAILURE;
}
g_reps = atoi(argv[12]);
l_run_check = atoi(argv[13]);
l_prefetch = LIBXSMM_GEMM_PREFETCH_NONE;
} else {
print_help();
return EXIT_FAILURE;
}
const char *env_arch = getenv("LIBXSMM_TARGET");
const int is_env_SPR = (
env_arch == libxsmm_stristr(env_arch, "spr") ||
env_arch == libxsmm_stristr(env_arch, "amx"));
int arch_cpuid = libxsmm_cpuid();
if ((!is_env_SPR && arch_cpuid < LIBXSMM_X86_AVX512_SPR)
&& (l_tc_config)) {
printf("Warning: external tile configuration will be ingnored\n");
l_tc_config = 0;
}
l_br = (l_br < 1) ? 1 : l_br;
l_br = (l_br_type == 0) ? 1 : l_br;
l_br_unroll = (l_br_type == 0) ? 0 : l_br_unroll;
/* check alpha */
if ( LIBXSMM_NEQ(l_alpha, 1.0) ) {
fprintf(stderr, "JIT: alpha needs to be 1.0!\n");
exit(EXIT_FAILURE);
}
/* check beta */
if ( LIBXSMM_NEQ(l_beta, 0.0) && LIBXSMM_NEQ(l_beta, 1.0) ) {
fprintf(stderr, "JIT: beta needs to be 0.0 or 1.0!\n");
exit(EXIT_FAILURE);
}
/* read the number of threads */
#if defined(_OPENMP)
#pragma omp parallel
{
#pragma omp master
{
l_n_threads = omp_get_num_threads();
}
}
#endif
if ( l_file_input != 0 ) {
l_file_handle = fopen( l_file_name, "r" );
} else {
if ( l_trans_b == 0 ) {
printf("------------------------------------------------\n");
printf("RUNNING (%ix%i) X (%ix%i) = (%ix%i), %s, BR=%i\n", l_m, l_k, l_k, l_n, l_m, l_n, l_precision, l_br);
printf("------------------------------------------------\n");
} else {
printf("------------------------------------------------\n");
printf("RUNNING (%ix%i) X (%ix%i)^T = (%ix%i), %s, BR=%i\n", l_m, l_k, l_k, l_n, l_m, l_n, l_precision, l_br);
printf("------------------------------------------------\n");
}
}
if ((strcmp(l_precision, "DP") == 0) && (l_trans_b == 0)) {
unsigned int l_keep_going = 0;
do {
if ( l_file_input != 0 ) {
char l_line[512];
if ( fgets( l_line, 512, l_file_handle) == NULL ) {
l_keep_going = 0;
break;
} else {
l_keep_going = 1;
}
if ( 6 != sscanf( l_line, "%i %i %i %i %i %i", &l_m, &l_n, &l_k, &l_lda, &l_ldb, &l_ldc ) ) exit(EXIT_FAILURE);
}
l_gemm_def.m = l_m;
l_gemm_def.n = l_n;
l_gemm_def.k = l_k;
l_gemm_def.lda = l_lda;
l_gemm_def.ldb = l_ldb;
l_gemm_def.ldc = l_ldc;
l_gemm_def.alpha = l_alpha;
l_gemm_def.beta = l_beta;
l_gemm_def.trans_a = l_trans_a;
l_gemm_def.trans_b = l_trans_b;
l_gemm_def.aligned_a = l_aligned_a;
l_gemm_def.aligned_c = l_aligned_c;
l_gemm_def.prefetch = l_prefetch;
l_gemm_def.br_type = l_br_type;
l_gemm_def.br_count = l_br;
l_gemm_def.br_unroll = l_br_unroll;
l_gemm_def.tc_config = l_tc_config;
#if defined(_OPENMP)
#pragma omp parallel reduction(+:l_runtime_libxsmm)
#endif
{
unsigned int l_r, l_i, l_j;
double* l_a_d = (double*)libxsmm_aligned_malloc((size_t)l_lda * (size_t)l_k * (size_t)l_br * sizeof(double), 64);
double* l_b_d = (double*)libxsmm_aligned_malloc((size_t)l_ldb * (size_t)l_n * (size_t)l_br * sizeof(double), 64);
double* l_c_d = (double*)libxsmm_aligned_malloc((size_t)l_ldc * (size_t)l_n * sizeof(double), 64);
/* touch A */
for (l_r = 0; l_r < l_br; l_r++) {
for (l_i = 0; l_i < l_lda; l_i++) {
for (l_j = 0; l_j < l_k; l_j++) {
l_a_d[(l_r * l_lda * l_k) + ((l_j * l_lda) + l_i)] = libxsmm_rng_f64();
}
}
}
/* touch B */
for (l_r = 0; l_r < l_br; l_r++) {
for (l_i = 0; l_i < l_ldb; l_i++) {
for (l_j = 0; l_j < l_n; l_j++) {
l_b_d[(l_r * l_ldb * l_n) + ((l_j * l_ldb) + l_i)] = libxsmm_rng_f64();
}
}
}
/* touch C */
for (l_i = 0; l_i < l_ldc; l_i++) {
for (l_j = 0; l_j < l_n; l_j++) {
l_c_d[(l_j * l_ldc) + l_i] = 0.0;
}
}
l_runtime_libxsmm = run_jit_double( &l_gemm_def, l_a_d, l_b_d, l_c_d, l_file_input );
libxsmm_free(l_a_d);
libxsmm_free(l_b_d);
libxsmm_free(l_c_d);
}
l_runtime_libxsmm /= (double)l_n_threads;
if ( l_file_input == 0 ) {
printf("avg %fs per core for libxsmm\n", l_runtime_libxsmm);
printf("avg %f GFLOPS per core for libxsmm\n", ((double)((double)g_reps * (double)l_m * (double)l_n * (double)l_k * (double)l_br) * 2.0) / (l_runtime_libxsmm * 1.0e9));
} else {
printf("%i %i %i %i %i %i %i %i %i %s %f\n", l_m, l_n, l_k, l_lda, l_ldb, l_ldc, l_br, l_br_type, l_br_unroll, l_precision, ((double)((double)g_reps * (double)l_m * (double)l_n * (double)l_k * (double)l_br) * 2.0) / (l_runtime_libxsmm * 1.0e9) );
}
} while ( l_keep_going );
}
else if ((strcmp(l_precision, "DP") == 0) && (l_trans_b != 0)) {
unsigned int l_keep_going = 0;
do {
if ( l_file_input != 0 ) {
char l_line[512];
if ( fgets( l_line, 512, l_file_handle) == NULL ) {
l_keep_going = 0;
break;
} else {
l_keep_going = 1;
}
if ( 6 != sscanf( l_line, "%i %i %i %i %i %i", &l_m, &l_n, &l_k, &l_lda, &l_ldb, &l_ldc ) ) exit(EXIT_FAILURE);
}
l_gemm_def.m = l_m;
l_gemm_def.n = l_n;
l_gemm_def.k = l_k;
l_gemm_def.lda = l_lda;
l_gemm_def.ldb = l_ldb;
l_gemm_def.ldc = l_ldc;
l_gemm_def.alpha = l_alpha;
l_gemm_def.beta = l_beta;
l_gemm_def.trans_a = l_trans_a;
l_gemm_def.trans_b = l_trans_b;
l_gemm_def.aligned_a = l_aligned_a;
l_gemm_def.aligned_c = l_aligned_c;
l_gemm_def.prefetch = l_prefetch;
l_gemm_def.br_type = l_br_type;
l_gemm_def.br_count = l_br;
l_gemm_def.br_unroll = l_br_unroll;
l_gemm_def.tc_config = l_tc_config;
#if defined(_OPENMP)
#pragma omp parallel reduction(+:l_runtime_libxsmm)
#endif
{
unsigned int l_r, l_i, l_j;
double* l_a_d = (double*)libxsmm_aligned_malloc((size_t)l_lda * (size_t)l_k * (size_t)l_br * sizeof(double), 64);
double* l_b_d = (double*)libxsmm_aligned_malloc((size_t)l_ldb * (size_t)l_k * (size_t)l_br * sizeof(double), 64);
double* l_c_d = (double*)libxsmm_aligned_malloc((size_t)l_ldc * (size_t)l_n * sizeof(double), 64);
/* touch A */
for (l_r = 0; l_r < l_br; l_r++) {
for (l_i = 0; l_i < l_lda; l_i++) {
for (l_j = 0; l_j < l_k; l_j++) {
l_a_d[(l_r * l_lda * l_k) + ((l_j * l_lda) + l_i)] = libxsmm_rng_f64();
}
}
}
/* touch B */
for (l_r = 0; l_r < l_br; l_r++) {
for (l_i = 0; l_i < l_ldb; l_i++) {
for (l_j = 0; l_j < l_n; l_j++) {
l_b_d[(l_r * l_ldb * l_n) + ((l_j * l_ldb) + l_i)] = libxsmm_rng_f64();
}
}
}
/* touch C */
for (l_i = 0; l_i < l_ldc; l_i++) {
for (l_j = 0; l_j < l_n; l_j++) {
l_c_d[(l_j * l_ldc) + l_i] = 0.0;
}
}
l_runtime_libxsmm = run_jit_double( &l_gemm_def, l_a_d, l_b_d, l_c_d, l_file_input );
libxsmm_free(l_a_d);
libxsmm_free(l_b_d);
libxsmm_free(l_c_d);
}
l_runtime_libxsmm /= (double)l_n_threads;
if ( l_file_input == 0 ) {
printf("avg %fs per core for libxsmm\n", l_runtime_libxsmm);
printf("avg %f GFLOPS per core for libxsmm\n", ((double)((double)g_reps * (double)l_m * (double)l_n * (double)l_k * (double)l_br) * 2.0) / (l_runtime_libxsmm * 1.0e9));
} else {
printf("%i %i %i %i %i %i %i %i %i %s %f\n", l_m, l_n, l_k, l_lda, l_ldb, l_ldc, l_br, l_br_type, l_br_unroll, l_precision, ((double)((double)g_reps * (double)l_m * (double)l_n * (double)l_k * (double)l_br) * 2.0) / (l_runtime_libxsmm * 1.0e9) );
}
} while ( l_keep_going );
}
else if ((strcmp(l_precision, "SP") == 0) && (l_trans_b == 0)) {
unsigned int l_keep_going = 0;
do {
if ( l_file_input != 0 ) {
char l_line[512];
if ( fgets( l_line, 512, l_file_handle) == NULL ) {
l_keep_going = 0;
break;
} else {
l_keep_going = 1;
}
if ( 6 != sscanf( l_line, "%i %i %i %i %i %i", &l_m, &l_n, &l_k, &l_lda, &l_ldb, &l_ldc ) ) exit(EXIT_FAILURE);
}
l_gemm_def.m = l_m;
l_gemm_def.n = l_n;
l_gemm_def.k = l_k;
l_gemm_def.lda = l_lda;
l_gemm_def.ldb = l_ldb;
l_gemm_def.ldc = l_ldc;
l_gemm_def.alpha = l_alpha;
l_gemm_def.beta = l_beta;
l_gemm_def.trans_a = l_trans_a;
l_gemm_def.trans_b = l_trans_b;
l_gemm_def.aligned_a = l_aligned_a;
l_gemm_def.aligned_c = l_aligned_c;
l_gemm_def.prefetch = l_prefetch;
l_gemm_def.br_type = l_br_type;
l_gemm_def.br_count = l_br;
l_gemm_def.br_unroll = l_br_unroll;
l_gemm_def.tc_config = l_tc_config;
#if defined(_OPENMP)
#pragma omp parallel reduction(+:l_runtime_libxsmm)
#endif
{
unsigned int l_r, l_i, l_j;
float* l_a_f = (float*)libxsmm_aligned_malloc((size_t)l_lda * (size_t)l_k * (size_t)l_br * sizeof(float), 64);
float* l_b_f = (float*)libxsmm_aligned_malloc((size_t)l_ldb * (size_t)l_n * (size_t)l_br * sizeof(float), 64);
float* l_c_f = (float*)libxsmm_aligned_malloc((size_t)l_ldc * (size_t)l_n * sizeof(float), 64);
/* touch A */
for (l_r = 0; l_r < l_br; l_r++) {
for (l_i = 0; l_i < l_lda; l_i++) {
for (l_j = 0; l_j < l_k; l_j++) {
l_a_f[(l_r * l_lda * l_k) + ((l_j * l_lda) + l_i)] = (float)libxsmm_rng_f64();
}
}
}
/* touch B */
for (l_r = 0; l_r < l_br; l_r++) {
for (l_i = 0; l_i < l_ldb; l_i++) {
for (l_j = 0; l_j < l_n; l_j++) {
l_b_f[(l_r * l_ldb * l_n) + ((l_j * l_ldb) + l_i)] = (float)libxsmm_rng_f64();
}
}
}
/* touch C */
for (l_i = 0; l_i < l_ldc; l_i++) {
for (l_j = 0; l_j < l_n; l_j++) {
l_c_f[(l_j * l_ldc) + l_i] = 0.f;
}
}
l_runtime_libxsmm = run_jit_float( &l_gemm_def, l_a_f, l_b_f, l_c_f, l_file_input );
libxsmm_free(l_a_f);
libxsmm_free(l_b_f);
libxsmm_free(l_c_f);
}
l_runtime_libxsmm /= (double)l_n_threads;
if ( l_file_input == 0 ) {
printf("avg %fs per core for libxsmm\n", l_runtime_libxsmm);
printf("avg %f GFLOPS per core for libxsmm\n", ((double)((double)g_reps * (double)l_m * (double)l_n * (double)l_k * (double)l_br) * 2.0) / (l_runtime_libxsmm * 1.0e9));
} else {
printf("%i %i %i %i %i %i %i %i %i %s %f\n", l_m, l_n, l_k, l_lda, l_ldb, l_ldc, l_br, l_br_type, l_br_unroll, l_precision, ((double)((double)g_reps * (double)l_m * (double)l_n * (double)l_k * (double)l_br) * 2.0) / (l_runtime_libxsmm * 1.0e9) );
}
} while ( l_keep_going );
}
else if ((strcmp(l_precision, "SP") == 0) && (l_trans_b != 0)) {
unsigned int l_keep_going = 0;
do {
if ( l_file_input != 0 ) {
char l_line[512];
if ( fgets( l_line, 512, l_file_handle) == NULL ) {
l_keep_going = 0;
break;
} else {
l_keep_going = 1;
}
if ( 6 != sscanf( l_line, "%i %i %i %i %i %i", &l_m, &l_n, &l_k, &l_lda, &l_ldb, &l_ldc ) ) exit(EXIT_FAILURE);
}
l_gemm_def.m = l_m;
l_gemm_def.n = l_n;
l_gemm_def.k = l_k;
l_gemm_def.lda = l_lda;
l_gemm_def.ldb = l_ldb;
l_gemm_def.ldc = l_ldc;
l_gemm_def.alpha = l_alpha;
l_gemm_def.beta = l_beta;
l_gemm_def.trans_a = l_trans_a;
l_gemm_def.trans_b = l_trans_b;
l_gemm_def.aligned_a = l_aligned_a;
l_gemm_def.aligned_c = l_aligned_c;
l_gemm_def.prefetch = l_prefetch;
l_gemm_def.br_type = l_br_type;
l_gemm_def.br_count = l_br;
l_gemm_def.br_unroll = l_br_unroll;
l_gemm_def.tc_config = l_tc_config;
#if defined(_OPENMP)
#pragma omp parallel reduction(+:l_runtime_libxsmm)
#endif
{
unsigned int l_r, l_i, l_j;
float* l_a_f = (float*)libxsmm_aligned_malloc((size_t)l_lda * (size_t)l_k * (size_t)l_br * sizeof(float), 64);
float* l_b_f = (float*)libxsmm_aligned_malloc((size_t)l_ldb * (size_t)l_k * (size_t)l_br * sizeof(float), 64);
float* l_c_f = (float*)libxsmm_aligned_malloc((size_t)l_ldc * (size_t)l_n * sizeof(float), 64);
/* touch A */
for (l_r = 0; l_r < l_br; l_r++) {
for (l_i = 0; l_i < l_lda; l_i++) {
for (l_j = 0; l_j < l_k; l_j++) {
l_a_f[(l_r * l_lda * l_k) + ((l_j * l_lda) + l_i)] = (float)libxsmm_rng_f64();
}
}
}
/* touch B */
for (l_r = 0; l_r < l_br; l_r++) {
for (l_i = 0; l_i < l_ldb; l_i++) {
for (l_j = 0; l_j < l_n; l_j++) {
l_b_f[(l_r * l_ldb * l_n) + ((l_j * l_ldb) + l_i)] = (float)libxsmm_rng_f64();
}
}
}
/* touch C */
for (l_i = 0; l_i < l_ldc; l_i++) {
for (l_j = 0; l_j < l_n; l_j++) {
l_c_f[(l_j * l_ldc) + l_i] = 0.f;
}
}
l_runtime_libxsmm = run_jit_float( &l_gemm_def, l_a_f, l_b_f, l_c_f, l_file_input );
libxsmm_free(l_a_f);
libxsmm_free(l_b_f);
libxsmm_free(l_c_f);
}
l_runtime_libxsmm /= (double)l_n_threads;
if ( l_file_input == 0 ) {
printf("avg %fs per core for libxsmm\n", l_runtime_libxsmm);
printf("avg %f GFLOPS per core for libxsmm\n", ((double)((double)g_reps * (double)l_m * (double)l_n * (double)l_k * (double)l_br) * 2.0) / (l_runtime_libxsmm * 1.0e9));
} else {
printf("%i %i %i %i %i %i %i %i %i %s %f\n", l_m, l_n, l_k, l_lda, l_ldb, l_ldc, l_br, l_br_type, l_br_unroll, l_precision, ((double)((double)g_reps * (double)l_m * (double)l_n * (double)l_k * (double)l_br) * 2.0) / (l_runtime_libxsmm * 1.0e9) );
}
} while ( l_keep_going );
} else if (strcmp(l_precision, "I16I32") == 0) {
unsigned int l_keep_going = 0;
do {
if ( l_file_input != 0 ) {
char l_line[512];
if ( fgets( l_line, 512, l_file_handle) == NULL ) {
l_keep_going = 0;
break;
} else {
l_keep_going = 1;
}
if ( 6 != sscanf( l_line, "%i %i %i %i %i %i", &l_m, &l_n, &l_k, &l_lda, &l_ldb, &l_ldc ) ) exit(EXIT_FAILURE);
}
l_gemm_def.m = l_m;
l_gemm_def.n = l_n;
l_gemm_def.k = l_k;
l_gemm_def.lda = l_lda;
l_gemm_def.ldb = l_ldb;
l_gemm_def.ldc = l_ldc;
l_gemm_def.alpha = l_alpha;
l_gemm_def.beta = l_beta;
l_gemm_def.trans_a = l_trans_a;
l_gemm_def.trans_b = l_trans_b;
l_gemm_def.aligned_a = l_aligned_a;
l_gemm_def.aligned_c = l_aligned_c;
l_gemm_def.prefetch = l_prefetch;
l_gemm_def.br_type = l_br_type;
l_gemm_def.br_count = l_br;
l_gemm_def.br_unroll = l_br_unroll;
l_gemm_def.tc_config = l_tc_config;
#if defined(_OPENMP)
#pragma omp parallel reduction(+:l_runtime_libxsmm)
#endif
{
unsigned int l_r, l_i, l_j;
short* l_a_w = (short*)libxsmm_aligned_malloc((size_t)l_lda * (size_t)l_k * (size_t)l_br * sizeof(short), 64);
short* l_b_w = (short*)libxsmm_aligned_malloc((size_t)l_ldb * (size_t)l_n * (size_t)l_br * sizeof(short), 64);
int* l_c_w_i = (int*)libxsmm_aligned_malloc((size_t)l_ldc * (size_t)l_n * sizeof(int), 64);
/* touch A */
for (l_r = 0; l_r < l_br; l_r++) {
for (l_i = 0; l_i < l_lda; l_i++) {
for (l_j = 0; l_j < l_k; l_j++) {
l_a_w[(l_r * l_lda * l_k) + ((l_j * l_lda) + l_i)] = (short)(libxsmm_rng_f64() * 10.0);
}
}
}
/* touch B */
for (l_r = 0; l_r < l_br; l_r++) {
for (l_i = 0; l_i < l_ldb; l_i++) {
for (l_j = 0; l_j < l_n; l_j++) {
l_b_w[(l_r * l_ldb * l_n) + ((l_j * l_ldb) + l_i)] = (short)(libxsmm_rng_f64() * 10.0);
}
}
}
/* touch C */
for (l_i = 0; l_i < l_ldc; l_i++) {
for (l_j = 0; l_j < l_n; l_j++) {
l_c_w_i[(l_j * l_ldc) + l_i] = 0;
}
}
l_runtime_libxsmm = run_jit_short_int( &l_gemm_def, l_a_w, l_b_w, l_c_w_i, l_file_input );
libxsmm_free(l_a_w);
libxsmm_free(l_b_w);
libxsmm_free(l_c_w_i);
}
l_runtime_libxsmm /= (double)l_n_threads;
if ( l_file_input == 0 ) {
printf("avg %fs per core for libxsmm\n", l_runtime_libxsmm);
printf("avg %f GFLOPS per oore for libxsmm\n", ((double)((double)g_reps * (double)l_m * (double)l_n * (double)l_k * (double)l_br) * 2.0) / (l_runtime_libxsmm * 1.0e9));
} else {
printf("%i %i %i %i %i %i %i %i %i %s %f\n", l_m, l_n, l_k, l_lda, l_ldb, l_ldc, l_br, l_br_type, l_br_unroll, l_precision, ((double)((double)g_reps * (double)l_m * (double)l_n * (double)l_k * (double)l_br) * 2.0) / (l_runtime_libxsmm * 1.0e9) );
}
} while ( l_keep_going );
} else if (strcmp(l_precision, "USI8I32") == 0) {
unsigned int l_keep_going = 0;
do {
if ( l_file_input != 0 ) {
char l_line[512];
if ( fgets( l_line, 512, l_file_handle) == NULL ) {
l_keep_going = 0;
break;
} else {
l_keep_going = 1;
}
if ( 6 != sscanf( l_line, "%i %i %i %i %i %i", &l_m, &l_n, &l_k, &l_lda, &l_ldb, &l_ldc ) ) exit(EXIT_FAILURE);
}
l_gemm_def.m = l_m;
l_gemm_def.n = l_n;
l_gemm_def.k = l_k;
l_gemm_def.lda = l_lda;
l_gemm_def.ldb = l_ldb;
l_gemm_def.ldc = l_ldc;
l_gemm_def.alpha = l_alpha;
l_gemm_def.beta = l_beta;
l_gemm_def.trans_a = l_trans_a;
l_gemm_def.trans_b = l_trans_b;
l_gemm_def.aligned_a = l_aligned_a;
l_gemm_def.aligned_c = l_aligned_c;
l_gemm_def.prefetch = l_prefetch;
l_gemm_def.br_type = l_br_type;
l_gemm_def.br_count = l_br;
l_gemm_def.br_unroll = l_br_unroll;
l_gemm_def.tc_config = l_tc_config;
#if defined(_OPENMP)
#pragma omp parallel reduction(+:l_runtime_libxsmm)
#endif
{
unsigned int l_r, l_i, l_j;
unsigned char* l_ua_b = (unsigned char*)libxsmm_aligned_malloc((size_t)l_lda * (size_t)l_k * (size_t)l_br * sizeof(unsigned char), 64);
char* l_sb_b = (char*)libxsmm_aligned_malloc((size_t)l_ldb * (size_t)l_n * (size_t)l_br * sizeof(char), 64);
int* l_c_b_i = (int*)libxsmm_aligned_malloc((size_t)l_ldc * (size_t)l_n * sizeof(int), 64);
/* touch A */
for (l_r = 0; l_r < l_br; l_r++) {
for (l_i = 0; l_i < l_lda; l_i++) {
for (l_j = 0; l_j < l_k; l_j++) {
l_ua_b[(l_r * l_lda * l_k) + ((l_j * l_lda) + l_i)] = (unsigned char)(libxsmm_rng_f64() * 5.0);
}
}
}
/* touch B */
for (l_r = 0; l_r < l_br; l_r++) {
for (l_i = 0; l_i < l_ldb; l_i++) {
for (l_j = 0; l_j < l_n; l_j++) {
l_sb_b[(l_r * l_ldb * l_n) + ((l_j * l_ldb) + l_i)] = (char)(libxsmm_rng_f64() * 5.0);
}
}
}
/* touch C */
for (l_i = 0; l_i < l_ldc; l_i++) {
for (l_j = 0; l_j < l_n; l_j++) {
l_c_b_i[(l_j * l_ldc) + l_i] = 0;
}
}
l_runtime_libxsmm = run_jit_uschar_int( &l_gemm_def, l_ua_b, l_sb_b, l_c_b_i, l_file_input );
libxsmm_free(l_ua_b);
libxsmm_free(l_sb_b);
libxsmm_free(l_c_b_i);
}
l_runtime_libxsmm /= (double)l_n_threads;
if ( l_file_input == 0 ) {
printf("avg %fs per core for libxsmm\n", l_runtime_libxsmm);
printf("avg %f GFLOPS per core for libxsmm\n", ((double)((double)g_reps * (double)l_m * (double)l_n * (double)l_k * (double)l_br) * 2.0) / (l_runtime_libxsmm * 1.0e9));
} else {
printf("%i %i %i %i %i %i %i %i %i %s %f\n", l_m, l_n, l_k, l_lda, l_ldb, l_ldc, l_br, l_br_type, l_br_unroll, l_precision, ((double)((double)g_reps * (double)l_m * (double)l_n * (double)l_k * (double)l_br) * 2.0) / (l_runtime_libxsmm * 1.0e9) );
}
} while ( l_keep_going );
} else if (strcmp(l_precision, "SUI8I32") == 0) {
unsigned int l_keep_going = 0;
do {
if ( l_file_input != 0 ) {
char l_line[512];
if ( fgets( l_line, 512, l_file_handle) == NULL ) {
l_keep_going = 0;
break;
} else {
l_keep_going = 1;
}
if ( 6 != sscanf( l_line, "%i %i %i %i %i %i", &l_m, &l_n, &l_k, &l_lda, &l_ldb, &l_ldc ) ) exit(EXIT_FAILURE);
}
l_gemm_def.m = l_m;
l_gemm_def.n = l_n;
l_gemm_def.k = l_k;
l_gemm_def.lda = l_lda;
l_gemm_def.ldb = l_ldb;
l_gemm_def.ldc = l_ldc;
l_gemm_def.alpha = l_alpha;
l_gemm_def.beta = l_beta;
l_gemm_def.trans_a = l_trans_a;
l_gemm_def.trans_b = l_trans_b;
l_gemm_def.aligned_a = l_aligned_a;
l_gemm_def.aligned_c = l_aligned_c;
l_gemm_def.prefetch = l_prefetch;
l_gemm_def.br_type = l_br_type;
l_gemm_def.br_count = l_br;
l_gemm_def.br_unroll = l_br_unroll;
l_gemm_def.tc_config = l_tc_config;
#if defined(_OPENMP)
#pragma omp parallel reduction(+:l_runtime_libxsmm)
#endif
{
unsigned int l_r, l_i, l_j;
char* l_sa_b = (char*)libxsmm_aligned_malloc((size_t)l_lda * (size_t)l_k * (size_t)l_br * sizeof(char), 64);
unsigned char* l_ub_b = (unsigned char*)libxsmm_aligned_malloc((size_t)l_ldb * (size_t)l_n * (size_t)l_br * sizeof(unsigned char), 64);
int* l_c_b_i = (int*)libxsmm_aligned_malloc((size_t)l_ldc * (size_t)l_n * sizeof(int), 64);
/* touch A */
for (l_r = 0; l_r < l_br; l_r++) {
for (l_i = 0; l_i < l_lda; l_i++) {
for (l_j = 0; l_j < l_k; l_j++) {
l_sa_b[(l_r * l_lda * l_k) + ((l_j * l_lda) + l_i)] = (char)(libxsmm_rng_f64() * 5.0);
}
}
}
/* touch B */
for (l_r = 0; l_r < l_br; l_r++) {
for (l_i = 0; l_i < l_ldb; l_i++) {
for (l_j = 0; l_j < l_n; l_j++) {
l_ub_b[(l_r * l_ldb * l_n) + ((l_j * l_ldb) + l_i)] = (unsigned char)(libxsmm_rng_f64() * 5.0);
}
}
}
/* touch C */
for (l_i = 0; l_i < l_ldc; l_i++) {
for (l_j = 0; l_j < l_n; l_j++) {
l_c_b_i[(l_j * l_ldc) + l_i] = 0;
}
}
l_runtime_libxsmm = run_jit_suchar_int( &l_gemm_def, l_sa_b, l_ub_b, l_c_b_i, l_file_input );
libxsmm_free(l_sa_b);
libxsmm_free(l_ub_b);
libxsmm_free(l_c_b_i);
}
l_runtime_libxsmm /= (double)l_n_threads;
if ( l_file_input == 0 ) {
printf("avg %fs per core for libxsmm\n", l_runtime_libxsmm);
printf("avg %f GFLOPS per core for libxsmm\n", ((double)((double)g_reps * (double)l_m * (double)l_n * (double)l_k * (double)l_br) * 2.0) / (l_runtime_libxsmm * 1.0e9));
} else {
printf("%i %i %i %i %i %i %i %i %i %s %f\n", l_m, l_n, l_k, l_lda, l_ldb, l_ldc, l_br, l_br_type, l_br_unroll, l_precision, ((double)((double)g_reps * (double)l_m * (double)l_n * (double)l_k * (double)l_br) * 2.0) / (l_runtime_libxsmm * 1.0e9) );
}
} while ( l_keep_going );
} else if (strcmp(l_precision, "SUI8UI8") == 0) {
unsigned int l_keep_going = 0;
do {
if ( l_file_input != 0 ) {
char l_line[512];
if ( fgets( l_line, 512, l_file_handle) == NULL ) {
l_keep_going = 0;
break;
} else {
l_keep_going = 1;
}
if ( 6 != sscanf( l_line, "%i %i %i %i %i %i", &l_m, &l_n, &l_k, &l_lda, &l_ldb, &l_ldc ) ) exit(EXIT_FAILURE);
}
l_gemm_def.m = l_m;
l_gemm_def.n = l_n;
l_gemm_def.k = l_k;
l_gemm_def.lda = l_lda;
l_gemm_def.ldb = l_ldb;
l_gemm_def.ldc = l_ldc;
l_gemm_def.alpha = l_alpha;
l_gemm_def.beta = l_beta;
l_gemm_def.trans_a = l_trans_a;
l_gemm_def.trans_b = l_trans_b;
l_gemm_def.aligned_a = l_aligned_a;
l_gemm_def.aligned_c = l_aligned_c;
l_gemm_def.prefetch = l_prefetch;
l_gemm_def.br_type = l_br_type;
l_gemm_def.br_count = l_br;
l_gemm_def.br_unroll = l_br_unroll;
l_gemm_def.tc_config = l_tc_config;
#if defined(_OPENMP)
#pragma omp parallel reduction(+:l_runtime_libxsmm)
#endif
{
unsigned int l_r, l_i, l_j;
char* l_sa_b = (char*)libxsmm_aligned_malloc((size_t)l_lda * (size_t)l_k * (size_t)l_br * sizeof(char), 64);
unsigned char* l_ub_b = (unsigned char*)libxsmm_aligned_malloc((size_t)l_ldb * (size_t)l_n * (size_t)l_br * sizeof(unsigned char), 64);
unsigned char* l_c_b_ub = (unsigned char*)libxsmm_aligned_malloc((size_t)l_ldc * (size_t)l_n * sizeof(unsigned char), 64);
/* touch A */
for (l_r = 0; l_r < l_br; l_r++) {
for (l_i = 0; l_i < l_lda; l_i++) {
for (l_j = 0; l_j < l_k; l_j++) {
l_sa_b[(l_r * l_lda * l_k) + ((l_j * l_lda) + l_i)] = (char)(libxsmm_rng_f64() * 2.0);
}
}
}
/* touch B */
for (l_r = 0; l_r < l_br; l_r++) {
for (l_i = 0; l_i < l_ldb; l_i++) {
for (l_j = 0; l_j < l_n; l_j++) {
l_ub_b[(l_r * l_ldb * l_n) + ((l_j * l_ldb) + l_i)] = (unsigned char)(libxsmm_rng_f64() * 2.0);
}
}
}
/* touch C */
for (l_i = 0; l_i < l_ldc; l_i++) {
for (l_j = 0; l_j < l_n; l_j++) {
l_c_b_ub[(l_j * l_ldc) + l_i] = 0;
}
}
l_runtime_libxsmm = run_jit_suchar_uchar( &l_gemm_def, l_sa_b, l_ub_b, l_c_b_ub, l_scf, l_file_input );
libxsmm_free(l_sa_b);
libxsmm_free(l_ub_b);
libxsmm_free(l_c_b_ub);
}
l_runtime_libxsmm /= (double)l_n_threads;
if ( l_file_input == 0 ) {
printf("avg %fs per core for libxsmm\n", l_runtime_libxsmm);
printf("avg %f GFLOPS per core for libxsmm\n", ((double)((double)g_reps * (double)l_m * (double)l_n * (double)l_k * (double)l_br) * 2.0) / (l_runtime_libxsmm * 1.0e9));
} else {
printf("%i %i %i %i %i %i %i %i %i %s %f\n", l_m, l_n, l_k, l_lda, l_ldb, l_ldc, l_br, l_br_type, l_br_unroll, l_precision, ((double)((double)g_reps * (double)l_m * (double)l_n * (double)l_k * (double)l_br) * 2.0) / (l_runtime_libxsmm * 1.0e9) );
}
} while ( l_keep_going );
} else if (strcmp(l_precision, "BF16F32") == 0) {
unsigned int l_keep_going = 0;
do {
if ( l_file_input != 0 ) {
char l_line[512];
if ( fgets( l_line, 512, l_file_handle) == NULL ) {
l_keep_going = 0;
break;
} else {
l_keep_going = 1;
}
if ( 6 != sscanf( l_line, "%i %i %i %i %i %i", &l_m, &l_n, &l_k, &l_lda, &l_ldb, &l_ldc ) ) exit(EXIT_FAILURE);
}
l_gemm_def.m = l_m;
l_gemm_def.n = l_n;
l_gemm_def.k = l_k;
l_gemm_def.lda = l_lda;
l_gemm_def.ldb = l_ldb;
l_gemm_def.ldc = l_ldc;
l_gemm_def.alpha = l_alpha;
l_gemm_def.beta = l_beta;
l_gemm_def.trans_a = l_trans_a;
l_gemm_def.trans_b = l_trans_b;
l_gemm_def.aligned_a = l_aligned_a;
l_gemm_def.aligned_c = l_aligned_c;
l_gemm_def.prefetch = l_prefetch;
l_gemm_def.br_type = l_br_type;
l_gemm_def.br_count = l_br;
l_gemm_def.br_unroll = l_br_unroll;
l_gemm_def.tc_config = l_tc_config;
#if defined(_OPENMP)
#pragma omp parallel reduction(+:l_runtime_libxsmm)
#endif
{
unsigned int l_r, l_i, l_j;
libxsmm_bfloat16* l_a_bf = (libxsmm_bfloat16*)libxsmm_aligned_malloc((size_t)l_lda * (size_t)l_k * (size_t)l_br * sizeof(libxsmm_bfloat16), 64);
libxsmm_bfloat16* l_b_bf = (libxsmm_bfloat16*)libxsmm_aligned_malloc((size_t)l_ldb * (size_t)l_n * (size_t)l_br * sizeof(libxsmm_bfloat16), 64);
float* l_c_bf_f = (float*)libxsmm_aligned_malloc((size_t)l_ldc * (size_t)l_n * sizeof(float), 64);
/* touch A */
for (l_r = 0; l_r < l_br; l_r++) {
for (l_i = 0; l_i < l_lda; l_i++) {
for (l_j = 0; l_j < l_k; l_j++) {
union libxsmm_bfloat16_hp tmp;
tmp.f = (float)libxsmm_rng_f64();
l_a_bf[(l_r * l_lda * l_k) + (l_j * l_lda) + l_i] = tmp.i[1];
}
}
}
/* touch B */
for (l_r = 0; l_r < l_br; l_r++) {
for (l_i = 0; l_i < l_ldb; l_i++) {
for (l_j = 0; l_j < l_n; l_j++) {
union libxsmm_bfloat16_hp tmp;
tmp.f = (float)libxsmm_rng_f64();
l_b_bf[(l_r * l_ldb * l_n) + (l_j * l_ldb) + l_i] = tmp.i[1];
}
}
}
/* touch C */
for (l_i = 0; l_i < l_ldc; l_i++) {
for (l_j = 0; l_j < l_n; l_j++) {
l_c_bf_f[(l_j * l_ldc) + l_i] = 0.0f;
}
}
l_runtime_libxsmm = run_jit_bfloat16_float( &l_gemm_def, l_a_bf, l_b_bf, l_c_bf_f, l_file_input );
libxsmm_free(l_a_bf);
libxsmm_free(l_b_bf);
libxsmm_free(l_c_bf_f);
}
l_runtime_libxsmm /= (double)l_n_threads;
if ( l_file_input == 0 ) {
printf("avg %fs per core for libxsmm\n", l_runtime_libxsmm);
printf("avg %f GFLOPS per core for libxsmm\n", ((double)((double)g_reps * (double)l_m * (double)l_n * (double)l_k * (double)l_br) * 2.0) / (l_runtime_libxsmm * 1.0e9));
} else {
printf("%i %i %i %i %i %i %i %i %i %s %f\n", l_m, l_n, l_k, l_lda, l_ldb, l_ldc, l_br, l_br_type, l_br_unroll, l_precision, ((double)((double)g_reps * (double)l_m * (double)l_n * (double)l_k * (double)l_br) * 2.0) / (l_runtime_libxsmm * 1.0e9) );
}
} while ( l_keep_going );
} else if (strcmp(l_precision, "BF16") == 0) {
unsigned int l_keep_going = 0;
do {
if ( l_file_input != 0 ) {
char l_line[512];
if ( fgets( l_line, 512, l_file_handle) == NULL ) {
l_keep_going = 0;
break;
} else {
l_keep_going = 1;
}
if ( 6 != sscanf( l_line, "%i %i %i %i %i %i", &l_m, &l_n, &l_k, &l_lda, &l_ldb, &l_ldc ) ) exit(EXIT_FAILURE);
}
l_gemm_def.m = l_m;
l_gemm_def.n = l_n;
l_gemm_def.k = l_k;
l_gemm_def.lda = l_lda;
l_gemm_def.ldb = l_ldb;
l_gemm_def.ldc = l_ldc;
l_gemm_def.alpha = l_alpha;
l_gemm_def.beta = l_beta;
l_gemm_def.trans_a = l_trans_a;
l_gemm_def.trans_b = l_trans_b;
l_gemm_def.aligned_a = l_aligned_a;
l_gemm_def.aligned_c = l_aligned_c;
l_gemm_def.prefetch = l_prefetch;
l_gemm_def.br_type = l_br_type;
l_gemm_def.br_count = l_br;
l_gemm_def.br_unroll = l_br_unroll;
l_gemm_def.tc_config = l_tc_config;
#if defined(_OPENMP)
#pragma omp parallel reduction(+:l_runtime_libxsmm)
#endif
{
unsigned int l_r, l_i, l_j;
libxsmm_bfloat16* l_a_bf = (libxsmm_bfloat16*)libxsmm_aligned_malloc((size_t)l_lda * (size_t)l_k * (size_t)l_br * sizeof(libxsmm_bfloat16), 64);
libxsmm_bfloat16* l_b_bf = (libxsmm_bfloat16*)libxsmm_aligned_malloc((size_t)l_ldb * (size_t)l_n * (size_t)l_br * sizeof(libxsmm_bfloat16), 64);
libxsmm_bfloat16* l_c_bf = (libxsmm_bfloat16*)libxsmm_aligned_malloc((size_t)l_ldc * (size_t)l_n * sizeof(libxsmm_bfloat16), 64);
/* touch A */
for (l_r = 0; l_r < l_br; l_r++) {
for (l_i = 0; l_i < l_lda; l_i++) {
for (l_j = 0; l_j < l_k; l_j++) {
union libxsmm_bfloat16_hp tmp;
tmp.f = (float)libxsmm_rng_f64();
l_a_bf[(l_r * l_lda * l_k) + (l_j * l_lda) + l_i] = tmp.i[1];
}
}
}
/* touch B */
for (l_r = 0; l_r < l_br; l_r++) {
for (l_i = 0; l_i < l_ldb; l_i++) {
for (l_j = 0; l_j < l_n; l_j++) {
union libxsmm_bfloat16_hp tmp;
tmp.f = (float)libxsmm_rng_f64();
l_b_bf[(l_r * l_ldb * l_n) + (l_j * l_ldb) + l_i] = tmp.i[1];
}
}
}
/* touch C */
for (l_i = 0; l_i < l_ldc; l_i++) {
for (l_j = 0; l_j < l_n; l_j++) {
union libxsmm_bfloat16_hp tmp;
tmp.f = 0.0f;
l_c_bf[(l_j * l_ldc) + l_i] = tmp.i[1];
}
}
l_runtime_libxsmm = run_jit_bfloat16( &l_gemm_def, l_a_bf, l_b_bf, l_c_bf, l_file_input );
libxsmm_free(l_a_bf);
libxsmm_free(l_b_bf);
libxsmm_free(l_c_bf);
}
l_runtime_libxsmm /= (double)l_n_threads;
if ( l_file_input == 0 ) {
printf("avg %fs per core for libxsmm\n", l_runtime_libxsmm);
printf("avg %f GFLOPS per core for libxsmm\n", ((double)((double)g_reps * (double)l_m * (double)l_n * (double)l_k * (double)l_br) * 2.0) / (l_runtime_libxsmm * 1.0e9));
} else {
printf("%i %i %i %i %i %i %i %i %i %s %f\n", l_m, l_n, l_k, l_lda, l_ldb, l_ldc, l_br, l_br_type, l_br_unroll, l_precision, ((double)((double)g_reps * (double)l_m * (double)l_n * (double)l_k * (double)l_br) * 2.0) / (l_runtime_libxsmm * 1.0e9) );
}
} while ( l_keep_going );
} else if (strcmp(l_precision, "BF16F32_FLAT") == 0) {
unsigned int l_keep_going = 0;
do {
if ( l_file_input != 0 ) {
char l_line[512];
if ( fgets( l_line, 512, l_file_handle) == NULL ) {
l_keep_going = 0;
break;
} else {
l_keep_going = 1;
}
if ( 6 != sscanf( l_line, "%i %i %i %i %i %i", &l_m, &l_n, &l_k, &l_lda, &l_ldb, &l_ldc ) ) exit(EXIT_FAILURE);
}
l_gemm_def.m = l_m;
l_gemm_def.n = l_n;
l_gemm_def.k = l_k;
l_gemm_def.lda = l_lda;
l_gemm_def.ldb = l_ldb;
l_gemm_def.ldc = l_ldc;
l_gemm_def.alpha = l_alpha;
l_gemm_def.beta = l_beta;
l_gemm_def.trans_a = l_trans_a;
l_gemm_def.trans_b = l_trans_b;
l_gemm_def.aligned_a = l_aligned_a;
l_gemm_def.aligned_c = l_aligned_c;
l_gemm_def.prefetch = l_prefetch;
l_gemm_def.br_type = l_br_type;
l_gemm_def.br_count = l_br;
l_gemm_def.br_unroll = l_br_unroll;
l_gemm_def.tc_config = l_tc_config;
#if defined(_OPENMP)
#pragma omp parallel reduction(+:l_runtime_libxsmm)
#endif
{
unsigned int l_r, l_i, l_j;
libxsmm_bfloat16* l_a_bf = (libxsmm_bfloat16*)libxsmm_aligned_malloc((size_t)l_lda * (size_t)l_k * (size_t)l_br * sizeof(libxsmm_bfloat16), 64);
libxsmm_bfloat16* l_b_bf = (libxsmm_bfloat16*)libxsmm_aligned_malloc((size_t)l_ldb * (size_t)l_n * (size_t)l_br * sizeof(libxsmm_bfloat16), 64);
float* l_c_bf_f = (float*)libxsmm_aligned_malloc((size_t)l_ldc * (size_t)l_n * sizeof(float), 64);
/* touch A */
for (l_r = 0; l_r < l_br; l_r++) {
for (l_i = 0; l_i < l_lda; l_i++) {
for (l_j = 0; l_j < l_k; l_j++) {
union libxsmm_bfloat16_hp tmp;
tmp.f = (float)libxsmm_rng_f64();
l_a_bf[(l_r * l_lda * l_k) + (l_j * l_lda) + l_i] = tmp.i[1];
}
}
}
/* touch B */
for (l_r = 0; l_r < l_br; l_r++) {
for (l_i = 0; l_i < l_ldb; l_i++) {
for (l_j = 0; l_j < l_n; l_j++) {
union libxsmm_bfloat16_hp tmp;
tmp.f = (float)libxsmm_rng_f64();
l_b_bf[(l_r * l_ldb * l_n) + (l_j * l_ldb) + l_i] = tmp.i[1];
}
}
}
/* touch C */
for (l_i = 0; l_i < l_ldc; l_i++) {
for (l_j = 0; l_j < l_n; l_j++) {
l_c_bf_f[(l_j * l_ldc) + l_i] = 0.f;
}
}
l_runtime_libxsmm = run_jit_bfloat16_float_flat( &l_gemm_def, l_a_bf, l_b_bf, l_c_bf_f, l_file_input );
libxsmm_free(l_a_bf);
libxsmm_free(l_b_bf);
libxsmm_free(l_c_bf_f);
}
l_runtime_libxsmm /= (double)l_n_threads;
if ( l_file_input == 0 ) {
printf("avg %fs per core for libxsmm\n", l_runtime_libxsmm);
printf("avg %f GFLOPS per core for libxsmm\n", ((double)((double)g_reps * (double)l_m * (double)l_n * (double)l_k * (double)l_br) * 2.0) / (l_runtime_libxsmm * 1.0e9));
} else {
printf("%i %i %i %i %i %i %i %i %i %s %f\n", l_m, l_n, l_k, l_lda, l_ldb, l_ldc, l_br, l_br_type, l_br_unroll, l_precision, ((double)((double)g_reps * (double)l_m * (double)l_n * (double)l_k * (double)l_br) * 2.0) / (l_runtime_libxsmm * 1.0e9) );
}
} while ( l_keep_going );
} else if (strcmp(l_precision, "BF16_FLAT") == 0) {
unsigned int l_keep_going = 0;
do {
if ( l_file_input != 0 ) {
char l_line[512];
if ( fgets( l_line, 512, l_file_handle) == NULL ) {
l_keep_going = 0;
break;
} else {
l_keep_going = 1;
}
if ( 6 != sscanf( l_line, "%i %i %i %i %i %i", &l_m, &l_n, &l_k, &l_lda, &l_ldb, &l_ldc ) ) exit(EXIT_FAILURE);
}
l_gemm_def.m = l_m;
l_gemm_def.n = l_n;
l_gemm_def.k = l_k;
l_gemm_def.lda = l_lda;
l_gemm_def.ldb = l_ldb;
l_gemm_def.ldc = l_ldc;
l_gemm_def.alpha = l_alpha;
l_gemm_def.beta = l_beta;
l_gemm_def.trans_a = l_trans_a;
l_gemm_def.trans_b = l_trans_b;
l_gemm_def.aligned_a = l_aligned_a;
l_gemm_def.aligned_c = l_aligned_c;
l_gemm_def.prefetch = l_prefetch;
l_gemm_def.br_type = l_br_type;
l_gemm_def.br_count = l_br;
l_gemm_def.br_unroll = l_br_unroll;
l_gemm_def.tc_config = l_tc_config;
#if defined(_OPENMP)
#pragma omp parallel reduction(+:l_runtime_libxsmm)
#endif
{
unsigned int l_r, l_i, l_j;
libxsmm_bfloat16* l_a_bf = (libxsmm_bfloat16*)libxsmm_aligned_malloc((size_t)l_lda * (size_t)l_k * (size_t)l_br * sizeof(libxsmm_bfloat16), 64);
libxsmm_bfloat16* l_b_bf = (libxsmm_bfloat16*)libxsmm_aligned_malloc((size_t)l_ldb * (size_t)l_n * (size_t)l_br * sizeof(libxsmm_bfloat16), 64);
libxsmm_bfloat16* l_c_bf = (libxsmm_bfloat16*)libxsmm_aligned_malloc((size_t)l_ldc * (size_t)l_n * sizeof(libxsmm_bfloat16), 64);
/* touch A */
for (l_r = 0; l_r < l_br; l_r++) {
for (l_i = 0; l_i < l_lda; l_i++) {
for (l_j = 0; l_j < l_k; l_j++) {
union libxsmm_bfloat16_hp tmp;
tmp.f = (float)libxsmm_rng_f64();
l_a_bf[(l_r * l_lda * l_k) + (l_j * l_lda) + l_i] = tmp.i[1];
}
}
}
/* touch B */
for (l_r = 0; l_r < l_br; l_r++) {
for (l_i = 0; l_i < l_ldb; l_i++) {
for (l_j = 0; l_j < l_n; l_j++) {
union libxsmm_bfloat16_hp tmp;
tmp.f = (float)libxsmm_rng_f64();
l_b_bf[(l_r * l_ldb * l_n) + (l_j * l_ldb) + l_i] = tmp.i[1];
}
}
}
/* touch C */
for (l_i = 0; l_i < l_ldc; l_i++) {
for (l_j = 0; l_j < l_n; l_j++) {
union libxsmm_bfloat16_hp tmp;
tmp.f = 0.0f;
l_c_bf[(l_j * l_ldc) + l_i] = tmp.i[1];
}
}
l_runtime_libxsmm = run_jit_bfloat16_flat( &l_gemm_def, l_a_bf, l_b_bf, l_c_bf, l_file_input );
libxsmm_free(l_a_bf);
libxsmm_free(l_b_bf);
libxsmm_free(l_c_bf);
}
l_runtime_libxsmm /= (double)l_n_threads;
if ( l_file_input == 0 ) {
printf("avg %fs per core for libxsmm\n", l_runtime_libxsmm);
printf("avg %f GFLOPS per core for libxsmm\n", ((double)((double)g_reps * (double)l_m * (double)l_n * (double)l_k * (double)l_br) * 2.0) / (l_runtime_libxsmm * 1.0e9));
} else {
printf("%i %i %i %i %i %i %i %i %i %s %f\n", l_m, l_n, l_k, l_lda, l_ldb, l_ldc, l_br, l_br_type, l_br_unroll, l_precision, ((double)((double)g_reps * (double)l_m * (double)l_n * (double)l_k * (double)l_br) * 2.0) / (l_runtime_libxsmm * 1.0e9) );
}
} while ( l_keep_going );
}
if ( l_file_input != 0 ) {
fclose( l_file_handle );
} else {
printf("------------------------------------------------\n");
}
LIBXSMM_UNUSED( l_run_check );
return EXIT_SUCCESS;
}
|
fx.c
|
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% FFFFF X X %
% F X X %
% FFF X %
% F X X %
% F X X %
% %
% %
% MagickCore Image Special Effects Methods %
% %
% Software Design %
% Cristy %
% October 1996 %
% %
% %
% Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/accelerate-private.h"
#include "magick/annotate.h"
#include "magick/artifact.h"
#include "magick/attribute.h"
#include "magick/cache.h"
#include "magick/cache-view.h"
#include "magick/channel.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/decorate.h"
#include "magick/distort.h"
#include "magick/draw.h"
#include "magick/effect.h"
#include "magick/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/fx.h"
#include "magick/fx-private.h"
#include "magick/gem.h"
#include "magick/geometry.h"
#include "magick/layer.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/opencl-private.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/pixel-private.h"
#include "magick/property.h"
#include "magick/quantum.h"
#include "magick/quantum-private.h"
#include "magick/random_.h"
#include "magick/random-private.h"
#include "magick/resample.h"
#include "magick/resample-private.h"
#include "magick/resize.h"
#include "magick/resource_.h"
#include "magick/splay-tree.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/thread-private.h"
#include "magick/threshold.h"
#include "magick/transform.h"
#include "magick/utility.h"
/*
Define declarations.
*/
#define LeftShiftOperator 0xf5U
#define RightShiftOperator 0xf6U
#define LessThanEqualOperator 0xf7U
#define GreaterThanEqualOperator 0xf8U
#define EqualOperator 0xf9U
#define NotEqualOperator 0xfaU
#define LogicalAndOperator 0xfbU
#define LogicalOrOperator 0xfcU
#define ExponentialNotation 0xfdU
struct _FxInfo
{
const Image
*images;
char
*expression;
FILE
*file;
SplayTreeInfo
*colors,
*symbols;
CacheView
**view;
RandomInfo
*random_info;
ExceptionInfo
*exception;
};
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ A c q u i r e F x I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireFxInfo() allocates the FxInfo structure.
%
% The format of the AcquireFxInfo method is:
%
% FxInfo *AcquireFxInfo(Image *image,const char *expression)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o expression: the expression.
%
*/
MagickExport FxInfo *AcquireFxInfo(const Image *image,const char *expression)
{
char
fx_op[2];
const Image
*next;
FxInfo
*fx_info;
register ssize_t
i;
fx_info=(FxInfo *) AcquireMagickMemory(sizeof(*fx_info));
if (fx_info == (FxInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) memset(fx_info,0,sizeof(*fx_info));
fx_info->exception=AcquireExceptionInfo();
fx_info->images=image;
fx_info->colors=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory,
RelinquishAlignedMemory);
fx_info->symbols=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory,
RelinquishMagickMemory);
fx_info->view=(CacheView **) AcquireQuantumMemory(GetImageListLength(
fx_info->images),sizeof(*fx_info->view));
if (fx_info->view == (CacheView **) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
i=0;
next=GetFirstImageInList(fx_info->images);
for ( ; next != (Image *) NULL; next=next->next)
{
fx_info->view[i]=AcquireVirtualCacheView(next,fx_info->exception);
i++;
}
fx_info->random_info=AcquireRandomInfo();
fx_info->expression=ConstantString(expression);
fx_info->file=stderr;
(void) SubstituteString(&fx_info->expression," ",""); /* compact string */
/*
Force right-to-left associativity for unary negation.
*/
(void) SubstituteString(&fx_info->expression,"-","-1.0*");
(void) SubstituteString(&fx_info->expression,"^-1.0*","^-");
(void) SubstituteString(&fx_info->expression,"E-1.0*","E-");
(void) SubstituteString(&fx_info->expression,"e-1.0*","e-");
/*
Convert compound to simple operators.
*/
fx_op[1]='\0';
*fx_op=(char) LeftShiftOperator;
(void) SubstituteString(&fx_info->expression,"<<",fx_op);
*fx_op=(char) RightShiftOperator;
(void) SubstituteString(&fx_info->expression,">>",fx_op);
*fx_op=(char) LessThanEqualOperator;
(void) SubstituteString(&fx_info->expression,"<=",fx_op);
*fx_op=(char) GreaterThanEqualOperator;
(void) SubstituteString(&fx_info->expression,">=",fx_op);
*fx_op=(char) EqualOperator;
(void) SubstituteString(&fx_info->expression,"==",fx_op);
*fx_op=(char) NotEqualOperator;
(void) SubstituteString(&fx_info->expression,"!=",fx_op);
*fx_op=(char) LogicalAndOperator;
(void) SubstituteString(&fx_info->expression,"&&",fx_op);
*fx_op=(char) LogicalOrOperator;
(void) SubstituteString(&fx_info->expression,"||",fx_op);
*fx_op=(char) ExponentialNotation;
(void) SubstituteString(&fx_info->expression,"**",fx_op);
return(fx_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A d d N o i s e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AddNoiseImage() adds random noise to the image.
%
% The format of the AddNoiseImage method is:
%
% Image *AddNoiseImage(const Image *image,const NoiseType noise_type,
% ExceptionInfo *exception)
% Image *AddNoiseImageChannel(const Image *image,const ChannelType channel,
% const NoiseType noise_type,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
% o noise_type: The type of noise: Uniform, Gaussian, Multiplicative,
% Impulse, Laplacian, or Poisson.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *AddNoiseImage(const Image *image,const NoiseType noise_type,
ExceptionInfo *exception)
{
Image
*noise_image;
noise_image=AddNoiseImageChannel(image,DefaultChannels,noise_type,exception);
return(noise_image);
}
MagickExport Image *AddNoiseImageChannel(const Image *image,
const ChannelType channel,const NoiseType noise_type,ExceptionInfo *exception)
{
#define AddNoiseImageTag "AddNoise/Image"
CacheView
*image_view,
*noise_view;
const char
*option;
double
attenuate;
Image
*noise_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RandomInfo
**magick_restrict random_info;
ssize_t
y;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
unsigned long
key;
#endif
/*
Initialize noise image attributes.
*/
assert(image != (const 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 defined(MAGICKCORE_OPENCL_SUPPORT)
noise_image=AccelerateAddNoiseImage(image,channel,noise_type,exception);
if (noise_image != (Image *) NULL)
return(noise_image);
#endif
noise_image=CloneImage(image,0,0,MagickTrue,exception);
if (noise_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(noise_image,DirectClass) == MagickFalse)
{
InheritException(exception,&noise_image->exception);
noise_image=DestroyImage(noise_image);
return((Image *) NULL);
}
/*
Add noise in each row.
*/
attenuate=1.0;
option=GetImageArtifact(image,"attenuate");
if (option != (char *) NULL)
attenuate=StringToDouble(option,(char **) NULL);
status=MagickTrue;
progress=0;
random_info=AcquireRandomInfoThreadSet();
image_view=AcquireVirtualCacheView(image,exception);
noise_view=AcquireAuthenticCacheView(noise_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,noise_image,image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
MagickBooleanType
sync;
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict noise_indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(noise_view,0,y,noise_image->columns,1,
exception);
if ((p == (PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
noise_indexes=GetCacheViewAuthenticIndexQueue(noise_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((channel & RedChannel) != 0)
SetPixelRed(q,ClampToQuantum(GenerateDifferentialNoise(random_info[id],
GetPixelRed(p),noise_type,attenuate)));
if (IsGrayColorspace(image->colorspace) != MagickFalse)
{
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
}
else
{
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,ClampToQuantum(GenerateDifferentialNoise(
random_info[id],GetPixelGreen(p),noise_type,attenuate)));
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,ClampToQuantum(GenerateDifferentialNoise(
random_info[id],GetPixelBlue(p),noise_type,attenuate)));
}
if ((channel & OpacityChannel) != 0)
SetPixelOpacity(q,ClampToQuantum(GenerateDifferentialNoise(
random_info[id],GetPixelOpacity(p),noise_type,attenuate)));
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelIndex(noise_indexes+x,ClampToQuantum(
GenerateDifferentialNoise(random_info[id],GetPixelIndex(
indexes+x),noise_type,attenuate)));
p++;
q++;
}
sync=SyncCacheViewAuthenticPixels(noise_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,AddNoiseImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
noise_view=DestroyCacheView(noise_view);
image_view=DestroyCacheView(image_view);
random_info=DestroyRandomInfoThreadSet(random_info);
if (status == MagickFalse)
noise_image=DestroyImage(noise_image);
return(noise_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% B l u e S h i f t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% BlueShiftImage() mutes the colors of the image to simulate a scene at
% nighttime in the moonlight.
%
% The format of the BlueShiftImage method is:
%
% Image *BlueShiftImage(const Image *image,const double factor,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o factor: the shift factor.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *BlueShiftImage(const Image *image,const double factor,
ExceptionInfo *exception)
{
#define BlueShiftImageTag "BlueShift/Image"
CacheView
*image_view,
*shift_view;
Image
*shift_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Allocate blue shift image.
*/
assert(image != (const 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);
shift_image=CloneImage(image,0,0,MagickTrue,exception);
if (shift_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(shift_image,DirectClass) == MagickFalse)
{
InheritException(exception,&shift_image->exception);
shift_image=DestroyImage(shift_image);
return((Image *) NULL);
}
/*
Blue-shift DirectClass image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
shift_view=AcquireAuthenticCacheView(shift_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,shift_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
MagickPixelPacket
pixel;
Quantum
quantum;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(shift_view,0,y,shift_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
quantum=GetPixelRed(p);
if (GetPixelGreen(p) < quantum)
quantum=GetPixelGreen(p);
if (GetPixelBlue(p) < quantum)
quantum=GetPixelBlue(p);
pixel.red=0.5*(GetPixelRed(p)+factor*quantum);
pixel.green=0.5*(GetPixelGreen(p)+factor*quantum);
pixel.blue=0.5*(GetPixelBlue(p)+factor*quantum);
quantum=GetPixelRed(p);
if (GetPixelGreen(p) > quantum)
quantum=GetPixelGreen(p);
if (GetPixelBlue(p) > quantum)
quantum=GetPixelBlue(p);
pixel.red=0.5*(pixel.red+factor*quantum);
pixel.green=0.5*(pixel.green+factor*quantum);
pixel.blue=0.5*(pixel.blue+factor*quantum);
SetPixelRed(q,ClampToQuantum(pixel.red));
SetPixelGreen(q,ClampToQuantum(pixel.green));
SetPixelBlue(q,ClampToQuantum(pixel.blue));
p++;
q++;
}
sync=SyncCacheViewAuthenticPixels(shift_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,BlueShiftImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
shift_view=DestroyCacheView(shift_view);
if (status == MagickFalse)
shift_image=DestroyImage(shift_image);
return(shift_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C h a r c o a l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CharcoalImage() creates a new image that is a copy of an existing one with
% the edge highlighted. It allocates the memory necessary for the new Image
% structure and returns a pointer to the new image.
%
% The format of the CharcoalImage method is:
%
% Image *CharcoalImage(const Image *image,const double radius,
% const double sigma,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o radius: the radius of the pixel neighborhood.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *CharcoalImage(const Image *image,const double radius,
const double sigma,ExceptionInfo *exception)
{
Image
*charcoal_image,
*edge_image;
MagickBooleanType
status;
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);
edge_image=EdgeImage(image,radius,exception);
if (edge_image == (Image *) NULL)
return((Image *) NULL);
charcoal_image=(Image *) NULL;
status=ClampImage(edge_image);
if (status != MagickFalse)
charcoal_image=BlurImage(edge_image,radius,sigma,exception);
edge_image=DestroyImage(edge_image);
if (charcoal_image == (Image *) NULL)
return((Image *) NULL);
status=NormalizeImage(charcoal_image);
if (status != MagickFalse)
status=NegateImage(charcoal_image,MagickFalse);
if (status != MagickFalse)
status=GrayscaleImage(charcoal_image,image->intensity);
if (status == MagickFalse)
charcoal_image=DestroyImage(charcoal_image);
return(charcoal_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o l o r i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ColorizeImage() blends the fill color with each pixel in the image.
% A percentage blend is specified with opacity. Control the application
% of different color components by specifying a different percentage for
% each component (e.g. 90/100/10 is 90% red, 100% green, and 10% blue).
%
% The format of the ColorizeImage method is:
%
% Image *ColorizeImage(const Image *image,const char *opacity,
% const PixelPacket colorize,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o opacity: A character string indicating the level of opacity as a
% percentage.
%
% o colorize: A color value.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ColorizeImage(const Image *image,const char *opacity,
const PixelPacket colorize,ExceptionInfo *exception)
{
#define ColorizeImageTag "Colorize/Image"
CacheView
*colorize_view,
*image_view;
GeometryInfo
geometry_info;
Image
*colorize_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
pixel;
MagickStatusType
flags;
ssize_t
y;
/*
Allocate colorized image.
*/
assert(image != (const 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);
colorize_image=CloneImage(image,0,0,MagickTrue,exception);
if (colorize_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(colorize_image,DirectClass) == MagickFalse)
{
InheritException(exception,&colorize_image->exception);
colorize_image=DestroyImage(colorize_image);
return((Image *) NULL);
}
if ((IsGrayColorspace(image->colorspace) != MagickFalse) ||
(IsPixelGray(&colorize) != MagickFalse))
(void) SetImageColorspace(colorize_image,sRGBColorspace);
if ((colorize_image->matte == MagickFalse) &&
(colorize.opacity != OpaqueOpacity))
(void) SetImageAlphaChannel(colorize_image,OpaqueAlphaChannel);
if (opacity == (const char *) NULL)
return(colorize_image);
/*
Determine RGB values of the pen color.
*/
flags=ParseGeometry(opacity,&geometry_info);
pixel.red=geometry_info.rho;
pixel.green=geometry_info.rho;
pixel.blue=geometry_info.rho;
pixel.opacity=(MagickRealType) OpaqueOpacity;
if ((flags & SigmaValue) != 0)
pixel.green=geometry_info.sigma;
if ((flags & XiValue) != 0)
pixel.blue=geometry_info.xi;
if ((flags & PsiValue) != 0)
pixel.opacity=geometry_info.psi;
/*
Colorize DirectClass image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
colorize_view=AcquireAuthenticCacheView(colorize_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,colorize_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(colorize_view,0,y,colorize_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,((GetPixelRed(p)*(100.0-pixel.red)+
colorize.red*pixel.red)/100.0));
SetPixelGreen(q,((GetPixelGreen(p)*(100.0-pixel.green)+
colorize.green*pixel.green)/100.0));
SetPixelBlue(q,((GetPixelBlue(p)*(100.0-pixel.blue)+
colorize.blue*pixel.blue)/100.0));
if (colorize_image->matte == MagickFalse)
SetPixelOpacity(q,GetPixelOpacity(p));
else
SetPixelOpacity(q,((GetPixelOpacity(p)*(100.0-pixel.opacity)+
colorize.opacity*pixel.opacity)/100.0));
p++;
q++;
}
sync=SyncCacheViewAuthenticPixels(colorize_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ColorizeImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
colorize_view=DestroyCacheView(colorize_view);
if (status == MagickFalse)
colorize_image=DestroyImage(colorize_image);
return(colorize_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o l o r M a t r i x I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ColorMatrixImage() applies color transformation to an image. This method
% permits saturation changes, hue rotation, luminance to alpha, and various
% other effects. Although variable-sized transformation matrices can be used,
% typically one uses a 5x5 matrix for an RGBA image and a 6x6 for CMYKA
% (or RGBA with offsets). The matrix is similar to those used by Adobe Flash
% except offsets are in column 6 rather than 5 (in support of CMYKA images)
% and offsets are normalized (divide Flash offset by 255).
%
% The format of the ColorMatrixImage method is:
%
% Image *ColorMatrixImage(const Image *image,
% const KernelInfo *color_matrix,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o color_matrix: the color matrix.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ColorMatrixImage(const Image *image,
const KernelInfo *color_matrix,ExceptionInfo *exception)
{
#define ColorMatrixImageTag "ColorMatrix/Image"
CacheView
*color_view,
*image_view;
double
ColorMatrix[6][6] =
{
{ 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 },
{ 0.0, 1.0, 0.0, 0.0, 0.0, 0.0 },
{ 0.0, 0.0, 1.0, 0.0, 0.0, 0.0 },
{ 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 },
{ 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 },
{ 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }
};
Image
*color_image;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
u,
v,
y;
/*
Create color matrix.
*/
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);
i=0;
for (v=0; v < (ssize_t) color_matrix->height; v++)
for (u=0; u < (ssize_t) color_matrix->width; u++)
{
if ((v < 6) && (u < 6))
ColorMatrix[v][u]=color_matrix->values[i];
i++;
}
/*
Initialize color image.
*/
color_image=CloneImage(image,0,0,MagickTrue,exception);
if (color_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(color_image,DirectClass) == MagickFalse)
{
InheritException(exception,&color_image->exception);
color_image=DestroyImage(color_image);
return((Image *) NULL);
}
if (image->debug != MagickFalse)
{
char
format[MaxTextExtent],
*message;
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" ColorMatrix image with color matrix:");
message=AcquireString("");
for (v=0; v < 6; v++)
{
*message='\0';
(void) FormatLocaleString(format,MaxTextExtent,"%.20g: ",(double) v);
(void) ConcatenateString(&message,format);
for (u=0; u < 6; u++)
{
(void) FormatLocaleString(format,MaxTextExtent,"%+f ",
ColorMatrix[v][u]);
(void) ConcatenateString(&message,format);
}
(void) LogMagickEvent(TransformEvent,GetMagickModule(),"%s",message);
}
message=DestroyString(message);
}
/*
ColorMatrix image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
color_view=AcquireAuthenticCacheView(color_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,color_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickRealType
pixel;
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
register IndexPacket
*magick_restrict color_indexes;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(color_view,0,y,color_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
color_indexes=GetCacheViewAuthenticIndexQueue(color_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
v;
size_t
height;
height=color_matrix->height > 6 ? 6UL : color_matrix->height;
for (v=0; v < (ssize_t) height; v++)
{
pixel=ColorMatrix[v][0]*GetPixelRed(p)+ColorMatrix[v][1]*
GetPixelGreen(p)+ColorMatrix[v][2]*GetPixelBlue(p);
if (image->matte != MagickFalse)
pixel+=ColorMatrix[v][3]*(QuantumRange-GetPixelOpacity(p));
if (image->colorspace == CMYKColorspace)
pixel+=ColorMatrix[v][4]*GetPixelIndex(indexes+x);
pixel+=QuantumRange*ColorMatrix[v][5];
switch (v)
{
case 0: SetPixelRed(q,ClampToQuantum(pixel)); break;
case 1: SetPixelGreen(q,ClampToQuantum(pixel)); break;
case 2: SetPixelBlue(q,ClampToQuantum(pixel)); break;
case 3:
{
if (image->matte != MagickFalse)
SetPixelAlpha(q,ClampToQuantum(pixel));
break;
}
case 4:
{
if (image->colorspace == CMYKColorspace)
SetPixelIndex(color_indexes+x,ClampToQuantum(pixel));
break;
}
}
}
p++;
q++;
}
if (SyncCacheViewAuthenticPixels(color_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ColorMatrixImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
color_view=DestroyCacheView(color_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
color_image=DestroyImage(color_image);
return(color_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y F x I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyFxInfo() deallocates memory associated with an FxInfo structure.
%
% The format of the DestroyFxInfo method is:
%
% ImageInfo *DestroyFxInfo(ImageInfo *fx_info)
%
% A description of each parameter follows:
%
% o fx_info: the fx info.
%
*/
MagickExport FxInfo *DestroyFxInfo(FxInfo *fx_info)
{
register ssize_t
i;
fx_info->exception=DestroyExceptionInfo(fx_info->exception);
fx_info->expression=DestroyString(fx_info->expression);
fx_info->symbols=DestroySplayTree(fx_info->symbols);
fx_info->colors=DestroySplayTree(fx_info->colors);
for (i=(ssize_t) GetImageListLength(fx_info->images)-1; i >= 0; i--)
fx_info->view[i]=DestroyCacheView(fx_info->view[i]);
fx_info->view=(CacheView **) RelinquishMagickMemory(fx_info->view);
fx_info->random_info=DestroyRandomInfo(fx_info->random_info);
fx_info=(FxInfo *) RelinquishMagickMemory(fx_info);
return(fx_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ F x E v a l u a t e C h a n n e l E x p r e s s i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FxEvaluateChannelExpression() evaluates an expression and returns the
% results.
%
% The format of the FxEvaluateExpression method is:
%
% MagickBooleanType FxEvaluateChannelExpression(FxInfo *fx_info,
% const ChannelType channel,const ssize_t x,const ssize_t y,
% double *alpha,Exceptioninfo *exception)
% MagickBooleanType FxEvaluateExpression(FxInfo *fx_info,double *alpha,
% Exceptioninfo *exception)
%
% A description of each parameter follows:
%
% o fx_info: the fx info.
%
% o channel: the channel.
%
% o x,y: the pixel position.
%
% o alpha: the result.
%
% o exception: return any errors or warnings in this structure.
%
*/
static double FxChannelStatistics(FxInfo *fx_info,const Image *image,
ChannelType channel,const char *symbol,ExceptionInfo *exception)
{
char
channel_symbol[MaxTextExtent],
key[MaxTextExtent],
statistic[MaxTextExtent];
const char
*value;
register const char
*p;
for (p=symbol; (*p != '.') && (*p != '\0'); p++) ;
*channel_symbol='\0';
if (*p == '.')
{
ssize_t
option;
(void) CopyMagickString(channel_symbol,p+1,MaxTextExtent);
option=ParseCommandOption(MagickChannelOptions,MagickTrue,channel_symbol);
if (option >= 0)
channel=(ChannelType) option;
}
(void) FormatLocaleString(key,MaxTextExtent,"%p.%.20g.%s",(void *) image,
(double) channel,symbol);
value=(const char *) GetValueFromSplayTree(fx_info->symbols,key);
if (value != (const char *) NULL)
return(QuantumScale*StringToDouble(value,(char **) NULL));
(void) DeleteNodeFromSplayTree(fx_info->symbols,key);
if (LocaleNCompare(symbol,"depth",5) == 0)
{
size_t
depth;
depth=GetImageChannelDepth(image,channel,exception);
(void) FormatLocaleString(statistic,MaxTextExtent,"%.20g",(double) depth);
}
if (LocaleNCompare(symbol,"kurtosis",8) == 0)
{
double
kurtosis,
skewness;
(void) GetImageChannelKurtosis(image,channel,&kurtosis,&skewness,
exception);
(void) FormatLocaleString(statistic,MaxTextExtent,"%.20g",kurtosis);
}
if (LocaleNCompare(symbol,"maxima",6) == 0)
{
double
maxima,
minima;
(void) GetImageChannelRange(image,channel,&minima,&maxima,exception);
(void) FormatLocaleString(statistic,MaxTextExtent,"%.20g",maxima);
}
if (LocaleNCompare(symbol,"mean",4) == 0)
{
double
mean,
standard_deviation;
(void) GetImageChannelMean(image,channel,&mean,&standard_deviation,
exception);
(void) FormatLocaleString(statistic,MaxTextExtent,"%.20g",mean);
}
if (LocaleNCompare(symbol,"minima",6) == 0)
{
double
maxima,
minima;
(void) GetImageChannelRange(image,channel,&minima,&maxima,exception);
(void) FormatLocaleString(statistic,MaxTextExtent,"%.20g",minima);
}
if (LocaleNCompare(symbol,"skewness",8) == 0)
{
double
kurtosis,
skewness;
(void) GetImageChannelKurtosis(image,channel,&kurtosis,&skewness,
exception);
(void) FormatLocaleString(statistic,MaxTextExtent,"%.20g",skewness);
}
if (LocaleNCompare(symbol,"standard_deviation",18) == 0)
{
double
mean,
standard_deviation;
(void) GetImageChannelMean(image,channel,&mean,&standard_deviation,
exception);
(void) FormatLocaleString(statistic,MaxTextExtent,"%.20g",
standard_deviation);
}
(void) AddValueToSplayTree(fx_info->symbols,ConstantString(key),
ConstantString(statistic));
return(QuantumScale*StringToDouble(statistic,(char **) NULL));
}
static double
FxEvaluateSubexpression(FxInfo *,const ChannelType,const ssize_t,
const ssize_t,const char *,const size_t,double *,ExceptionInfo *);
static inline MagickBooleanType IsFxFunction(const char *expression,
const char *name,const size_t length)
{
int
c;
c=expression[length];
if ((LocaleNCompare(expression,name,length) == 0) &&
((isspace(c) != 0) || (c == '(')))
return(MagickTrue);
return(MagickFalse);
}
static MagickOffsetType FxGCD(MagickOffsetType alpha,MagickOffsetType beta)
{
if (beta != 0)
return(FxGCD(beta,alpha % beta));
return(alpha);
}
static inline const char *FxSubexpression(const char *expression,
ExceptionInfo *exception)
{
const char
*subexpression;
register ssize_t
level;
level=0;
subexpression=expression;
while ((*subexpression != '\0') &&
((level != 1) || (strchr(")",(int) *subexpression) == (char *) NULL)))
{
if (strchr("(",(int) *subexpression) != (char *) NULL)
level++;
else
if (strchr(")",(int) *subexpression) != (char *) NULL)
level--;
subexpression++;
}
if (*subexpression == '\0')
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UnbalancedParenthesis","`%s'",expression);
return(subexpression);
}
static double FxGetSymbol(FxInfo *fx_info,const ChannelType channel,
const ssize_t x,const ssize_t y,const char *expression,const size_t depth,
ExceptionInfo *exception)
{
char
*q,
symbol[MaxTextExtent];
const char
*p,
*value;
double
alpha,
beta;
Image
*image;
MagickBooleanType
status;
MagickPixelPacket
pixel;
PointInfo
point;
register ssize_t
i;
size_t
level;
p=expression;
i=GetImageIndexInList(fx_info->images);
level=0;
point.x=(double) x;
point.y=(double) y;
if (isalpha((int) ((unsigned char) *(p+1))) == 0)
{
char
*subexpression;
subexpression=AcquireString(expression);
if (strchr("suv",(int) *p) != (char *) NULL)
{
switch (*p)
{
case 's':
default:
{
i=GetImageIndexInList(fx_info->images);
break;
}
case 'u': i=0; break;
case 'v': i=1; break;
}
p++;
if (*p == '[')
{
level++;
q=subexpression;
for (p++; *p != '\0'; )
{
if (*p == '[')
level++;
else
if (*p == ']')
{
level--;
if (level == 0)
break;
}
*q++=(*p++);
}
*q='\0';
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,
depth,&beta,exception);
i=(ssize_t) alpha;
if (*p != '\0')
p++;
}
if (*p == '.')
p++;
}
if ((*p == 'p') && (isalpha((int) ((unsigned char) *(p+1))) == 0))
{
p++;
if (*p == '{')
{
level++;
q=subexpression;
for (p++; *p != '\0'; )
{
if (*p == '{')
level++;
else
if (*p == '}')
{
level--;
if (level == 0)
break;
}
*q++=(*p++);
}
*q='\0';
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,
depth,&beta,exception);
point.x=alpha;
point.y=beta;
if (*p != '\0')
p++;
}
else
if (*p == '[')
{
level++;
q=subexpression;
for (p++; *p != '\0'; )
{
if (*p == '[')
level++;
else
if (*p == ']')
{
level--;
if (level == 0)
break;
}
*q++=(*p++);
}
*q='\0';
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,
depth,&beta,exception);
point.x+=alpha;
point.y+=beta;
if (*p != '\0')
p++;
}
if (*p == '.')
p++;
}
subexpression=DestroyString(subexpression);
}
image=GetImageFromList(fx_info->images,i);
if (image == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"NoSuchImage","`%s'",expression);
return(0.0);
}
i=GetImageIndexInList(image);
GetMagickPixelPacket(image,&pixel);
status=InterpolateMagickPixelPacket(image,fx_info->view[i],image->interpolate,
point.x,point.y,&pixel,exception);
(void) status;
if ((strlen(p) > 2) &&
(LocaleCompare(p,"intensity") != 0) &&
(LocaleCompare(p,"luma") != 0) &&
(LocaleCompare(p,"luminance") != 0) &&
(LocaleCompare(p,"hue") != 0) &&
(LocaleCompare(p,"saturation") != 0) &&
(LocaleCompare(p,"lightness") != 0))
{
char
name[MaxTextExtent];
(void) CopyMagickString(name,p,MaxTextExtent);
for (q=name+(strlen(name)-1); q > name; q--)
{
if (*q == ')')
break;
if (*q == '.')
{
*q='\0';
break;
}
}
if ((strlen(name) > 2) &&
(GetValueFromSplayTree(fx_info->symbols,name) == (const char *) NULL))
{
MagickPixelPacket
*color;
color=(MagickPixelPacket *) GetValueFromSplayTree(fx_info->colors,
name);
if (color != (MagickPixelPacket *) NULL)
{
pixel=(*color);
p+=strlen(name);
}
else
if (QueryMagickColor(name,&pixel,fx_info->exception) != MagickFalse)
{
(void) AddValueToSplayTree(fx_info->colors,ConstantString(name),
CloneMagickPixelPacket(&pixel));
p+=strlen(name);
}
}
}
(void) CopyMagickString(symbol,p,MaxTextExtent);
StripString(symbol);
if (*symbol == '\0')
{
switch (channel)
{
case RedChannel: return(QuantumScale*pixel.red);
case GreenChannel: return(QuantumScale*pixel.green);
case BlueChannel: return(QuantumScale*pixel.blue);
case OpacityChannel:
{
double
alpha;
if (pixel.matte == MagickFalse)
return(1.0);
alpha=(double) (QuantumScale*GetPixelAlpha(&pixel));
return(alpha);
}
case IndexChannel:
{
if (image->colorspace != CMYKColorspace)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ImageError,"ColorSeparatedImageRequired","`%s'",
image->filename);
return(0.0);
}
return(QuantumScale*pixel.index);
}
case DefaultChannels:
return(QuantumScale*GetMagickPixelIntensity(image,&pixel));
default:
break;
}
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UnableToParseExpression","`%s'",p);
return(0.0);
}
switch (*symbol)
{
case 'A':
case 'a':
{
if (LocaleCompare(symbol,"a") == 0)
return((double) (QuantumScale*GetPixelAlpha(&pixel)));
break;
}
case 'B':
case 'b':
{
if (LocaleCompare(symbol,"b") == 0)
return(QuantumScale*pixel.blue);
break;
}
case 'C':
case 'c':
{
if (IsFxFunction(symbol,"channel",7) != MagickFalse)
{
GeometryInfo
channel_info;
MagickStatusType
flags;
flags=ParseGeometry(symbol+7,&channel_info);
if (image->colorspace == CMYKColorspace)
switch (channel)
{
case CyanChannel:
{
if ((flags & RhoValue) == 0)
return(0.0);
return(channel_info.rho);
}
case MagentaChannel:
{
if ((flags & SigmaValue) == 0)
return(0.0);
return(channel_info.sigma);
}
case YellowChannel:
{
if ((flags & XiValue) == 0)
return(0.0);
return(channel_info.xi);
}
case BlackChannel:
{
if ((flags & PsiValue) == 0)
return(0.0);
return(channel_info.psi);
}
case OpacityChannel:
{
if ((flags & ChiValue) == 0)
return(0.0);
return(channel_info.chi);
}
default:
return(0.0);
}
switch (channel)
{
case RedChannel:
{
if ((flags & RhoValue) == 0)
return(0.0);
return(channel_info.rho);
}
case GreenChannel:
{
if ((flags & SigmaValue) == 0)
return(0.0);
return(channel_info.sigma);
}
case BlueChannel:
{
if ((flags & XiValue) == 0)
return(0.0);
return(channel_info.xi);
}
case OpacityChannel:
{
if ((flags & PsiValue) == 0)
return(0.0);
return(channel_info.psi);
}
case IndexChannel:
{
if ((flags & ChiValue) == 0)
return(0.0);
return(channel_info.chi);
}
default:
return(0.0);
}
}
if (LocaleCompare(symbol,"c") == 0)
return(QuantumScale*pixel.red);
break;
}
case 'D':
case 'd':
{
if (LocaleNCompare(symbol,"depth",5) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
break;
}
case 'E':
case 'e':
{
if (LocaleCompare(symbol,"extent") == 0)
{
if (image->extent != 0)
return((double) image->extent);
return((double) GetBlobSize(image));
}
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(symbol,"g") == 0)
return(QuantumScale*pixel.green);
break;
}
case 'K':
case 'k':
{
if (LocaleNCompare(symbol,"kurtosis",8) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
if (LocaleCompare(symbol,"k") == 0)
{
if (image->colorspace != CMYKColorspace)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"ColorSeparatedImageRequired","`%s'",
image->filename);
return(0.0);
}
return(QuantumScale*pixel.index);
}
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(symbol,"h") == 0)
return((double) image->rows);
if (LocaleCompare(symbol,"hue") == 0)
{
double
hue,
lightness,
saturation;
ConvertRGBToHSL(ClampToQuantum(pixel.red),ClampToQuantum(pixel.green),
ClampToQuantum(pixel.blue),&hue,&saturation,&lightness);
return(hue);
}
break;
}
case 'I':
case 'i':
{
if ((LocaleCompare(symbol,"image.depth") == 0) ||
(LocaleCompare(symbol,"image.minima") == 0) ||
(LocaleCompare(symbol,"image.maxima") == 0) ||
(LocaleCompare(symbol,"image.mean") == 0) ||
(LocaleCompare(symbol,"image.kurtosis") == 0) ||
(LocaleCompare(symbol,"image.skewness") == 0) ||
(LocaleCompare(symbol,"image.standard_deviation") == 0))
return(FxChannelStatistics(fx_info,image,channel,symbol+6,exception));
if (LocaleCompare(symbol,"image.resolution.x") == 0)
return(image->x_resolution);
if (LocaleCompare(symbol,"image.resolution.y") == 0)
return(image->y_resolution);
if (LocaleCompare(symbol,"intensity") == 0)
return(QuantumScale*GetMagickPixelIntensity(image,&pixel));
if (LocaleCompare(symbol,"i") == 0)
return((double) x);
break;
}
case 'J':
case 'j':
{
if (LocaleCompare(symbol,"j") == 0)
return((double) y);
break;
}
case 'L':
case 'l':
{
if (LocaleCompare(symbol,"lightness") == 0)
{
double
hue,
lightness,
saturation;
ConvertRGBToHSL(ClampToQuantum(pixel.red),ClampToQuantum(pixel.green),
ClampToQuantum(pixel.blue),&hue,&saturation,&lightness);
return(lightness);
}
if (LocaleCompare(symbol,"luma") == 0)
{
double
luma;
luma=0.212656*pixel.red+0.715158*pixel.green+0.072186*pixel.blue;
return(QuantumScale*luma);
}
if (LocaleCompare(symbol,"luminance") == 0)
{
double
luminance;
luminance=0.212656*pixel.red+0.715158*pixel.green+0.072186*pixel.blue;
return(QuantumScale*luminance);
}
break;
}
case 'M':
case 'm':
{
if (LocaleNCompare(symbol,"maxima",6) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
if (LocaleNCompare(symbol,"mean",4) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
if (LocaleNCompare(symbol,"minima",6) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
if (LocaleCompare(symbol,"m") == 0)
return(QuantumScale*pixel.green);
break;
}
case 'N':
case 'n':
{
if (LocaleCompare(symbol,"n") == 0)
return((double) GetImageListLength(fx_info->images));
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(symbol,"o") == 0)
return(QuantumScale*pixel.opacity);
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(symbol,"page.height") == 0)
return((double) image->page.height);
if (LocaleCompare(symbol,"page.width") == 0)
return((double) image->page.width);
if (LocaleCompare(symbol,"page.x") == 0)
return((double) image->page.x);
if (LocaleCompare(symbol,"page.y") == 0)
return((double) image->page.y);
if (LocaleCompare(symbol,"printsize.x") == 0)
return(PerceptibleReciprocal(image->x_resolution)*image->columns);
if (LocaleCompare(symbol,"printsize.y") == 0)
return(PerceptibleReciprocal(image->y_resolution)*image->rows);
break;
}
case 'Q':
case 'q':
{
if (LocaleCompare(symbol,"quality") == 0)
return((double) image->quality);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(symbol,"resolution.x") == 0)
return(image->x_resolution);
if (LocaleCompare(symbol,"resolution.y") == 0)
return(image->y_resolution);
if (LocaleCompare(symbol,"r") == 0)
return(QuantumScale*pixel.red);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(symbol,"saturation") == 0)
{
double
hue,
lightness,
saturation;
ConvertRGBToHSL(ClampToQuantum(pixel.red),ClampToQuantum(pixel.green),
ClampToQuantum(pixel.blue),&hue,&saturation,&lightness);
return(saturation);
}
if (LocaleNCompare(symbol,"skewness",8) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
if (LocaleNCompare(symbol,"standard_deviation",18) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
break;
}
case 'T':
case 't':
{
if (LocaleCompare(symbol,"t") == 0)
return((double) GetImageIndexInList(fx_info->images));
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(symbol,"w") == 0)
return((double) image->columns);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(symbol,"y") == 0)
return(QuantumScale*pixel.blue);
break;
}
case 'Z':
case 'z':
{
if (LocaleCompare(symbol,"z") == 0)
{
double
depth;
depth=(double) GetImageChannelDepth(image,channel,fx_info->exception);
return(depth);
}
break;
}
default:
break;
}
value=(const char *) GetValueFromSplayTree(fx_info->symbols,symbol);
if (value != (const char *) NULL)
return(StringToDouble(value,(char **) NULL));
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UnableToParseExpression","`%s'",symbol);
return(0.0);
}
static const char *FxOperatorPrecedence(const char *expression,
ExceptionInfo *exception)
{
typedef enum
{
UndefinedPrecedence,
NullPrecedence,
BitwiseComplementPrecedence,
ExponentPrecedence,
ExponentialNotationPrecedence,
MultiplyPrecedence,
AdditionPrecedence,
ShiftPrecedence,
RelationalPrecedence,
EquivalencyPrecedence,
BitwiseAndPrecedence,
BitwiseOrPrecedence,
LogicalAndPrecedence,
LogicalOrPrecedence,
TernaryPrecedence,
AssignmentPrecedence,
CommaPrecedence,
SeparatorPrecedence
} FxPrecedence;
FxPrecedence
precedence,
target;
register const char
*subexpression;
register int
c;
size_t
level;
c=(-1);
level=0;
subexpression=(const char *) NULL;
target=NullPrecedence;
while ((c != '\0') && (*expression != '\0'))
{
precedence=UndefinedPrecedence;
if ((isspace((int) ((unsigned char) *expression)) != 0) || (c == (int) '@'))
{
expression++;
continue;
}
switch (*expression)
{
case 'A':
case 'a':
{
#if defined(MAGICKCORE_HAVE_ACOSH)
if (IsFxFunction(expression,"acosh",5) != MagickFalse)
{
expression+=5;
break;
}
#endif
#if defined(MAGICKCORE_HAVE_ASINH)
if (IsFxFunction(expression,"asinh",5) != MagickFalse)
{
expression+=5;
break;
}
#endif
#if defined(MAGICKCORE_HAVE_ATANH)
if (IsFxFunction(expression,"atanh",5) != MagickFalse)
{
expression+=5;
break;
}
#endif
if (IsFxFunction(expression,"atan2",5) != MagickFalse)
{
expression+=5;
break;
}
break;
}
case 'E':
case 'e':
{
if ((isdigit(c) != 0) &&
((LocaleNCompare(expression,"E+",2) == 0) ||
(LocaleNCompare(expression,"E-",2) == 0)))
{
expression+=2; /* scientific notation */
break;
}
}
case 'J':
case 'j':
{
if ((IsFxFunction(expression,"j0",2) != MagickFalse) ||
(IsFxFunction(expression,"j1",2) != MagickFalse))
{
expression+=2;
break;
}
break;
}
case '#':
{
while (isxdigit((int) ((unsigned char) *(expression+1))) != 0)
expression++;
break;
}
default:
break;
}
if ((c == (int) '{') || (c == (int) '['))
level++;
else
if ((c == (int) '}') || (c == (int) ']'))
level--;
if (level == 0)
switch ((unsigned char) *expression)
{
case '~':
case '!':
{
precedence=BitwiseComplementPrecedence;
break;
}
case '^':
case '@':
{
precedence=ExponentPrecedence;
break;
}
default:
{
if (((c != 0) && ((isdigit(c) != 0) ||
(strchr(")",c) != (char *) NULL))) &&
(((islower((int) ((unsigned char) *expression)) != 0) ||
(strchr("(",(int) ((unsigned char) *expression)) != (char *) NULL)) ||
((isdigit(c) == 0) &&
(isdigit((int) ((unsigned char) *expression)) != 0))) &&
(strchr("xy",(int) ((unsigned char) *expression)) == (char *) NULL))
precedence=MultiplyPrecedence;
break;
}
case '*':
case '/':
case '%':
{
precedence=MultiplyPrecedence;
break;
}
case '+':
case '-':
{
if ((strchr("(+-/*%:&^|<>~,",c) == (char *) NULL) ||
(isalpha(c) != 0))
precedence=AdditionPrecedence;
break;
}
case LeftShiftOperator:
case RightShiftOperator:
{
precedence=ShiftPrecedence;
break;
}
case '<':
case LessThanEqualOperator:
case GreaterThanEqualOperator:
case '>':
{
precedence=RelationalPrecedence;
break;
}
case EqualOperator:
case NotEqualOperator:
{
precedence=EquivalencyPrecedence;
break;
}
case '&':
{
precedence=BitwiseAndPrecedence;
break;
}
case '|':
{
precedence=BitwiseOrPrecedence;
break;
}
case LogicalAndOperator:
{
precedence=LogicalAndPrecedence;
break;
}
case LogicalOrOperator:
{
precedence=LogicalOrPrecedence;
break;
}
case ExponentialNotation:
{
precedence=ExponentialNotationPrecedence;
break;
}
case ':':
case '?':
{
precedence=TernaryPrecedence;
break;
}
case '=':
{
precedence=AssignmentPrecedence;
break;
}
case ',':
{
precedence=CommaPrecedence;
break;
}
case ';':
{
precedence=SeparatorPrecedence;
break;
}
}
if ((precedence == BitwiseComplementPrecedence) ||
(precedence == TernaryPrecedence) ||
(precedence == AssignmentPrecedence))
{
if (precedence > target)
{
/*
Right-to-left associativity.
*/
target=precedence;
subexpression=expression;
}
}
else
if (precedence >= target)
{
/*
Left-to-right associativity.
*/
target=precedence;
subexpression=expression;
}
if (strchr("(",(int) *expression) != (char *) NULL)
expression=FxSubexpression(expression,exception);
c=(int) (*expression++);
}
return(subexpression);
}
static double FxEvaluateSubexpression(FxInfo *fx_info,const ChannelType channel,
const ssize_t x,const ssize_t y,const char *expression,const size_t depth,
double *beta,ExceptionInfo *exception)
{
#define FxMaxParenthesisDepth 58
#define FxMaxSubexpressionDepth 200
#define FxReturn(value) \
{ \
subexpression=DestroyString(subexpression); \
return(value); \
}
char
*q,
*subexpression;
double
alpha,
gamma;
register const char
*p;
*beta=0.0;
subexpression=AcquireString(expression);
*subexpression='\0';
if (depth > FxMaxSubexpressionDepth)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UnableToParseExpression","`%s'",expression);
FxReturn(0.0);
}
if (exception->severity >= ErrorException)
FxReturn(0.0);
while (isspace((int) ((unsigned char) *expression)) != 0)
expression++;
if (*expression == '\0')
FxReturn(0.0);
p=FxOperatorPrecedence(expression,exception);
if (p != (const char *) NULL)
{
(void) CopyMagickString(subexpression,expression,(size_t)
(p-expression+1));
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,depth+1,
beta,exception);
switch ((unsigned char) *p)
{
case '~':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
*beta=(double) (~(size_t) *beta);
FxReturn(*beta);
}
case '!':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(*beta == 0.0 ? 1.0 : 0.0);
}
case '^':
{
*beta=pow(alpha,FxEvaluateSubexpression(fx_info,channel,x,y,++p,
depth+1,beta,exception));
FxReturn(*beta);
}
case '*':
case ExponentialNotation:
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha*(*beta));
}
case '/':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(PerceptibleReciprocal(*beta)*alpha);
}
case '%':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
*beta=fabs(floor((*beta)+0.5));
FxReturn(fmod(alpha,(double) *beta));
}
case '+':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha+(*beta));
}
case '-':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha-(*beta));
}
case LeftShiftOperator:
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
if ((size_t) (gamma+0.5) > (8*sizeof(size_t)))
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"ShiftCountOverflow","`%s'",subexpression);
FxReturn(0.0);
}
*beta=(double) ((size_t) (alpha+0.5) << (size_t) (gamma+0.5));
FxReturn(*beta);
}
case RightShiftOperator:
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
if ((size_t) (gamma+0.5) > (8*sizeof(size_t)))
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"ShiftCountOverflow","`%s'",subexpression);
FxReturn(0.0);
}
*beta=(double) ((size_t) (alpha+0.5) >> (size_t) (gamma+0.5));
FxReturn(*beta);
}
case '<':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha < *beta ? 1.0 : 0.0);
}
case LessThanEqualOperator:
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha <= *beta ? 1.0 : 0.0);
}
case '>':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha > *beta ? 1.0 : 0.0);
}
case GreaterThanEqualOperator:
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha >= *beta ? 1.0 : 0.0);
}
case EqualOperator:
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(fabs(alpha-(*beta)) < MagickEpsilon ? 1.0 : 0.0);
}
case NotEqualOperator:
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(fabs(alpha-(*beta)) >= MagickEpsilon ? 1.0 : 0.0);
}
case '&':
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
*beta=(double) ((size_t) (alpha+0.5) & (size_t) (gamma+0.5));
FxReturn(*beta);
}
case '|':
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
*beta=(double) ((size_t) (alpha+0.5) | (size_t) (gamma+0.5));
FxReturn(*beta);
}
case LogicalAndOperator:
{
p++;
if (alpha <= 0.0)
{
*beta=0.0;
FxReturn(*beta);
}
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,beta,
exception);
*beta=(gamma > 0.0) ? 1.0 : 0.0;
FxReturn(*beta);
}
case LogicalOrOperator:
{
p++;
if (alpha > 0.0)
{
*beta=1.0;
FxReturn(*beta);
}
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,beta,
exception);
*beta=(gamma > 0.0) ? 1.0 : 0.0;
FxReturn(*beta);
}
case '?':
{
double
gamma;
(void) CopyMagickString(subexpression,++p,MaxTextExtent);
q=subexpression;
p=StringToken(":",&q);
if (q == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"UnableToParseExpression","`%s'",subexpression);
FxReturn(0.0);
}
if (fabs(alpha) >= MagickEpsilon)
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,beta,
exception);
else
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,q,depth+1,beta,
exception);
FxReturn(gamma);
}
case '=':
{
char
numeric[MaxTextExtent];
q=subexpression;
while (isalpha((int) ((unsigned char) *q)) != 0)
q++;
if (*q != '\0')
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"UnableToParseExpression","`%s'",subexpression);
FxReturn(0.0);
}
ClearMagickException(exception);
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
(void) FormatLocaleString(numeric,MaxTextExtent,"%.20g",(double)
*beta);
(void) DeleteNodeFromSplayTree(fx_info->symbols,subexpression);
(void) AddValueToSplayTree(fx_info->symbols,ConstantString(
subexpression),ConstantString(numeric));
FxReturn(*beta);
}
case ',':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha);
}
case ';':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(*beta);
}
default:
{
gamma=alpha*FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,
beta,exception);
FxReturn(gamma);
}
}
}
if (strchr("(",(int) *expression) != (char *) NULL)
{
if (depth >= FxMaxParenthesisDepth)
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"ParenthesisNestedTooDeeply","`%s'",expression);
(void) CopyMagickString(subexpression,expression+1,MaxTextExtent);
if (strlen(subexpression) != 0)
subexpression[strlen(subexpression)-1]='\0';
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,depth+1,
beta,exception);
FxReturn(gamma);
}
switch (*expression)
{
case '+':
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,expression+1,depth+1,
beta,exception);
FxReturn(1.0*gamma);
}
case '-':
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,expression+1,depth+1,
beta,exception);
FxReturn(-1.0*gamma);
}
case '~':
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,expression+1,depth+1,
beta,exception);
FxReturn((double) (~(size_t) (gamma+0.5)));
}
case 'A':
case 'a':
{
if (IsFxFunction(expression,"abs",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(fabs(alpha));
}
#if defined(MAGICKCORE_HAVE_ACOSH)
if (IsFxFunction(expression,"acosh",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(acosh(alpha));
}
#endif
if (IsFxFunction(expression,"acos",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(acos(alpha));
}
#if defined(MAGICKCORE_HAVE_J1)
if (IsFxFunction(expression,"airy",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
if (alpha == 0.0)
FxReturn(1.0);
gamma=2.0*j1((MagickPI*alpha))/(MagickPI*alpha);
FxReturn(gamma*gamma);
}
#endif
#if defined(MAGICKCORE_HAVE_ASINH)
if (IsFxFunction(expression,"asinh",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(asinh(alpha));
}
#endif
if (IsFxFunction(expression,"asin",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(asin(alpha));
}
if (IsFxFunction(expression,"alt",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(((ssize_t) alpha) & 0x01 ? -1.0 : 1.0);
}
if (IsFxFunction(expression,"atan2",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(atan2(alpha,*beta));
}
#if defined(MAGICKCORE_HAVE_ATANH)
if (IsFxFunction(expression,"atanh",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(atanh(alpha));
}
#endif
if (IsFxFunction(expression,"atan",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(atan(alpha));
}
if (LocaleCompare(expression,"a") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'B':
case 'b':
{
if (LocaleCompare(expression,"b") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'C':
case 'c':
{
if (IsFxFunction(expression,"ceil",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(ceil(alpha));
}
if (IsFxFunction(expression,"clamp",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
if (alpha < 0.0)
FxReturn(0.0);
if (alpha > 1.0)
FxReturn(1.0);
FxReturn(alpha);
}
if (IsFxFunction(expression,"cosh",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(cosh(alpha));
}
if (IsFxFunction(expression,"cos",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(cos(alpha));
}
if (LocaleCompare(expression,"c") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'D':
case 'd':
{
if (IsFxFunction(expression,"debug",5) != MagickFalse)
{
const char
*type;
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
if (fx_info->images->colorspace == CMYKColorspace)
switch (channel)
{
case CyanChannel: type="cyan"; break;
case MagentaChannel: type="magenta"; break;
case YellowChannel: type="yellow"; break;
case OpacityChannel: type="opacity"; break;
case BlackChannel: type="black"; break;
default: type="unknown"; break;
}
else
switch (channel)
{
case RedChannel: type="red"; break;
case GreenChannel: type="green"; break;
case BlueChannel: type="blue"; break;
case OpacityChannel: type="opacity"; break;
default: type="unknown"; break;
}
*subexpression='\0';
if (strlen(subexpression) > 1)
(void) CopyMagickString(subexpression,expression+6,MaxTextExtent);
if (strlen(subexpression) > 1)
subexpression[strlen(subexpression)-1]='\0';
if (fx_info->file != (FILE *) NULL)
(void) FormatLocaleFile(fx_info->file,
"%s[%.20g,%.20g].%s: %s=%.*g\n",fx_info->images->filename,
(double) x,(double) y,type,subexpression,GetMagickPrecision(),
(double) alpha);
FxReturn(0.0);
}
if (IsFxFunction(expression,"drc",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn((alpha/(*beta*(alpha-1.0)+1.0)));
}
break;
}
case 'E':
case 'e':
{
if (LocaleCompare(expression,"epsilon") == 0)
FxReturn(MagickEpsilon);
#if defined(MAGICKCORE_HAVE_ERF)
if (LocaleNCompare(expression,"erp",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(erf(alpha));
}
#endif
if (IsFxFunction(expression,"exp",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(exp(alpha));
}
if (LocaleCompare(expression,"e") != MagickFalse)
FxReturn(2.7182818284590452354);
break;
}
case 'F':
case 'f':
{
if (IsFxFunction(expression,"floor",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(floor(alpha));
}
break;
}
case 'G':
case 'g':
{
if (IsFxFunction(expression,"gauss",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
gamma=exp((-alpha*alpha/2.0))/sqrt(2.0*MagickPI);
FxReturn(gamma);
}
if (IsFxFunction(expression,"gcd",3) != MagickFalse)
{
MagickOffsetType
gcd;
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
gcd=FxGCD((MagickOffsetType) (alpha+0.5),(MagickOffsetType)
(*beta+0.5));
FxReturn((double) gcd);
}
if (LocaleCompare(expression,"g") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(expression,"h") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
if (LocaleCompare(expression,"hue") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
if (IsFxFunction(expression,"hypot",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(hypot(alpha,*beta));
}
break;
}
case 'K':
case 'k':
{
if (LocaleCompare(expression,"k") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'I':
case 'i':
{
if (LocaleCompare(expression,"intensity") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
if (IsFxFunction(expression,"int",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(floor(alpha));
}
if (IsFxFunction(expression,"isnan",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn((double) !!IsNaN(alpha));
}
if (LocaleCompare(expression,"i") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'J':
case 'j':
{
if (LocaleCompare(expression,"j") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
#if defined(MAGICKCORE_HAVE_J0)
if (IsFxFunction(expression,"j0",2) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2,
depth+1,beta,exception);
FxReturn(j0(alpha));
}
#endif
#if defined(MAGICKCORE_HAVE_J1)
if (IsFxFunction(expression,"j1",2) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2,
depth+1,beta,exception);
FxReturn(j1(alpha));
}
#endif
#if defined(MAGICKCORE_HAVE_J1)
if (IsFxFunction(expression,"jinc",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
if (alpha == 0.0)
FxReturn(1.0);
gamma=(2.0*j1((MagickPI*alpha))/(MagickPI*alpha));
FxReturn(gamma);
}
#endif
break;
}
case 'L':
case 'l':
{
if (IsFxFunction(expression,"ln",2) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2,
depth+1,beta,exception);
FxReturn(log(alpha));
}
if (IsFxFunction(expression,"logtwo",6) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+6,
depth+1,beta,exception);
FxReturn(log10(alpha)/log10(2.0));
}
if (IsFxFunction(expression,"log",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(log10(alpha));
}
if (LocaleCompare(expression,"lightness") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'M':
case 'm':
{
if (LocaleCompare(expression,"MaxRGB") == 0)
FxReturn((double) QuantumRange);
if (LocaleNCompare(expression,"maxima",6) == 0)
break;
if (IsFxFunction(expression,"max",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(alpha > *beta ? alpha : *beta);
}
if (LocaleNCompare(expression,"minima",6) == 0)
break;
if (IsFxFunction(expression,"min",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(alpha < *beta ? alpha : *beta);
}
if (IsFxFunction(expression,"mod",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
gamma=alpha-floor((alpha*PerceptibleReciprocal(*beta)))*(*beta);
FxReturn(gamma);
}
if (LocaleCompare(expression,"m") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'N':
case 'n':
{
if (IsFxFunction(expression,"not",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn((double) (alpha < MagickEpsilon));
}
if (LocaleCompare(expression,"n") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(expression,"Opaque") == 0)
FxReturn(1.0);
if (LocaleCompare(expression,"o") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(expression,"phi") == 0)
FxReturn(MagickPHI);
if (LocaleCompare(expression,"pi") == 0)
FxReturn(MagickPI);
if (IsFxFunction(expression,"pow",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(pow(alpha,*beta));
}
if (LocaleCompare(expression,"p") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'Q':
case 'q':
{
if (LocaleCompare(expression,"QuantumRange") == 0)
FxReturn((double) QuantumRange);
if (LocaleCompare(expression,"QuantumScale") == 0)
FxReturn(QuantumScale);
break;
}
case 'R':
case 'r':
{
if (IsFxFunction(expression,"rand",4) != MagickFalse)
{
double
alpha;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_FxEvaluateSubexpression)
#endif
alpha=GetPseudoRandomValue(fx_info->random_info);
FxReturn(alpha);
}
if (IsFxFunction(expression,"round",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(floor(alpha+0.5));
}
if (LocaleCompare(expression,"r") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'S':
case 's':
{
if (LocaleCompare(expression,"saturation") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
if (IsFxFunction(expression,"sign",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(alpha < 0.0 ? -1.0 : 1.0);
}
if (IsFxFunction(expression,"sinc",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
if (alpha == 0)
FxReturn(1.0);
gamma=(sin((MagickPI*alpha))/(MagickPI*alpha));
FxReturn(gamma);
}
if (IsFxFunction(expression,"sinh",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(sinh(alpha));
}
if (IsFxFunction(expression,"sin",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(sin(alpha));
}
if (IsFxFunction(expression,"sqrt",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(sqrt(alpha));
}
if (IsFxFunction(expression,"squish",6) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+6,
depth+1,beta,exception);
FxReturn((1.0/(1.0+exp(-alpha))));
}
if (LocaleCompare(expression,"s") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'T':
case 't':
{
if (IsFxFunction(expression,"tanh",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(tanh(alpha));
}
if (IsFxFunction(expression,"tan",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(tan(alpha));
}
if (LocaleCompare(expression,"Transparent") == 0)
FxReturn(0.0);
if (IsFxFunction(expression,"trunc",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
if (alpha >= 0.0)
FxReturn(floor(alpha));
FxReturn(ceil(alpha));
}
if (LocaleCompare(expression,"t") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'U':
case 'u':
{
if (LocaleCompare(expression,"u") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'V':
case 'v':
{
if (LocaleCompare(expression,"v") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'W':
case 'w':
{
if (LocaleNCompare(expression,"while(",6) == 0)
{
do
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
} while (fabs(alpha) >= MagickEpsilon);
FxReturn(*beta);
}
if (LocaleCompare(expression,"w") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(expression,"y") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'Z':
case 'z':
{
if (LocaleCompare(expression,"z") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
default:
break;
}
q=(char *) expression;
alpha=InterpretSiPrefixValue(expression,&q);
if (q == expression)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
FxReturn(alpha);
}
MagickExport MagickBooleanType FxEvaluateExpression(FxInfo *fx_info,
double *alpha,ExceptionInfo *exception)
{
MagickBooleanType
status;
status=FxEvaluateChannelExpression(fx_info,GrayChannel,0,0,alpha,exception);
return(status);
}
MagickExport MagickBooleanType FxPreprocessExpression(FxInfo *fx_info,
double *alpha,ExceptionInfo *exception)
{
FILE
*file;
MagickBooleanType
status;
file=fx_info->file;
fx_info->file=(FILE *) NULL;
status=FxEvaluateChannelExpression(fx_info,GrayChannel,0,0,alpha,exception);
fx_info->file=file;
return(status);
}
MagickExport MagickBooleanType FxEvaluateChannelExpression(FxInfo *fx_info,
const ChannelType channel,const ssize_t x,const ssize_t y,double *alpha,
ExceptionInfo *exception)
{
double
beta;
beta=0.0;
*alpha=FxEvaluateSubexpression(fx_info,channel,x,y,fx_info->expression,0,
&beta,exception);
return(exception->severity == OptionError ? MagickFalse : MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F x I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FxImage() applies a mathematical expression to the specified image.
%
% The format of the FxImage method is:
%
% Image *FxImage(const Image *image,const char *expression,
% ExceptionInfo *exception)
% Image *FxImageChannel(const Image *image,const ChannelType channel,
% const char *expression,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% o expression: A mathematical expression.
%
% o exception: return any errors or warnings in this structure.
%
*/
static FxInfo **DestroyFxThreadSet(FxInfo **fx_info)
{
register ssize_t
i;
assert(fx_info != (FxInfo **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (fx_info[i] != (FxInfo *) NULL)
fx_info[i]=DestroyFxInfo(fx_info[i]);
fx_info=(FxInfo **) RelinquishMagickMemory(fx_info);
return(fx_info);
}
static FxInfo **AcquireFxThreadSet(const Image *image,const char *expression,
ExceptionInfo *exception)
{
char
*fx_expression;
double
alpha;
FxInfo
**fx_info;
register ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
fx_info=(FxInfo **) AcquireQuantumMemory(number_threads,sizeof(*fx_info));
if (fx_info == (FxInfo **) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return((FxInfo **) NULL);
}
(void) memset(fx_info,0,number_threads*sizeof(*fx_info));
if (*expression != '@')
fx_expression=ConstantString(expression);
else
fx_expression=FileToString(expression+1,~0UL,exception);
for (i=0; i < (ssize_t) number_threads; i++)
{
MagickBooleanType
status;
fx_info[i]=AcquireFxInfo(image,fx_expression);
if (fx_info[i] == (FxInfo *) NULL)
break;
status=FxPreprocessExpression(fx_info[i],&alpha,exception);
if (status == MagickFalse)
break;
}
fx_expression=DestroyString(fx_expression);
if (i < (ssize_t) number_threads)
fx_info=DestroyFxThreadSet(fx_info);
return(fx_info);
}
MagickExport Image *FxImage(const Image *image,const char *expression,
ExceptionInfo *exception)
{
Image
*fx_image;
fx_image=FxImageChannel(image,GrayChannel,expression,exception);
return(fx_image);
}
MagickExport Image *FxImageChannel(const Image *image,const ChannelType channel,
const char *expression,ExceptionInfo *exception)
{
#define FxImageTag "Fx/Image"
CacheView
*fx_view;
FxInfo
**magick_restrict fx_info;
Image
*fx_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (expression == (const char *) NULL)
return(CloneImage(image,0,0,MagickTrue,exception));
fx_info=AcquireFxThreadSet(image,expression,exception);
if (fx_info == (FxInfo **) NULL)
return((Image *) NULL);
fx_image=CloneImage(image,0,0,MagickTrue,exception);
if (fx_image == (Image *) NULL)
{
fx_info=DestroyFxThreadSet(fx_info);
return((Image *) NULL);
}
if (SetImageStorageClass(fx_image,DirectClass) == MagickFalse)
{
InheritException(exception,&fx_image->exception);
fx_info=DestroyFxThreadSet(fx_info);
fx_image=DestroyImage(fx_image);
return((Image *) NULL);
}
/*
Fx image.
*/
status=MagickTrue;
progress=0;
fx_view=AcquireAuthenticCacheView(fx_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,fx_image,fx_image->rows,1)
#endif
for (y=0; y < (ssize_t) fx_image->rows; y++)
{
const int
id = GetOpenMPThreadId();
double
alpha;
register IndexPacket
*magick_restrict fx_indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(fx_view,0,y,fx_image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
fx_indexes=GetCacheViewAuthenticIndexQueue(fx_view);
alpha=0.0;
for (x=0; x < (ssize_t) fx_image->columns; x++)
{
if ((channel & RedChannel) != 0)
{
(void) FxEvaluateChannelExpression(fx_info[id],RedChannel,x,y,
&alpha,exception);
SetPixelRed(q,ClampToQuantum((MagickRealType) QuantumRange*alpha));
}
if ((channel & GreenChannel) != 0)
{
(void) FxEvaluateChannelExpression(fx_info[id],GreenChannel,x,y,
&alpha,exception);
SetPixelGreen(q,ClampToQuantum((MagickRealType) QuantumRange*alpha));
}
if ((channel & BlueChannel) != 0)
{
(void) FxEvaluateChannelExpression(fx_info[id],BlueChannel,x,y,
&alpha,exception);
SetPixelBlue(q,ClampToQuantum((MagickRealType) QuantumRange*alpha));
}
if ((channel & OpacityChannel) != 0)
{
(void) FxEvaluateChannelExpression(fx_info[id],OpacityChannel,x,y,
&alpha,exception);
if (image->matte == MagickFalse)
SetPixelOpacity(q,ClampToQuantum((MagickRealType) QuantumRange*
alpha));
else
SetPixelOpacity(q,ClampToQuantum((MagickRealType) (QuantumRange-
QuantumRange*alpha)));
}
if (((channel & IndexChannel) != 0) &&
(fx_image->colorspace == CMYKColorspace))
{
(void) FxEvaluateChannelExpression(fx_info[id],IndexChannel,x,y,
&alpha,exception);
SetPixelIndex(fx_indexes+x,ClampToQuantum((MagickRealType)
QuantumRange*alpha));
}
q++;
}
if (SyncCacheViewAuthenticPixels(fx_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,FxImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
fx_view=DestroyCacheView(fx_view);
fx_info=DestroyFxThreadSet(fx_info);
if (status == MagickFalse)
fx_image=DestroyImage(fx_image);
return(fx_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I m p l o d e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ImplodeImage() creates a new image that is a copy of an existing
% one with the image pixels "implode" by the specified percentage. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ImplodeImage method is:
%
% Image *ImplodeImage(const Image *image,const double amount,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o implode_image: Method ImplodeImage returns a pointer to the image
% after it is implode. A null image is returned if there is a memory
% shortage.
%
% o image: the image.
%
% o amount: Define the extent of the implosion.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ImplodeImage(const Image *image,const double amount,
ExceptionInfo *exception)
{
#define ImplodeImageTag "Implode/Image"
CacheView
*image_view,
*implode_view;
double
radius;
Image
*implode_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
zero;
PointInfo
center,
scale;
ssize_t
y;
/*
Initialize implode image attributes.
*/
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);
implode_image=CloneImage(image,0,0,MagickTrue,exception);
if (implode_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(implode_image,DirectClass) == MagickFalse)
{
InheritException(exception,&implode_image->exception);
implode_image=DestroyImage(implode_image);
return((Image *) NULL);
}
if (implode_image->background_color.opacity != OpaqueOpacity)
implode_image->matte=MagickTrue;
/*
Compute scaling factor.
*/
scale.x=1.0;
scale.y=1.0;
center.x=0.5*image->columns;
center.y=0.5*image->rows;
radius=center.x;
if (image->columns > image->rows)
scale.y=(double) image->columns/(double) image->rows;
else
if (image->columns < image->rows)
{
scale.x=(double) image->rows/(double) image->columns;
radius=center.y;
}
/*
Implode image.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(implode_image,&zero);
image_view=AcquireVirtualCacheView(image,exception);
implode_view=AcquireAuthenticCacheView(implode_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,implode_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
double
distance;
MagickPixelPacket
pixel;
PointInfo
delta;
register IndexPacket
*magick_restrict implode_indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(implode_view,0,y,implode_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
implode_indexes=GetCacheViewAuthenticIndexQueue(implode_view);
delta.y=scale.y*(double) (y-center.y);
pixel=zero;
for (x=0; x < (ssize_t) image->columns; x++)
{
/*
Determine if the pixel is within an ellipse.
*/
delta.x=scale.x*(double) (x-center.x);
distance=delta.x*delta.x+delta.y*delta.y;
if (distance < (radius*radius))
{
double
factor;
/*
Implode the pixel.
*/
factor=1.0;
if (distance > 0.0)
factor=pow(sin((double) (MagickPI*sqrt((double) distance)/
radius/2)),-amount);
status=InterpolateMagickPixelPacket(image,image_view,
UndefinedInterpolatePixel,(double) (factor*delta.x/scale.x+
center.x),(double) (factor*delta.y/scale.y+center.y),&pixel,
exception);
if (status == MagickFalse)
break;
SetPixelPacket(implode_image,&pixel,q,implode_indexes+x);
}
q++;
}
if (SyncCacheViewAuthenticPixels(implode_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ImplodeImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
implode_view=DestroyCacheView(implode_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
implode_image=DestroyImage(implode_image);
return(implode_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M o r p h I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% The MorphImages() method requires a minimum of two images. The first
% image is transformed into the second by a number of intervening images
% as specified by frames.
%
% The format of the MorphImage method is:
%
% Image *MorphImages(const Image *image,const size_t number_frames,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o number_frames: Define the number of in-between image to generate.
% The more in-between frames, the smoother the morph.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *MorphImages(const Image *image,
const size_t number_frames,ExceptionInfo *exception)
{
#define MorphImageTag "Morph/Image"
double
alpha,
beta;
Image
*morph_image,
*morph_images;
MagickBooleanType
status;
MagickOffsetType
scene;
register const Image
*next;
register ssize_t
i;
ssize_t
y;
/*
Clone first frame in sequence.
*/
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);
morph_images=CloneImage(image,0,0,MagickTrue,exception);
if (morph_images == (Image *) NULL)
return((Image *) NULL);
if (GetNextImageInList(image) == (Image *) NULL)
{
/*
Morph single image.
*/
for (i=1; i < (ssize_t) number_frames; i++)
{
morph_image=CloneImage(image,0,0,MagickTrue,exception);
if (morph_image == (Image *) NULL)
{
morph_images=DestroyImageList(morph_images);
return((Image *) NULL);
}
AppendImageToList(&morph_images,morph_image);
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,MorphImageTag,(MagickOffsetType) i,
number_frames);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
return(GetFirstImageInList(morph_images));
}
/*
Morph image sequence.
*/
status=MagickTrue;
scene=0;
next=image;
for ( ; GetNextImageInList(next) != (Image *) NULL; next=GetNextImageInList(next))
{
for (i=0; i < (ssize_t) number_frames; i++)
{
CacheView
*image_view,
*morph_view;
beta=(double) (i+1.0)/(double) (number_frames+1.0);
alpha=1.0-beta;
morph_image=ResizeImage(next,(size_t) (alpha*next->columns+beta*
GetNextImageInList(next)->columns+0.5),(size_t) (alpha*
next->rows+beta*GetNextImageInList(next)->rows+0.5),
next->filter,next->blur,exception);
if (morph_image == (Image *) NULL)
{
morph_images=DestroyImageList(morph_images);
return((Image *) NULL);
}
if (SetImageStorageClass(morph_image,DirectClass) == MagickFalse)
{
InheritException(exception,&morph_image->exception);
morph_image=DestroyImage(morph_image);
return((Image *) NULL);
}
AppendImageToList(&morph_images,morph_image);
morph_images=GetLastImageInList(morph_images);
morph_image=ResizeImage(GetNextImageInList(next),morph_images->columns,
morph_images->rows,GetNextImageInList(next)->filter,
GetNextImageInList(next)->blur,exception);
if (morph_image == (Image *) NULL)
{
morph_images=DestroyImageList(morph_images);
return((Image *) NULL);
}
image_view=AcquireVirtualCacheView(morph_image,exception);
morph_view=AcquireAuthenticCacheView(morph_images,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(morph_image,morph_image,morph_image->rows,1)
#endif
for (y=0; y < (ssize_t) morph_images->rows; y++)
{
MagickBooleanType
sync;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,morph_image->columns,1,
exception);
q=GetCacheViewAuthenticPixels(morph_view,0,y,morph_images->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) morph_images->columns; x++)
{
SetPixelRed(q,ClampToQuantum(alpha*
GetPixelRed(q)+beta*GetPixelRed(p)));
SetPixelGreen(q,ClampToQuantum(alpha*
GetPixelGreen(q)+beta*GetPixelGreen(p)));
SetPixelBlue(q,ClampToQuantum(alpha*
GetPixelBlue(q)+beta*GetPixelBlue(p)));
SetPixelOpacity(q,ClampToQuantum(alpha*
GetPixelOpacity(q)+beta*GetPixelOpacity(p)));
p++;
q++;
}
sync=SyncCacheViewAuthenticPixels(morph_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
morph_view=DestroyCacheView(morph_view);
image_view=DestroyCacheView(image_view);
morph_image=DestroyImage(morph_image);
}
if (i < (ssize_t) number_frames)
break;
/*
Clone last frame in sequence.
*/
morph_image=CloneImage(GetNextImageInList(next),0,0,MagickTrue,exception);
if (morph_image == (Image *) NULL)
{
morph_images=DestroyImageList(morph_images);
return((Image *) NULL);
}
AppendImageToList(&morph_images,morph_image);
morph_images=GetLastImageInList(morph_images);
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,MorphImageTag,scene,
GetImageListLength(image));
if (proceed == MagickFalse)
status=MagickFalse;
}
scene++;
}
if (GetNextImageInList(next) != (Image *) NULL)
{
morph_images=DestroyImageList(morph_images);
return((Image *) NULL);
}
return(GetFirstImageInList(morph_images));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P l a s m a I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PlasmaImage() initializes an image with plasma fractal values. The image
% must be initialized with a base color and the random number generator
% seeded before this method is called.
%
% The format of the PlasmaImage method is:
%
% MagickBooleanType PlasmaImage(Image *image,const SegmentInfo *segment,
% size_t attenuate,size_t depth)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o segment: Define the region to apply plasma fractals values.
%
% o attenuate: Define the plasma attenuation factor.
%
% o depth: Limit the plasma recursion depth.
%
*/
static inline Quantum PlasmaPixel(RandomInfo *random_info,
const MagickRealType pixel,const double noise)
{
Quantum
plasma;
plasma=ClampToQuantum(pixel+noise*GetPseudoRandomValue(random_info)-
noise/2.0);
if (plasma <= 0)
return((Quantum) 0);
if (plasma >= QuantumRange)
return(QuantumRange);
return(plasma);
}
MagickExport MagickBooleanType PlasmaImageProxy(Image *image,
CacheView *image_view,CacheView *u_view,CacheView *v_view,
RandomInfo *random_info,const SegmentInfo *segment,size_t attenuate,
size_t depth)
{
ExceptionInfo
*exception;
double
plasma;
PixelPacket
u,
v;
ssize_t
x,
x_mid,
y,
y_mid;
if ((fabs(segment->x2-segment->x1) <= MagickEpsilon) &&
(fabs(segment->y2-segment->y1) <= MagickEpsilon))
return(MagickTrue);
if (depth != 0)
{
MagickBooleanType
status;
SegmentInfo
local_info;
/*
Divide the area into quadrants and recurse.
*/
depth--;
attenuate++;
x_mid=(ssize_t) ceil((segment->x1+segment->x2)/2-0.5);
y_mid=(ssize_t) ceil((segment->y1+segment->y2)/2-0.5);
local_info=(*segment);
local_info.x2=(double) x_mid;
local_info.y2=(double) y_mid;
(void) PlasmaImageProxy(image,image_view,u_view,v_view,random_info,
&local_info,attenuate,depth);
local_info=(*segment);
local_info.y1=(double) y_mid;
local_info.x2=(double) x_mid;
(void) PlasmaImageProxy(image,image_view,u_view,v_view,random_info,
&local_info,attenuate,depth);
local_info=(*segment);
local_info.x1=(double) x_mid;
local_info.y2=(double) y_mid;
(void) PlasmaImageProxy(image,image_view,u_view,v_view,random_info,
&local_info,attenuate,depth);
local_info=(*segment);
local_info.x1=(double) x_mid;
local_info.y1=(double) y_mid;
status=PlasmaImageProxy(image,image_view,u_view,v_view,random_info,
&local_info,attenuate,depth);
return(status);
}
x_mid=(ssize_t) ceil((segment->x1+segment->x2)/2-0.5);
y_mid=(ssize_t) ceil((segment->y1+segment->y2)/2-0.5);
if ((fabs(segment->x1-x_mid) < MagickEpsilon) &&
(fabs(segment->x2-x_mid) < MagickEpsilon) &&
(fabs(segment->y1-y_mid) < MagickEpsilon) &&
(fabs(segment->y2-y_mid) < MagickEpsilon))
return(MagickFalse);
/*
Average pixels and apply plasma.
*/
exception=(&image->exception);
plasma=(double) QuantumRange/(2.0*attenuate);
if ((fabs(segment->x1-x_mid) > MagickEpsilon) ||
(fabs(segment->x2-x_mid) > MagickEpsilon))
{
register PixelPacket
*magick_restrict q;
/*
Left pixel.
*/
x=(ssize_t) ceil(segment->x1-0.5);
(void) GetOneCacheViewVirtualPixel(u_view,x,(ssize_t)
ceil(segment->y1-0.5),&u,exception);
(void) GetOneCacheViewVirtualPixel(v_view,x,(ssize_t)
ceil(segment->y2-0.5),&v,exception);
q=QueueCacheViewAuthenticPixels(image_view,x,y_mid,1,1,exception);
if (q == (PixelPacket *) NULL)
return(MagickTrue);
SetPixelRed(q,PlasmaPixel(random_info,(MagickRealType) (u.red+v.red)/2.0,
plasma));
SetPixelGreen(q,PlasmaPixel(random_info,(MagickRealType) (u.green+
v.green)/2.0,plasma));
SetPixelBlue(q,PlasmaPixel(random_info,(MagickRealType) (u.blue+v.blue)/
2.0,plasma));
(void) SyncCacheViewAuthenticPixels(image_view,exception);
if (fabs(segment->x1-segment->x2) > MagickEpsilon)
{
/*
Right pixel.
*/
x=(ssize_t) ceil(segment->x2-0.5);
(void) GetOneCacheViewVirtualPixel(u_view,x,(ssize_t)
ceil(segment->y1-0.5),&u,exception);
(void) GetOneCacheViewVirtualPixel(v_view,x,(ssize_t)
ceil(segment->y2-0.5),&v,exception);
q=QueueCacheViewAuthenticPixels(image_view,x,y_mid,1,1,exception);
if (q == (PixelPacket *) NULL)
return(MagickTrue);
SetPixelRed(q,PlasmaPixel(random_info,(MagickRealType) (u.red+v.red)/
2.0,plasma));
SetPixelGreen(q,PlasmaPixel(random_info,(MagickRealType) (u.green+
v.green)/2.0,plasma));
SetPixelBlue(q,PlasmaPixel(random_info,(MagickRealType) (u.blue+
v.blue)/2.0,plasma));
(void) SyncCacheViewAuthenticPixels(image_view,exception);
}
}
if ((fabs(segment->y1-y_mid) > MagickEpsilon) ||
(fabs(segment->y2-y_mid) > MagickEpsilon))
{
if ((fabs(segment->x1-x_mid) > MagickEpsilon) ||
(fabs(segment->y2-y_mid) > MagickEpsilon))
{
register PixelPacket
*magick_restrict q;
/*
Bottom pixel.
*/
y=(ssize_t) ceil(segment->y2-0.5);
(void) GetOneCacheViewVirtualPixel(u_view,(ssize_t)
ceil(segment->x1-0.5),y,&u,exception);
(void) GetOneCacheViewVirtualPixel(v_view,(ssize_t)
ceil(segment->x2-0.5),y,&v,exception);
q=QueueCacheViewAuthenticPixels(image_view,x_mid,y,1,1,exception);
if (q == (PixelPacket *) NULL)
return(MagickTrue);
SetPixelRed(q,PlasmaPixel(random_info,(MagickRealType) (u.red+v.red)/
2.0,plasma));
SetPixelGreen(q,PlasmaPixel(random_info,(MagickRealType) (u.green+
v.green)/2.0,plasma));
SetPixelBlue(q,PlasmaPixel(random_info,(MagickRealType) (u.blue+
v.blue)/2.0,plasma));
(void) SyncCacheViewAuthenticPixels(image_view,exception);
}
if (fabs(segment->y1-segment->y2) > MagickEpsilon)
{
register PixelPacket
*magick_restrict q;
/*
Top pixel.
*/
y=(ssize_t) ceil(segment->y1-0.5);
(void) GetOneCacheViewVirtualPixel(u_view,(ssize_t)
ceil(segment->x1-0.5),y,&u,exception);
(void) GetOneCacheViewVirtualPixel(v_view,(ssize_t)
ceil(segment->x2-0.5),y,&v,exception);
q=QueueCacheViewAuthenticPixels(image_view,x_mid,y,1,1,exception);
if (q == (PixelPacket *) NULL)
return(MagickTrue);
SetPixelRed(q,PlasmaPixel(random_info,(MagickRealType) (u.red+
v.red)/2.0,plasma));
SetPixelGreen(q,PlasmaPixel(random_info,(MagickRealType) (u.green+
v.green)/2.0,plasma));
SetPixelBlue(q,PlasmaPixel(random_info,(MagickRealType) (u.blue+
v.blue)/2.0,plasma));
(void) SyncCacheViewAuthenticPixels(image_view,exception);
}
}
if ((fabs(segment->x1-segment->x2) > MagickEpsilon) ||
(fabs(segment->y1-segment->y2) > MagickEpsilon))
{
register PixelPacket
*magick_restrict q;
/*
Middle pixel.
*/
x=(ssize_t) ceil(segment->x1-0.5);
y=(ssize_t) ceil(segment->y1-0.5);
(void) GetOneCacheViewVirtualPixel(u_view,x,y,&u,exception);
x=(ssize_t) ceil(segment->x2-0.5);
y=(ssize_t) ceil(segment->y2-0.5);
(void) GetOneCacheViewVirtualPixel(v_view,x,y,&v,exception);
q=QueueCacheViewAuthenticPixels(image_view,x_mid,y_mid,1,1,exception);
if (q == (PixelPacket *) NULL)
return(MagickTrue);
SetPixelRed(q,PlasmaPixel(random_info,(MagickRealType) (u.red+v.red)/2.0,
plasma));
SetPixelGreen(q,PlasmaPixel(random_info,(MagickRealType) (u.green+
v.green)/2.0,plasma));
SetPixelBlue(q,PlasmaPixel(random_info,(MagickRealType) (u.blue+v.blue)/
2.0,plasma));
(void) SyncCacheViewAuthenticPixels(image_view,exception);
}
if ((fabs(segment->x2-segment->x1) < 3.0) &&
(fabs(segment->y2-segment->y1) < 3.0))
return(MagickTrue);
return(MagickFalse);
}
MagickExport MagickBooleanType PlasmaImage(Image *image,
const SegmentInfo *segment,size_t attenuate,size_t depth)
{
CacheView
*image_view,
*u_view,
*v_view;
MagickBooleanType
status;
RandomInfo
*random_info;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
image_view=AcquireAuthenticCacheView(image,&image->exception);
u_view=AcquireVirtualCacheView(image,&image->exception);
v_view=AcquireVirtualCacheView(image,&image->exception);
random_info=AcquireRandomInfo();
status=PlasmaImageProxy(image,image_view,u_view,v_view,random_info,segment,
attenuate,depth);
random_info=DestroyRandomInfo(random_info);
v_view=DestroyCacheView(v_view);
u_view=DestroyCacheView(u_view);
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P o l a r o i d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PolaroidImage() simulates a Polaroid picture.
%
% The format of the AnnotateImage method is:
%
% Image *PolaroidImage(const Image *image,const DrawInfo *draw_info,
% const double angle,ExceptionInfo exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o angle: Apply the effect along this angle.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *PolaroidImage(const Image *image,const DrawInfo *draw_info,
const double angle,ExceptionInfo *exception)
{
const char
*value;
Image
*bend_image,
*caption_image,
*flop_image,
*picture_image,
*polaroid_image,
*rotate_image,
*trim_image;
size_t
height;
ssize_t
quantum;
/*
Simulate a Polaroid picture.
*/
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);
quantum=(ssize_t) MagickMax(MagickMax((double) image->columns,(double)
image->rows)/25.0,10.0);
height=image->rows+2*quantum;
caption_image=(Image *) NULL;
value=GetImageProperty(image,"Caption");
if (value != (const char *) NULL)
{
char
*caption;
/*
Generate caption image.
*/
caption_image=CloneImage(image,image->columns,1,MagickTrue,exception);
if (caption_image == (Image *) NULL)
return((Image *) NULL);
caption=InterpretImageProperties((ImageInfo *) NULL,(Image *) image,
value);
if (caption != (char *) NULL)
{
char
geometry[MaxTextExtent];
DrawInfo
*annotate_info;
MagickBooleanType
status;
ssize_t
count;
TypeMetric
metrics;
annotate_info=CloneDrawInfo((const ImageInfo *) NULL,draw_info);
(void) CloneString(&annotate_info->text,caption);
count=FormatMagickCaption(caption_image,annotate_info,MagickTrue,
&metrics,&caption);
status=SetImageExtent(caption_image,image->columns,(size_t)
((count+1)*(metrics.ascent-metrics.descent)+0.5));
if (status == MagickFalse)
caption_image=DestroyImage(caption_image);
else
{
caption_image->background_color=image->border_color;
(void) SetImageBackgroundColor(caption_image);
(void) CloneString(&annotate_info->text,caption);
(void) FormatLocaleString(geometry,MaxTextExtent,"+0+%.20g",
metrics.ascent);
if (annotate_info->gravity == UndefinedGravity)
(void) CloneString(&annotate_info->geometry,AcquireString(
geometry));
(void) AnnotateImage(caption_image,annotate_info);
height+=caption_image->rows;
}
annotate_info=DestroyDrawInfo(annotate_info);
caption=DestroyString(caption);
}
}
picture_image=CloneImage(image,image->columns+2*quantum,height,MagickTrue,
exception);
if (picture_image == (Image *) NULL)
{
if (caption_image != (Image *) NULL)
caption_image=DestroyImage(caption_image);
return((Image *) NULL);
}
picture_image->background_color=image->border_color;
(void) SetImageBackgroundColor(picture_image);
(void) CompositeImage(picture_image,OverCompositeOp,image,quantum,quantum);
if (caption_image != (Image *) NULL)
{
(void) CompositeImage(picture_image,OverCompositeOp,caption_image,
quantum,(ssize_t) (image->rows+3*quantum/2));
caption_image=DestroyImage(caption_image);
}
(void) QueryColorDatabase("none",&picture_image->background_color,exception);
(void) SetImageAlphaChannel(picture_image,OpaqueAlphaChannel);
rotate_image=RotateImage(picture_image,90.0,exception);
picture_image=DestroyImage(picture_image);
if (rotate_image == (Image *) NULL)
return((Image *) NULL);
picture_image=rotate_image;
bend_image=WaveImage(picture_image,0.01*picture_image->rows,2.0*
picture_image->columns,exception);
picture_image=DestroyImage(picture_image);
if (bend_image == (Image *) NULL)
return((Image *) NULL);
InheritException(&bend_image->exception,exception);
picture_image=bend_image;
rotate_image=RotateImage(picture_image,-90.0,exception);
picture_image=DestroyImage(picture_image);
if (rotate_image == (Image *) NULL)
return((Image *) NULL);
picture_image=rotate_image;
picture_image->background_color=image->background_color;
polaroid_image=ShadowImage(picture_image,80.0,2.0,quantum/3,quantum/3,
exception);
if (polaroid_image == (Image *) NULL)
{
picture_image=DestroyImage(picture_image);
return(picture_image);
}
flop_image=FlopImage(polaroid_image,exception);
polaroid_image=DestroyImage(polaroid_image);
if (flop_image == (Image *) NULL)
{
picture_image=DestroyImage(picture_image);
return(picture_image);
}
polaroid_image=flop_image;
(void) CompositeImage(polaroid_image,OverCompositeOp,picture_image,
(ssize_t) (-0.01*picture_image->columns/2.0),0L);
picture_image=DestroyImage(picture_image);
(void) QueryColorDatabase("none",&polaroid_image->background_color,exception);
rotate_image=RotateImage(polaroid_image,angle,exception);
polaroid_image=DestroyImage(polaroid_image);
if (rotate_image == (Image *) NULL)
return((Image *) NULL);
polaroid_image=rotate_image;
trim_image=TrimImage(polaroid_image,exception);
polaroid_image=DestroyImage(polaroid_image);
if (trim_image == (Image *) NULL)
return((Image *) NULL);
polaroid_image=trim_image;
return(polaroid_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e p i a T o n e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% MagickSepiaToneImage() applies a special effect to the image, similar to the
% effect achieved in a photo darkroom by sepia toning. Threshold ranges from
% 0 to QuantumRange and is a measure of the extent of the sepia toning. A
% threshold of 80% is a good starting point for a reasonable tone.
%
% The format of the SepiaToneImage method is:
%
% Image *SepiaToneImage(const Image *image,const double threshold,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o threshold: the tone threshold.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SepiaToneImage(const Image *image,const double threshold,
ExceptionInfo *exception)
{
#define SepiaToneImageTag "SepiaTone/Image"
CacheView
*image_view,
*sepia_view;
Image
*sepia_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Initialize sepia-toned image attributes.
*/
assert(image != (const 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);
sepia_image=CloneImage(image,0,0,MagickTrue,exception);
if (sepia_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(sepia_image,DirectClass) == MagickFalse)
{
InheritException(exception,&sepia_image->exception);
sepia_image=DestroyImage(sepia_image);
return((Image *) NULL);
}
/*
Tone each row of the image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
sepia_view=AcquireAuthenticCacheView(sepia_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,sepia_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(sepia_view,0,y,sepia_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
intensity,
tone;
intensity=GetPixelIntensity(image,p);
tone=intensity > threshold ? (double) QuantumRange : intensity+
(double) QuantumRange-threshold;
SetPixelRed(q,ClampToQuantum(tone));
tone=intensity > (7.0*threshold/6.0) ? (double) QuantumRange :
intensity+(double) QuantumRange-7.0*threshold/6.0;
SetPixelGreen(q,ClampToQuantum(tone));
tone=intensity < (threshold/6.0) ? 0 : intensity-threshold/6.0;
SetPixelBlue(q,ClampToQuantum(tone));
tone=threshold/7.0;
if ((double) GetPixelGreen(q) < tone)
SetPixelGreen(q,ClampToQuantum(tone));
if ((double) GetPixelBlue(q) < tone)
SetPixelBlue(q,ClampToQuantum(tone));
SetPixelOpacity(q,GetPixelOpacity(p));
p++;
q++;
}
if (SyncCacheViewAuthenticPixels(sepia_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,SepiaToneImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
sepia_view=DestroyCacheView(sepia_view);
image_view=DestroyCacheView(image_view);
(void) NormalizeImage(sepia_image);
(void) ContrastImage(sepia_image,MagickTrue);
if (status == MagickFalse)
sepia_image=DestroyImage(sepia_image);
return(sepia_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S h a d o w I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ShadowImage() simulates a shadow from the specified image and returns it.
%
% The format of the ShadowImage method is:
%
% Image *ShadowImage(const Image *image,const double opacity,
% const double sigma,const ssize_t x_offset,const ssize_t y_offset,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o opacity: percentage transparency.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o x_offset: the shadow x-offset.
%
% o y_offset: the shadow y-offset.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ShadowImage(const Image *image,const double opacity,
const double sigma,const ssize_t x_offset,const ssize_t y_offset,
ExceptionInfo *exception)
{
#define ShadowImageTag "Shadow/Image"
CacheView
*image_view;
Image
*border_image,
*clone_image,
*shadow_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
border_info;
ssize_t
y;
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);
clone_image=CloneImage(image,0,0,MagickTrue,exception);
if (clone_image == (Image *) NULL)
return((Image *) NULL);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(clone_image,sRGBColorspace);
(void) SetImageVirtualPixelMethod(clone_image,EdgeVirtualPixelMethod);
clone_image->compose=OverCompositeOp;
border_info.width=(size_t) floor(2.0*sigma+0.5);
border_info.height=(size_t) floor(2.0*sigma+0.5);
border_info.x=0;
border_info.y=0;
(void) QueryColorDatabase("none",&clone_image->border_color,exception);
border_image=BorderImage(clone_image,&border_info,exception);
clone_image=DestroyImage(clone_image);
if (border_image == (Image *) NULL)
return((Image *) NULL);
if (border_image->matte == MagickFalse)
(void) SetImageAlphaChannel(border_image,OpaqueAlphaChannel);
/*
Shadow image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(border_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(border_image,border_image,border_image->rows,1)
#endif
for (y=0; y < (ssize_t) border_image->rows; y++)
{
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,border_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) border_image->columns; x++)
{
SetPixelRed(q,border_image->background_color.red);
SetPixelGreen(q,border_image->background_color.green);
SetPixelBlue(q,border_image->background_color.blue);
if (border_image->matte == MagickFalse)
SetPixelOpacity(q,border_image->background_color.opacity);
else
SetPixelOpacity(q,ClampToQuantum((double) (QuantumRange-
GetPixelAlpha(q)*opacity/100.0)));
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ShadowImageTag,progress,
border_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
shadow_image=BlurImageChannel(border_image,AlphaChannel,0.0,sigma,exception);
border_image=DestroyImage(border_image);
if (shadow_image == (Image *) NULL)
return((Image *) NULL);
if (shadow_image->page.width == 0)
shadow_image->page.width=shadow_image->columns;
if (shadow_image->page.height == 0)
shadow_image->page.height=shadow_image->rows;
shadow_image->page.width+=x_offset-(ssize_t) border_info.width;
shadow_image->page.height+=y_offset-(ssize_t) border_info.height;
shadow_image->page.x+=x_offset-(ssize_t) border_info.width;
shadow_image->page.y+=y_offset-(ssize_t) border_info.height;
return(shadow_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S k e t c h I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SketchImage() simulates a pencil sketch. We convolve the image with a
% Gaussian operator of the given radius and standard deviation (sigma). For
% reasonable results, radius should be larger than sigma. Use a radius of 0
% and SketchImage() selects a suitable radius for you. Angle gives the angle
% of the sketch.
%
% The format of the SketchImage method is:
%
% Image *SketchImage(const Image *image,const double radius,
% const double sigma,const double angle,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o radius: the radius of the Gaussian, in pixels, not counting
% the center pixel.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o angle: Apply the effect along this angle.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SketchImage(const Image *image,const double radius,
const double sigma,const double angle,ExceptionInfo *exception)
{
CacheView
*random_view;
Image
*blend_image,
*blur_image,
*dodge_image,
*random_image,
*sketch_image;
MagickBooleanType
status;
MagickPixelPacket
zero;
RandomInfo
**magick_restrict random_info;
ssize_t
y;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
unsigned long
key;
#endif
/*
Sketch image.
*/
random_image=CloneImage(image,image->columns << 1,image->rows << 1,
MagickTrue,exception);
if (random_image == (Image *) NULL)
return((Image *) NULL);
status=MagickTrue;
GetMagickPixelPacket(random_image,&zero);
random_info=AcquireRandomInfoThreadSet();
random_view=AcquireAuthenticCacheView(random_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(random_image,random_image,random_image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) random_image->rows; y++)
{
const int
id = GetOpenMPThreadId();
MagickPixelPacket
pixel;
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(random_view,0,y,random_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(random_view);
pixel=zero;
for (x=0; x < (ssize_t) random_image->columns; x++)
{
pixel.red=(MagickRealType) (QuantumRange*
GetPseudoRandomValue(random_info[id]));
pixel.green=pixel.red;
pixel.blue=pixel.red;
if (image->colorspace == CMYKColorspace)
pixel.index=pixel.red;
SetPixelPacket(random_image,&pixel,q,indexes+x);
q++;
}
if (SyncCacheViewAuthenticPixels(random_view,exception) == MagickFalse)
status=MagickFalse;
}
random_info=DestroyRandomInfoThreadSet(random_info);
if (status == MagickFalse)
{
random_view=DestroyCacheView(random_view);
random_image=DestroyImage(random_image);
return(random_image);
}
random_view=DestroyCacheView(random_view);
blur_image=MotionBlurImage(random_image,radius,sigma,angle,exception);
random_image=DestroyImage(random_image);
if (blur_image == (Image *) NULL)
return((Image *) NULL);
dodge_image=EdgeImage(blur_image,radius,exception);
blur_image=DestroyImage(blur_image);
if (dodge_image == (Image *) NULL)
return((Image *) NULL);
status=ClampImage(dodge_image);
if (status != MagickFalse)
status=NormalizeImage(dodge_image);
if (status != MagickFalse)
status=NegateImage(dodge_image,MagickFalse);
if (status != MagickFalse)
status=TransformImage(&dodge_image,(char *) NULL,"50%");
sketch_image=CloneImage(image,0,0,MagickTrue,exception);
if (sketch_image == (Image *) NULL)
{
dodge_image=DestroyImage(dodge_image);
return((Image *) NULL);
}
(void) CompositeImage(sketch_image,ColorDodgeCompositeOp,dodge_image,0,0);
dodge_image=DestroyImage(dodge_image);
blend_image=CloneImage(image,0,0,MagickTrue,exception);
if (blend_image == (Image *) NULL)
{
sketch_image=DestroyImage(sketch_image);
return((Image *) NULL);
}
(void) SetImageArtifact(blend_image,"compose:args","20x80");
(void) CompositeImage(sketch_image,BlendCompositeOp,blend_image,0,0);
blend_image=DestroyImage(blend_image);
return(sketch_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S o l a r i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SolarizeImage() applies a special effect to the image, similar to the effect
% achieved in a photo darkroom by selectively exposing areas of photo
% sensitive paper to light. Threshold ranges from 0 to QuantumRange and is a
% measure of the extent of the solarization.
%
% The format of the SolarizeImage method is:
%
% MagickBooleanType SolarizeImage(Image *image,const double threshold)
% MagickBooleanType SolarizeImageChannel(Image *image,
% const ChannelType channel,const double threshold,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
% o threshold: Define the extent of the solarization.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SolarizeImage(Image *image,
const double threshold)
{
MagickBooleanType
status;
status=SolarizeImageChannel(image,DefaultChannels,threshold,
&image->exception);
return(status);
}
MagickExport MagickBooleanType SolarizeImageChannel(Image *image,
const ChannelType channel,const double threshold,ExceptionInfo *exception)
{
#define SolarizeImageTag "Solarize/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace);
if (image->storage_class == PseudoClass)
{
register ssize_t
i;
/*
Solarize colormap.
*/
for (i=0; i < (ssize_t) image->colors; i++)
{
if ((channel & RedChannel) != 0)
if ((double) image->colormap[i].red > threshold)
image->colormap[i].red=QuantumRange-image->colormap[i].red;
if ((channel & GreenChannel) != 0)
if ((double) image->colormap[i].green > threshold)
image->colormap[i].green=QuantumRange-image->colormap[i].green;
if ((channel & BlueChannel) != 0)
if ((double) image->colormap[i].blue > threshold)
image->colormap[i].blue=QuantumRange-image->colormap[i].blue;
}
}
/*
Solarize image.
*/
status=MagickTrue;
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,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((channel & RedChannel) != 0)
if ((double) GetPixelRed(q) > threshold)
SetPixelRed(q,QuantumRange-GetPixelRed(q));
if ((channel & GreenChannel) != 0)
if ((double) GetPixelGreen(q) > threshold)
SetPixelGreen(q,QuantumRange-GetPixelGreen(q));
if ((channel & BlueChannel) != 0)
if ((double) GetPixelBlue(q) > threshold)
SetPixelBlue(q,QuantumRange-GetPixelBlue(q));
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,SolarizeImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S t e g a n o I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SteganoImage() hides a digital watermark within the image. Recover
% the hidden watermark later to prove that the authenticity of an image.
% Offset defines the start position within the image to hide the watermark.
%
% The format of the SteganoImage method is:
%
% Image *SteganoImage(const Image *image,Image *watermark,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o watermark: the watermark image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SteganoImage(const Image *image,const Image *watermark,
ExceptionInfo *exception)
{
#define GetBit(alpha,i) ((((size_t) (alpha) >> (size_t) (i)) & 0x01) != 0)
#define SetBit(alpha,i,set) (alpha)=(Quantum) ((set) != 0 ? (size_t) (alpha) \
| (one << (size_t) (i)) : (size_t) (alpha) & ~(one << (size_t) (i)))
#define SteganoImageTag "Stegano/Image"
CacheView
*stegano_view,
*watermark_view;
Image
*stegano_image;
int
c;
MagickBooleanType
status;
PixelPacket
pixel;
register PixelPacket
*q;
register ssize_t
x;
size_t
depth,
one;
ssize_t
i,
j,
k,
y;
/*
Initialize steganographic image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(watermark != (const Image *) NULL);
assert(watermark->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
one=1UL;
stegano_image=CloneImage(image,0,0,MagickTrue,exception);
if (stegano_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(stegano_image,DirectClass) == MagickFalse)
{
InheritException(exception,&stegano_image->exception);
stegano_image=DestroyImage(stegano_image);
return((Image *) NULL);
}
stegano_image->depth=MAGICKCORE_QUANTUM_DEPTH;
/*
Hide watermark in low-order bits of image.
*/
c=0;
i=0;
j=0;
depth=stegano_image->depth;
k=image->offset;
status=MagickTrue;
watermark_view=AcquireVirtualCacheView(watermark,exception);
stegano_view=AcquireAuthenticCacheView(stegano_image,exception);
for (i=(ssize_t) depth-1; (i >= 0) && (j < (ssize_t) depth); i--)
{
for (y=0; (y < (ssize_t) watermark->rows) && (j < (ssize_t) depth); y++)
{
for (x=0; (x < (ssize_t) watermark->columns) && (j < (ssize_t) depth); x++)
{
(void) GetOneCacheViewVirtualPixel(watermark_view,x,y,&pixel,exception);
if ((k/(ssize_t) stegano_image->columns) >= (ssize_t) stegano_image->rows)
break;
q=GetCacheViewAuthenticPixels(stegano_view,k % (ssize_t)
stegano_image->columns,k/(ssize_t) stegano_image->columns,1,1,
exception);
if (q == (PixelPacket *) NULL)
break;
switch (c)
{
case 0:
{
SetBit(GetPixelRed(q),j,GetBit(ClampToQuantum(GetPixelIntensity(
image,&pixel)),i));
break;
}
case 1:
{
SetBit(GetPixelGreen(q),j,GetBit(ClampToQuantum(GetPixelIntensity(
image,&pixel)),i));
break;
}
case 2:
{
SetBit(GetPixelBlue(q),j,GetBit(ClampToQuantum(GetPixelIntensity(
image,&pixel)),i));
break;
}
}
if (SyncCacheViewAuthenticPixels(stegano_view,exception) == MagickFalse)
break;
c++;
if (c == 3)
c=0;
k++;
if (k == (ssize_t) (stegano_image->columns*stegano_image->columns))
k=0;
if (k == image->offset)
j++;
}
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,SteganoImageTag,(MagickOffsetType)
(depth-i),depth);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
stegano_view=DestroyCacheView(stegano_view);
watermark_view=DestroyCacheView(watermark_view);
if (stegano_image->storage_class == PseudoClass)
(void) SyncImage(stegano_image);
if (status == MagickFalse)
stegano_image=DestroyImage(stegano_image);
return(stegano_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S t e r e o A n a g l y p h I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% StereoAnaglyphImage() combines two images and produces a single image that
% is the composite of a left and right image of a stereo pair. Special
% red-green stereo glasses are required to view this effect.
%
% The format of the StereoAnaglyphImage method is:
%
% Image *StereoImage(const Image *left_image,const Image *right_image,
% ExceptionInfo *exception)
% Image *StereoAnaglyphImage(const Image *left_image,
% const Image *right_image,const ssize_t x_offset,const ssize_t y_offset,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o left_image: the left image.
%
% o right_image: the right image.
%
% o exception: return any errors or warnings in this structure.
%
% o x_offset: amount, in pixels, by which the left image is offset to the
% right of the right image.
%
% o y_offset: amount, in pixels, by which the left image is offset to the
% bottom of the right image.
%
%
*/
MagickExport Image *StereoImage(const Image *left_image,
const Image *right_image,ExceptionInfo *exception)
{
return(StereoAnaglyphImage(left_image,right_image,0,0,exception));
}
MagickExport Image *StereoAnaglyphImage(const Image *left_image,
const Image *right_image,const ssize_t x_offset,const ssize_t y_offset,
ExceptionInfo *exception)
{
#define StereoImageTag "Stereo/Image"
const Image
*image;
Image
*stereo_image;
MagickBooleanType
status;
ssize_t
y;
assert(left_image != (const Image *) NULL);
assert(left_image->signature == MagickCoreSignature);
if (left_image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
left_image->filename);
assert(right_image != (const Image *) NULL);
assert(right_image->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=left_image;
if ((left_image->columns != right_image->columns) ||
(left_image->rows != right_image->rows))
ThrowImageException(ImageError,"LeftAndRightImageSizesDiffer");
/*
Initialize stereo image attributes.
*/
stereo_image=CloneImage(left_image,left_image->columns,left_image->rows,
MagickTrue,exception);
if (stereo_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(stereo_image,DirectClass) == MagickFalse)
{
InheritException(exception,&stereo_image->exception);
stereo_image=DestroyImage(stereo_image);
return((Image *) NULL);
}
(void) SetImageColorspace(stereo_image,sRGBColorspace);
/*
Copy left image to red channel and right image to blue channel.
*/
status=MagickTrue;
for (y=0; y < (ssize_t) stereo_image->rows; y++)
{
register const PixelPacket
*magick_restrict p,
*magick_restrict q;
register ssize_t
x;
register PixelPacket
*magick_restrict r;
p=GetVirtualPixels(left_image,-x_offset,y-y_offset,image->columns,1,
exception);
q=GetVirtualPixels(right_image,0,y,right_image->columns,1,exception);
r=QueueAuthenticPixels(stereo_image,0,y,stereo_image->columns,1,exception);
if ((p == (PixelPacket *) NULL) || (q == (PixelPacket *) NULL) ||
(r == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) stereo_image->columns; x++)
{
SetPixelRed(r,GetPixelRed(p));
SetPixelGreen(r,GetPixelGreen(q));
SetPixelBlue(r,GetPixelBlue(q));
SetPixelOpacity(r,(GetPixelOpacity(p)+q->opacity)/2);
p++;
q++;
r++;
}
if (SyncAuthenticPixels(stereo_image,exception) == MagickFalse)
break;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,StereoImageTag,(MagickOffsetType) y,
stereo_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
if (status == MagickFalse)
stereo_image=DestroyImage(stereo_image);
return(stereo_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S w i r l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SwirlImage() swirls the pixels about the center of the image, where
% degrees indicates the sweep of the arc through which each pixel is moved.
% You get a more dramatic effect as the degrees move from 1 to 360.
%
% The format of the SwirlImage method is:
%
% Image *SwirlImage(const Image *image,double degrees,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o degrees: Define the tightness of the swirling effect.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SwirlImage(const Image *image,double degrees,
ExceptionInfo *exception)
{
#define SwirlImageTag "Swirl/Image"
CacheView
*image_view,
*swirl_view;
double
radius;
Image
*swirl_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
zero;
PointInfo
center,
scale;
ssize_t
y;
/*
Initialize swirl image attributes.
*/
assert(image != (const 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);
swirl_image=CloneImage(image,0,0,MagickTrue,exception);
if (swirl_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(swirl_image,DirectClass) == MagickFalse)
{
InheritException(exception,&swirl_image->exception);
swirl_image=DestroyImage(swirl_image);
return((Image *) NULL);
}
if (swirl_image->background_color.opacity != OpaqueOpacity)
swirl_image->matte=MagickTrue;
/*
Compute scaling factor.
*/
center.x=(double) image->columns/2.0;
center.y=(double) image->rows/2.0;
radius=MagickMax(center.x,center.y);
scale.x=1.0;
scale.y=1.0;
if (image->columns > image->rows)
scale.y=(double) image->columns/(double) image->rows;
else
if (image->columns < image->rows)
scale.x=(double) image->rows/(double) image->columns;
degrees=(double) DegreesToRadians(degrees);
/*
Swirl image.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(swirl_image,&zero);
image_view=AcquireVirtualCacheView(image,exception);
swirl_view=AcquireAuthenticCacheView(swirl_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,swirl_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
double
distance;
MagickPixelPacket
pixel;
PointInfo
delta;
register IndexPacket
*magick_restrict swirl_indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(swirl_view,0,y,swirl_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
swirl_indexes=GetCacheViewAuthenticIndexQueue(swirl_view);
delta.y=scale.y*(double) (y-center.y);
pixel=zero;
for (x=0; x < (ssize_t) image->columns; x++)
{
/*
Determine if the pixel is within an ellipse.
*/
delta.x=scale.x*(double) (x-center.x);
distance=delta.x*delta.x+delta.y*delta.y;
if (distance < (radius*radius))
{
double
cosine,
factor,
sine;
/*
Swirl the pixel.
*/
factor=1.0-sqrt(distance)/radius;
sine=sin((double) (degrees*factor*factor));
cosine=cos((double) (degrees*factor*factor));
status=InterpolateMagickPixelPacket(image,image_view,
UndefinedInterpolatePixel,(double) ((cosine*delta.x-sine*delta.y)/
scale.x+center.x),(double) ((sine*delta.x+cosine*delta.y)/scale.y+
center.y),&pixel,exception);
if (status == MagickFalse)
break;
SetPixelPacket(swirl_image,&pixel,q,swirl_indexes+x);
}
q++;
}
if (SyncCacheViewAuthenticPixels(swirl_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,SwirlImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
swirl_view=DestroyCacheView(swirl_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
swirl_image=DestroyImage(swirl_image);
return(swirl_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T i n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TintImage() applies a color vector to each pixel in the image. The length
% of the vector is 0 for black and white and at its maximum for the midtones.
% The vector weighting function is f(x)=(1-(4.0*((x-0.5)*(x-0.5))))
%
% The format of the TintImage method is:
%
% Image *TintImage(const Image *image,const char *opacity,
% const PixelPacket tint,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o opacity: A color value used for tinting.
%
% o tint: A color value used for tinting.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *TintImage(const Image *image,const char *opacity,
const PixelPacket tint,ExceptionInfo *exception)
{
#define TintImageTag "Tint/Image"
CacheView
*image_view,
*tint_view;
GeometryInfo
geometry_info;
Image
*tint_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
color_vector,
pixel;
MagickStatusType
flags;
ssize_t
y;
/*
Allocate tint image.
*/
assert(image != (const 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);
tint_image=CloneImage(image,0,0,MagickTrue,exception);
if (tint_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(tint_image,DirectClass) == MagickFalse)
{
InheritException(exception,&tint_image->exception);
tint_image=DestroyImage(tint_image);
return((Image *) NULL);
}
if ((IsGrayColorspace(image->colorspace) != MagickFalse) &&
(IsPixelGray(&tint) == MagickFalse))
(void) SetImageColorspace(tint_image,sRGBColorspace);
if (opacity == (const char *) NULL)
return(tint_image);
/*
Determine RGB values of the tint color.
*/
flags=ParseGeometry(opacity,&geometry_info);
pixel.red=geometry_info.rho;
pixel.green=geometry_info.rho;
pixel.blue=geometry_info.rho;
pixel.opacity=(MagickRealType) OpaqueOpacity;
if ((flags & SigmaValue) != 0)
pixel.green=geometry_info.sigma;
if ((flags & XiValue) != 0)
pixel.blue=geometry_info.xi;
if ((flags & PsiValue) != 0)
pixel.opacity=geometry_info.psi;
color_vector.red=(MagickRealType) (pixel.red*tint.red/100.0-
PixelPacketIntensity(&tint));
color_vector.green=(MagickRealType) (pixel.green*tint.green/100.0-
PixelPacketIntensity(&tint));
color_vector.blue=(MagickRealType) (pixel.blue*tint.blue/100.0-
PixelPacketIntensity(&tint));
/*
Tint image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
tint_view=AcquireAuthenticCacheView(tint_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,tint_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(tint_view,0,y,tint_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
weight;
MagickPixelPacket
pixel;
weight=QuantumScale*GetPixelRed(p)-0.5;
pixel.red=(MagickRealType) GetPixelRed(p)+color_vector.red*(1.0-(4.0*
(weight*weight)));
SetPixelRed(q,ClampToQuantum(pixel.red));
weight=QuantumScale*GetPixelGreen(p)-0.5;
pixel.green=(MagickRealType) GetPixelGreen(p)+color_vector.green*(1.0-
(4.0*(weight*weight)));
SetPixelGreen(q,ClampToQuantum(pixel.green));
weight=QuantumScale*GetPixelBlue(p)-0.5;
pixel.blue=(MagickRealType) GetPixelBlue(p)+color_vector.blue*(1.0-(4.0*
(weight*weight)));
SetPixelBlue(q,ClampToQuantum(pixel.blue));
SetPixelOpacity(q,GetPixelOpacity(p));
p++;
q++;
}
if (SyncCacheViewAuthenticPixels(tint_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,TintImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
tint_view=DestroyCacheView(tint_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
tint_image=DestroyImage(tint_image);
return(tint_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% V i g n e t t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% VignetteImage() softens the edges of the image in vignette style.
%
% The format of the VignetteImage method is:
%
% Image *VignetteImage(const Image *image,const double radius,
% const double sigma,const ssize_t x,const ssize_t y,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o radius: the radius of the pixel neighborhood.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o x, y: Define the x and y ellipse offset.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *VignetteImage(const Image *image,const double radius,
const double sigma,const ssize_t x,const ssize_t y,ExceptionInfo *exception)
{
char
ellipse[MaxTextExtent];
DrawInfo
*draw_info;
Image
*blur_image,
*canvas_image,
*oval_image,
*vignette_image;
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);
canvas_image=CloneImage(image,0,0,MagickTrue,exception);
if (canvas_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(canvas_image,DirectClass) == MagickFalse)
{
InheritException(exception,&canvas_image->exception);
canvas_image=DestroyImage(canvas_image);
return((Image *) NULL);
}
canvas_image->matte=MagickTrue;
oval_image=CloneImage(canvas_image,canvas_image->columns,canvas_image->rows,
MagickTrue,exception);
if (oval_image == (Image *) NULL)
{
canvas_image=DestroyImage(canvas_image);
return((Image *) NULL);
}
(void) QueryColorDatabase("#000000",&oval_image->background_color,exception);
(void) SetImageBackgroundColor(oval_image);
draw_info=CloneDrawInfo((const ImageInfo *) NULL,(const DrawInfo *) NULL);
(void) QueryColorDatabase("#ffffff",&draw_info->fill,exception);
(void) QueryColorDatabase("#ffffff",&draw_info->stroke,exception);
(void) FormatLocaleString(ellipse,MaxTextExtent,
"ellipse %g,%g,%g,%g,0.0,360.0",image->columns/2.0,
image->rows/2.0,image->columns/2.0-x,image->rows/2.0-y);
draw_info->primitive=AcquireString(ellipse);
(void) DrawImage(oval_image,draw_info);
draw_info=DestroyDrawInfo(draw_info);
blur_image=BlurImage(oval_image,radius,sigma,exception);
oval_image=DestroyImage(oval_image);
if (blur_image == (Image *) NULL)
{
canvas_image=DestroyImage(canvas_image);
return((Image *) NULL);
}
blur_image->matte=MagickFalse;
(void) CompositeImage(canvas_image,CopyOpacityCompositeOp,blur_image,0,0);
blur_image=DestroyImage(blur_image);
vignette_image=MergeImageLayers(canvas_image,FlattenLayer,exception);
canvas_image=DestroyImage(canvas_image);
if (vignette_image != (Image *) NULL)
(void) TransformImageColorspace(vignette_image,image->colorspace);
return(vignette_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W a v e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WaveImage() creates a "ripple" effect in the image by shifting the pixels
% vertically along a sine wave whose amplitude and wavelength is specified
% by the given parameters.
%
% The format of the WaveImage method is:
%
% Image *WaveImage(const Image *image,const double amplitude,
% const double wave_length,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o amplitude, wave_length: Define the amplitude and wave length of the
% sine wave.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *WaveImage(const Image *image,const double amplitude,
const double wave_length,ExceptionInfo *exception)
{
#define WaveImageTag "Wave/Image"
CacheView
*image_view,
*wave_view;
float
*sine_map;
Image
*wave_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
zero;
register ssize_t
i;
ssize_t
y;
/*
Initialize wave image attributes.
*/
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);
wave_image=CloneImage(image,image->columns,(size_t) (image->rows+2.0*
fabs(amplitude)),MagickTrue,exception);
if (wave_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(wave_image,DirectClass) == MagickFalse)
{
InheritException(exception,&wave_image->exception);
wave_image=DestroyImage(wave_image);
return((Image *) NULL);
}
if (wave_image->background_color.opacity != OpaqueOpacity)
wave_image->matte=MagickTrue;
/*
Allocate sine map.
*/
sine_map=(float *) AcquireQuantumMemory((size_t) wave_image->columns,
sizeof(*sine_map));
if (sine_map == (float *) NULL)
{
wave_image=DestroyImage(wave_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
for (i=0; i < (ssize_t) wave_image->columns; i++)
sine_map[i]=(float) fabs(amplitude)+amplitude*sin((double)
((2.0*MagickPI*i)/wave_length));
/*
Wave image.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(wave_image,&zero);
image_view=AcquireVirtualCacheView(image,exception);
wave_view=AcquireAuthenticCacheView(wave_image,exception);
(void) SetCacheViewVirtualPixelMethod(image_view,
BackgroundVirtualPixelMethod);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,wave_image,wave_image->rows,1)
#endif
for (y=0; y < (ssize_t) wave_image->rows; y++)
{
MagickPixelPacket
pixel;
register IndexPacket
*magick_restrict indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(wave_view,0,y,wave_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(wave_view);
pixel=zero;
for (x=0; x < (ssize_t) wave_image->columns; x++)
{
status=InterpolateMagickPixelPacket(image,image_view,
UndefinedInterpolatePixel,(double) x,(double) (y-sine_map[x]),&pixel,
exception);
if (status == MagickFalse)
break;
SetPixelPacket(wave_image,&pixel,q,indexes+x);
q++;
}
if (SyncCacheViewAuthenticPixels(wave_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,WaveImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
wave_view=DestroyCacheView(wave_view);
image_view=DestroyCacheView(image_view);
sine_map=(float *) RelinquishMagickMemory(sine_map);
if (status == MagickFalse)
wave_image=DestroyImage(wave_image);
return(wave_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W a v e l e t D e n o i s e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WaveletDenoiseImage() removes noise from the image using a wavelet
% transform. The wavelet transform is a fast hierarchical scheme for
% processing an image using a set of consecutive lowpass and high_pass filters,
% followed by a decimation. This results in a decomposition into different
% scales which can be regarded as different “frequency bands”, determined by
% the mother wavelet. Adapted from dcraw.c by David Coffin.
%
% The format of the WaveletDenoiseImage method is:
%
% Image *WaveletDenoiseImage(const Image *image,const double threshold,
% const double softness,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o threshold: set the threshold for smoothing.
%
% o softness: attenuate the smoothing threshold.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline void HatTransform(const float *magick_restrict pixels,
const size_t stride,const size_t extent,const size_t scale,float *kernel)
{
const float
*magick_restrict p,
*magick_restrict q,
*magick_restrict r;
register ssize_t
i;
p=pixels;
q=pixels+scale*stride,
r=pixels+scale*stride;
for (i=0; i < (ssize_t) scale; i++)
{
kernel[i]=0.25f*(*p+(*p)+(*q)+(*r));
p+=stride;
q-=stride;
r+=stride;
}
for ( ; i < (ssize_t) (extent-scale); i++)
{
kernel[i]=0.25f*(2.0f*(*p)+*(p-scale*stride)+*(p+scale*stride));
p+=stride;
}
q=p-scale*stride;
r=pixels+stride*(extent-2);
for ( ; i < (ssize_t) extent; i++)
{
kernel[i]=0.25f*(*p+(*p)+(*q)+(*r));
p+=stride;
q+=stride;
r-=stride;
}
}
MagickExport Image *WaveletDenoiseImage(const Image *image,
const double threshold,const double softness,ExceptionInfo *exception)
{
CacheView
*image_view,
*noise_view;
float
*kernel,
*pixels;
Image
*noise_image;
MagickBooleanType
status;
MagickSizeType
number_pixels;
MemoryInfo
*pixels_info;
size_t
max_channels;
ssize_t
channel;
static const double
noise_levels[]= {
0.8002, 0.2735, 0.1202, 0.0585, 0.0291, 0.0152, 0.0080, 0.0044 };
/*
Initialize noise image attributes.
*/
assert(image != (const 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);
noise_image=(Image *) NULL;
#if defined(MAGICKCORE_OPENCL_SUPPORT)
noise_image=AccelerateWaveletDenoiseImage(image,threshold,exception);
if (noise_image != (Image *) NULL)
return(noise_image);
#endif
noise_image=CloneImage(image,0,0,MagickTrue,exception);
if (noise_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(noise_image,DirectClass) == MagickFalse)
{
noise_image=DestroyImage(noise_image);
return((Image *) NULL);
}
if (AcquireMagickResource(WidthResource,3*image->columns) == MagickFalse)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
pixels_info=AcquireVirtualMemory(3*image->columns,image->rows*
sizeof(*pixels));
kernel=(float *) AcquireQuantumMemory(MagickMax(image->rows,image->columns)+1,
GetOpenMPMaximumThreads()*sizeof(*kernel));
if ((pixels_info == (MemoryInfo *) NULL) || (kernel == (float *) NULL))
{
if (kernel != (float *) NULL)
kernel=(float *) RelinquishMagickMemory(kernel);
if (pixels_info != (MemoryInfo *) NULL)
pixels_info=RelinquishVirtualMemory(pixels_info);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(float *) GetVirtualMemoryBlob(pixels_info);
status=MagickTrue;
number_pixels=image->columns*image->rows;
max_channels=(size_t) (image->colorspace == CMYKColorspace ? 4 : 3);
image_view=AcquireAuthenticCacheView(image,exception);
noise_view=AcquireAuthenticCacheView(noise_image,exception);
for (channel=0; channel < (ssize_t) max_channels; channel++)
{
register ssize_t
i;
size_t
high_pass,
low_pass;
ssize_t
level,
y;
if (status == MagickFalse)
continue;
/*
Copy channel from image to wavelet pixel array.
*/
i=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
ssize_t
x;
p=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
{
status=MagickFalse;
break;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
switch (channel)
{
case 0: pixels[i]=(float) GetPixelRed(p); break;
case 1: pixels[i]=(float) GetPixelGreen(p); break;
case 2: pixels[i]=(float) GetPixelBlue(p); break;
case 3: pixels[i]=(float) indexes[x]; break;
default: break;
}
i++;
p++;
}
}
/*
Low pass filter outputs are called approximation kernel & high pass
filters are referred to as detail kernel. The detail kernel
have high values in the noisy parts of the signal.
*/
high_pass=0;
for (level=0; level < 5; level++)
{
double
magnitude;
ssize_t
x,
y;
low_pass=(size_t) (number_pixels*((level & 0x01)+1));
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,1) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
register float
*magick_restrict p,
*magick_restrict q;
register ssize_t
x;
p=kernel+id*image->columns;
q=pixels+y*image->columns;
HatTransform(q+high_pass,1,image->columns,(size_t) (1UL << level),p);
q+=low_pass;
for (x=0; x < (ssize_t) image->columns; x++)
*q++=(*p++);
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,1) \
magick_number_threads(image,image,image->columns,1)
#endif
for (x=0; x < (ssize_t) image->columns; x++)
{
const int
id = GetOpenMPThreadId();
register float
*magick_restrict p,
*magick_restrict q;
register ssize_t
y;
p=kernel+id*image->rows;
q=pixels+x+low_pass;
HatTransform(q,image->columns,image->rows,(size_t) (1UL << level),p);
for (y=0; y < (ssize_t) image->rows; y++)
{
*q=(*p++);
q+=image->columns;
}
}
/*
To threshold, each coefficient is compared to a threshold value and
attenuated / shrunk by some factor.
*/
magnitude=threshold*noise_levels[level];
for (i=0; i < (ssize_t) number_pixels; ++i)
{
pixels[high_pass+i]-=pixels[low_pass+i];
if (pixels[high_pass+i] < -magnitude)
pixels[high_pass+i]+=magnitude-softness*magnitude;
else
if (pixels[high_pass+i] > magnitude)
pixels[high_pass+i]-=magnitude-softness*magnitude;
else
pixels[high_pass+i]*=softness;
if (high_pass != 0)
pixels[i]+=pixels[high_pass+i];
}
high_pass=low_pass;
}
/*
Reconstruct image from the thresholded wavelet kernel.
*/
i=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register IndexPacket
*magick_restrict noise_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
q=GetCacheViewAuthenticPixels(noise_view,0,y,noise_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
break;
}
noise_indexes=GetCacheViewAuthenticIndexQueue(noise_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
float
pixel;
pixel=pixels[i]+pixels[low_pass+i];
switch (channel)
{
case 0: SetPixelRed(q,ClampToQuantum(pixel)); break;
case 1: SetPixelGreen(q,ClampToQuantum(pixel)); break;
case 2: SetPixelBlue(q,ClampToQuantum(pixel)); break;
case 3: SetPixelIndex(noise_indexes+x,ClampToQuantum(pixel)); break;
default: break;
}
i++;
q++;
}
sync=SyncCacheViewAuthenticPixels(noise_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,AddNoiseImageTag,(MagickOffsetType)
channel,max_channels);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
noise_view=DestroyCacheView(noise_view);
image_view=DestroyCacheView(image_view);
kernel=(float *) RelinquishMagickMemory(kernel);
pixels_info=RelinquishVirtualMemory(pixels_info);
return(noise_image);
}
|
triad.h
|
#ifndef TRIAD_H
#define TRIAD_H
#include <iostream>
#include <vector>
#include <random>
#include <set>
namespace TSnap {
/////////////////////////////////////////////////
// Triads and clustering coefficient
/// Computes the average clustering coefficient as defined in Watts and Strogatz, Collective dynamics of 'small-world' networks. ##TSnap::GetClustCf
template <class PGraph> double GetClustCf(const PGraph& Graph, int64_t SampleNodes=-1);
/// Computes the distribution of average clustering coefficient. ##TSnap::GetClustCf1
template <class PGraph> double GetClustCf(const PGraph& Graph, TFltPrV& DegToCCfV, int64_t SampleNodes=-1);
/// Computes the distribution of average clustering coefficient as well as the number of open and closed triads in the graph. ##TSnap::GetClustCf2
template <class PGraph> double GetClustCf(const PGraph& Graph, TFltPrV& DegToCCfV, int64& ClosedTriadsX, int64& OpenTriadsX, int64_t SampleNodes=-1);
/// Returns clustering coefficient of a particular node. ##TSnap::GetNodeClustCf
template <class PGraph> double GetNodeClustCf(const PGraph& Graph, const int& NId);
/// Computes clustering coefficient of each node of the Graph. ##TSnap::GetClustCf1
template <class PGraph> void GetNodeClustCf(const PGraph& Graph, TIntFltH& NIdCCfH);
template <class PGraph> void GetNodeClustCf_scala(const PGraph& Graph, TIntFltH& NIdCCfH);
template <class PGraph> void GetNodeClustCf(const PGraph& Graph, std::vector<float>& NIdCCfH);
/// Returns the number of triangles in a graph. ##TSnap::GetTriads
template <class PGraph> int64 GetTriads(const PGraph& Graph, int64_t SampleNodes=-1);
/// Computes the number of Closed and Open triads. ##TSnap::GetTriads1
template <class PGraph> int64 GetTriads(const PGraph& Graph, int64& ClosedTriadsX, int64& OpenTriadsX, int64_t SampleNodes);
/// Computes the number of open and close triads for every node of the network. ##TSnap::GetTriads2
template <class PGraph> void GetTriads(const PGraph& Graph, TIntTrV& NIdCOTriadV, int64_t SampleNodes=-1);
template <class PGraph> void GetTriads_v0(const PGraph& Graph, TIntTrV& NIdCOTriadV, int SampleNodes=-1);
template <class PGraph> void GetTriads(const PGraph& Graph, std::vector<TUInt64Tr>& NIdCOTriadV, int64_t SampleNodes=-1);
/// Counts the number of edges that participate in at least one triad. ##TSnap::GetTriadEdges
template <class PGraph> int GetTriadEdges(const PGraph& Graph, int SampleEdges=-1);
/// Returns the number of undirected triads a node \c NId participates in. ##TSnap::GetNodeTriads
template <class PGraph> int GetNodeTriads(const PGraph& Graph, const int& NId);
/// Returns number of Open and Closed triads a node \c NId participates in. ##TSnap::GetNodeTriads1
template <class PGraph> int GetNodeTriads(const PGraph& Graph, const int& NId, int& ClosedNTriadsX, int& OpenNTriadsX);
/// Returns the number of triads between a node \c NId and a subset of its neighbors \c GroupSet. ##TSnap::GetNodeTriads3
template <class PGraph>
int GetNodeTriads(const PGraph& Graph, const int& NId, const TIntSet& GroupSet, int& InGroupEdgesX, int& InOutGroupEdgesX, int& OutGroupEdgesX);
/// Triangle Participation Ratio: For each node counts how many triangles it participates in and then returns a set of pairs (number of triangles, number of such nodes). ##TSnap::GetTriadParticip
template <class PGraph> void GetTriadParticip(const PGraph& Graph, TIntPrV& TriadCntV);
/// Returns a number of shared neighbors between a pair of nodes NId1 and NId2.
template<class PGraph> int GetCmnNbrs(const PGraph& Graph, const int& NId1, const int& NId2);
/// Returns the shared neighbors between a pair of nodes NId1 and NId2.
template<class PGraph> int GetCmnNbrs(const PGraph& Graph, const int& NId1, const int& NId2, TIntV& NbrV);
/// Returns the number of length 2 directed paths between a pair of nodes NId1, NId2 (NId1 --> U --> NId2).
template<class PGraph> int GetLen2Paths(const PGraph& Graph, const int& NId1, const int& NId2);
/// Returns the 2 directed paths between a pair of nodes NId1, NId2 (NId1 --> U --> NId2). ##TSnap::GetLen2Paths
template<class PGraph> int GetLen2Paths(const PGraph& Graph, const int& NId1, const int& NId2, TIntV& NbrV);
/// Returns the number of triangles in graph \c Graph, original version
template<class PGraph> int64 CountTriangles(const PGraph& Graph);
/// Returns the number of triangles in graph \c Graph, newer version
template<class PGraph> int64 GetTriangleCnt(const PGraph& Graph);
/// Merges neighbors.
template<class PGraph> void MergeNbrs(TIntV& NeighbourV, const typename PGraph::TObj::TNodeI& NI);
template<class PGraph> void GetMergeSortedV(TIntV& NeighbourV, typename PGraph::TObj::TNodeI NI);
/// Returns sorted vector \c NbrV containing unique in or out neighbors of node \c NId in graph \c Graph
template <class PGraph> void GetUniqueNbrV(const PGraph& Graph, const int& NId, TIntV& NbrV);
template <class PGraph> void GetUniqueNbrV(const PGraph& Graph, const int64_t& NId, std::vector< int64_t>& NbrV);
/// Returns the number of common elements in two sorted TInt vectors
int GetCommon(TIntV& A, TIntV& B);
int64_t GetCommon(const std::vector< int64_t>& A, const std::vector< int64_t>& B);
/////////////////////////////////////////////////
// Implementation
template<class PGraph> void GetMergeSortedV(TIntV& NeighbourV, typename PGraph::TObj::TNodeI NI) {
int j = 0;
int k = 0;
int prev = -1;
int indeg = NI.GetInDeg();
int outdeg = NI.GetOutDeg();
if (indeg > 0 && outdeg > 0) {
int v1 = NI.GetInNId(j);
int v2 = NI.GetOutNId(k);
while (1) {
if (v1 <= v2) {
if (prev != v1) {
NeighbourV.Add(v1);
prev = v1;
}
j += 1;
if (j >= indeg) {
break;
}
v1 = NI.GetInNId(j);
} else {
if (prev != v2) {
NeighbourV.Add(v2);
prev = v2;
}
k += 1;
if (k >= outdeg) {
break;
}
v2 = NI.GetOutNId(k);
}
}
}
while (j < indeg) {
int v = NI.GetInNId(j);
if (prev != v) {
NeighbourV.Add(v);
prev = v;
}
j += 1;
}
while (k < outdeg) {
int v = NI.GetOutNId(k);
if (prev != v) {
NeighbourV.Add(v);
prev = v;
}
k += 1;
}
}
template <class PGraph> double GetClustCf(const PGraph& Graph, int64_t SampleNodes) {
std::vector<TUInt64Tr> NIdCOTriadV;
GetTriads(Graph, NIdCOTriadV, SampleNodes);
if (NIdCOTriadV.empty()) {
return 0.0;
}
double SumCcf = 0.0;
for ( int64_t i = 0; i < NIdCOTriadV.size(); i++) {
const double OpenCnt = NIdCOTriadV[i].Val2()+NIdCOTriadV[i].Val3();
if (OpenCnt > 0) {
SumCcf += NIdCOTriadV[i].Val2() / OpenCnt; }
}
IAssert(SumCcf>=0);
return SumCcf / double(NIdCOTriadV.size());
}
template <class PGraph> double GetClustCf(const PGraph& Graph, TFltPrV& DegToCCfV, int64_t SampleNodes) {
TIntTrV NIdCOTriadV;
GetTriads(Graph, NIdCOTriadV, SampleNodes);
THash<TInt, TFltPr> DegSumCnt;
double SumCcf = 0.0;
for (int i = 0; i < NIdCOTriadV.Len(); i++) {
const int D = NIdCOTriadV[i].Val2()+NIdCOTriadV[i].Val3();
const double Ccf = D!=0 ? NIdCOTriadV[i].Val2() / double(D) : 0.0;
TFltPr& SumCnt = DegSumCnt.AddDat(Graph->GetNI(NIdCOTriadV[i].Val1).GetDeg());
SumCnt.Val1 += Ccf;
SumCnt.Val2 += 1;
SumCcf += Ccf;
}
// get average clustering coefficient for each degree
DegToCCfV.Gen(DegSumCnt.Len(), 0);
for (int d = 0; d < DegSumCnt.Len(); d++) {
DegToCCfV.Add(TFltPr(DegSumCnt.GetKey(d).Val, double(DegSumCnt[d].Val1()/DegSumCnt[d].Val2())));
}
DegToCCfV.Sort();
return SumCcf / double(NIdCOTriadV.Len());
}
template <class PGraph>
double GetClustCf(const PGraph& Graph, TFltPrV& DegToCCfV, int64& ClosedTriads, int64& OpenTriads, int64_t SampleNodes) {
TIntTrV NIdCOTriadV;
GetTriads(Graph, NIdCOTriadV, SampleNodes);
THash<TInt, TFltPr> DegSumCnt;
double SumCcf = 0.0;
int64 closedTriads = 0;
int64 openTriads = 0;
for (int i = 0; i < NIdCOTriadV.Len(); i++) {
const int D = NIdCOTriadV[i].Val2()+NIdCOTriadV[i].Val3();
const double Ccf = D!=0 ? NIdCOTriadV[i].Val2() / double(D) : 0.0;
closedTriads += NIdCOTriadV[i].Val2;
openTriads += NIdCOTriadV[i].Val3;
TFltPr& SumCnt = DegSumCnt.AddDat(Graph->GetNI(NIdCOTriadV[i].Val1).GetDeg());
SumCnt.Val1 += Ccf;
SumCnt.Val2 += 1;
SumCcf += Ccf;
}
// get average clustering coefficient for each degree
DegToCCfV.Gen(DegSumCnt.Len(), 0);
for (int d = 0; d < DegSumCnt.Len(); d++) {
DegToCCfV.Add(TFltPr(DegSumCnt.GetKey(d).Val, DegSumCnt[d].Val1()/DegSumCnt[d].Val2()));
}
//if(closedTriads/3 > (uint64) TInt::Mx) { WarnNotify(TStr::Fmt("[%s line %d] %g closed triads.\n", __FILE__, __LINE__, float(closedTriads/3)).CStr()); }
//if(openTriads > (uint64) TInt::Mx) { WarnNotify(TStr::Fmt("[%s line %d] %g open triads.\n", __FILE__, __LINE__, float(openTriads/3)).CStr()); }
ClosedTriads = closedTriads/int64(3); // each triad is counted 3 times
OpenTriads = openTriads;
DegToCCfV.Sort();
return SumCcf / double(NIdCOTriadV.Len());
}
template <class PGraph>
double GetNodeClustCf(const PGraph& Graph, const int& NId) {
int Open, Closed;
GetNodeTriads(Graph, NId, Open, Closed);
//const double Deg = Graph->GetNI(NId).GetDeg();
return (Open+Closed)==0 ? 0 : double(Open)/double(Open+Closed);
}
template <class PGraph>
void GetNodeClustCf(const PGraph& Graph, std::vector<float>& NIdCCfH) {
std::vector<TUInt64Tr> NIdCOTriadV;
GetTriads(Graph, NIdCOTriadV);
NIdCCfH.clear();
NIdCCfH.reserve(Graph->GetNodes());
for ( int64_t i = 0; i < NIdCOTriadV.size(); i++) {
const int64_t D = NIdCOTriadV[i].Val2()+NIdCOTriadV[i].Val3();
const double CCf = D!=0 ? NIdCOTriadV[i].Val2() / double(D) : 0.0;
NIdCCfH[NIdCOTriadV[i].Val1] = CCf;
}
}
template <class PGraph>
void GetNodeClustCf(const PGraph& Graph, TIntFltH& NIdCCfH) {
TIntTrV NIdCOTriadV;
GetTriads(Graph, NIdCOTriadV);
NIdCCfH.Clr(false);
for (int i = 0; i < NIdCOTriadV.Len(); i++) {
const int D = NIdCOTriadV[i].Val2()+NIdCOTriadV[i].Val3();
const double CCf = D!=0 ? NIdCOTriadV[i].Val2() / double(D) : 0.0;
NIdCCfH.AddDat(NIdCOTriadV[i].Val1, CCf);
}
}
template <class PGraph>
void GetNodeClustCf_scala(const PGraph& Graph, TIntFltH& NIdCCfH) {
TIntTrV NIdCOTriadV;
GetTriads_v0(Graph, NIdCOTriadV);
NIdCCfH.Clr(false);
for (int i = 0; i < NIdCOTriadV.Len(); i++) {
const int D = NIdCOTriadV[i].Val2()+NIdCOTriadV[i].Val3();
const double CCf = D!=0 ? NIdCOTriadV[i].Val2() / double(D) : 0.0;
NIdCCfH.AddDat(NIdCOTriadV[i].Val1, CCf);
}
}
template <class PGraph>
int64 GetTriads(const PGraph& Graph, int64_t SampleNodes) {
int64 OpenTriads, ClosedTriads;
return GetTriads(Graph, ClosedTriads, OpenTriads, SampleNodes);
}
template <class PGraph>
int64 GetTriads(const PGraph& Graph, int64& ClosedTriads, int64& OpenTriads, int64_t SampleNodes) {
std::vector<TUInt64Tr> NIdCOTriadV;
GetTriads(Graph, NIdCOTriadV, SampleNodes);
uint64 closedTriads = 0;
uint64 openTriads = 0;
for ( int64_t i = 0; i < NIdCOTriadV.size(); i++) {
closedTriads += NIdCOTriadV[i].Val2;
openTriads += NIdCOTriadV[i].Val3;
}
ClosedTriads = int64(closedTriads/3); // each triad is counted 3 times
OpenTriads = int64(openTriads);
return ClosedTriads;
}
// Function pretends that the graph is undirected (count unique connected triples of nodes)
// This implementation is slower, it uses hash tables directly
template <class PGraph>
void GetTriads_v0(const PGraph& Graph, TIntTrV& NIdCOTriadV, int SampleNodes) {
const bool IsDir = Graph->HasFlag(gfDirected);
TIntSet NbrH;
TIntV NIdV;
TRnd Rnd(0);
Graph->GetNIdV(NIdV);
NIdV.Shuffle(Rnd);
if (SampleNodes == -1) {
SampleNodes = Graph->GetNodes(); }
NIdCOTriadV.Clr(false);
NIdCOTriadV.Reserve(SampleNodes);
for (int node = 0; node < SampleNodes; node++) {
typename PGraph::TObj::TNodeI NI = Graph->GetNI(NIdV[node]);
if (NI.GetDeg() < 2) {
NIdCOTriadV.Add(TIntTr(NI.GetId(), 0, 0)); // zero triangles
continue;
}
// find neighborhood
NbrH.Clr(false);
for (int e = 0; e < NI.GetOutDeg(); e++) {
if (NI.GetOutNId(e) != NI.GetId()) {
NbrH.AddKey(NI.GetOutNId(e)); }
}
if (IsDir) {
for (int e = 0; e < NI.GetInDeg(); e++) {
if (NI.GetInNId(e) != NI.GetId()) {
NbrH.AddKey(NI.GetInNId(e)); }
}
}
// count connected neighbors
int OpenCnt=0, CloseCnt=0;
for (int srcNbr = 0; srcNbr < NbrH.Len(); srcNbr++) {
const typename PGraph::TObj::TNodeI SrcNode = Graph->GetNI(NbrH.GetKey(srcNbr));
for (int dstNbr = srcNbr+1; dstNbr < NbrH.Len(); dstNbr++) {
const int dstNId = NbrH.GetKey(dstNbr);
if (SrcNode.IsNbrNId(dstNId)) { CloseCnt++; } // is edge
else { OpenCnt++; }
}
}
IAssert(2*(OpenCnt+CloseCnt) == NbrH.Len()*(NbrH.Len()-1));
NIdCOTriadV.Add(TIntTr(NI.GetId(), CloseCnt, OpenCnt));
}
}
// Function pretends that the graph is undirected (count unique connected triples of nodes)
// This implementation is faster, it converts hash tables to vectors
template <class PGraph>
void GetTriads(const PGraph& Graph, TIntTrV& NIdCOTriadV, int64_t SampleNodes) {
const bool IsDir = Graph->HasFlag(gfDirected);
TIntSet NbrH;
TIntV NIdV;
//TRnd Rnd(0);
TRnd Rnd(1);
int NNodes;
TIntV Nbrs;
int NId;
int64 hcount;
hcount = 0;
NNodes = Graph->GetNodes();
Graph->GetNIdV(NIdV);
NIdV.Shuffle(Rnd);
if (SampleNodes == -1) {
SampleNodes = NNodes;
}
int MxId = -1;
for (int i = 0; i < NNodes; i++) {
if (NIdV[i] > MxId) {
MxId = NIdV[i];
}
}
TVec<TIntV> NbrV(MxId + 1);
if (IsDir) {
// get in and out neighbors
for (int node = 0; node < NNodes; node++) {
int NId = NIdV[node];
NbrV[NId] = TIntV();
GetUniqueNbrV(Graph, NId, NbrV[NId]);
}
} else {
// get only out neighbors
for (int node = 0; node < NNodes; node++) {
int NId = NIdV[node];
typename PGraph::TObj::TNodeI NI = Graph->GetNI(NId);
NbrV[NId] = TIntV();
NbrV[NId].Reserve(NI.GetOutDeg());
NbrV[NId].Reduce(0);
for (int i = 0; i < NI.GetOutDeg(); i++) {
NbrV[NId].Add(NI.GetOutNId(i));
}
}
}
NIdCOTriadV.Clr(false);
NIdCOTriadV.Reserve(SampleNodes);
for (int node = 0; node < SampleNodes; node++) {
typename PGraph::TObj::TNodeI NI = Graph->GetNI(NIdV[node]);
int NLen;
NId = NI.GetId();
hcount++;
if (NI.GetDeg() < 2) {
NIdCOTriadV.Add(TIntTr(NId, 0, 0)); // zero triangles
continue;
}
Nbrs = NbrV[NId];
NLen = Nbrs.Len();
// count connected neighbors
int OpenCnt1 = 0, CloseCnt1 = 0;
for (int srcNbr = 0; srcNbr < NLen; srcNbr++) {
int Count = GetCommon(NbrV[NbrV[NId][srcNbr]],Nbrs);
CloseCnt1 += Count;
}
CloseCnt1 /= 2;
OpenCnt1 = (NLen*(NLen-1))/2 - CloseCnt1;
NIdCOTriadV.Add(TIntTr(NId, CloseCnt1, OpenCnt1));
}
}
template <class PGraph>
void GetTriads(const PGraph& Graph, std::vector<TUInt64Tr>& NIdCOTriadV,
int64_t SampleNodes) {
const bool IsDir = Graph->HasFlag(gfDirected);
int64_t NNodes = Graph->GetNodes();
int64 hcount;
hcount = 0;
std::vector< int64_t> samples;
int64_t nodesToProcess = NNodes;
if (SampleNodes != -1) {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution< int64_t> dis(0, NNodes);
std::set< int64_t> set_samples;
for( int64_t i = 0; i < SampleNodes; ) {
int64_t id = dis(gen);
if (!set_samples.count(id)) {
set_samples.insert(id);
samples.push_back(id);
i++;
}
}
nodesToProcess = samples.size();
}
NIdCOTriadV.resize(nodesToProcess);
std::vector< int64_t> Nbrs1;
std::vector< int64_t> Nbrs2;
for ( int64_t node = 0; node < nodesToProcess; node++) {
typename PGraph::TObj::TNodeI NI;
if (SampleNodes == -1) {
NI = Graph->GetNI(node);
} else {
NI = Graph->GetNI(samples[node]);
}
hcount++;
if (NI.GetDeg() < 2) {
NIdCOTriadV[node] = TUInt64Tr(node, 0, 0); // zero triangles
continue;
}
Nbrs1.clear();
GetUniqueNbrV(Graph, node, Nbrs1);
// count connected neighbors
int64_t OpenCnt1 = 0, CloseCnt1 = 0;
for ( int64_t srcNbr = 0; srcNbr < Nbrs1.size(); srcNbr++) {
Nbrs2.clear();
GetUniqueNbrV(Graph, Nbrs1[srcNbr], Nbrs2);
int64_t Count = GetCommon(Nbrs2,Nbrs1);
CloseCnt1 += Count;
}
CloseCnt1 /= 2;
OpenCnt1 = (Nbrs1.size()*(Nbrs1.size()-1))/2 - CloseCnt1;
NIdCOTriadV[node] = TUInt64Tr(node, CloseCnt1, OpenCnt1);
}
}
template<class PGraph>
int64 CountTriangles(const PGraph& Graph) {
THash<TInt, TInt> H;
TIntV MapV;
int ind = 0;
for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
H.AddDat(NI.GetId(), ind);
MapV.Add(NI.GetId());
ind += 1;
}
TVec<TIntV> HigherDegNbrV(ind);
#ifdef USE_OPENMP
#pragma omp parallel for schedule(dynamic)
#endif
for (int i = 0; i < ind; i++) {
typename PGraph::TObj::TNodeI NI = Graph->GetNI(MapV[i]);
TIntV NbrV;
GetMergeSortedV<PGraph>(NbrV, NI);
TIntV V;
for (int j = 0; j < NbrV.Len(); j++) {
TInt Vert = NbrV[j];
TInt Deg = Graph->GetNI(Vert).GetDeg();
if (Deg > NI.GetDeg() ||
(( int64_t)Deg == NI.GetDeg() && Vert > NI.GetId())) {
V.Add(Vert);
}
}
HigherDegNbrV[i] = V;
}
int64 cnt = 0;
#ifdef USE_OPENMP
#pragma omp parallel for schedule(dynamic) reduction(+:cnt)
#endif
for (int i = 0; i < HigherDegNbrV.Len(); i++) {
for (int j = 0; j < HigherDegNbrV[i].Len(); j++) {
TInt NbrInd = H.GetDat(HigherDegNbrV[i][j]);
int64 num = GetCommon(HigherDegNbrV[i], HigherDegNbrV[NbrInd]);
cnt += num;
}
}
return cnt;
}
template<class PGraph>
int64 GetTriangleCnt(const PGraph& Graph) {
struct timeval start, end;
struct timeval startall, endall;
float delta;
TTmProfiler Profiler;
int TimerId = Profiler.AddTimer("Profiler");
int TimerAll = Profiler.AddTimer("ProfilerAll");
const int NNodes = Graph->GetNodes();
TIntV MapV(NNodes);
TVec<typename PGraph::TObj::TNodeI> NV(NNodes);
NV.Reduce(0);
Profiler.ResetTimer(TimerAll);
Profiler.StartTimer(TimerAll);
gettimeofday(&startall, NULL);
Profiler.ResetTimer(TimerId);
Profiler.StartTimer(TimerId);
gettimeofday(&start, NULL);
int MxId = -1;
int ind = 0;
for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
NV.Add(NI);
int Id = NI.GetId();
if (Id > MxId) {
MxId = Id;
}
MapV[ind] = Id;
ind++;
}
TIntV IndV(MxId+1);
for (int j = 0; j < NNodes; j++) {
IndV[MapV[j]] = j;
}
gettimeofday(&end, NULL);
Profiler.StopTimer(TimerId);
delta = ((end.tv_sec - start.tv_sec) * 1000000u +
end.tv_usec - start.tv_usec) / 1.e6;
printf("__nodemap__\ttime %7.3f\tcpu %8.3f\n", delta, Profiler.GetTimerSec(TimerId));
Profiler.ResetTimer(TimerId);
Profiler.StartTimer(TimerId);
gettimeofday(&start, NULL);
ind = MapV.Len();
Profiler.ResetTimer(TimerId);
Profiler.StartTimer(TimerId);
gettimeofday(&start, NULL);
TVec<TIntV> HigherDegNbrV(ind);
for (int i = 0; i < ind; i++) {
HigherDegNbrV[i] = TVec<TInt>();
HigherDegNbrV[i].Reserve(NV[i].GetDeg());
HigherDegNbrV[i].Reduce(0);
}
gettimeofday(&end, NULL);
Profiler.StopTimer(TimerId);
delta = ((end.tv_sec - start.tv_sec) * 1000000u +
end.tv_usec - start.tv_usec) / 1.e6;
printf("__valloc__\ttime %7.3f\tcpu %8.3f\n", delta, Profiler.GetTimerSec(TimerId));
Profiler.ResetTimer(TimerId);
Profiler.StartTimer(TimerId);
gettimeofday(&start, NULL);
#ifdef USE_OPENMP
#pragma omp parallel for schedule(dynamic)
#endif
for (int i = 0; i < ind; i++) {
typename PGraph::TObj::TNodeI NI = NV[i];
//HigherDegNbrV[i] = TVec<TInt>();
//HigherDegNbrV[i].Reserve(NI.GetDeg());
//HigherDegNbrV[i].Reduce(0);
MergeNbrs<PGraph>(HigherDegNbrV[i], NI);
int k = 0;
for (int j = 0; j < HigherDegNbrV[i].Len(); j++) {
TInt Vert = HigherDegNbrV[i][j];
TInt Deg = NV[IndV[Vert]].GetDeg();
if (Deg > NI.GetDeg() ||
(Deg == NI.GetDeg() && Vert > NI.GetId())) {
HigherDegNbrV[i][k] = Vert;
k++;
}
}
HigherDegNbrV[i].Reduce(k);
}
gettimeofday(&end, NULL);
Profiler.StopTimer(TimerId);
delta = ((end.tv_sec - start.tv_sec) * 1000000u +
end.tv_usec - start.tv_usec) / 1.e6;
printf("__sort__\ttime %7.3f\tcpu %8.3f\n", delta, Profiler.GetTimerSec(TimerId));
Profiler.ResetTimer(TimerId);
Profiler.StartTimer(TimerId);
gettimeofday(&start, NULL);
int64 cnt = 0;
#ifdef USE_OPENMP
#pragma omp parallel for schedule(dynamic) reduction(+:cnt)
#endif
for (int i = 0; i < HigherDegNbrV.Len(); i++) {
for (int j = 0; j < HigherDegNbrV[i].Len(); j++) {
//TInt NbrInd = H.GetDat(HigherDegNbrV[i][j]);
TInt NbrInd = IndV[HigherDegNbrV[i][j]];
int64 num = GetCommon(HigherDegNbrV[i], HigherDegNbrV[NbrInd]);
cnt += num;
}
}
gettimeofday(&end, NULL);
Profiler.StopTimer(TimerId);
delta = ((end.tv_sec - start.tv_sec) * 1000000u +
end.tv_usec - start.tv_usec) / 1.e6;
printf("__count__\ttime %7.3f\tcpu %8.3f\n", delta, Profiler.GetTimerSec(TimerId));
gettimeofday(&endall, NULL);
Profiler.StopTimer(TimerAll);
delta = ((endall.tv_sec - startall.tv_sec) * 1000000u +
endall.tv_usec - startall.tv_usec) / 1.e6;
printf("__all__ \ttime %7.3f\tcpu %8.3f\n", delta, Profiler.GetTimerSec(TimerAll));
return cnt;
}
template<class PGraph>
void MergeNbrs(TIntV& NeighbourV, const typename PGraph::TObj::TNodeI& NI) {
int j = 0;
int k = 0;
int prev = -1;
int indeg = NI.GetInDeg();
int outdeg = NI.GetOutDeg();
//while (j < NI.GetInDeg() && k < NI.GetOutDeg()) {
if (indeg > 0 && outdeg > 0) {
int v1 = NI.GetInNId(j);
int v2 = NI.GetOutNId(k);
while (1) {
if (v1 <= v2) {
if (prev != v1) {
NeighbourV.Add(v1);
prev = v1;
}
j += 1;
if (j >= indeg) {
break;
}
v1 = NI.GetInNId(j);
} else {
if (prev != v2) {
NeighbourV.Add(v2);
prev = v2;
}
k += 1;
if (k >= outdeg) {
break;
}
v2 = NI.GetOutNId(k);
}
}
}
while (j < indeg) {
int v = NI.GetInNId(j);
if (prev != v) {
NeighbourV.Add(v);
prev = v;
}
j += 1;
}
while (k < outdeg) {
int v = NI.GetOutNId(k);
if (prev != v) {
NeighbourV.Add(v);
prev = v;
}
k += 1;
}
}
// Count the number of edges that participate in at least one triad
template <class PGraph>
int GetTriadEdges(const PGraph& Graph, int SampleEdges) {
const bool IsDir = Graph->HasFlag(gfDirected);
TIntSet NbrH;
int TriadEdges = 0;
for(typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
NbrH.Clr(false);
for (int e = 0; e < NI.GetOutDeg(); e++) {
if (NI.GetOutNId(e) != NI.GetId()) {
NbrH.AddKey(NI.GetOutNId(e)); }
}
if (IsDir) {
for (int e = 0; e < NI.GetInDeg(); e++) {
if (NI.GetInNId(e) != NI.GetId()) {
NbrH.AddKey(NI.GetInNId(e)); }
}
}
for (int e = 0; e < NI.GetOutDeg(); e++) {
if (!IsDir && NI.GetId()<NI.GetOutNId(e)) { continue; } // for undirected graphs count each edge only once
const typename PGraph::TObj::TNodeI SrcNode = Graph->GetNI(NI.GetOutNId(e));
bool Triad=false;
for (int e1 = 0; e1 < SrcNode.GetOutDeg(); e1++) {
if (NbrH.IsKey(SrcNode.GetOutNId(e1))) { Triad=true; break; }
}
if (IsDir && ! Triad) {
for (int e1 = 0; e1 < SrcNode.GetInDeg(); e1++) {
if (NbrH.IsKey(SrcNode.GetInNId(e1))) { Triad=true; break; }
}
}
if (Triad) { TriadEdges++; }
}
}
return TriadEdges;
}
// Returns number of undirected triads a node participates in
template <class PGraph>
int GetNodeTriads(const PGraph& Graph, const int& NId) {
int ClosedTriads=0, OpenTriads=0;
return GetNodeTriads(Graph, NId, ClosedTriads, OpenTriads);
}
// Return number of undirected triads a node participates in
template <class PGraph>
int GetNodeTriads(const PGraph& Graph, const int& NId, int& ClosedTriads, int& OpenTriads) {
const typename PGraph::TObj::TNodeI NI = Graph->GetNI(NId);
ClosedTriads=0; OpenTriads=0;
if (NI.GetDeg() < 2) { return 0; }
// find neighborhood
TIntSet NbrSet(NI.GetDeg());
for (int e = 0; e < NI.GetOutDeg(); e++) {
if (NI.GetOutNId(e) != NI.GetId()) { // exclude self edges
NbrSet.AddKey(NI.GetOutNId(e)); }
}
if (Graph->HasFlag(gfDirected)) {
for (int e = 0; e < NI.GetInDeg(); e++) {
if (NI.GetInNId(e) != NI.GetId()) { // exclude self edges
NbrSet.AddKey(NI.GetInNId(e)); }
}
}
// count connected neighbors
for (int srcNbr = 0; srcNbr < NbrSet.Len(); srcNbr++) {
const typename PGraph::TObj::TNodeI SrcNode = Graph->GetNI(NbrSet.GetKey(srcNbr));
for (int dstNbr = srcNbr+1; dstNbr < NbrSet.Len(); dstNbr++) {
const int dstNId = NbrSet.GetKey(dstNbr);
if (SrcNode.IsNbrNId(dstNId)) { ClosedTriads++; }
else { OpenTriads++; }
}
}
return ClosedTriads;
}
// Node NId and a subset of its neighbors GroupSet
// InGroupEdges ... triads (NId, g1, g2), where g1 and g2 are in GroupSet
// InOutGroupEdges ... triads (NId, g1, o1), where g1 in GroupSet and o1 not in GroupSet
// OutGroupEdges ... triads (NId, o1, o2), where o1 and o2 are not in GroupSet
template <class PGraph>
int GetNodeTriads(const PGraph& Graph, const int& NId, const TIntSet& GroupSet, int& InGroupEdges, int& InOutGroupEdges, int& OutGroupEdges) {
const typename PGraph::TObj::TNodeI NI = Graph->GetNI(NId);
const bool IsDir = Graph->HasFlag(gfDirected);
InGroupEdges=0; InOutGroupEdges=0; OutGroupEdges=0;
if (NI.GetDeg() < 2) { return 0; }
// find neighborhood
TIntSet NbrSet(NI.GetDeg());
for (int e = 0; e < NI.GetOutDeg(); e++) {
if (NI.GetOutNId(e) != NI.GetId()) { // exclude self edges
NbrSet.AddKey(NI.GetOutNId(e)); }
}
if (IsDir) {
for (int e = 0; e < NI.GetInDeg(); e++) {
if (NI.GetInNId(e) != NI.GetId()) {
NbrSet.AddKey(NI.GetInNId(e)); }
}
}
// count connected neighbors
for (int srcNbr = 0; srcNbr < NbrSet.Len(); srcNbr++) {
const int NbrId = NbrSet.GetKey(srcNbr);
const bool NbrIn = GroupSet.IsKey(NbrId);
const typename PGraph::TObj::TNodeI SrcNode = Graph->GetNI(NbrId);
for (int dstNbr = srcNbr+1; dstNbr < NbrSet.Len(); dstNbr++) {
const int DstNId = NbrSet.GetKey(dstNbr);
if (SrcNode.IsNbrNId(DstNId)) { // triad (NId, NbrId, DstNid)
bool DstIn = GroupSet.IsKey(DstNId);
if (NbrIn && DstIn) { InGroupEdges++; }
else if (NbrIn || DstIn) { InOutGroupEdges++; }
else { OutGroupEdges++; }
}
}
}
return InGroupEdges;
}
// For each node count how many triangles it participates in
template <class PGraph>
void GetTriadParticip(const PGraph& Graph, TIntPrV& TriadCntV) {
TIntH TriadCntH;
for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
const int Triads = GetNodeTriads(Graph, NI.GetId());
TriadCntH.AddDat(Triads) += 1;
}
TriadCntH.GetKeyDatPrV(TriadCntV);
TriadCntV.Sort();
}
template<class PGraph>
int GetCmnNbrs(const PGraph& Graph, const int& NId1, const int& NId2) {
TIntV NbrV;
return GetCmnNbrs(Graph, NId1, NId2, NbrV);
}
// Get common neighbors between a pair of nodes (undirected)
template<class PGraph>
int GetCmnNbrs(const PGraph& Graph, const int& NId1, const int& NId2, TIntV& NbrV) {
if (! Graph->IsNode(NId1) || ! Graph->IsNode(NId2)) { NbrV.Clr(false); return 0; }
typename PGraph::TObj::TNodeI NI1 = Graph->GetNI(NId1);
typename PGraph::TObj::TNodeI NI2 = Graph->GetNI(NId2);
NbrV.Clr(false);
NbrV.Reserve(TMath::Mn(NI1.GetDeg(), NI2.GetDeg()));
TIntSet NSet1(NI1.GetDeg()), NSet2(NI2.GetDeg());
for (int i = 0; i < NI1.GetDeg(); i++) {
const int nid = NI1.GetNbrNId(i);
if (nid!=NId1 && nid!=NId2) {
NSet1.AddKey(nid); }
}
for (int i = 0; i < NI2.GetDeg(); i++) {
const int nid = NI2.GetNbrNId(i);
if (NSet1.IsKey(nid)) {
NSet2.AddKey(nid);
}
}
NSet2.GetKeyV(NbrV);
return NbrV.Len();
}
template<>
inline int GetCmnNbrs<PUNGraph>(const PUNGraph& Graph, const int& NId1, const int& NId2, TIntV& NbrV) {
if (! Graph->IsNode(NId1) || ! Graph->IsNode(NId2)) { NbrV.Clr(false); return 0; }
const TUNGraph::TNodeI NI1 = Graph->GetNI(NId1);
const TUNGraph::TNodeI NI2 = Graph->GetNI(NId2);
int i=0, j=0;
NbrV.Clr(false);
NbrV.Reserve(TMath::Mn(NI1.GetDeg(), NI2.GetDeg()));
while (i < NI1.GetDeg() && j < NI2.GetDeg()) {
const int nid = NI1.GetNbrNId(i);
while (j < NI2.GetDeg() && NI2.GetNbrNId(j) < nid) { j++; }
if (j < NI2.GetDeg() && nid==NI2.GetNbrNId(j) && nid!=NId1 && nid!=NId2) {
IAssert(NbrV.Empty() || NbrV.Last() < nid);
NbrV.Add(nid);
j++;
}
i++;
}
return NbrV.Len();
}
// get number of length 2 directed paths between a pair of nodes
// for a pair of nodes (i,j): |{u: (i,u) and (u,j) }|
template<class PGraph>
int GetLen2Paths(const PGraph& Graph, const int& NId1, const int& NId2) {
TIntV NbrV;
return GetLen2Paths(Graph, NId1, NId2, NbrV);
}
// get number of length 2 directed paths between a pair of nodes
// for a pair of nodes (i,j): {u: (i,u) and (u,j) }
template<class PGraph>
int GetLen2Paths(const PGraph& Graph, const int& NId1, const int& NId2, TIntV& NbrV) {
const typename PGraph::TObj::TNodeI NI = Graph->GetNI(NId1);
NbrV.Clr(false);
NbrV.Reserve(NI.GetOutDeg());
for (int e = 0; e < NI.GetOutDeg(); e++) {
const typename PGraph::TObj::TNodeI MidNI = Graph->GetNI(NI.GetOutNId(e));
if (MidNI.IsOutNId(NId2)) {
NbrV.Add(MidNI.GetId());
}
}
return NbrV.Len();
}
template <class PGraph>
void GetUniqueNbrV(const PGraph& Graph, const int& NId, TIntV& NbrV) {
typename PGraph::TObj::TNodeI NI = Graph->GetNI(NId);
NbrV.Reserve(NI.GetDeg());
NbrV.Reduce(0);
int j = 0;
int k = 0;
int Prev = -1;
int InDeg = NI.GetInDeg();
int OutDeg = NI.GetOutDeg();
if (InDeg > 0 && OutDeg > 0) {
int v1 = NI.GetInNId(j);
int v2 = NI.GetOutNId(k);
while (1) {
if (v1 <= v2) {
if (Prev != v1) {
if (v1 != NId) {
NbrV.Add(v1);
Prev = v1;
}
}
j += 1;
if (j >= InDeg) {
break;
}
v1 = NI.GetInNId(j);
} else {
if (Prev != v2) {
if (v2 != NId) {
NbrV.Add(v2);
}
Prev = v2;
}
k += 1;
if (k >= OutDeg) {
break;
}
v2 = NI.GetOutNId(k);
}
}
}
while (j < InDeg) {
int v = NI.GetInNId(j);
if (Prev != v) {
if (v != NId) {
NbrV.Add(v);
}
Prev = v;
}
j += 1;
}
while (k < OutDeg) {
int v = NI.GetOutNId(k);
if (Prev != v) {
if (v != NId) {
NbrV.Add(v);
}
Prev = v;
}
k += 1;
}
}
template <class PGraph>
void GetUniqueNbrV(const PGraph& Graph, const int64_t& NId, std::vector< int64_t>& NbrV) {
typename PGraph::TObj::TNodeI NI = Graph->GetNI(NId);
int64_t j = 0;
int64_t k = 0;
int64_t Prev = -1;
int64_t InDeg = NI.GetInDeg();
int64_t OutDeg = NI.GetOutDeg();
if (InDeg > 0 && OutDeg > 0) {
int64_t v1 = NI.GetInNId(j);
int64_t v2 = NI.GetOutNId(k);
while (1) {
if (v1 <= v2) {
if (Prev != v1) {
if (v1 != NId) {
NbrV.push_back(v1);
Prev = v1;
}
}
j += 1;
if (j >= InDeg) {
break;
}
v1 = NI.GetInNId(j);
} else {
if (Prev != v2) {
if (v2 != NId) {
NbrV.push_back(v2);
}
Prev = v2;
}
k += 1;
if (k >= OutDeg) {
break;
}
v2 = NI.GetOutNId(k);
}
}
}
while (j < InDeg) {
int64_t v = NI.GetInNId(j);
if (Prev != v) {
if (v != NId) {
NbrV.push_back(v);
}
Prev = v;
}
j += 1;
}
while (k < OutDeg) {
int64_t v = NI.GetOutNId(k);
if (Prev != v) {
if (v != NId) {
NbrV.push_back(v);
}
Prev = v;
}
k += 1;
}
}
}; // mamespace TSnap
/////////////////////////////////////////////////
// Node and Edge Network Constraint (by Ron Burt)
// works for directed and undirected graphs (but not for multigraphs)
template <class PGraph>
class TNetConstraint {
public:
PGraph Graph;
THash<TIntPr, TFlt> NodePrCH; // pairs of nodes that have non-zero network constraint
public:
TNetConstraint(const PGraph& GraphPt, const bool& CalcaAll=true);
int Len() const { return NodePrCH.Len(); }
double GetC(const int& ConstraintN) const { return NodePrCH[ConstraintN]; }
TIntPr GetNodePr(const int& ConstraintN) const { return NodePrCH.GetKey(ConstraintN); }
double GetEdgeC(const int& NId1, const int& NId2) const;
double GetNodeC(const int& NId) const;
void AddConstraint(const int& NId1, const int& NId2);
void CalcConstraints();
void CalcConstraints(const int& NId);
void Dump() const;
static void Test();
};
template <class PGraph>
TNetConstraint<PGraph>::TNetConstraint(const PGraph& GraphPt, const bool& CalcaAll) : Graph(GraphPt) {
CAssert(! HasGraphFlag(typename PGraph::TObj, gfMultiGraph)); // must not be multigraph
if (CalcaAll) {
CalcConstraints();
}
}
template <class PGraph>
double TNetConstraint<PGraph>::GetEdgeC(const int& NId1, const int& NId2) const {
if (NodePrCH.IsKey(TIntPr(NId1, NId2))) {
return NodePrCH.GetDat(TIntPr(NId1, NId2)); }
else {
return 0.0; }
}
template <class PGraph>
double TNetConstraint<PGraph>::GetNodeC(const int& NId) const {
typename PGraph::TObj::TNodeI NI1 = Graph->GetNI(NId);
if (NI1.GetOutDeg() == 0) { return 0.0; }
int KeyId = -1;
for (int k = 0; k<NI1.GetOutDeg(); k++) {
KeyId = NodePrCH.GetKeyId(TIntPr(NI1.GetId(), NI1.GetOutNId(k)));
if (KeyId > -1) { break; }
}
if (KeyId < 0) { return 0.0; }
double Constraint = NodePrCH[KeyId];
for (int i = KeyId-1; i >-1 && NodePrCH.GetKey(i).Val1()==NId; i--) {
Constraint += NodePrCH[i];
}
for (int i = KeyId+1; i < NodePrCH.Len() && NodePrCH.GetKey(i).Val1()==NId; i++) {
Constraint += NodePrCH[i];
}
return Constraint;
}
template <class PGraph>
void TNetConstraint<PGraph>::AddConstraint(const int& NId1, const int& NId2) {
if (NId1==NId2 || NodePrCH.IsKey(TIntPr(NId1, NId2))) {
return;
}
typename PGraph::TObj::TNodeI NI1 = Graph->GetNI(NId1);
double Constraint = 0.0;
if (NI1.IsOutNId(NId2)) { // is direct edge
Constraint += 1.0/(double) NI1.GetOutDeg();
}
const double SrcC = 1.0/(double) NI1.GetOutDeg();
for (int e = 0; e < NI1.GetOutDeg(); e++) {
const int MidNId = NI1.GetOutNId(e);
if (MidNId == NId1 || MidNId == NId2) { continue; }
const typename PGraph::TObj::TNodeI MidNI = Graph->GetNI(MidNId);
if (MidNI.IsOutNId(NId2)) {
Constraint += SrcC * (1.0/(double)MidNI.GetOutDeg());
}
}
if (Constraint==0) { return; }
Constraint = TMath::Sqr(Constraint);
NodePrCH.AddDat(TIntPr(NId1, NId2), Constraint);
}
template <class PGraph>
void TNetConstraint<PGraph>::CalcConstraints() {
// add edges
for (typename PGraph::TObj::TEdgeI EI = Graph->BegEI(); EI < Graph->EndEI(); EI++) {
AddConstraint(EI.GetSrcNId(), EI.GetDstNId());
AddConstraint(EI.GetDstNId(), EI.GetSrcNId());
}
// add open triads
for (typename PGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) {
for (int i = 0; i < NI.GetDeg(); i++) {
const int NId1 = NI.GetNbrNId(i);
for (int j = 0; j < NI.GetDeg(); j++) {
const int NId2 = NI.GetNbrNId(j);
AddConstraint(NId1, NId2);
}
}
}
NodePrCH.SortByKey();
}
// calculate constraints around a node id
template <class PGraph>
void TNetConstraint<PGraph>::CalcConstraints(const int& NId) {
typename PGraph::TObj::TNodeI StartNI = Graph->GetNI(NId);
TIntSet SeenSet;
for (int e = 0; e < StartNI.GetOutDeg(); e++) {
typename PGraph::TObj::TNodeI MidNI = Graph->GetNI(StartNI.GetOutNId(e));
AddConstraint(NId, MidNI.GetId());
for (int i = 0; i < MidNI.GetOutDeg(); i++) {
const int EndNId = MidNI.GetOutNId(i);
if (! SeenSet.IsKey(EndNId)) {
AddConstraint(NId, EndNId);
SeenSet.AddKey(EndNId);
}
}
}
}
template <class PGraph>
void TNetConstraint<PGraph>::Dump() const {
printf("Edge network constraint: (%d, %d)\n", Graph->GetNodes(), Graph->GetEdges());
for (int e = 0; e < NodePrCH.Len(); e++) {
printf(" %4d %4d : %f\n", NodePrCH.GetKey(e).Val1(), NodePrCH.GetKey(e).Val2(), NodePrCH[e].Val);
}
printf("\n");
}
// example from page 56 of Structural Holes by Ronald S. Burt
// (http://www.amazon.com/Structural-Holes-Social-Structure-Competition/dp/0674843711)
template <class PGraph>
void TNetConstraint<PGraph>::Test() {
PUNGraph G = TUNGraph::New();
G->AddNode(0); G->AddNode(1); G->AddNode(2); G->AddNode(3);
G->AddNode(4); G->AddNode(5); G->AddNode(6);
G->AddEdge(0,1); G->AddEdge(0,2); G->AddEdge(0,3); G->AddEdge(0,4); G->AddEdge(0,5); G->AddEdge(0,6);
G->AddEdge(1,2); G->AddEdge(1,5); G->AddEdge(1,6);
G->AddEdge(2,4);
TNetConstraint<PUNGraph> NetConstraint(G, true);
// NetConstraint.CalcConstraints(0);
NetConstraint.Dump();
printf("middle node network constraint: %f\n", NetConstraint.GetNodeC(0));
}
#endif // TRIAD_H
|
ttables.h
|
// Copyright 2013 by Chris Dyer
//
// 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 _TTABLES_H_
#define _TTABLES_H_
#include <cassert>
#include <cmath>
#include <fstream>
#include <iostream>
#include <vector>
#include "src/hashtables.h"
#include "src/corpus.h"
struct Md {
static double digamma(double x) {
double result = 0, xx, xx2, xx4;
for ( ; x < 7; ++x)
result -= 1/x;
x -= 1.0/2.0;
xx = 1.0/x;
xx2 = xx*xx;
xx4 = xx2*xx2;
result += log(x)+(1./24.)*xx2-(7.0/960.0)*xx4+(31.0/8064.0)*xx4*xx2-(127.0/30720.0)*xx4*xx4;
return result;
}
static inline double log_poisson(unsigned x, const double& lambda) {
assert(lambda > 0.0);
return std::log(lambda) * x - lgamma(x + 1) - lambda;
}
};
class TTable {
public:
TTable() : frozen_(false), probs_initialized_(false) {}
// typedef std::unordered_map<unsigned, double> Word2Double;
typedef std::vector<Word2Double> Word2Word2Double;
inline double prob(const unsigned e, const unsigned f) const {
return probs_initialized_ ? ttable[e].find(f)->second : 1e-9;
}
inline double safe_prob(const int& e, const int& f) const {
if (e < static_cast<int>(ttable.size())) {
const Word2Double& cpd = ttable[e];
const Word2Double::const_iterator it = cpd.find(f);
if (it == cpd.end()) return 1e-9;
return it->second;
} else {
return 1e-9;
}
}
inline void SetMaxE(const unsigned e) {
// NOT thread safe
if (e >= counts.size())
counts.resize(e + 1);
}
inline void Insert(const unsigned e, const unsigned f) {
// NOT thread safe
if (e >= counts.size())
counts.resize(e + 1);
counts[e][f] = 0;
}
inline void Increment(const unsigned e, const unsigned f, const double x) {
counts[e].find(f)->second += x; // Ignore race conditions here.
}
void NormalizeVB(const double alpha) {
ttable.swap(counts);
#pragma omp parallel for schedule(dynamic)
#ifndef _MSC_VER
for (unsigned i = 0; i < ttable.size(); ++i) {
#else
for (int i = 0; i < ttable.size(); ++i) { // MSVC only supports OpenMP 2.0, which doesn't allow signed types here
#endif
double tot = 0;
Word2Double& cpd = ttable[i];
for (Word2Double::iterator it = cpd.begin(); it != cpd.end(); ++it)
tot += it->second + alpha;
if (!tot) tot = 1;
const double digamma_tot = Md::digamma(tot);
for (Word2Double::iterator it = cpd.begin(); it != cpd.end(); ++it)
it->second = exp(Md::digamma(it->second + alpha) - digamma_tot);
}
ClearCounts();
probs_initialized_ = true;
}
void Normalize() {
ttable.swap(counts);
#pragma omp parallel for schedule(dynamic)
#ifndef _MSC_VER
for (unsigned i = 0; i < ttable.size(); ++i) {
#else
for (int i = 0; i < ttable.size(); ++i) {
#endif
double tot = 0;
Word2Double& cpd = ttable[i];
for (Word2Double::iterator it = cpd.begin(); it != cpd.end(); ++it)
tot += it->second;
if (!tot) tot = 1;
for (Word2Double::iterator it = cpd.begin(); it != cpd.end(); ++it)
it->second /= tot;
}
ClearCounts();
probs_initialized_ = true;
}
void Freeze() {
// duplicate all values in counts into ttable
// later updates to both are semi-threadsafe
assert (!frozen_);
if (!frozen_) {
ttable.resize(counts.size());
for (unsigned i = 0; i < counts.size(); ++i) {
ttable[i] = counts[i];
}
}
frozen_ = true;
}
// adds counts from another TTable - probabilities remain unchanged
TTable& operator+=(const TTable& rhs) {
if (rhs.counts.size() > counts.size()) counts.resize(rhs.counts.size());
for (unsigned i = 0; i < rhs.counts.size(); ++i) {
const Word2Double& cpd = rhs.counts[i];
Word2Double& tgt = counts[i];
for (Word2Double::const_iterator j = cpd.begin(); j != cpd.end(); ++j) {
tgt[j->first] += j->second;
}
}
return *this;
}
void ExportToFile(const char* filename, Dict& d, double BEAM_THRESHOLD) const {
std::ofstream file(filename);
for (unsigned i = 0; i < ttable.size(); ++i) {
const std::string& a = d.Convert(i);
const Word2Double& cpd = ttable[i];
double max_p = -1;
for (auto& it : cpd)
if (it.second > max_p) max_p = it.second;
const double threshold = - log(max_p) * BEAM_THRESHOLD;
for (auto& it : cpd) {
const std::string& b = d.Convert(it.first);
double c = log(it.second);
if (c >= threshold)
file << a << '\t' << b << '\t' << c << std::endl;
}
}
file.close();
}
private:
void ClearCounts() {
#pragma omp parallel for schedule(dynamic)
#ifndef _MSC_VER
for (size_t i=0; i<counts.size();++i) {
#else
for(int i = 0; i<counts.size(); ++i) {
#endif
for (auto& cnt : counts[i]) {
cnt.second = 0.0;
}
}
}
Word2Word2Double ttable;
Word2Word2Double counts;
bool frozen_; // Disallow new e,f pairs to be added to counts
bool probs_initialized_; // If we can use the values in probs
public:
void DeserializeLogProbsFromText(std::istream* in, Dict& d);
};
#endif
|
image.c
|
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% IIIII M M AAA GGGG EEEEE %
% I MM MM A A G E %
% I M M M AAAAA G GG EEE %
% I M M A A G G E %
% IIIII M M A A GGGG EEEEE %
% %
% %
% MagickCore Image Methods %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2014 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 "MagickCore/studio.h"
#include "MagickCore/animate.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-private.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/client.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/compress.h"
#include "MagickCore/constitute.h"
#include "MagickCore/display.h"
#include "MagickCore/draw.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/gem.h"
#include "MagickCore/geometry.h"
#include "MagickCore/histogram.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magic.h"
#include "MagickCore/magick.h"
#include "MagickCore/magick-private.h"
#include "MagickCore/memory_.h"
#include "MagickCore/module.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/paint.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/profile.h"
#include "MagickCore/property.h"
#include "MagickCore/quantize.h"
#include "MagickCore/random_.h"
#include "MagickCore/resource_.h"
#include "MagickCore/segment.h"
#include "MagickCore/semaphore.h"
#include "MagickCore/signature-private.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/timer.h"
#include "MagickCore/token.h"
#include "MagickCore/utility.h"
#include "MagickCore/utility-private.h"
#include "MagickCore/version.h"
#include "MagickCore/xwindow-private.h"
/*
Constant declaration.
*/
const char
BackgroundColor[] = "#ffffff", /* white */
BorderColor[] = "#dfdfdf", /* gray */
DefaultTileFrame[] = "15x15+3+3",
DefaultTileGeometry[] = "120x120+4+3>",
DefaultTileLabel[] = "%f\n%G\n%b",
ForegroundColor[] = "#000", /* black */
LoadImageTag[] = "Load/Image",
LoadImagesTag[] = "Load/Images",
MatteColor[] = "#bdbdbd", /* gray */
PSDensityGeometry[] = "72.0x72.0",
PSPageGeometry[] = "612x792",
SaveImageTag[] = "Save/Image",
SaveImagesTag[] = "Save/Images",
TransparentColor[] = "#00000000"; /* transparent black */
const double
DefaultResolution = 72.0;
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireImage() returns a pointer to an image structure initialized to
% default values.
%
% The format of the AcquireImage method is:
%
% Image *AcquireImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: Many of the image default values are set from this
% structure. For example, filename, compression, depth, background color,
% and others.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *AcquireImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
const char
*option;
Image
*image;
MagickStatusType
flags;
/*
Allocate image structure.
*/
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
image=(Image *) AcquireMagickMemory(sizeof(*image));
if (image == (Image *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) ResetMagickMemory(image,0,sizeof(*image));
/*
Initialize Image structure.
*/
(void) CopyMagickString(image->magick,"MIFF",MaxTextExtent);
image->storage_class=DirectClass;
image->depth=MAGICKCORE_QUANTUM_DEPTH;
image->colorspace=sRGBColorspace;
image->rendering_intent=PerceptualIntent;
image->gamma=1.000f/2.200f;
image->chromaticity.red_primary.x=0.6400f;
image->chromaticity.red_primary.y=0.3300f;
image->chromaticity.red_primary.z=0.0300f;
image->chromaticity.green_primary.x=0.3000f;
image->chromaticity.green_primary.y=0.6000f;
image->chromaticity.green_primary.z=0.1000f;
image->chromaticity.blue_primary.x=0.1500f;
image->chromaticity.blue_primary.y=0.0600f;
image->chromaticity.blue_primary.z=0.7900f;
image->chromaticity.white_point.x=0.3127f;
image->chromaticity.white_point.y=0.3290f;
image->chromaticity.white_point.z=0.3583f;
image->interlace=NoInterlace;
image->ticks_per_second=UndefinedTicksPerSecond;
image->compose=OverCompositeOp;
(void) QueryColorCompliance(BackgroundColor,AllCompliance,
&image->background_color,exception);
(void) QueryColorCompliance(BorderColor,AllCompliance,&image->border_color,
exception);
(void) QueryColorCompliance(MatteColor,AllCompliance,&image->matte_color,
exception);
(void) QueryColorCompliance(TransparentColor,AllCompliance,
&image->transparent_color,exception);
GetTimerInfo(&image->timer);
image->cache=AcquirePixelCache(0);
image->channel_mask=DefaultChannels;
image->channel_map=AcquirePixelChannelMap();
image->blob=CloneBlobInfo((BlobInfo *) NULL);
image->timestamp=time((time_t *) NULL);
image->debug=IsEventLogging();
image->reference_count=1;
image->semaphore=AcquireSemaphoreInfo();
image->signature=MagickSignature;
if (image_info == (ImageInfo *) NULL)
return(image);
/*
Transfer image info.
*/
SetBlobExempt(image,image_info->file != (FILE *) NULL ? MagickTrue :
MagickFalse);
(void) CopyMagickString(image->filename,image_info->filename,MaxTextExtent);
(void) CopyMagickString(image->magick_filename,image_info->filename,
MaxTextExtent);
(void) CopyMagickString(image->magick,image_info->magick,MaxTextExtent);
if (image_info->size != (char *) NULL)
{
(void) ParseAbsoluteGeometry(image_info->size,&image->extract_info);
image->columns=image->extract_info.width;
image->rows=image->extract_info.height;
image->offset=image->extract_info.x;
image->extract_info.x=0;
image->extract_info.y=0;
}
if (image_info->extract != (char *) NULL)
{
RectangleInfo
geometry;
flags=ParseAbsoluteGeometry(image_info->extract,&geometry);
if (((flags & XValue) != 0) || ((flags & YValue) != 0))
{
image->extract_info=geometry;
Swap(image->columns,image->extract_info.width);
Swap(image->rows,image->extract_info.height);
}
}
image->compression=image_info->compression;
image->quality=image_info->quality;
image->endian=image_info->endian;
image->interlace=image_info->interlace;
image->units=image_info->units;
if (image_info->density != (char *) NULL)
{
GeometryInfo
geometry_info;
flags=ParseGeometry(image_info->density,&geometry_info);
image->resolution.x=geometry_info.rho;
image->resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->resolution.y=image->resolution.x;
}
if (image_info->page != (char *) NULL)
{
char
*geometry;
image->page=image->extract_info;
geometry=GetPageGeometry(image_info->page);
(void) ParseAbsoluteGeometry(geometry,&image->page);
geometry=DestroyString(geometry);
}
if (image_info->depth != 0)
image->depth=image_info->depth;
image->dither=image_info->dither;
image->background_color=image_info->background_color;
image->border_color=image_info->border_color;
image->matte_color=image_info->matte_color;
image->transparent_color=image_info->transparent_color;
image->ping=image_info->ping;
image->progress_monitor=image_info->progress_monitor;
image->client_data=image_info->client_data;
if (image_info->cache != (void *) NULL)
ClonePixelCacheMethods(image->cache,image_info->cache);
/*
Set all global options that map to per-image settings.
*/
(void) SyncImageSettings(image_info,image,exception);
/*
Global options that are only set for new images.
*/
image->image_info=(ImageInfo *) NULL;
option=GetImageOption(image_info,"delay");
if (option != (const char *) NULL)
{
GeometryInfo
geometry_info;
flags=ParseGeometry(option,&geometry_info);
if ((flags & GreaterValue) != 0)
{
if (image->delay > (size_t) floor(geometry_info.rho+0.5))
image->delay=(size_t) floor(geometry_info.rho+0.5);
}
else
if ((flags & LessValue) != 0)
{
if (image->delay < (size_t) floor(geometry_info.rho+0.5))
image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5);
}
else
image->delay=(size_t) floor(geometry_info.rho+0.5);
if ((flags & SigmaValue) != 0)
image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5);
}
option=GetImageOption(image_info,"dispose");
if (option != (const char *) NULL)
image->dispose=(DisposeType) ParseCommandOption(MagickDisposeOptions,
MagickFalse,option);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e I m a g e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireImageInfo() allocates the ImageInfo structure.
%
% The format of the AcquireImageInfo method is:
%
% ImageInfo *AcquireImageInfo(void)
%
*/
MagickExport ImageInfo *AcquireImageInfo(void)
{
ImageInfo
*image_info;
image_info=(ImageInfo *) AcquireMagickMemory(sizeof(*image_info));
if (image_info == (ImageInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
GetImageInfo(image_info);
return(image_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e N e x t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireNextImage() initializes the next image in a sequence to
% default values. The next member of image points to the newly allocated
% image. If there is a memory shortage, next is assigned NULL.
%
% The format of the AcquireNextImage method is:
%
% void AcquireNextImage(const ImageInfo *image_info,Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: Many of the image default values are set from this
% structure. For example, filename, compression, depth, background color,
% and others.
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport void AcquireNextImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
/*
Allocate image structure.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
image->next=AcquireImage(image_info,exception);
if (GetNextImageInList(image) == (Image *) NULL)
return;
(void) CopyMagickString(GetNextImageInList(image)->filename,image->filename,
MaxTextExtent);
if (image_info != (ImageInfo *) NULL)
(void) CopyMagickString(GetNextImageInList(image)->filename,
image_info->filename,MaxTextExtent);
DestroyBlob(GetNextImageInList(image));
image->next->blob=ReferenceBlob(image->blob);
image->next->endian=image->endian;
image->next->scene=image->scene+1;
image->next->previous=image;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A p p e n d I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AppendImages() takes all images from the current image pointer to the end
% of the image list and appends them to each other top-to-bottom if the
% stack parameter is true, otherwise left-to-right.
%
% The current gravity setting effects how the image is justified in the
% final image.
%
% The format of the AppendImages method is:
%
% Image *AppendImages(const Image *images,const MagickBooleanType stack,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o images: the image sequence.
%
% o stack: A value other than 0 stacks the images top-to-bottom.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *AppendImages(const Image *images,
const MagickBooleanType stack,ExceptionInfo *exception)
{
#define AppendImageTag "Append/Image"
CacheView
*append_view;
Image
*append_image;
MagickBooleanType
status;
MagickOffsetType
n;
PixelTrait
alpha_trait;
RectangleInfo
geometry;
register const Image
*next;
size_t
height,
number_images,
width;
ssize_t
x_offset,
y,
y_offset;
/*
Compute maximum area of appended area.
*/
assert(images != (Image *) NULL);
assert(images->signature == MagickSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
alpha_trait=images->alpha_trait;
number_images=1;
width=images->columns;
height=images->rows;
next=GetNextImageInList(images);
for ( ; next != (Image *) NULL; next=GetNextImageInList(next))
{
if (next->alpha_trait == BlendPixelTrait)
alpha_trait=BlendPixelTrait;
number_images++;
if (stack != MagickFalse)
{
if (next->columns > width)
width=next->columns;
height+=next->rows;
continue;
}
width+=next->columns;
if (next->rows > height)
height=next->rows;
}
/*
Append images.
*/
append_image=CloneImage(images,width,height,MagickTrue,exception);
if (append_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(append_image,DirectClass,exception) == MagickFalse)
{
append_image=DestroyImage(append_image);
return((Image *) NULL);
}
append_image->alpha_trait=alpha_trait;
(void) SetImageBackgroundColor(append_image,exception);
status=MagickTrue;
x_offset=0;
y_offset=0;
next=images;
append_view=AcquireAuthenticCacheView(append_image,exception);
for (n=0; n < (MagickOffsetType) number_images; n++)
{
CacheView
*image_view;
Image
*image;
MagickBooleanType
proceed;
image=CloneImage(next,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
break;
(void) TransformImageColorspace(image,append_image->colorspace,exception);
SetGeometry(append_image,&geometry);
GravityAdjustGeometry(image->columns,image->rows,image->gravity,&geometry);
if (stack != MagickFalse)
x_offset-=geometry.x;
else
y_offset-=geometry.y;
image_view=AcquireVirtualCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
PixelInfo
pixel;
register const Quantum
*restrict p;
register Quantum
*restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(append_view,x_offset,y+y_offset,
image->columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
GetPixelInfo(image,&pixel);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelReadMask(image,p) == 0)
{
SetPixelBackgoundColor(append_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(append_image);
continue;
}
GetPixelInfoPixel(image,p,&pixel);
SetPixelInfoPixel(append_image,&pixel,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(append_image);
}
sync=SyncCacheViewAuthenticPixels(append_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (stack == MagickFalse)
{
x_offset+=(ssize_t) image->columns;
y_offset=0;
}
else
{
x_offset=0;
y_offset+=(ssize_t) image->rows;
}
image=DestroyImage(image);
proceed=SetImageProgress(append_image,AppendImageTag,n,number_images);
if (proceed == MagickFalse)
break;
next=GetNextImageInList(next);
}
append_view=DestroyCacheView(append_view);
if (status == MagickFalse)
append_image=DestroyImage(append_image);
return(append_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C a t c h I m a g e E x c e p t i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CatchImageException() returns if no exceptions are found in the image
% sequence, otherwise it determines the most severe exception and reports
% it as a warning or error depending on the severity.
%
% The format of the CatchImageException method is:
%
% ExceptionType CatchImageException(Image *image)
%
% A description of each parameter follows:
%
% o image: An image sequence.
%
*/
MagickExport ExceptionType CatchImageException(Image *image)
{
ExceptionInfo
*exception;
ExceptionType
severity;
assert(image != (const Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
exception=AcquireExceptionInfo();
CatchException(exception);
severity=exception->severity;
exception=DestroyExceptionInfo(exception);
return(severity);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l i p I m a g e P a t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClipImagePath() sets the image clip mask based any clipping path information
% if it exists.
%
% The format of the ClipImagePath method is:
%
% MagickBooleanType ClipImagePath(Image *image,const char *pathname,
% const MagickBooleanType inside,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o pathname: name of clipping path resource. If name is preceded by #, use
% clipping path numbered by name.
%
% o inside: if non-zero, later operations take effect inside clipping path.
% Otherwise later operations take effect outside clipping path.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ClipImage(Image *image,ExceptionInfo *exception)
{
return(ClipImagePath(image,"#1",MagickTrue,exception));
}
MagickExport MagickBooleanType ClipImagePath(Image *image,const char *pathname,
const MagickBooleanType inside,ExceptionInfo *exception)
{
#define ClipImagePathTag "ClipPath/Image"
char
*property;
const char
*value;
Image
*clip_mask;
ImageInfo
*image_info;
assert(image != (const Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(pathname != NULL);
property=AcquireString(pathname);
(void) FormatLocaleString(property,MaxTextExtent,"8BIM:1999,2998:%s",
pathname);
value=GetImageProperty(image,property,exception);
property=DestroyString(property);
if (value == (const char *) NULL)
{
ThrowFileException(exception,OptionError,"NoClipPathDefined",
image->filename);
return(MagickFalse);
}
image_info=AcquireImageInfo();
(void) CopyMagickString(image_info->filename,image->filename,MaxTextExtent);
(void) ConcatenateMagickString(image_info->filename,pathname,MaxTextExtent);
clip_mask=BlobToImage(image_info,value,strlen(value),exception);
image_info=DestroyImageInfo(image_info);
if (clip_mask == (Image *) NULL)
return(MagickFalse);
if (clip_mask->storage_class == PseudoClass)
{
(void) SyncImage(clip_mask,exception);
if (SetImageStorageClass(clip_mask,DirectClass,exception) == MagickFalse)
return(MagickFalse);
}
if (inside == MagickFalse)
(void) NegateImage(clip_mask,MagickFalse,exception);
(void) FormatLocaleString(clip_mask->magick_filename,MaxTextExtent,
"8BIM:1999,2998:%s\nPS",pathname);
(void) SetImageMask(image,clip_mask,exception);
clip_mask=DestroyImage(clip_mask);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneImage() copies an image and returns the copy as a new image object.
%
% If the specified columns and rows is 0, an exact copy of the image is
% returned, otherwise the pixel data is undefined and must be initialized
% with the QueueAuthenticPixels() and SyncAuthenticPixels() methods. On
% failure, a NULL image is returned and exception describes the reason for the
% failure.
%
% The format of the CloneImage method is:
%
% Image *CloneImage(const Image *image,const size_t columns,
% const size_t rows,const MagickBooleanType orphan,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o columns: the number of columns in the cloned image.
%
% o rows: the number of rows in the cloned image.
%
% o detach: With a value other than 0, the cloned image is detached from
% its parent I/O stream.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *CloneImage(const Image *image,const size_t columns,
const size_t rows,const MagickBooleanType detach,ExceptionInfo *exception)
{
Image
*clone_image;
double
scale;
size_t
length;
/*
Clone the image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
clone_image=(Image *) AcquireMagickMemory(sizeof(*clone_image));
if (clone_image == (Image *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(clone_image,0,sizeof(*clone_image));
clone_image->signature=MagickSignature;
clone_image->storage_class=image->storage_class;
clone_image->number_channels=image->number_channels;
clone_image->number_meta_channels=image->number_meta_channels;
clone_image->metacontent_extent=image->metacontent_extent;
clone_image->colorspace=image->colorspace;
clone_image->read_mask=image->read_mask;
clone_image->write_mask=image->write_mask;
clone_image->alpha_trait=image->alpha_trait;
clone_image->columns=image->columns;
clone_image->rows=image->rows;
clone_image->dither=image->dither;
if (image->colormap != (PixelInfo *) NULL)
{
/*
Allocate and copy the image colormap.
*/
clone_image->colors=image->colors;
length=(size_t) image->colors;
clone_image->colormap=(PixelInfo *) AcquireQuantumMemory(length,
sizeof(*clone_image->colormap));
if (clone_image->colormap == (PixelInfo *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
(void) CopyMagickMemory(clone_image->colormap,image->colormap,length*
sizeof(*clone_image->colormap));
}
(void) CloneImageProfiles(clone_image,image);
(void) CloneImageProperties(clone_image,image);
(void) CloneImageArtifacts(clone_image,image);
GetTimerInfo(&clone_image->timer);
if (image->ascii85 != (void *) NULL)
Ascii85Initialize(clone_image);
clone_image->magick_columns=image->magick_columns;
clone_image->magick_rows=image->magick_rows;
clone_image->type=image->type;
clone_image->channel_mask=image->channel_mask;
clone_image->channel_map=ClonePixelChannelMap(image->channel_map);
(void) CopyMagickString(clone_image->magick_filename,image->magick_filename,
MaxTextExtent);
(void) CopyMagickString(clone_image->magick,image->magick,MaxTextExtent);
(void) CopyMagickString(clone_image->filename,image->filename,MaxTextExtent);
clone_image->progress_monitor=image->progress_monitor;
clone_image->client_data=image->client_data;
clone_image->reference_count=1;
clone_image->next=image->next;
clone_image->previous=image->previous;
clone_image->list=NewImageList();
if (detach == MagickFalse)
clone_image->blob=ReferenceBlob(image->blob);
else
{
clone_image->next=NewImageList();
clone_image->previous=NewImageList();
clone_image->blob=CloneBlobInfo((BlobInfo *) NULL);
}
clone_image->ping=image->ping;
clone_image->debug=IsEventLogging();
clone_image->semaphore=AcquireSemaphoreInfo();
if ((columns == 0) || (rows == 0))
{
if (image->montage != (char *) NULL)
(void) CloneString(&clone_image->montage,image->montage);
if (image->directory != (char *) NULL)
(void) CloneString(&clone_image->directory,image->directory);
clone_image->cache=ReferencePixelCache(image->cache);
return(clone_image);
}
scale=1.0;
if (image->columns != 0)
scale=(double) columns/(double) image->columns;
clone_image->page.width=(size_t) floor(scale*image->page.width+0.5);
clone_image->page.x=(ssize_t) ceil(scale*image->page.x-0.5);
clone_image->tile_offset.x=(ssize_t) ceil(scale*image->tile_offset.x-0.5);
scale=1.0;
if (image->rows != 0)
scale=(double) rows/(double) image->rows;
clone_image->page.height=(size_t) floor(scale*image->page.height+0.5);
clone_image->page.y=(ssize_t) ceil(scale*image->page.y-0.5);
clone_image->tile_offset.y=(ssize_t) ceil(scale*image->tile_offset.y-0.5);
clone_image->columns=columns;
clone_image->rows=rows;
clone_image->cache=ClonePixelCache(image->cache);
return(clone_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e I m a g e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneImageInfo() makes a copy of the given image info structure. If
% NULL is specified, a new image info structure is created initialized to
% default values.
%
% The format of the CloneImageInfo method is:
%
% ImageInfo *CloneImageInfo(const ImageInfo *image_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
*/
MagickExport ImageInfo *CloneImageInfo(const ImageInfo *image_info)
{
ImageInfo
*clone_info;
clone_info=AcquireImageInfo();
if (image_info == (ImageInfo *) NULL)
return(clone_info);
clone_info->compression=image_info->compression;
clone_info->temporary=image_info->temporary;
clone_info->adjoin=image_info->adjoin;
clone_info->antialias=image_info->antialias;
clone_info->scene=image_info->scene;
clone_info->number_scenes=image_info->number_scenes;
clone_info->depth=image_info->depth;
(void) CloneString(&clone_info->size,image_info->size);
(void) CloneString(&clone_info->extract,image_info->extract);
(void) CloneString(&clone_info->scenes,image_info->scenes);
(void) CloneString(&clone_info->page,image_info->page);
clone_info->interlace=image_info->interlace;
clone_info->endian=image_info->endian;
clone_info->units=image_info->units;
clone_info->quality=image_info->quality;
(void) CloneString(&clone_info->sampling_factor,image_info->sampling_factor);
(void) CloneString(&clone_info->server_name,image_info->server_name);
(void) CloneString(&clone_info->font,image_info->font);
(void) CloneString(&clone_info->texture,image_info->texture);
(void) CloneString(&clone_info->density,image_info->density);
clone_info->pointsize=image_info->pointsize;
clone_info->fuzz=image_info->fuzz;
clone_info->background_color=image_info->background_color;
clone_info->border_color=image_info->border_color;
clone_info->matte_color=image_info->matte_color;
clone_info->transparent_color=image_info->transparent_color;
clone_info->dither=image_info->dither;
clone_info->monochrome=image_info->monochrome;
clone_info->colorspace=image_info->colorspace;
clone_info->type=image_info->type;
clone_info->orientation=image_info->orientation;
clone_info->preview_type=image_info->preview_type;
clone_info->group=image_info->group;
clone_info->ping=image_info->ping;
clone_info->verbose=image_info->verbose;
(void) CloneString(&clone_info->view,image_info->view);
clone_info->progress_monitor=image_info->progress_monitor;
clone_info->client_data=image_info->client_data;
clone_info->cache=image_info->cache;
if (image_info->cache != (void *) NULL)
clone_info->cache=ReferencePixelCache(image_info->cache);
if (image_info->profile != (void *) NULL)
clone_info->profile=(void *) CloneStringInfo((StringInfo *)
image_info->profile);
SetImageInfoFile(clone_info,image_info->file);
SetImageInfoBlob(clone_info,image_info->blob,image_info->length);
clone_info->stream=image_info->stream;
(void) CopyMagickString(clone_info->magick,image_info->magick,MaxTextExtent);
(void) CopyMagickString(clone_info->unique,image_info->unique,MaxTextExtent);
(void) CopyMagickString(clone_info->zero,image_info->zero,MaxTextExtent);
(void) CopyMagickString(clone_info->filename,image_info->filename,
MaxTextExtent);
clone_info->channel=image_info->channel;
(void) CloneImageOptions(clone_info,image_info);
clone_info->debug=IsEventLogging();
clone_info->signature=image_info->signature;
return(clone_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyImage() dereferences an image, deallocating memory associated with
% the image if the reference count becomes zero.
%
% The format of the DestroyImage method is:
%
% Image *DestroyImage(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport Image *DestroyImage(Image *image)
{
MagickBooleanType
destroy;
/*
Dereference image.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
destroy=MagickFalse;
LockSemaphoreInfo(image->semaphore);
image->reference_count--;
if (image->reference_count == 0)
destroy=MagickTrue;
UnlockSemaphoreInfo(image->semaphore);
if (destroy == MagickFalse)
return((Image *) NULL);
/*
Destroy image.
*/
DestroyImagePixels(image);
image->channel_map=DestroyPixelChannelMap(image->channel_map);
if (image->montage != (char *) NULL)
image->montage=DestroyString(image->montage);
if (image->directory != (char *) NULL)
image->directory=DestroyString(image->directory);
if (image->colormap != (PixelInfo *) NULL)
image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap);
if (image->geometry != (char *) NULL)
image->geometry=DestroyString(image->geometry);
DestroyImageProfiles(image);
DestroyImageProperties(image);
DestroyImageArtifacts(image);
if (image->ascii85 != (Ascii85Info*) NULL)
image->ascii85=(Ascii85Info *) RelinquishMagickMemory(image->ascii85);
DestroyBlob(image);
if (image->semaphore != (SemaphoreInfo *) NULL)
RelinquishSemaphoreInfo(&image->semaphore);
image->signature=(~MagickSignature);
image=(Image *) RelinquishMagickMemory(image);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y I m a g e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyImageInfo() deallocates memory associated with an ImageInfo
% structure.
%
% The format of the DestroyImageInfo method is:
%
% ImageInfo *DestroyImageInfo(ImageInfo *image_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
*/
MagickExport ImageInfo *DestroyImageInfo(ImageInfo *image_info)
{
assert(image_info != (ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
if (image_info->size != (char *) NULL)
image_info->size=DestroyString(image_info->size);
if (image_info->extract != (char *) NULL)
image_info->extract=DestroyString(image_info->extract);
if (image_info->scenes != (char *) NULL)
image_info->scenes=DestroyString(image_info->scenes);
if (image_info->page != (char *) NULL)
image_info->page=DestroyString(image_info->page);
if (image_info->sampling_factor != (char *) NULL)
image_info->sampling_factor=DestroyString(
image_info->sampling_factor);
if (image_info->server_name != (char *) NULL)
image_info->server_name=DestroyString(
image_info->server_name);
if (image_info->font != (char *) NULL)
image_info->font=DestroyString(image_info->font);
if (image_info->texture != (char *) NULL)
image_info->texture=DestroyString(image_info->texture);
if (image_info->density != (char *) NULL)
image_info->density=DestroyString(image_info->density);
if (image_info->view != (char *) NULL)
image_info->view=DestroyString(image_info->view);
if (image_info->cache != (void *) NULL)
image_info->cache=DestroyPixelCache(image_info->cache);
if (image_info->profile != (StringInfo *) NULL)
image_info->profile=(void *) DestroyStringInfo((StringInfo *)
image_info->profile);
DestroyImageOptions(image_info);
image_info->signature=(~MagickSignature);
image_info=(ImageInfo *) RelinquishMagickMemory(image_info);
return(image_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D i s a s s o c i a t e I m a g e S t r e a m %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DisassociateImageStream() disassociates the image stream. It checks if the
% blob of the specified image is referenced by other images. If the reference
% count is higher then 1 a new blob is assigned to the specified image.
%
% The format of the DisassociateImageStream method is:
%
% void DisassociateImageStream(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport void DisassociateImageStream(Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
DisassociateBlob(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageInfo() initializes image_info to default values.
%
% The format of the GetImageInfo method is:
%
% void GetImageInfo(ImageInfo *image_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
*/
MagickExport void GetImageInfo(ImageInfo *image_info)
{
char
*synchronize;
ExceptionInfo
*exception;
/*
File and image dimension members.
*/
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image_info != (ImageInfo *) NULL);
(void) ResetMagickMemory(image_info,0,sizeof(*image_info));
image_info->adjoin=MagickTrue;
image_info->interlace=NoInterlace;
image_info->channel=DefaultChannels;
image_info->quality=UndefinedCompressionQuality;
image_info->antialias=MagickTrue;
image_info->dither=MagickTrue;
synchronize=GetEnvironmentValue("MAGICK_SYNCHRONIZE");
if (synchronize != (const char *) NULL)
{
image_info->synchronize=IsStringTrue(synchronize);
synchronize=DestroyString(synchronize);
}
exception=AcquireExceptionInfo();
(void) QueryColorCompliance(BackgroundColor,AllCompliance,
&image_info->background_color,exception);
(void) QueryColorCompliance(BorderColor,AllCompliance,
&image_info->border_color,exception);
(void) QueryColorCompliance(MatteColor,AllCompliance,&image_info->matte_color,
exception);
(void) QueryColorCompliance(TransparentColor,AllCompliance,
&image_info->transparent_color,exception);
exception=DestroyExceptionInfo(exception);
image_info->debug=IsEventLogging();
image_info->signature=MagickSignature;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e I n f o F i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageInfoFile() returns the image info file member.
%
% The format of the GetImageInfoFile method is:
%
% FILE *GetImageInfoFile(const ImageInfo *image_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
*/
MagickExport FILE *GetImageInfoFile(const ImageInfo *image_info)
{
return(image_info->file);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e M a s k %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageMask() returns the mask associated with the image.
%
% The format of the GetImageMask method is:
%
% Image *GetImageMask(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport Image *GetImageMask(const Image *image,ExceptionInfo *exception)
{
CacheView
*mask_view,
*image_view;
Image
*mask_image;
MagickBooleanType
status;
ssize_t
y;
/*
Get image mask.
*/
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickSignature);
mask_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
if (mask_image == (Image *) NULL)
return((Image *) NULL);
status=MagickTrue;
(void) SetImageColorspace(mask_image,GRAYColorspace,exception);
mask_image->read_mask=MagickFalse;
image_view=AcquireVirtualCacheView(image,exception);
mask_view=AcquireAuthenticCacheView(mask_image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*restrict p;
register Quantum
*restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(mask_view,0,y,mask_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelGray(mask_image,GetPixelReadMask(image,p),q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(mask_image);
}
if (SyncCacheViewAuthenticPixels(mask_view,exception) == MagickFalse)
status=MagickFalse;
}
mask_view=DestroyCacheView(mask_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
mask_image=DestroyImage(mask_image);
return(mask_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t I m a g e R e f e r e n c e C o u n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageReferenceCount() returns the image reference count.
%
% The format of the GetReferenceCount method is:
%
% ssize_t GetImageReferenceCount(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport ssize_t GetImageReferenceCount(Image *image)
{
ssize_t
reference_count;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
LockSemaphoreInfo(image->semaphore);
reference_count=image->reference_count;
UnlockSemaphoreInfo(image->semaphore);
return(reference_count);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e V i r t u a l P i x e l M e t h o d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageVirtualPixelMethod() gets the "virtual pixels" method for the
% image. A virtual pixel is any pixel access that is outside the boundaries
% of the image cache.
%
% The format of the GetImageVirtualPixelMethod() method is:
%
% VirtualPixelMethod GetImageVirtualPixelMethod(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport VirtualPixelMethod GetImageVirtualPixelMethod(const Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
return(GetPixelCacheVirtualMethod(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I n t e r p r e t I m a g e F i l e n a m e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InterpretImageFilename() interprets embedded characters in an image filename.
% The filename length is returned.
%
% The format of the InterpretImageFilename method is:
%
% size_t InterpretImageFilename(const ImageInfo *image_info,Image *image,
% const char *format,int value,char *filename,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image_info: the image info..
%
% o image: the image.
%
% o format: A filename describing the format to use to write the numeric
% argument. Only the first numeric format identifier is replaced.
%
% o value: Numeric value to substitute into format filename.
%
% o filename: return the formatted filename in this character buffer.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport size_t InterpretImageFilename(const ImageInfo *image_info,
Image *image,const char *format,int value,char *filename,
ExceptionInfo *exception)
{
char
*q;
int
c;
MagickBooleanType
canonical;
register const char
*p;
size_t
length;
canonical=MagickFalse;
length=0;
(void) CopyMagickString(filename,format,MaxTextExtent);
for (p=strchr(format,'%'); p != (char *) NULL; p=strchr(p+1,'%'))
{
q=(char *) p+1;
if (*q == '%')
{
p=q+1;
continue;
}
if (*q == '0')
{
ssize_t
value;
value=(ssize_t) strtol(q,&q,10);
(void) value;
}
switch (*q)
{
case 'd':
case 'o':
case 'x':
{
q++;
c=(*q);
*q='\0';
(void) FormatLocaleString(filename+(p-format),(size_t) (MaxTextExtent-
(p-format)),p,value);
*q=c;
(void) ConcatenateMagickString(filename,q,MaxTextExtent);
canonical=MagickTrue;
if (*(q-1) != '%')
break;
p++;
break;
}
case '[':
{
char
pattern[MaxTextExtent];
const char
*value;
register char
*r;
register ssize_t
i;
ssize_t
depth;
/*
Image option.
*/
/* FUTURE: Compare update with code from InterpretImageProperties()
Note that a 'filename:' property should not need depth recursion.
*/
if (strchr(p,']') == (char *) NULL)
break;
depth=1;
r=q+1;
for (i=0; (i < (MaxTextExtent-1L)) && (*r != '\0'); i++)
{
if (*r == '[')
depth++;
if (*r == ']')
depth--;
if (depth <= 0)
break;
pattern[i]=(*r++);
}
pattern[i]='\0';
if (LocaleNCompare(pattern,"filename:",9) != 0)
break;
value=(const char *) NULL;
#if 0
// FUTURE: remove this code. -- Anthony 29 Arpil 2012
// Removed as GetMagickProperty() will will never match a "filename:"
// string as this is not a 'known' image property.
//
if ((image_info != (const ImageInfo *) NULL) &&
(image != (const Image *) NULL))
value=GetMagickProperty(image_info,image,pattern,exception);
else
#endif
if (image != (Image *) NULL)
value=GetImageProperty(image,pattern,exception);
if ((value == (const char *) NULL) && (image != (Image *) NULL))
value=GetImageArtifact(image,pattern);
if ((value == (const char *) NULL) &&
(image_info != (ImageInfo *) NULL))
value=GetImageOption(image_info,pattern);
if (value == (const char *) NULL)
break;
q--;
c=(*q);
*q='\0';
(void) CopyMagickString(filename+(p-format-length),value,(size_t)
(MaxTextExtent-(p-format-length)));
length+=strlen(pattern)-1;
*q=c;
(void) ConcatenateMagickString(filename,r+1,MaxTextExtent);
canonical=MagickTrue;
if (*(q-1) != '%')
break;
p++;
break;
}
default:
break;
}
}
for (q=filename; *q != '\0'; q++)
if ((*q == '%') && (*(q+1) == '%'))
{
(void) CopyMagickString(q,q+1,(size_t) (MaxTextExtent-(q-filename)));
canonical=MagickTrue;
}
if (canonical == MagickFalse)
(void) CopyMagickString(filename,format,MaxTextExtent);
return(strlen(filename));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s H i g h D y n a m i c R a n g e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsHighDynamicRangeImage() returns MagickTrue if any pixel component is
% non-integer or exceeds the bounds of the quantum depth (e.g. for Q16
% 0..65535.
%
% The format of the IsHighDynamicRangeImage method is:
%
% MagickBooleanType IsHighDynamicRangeImage(const Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType IsHighDynamicRangeImage(const Image *image,
ExceptionInfo *exception)
{
#if !defined(MAGICKCORE_HDRI_SUPPORT)
(void) image;
(void) exception;
return(MagickFalse);
#else
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=MagickTrue;
image_view=AcquireVirtualCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*p;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,p) == 0)
{
p+=GetPixelChannels(image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
pixel;
PixelTrait
traits;
traits=GetPixelChannelTraits(image,(PixelChannel) i);
if (traits == UndefinedPixelTrait)
continue;
pixel=(double) p[i];
if ((pixel < 0.0) || (pixel > QuantumRange) ||
(pixel != (double) ((QuantumAny) pixel)))
break;
}
p+=GetPixelChannels(image);
if (i < (ssize_t) GetPixelChannels(image))
status=MagickFalse;
}
if (x < (ssize_t) image->columns)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status != MagickFalse ? MagickFalse : MagickTrue);
#endif
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s I m a g e O b j e c t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsImageObject() returns MagickTrue if the image sequence contains a valid
% set of image objects.
%
% The format of the IsImageObject method is:
%
% MagickBooleanType IsImageObject(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport MagickBooleanType IsImageObject(const Image *image)
{
register const Image
*p;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
for (p=image; p != (Image *) NULL; p=GetNextImageInList(p))
if (p->signature != MagickSignature)
return(MagickFalse);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s T a i n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsTaintImage() returns MagickTrue any pixel in the image has been altered
% since it was first constituted.
%
% The format of the IsTaintImage method is:
%
% MagickBooleanType IsTaintImage(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport MagickBooleanType IsTaintImage(const Image *image)
{
char
magick[MaxTextExtent],
filename[MaxTextExtent];
register const Image
*p;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickSignature);
(void) CopyMagickString(magick,image->magick,MaxTextExtent);
(void) CopyMagickString(filename,image->filename,MaxTextExtent);
for (p=image; p != (Image *) NULL; p=GetNextImageInList(p))
{
if (p->taint != MagickFalse)
return(MagickTrue);
if (LocaleCompare(p->magick,magick) != 0)
return(MagickTrue);
if (LocaleCompare(p->filename,filename) != 0)
return(MagickTrue);
}
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M o d i f y I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ModifyImage() ensures that there is only a single reference to the image
% to be modified, updating the provided image pointer to point to a clone of
% the original image if necessary.
%
% The format of the ModifyImage method is:
%
% MagickBooleanType ModifyImage(Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ModifyImage(Image **image,
ExceptionInfo *exception)
{
Image
*clone_image;
assert(image != (Image **) NULL);
assert(*image != (Image *) NULL);
assert((*image)->signature == MagickSignature);
if ((*image)->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*image)->filename);
if (GetImageReferenceCount(*image) <= 1)
return(MagickTrue);
clone_image=CloneImage(*image,0,0,MagickTrue,exception);
LockSemaphoreInfo((*image)->semaphore);
(*image)->reference_count--;
UnlockSemaphoreInfo((*image)->semaphore);
*image=clone_image;
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% N e w M a g i c k I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% NewMagickImage() creates a blank image canvas of the specified size and
% background color.
%
% The format of the NewMagickImage method is:
%
% Image *NewMagickImage(const ImageInfo *image_info,const size_t width,
% const size_t height,const PixelInfo *background,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o width: the image width.
%
% o height: the image height.
%
% o background: the image color.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *NewMagickImage(const ImageInfo *image_info,
const size_t width,const size_t height,const PixelInfo *background,
ExceptionInfo *exception)
{
CacheView
*image_view;
Image
*image;
MagickBooleanType
status;
ssize_t
y;
assert(image_info != (const ImageInfo *) NULL);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image_info->signature == MagickSignature);
assert(background != (const PixelInfo *) NULL);
image=AcquireImage(image_info,exception);
image->columns=width;
image->rows=height;
image->colorspace=background->colorspace;
image->alpha_trait=background->alpha_trait;
image->fuzz=background->fuzz;
image->depth=background->depth;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelInfoPixel(image,background,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
image=DestroyImage(image);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e f e r e n c e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReferenceImage() increments the reference count associated with an image
% returning a pointer to the image.
%
% The format of the ReferenceImage method is:
%
% Image *ReferenceImage(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport Image *ReferenceImage(Image *image)
{
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickSignature);
LockSemaphoreInfo(image->semaphore);
image->reference_count++;
UnlockSemaphoreInfo(image->semaphore);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s e t I m a g e P a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResetImagePage() resets the image page canvas and position.
%
% The format of the ResetImagePage method is:
%
% MagickBooleanType ResetImagePage(Image *image,const char *page)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o page: the relative page specification.
%
*/
MagickExport MagickBooleanType ResetImagePage(Image *image,const char *page)
{
MagickStatusType
flags;
RectangleInfo
geometry;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
flags=ParseAbsoluteGeometry(page,&geometry);
if ((flags & WidthValue) != 0)
{
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
image->page.width=geometry.width;
image->page.height=geometry.height;
}
if ((flags & AspectValue) != 0)
{
if ((flags & XValue) != 0)
image->page.x+=geometry.x;
if ((flags & YValue) != 0)
image->page.y+=geometry.y;
}
else
{
if ((flags & XValue) != 0)
{
image->page.x=geometry.x;
if ((image->page.width == 0) && (geometry.x > 0))
image->page.width=image->columns+geometry.x;
}
if ((flags & YValue) != 0)
{
image->page.y=geometry.y;
if ((image->page.height == 0) && (geometry.y > 0))
image->page.height=image->rows+geometry.y;
}
}
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e B a c k g r o u n d C o l o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageBackgroundColor() initializes the image pixels to the image
% background color. The background color is defined by the background_color
% member of the image structure.
%
% The format of the SetImage method is:
%
% MagickBooleanType SetImageBackgroundColor(Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageBackgroundColor(Image *image,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickSignature);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if ((IsPixelInfoGray(&image->background_color) == MagickFalse) &&
(IsGrayColorspace(image->colorspace) != MagickFalse))
(void) TransformImageColorspace(image,sRGBColorspace,exception);
if ((image->background_color.alpha_trait == BlendPixelTrait) &&
(image->alpha_trait != BlendPixelTrait))
(void) SetImageAlpha(image,OpaqueAlpha,exception);
/*
Set image background color.
*/
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelInfoPixel(image,&image->background_color,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e C h a n n e l M a s k %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageChannelMask() sets the image channel mask from the specified channel
% mask.
%
% The format of the SetImageChannelMask method is:
%
% ChannelType SetImageChannelMask(Image *image,
% const ChannelType channel_mask)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel_mask: the channel mask.
%
*/
MagickExport ChannelType SetImageChannelMask(Image *image,
const ChannelType channel_mask)
{
ChannelType
mask;
mask=image->channel_mask;
image->channel_mask=channel_mask;
SetPixelChannelMask(image,channel_mask);
return(mask);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e C o l o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageColor() set the entire image canvas to the specified color.
%
% The format of the SetImageColor method is:
%
% MagickBooleanType SetImageColor(Image *image,const PixelInfo *color,
% ExeptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o background: the image color.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageColor(Image *image,
const PixelInfo *color,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickSignature);
assert(color != (const PixelInfo *) NULL);
image->colorspace=color->colorspace;
image->alpha_trait=color->alpha_trait;
image->fuzz=color->fuzz;
image->depth=color->depth;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelInfoPixel(image,color,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e S t o r a g e C l a s s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageStorageClass() sets the image class: DirectClass for true color
% images or PseudoClass for colormapped images.
%
% The format of the SetImageStorageClass method is:
%
% MagickBooleanType SetImageStorageClass(Image *image,
% const ClassType storage_class,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o storage_class: The image class.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageStorageClass(Image *image,
const ClassType storage_class,ExceptionInfo *exception)
{
image->storage_class=storage_class;
return(SyncImagePixelCache(image,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e E x t e n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageExtent() sets the image size (i.e. columns & rows).
%
% The format of the SetImageExtent method is:
%
% MagickBooleanType SetImageExtent(Image *image,const size_t columns,
% const size_t rows,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o columns: The image width in pixels.
%
% o rows: The image height in pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageExtent(Image *image,const size_t columns,
const size_t rows,ExceptionInfo *exception)
{
if ((columns == 0) || (rows == 0))
return(MagickFalse);
image->columns=columns;
image->rows=rows;
return(SyncImagePixelCache(image,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ S e t I m a g e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageInfo() initializes the 'magick' field of the ImageInfo structure.
% It is set to a type of image format based on the prefix or suffix of the
% filename. For example, 'ps:image' returns PS indicating a Postscript image.
% JPEG is returned for this filename: 'image.jpg'. The filename prefix has
% precendence over the suffix. Use an optional index enclosed in brackets
% after a file name to specify a desired scene of a multi-resolution image
% format like Photo CD (e.g. img0001.pcd[4]). A True (non-zero) return value
% indicates success.
%
% The format of the SetImageInfo method is:
%
% MagickBooleanType SetImageInfo(ImageInfo *image_info,
% const unsigned int frames,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o frames: the number of images you intend to write.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageInfo(ImageInfo *image_info,
const unsigned int frames,ExceptionInfo *exception)
{
char
extension[MaxTextExtent],
filename[MaxTextExtent],
magic[MaxTextExtent],
*q,
subimage[MaxTextExtent];
const MagicInfo
*magic_info;
const MagickInfo
*magick_info;
ExceptionInfo
*sans_exception;
Image
*image;
MagickBooleanType
status;
register const char
*p;
ssize_t
count;
unsigned char
magick[2*MaxTextExtent];
/*
Look for 'image.format' in filename.
*/
assert(image_info != (ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
*subimage='\0';
GetPathComponent(image_info->filename,SubimagePath,subimage);
if (*subimage != '\0')
{
/*
Look for scene specification (e.g. img0001.pcd[4]).
*/
if (IsSceneGeometry(subimage,MagickFalse) == MagickFalse)
{
if (IsGeometry(subimage) != MagickFalse)
(void) CloneString(&image_info->extract,subimage);
}
else
{
size_t
first,
last;
(void) CloneString(&image_info->scenes,subimage);
image_info->scene=StringToUnsignedLong(image_info->scenes);
image_info->number_scenes=image_info->scene;
p=image_info->scenes;
for (q=(char *) image_info->scenes; *q != '\0'; p++)
{
while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ','))
p++;
first=(size_t) strtol(p,&q,10);
last=first;
while (isspace((int) ((unsigned char) *q)) != 0)
q++;
if (*q == '-')
last=(size_t) strtol(q+1,&q,10);
if (first > last)
Swap(first,last);
if (first < image_info->scene)
image_info->scene=first;
if (last > image_info->number_scenes)
image_info->number_scenes=last;
p=q;
}
image_info->number_scenes-=image_info->scene-1;
}
}
*extension='\0';
GetPathComponent(image_info->filename,ExtensionPath,extension);
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (*extension != '\0')
if ((LocaleCompare(extension,"gz") == 0) ||
(LocaleCompare(extension,"Z") == 0) ||
(LocaleCompare(extension,"svgz") == 0) ||
(LocaleCompare(extension,"wmz") == 0))
{
char
path[MaxTextExtent];
(void) CopyMagickString(path,image_info->filename,MaxTextExtent);
path[strlen(path)-strlen(extension)-1]='\0';
GetPathComponent(path,ExtensionPath,extension);
}
#endif
#if defined(MAGICKCORE_BZLIB_DELEGATE)
if (*extension != '\0')
if (LocaleCompare(extension,"bz2") == 0)
{
char
path[MaxTextExtent];
(void) CopyMagickString(path,image_info->filename,MaxTextExtent);
path[strlen(path)-strlen(extension)-1]='\0';
GetPathComponent(path,ExtensionPath,extension);
}
#endif
image_info->affirm=MagickFalse;
sans_exception=AcquireExceptionInfo();
if (*extension != '\0')
{
MagickFormatType
format_type;
register ssize_t
i;
static const char
*format_type_formats[] =
{
"AUTOTRACE",
"BROWSE",
"DCRAW",
"EDIT",
"EPHEMERAL",
"LAUNCH",
"MPEG:DECODE",
"MPEG:ENCODE",
"PRINT",
"PS:ALPHA",
"PS:CMYK",
"PS:COLOR",
"PS:GRAY",
"PS:MONO",
"SCAN",
"SHOW",
"WIN",
(char *) NULL
};
/*
User specified image format.
*/
(void) CopyMagickString(magic,extension,MaxTextExtent);
LocaleUpper(magic);
/*
Look for explicit image formats.
*/
format_type=UndefinedFormatType;
i=0;
while ((format_type == UndefinedFormatType) &&
(format_type_formats[i] != (char *) NULL))
{
if ((*magic == *format_type_formats[i]) &&
(LocaleCompare(magic,format_type_formats[i]) == 0))
format_type=ExplicitFormatType;
i++;
}
magick_info=GetMagickInfo(magic,sans_exception);
if ((magick_info != (const MagickInfo *) NULL) &&
(magick_info->format_type != UndefinedFormatType))
format_type=magick_info->format_type;
if (format_type == UndefinedFormatType)
(void) CopyMagickString(image_info->magick,magic,MaxTextExtent);
else
if (format_type == ExplicitFormatType)
{
image_info->affirm=MagickTrue;
(void) CopyMagickString(image_info->magick,magic,MaxTextExtent);
}
if (LocaleCompare(magic,"RGB") == 0)
image_info->affirm=MagickFalse; /* maybe SGI disguised as RGB */
}
/*
Look for explicit 'format:image' in filename.
*/
*magic='\0';
GetPathComponent(image_info->filename,MagickPath,magic);
if (*magic == '\0')
(void) CopyMagickString(magic,image_info->magick,MaxTextExtent);
else
{
/*
User specified image format.
*/
LocaleUpper(magic);
if (IsMagickConflict(magic) == MagickFalse)
{
(void) CopyMagickString(image_info->magick,magic,MaxTextExtent);
if (LocaleCompare(magic,"EPHEMERAL") != 0)
image_info->affirm=MagickTrue;
else
image_info->temporary=MagickTrue;
}
}
magick_info=GetMagickInfo(magic,sans_exception);
sans_exception=DestroyExceptionInfo(sans_exception);
if ((magick_info == (const MagickInfo *) NULL) ||
(GetMagickEndianSupport(magick_info) == MagickFalse))
image_info->endian=UndefinedEndian;
GetPathComponent(image_info->filename,CanonicalPath,filename);
(void) CopyMagickString(image_info->filename,filename,MaxTextExtent);
if ((image_info->adjoin != MagickFalse) && (frames > 1))
{
/*
Test for multiple image support (e.g. image%02d.png).
*/
(void) InterpretImageFilename(image_info,(Image *) NULL,
image_info->filename,(int) image_info->scene,filename,exception);
if ((LocaleCompare(filename,image_info->filename) != 0) &&
(strchr(filename,'%') == (char *) NULL))
image_info->adjoin=MagickFalse;
}
if ((image_info->adjoin != MagickFalse) && (frames > 0))
{
/*
Some image formats do not support multiple frames per file.
*/
magick_info=GetMagickInfo(magic,exception);
if (magick_info != (const MagickInfo *) NULL)
if (GetMagickAdjoin(magick_info) == MagickFalse)
image_info->adjoin=MagickFalse;
}
if (image_info->affirm != MagickFalse)
return(MagickTrue);
if (frames == 0)
{
/*
Determine the image format from the first few bytes of the file.
*/
image=AcquireImage(image_info,exception);
(void) CopyMagickString(image->filename,image_info->filename,
MaxTextExtent);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImage(image);
return(MagickFalse);
}
if ((IsBlobSeekable(image) == MagickFalse) ||
(IsBlobExempt(image) != MagickFalse))
{
/*
Copy standard input or pipe to temporary file.
*/
*filename='\0';
status=ImageToFile(image,filename,exception);
(void) CloseBlob(image);
if (status == MagickFalse)
{
image=DestroyImage(image);
return(MagickFalse);
}
SetImageInfoFile(image_info,(FILE *) NULL);
(void) CopyMagickString(image->filename,filename,MaxTextExtent);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImage(image);
return(MagickFalse);
}
(void) CopyMagickString(image_info->filename,filename,MaxTextExtent);
image_info->temporary=MagickTrue;
}
(void) ResetMagickMemory(magick,0,sizeof(magick));
count=ReadBlob(image,2*MaxTextExtent,magick);
(void) SeekBlob(image,-((MagickOffsetType) count),SEEK_CUR);
(void) CloseBlob(image);
image=DestroyImage(image);
/*
Check magic.xml configuration file.
*/
sans_exception=AcquireExceptionInfo();
magic_info=GetMagicInfo(magick,(size_t) count,sans_exception);
if ((magic_info != (const MagicInfo *) NULL) &&
(GetMagicName(magic_info) != (char *) NULL))
{
(void) CopyMagickString(image_info->magick,GetMagicName(magic_info),
MaxTextExtent);
magick_info=GetMagickInfo(image_info->magick,sans_exception);
if ((magick_info == (const MagickInfo *) NULL) ||
(GetMagickEndianSupport(magick_info) == MagickFalse))
image_info->endian=UndefinedEndian;
sans_exception=DestroyExceptionInfo(sans_exception);
return(MagickTrue);
}
magick_info=GetMagickInfo(image_info->magick,sans_exception);
if ((magick_info == (const MagickInfo *) NULL) ||
(GetMagickEndianSupport(magick_info) == MagickFalse))
image_info->endian=UndefinedEndian;
sans_exception=DestroyExceptionInfo(sans_exception);
}
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e I n f o B l o b %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageInfoBlob() sets the image info blob member.
%
% The format of the SetImageInfoBlob method is:
%
% void SetImageInfoBlob(ImageInfo *image_info,const void *blob,
% const size_t length)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o blob: the blob.
%
% o length: the blob length.
%
*/
MagickExport void SetImageInfoBlob(ImageInfo *image_info,const void *blob,
const size_t length)
{
assert(image_info != (ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
image_info->blob=(void *) blob;
image_info->length=length;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e I n f o F i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageInfoFile() sets the image info file member.
%
% The format of the SetImageInfoFile method is:
%
% void SetImageInfoFile(ImageInfo *image_info,FILE *file)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o file: the file.
%
*/
MagickExport void SetImageInfoFile(ImageInfo *image_info,FILE *file)
{
assert(image_info != (ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
image_info->file=file;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e M a s k %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageMask() associates a mask with the image. The mask must be the same
% dimensions as the image.
%
% The format of the SetImageMask method is:
%
% MagickBooleanType SetImageMask(Image *image,const Image *mask,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o mask: the image mask.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageMask(Image *image,const Image *mask,
ExceptionInfo *exception)
{
CacheView
*mask_view,
*image_view;
MagickBooleanType
status;
ssize_t
y;
/*
Set image mask.
*/
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickSignature);
if (mask == (const Image *) NULL)
{
image->read_mask=MagickFalse;
return(SyncImagePixelCache(image,exception));
}
image->read_mask=MagickTrue;
if (SyncImagePixelCache(image,exception) == MagickFalse)
return(MagickFalse);
status=MagickTrue;
mask_view=AcquireVirtualCacheView(mask,exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(mask,image,1,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*restrict p;
register Quantum
*restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(mask_view,0,y,mask->columns,1,exception);
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelReadMask(image,ClampToQuantum(GetPixelIntensity(mask,p)),q);
p+=GetPixelChannels(mask);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
mask_view=DestroyCacheView(mask_view);
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e A l p h a %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageAlpha() sets the alpha levels of the image.
%
% The format of the SetImageAlpha method is:
%
% MagickBooleanType SetImageAlpha(Image *image,const Quantum alpha,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o Alpha: the level of transparency: 0 is fully opaque and QuantumRange is
% fully transparent.
%
*/
MagickExport MagickBooleanType SetImageAlpha(Image *image,const Quantum alpha,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickSignature);
image->alpha_trait=BlendPixelTrait;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelReadMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
SetPixelAlpha(image,alpha,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e V i r t u a l P i x e l M e t h o d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageVirtualPixelMethod() sets the "virtual pixels" method for the
% image and returns the previous setting. A virtual pixel is any pixel access
% that is outside the boundaries of the image cache.
%
% The format of the SetImageVirtualPixelMethod() method is:
%
% VirtualPixelMethod SetImageVirtualPixelMethod(Image *image,
% const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o virtual_pixel_method: choose the type of virtual pixel.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport VirtualPixelMethod SetImageVirtualPixelMethod(Image *image,
const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception)
{
assert(image != (const Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
return(SetPixelCacheVirtualMethod(image,virtual_pixel_method,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S m u s h I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SmushImages() takes all images from the current image pointer to the end
% of the image list and smushes them to each other top-to-bottom if the
% stack parameter is true, otherwise left-to-right.
%
% The current gravity setting now effects how the image is justified in the
% final image.
%
% The format of the SmushImages method is:
%
% Image *SmushImages(const Image *images,const MagickBooleanType stack,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o images: the image sequence.
%
% o stack: A value other than 0 stacks the images top-to-bottom.
%
% o offset: minimum distance in pixels between images.
%
% o exception: return any errors or warnings in this structure.
%
*/
static ssize_t SmushXGap(const Image *smush_image,const Image *images,
const ssize_t offset,ExceptionInfo *exception)
{
CacheView
*left_view,
*right_view;
const Image
*left_image,
*right_image;
RectangleInfo
left_geometry,
right_geometry;
register const Quantum
*p;
register ssize_t
i,
y;
size_t
gap;
ssize_t
x;
if (images->previous == (Image *) NULL)
return(0);
right_image=images;
SetGeometry(smush_image,&right_geometry);
GravityAdjustGeometry(right_image->columns,right_image->rows,
right_image->gravity,&right_geometry);
left_image=images->previous;
SetGeometry(smush_image,&left_geometry);
GravityAdjustGeometry(left_image->columns,left_image->rows,
left_image->gravity,&left_geometry);
gap=right_image->columns;
left_view=AcquireVirtualCacheView(left_image,exception);
right_view=AcquireVirtualCacheView(right_image,exception);
for (y=0; y < (ssize_t) smush_image->rows; y++)
{
for (x=(ssize_t) left_image->columns-1; x > 0; x--)
{
p=GetCacheViewVirtualPixels(left_view,x,left_geometry.y+y,1,1,exception);
if ((p == (const Quantum *) NULL) ||
(GetPixelAlpha(left_image,p) != TransparentAlpha) ||
((left_image->columns-x-1) >= gap))
break;
}
i=(ssize_t) left_image->columns-x-1;
for (x=0; x < (ssize_t) right_image->columns; x++)
{
p=GetCacheViewVirtualPixels(right_view,x,right_geometry.y+y,1,1,
exception);
if ((p == (const Quantum *) NULL) ||
(GetPixelAlpha(right_image,p) != TransparentAlpha) ||
((x+i) >= (ssize_t) gap))
break;
}
if ((x+i) < (ssize_t) gap)
gap=(size_t) (x+i);
}
right_view=DestroyCacheView(right_view);
left_view=DestroyCacheView(left_view);
if (y < (ssize_t) smush_image->rows)
return(offset);
return((ssize_t) gap-offset);
}
static ssize_t SmushYGap(const Image *smush_image,const Image *images,
const ssize_t offset,ExceptionInfo *exception)
{
CacheView
*bottom_view,
*top_view;
const Image
*bottom_image,
*top_image;
RectangleInfo
bottom_geometry,
top_geometry;
register const Quantum
*p;
register ssize_t
i,
x;
size_t
gap;
ssize_t
y;
if (images->previous == (Image *) NULL)
return(0);
bottom_image=images;
SetGeometry(smush_image,&bottom_geometry);
GravityAdjustGeometry(bottom_image->columns,bottom_image->rows,
bottom_image->gravity,&bottom_geometry);
top_image=images->previous;
SetGeometry(smush_image,&top_geometry);
GravityAdjustGeometry(top_image->columns,top_image->rows,top_image->gravity,
&top_geometry);
gap=bottom_image->rows;
top_view=AcquireVirtualCacheView(top_image,exception);
bottom_view=AcquireVirtualCacheView(bottom_image,exception);
for (x=0; x < (ssize_t) smush_image->columns; x++)
{
for (y=(ssize_t) top_image->rows-1; y > 0; y--)
{
p=GetCacheViewVirtualPixels(top_view,top_geometry.x+x,y,1,1,exception);
if ((p == (const Quantum *) NULL) ||
(GetPixelAlpha(top_image,p) != TransparentAlpha) ||
((top_image->rows-y-1) >= gap))
break;
}
i=(ssize_t) top_image->rows-y-1;
for (y=0; y < (ssize_t) bottom_image->rows; y++)
{
p=GetCacheViewVirtualPixels(bottom_view,bottom_geometry.x+x,y,1,1,
exception);
if ((p == (const Quantum *) NULL) ||
(GetPixelAlpha(bottom_image,p) != TransparentAlpha) ||
((y+i) >= (ssize_t) gap))
break;
}
if ((y+i) < (ssize_t) gap)
gap=(size_t) (y+i);
}
bottom_view=DestroyCacheView(bottom_view);
top_view=DestroyCacheView(top_view);
if (x < (ssize_t) smush_image->columns)
return(offset);
return((ssize_t) gap-offset);
}
MagickExport Image *SmushImages(const Image *images,
const MagickBooleanType stack,const ssize_t offset,ExceptionInfo *exception)
{
#define SmushImageTag "Smush/Image"
const Image
*image;
Image
*smush_image;
MagickBooleanType
proceed,
status;
MagickOffsetType
n;
PixelTrait
alpha_trait;
RectangleInfo
geometry;
register const Image
*next;
size_t
height,
number_images,
width;
ssize_t
x_offset,
y_offset;
/*
Compute maximum area of smushed area.
*/
assert(images != (Image *) NULL);
assert(images->signature == MagickSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=images;
alpha_trait=image->alpha_trait;
number_images=1;
width=image->columns;
height=image->rows;
next=GetNextImageInList(image);
for ( ; next != (Image *) NULL; next=GetNextImageInList(next))
{
if (next->alpha_trait == BlendPixelTrait)
alpha_trait=BlendPixelTrait;
number_images++;
if (stack != MagickFalse)
{
if (next->columns > width)
width=next->columns;
height+=next->rows;
if (next->previous != (Image *) NULL)
height+=offset;
continue;
}
width+=next->columns;
if (next->previous != (Image *) NULL)
width+=offset;
if (next->rows > height)
height=next->rows;
}
/*
Smush images.
*/
smush_image=CloneImage(image,width,height,MagickTrue,exception);
if (smush_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(smush_image,DirectClass,exception) == MagickFalse)
{
smush_image=DestroyImage(smush_image);
return((Image *) NULL);
}
smush_image->alpha_trait=alpha_trait;
(void) SetImageBackgroundColor(smush_image,exception);
status=MagickTrue;
x_offset=0;
y_offset=0;
for (n=0; n < (MagickOffsetType) number_images; n++)
{
SetGeometry(smush_image,&geometry);
GravityAdjustGeometry(image->columns,image->rows,image->gravity,&geometry);
if (stack != MagickFalse)
{
x_offset-=geometry.x;
y_offset-=SmushYGap(smush_image,image,offset,exception);
}
else
{
x_offset-=SmushXGap(smush_image,image,offset,exception);
y_offset-=geometry.y;
}
status=CompositeImage(smush_image,image,OverCompositeOp,MagickTrue,x_offset,
y_offset,exception);
proceed=SetImageProgress(image,SmushImageTag,n,number_images);
if (proceed == MagickFalse)
break;
if (stack == MagickFalse)
{
x_offset+=(ssize_t) image->columns;
y_offset=0;
}
else
{
x_offset=0;
y_offset+=(ssize_t) image->rows;
}
image=GetNextImageInList(image);
}
if (stack == MagickFalse)
smush_image->columns=(size_t) x_offset;
else
smush_image->rows=(size_t) y_offset;
if (status == MagickFalse)
smush_image=DestroyImage(smush_image);
return(smush_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S t r i p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% StripImage() strips an image of all profiles and comments.
%
% The format of the StripImage method is:
%
% MagickBooleanType StripImage(Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType StripImage(Image *image,ExceptionInfo *exception)
{
MagickBooleanType
status;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
(void) exception;
DestroyImageProfiles(image);
(void) DeleteImageProperty(image,"comment");
(void) DeleteImageProperty(image,"date:create");
(void) DeleteImageProperty(image,"date:modify");
status=SetImageArtifact(image,"png:exclude-chunk",
"EXIF,iCCP,iTXt,sRGB,tEXt,zCCP,zTXt,date");
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ S y n c I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SyncImage() initializes the red, green, and blue intensities of each pixel
% as defined by the colormap index.
%
% The format of the SyncImage method is:
%
% MagickBooleanType SyncImage(Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline Quantum PushColormapIndex(Image *image,const Quantum index,
MagickBooleanType *range_exception)
{
if ((size_t) index < image->colors)
return(index);
*range_exception=MagickTrue;
return((Quantum) 0);
}
MagickExport MagickBooleanType SyncImage(Image *image,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
range_exception,
status;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickSignature);
if (image->storage_class == DirectClass)
return(MagickFalse);
range_exception=MagickFalse;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(range_exception,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
Quantum
index;
register Quantum
*restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
index=PushColormapIndex(image,GetPixelIndex(image,q),&range_exception);
SetPixelInfoPixel(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if ((image->ping == MagickFalse) && (range_exception != MagickFalse))
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
"InvalidColormapIndex","`%s'",image->filename);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S y n c I m a g e S e t t i n g s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SyncImageSettings() syncs any image_info global options into per-image
% attributes.
%
% Note: in IMv6 free form 'options' were always mapped into 'artifacts', so
% that operations and coders can find such settings. In IMv7 if a desired
% per-image artifact is not set, then it will directly look for a global
% option as a fallback, as such this copy is no longer needed, only the
% link set up.
%
% The format of the SyncImageSettings method is:
%
% MagickBooleanType SyncImageSettings(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
% MagickBooleanType SyncImagesSettings(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SyncImagesSettings(ImageInfo *image_info,
Image *images,ExceptionInfo *exception)
{
Image
*image;
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(images != (Image *) NULL);
assert(images->signature == MagickSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
image=images;
for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
(void) SyncImageSettings(image_info,image,exception);
(void) DeleteImageOption(image_info,"page");
return(MagickTrue);
}
MagickExport MagickBooleanType SyncImageSettings(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
const char
*option;
GeometryInfo
geometry_info;
MagickStatusType
flags;
ResolutionType
units;
/*
Sync image options.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
option=GetImageOption(image_info,"background");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&image->background_color,
exception);
option=GetImageOption(image_info,"black-point-compensation");
if (option != (const char *) NULL)
image->black_point_compensation=(MagickBooleanType) ParseCommandOption(
MagickBooleanOptions,MagickFalse,option);
option=GetImageOption(image_info,"blue-primary");
if (option != (const char *) NULL)
{
flags=ParseGeometry(option,&geometry_info);
image->chromaticity.blue_primary.x=geometry_info.rho;
image->chromaticity.blue_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.blue_primary.y=image->chromaticity.blue_primary.x;
}
option=GetImageOption(image_info,"bordercolor");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&image->border_color,
exception);
option=GetImageOption(image_info,"channel");
if (option != (const char *) NULL)
(void) SetPixelChannelMask(image,(ChannelType) ParseChannelOption(option));
/* FUTURE: do not sync compose to per-image compose setting here */
option=GetImageOption(image_info,"compose");
if (option != (const char *) NULL)
image->compose=(CompositeOperator) ParseCommandOption(MagickComposeOptions,
MagickFalse,option);
/* -- */
option=GetImageOption(image_info,"compress");
if (option != (const char *) NULL)
image->compression=(CompressionType) ParseCommandOption(
MagickCompressOptions,MagickFalse,option);
option=GetImageOption(image_info,"debug");
if (option != (const char *) NULL)
image->debug=(MagickBooleanType) ParseCommandOption(MagickBooleanOptions,
MagickFalse,option);
option=GetImageOption(image_info,"density");
if (option != (const char *) NULL)
{
GeometryInfo
geometry_info;
flags=ParseGeometry(option,&geometry_info);
image->resolution.x=geometry_info.rho;
image->resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->resolution.y=image->resolution.x;
}
option=GetImageOption(image_info,"depth");
if (option != (const char *) NULL)
image->depth=StringToUnsignedLong(option);
option=GetImageOption(image_info,"endian");
if (option != (const char *) NULL)
image->endian=(EndianType) ParseCommandOption(MagickEndianOptions,
MagickFalse,option);
option=GetImageOption(image_info,"filter");
if (option != (const char *) NULL)
image->filter=(FilterTypes) ParseCommandOption(MagickFilterOptions,
MagickFalse,option);
option=GetImageOption(image_info,"fuzz");
if (option != (const char *) NULL)
image->fuzz=StringToDoubleInterval(option,(double) QuantumRange+1.0);
option=GetImageOption(image_info,"gravity");
if (option != (const char *) NULL)
image->gravity=(GravityType) ParseCommandOption(MagickGravityOptions,
MagickFalse,option);
option=GetImageOption(image_info,"green-primary");
if (option != (const char *) NULL)
{
flags=ParseGeometry(option,&geometry_info);
image->chromaticity.green_primary.x=geometry_info.rho;
image->chromaticity.green_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.green_primary.y=image->chromaticity.green_primary.x;
}
option=GetImageOption(image_info,"intent");
if (option != (const char *) NULL)
image->rendering_intent=(RenderingIntent) ParseCommandOption(
MagickIntentOptions,MagickFalse,option);
option=GetImageOption(image_info,"intensity");
if (option != (const char *) NULL)
image->intensity=(PixelIntensityMethod) ParseCommandOption(
MagickPixelIntensityOptions,MagickFalse,option);
option=GetImageOption(image_info,"interlace");
if (option != (const char *) NULL)
image->interlace=(InterlaceType) ParseCommandOption(MagickInterlaceOptions,
MagickFalse,option);
option=GetImageOption(image_info,"interpolate");
if (option != (const char *) NULL)
image->interpolate=(PixelInterpolateMethod) ParseCommandOption(
MagickInterpolateOptions,MagickFalse,option);
option=GetImageOption(image_info,"loop");
if (option != (const char *) NULL)
image->iterations=StringToUnsignedLong(option);
option=GetImageOption(image_info,"mattecolor");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&image->matte_color,
exception);
option=GetImageOption(image_info,"orient");
if (option != (const char *) NULL)
image->orientation=(OrientationType) ParseCommandOption(
MagickOrientationOptions,MagickFalse,option);
option=GetImageOption(image_info,"page");
if (option != (const char *) NULL)
{
char
*geometry;
geometry=GetPageGeometry(option);
flags=ParseAbsoluteGeometry(geometry,&image->page);
geometry=DestroyString(geometry);
}
option=GetImageOption(image_info,"quality");
if (option != (const char *) NULL)
image->quality=StringToUnsignedLong(option);
option=GetImageOption(image_info,"red-primary");
if (option != (const char *) NULL)
{
flags=ParseGeometry(option,&geometry_info);
image->chromaticity.red_primary.x=geometry_info.rho;
image->chromaticity.red_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.red_primary.y=image->chromaticity.red_primary.x;
}
if (image_info->quality != UndefinedCompressionQuality)
image->quality=image_info->quality;
option=GetImageOption(image_info,"scene");
if (option != (const char *) NULL)
image->scene=StringToUnsignedLong(option);
option=GetImageOption(image_info,"taint");
if (option != (const char *) NULL)
image->taint=(MagickBooleanType) ParseCommandOption(MagickBooleanOptions,
MagickFalse,option);
option=GetImageOption(image_info,"tile-offset");
if (option != (const char *) NULL)
{
char
*geometry;
geometry=GetPageGeometry(option);
flags=ParseAbsoluteGeometry(geometry,&image->tile_offset);
geometry=DestroyString(geometry);
}
option=GetImageOption(image_info,"transparent-color");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&image->transparent_color,
exception);
option=GetImageOption(image_info,"type");
if (option != (const char *) NULL)
image->type=(ImageType) ParseCommandOption(MagickTypeOptions,MagickFalse,
option);
option=GetImageOption(image_info,"units");
units=image_info->units;
if (option != (const char *) NULL)
units=(ResolutionType) ParseCommandOption(MagickResolutionOptions,
MagickFalse,option);
if (units != UndefinedResolution)
{
if (image->units != units)
switch (image->units)
{
case PixelsPerInchResolution:
{
if (units == PixelsPerCentimeterResolution)
{
image->resolution.x/=2.54;
image->resolution.y/=2.54;
}
break;
}
case PixelsPerCentimeterResolution:
{
if (units == PixelsPerInchResolution)
{
image->resolution.x=(double) ((size_t) (100.0*2.54*
image->resolution.x+0.5))/100.0;
image->resolution.y=(double) ((size_t) (100.0*2.54*
image->resolution.y+0.5))/100.0;
}
break;
}
default:
break;
}
image->units=units;
}
option=GetImageOption(image_info,"virtual-pixel");
if (option != (const char *) NULL)
(void) SetImageVirtualPixelMethod(image,(VirtualPixelMethod)
ParseCommandOption(MagickVirtualPixelOptions,MagickFalse,option),
exception);
option=GetImageOption(image_info,"white-point");
if (option != (const char *) NULL)
{
flags=ParseGeometry(option,&geometry_info);
image->chromaticity.white_point.x=geometry_info.rho;
image->chromaticity.white_point.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.white_point.y=image->chromaticity.white_point.x;
}
ResetImageOptionIterator(image_info);
#if 0
{
/* IMv6: Copy freeform global options into per-image artifacts, so
* various operations and coders can access them.
*
* This has a problem, as per-image artefacts may have been set in
* parenthesis, but may not be unset when parenthesis ends.
*/
char
property[MaxTextExtent];
const char
*value;
for (option=GetNextImageOption(image_info); option != (const char *) NULL; )
{
value=GetImageOption(image_info,option);
if (value != (const char *) NULL)
{
(void) FormatLocaleString(property,MaxTextExtent,"%s",option);
(void) SetImageArtifact(image,property,value);
}
option=GetNextImageOption(image_info);
}
}
#else
/* IMv7: pointer to allow the lookup of pre-image artefact will fallback to
a global option setting/define. This saves a lot of duplication of
global options into per-image artifacts, while ensuring only specifically
set per-image artifacts are preverved when parenthesis ends.
This pointer is never explictally freed, as it is only used as a back
reference, not as the main pointer to the image_info structure. Images
being removed from a image_info image list (or yet to be added to such),
should have this pointer reset to NULL.
*/
image->image_info=image_info;
#endif
return(MagickTrue);
}
|
GB_binop__isle_uint16.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__isle_uint16)
// A.*B function (eWiseMult): GB (_AemultB_08__isle_uint16)
// A.*B function (eWiseMult): GB (_AemultB_02__isle_uint16)
// A.*B function (eWiseMult): GB (_AemultB_04__isle_uint16)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__isle_uint16)
// A*D function (colscale): GB (_AxD__isle_uint16)
// D*A function (rowscale): GB (_DxB__isle_uint16)
// C+=B function (dense accum): GB (_Cdense_accumB__isle_uint16)
// C+=b function (dense accum): GB (_Cdense_accumb__isle_uint16)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isle_uint16)
// C=scalar+B GB (_bind1st__isle_uint16)
// C=scalar+B' GB (_bind1st_tran__isle_uint16)
// C=A+scalar GB (_bind2nd__isle_uint16)
// C=A'+scalar GB (_bind2nd_tran__isle_uint16)
// C type: uint16_t
// A type: uint16_t
// A pattern? 0
// B type: uint16_t
// B pattern? 0
// BinaryOp: cij = (aij <= bij)
#define GB_ATYPE \
uint16_t
#define GB_BTYPE \
uint16_t
#define GB_CTYPE \
uint16_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) \
uint16_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) \
uint16_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) \
uint16_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_ISLE || GxB_NO_UINT16 || GxB_NO_ISLE_UINT16)
//------------------------------------------------------------------------------
// 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__isle_uint16)
(
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__isle_uint16)
(
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__isle_uint16)
(
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 uint16_t
uint16_t bwork = (*((uint16_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__isle_uint16)
(
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
uint16_t *restrict Cx = (uint16_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__isle_uint16)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint16_t *restrict Cx = (uint16_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__isle_uint16)
(
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) ;
uint16_t alpha_scalar ;
uint16_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((uint16_t *) alpha_scalar_in)) ;
beta_scalar = (*((uint16_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__isle_uint16)
(
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__isle_uint16)
(
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__isle_uint16)
(
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__isle_uint16)
(
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__isle_uint16)
(
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
uint16_t *Cx = (uint16_t *) Cx_output ;
uint16_t x = (*((uint16_t *) x_input)) ;
uint16_t *Bx = (uint16_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 ;
uint16_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__isle_uint16)
(
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 ;
uint16_t *Cx = (uint16_t *) Cx_output ;
uint16_t *Ax = (uint16_t *) Ax_input ;
uint16_t y = (*((uint16_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
uint16_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) \
{ \
uint16_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x <= aij) ; \
}
GrB_Info GB (_bind1st_tran__isle_uint16)
(
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 \
uint16_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint16_t x = (*((const uint16_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint16_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) \
{ \
uint16_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij <= y) ; \
}
GrB_Info GB (_bind2nd_tran__isle_uint16)
(
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
uint16_t y = (*((const uint16_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
fx.c
|
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% FFFFF X X %
% F X X %
% FFF X %
% F X X %
% F X X %
% %
% %
% MagickCore Image Special Effects Methods %
% %
% Software Design %
% Cristy %
% October 1996 %
% %
% %
% %
% Copyright 1999-2020 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/accelerate-private.h"
#include "MagickCore/annotate.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/channel.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite.h"
#include "MagickCore/decorate.h"
#include "MagickCore/distort.h"
#include "MagickCore/draw.h"
#include "MagickCore/effect.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/fx.h"
#include "MagickCore/fx-private.h"
#include "MagickCore/gem.h"
#include "MagickCore/gem-private.h"
#include "MagickCore/geometry.h"
#include "MagickCore/layer.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/memory-private.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/random_.h"
#include "MagickCore/random-private.h"
#include "MagickCore/resample.h"
#include "MagickCore/resample-private.h"
#include "MagickCore/resize.h"
#include "MagickCore/resource_.h"
#include "MagickCore/splay-tree.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"
#include "MagickCore/transform-private.h"
#include "MagickCore/utility.h"
/*
Typedef declarations.
*/
typedef enum
{
BitwiseAndAssignmentOperator = 0xd9U,
BitwiseOrAssignmentOperator,
LeftShiftAssignmentOperator,
RightShiftAssignmentOperator,
PowerAssignmentOperator,
ModuloAssignmentOperator,
PlusAssignmentOperator,
SubtractAssignmentOperator,
MultiplyAssignmentOperator,
DivideAssignmentOperator,
IncrementAssignmentOperator,
DecrementAssignmentOperator,
LeftShiftOperator,
RightShiftOperator,
LessThanEqualOperator,
GreaterThanEqualOperator,
EqualOperator,
NotEqualOperator,
LogicalAndOperator,
LogicalOrOperator,
ExponentialNotation
} FxOperator;
struct _FxInfo
{
const Image
*images;
char
*expression;
FILE
*file;
SplayTreeInfo
*colors,
*symbols;
CacheView
**view;
RandomInfo
*random_info;
ExceptionInfo
*exception;
};
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ A c q u i r e F x I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireFxInfo() allocates the FxInfo structure.
%
% The format of the AcquireFxInfo method is:
%
% FxInfo *AcquireFxInfo(Image *images,const char *expression,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o images: the image sequence.
%
% o expression: the expression.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickPrivate FxInfo *AcquireFxInfo(const Image *images,const char *expression,
ExceptionInfo *exception)
{
const Image
*next;
FxInfo
*fx_info;
ssize_t
i;
unsigned char
fx_op[2];
fx_info=(FxInfo *) AcquireCriticalMemory(sizeof(*fx_info));
(void) memset(fx_info,0,sizeof(*fx_info));
fx_info->exception=AcquireExceptionInfo();
fx_info->images=images;
fx_info->colors=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory,
RelinquishMagickMemory);
fx_info->symbols=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory,
RelinquishMagickMemory);
fx_info->view=(CacheView **) AcquireQuantumMemory(GetImageListLength(
fx_info->images),sizeof(*fx_info->view));
if (fx_info->view == (CacheView **) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
i=0;
next=GetFirstImageInList(fx_info->images);
for ( ; next != (Image *) NULL; next=next->next)
{
fx_info->view[i]=AcquireVirtualCacheView(next,exception);
i++;
}
fx_info->random_info=AcquireRandomInfo();
fx_info->expression=ConstantString(expression);
fx_info->file=stderr;
/*
Convert compound to simple operators.
*/
fx_op[1]='\0';
*fx_op=(unsigned char) BitwiseAndAssignmentOperator;
(void) SubstituteString(&fx_info->expression,"&=",(char *) fx_op);
*fx_op=(unsigned char) BitwiseOrAssignmentOperator;
(void) SubstituteString(&fx_info->expression,"|=",(char *) fx_op);
*fx_op=(unsigned char) LeftShiftAssignmentOperator;
(void) SubstituteString(&fx_info->expression,"<<=",(char *) fx_op);
*fx_op=(unsigned char) RightShiftAssignmentOperator;
(void) SubstituteString(&fx_info->expression,">>=",(char *) fx_op);
*fx_op=(unsigned char) PowerAssignmentOperator;
(void) SubstituteString(&fx_info->expression,"^=",(char *) fx_op);
*fx_op=(unsigned char) ModuloAssignmentOperator;
(void) SubstituteString(&fx_info->expression,"%=",(char *) fx_op);
*fx_op=(unsigned char) PlusAssignmentOperator;
(void) SubstituteString(&fx_info->expression,"+=",(char *) fx_op);
*fx_op=(unsigned char) SubtractAssignmentOperator;
(void) SubstituteString(&fx_info->expression,"-=",(char *) fx_op);
*fx_op=(unsigned char) MultiplyAssignmentOperator;
(void) SubstituteString(&fx_info->expression,"*=",(char *) fx_op);
*fx_op=(unsigned char) DivideAssignmentOperator;
(void) SubstituteString(&fx_info->expression,"/=",(char *) fx_op);
*fx_op=(unsigned char) IncrementAssignmentOperator;
(void) SubstituteString(&fx_info->expression,"++",(char *) fx_op);
*fx_op=(unsigned char) DecrementAssignmentOperator;
(void) SubstituteString(&fx_info->expression,"--",(char *) fx_op);
*fx_op=(unsigned char) LeftShiftOperator;
(void) SubstituteString(&fx_info->expression,"<<",(char *) fx_op);
*fx_op=(unsigned char) RightShiftOperator;
(void) SubstituteString(&fx_info->expression,">>",(char *) fx_op);
*fx_op=(unsigned char) LessThanEqualOperator;
(void) SubstituteString(&fx_info->expression,"<=",(char *) fx_op);
*fx_op=(unsigned char) GreaterThanEqualOperator;
(void) SubstituteString(&fx_info->expression,">=",(char *) fx_op);
*fx_op=(unsigned char) EqualOperator;
(void) SubstituteString(&fx_info->expression,"==",(char *) fx_op);
*fx_op=(unsigned char) NotEqualOperator;
(void) SubstituteString(&fx_info->expression,"!=",(char *) fx_op);
*fx_op=(unsigned char) LogicalAndOperator;
(void) SubstituteString(&fx_info->expression,"&&",(char *) fx_op);
*fx_op=(unsigned char) LogicalOrOperator;
(void) SubstituteString(&fx_info->expression,"||",(char *) fx_op);
*fx_op=(unsigned char) ExponentialNotation;
(void) SubstituteString(&fx_info->expression,"**",(char *) fx_op);
/*
Force right-to-left associativity for unary negation.
*/
(void) SubstituteString(&fx_info->expression,"-","-1.0*");
(void) SubstituteString(&fx_info->expression,"^-1.0*","^-");
(void) SubstituteString(&fx_info->expression,"E-1.0*","E-");
(void) SubstituteString(&fx_info->expression,"e-1.0*","e-");
(void) SubstituteString(&fx_info->expression," ",""); /* compact string */
return(fx_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y F x I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyFxInfo() deallocates memory associated with an FxInfo structure.
%
% The format of the DestroyFxInfo method is:
%
% ImageInfo *DestroyFxInfo(ImageInfo *fx_info)
%
% A description of each parameter follows:
%
% o fx_info: the fx info.
%
*/
MagickPrivate FxInfo *DestroyFxInfo(FxInfo *fx_info)
{
ssize_t
i;
fx_info->exception=DestroyExceptionInfo(fx_info->exception);
fx_info->expression=DestroyString(fx_info->expression);
fx_info->symbols=DestroySplayTree(fx_info->symbols);
fx_info->colors=DestroySplayTree(fx_info->colors);
for (i=(ssize_t) GetImageListLength(fx_info->images)-1; i >= 0; i--)
fx_info->view[i]=DestroyCacheView(fx_info->view[i]);
fx_info->view=(CacheView **) RelinquishMagickMemory(fx_info->view);
fx_info->random_info=DestroyRandomInfo(fx_info->random_info);
fx_info=(FxInfo *) RelinquishMagickMemory(fx_info);
return(fx_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ F x E v a l u a t e C h a n n e l E x p r e s s i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FxEvaluateChannelExpression() evaluates an expression and returns the
% results.
%
% The format of the FxEvaluateExpression method is:
%
% double FxEvaluateChannelExpression(FxInfo *fx_info,
% const PixelChannel channel,const ssize_t x,const ssize_t y,
% double *alpha,Exceptioninfo *exception)
% double FxEvaluateExpression(FxInfo *fx_info,
% double *alpha,Exceptioninfo *exception)
%
% A description of each parameter follows:
%
% o fx_info: the fx info.
%
% o channel: the channel.
%
% o x,y: the pixel position.
%
% o alpha: the result.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline const double *GetFxSymbolValue(FxInfo *magick_restrict fx_info,
const char *symbol)
{
return((const double *) GetValueFromSplayTree(fx_info->symbols,symbol));
}
static inline MagickBooleanType SetFxSymbolValue(
FxInfo *magick_restrict fx_info,const char *magick_restrict symbol,
double const value)
{
double
*object;
object=(double *) GetValueFromSplayTree(fx_info->symbols,symbol);
if (object != (double *) NULL)
{
*object=value;
return(MagickTrue);
}
object=(double *) AcquireMagickMemory(sizeof(*object));
if (object == (double *) NULL)
{
(void) ThrowMagickException(fx_info->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
fx_info->images->filename);
return(MagickFalse);
}
*object=value;
return(AddValueToSplayTree(fx_info->symbols,ConstantString(symbol),object));
}
static double FxChannelStatistics(FxInfo *fx_info,Image *image,
PixelChannel channel,const char *symbol,ExceptionInfo *exception)
{
ChannelType
channel_mask;
char
key[MagickPathExtent];
const double
*value;
double
statistic;
const char
*p;
channel_mask=UndefinedChannel;
for (p=symbol; (*p != '.') && (*p != '\0'); p++) ;
if (*p == '.')
{
ssize_t
option;
option=ParseCommandOption(MagickPixelChannelOptions,MagickTrue,p+1);
if (option >= 0)
{
channel=(PixelChannel) option;
channel_mask=SetPixelChannelMask(image,(ChannelType)
(1UL << channel));
}
}
(void) FormatLocaleString(key,MagickPathExtent,"%p.%.20g.%s",(void *) image,
(double) channel,symbol);
value=GetFxSymbolValue(fx_info,key);
if (value != (const double *) NULL)
{
if (channel_mask != UndefinedChannel)
(void) SetPixelChannelMask(image,channel_mask);
return(QuantumScale*(*value));
}
statistic=0.0;
if (LocaleNCompare(symbol,"depth",5) == 0)
{
size_t
depth;
depth=GetImageDepth(image,exception);
statistic=(double) depth;
}
if (LocaleNCompare(symbol,"kurtosis",8) == 0)
{
double
kurtosis,
skewness;
(void) GetImageKurtosis(image,&kurtosis,&skewness,exception);
statistic=kurtosis;
}
if (LocaleNCompare(symbol,"maxima",6) == 0)
{
double
maxima,
minima;
(void) GetImageRange(image,&minima,&maxima,exception);
statistic=maxima;
}
if (LocaleNCompare(symbol,"mean",4) == 0)
{
double
mean,
standard_deviation;
(void) GetImageMean(image,&mean,&standard_deviation,exception);
statistic=mean;
}
if (LocaleNCompare(symbol,"median",6) == 0)
{
double
median;
(void) GetImageMedian(image,&median,exception);
statistic=median;
}
if (LocaleNCompare(symbol,"minima",6) == 0)
{
double
maxima,
minima;
(void) GetImageRange(image,&minima,&maxima,exception);
statistic=minima;
}
if (LocaleNCompare(symbol,"skewness",8) == 0)
{
double
kurtosis,
skewness;
(void) GetImageKurtosis(image,&kurtosis,&skewness,exception);
statistic=skewness;
}
if (LocaleNCompare(symbol,"standard_deviation",18) == 0)
{
double
mean,
standard_deviation;
(void) GetImageMean(image,&mean,&standard_deviation,exception);
statistic=standard_deviation;
}
if (channel_mask != UndefinedChannel)
(void) SetPixelChannelMask(image,channel_mask);
if (SetFxSymbolValue(fx_info,key,statistic) == MagickFalse)
return(0.0);
return(QuantumScale*statistic);
}
static double
FxEvaluateSubexpression(FxInfo *,const PixelChannel,const ssize_t,
const ssize_t,const char *,const size_t,double *,ExceptionInfo *);
static inline MagickBooleanType IsFxFunction(const char *expression,
const char *name,const size_t length)
{
int
c;
size_t
i;
for (i=0; i <= length; i++)
if (expression[i] == '\0')
return(MagickFalse);
c=expression[length];
if ((LocaleNCompare(expression,name,length) == 0) &&
((isspace((int) ((unsigned char) c)) == 0) || (c == '(')))
return(MagickTrue);
return(MagickFalse);
}
static inline double FxGCD(const double alpha,const double beta)
{
if (alpha < beta)
return(FxGCD(beta,alpha));
if (fabs(beta) < 0.001)
return(alpha);
return(FxGCD(beta,alpha-beta*floor(alpha/beta)));
}
static inline const char *FxSubexpression(const char *expression,
ExceptionInfo *exception)
{
const char
*subexpression;
ssize_t
level;
level=0;
subexpression=expression;
while ((*subexpression != '\0') &&
((level != 1) || (strchr(")",(int) *subexpression) == (char *) NULL)))
{
if (strchr("(",(int) *subexpression) != (char *) NULL)
level++;
else
if (strchr(")",(int) *subexpression) != (char *) NULL)
level--;
subexpression++;
}
if (*subexpression == '\0')
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UnbalancedParenthesis","`%s'",expression);
return(subexpression);
}
static double FxGetSymbol(FxInfo *fx_info,const PixelChannel channel,
const ssize_t x,const ssize_t y,const char *expression,const size_t depth,
ExceptionInfo *exception)
{
char
*q,
symbol[MagickPathExtent];
const char
*artifact,
*p;
const double
*value;
double
alpha,
beta;
Image
*image;
MagickBooleanType
status;
PixelInfo
pixel;
PointInfo
point;
ssize_t
i;
size_t
level;
p=expression;
i=GetImageIndexInList(fx_info->images);
level=0;
point.x=(double) x;
point.y=(double) y;
if (isalpha((int) ((unsigned char) *(p+1))) == 0)
{
char
*subexpression;
subexpression=AcquireString(expression);
if (strchr("suv",(int) *p) != (char *) NULL)
{
switch (*p)
{
case 's':
default:
{
i=GetImageIndexInList(fx_info->images);
break;
}
case 'u': i=0; break;
case 'v': i=1; break;
}
p++;
if (*p == '[')
{
level++;
q=subexpression;
for (p++; *p != '\0'; )
{
if (*p == '[')
level++;
else
if (*p == ']')
{
level--;
if (level == 0)
break;
}
*q++=(*p++);
}
*q='\0';
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,
depth,&beta,exception);
i=(ssize_t) alpha;
if (*p != '\0')
p++;
}
if (*p == '.')
p++;
}
if ((*p == 'p') && (isalpha((int) ((unsigned char) *(p+1))) == 0))
{
p++;
if (*p == '{')
{
level++;
q=subexpression;
for (p++; *p != '\0'; )
{
if (*p == '{')
level++;
else
if (*p == '}')
{
level--;
if (level == 0)
break;
}
*q++=(*p++);
}
*q='\0';
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,
depth,&beta,exception);
point.x=alpha;
point.y=beta;
if (*p != '\0')
p++;
}
else
if (*p == '[')
{
level++;
q=subexpression;
for (p++; *p != '\0'; )
{
if (*p == '[')
level++;
else
if (*p == ']')
{
level--;
if (level == 0)
break;
}
*q++=(*p++);
}
*q='\0';
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,
depth,&beta,exception);
point.x+=alpha;
point.y+=beta;
if (*p != '\0')
p++;
}
if (*p == '.')
p++;
}
subexpression=DestroyString(subexpression);
}
image=GetImageFromList(fx_info->images,i);
if (image == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"NoSuchImage","`%s'",expression);
return(0.0);
}
i=GetImageIndexInList(image);
GetPixelInfo(image,&pixel);
status=InterpolatePixelInfo(image,fx_info->view[i],image->interpolate,
point.x,point.y,&pixel,exception);
(void) status;
if ((*p != '\0') && (*(p+1) != '\0') && (*(p+2) != '\0') &&
(LocaleCompare(p,"intensity") != 0) && (LocaleCompare(p,"luma") != 0) &&
(LocaleCompare(p,"luminance") != 0) && (LocaleCompare(p,"hue") != 0) &&
(LocaleCompare(p,"saturation") != 0) &&
(LocaleCompare(p,"lightness") != 0))
{
char
name[MagickPathExtent];
size_t
length;
(void) CopyMagickString(name,p,MagickPathExtent);
length=strlen(name);
for (q=name+length-1; q > name; q--)
{
if (*q == ')')
break;
if (*q == '.')
{
*q='\0';
break;
}
}
q=name;
if ((*q != '\0') && (*(q+1) != '\0') && (*(q+2) != '\0') &&
(GetFxSymbolValue(fx_info,name) == (const double *) NULL))
{
PixelInfo
*color;
color=(PixelInfo *) GetValueFromSplayTree(fx_info->colors,name);
if (color != (PixelInfo *) NULL)
{
pixel=(*color);
p+=length;
}
else
{
MagickBooleanType
status;
status=QueryColorCompliance(name,AllCompliance,&pixel,
fx_info->exception);
if (status != MagickFalse)
{
(void) AddValueToSplayTree(fx_info->colors,
ConstantString(name),ClonePixelInfo(&pixel));
p+=length;
}
}
}
}
(void) CopyMagickString(symbol,p,MagickPathExtent);
StripString(symbol);
if (*symbol == '\0')
{
switch (channel)
{
case RedPixelChannel: return(QuantumScale*pixel.red);
case GreenPixelChannel: return(QuantumScale*pixel.green);
case BluePixelChannel: return(QuantumScale*pixel.blue);
case BlackPixelChannel:
{
if (image->colorspace != CMYKColorspace)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ImageError,"ColorSeparatedImageRequired","`%s'",
image->filename);
return(0.0);
}
return(QuantumScale*pixel.black);
}
case AlphaPixelChannel:
{
if (pixel.alpha_trait == UndefinedPixelTrait)
return(1.0);
alpha=(double) (QuantumScale*pixel.alpha);
return(alpha);
}
case CompositePixelChannel:
{
Quantum
quantum_pixel[MaxPixelChannels];
SetPixelViaPixelInfo(image,&pixel,quantum_pixel);
return(QuantumScale*GetPixelIntensity(image,quantum_pixel));
}
case IndexPixelChannel:
return(0.0);
default:
break;
}
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UnableToParseExpression","`%s'",p);
return(0.0);
}
switch (*symbol)
{
case 'A':
case 'a':
{
if (LocaleCompare(symbol,"a") == 0)
return((QuantumScale*pixel.alpha));
break;
}
case 'B':
case 'b':
{
if (LocaleCompare(symbol,"b") == 0)
return(QuantumScale*pixel.blue);
break;
}
case 'C':
case 'c':
{
if (IsFxFunction(symbol,"channel",7) != MagickFalse)
{
GeometryInfo
channel_info;
MagickStatusType
flags;
flags=ParseGeometry(symbol+7,&channel_info);
if (image->colorspace == CMYKColorspace)
switch (channel)
{
case CyanPixelChannel:
{
if ((flags & RhoValue) == 0)
return(0.0);
return(channel_info.rho);
}
case MagentaPixelChannel:
{
if ((flags & SigmaValue) == 0)
return(0.0);
return(channel_info.sigma);
}
case YellowPixelChannel:
{
if ((flags & XiValue) == 0)
return(0.0);
return(channel_info.xi);
}
case BlackPixelChannel:
{
if ((flags & PsiValue) == 0)
return(0.0);
return(channel_info.psi);
}
case AlphaPixelChannel:
{
if ((flags & ChiValue) == 0)
return(0.0);
return(channel_info.chi);
}
default:
return(0.0);
}
switch (channel)
{
case RedPixelChannel:
{
if ((flags & RhoValue) == 0)
return(0.0);
return(channel_info.rho);
}
case GreenPixelChannel:
{
if ((flags & SigmaValue) == 0)
return(0.0);
return(channel_info.sigma);
}
case BluePixelChannel:
{
if ((flags & XiValue) == 0)
return(0.0);
return(channel_info.xi);
}
case BlackPixelChannel:
{
if ((flags & ChiValue) == 0)
return(0.0);
return(channel_info.chi);
}
case AlphaPixelChannel:
{
if ((flags & PsiValue) == 0)
return(0.0);
return(channel_info.psi);
}
default:
return(0.0);
}
}
if (LocaleCompare(symbol,"c") == 0)
return(QuantumScale*pixel.red);
break;
}
case 'D':
case 'd':
{
if (LocaleNCompare(symbol,"depth",5) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
break;
}
case 'E':
case 'e':
{
if (LocaleCompare(symbol,"extent") == 0)
{
if (image->extent != 0)
return((double) image->extent);
return((double) GetBlobSize(image));
}
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(symbol,"g") == 0)
return(QuantumScale*pixel.green);
break;
}
case 'K':
case 'k':
{
if (LocaleNCompare(symbol,"kurtosis",8) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
if (LocaleCompare(symbol,"k") == 0)
{
if (image->colorspace != CMYKColorspace)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"ColorSeparatedImageRequired","`%s'",
image->filename);
return(0.0);
}
return(QuantumScale*pixel.black);
}
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(symbol,"h") == 0)
return((double) image->rows);
if (LocaleCompare(symbol,"hue") == 0)
{
double
hue,
lightness,
saturation;
ConvertRGBToHSL(pixel.red,pixel.green,pixel.blue,&hue,&saturation,
&lightness);
return(hue);
}
break;
}
case 'I':
case 'i':
{
if ((LocaleCompare(symbol,"image.depth") == 0) ||
(LocaleCompare(symbol,"image.minima") == 0) ||
(LocaleCompare(symbol,"image.maxima") == 0) ||
(LocaleCompare(symbol,"image.mean") == 0) ||
(LocaleCompare(symbol,"image.kurtosis") == 0) ||
(LocaleCompare(symbol,"image.skewness") == 0) ||
(LocaleCompare(symbol,"image.standard_deviation") == 0))
return(FxChannelStatistics(fx_info,image,channel,symbol+6,exception));
if (LocaleCompare(symbol,"image.resolution.x") == 0)
return(image->resolution.x);
if (LocaleCompare(symbol,"image.resolution.y") == 0)
return(image->resolution.y);
if (LocaleCompare(symbol,"intensity") == 0)
{
Quantum
quantum_pixel[MaxPixelChannels];
SetPixelViaPixelInfo(image,&pixel,quantum_pixel);
return(QuantumScale*GetPixelIntensity(image,quantum_pixel));
}
if (LocaleCompare(symbol,"i") == 0)
return((double) x);
break;
}
case 'J':
case 'j':
{
if (LocaleCompare(symbol,"j") == 0)
return((double) y);
break;
}
case 'L':
case 'l':
{
if (LocaleCompare(symbol,"lightness") == 0)
{
double
hue,
lightness,
saturation;
ConvertRGBToHSL(pixel.red,pixel.green,pixel.blue,&hue,&saturation,
&lightness);
return(lightness);
}
if (LocaleCompare(symbol,"luma") == 0)
{
double
luma;
luma=0.212656*pixel.red+0.715158*pixel.green+0.072186*pixel.blue;
return(QuantumScale*luma);
}
if (LocaleCompare(symbol,"luminance") == 0)
{
double
luminence;
luminence=0.212656*pixel.red+0.715158*pixel.green+0.072186*pixel.blue;
return(QuantumScale*luminence);
}
break;
}
case 'M':
case 'm':
{
if (LocaleNCompare(symbol,"maxima",6) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
if (LocaleNCompare(symbol,"mean",4) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
if (LocaleNCompare(symbol,"median",6) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
if (LocaleNCompare(symbol,"minima",6) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
if (LocaleCompare(symbol,"m") == 0)
return(QuantumScale*pixel.green);
break;
}
case 'N':
case 'n':
{
if (LocaleCompare(symbol,"n") == 0)
return((double) GetImageListLength(fx_info->images));
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(symbol,"o") == 0)
return(QuantumScale*pixel.alpha);
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(symbol,"page.height") == 0)
return((double) image->page.height);
if (LocaleCompare(symbol,"page.width") == 0)
return((double) image->page.width);
if (LocaleCompare(symbol,"page.x") == 0)
return((double) image->page.x);
if (LocaleCompare(symbol,"page.y") == 0)
return((double) image->page.y);
if (LocaleCompare(symbol,"printsize.x") == 0)
return(PerceptibleReciprocal(image->resolution.x)*image->columns);
if (LocaleCompare(symbol,"printsize.y") == 0)
return(PerceptibleReciprocal(image->resolution.y)*image->rows);
break;
}
case 'Q':
case 'q':
{
if (LocaleCompare(symbol,"quality") == 0)
return((double) image->quality);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(symbol,"resolution.x") == 0)
return(image->resolution.x);
if (LocaleCompare(symbol,"resolution.y") == 0)
return(image->resolution.y);
if (LocaleCompare(symbol,"r") == 0)
return(QuantumScale*pixel.red);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(symbol,"saturation") == 0)
{
double
hue,
lightness,
saturation;
ConvertRGBToHSL(pixel.red,pixel.green,pixel.blue,&hue,&saturation,
&lightness);
return(saturation);
}
if (LocaleNCompare(symbol,"skewness",8) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
if (LocaleNCompare(symbol,"standard_deviation",18) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
break;
}
case 'T':
case 't':
{
if (LocaleCompare(symbol,"t") == 0)
return((double) GetImageIndexInList(fx_info->images));
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(symbol,"w") == 0)
return((double) image->columns);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(symbol,"y") == 0)
return(QuantumScale*pixel.blue);
break;
}
case 'Z':
case 'z':
{
if (LocaleCompare(symbol,"z") == 0)
return((double) GetImageDepth(image,fx_info->exception));
break;
}
default:
break;
}
value=GetFxSymbolValue(fx_info,symbol);
if (value != (const double *) NULL)
return(*value);
artifact=GetImageArtifact(image,symbol);
if (artifact != (const char *) NULL)
return(StringToDouble(artifact,(char **) NULL));
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UndefinedVariable","`%s'",symbol);
(void) SetFxSymbolValue(fx_info,symbol,0.0);
return(0.0);
}
static const char *FxOperatorPrecedence(const char *expression,
ExceptionInfo *exception)
{
typedef enum
{
UndefinedPrecedence,
NullPrecedence,
BitwiseComplementPrecedence,
ExponentPrecedence,
ExponentialNotationPrecedence,
MultiplyPrecedence,
AdditionPrecedence,
ShiftPrecedence,
RelationalPrecedence,
EquivalencyPrecedence,
BitwiseAndPrecedence,
BitwiseOrPrecedence,
LogicalAndPrecedence,
LogicalOrPrecedence,
TernaryPrecedence,
AssignmentPrecedence,
CommaPrecedence,
SeparatorPrecedence
} FxPrecedence;
FxPrecedence
precedence,
target;
const char
*subexpression;
int
c;
size_t
level;
c=(-1);
level=0;
subexpression=(const char *) NULL;
target=NullPrecedence;
while ((c != '\0') && (*expression != '\0'))
{
precedence=UndefinedPrecedence;
if ((isspace((int) ((unsigned char) *expression)) != 0) || (c == (int) '@'))
{
expression++;
continue;
}
switch (*expression)
{
case 'A':
case 'a':
{
#if defined(MAGICKCORE_HAVE_ACOSH)
if (IsFxFunction(expression,"acosh",5) != MagickFalse)
{
expression+=5;
break;
}
#endif
#if defined(MAGICKCORE_HAVE_ASINH)
if (IsFxFunction(expression,"asinh",5) != MagickFalse)
{
expression+=5;
break;
}
#endif
#if defined(MAGICKCORE_HAVE_ATANH)
if (IsFxFunction(expression,"atanh",5) != MagickFalse)
{
expression+=5;
break;
}
#endif
if (IsFxFunction(expression,"atan2",5) != MagickFalse)
{
expression+=5;
break;
}
break;
}
case 'E':
case 'e':
{
if ((isdigit((int) ((unsigned char) c)) != 0) &&
((LocaleNCompare(expression,"E+",2) == 0) ||
(LocaleNCompare(expression,"E-",2) == 0)))
{
expression+=2; /* scientific notation */
break;
}
}
case 'J':
case 'j':
{
if ((IsFxFunction(expression,"j0",2) != MagickFalse) ||
(IsFxFunction(expression,"j1",2) != MagickFalse))
{
expression+=2;
break;
}
break;
}
case '#':
{
while (isxdigit((int) ((unsigned char) *(expression+1))) != 0)
expression++;
break;
}
default:
break;
}
if ((c == (int) '{') || (c == (int) '['))
level++;
else
if ((c == (int) '}') || (c == (int) ']'))
level--;
if (level == 0)
switch ((unsigned char) *expression)
{
case '~':
case '!':
{
precedence=BitwiseComplementPrecedence;
break;
}
case '^':
case '@':
{
precedence=ExponentPrecedence;
break;
}
default:
{
if (((c != 0) && ((isdigit((int) ((unsigned char) c)) != 0) ||
(strchr(")",c) != (char *) NULL))) &&
(((islower((int) ((unsigned char) *expression)) != 0) ||
(strchr("(",(int) ((unsigned char) *expression)) != (char *) NULL)) ||
((isdigit((int) ((unsigned char) c)) == 0) &&
(isdigit((int) ((unsigned char) *expression)) != 0))) &&
(strchr("xy",(int) ((unsigned char) *expression)) == (char *) NULL))
precedence=MultiplyPrecedence;
break;
}
case '*':
case '/':
case '%':
{
precedence=MultiplyPrecedence;
break;
}
case '+':
case '-':
{
if ((strchr("(+-/*%:&^|<>~,",c) == (char *) NULL) ||
(isalpha((int) ((unsigned char) c)) != 0))
precedence=AdditionPrecedence;
break;
}
case BitwiseAndAssignmentOperator:
case BitwiseOrAssignmentOperator:
case LeftShiftAssignmentOperator:
case RightShiftAssignmentOperator:
case PowerAssignmentOperator:
case ModuloAssignmentOperator:
case PlusAssignmentOperator:
case SubtractAssignmentOperator:
case MultiplyAssignmentOperator:
case DivideAssignmentOperator:
case IncrementAssignmentOperator:
case DecrementAssignmentOperator:
{
precedence=AssignmentPrecedence;
break;
}
case LeftShiftOperator:
case RightShiftOperator:
{
precedence=ShiftPrecedence;
break;
}
case '<':
case LessThanEqualOperator:
case GreaterThanEqualOperator:
case '>':
{
precedence=RelationalPrecedence;
break;
}
case EqualOperator:
case NotEqualOperator:
{
precedence=EquivalencyPrecedence;
break;
}
case '&':
{
precedence=BitwiseAndPrecedence;
break;
}
case '|':
{
precedence=BitwiseOrPrecedence;
break;
}
case LogicalAndOperator:
{
precedence=LogicalAndPrecedence;
break;
}
case LogicalOrOperator:
{
precedence=LogicalOrPrecedence;
break;
}
case ExponentialNotation:
{
precedence=ExponentialNotationPrecedence;
break;
}
case ':':
case '?':
{
precedence=TernaryPrecedence;
break;
}
case '=':
{
precedence=AssignmentPrecedence;
break;
}
case ',':
{
precedence=CommaPrecedence;
break;
}
case ';':
{
precedence=SeparatorPrecedence;
break;
}
}
if ((precedence == BitwiseComplementPrecedence) ||
(precedence == TernaryPrecedence) ||
(precedence == AssignmentPrecedence))
{
if (precedence > target)
{
/*
Right-to-left associativity.
*/
target=precedence;
subexpression=expression;
}
}
else
if (precedence >= target)
{
/*
Left-to-right associativity.
*/
target=precedence;
subexpression=expression;
}
if (strchr("(",(int) *expression) != (char *) NULL)
expression=FxSubexpression(expression,exception);
c=(int) (*expression++);
}
return(subexpression);
}
static double FxEvaluateSubexpression(FxInfo *fx_info,
const PixelChannel channel,const ssize_t x,const ssize_t y,
const char *expression,const size_t depth,double *beta,
ExceptionInfo *exception)
{
#define FxMaxParenthesisDepth 58
#define FxMaxSubexpressionDepth 200
#define FxReturn(value) \
{ \
subexpression=DestroyString(subexpression); \
return(value); \
}
#define FxParseConditional(subexpression,sentinal,p,q) \
{ \
p=subexpression; \
for (q=(char *) p; (*q != (sentinal)) && (*q != '\0'); q++) \
if (*q == '(') \
{ \
for (q++; (*q != ')') && (*q != '\0'); q++); \
if (*q == '\0') \
break; \
} \
if (*q == '\0') \
{ \
(void) ThrowMagickException(exception,GetMagickModule(), \
OptionError,"UnableToParseExpression","`%s'",subexpression); \
FxReturn(0.0); \
} \
if (strlen(q) == 1) \
*(q+1)='\0'; \
*q='\0'; \
}
char
*q,
*subexpression;
double
alpha,
gamma,
sans,
value;
const char
*p;
*beta=0.0;
sans=0.0;
subexpression=AcquireString(expression);
*subexpression='\0';
if (depth > FxMaxSubexpressionDepth)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UnableToParseExpression","`%s'",expression);
FxReturn(0.0);
}
if (exception->severity >= ErrorException)
FxReturn(0.0);
while (isspace((int) ((unsigned char) *expression)) != 0)
expression++;
if (*expression == '\0')
FxReturn(0.0);
p=FxOperatorPrecedence(expression,exception);
if (p != (const char *) NULL)
{
(void) CopyMagickString(subexpression,expression,(size_t)
(p-expression+1));
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,depth+1,
beta,exception);
switch ((unsigned char) *p)
{
case '~':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
*beta=(double) (~(size_t) *beta);
FxReturn(*beta);
}
case '!':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(*beta == 0.0 ? 1.0 : 0.0);
}
case '^':
{
*beta=pow(alpha,FxEvaluateSubexpression(fx_info,channel,x,y,++p,
depth+1,beta,exception));
FxReturn(*beta);
}
case '*':
case ExponentialNotation:
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha*(*beta));
}
case '/':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(PerceptibleReciprocal(*beta)*alpha);
}
case '%':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(fmod(alpha,*beta));
}
case '+':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha+(*beta));
}
case '-':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha-(*beta));
}
case BitwiseAndAssignmentOperator:
{
q=subexpression;
while (isalpha((int) ((unsigned char) *q)) != 0)
q++;
if (*q != '\0')
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"UnableToParseExpression","`%s'",subexpression);
FxReturn(0.0);
}
ClearMagickException(exception);
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
value=(double) ((size_t) (alpha+0.5) & (size_t) (*beta+0.5));
if (SetFxSymbolValue(fx_info,subexpression,value) == MagickFalse)
return(0.0);
FxReturn(*beta);
}
case BitwiseOrAssignmentOperator:
{
q=subexpression;
while (isalpha((int) ((unsigned char) *q)) != 0)
q++;
if (*q != '\0')
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"UnableToParseExpression","`%s'",subexpression);
FxReturn(0.0);
}
ClearMagickException(exception);
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
value=(double) ((size_t) (alpha+0.5) | (size_t) (*beta+0.5));
if (SetFxSymbolValue(fx_info,subexpression,value) == MagickFalse)
return(0.0);
FxReturn(*beta);
}
case LeftShiftAssignmentOperator:
{
q=subexpression;
while (isalpha((int) ((unsigned char) *q)) != 0)
q++;
if (*q != '\0')
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"UnableToParseExpression","`%s'",subexpression);
FxReturn(0.0);
}
ClearMagickException(exception);
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
if ((size_t) (*beta+0.5) >= (8*sizeof(size_t)))
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"ShiftCountOverflow","`%s'",subexpression);
FxReturn(0.0);
}
value=(double) ((size_t) (alpha+0.5) << (size_t) (*beta+0.5));
if (SetFxSymbolValue(fx_info,subexpression,value) == MagickFalse)
return(0.0);
FxReturn(*beta);
}
case RightShiftAssignmentOperator:
{
q=subexpression;
while (isalpha((int) ((unsigned char) *q)) != 0)
q++;
if (*q != '\0')
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"UnableToParseExpression","`%s'",subexpression);
FxReturn(0.0);
}
ClearMagickException(exception);
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
if ((size_t) (*beta+0.5) >= (8*sizeof(size_t)))
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"ShiftCountOverflow","`%s'",subexpression);
FxReturn(0.0);
}
value=(double) ((size_t) (alpha+0.5) >> (size_t) (*beta+0.5));
if (SetFxSymbolValue(fx_info,subexpression,value) == MagickFalse)
return(0.0);
FxReturn(*beta);
}
case PowerAssignmentOperator:
{
q=subexpression;
while (isalpha((int) ((unsigned char) *q)) != 0)
q++;
if (*q != '\0')
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"UnableToParseExpression","`%s'",subexpression);
FxReturn(0.0);
}
ClearMagickException(exception);
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
value=pow(alpha,*beta);
if (SetFxSymbolValue(fx_info,subexpression,value) == MagickFalse)
return(0.0);
FxReturn(*beta);
}
case ModuloAssignmentOperator:
{
q=subexpression;
while (isalpha((int) ((unsigned char) *q)) != 0)
q++;
if (*q != '\0')
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"UnableToParseExpression","`%s'",subexpression);
FxReturn(0.0);
}
ClearMagickException(exception);
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
value=fmod(alpha,*beta);
if (SetFxSymbolValue(fx_info,subexpression,value) == MagickFalse)
return(0.0);
FxReturn(*beta);
}
case PlusAssignmentOperator:
{
q=subexpression;
while (isalpha((int) ((unsigned char) *q)) != 0)
q++;
if (*q != '\0')
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"UnableToParseExpression","`%s'",subexpression);
FxReturn(0.0);
}
ClearMagickException(exception);
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
value=alpha+(*beta);
if (SetFxSymbolValue(fx_info,subexpression,value) == MagickFalse)
return(0.0);
FxReturn(*beta);
}
case SubtractAssignmentOperator:
{
q=subexpression;
while (isalpha((int) ((unsigned char) *q)) != 0)
q++;
if (*q != '\0')
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"UnableToParseExpression","`%s'",subexpression);
FxReturn(0.0);
}
ClearMagickException(exception);
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
value=alpha-(*beta);
if (SetFxSymbolValue(fx_info,subexpression,value) == MagickFalse)
return(0.0);
FxReturn(*beta);
}
case MultiplyAssignmentOperator:
{
q=subexpression;
while (isalpha((int) ((unsigned char) *q)) != 0)
q++;
if (*q != '\0')
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"UnableToParseExpression","`%s'",subexpression);
FxReturn(0.0);
}
ClearMagickException(exception);
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
value=alpha*(*beta);
if (SetFxSymbolValue(fx_info,subexpression,value) == MagickFalse)
return(0.0);
FxReturn(*beta);
}
case DivideAssignmentOperator:
{
q=subexpression;
while (isalpha((int) ((unsigned char) *q)) != 0)
q++;
if (*q != '\0')
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"UnableToParseExpression","`%s'",subexpression);
FxReturn(0.0);
}
ClearMagickException(exception);
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
value=alpha*PerceptibleReciprocal(*beta);
if (SetFxSymbolValue(fx_info,subexpression,value) == MagickFalse)
return(0.0);
FxReturn(*beta);
}
case IncrementAssignmentOperator:
{
if (*subexpression == '\0')
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
value=alpha+1.0;
if (*subexpression == '\0')
{
if (SetFxSymbolValue(fx_info,p,value) == MagickFalse)
return(0.0);
}
else
if (SetFxSymbolValue(fx_info,subexpression,value) == MagickFalse)
return(0.0);
FxReturn(*beta);
}
case DecrementAssignmentOperator:
{
if (*subexpression == '\0')
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
value=alpha-1.0;
if (*subexpression == '\0')
{
if (SetFxSymbolValue(fx_info,p,value) == MagickFalse)
return(0.0);
}
else
if (SetFxSymbolValue(fx_info,subexpression,value) == MagickFalse)
return(0.0);
FxReturn(*beta);
}
case LeftShiftOperator:
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
if ((size_t) (gamma+0.5) >= (8*sizeof(size_t)))
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"ShiftCountOverflow","`%s'",subexpression);
FxReturn(0.0);
}
*beta=(double) ((size_t) (alpha+0.5) << (size_t) (gamma+0.5));
FxReturn(*beta);
}
case RightShiftOperator:
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
if ((size_t) (gamma+0.5) >= (8*sizeof(size_t)))
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"ShiftCountOverflow","`%s'",subexpression);
FxReturn(0.0);
}
*beta=(double) ((size_t) (alpha+0.5) >> (size_t) (gamma+0.5));
FxReturn(*beta);
}
case '<':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha < *beta ? 1.0 : 0.0);
}
case LessThanEqualOperator:
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha <= *beta ? 1.0 : 0.0);
}
case '>':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha > *beta ? 1.0 : 0.0);
}
case GreaterThanEqualOperator:
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha >= *beta ? 1.0 : 0.0);
}
case EqualOperator:
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(fabs(alpha-(*beta)) < MagickEpsilon ? 1.0 : 0.0);
}
case NotEqualOperator:
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(fabs(alpha-(*beta)) >= MagickEpsilon ? 1.0 : 0.0);
}
case '&':
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
*beta=(double) ((size_t) (alpha+0.5) & (size_t) (gamma+0.5));
FxReturn(*beta);
}
case '|':
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
*beta=(double) ((size_t) (alpha+0.5) | (size_t) (gamma+0.5));
FxReturn(*beta);
}
case LogicalAndOperator:
{
p++;
if (alpha <= 0.0)
{
*beta=0.0;
FxReturn(*beta);
}
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,beta,
exception);
*beta=(gamma > 0.0) ? 1.0 : 0.0;
FxReturn(*beta);
}
case LogicalOrOperator:
{
p++;
if (alpha > 0.0)
{
*beta=1.0;
FxReturn(*beta);
}
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,beta,
exception);
*beta=(gamma > 0.0) ? 1.0 : 0.0;
FxReturn(*beta);
}
case '?':
{
(void) CopyMagickString(subexpression,++p,MagickPathExtent-1);
FxParseConditional(subexpression,':',p,q);
if (fabs(alpha) >= MagickEpsilon)
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,beta,
exception);
else
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,q+1,depth+1,beta,
exception);
FxReturn(gamma);
}
case '=':
{
q=subexpression;
while (isalpha((int) ((unsigned char) *q)) != 0)
q++;
if (*q != '\0')
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"UnableToParseExpression","`%s'",subexpression);
FxReturn(0.0);
}
ClearMagickException(exception);
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
value=(*beta);
if (SetFxSymbolValue(fx_info,subexpression,value) == MagickFalse)
return(0.0);
FxReturn(*beta);
}
case ',':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha);
}
case ';':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(*beta);
}
default:
{
gamma=alpha*FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,
beta,exception);
FxReturn(gamma);
}
}
}
if (strchr("(",(int) *expression) != (char *) NULL)
{
size_t
length;
if (depth >= FxMaxParenthesisDepth)
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"ParenthesisNestedTooDeeply","`%s'",expression);
length=CopyMagickString(subexpression,expression+1,MagickPathExtent);
if (length != 0)
subexpression[length-1]='\0';
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,depth+1,
beta,exception);
FxReturn(gamma);
}
switch (*expression)
{
case '+':
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,expression+1,depth+1,
beta,exception);
FxReturn(1.0*gamma);
}
case '-':
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,expression+1,depth+1,
beta,exception);
FxReturn(-1.0*gamma);
}
case '~':
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,expression+1,depth+1,
beta,exception);
FxReturn((double) (~(size_t) (gamma+0.5)));
}
case 'A':
case 'a':
{
if (IsFxFunction(expression,"abs",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(fabs(alpha));
}
#if defined(MAGICKCORE_HAVE_ACOSH)
if (IsFxFunction(expression,"acosh",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(acosh(alpha));
}
#endif
if (IsFxFunction(expression,"acos",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(acos(alpha));
}
#if defined(MAGICKCORE_HAVE_J1)
if (IsFxFunction(expression,"airy",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
if (alpha == 0.0)
FxReturn(1.0);
gamma=2.0*j1((MagickPI*alpha))/(MagickPI*alpha);
FxReturn(gamma*gamma);
}
#endif
#if defined(MAGICKCORE_HAVE_ASINH)
if (IsFxFunction(expression,"asinh",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(asinh(alpha));
}
#endif
if (IsFxFunction(expression,"asin",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(asin(alpha));
}
if (IsFxFunction(expression,"alt",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(((ssize_t) alpha) & 0x01 ? -1.0 : 1.0);
}
if (IsFxFunction(expression,"atan2",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(atan2(alpha,*beta));
}
#if defined(MAGICKCORE_HAVE_ATANH)
if (IsFxFunction(expression,"atanh",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(atanh(alpha));
}
#endif
if (IsFxFunction(expression,"atan",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(atan(alpha));
}
if (LocaleCompare(expression,"a") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'B':
case 'b':
{
if (LocaleCompare(expression,"b") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'C':
case 'c':
{
if (IsFxFunction(expression,"ceil",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(ceil(alpha));
}
if (IsFxFunction(expression,"clamp",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
if (alpha < 0.0)
FxReturn(0.0);
if (alpha > 1.0)
FxReturn(1.0);
FxReturn(alpha);
}
if (IsFxFunction(expression,"cosh",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(cosh(alpha));
}
if (IsFxFunction(expression,"cos",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(cos(alpha));
}
if (LocaleCompare(expression,"c") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'D':
case 'd':
{
if (IsFxFunction(expression,"debug",5) != MagickFalse)
{
const char
*type;
size_t
length;
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
switch (fx_info->images->colorspace)
{
case CMYKColorspace:
{
switch (channel)
{
case CyanPixelChannel: type="cyan"; break;
case MagentaPixelChannel: type="magenta"; break;
case YellowPixelChannel: type="yellow"; break;
case AlphaPixelChannel: type="alpha"; break;
case BlackPixelChannel: type="black"; break;
default: type="unknown"; break;
}
break;
}
case GRAYColorspace:
{
switch (channel)
{
case RedPixelChannel: type="gray"; break;
case AlphaPixelChannel: type="alpha"; break;
default: type="unknown"; break;
}
break;
}
default:
{
switch (channel)
{
case RedPixelChannel: type="red"; break;
case GreenPixelChannel: type="green"; break;
case BluePixelChannel: type="blue"; break;
case AlphaPixelChannel: type="alpha"; break;
default: type="unknown"; break;
}
break;
}
}
*subexpression='\0';
length=1;
if (strlen(expression) > 6)
length=CopyMagickString(subexpression,expression+6,
MagickPathExtent);
if (length != 0)
subexpression[length-1]='\0';
if (fx_info->file != (FILE *) NULL)
(void) FormatLocaleFile(fx_info->file,"%s[%.20g,%.20g].%s: "
"%s=%.*g\n",fx_info->images->filename,(double) x,(double) y,type,
subexpression,GetMagickPrecision(),alpha);
FxReturn(alpha);
}
if (IsFxFunction(expression,"do",2) != MagickFalse)
{
size_t
length;
/*
Parse do(expression,condition test).
*/
length=CopyMagickString(subexpression,expression+3,
MagickPathExtent-1);
if (length != 0)
subexpression[length-1]='\0';
FxParseConditional(subexpression,',',p,q);
for (alpha=0.0; ; )
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,q+1,depth+1,beta,
exception);
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,&sans,
exception);
if (fabs(gamma) < MagickEpsilon)
break;
}
FxReturn(alpha);
}
if (IsFxFunction(expression,"drc",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn((alpha/(*beta*(alpha-1.0)+1.0)));
}
break;
}
case 'E':
case 'e':
{
if (LocaleCompare(expression,"epsilon") == 0)
FxReturn(MagickEpsilon);
#if defined(MAGICKCORE_HAVE_ERF)
if (IsFxFunction(expression,"erf",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(erf(alpha));
}
#endif
if (IsFxFunction(expression,"exp",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(exp(alpha));
}
if (LocaleCompare(expression,"e") == 0)
FxReturn(2.7182818284590452354);
break;
}
case 'F':
case 'f':
{
if (IsFxFunction(expression,"floor",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(floor(alpha));
}
if (IsFxFunction(expression,"for",3) != MagickFalse)
{
double
sans = 0.0;
size_t
length;
/*
Parse for(initialization, condition test, expression).
*/
length=CopyMagickString(subexpression,expression+4,
MagickPathExtent-1);
if (length != 0)
subexpression[length-1]='\0';
FxParseConditional(subexpression,',',p,q);
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,&sans,
exception);
(void) CopyMagickString(subexpression,q+1,MagickPathExtent-1);
FxParseConditional(subexpression,',',p,q);
for (alpha=0.0; ; )
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,&sans,
exception);
if (fabs(gamma) < MagickEpsilon)
break;
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,q+1,depth+1,beta,
exception);
}
FxReturn(alpha);
}
break;
}
case 'G':
case 'g':
{
if (IsFxFunction(expression,"gauss",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(exp((-alpha*alpha/2.0))/sqrt(2.0*MagickPI));
}
if (IsFxFunction(expression,"gcd",3) != MagickFalse)
{
double
gcd;
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
gcd=FxGCD(alpha,*beta);
FxReturn(gcd);
}
if (LocaleCompare(expression,"g") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(expression,"h") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
if (LocaleCompare(expression,"hue") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
if (IsFxFunction(expression,"hypot",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(hypot(alpha,*beta));
}
break;
}
case 'K':
case 'k':
{
if (LocaleCompare(expression,"k") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'I':
case 'i':
{
if (IsFxFunction(expression,"if",2) != MagickFalse)
{
double
sans = 0.0;
size_t
length;
length=CopyMagickString(subexpression,expression+3,
MagickPathExtent-1);
if (length != 0)
subexpression[length-1]='\0';
FxParseConditional(subexpression,',',p,q);
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,&sans,
exception);
(void) CopyMagickString(subexpression,q+1,MagickPathExtent-1);
FxParseConditional(subexpression,',',p,q);
if (fabs(alpha) >= MagickEpsilon)
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,beta,
exception);
else
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,q+1,depth+1,beta,
exception);
FxReturn(alpha);
}
if (LocaleCompare(expression,"intensity") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
if (IsFxFunction(expression,"int",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(floor(alpha));
}
if (IsFxFunction(expression,"isnan",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn((double) !!IsNaN(alpha));
}
if (LocaleCompare(expression,"i") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'J':
case 'j':
{
if (LocaleCompare(expression,"j") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
#if defined(MAGICKCORE_HAVE_J0)
if (IsFxFunction(expression,"j0",2) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2,
depth+1,beta,exception);
FxReturn(j0(alpha));
}
#endif
#if defined(MAGICKCORE_HAVE_J1)
if (IsFxFunction(expression,"j1",2) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2,
depth+1,beta,exception);
FxReturn(j1(alpha));
}
#endif
#if defined(MAGICKCORE_HAVE_J1)
if (IsFxFunction(expression,"jinc",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
if (alpha == 0.0)
FxReturn(1.0);
FxReturn((2.0*j1((MagickPI*alpha))/(MagickPI*alpha)));
}
#endif
break;
}
case 'L':
case 'l':
{
if (IsFxFunction(expression,"ln",2) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2,
depth+1,beta,exception);
FxReturn(log(alpha));
}
if (IsFxFunction(expression,"logtwo",6) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+6,
depth+1,beta,exception);
FxReturn(log10(alpha)/log10(2.0));
}
if (IsFxFunction(expression,"log",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(log10(alpha));
}
if (LocaleCompare(expression,"lightness") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'M':
case 'm':
{
if (LocaleCompare(expression,"MaxRGB") == 0)
FxReturn(QuantumRange);
if (LocaleNCompare(expression,"maxima",6) == 0)
break;
if (IsFxFunction(expression,"max",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(alpha > *beta ? alpha : *beta);
}
if (LocaleNCompare(expression,"minima",6) == 0)
break;
if (IsFxFunction(expression,"min",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(alpha < *beta ? alpha : *beta);
}
if (IsFxFunction(expression,"mod",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(alpha-floor((alpha*PerceptibleReciprocal(*beta)))*(*beta));
}
if (LocaleCompare(expression,"m") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'N':
case 'n':
{
if (IsFxFunction(expression,"not",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn((double) (alpha < MagickEpsilon));
}
if (LocaleCompare(expression,"n") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(expression,"Opaque") == 0)
FxReturn(1.0);
if (LocaleCompare(expression,"o") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(expression,"phi") == 0)
FxReturn(MagickPHI);
if (LocaleCompare(expression,"pi") == 0)
FxReturn(MagickPI);
if (IsFxFunction(expression,"pow",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(pow(alpha,*beta));
}
if (LocaleCompare(expression,"p") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'Q':
case 'q':
{
if (LocaleCompare(expression,"QuantumRange") == 0)
FxReturn(QuantumRange);
if (LocaleCompare(expression,"QuantumScale") == 0)
FxReturn(QuantumScale);
break;
}
case 'R':
case 'r':
{
if (IsFxFunction(expression,"rand",4) != MagickFalse)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_FxEvaluateSubexpression)
#endif
alpha=GetPseudoRandomValue(fx_info->random_info);
FxReturn(alpha);
}
if (IsFxFunction(expression,"round",5) != MagickFalse)
{
/*
Round the fraction to nearest integer.
*/
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
if ((alpha-floor(alpha)) < (ceil(alpha)-alpha))
FxReturn(floor(alpha));
FxReturn(ceil(alpha));
}
if (LocaleCompare(expression,"r") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'S':
case 's':
{
if (LocaleCompare(expression,"saturation") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
if (IsFxFunction(expression,"sign",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(alpha < 0.0 ? -1.0 : 1.0);
}
if (IsFxFunction(expression,"sinc",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
if (alpha == 0)
FxReturn(1.0);
FxReturn(sin((MagickPI*alpha))/(MagickPI*alpha));
}
if (IsFxFunction(expression,"sinh",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(sinh(alpha));
}
if (IsFxFunction(expression,"sin",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(sin(alpha));
}
if (IsFxFunction(expression,"sqrt",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(sqrt(alpha));
}
if (IsFxFunction(expression,"squish",6) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+6,
depth+1,beta,exception);
FxReturn((1.0/(1.0+exp(-alpha))));
}
if (LocaleCompare(expression,"s") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'T':
case 't':
{
if (IsFxFunction(expression,"tanh",4) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(tanh(alpha));
}
if (IsFxFunction(expression,"tan",3) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(tan(alpha));
}
if (LocaleCompare(expression,"Transparent") == 0)
FxReturn(0.0);
if (IsFxFunction(expression,"trunc",5) != MagickFalse)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
if (alpha >= 0.0)
FxReturn(floor(alpha));
FxReturn(ceil(alpha));
}
if (LocaleCompare(expression,"t") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'U':
case 'u':
{
if (LocaleCompare(expression,"u") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'V':
case 'v':
{
if (LocaleCompare(expression,"v") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'W':
case 'w':
{
if (IsFxFunction(expression,"while",5) != MagickFalse)
{
size_t
length;
/*
Parse while(condition test, expression).
*/
length=CopyMagickString(subexpression,expression+6,
MagickPathExtent-1);
if (length != 0)
subexpression[length-1]='\0';
FxParseConditional(subexpression,',',p,q);
for (alpha=0.0; ; )
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,&sans,
exception);
if (fabs(gamma) < MagickEpsilon)
break;
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,q+1,depth+1,
beta,exception);
}
FxReturn(alpha);
}
if (LocaleCompare(expression,"w") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(expression,"y") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'Z':
case 'z':
{
if (LocaleCompare(expression,"z") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
default:
break;
}
subexpression=DestroyString(subexpression);
q=(char *) expression;
alpha=InterpretSiPrefixValue(expression,&q);
if (q == expression)
alpha=FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception);
FxReturn(alpha);
}
MagickPrivate MagickBooleanType FxEvaluateExpression(FxInfo *fx_info,
double *alpha,ExceptionInfo *exception)
{
MagickBooleanType
status;
status=FxEvaluateChannelExpression(fx_info,GrayPixelChannel,0,0,alpha,
exception);
return(status);
}
MagickExport MagickBooleanType FxPreprocessExpression(FxInfo *fx_info,
double *alpha,ExceptionInfo *exception)
{
FILE
*file;
MagickBooleanType
status;
file=fx_info->file;
fx_info->file=(FILE *) NULL;
status=FxEvaluateChannelExpression(fx_info,GrayPixelChannel,0,0,alpha,
exception);
fx_info->file=file;
return(status);
}
MagickPrivate MagickBooleanType FxEvaluateChannelExpression(FxInfo *fx_info,
const PixelChannel channel,const ssize_t x,const ssize_t y,
double *alpha,ExceptionInfo *exception)
{
double
beta;
beta=0.0;
*alpha=FxEvaluateSubexpression(fx_info,channel,x,y,fx_info->expression,0,
&beta,exception);
return(exception->severity == OptionError ? MagickFalse : MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F x I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FxImage() applies a mathematical expression to the specified image.
%
% The format of the FxImage method is:
%
% Image *FxImage(const Image *image,const char *expression,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o expression: A mathematical expression.
%
% o exception: return any errors or warnings in this structure.
%
*/
static FxInfo **DestroyFxThreadSet(FxInfo **fx_info)
{
ssize_t
i;
assert(fx_info != (FxInfo **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (fx_info[i] != (FxInfo *) NULL)
fx_info[i]=DestroyFxInfo(fx_info[i]);
fx_info=(FxInfo **) RelinquishMagickMemory(fx_info);
return(fx_info);
}
static FxInfo **AcquireFxThreadSet(const Image *image,const char *expression,
ExceptionInfo *exception)
{
char
*fx_expression;
double
alpha;
FxInfo
**fx_info;
ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
fx_info=(FxInfo **) AcquireQuantumMemory(number_threads,sizeof(*fx_info));
if (fx_info == (FxInfo **) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return((FxInfo **) NULL);
}
(void) memset(fx_info,0,number_threads*sizeof(*fx_info));
if (*expression != '@')
fx_expression=ConstantString(expression);
else
fx_expression=FileToString(expression+1,~0UL,exception);
for (i=0; i < (ssize_t) number_threads; i++)
{
MagickBooleanType
status;
fx_info[i]=AcquireFxInfo(image,fx_expression,exception);
if (fx_info[i] == (FxInfo *) NULL)
break;
status=FxPreprocessExpression(fx_info[i],&alpha,exception);
if (status == MagickFalse)
break;
}
fx_expression=DestroyString(fx_expression);
if (i < (ssize_t) number_threads)
fx_info=DestroyFxThreadSet(fx_info);
return(fx_info);
}
MagickExport Image *FxImage(const Image *image,const char *expression,
ExceptionInfo *exception)
{
#define FxImageTag "Fx/Image"
CacheView
*fx_view,
*image_view;
FxInfo
**magick_restrict fx_info;
Image
*fx_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (expression == (const char *) NULL)
return(CloneImage(image,0,0,MagickTrue,exception));
fx_info=AcquireFxThreadSet(image,expression,exception);
if (fx_info == (FxInfo **) NULL)
return((Image *) NULL);
fx_image=CloneImage(image,0,0,MagickTrue,exception);
if (fx_image == (Image *) NULL)
{
fx_info=DestroyFxThreadSet(fx_info);
return((Image *) NULL);
}
if (SetImageStorageClass(fx_image,DirectClass,exception) == MagickFalse)
{
fx_info=DestroyFxThreadSet(fx_info);
fx_image=DestroyImage(fx_image);
return((Image *) NULL);
}
/*
Fx image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
fx_view=AcquireAuthenticCacheView(fx_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic) shared(progress,status) \
magick_number_threads(image,fx_image,fx_image->rows,1)
#endif
for (y=0; y < (ssize_t) fx_image->rows; y++)
{
const int
id = GetOpenMPThreadId();
const Quantum
*magick_restrict p;
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(fx_view,0,y,fx_image->columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) fx_image->columns; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
alpha;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait fx_traits=GetPixelChannelTraits(fx_image,channel);
if ((traits == UndefinedPixelTrait) ||
(fx_traits == UndefinedPixelTrait))
continue;
if ((fx_traits & CopyPixelTrait) != 0)
{
SetPixelChannel(fx_image,channel,p[i],q);
continue;
}
alpha=0.0;
(void) FxEvaluateChannelExpression(fx_info[id],channel,x,y,&alpha,
exception);
q[i]=ClampToQuantum(QuantumRange*alpha);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(fx_image);
}
if (SyncCacheViewAuthenticPixels(fx_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,FxImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
fx_view=DestroyCacheView(fx_view);
image_view=DestroyCacheView(image_view);
fx_info=DestroyFxThreadSet(fx_info);
if (status == MagickFalse)
fx_image=DestroyImage(fx_image);
return(fx_image);
}
|
GB_binop__times_uint16.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__times_uint16)
// A.*B function (eWiseMult): GB (_AemultB_08__times_uint16)
// A.*B function (eWiseMult): GB (_AemultB_02__times_uint16)
// A.*B function (eWiseMult): GB (_AemultB_04__times_uint16)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__times_uint16)
// A*D function (colscale): GB (_AxD__times_uint16)
// D*A function (rowscale): GB (_DxB__times_uint16)
// C+=B function (dense accum): GB (_Cdense_accumB__times_uint16)
// C+=b function (dense accum): GB (_Cdense_accumb__times_uint16)
// C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__times_uint16)
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__times_uint16)
// C=scalar+B GB (_bind1st__times_uint16)
// C=scalar+B' GB (_bind1st_tran__times_uint16)
// C=A+scalar GB (_bind2nd__times_uint16)
// C=A'+scalar GB (_bind2nd_tran__times_uint16)
// C type: uint16_t
// A type: uint16_t
// A pattern? 0
// B type: uint16_t
// B pattern? 0
// BinaryOp: cij = (aij * bij)
#define GB_ATYPE \
uint16_t
#define GB_BTYPE \
uint16_t
#define GB_CTYPE \
uint16_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) \
uint16_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) \
uint16_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) \
uint16_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_TIMES || GxB_NO_UINT16 || GxB_NO_TIMES_UINT16)
//------------------------------------------------------------------------------
// 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__times_uint16)
(
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__times_uint16)
(
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__times_uint16)
(
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__times_uint16)
(
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 uint16_t
uint16_t bwork = (*((uint16_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__times_uint16)
(
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
uint16_t *restrict Cx = (uint16_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__times_uint16)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint16_t *restrict Cx = (uint16_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__times_uint16)
(
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) ;
uint16_t alpha_scalar ;
uint16_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((uint16_t *) alpha_scalar_in)) ;
beta_scalar = (*((uint16_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__times_uint16)
(
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__times_uint16)
(
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__times_uint16)
(
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__times_uint16)
(
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__times_uint16)
(
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
uint16_t *Cx = (uint16_t *) Cx_output ;
uint16_t x = (*((uint16_t *) x_input)) ;
uint16_t *Bx = (uint16_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 ;
uint16_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__times_uint16)
(
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 ;
uint16_t *Cx = (uint16_t *) Cx_output ;
uint16_t *Ax = (uint16_t *) Ax_input ;
uint16_t y = (*((uint16_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
uint16_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) \
{ \
uint16_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x * aij) ; \
}
GrB_Info GB (_bind1st_tran__times_uint16)
(
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 \
uint16_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint16_t x = (*((const uint16_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint16_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) \
{ \
uint16_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij * y) ; \
}
GrB_Info GB (_bind2nd_tran__times_uint16)
(
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
uint16_t y = (*((const uint16_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_unop__identity_int16_fp32.c
|
//------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__identity_int16_fp32)
// op(A') function: GB (_unop_tran__identity_int16_fp32)
// C type: int16_t
// A type: float
// cast: int16_t cij = GB_cast_to_int16_t ((double) (aij))
// unaryop: cij = aij
#define GB_ATYPE \
float
#define GB_CTYPE \
int16_t
// 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_CAST(z, aij) \
int16_t z = GB_cast_to_int16_t ((double) (aij)) ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
float aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
int16_t z = GB_cast_to_int16_t ((double) (aij)) ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_INT16 || GxB_NO_FP32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_int16_fp32)
(
int16_t *Cx, // Cx and Ax may be aliased
const float *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
float aij = Ax [p] ;
int16_t z = GB_cast_to_int16_t ((double) (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 ;
float aij = Ax [p] ;
int16_t z = GB_cast_to_int16_t ((double) (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_int16_fp32)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
core_ztrsm.c
|
/**
*
* @file
*
* PLASMA is a software package provided by:
* University of Tennessee, US,
* University of Manchester, UK.
*
* @precisions normal z -> c d s
*
**/
#include "core_blas.h"
#include "plasma_types.h"
#include "core_lapack.h"
/***************************************************************************//**
*
* @ingroup core_trsm
*
* Solves one of the matrix equations
*
* \f[ op( A )\times X = \alpha B, \f] or
* \f[ X \times op( A ) = \alpha B, \f]
*
* where op( A ) is one of:
* \f[ op( A ) = A, \f]
* \f[ op( A ) = A^T, \f]
* \f[ op( A ) = A^H, \f]
*
* alpha is a scalar, X and B are m-by-n matrices, and
* A is a unit or non-unit, upper or lower triangular matrix.
* The matrix X overwrites B.
*
*******************************************************************************
*
* @param[in] side
* - PlasmaLeft: op(A)*X = B,
* - PlasmaRight: X*op(A) = B.
*
* @param[in] uplo
* - PlasmaUpper: A is upper triangular,
* - PlasmaLower: A is lower triangular.
*
* @param[in] transa
* - PlasmaNoTrans: A is not transposed,
* - PlasmaTrans: A is transposed,
* - PlasmaConjTrans: A is conjugate transposed.
*
* @param[in] diag
* - PlasmaNonUnit: A has non-unit diagonal,
* - PlasmaUnit: A has unit diagonal.
*
* @param[in] m
* The number of rows of the matrix B. m >= 0.
*
* @param[in] n
* The number of columns of the matrix B. n >= 0.
*
* @param[in] alpha
* The scalar alpha.
*
* @param[in] A
* The lda-by-ka triangular matrix,
* where ka = m if side = PlasmaLeft,
* and ka = n if side = PlasmaRight.
* 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. lda >= max(1,k).
*
* @param[in,out] B
* On entry, the ldb-by-n right hand side matrix B.
* On exit, if return value = 0, the ldb-by-n solution matrix X.
*
* @param[in] ldb
* The leading dimension of the array B. ldb >= max(1,m).
*
******************************************************************************/
void core_ztrsm(plasma_enum_t side, plasma_enum_t uplo,
plasma_enum_t transa, plasma_enum_t diag,
int m, int n,
plasma_complex64_t alpha, const plasma_complex64_t *A, int lda,
plasma_complex64_t *B, int ldb)
{
cblas_ztrsm(CblasColMajor,
(CBLAS_SIDE)side, (CBLAS_UPLO)uplo,
(CBLAS_TRANSPOSE)transa, (CBLAS_DIAG)diag,
m, n,
CBLAS_SADDR(alpha), A, lda,
B, ldb);
}
/******************************************************************************/
void core_omp_ztrsm(
plasma_enum_t side, plasma_enum_t uplo,
plasma_enum_t transa, plasma_enum_t diag,
int m, int n,
plasma_complex64_t alpha, const plasma_complex64_t *A, int lda,
plasma_complex64_t *B, int ldb,
plasma_sequence_t *sequence, plasma_request_t *request)
{
int ak;
if (side == PlasmaLeft)
ak = m;
else
ak = n;
#pragma omp task depend(in:A[0:lda*ak]) \
depend(inout:B[0:ldb*n])
{
if (sequence->status == PlasmaSuccess)
core_ztrsm(side, uplo,
transa, diag,
m, n,
alpha, A, lda,
B, ldb);
}
}
|
GridInit.c
|
#include "XSbench_header.h"
SimulationData grid_init_do_not_profile( Inputs in, int mype )
{
// Structure to hold all allocated simuluation data arrays
SimulationData SD;
// Keep track of how much data we're allocating
size_t nbytes = 0;
// Set the initial seed value
uint64_t seed = 42;
////////////////////////////////////////////////////////////////////
// Initialize Nuclide Grids
////////////////////////////////////////////////////////////////////
if(mype == 0) printf("Intializing nuclide grids...\n");
// First, we need to initialize our nuclide grid. This comes in the form
// of a flattened 2D array that hold all the information we need to define
// the cross sections for all isotopes in the simulation.
// The grid is composed of "NuclideGridPoint" structures, which hold the
// energy level of the grid point and all associated XS data at that level.
// An array of structures (AOS) is used instead of
// a structure of arrays, as the grid points themselves are accessed in
// a random order, but all cross section interaction channels and the
// energy level are read whenever the gridpoint is accessed, meaning the
// AOS is more cache efficient.
// Initialize Nuclide Grid
SD.length_nuclide_grid = in.n_isotopes * in.n_gridpoints;
SD.nuclide_grid = (NuclideGridPoint *) malloc( SD.length_nuclide_grid * sizeof(NuclideGridPoint));
assert(SD.nuclide_grid != NULL);
nbytes += SD.length_nuclide_grid * sizeof(NuclideGridPoint);
for( int i = 0; i < SD.length_nuclide_grid; i++ )
{
SD.nuclide_grid[i].energy = LCG_random_double(&seed);
SD.nuclide_grid[i].total_xs = LCG_random_double(&seed);
SD.nuclide_grid[i].elastic_xs = LCG_random_double(&seed);
SD.nuclide_grid[i].absorbtion_xs = LCG_random_double(&seed);
SD.nuclide_grid[i].fission_xs = LCG_random_double(&seed);
SD.nuclide_grid[i].nu_fission_xs = LCG_random_double(&seed);
}
// Sort so that each nuclide has data stored in ascending energy order.
for( int i = 0; i < in.n_isotopes; i++ )
qsort( &SD.nuclide_grid[i*in.n_gridpoints], in.n_gridpoints, sizeof(NuclideGridPoint), NGP_compare);
// error debug check
/*
for( int i = 0; i < in.n_isotopes; i++ )
{
printf("NUCLIDE %d ==============================\n", i);
for( int j = 0; j < in.n_gridpoints; j++ )
printf("E%d = %lf\n", j, SD.nuclide_grid[i * in.n_gridpoints + j].energy);
}
*/
////////////////////////////////////////////////////////////////////
// Initialize Acceleration Structure
////////////////////////////////////////////////////////////////////
if( in.grid_type == NUCLIDE )
{
SD.length_unionized_energy_array = 0;
SD.length_index_grid = 0;
}
if( in.grid_type == UNIONIZED )
{
if(mype == 0) printf("Intializing unionized grid...\n");
// Allocate space to hold the union of all nuclide energy data
SD.length_unionized_energy_array = in.n_isotopes * in.n_gridpoints;
SD.unionized_energy_array = (double *) malloc( SD.length_unionized_energy_array * sizeof(double));
assert(SD.unionized_energy_array != NULL );
nbytes += SD.length_unionized_energy_array * sizeof(double);
// Copy energy data over from the nuclide energy grid
for( int i = 0; i < SD.length_unionized_energy_array; i++ )
SD.unionized_energy_array[i] = SD.nuclide_grid[i].energy;
// Sort unionized energy array
qsort( SD.unionized_energy_array, SD.length_unionized_energy_array, sizeof(double), double_compare);
// Allocate space to hold the acceleration grid indices
SD.length_index_grid = SD.length_unionized_energy_array * in.n_isotopes;
SD.index_grid = (int *) malloc( SD.length_index_grid * sizeof(int));
assert(SD.index_grid != NULL);
nbytes += SD.length_index_grid * sizeof(int);
// Generates the double indexing grid
int * idx_low = (int *) calloc( in.n_isotopes, sizeof(int));
assert(idx_low != NULL );
double * energy_high = (double *) malloc( in.n_isotopes * sizeof(double));
assert(energy_high != NULL );
for( int i = 0; i < in.n_isotopes; i++ )
energy_high[i] = SD.nuclide_grid[i * in.n_gridpoints + 1].energy;
for( long e = 0; e < SD.length_unionized_energy_array; e++ )
{
double unionized_energy = SD.unionized_energy_array[e];
for( long i = 0; i < in.n_isotopes; i++ )
{
if( unionized_energy < energy_high[i] )
SD.index_grid[e * in.n_isotopes + i] = idx_low[i];
else if( idx_low[i] == in.n_gridpoints - 2 )
SD.index_grid[e * in.n_isotopes + i] = idx_low[i];
else
{
idx_low[i]++;
SD.index_grid[e * in.n_isotopes + i] = idx_low[i];
energy_high[i] = SD.nuclide_grid[i * in.n_gridpoints + idx_low[i] + 1].energy;
}
}
}
free(idx_low);
free(energy_high);
}
if( in.grid_type == HASH )
{
if(mype == 0) printf("Intializing hash grid...\n");
SD.length_unionized_energy_array = 0;
SD.length_index_grid = in.hash_bins * in.n_isotopes;
SD.index_grid = (int *) malloc( SD.length_index_grid * sizeof(int));
assert(SD.index_grid != NULL);
nbytes += SD.length_index_grid * sizeof(int);
double du = 1.0 / in.hash_bins;
// For each energy level in the hash table
#pragma omp parallel for
for( long e = 0; e < in.hash_bins; e++ )
{
double energy = e * du;
// We need to determine the bounding energy levels for all isotopes
for( long i = 0; i < in.n_isotopes; i++ )
{
SD.index_grid[e * in.n_isotopes + i] = grid_search_nuclide( in.n_gridpoints, energy, SD.nuclide_grid + i * in.n_gridpoints, 0, in.n_gridpoints-1);
}
}
}
////////////////////////////////////////////////////////////////////
// Initialize Materials and Concentrations
////////////////////////////////////////////////////////////////////
if(mype == 0) printf("Intializing material data...\n");
// Set the number of nuclides in each material
SD.num_nucs = load_num_nucs(in.n_isotopes);
SD.length_num_nucs = 12; // There are always 12 materials in XSBench
// Intialize the flattened 2D grid of material data. The grid holds
// a list of nuclide indices for each of the 12 material types. The
// grid is allocated as a full square grid, even though not all
// materials have the same number of nuclides.
SD.mats = load_mats(SD.num_nucs, in.n_isotopes, &SD.max_num_nucs);
SD.length_mats = SD.length_num_nucs * SD.max_num_nucs;
// Intialize the flattened 2D grid of nuclide concentration data. The grid holds
// a list of nuclide concentrations for each of the 12 material types. The
// grid is allocated as a full square grid, even though not all
// materials have the same number of nuclides.
SD.concs = load_concs(SD.num_nucs, SD.max_num_nucs);
SD.length_concs = SD.length_mats;
// Allocate and initialize replicas
#ifdef AML
// num_nucs
aml_replicaset_hwloc_create(&(SD.num_nucs_replica),
SD.length_num_nucs * sizeof(*(SD.num_nucs)),
HWLOC_OBJ_CORE,
HWLOC_DISTANCES_KIND_FROM_OS |
HWLOC_DISTANCES_KIND_MEANS_LATENCY);
nbytes += (SD.num_nucs_replica)->n * (SD.num_nucs_replica)->size;
aml_replicaset_init(SD.num_nucs_replica, SD.num_nucs);
// concs
aml_replicaset_hwloc_create(&(SD.concs_replica),
SD.length_concs * sizeof(*(SD.concs)),
HWLOC_OBJ_CORE,
HWLOC_DISTANCES_KIND_FROM_OS |
HWLOC_DISTANCES_KIND_MEANS_LATENCY);
nbytes += (SD.concs_replica)->n * (SD.concs_replica)->size;
aml_replicaset_init(SD.concs_replica, SD.concs);
// unionized_energy_array
if( in.grid_type == UNIONIZED ){
aml_replicaset_hwloc_create(&(SD.unionized_energy_array_replica),
SD.length_unionized_energy_array * sizeof(*(SD.unionized_energy_array)),
HWLOC_OBJ_CORE,
HWLOC_DISTANCES_KIND_FROM_OS |
HWLOC_DISTANCES_KIND_MEANS_LATENCY);
nbytes += (SD.unionized_energy_array_replica)->n * (SD.unionized_energy_array_replica)->size;
aml_replicaset_init(SD.unionized_energy_array_replica, SD.unionized_energy_array);
}
// index grid
if( in.grid_type == UNIONIZED || in.grid_type == HASH ){
aml_replicaset_hwloc_create(&(SD.index_grid_replica),
SD.length_index_grid * sizeof(*(SD.index_grid)),
HWLOC_OBJ_CORE,
HWLOC_DISTANCES_KIND_FROM_OS |
HWLOC_DISTANCES_KIND_MEANS_LATENCY);
nbytes += (SD.index_grid_replica)->n * (SD.index_grid_replica)->size;
aml_replicaset_init(SD.index_grid_replica, SD.index_grid);
}
// nuclide grid
aml_replicaset_hwloc_create(&(SD.nuclide_grid_replica),
SD.length_nuclide_grid * sizeof(*(SD.nuclide_grid)),
HWLOC_OBJ_CORE,
HWLOC_DISTANCES_KIND_FROM_OS |
HWLOC_DISTANCES_KIND_MEANS_LATENCY);
nbytes += (SD.nuclide_grid_replica)->n * (SD.nuclide_grid_replica)->size;
aml_replicaset_init(SD.nuclide_grid_replica, SD.nuclide_grid);
#endif
if(mype == 0) printf("Intialization complete. Allocated %.0lf MB of data.\n", nbytes/1024.0/1024.0 );
return SD;
}
|
looptc_c4.c
|
#include <string.h>
void deinterleave(char *page, char *transposed, const int ntabs, const int nchannels, const int ntimes, const int padded_size) {
int tab;
for (tab = 0; tab < ntabs; tab++) {
// unroll time dimension 4x
int time;
for (time = 0; time < ntimes; time+=4) {
// build temporary array containing 4 complete channel rows
char temp[4 * nchannels];
int channel;
#pragma omp parallel for
for (channel = 0; channel < nchannels; channel++) {
// reverse freq order to comply with header
temp[1*nchannels-channel-1] = page[(tab*nchannels + channel) * padded_size + (time + 0)];
temp[2*nchannels-channel-1] = page[(tab*nchannels + channel) * padded_size + (time + 1)];
temp[3*nchannels-channel-1] = page[(tab*nchannels + channel) * padded_size + (time + 2)];
temp[4*nchannels-channel-1] = page[(tab*nchannels + channel) * padded_size + (time + 3)];
}
// copy 4 full row at once
memcpy(&transposed[time*nchannels], temp, 4*nchannels);
}
}
}
|
issue_001.c
|
#include <stdio.h>
#include "assert.h"
#include <unistd.h>
// 920 fails
#define TRIALS 600 //#919
// 6000 fails
#define N 64*5000
int main() {
int fail = 0;
double A[N], B[N], C[N];
for (int i = 0; i < N; i++) {
A[i] = 0.0;
B[i] = 0.0;
C[i] = 1.0;
}
int nte = 32;
int tl = 64;
int blockSize = tl;
for (int t = 0 ; t < TRIALS ; t++) {
#pragma omp target
#pragma omp teams num_teams(nte) thread_limit(tl)
{
#pragma omp distribute
for(int j = 0 ; j < N ; j += blockSize) {
#pragma omp parallel for
for(int i = j ; i < j+blockSize; i++) {
A[i] += B[i] + C[i];
}
}
}
}
for(int i = 0 ; i < N ; i++) {
if (A[i] != TRIALS) {
printf("Error at A[%d], h = %lf, d = %lf\n", i, (double) (2.0+3.0)*TRIALS, A[i]);
fail = 1;
break;
}
}
if(fail) {
printf("Failed\n");
return 1;
}
else {
printf("Succeeded\n");
return 0;
}
}
|
SymbolicDerivatives.h
|
#ifndef _SymbolicDerivatives_H_
#define _SymbolicDerivatives_H_
#ifdef _OPENMP
#include <omp.h>
#endif
// #define SYMBDER_WITH_MMVII true
#define SYMBDER_WITH_EIGEN false
#if SYMBDER_WITH_EIGEN
#include "ExternalInclude/Eigen/Dense" // TODO => replace with standard eigen file
#define EIGEN_ALLIGNMENT_IN_MMVII EIGEN_MAKE_ALIGNED_OPERATOR_NEW
#else
#define EIGEN_ALLIGNMENT_IN_MMVII
#endif
/*
*/
/** \file SymbolicDerivates.h
\brief File for generating symbolic derivate
Classes for generated symbolic derivative. All classes are single template classes.
The template parameter indicate the numerical type used for storage/computation
(float, double ...)
This file is the only file to include. It contains :
* declaration of operators
* definition of "main" classes : cFormula , cCoordinatorF , cImplemF " ;
* the 3 class for Atomic formula who will (probably) stay the same : Unkown, Observation, Constants
This file include 2 files corresponding to following type of formula :
* classes for "unary" formulas in "MMVII_FormDer_UnaryOp.h"
* classes for "binary" formulas in "MMVII_FormDer_BinaryOp.h"
These 2 files have "vocation" to be extended during the future.
-------------------------------------------------
* cFormula<Type> : represent a mathematicall formula; as in math :
- if F is a formula, exp(F), log(F) ....are formulas
- if F1 and F2 are formulas, F1+F2 , F1*F2 ... are formulas
- there exist some atomic formulas like constants, unknown and observations
- if F is a formula F->Derivate(k) is a formula corresponding to is derivate dF/dXk
Formulas are a complete algebric type.
* cCoordinatorF<Type> : is the "coordinator" class.
This class has, between others, the responsability of :
- creating the initial atomic formula corresponding to unknowns and observation
- maintain an inventory of existing formulas for efficiency purpose
* Using this library is mainly :
- create a coordinator with a given number of unkown and observations
- create a formula using atoms an operator, generally the user function creating a
formula will be a template that can operate on any complete algebric type
(double, float, Formula , jets ...)
- indicate to the coordinator the formula you want work on, with generally its derivate
- evaluate the values of the formula for given unknows and observations
cFormula<Type> is no more than an encapsulation of a pointer on the "concrete" class cImplemF.
* cImplemF<Type> : is the mother class of all the formula. It's a pure abstract class, it contains
several pure virtual methods. The two main methods are "Derivate" and "ComputeBuf", this is
the two methods the users will have to define when extension to the library with new
operator is required.
- cFormula<Type> Derivate(int aK) return the formula of its derivate by Xk. Heres is
two example extract from the code, one for multiplication, other from unknowns :
o return mF2*mF1->Derivate(aK) + mF1*mF2->Derivate(aK); // From cMulF : (FG)' = F'G + FG'
o return (aK==mNumUnk) ? tImplemF::mCoordF->Cste1() : tImplemF::mCoordF->Cste0(); // from cUnknownF
- void ComputeBuf(int aK0,int aK1) : update the buffer of its data, once it subformula has
been updated, this is method that does the real job. Here an extract from cExpF and cDivF :
o for (int aK=aK0 ; aK<aK1 ; aK++) mDataBuf[aK] = std::exp(mDataF[aK]);
o for (int aK=aK0 ; aK<aK1 ; aK++) mDataBuf[aK] = mDataF1[aK] / mDataF2[aK];
*/
#include "SymbDer_Common.h"
/*
#if (SYMBDER_WITH_MMVII)
#include "include/MMVII_all.h"
#include "include/MMVII_Derivatives.h"
#define SYMBDER_cMemCheck MMVII::cMemCheck
#else //========================================================== WITH_MMVI
class SYMBDER_cMemCheck
{
};
#endif
*/
#if (SYMBDER_WITH_MMVII)
#else
#include <memory>
#include <map>
#include <iostream>
#include <cassert>
#include "memory.h"
#include <memory>
#include <iostream>
#include <fstream>
#include <string>
#include <typeinfo>
#include <vector>
#include <list>
#include <map>
#include <ctime>
#include <chrono>
#include <math.h>
#include <cmath>
#include <algorithm>
#include <sstream>
#include <iomanip>
#endif //========================================================== WITH_MMVI
// REDUCTION RULES
// TODO => REPLACE BY METHOD ON COORDINATOR WHEN THEY IMPROVE THINGS ....
#define DOREDUCE false
#define REDUCE_CSTE true // Cste+Cste => cste
#define REDUCE_MM DOREDUCE // - - x => x ; a-(-b) => a+b
#define REDUCE_ASSOCP DOREDUCE /* B + (A + C) = > A + ( B + C),
more generally order the + operator, could be done with '*' */
#define REDUCE_DISTRIB DOREDUCE // A#B ~ A#C=> A#(B~C) ; # in "*/" and ~ in "+-"
#define REDUCE_ApA DOREDUCE // A+A => 2*A, not good by itself, but may creat other reduc
#define REDUCE_DIST1 DOREDUCE // A + A*C => A *(1+C) si C est csteto have all constant close
static inline void SHOW_REDUCE(const std::string & aMes) {} // std::cout << "REDUCE " << aMes << "\n";}
namespace NS_SymbolicDerivative
{
/* *************************************************** */
/* */
/* P0-Definition of global functions */
/* */
/* *************************************************** */
/// The CreateCste is required for formula, so we need it also on num type
template <class Type> inline Type CreateCste(const Type & aV,const Type &) { return aV; }
/// because pow is defined in std and there is cast int->float that would make it unaccessible
template <class Type> inline Type pow(const Type & aV,const int & aExp)
{
return std::pow(aV,Type(aExp));
}
//============= BASIC ERROR HANDLING ==============
/** This function computes derivates by finites difference
It is used in the tests to check correction of symbolic derivatives. Also used
in didactic parts.
*/
template <class Type,class TypeFct>
std::vector<Type> NumericalDerivate
(
TypeFct & aFctr, ///< Function
const std::vector<Type> & aVUk, ///< Unknown
const std::vector<Type> & aVObs, ///< Observations
int aNumVar, ///< Num of unknown we derivate by
const Type & aEpsilon ///< "Small" number to compute variations
)
{
std::vector<Type> aVPlus = aVUk;
aVPlus.at(aNumVar) += aEpsilon;
std::vector<Type> aResPlus = aFctr( aVPlus,aVObs);
std::vector<Type> aVMinus = aVUk;
aVMinus.at(aNumVar) -= aEpsilon;
std::vector<Type> aResMinus = aFctr( aVMinus,aVObs);
std::vector<Type> aDerivate;
for (size_t aK=0 ; aK<aResPlus.size() ; aK++)
aDerivate.push_back((aResPlus.at(aK)-aResMinus.at(aK)) / (2*aEpsilon));
return aDerivate;
}
/* *************************************************** */
/* *************************************************** */
/* * * */
/* * Main user interace * */
/* * * */
/* *************************************************** */
/* *************************************************** */
// ------------- The two classes visible by user are cFormula and cCoordinatorF ------
/** Abstraction of mathemicall formula, this the object manipulated by user, its
has all algerbric operation required. This object is just an encapsulation of
a pointer on cImplemF.
*/
template <class TypeElem> class cFormula ;
/** Class for managing the "context", i.e. coordinating all the formula
and their derivative corresponding to a single use .
A coordinator is also a calculator, as it make computation on formulas
*/
template <class TypeElem> class cCoordinatorF;
// -------- Declaration all binary operators ----------------
// For each operator with have the 3 versions "Formula x Formula" ,
// "Number x Formula" and "Formula x Number" , the two last are rather
// syntactic suggar (i.e. make usage easier, but do not extend the library power)
// Operator +
template <class TypeElem> cFormula <TypeElem>
operator +(const cFormula <TypeElem> & aF1 ,const cFormula <TypeElem> & aF2);
template <class TypeElem> cFormula <TypeElem> operator +(const TypeElem & aV1,const cFormula <TypeElem> & aF2);
template <class TypeElem> cFormula <TypeElem> operator +(const cFormula <TypeElem> & aF1,const TypeElem & aV2);
// Operator *
template <class TypeElem> cFormula <TypeElem>
operator *(const cFormula <TypeElem> & aF1 ,const cFormula <TypeElem> & aF2);
template <class TypeElem> cFormula <TypeElem> operator *(const TypeElem & aV1,const cFormula <TypeElem> & aF2);
template <class TypeElem> cFormula <TypeElem> operator *(const cFormula <TypeElem> & aF1,const TypeElem & aV2);
// Operator -
template <class TypeElem> cFormula <TypeElem>
operator -(const cFormula <TypeElem> & aF1 ,const cFormula <TypeElem> & aF2);
template <class TypeElem> cFormula <TypeElem> operator -(const TypeElem & aV1,const cFormula <TypeElem> & aF2);
template <class TypeElem> cFormula <TypeElem> operator -(const cFormula <TypeElem> & aF1,const TypeElem & aV2);
// Operator /
template <class TypeElem> cFormula <TypeElem>
operator /(const cFormula <TypeElem> & aF1 ,const cFormula <TypeElem> & aF2);
template <class TypeElem> cFormula <TypeElem> operator /(const TypeElem & aV1,const cFormula <TypeElem> & aF2);
template <class TypeElem> cFormula <TypeElem> operator /(const cFormula <TypeElem> & aF1,const TypeElem & aV2);
// pow
template <class TypeElem> cFormula <TypeElem>
pow (const cFormula <TypeElem> & aF1 ,const cFormula <TypeElem> & aF2);
template <class TypeElem> cFormula <TypeElem> pow (const TypeElem & aV1,const cFormula <TypeElem> & aF2);
/// This one defined in MMVII_FormDer_UnaryOp.h
template <class TypeElem> cFormula <TypeElem> pow (const cFormula <TypeElem> & aF1,const TypeElem & aV2);
template <class TypeElem> cFormula <TypeElem> pow (const cFormula <TypeElem> & aF1,const int & aV2);
// -------- integer low power ----------------
template <class TypeElem> cFormula <TypeElem> square(const cFormula <TypeElem> & aF);
template <class TypeElem> cFormula <TypeElem> cube(const cFormula <TypeElem> & aF);
template <class TypeElem> cFormula <TypeElem> pow4(const cFormula <TypeElem> & aF);
template <class TypeElem> cFormula <TypeElem> pow5(const cFormula <TypeElem> & aF);
template <class TypeElem> cFormula <TypeElem> pow6(const cFormula <TypeElem> & aF);
template <class TypeElem> cFormula <TypeElem> pow7(const cFormula <TypeElem> & aF);
template <class TypeElem> cFormula <TypeElem> pow8(const cFormula <TypeElem> & aF);
template <class TypeElem> cFormula <TypeElem> pow9(const cFormula <TypeElem> & aF);
// --- other unary operator
template <class TypeElem> cFormula <TypeElem> exp(const cFormula <TypeElem> & aF);
template <class TypeElem> cFormula <TypeElem> operator - (const cFormula <TypeElem> & aF);
template <class TypeElem> cFormula <TypeElem> log(const cFormula <TypeElem> & aF);
// ---- sometime we need a templetized way to create constants
template <class T> cFormula<T> CreateCste(const T & aV,const cFormula<T> & aF);
/// --- powI , return pow of integral exponent,
template <class Type> Type powI(const Type & aV,const int & aExp)
{
switch (aExp)
{
// case 0 : return Type(1.0);
case 0 : return CreateCste(1.0,aV);
case 1 : return aV;
case 2 : return square(aV);
case 3 : return cube(aV);
case 4 : return pow4(aV);
case 5 : return pow5(aV);
case 6 : return pow6(aV);
case 7 : return pow7(aV);
case 8 : return pow8(aV);
case 9 : return pow9(aV);
}
// else use the classical pow
return pow(aV,aExp);
}
// -------- Declaration of Coordinator class ----------------
template <class TypeElem> class cCoordinatorF : public cCalculator<TypeElem> // , public SYMBDER_cMemCheck
{
public :
typedef cFormula <TypeElem> tFormula;
typedef std::vector<TypeElem> tOneRes;
// --------------------------- Constructors / Destructor -------------------
/// Constructor with explicit Id for Unknown/Observation. Used if we want to analyze the generated code
inline cCoordinatorF(const std::string &aName, int SzBuf, const std::vector<std::string> & aVecUK, const std::vector<std::string> & aVecObs);
/// Constructor with basic Id (used if we dont generate code, or dont want to analyse it by human)
inline cCoordinatorF(const std::string &aName, int SzBuf,int aNbUnknown,int aNbObservation);
/// Destructeur will free allocated formulas
virtual ~cCoordinatorF();
/// Copies are not allowed on this kind of object.
cCoordinatorF(const cCoordinatorF<TypeElem> &) = delete;
// --------------------------- Accessors to Atomic Formulas -------------------
const std::vector<tFormula>& VUk() const {return mVFormUnknowns;} ///< Unknowns
const std::vector<tFormula>& VObs() const {return mVFormObservations;} ///< Observations
// --------------------------- Manipulation -------------------
/// Set the formulas that with be used for computation
void SetCurFormulas(const std::vector<tFormula> &);
/** SetCurFormulas + all its derivative , order of storage will be
VF0 dVF0/dX0 dVF0/dX1 .... VF1 dVF1/dX0 ... */
void SetCurFormulasWithDerivative(const std::vector<tFormula> & aVF);
// ---------- Code generator ---------------
/** Generate code, class cName , file cName.h, cName.cpp. Return filename w/o ext, or "" if error */
std::pair<std::string,std::string> GenerateCode(const std::string &aFilePrefix="CodeGen_") const
{ return GenCodeShortExpr(aFilePrefix);
}
std::pair<std::string,std::string> GenerateCodeTemplate(const std::string &aFilePrefix="CodeGen_") const
{ return GenCodeShortExprTemplate(aFilePrefix);
}
std::pair<std::string,std::string> GenerateCodeForType(const std::string& aTypeName, const std::string &aFilePrefix="CodeGen_") const
{ return GenCodeShortExprForType(aTypeName,aFilePrefix);
}
std::pair<std::string,std::string> GenCodeShortExpr(const std::string &aFilePrefix="CodeGen_") const
{
return GenCodeCommon(aFilePrefix, "", true);
}
std::pair<std::string,std::string> GenCodeLonExpr(const std::string &aFilePrefix="CodeGen_") const
{
return GenCodeCommon(aFilePrefix, "", false);
}
std::pair<std::string,std::string> GenCodeShortExprTemplate(const std::string &aFilePrefix="CodeGen_") const
{
return GenCodeCommon(aFilePrefix, "template<>", true);
}
std::pair<std::string,std::string> GenCodeLonExprTemplate(const std::string &aFilePrefix="CodeGen_") const
{
return GenCodeCommon(aFilePrefix, "template<>", false);
}
std::pair<std::string,std::string> GenCodeShortExprForType(const std::string& aTypeName, const std::string &aFilePrefix="CodeGen_") const
{
return GenCodeCommon(aFilePrefix, aTypeName, true);
}
std::pair<std::string,std::string> GenCodeLonExprForType(const std::string& aTypeName, const std::string &aFilePrefix="CodeGen_") const
{
return GenCodeCommon(aFilePrefix, aTypeName, false);
}
// =========== Parametrisation of the generated code =========
/// The default value is not always adequate "SymbDer/SymbDer_Common.h"
void SetHeaderIncludeSymbDer(const std::string &aH) {mHeaderIncludeSymbDer= aH;}
void SetDirGenCode(const std::string &aDir) {mDirGenCode= aDir;}
private : // END-USER
/* =================================================================================
ABOVE WAS THE REAL PUBLIC PART OF cCoordinatorF FOR USER OF LIBRARY. THE REST
IS PUBLIC FOR IMPLEMENTERS BUT NOT NEEDED BY USER
=====================================================================================*/
public :
// Result of several evaluation are stored in a buffer, Eigen vector are used
// as they implement efficiently arithmetical operation
// typedef Eigen::Array<TypeElem, 1, Eigen::Dynamic> tBuf;
typedef std::vector<TypeElem> tBuf;
// --------------------------- Acces to function from names, values -------------------
/// Indicate if the formula corresponding to a given string already exist
inline bool ExistFunc(const std::string & aName) const
{
return (mDicoFunc.find(aName) != mDicoFunc.end());
}
/// Func of given name, Error if don't exist
inline tFormula FuncOfName(const std::string & aName) const ;
/// Add a function (put it in dico), Error if already exist
inline void AddFormula(tFormula aPF)
{
if (ExistFunc(aPF->Name())) InternalError ("Multiple add of identic name :[" + aPF->Name() + "]",this->Name());
mDicoFunc[aPF->Name()] = aPF;
mVAllFormula.push_back(aPF);
aPF->TryReducAssoc();
}
/// Func of given constant, create if don't exist
inline tFormula CsteOfVal(const TypeElem & aCste) ;
tFormula Cste0() const {return mCste0;} ///< Acces to a current constant
tFormula Cste1() const {return mCste1;} ///< Another Acces to a current constant
tFormula Cste2() const {return mCste2;} ///< Yet another Acces to a current constant
/// Tuning --- Print the stack of function as a tree
inline void ShowStackFunc() const;
/// Formula used for computation,
const std::vector<tFormula>& VReached() const {return mVReachedF;}
// Current (top) formulas
const std::vector<tFormula>& VCurrent() const {return mVCurF;}
size_t NbCurFonc() const {return mVAllFormula.size();}
private :
/// Called by cCalculator::PushNewEvals to Set Unknown/Observations
virtual void SetNewUks(const std::vector<TypeElem> &aVUks) override;
virtual void SetNewObs(const std::vector<TypeElem> &aVObs) override;
/** Make the evaluation of current functions on pushed values */
virtual void DoEval() override;
/// Used to generate automatically Id for Unknown/Observatio, when we dont need to control them explicitely
static std::vector<std::string> MakeAutomId(const std::string & aPrefix,int aNb);
std::pair<std::string,std::string> GenCodeCommon(const std::string &aPrefix, std::string aTypeName, bool isShortExpr) const;
std::string TypeElemName() const;
size_t mNbCste; ///< Number Cste
std::vector<tFormula> mVFormUnknowns; ///< Vector of All Unknowns
std::vector<tFormula> mVFormObservations; ///< Vector of All Observations
std::map<std::string,tFormula> mDicoFunc; ///< Map Name => Func
std::vector<tFormula> mVAllFormula; ///< Vector of All Func, allow to parse them in creation order
std::map<TypeElem,tFormula> mDicoCste; ///< Map Value => Func Constant
tFormula mCste0; ///< Fonc constant null
tFormula mCste1; ///< Fonc constant 1
tFormula mCste2; ///< Fonc constant 1
std::vector<tFormula> mVCurF; ///< Current evaluted formulas
std::vector<tFormula> mVReachedF; ///< Formula "reachable" i.e. necessary to comput mVCurF
std::string mHeaderIncludeSymbDer; ///< Compilation environment may want to change it
std::string mDirGenCode; ///< Want to put generated code in a fixed folde ?
};
/* **************************************************
* *
* Pre-Declaration of all classes *
* Not required by compilation *
* (Except for cImplemF )but I like to have *
* a quick view of all existing classes *
* *
* **************************************************/
/** "Mother" Interface class of all classes implementing the service ,
abstract class with pure virtual method
*/
template <class TypeElem> class cImplemF ;
// --------------- "Atomic" function : Unknown, constant, observation-----------------
template <class TypeElem> class cAtomicF ; ///< Mother Class of all atomic formulas
/// "Observations" corresponding to user constant (change for each evaluation)
template <class TypeElem> class cObservationF ;
/// "Constant" function
template <class TypeElem> class cConstantF ;
/// "Unknown" for representing coordinates function X0,X1,X2 ....
template <class TypeElem> class cUnknownF;
// ----------------------------- Unary operator ------------------------------------
template <class TypeElem> class cUnaryF ; ///< Mother Class of all unary operator
template <class TypeElem> class cSquareF ; ///< Class for square operator
template <class TypeElem> class cExpF ; ///< Class for exponential operator
template <class TypeElem> class cMin1F ; ///< Class for Unary Minus
template <class TypeElem> class cLogF ; ///< Class for neperien log
// -------------------------------- Binary operator -------------------------------------
template <class TypeElem> class cBinaryF ; ///< Mother class of binary operators
template <class TypeElem> class cSumF ; ///< Class for sum of 2 functions
template <class TypeElem> class cMulF ; ///< Class for multiplication of 2 functions
template <class TypeElem> class cSubF ; ///< Class for substraction of 2 functions
template <class TypeElem> class cDivF ; ///< Class for division of 2 functions
template <class TypeElem> class cPowF ; ///< Class for division of 2 functions
/* *************************************************** */
/* *************************************************** */
/* * * */
/* * Definition of all classes * */
/* * * */
/* *************************************************** */
/* *************************************************** */
// ------------------- 2 "Main" Classes -------------------------
// cFormula / cImplemF
// ----------------------------------------------------------------
template <class TypeElem> class cImplemF : public SYMBDER_cMemCheck
{
public :
// See eigen documentation, this macro is mandatory for alignment reason
// EIGEN_MAKE_ALIGNED_OPERATOR_NEW
EIGEN_ALLIGNMENT_IN_MMVII
typedef TypeElem tElem;
typedef cCoordinatorF<TypeElem> tCoordF;
typedef typename tCoordF::tBuf tBuf;
typedef typename tCoordF::tFormula tFormula;
//----------- For derivation and reduction--------------
virtual bool IsCste(const TypeElem &) const {return false;} ///< To redefine in constant func, Used for simplification in "/ * + -"
virtual bool IsDistribInt() const {return false;} ///< To redefine in *,/ for distributivity
virtual tFormula Derivate(int aK) const = 0; ///< Compute the formula of it's derivative to Kth unknown
/** In this functionwe try to make reduction using associativity (and maybe others),
as we want to do it only on maximal chains of + (or *) this has to be run by the father of
the chain
*/
void TryReducAssoc();
virtual cImplemF<TypeElem> * ReducAssoc() {return this;}
virtual bool IsMult() const {return false;}
virtual bool IsSum() const {return false;}
bool ReducAssocTried() const {return mReducAssocTried;}
virtual cFormula<TypeElem> VOper2(const tFormula &,const tFormula &) const; ///< Use in distributive reducion to recal the operator binaire if suitable
// -------------- For Computation -------------------------
/// Method that wil compute data inside mBuf
virtual void ComputeBuf(int aK0,int aK1) =0;
/// Return "Sub"-formula referenced
virtual std::vector<tFormula> Ref() const =0;
// ---------- Accessors ---------------
const std::string & Name() const {return mName;} ///< Standard accessor
tCoordF * CoordF() const {return mCoordF;} ///< Standard accesor
int NumGlob() const {return mNumGlob;} ///< Standard accessor
// ---------- Acces to Buf data ---------------
void SetBuf(size_t anIndex,const TypeElem & aVal) {mBuf.at(anIndex) = aVal;}
const TypeElem & GetBuf(size_t anIndex) {return mBuf.at(anIndex);}
TypeElem * DataBuf() {return mDataBuf;}
// ---------- Reached Flag ---------------
bool Reached() const {return mReached;} ///< Standard accessor
void SetReached(bool IsReached) {mReached = IsReached;} ///< Fix Reached
/// Compute in the reference graphe and put formula explored in VReached
void CalcRecursiveDepth(std::vector<tFormula> & VReached) ;
int Depth() const {return mDepth;} ///< Standard accessor
void SetDepth(int aDepth) {mDepth = aDepth;} ///< Fix Reached
// ---------- Code gen -----------------------
virtual bool isAtomic() const { return false;}
virtual std::string GenCodeFormName() const {return NameGlob();} // Name of formula, referenced value for Atomic
virtual std::string GenCodeShortExpr() const = 0; // N-Addresses code generation
virtual std::string GenCodeDef() const = 0; // Formula definition generation
virtual std::string GenCodeRef() const; // Formula reference generation
int UsedCnt() const {return mUsedCnt;} ///< Standard accessor
// ---------- Tuning / Debugging / Analysing ---------------
/// Used to print constant from generic formula
virtual const TypeElem * ValCste() const {return nullptr;}
/// Infixed "Pretty" Print . For tuning and checking (i.e correction of reduction, derivative, rewrite ...)
virtual std::string InfixPPrint() const =0;
/// Number of reference that would occur without reduction on identic formula (to test performance in paper)
int RecursiveRec() const;
// Every where a reference name is needed
std::string NameGlob() const { return "F" + std::to_string(NumGlob());}
/// Access at global level is 4 reducing, also it is used 4 implemant in Unary & Binary
virtual const std::string & NameOperator() const = 0;
// -------------------- Destructor / Constructor --------------------------
virtual ~cImplemF () {} ///< Add a virtual ~X() when we have virtual methods, who knows ...
protected :
inline cImplemF (tCoordF * aCoordF,const std::string & aName) :
mCoordF (aCoordF),
mBuf (mCoordF->SzBuf(),TypeElem(0.0)),
mDataBuf (mBuf.data()),
mName (aName),
mNumGlob (mCoordF->NbCurFonc()),
mReached (false),
mDepth (-1),
mUsedCnt (0),
mReducAssocTried (false)
{
}
tCoordF * mCoordF; ///< Coordinator that manage all the funcion cooperating
tBuf mBuf; ///< Buf to store values
TypeElem * mDataBuf; ///< Raw pointer
const std::string mName; ///< string represention of the formula as for ex : C2, X1, V0 , square F3, F18/F3 ...
int mNumGlob; ///< Global number (!= Num in class)
bool mReached; ///< Flag to know if a formula is usefull for compute current
int mDepth; ///< Used for topological sort
private :
cImplemF (const cImplemF<TypeElem> &) = delete; ///< No Copy
unsigned mUsedCnt;
bool mReducAssocTried;
};
template <class TypeElem> class cFormula
{
public :
typedef cCoordinatorF<TypeElem> tCoordF;
typedef cImplemF<TypeElem> tImplemF;
typedef typename tCoordF::tFormula tFormula;
// -------------------- constructor -------------------
/// Construct from a pointer, standard
cFormula (tImplemF * aRawPtr) :
mPtr (aRawPtr)
{
}
/// Default constructor, required by some code (vector ?)
cFormula ():
cFormula <TypeElem> (nullptr)
{
}
// --------------- operator on pointer ---------------------
// UNUSED 4 NOW tImplemF & operator*() const {return *mPtr;} ///< Standard behaviour of a pointer
tImplemF * operator->() const {return mPtr;} ///< Standard behaviour of a pointer
tImplemF * RawPtr() const {return mPtr;} ///< Explicit acces
// DO NOT WORK const std::unique_ptr<tImplemF> operator->() const {return std::unique_ptr<mPtr>;}
bool IsNull() const {return mPtr==nullptr;} ///< Safer than giving acces to raw pointer
// --------------- Naming ---------------------
/// Generate the unique indentifier of a binary expression
std::string NameFormulaBin(const std::string & aNameOper,const tFormula & aF2) const
{
return (*this)->NameGlob() + aNameOper + aF2->NameGlob();
}
/// Generate the unique indentifier of a unary expression
std::string NameFormulaUn(const std::string & aNameOper) const
{
return aNameOper + " " + (*this)->NameGlob();
}
/// To allow destruction without giving access to raw pointer
void FreeMem() {delete mPtr; mPtr=nullptr;}
private :
tImplemF* mPtr; ///< Faster than shared and deallocation is easy as object controlled by context
};
/* *************************************************** */
/* *************************************************** */
/* * * */
/* * ATOMIC FORMULA * */
/* * * */
/* *************************************************** */
/* *************************************************** */
/* ----------------------------------------------------------
Class for atomic formula
MOTHER CLASS : cAtomicF
DERIVED : cUnknownF / cObservationF / cConstantF
----------------------------------------------------------------*/
template <class TypeElem> class cAtomicF : public cImplemF<TypeElem>
{
public :
typedef cImplemF<TypeElem> tImplemF;
typedef typename tImplemF::tCoordF tCoordF;
typedef typename tCoordF::tFormula tFormula;
/// Should work always
std::string InfixPPrint() const override {return tImplemF::Name();}
/// Rule deriv=0 , work by default (constant and observations)
tFormula Derivate(int aK) const override {return tImplemF::mCoordF->Cste0();}
/// Generally nothing to do in atomic, their buffer has been filled witj adequate values
void ComputeBuf(int aK0,int aK1) override { }
std::vector<tFormula> Ref() const override{return std::vector<tFormula>();}
protected :
bool isAtomic() const override { return true;}
std::string GenCodeFormName() const override { return this->Name();}
std::string GenCodeShortExpr() const override { return this->GenCodeFormName();}
std::string GenCodeRef() const override { return this->GenCodeFormName();}
std::string GenCodeDef() const override { return mCodeValue;}
inline cAtomicF(tCoordF * aCoordF,const std::string& aName) :
tImplemF (aCoordF,aName)
{ }
std::string mCodeValue;
};
template <class TypeElem> class cUnknownF : public cAtomicF<TypeElem>
{
public :
typedef cAtomicF<TypeElem> tAtom;
typedef typename tAtom::tImplemF tImplemF;
typedef typename tImplemF::tCoordF tCoordF;
typedef typename tCoordF::tFormula tFormula;
const std::string & NameOperator() const override {static std::string s("UK"); return s;}
std::string InfixPPrint() const override {return tImplemF::Name();}
/// rule : dXi/dXj = delta(i,j)
tFormula Derivate(int aK) const override
{
return (aK==mNumUnk) ? tImplemF::mCoordF->Cste1() : tImplemF::mCoordF->Cste0();
}
friend tCoordF;
private :
inline cUnknownF(tCoordF * aCoordF,const std::string& aName,int aNum) :
tAtom (aCoordF,aName),
mNumUnk (aNum)
{
this->mCodeValue = "this->mVUk[aK][" + std::to_string(mNumUnk) + "]";
}
int mNumUnk; ///< Number of the Unknown; like : 0 for X0, 1 for X1 ...
};
template <class TypeElem> class cObservationF : public cAtomicF<TypeElem>
{
public :
typedef cAtomicF<TypeElem> tAtom;
typedef typename tAtom::tImplemF tImplemF;
typedef typename tImplemF::tCoordF tCoordF;
typedef typename tCoordF::tFormula tFormula;
friend tCoordF;
const std::string & NameOperator() const override {static std::string s("Obs"); return s;}
private :
inline cObservationF(tCoordF * aCoordF,const std::string & aName,int aNum) :
tAtom (aCoordF,aName),
mNum (aNum)
{
this->mCodeValue = "this->mVObs[aK][" + std::to_string(mNum) + "]";
}
int mNum; ///< Number of the Observation; like : 0 for V0, 1 for V1 ...
};
template <class TypeElem> class cConstantF : public cAtomicF<TypeElem>
{
public :
typedef cAtomicF<TypeElem> tAtom;
typedef typename tAtom::tImplemF tImplemF;
typedef typename tImplemF::tCoordF tCoordF;
typedef typename tCoordF::tFormula tFormula;
typedef typename tCoordF::tBuf tBuf;
friend tCoordF;
bool IsCste(const TypeElem &K) const override {return mVal==K;} ///< Here we know if we are a constant of value K
const TypeElem * ValCste() const override {return &mVal;}
const std::string & NameOperator() const override {static std::string s("Cste"); return s;}
protected :
inline cConstantF(tCoordF * aCoordF,const std::string & aName,int aNum,const TypeElem& aVal) :
tAtom (aCoordF,aName),
mNum (aNum),
mVal (aVal)
{
for (auto & aV : tImplemF::mBuf) aV = aVal; // Initialize buf with const val
std::stringstream ss;
// Precision that ensures that Num0 -> ASCII -> Num1 => Num1 == Num0
// May cause some odd but correct value for non exactly representable numbers
ss << std::setprecision(std::numeric_limits<decltype(mVal)>::max_digits10) << mVal;
this->mCodeValue = ss.str();
}
std::string GenCodeFormName() const override { return this->mCodeValue;}
int mNum;
const TypeElem mVal;
};
/* *************************************************** */
/* *************************************************** */
/* * * */
/* * cFormula / cImplemF / cCoordinatorF * */
/* * External Definition of methods * */
/* * * */
/* *************************************************** */
/* *************************************************** */
/* ---------------------- */
/* cFormula */
/* ---------------------- */
template <class T> cFormula<T> CreateCste(const T & aV,const cFormula<T> & aF)
{
return aF->CoordF()->CsteOfVal(aV);
}
/* ---------------------- */
/* cImplemF */
/* ---------------------- */
template <class TypeElem> int cImplemF<TypeElem>::RecursiveRec() const
{
int aRes = 1;
for (const auto & aF : Ref())
{
aRes += aF->RecursiveRec();
}
return aRes;
}
template <class TypeElem> void cImplemF<TypeElem>::CalcRecursiveDepth(std::vector<tFormula> & aVReached)
{
if (mDepth != -1) {
mUsedCnt++;
return; // if we were already here , nothing to do
}
mUsedCnt = 1;
for (const auto & aF : Ref())
{
aF->CalcRecursiveDepth(aVReached); // parse sub formula
mDepth = std::max(mDepth,aF->mDepth); // Memo max depth
}
mDepth++; // my depth is 1 + max of depth of my referenced formulas
aVReached.push_back(tFormula(this));
}
template <class TypeElem> void cImplemF<TypeElem>::TryReducAssoc()
{
for (auto & aF : Ref())
{
// F will not belong to the terminal command that will have to reparsed
// If we are in the config (A+B) + .. maybe the chain will grow later
if (aF->NameOperator() != NameOperator())
{
aF = aF->ReducAssoc();
}
aF->mReducAssocTried = true;
}
}
template <class TypeElem> cFormula<TypeElem> cImplemF<TypeElem>::VOper2(const tFormula & aF1,const tFormula &) const
{
InternalError("Incorrect virtual binary operation",this->mCoordF->Name());
return aF1;
}
template <class TypeElem>
std::string cImplemF<TypeElem>::GenCodeRef() const
{
if (UsedCnt() == 1) {
return GenCodeDef();
} else {
return GenCodeFormName();
}
}
/* ---------------------- */
/* cCoordinatorF */
/* ---------------------- */
template <class TypeElem>
std::vector<std::string> cCoordinatorF<TypeElem>::MakeAutomId(const std::string & aPrefix,int aNb)
{
std::vector<std::string> aRes;
for (int aK=0 ; aK<aNb ; aK++)
aRes.push_back(aPrefix+ std::to_string(aK));
return aRes;
}
template <class TypeElem>
cCoordinatorF<TypeElem>::cCoordinatorF
(
const std::string & aName,
int aSzBuf,
const std::vector<std::string> & aVNameUK,
const std::vector<std::string> & aVNameObs
) :
cCalculator<TypeElem>(aName,aSzBuf,aVNameUK,aVNameObs),
mNbCste (0),
mCste0 (CsteOfVal(0.0)),
mCste1 (CsteOfVal(1.0)),
mCste2 (CsteOfVal(2.0)),
mHeaderIncludeSymbDer ("SymbDer/SymbDer_Common.h"),
mDirGenCode ("")
{
// Generate all the function corresponding to unknown
for (size_t aNumUK=0 ; aNumUK<this->mNbUK ; aNumUK++)
{
tFormula aFuncUK(new cUnknownF<TypeElem>(this,aVNameUK[aNumUK],aNumUK)); // Create it
mVFormUnknowns.push_back(aFuncUK); // Push it in vector of coordinat func
AddFormula(aFuncUK); // Add to all func
}
// Generate all the function corresponding to observations
for (size_t aNumObs=0 ; aNumObs<this->mNbObs ; aNumObs++)
{
tFormula aFuncObs(new cObservationF<TypeElem>(this,aVNameObs[aNumObs],aNumObs)); // Create it
mVFormObservations.push_back(aFuncObs); // Push it in vector of coordinat func
AddFormula(aFuncObs); // Add to all func
}
}
template <class TypeElem>
cCoordinatorF<TypeElem>::cCoordinatorF(const std::string &aName, int aSzBuf, int aNbUK, int aNbObs) :
cCoordinatorF<TypeElem>(aName,aSzBuf,MakeAutomId("X",aNbUK),MakeAutomId("V",aNbObs))
{
}
template <class TypeElem>
cCoordinatorF<TypeElem>::~cCoordinatorF()
{
for (auto & aForm : mVAllFormula)
{
aForm.FreeMem();
}
}
template <class TypeElem>
cFormula<TypeElem> cCoordinatorF<TypeElem>::CsteOfVal(const TypeElem & aCste)
{
tFormula & aRef = mDicoCste[aCste];
if (aRef.IsNull()) // If it was not existing, the map contain now the def element
{
// The ! is used to make constant first in alphab order, used for reduction ?
aRef=tFormula(new cConstantF<TypeElem>(this,"_C"+std::to_string(mNbCste),mNbCste,aCste));
mNbCste++;
AddFormula(aRef);
}
return aRef;
}
template <class TypeElem>
cFormula <TypeElem> cCoordinatorF<TypeElem>::FuncOfName(const std::string & aName) const
{
const auto & anIt = mDicoFunc.find(aName);
if (anIt == mDicoFunc.end()) InternalError ("Try to acces non existing name :[" + aName + "]",this->Name());
return anIt->second;
}
template <class TypeElem>
void cCoordinatorF<TypeElem>::SetNewUks(const std::vector<TypeElem> & aVUks)
{
for (size_t aK=0 ; aK<aVUks.size() ; aK++) // Init Vals of formulas buffer
{
mVFormUnknowns[aK]->SetBuf(this->mNbInBuf,aVUks[aK]);
}
}
template <class TypeElem>
void cCoordinatorF<TypeElem>::SetNewObs(const std::vector<TypeElem> & aVObs)
{
for (size_t aK=0 ; aK<aVObs.size() ; aK++) // Init Vals of formulas buffer
{
mVFormObservations[aK]->SetBuf(this->mNbInBuf,aVObs[aK]);
}
}
template <class TypeElem>
void cCoordinatorF<TypeElem>::SetCurFormulasWithDerivative(const std::vector<tFormula> & aVF)
{
std::vector<tFormula> aVWDer;
for (const auto & aF : aVF)
{
aVWDer.push_back(aF);
for (size_t aUK=0 ; aUK<this->mNbUK ; aUK++)
{
aVWDer.push_back(aF->Derivate(aUK));
}
}
SetCurFormulas(aVWDer);
this->mWithDer = true;
this->mSzInterval = 1+this->mNbUK;
this->mNbElem = aVF.size();
}
template <class TypeElem>
void cCoordinatorF<TypeElem>::SetCurFormulas(const std::vector<tFormula> & aVF0)
{
std::vector<tFormula> aVF;
for(auto aF : aVF0)
{
if (! aF->ReducAssocTried())
{
aF = tFormula(aF->ReducAssoc());
// std::cout << "GGGGGGGG " << aF->Name() << " \n";
}
aVF.push_back(aF);
}
this->mWithDer=false;
this->mSzInterval = 1;
this->mNbElem = aVF0.size();
mVCurF = aVF;
// Erase previous
for (auto & aF : mVReachedF)
aF->SetDepth(-1);
mVReachedF.clear();
// Compute depth for topologicall sort
for (auto & aF : mVCurF)
{
aF->CalcRecursiveDepth(mVReachedF);
}
// Use depth to have topological sort
// In fact it is probably not necessary to make this sort, initial order of reaching order
// should work; by the way : no dammage ..
std::sort
(
mVReachedF.begin(),
mVReachedF.end(),
[](const tFormula & aF1,const tFormula &aF2) {return aF1->Depth() < aF2->Depth();}
);
// Make Buf of Res to have right size
for (auto & aLine : this->mBufLineRes)
{
aLine.resize(mVCurF.size());
}
}
template <class TypeElem>
void cCoordinatorF<TypeElem>::DoEval()
{
// Make the real hard stuff, compute the data, the depedancy ordering should make it coherent
#ifdef _OPENMP
#pragma omp parallel
{
size_t thread_num = omp_get_thread_num();
size_t num_threads = omp_get_num_threads();
size_t start = thread_num * this->mNbInBuf / num_threads;
size_t end = (thread_num + 1) * this->mNbInBuf / num_threads;
if (end>start)
{
for (auto & aF : mVReachedF)
{
aF->ComputeBuf(start,end);
}
}
}
#else
for (auto & aF : mVReachedF)
{
aF->ComputeBuf(0,this->mNbInBuf);
}
#endif
for (size_t aKLine=0 ; aKLine<this->mNbInBuf ; aKLine++)
{
std::vector<TypeElem> & aLine = this->mBufLineRes[aKLine];
for (size_t aKFunc=0 ; aKFunc< mVCurF.size() ; aKFunc++)
aLine[aKFunc] = mVCurF[aKFunc]->GetBuf(aKLine);
}
}
template <class TypeElem>
void cCoordinatorF<TypeElem>::ShowStackFunc() const
{
for (const auto & aForm : mVAllFormula)
{
if (aForm->Depth()==-1)
std::cout << "---" ;
else
std::cout << "-" << aForm->Depth() << "-";
std::cout << aForm->UsedCnt() << "- ";
std::cout << aForm->NameGlob() << " => " << aForm->Name();
const TypeElem * aPV = aForm->ValCste();
if (aPV)
std::cout << " ; Val=" << *aPV;
std::cout << "\n";
}
std::cout << "REACHED ";
for (const auto & aForm : mVReachedF)
{
std::cout << aForm->NumGlob() << " ";
}
std::cout << "\n";
std::cout << "CUR ";
for (const auto & aForm : mVCurF)
{
std::cout << aForm->NumGlob() << " ";
}
std::cout << "\n";
}
// return
inline std::string VStr2CPP(const std::vector<std::string> & aVS)
{
std::string aRes = "{";
for (size_t aK=0 ; aK<aVS.size() ; aK++)
{
if (aK!=0)
aRes = aRes + "," ;
aRes = aRes + "\""+ aVS[aK] + "\"" ;
}
return aRes+ "}";
}
template <class TypeElem>
std::pair<std::string,std::string> cCoordinatorF<TypeElem>::GenCodeCommon(const std::string& aPrefix, std::string aTypeName, bool isShortExpr) const
{
std::string aName = this->Name();
if (aName.size() == 0)
UserSError("Formula name is empty.",this->Name());
for (auto &c : aName) {
if (!std::isalnum(c) && c != '_')
UserSError("Formula name is not a valid C++ identifier: '_,a..z,A..Z,0..9' only.",this->Name());
}
std::string aClassName = "c" + aName;
if (aTypeName.size()==0)
aTypeName = this->TypeElemName();
bool isTemplated = aTypeName=="template<>";
if (isTemplated)
aTypeName = "TypeElem";
std::string aVectorName = "std::vector<" + aTypeName + ">";
if (! isShortExpr)
aClassName = aClassName + "LongExpr";
std::string aParentClass = "cCompiledCalculator<" + aTypeName + ">";
std::string aFileName = aPrefix + aClassName;
std::ofstream aOs(mDirGenCode + aFileName + ".h");
if (!aOs)
return std::make_pair(std::string(),std::string());
aOs << "#ifdef _OPENMP\n"
"#include <omp.h>\n"
"#endif\n"
"#include \"" << mHeaderIncludeSymbDer << "\"\n"
"\n"
"namespace NS_SymbolicDerivative {\n\n";
if (isTemplated) {
aOs << "template<typename TypeElem>\n";
}
aOs << "class " << aClassName << " : public " << aParentClass << "\n"
"{\n"
"public:\n"
" typedef " << aParentClass << " Super;\n"
" " << aClassName << "(size_t aSzBuf) : \n";
aOs
<< " Super(\n"
<< " \"" << aName << "\",\n"
<< " " << " aSzBuf,//SzBuf\n"
<< " " << this->mNbElem << ",//NbElement\n"
<< " " << mVCurF.size() << ",//SzOfLine\n"
<< " " << VStr2CPP(this->NamesUk()) << ",// Name Unknowns\n"
<< " " << VStr2CPP(this->NamesObs()) << ",// Name Observations\n"
<< " " << this->mWithDer << ",//With derivative ?\n"
<< " " << this->mSzInterval << "//Size of interv\n"
<< " )\n";
aOs<<
" {\n"
" }\n"
" static std::string FormulaName() { return \"" << aName << "\";}\n"
"protected:\n"
" virtual void DoEval() override;\n"
"private:\n"
" static Super* Alloc(int aSzBuf) {return new " << aClassName << "(aSzBuf); }\n"
" friend void cName2CalcRegisterAll(void);\n"
" static void Register() {cName2Calc<TypeElem>::Register(FormulaName()," << aClassName << "::Alloc);}\n"
"};\n"
"\n";
if (! isTemplated) {
aOs << "} // namespace NS_SymbolicDerivative\n";
aOs = std::ofstream(mDirGenCode+aFileName + ".cpp");
if (!aOs)
return std::make_pair(std::string(),std::string());
aOs << "#include \"" + aFileName + ".h\"\n"
"\n"
"namespace NS_SymbolicDerivative {\n"
"\n"
"void " << aClassName << "::DoEval()\n";
} else {
aOs << "\n"
"template<typename TypeElem>\n"
"void " << aClassName << "<TypeElem>::DoEval()\n";
}
aOs << "{\n"
"#ifdef _OPENMP\n"
"#pragma omp parallel for\n"
"#endif\n"
" for (size_t aK=0; aK < this->mNbInBuf; aK++) {\n"
"// Declare local vars in loop to make them per thread\n";
for (auto & aForm : mVFormUnknowns)
aOs << " " << aTypeName << " &" << aForm->GenCodeFormName() << " = " << aForm->GenCodeDef() << ";\n";
for (const auto & aForm : mVFormObservations)
aOs << " " << aTypeName << " &" << aForm->GenCodeFormName() << " = " << aForm->GenCodeDef() << ";\n";
if (isShortExpr) {
for (const auto & aForm : mVReachedF) {
if (!aForm->isAtomic())
aOs << " " << aTypeName << " " << aForm->GenCodeFormName() << " = " << aForm->GenCodeShortExpr() << ";\n";
}
for (size_t i=0; i<mVCurF.size(); i++)
aOs << " this->mBufLineRes[aK][" << i << "] = " << mVCurF[i]->GenCodeFormName() << ";\n";
} else {
for (const auto & aForm : mVReachedF) {
if (aForm->UsedCnt() != 1 && !aForm->isAtomic()) {
aOs << " " << aTypeName << " " << aForm->GenCodeFormName() << " = " << aForm->GenCodeDef() << ";\n";
}
}
for (size_t i=0; i<mVCurF.size(); i++)
aOs << " this->mBufLineRes[aK][" << i << "] = " << mVCurF[i]->GenCodeRef() << ";\n";
}
aOs << " }\n"
"}\n\n";
aOs << "} // namespace NS_SymbolicDerivative\n";
return std::make_pair(aClassName, aFileName);
}
template<>
inline std::string cCoordinatorF<double>::TypeElemName() const {return "double";}
template<>
inline std::string cCoordinatorF<float>::TypeElemName() const {return "float";}
template<typename T>
struct Detect_if_TypeElemName_is_defined : std::false_type
{ };
template<class TypeElem>
inline std::string cCoordinatorF<TypeElem>::TypeElemName() const
{
static_assert( Detect_if_TypeElemName_is_defined<TypeElem>::value , "** You must define cCoordinatorF::TypeElemName() for you type **");
return "";
}
} // NS_Symbolic_Derivative
#include "SymbDer_UnaryOp.h"
#include "SymbDer_BinaryOp.h"
/*
https://www.itl.nist.gov/div898/strd/nls/data/ratkowsky3.shtml
http://en.wikipedia.org/wiki/Automatic_differentiation
https://git.irc.umbc.edu/photorig/openMVG/blob/260584fda68dce095e279362efd24a2d7d7cf5d9/src/third_party/ceres-solver/include/ceres/jet.h
https://mc-stan.org/
http://www.met.reading.ac.uk/clouds/adept/array_features.html
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.89.7749&rep=rep1&type=pdf
http://www.autodiff.org/
*/
#endif // _SymbolicDerivatives_H_
|
auction_cpu.h
|
/**
* @file auction_cpu.h
* @author Jiaqi Gu, Yibo Lin
* @date Apr 2019
*/
#ifndef _DREAMPLACE_GLOBAL_MOVE_AUCTION_CPU_H
#define _DREAMPLACE_GLOBAL_MOVE_AUCTION_CPU_H
#include <iostream>
#include <cstring>
#include <cassert>
DREAMPLACE_BEGIN_NAMESPACE
#define AUCTION_MAX_EPS 10.0 // Larger values mean solution is more approximate
#define AUCTION_MIN_EPS 1.0
#define AUCTION_FACTOR 0.1
#define AUCTION_MAX_ITERS 9999
#define BIG_NEGATIVE -9999999
/// @return 1 if found a solution
template <typename T>
int run_auction(
int num_nodes,
T* data_ptr, // data, num_nodes*num_nodes in row-major
int* person2item_ptr, // results
float auction_max_eps,
float auction_min_eps,
float auction_factor,
int auction_max_iters,
int* item2person_ptr=nullptr,
T* bids_ptr=nullptr,
T* prices_ptr=nullptr,
int* sbids_ptr=nullptr
)
{
// --
// Declare variables
bool allocate_flag = false;
if (!item2person_ptr)
{
item2person_ptr = (int*)malloc(num_nodes * sizeof(int));
bids_ptr = (T*)malloc(num_nodes * num_nodes * sizeof(T));
prices_ptr = (T*)malloc(num_nodes * sizeof(T));
//bidders_ptr = (int*)malloc(num_nodes * num_nodes * sizeof(int)); // unused
sbids_ptr = (int*)malloc(num_nodes * sizeof(int));
allocate_flag = true;
}
int *data = data_ptr;
int *person2item = person2item_ptr;
int *item2person = item2person_ptr;
int *prices = prices_ptr;
int *sbids = sbids_ptr;
int *bids = bids_ptr;
int num_assigned = 0;
for(int i = 0; i < num_nodes; i++) {
prices[i] = 0.0;
person2item[i] = -1;
}
// Start timer
float auction_eps = auction_max_eps;
int counter = 0;
while(auction_eps >= auction_min_eps && counter < auction_max_iters) {
for(int i = 0; i < num_nodes; i++) {
person2item[i] = -1;
item2person[i] = -1;
}
num_assigned = 0;
while(num_assigned < num_nodes && counter < auction_max_iters){
counter += 1;
std::memset(bids, 0, num_nodes * num_nodes * sizeof(T));
std::memset(sbids, 0, num_nodes * sizeof(int));
// #pragma omp parallel for num_threads(1)
for(int i = 0; i < num_nodes; i++) {
if(person2item[i] == -1) {
T top1_val = BIG_NEGATIVE;
T top2_val = BIG_NEGATIVE;
int top1_col = BIG_NEGATIVE;
T tmp_val = BIG_NEGATIVE;
for (int col = 0; col < num_nodes; col++)
{
tmp_val = data[i * num_nodes + col];
if (tmp_val < 0)
{
continue;
}
tmp_val = tmp_val - prices[col];
if (tmp_val >= top1_val)
{
top2_val = top1_val;
top1_col = col;
top1_val = tmp_val;
}
else if (tmp_val > top2_val)
{
top2_val = tmp_val;
}
}
if (top2_val == BIG_NEGATIVE)
{
top2_val = top1_val;
}
T bid = top1_val - top2_val + auction_eps;
bids[num_nodes * top1_col + i] = bid;
sbids[top1_col] = 1;
}
}
// #pragma omp parallel for num_threads(1)
for(int j = 0; j < num_nodes; j++) {
if(sbids[j] != 0) {
T high_bid = 0.0;
int high_bidder = -1;
T tmp_bid = -1;
for(int i = 0; i < num_nodes; i++){
tmp_bid = bids[num_nodes * j + i];
if(tmp_bid > high_bid){
high_bid = tmp_bid;
high_bidder = i;
}
}
int current_person = item2person[j];
if(current_person >= 0){
person2item[current_person] = -1;
} else {
// #pragma omp atomic
num_assigned++;
}
prices[j] += high_bid;
person2item[high_bidder] = j;
item2person[j] = high_bidder;
}
}
}
auction_eps *= auction_factor;
}
// //Print results
// int score = 0;
// for (int i = 0; i < num_nodes; i++) {
// std::cout << i << " " << person2item[i] << std::endl;
// score += data[i * num_nodes + person2item[i]];
// }
// std::cerr << "score=" <<score << std::endl;
if (allocate_flag)
{
free(item2person_ptr);
free(bids_ptr);
free(prices_ptr);
//free(bidders_ptr);
free(sbids_ptr);
}
return (num_assigned >= num_nodes);
} // end run_auction
template <typename T>
class AuctionAlgorithmCPULauncher
{
public:
const char* name() const
{
return "AuctionAlgorithmCPULauncher";
}
/// @brief solve assignment problem with auction algorithm
/// The matrix is converted to non-negative matrix with maximization
/// Skipped edges are assigned with BIG_NEGATIVE
/// @param cost a nxn row-major cost matrix
/// @param sol solution mapping from row to column
/// @param n dimension
/// @param skip_threshold if the weight is larger than the threshold, do not add the edge
/// @param minimize_flag true for minimization problem and false or maximization
T run(const T* cost, int* sol, int n, T skip_threshold = std::numeric_limits<T>::max(),
int minimize_flag = 1,
T auction_max_eps=AUCTION_MAX_EPS,
T auction_min_eps=AUCTION_MIN_EPS,
float auction_factor=AUCTION_FACTOR,
int auction_max_iters=AUCTION_MAX_ITERS
)
{
int nn = n*n;
m_matrix.resize(nn);
m_item2person.resize(n);
m_bids.resize(nn);
m_prices.resize(n);
//m_bidders.resize(nn);
m_sbids.resize(n);
if (minimize_flag)
{
T max_cost = 0;
for (int i = 0; i < nn; ++i)
{
T c = cost[i];
if (c < skip_threshold)
{
max_cost = std::max(max_cost, c);
}
}
for ( int row = 0 ; row < n ; row++ )
{
for ( int col = 0 ; col < n ; col++ )
{
int idx = n*row+col;
T c = cost[idx];
m_matrix[idx] = (c < skip_threshold)? max_cost-c : BIG_NEGATIVE;
}
}
}
else
{
std::copy(cost, cost+nn, m_matrix.data());
}
int ret = run_auction<T>(
n,
m_matrix.data(),
sol,
auction_max_eps,
auction_min_eps,
auction_factor,
auction_max_iters,
m_item2person.data(),
m_bids.data(),
m_prices.data(),
m_sbids.data()
);
// Get solution and display objective.
T total_cost = 0;
if (ret)
{
for ( int row = 0 ; row < n ; row++ )
{
int col = sol[row];
total_cost += cost[n*row+col];
}
}
else // not found a solution and terminated early
{
total_cost = std::numeric_limits<T>::max();
for (int row = 0; row < n; ++row)
{
sol[row] = row;
}
}
return total_cost;
}
protected:
std::vector<T> m_matrix;
std::vector<int> m_item2person;
std::vector<T> m_bids;
std::vector<T> m_prices;
std::vector<int> m_sbids;
};
DREAMPLACE_END_NAMESPACE
#endif
|
racey_tasks.c
|
//
// This is a very simple program to play with tasks.
//
// the idea is to print one of two strings
//
// I think race cars are fun.
// I think car races are fun
//
// This is a race condition since depending on how the
// threads are scheduled, you will get a different answer.
// We aren't writing any variables. Hence this is not
// a data race and the program is legal.
//
#include <stdio.h>
#include <omp.h>
int main()
{
printf("I think");
#pragma omp parallel
{
#pragma omp single
{
#pragma omp task
printf(" car");
#pragma omp task
printf(" race");
}
}
printf("s");
printf(" are fun!\n");
}
|
declare-target-4.c
|
/* { dg-do compile } */
/* { dg-options "-fopenmp" } */
#pragma omp declare target device_type (any) /* { dg-warning "directive with only 'device_type' clauses ignored" } */
void f1 (void) {}
void f2 (void);
#pragma omp declare target to (f1) device_type (any) to (f2)
void f3 (void) {}
void f4 (void) {}
#pragma omp declare target device_type (host) to (f3)
#pragma omp declare target to (f4) device_type (nohost)
#pragma omp declare target
void f5 (void);
void f6 (void) {}
void f7 (void) {}
#pragma omp declare target to (f7)
void f8 (void) {}
#pragma omp declare target to (f8, f5)
#pragma omp declare target to (f5) to(f8)
#pragma omp declare target to (f8) device_type (host)
void f9 (void) {}
#pragma omp declare target to (f9) device_type (nohost)
#pragma omp declare target to (f9)
void f10 (void) {}
#pragma omp declare target device_type (any) to (f10)
void f11 (void) {}
#pragma omp end declare target
void f12 (void) {}
#pragma omp declare target device_type (any) to (f12)
#pragma omp declare target to (f12) device_type (host)
void f13 (void) {}
#pragma omp declare target device_type (host) to (f13)
#pragma omp declare target to (f13) device_type (nohost)
void f14 (void) {}
#pragma omp declare target device_type (nohost) to (f14)
#pragma omp declare target device_type (any) to (f14)
void f15 (void) {}
#pragma omp declare target device_type (host) to (f15) device_type (nohost)
void f16 (void) {}
#pragma omp declare target device_type (any) to (f15) device_type (any)
|
GB_binop__isgt_uint64.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__isgt_uint64)
// A.*B function (eWiseMult): GB (_AemultB_08__isgt_uint64)
// A.*B function (eWiseMult): GB (_AemultB_02__isgt_uint64)
// A.*B function (eWiseMult): GB (_AemultB_04__isgt_uint64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__isgt_uint64)
// A*D function (colscale): GB (_AxD__isgt_uint64)
// D*A function (rowscale): GB (_DxB__isgt_uint64)
// C+=B function (dense accum): GB (_Cdense_accumB__isgt_uint64)
// C+=b function (dense accum): GB (_Cdense_accumb__isgt_uint64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isgt_uint64)
// C=scalar+B GB (_bind1st__isgt_uint64)
// C=scalar+B' GB (_bind1st_tran__isgt_uint64)
// C=A+scalar GB (_bind2nd__isgt_uint64)
// C=A'+scalar GB (_bind2nd_tran__isgt_uint64)
// C type: uint64_t
// A type: uint64_t
// A pattern? 0
// B type: uint64_t
// B pattern? 0
// BinaryOp: cij = (aij > bij)
#define GB_ATYPE \
uint64_t
#define GB_BTYPE \
uint64_t
#define GB_CTYPE \
uint64_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
uint64_t aij = GBX (Ax, pA, A_iso)
// 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) \
uint64_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) \
uint64_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = (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_ISGT || GxB_NO_UINT64 || GxB_NO_ISGT_UINT64)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__isgt_uint64)
(
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__isgt_uint64)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__isgt_uint64)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type uint64_t
uint64_t bwork = (*((uint64_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__isgt_uint64)
(
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
uint64_t *restrict Cx = (uint64_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__isgt_uint64)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint64_t *restrict Cx = (uint64_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__isgt_uint64)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool 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) ;
uint64_t alpha_scalar ;
uint64_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((uint64_t *) alpha_scalar_in)) ;
beta_scalar = (*((uint64_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__isgt_uint64)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_08_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__isgt_uint64)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__isgt_uint64)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_04_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__isgt_uint64)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__isgt_uint64)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint64_t *Cx = (uint64_t *) Cx_output ;
uint64_t x = (*((uint64_t *) x_input)) ;
uint64_t *Bx = (uint64_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
uint64_t bij = GBX (Bx, p, false) ;
Cx [p] = (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_uint64)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
uint64_t *Cx = (uint64_t *) Cx_output ;
uint64_t *Ax = (uint64_t *) Ax_input ;
uint64_t y = (*((uint64_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
uint64_t aij = GBX (Ax, p, false) ;
Cx [p] = (aij > y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint64_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x > aij) ; \
}
GrB_Info GB (_bind1st_tran__isgt_uint64)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
uint64_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint64_t x = (*((const uint64_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint64_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint64_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij > y) ; \
}
GrB_Info GB (_bind2nd_tran__isgt_uint64)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint64_t y = (*((const uint64_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
6.datarace.c
|
#include <stdio.h>
#include <omp.h>
#define N 1 << 10
#define NUM_THREADS 8
/* Execute several times before answering the questions */
/* Q1: Is the program always executing correctly? Add two */
/* alternative directives to make it correct. */
int main()
{
int i, x=0;
omp_set_num_threads(NUM_THREADS);
#pragma omp parallel private(i)
{
int id=omp_get_thread_num();
for (i=id; i < N; i+=NUM_THREADS) {
x++;
}
}
if (x==N) printf("Congratulations!, program executed correctly (x = %d)\n", x);
else printf("Sorry, something went wrong, value of x = %d\n", x);
return 0;
}
|
BSSNScalar_Field.c
|
// Part P0: Set the number of ghost cells, from NRPy+'s FD_CENTDERIVS_ORDER
#define NGHOSTS 3
// Step P1a: Import needed header files
#include "stdio.h"
#include "stdlib.h"
#include <stdint.h>
#include "math.h"
#include "time.h"
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
// Step P1b: Import necessary gsl libraries for interpolating the initial data onto the grid
#include "gsl/gsl_spline.h"
#include "gsl/gsl_errno.h"
#include "gsl/gsl_interp.h"
// Step P2: Add needed #define's to set data type, the IDX4() macro, and the gridfunctions
// Step P2a: set REAL=double, so that all floating point numbers are stored to at least ~16 significant digits.
#define REAL double
// Step P3: Set free parameters
// Step P3a: Free parameters for the numerical grid
// Spherical coordinates parameter
const REAL RMAX = 30.; /* Set to approximately the time you wish to evolve for,
* so that at t=t_final data at the origin is not
* affected by the boundary conditions */
// Time coordinate parameters
const REAL t_final = 50.;
const REAL CFL_FACTOR = 0.5; // Set the CFL Factor
// Step P3b: Free parameters for the spacetime evolution
const REAL eta = 2.; // Gamma-driving shift condition parameter.
// Step P4: Implement the algorithm for upwinding.
// *NOTE*: This upwinding is backwards from
// usual upwinding algorithms, because the
// upwinding control vector in BSSN (the shift)
// acts like a *negative* velocity.
#define UPWIND_ALG(UpwindVecU) UpwindVecU > 0.0 ? 1.0 : 0.0
// Step P5: Set free parameters for Psi initial data
const REAL psi_posn_x = 0.0,psi_posn_y = 0.0,psi_posn_z = 0.0;
// Step P5b: Set free parameters for the scalar field
const REAL scalar_posn_x = 0.0;
const REAL scalar_posn_y = 0.0;
const REAL scalar_posn_z = 0.0;
const REAL br_on = 1.; // Turn on(1.)/off(0.) scalar field backreaction on the metric
const REAL pot1_on = 0.; // Turn on(1.)/off(0.) quadratic potential
const REAL pot2_on = 0.; // Turn on(1.)/off(0.) self-interactiong potential
// Make sure only one potential is on at a time
// Variables for the scalar field potential
const REAL scalarmass = 1.; // Scalar mass, \mu = c/\hbar m
const REAL fa = 0.05; // Decay constant, only relevant for the self-interacting potential
//Step P5c: Declare vars for initial data arrays
// We use initial data profiles for the scalar
// and the conformal factor that is known to
// lead to stable scalar field evolution
REAL uu_in;
REAL vv_in;
REAL psi_in;
REAL alpha_in;
REAL r_scalar;
REAL r_psi;
// Step P6: Declare the IDX4(gf,i,j,k) macro, which enables us to store 4-dimensions of
// data in a 1D array. In this case, consecutive values of "i"
// (all other indices held to a fixed value) are consecutive in memory, where
// consecutive values of "j" (fixing all other indices) are separated by
// Nxx_plus_2NGHOSTS[0] elements in memory. Similarly, consecutive values of
// "k" are separated by Nxx_plus_2NGHOSTS[0]*Nxx_plus_2NGHOSTS[1] in memory, etc.
#define IDX4(g,i,j,k) \
( (i) + Nxx_plus_2NGHOSTS[0] * ( (j) + Nxx_plus_2NGHOSTS[1] * ( (k) + Nxx_plus_2NGHOSTS[2] * (g) ) ) )
#define IDX3(i,j,k) ( (i) + Nxx_plus_2NGHOSTS[0] * ( (j) + Nxx_plus_2NGHOSTS[1] * (k) ) )
// Assuming idx = IDX3(i,j,k). Much faster if idx can be reused over and over:
#define IDX4pt(g,idx) ( (idx) + (Nxx_plus_2NGHOSTS[0]*Nxx_plus_2NGHOSTS[1]*Nxx_plus_2NGHOSTS[2]) * (g) )
// Step P7: Set #define's for BSSN gridfunctions. C code generated above
#include "gridfunction_defines.h"
#define LOOP_REGION(i0min,i0max, i1min,i1max, i2min,i2max) \
for(int i2=i2min;i2<i2max;i2++) for(int i1=i1min;i1<i1max;i1++) for(int i0=i0min;i0<i0max;i0++)
void xxCart(REAL *xx[3],const int i0,const int i1,const int i2, REAL xCart[3]) {
REAL xx0 = xx[0][i0];
REAL xx1 = xx[1][i1];
REAL xx2 = xx[2][i2];
#include "xxCart.h"
}
// Step P8: Include basic functions needed to impose curvilinear
// parity and boundary conditions.
#include "curvilinear_parity_and_outer_boundary_conditions.h"
#include "enforce_detgammabar_constraint.h"
// Step P9: Find the CFL-constrained timestep
REAL find_timestep(const int Nxx_plus_2NGHOSTS[3],const REAL dxx[3],REAL *xx[3], const REAL CFL_FACTOR) {
const REAL dxx0 = dxx[0], dxx1 = dxx[1], dxx2 = dxx[2];
REAL dsmin = 1e38; // Start with a crazy high value... close to the largest number in single precision.
LOOP_REGION(NGHOSTS,Nxx_plus_2NGHOSTS[0]-NGHOSTS, NGHOSTS,Nxx_plus_2NGHOSTS[1]-NGHOSTS, NGHOSTS,Nxx_plus_2NGHOSTS[2]-NGHOSTS) {
const REAL xx0 = xx[0][i0], xx1 = xx[1][i1], xx2 = xx[2][i2];
REAL ds_dirn0, ds_dirn1, ds_dirn2;
#include "ds_dirn.h"
#define MIN(A, B) ( ((A) < (B)) ? (A) : (B) )
// Set dsmin = MIN(dsmin, ds_dirn0, ds_dirn1, ds_dirn2);
dsmin = MIN(dsmin,MIN(ds_dirn0,MIN(ds_dirn1,ds_dirn2)));
}
return dsmin*CFL_FACTOR;
}
// Contains BSSN_ID() for arbitrary initial data array
#include "ID_array_psi.h"
// Step P10: Declare the function for the exact solution. time==0 corresponds to the initial data.
void initial_data(const int Nxx_plus_2NGHOSTS[3],REAL *xx[3], REAL *in_gfs) {
// Step P11a: Declare initial data arrays
FILE *uu_file = fopen("BSSN_SF/InitialData/phiCC9.csv", "r");
FILE *vv_file = fopen("BSSN_SF/InitialData/PiCC9.csv", "r");
FILE *psi_file = fopen("BSSN_SF/InitialData/psiCC9.csv", "r");
FILE *alpha_file = fopen("BSSN_SF/InitialData/alphaCC9.csv", "r");
int temp;
int alen = 0;
while(fscanf(uu_file,"%lf\n",&temp)==1){
alen++;
}
double r_arr[alen];
double uu_in_arr[alen];
double vv_in_arr[alen];
double psi_in_arr[alen];
double alpha_in_arr[alen];
rewind(uu_file);
for(int i=0;i<alen;i++){
r_arr[i] = 0.01*i;
fscanf(uu_file, "%lf\n", &uu_in_arr[i]);
fscanf(vv_file, "%lf\n", &vv_in_arr[i]);
fscanf(psi_file, "%lf\n", &psi_in_arr[i]);
fscanf(alpha_file, "%lf\n", &alpha_in_arr[i]);
}
// Step P11b: Declare splines to interpolate onto the cartesian grid
gsl_interp_accel *acc = gsl_interp_accel_alloc ();
gsl_spline *spline_u = gsl_spline_alloc (gsl_interp_cspline, alen);
gsl_spline_init(spline_u, r_arr, uu_in_arr, alen);
gsl_spline *spline_v = gsl_spline_alloc (gsl_interp_cspline, alen);
gsl_spline_init(spline_v, r_arr, vv_in_arr, alen);
gsl_spline *spline_psi = gsl_spline_alloc (gsl_interp_cspline, alen);
gsl_spline_init(spline_psi, r_arr, psi_in_arr, alen);
gsl_spline *spline_alpha = gsl_spline_alloc (gsl_interp_cspline, alen);
gsl_spline_init(spline_alpha, r_arr, alpha_in_arr, alen);
#pragma omp parallel for
LOOP_REGION(0,Nxx_plus_2NGHOSTS[0], 0,Nxx_plus_2NGHOSTS[1], 0,Nxx_plus_2NGHOSTS[2]) {
const int idx = IDX3(i0,i1,i2);
REAL xCart[3];
xxCart(xx, i0,i1,i2, xCart);
{
r_psi = sqrt(pow(-psi_posn_x + xCart[0], 2) + pow(-psi_posn_y + xCart[1], 2) + pow(-psi_posn_z + xCart[2], 2));
psi_in = gsl_spline_eval (spline_psi, r_psi, acc);
alpha_in = gsl_spline_eval (spline_alpha, r_psi, acc);
}
BSSN_ID(xx[0][i0],xx[1][i1],xx[2][i2],xCart[0],xCart[1],xCart[2],
&in_gfs[IDX4pt(HDD00GF,idx)],&in_gfs[IDX4pt(HDD01GF,idx)],&in_gfs[IDX4pt(HDD02GF,idx)],
&in_gfs[IDX4pt(HDD11GF,idx)],&in_gfs[IDX4pt(HDD12GF,idx)],&in_gfs[IDX4pt(HDD22GF,idx)],
&in_gfs[IDX4pt(TRKGF,idx)],
&in_gfs[IDX4pt(ADD00GF,idx)],&in_gfs[IDX4pt(ADD01GF,idx)],&in_gfs[IDX4pt(ADD02GF,idx)],
&in_gfs[IDX4pt(ADD11GF,idx)],&in_gfs[IDX4pt(ADD12GF,idx)],&in_gfs[IDX4pt(ADD22GF,idx)],
&in_gfs[IDX4pt(LAMBDAU0GF,idx)],&in_gfs[IDX4pt(LAMBDAU1GF,idx)],&in_gfs[IDX4pt(LAMBDAU2GF,idx)],
&in_gfs[IDX4pt(VETU0GF,idx)],&in_gfs[IDX4pt(VETU1GF,idx)],&in_gfs[IDX4pt(VETU2GF,idx)],
&in_gfs[IDX4pt(BETU0GF,idx)],&in_gfs[IDX4pt(BETU1GF,idx)],&in_gfs[IDX4pt(BETU2GF,idx)],
&in_gfs[IDX4pt(ALPHAGF,idx)],&in_gfs[IDX4pt(CFGF,idx)]);
REAL xx0 = xCart[0];
REAL xx1 = xCart[1];
REAL xx2 = xCart[2];
{
r_scalar = sqrt(pow(-scalar_posn_x + xx0, 2) + pow(-scalar_posn_y + xx1, 2) + pow(-scalar_posn_z + xx2, 2));
in_gfs[IDX4(UUGF, i0, i1, i2)] = gsl_spline_eval (spline_u, r_scalar, acc);
in_gfs[IDX4(VVGF, i0, i1, i2)] = gsl_spline_eval (spline_v, r_scalar, acc);
}
}
}
// Step P12: Implement Hamiltonian constraint diagnostic
void Hamiltonian_constraint(const int Nxx[3],const int Nxx_plus_2NGHOSTS[3],const REAL dxx[3], REAL *xx[3],
REAL *in_gfs, REAL *aux_gfs) {
#include "Hamiltonian.h"
}
// Step P13: Declare the function to evaluate the BSSN RHSs
void rhs_eval(const int Nxx[3],const int Nxx_plus_2NGHOSTS[3],const REAL dxx[3], REAL *xx[3], const REAL *in_gfs,REAL *rhs_gfs) {
#include "BSSN_RHSs.h"
}
#include "ID_array_ADM.h"
// main() function:
// Step 0: Read command-line input, set up grid structure, allocate memory for gridfunctions, set up coordinates
// Step 1: Set up scalar wave initial data
// Step 2: Evolve scalar wave initial data forward in time using Method of Lines with RK4 algorithm,
// applying quadratic extrapolation outer boundary conditions.
// Step 3: Output relative error between numerical and exact solution.
// Step 4: Free all allocated memory
int main(int argc, const char *argv[]) {
// Step 0a: Read command-line input, error out if nonconformant
if(argc != 4 || atoi(argv[1]) < NGHOSTS) {
printf("Error: Expected one command-line argument: ./BSSNCurvilinear_Playground Nx0 Nx1 Nx2,\n");
printf("where Nx[0,1,2] is the number of grid points in the 0, 1, and 2 directions.\n");
printf("Nx[] MUST BE larger than NGHOSTS (= %d)\n",NGHOSTS);
exit(1);
}
// Step 0b: Set up numerical grid structure, first in space...
const int Nx0 = atoi(argv[1]);
const int Nx1 = atoi(argv[2]);
const int Nx2 = atoi(argv[3]);
if(Nx0%2 != 0 || Nx1%2 != 0 || Nx2%2 != 0) {
printf("Error: Cannot guarantee a proper cell-centered grid if number of grid cells not set to even number.\n");
printf(" For example, in case of angular directions, proper symmetry zones will not exist.\n");
exit(1);
}
const int Nxx[3] = { Nx0, Nx1, Nx2 };
const int Nxx_plus_2NGHOSTS[3] = { Nxx[0]+2*NGHOSTS, Nxx[1]+2*NGHOSTS, Nxx[2]+2*NGHOSTS };
const int Nxx_plus_2NGHOSTS_tot = Nxx_plus_2NGHOSTS[0]*Nxx_plus_2NGHOSTS[1]*Nxx_plus_2NGHOSTS[2];
#include "xxminmax.h"
// Step 0c: Allocate memory for gridfunctions
REAL *evol_gfs = (REAL *)malloc(sizeof(REAL) * NUM_EVOL_GFS * Nxx_plus_2NGHOSTS_tot);
REAL *next_in_gfs = (REAL *)malloc(sizeof(REAL) * NUM_EVOL_GFS * Nxx_plus_2NGHOSTS_tot);
REAL *aux_gfs = (REAL *)malloc(sizeof(REAL) * NUM_AUX_GFS * Nxx_plus_2NGHOSTS_tot);
REAL *k1_gfs = (REAL *)malloc(sizeof(REAL) * NUM_EVOL_GFS * Nxx_plus_2NGHOSTS_tot);
REAL *k2_gfs = (REAL *)malloc(sizeof(REAL) * NUM_EVOL_GFS * Nxx_plus_2NGHOSTS_tot);
REAL *k3_gfs = (REAL *)malloc(sizeof(REAL) * NUM_EVOL_GFS * Nxx_plus_2NGHOSTS_tot);
REAL *k4_gfs = (REAL *)malloc(sizeof(REAL) * NUM_EVOL_GFS * Nxx_plus_2NGHOSTS_tot);
// Step 0d: Set up space and time coordinates
// Step 0d.i: Set \Delta x^i on uniform grids.
REAL dxx[3];
for(int i=0;i<3;i++) dxx[i] = (xxmax[i] - xxmin[i]) / ((REAL)Nxx[i]);
// Step 0d.ii: Set up uniform coordinate grids
REAL *xx[3];
for(int i=0;i<3;i++) {
xx[i] = (REAL *)malloc(sizeof(REAL)*Nxx_plus_2NGHOSTS[i]);
for(int j=0;j<Nxx_plus_2NGHOSTS[i];j++) {
xx[i][j] = xxmin[i] + ((REAL)(j-NGHOSTS) + (1.0/2.0))*dxx[i]; // Cell-centered grid.
}
}
// Step 0d.iii: Set timestep based on smallest proper distance between gridpoints and CFL factor
REAL dt = find_timestep(Nxx_plus_2NGHOSTS, dxx,xx, CFL_FACTOR);
//printf("# Timestep set to = %e\n",(double)dt);
int N_final = (int)(t_final / dt + 0.5); // The number of iterations in time.
//Add 0.5 to account for C rounding down integers.
// Step 0e: Find ghostzone mappings and parities:
gz_map *bc_gz_map = (gz_map *)malloc(sizeof(gz_map)*Nxx_plus_2NGHOSTS_tot);
parity_condition *bc_parity_conditions = (parity_condition *)malloc(sizeof(parity_condition)*Nxx_plus_2NGHOSTS_tot);
set_up_bc_gz_map_and_parity_conditions(Nxx_plus_2NGHOSTS,xx,dxx,xxmin,xxmax, bc_gz_map, bc_parity_conditions);
// Step 1: Set up initial data to be exact solution at time=0:
initial_data(Nxx_plus_2NGHOSTS, xx, evol_gfs);
// Step 1b: Apply boundary conditions *FOR VALIDATION PURPOSES*
apply_bcs(Nxx, Nxx_plus_2NGHOSTS, bc_gz_map,bc_parity_conditions, evol_gfs);
enforce_detgammabar_constraint(Nxx_plus_2NGHOSTS, xx, evol_gfs);
// Step 2: Evaluate Hamiltonian constraint violation
//Hamiltonian_constraint(Nxx,Nxx_plus_2NGHOSTS,dxx, xx, evol_gfs, aux_gfs);
// Step 3: Start the timer, for keeping track of how fast the simulation is progressing.
struct timespec start, end;
//clock_gettime(CLOCK_REALTIME, &start);
// Step 4: Integrate the initial data forward in time using the Method of Lines and RK4
char filename2[100];
sprintf(filename2,"BSSN_SF-evolution/quad_pot_uu_vv_cf.txt");
FILE *evol = fopen(filename2, "w");
for(int n=0;n<=N_final;n++) { // Main loop to progress forward in time.
/***************************************************/
/* Implement RK4 for Method of Lines timestepping: */
/***************************************************/
/* -= RK4: Step 1 of 4 =- */
/* First evaluate k1 = RHSs expression */
rhs_eval(Nxx,Nxx_plus_2NGHOSTS,dxx, xx,evol_gfs, k1_gfs);
/* Next k1 -> k1*dt, and then set the input for */
/* the next RHS eval call to y_n+k1/2 */
#pragma omp parallel for
for(int i=0;i<Nxx_plus_2NGHOSTS_tot*NUM_EVOL_GFS;i++) {
k1_gfs[i] *= dt;
next_in_gfs[i] = evol_gfs[i] + k1_gfs[i]*0.5;
}
/* Finally, apply boundary conditions to */
/* next_in_gfs, so its data are set everywhere. */
apply_bcs(Nxx, Nxx_plus_2NGHOSTS, bc_gz_map,bc_parity_conditions, next_in_gfs);
enforce_detgammabar_constraint(Nxx_plus_2NGHOSTS, xx, next_in_gfs);
/* -= RK4: Step 2 of 4 =- */
rhs_eval(Nxx,Nxx_plus_2NGHOSTS,dxx, xx,next_in_gfs, k2_gfs);
#pragma omp parallel for
for(int i=0;i<Nxx_plus_2NGHOSTS_tot*NUM_EVOL_GFS;i++) {
k2_gfs[i] *= dt;
next_in_gfs[i] = evol_gfs[i] + k2_gfs[i]*0.5;
}
apply_bcs(Nxx, Nxx_plus_2NGHOSTS, bc_gz_map,bc_parity_conditions, next_in_gfs);
enforce_detgammabar_constraint(Nxx_plus_2NGHOSTS, xx, next_in_gfs);
/* -= RK4: Step 3 of 4 =- */
rhs_eval(Nxx,Nxx_plus_2NGHOSTS,dxx, xx,next_in_gfs, k3_gfs);
#pragma omp parallel for
for(int i=0;i<Nxx_plus_2NGHOSTS_tot*NUM_EVOL_GFS;i++) {
k3_gfs[i] *= dt;
next_in_gfs[i] = evol_gfs[i] + k3_gfs[i];
}
apply_bcs(Nxx, Nxx_plus_2NGHOSTS, bc_gz_map,bc_parity_conditions, next_in_gfs);
enforce_detgammabar_constraint(Nxx_plus_2NGHOSTS, xx, next_in_gfs);
/* -= RK4: Step 4 of 4 =- */
rhs_eval(Nxx,Nxx_plus_2NGHOSTS,dxx, xx,next_in_gfs, k4_gfs);
#pragma omp parallel for
for(int i=0;i<Nxx_plus_2NGHOSTS_tot*NUM_EVOL_GFS;i++) {
k4_gfs[i] *= dt;
evol_gfs[i] += (1.0/6.0)*(k1_gfs[i] + 2.0*k2_gfs[i] + 2.0*k3_gfs[i] + k4_gfs[i]);
}
Hamiltonian_constraint(Nxx,Nxx_plus_2NGHOSTS,dxx, xx, evol_gfs, aux_gfs);
apply_bcs(Nxx, Nxx_plus_2NGHOSTS, bc_gz_map,bc_parity_conditions, evol_gfs);
enforce_detgammabar_constraint(Nxx_plus_2NGHOSTS, xx, evol_gfs);
/* Output the solution of the scalar field and the conformal factor at diffrent time slices on a 2D grid */
if(n%10 == 0) {
char filename[100];
sprintf(filename,"BSSN_SF-output2D/quad_pot_2d_t-%08d.txt",n);
FILE *out2D = fopen(filename, "w");
const int i0MIN=NGHOSTS; // In spherical, r=Delta r/2.
const int i1mid=Nxx_plus_2NGHOSTS[1]/2;
const int i2mid=Nxx_plus_2NGHOSTS[2]/2;
LOOP_REGION(NGHOSTS,Nxx_plus_2NGHOSTS[0]-NGHOSTS, NGHOSTS,Nxx_plus_2NGHOSTS[1]-NGHOSTS, NGHOSTS,Nxx_plus_2NGHOSTS[2]-NGHOSTS) {
REAL xx0 = xx[0][i0];
REAL xx1 = xx[1][i1];
REAL xx2 = xx[2][i2];
REAL xCart[3];
#include "xxCart.h"
int idx = IDX3(i0,i1,i2);
ADMCart_ID(out2D, n*(double)dt , xx0, xx1, xx2, xCart[0], xCart[1], xCart[2],
evol_gfs[IDX4pt(HDD00GF,idx)], evol_gfs[IDX4pt(HDD01GF,idx)], evol_gfs[IDX4pt(HDD02GF,idx)],
evol_gfs[IDX4pt(HDD11GF,idx)], evol_gfs[IDX4pt(HDD12GF,idx)], evol_gfs[IDX4pt(HDD22GF,idx)],
evol_gfs[IDX4pt(ADD00GF,idx)], evol_gfs[IDX4pt(ADD01GF,idx)], evol_gfs[IDX4pt(ADD02GF,idx)],
evol_gfs[IDX4pt(ADD11GF,idx)], evol_gfs[IDX4pt(ADD12GF,idx)], evol_gfs[IDX4pt(ADD22GF,idx)],
evol_gfs[IDX4pt(TRKGF,idx)],
evol_gfs[IDX4pt(LAMBDAU0GF,idx)],evol_gfs[IDX4pt(LAMBDAU1GF,idx)],evol_gfs[IDX4pt(LAMBDAU2GF,idx)],
evol_gfs[IDX4pt(VETU0GF,idx)],evol_gfs[IDX4pt(VETU1GF,idx)],evol_gfs[IDX4pt(VETU2GF,idx)],
evol_gfs[IDX4pt(BETU0GF,idx)],evol_gfs[IDX4pt(BETU1GF,idx)],evol_gfs[IDX4pt(BETU2GF,idx)],
evol_gfs[IDX4pt(ALPHAGF,idx)],evol_gfs[IDX4pt(CFGF,idx)],
evol_gfs[IDX4pt(UUGF,idx)],evol_gfs[IDX4pt(VVGF,idx)]);
}
fclose(out2D);
}
// Output time evolution at r=0
int idx0 = IDX3(0,0,0);
fprintf(evol,"%e %e %e %e\n", n*dt, evol_gfs[IDX4pt(UUGF,idx0)],evol_gfs[IDX4pt(VVGF,idx0)],evol_gfs[IDX4pt(CFGF,idx0)]);
// Progress indicator printing to stdout
// Measure average time per iteration
//clock_gettime(CLOCK_REALTIME, &end);
const long long unsigned int time_in_ns = 1000000000L * (end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec;
const REAL s_per_iteration_avg = ((REAL)time_in_ns / (REAL)n) / 1.0e9;
const int iterations_remaining = N_final - n;
const REAL time_remaining_in_mins = s_per_iteration_avg * (REAL)iterations_remaining / 60.0;
const REAL num_RHS_pt_evals = (REAL)(Nxx[0]*Nxx[1]*Nxx[2]) * 4.0 * (REAL)n; // 4 RHS evals per gridpoint for RK4
const REAL RHS_pt_evals_per_sec = num_RHS_pt_evals / ((REAL)time_in_ns / 1.0e9);
// Progress indicator printing to stdout
printf("%c[2K", 27); // Clear the line
printf("It: %d t=%.2f | %.1f%%; ETA %.0f s | t/h %.2f | gp/s %.2e\r", // \r is carriage return, move cursor to the beginning of the line
n, n * (double)dt, (double)(100.0 * (REAL)n / (REAL)N_final),
(double)time_remaining_in_mins*60, (double)(dt * 3600.0 / s_per_iteration_avg), (double)RHS_pt_evals_per_sec);
fflush(stdout); // Flush the stdout buffer
} // End main loop to progress forward in time.
printf("\n"); // Clear the line.
fclose(evol);
/* Step 4: Free all allocated memory */
free(bc_parity_conditions);
free(bc_gz_map);
free(k4_gfs);
free(k3_gfs);
free(k2_gfs);
free(k1_gfs);
free(aux_gfs);
free(next_in_gfs);
free(evol_gfs);
for(int i=0;i<3;i++) free(xx[i]);
return 0;
}
|
GB_unop__trunc_fc64_fc64.c
|
//------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop_apply__trunc_fc64_fc64
// op(A') function: GB_unop_tran__trunc_fc64_fc64
// C type: GxB_FC64_t
// A type: GxB_FC64_t
// cast: GxB_FC64_t cij = aij
// unaryop: cij = GB_ctrunc (aij)
#define GB_ATYPE \
GxB_FC64_t
#define GB_CTYPE \
GxB_FC64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
GxB_FC64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = GB_ctrunc (x) ;
// casting
#define GB_CAST(z, aij) \
GxB_FC64_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GxB_FC64_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
GxB_FC64_t z = aij ; \
Cx [pC] = GB_ctrunc (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_TRUNC || GxB_NO_FC64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__trunc_fc64_fc64
(
GxB_FC64_t *Cx, // Cx and Ax may be aliased
const GxB_FC64_t *Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GxB_FC64_t aij = Ax [p] ;
GxB_FC64_t z = aij ;
Cx [p] = GB_ctrunc (z) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_tran__trunc_fc64_fc64
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
pooling_hcl_arm.h
|
/*
* 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: [email protected]
*/
#include "pooling_param.h"
#include "graph/tensor.h"
#include "graph/node.h"
#include "graph/graph.h"
#include "module/module.h"
#include "operator/op.h"
#include "utility/float.h"
#include "utility/sys_port.h"
#include "utility/log.h"
#include "device/cpu/cpu_node.h"
#include "device/cpu/cpu_graph.h"
#include "device/cpu/cpu_module.h"
#include <assert.h>
#include <math.h>
#include <stddef.h>
#include <arm_neon.h>
#define POOL_GENERIC 0
#define POOL_K2S2 1
#define POOL_K3S2 2
#define POOL_K3S1 3
typedef void (*pooling_kernel_t)(const void* input, void* output, int inc, int inh, int inw, int outh, int outw, int,
int, int, int, int, int, int pad_h1, int pad_w1, int);
static void avg_2x2s2(const float* input, float* output, int inc, int inh, int inw, int outh, int outw, int k_h,
int k_w, int s_h, int s_w, int pad_h0, int pad_w0, int pad_h1, int pad_w1, int is_caffe)
{
int in_hw = inw * inh;
int out_hw = outh * outw;
if (pad_w1 > 0)
{
outw--;
}
if (pad_h1 > 0)
{
outh--;
}
int block_w = outw >> 2;
int remain_w = inw - outw * 2;
for (int c = 0; c < inc; c++)
{
const float* line0 = input + c * in_hw;
const float* line1 = line0 + inw;
float* out_ptr = output + c * out_hw;
for (int i = 0; i < outh; i++)
{
for (int j = 0; j < block_w; j++)
{
float32x4_t p00 = vld1q_f32(line0);
float32x4_t p10 = vld1q_f32(line1);
float32x4_t sum0 = vaddq_f32(p00, p10);
float32x4_t p01 = vld1q_f32(line0 + 4);
float32x4_t p11 = vld1q_f32(line1 + 4);
float32x4_t sum1 = vaddq_f32(p01, p11);
#ifdef __aarch64__
sum0 = vpaddq_f32(sum0, sum1);
#else
float32x2_t sum0_1 = vpadd_f32(vget_low_f32(sum0), vget_high_f32(sum0));
float32x2_t sum0_2 = vpadd_f32(vget_low_f32(sum1), vget_high_f32(sum1));
sum0 = vcombine_f32(sum0_1, sum0_2);
#endif
sum0 = vmulq_n_f32(sum0, 0.25f);
vst1q_f32(out_ptr, sum0);
line0 += 8;
line1 += 8;
out_ptr += 4;
}
for (int j = block_w * 4; j < outw; j++)
{
float32x2_t p1 = vld1_f32(line0);
float32x2_t p2 = vld1_f32(line1);
float32x2_t sum = vadd_f32(p1, p2);
*out_ptr = (sum[0] + sum[1]) * 0.25f;
out_ptr++;
line0 += 2;
line1 += 2;
}
if (pad_w1)
{
*out_ptr = (line0[0] + line1[0]) * 0.5f;
out_ptr++;
}
line0 += remain_w + inw;
line1 += remain_w + inw;
}
if (pad_h1)
{
for (int j = 0; j < block_w; j++)
{
float32x4_t p00 = vld1q_f32(line0);
float32x4_t p01 = vld1q_f32(line0 + 4);
#ifdef __aarch64__
p00 = vpaddq_f32(p00, p01);
#else
float32x2_t sum0_1 = vpadd_f32(vget_low_f32(p00), vget_high_f32(p00));
float32x2_t sum0_2 = vpadd_f32(vget_low_f32(p01), vget_high_f32(p01));
p00 = vcombine_f32(sum0_1, sum0_2);
#endif
p00 = vmulq_n_f32(p00, 0.5f);
vst1q_f32(out_ptr, p00);
line0 += 8;
out_ptr += 4;
}
for (int j = block_w * 4; j < outw; j++)
{
float32x2_t p1 = vld1_f32(line0);
*out_ptr = (p1[0] + p1[1]) * 0.5f;
out_ptr++;
line0 += 2;
}
if (pad_w1)
{
*out_ptr = line0[0];
out_ptr++;
}
}
}
}
static void max_2x2s2(const float* input, float* output, int inc, int inh, int inw, int outh, int outw, int k_h,
int k_w, int s_h, int s_w, int pad_h0, int pad_w0, int pad_h1, int pad_w1, int is_caffe)
{
int in_hw = inw * inh;
int out_hw = outh * outw;
if (pad_w1 > 0)
{
outw--;
}
if (pad_h1 > 0)
{
outh--;
}
int block_w = outw >> 2;
int remain_w = inw - outw * 2;
for (int c = 0; c < inc; c++)
{
const float* line0 = input + c * in_hw;
const float* line1 = line0 + inw;
float* out_ptr = output + c * out_hw;
for (int i = 0; i < outh; i++)
{
for (int j = 0; j < block_w; j++)
{
float32x4_t p00 = vld1q_f32(line0);
float32x4_t p10 = vld1q_f32(line1);
float32x4_t p01 = vld1q_f32(line0 + 4);
float32x4_t p11 = vld1q_f32(line1 + 4);
#ifdef __aarch64__
float32x4_t max0 = vmaxq_f32(p00, p10);
float32x4_t max1 = vmaxq_f32(p01, p11);
/* pairwaise max */
float32x4_t _max = vpmaxq_f32(max0, max1);
#else
float32x2_t max0_1 = vpmax_f32(vget_low_f32(p00), vget_low_f32(p10));
float32x2_t max0_2 = vpmax_f32(vget_high_f32(p00), vget_high_f32(p10));
max0_1 = vpmax_f32(max0_1, max0_2);
float32x2_t max1_1 = vpmax_f32(vget_low_f32(p01), vget_low_f32(p11));
float32x2_t max1_2 = vpmax_f32(vget_high_f32(p01), vget_high_f32(p11));
max1_1 = vpmax_f32(max1_1, max1_2);
float32x4_t _max = vcombine_f32(max0_1, max1_1);
#endif
vst1q_f32(out_ptr, _max);
line0 += 8;
line1 += 8;
out_ptr += 4;
}
for (int j = block_w * 4; j < outw; j++)
{
float32x2_t p1 = vld1_f32(line0);
float32x2_t p2 = vld1_f32(line1);
float32x2_t _max = vmax_f32(p1, p2);
*out_ptr = fmax(_max[0], _max[1]);
out_ptr++;
line0 += 2;
line1 += 2;
}
if (pad_w1 > 0)
{
*out_ptr = fmax(line0[0], line1[0]);
out_ptr++;
}
line0 += remain_w + inw;
line1 += remain_w + inw;
}
if (pad_h1 > 0)
{
for (int j = 0; j < block_w; j++)
{
float32x4_t p00 = vld1q_f32(line0);
float32x4_t p01 = vld1q_f32(line0 + 4);
#ifdef __aarch64__
p00 = vpmaxq_f32(p00, p01);
#else
float32x2_t max0_1 = vpmax_f32(vget_low_f32(p00), vget_high_f32(p00));
float32x2_t max0_2 = vpmax_f32(vget_low_f32(p01), vget_high_f32(p01));
p00 = vcombine_f32(max0_1, max0_2);
#endif
vst1q_f32(out_ptr, p00);
line0 += 8;
out_ptr += 4;
}
for (int j = block_w * 4; j < outw; j++)
{
float32x2_t p1 = vld1_f32(line0);
*out_ptr = fmax(p1[0], p1[1]);
out_ptr++;
line0 += 2;
}
if (pad_w1 > 0)
{
*out_ptr = line0[0];
out_ptr++;
}
}
}
}
static void avg_3x3s2(const float* input, float* output, int inc, int inh, int inw, int outh, int outw, int k_h,
int k_w, int s_h, int s_w, int pad_h0, int pad_w0, int pad_h1, int pad_w1, int is_caffe)
{
int in_hw = inw * inh;
int out_hw = outh * outw;
if (pad_w1 > 0)
{
outw--;
}
if (pad_h1 > 0)
{
outh--;
}
int block_w = outw >> 2;
int remain_w = inw - outw * 2;
for (int c = 0; c < inc; c++)
{
const float* line0 = input + c * in_hw;
const float* line1 = line0 + inw;
const float* line2 = line1 + inw;
float* out_ptr = output + c * out_hw;
for (int i = 0; i < outh; i++)
{
float32x4x2_t p00 = vld2q_f32(line0);
float32x4x2_t p10 = vld2q_f32(line1);
float32x4x2_t p20 = vld2q_f32(line2);
for (int j = 0; j < block_w; j++)
{
float32x4x2_t p00_new = vld2q_f32(line0 + 8);
float32x4_t sum0 = vaddq_f32(p00.val[0], p00.val[1]);
float32x4_t p01 = vextq_f32(p00.val[0], p00_new.val[0], 1);
sum0 = vaddq_f32(sum0, p01);
float32x4x2_t p10_new = vld2q_f32(line1 + 8);
float32x4_t sum1 = vaddq_f32(p10.val[0], p10.val[1]);
float32x4_t p11 = vextq_f32(p10.val[0], p10_new.val[0], 1);
sum1 = vaddq_f32(sum1, p11);
float32x4x2_t p20_new = vld2q_f32(line2 + 8);
float32x4_t sum2 = vaddq_f32(p20.val[0], p20.val[1]);
float32x4_t p21 = vextq_f32(p20.val[0], p20_new.val[0], 1);
sum2 = vaddq_f32(sum2, p21);
sum0 = vaddq_f32(vaddq_f32(sum0, sum1), sum2);
sum0 = vmulq_n_f32(sum0, 0.11111111f);
vst1q_f32(out_ptr, sum0);
p00 = p00_new;
p10 = p10_new;
p20 = p20_new;
line0 += 8;
line1 += 8;
line2 += 8;
out_ptr += 4;
}
for (int j = block_w * 4; j < outw; j++)
{
*out_ptr = (line0[0] + line0[1] + line0[2] + line1[0] + line1[1] + line1[2] + line2[0] + line2[1] + line2[2]) * 0.11111111f;
out_ptr++;
line0 += 2;
line1 += 2;
line2 += 2;
}
if (pad_w1 == 1)
{
*out_ptr = (line0[0] + line0[1] + line1[0] + line1[1] + line2[0] + line2[1]) * 0.16666667f;
out_ptr++;
}
line0 += remain_w + inw;
line1 += remain_w + inw;
line2 += remain_w + inw;
}
if (pad_h1 == 1)
{
float32x4x2_t p00 = vld2q_f32(line0);
float32x4x2_t p10 = vld2q_f32(line1);
for (int j = 0; j < block_w; j++)
{
float32x4x2_t p00_new = vld2q_f32(line0 + 8);
float32x4_t sum0 = vaddq_f32(p00.val[0], p00.val[1]);
float32x4_t p01 = vextq_f32(p00.val[0], p00_new.val[0], 1);
sum0 = vaddq_f32(sum0, p01);
float32x4x2_t p10_new = vld2q_f32(line1 + 8);
float32x4_t sum1 = vaddq_f32(p10.val[0], p10.val[1]);
float32x4_t p11 = vextq_f32(p10.val[0], p10_new.val[0], 1);
sum1 = vaddq_f32(sum1, p11);
sum0 = vaddq_f32(sum0, sum1);
sum0 = vmulq_n_f32(sum0, 0.16666667f);
vst1q_f32(out_ptr, sum0);
p00 = p00_new;
p10 = p10_new;
line0 += 8;
line1 += 8;
out_ptr += 4;
}
for (int j = block_w * 4; j < outw; j++)
{
*out_ptr = (line0[0] + line0[1] + line0[2] + line1[0] + line1[1] + line1[2]) * 0.16666667f;
out_ptr++;
line0 += 2;
line1 += 2;
}
if (pad_w1 == 1)
{
*out_ptr = (line0[0] + line0[1] + line1[0] + line1[1]) * 0.25f;
out_ptr++;
}
else if (pad_w1 == 2)
{
*out_ptr = (line0[0] + line1[0]) * 0.5f;
out_ptr++;
}
}
else if (pad_h1 == 2)
{
float32x4x2_t p00 = vld2q_f32(line0);
for (int j = 0; j < block_w; j++)
{
float32x4x2_t p00_new = vld2q_f32(line0 + 8);
float32x4_t sum0 = vaddq_f32(p00.val[0], p00.val[1]);
float32x4_t p01 = vextq_f32(p00.val[0], p00_new.val[0], 1);
sum0 = vaddq_f32(sum0, p01);
sum0 = vmulq_n_f32(sum0, 0.3333333f);
vst1q_f32(out_ptr, sum0);
p00 = p00_new;
line0 += 8;
out_ptr += 4;
}
for (int j = block_w * 4; j < outw; j++)
{
*out_ptr = (line0[0] + line0[1] + line0[2]) * 0.3333333f;
out_ptr++;
line0 += 2;
}
if (pad_w1 == 1)
{
*out_ptr = (line0[0] + line0[1]) * 0.5f;
out_ptr++;
}
else if (pad_w1 == 2)
{
*out_ptr = line0[0];
out_ptr++;
}
}
}
}
static void max_3x3s2(const float* input, float* output, int inc, int inh, int inw, int outh, int outw, int k_h,
int k_w, int s_h, int s_w, int pad_h0, int pad_w0, int pad_h1, int pad_w1, int is_caffe)
{
int in_hw = inw * inh;
int out_hw = outh * outw;
if (pad_w1 > 0)
{
outw--;
}
if (pad_h1 > 0)
{
outh--;
}
int block_w = outw >> 2;
int remain_w = inw - outw * 2;
for (int c = 0; c < inc; c++)
{
const float* line0 = input + c * in_hw;
const float* line1 = line0 + inw;
const float* line2 = line1 + inw;
float* out_ptr = output + c * out_hw;
for (int i = 0; i < outh; i++)
{
float32x4x2_t p00 = vld2q_f32(line0);
float32x4x2_t p10 = vld2q_f32(line1);
float32x4x2_t p20 = vld2q_f32(line2);
for (int j = 0; j < block_w; j++)
{
/*
p00 = [1,2,3,4,5,6,7,8]
p00.val[0]=[1,3,5,7]
max0 = [2,4,6,8]
p00_new = [9,10,11,12,13,14,15,16]
p01 = [3,5,7,9]
max0=max(max0,p01)=[3,5,7,9]
*/
float32x4x2_t p00_new = vld2q_f32(line0 + 8);
float32x4_t max0 = vmaxq_f32(p00.val[0], p00.val[1]);
float32x4_t p01 = vextq_f32(p00.val[0], p00_new.val[0], 1);
max0 = vmaxq_f32(max0, p01);
float32x4x2_t p10_new = vld2q_f32(line1 + 8);
float32x4_t max1 = vmaxq_f32(p10.val[0], p10.val[1]);
float32x4_t p11 = vextq_f32(p10.val[0], p10_new.val[0], 1);
max1 = vmaxq_f32(max1, p11);
float32x4x2_t p20_new = vld2q_f32(line2 + 8);
float32x4_t max2 = vmaxq_f32(p20.val[0], p20.val[1]);
float32x4_t p21 = vextq_f32(p20.val[0], p20_new.val[0], 1);
max2 = vmaxq_f32(max2, p21);
max0 = vmaxq_f32(vmaxq_f32(max0, max1), max2);
vst1q_f32(out_ptr, max0);
p00 = p00_new;
p10 = p10_new;
p20 = p20_new;
line0 += 8;
line1 += 8;
line2 += 8;
out_ptr += 4;
}
for (int j = block_w * 4; j < outw; j++)
{
float max0 = fmax(fmax(line0[0], line0[1]), line0[2]);
float max1 = fmax(fmax(line1[0], line1[1]), line1[2]);
float max2 = fmax(fmax(line2[0], line2[1]), line2[2]);
*out_ptr = fmax(fmax(max0, max1), max2);
out_ptr++;
line0 += 2;
line1 += 2;
line2 += 2;
}
if (pad_w1 == 1)
{
float max0 = fmax(fmax(line0[0], line0[1]), fmax(line1[0], line1[1]));
*out_ptr = fmax(fmax(line2[0], line2[1]), max0);
out_ptr++;
}
line0 += remain_w + inw;
line1 += remain_w + inw;
line2 += remain_w + inw;
}
if (pad_h1 == 1)
{
float32x4x2_t p00 = vld2q_f32(line0);
float32x4x2_t p10 = vld2q_f32(line1);
for (int j = 0; j < block_w; j++)
{
float32x4x2_t p00_new = vld2q_f32(line0 + 8);
float32x4_t max0 = vmaxq_f32(p00.val[0], p00.val[1]);
float32x4_t p01 = vextq_f32(p00.val[0], p00_new.val[0], 1);
max0 = vmaxq_f32(max0, p01);
float32x4x2_t p10_new = vld2q_f32(line1 + 8);
float32x4_t max1 = vmaxq_f32(p10.val[0], p10.val[1]);
float32x4_t p11 = vextq_f32(p10.val[0], p10_new.val[0], 1);
max1 = vmaxq_f32(max1, p11);
vst1q_f32(out_ptr, vmaxq_f32(max0, max1));
p00 = p00_new;
p10 = p10_new;
line0 += 8;
line1 += 8;
out_ptr += 4;
}
for (int j = block_w * 4; j < outw; j++)
{
float max0 = fmax(fmax(line0[0], line0[1]), line0[2]);
float max1 = fmax(fmax(line1[0], line1[1]), line1[2]);
*out_ptr = fmax(max0, max1);
out_ptr++;
line0 += 2;
line1 += 2;
}
if (pad_w1 == 1)
{
*out_ptr = fmax(fmax(line0[0], line0[1]), fmax(line1[0], line1[1]));
out_ptr++;
}
}
}
}
static void avg_2x2s2_p1(const float* input, float* output, int inc, int inh, int inw, int outh, int outw, int k_h,
int k_w, int s_h, int s_w, int pad_h0, int pad_w0, int pad_h1, int pad_w1, int is_caffe)
{
int in_hw = inw * inh;
int out_hw = outh * outw;
if (inw % 2 == 0)
outw--;
if (inh % 2 == 0)
outh--;
int block_w = (outw - 1) >> 2;
int remain_w = inw - outw * 2 + 1;
for (int c = 0; c < inc; c++)
{
const float* line00 = input + c * in_hw;
float* out_ptr = output + c * out_hw;
// h begin
if (is_caffe == 0)
*out_ptr = line00[0];
else
*out_ptr = line00[0] * 0.25f;
out_ptr++;
line00++;
for (int j = 0; j < block_w; j++)
{
float32x4_t p00 = vld1q_f32(line00);
float32x4_t p01 = vld1q_f32(line00 + 4);
#ifdef __aarch64__
float32x4_t sum0 = vpaddq_f32(p00, p01);
#else
float32x2_t sum0_1 = vpadd_f32(vget_low_f32(p00), vget_high_f32(p00));
float32x2_t sum0_2 = vpadd_f32(vget_low_f32(p01), vget_high_f32(p01));
float32x4_t sum0 = vcombine_f32(sum0_1, sum0_2);
#endif
if (is_caffe == 0)
sum0 = vmulq_n_f32(sum0, 0.5f);
else
sum0 = vmulq_n_f32(sum0, 0.25f);
vst1q_f32(out_ptr, sum0);
line00 += 8;
out_ptr += 4;
}
for (int j = block_w * 4 + 1; j < outw; j++)
{
if (is_caffe == 0)
*out_ptr = (line00[0] + line00[1]) * 0.5f;
else
*out_ptr = (line00[0] + line00[1]) * 0.25f;
out_ptr++;
line00 += 2;
}
if (inw % 2 == 0)
{
if (is_caffe == 0)
*out_ptr = line00[0];
else
*out_ptr = line00[0] * 0.25f;
out_ptr++;
}
line00 += remain_w;
// h center
const float* line0 = line00;
const float* line1 = line0 + inw;
for (int i = 1; i < outh; i++)
{
// w begin
if (is_caffe == 0)
*out_ptr = (line0[0] + line1[0]) * 0.5f;
else
*out_ptr = (line0[0] + line1[0]) * 0.25f;
out_ptr++;
line0++;
line1++;
// w center
for (int j = 0; j < block_w; j++)
{
float32x4_t p00 = vld1q_f32(line0);
float32x4_t p10 = vld1q_f32(line1);
float32x4_t sum0 = vaddq_f32(p00, p10);
float32x4_t p01 = vld1q_f32(line0 + 4);
float32x4_t p11 = vld1q_f32(line1 + 4);
float32x4_t sum1 = vaddq_f32(p01, p11);
#ifdef __aarch64__
float32x4_t _sum = vpaddq_f32(sum0, sum1);
#else
float32x2_t sum0_1 = vpadd_f32(vget_low_f32(sum0), vget_high_f32(sum0));
float32x2_t sum0_2 = vpadd_f32(vget_low_f32(sum1), vget_high_f32(sum1));
float32x4_t _sum = vcombine_f32(sum0_1, sum0_2);
#endif
_sum = vmulq_n_f32(_sum, 0.25f);
vst1q_f32(out_ptr, _sum);
out_ptr += 4;
line0 += 8;
line1 += 8;
}
for (int j = block_w * 4 + 1; j < outw; j++)
{
*out_ptr = (line0[0] + line0[1] + line1[0] + line1[1]) * 0.25f;
out_ptr++;
line0 += 2;
line1 += 2;
}
// w end
if (inw % 2 == 0)
{
if (is_caffe == 0)
*out_ptr = (line0[0] + line1[0]) * 0.5f;
else
*out_ptr = (line0[0] + line1[0]) * 0.25f;
out_ptr++;
}
line0 += remain_w + inw;
line1 += remain_w + inw;
}
// h end
if (inh % 2 == 0)
{
if (is_caffe == 0)
*out_ptr = line0[0];
else
*out_ptr = line0[0] * 0.25f;
out_ptr++;
line0++;
for (int j = 0; j < block_w; j++)
{
float32x4_t p00 = vld1q_f32(line0);
float32x4_t p01 = vld1q_f32(line0 + 4);
#ifdef __aarch64__
float32x4_t _sum = vpaddq_f32(p00, p01);
#else
float32x2_t sum0_1 = vpadd_f32(vget_low_f32(p00), vget_high_f32(p00));
float32x2_t sum0_2 = vpadd_f32(vget_low_f32(p01), vget_high_f32(p01));
float32x4_t _sum = vcombine_f32(sum0_1, sum0_2);
#endif
if (is_caffe == 0)
_sum = vmulq_n_f32(_sum, 0.5f);
else
_sum = vmulq_n_f32(_sum, 0.25f);
vst1q_f32(out_ptr, _sum);
out_ptr += 4;
line0 += 8;
}
for (int j = block_w * 4 + 1; j < outw; j++)
{
if (is_caffe == 0)
*out_ptr = (line0[0] + line0[1]) * 0.5f;
else
*out_ptr = (line0[0] + line0[1]) * 0.25f;
out_ptr++;
line0 += 2;
}
if (inw % 2 == 0)
{
if (is_caffe == 0)
*out_ptr = line0[0];
else
*out_ptr = line0[0] * 0.25f;
}
}
}
}
static void max_2x2s2_p1(const float* input, float* output, int inc, int inh, int inw, int outh, int outw, int k_h,
int k_w, int s_h, int s_w, int pad_h0, int pad_w0, int pad_h1, int pad_w1, int is_caffe)
{
int in_hw = inw * inh;
int out_hw = outh * outw;
if (inw % 2 == 0)
outw--;
if (inh % 2 == 0)
outh--;
int block_w = (outw - 1) >> 2;
int remain_w = inw - outw * 2 + 1;
for (int c = 0; c < inc; c++)
{
const float* line00 = input + c * in_hw;
float* out_ptr = output + c * out_hw;
// h begin
*out_ptr = line00[0];
out_ptr++;
line00++;
for (int j = 0; j < block_w; j++)
{
float32x4_t p00 = vld1q_f32(line00);
float32x4_t p01 = vld1q_f32(line00 + 4);
#ifdef __aarch64__
float32x4_t _max = vpmaxq_f32(p00, p01);
#else
float32x2_t max0_1 = vpmax_f32(vget_low_f32(p00), vget_high_f32(p00));
float32x2_t max0_2 = vpmax_f32(vget_low_f32(p01), vget_high_f32(p01));
float32x4_t _max = vcombine_f32(max0_1, max0_2);
#endif
vst1q_f32(out_ptr, _max);
out_ptr += 4;
line00 += 8;
}
for (int j = block_w * 4 + 1; j < outw; j++)
{
*out_ptr = fmax(line00[0], line00[1]);
out_ptr++;
line00 += 2;
}
if (inw % 2 == 0)
{
*out_ptr = line00[0];
out_ptr++;
}
line00 += remain_w;
// h center
const float* line0 = line00;
const float* line1 = line0 + inw;
for (int i = 1; i < outh; i++)
{
// w begin
*out_ptr = fmax(line0[0], line1[0]);
out_ptr++;
line0++;
line1++;
// w center
for (int j = 0; j < block_w; j++)
{
float32x4_t p00 = vld1q_f32(line0);
float32x4_t p10 = vld1q_f32(line1);
float32x4_t p01 = vld1q_f32(line0 + 4);
float32x4_t p11 = vld1q_f32(line1 + 4);
#ifdef __aarch64__
float32x4_t max0 = vmaxq_f32(p00, p10);
float32x4_t max1 = vmaxq_f32(p01, p11);
float32x4_t _max = vpmaxq_f32(max0, max1);
#else
float32x2_t max0_1 = vpmax_f32(vget_low_f32(p00), vget_low_f32(p10));
float32x2_t max0_2 = vpmax_f32(vget_high_f32(p00), vget_high_f32(p10));
max0_1 = vpmax_f32(max0_1, max0_2);
float32x2_t max1_1 = vpmax_f32(vget_low_f32(p01), vget_low_f32(p11));
float32x2_t max1_2 = vpmax_f32(vget_high_f32(p01), vget_high_f32(p11));
max1_1 = vpmax_f32(max1_1, max1_2);
float32x4_t _max = vcombine_f32(max0_1, max1_1);
#endif
vst1q_f32(out_ptr, _max);
out_ptr += 4;
line0 += 8;
line1 += 8;
}
for (int j = block_w * 4 + 1; j < outw; j++)
{
float32x2_t p1 = vld1_f32(line0);
float32x2_t p2 = vld1_f32(line1);
float32x2_t _max = vmax_f32(p1, p2);
*out_ptr = fmax(_max[0], _max[1]);
out_ptr++;
line0 += 2;
line1 += 2;
}
// w end
if (inw % 2 == 0)
{
*out_ptr = fmax(line0[0], line1[0]);
out_ptr++;
}
line0 += remain_w + inw;
line1 += remain_w + inw;
}
// h end
if (inh % 2 == 0)
{
*out_ptr = line0[0];
out_ptr++;
line0++;
for (int j = 0; j < block_w; j++)
{
float32x4_t p00 = vld1q_f32(line0);
float32x4_t p01 = vld1q_f32(line0 + 4);
#ifdef __aarch64__
float32x4_t _max = vpmaxq_f32(p00, p01);
#else
float32x2_t max0_1 = vpmax_f32(vget_low_f32(p00), vget_high_f32(p00));
float32x2_t max0_2 = vpmax_f32(vget_low_f32(p01), vget_high_f32(p01));
float32x4_t _max = vcombine_f32(max0_1, max0_2);
#endif
vst1q_f32(out_ptr, _max);
out_ptr += 4;
line0 += 8;
}
for (int j = block_w * 4 + 1; j < outw; j++)
{
*out_ptr = fmax(line0[0], line0[1]);
out_ptr++;
line0 += 2;
}
if (inw % 2 == 0)
{
*out_ptr = line0[0];
}
}
}
}
static void max_3x3s2_p1(const float* input, float* output, int inc, int inh, int inw, int outh, int outw, int k_h,
int k_w, int s_h, int s_w, int pad_h0, int pad_w0, int pad_h1, int pad_w1, int is_caffe)
{
// TLOG_ERR("max_3x3s2_p1\n");
int in_hw = inw * inh;
int out_hw = outh * outw;
if (is_caffe == 1 || inw % 2 == 1)
outw--;
if (is_caffe == 1 || inh % 2 == 1)
outh--;
int block_w = (outw - 1) >> 2;
int remain_w = inw - outw * 2 + 1;
for (int c = 0; c < inc; c++)
{
const float* line1 = input + c * in_hw;
const float* line2 = line1 + inw;
float* out_ptr = output + c * out_hw;
// h begin ---------------------------------------
*out_ptr = fmax(fmax(line1[0], line1[1]), fmax(line2[0], line2[1]));
out_ptr++;
line1 += 1;
line2 += 1;
float32x4x2_t p10 = vld2q_f32(line1);
float32x4x2_t p20 = vld2q_f32(line2);
for (int j = 0; j < block_w; j++)
{
float32x4x2_t p10_new = vld2q_f32(line1 + 8);
float32x4_t max1 = vmaxq_f32(p10.val[0], p10.val[1]);
float32x4_t p11 = vextq_f32(p10.val[0], p10_new.val[0], 1);
max1 = vmaxq_f32(max1, p11);
float32x4x2_t p20_new = vld2q_f32(line2 + 8);
float32x4_t max2 = vmaxq_f32(p20.val[0], p20.val[1]);
float32x4_t p21 = vextq_f32(p20.val[0], p20_new.val[0], 1);
max2 = vmaxq_f32(max2, p21);
max1 = vmaxq_f32(max1, max2);
vst1q_f32(out_ptr, max1);
p10 = p10_new;
p20 = p20_new;
line1 += 8;
line2 += 8;
out_ptr += 4;
}
for (int j = block_w * 4 + 1; j < outw; j++)
{
float max1 = fmax(fmax(line1[0], line1[1]), line1[2]);
float max2 = fmax(fmax(line2[0], line2[1]), line2[2]);
*out_ptr = fmax(max1, max2);
out_ptr++;
line1 += 2;
line2 += 2;
}
if (inw % 2 == 1)
{
*out_ptr = fmax(fmax(line1[0], line1[1]), fmax(line2[0], line2[1]));
out_ptr++;
}
else if (is_caffe == 1 && inw % 2 == 0)
{
*out_ptr = fmax(line1[0], line2[0]);
out_ptr++;
}
line1 += remain_w;
line2 += remain_w;
// h center ---------------------------------------
const float* line0 = line1;
line1 = line2;
line2 = line1 + inw;
for (int i = 1; i < outh; i++)
{
// left
float max0 = fmax(fmax(line1[0], line1[1]), fmax(line2[0], line2[1]));
*out_ptr = fmax(fmax(line0[0], line0[1]), max0);
out_ptr++;
line0 += 1;
line1 += 1;
line2 += 1;
// mid
float32x4x2_t p00 = vld2q_f32(line0);
float32x4x2_t p10 = vld2q_f32(line1);
float32x4x2_t p20 = vld2q_f32(line2);
for (int j = 0; j < block_w; j++)
{
float32x4x2_t p00_new = vld2q_f32(line0 + 8);
float32x4_t max0 = vmaxq_f32(p00.val[0], p00.val[1]);
float32x4_t p01 = vextq_f32(p00.val[0], p00_new.val[0], 1);
max0 = vmaxq_f32(max0, p01);
float32x4x2_t p10_new = vld2q_f32(line1 + 8);
float32x4_t max1 = vmaxq_f32(p10.val[0], p10.val[1]);
float32x4_t p11 = vextq_f32(p10.val[0], p10_new.val[0], 1);
max1 = vmaxq_f32(max1, p11);
float32x4x2_t p20_new = vld2q_f32(line2 + 8);
float32x4_t max2 = vmaxq_f32(p20.val[0], p20.val[1]);
float32x4_t p21 = vextq_f32(p20.val[0], p20_new.val[0], 1);
max2 = vmaxq_f32(max2, p21);
max0 = vmaxq_f32(vmaxq_f32(max0, max1), max2);
vst1q_f32(out_ptr, max0);
p00 = p00_new;
p10 = p10_new;
p20 = p20_new;
line0 += 8;
line1 += 8;
line2 += 8;
out_ptr += 4;
}
for (int j = block_w * 4 + 1; j < outw; j++)
{
float max0 = fmax(fmax(line0[0], line0[1]), line0[2]);
float max1 = fmax(fmax(line1[0], line1[1]), line1[2]);
float max2 = fmax(fmax(line2[0], line2[1]), line2[2]);
*out_ptr = fmax(fmax(max0, max1), max2);
out_ptr++;
line0 += 2;
line1 += 2;
line2 += 2;
}
if (inw % 2 == 1)
{
max0 = fmax(fmax(line1[0], line1[1]), fmax(line2[0], line2[1]));
*out_ptr = fmax(fmax(line0[0], line0[1]), max0);
out_ptr++;
}
else if (inw % 2 == 0 && is_caffe == 1)
{
*out_ptr = fmax(fmax(line0[0], line1[0]), line2[0]);
out_ptr++;
}
line0 += inw + remain_w;
line1 += inw + remain_w;
line2 += inw + remain_w;
}
// h end ------------------------------------------
if (inh % 2 == 1)
{
*out_ptr = fmax(fmax(line1[0], line1[1]), fmax(line0[0], line0[1]));
out_ptr++;
line0 += 1;
line1 += 1;
float32x4x2_t p00 = vld2q_f32(line0);
float32x4x2_t p10 = vld2q_f32(line1);
for (int j = 0; j < block_w; j++)
{
float32x4x2_t p00_new = vld2q_f32(line0 + 8);
float32x4_t max0 = vmaxq_f32(p00.val[0], p00.val[1]);
float32x4_t p01 = vextq_f32(p00.val[0], p00_new.val[0], 1);
max0 = vmaxq_f32(max0, p01);
float32x4x2_t p10_new = vld2q_f32(line1 + 8);
float32x4_t max1 = vmaxq_f32(p10.val[0], p10.val[1]);
float32x4_t p11 = vextq_f32(p10.val[0], p10_new.val[0], 1);
max1 = vmaxq_f32(max1, p11);
max0 = vmaxq_f32(max0, max1);
vst1q_f32(out_ptr, max0);
p00 = p00_new;
p10 = p10_new;
line0 += 8;
line1 += 8;
out_ptr += 4;
}
for (int j = block_w * 4 + 1; j < outw; j++)
{
float max0 = fmax(fmax(line0[0], line0[1]), line0[2]);
float max1 = fmax(fmax(line1[0], line1[1]), line1[2]);
*out_ptr = fmax(max0, max1);
out_ptr++;
line0 += 2;
line1 += 2;
}
if (inw % 2 == 1)
{
*out_ptr = fmax(fmax(line1[0], line1[1]), fmax(line0[0], line0[1]));
out_ptr++;
}
else if (inw % 2 == 0 && is_caffe == 1)
{
*out_ptr = fmax(line0[0], line1[0]);
out_ptr++;
}
}
else if (inh % 2 == 0 && is_caffe == 1)
{
*out_ptr = fmax(line0[0], line0[1]);
out_ptr++;
line0 += 1;
float32x4x2_t p00 = vld2q_f32(line0);
for (int j = 0; j < block_w; j++)
{
float32x4x2_t p00_new = vld2q_f32(line0 + 8);
float32x4_t max0 = vmaxq_f32(p00.val[0], p00.val[1]);
float32x4_t p01 = vextq_f32(p00.val[0], p00_new.val[0], 1);
max0 = vmaxq_f32(max0, p01);
vst1q_f32(out_ptr, max0);
p00 = p00_new;
line0 += 8;
out_ptr += 4;
}
for (int j = block_w * 4 + 1; j < outw; j++)
{
*out_ptr = fmax(fmax(line0[0], line0[1]), line0[2]);
out_ptr++;
line0 += 2;
}
if (inw % 2 == 1)
{
*out_ptr = fmax(line0[0], line0[1]);
out_ptr++;
}
else if (inw % 2 == 0)
{
*out_ptr = line0[0];
}
}
}
}
static void avg_3x3s2_p1(const float* input, float* output, int inc, int inh, int inw, int outh, int outw, int k_h,
int k_w, int s_h, int s_w, int pad_h0, int pad_w0, int pad_h1, int pad_w1, int is_caffe)
{
int in_hw = inw * inh;
int out_hw = outh * outw;
if (is_caffe == 1 || inw % 2 == 1)
outw--;
if (is_caffe == 1 || inh % 2 == 1)
outh--;
int block_w = (outw - 1) >> 2;
int remain_w = inw - outw * 2 + 1;
for (int c = 0; c < inc; c++)
{
const float* line1 = input + c * in_hw;
const float* line2 = line1 + inw;
float* out_ptr = output + c * out_hw;
// h begin ---------------------------------------
if (is_caffe == 0)
*out_ptr = (line1[0] + line1[1] + line2[0] + line2[1]) * 0.25f;
else
*out_ptr = (line1[0] + line1[1] + line2[0] + line2[1]) * 0.11111111f;
out_ptr++;
line1 += 1;
line2 += 1;
float32x4x2_t p10 = vld2q_f32(line1);
float32x4x2_t p20 = vld2q_f32(line2);
for (int j = 0; j < block_w; j++)
{
float32x4x2_t p10_new = vld2q_f32(line1 + 8);
float32x4_t sum1 = vaddq_f32(p10.val[0], p10.val[1]);
float32x4_t p11 = vextq_f32(p10.val[0], p10_new.val[0], 1);
sum1 = vaddq_f32(sum1, p11);
float32x4x2_t p20_new = vld2q_f32(line2 + 8);
float32x4_t sum2 = vaddq_f32(p20.val[0], p20.val[1]);
float32x4_t p21 = vextq_f32(p20.val[0], p20_new.val[0], 1);
sum2 = vaddq_f32(sum2, p21);
sum1 = vaddq_f32(sum1, sum2);
if (is_caffe == 0)
sum1 = vmulq_n_f32(sum1, 0.16666667f);
else
sum1 = vmulq_n_f32(sum1, 0.11111111f);
vst1q_f32(out_ptr, sum1);
p10 = p10_new;
p20 = p20_new;
line1 += 8;
line2 += 8;
out_ptr += 4;
}
for (int j = block_w * 4 + 1; j < outw; j++)
{
if (is_caffe == 0)
*out_ptr = (line1[0] + line1[1] + line1[2] + line2[0] + line2[1] + line2[2]) * 0.16666667f;
else
*out_ptr = (line1[0] + line1[1] + line1[2] + line2[0] + line2[1] + line2[2]) * 0.11111111f;
out_ptr++;
line1 += 2;
line2 += 2;
}
if (inw % 2 == 1)
{
if (is_caffe == 0)
*out_ptr = (line1[0] + line1[1] + line2[0] + line2[1]) * 0.25f;
else
*out_ptr = (line1[0] + line1[1] + line2[0] + line2[1]) * 0.11111111f;
out_ptr++;
}
else if (inw % 2 == 0 && is_caffe == 1)
{
*out_ptr = (line1[0] + line2[0]) * 0.16666667f;
out_ptr++;
}
line1 += remain_w;
line2 += remain_w;
// h center ---------------------------------------
const float* line0 = line1;
line1 = line2;
line2 = line1 + inw;
for (int i = 1; i < outh; i++)
{
// left
if (is_caffe == 0)
*out_ptr = (line0[0] + line0[1] + line1[0] + line1[1] + line2[0] + line2[1]) * 0.16666667f;
else
*out_ptr = (line0[0] + line0[1] + line1[0] + line1[1] + line2[0] + line2[1]) * 0.11111111f;
out_ptr++;
line0 += 1;
line1 += 1;
line2 += 1;
// mid
float32x4x2_t p00 = vld2q_f32(line0);
float32x4x2_t p10 = vld2q_f32(line1);
float32x4x2_t p20 = vld2q_f32(line2);
for (int j = 0; j < block_w; j++)
{
float32x4x2_t p00_new = vld2q_f32(line0 + 8);
float32x4_t sum0 = vaddq_f32(p00.val[0], p00.val[1]);
float32x4_t p01 = vextq_f32(p00.val[0], p00_new.val[0], 1);
sum0 = vaddq_f32(sum0, p01);
float32x4x2_t p10_new = vld2q_f32(line1 + 8);
float32x4_t sum1 = vaddq_f32(p10.val[0], p10.val[1]);
float32x4_t p11 = vextq_f32(p10.val[0], p10_new.val[0], 1);
sum1 = vaddq_f32(sum1, p11);
float32x4x2_t p20_new = vld2q_f32(line2 + 8);
float32x4_t sum2 = vaddq_f32(p20.val[0], p20.val[1]);
float32x4_t p21 = vextq_f32(p20.val[0], p20_new.val[0], 1);
sum2 = vaddq_f32(sum2, p21);
sum0 = vaddq_f32(vaddq_f32(sum0, sum1), sum2);
sum0 = vmulq_n_f32(sum0, 0.11111111f);
vst1q_f32(out_ptr, sum0);
p00 = p00_new;
p10 = p10_new;
p20 = p20_new;
line0 += 8;
line1 += 8;
line2 += 8;
out_ptr += 4;
}
for (int j = block_w * 4 + 1; j < outw; j++)
{
*out_ptr = (line0[0] + line0[1] + line0[2] + line1[0] + line1[1] + line1[2] + line2[0] + line2[1] + line2[2]) * 0.11111111f;
out_ptr++;
line0 += 2;
line1 += 2;
line2 += 2;
}
// end
if (inw % 2 == 1)
{
if (is_caffe == 0)
*out_ptr = (line0[0] + line0[1] + line1[0] + line1[1] + line2[0] + line2[1]) * 0.16666667f;
else
*out_ptr = (line0[0] + line0[1] + line1[0] + line1[1] + line2[0] + line2[1]) * 0.11111111f;
out_ptr++;
}
else if (inw % 2 == 0 && is_caffe == 1)
{
*out_ptr = (line0[0] + line1[0] + line2[0]) * 0.16666667f;
out_ptr++;
}
line0 += remain_w + inw;
line1 += remain_w + inw;
line2 += remain_w + inw;
}
// h end-------------------------------
if (inh % 2 == 1)
{
if (is_caffe == 0)
*out_ptr = (line0[0] + line0[1] + line1[0] + line1[1]) * 0.25f;
else
*out_ptr = (line0[0] + line0[1] + line1[0] + line1[1]) * 0.11111111f;
out_ptr++;
line0 += 1;
line1 += 1;
float32x4x2_t p00 = vld2q_f32(line0);
float32x4x2_t p10 = vld2q_f32(line1);
for (int j = 0; j < block_w; j++)
{
float32x4x2_t p00_new = vld2q_f32(line0 + 8);
float32x4_t sum0 = vaddq_f32(p00.val[0], p00.val[1]);
float32x4_t p01 = vextq_f32(p00.val[0], p00_new.val[0], 1);
sum0 = vaddq_f32(sum0, p01);
float32x4x2_t p10_new = vld2q_f32(line1 + 8);
float32x4_t sum1 = vaddq_f32(p10.val[0], p10.val[1]);
float32x4_t p11 = vextq_f32(p10.val[0], p10_new.val[0], 1);
sum1 = vaddq_f32(sum1, p11);
sum0 = vaddq_f32(sum0, sum1);
if (is_caffe == 0)
sum0 = vmulq_n_f32(sum0, 0.16666667f);
else
sum0 = vmulq_n_f32(sum0, 0.11111111f);
vst1q_f32(out_ptr, sum0);
p00 = p00_new;
p10 = p10_new;
line0 += 8;
line1 += 8;
out_ptr += 4;
}
for (int j = block_w * 4 + 1; j < outw; j++)
{
if (is_caffe == 0)
*out_ptr = (line0[0] + line0[1] + line0[2] + line1[0] + line1[1] + line1[2]) * 0.16666667f;
else
*out_ptr = (line0[0] + line0[1] + line0[2] + line1[0] + line1[1] + line1[2]) * 0.11111111f;
out_ptr++;
line0 += 2;
line1 += 2;
}
if (inw % 2 == 1)
{
if (is_caffe == 0)
*out_ptr = (line0[0] + line0[1] + line1[0] + line1[1]) * 0.25f;
else
*out_ptr = (line0[0] + line0[1] + line1[0] + line1[1]) * 0.11111111f;
out_ptr++;
}
else if (inw % 2 == 0 && is_caffe == 1)
{
*out_ptr = (line0[0] + line1[0]) * 0.16666667f;
out_ptr++;
}
}
else if (inw % 2 == 0 && is_caffe == 1)
{
*out_ptr = (line0[0] + line0[1]) * 0.16666667f;
out_ptr++;
line0 += 1;
float32x4x2_t p00 = vld2q_f32(line0);
for (int j = 0; j < block_w; j++)
{
float32x4x2_t p00_new = vld2q_f32(line0 + 8);
float32x4_t sum0 = vaddq_f32(p00.val[0], p00.val[1]);
float32x4_t p01 = vextq_f32(p00.val[0], p00_new.val[0], 1);
sum0 = vaddq_f32(sum0, p01);
sum0 = vmulq_n_f32(sum0, 0.16666667f);
vst1q_f32(out_ptr, sum0);
p00 = p00_new;
line0 += 8;
out_ptr += 4;
}
for (int j = block_w * 4 + 1; j < outw; j++)
{
*out_ptr = (line0[0] + line0[1] + line0[2]) * 0.16666667f;
out_ptr++;
line0 += 2;
}
if (inw % 2 == 1)
{
*out_ptr = (line0[0] + line0[1]) * 0.16666667f;
out_ptr++;
}
else if (inw % 2 == 0)
{
*out_ptr = line0[0] * 0.25f;
out_ptr++;
}
}
}
}
static void max_3x3s1_p1(const float* input, float* output, int inc, int inh, int inw, int outh, int outw, int k_h,
int k_w, int s_h, int s_w, int pad_h0, int pad_w0, int pad_h1, int pad_w1, int is_caffe)
{
// TLOG_ERR("max_3x3s1_p1\n");
int in_hw = inw * inh;
int mid_w = inw - 2;
int mid_h = inh - 2;
for (int c = 0; c < inc; c++)
{
const float* line1 = input + c * in_hw;
const float* line2 = line1 + inw;
float* out_ptr = output + c * in_hw;
// h begin left----[line1+=0]-----------------------------------
*out_ptr = fmax(fmax(line1[0], line1[1]), fmax(line2[0], line2[1]));
out_ptr++;
// h begin center----[line1+=1]----------------------------------
for (int j = 0; j < mid_w; j++)
{
float max1 = fmax(fmax(line1[0], line1[1]), line1[2]);
float max2 = fmax(fmax(line2[0], line2[1]), line2[2]);
*out_ptr = fmax(max2, max1);
out_ptr++;
line1 += 1;
line2 += 1;
}
// h begin right----[line1+=2]-----------------------------------
*out_ptr = fmax(fmax(line1[0], line1[1]), fmax(line2[0], line2[1]));
out_ptr++;
line1 += 2;
line2 += 2;
// h center ---------------------------------------
const float* line0 = input + c * in_hw;
for (int i = 0; i < mid_h; i++)
{
// left
float max0 = fmax(fmax(line1[0], line1[1]), fmax(line2[0], line2[1]));
*out_ptr = fmax(fmax(line0[0], line0[1]), max0);
out_ptr++;
// mid
for (int j = 0; j < mid_w; j++)
{
float max0 = fmax(fmax(line0[0], line0[1]), line0[2]);
float max1 = fmax(fmax(line1[0], line1[1]), line1[2]);
float max2 = fmax(fmax(line2[0], line2[1]), line2[2]);
*out_ptr = fmax(fmax(max0, max1), max2);
out_ptr++;
line0 += 1;
line1 += 1;
line2 += 1;
}
max0 = fmax(fmax(line1[0], line1[1]), fmax(line2[0], line2[1]));
*out_ptr = fmax(fmax(line0[0], line0[1]), max0);
out_ptr++;
line0 += 2;
line1 += 2;
line2 += 2;
}
// h end ------------------------------------------
*out_ptr = fmax(fmax(line1[0], line1[1]), fmax(line0[0], line0[1]));
out_ptr++;
for (int j = 0; j < mid_w; j++)
{
float max0 = fmax(fmax(line0[0], line0[1]), line0[2]);
float max1 = fmax(fmax(line1[0], line1[1]), line1[2]);
*out_ptr = fmax(max0, max1);
out_ptr++;
line0 += 1;
line1 += 1;
}
*out_ptr = fmax(fmax(line1[0], line1[1]), fmax(line0[0], line0[1]));
}
}
static void avg_3x3s1_p1(const float* input, float* output, int inc, int inh, int inw, int outh, int outw, int k_h,
int k_w, int s_h, int s_w, int pad_h0, int pad_w0, int pad_h1, int pad_w1, int is_caffe)
{
// TLOG_ERR("avg_3x3s1_p1\n");
int in_hw = inw * inh;
int mid_w = inw - 2;
int mid_h = inh - 2;
for (int c = 0; c < inc; c++)
{
const float* line1 = input + c * in_hw;
const float* line2 = line1 + inw;
float* out_ptr = output + c * in_hw;
// h begin left----[line1+=0]-----------------------------------
if (is_caffe == 0)
*out_ptr = (line1[0] + line1[1] + line2[0] + line2[1]) * 0.25f;
else
*out_ptr = (line1[0] + line1[1] + line2[0] + line2[1]) * 0.11111111f;
out_ptr++;
// h begin center----[line1+=1]----------------------------------
for (int j = 0; j < mid_w; j++)
{
if (is_caffe == 0)
*out_ptr = (line1[0] + line1[1] + line1[2] + line2[0] + line2[1] + line2[2]) * 0.16666667f;
else
*out_ptr = (line1[0] + line1[1] + line1[2] + line2[0] + line2[1] + line2[2]) * 0.11111111f;
out_ptr++;
line1 += 1;
line2 += 1;
}
// h begin right----[line1+=2]-----------------------------------
if (is_caffe == 0)
*out_ptr = (line1[0] + line1[1] + line2[0] + line2[1]) * 0.25f;
else
*out_ptr = (line1[0] + line1[1] + line2[0] + line2[1]) * 0.11111111f;
out_ptr++;
line1 += 2;
line2 += 2;
// h center ---------------------------------------
const float* line0 = input + c * in_hw;
for (int i = 0; i < mid_h; i++)
{
// left
if (is_caffe == 0)
*out_ptr = (line0[0] + line0[1] + line1[0] + line1[1] + line2[0] + line2[1]) * 0.16666667f;
else
*out_ptr = (line0[0] + line0[1] + line1[0] + line1[1] + line2[0] + line2[1]) * 0.11111111f;
out_ptr++;
// mid
for (int j = 0; j < mid_w; j++)
{
*out_ptr = (line0[0] + line0[1] + line0[2] + line1[0] + line1[1] + line1[2] + line2[0] + line2[1] + line2[2]) * 0.11111111f;
out_ptr++;
line0 += 1;
line1 += 1;
line2 += 1;
}
if (is_caffe == 0)
*out_ptr = (line0[0] + line0[1] + line1[0] + line1[1] + line2[0] + line2[1]) * 0.16666667f;
else
*out_ptr = (line0[0] + line0[1] + line1[0] + line1[1] + line2[0] + line2[1]) * 0.11111111f;
out_ptr++;
line0 += 2;
line1 += 2;
line2 += 2;
}
// h end ------------------------------------------
if (is_caffe == 0)
*out_ptr = (line0[0] + line0[1] + line1[0] + line1[1]) * 0.25f;
else
*out_ptr = (line0[0] + line0[1] + line1[0] + line1[1]) * 0.11111111f;
out_ptr++;
for (int j = 0; j < mid_w; j++)
{
if (is_caffe == 0)
*out_ptr = (line0[0] + line0[1] + line0[2] + line1[0] + line1[1] + line1[2]) * 0.16666667f;
else
*out_ptr = (line0[0] + line0[1] + line0[2] + line1[0] + line1[1] + line1[2]) * 0.11111111f;
out_ptr++;
line0 += 1;
line1 += 1;
}
if (is_caffe == 0)
*out_ptr = (line0[0] + line0[1] + line1[0] + line1[1]) * 0.25f;
else
*out_ptr = (line0[0] + line0[1] + line1[0] + line1[1]) * 0.11111111f;
}
}
static void avg_global(const float* input, float* output, int inc, int inh, int inw, int outh, int outw, int k_h,
int k_w, int s_h, int s_w, int pad_h0, int pad_w0, int pad_h1, int pad_w1, int is_caffe)
{
int in_hw = inw * inh;
int block = in_hw >> 3;
int tail = in_hw & ~7;
for (int c = 0; c < inc; c++)
{
const float* line0 = input + c * in_hw;
float* out_ptr = output + c;
float sum = 0.f;
for (int j = 0; j < block; j++)
{
float32x4_t p00 = vld1q_f32(line0);
float32x4_t p01 = vld1q_f32(line0 + 4);
p00 = vaddq_f32(p00, p01);
// p00=vpaddq_f32(p00,p00);
// sum+=(p00[0]+p00[1]);
sum += (p00[0] + p00[1] + p00[2] + p00[3]);
line0 += 8;
}
for (int j = tail; j < in_hw; j++)
{
sum += line0[0];
line0++;
}
*out_ptr = sum / in_hw;
}
}
static void max_global(const float* input, float* output, int inc, int inh, int inw, int outh, int outw, int k_h,
int k_w, int s_h, int s_w, int pad_h0, int pad_w0, int pad_h1, int pad_w1, int is_caffe)
{
int in_hw = inw * inh;
int block = in_hw >> 3;
int tail = in_hw & ~7;
for (int c = 0; c < inc; c++)
{
const float* line0 = input + c * in_hw;
float* out_ptr = output + c;
float32x4_t p00 = vld1q_f32(line0);
float32x4_t res = p00;
for (int j = 0; j < block; j++)
{
float32x4_t p00 = vld1q_f32(line0);
float32x4_t p01 = vld1q_f32(line0 + 4);
float32x4_t max0 = vmaxq_f32(p00, p01);
res = vmaxq_f32(res, max0);
line0 += 8;
}
float max_ = fmax(fmax(res[0], res[1]), fmax(res[2], res[3]));
for (int j = tail; j < in_hw; j++)
{
max_ = fmax(max_, line0[0]);
line0++;
}
*out_ptr = max_;
}
}
int pooling_kernel_perf_prerun(struct tensor* input, struct tensor* out, struct pool_param* param)
{
int pool_size = POOL_GENERIC;
/* global pooling */
if (param->global)
{
if (param->pool_method == POOL_AVG)
param->funct = (pooling_kernel_t)avg_global;
else if (param->pool_method == POOL_MAX)
param->funct = (pooling_kernel_t)max_global;
assert(param->funct != NULL);
return 0;
}
/* general pooling */
if (param->stride_h == 2 && param->stride_w == 2)
{
if (param->kernel_h == 2 && param->kernel_w == 2)
pool_size = POOL_K2S2;
else if (param->kernel_h == 3 && param->kernel_w == 3)
pool_size = POOL_K3S2;
}
else if (param->stride_h == 1 && param->stride_w == 1)
{
if (param->kernel_h == 3 && param->kernel_w == 3)
pool_size = POOL_K3S1;
}
/* general max pooling, k2s2, k2k2p1, k3s1p1, k3s2, k3s2p1 */
if (param->pool_method == POOL_MAX)
{
if ((param->pad_h0 == param->pad_w0) && (param->pad_h1 == param->pad_w1))
{
if (param->pad_h0 == 0)
{
if (pool_size == POOL_K2S2)
param->funct = (pooling_kernel_t)max_2x2s2;
else if (pool_size == POOL_K3S2)
param->funct = (pooling_kernel_t)max_3x3s2;
}
else if (param->pad_h0 == 1)
{
if (pool_size == POOL_K2S2)
param->funct = (pooling_kernel_t)max_2x2s2_p1;
else if (pool_size == POOL_K3S2)
param->funct = (pooling_kernel_t)max_3x3s2_p1;
else if (pool_size == POOL_K3S1)
param->funct = (pooling_kernel_t)max_3x3s1_p1;
}
}
if (param->funct != NULL)
return 0;
else
{
TLOG_ERR("perf general max pooling func not be find\n");
return -1;
}
}
/* general avg pooling, k2s2, k2s2p1, k3s2, k3s2p1 */
if (param->pool_method == POOL_AVG)
{
if ((param->pad_h0 == param->pad_w0) && (param->pad_h1 == param->pad_w1))
{
if (param->pad_h0 == 0 && param->pad_h1 == 0)
{
if (pool_size == POOL_K2S2)
param->funct = (pooling_kernel_t)avg_2x2s2;
else if (pool_size == POOL_K3S2)
param->funct = (pooling_kernel_t)avg_3x3s2;
}
else if (param->pad_h0 == 1 && param->pad_h1 == 1)
{
if (pool_size == POOL_K2S2)
param->funct = (pooling_kernel_t)avg_2x2s2_p1;
else if (pool_size == POOL_K3S2)
param->funct = (pooling_kernel_t)avg_3x3s2_p1;
else if (pool_size == POOL_K3S1)
param->funct = (pooling_kernel_t)avg_3x3s1_p1;
}
else if (param->pad_h0 == 0 && param->pad_h1 == 1)
{
if (pool_size == POOL_K3S2)
param->funct = (pooling_kernel_t)avg_3x3s2;
}
}
if (param->funct != NULL)
return 0;
else
{
TLOG_ERR("perf general avg pooling func not be find\n");
return -1;
}
}
TLOG_ERR("perf pooling func not be find\n");
return -1;
}
int pooling_kernel_perf_run(struct tensor* input, struct tensor* output, struct pool_param* param, int num_thread)
{
// TLOG_ERR("perf pooling_kernel_run\n");
int is_caffe = param->caffe_flavor;
pooling_kernel_t kernel = (pooling_kernel_t)(param->funct);
int batch = input->dims[0];
int c = input->dims[1];
int in_h = input->dims[2];
int in_w = input->dims[3];
int out_h = output->dims[2];
int out_w = output->dims[3];
int img_size = c * in_h * in_w;
int feature_size = c * out_h * out_w;
for (int n = 0; n < batch; n++)
{
void* input_frame = input->data + n * img_size * input->elem_size;
void* output_frame = output->data + n * feature_size * output->elem_size;
#pragma omp parallel for num_threads(num_thread)
for (int ch = 0; ch < c; ch++)
{
void* cur_input = input_frame + ch * in_h * in_w * input->elem_size;
void* cur_output = output_frame + ch * out_h * out_w * output->elem_size;
kernel(cur_input, cur_output, 1, in_h, in_w, out_h, out_w, param->kernel_h, param->kernel_w,
param->stride_h, param->stride_w, param->pad_h0, param->pad_w0, param->pad_h1, param->pad_w1,
is_caffe);
}
}
return 0;
}
|
threadprivate2.c
|
#include <stdio.h>
#ifdef _OPENMP
#include <omp.h>
#endif
int counter=0;
#ifdef _OPENMP
#pragma omp threadprivate(counter)
#endif
int main(void)
{
int i;
#pragma omp parallel for
for(i=0;i<10000;i++)
counter++;
#pragma omp parallel for
for(i=0;i<10000;i++)
counter+=3;
#pragma omp parallel
printf("counter=%d\n",counter);
}
|
psd.c
|
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP SSSSS DDDD %
% P P SS D D %
% PPPP SSS D D %
% P SS D D %
% P SSSSS DDDD %
% %
% %
% Read/Write Adobe Photoshop Image Format %
% %
% Software Design %
% Cristy %
% Leonard Rosenthol %
% July 1992 %
% Dirk Lemstra %
% December 2013 %
% %
% %
% 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://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 "MagickCore/studio.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/channel.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colormap-private.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/module.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/policy.h"
#include "MagickCore/profile.h"
#include "MagickCore/property.h"
#include "MagickCore/registry.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#ifdef MAGICKCORE_ZLIB_DELEGATE
#include <zlib.h>
#endif
#include "psd-private.h"
/*
Define declaractions.
*/
#define MaxPSDChannels 56
#define PSDQuantum(x) (((ssize_t) (x)+1) & -2)
/*
Enumerated declaractions.
*/
typedef enum
{
Raw = 0,
RLE = 1,
ZipWithoutPrediction = 2,
ZipWithPrediction = 3
} PSDCompressionType;
typedef enum
{
BitmapMode = 0,
GrayscaleMode = 1,
IndexedMode = 2,
RGBMode = 3,
CMYKMode = 4,
MultichannelMode = 7,
DuotoneMode = 8,
LabMode = 9
} PSDImageType;
/*
Typedef declaractions.
*/
typedef struct _ChannelInfo
{
short
type;
size_t
size;
} ChannelInfo;
typedef struct _MaskInfo
{
Image
*image;
RectangleInfo
page;
unsigned char
background,
flags;
} MaskInfo;
typedef struct _LayerInfo
{
ChannelInfo
channel_info[MaxPSDChannels];
char
blendkey[4];
Image
*image;
MaskInfo
mask;
Quantum
opacity;
RectangleInfo
page;
size_t
offset_x,
offset_y;
unsigned char
clipping,
flags,
name[256],
visible;
unsigned short
channels;
StringInfo
*info;
} LayerInfo;
/*
Forward declarations.
*/
static MagickBooleanType
WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s P S D %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsPSD()() returns MagickTrue if the image format type, identified by the
% magick string, is PSD.
%
% The format of the IsPSD method is:
%
% MagickBooleanType IsPSD(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsPSD(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (LocaleNCompare((const char *) magick,"8BPS",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPSDImage() reads an Adobe Photoshop image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadPSDImage method is:
%
% Image *ReadPSDImage(image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static const char *CompositeOperatorToPSDBlendMode(Image *image)
{
switch (image->compose)
{
case ColorBurnCompositeOp:
return(image->endian == LSBEndian ? "vidi" : "idiv");
case ColorDodgeCompositeOp:
return(image->endian == LSBEndian ? " vid" : "div ");
case ColorizeCompositeOp:
return(image->endian == LSBEndian ? "rloc" : "colr");
case DarkenCompositeOp:
return(image->endian == LSBEndian ? "krad" : "dark");
case DifferenceCompositeOp:
return(image->endian == LSBEndian ? "ffid" : "diff");
case DissolveCompositeOp:
return(image->endian == LSBEndian ? "ssid" : "diss");
case ExclusionCompositeOp:
return(image->endian == LSBEndian ? "dums" : "smud");
case HardLightCompositeOp:
return(image->endian == LSBEndian ? "tiLh" : "hLit");
case HardMixCompositeOp:
return(image->endian == LSBEndian ? "xiMh" : "hMix");
case HueCompositeOp:
return(image->endian == LSBEndian ? " euh" : "hue ");
case LightenCompositeOp:
return(image->endian == LSBEndian ? "etil" : "lite");
case LinearBurnCompositeOp:
return(image->endian == LSBEndian ? "nrbl" : "lbrn");
case LinearDodgeCompositeOp:
return(image->endian == LSBEndian ? "gddl" : "lddg");
case LinearLightCompositeOp:
return(image->endian == LSBEndian ? "tiLl" : "lLit");
case LuminizeCompositeOp:
return(image->endian == LSBEndian ? " mul" : "lum ");
case MultiplyCompositeOp:
return(image->endian == LSBEndian ? " lum" : "mul ");
case OverlayCompositeOp:
return(image->endian == LSBEndian ? "revo" : "over");
case PinLightCompositeOp:
return(image->endian == LSBEndian ? "tiLp" : "pLit");
case SaturateCompositeOp:
return(image->endian == LSBEndian ? " tas" : "sat ");
case ScreenCompositeOp:
return(image->endian == LSBEndian ? "nrcs" : "scrn");
case SoftLightCompositeOp:
return(image->endian == LSBEndian ? "tiLs" : "sLit");
case VividLightCompositeOp:
return(image->endian == LSBEndian ? "tiLv" : "vLit");
case OverCompositeOp:
default:
return(image->endian == LSBEndian ? "mron" : "norm");
}
}
/*
For some reason Photoshop seems to blend semi-transparent pixels with white.
This method reverts the blending. This can be disabled by setting the
option 'psd:alpha-unblend' to off.
*/
static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info,
Image *image,ExceptionInfo* exception)
{
const char
*option;
MagickBooleanType
status;
ssize_t
y;
if (image->alpha_trait != BlendPixelTrait || image->colorspace != sRGBColorspace)
return(MagickTrue);
option=GetImageOption(image_info,"psd:alpha-unblend");
if (IsStringFalse(option) != MagickFalse)
return(MagickTrue);
status=MagickTrue;
#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 Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma;
register ssize_t
i;
gamma=QuantumScale*GetPixelAlpha(image, q);
if (gamma != 0.0 && gamma != 1.0)
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
if (channel != AlphaPixelChannel)
q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma);
}
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
status=MagickFalse;
}
return(status);
}
static inline CompressionType ConvertPSDCompression(
PSDCompressionType compression)
{
switch (compression)
{
case RLE:
return RLECompression;
case ZipWithPrediction:
case ZipWithoutPrediction:
return ZipCompression;
default:
return NoCompression;
}
}
static MagickBooleanType ApplyPSDLayerOpacity(Image *image,Quantum opacity,
MagickBooleanType revert,ExceptionInfo *exception)
{
MagickBooleanType
status;
ssize_t
y;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" applying layer opacity %.20g", (double) opacity);
if (opacity == OpaqueAlpha)
return(MagickTrue);
if (image->alpha_trait != BlendPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
status=MagickTrue;
#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 Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (revert == MagickFalse)
SetPixelAlpha(image,(Quantum) (QuantumScale*(GetPixelAlpha(image,q))*
opacity),q);
else if (opacity > 0)
SetPixelAlpha(image,(Quantum) (QuantumRange*(GetPixelAlpha(image,q)/
(MagickRealType) opacity)),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
status=MagickFalse;
}
return(status);
}
static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask,
Quantum background,MagickBooleanType revert,ExceptionInfo *exception)
{
Image
*complete_mask;
MagickBooleanType
status;
PixelInfo
color;
ssize_t
y;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" applying opacity mask");
complete_mask=CloneImage(image,image->columns,image->rows,MagickTrue,
exception);
if (complete_mask == (Image *) NULL)
return(MagickFalse);
complete_mask->alpha_trait=BlendPixelTrait;
GetPixelInfo(complete_mask,&color);
color.red=background;
SetImageColor(complete_mask,&color,exception);
status=CompositeImage(complete_mask,mask,OverCompositeOp,MagickTrue,
mask->page.x-image->page.x,mask->page.y-image->page.y,exception);
if (status == MagickFalse)
{
complete_mask=DestroyImage(complete_mask);
return(status);
}
image->alpha_trait=BlendPixelTrait;
#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 Quantum
*magick_restrict q;
register Quantum
*p;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception);
if ((q == (Quantum *) NULL) || (p == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickRealType
alpha,
intensity;
alpha=GetPixelAlpha(image,q);
intensity=GetPixelIntensity(complete_mask,p);
if (revert == MagickFalse)
SetPixelAlpha(image,ClampToQuantum(intensity*(QuantumScale*alpha)),q);
else if (intensity > 0)
SetPixelAlpha(image,ClampToQuantum((alpha/intensity)*QuantumRange),q);
q+=GetPixelChannels(image);
p+=GetPixelChannels(complete_mask);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
status=MagickFalse;
}
complete_mask=DestroyImage(complete_mask);
return(status);
}
static void PreservePSDOpacityMask(Image *image,LayerInfo* layer_info,
ExceptionInfo *exception)
{
char
*key;
RandomInfo
*random_info;
StringInfo
*key_info;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" preserving opacity mask");
random_info=AcquireRandomInfo();
key_info=GetRandomKey(random_info,2+1);
key=(char *) GetStringInfoDatum(key_info);
key[8]=layer_info->mask.background;
key[9]='\0';
layer_info->mask.image->page.x+=layer_info->page.x;
layer_info->mask.image->page.y+=layer_info->page.y;
(void) SetImageRegistry(ImageRegistryType,(const char *) key,
layer_info->mask.image,exception);
(void) SetImageArtifact(layer_info->image,"psd:opacity-mask",
(const char *) key);
key_info=DestroyStringInfo(key_info);
random_info=DestroyRandomInfo(random_info);
}
static ssize_t DecodePSDPixels(const size_t number_compact_pixels,
const unsigned char *compact_pixels,const ssize_t depth,
const size_t number_pixels,unsigned char *pixels)
{
#define CheckNumberCompactPixels \
if (packets == 0) \
return(i); \
packets--
#define CheckNumberPixels(count) \
if (((ssize_t) i + count) > (ssize_t) number_pixels) \
return(i); \
i+=count
int
pixel;
register ssize_t
i,
j;
size_t
length;
ssize_t
packets;
packets=(ssize_t) number_compact_pixels;
for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); )
{
packets--;
length=(size_t) (*compact_pixels++);
if (length == 128)
continue;
if (length > 128)
{
length=256-length+1;
CheckNumberCompactPixels;
pixel=(*compact_pixels++);
for (j=0; j < (ssize_t) length; j++)
{
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(pixel >> 7) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 6) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 5) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 4) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 3) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 2) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 1) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(unsigned char) ((pixel >> 6) & 0x03);
*pixels++=(unsigned char) ((pixel >> 4) & 0x03);
*pixels++=(unsigned char) ((pixel >> 2) & 0x03);
*pixels++=(unsigned char) ((pixel & 0x03) & 0x03);
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(unsigned char) ((pixel >> 4) & 0xff);
*pixels++=(unsigned char) ((pixel & 0x0f) & 0xff);
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(unsigned char) pixel;
break;
}
}
}
continue;
}
length++;
for (j=0; j < (ssize_t) length; j++)
{
CheckNumberCompactPixels;
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(*compact_pixels >> 6) & 0x03;
*pixels++=(*compact_pixels >> 4) & 0x03;
*pixels++=(*compact_pixels >> 2) & 0x03;
*pixels++=(*compact_pixels & 0x03) & 0x03;
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(*compact_pixels >> 4) & 0xff;
*pixels++=(*compact_pixels & 0x0f) & 0xff;
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(*compact_pixels);
break;
}
}
compact_pixels++;
}
}
return(i);
}
static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info,
const ssize_t number_layers)
{
ssize_t
i;
for (i=0; i<number_layers; i++)
{
if (layer_info[i].image != (Image *) NULL)
layer_info[i].image=DestroyImage(layer_info[i].image);
if (layer_info[i].mask.image != (Image *) NULL)
layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image);
if (layer_info[i].info != (StringInfo *) NULL)
layer_info[i].info=DestroyStringInfo(layer_info[i].info);
}
return (LayerInfo *) RelinquishMagickMemory(layer_info);
}
static inline size_t GetPSDPacketSize(const Image *image)
{
if (image->storage_class == PseudoClass)
{
if (image->colors > 256)
return(2);
}
if (image->depth > 16)
return(4);
if (image->depth > 8)
return(2);
return(1);
}
static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image)
{
if (psd_info->version == 1)
return((MagickSizeType) ReadBlobLong(image));
return((MagickSizeType) ReadBlobLongLong(image));
}
static inline size_t GetPSDRowSize(Image *image)
{
if (image->depth == 1)
return(((image->columns+7)/8)*GetPSDPacketSize(image));
else
return(image->columns*GetPSDPacketSize(image));
}
static const char *ModeToString(PSDImageType type)
{
switch (type)
{
case BitmapMode: return "Bitmap";
case GrayscaleMode: return "Grayscale";
case IndexedMode: return "Indexed";
case RGBMode: return "RGB";
case CMYKMode: return "CMYK";
case MultichannelMode: return "Multichannel";
case DuotoneMode: return "Duotone";
case LabMode: return "L*A*B";
default: return "unknown";
}
}
static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception)
{
ChannelType
channel_mask;
MagickBooleanType
status;
channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~
AlphaChannel));
status=NegateImage(image,MagickFalse,exception);
(void) SetImageChannelMask(image,channel_mask);
return(status);
}
static StringInfo *ParseImageResourceBlocks(Image *image,
const unsigned char *blocks,size_t length,
MagickBooleanType *has_merged_image,ExceptionInfo *exception)
{
const unsigned char
*p;
StringInfo
*profile;
unsigned char
name_length;
unsigned int
count;
unsigned short
id,
short_sans;
if (length < 16)
return((StringInfo *) NULL);
profile=BlobToStringInfo((const unsigned char *) NULL,length);
SetStringInfoDatum(profile,blocks);
SetStringInfoName(profile,"8bim");
for (p=blocks; (p >= blocks) && (p < (blocks+length-7)); )
{
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
break;
p+=4;
p=PushShortPixel(MSBEndian,p,&id);
p=PushCharPixel(p,&name_length);
if ((name_length % 2) == 0)
name_length++;
p+=name_length;
if (p > (blocks+length-4))
break;
p=PushLongPixel(MSBEndian,p,&count);
if ((p+count) > (blocks+length))
break;
switch (id)
{
case 0x03ed:
{
char
value[MagickPathExtent];
unsigned short
resolution;
/*
Resolution info.
*/
if (count < 16)
break;
p=PushShortPixel(MSBEndian,p,&resolution);
image->resolution.x=(double) resolution;
(void) FormatLocaleString(value,MagickPathExtent,"%g",
image->resolution.x);
(void) SetImageProperty(image,"tiff:XResolution",value,exception);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&resolution);
image->resolution.y=(double) resolution;
(void) FormatLocaleString(value,MagickPathExtent,"%g",
image->resolution.y);
(void) SetImageProperty(image,"tiff:YResolution",value,exception);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
image->units=PixelsPerInchResolution;
break;
}
case 0x0421:
{
if ((count > 3) && (*(p+4) == 0))
*has_merged_image=MagickFalse;
p+=count;
break;
}
default:
{
p+=count;
break;
}
}
if ((count & 0x01) != 0)
p++;
}
return(profile);
}
static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode)
{
if (mode == (const char *) NULL)
return(OverCompositeOp);
if (LocaleNCompare(mode,"norm",4) == 0)
return(OverCompositeOp);
if (LocaleNCompare(mode,"mul ",4) == 0)
return(MultiplyCompositeOp);
if (LocaleNCompare(mode,"diss",4) == 0)
return(DissolveCompositeOp);
if (LocaleNCompare(mode,"diff",4) == 0)
return(DifferenceCompositeOp);
if (LocaleNCompare(mode,"dark",4) == 0)
return(DarkenCompositeOp);
if (LocaleNCompare(mode,"lite",4) == 0)
return(LightenCompositeOp);
if (LocaleNCompare(mode,"hue ",4) == 0)
return(HueCompositeOp);
if (LocaleNCompare(mode,"sat ",4) == 0)
return(SaturateCompositeOp);
if (LocaleNCompare(mode,"colr",4) == 0)
return(ColorizeCompositeOp);
if (LocaleNCompare(mode,"lum ",4) == 0)
return(LuminizeCompositeOp);
if (LocaleNCompare(mode,"scrn",4) == 0)
return(ScreenCompositeOp);
if (LocaleNCompare(mode,"over",4) == 0)
return(OverlayCompositeOp);
if (LocaleNCompare(mode,"hLit",4) == 0)
return(HardLightCompositeOp);
if (LocaleNCompare(mode,"sLit",4) == 0)
return(SoftLightCompositeOp);
if (LocaleNCompare(mode,"smud",4) == 0)
return(ExclusionCompositeOp);
if (LocaleNCompare(mode,"div ",4) == 0)
return(ColorDodgeCompositeOp);
if (LocaleNCompare(mode,"idiv",4) == 0)
return(ColorBurnCompositeOp);
if (LocaleNCompare(mode,"lbrn",4) == 0)
return(LinearBurnCompositeOp);
if (LocaleNCompare(mode,"lddg",4) == 0)
return(LinearDodgeCompositeOp);
if (LocaleNCompare(mode,"lLit",4) == 0)
return(LinearLightCompositeOp);
if (LocaleNCompare(mode,"vLit",4) == 0)
return(VividLightCompositeOp);
if (LocaleNCompare(mode,"pLit",4) == 0)
return(PinLightCompositeOp);
if (LocaleNCompare(mode,"hMix",4) == 0)
return(HardMixCompositeOp);
return(OverCompositeOp);
}
static inline void ReversePSDString(Image *image,char *p,size_t length)
{
char
*q;
if (image->endian == MSBEndian)
return;
q=p+length;
for(--q; p < q; ++p, --q)
{
*p = *p ^ *q,
*q = *p ^ *q,
*p = *p ^ *q;
}
}
static inline void SetPSDPixel(Image *image,const size_t channels,
const ssize_t type,const size_t packet_size,const Quantum pixel,Quantum *q,
ExceptionInfo *exception)
{
if (image->storage_class == PseudoClass)
{
PixelInfo
*color;
if (type == 0)
{
if (packet_size == 1)
SetPixelIndex(image,ScaleQuantumToChar(pixel),q);
else
SetPixelIndex(image,ScaleQuantumToShort(pixel),q);
}
color=image->colormap+(ssize_t) ConstrainColormapIndex(image,
GetPixelIndex(image,q),exception);
if ((type == 0) && (channels > 1))
return;
else
color->alpha=(MagickRealType) pixel;
SetPixelViaPixelInfo(image,color,q);
return;
}
switch (type)
{
case -1:
{
SetPixelAlpha(image,pixel,q);
break;
}
case -2:
case 0:
{
SetPixelRed(image,pixel,q);
break;
}
case -3:
case 1:
{
SetPixelGreen(image,pixel,q);
break;
}
case -4:
case 2:
{
SetPixelBlue(image,pixel,q);
break;
}
case 3:
{
if (image->colorspace == CMYKColorspace)
SetPixelBlack(image,pixel,q);
else
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,pixel,q);
break;
}
case 4:
{
if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) &&
(channels > 3))
break;
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,pixel,q);
break;
}
}
}
static MagickBooleanType ReadPSDChannelPixels(Image *image,
const size_t channels,const size_t row,const ssize_t type,
const unsigned char *pixels,ExceptionInfo *exception)
{
Quantum
pixel;
register const unsigned char
*p;
register Quantum
*q;
register ssize_t
x;
size_t
packet_size;
p=pixels;
q=GetAuthenticPixels(image,0,row,image->columns,1,exception);
if (q == (Quantum *) NULL)
return MagickFalse;
packet_size=GetPSDPacketSize(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (packet_size == 1)
pixel=ScaleCharToQuantum(*p++);
else if (packet_size == 2)
{
unsigned short
nibble;
p=PushShortPixel(MSBEndian,p,&nibble);
pixel=ScaleShortToQuantum(nibble);
}
else
{
MagickFloatType
nibble;
p=PushFloatPixel(MSBEndian,p,&nibble);
pixel=ClampToQuantum((MagickRealType)QuantumRange*nibble);
}
if (image->depth > 1)
{
SetPSDPixel(image,channels,type,packet_size,pixel,q,exception);
q+=GetPixelChannels(image);
}
else
{
ssize_t
bit,
number_bits;
number_bits=image->columns-x;
if (number_bits > 8)
number_bits=8;
for (bit = 0; bit < number_bits; bit++)
{
SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel)
& (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q,exception);
q+=GetPixelChannels(image);
x++;
}
if (x != (ssize_t) image->columns)
x--;
continue;
}
}
return(SyncAuthenticPixels(image,exception));
}
static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels,
const ssize_t type,ExceptionInfo *exception)
{
MagickBooleanType
status;
size_t
count,
row_size;
ssize_t
y;
unsigned char
*pixels;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is RAW");
row_size=GetPSDRowSize(image);
pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=MagickTrue;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=MagickFalse;
count=ReadBlob(image,row_size,pixels);
if (count != row_size)
{
status=MagickFalse;
break;
}
status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
static inline MagickOffsetType *ReadPSDRLESizes(Image *image,
const PSDInfo *psd_info,const size_t size)
{
MagickOffsetType
*sizes;
ssize_t
y;
sizes=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*sizes));
if(sizes != (MagickOffsetType *) NULL)
{
for (y=0; y < (ssize_t) size; y++)
{
if (psd_info->version == 1)
sizes[y]=(MagickOffsetType) ReadBlobShort(image);
else
sizes[y]=(MagickOffsetType) ReadBlobLong(image);
}
}
return sizes;
}
static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info,
const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception)
{
MagickBooleanType
status;
size_t
length,
row_size;
ssize_t
count,
y;
unsigned char
*compact_pixels,
*pixels;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is RLE compressed");
row_size=GetPSDRowSize(image);
pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
length=0;
for (y=0; y < (ssize_t) image->rows; y++)
if ((MagickOffsetType) length < sizes[y])
length=(size_t) sizes[y];
if (length > (row_size+512)) // arbitrary number
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowBinaryException(ResourceLimitError,"InvalidLength",image->filename);
}
compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels));
if (compact_pixels == (unsigned char *) NULL)
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) memset(compact_pixels,0,length*sizeof(*compact_pixels));
status=MagickTrue;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=MagickFalse;
count=ReadBlob(image,(size_t) sizes[y],compact_pixels);
if (count != (ssize_t) sizes[y])
break;
count=DecodePSDPixels((size_t) sizes[y],compact_pixels,
(ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels);
if (count != (ssize_t) row_size)
break;
status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels,
exception);
if (status == MagickFalse)
break;
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels,
const ssize_t type,const PSDCompressionType compression,
const size_t compact_size,ExceptionInfo *exception)
{
MagickBooleanType
status;
register unsigned char
*p;
size_t
count,
length,
packet_size,
row_size;
ssize_t
y;
unsigned char
*compact_pixels,
*pixels;
z_stream
stream;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is ZIP compressed");
compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size,
sizeof(*compact_pixels));
if (compact_pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
packet_size=GetPSDPacketSize(image);
row_size=image->columns*packet_size;
count=image->rows*row_size;
pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
{
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
if (ReadBlob(image,compact_size,compact_pixels) != (ssize_t) compact_size)
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile",
image->filename);
}
memset(&stream,0,sizeof(stream));
stream.data_type=Z_BINARY;
stream.next_in=(Bytef *)compact_pixels;
stream.avail_in=(uInt) compact_size;
stream.next_out=(Bytef *)pixels;
stream.avail_out=(uInt) count;
if (inflateInit(&stream) == Z_OK)
{
int
ret;
while (stream.avail_out > 0)
{
ret=inflate(&stream,Z_SYNC_FLUSH);
if ((ret != Z_OK) && (ret != Z_STREAM_END))
{
(void) inflateEnd(&stream);
compact_pixels=(unsigned char *) RelinquishMagickMemory(
compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(MagickFalse);
}
if (ret == Z_STREAM_END)
break;
}
(void) inflateEnd(&stream);
}
if (compression == ZipWithPrediction)
{
p=pixels;
while (count > 0)
{
length=image->columns;
while (--length)
{
if (packet_size == 2)
{
p[2]+=p[0]+((p[1]+p[3]) >> 8);
p[3]+=p[1];
}
// else if (packet_size == 4)
// {
// TODO: Figure out what to do there.
// }
else
*(p+1)+=*p;
p+=packet_size;
}
p+=packet_size;
count-=row_size;
}
}
status=MagickTrue;
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=ReadPSDChannelPixels(image,channels,y,type,p,exception);
if (status == MagickFalse)
break;
p+=row_size;
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
#endif
static MagickBooleanType ReadPSDChannel(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info,
const size_t channel,const PSDCompressionType compression,
ExceptionInfo *exception)
{
Image
*channel_image,
*mask;
MagickOffsetType
offset;
MagickBooleanType
status;
channel_image=image;
mask=(Image *) NULL;
if ((layer_info->channel_info[channel].type < -1) &&
(layer_info->mask.page.width > 0) && (layer_info->mask.page.height > 0))
{
const char
*option;
/*
Ignore mask that is not a user supplied layer mask, if the mask is
disabled or if the flags have unsupported values.
*/
option=GetImageOption(image_info,"psd:preserve-opacity-mask");
if ((layer_info->channel_info[channel].type != -2) ||
(layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) &&
(IsStringTrue(option) == MagickFalse)))
{
SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR);
return(MagickTrue);
}
mask=CloneImage(image,layer_info->mask.page.width,
layer_info->mask.page.height,MagickFalse,exception);
if (mask != (Image *) NULL)
{
SetImageType(mask,GrayscaleType,exception);
channel_image=mask;
}
}
offset=TellBlob(image);
status=MagickFalse;
switch(compression)
{
case Raw:
status=ReadPSDChannelRaw(channel_image,psd_info->channels,
layer_info->channel_info[channel].type,exception);
break;
case RLE:
{
MagickOffsetType
*sizes;
sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows);
if (sizes == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ReadPSDChannelRLE(channel_image,psd_info,
layer_info->channel_info[channel].type,sizes,exception);
sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);
}
break;
case ZipWithPrediction:
case ZipWithoutPrediction:
#ifdef MAGICKCORE_ZLIB_DELEGATE
status=ReadPSDChannelZip(channel_image,layer_info->channels,
layer_info->channel_info[channel].type,compression,
layer_info->channel_info[channel].size-2,exception);
#else
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn",
"'%s' (ZLIB)",image->filename);
#endif
break;
default:
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"CompressionNotSupported","'%.20g'",(double) compression);
break;
}
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
if (status == MagickFalse)
{
if (mask != (Image *) NULL)
DestroyImage(mask);
ThrowBinaryException(CoderError,"UnableToDecompressImage",
image->filename);
}
if (mask != (Image *) NULL)
{
if (layer_info->mask.image != (Image *) NULL)
layer_info->mask.image=DestroyImage(layer_info->mask.image);
layer_info->mask.image=mask;
}
return(status);
}
static MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info,
const PSDInfo *psd_info,LayerInfo* layer_info,ExceptionInfo *exception)
{
char
message[MagickPathExtent];
MagickBooleanType
status;
PSDCompressionType
compression;
ssize_t
j;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" setting up new layer image");
if (psd_info->mode != IndexedMode)
(void) SetImageBackgroundColor(layer_info->image,exception);
layer_info->image->compose=PSDBlendModeToCompositeOperator(
layer_info->blendkey);
if (layer_info->visible == MagickFalse)
layer_info->image->compose=NoCompositeOp;
/*
Set up some hidden attributes for folks that need them.
*/
(void) FormatLocaleString(message,MagickPathExtent,"%.20g",
(double) layer_info->page.x);
(void) SetImageArtifact(layer_info->image,"psd:layer.x",message);
(void) FormatLocaleString(message,MagickPathExtent,"%.20g",
(double) layer_info->page.y);
(void) SetImageArtifact(layer_info->image,"psd:layer.y",message);
(void) FormatLocaleString(message,MagickPathExtent,"%.20g",(double)
layer_info->opacity);
(void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message);
(void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name,
exception);
status=MagickTrue;
for (j=0; j < (ssize_t) layer_info->channels; j++)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading data for channel %.20g",(double) j);
compression=(PSDCompressionType) ReadBlobShort(layer_info->image);
/* TODO: Remove this when we figure out how to support this */
if ((compression == ZipWithPrediction) && (image->depth == 32))
{
(void) ThrowMagickException(exception,GetMagickModule(),
TypeError,"CompressionNotSupported","ZipWithPrediction(32 bit)");
return(MagickFalse);
}
layer_info->image->compression=ConvertPSDCompression(compression);
if (layer_info->channel_info[j].type == -1)
layer_info->image->alpha_trait=BlendPixelTrait;
status=ReadPSDChannel(layer_info->image,image_info,psd_info,layer_info,j,
compression,exception);
if (status == MagickFalse)
break;
}
if (status != MagickFalse)
status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity,
MagickFalse,exception);
if ((status != MagickFalse) &&
(layer_info->image->colorspace == CMYKColorspace))
status=NegateCMYK(layer_info->image,exception);
if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL))
{
const char
*option;
layer_info->mask.image->page.x=layer_info->mask.page.x;
layer_info->mask.image->page.y=layer_info->mask.page.y;
/* Do not composite the mask when it is disabled */
if ((layer_info->mask.flags & 0x02) == 0x02)
layer_info->mask.image->compose=NoCompositeOp;
else
status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image,
layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse,
exception);
option=GetImageOption(image_info,"psd:preserve-opacity-mask");
if (IsStringTrue(option) != MagickFalse)
PreservePSDOpacityMask(image,layer_info,exception);
layer_info->mask.image=DestroyImage(layer_info->mask.image);
}
return(status);
}
static MagickBooleanType CheckPSDChannels(const PSDInfo *psd_info,
LayerInfo *layer_info)
{
int
channel_type;
register ssize_t
i;
if (layer_info->channels < psd_info->min_channels)
return(MagickFalse);
channel_type=RedChannel;
if (psd_info->min_channels >= 3)
channel_type|=(GreenChannel | BlueChannel);
if (psd_info->min_channels >= 4)
channel_type|=BlackChannel;
for (i=0; i < layer_info->channels; i++)
{
short
type;
type=layer_info->channel_info[i].type;
if (type == -1)
{
channel_type|=AlphaChannel;
continue;
}
if (type < -1)
continue;
if (type == 0)
channel_type&=~RedChannel;
else if (type == 1)
channel_type&=~GreenChannel;
else if (type == 2)
channel_type&=~BlueChannel;
else if (type == 3)
channel_type&=~BlackChannel;
}
if (channel_type == 0)
return(MagickTrue);
if ((channel_type == AlphaChannel) &&
(layer_info->channels >= psd_info->min_channels + 1))
return(MagickTrue);
return(MagickFalse);
}
static MagickBooleanType ReadPSDLayersInternal(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,
const MagickBooleanType skip_layers,ExceptionInfo *exception)
{
char
type[4];
LayerInfo
*layer_info;
MagickSizeType
size;
MagickBooleanType
status;
register ssize_t
i;
ssize_t
count,
j,
number_layers;
size=GetPSDSize(psd_info,image);
if (size == 0)
{
/*
Skip layers & masks.
*/
(void) ReadBlobLong(image);
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
status=MagickFalse;
if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0))
return(MagickTrue);
else
{
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
if ((count != 0) && ((LocaleNCompare(type,"Lr16",4) == 0) ||
(LocaleNCompare(type,"Lr32",4) == 0)))
size=GetPSDSize(psd_info,image);
else
return(MagickTrue);
}
}
status=MagickTrue;
if (size != 0)
{
layer_info=(LayerInfo *) NULL;
number_layers=(short) ReadBlobShort(image);
if (number_layers < 0)
{
/*
The first alpha channel in the merged result contains the
transparency data for the merged result.
*/
number_layers=MagickAbsoluteValue(number_layers);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" negative layer count corrected for");
image->alpha_trait=BlendPixelTrait;
}
/*
We only need to know if the image has an alpha channel
*/
if (skip_layers != MagickFalse)
return(MagickTrue);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image contains %.20g layers",(double) number_layers);
if (number_layers == 0)
ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers",
image->filename);
layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers,
sizeof(*layer_info));
if (layer_info == (LayerInfo *) NULL)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" allocation of LayerInfo failed");
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) memset(layer_info,0,(size_t) number_layers*
sizeof(*layer_info));
for (i=0; i < number_layers; i++)
{
ssize_t
x,
y;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading layer #%.20g",(double) i+1);
layer_info[i].page.y=ReadBlobSignedLong(image);
layer_info[i].page.x=ReadBlobSignedLong(image);
y=ReadBlobSignedLong(image);
x=ReadBlobSignedLong(image);
layer_info[i].page.width=(size_t) (x-layer_info[i].page.x);
layer_info[i].page.height=(size_t) (y-layer_info[i].page.y);
layer_info[i].channels=ReadBlobShort(image);
if (layer_info[i].channels > MaxPSDChannels)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded",
image->filename);
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g",
(double) layer_info[i].page.x,(double) layer_info[i].page.y,
(double) layer_info[i].page.height,(double)
layer_info[i].page.width,(double) layer_info[i].channels);
for (j=0; j < (ssize_t) layer_info[i].channels; j++)
{
layer_info[i].channel_info[j].type=(short) ReadBlobShort(image);
if ((layer_info[i].channel_info[j].type < -4) ||
(layer_info[i].channel_info[j].type > 4))
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"NoSuchImageChannel",
image->filename);
}
layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info,
image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" channel[%.20g]: type=%.20g, size=%.20g",(double) j,
(double) layer_info[i].channel_info[j].type,
(double) layer_info[i].channel_info[j].size);
}
if (CheckPSDChannels(psd_info,&layer_info[i]) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"ImproperImageHeader",
image->filename);
}
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer type was %.4s instead of 8BIM", type);
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"ImproperImageHeader",
image->filename);
}
count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey);
ReversePSDString(image,layer_info[i].blendkey,4);
layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
layer_info[i].clipping=(unsigned char) ReadBlobByte(image);
layer_info[i].flags=(unsigned char) ReadBlobByte(image);
layer_info[i].visible=!(layer_info[i].flags & 0x02);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s",
layer_info[i].blendkey,(double) layer_info[i].opacity,
layer_info[i].clipping ? "true" : "false",layer_info[i].flags,
layer_info[i].visible ? "true" : "false");
(void) ReadBlobByte(image); /* filler */
size=ReadBlobLong(image);
if (size != 0)
{
MagickSizeType
combined_length,
length;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer contains additional info");
length=ReadBlobLong(image);
combined_length=length+4;
if (length != 0)
{
/*
Layer mask info.
*/
layer_info[i].mask.page.y=ReadBlobSignedLong(image);
layer_info[i].mask.page.x=ReadBlobSignedLong(image);
layer_info[i].mask.page.height=(size_t) (ReadBlobSignedLong(image)-
layer_info[i].mask.page.y);
layer_info[i].mask.page.width=(size_t) (ReadBlobSignedLong(image)-
layer_info[i].mask.page.x);
layer_info[i].mask.background=(unsigned char) ReadBlobByte(
image);
layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image);
if (!(layer_info[i].mask.flags & 0x01))
{
layer_info[i].mask.page.y=layer_info[i].mask.page.y-
layer_info[i].page.y;
layer_info[i].mask.page.x=layer_info[i].mask.page.x-
layer_info[i].page.x;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g",
(double) layer_info[i].mask.page.x,(double)
layer_info[i].mask.page.y,(double)
layer_info[i].mask.page.width,(double)
layer_info[i].mask.page.height,(double) ((MagickOffsetType)
length)-18);
/*
Skip over the rest of the layer mask information.
*/
if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
length=ReadBlobLong(image);
combined_length+=length+4;
if (length != 0)
{
/*
Layer blending ranges info.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer blending ranges: length=%.20g",(double)
((MagickOffsetType) length));
if (DiscardBlobBytes(image,length) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
/*
Layer name.
*/
length=(MagickSizeType) (unsigned char) ReadBlobByte(image);
combined_length+=length+1;
if (length > 0)
(void) ReadBlob(image,(size_t) length++,layer_info[i].name);
layer_info[i].name[length]='\0';
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer name: %s",layer_info[i].name);
if ((length % 4) != 0)
{
length=4-(length % 4);
combined_length+=length;
/* Skip over the padding of the layer name */
if (DiscardBlobBytes(image,length) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
length=(MagickSizeType) size-combined_length;
if (length > 0)
{
unsigned char
*info;
if (length > GetBlobSize(image))
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"InsufficientImageDataInFile",image->filename);
}
layer_info[i].info=AcquireStringInfo((const size_t) length);
info=GetStringInfoDatum(layer_info[i].info);
(void) ReadBlob(image,(const size_t) length,info);
}
}
}
for (i=0; i < number_layers; i++)
{
if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is empty");
if (layer_info[i].info != (StringInfo *) NULL)
layer_info[i].info=DestroyStringInfo(layer_info[i].info);
continue;
}
/*
Allocate layered image.
*/
layer_info[i].image=CloneImage(image,layer_info[i].page.width,
layer_info[i].page.height,MagickFalse,exception);
if (layer_info[i].image == (Image *) NULL)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" allocation of image for layer %.20g failed",(double) i);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
if (layer_info[i].info != (StringInfo *) NULL)
{
(void) SetImageProfile(layer_info[i].image,"psd:additional-info",
layer_info[i].info,exception);
layer_info[i].info=DestroyStringInfo(layer_info[i].info);
}
}
if (image_info->ping == MagickFalse)
{
for (i=0; i < number_layers; i++)
{
if (layer_info[i].image == (Image *) NULL)
{
for (j=0; j < layer_info[i].channels; j++)
{
if (DiscardBlobBytes(image,(MagickSizeType)
layer_info[i].channel_info[j].size) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
continue;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading data for layer %.20g",(double) i);
status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i],
exception);
if (status == MagickFalse)
break;
status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType)
number_layers);
if (status == MagickFalse)
break;
}
}
if (status != MagickFalse)
{
for (i=0; i < number_layers; i++)
{
if (layer_info[i].image == (Image *) NULL)
{
for (j=i; j < number_layers - 1; j++)
layer_info[j] = layer_info[j+1];
number_layers--;
i--;
}
}
if (number_layers > 0)
{
for (i=0; i < number_layers; i++)
{
if (i > 0)
layer_info[i].image->previous=layer_info[i-1].image;
if (i < (number_layers-1))
layer_info[i].image->next=layer_info[i+1].image;
layer_info[i].image->page=layer_info[i].page;
}
image->next=layer_info[0].image;
layer_info[0].image->previous=image;
}
layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info);
}
else
layer_info=DestroyLayerInfo(layer_info,number_layers);
}
return(status);
}
ModuleExport MagickBooleanType ReadPSDLayers(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,ExceptionInfo *exception)
{
PolicyDomain
domain;
PolicyRights
rights;
domain=CoderPolicyDomain;
rights=ReadPolicyRights;
if (IsRightsAuthorized(domain,rights,"PSD") == MagickFalse)
return(MagickTrue);
return(ReadPSDLayersInternal(image,image_info,psd_info,MagickFalse,
exception));
}
static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info,
Image *image,const PSDInfo *psd_info,ExceptionInfo *exception)
{
MagickOffsetType
*sizes;
MagickBooleanType
status;
PSDCompressionType
compression;
register ssize_t
i;
compression=(PSDCompressionType) ReadBlobMSBShort(image);
image->compression=ConvertPSDCompression(compression);
if (compression != Raw && compression != RLE)
{
(void) ThrowMagickException(exception,GetMagickModule(),
TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression);
return(MagickFalse);
}
sizes=(MagickOffsetType *) NULL;
if (compression == RLE)
{
sizes=ReadPSDRLESizes(image,psd_info,image->rows*psd_info->channels);
if (sizes == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
status=MagickTrue;
for (i=0; i < (ssize_t) psd_info->channels; i++)
{
ssize_t
type;
type=i;
if ((type == 1) && (psd_info->channels == 2))
type=-1;
if (compression == RLE)
status=ReadPSDChannelRLE(image,psd_info,type,sizes+(i*image->rows),
exception);
else
status=ReadPSDChannelRaw(image,psd_info->channels,type,exception);
if (status != MagickFalse)
status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels);
if (status == MagickFalse)
break;
}
if ((status != MagickFalse) && (image->colorspace == CMYKColorspace))
status=NegateCMYK(image,exception);
if (status != MagickFalse)
status=CorrectPSDAlphaBlend(image_info,image,exception);
sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);
return(status);
}
static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
has_merged_image,
skip_layers;
MagickOffsetType
offset;
MagickSizeType
length;
MagickBooleanType
status;
PSDInfo
psd_info;
register ssize_t
i;
ssize_t
count;
StringInfo
*profile;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read image header.
*/
image->endian=MSBEndian;
count=ReadBlob(image,4,(unsigned char *) psd_info.signature);
psd_info.version=ReadBlobMSBShort(image);
if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) ||
((psd_info.version != 1) && (psd_info.version != 2)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
(void) ReadBlob(image,6,psd_info.reserved);
psd_info.channels=ReadBlobMSBShort(image);
if (psd_info.channels < 1)
ThrowReaderException(CorruptImageError,"MissingImageChannel");
if (psd_info.channels > MaxPSDChannels)
ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded");
psd_info.rows=ReadBlobMSBLong(image);
psd_info.columns=ReadBlobMSBLong(image);
if ((psd_info.version == 1) && ((psd_info.rows > 30000) ||
(psd_info.columns > 30000)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
psd_info.depth=ReadBlobMSBShort(image);
if ((psd_info.depth != 1) && (psd_info.depth != 8) &&
(psd_info.depth != 16) && (psd_info.depth != 32))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
psd_info.mode=ReadBlobMSBShort(image);
if ((psd_info.mode == IndexedMode) && (psd_info.channels > 3))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s",
(double) psd_info.columns,(double) psd_info.rows,(double)
psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType)
psd_info.mode));
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Initialize image.
*/
image->depth=psd_info.depth;
image->columns=psd_info.columns;
image->rows=psd_info.rows;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
status=ResetImagePixels(image,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
psd_info.min_channels=3;
if (psd_info.mode == LabMode)
SetImageColorspace(image,LabColorspace,exception);
if (psd_info.mode == CMYKMode)
{
psd_info.min_channels=4;
SetImageColorspace(image,CMYKColorspace,exception);
if (psd_info.channels > 4)
SetImageAlphaChannel(image,ActivateAlphaChannel,exception);
}
else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) ||
(psd_info.mode == DuotoneMode))
{
if (psd_info.depth != 32)
{
status=AcquireImageColormap(image,psd_info.depth < 16 ? 256 : 65536,
exception);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image colormap allocated");
}
psd_info.min_channels=1;
SetImageColorspace(image,GRAYColorspace,exception);
if (psd_info.channels > 1)
SetImageAlphaChannel(image,ActivateAlphaChannel,exception);
}
else
if (psd_info.channels > 3)
SetImageAlphaChannel(image,ActivateAlphaChannel,exception);
if (psd_info.channels < psd_info.min_channels)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Read PSD raster colormap only present for indexed and duotone images.
*/
length=ReadBlobMSBLong(image);
if ((psd_info.mode == IndexedMode) && (length < 3))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (length != 0)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading colormap");
if ((psd_info.mode == DuotoneMode) || (psd_info.depth == 32))
{
/*
Duotone image data; the format of this data is undocumented.
32 bits per pixel; the colormap is ignored.
*/
(void) SeekBlob(image,(const MagickOffsetType) length,SEEK_CUR);
}
else
{
size_t
number_colors;
/*
Read PSD raster colormap.
*/
number_colors=length/3;
if (number_colors > 65536)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->alpha_trait=UndefinedPixelTrait;
}
}
if ((image->depth == 1) && (image->storage_class != PseudoClass))
ThrowReaderException(CorruptImageError, "ImproperImageHeader");
has_merged_image=MagickTrue;
profile=(StringInfo *) NULL;
length=ReadBlobMSBLong(image);
if (length != 0)
{
unsigned char
*blocks;
/*
Image resources block.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading image resource blocks - %.20g bytes",(double)
((MagickOffsetType) length));
if (length > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
blocks=(unsigned char *) AcquireQuantumMemory((size_t) length,
sizeof(*blocks));
if (blocks == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) length,blocks);
if ((count != (ssize_t) length) || (length < 4) ||
(LocaleNCompare((char *) blocks,"8BIM",4) != 0))
{
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
profile=ParseImageResourceBlocks(image,blocks,(size_t) length,
&has_merged_image,exception);
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
}
/*
Layer and mask block.
*/
length=GetPSDSize(&psd_info,image);
if (length == 8)
{
length=ReadBlobMSBLong(image);
length=ReadBlobMSBLong(image);
}
offset=TellBlob(image);
skip_layers=MagickFalse;
if ((image_info->number_scenes == 1) && (image_info->scene == 0) &&
(has_merged_image != MagickFalse))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" read composite only");
skip_layers=MagickTrue;
}
if (length == 0)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has no layers");
}
else
{
if (ReadPSDLayersInternal(image,image_info,&psd_info,skip_layers,
exception) != MagickTrue)
{
if (profile != (StringInfo *) NULL)
profile=DestroyStringInfo(profile);
(void) CloseBlob(image);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Skip the rest of the layer and mask information.
*/
SeekBlob(image,offset+length,SEEK_SET);
}
/*
If we are only "pinging" the image, then we're done - so return.
*/
if (EOFBlob(image) != MagickFalse)
{
if (profile != (StringInfo *) NULL)
profile=DestroyStringInfo(profile);
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
}
if (image_info->ping != MagickFalse)
{
if (profile != (StringInfo *) NULL)
profile=DestroyStringInfo(profile);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Read the precombined layer, present for PSD < 4 compatibility.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading the precombined layer");
if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1))
has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image,
&psd_info,exception);
if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) &&
(length != 0))
{
SeekBlob(image,offset,SEEK_SET);
status=ReadPSDLayersInternal(image,image_info,&psd_info,MagickFalse,
exception);
if (status != MagickTrue)
{
if (profile != (StringInfo *) NULL)
profile=DestroyStringInfo(profile);
(void) CloseBlob(image);
image=DestroyImageList(image);
return((Image *) NULL);
}
}
if (has_merged_image == MagickFalse)
{
Image
*merged;
if (GetImageListLength(image) == 1)
{
if (profile != (StringInfo *) NULL)
profile=DestroyStringInfo(profile);
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
}
SetImageAlphaChannel(image,TransparentAlphaChannel,exception);
image->background_color.alpha=TransparentAlpha;
image->background_color.alpha_trait=BlendPixelTrait;
merged=MergeImageLayers(image,FlattenLayer,exception);
ReplaceImageInList(&image,merged);
}
if (profile != (StringInfo *) NULL)
{
(void) SetImageProfile(image,GetStringInfoName(profile),profile,
exception);
profile=DestroyStringInfo(profile);
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterPSDImage() adds properties for the PSD image format to
% the list of supported formats. The properties include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterPSDImage method is:
%
% size_t RegisterPSDImage(void)
%
*/
ModuleExport size_t RegisterPSDImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("PSD","PSB","Adobe Large Document Format");
entry->decoder=(DecodeImageHandler *) ReadPSDImage;
entry->encoder=(EncodeImageHandler *) WritePSDImage;
entry->magick=(IsImageFormatHandler *) IsPSD;
entry->flags|=CoderDecoderSeekableStreamFlag;
entry->flags|=CoderEncoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PSD","PSD","Adobe Photoshop bitmap");
entry->decoder=(DecodeImageHandler *) ReadPSDImage;
entry->encoder=(EncodeImageHandler *) WritePSDImage;
entry->magick=(IsImageFormatHandler *) IsPSD;
entry->flags|=CoderDecoderSeekableStreamFlag;
entry->flags|=CoderEncoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterPSDImage() removes format registrations made by the
% PSD module from the list of supported formats.
%
% The format of the UnregisterPSDImage method is:
%
% UnregisterPSDImage(void)
%
*/
ModuleExport void UnregisterPSDImage(void)
{
(void) UnregisterMagickInfo("PSB");
(void) UnregisterMagickInfo("PSD");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePSDImage() writes an image in the Adobe Photoshop encoded image format.
%
% The format of the WritePSDImage method is:
%
% MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image,
const size_t offset)
{
if (psd_info->version == 1)
return(WriteBlobMSBShort(image,(unsigned short) offset));
return(WriteBlobMSBLong(image,(unsigned int) offset));
}
static inline ssize_t WritePSDOffset(const PSDInfo *psd_info,Image *image,
const MagickSizeType size,const MagickSizeType offset)
{
MagickSizeType
current_offset;
ssize_t
result;
current_offset=TellBlob(image);
SeekBlob(image,offset,SEEK_SET);
if (psd_info->version == 1)
result=WriteBlobMSBShort(image,(unsigned short) size);
else
result=WriteBlobMSBLong(image,(unsigned int) size);
SeekBlob(image,current_offset,SEEK_SET);
return(result);
}
static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image,
const MagickSizeType size)
{
if (psd_info->version == 1)
return(WriteBlobLong(image,(unsigned int) size));
return(WriteBlobLongLong(image,size));
}
static inline ssize_t WritePSDSize(const PSDInfo *psd_info,Image *image,
const MagickSizeType size,const MagickSizeType offset)
{
MagickSizeType
current_offset;
ssize_t
result;
current_offset=TellBlob(image);
SeekBlob(image,offset,SEEK_SET);
result=SetPSDSize(psd_info, image, size);
SeekBlob(image,current_offset,SEEK_SET);
return(result);
}
static size_t PSDPackbitsEncodeImage(Image *image,const size_t length,
const unsigned char *pixels,unsigned char *compact_pixels,
ExceptionInfo *exception)
{
int
count;
register ssize_t
i,
j;
register unsigned char
*q;
unsigned char
*packbits;
/*
Compress pixels with Packbits encoding.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(pixels != (unsigned char *) NULL);
assert(compact_pixels != (unsigned char *) NULL);
packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits));
if (packbits == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
q=compact_pixels;
for (i=(ssize_t) length; i != 0; )
{
switch (i)
{
case 1:
{
i--;
*q++=(unsigned char) 0;
*q++=(*pixels);
break;
}
case 2:
{
i-=2;
*q++=(unsigned char) 1;
*q++=(*pixels);
*q++=pixels[1];
break;
}
case 3:
{
i-=3;
if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2)))
{
*q++=(unsigned char) ((256-3)+1);
*q++=(*pixels);
break;
}
*q++=(unsigned char) 2;
*q++=(*pixels);
*q++=pixels[1];
*q++=pixels[2];
break;
}
default:
{
if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2)))
{
/*
Packed run.
*/
count=3;
while (((ssize_t) count < i) && (*pixels == *(pixels+count)))
{
count++;
if (count >= 127)
break;
}
i-=count;
*q++=(unsigned char) ((256-count)+1);
*q++=(*pixels);
pixels+=count;
break;
}
/*
Literal run.
*/
count=0;
while ((*(pixels+count) != *(pixels+count+1)) ||
(*(pixels+count+1) != *(pixels+count+2)))
{
packbits[count+1]=pixels[count];
count++;
if (((ssize_t) count >= (i-3)) || (count >= 127))
break;
}
i-=count;
*packbits=(unsigned char) (count-1);
for (j=0; j <= (ssize_t) count; j++)
*q++=packbits[j];
pixels+=count;
break;
}
}
}
*q++=(unsigned char) 128; /* EOD marker */
packbits=(unsigned char *) RelinquishMagickMemory(packbits);
return((size_t) (q-compact_pixels));
}
static size_t WriteCompressionStart(const PSDInfo *psd_info,Image *image,
const Image *next_image,const CompressionType compression,
const ssize_t channels)
{
size_t
length;
ssize_t
i,
y;
if (compression == RLECompression)
{
length=WriteBlobShort(image,RLE);
for (i=0; i < channels; i++)
for (y=0; y < (ssize_t) next_image->rows; y++)
length+=SetPSDOffset(psd_info,image,0);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
else if (compression == ZipCompression)
length=WriteBlobShort(image,ZipWithoutPrediction);
#endif
else
length=WriteBlobShort(image,Raw);
return(length);
}
static size_t WritePSDChannel(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
const QuantumType quantum_type, unsigned char *compact_pixels,
MagickOffsetType size_offset,const MagickBooleanType separate,
const CompressionType compression,ExceptionInfo *exception)
{
int
y;
MagickBooleanType
monochrome;
QuantumInfo
*quantum_info;
register const Quantum
*p;
register ssize_t
i;
size_t
count,
length;
unsigned char
*pixels;
#ifdef MAGICKCORE_ZLIB_DELEGATE
#define CHUNK 16384
int
flush,
level;
unsigned char
*compressed_pixels;
z_stream
stream;
compressed_pixels=(unsigned char *) NULL;
flush=Z_NO_FLUSH;
#endif
count=0;
if (separate != MagickFalse)
{
size_offset=TellBlob(image)+2;
count+=WriteCompressionStart(psd_info,image,next_image,compression,1);
}
if (next_image->depth > 8)
next_image->depth=16;
monochrome=IsImageMonochrome(image) && (image->depth == 1) ?
MagickTrue : MagickFalse;
quantum_info=AcquireQuantumInfo(image_info,next_image);
if (quantum_info == (QuantumInfo *) NULL)
return(0);
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (compression == ZipCompression)
{
compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK,
sizeof(*compressed_pixels));
if (compressed_pixels == (unsigned char *) NULL)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
memset(&stream,0,sizeof(stream));
stream.data_type=Z_BINARY;
level=Z_DEFAULT_COMPRESSION;
if ((image_info->quality > 0 && image_info->quality < 10))
level=(int) image_info->quality;
if (deflateInit(&stream,level) != Z_OK)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
}
#endif
for (y=0; y < (ssize_t) next_image->rows; y++)
{
p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (monochrome != MagickFalse)
for (i=0; i < (ssize_t) length; i++)
pixels[i]=(~pixels[i]);
if (compression == RLECompression)
{
length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels,
exception);
count+=WriteBlob(image,length,compact_pixels);
size_offset+=WritePSDOffset(psd_info,image,length,size_offset);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
else if (compression == ZipCompression)
{
stream.avail_in=(uInt) length;
stream.next_in=(Bytef *) pixels;
if (y == (ssize_t) next_image->rows-1)
flush=Z_FINISH;
do {
stream.avail_out=(uInt) CHUNK;
stream.next_out=(Bytef *) compressed_pixels;
if (deflate(&stream,flush) == Z_STREAM_ERROR)
break;
length=(size_t) CHUNK-stream.avail_out;
if (length > 0)
count+=WriteBlob(image,length,compressed_pixels);
} while (stream.avail_out == 0);
}
#endif
else
count+=WriteBlob(image,length,pixels);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (compression == ZipCompression)
{
(void) deflateEnd(&stream);
compressed_pixels=(unsigned char *) RelinquishMagickMemory(
compressed_pixels);
}
#endif
quantum_info=DestroyQuantumInfo(quantum_info);
return(count);
}
static unsigned char *AcquireCompactPixels(const Image *image,
ExceptionInfo *exception)
{
size_t
packet_size;
unsigned char
*compact_pixels;
packet_size=image->depth > 8UL ? 2UL : 1UL;
compact_pixels=(unsigned char *) AcquireQuantumMemory((9*
image->columns)+1,packet_size*sizeof(*compact_pixels));
if (compact_pixels == (unsigned char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
}
return(compact_pixels);
}
static size_t WritePSDChannels(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
MagickOffsetType size_offset,const MagickBooleanType separate,
ExceptionInfo *exception)
{
CompressionType
compression;
Image
*mask;
MagickOffsetType
rows_offset;
size_t
channels,
count,
length,
offset_length;
unsigned char
*compact_pixels;
count=0;
offset_length=0;
rows_offset=0;
compact_pixels=(unsigned char *) NULL;
compression=next_image->compression;
if (image_info->compression != UndefinedCompression)
compression=image_info->compression;
if (compression == RLECompression)
{
compact_pixels=AcquireCompactPixels(next_image,exception);
if (compact_pixels == (unsigned char *) NULL)
return(0);
}
channels=1;
if (separate == MagickFalse)
{
if (next_image->storage_class != PseudoClass)
{
if (IsImageGray(next_image) == MagickFalse)
channels=next_image->colorspace == CMYKColorspace ? 4 : 3;
if (next_image->alpha_trait != UndefinedPixelTrait)
channels++;
}
rows_offset=TellBlob(image)+2;
count+=WriteCompressionStart(psd_info,image,next_image,compression,
channels);
offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4));
}
size_offset+=2;
if (next_image->storage_class == PseudoClass)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
IndexQuantum,compact_pixels,rows_offset,separate,compression,
exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
else
{
if (IsImageGray(next_image) != MagickFalse)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
GrayQuantum,compact_pixels,rows_offset,separate,compression,
exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
else
{
if (next_image->colorspace == CMYKColorspace)
(void) NegateCMYK(next_image,exception);
length=WritePSDChannel(psd_info,image_info,image,next_image,
RedQuantum,compact_pixels,rows_offset,separate,compression,
exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
length=WritePSDChannel(psd_info,image_info,image,next_image,
GreenQuantum,compact_pixels,rows_offset,separate,compression,
exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
length=WritePSDChannel(psd_info,image_info,image,next_image,
BlueQuantum,compact_pixels,rows_offset,separate,compression,
exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
if (next_image->colorspace == CMYKColorspace)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
BlackQuantum,compact_pixels,rows_offset,separate,compression,
exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
}
if (next_image->alpha_trait != UndefinedPixelTrait)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
AlphaQuantum,compact_pixels,rows_offset,separate,compression,
exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
if (next_image->colorspace == CMYKColorspace)
(void) NegateCMYK(next_image,exception);
if (separate != MagickFalse)
{
const char
*property;
property=GetImageArtifact(next_image,"psd:opacity-mask");
if (property != (const char *) NULL)
{
mask=(Image *) GetImageRegistry(ImageRegistryType,property,
exception);
if (mask != (Image *) NULL)
{
if (compression == RLECompression)
{
compact_pixels=AcquireCompactPixels(mask,exception);
if (compact_pixels == (unsigned char *) NULL)
return(0);
}
length=WritePSDChannel(psd_info,image_info,image,mask,
RedQuantum,compact_pixels,rows_offset,MagickTrue,compression,
exception);
(void) WritePSDSize(psd_info,image,length,size_offset);
count+=length;
compact_pixels=(unsigned char *) RelinquishMagickMemory(
compact_pixels);
}
}
}
return(count);
}
static size_t WritePascalString(Image *image,const char *value,size_t padding)
{
size_t
count,
length;
register ssize_t
i;
/*
Max length is 255.
*/
count=0;
length=(strlen(value) > 255UL ) ? 255UL : strlen(value);
if (length == 0)
count+=WriteBlobByte(image,0);
else
{
count+=WriteBlobByte(image,(unsigned char) length);
count+=WriteBlob(image,length,(const unsigned char *) value);
}
length++;
if ((length % padding) == 0)
return(count);
for (i=0; i < (ssize_t) (padding-(length % padding)); i++)
count+=WriteBlobByte(image,0);
return(count);
}
static void WriteResolutionResourceBlock(Image *image)
{
double
x_resolution,
y_resolution;
unsigned short
units;
if (image->units == PixelsPerCentimeterResolution)
{
x_resolution=2.54*65536.0*image->resolution.x+0.5;
y_resolution=2.54*65536.0*image->resolution.y+0.5;
units=2;
}
else
{
x_resolution=65536.0*image->resolution.x+0.5;
y_resolution=65536.0*image->resolution.y+0.5;
units=1;
}
(void) WriteBlob(image,4,(const unsigned char *) "8BIM");
(void) WriteBlobMSBShort(image,0x03ED);
(void) WriteBlobMSBShort(image,0);
(void) WriteBlobMSBLong(image,16); /* resource size */
(void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5));
(void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */
(void) WriteBlobMSBShort(image,units); /* width unit */
(void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5));
(void) WriteBlobMSBShort(image,units); /* vertical resolution unit */
(void) WriteBlobMSBShort(image,units); /* height unit */
}
static inline size_t WriteChannelSize(const PSDInfo *psd_info,Image *image,
const signed short channel)
{
size_t
count;
count=(size_t) WriteBlobShort(image,channel);
count+=SetPSDSize(psd_info,image,0);
return(count);
}
static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile)
{
register const unsigned char
*p;
size_t
length;
unsigned char
*datum;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
length=GetStringInfoLength(bim_profile);
if (length < 16)
return;
datum=GetStringInfoDatum(bim_profile);
for (p=datum; (p >= datum) && (p < (datum+length-16)); )
{
register unsigned char
*q;
q=(unsigned char *) p;
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
break;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
if (id == 0x0000040f)
{
ssize_t
quantum;
quantum=PSDQuantum(count)+12;
if ((quantum >= 12) && (quantum < (ssize_t) length))
{
if ((q+quantum < (datum+length-16)))
(void) memmove(q,q+quantum,length-quantum-(q-datum));
SetStringInfoLength(bim_profile,length-quantum);
}
break;
}
p+=count;
if ((count & 0x01) != 0)
p++;
}
}
static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile)
{
register const unsigned char
*p;
size_t
length;
unsigned char
*datum;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
length=GetStringInfoLength(bim_profile);
if (length < 16)
return;
datum=GetStringInfoDatum(bim_profile);
for (p=datum; (p >= datum) && (p < (datum+length-16)); )
{
register unsigned char
*q;
ssize_t
cnt;
q=(unsigned char *) p;
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
return;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
cnt=PSDQuantum(count);
if (cnt < 0)
return;
if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12)) &&
((ssize_t) length-(cnt+12)-(q-datum)) > 0)
{
(void) memmove(q,q+cnt+12,length-(cnt+12)-(q-datum));
SetStringInfoLength(bim_profile,length-(cnt+12));
break;
}
p+=count;
if ((count & 0x01) != 0)
p++;
}
}
static const StringInfo *GetAdditionalInformation(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
#define PSDKeySize 5
#define PSDAllowedLength 36
char
key[PSDKeySize];
/* Whitelist of keys from: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ */
const char
allowed[PSDAllowedLength][PSDKeySize] = {
"blnc", "blwh", "brit", "brst", "clbl", "clrL", "curv", "expA", "FMsk",
"GdFl", "grdm", "hue ", "hue2", "infx", "knko", "lclr", "levl", "lnsr",
"lfx2", "luni", "lrFX", "lspf", "lyid", "lyvr", "mixr", "nvrt", "phfl",
"post", "PtFl", "selc", "shpa", "sn2P", "SoCo", "thrs", "tsly", "vibA"
},
*option;
const StringInfo
*info;
MagickBooleanType
found;
register size_t
i;
size_t
remaining_length,
length;
StringInfo
*profile;
unsigned char
*p;
unsigned int
size;
info=GetImageProfile(image,"psd:additional-info");
if (info == (const StringInfo *) NULL)
return((const StringInfo *) NULL);
option=GetImageOption(image_info,"psd:additional-info");
if (LocaleCompare(option,"all") == 0)
return(info);
if (LocaleCompare(option,"selective") != 0)
{
profile=RemoveImageProfile(image,"psd:additional-info");
return(DestroyStringInfo(profile));
}
length=GetStringInfoLength(info);
p=GetStringInfoDatum(info);
remaining_length=length;
length=0;
while (remaining_length >= 12)
{
/* skip over signature */
p+=4;
key[0]=(*p++);
key[1]=(*p++);
key[2]=(*p++);
key[3]=(*p++);
key[4]='\0';
size=(unsigned int) (*p++) << 24;
size|=(unsigned int) (*p++) << 16;
size|=(unsigned int) (*p++) << 8;
size|=(unsigned int) (*p++);
size=size & 0xffffffff;
remaining_length-=12;
if ((size_t) size > remaining_length)
return((const StringInfo *) NULL);
found=MagickFalse;
for (i=0; i < PSDAllowedLength; i++)
{
if (LocaleNCompare(key,allowed[i],PSDKeySize) != 0)
continue;
found=MagickTrue;
break;
}
remaining_length-=(size_t) size;
if (found == MagickFalse)
{
if (remaining_length > 0)
p=(unsigned char *) memmove(p-12,p+size,remaining_length);
continue;
}
length+=(size_t) size+12;
p+=size;
}
profile=RemoveImageProfile(image,"psd:additional-info");
if (length == 0)
return(DestroyStringInfo(profile));
SetStringInfoLength(profile,(const size_t) length);
SetImageProfile(image,"psd:additional-info",info,exception);
return(profile);
}
static MagickBooleanType WritePSDLayersInternal(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,size_t *layers_size,
ExceptionInfo *exception)
{
char
layer_name[MagickPathExtent];
const char
*property;
const StringInfo
*info;
Image
*base_image,
*next_image;
MagickBooleanType
status;
MagickOffsetType
*layer_size_offsets,
size_offset;
register ssize_t
i;
size_t
layer_count,
layer_index,
length,
name_length,
rounded_size,
size;
status=MagickTrue;
base_image=GetNextImageInList(image);
if (base_image == (Image *) NULL)
base_image=image;
size=0;
size_offset=TellBlob(image);
SetPSDSize(psd_info,image,0);
layer_count=0;
for (next_image=base_image; next_image != NULL; )
{
layer_count++;
next_image=GetNextImageInList(next_image);
}
if (image->alpha_trait != UndefinedPixelTrait)
size+=WriteBlobShort(image,-(unsigned short) layer_count);
else
size+=WriteBlobShort(image,(unsigned short) layer_count);
layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory(
(size_t) layer_count,sizeof(MagickOffsetType));
if (layer_size_offsets == (MagickOffsetType *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
layer_index=0;
for (next_image=base_image; next_image != NULL; )
{
Image
*mask;
unsigned char
default_color;
unsigned short
channels,
total_channels;
mask=(Image *) NULL;
property=GetImageArtifact(next_image,"psd:opacity-mask");
default_color=0;
if (property != (const char *) NULL)
{
mask=(Image *) GetImageRegistry(ImageRegistryType,property,exception);
default_color=strlen(property) == 9 ? 255 : 0;
}
size+=WriteBlobSignedLong(image,(signed int) next_image->page.y);
size+=WriteBlobSignedLong(image,(signed int) next_image->page.x);
size+=WriteBlobSignedLong(image,(signed int) (next_image->page.y+
next_image->rows));
size+=WriteBlobSignedLong(image,(signed int) (next_image->page.x+
next_image->columns));
channels=1U;
if ((next_image->storage_class != PseudoClass) &&
(IsImageGray(next_image) == MagickFalse))
channels=next_image->colorspace == CMYKColorspace ? 4U : 3U;
total_channels=channels;
if (next_image->alpha_trait != UndefinedPixelTrait)
total_channels++;
if (mask != (Image *) NULL)
total_channels++;
size+=WriteBlobShort(image,total_channels);
layer_size_offsets[layer_index++]=TellBlob(image);
for (i=0; i < (ssize_t) channels; i++)
size+=WriteChannelSize(psd_info,image,(signed short) i);
if (next_image->alpha_trait != UndefinedPixelTrait)
size+=WriteChannelSize(psd_info,image,-1);
if (mask != (Image *) NULL)
size+=WriteChannelSize(psd_info,image,-2);
size+=WriteBlobString(image,image->endian == LSBEndian ? "MIB8" :"8BIM");
size+=WriteBlobString(image,CompositeOperatorToPSDBlendMode(image));
property=GetImageArtifact(next_image,"psd:layer.opacity");
if (property != (const char *) NULL)
{
Quantum
opacity;
opacity=(Quantum) StringToInteger(property);
size+=WriteBlobByte(image,ScaleQuantumToChar(opacity));
(void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue,exception);
}
else
size+=WriteBlobByte(image,255);
size+=WriteBlobByte(image,0);
size+=WriteBlobByte(image,next_image->compose==NoCompositeOp ?
1 << 0x02 : 1); /* layer properties - visible, etc. */
size+=WriteBlobByte(image,0);
info=GetAdditionalInformation(image_info,next_image,exception);
property=(const char *) GetImageProperty(next_image,"label",exception);
if (property == (const char *) NULL)
{
(void) FormatLocaleString(layer_name,MagickPathExtent,"L%.20g",
(double) layer_index);
property=layer_name;
}
name_length=strlen(property)+1;
if ((name_length % 4) != 0)
name_length+=(4-(name_length % 4));
if (info != (const StringInfo *) NULL)
name_length+=GetStringInfoLength(info);
name_length+=8;
if (mask != (Image *) NULL)
name_length+=20;
size+=WriteBlobLong(image,(unsigned int) name_length);
if (mask == (Image *) NULL)
size+=WriteBlobLong(image,0);
else
{
if (mask->compose != NoCompositeOp)
(void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum(
default_color),MagickTrue,exception);
mask->page.y+=image->page.y;
mask->page.x+=image->page.x;
size+=WriteBlobLong(image,20);
size+=WriteBlobSignedLong(image,mask->page.y);
size+=WriteBlobSignedLong(image,mask->page.x);
size+=WriteBlobSignedLong(image,(const signed int) mask->rows+
mask->page.y);
size+=WriteBlobSignedLong(image,(const signed int) mask->columns+
mask->page.x);
size+=WriteBlobByte(image,default_color);
size+=WriteBlobByte(image,mask->compose == NoCompositeOp ? 2 : 0);
size+=WriteBlobMSBShort(image,0);
}
size+=WriteBlobLong(image,0);
size+=WritePascalString(image,property,4);
if (info != (const StringInfo *) NULL)
size+=WriteBlob(image,GetStringInfoLength(info),
GetStringInfoDatum(info));
next_image=GetNextImageInList(next_image);
}
/*
Now the image data!
*/
next_image=base_image;
layer_index=0;
while (next_image != NULL)
{
length=WritePSDChannels(psd_info,image_info,image,next_image,
layer_size_offsets[layer_index++],MagickTrue,exception);
if (length == 0)
{
status=MagickFalse;
break;
}
size+=length;
next_image=GetNextImageInList(next_image);
}
/*
Write the total size
*/
if (layers_size != (size_t*) NULL)
*layers_size=size;
if ((size/2) != ((size+1)/2))
rounded_size=size+1;
else
rounded_size=size;
(void) WritePSDSize(psd_info,image,rounded_size,size_offset);
layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory(
layer_size_offsets);
/*
Remove the opacity mask from the registry
*/
next_image=base_image;
while (next_image != (Image *) NULL)
{
property=GetImageArtifact(next_image,"psd:opacity-mask");
if (property != (const char *) NULL)
DeleteImageRegistry(property);
next_image=GetNextImageInList(next_image);
}
return(status);
}
ModuleExport MagickBooleanType WritePSDLayers(Image * image,
const ImageInfo *image_info,const PSDInfo *psd_info,ExceptionInfo *exception)
{
PolicyDomain
domain;
PolicyRights
rights;
domain=CoderPolicyDomain;
rights=WritePolicyRights;
if (IsRightsAuthorized(domain,rights,"PSD") == MagickFalse)
return(MagickTrue);
return WritePSDLayersInternal(image,image_info,psd_info,(size_t*) NULL,
exception);
}
static MagickBooleanType WritePSDImage(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
const StringInfo
*icc_profile;
MagickBooleanType
status;
PSDInfo
psd_info;
register ssize_t
i;
size_t
length,
num_channels,
packet_size;
StringInfo
*bim_profile;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
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);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
packet_size=(size_t) (image->depth > 8 ? 6 : 3);
if (image->alpha_trait != UndefinedPixelTrait)
packet_size+=image->depth > 8 ? 2 : 1;
psd_info.version=1;
if ((LocaleCompare(image_info->magick,"PSB") == 0) ||
(image->columns > 30000) || (image->rows > 30000))
psd_info.version=2;
(void) WriteBlob(image,4,(const unsigned char *) "8BPS");
(void) WriteBlobMSBShort(image,psd_info.version); /* version */
for (i=1; i <= 6; i++)
(void) WriteBlobByte(image, 0); /* 6 bytes of reserved */
/* When the image has a color profile it won't be converted to gray scale */
if ((GetImageProfile(image,"icc") == (StringInfo *) NULL) &&
(SetImageGray(image,exception) != MagickFalse))
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);
else
if ((image_info->type != TrueColorType) && (image_info->type !=
TrueColorAlphaType) && (image->storage_class == PseudoClass))
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);
else
{
if (image->storage_class == PseudoClass)
(void) SetImageStorageClass(image,DirectClass,exception);
if (image->colorspace != CMYKColorspace)
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL);
else
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL);
}
(void) WriteBlobMSBShort(image,(unsigned short) num_channels);
(void) WriteBlobMSBLong(image,(unsigned int) image->rows);
(void) WriteBlobMSBLong(image,(unsigned int) image->columns);
if (IsImageGray(image) != MagickFalse)
{
MagickBooleanType
monochrome;
/*
Write depth & mode.
*/
monochrome=IsImageMonochrome(image) && (image->depth == 1) ?
MagickTrue : MagickFalse;
(void) WriteBlobMSBShort(image,(unsigned short)
(monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8));
(void) WriteBlobMSBShort(image,(unsigned short)
(monochrome != MagickFalse ? BitmapMode : GrayscaleMode));
}
else
{
(void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class ==
PseudoClass ? 8 : image->depth > 8 ? 16 : 8));
if (((image_info->colorspace != UndefinedColorspace) ||
(image->colorspace != CMYKColorspace)) &&
(image_info->colorspace != CMYKColorspace))
{
(void) TransformImageColorspace(image,sRGBColorspace,exception);
(void) WriteBlobMSBShort(image,(unsigned short)
(image->storage_class == PseudoClass ? IndexedMode : RGBMode));
}
else
{
if (image->colorspace != CMYKColorspace)
(void) TransformImageColorspace(image,CMYKColorspace,exception);
(void) WriteBlobMSBShort(image,CMYKMode);
}
}
if ((IsImageGray(image) != MagickFalse) ||
(image->storage_class == DirectClass) || (image->colors > 256))
(void) WriteBlobMSBLong(image,0);
else
{
/*
Write PSD raster colormap.
*/
(void) WriteBlobMSBLong(image,768);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(
image->colormap[i].green));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
}
/*
Image resource block.
*/
length=28; /* 0x03EB */
bim_profile=(StringInfo *) GetImageProfile(image,"8bim");
icc_profile=GetImageProfile(image,"icc");
if (bim_profile != (StringInfo *) NULL)
{
bim_profile=CloneStringInfo(bim_profile);
if (icc_profile != (StringInfo *) NULL)
RemoveICCProfileFromResourceBlock(bim_profile);
RemoveResolutionFromResourceBlock(bim_profile);
length+=PSDQuantum(GetStringInfoLength(bim_profile));
}
if (icc_profile != (const StringInfo *) NULL)
length+=PSDQuantum(GetStringInfoLength(icc_profile))+12;
(void) WriteBlobMSBLong(image,(unsigned int) length);
WriteResolutionResourceBlock(image);
if (bim_profile != (StringInfo *) NULL)
{
(void) WriteBlob(image,GetStringInfoLength(bim_profile),
GetStringInfoDatum(bim_profile));
bim_profile=DestroyStringInfo(bim_profile);
}
if (icc_profile != (StringInfo *) NULL)
{
(void) WriteBlob(image,4,(const unsigned char *) "8BIM");
(void) WriteBlobMSBShort(image,0x0000040F);
(void) WriteBlobMSBShort(image,0);
(void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength(
icc_profile));
(void) WriteBlob(image,GetStringInfoLength(icc_profile),
GetStringInfoDatum(icc_profile));
if ((MagickOffsetType) GetStringInfoLength(icc_profile) !=
PSDQuantum(GetStringInfoLength(icc_profile)))
(void) WriteBlobByte(image,0);
}
if (status != MagickFalse)
{
MagickOffsetType
size_offset;
size_t
size;
size_offset=TellBlob(image);
SetPSDSize(&psd_info,image,0);
status=WritePSDLayersInternal(image,image_info,&psd_info,&size,
exception);
size_offset+=WritePSDSize(&psd_info,image,size+
(psd_info.version == 1 ? 8 : 12),size_offset);
}
(void) WriteBlobMSBLong(image,0); /* user mask data */
/*
Write composite image.
*/
if (status != MagickFalse)
{
CompressionType
compression;
compression=image->compression;
if (image->compression == ZipCompression)
image->compression=RLECompression;
if (image_info->compression != UndefinedCompression)
image->compression=image_info->compression;
if (WritePSDChannels(&psd_info,image_info,image,image,0,MagickFalse,
exception) == 0)
status=MagickFalse;
image->compression=compression;
}
(void) CloseBlob(image);
return(status);
}
|
sicm_low.c
|
#include "sicm_low.h"
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <math.h>
#include <numa.h>
#include <numaif.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/mman.h>
// https://www.mail-archive.com/[email protected]/msg20403.html
#ifndef MAP_HUGE_SHIFT
#include <linux/mman.h>
#endif
#include "sicm_impl.h"
#define X86_CPUID_MODEL_MASK (0xf<<4)
#define X86_CPUID_EXT_MODEL_MASK (0xf<<16)
int normal_page_size = -1;
sicm_device_tag sicm_get_device_tag(char *env) {
size_t max_chars;
max_chars = 32;
if(strncmp(env, "SICM_DRAM", max_chars) == 0) {
return SICM_DRAM;
} else if(strncmp(env, "SICM_KNL_HBM", max_chars) == 0) {
return SICM_KNL_HBM;
} else if(strncmp(env, "SICM_POWERPC_HBM", max_chars) == 0) {
return SICM_POWERPC_HBM;
}
return INVALID_TAG;
}
char * sicm_device_tag_str(sicm_device_tag tag) {
switch(tag) {
case SICM_DRAM:
return "SICM_DRAM";
case SICM_KNL_HBM:
return "SICM_KNL_HBM";
case SICM_POWERPC_HBM:
return "SICM_POWERPC_HBM";
case SICM_OPTANE:
return "SICM_OPTANE";
case INVALID_TAG:
break;
}
return NULL;
}
static int sicm_device_compare(const void * lhs, const void * rhs) {
sicm_device * l = * (sicm_device **) lhs;
sicm_device * r = * (sicm_device **) rhs;
if (l->node != r->node) {
return l->node - r->node;
}
return l->page_size - r->page_size;
}
/* Only initialize SICM once */
static int sicm_init_count = 0;
static pthread_mutex_t sicm_init_count_mutex = PTHREAD_MUTEX_INITIALIZER;
static sicm_device_list sicm_global_devices = {};
static sicm_device *sicm_global_device_array = NULL;
/* set in sicm_init */
struct sicm_device *sicm_default_device_ptr = NULL;
struct sicm_device_list sicm_init() {
/* Check whether or not the global devices list has been initialized already */
pthread_mutex_lock(&sicm_init_count_mutex);
if (sicm_init_count) {
sicm_init_count++;
pthread_mutex_unlock(&sicm_init_count_mutex);
return sicm_global_devices;
}
// Find the number of huge page sizes
int huge_page_size_count = 0;
DIR* dir;
struct dirent* entry;
dir = opendir("/sys/kernel/mm/hugepages");
while((entry = readdir(dir)) != NULL)
if(entry->d_name[0] != '.') huge_page_size_count++;
closedir(dir);
int node_count = numa_max_node() + 1, depth;
int device_count = node_count * (huge_page_size_count + 1);
struct bitmask* non_dram_nodes = numa_bitmask_alloc(node_count);
sicm_global_device_array = malloc(device_count * sizeof(struct sicm_device));
int* huge_page_sizes = malloc(huge_page_size_count * sizeof(int));
int i, j;
int idx = 0;
normal_page_size = numa_pagesize() / 1024;
// initialize the device list
sicm_device **devices = malloc(device_count * sizeof(sicm_device *));
for(i = 0; i < device_count; i++) {
devices[i] = &sicm_global_device_array[i];
devices[i]->tag = INVALID_TAG;
devices[i]->node = -1;
devices[i]->page_size = -1;
}
// Find the actual set of huge page sizes (reported in KiB)
dir = opendir("/sys/kernel/mm/hugepages");
i = 0;
while((entry = readdir(dir)) != NULL) {
if(entry->d_name[0] != '.') {
huge_page_sizes[i] = 0;
for(j = 0; j < 10; j++) {
if(entry->d_name[j] == '\0') {
j = -1;
break;
}
}
if(j < 0) break;
for(; entry->d_name[j] >= '0' && entry->d_name[j] <= '9'; j++) {
huge_page_sizes[i] *= 10;
huge_page_sizes[i] += entry->d_name[j] - '0';
}
i++;
}
}
closedir(dir);
struct bitmask* cpumask = numa_allocate_cpumask();
int cpu_count = numa_num_possible_cpus();
struct bitmask* compute_nodes = numa_bitmask_alloc(node_count);
i = 0;
for(i = 0; i < node_count; i++) {
numa_node_to_cpus(i, cpumask);
for(j = 0; j < cpu_count; j++) {
if(numa_bitmask_isbitset(cpumask, j)) {
numa_bitmask_setbit(compute_nodes, i);
break;
}
}
}
numa_free_cpumask(cpumask);
#ifdef __x86_64__
// Knights Landing
uint32_t xeon_phi_model = (0x7<<4);
uint32_t xeon_phi_ext_model = (0x5<<16);
uint32_t registers[4];
uint32_t expected = xeon_phi_model | xeon_phi_ext_model;
asm volatile("cpuid":"=a"(registers[0]),
"=b"(registers[1]),
"=c"(registers[2]),
"=d"(registers[2]):"0"(1), "2"(0));
uint32_t actual = registers[0] & (X86_CPUID_MODEL_MASK | X86_CPUID_EXT_MODEL_MASK);
if (actual == expected) {
for(i = 0; i <= numa_max_node(); i++) {
if(!numa_bitmask_isbitset(compute_nodes, i)) {
long size = -1;
if ((numa_node_size(i, &size) != -1) && size) {
int compute_node = -1;
/*
* On Knights Landing machines, high-bandwidth memory always has
* higher NUMA distances (to prevent malloc from giving you HBM)
* but I'm pretty sure the compute node closest to an HBM node
* always has NUMA distance 31, e.g.,
* https://goparallel.sourceforge.net/wp-content/uploads/2016/05/Colfax_KNL_Clustering_Modes_Guide.pdf
*/
for(j = 0; j < numa_max_node(); j++) {
if(numa_distance(i, j) == 31) compute_node = j;
}
devices[idx]->tag = SICM_KNL_HBM;
devices[idx]->node = i;
devices[idx]->page_size = normal_page_size;
devices[idx]->data.knl_hbm = (struct sicm_knl_hbm_data){
.compute_node=compute_node };
numa_bitmask_setbit(non_dram_nodes, i);
idx++;
for(j = 0; j < huge_page_size_count; j++) {
devices[idx]->tag = SICM_KNL_HBM;
devices[idx]->node = i;
devices[idx]->page_size = huge_page_sizes[j];
devices[idx]->data.knl_hbm = (struct sicm_knl_hbm_data){
.compute_node=compute_node };
idx++;
}
}
}
}
} else {
// Optane support
// This is a bit of a hack: on x86_64 architecture that is not KNL,
// NUMA nodes without CPUs are assumed to be Optane nodes
for(i = 0; i <= numa_max_node(); i++) {
if(!numa_bitmask_isbitset(compute_nodes, i)) {
long size = -1;
if ((numa_node_size(i, &size) != -1) && size) {
int compute_node = -1;
int dist = 1000;
for(j = 0; j < numa_max_node(); j++) {
if (i == j)
continue;
int d = numa_distance(i, j);
if (d < dist) {
dist = d;
compute_node = j;
}
}
devices[idx]->tag = SICM_OPTANE;
devices[idx]->node = i;
devices[idx]->page_size = normal_page_size;
devices[idx]->data.optane = (struct sicm_optane_data){
.compute_node=compute_node };
numa_bitmask_setbit(non_dram_nodes, i);
idx++;
for(j = 0; j < huge_page_size_count; j++) {
devices[idx]->tag = SICM_OPTANE;
devices[idx]->node = i;
devices[idx]->page_size = huge_page_sizes[j];
devices[idx]->data.optane = (struct sicm_optane_data){
.compute_node=compute_node };
idx++;
}
}
}
}
}
#endif
#ifdef __powerpc__
// Power PC
for(i = 0; i <= numa_max_node(); i++) {
if(!numa_bitmask_isbitset(compute_nodes, i)) {
// make sure the numa node has memory on it
long size = -1;
if ((numa_node_size(i, &size) != -1) && size) {
devices[idx]->tag = SICM_POWERPC_HBM;
devices[idx]->node = i;
devices[idx]->page_size = normal_page_size;
devices[idx]->data.powerpc_hbm = (struct sicm_powerpc_hbm_data){ };
numa_bitmask_setbit(non_dram_nodes, i);
idx++;
for(j = 0; j < huge_page_size_count; j++) {
devices[idx]->tag = SICM_POWERPC_HBM;
devices[idx]->node = i;
devices[idx]->page_size = huge_page_sizes[j];
devices[idx]->data.powerpc_hbm = (struct sicm_powerpc_hbm_data){ };
idx++;
}
}
}
}
#endif
// DRAM
for(i = 0; i <= numa_max_node(); i++) {
if(!numa_bitmask_isbitset(non_dram_nodes, i)) {
long size = -1;
if ((numa_node_size(i, &size) != -1) && size) {
devices[idx]->tag = SICM_DRAM;
devices[idx]->node = i;
devices[idx]->page_size = normal_page_size;
devices[idx]->data.dram = (struct sicm_dram_data){ };
idx++;
for(j = 0; j < huge_page_size_count; j++) {
devices[idx]->tag = SICM_DRAM;
devices[idx]->node = i;
devices[idx]->page_size = huge_page_sizes[j];
devices[idx]->data.dram = (struct sicm_dram_data){ };
idx++;
}
}
}
}
numa_bitmask_free(compute_nodes);
numa_bitmask_free(non_dram_nodes);
free(huge_page_sizes);
qsort(devices, idx, sizeof(sicm_device *), sicm_device_compare);
sicm_global_devices = (struct sicm_device_list){ .count = idx, .devices = devices };
sicm_default_device(0);
sicm_init_count++;
pthread_mutex_unlock(&sicm_init_count_mutex);
return sicm_global_devices;
}
sicm_device *sicm_default_device(const unsigned int idx) {
if (idx < sicm_global_devices.count) {
sicm_default_device_ptr = sicm_global_devices.devices[idx];
}
return sicm_default_device_ptr;
}
/* Frees memory up */
void sicm_fini() {
pthread_mutex_lock(&sicm_init_count_mutex);
if (sicm_init_count) {
sicm_init_count--;
if (sicm_init_count == 0) {
free(sicm_global_devices.devices);
free(sicm_global_device_array);
memset(&sicm_global_devices, 0, sizeof(sicm_global_devices));
}
}
pthread_mutex_unlock(&sicm_init_count_mutex);
}
void sicm_device_list_free(sicm_device_list *devs) {
if (devs == NULL)
return;
free(devs->devices);
}
sicm_device *sicm_find_device(sicm_device_list *devs, const sicm_device_tag type, const int page_size, sicm_device *old) {
sicm_device *dev = NULL;
if (devs) {
unsigned int i;
for(i = 0; i < devs->count; i++) {
if ((devs->devices[i]->tag == type) &&
((page_size == 0) || (sicm_device_page_size(devs->devices[i]) == page_size)) &&
!sicm_device_eq(devs->devices[i], old)) {
dev = devs->devices[i];
break;
}
}
}
return dev;
}
void* sicm_device_alloc(struct sicm_device* device, size_t size) {
switch(device->tag) {
case SICM_DRAM:
case SICM_KNL_HBM:
case SICM_OPTANE:
case SICM_POWERPC_HBM:; // labels can't be followed by declarations
int page_size = sicm_device_page_size(device);
if(page_size == normal_page_size)
return numa_alloc_onnode(size, sicm_numa_id(device));
else {
int shift = 10; // i.e., 1024
int remaining = page_size;
while(remaining > 1) {
shift++;
remaining >>= 1;
}
int old_mode;
nodemask_t old_nodemask;
get_mempolicy(&old_mode, old_nodemask.n, numa_max_node() + 2, NULL, 0);
nodemask_t nodemask;
nodemask_zero(&nodemask);
nodemask_set_compat(&nodemask, sicm_numa_id(device));
set_mempolicy(MPOL_BIND, nodemask.n, numa_max_node() + 2);
void* ptr = mmap(NULL, size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | (shift << MAP_HUGE_SHIFT), -1, 0);
if(ptr == MAP_FAILED) {
printf("huge page allocation error: %s\n", strerror(errno));
}
set_mempolicy(old_mode, old_nodemask.n, numa_max_node() + 2);
return ptr;
}
case INVALID_TAG:
break;
}
printf("error in sicm_alloc: unknown tag\n");
exit(-1);
}
void* sicm_device_alloc_mmapped(struct sicm_device* device, size_t size, int fd, off_t offset) {
switch(device->tag) {
case SICM_DRAM:
case SICM_KNL_HBM:
case SICM_OPTANE:
case SICM_POWERPC_HBM:; // labels can't be followed by declarations
int page_size = sicm_device_page_size(device);
if(page_size == normal_page_size)
return numa_alloc_onnode(size, sicm_numa_id(device));
else {
int shift = 10; // i.e., 1024
int remaining = page_size;
while(remaining > 1) {
shift++;
remaining >>= 1;
}
int old_mode;
nodemask_t old_nodemask;
get_mempolicy(&old_mode, old_nodemask.n, numa_max_node() + 2, NULL, 0);
nodemask_t nodemask;
nodemask_zero(&nodemask);
nodemask_set_compat(&nodemask, sicm_numa_id(device));
set_mempolicy(MPOL_BIND, nodemask.n, numa_max_node() + 2);
void* ptr = mmap(NULL, size, PROT_READ | PROT_WRITE,
MAP_SHARED, fd, offset);
if(ptr == MAP_FAILED) {
printf("huge page allocation error: %s\n", strerror(errno));
}
set_mempolicy(old_mode, old_nodemask.n, numa_max_node() + 2);
return ptr;
}
case INVALID_TAG:
break;
}
printf("error in sicm_alloc: unknown tag\n");
exit(-1);
}
int sicm_can_place_exact(struct sicm_device* device) {
switch(device->tag) {
case SICM_DRAM:
case SICM_KNL_HBM:
case SICM_OPTANE:
case SICM_POWERPC_HBM:
return 1;
case INVALID_TAG:
break;
}
return 0;
}
void* sicm_alloc_exact(struct sicm_device* device, void* base, size_t size) {
switch(device->tag) {
case SICM_DRAM:
case SICM_KNL_HBM:
case SICM_OPTANE:
case SICM_POWERPC_HBM:; // labels can't be followed by declarations
int page_size = sicm_device_page_size(device);
if(page_size == normal_page_size) {
int old_mode;
nodemask_t old_nodemask;
get_mempolicy(&old_mode, old_nodemask.n, numa_max_node() + 2, NULL, 0);
nodemask_t nodemask;
nodemask_zero(&nodemask);
nodemask_set_compat(&nodemask, sicm_numa_id(device));
set_mempolicy(MPOL_BIND, nodemask.n, numa_max_node() + 2);
void* ptr = mmap(base, size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, -1, 0);
if(ptr == (void*)-1) {
printf("exact allocation error: %s\n", strerror(errno));
}
set_mempolicy(old_mode, old_nodemask.n, numa_max_node() + 2);
return ptr;
}
else {
int shift = 10; // i.e., 1024
int remaining = page_size;
while(remaining > 1) {
shift++;
remaining >>= 1;
}
int old_mode;
nodemask_t old_nodemask;
get_mempolicy(&old_mode, old_nodemask.n, numa_max_node() + 2, NULL, 0);
nodemask_t nodemask;
nodemask_zero(&nodemask);
nodemask_set_compat(&nodemask, sicm_numa_id(device));
set_mempolicy(MPOL_BIND, nodemask.n, numa_max_node() + 2);
void* ptr = mmap(base, size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS | MAP_HUGETLB | (shift << MAP_HUGE_SHIFT), -1, 0);
printf("alloc exact: %p, %p\n", base, ptr);
if(ptr == (void*)-1) {
printf("huge page allocation error: %s\n", strerror(errno));
}
set_mempolicy(old_mode, old_nodemask.n, numa_max_node() + 2);
return ptr;
}
case INVALID_TAG:
break;
}
printf("error in sicm_alloc_exact: unknown tag\n");
exit(-1);
}
void sicm_device_free(struct sicm_device* device, void* ptr, size_t size) {
switch(device->tag) {
case SICM_DRAM:
case SICM_KNL_HBM:
case SICM_OPTANE:
case SICM_POWERPC_HBM:
if(sicm_device_page_size(device) == normal_page_size)
//numa_free(ptr, size);
munmap(ptr, size);
else {
// Huge page allocation occurs in whole page chunks, so we need
// to free (unmap) in whole page chunks.
int page_size = sicm_device_page_size(device);
munmap(ptr, sicm_div_ceil(size, page_size * 1024) * page_size * 1024);
}
break;
case INVALID_TAG:
default:
printf("error in sicm_device_free: unknown tag\n");
exit(-1);
}
}
int sicm_numa_id(struct sicm_device* device) {
return device?device->node:-1;
}
int sicm_device_page_size(struct sicm_device* device) {
return device?device->page_size:-1;
}
int sicm_device_eq(sicm_device* dev1, sicm_device* dev2) {
if (!dev1 || !dev2) {
return 0;
}
if (dev1 == dev2) {
return 1;
}
if (dev1->tag != dev2->tag) {
return 0;
}
if (dev1->node != dev2->node) {
return 0;
}
if (dev1->page_size != dev2->page_size) {
return 0;
}
switch(dev1->tag) {
case SICM_DRAM:
return 1;
case SICM_KNL_HBM:
return
(dev1->data.knl_hbm.compute_node == dev2->data.knl_hbm.compute_node);
case SICM_OPTANE:
return
(dev1->data.optane.compute_node == dev2->data.optane.compute_node);
case SICM_POWERPC_HBM:
return 1;
case INVALID_TAG:
default:
return 0;
}
return 0;
}
int sicm_move(struct sicm_device* src, struct sicm_device* dst, void* ptr, size_t size) {
if(sicm_numa_id(src) >= 0) {
int dst_node = sicm_numa_id(dst);
if(dst_node >= 0) {
nodemask_t nodemask;
nodemask_zero(&nodemask);
nodemask_set_compat(&nodemask, dst_node);
return mbind(ptr, size, MPOL_BIND, nodemask.n, numa_max_node() + 2, MPOL_MF_MOVE);
}
}
return -1;
}
int sicm_pin(struct sicm_device* device) {
int ret = -1;
switch(device->tag) {
case SICM_DRAM:
case SICM_KNL_HBM:
case SICM_OPTANE:
case SICM_POWERPC_HBM:
#pragma omp parallel
ret = numa_run_on_node(device->node);
break;
case INVALID_TAG:
break;
}
return ret;
}
/**
* @input buf - sting with meminfo data
* @input buf_len - length of buffer (buf)
* @input field - field looking for (e.g., "MemFree")
* @inout value - output result found in buf input
*
* @return: -1 (error), 0 (not found), 1 (found)
*
* @Notes:
* - Note this assumes you do not split meminfo lines up,
* or at least the fields you care about are fully contained
* in the input buffer (i.e., not split up between reads and
* get partial line of input in buf).
* - Field names look like "MemTotal"
* - Not very pretty, but gets the correct values from meminfo
* likely needs some more bounds checking (e.g., buf[i]).
*/
static int parse_meminfo(char *buf, int buf_len, char *field, size_t *value)
{
char str[128];
int i;
int found = 0;
if (0 >= buf_len) {
fprintf (stderr, "Error: Bad parameter (bugus buf_len)\n");
return -1;
}
if ((NULL == buf) || (NULL == field) || (NULL == value)) {
fprintf (stderr, "Error: Bad parameter\n");
return -1;
}
for (i=0; i <= buf_len; i++) {
if (buf[i] == field[0]) {
char *s1 = &buf[i];
char *s2 = &field[0];
char tmp[128];
int k=0;
while (*s1++ == *s2++) {
i++;
}
if (buf[i] == ':') {
/* This is our line of info */
/* Move past colon */
i++;
/* Move past blank spaces (careful of buf_len) */
while ((i <= buf_len) && (buf[i] == ' ')) {
i++;
}
/*
* Grab digits before space and units, e.g.,
* Node 0 MemFree: 6348756 kB
*/
while ((i <= buf_len) && (buf[i] != ' ')) {
tmp[k] = buf[i];
k++;
i++;
}
tmp[k] = '\0';
*value = strtol(tmp, NULL, 0);
/* Found, all done. */
found = 1;
break;
}
/* NOT our match, keep looking*/
}
}
return found;
}
size_t sicm_capacity(struct sicm_device* device) {
static const size_t path_len = 100;
char path[path_len];
int i;
switch(device->tag) {
case SICM_DRAM:
case SICM_KNL_HBM:
case SICM_OPTANE:
case SICM_POWERPC_HBM:;
int node = sicm_numa_id(device);
int page_size = sicm_device_page_size(device);
if(page_size == normal_page_size) {
snprintf(path, path_len, "/sys/devices/system/node/node%d/meminfo", node);
int fd = open(path, O_RDONLY);
#if 0
char data[31];
if (read(fd, data, 31) != 31) {
close(fd);
return -1;
}
close(fd);
size_t res = 0;
size_t factor = 1;
for(i = 30; data[i] != ' '; i--) {
res += factor * (data[i] - '0');
factor *= 10;
}
return res;
#else
char data[128];
if (read(fd, data, 128) != 128) {
close(fd);
return -1;
}
close(fd);
size_t res = 0;
int rc = 0;
/* TODO: More testing */
rc = parse_meminfo(data, 128, "MemTotal", &res);
if (rc <= 0) {
fprintf(stderr, "Error: failed to get available memory for node %d\n", node);
return -1;
}
return res;
#endif
}
else {
snprintf(path, path_len, "/sys/devices/system/node/node%d/hugepages/hugepages-%dkB/nr_hugepages", node, page_size);
int fd = open(path, O_RDONLY);
int pages = 0;
char data[10];
while(read(fd, data, 10) > 0) {
for(i = 0; i < 10; i++) {
if(data[i] < '0' || data[i] > '9') break;
pages *= 10;
pages += data[i] - '0';
}
}
close(fd);
return pages * page_size;
}
case INVALID_TAG:
default:
return -1;
}
}
size_t sicm_avail(struct sicm_device* device) {
static const size_t path_len = 100;
char path[path_len];
int i;
switch(device->tag) {
case SICM_DRAM:
case SICM_KNL_HBM:
case SICM_OPTANE:
case SICM_POWERPC_HBM:;
int node = sicm_numa_id(device);
int page_size = sicm_device_page_size(device);
if(page_size == normal_page_size) {
snprintf(path, path_len, "/sys/devices/system/node/node%d/meminfo", node);
int fd = open(path, O_RDONLY);
#if 0
char data[66];
if (read(fd, data, 66) != 66) {
close(fd);
return -1;
}
close(fd);
size_t res = 0;
size_t factor = 1;
for(i = 65; data[i] != ' '; i--) {
res += factor * (data[i] - '0');
factor *= 10;
}
#else
char data[128];
if (read(fd, data, 128) != 128) {
close(fd);
return -1;
}
close(fd);
size_t res = 0;
int rc = 0;
/* TODO: More testing */
rc = parse_meminfo(data, 128, "MemFree", &res);
if (rc <= 0) {
fprintf(stderr, "Error: failed to get available memory for node %d\n", node);
return -1;
}
#endif
return res;
}
else {
snprintf(path, path_len, "/sys/devices/system/node/node%d/hugepages/hugepages-%dkB/free_hugepages", node, page_size);
int fd = open(path, O_RDONLY);
int pages = 0;
char data[10];
while(read(fd, data, 10) > 0) {
for(i = 0; i < 10; i++) {
if(data[i] < '0' || data[i] > '9') break;
pages *= 10;
pages += data[i] - '0';
}
}
close(fd);
return pages * page_size;
}
case INVALID_TAG:
default:
return -1;
}
}
int sicm_model_distance(struct sicm_device* device) {
switch(device->tag) {
case SICM_DRAM:
case SICM_KNL_HBM:
case SICM_OPTANE:
case SICM_POWERPC_HBM:;
int node = sicm_numa_id(device);
return numa_distance(node, numa_node_of_cpu(sched_getcpu()));
case INVALID_TAG:
default:
return -1;
}
}
int sicm_is_near(struct sicm_device* device) {
int dist;
dist = numa_distance(sicm_numa_id(device), numa_node_of_cpu(sched_getcpu()));
switch(device->tag) {
case SICM_DRAM:
return dist == 10;
case SICM_KNL_HBM:
return dist == 31;
case SICM_OPTANE:
return dist == 17;
case SICM_POWERPC_HBM:
return dist == 80;
case INVALID_TAG:
default:
return 0;
}
}
void sicm_latency(struct sicm_device* device, size_t size, int iter, struct sicm_timing* res) {
struct timespec start, end;
int i;
char b = 0;
unsigned int n = time(NULL);
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
char* blob = sicm_device_alloc(device, size);
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
res->alloc = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_nsec - start.tv_nsec) / 1000;
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
for(i = 0; i < iter; i++) {
sicm_rand(n);
blob[n % size] = 0;
}
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
res->write = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_nsec - start.tv_nsec) / 1000;
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
for(i = 0; i < iter; i++) {
sicm_rand(n);
b = blob[n % size];
}
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
// Write it back so hopefully it won't compile away the read
blob[0] = b;
res->read = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_nsec - start.tv_nsec) / 1000;
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
sicm_device_free(device, blob, size);
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
res->free = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_nsec - start.tv_nsec) / 1000;
}
size_t sicm_bandwidth_linear2(struct sicm_device* device, size_t size,
size_t (*kernel)(double*, double*, size_t)) {
struct timespec start, end;
double* a = sicm_device_alloc(device, size * sizeof(double));
double* b = sicm_device_alloc(device, size * sizeof(double));
unsigned int i;
#pragma omp parallel for
for(i = 0; i < size; i++) {
a[i] = 1;
b[i] = 2;
}
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
size_t accesses = kernel(a, b, size);
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
size_t delta = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_nsec - start.tv_nsec) / 1000;
sicm_device_free(device, a, size * sizeof(double));
sicm_device_free(device, b, size * sizeof(double));
return accesses / delta;
}
size_t sicm_bandwidth_random2(struct sicm_device* device, size_t size,
size_t (*kernel)(double*, double*, size_t*, size_t)) {
struct timespec start, end;
double* a = sicm_device_alloc(device, size * sizeof(double));
double* b = sicm_device_alloc(device, size * sizeof(double));
size_t* indexes = sicm_device_alloc(device, size * sizeof(size_t));
unsigned int i;
#pragma omp parallel for
for(i = 0; i < size; i++) {
a[i] = 1;
b[i] = 2;
indexes[i] = sicm_hash(i) % size;
}
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
size_t accesses = kernel(a, b, indexes, size);
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
size_t delta = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_nsec - start.tv_nsec) / 1000;
sicm_device_free(device, a, size * sizeof(double));
sicm_device_free(device, b, size * sizeof(double));
sicm_device_free(device, indexes, size * sizeof(size_t));
return accesses / delta;
}
size_t sicm_bandwidth_linear3(struct sicm_device* device, size_t size,
size_t (*kernel)(double*, double*, double*, size_t)) {
struct timespec start, end;
double* a = sicm_device_alloc(device, 3 * size * sizeof(double));
double* b = &a[size];
double* c = &a[size * 2];
unsigned int i;
#pragma omp parallel for
for(i = 0; i < size; i++) {
a[i] = 1;
b[i] = 2;
c[i] = 3;
}
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
size_t accesses = kernel(a, b, c, size);
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
size_t delta = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_nsec - start.tv_nsec) / 1000;
sicm_device_free(device, a, 3 * size * sizeof(double));
return accesses / delta;
}
size_t sicm_bandwidth_random3(struct sicm_device* device, size_t size,
size_t (*kernel)(double*, double*, double*, size_t*, size_t)) {
struct timespec start, end;
double* a = sicm_device_alloc(device, size * sizeof(double));
double* b = sicm_device_alloc(device, size * sizeof(double));
double* c = sicm_device_alloc(device, size * sizeof(double));
size_t* indexes = sicm_device_alloc(device, size * sizeof(size_t));
unsigned int i;
#pragma omp parallel for
for(i = 0; i < size; i++) {
a[i] = 1;
b[i] = 2;
c[i] = 3;
indexes[i] = sicm_hash(i) % size;
}
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
size_t accesses = kernel(a, b, c, indexes, size);
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
size_t delta = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_nsec - start.tv_nsec) / 1000;
sicm_device_free(device, a, size * sizeof(double));
sicm_device_free(device, b, size * sizeof(double));
sicm_device_free(device, c, size * sizeof(double));
sicm_device_free(device, indexes, size * sizeof(size_t));
return accesses / delta;
}
size_t sicm_triad_kernel_linear(double* a, double* b, double* c, size_t size) {
int i;
double scalar = 3.0;
#pragma omp parallel for
for(i = 0; i < size; i++) {
a[i] = b[i] + scalar * c[i];
}
return size * 3 * sizeof(double);
}
size_t sicm_triad_kernel_random(double* a, double* b, double* c, size_t* indexes, size_t size) {
int i, idx;
double scalar = 3.0;
#pragma omp parallel for
for(i = 0; i < size; i++) {
idx = indexes[i];
a[idx] = b[idx] + scalar * c[idx];
}
return size * (sizeof(size_t) + 3 * sizeof(double));
}
|
decorate.c
|
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% DDDD EEEEE CCCC OOO RRRR AAA TTTTT EEEEE %
% D D E C O O R R A A T E %
% D D EEE C O O RRRR AAAAA T EEE %
% D D E C O O R R A A T E %
% DDDD EEEEE CCCC OOO R R A A T EEEEE %
% %
% %
% MagickCore Image Decoration Methods %
% %
% Software Design %
% John Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2011 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/cache-view.h"
#include "magick/color-private.h"
#include "magick/colorspace-private.h"
#include "magick/composite.h"
#include "magick/decorate.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel-private.h"
#include "magick/quantum.h"
#include "magick/thread-private.h"
#include "magick/transform.h"
/*
Define declarations.
*/
#define AccentuateModulate ScaleCharToQuantum(80)
#define HighlightModulate ScaleCharToQuantum(125)
#define ShadowModulate ScaleCharToQuantum(135)
#define DepthModulate ScaleCharToQuantum(185)
#define TroughModulate ScaleCharToQuantum(110)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% B o r d e r I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% BorderImage() surrounds the image with a border of the color defined by
% the bordercolor member of the image structure. The width and height
% of the border are defined by the corresponding members of the border_info
% structure.
%
% The format of the BorderImage method is:
%
% Image *BorderImage(const Image *image,const RectangleInfo *border_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o border_info: Define the width and height of the border.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *BorderImage(const Image *image,
const RectangleInfo *border_info,ExceptionInfo *exception)
{
Image
*border_image,
*clone_image;
FrameInfo
frame_info;
assert(image != (const Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(border_info != (RectangleInfo *) NULL);
frame_info.width=image->columns+(border_info->width << 1);
frame_info.height=image->rows+(border_info->height << 1);
frame_info.x=(ssize_t) border_info->width;
frame_info.y=(ssize_t) border_info->height;
frame_info.inner_bevel=0;
frame_info.outer_bevel=0;
clone_image=CloneImage(image,0,0,MagickTrue,exception);
if (clone_image == (Image *) NULL)
return((Image *) NULL);
clone_image->matte_color=image->border_color;
border_image=FrameImage(clone_image,&frame_info,exception);
clone_image=DestroyImage(clone_image);
if (border_image != (Image *) NULL)
border_image->matte_color=image->matte_color;
return(border_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F r a m e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FrameImage() adds a simulated three-dimensional border around the image.
% The color of the border is defined by the matte_color member of image.
% Members width and height of frame_info specify the border width of the
% vertical and horizontal sides of the frame. Members inner and outer
% indicate the width of the inner and outer shadows of the frame.
%
% The format of the FrameImage method is:
%
% Image *FrameImage(const Image *image,const FrameInfo *frame_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o frame_info: Define the width and height of the frame and its bevels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *FrameImage(const Image *image,const FrameInfo *frame_info,
ExceptionInfo *exception)
{
#define FrameImageTag "Frame/Image"
CacheView
*image_view,
*frame_view;
Image
*frame_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
accentuate,
border,
highlight,
interior,
matte,
shadow,
trough;
register ssize_t
x;
size_t
bevel_width,
height,
width;
ssize_t
y;
/*
Check frame geometry.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(frame_info != (FrameInfo *) NULL);
if ((frame_info->outer_bevel < 0) || (frame_info->inner_bevel < 0))
ThrowImageException(OptionError,"FrameIsLessThanImageSize");
bevel_width=(size_t) (frame_info->outer_bevel+frame_info->inner_bevel);
width=frame_info->width-frame_info->x-bevel_width;
height=frame_info->height-frame_info->y-bevel_width;
if ((width < image->columns) || (height < image->rows))
ThrowImageException(OptionError,"FrameIsLessThanImageSize");
/*
Initialize framed image attributes.
*/
frame_image=CloneImage(image,frame_info->width,frame_info->height,MagickTrue,
exception);
if (frame_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(frame_image,DirectClass) == MagickFalse)
{
InheritException(exception,&frame_image->exception);
frame_image=DestroyImage(frame_image);
return((Image *) NULL);
}
if (frame_image->matte_color.opacity != OpaqueOpacity)
frame_image->matte=MagickTrue;
frame_image->page=image->page;
if ((image->page.width != 0) && (image->page.height != 0))
{
frame_image->page.width+=frame_image->columns-image->columns;
frame_image->page.height+=frame_image->rows-image->rows;
}
/*
Initialize 3D effects color.
*/
GetMagickPixelPacket(frame_image,&interior);
SetMagickPixelPacket(frame_image,&image->border_color,(IndexPacket *) NULL,
&interior);
GetMagickPixelPacket(frame_image,&matte);
matte.colorspace=RGBColorspace;
SetMagickPixelPacket(frame_image,&image->matte_color,(IndexPacket *) NULL,
&matte);
GetMagickPixelPacket(frame_image,&border);
border.colorspace=RGBColorspace;
SetMagickPixelPacket(frame_image,&image->border_color,(IndexPacket *) NULL,
&border);
GetMagickPixelPacket(frame_image,&accentuate);
accentuate.red=(MagickRealType) (QuantumScale*((QuantumRange-
AccentuateModulate)*matte.red+(QuantumRange*AccentuateModulate)));
accentuate.green=(MagickRealType) (QuantumScale*((QuantumRange-
AccentuateModulate)*matte.green+(QuantumRange*AccentuateModulate)));
accentuate.blue=(MagickRealType) (QuantumScale*((QuantumRange-
AccentuateModulate)*matte.blue+(QuantumRange*AccentuateModulate)));
accentuate.opacity=matte.opacity;
GetMagickPixelPacket(frame_image,&highlight);
highlight.red=(MagickRealType) (QuantumScale*((QuantumRange-
HighlightModulate)*matte.red+(QuantumRange*HighlightModulate)));
highlight.green=(MagickRealType) (QuantumScale*((QuantumRange-
HighlightModulate)*matte.green+(QuantumRange*HighlightModulate)));
highlight.blue=(MagickRealType) (QuantumScale*((QuantumRange-
HighlightModulate)*matte.blue+(QuantumRange*HighlightModulate)));
highlight.opacity=matte.opacity;
GetMagickPixelPacket(frame_image,&shadow);
shadow.red=QuantumScale*matte.red*ShadowModulate;
shadow.green=QuantumScale*matte.green*ShadowModulate;
shadow.blue=QuantumScale*matte.blue*ShadowModulate;
shadow.opacity=matte.opacity;
GetMagickPixelPacket(frame_image,&trough);
trough.red=QuantumScale*matte.red*TroughModulate;
trough.green=QuantumScale*matte.green*TroughModulate;
trough.blue=QuantumScale*matte.blue*TroughModulate;
trough.opacity=matte.opacity;
if (image->colorspace == CMYKColorspace)
{
ConvertRGBToCMYK(&interior);
ConvertRGBToCMYK(&matte);
ConvertRGBToCMYK(&border);
ConvertRGBToCMYK(&accentuate);
ConvertRGBToCMYK(&highlight);
ConvertRGBToCMYK(&shadow);
ConvertRGBToCMYK(&trough);
}
status=MagickTrue;
progress=0;
image_view=AcquireCacheView(image);
frame_view=AcquireCacheView(frame_image);
height=(size_t) (frame_info->outer_bevel+(frame_info->y-bevel_width)+
frame_info->inner_bevel);
if (height != 0)
{
register IndexPacket
*restrict frame_indexes;
register ssize_t
x;
register PixelPacket
*restrict q;
/*
Draw top of ornamental border.
*/
q=QueueCacheViewAuthenticPixels(frame_view,0,0,frame_image->columns,
height,exception);
frame_indexes=GetCacheViewAuthenticIndexQueue(frame_view);
if (q != (PixelPacket *) NULL)
{
/*
Draw top of ornamental border.
*/
for (y=0; y < (ssize_t) frame_info->outer_bevel; y++)
{
for (x=0; x < (ssize_t) (frame_image->columns-y); x++)
{
if (x < y)
SetPixelPacket(frame_image,&highlight,q,frame_indexes);
else
SetPixelPacket(frame_image,&accentuate,q,frame_indexes);
q++;
frame_indexes++;
}
for ( ; x < (ssize_t) frame_image->columns; x++)
{
SetPixelPacket(frame_image,&shadow,q,frame_indexes);
q++;
frame_indexes++;
}
}
for (y=0; y < (ssize_t) (frame_info->y-bevel_width); y++)
{
for (x=0; x < (ssize_t) frame_info->outer_bevel; x++)
{
SetPixelPacket(frame_image,&highlight,q,frame_indexes);
q++;
frame_indexes++;
}
width=frame_image->columns-2*frame_info->outer_bevel;
for (x=0; x < (ssize_t) width; x++)
{
SetPixelPacket(frame_image,&matte,q,frame_indexes);
q++;
frame_indexes++;
}
for (x=0; x < (ssize_t) frame_info->outer_bevel; x++)
{
SetPixelPacket(frame_image,&shadow,q,frame_indexes);
q++;
frame_indexes++;
}
}
for (y=0; y < (ssize_t) frame_info->inner_bevel; y++)
{
for (x=0; x < (ssize_t) frame_info->outer_bevel; x++)
{
SetPixelPacket(frame_image,&highlight,q,frame_indexes);
q++;
frame_indexes++;
}
for (x=0; x < (ssize_t) (frame_info->x-bevel_width); x++)
{
SetPixelPacket(frame_image,&matte,q,frame_indexes);
q++;
frame_indexes++;
}
width=image->columns+((size_t) frame_info->inner_bevel << 1)-
y;
for (x=0; x < (ssize_t) width; x++)
{
if (x < y)
SetPixelPacket(frame_image,&shadow,q,frame_indexes);
else
SetPixelPacket(frame_image,&trough,q,frame_indexes);
q++;
frame_indexes++;
}
for ( ; x < (ssize_t) (image->columns+2*frame_info->inner_bevel); x++)
{
SetPixelPacket(frame_image,&highlight,q,frame_indexes);
q++;
frame_indexes++;
}
width=frame_info->width-frame_info->x-image->columns-bevel_width;
for (x=0; x < (ssize_t) width; x++)
{
SetPixelPacket(frame_image,&matte,q,frame_indexes);
q++;
frame_indexes++;
}
for (x=0; x < (ssize_t) frame_info->outer_bevel; x++)
{
SetPixelPacket(frame_image,&shadow,q,frame_indexes);
q++;
frame_indexes++;
}
}
(void) SyncCacheViewAuthenticPixels(frame_view,exception);
}
}
/*
Draw sides of ornamental border.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic,4) shared(progress,status) omp_throttle(1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*restrict frame_indexes;
register ssize_t
x;
register PixelPacket
*restrict q;
/*
Initialize scanline with matte color.
*/
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(frame_view,0,frame_info->y+y,
frame_image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
frame_indexes=GetCacheViewAuthenticIndexQueue(frame_view);
for (x=0; x < (ssize_t) frame_info->outer_bevel; x++)
{
SetPixelPacket(frame_image,&highlight,q,frame_indexes);
q++;
frame_indexes++;
}
for (x=0; x < (ssize_t) (frame_info->x-bevel_width); x++)
{
SetPixelPacket(frame_image,&matte,q,frame_indexes);
q++;
frame_indexes++;
}
for (x=0; x < (ssize_t) frame_info->inner_bevel; x++)
{
SetPixelPacket(frame_image,&shadow,q,frame_indexes);
q++;
frame_indexes++;
}
/*
Set frame interior to interior color.
*/
if ((image->compose != CopyCompositeOp) &&
((image->compose != OverCompositeOp) || (image->matte != MagickFalse)))
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelPacket(frame_image,&interior,q,frame_indexes);
q++;
frame_indexes++;
}
else
{
register const IndexPacket
*indexes;
register const PixelPacket
*p;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
(void) CopyMagickMemory(q,p,image->columns*sizeof(*p));
if ((image->colorspace == CMYKColorspace) &&
(frame_image->colorspace == CMYKColorspace))
{
(void) CopyMagickMemory(frame_indexes,indexes,image->columns*
sizeof(*indexes));
frame_indexes+=image->columns;
}
q+=image->columns;
}
for (x=0; x < (ssize_t) frame_info->inner_bevel; x++)
{
SetPixelPacket(frame_image,&highlight,q,frame_indexes);
q++;
frame_indexes++;
}
width=frame_info->width-frame_info->x-image->columns-bevel_width;
for (x=0; x < (ssize_t) width; x++)
{
SetPixelPacket(frame_image,&matte,q,frame_indexes);
q++;
frame_indexes++;
}
for (x=0; x < (ssize_t) frame_info->outer_bevel; x++)
{
SetPixelPacket(frame_image,&shadow,q,frame_indexes);
q++;
frame_indexes++;
}
if (SyncCacheViewAuthenticPixels(frame_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_FrameImage)
#endif
proceed=SetImageProgress(image,FrameImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
height=(size_t) (frame_info->inner_bevel+frame_info->height-
frame_info->y-image->rows-bevel_width+frame_info->outer_bevel);
if (height != 0)
{
register IndexPacket
*restrict frame_indexes;
register ssize_t
x;
register PixelPacket
*restrict q;
/*
Draw bottom of ornamental border.
*/
q=QueueCacheViewAuthenticPixels(frame_view,0,(ssize_t) (frame_image->rows-
height),frame_image->columns,height,exception);
if (q != (PixelPacket *) NULL)
{
/*
Draw bottom of ornamental border.
*/
frame_indexes=GetCacheViewAuthenticIndexQueue(frame_view);
for (y=frame_info->inner_bevel-1; y >= 0; y--)
{
for (x=0; x < (ssize_t) frame_info->outer_bevel; x++)
{
SetPixelPacket(frame_image,&highlight,q,frame_indexes);
q++;
frame_indexes++;
}
for (x=0; x < (ssize_t) (frame_info->x-bevel_width); x++)
{
SetPixelPacket(frame_image,&matte,q,frame_indexes);
q++;
frame_indexes++;
}
for (x=0; x < y; x++)
{
SetPixelPacket(frame_image,&shadow,q,frame_indexes);
q++;
frame_indexes++;
}
for ( ; x < (ssize_t) (image->columns+2*frame_info->inner_bevel); x++)
{
if (x >= (ssize_t) (image->columns+2*frame_info->inner_bevel-y))
SetPixelPacket(frame_image,&highlight,q,frame_indexes);
else
SetPixelPacket(frame_image,&accentuate,q,frame_indexes);
q++;
frame_indexes++;
}
width=frame_info->width-frame_info->x-image->columns-bevel_width;
for (x=0; x < (ssize_t) width; x++)
{
SetPixelPacket(frame_image,&matte,q,frame_indexes);
q++;
frame_indexes++;
}
for (x=0; x < (ssize_t) frame_info->outer_bevel; x++)
{
SetPixelPacket(frame_image,&shadow,q,frame_indexes);
q++;
frame_indexes++;
}
}
height=frame_info->height-frame_info->y-image->rows-bevel_width;
for (y=0; y < (ssize_t) height; y++)
{
for (x=0; x < (ssize_t) frame_info->outer_bevel; x++)
{
SetPixelPacket(frame_image,&highlight,q,frame_indexes);
q++;
frame_indexes++;
}
width=frame_image->columns-2*frame_info->outer_bevel;
for (x=0; x < (ssize_t) width; x++)
{
SetPixelPacket(frame_image,&matte,q,frame_indexes);
q++;
frame_indexes++;
}
for (x=0; x < (ssize_t) frame_info->outer_bevel; x++)
{
SetPixelPacket(frame_image,&shadow,q,frame_indexes);
q++;
frame_indexes++;
}
}
for (y=frame_info->outer_bevel-1; y >= 0; y--)
{
for (x=0; x < y; x++)
{
SetPixelPacket(frame_image,&highlight,q,frame_indexes);
q++;
frame_indexes++;
}
for ( ; x < (ssize_t) frame_image->columns; x++)
{
if (x >= (ssize_t) (frame_image->columns-y))
SetPixelPacket(frame_image,&shadow,q,frame_indexes);
else
SetPixelPacket(frame_image,&trough,q,frame_indexes);
q++;
frame_indexes++;
}
}
(void) SyncCacheViewAuthenticPixels(frame_view,exception);
}
}
frame_view=DestroyCacheView(frame_view);
image_view=DestroyCacheView(image_view);
if ((image->compose != CopyCompositeOp) &&
((image->compose != OverCompositeOp) || (image->matte != MagickFalse)))
{
x=(ssize_t) (frame_info->outer_bevel+(frame_info->x-bevel_width)+
frame_info->inner_bevel);
y=(ssize_t) (frame_info->outer_bevel+(frame_info->y-bevel_width)+
frame_info->inner_bevel);
(void) CompositeImage(frame_image,image->compose,image,x,y);
}
return(frame_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R a i s e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RaiseImage() creates a simulated three-dimensional button-like effect
% by lightening and darkening the edges of the image. Members width and
% height of raise_info define the width of the vertical and horizontal
% edge of the effect.
%
% The format of the RaiseImage method is:
%
% MagickBooleanType RaiseImage(const Image *image,
% const RectangleInfo *raise_info,const MagickBooleanType raise)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o raise_info: Define the width and height of the raise area.
%
% o raise: A value other than zero creates a 3-D raise effect,
% otherwise it has a lowered effect.
%
*/
MagickExport MagickBooleanType RaiseImage(Image *image,
const RectangleInfo *raise_info,const MagickBooleanType raise)
{
#define AccentuateFactor ScaleCharToQuantum(135)
#define HighlightFactor ScaleCharToQuantum(190)
#define ShadowFactor ScaleCharToQuantum(190)
#define RaiseImageTag "Raise/Image"
#define TroughFactor ScaleCharToQuantum(135)
CacheView
*image_view;
ExceptionInfo
*exception;
MagickBooleanType
status;
MagickOffsetType
progress;
Quantum
foreground,
background;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(raise_info != (RectangleInfo *) NULL);
if ((image->columns <= (raise_info->width << 1)) ||
(image->rows <= (raise_info->height << 1)))
ThrowBinaryException(OptionError,"ImageSizeMustExceedBevelWidth",
image->filename);
foreground=(Quantum) QuantumRange;
background=(Quantum) 0;
if (raise == MagickFalse)
{
foreground=(Quantum) 0;
background=(Quantum) QuantumRange;
}
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
/*
Raise image.
*/
status=MagickTrue;
progress=0;
exception=(&image->exception);
image_view=AcquireCacheView(image);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic,4) shared(progress,status) omp_throttle(1)
#endif
for (y=0; y < (ssize_t) raise_info->height; y++)
{
register ssize_t
x;
register PixelPacket
*restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < y; x++)
{
SetPixelRed(q,ClampToQuantum(QuantumScale*((MagickRealType)
GetPixelRed(q)*HighlightFactor+(MagickRealType) foreground*
(QuantumRange-HighlightFactor))));
SetPixelGreen(q,ClampToQuantum(QuantumScale*((MagickRealType)
GetPixelGreen(q)*HighlightFactor+(MagickRealType) foreground*
(QuantumRange-HighlightFactor))));
SetPixelBlue(q,ClampToQuantum(QuantumScale*((MagickRealType)
GetPixelBlue(q)*HighlightFactor+(MagickRealType) foreground*
(QuantumRange-HighlightFactor))));
q++;
}
for ( ; x < (ssize_t) (image->columns-y); x++)
{
SetPixelRed(q,ClampToQuantum(QuantumScale*((MagickRealType)
GetPixelRed(q)*AccentuateFactor+(MagickRealType) foreground*
(QuantumRange-AccentuateFactor))));
SetPixelGreen(q,ClampToQuantum(QuantumScale*((MagickRealType)
GetPixelGreen(q)*AccentuateFactor+(MagickRealType) foreground*
(QuantumRange-AccentuateFactor))));
SetPixelBlue(q,ClampToQuantum(QuantumScale*((MagickRealType)
GetPixelBlue(q)*AccentuateFactor+(MagickRealType) foreground*
(QuantumRange-AccentuateFactor))));
q++;
}
for ( ; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ClampToQuantum(QuantumScale*((MagickRealType)
GetPixelRed(q)*ShadowFactor+(MagickRealType) background*
(QuantumRange-ShadowFactor))));
SetPixelGreen(q,ClampToQuantum(QuantumScale*((MagickRealType)
GetPixelGreen(q)*ShadowFactor+(MagickRealType) background*
(QuantumRange-ShadowFactor))));
SetPixelBlue(q,ClampToQuantum(QuantumScale*((MagickRealType)
GetPixelBlue(q)*ShadowFactor+(MagickRealType) background*
(QuantumRange-ShadowFactor))));
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,RaiseImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic,4) shared(progress,status) omp_throttle(1)
#endif
for (y=(ssize_t) raise_info->height; y < (ssize_t) (image->rows-raise_info->height); y++)
{
register ssize_t
x;
register PixelPacket
*restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) raise_info->width; x++)
{
SetPixelRed(q,ClampToQuantum(QuantumScale*((MagickRealType)
GetPixelRed(q)*HighlightFactor+(MagickRealType) foreground*
(QuantumRange-HighlightFactor))));
SetPixelGreen(q,ClampToQuantum(QuantumScale*((MagickRealType)
GetPixelGreen(q)*HighlightFactor+(MagickRealType) foreground*
(QuantumRange-HighlightFactor))));
SetPixelBlue(q,ClampToQuantum(QuantumScale*((MagickRealType)
GetPixelBlue(q)*HighlightFactor+(MagickRealType) foreground*
(QuantumRange-HighlightFactor))));
q++;
}
for ( ; x < (ssize_t) (image->columns-raise_info->width); x++)
q++;
for ( ; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ClampToQuantum(QuantumScale*((MagickRealType)
GetPixelRed(q)*ShadowFactor+(MagickRealType) background*
(QuantumRange-ShadowFactor))));
SetPixelGreen(q,ClampToQuantum(QuantumScale*((MagickRealType)
GetPixelGreen(q)*ShadowFactor+(MagickRealType) background*
(QuantumRange-ShadowFactor))));
SetPixelBlue(q,ClampToQuantum(QuantumScale*((MagickRealType)
GetPixelBlue(q)*ShadowFactor+(MagickRealType) background*
(QuantumRange-ShadowFactor))));
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,RaiseImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic,4) shared(progress,status) omp_throttle(1)
#endif
for (y=(ssize_t) (image->rows-raise_info->height); y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register PixelPacket
*restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) (image->rows-y); x++)
{
SetPixelRed(q,ClampToQuantum(QuantumScale*((MagickRealType)
GetPixelRed(q)*HighlightFactor+(MagickRealType) foreground*
(QuantumRange-HighlightFactor))));
SetPixelGreen(q,ClampToQuantum(QuantumScale*((MagickRealType)
GetPixelGreen(q)*HighlightFactor+(MagickRealType) foreground*
(QuantumRange-HighlightFactor))));
SetPixelBlue(q,ClampToQuantum(QuantumScale*((MagickRealType)
GetPixelBlue(q)*HighlightFactor+(MagickRealType) foreground*
(QuantumRange-HighlightFactor))));
q++;
}
for ( ; x < (ssize_t) (image->columns-(image->rows-y)); x++)
{
SetPixelRed(q,ClampToQuantum(QuantumScale*((MagickRealType)
GetPixelRed(q)*TroughFactor+(MagickRealType) background*
(QuantumRange-TroughFactor))));
SetPixelGreen(q,ClampToQuantum(QuantumScale*((MagickRealType)
GetPixelGreen(q)*TroughFactor+(MagickRealType) background*
(QuantumRange-TroughFactor))));
SetPixelBlue(q,ClampToQuantum(QuantumScale*((MagickRealType)
GetPixelBlue(q)*TroughFactor+(MagickRealType) background*
(QuantumRange-TroughFactor))));
q++;
}
for ( ; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ClampToQuantum(QuantumScale*((MagickRealType)
GetPixelRed(q)*ShadowFactor+(MagickRealType) background*
(QuantumRange-ShadowFactor))));
SetPixelGreen(q,ClampToQuantum(QuantumScale*((MagickRealType)
GetPixelGreen(q)*ShadowFactor+(MagickRealType) background*
(QuantumRange-ShadowFactor))));
SetPixelBlue(q,ClampToQuantum(QuantumScale*((MagickRealType)
GetPixelBlue(q)*ShadowFactor+(MagickRealType) background*
(QuantumRange-ShadowFactor))));
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_RaiseImage)
#endif
proceed=SetImageProgress(image,RaiseImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
|
solvers.h
|
#ifndef SOLVERS_H
#define SOLVERS_H
#include "loss.h"
#include "regul.h"
#include "list.h"
#define USING_SOLVER \
typedef typename loss_type::variable_type D; \
typedef typename loss_type::value_type T; \
typedef typename loss_type::index_type I;\
typedef loss_type LT; \
using Solver<loss_type>::_L; \
using Solver<loss_type>::_loss; \
using Solver<loss_type>::_regul; \
using Solver<loss_type>::_Li; \
using Solver<loss_type>::_verbose; \
using Solver<loss_type>::_max_iter_backtracking;
#define USING_INCREMENTAL_SOLVER \
USING_SOLVER; \
using IncrementalSolver<loss_type>::_minibatch; \
using IncrementalSolver<loss_type>::_non_uniform_sampling; \
using IncrementalSolver<loss_type>::_n; \
using IncrementalSolver<loss_type>::_qi;
#define USING_SVRG_SOLVER \
USING_INCREMENTAL_SOLVER; \
using SVRG_Solver<loss_type>::_xtilde;\
using SVRG_Solver<loss_type>::_gtilde;
#define USING_ACC_SVRG_SOLVER \
using Acc_SVRG_Solver<loss_type,allow_acc>::_y;\
using Acc_SVRG_Solver<loss_type,allow_acc>::_etak;\
using Acc_SVRG_Solver<loss_type,allow_acc>::_gammak;\
using Acc_SVRG_Solver<loss_type,allow_acc>::_mu;\
using Acc_SVRG_Solver<loss_type,allow_acc>::_deltak;\
using Acc_SVRG_Solver<loss_type,allow_acc>::_thetak;\
using Acc_SVRG_Solver<loss_type,allow_acc>::_accelerated_solver;\
USING_SVRG_SOLVER;
enum solver_t { ISTA, CATALYST_ISTA, QNING_ISTA, FISTA, SAGA, SVRG, SVRG_UNIFORM, CATALYST_SVRG, ACC_SVRG, MISO, CATALYST_MISO, QNING_SVRG, QNING_MISO, AUTO, INCORRECT_SOLVER };
solver_t solver_from_string(char* regul) {
if (strcmp(regul,"ista")==0) return ISTA;
if (strcmp(regul,"catalyst-ista")==0) return CATALYST_ISTA;
if (strcmp(regul,"qning-ista")==0) return QNING_ISTA;
if (strcmp(regul,"fista")==0) return FISTA;
if (strcmp(regul,"saga")==0) return SAGA;
if (strcmp(regul,"svrg")==0) return SVRG;
if (strcmp(regul,"catalyst-svrg")==0) return CATALYST_SVRG;
if (strcmp(regul,"qning-svrg")==0) return QNING_SVRG;
if (strcmp(regul,"qning-miso")==0) return QNING_MISO;
if (strcmp(regul,"acc-svrg")==0) return ACC_SVRG;
if (strcmp(regul,"miso")==0) return MISO;
if (strcmp(regul,"catalyst-miso")==0) return CATALYST_MISO;
if (strcmp(regul,"svrg-uniform")==0) return SVRG_UNIFORM;
if (strcmp(regul,"auto")==0) return AUTO;
return INCORRECT_SOLVER;
}
template <typename T> struct ParamSolver {
ParamSolver() { nepochs=100; it0=10; tol=T(1e-3); verbose=false; solver=FISTA;
max_iter_backtracking=500; minibatch=1; threads=-1; non_uniform_sampling=true; l_memory=20; freq_restart=50; };
int nepochs;
T tol;
int it0;
bool verbose;
solver_t solver;
int max_iter_backtracking;
int minibatch;
int threads;
bool non_uniform_sampling;
int l_memory;
int freq_restart;
};
template <typename loss_type>
class Solver {
public:
typedef typename loss_type::variable_type D;
typedef typename loss_type::value_type T;
typedef typename loss_type::index_type I;
Solver(const loss_type& loss, const Regularizer<D,I>& regul, const
ParamSolver<T>& param) : _loss(loss), _regul(regul) {
_verbose=param.verbose;
_it0=MAX(param.it0,1);
_tol=param.tol;
_nepochs=param.nepochs;
_max_iter_backtracking=param.max_iter_backtracking;
_best_dual=-INFINITY;
_best_primal=INFINITY;
_duality = _loss.provides_fenchel() && regul.provides_fenchel();
_optim_info.resize(6,MAX(param.nepochs/_it0,1));
_L=0;
};
virtual ~Solver() { };
virtual void solve(const D& x0, D& x) {
_time.start();
x.copy(x0);
if (!_duality && _nepochs > 1) _xold.copy(x0);
solver_init(x0);
if (_verbose) {
cout << "*********************************" << endl;
print();
_loss.print();
_regul.print();
}
for (int it = 1; it<=_nepochs; ++it) {
if ((it % _it0) == 0)
if (test_stopping_criterion(x,it))
break;
solver_aux(x);
}
_time.stop();
if (_verbose)
_time.printElapsed();
if (_best_primal != INFINITY) x.copy(_bestx);
}
void get_optim_info(Matrix<T>& optim) const {
int count=0;
for (int ii=0; ii<_optim_info.n(); ++ii)
if (_optim_info(0,ii) != 0) ++count;
if (count > 0) {
optim.resize(6,count);
}
for (int ii=0; ii<count; ++ii)
for (int jj=0; jj<6; ++jj)
optim(jj,ii)=_optim_info(jj,ii);
};
void eval(const D& x) {
test_stopping_criterion(x,1);
_optim_info(5,0)=0;
};
virtual void set_dual_variable(const D& dual0) { };
virtual void save_state() { };
virtual void restore_state() { };
private:
inline T get_dual(const D& x) const {
if (!_regul.provides_fenchel() || !_loss.provides_fenchel()) {
cerr << "Error: no duality gap available" << endl;
return -INFINITY;
}
D grad1, grad2;
_loss.get_dual_variable(x,grad1,grad2);
const T dual = - _regul.fenchel(grad1,grad2);
return dual - _loss.fenchel(grad1);
};
inline bool test_stopping_criterion(const D& x, const int it) {
const T primal =_loss.eval(x) + _regul.eval(x);
_best_primal = MIN(_best_primal,primal);
const int ii=MAX(it/_it0-1,0);
const double sec = _time.getElapsed();
Vector<T> optim;
_optim_info.refCol(ii,optim);
if (_best_primal == primal)
_bestx.copy(x);
if (_verbose) {
if (primal==_best_primal) {
cout << "Epoch: " << it << ", primal objective: " << primal << ", time: " << sec << endl;
} else {
cout << "Epoch: " << it << ", primal objective: " << primal << ", best primal: " << _best_primal << ", time: " << sec << endl;
}
}
optim[0]=it; optim[1]=primal; optim[5]=sec;
if (_duality) {
const T dual=get_dual(x);
_best_dual=MAX(_best_dual,dual);
const T duality_gap=(_best_primal-_best_dual)/abs<T>(_best_primal);
if (_verbose)
cout << "Best relative duality gap: " << duality_gap << endl;
optim[2]=_best_dual; optim[3]=duality_gap;
return duality_gap < _tol;
} else {
_xold.sub(x);
const T diff=sqrt(_xold.nrm2sq()/MAX(EPSILON,x.nrm2sq()));
_xold.copy(x);
optim[4]=diff;
return diff < _tol;
}
}
protected:
virtual void solver_init(const D& x0) = 0;
virtual void solver_aux(D& x) = 0;
virtual void print() const = 0;
virtual int minibatch() const { return 1; };
bool _verbose;
int _it0;
int _nepochs;
int _max_iter_backtracking;
int _restart_frequency;
T _tol;
const loss_type& _loss;
const Regularizer<D,I>& _regul;
Timer _time;
T _best_dual;
T _best_primal;
Matrix<T> _optim_info;
bool _duality;
D _xold;
T _L;
D _bestx;
Vector<T> _Li;
};
template <typename loss_type>
class ISTA_Solver: public Solver<loss_type> {
public:
USING_SOLVER;
ISTA_Solver(const loss_type& loss, const Regularizer<D,I>& regul, const ParamSolver<T>& param, const Vector<T>* Li=NULL) : Solver<loss_type>(loss,regul,param) {
_L=0;
if (Li) {
_Li.copy(*Li);
_L = _Li.maxval()/100;
}
};
protected:
virtual void solver_init(const D& x0) {
if (_L==0) {
_loss.lipschitz(_Li);
_L = _Li.maxval()/100;
}
};
virtual void solver_aux(D& x) {
int iter=1;
const T fx = _loss.eval(x);
D grad, tmp, tmp2;
_loss.grad(x,grad);
while (iter < _max_iter_backtracking) {
tmp2.copy(x);
tmp2.add(grad,-T(1.0)/_L);
_regul.prox(tmp2,tmp,T(1.0)/_L);
const T fprox = _loss.eval(tmp);
tmp2.copy(tmp);
tmp2.sub(x);
if (fprox <= fx + grad.dot(tmp2) + T(0.5)*_L*tmp2.nrm2sq() + EPSILON) {
x.copy(tmp);
break;
}
_L *= T(1.5);
if (_verbose)
cout << "new value for L: " << _L << endl;
++iter;
if (iter == _max_iter_backtracking)
cout << "Warning: maximum number of backtracking iterations has been reached" << endl;
}
};
void print() const {
cout << "ISTA Solver" << endl;
};
T init_kappa_acceleration(const D& x0) {
ISTA_Solver<loss_type>::solver_init(x0);
return _L;
};
};
template <typename loss_type>
class FISTA_Solver final: public ISTA_Solver<loss_type> {
public:
USING_SOLVER;
FISTA_Solver(const loss_type& loss, const Regularizer<D,I>& regul, const ParamSolver<T>& param) : ISTA_Solver<loss_type>(loss,regul,param) { };
protected:
virtual void solver_init(const D& x0) {
ISTA_Solver<loss_type>::solver_init(x0);
_t = T(1.0);
_y.copy(x0);
};
virtual void solver_aux(D& x) {
ISTA_Solver<loss_type>::solver_aux(_y);
D diff;
diff.copy(x);
x.copy(_y);
diff.sub(x);
const T old_t=_t;
_t=(1.0+sqrt(1+4*_t*_t))/2;
_y.add(diff,(T(1.0)-old_t)/_t);
};
virtual void print() const {
cout << "FISTA Solver" << endl;
};
T _t;
D _y;
};
template <typename loss_type>
class IncrementalSolver: public Solver<loss_type> {
public:
USING_SOLVER;
IncrementalSolver(const loss_type& loss, const Regularizer<D,I>& regul, const ParamSolver<T>& param, const Vector<T>* Li=NULL) : Solver<loss_type>(loss,regul,param) {
_minibatch=param.minibatch;
_non_uniform_sampling=param.non_uniform_sampling;
if (Li) _Li.copy(*Li);
};
protected:
virtual void solver_init(const D& x0) {
if (_Li.n() == 0)
_loss.lipschitz(_Li);
_n=_Li.n();
if (_L==0) {
_qi.copy(_Li);
_qi.scal(T(1.0)/_qi.sum());
const T Lmean = _Li.mean();
const T Lmax = _Li.maxval();
_non_uniform_sampling = (_non_uniform_sampling && Lmean <= T(0.9)*Lmax);
_L = _non_uniform_sampling ? Lmean : Lmax;
if (_minibatch > 1)
heuristic_L(x0);
_oldL=_L;
if (_non_uniform_sampling)
init_nonu_sampling();
}
this->check_mkl(x0);
};
void print() const {
cout << "Incremental Solver ";
if (_non_uniform_sampling) {
cout << "with non uniform sampling" << endl;
} else {
cout << "with uniform sampling" << endl;
}
cout << "Lipschitz constant: " << _L << endl;
};
bool _non_uniform_sampling;
int _minibatch;
int _n;
Vector<T> _qi;
Vector<double> _Ui;
Vector<int> _Ki;
T _oldL;
void init_nonu_sampling() {
_Ui.resize(_n);
for (int ii=0; ii<_n; ++ii) _Ui[ii]=static_cast<double>(_qi[ii]);
_Ui.scal(_n/_Ui.asum());
_Ki.resize(_n);
_Ki.set(0);
List<int> overfull;
List<int> underfull;
for (int ii=0; ii<_n; ++ii) {
if (_Ui[ii] < double(1.0)) {
underfull.push_back(ii);
} else if (_Ui[ii] > double(1.0)) {
overfull.push_back(ii);
}
}
while (underfull.size() > 0 && overfull.size() > 0) {
const int indj = underfull.front();
underfull.pop_front();
const int indi = overfull.front();
overfull.pop_front();
_Ki[indj]=indi;
_Ui[indi]=_Ui[indi] + _Ui[indj] - double(1.0);
if (_Ui[indi] < double(1.0)) {
underfull.push_back(indi);
} else if (_Ui[indi] > double(1.0)) {
overfull.push_back(indi);
}
}
};
int nonu_sampling() {
const double x = static_cast<double>(random()-1)/RAND_MAX;
const int ind = static_cast<int>(floor(_n*x))+1;
const double y = _n*x+1-ind;
if (y < _Ui[ind-1]) return ind-1;
return _Ki[ind-1];
};
virtual int minibatch() const { return _minibatch; };
T init_kappa_acceleration(const D& x0) {
IncrementalSolver<loss_type>::solver_init(x0);
const T mu = _regul.strong_convexity();
return ((this->_oldL/(_n) - mu));
};
void check_mkl(const Vector<T>& x0) const { };
void check_mkl(const Matrix<T>& x0) const {
if (x0.m() <= 15 || x0.n() <= 15) {
set_mkl_sequential(); // TODO should be local
}
};
private:
void heuristic_L(const D& x) {
if (_verbose)
cout << "Heuristic: Initial L=" << _L;
const T Lmax=_L;
_L /= _minibatch;
int iter=0;
D tmp, tmp2, grad;
while (iter <= log(_minibatch)/log(2.0) && _L < Lmax) {
tmp.copy(x);
const T fx=_loss.eval_random_minibatch(tmp,_minibatch);
_loss.grad_random_minibatch(tmp,grad,_minibatch); // should do non uniform
// compute grad and fx
tmp.add(grad,-T(1.0)/_L);
const T ftmp=_loss.eval_random_minibatch(tmp,_minibatch);
tmp2.copy(tmp);
tmp2.sub(x);
const T s1 =fx + grad.dot(tmp2);
const T s2=T(0.5)*tmp2.nrm2sq();
if (ftmp > s1 + _L*s2)
_L = MIN( MAX(2.0*_L, (ftmp-s1)/s2),Lmax);
++iter;
}
if (_verbose)
cout << ", Final L=" << _L << endl;
}
};
template <typename loss_type>
class SVRG_Solver: public IncrementalSolver<loss_type> {
public:
USING_INCREMENTAL_SOLVER;
SVRG_Solver(const loss_type& loss, const Regularizer<D,I>& regul, const ParamSolver<T>& param, const Vector<T>* Li=NULL) : IncrementalSolver<loss_type>(loss,regul,param,Li) {
};
protected:
virtual void solver_init(const D& x0) {
IncrementalSolver<loss_type>::solver_init(x0);
_xtilde.copy(x0);
_loss.grad(_xtilde,_gtilde);
};
virtual void solver_aux(D& x) {
const int nn = _n/_minibatch;
const T eta = T(1.0)/(3*_L);
D tmp;
for (int ii = 0; ii<nn; ++ii) {
tmp.copy(x);
tmp.add(_gtilde,-eta);
for (int jj=0; jj<_minibatch; ++jj) {
const int ind = _non_uniform_sampling ? this->nonu_sampling() : random() % _n;
const T scal = _non_uniform_sampling ? T(1.0)/(_minibatch*_qi[ind]*_n) : T(1.0)/_minibatch;
_loss.double_add_grad(x,_xtilde,ind,tmp,-scal*eta,scal*eta, jj==0 ? T(_minibatch) : 0);
}
_regul.prox(tmp,x,eta);
if (random() % nn == 0) {
_xtilde.copy(x);
_loss.grad(_xtilde,_gtilde);
}
}
};
void print() const {
cout << "SVRG Solver" << endl;
IncrementalSolver<loss_type>::print();
};
D _xtilde, _gtilde;
};
template <typename loss_type>
class MISO_Solver: public IncrementalSolver<loss_type> {
public:
USING_INCREMENTAL_SOLVER;
MISO_Solver(const loss_type& loss, const Regularizer<D,I>& regul, const ParamSolver<T>& param, const Vector<T>* Li=NULL) : IncrementalSolver<loss_type>(loss,regul,param,Li) {
_minibatch=1;
_mu= _regul.id() == L2 ? _regul.strong_convexity() : 0;
_kappa = _loss.kappa();
if (_loss.id() == PPA) _mu += _kappa;
_isprox=(_regul.id() != L2 || _regul.intercept()) && _regul.id() != NONE;
_is_lazy = _isprox && _regul.is_lazy() && _loss.is_sparse();
_extern_zis=false;
_count=0;
};
virtual void set_dual_variable(const D& dual0) {
_extern_zis=true;
_zis.copyRef(dual0);
};
virtual void solve(const D& y, D& x) {
if (_count > 0 && (_count % 10) != 0) {
D& ref_barz = _isprox ? _barz : x;
ref_barz.add(_oldy,-_kappa/_mu); // necessary to have PPA loss here
ref_barz.add(y,_kappa/_mu);
const bool is_lazy = _isprox && _regul.is_lazy() && _loss.is_sparse();
if (_isprox && !is_lazy)
_regul.prox(ref_barz,x,T(1.0)/_mu);
} else if (_count==0) {
x.copy(y); // just to have the right size
}
if (_loss.id()==PPA)
_loss.get_anchor_point(_oldy);
Solver<loss_type>::solve(x,x);
};
virtual void save_state() {
_count2=_count;
_barz2.copy(_barz);
_zis2.copy(_zis);
_oldy2.copy(_oldy);
};
virtual void restore_state() {
_count=_count2;
_barz.copy(_barz2);
_zis.copy(_zis2);
_oldy.copy(_oldy2);
};
protected:
virtual void solver_init(const D& x0) {
// initial point will be in fact _z of PPA
if (_count==0) {
IncrementalSolver<loss_type>::solver_init(x0);
_delta=MIN(T(1.0), _n*_mu/(2*_L));
if (_non_uniform_sampling) {
const T beta=T(0.5)*_mu*_n;
if (this->_Li.maxval() <= beta) {
_non_uniform_sampling=false;
_delta=T(1.0);
} else if (this->_Li.minval() >= beta) {
// no change
} else {
_qi.copy(this->_Li);
_qi.thrsmax(beta);
_qi.scal(T(1.0)/_qi.sum());
Vector<T> tmp;
tmp.copy(_qi);
tmp.inv();
tmp.mult(tmp,this->_Li);
_L = tmp.maxval()/_n;
this->init_nonu_sampling();
_delta=MIN(_n*_qi.minval(), _n*_mu/(2*_L));
}
}
if (_non_uniform_sampling)
_delta=MIN(_delta,_n*_qi.minval());
if (_isprox)
_barz.copy(x0); // if PPA, x0 should be the anchor point and _barz = X*_Zis + x0
init_dual_variables(x0);
}
};
virtual void solver_aux(D& x) {
D& ref_barz = _isprox ? _barz : x;
if (_count++ % 10 == 0) {
if (_loss.id()==PPA) {
_loss.get_anchor_point(ref_barz);
ref_barz.scal(_kappa/_mu);
} else {
ref_barz.setZeros();
}
if (_count > 1 || _extern_zis) _loss.add_feature(_zis,ref_barz,T(1.0)/(_n*_mu));
if (_isprox && !_is_lazy)
_regul.prox(ref_barz,x,T(1.0)/_mu);
}
Vector<typename loss_type::index_type> indices;
for (int ii = 0; ii<_n; ++ii) {
const int ind = _non_uniform_sampling ? this->nonu_sampling() : random() % _n;
const T scal = _non_uniform_sampling ? T(1.0)/(_qi[ind]*_n) : T(1.0);
const T deltas=scal*_delta;
if (_is_lazy) {
_loss.get_coordinates(ind,indices);
_regul.lazy_prox(ref_barz,x,indices,T(1.0)/_mu);
}
solver_aux_aux(x,ref_barz,ind,deltas);
if (_isprox && (!_is_lazy || ii==_n-1))
_regul.prox(ref_barz,x,T(1.0)/_mu);
}
};
void print() const {
cout << "MISO Solver" << endl;
IncrementalSolver<loss_type>::print();
};
private:
D _zis, _zis2;
D _barz, _barz2;
D _oldy, _oldy2;
T _mu;
T _kappa;
T _delta;
int _count, _count2;
bool _perform_update_barz;
bool _isprox, _is_lazy,_extern_zis;
void inline init_dual_variables(const Vector<T>& x0) {
if (_zis.n() != _n) {
_zis.resize(_n);
_zis.setZeros();
}
}
void inline init_dual_variables(const Matrix<T>& x0) {
const int nclasses=_loss.transpose() ? x0.m() : x0.n();
if (_zis.n() != _n || _zis.m() != nclasses) {
_zis.resize(nclasses,_n);
_zis.setZeros();
}
}
void inline solver_aux_aux(const Vector<T>& x,Vector<T>& ref_barz,const int ind, const T deltas) {
const T oldzi = _zis[ind];
_zis[ind] = (T(1.0)-deltas)*_zis[ind] + deltas*(-_loss.scal_grad(x,ind));
_loss.add_feature(ref_barz,ind,(_zis[ind]-oldzi)/(_n*_mu));
};
void inline solver_aux_aux(const Matrix<T>& x, Matrix<T>& ref_barz,const int ind, const T deltas) {
Vector<T> oldzi, newzi;
_zis.copyCol(ind,oldzi);
_zis.refCol(ind,newzi);
_loss.scal_grad(x,ind,newzi);
newzi.add_scal(oldzi,T(1.0)-deltas,-deltas);
oldzi.sub(newzi);
oldzi.scal(-T(1.0)/(_n*_mu));
_loss.add_feature(ref_barz,ind,oldzi);
};
};
template <typename SolverType>
class Catalyst : public SolverType {
public:
typedef typename SolverType::LT loss_type;
USING_SOLVER
Catalyst(const loss_type& loss, const Regularizer<D,I>& regul, const ParamSolver<T>& param) : SolverType(loss,regul,param) {
_auxiliary_solver=NULL;
_loss_ppa=NULL;
_accelerated_solver=true;
_freq_restart=regul.strong_convexity() > 0 ? param.nepochs+2 : param.freq_restart;
};
~Catalyst() {
if(_auxiliary_solver) delete(_auxiliary_solver);
if(_loss_ppa) delete(_loss_ppa);
};
virtual void set_dual_variable(const D& dual0) {
_dual_var.copyRef(dual0);
};
protected:
virtual void solver_init(const D& x0) {
_kappa = this->init_kappa_acceleration(x0);
_mu = _regul.strong_convexity();
_count=0;
_accelerated_solver=_kappa > 0; //this->_oldL/(_n) >= _mu;
if (_accelerated_solver) {
ParamSolver<T> param2;
param2.nepochs=1;
param2.it0=2;
param2.verbose=false;
param2.minibatch=this->minibatch();
this->_Li.add(_kappa);
_loss_ppa = new ProximalPointLoss<loss_type>(_loss,x0,_kappa);
_auxiliary_solver = new SolverType(*_loss_ppa,_regul,param2,&this->_Li);
if (_dual_var.size() > 0)
_auxiliary_solver->set_dual_variable(_dual_var);
_y.copy(x0);
_alpha=T(1.0);
} else {
if (_verbose)
cout << "Switching to regular solver, problem is well conditioned" << endl;
SolverType::solver_init(x0);
}
};
virtual void solver_aux(D& x) {
if (_accelerated_solver) {
const T q = _mu/(_mu+_kappa);
D xold;
xold.copy(x);
_auxiliary_solver->solve(_y,x);
const T alphaold=_alpha;
_alpha = solve_binomial(T(1.0),_alpha*_alpha-q,-_alpha*_alpha);
T beta= alphaold*(T(1.0)-alphaold)/(alphaold*alphaold+_alpha);
if (++_count % _freq_restart == 0) {
beta=0;
_alpha=T(1.0);
}
_y.copy(xold);
_y.add_scal(x,T(1.0)+beta,-beta);
_loss_ppa->set_anchor_point(_y);
} else {
SolverType::solver_aux(x);
}
};
void print() const {
cout << "Catalyst Accelerator" << endl;
SolverType::print();
};
int _count, _freq_restart;
T _kappa, _alpha, _mu;
D _y, _dual_var;
bool _accelerated_solver;
SolverType* _auxiliary_solver;
ProximalPointLoss<loss_type>* _loss_ppa;
};
template <typename SolverType>
class QNing final: public Catalyst<SolverType> {
public:
typedef typename SolverType::LT loss_type;
USING_SOLVER
using Catalyst<SolverType>::_kappa;
using Catalyst<SolverType>::_accelerated_solver;
using Catalyst<SolverType>::_auxiliary_solver;
using Catalyst<SolverType>::_loss_ppa;
using Catalyst<SolverType>::_y;
QNing(const loss_type& loss, const Regularizer<D,I>& regul, const
ParamSolver<T>& param) : Catalyst<SolverType>(loss,regul,param),
_l_memory(param.l_memory) {
_skipping_steps=0;
_line_search_steps=0;
};
virtual void solve(const D& x0, D& x) {
Solver<loss_type>::solve(x0,x);
if (_verbose)
cout << "Total additional line search steps: " << _line_search_steps << endl;
if (_verbose)
cout << "Total skipping l-bfgs steps: " << _skipping_steps << endl;
};
protected:
virtual void solver_init(const D& x0) {
Catalyst<SolverType>::solver_init(x0);
if (_accelerated_solver) {
_h0=T(1.0)/_kappa;
_m=0;
if (_verbose)
cout << "Memory parameter: " << _l_memory << endl;
_ys.resize(x0.size(),_l_memory);
_ss.resize(x0.size(),_l_memory);
_rhos.resize(_l_memory);
_etak=T(1.0);
_skipping_steps=0;
_line_search_steps=0;
}
};
virtual void solver_aux(D& x) {
if (_accelerated_solver) {
if (_gk.size() == 0)
get_gradient(x);
// update variable _y and test
D oldyk; oldyk.copy(_y);
D oldxk; oldxk.copy(x);
T oldFk=_Fk;
D oldgk; oldgk.copy(_gk);
D g; get_lbfgs_direction(g);
const int max_iter=5;
_auxiliary_solver->save_state();
for (int ii=1; ii<=max_iter; ++ii) {
_y.copy(oldyk);
_y.add(g,-_etak);
_y.add(oldgk,-(T(1.0)-_etak)/_kappa);
get_gradient(x); // _gk = kappa(x-y)
if (_etak == 0 || _Fk <= oldFk - (T(0.25)/_kappa)*oldgk.nrm2sq()) break;
if (_Fk > 1.05*oldFk) {
_auxiliary_solver->restore_state();
x.copy(oldxk);
}
_etak /= 2;
_line_search_steps++;
if (ii==max_iter-1 || _etak < T(0.1)) {
_etak=0;
}
}
if (_Fk > 1.05*oldFk) {
_auxiliary_solver->restore_state();
x.copy(oldxk);
reset_lbfgs();
} else {
oldyk.add_scal(_y,T(1.0),-T(1.0));
oldgk.add_scal(_gk,T(1.0),-T(1.0));
update_lbfgs_matrix(oldyk,oldgk);
}
_etak=MAX(MIN(T(1.0),_etak*T(1.2)),T(0.1));
} else {
SolverType::solver_aux(x);
}
};
void print() const {
cout << "QNing Accelerator" << endl;
SolverType::print();
};
private:
inline void get_lbfgs_direction(Vector<T>& g) const {
g.copy(_gk);
get_lbfgs_direction_aux(g);
};
inline void get_lbfgs_direction(Matrix<T>& g) const {
g.copy(_gk);
Vector<T> gg;
g.toVect(gg);
get_lbfgs_direction_aux(gg);
};
inline void get_lbfgs_direction_aux(Vector<T>& g) const {
// two-loop recursion algorithm
Vector<T> alphas(_l_memory);
Vector<T> cols, coly;
T gamma=T(1.0)/_kappa;
for (int ii = _m-1; ii>= MAX(_m-_l_memory,0); --ii) {
const int ind = ii % _l_memory;
_ss.refCol(ind,cols);
_ys.refCol(ind,coly);
if (ii==_m-1)
gamma=cols.dot(coly)/coly.nrm2sq();
alphas[ind]=_rhos[ind]*cols.dot(g);
g.add(coly,-alphas[ind]);
}
g.scal(gamma);
for (int ii = MAX(_m-_l_memory,0); ii<= _m-1; ++ii) {
const int ind = ii % _l_memory;
_ss.refCol(ind,cols);
_ys.refCol(ind,coly);
const T beta = _rhos[ind]*coly.dot(g);
g.add(cols,alphas[ind]-beta);
}
};
inline void update_lbfgs_matrix(const Matrix<T>& sk, const Matrix<T>& yk) {
Vector<T> skk, ykk;
sk.toVect(skk);
yk.toVect(ykk);
update_lbfgs_matrix(skk,ykk);
};
inline void update_lbfgs_matrix(const Vector<T>& sk, const Vector<T>& yk) {
const T theta=sk.dot(yk);
if (theta > T(1e-12)) {
Vector<T> coly, cols;
const int ind=_m % _l_memory;
_ys.refCol(ind,coly); coly.copy(yk);
_ss.refCol(ind,cols); cols.copy(sk);
_rhos[ind]=T(1.0)/theta;
_m++;
} else {
_skipping_steps++;
//if (_skipping_steps % 10 == 0)
// reset_lbfgs();
}
};
void reset_lbfgs() {
_m=0;
};
void get_gradient(D& x) {
_loss_ppa->set_anchor_point(_y);
_auxiliary_solver->solve(_y,x);
_gk.copy(_y);
_gk.add_scal(x,-_kappa,_kappa);
_Fk=_loss_ppa->eval(x)+_regul.eval(x);
};
T _h0;
int _l_memory;
INTM _m;
Matrix<T> _ys, _ss;
Vector<T> _rhos;
D _gk, _xk;
T _Fk;
T _etak;
int _skipping_steps, _line_search_steps;
};
template <typename loss_type, bool allow_acc = true>
class Acc_SVRG_Solver: public SVRG_Solver<loss_type> {
public:
USING_SVRG_SOLVER;
Acc_SVRG_Solver(const loss_type& loss, const Regularizer<D,I>& regul, const
ParamSolver<T>& param, const Vector<T>* Li=NULL) : SVRG_Solver<loss_type>(loss,regul,param,Li) {
_accelerated_solver=allow_acc;
};
virtual void solver_init(const D& x0) {
IncrementalSolver<loss_type>::solver_init(x0);
_mu = _regul.strong_convexity();
_nn=_n/_minibatch;
_accelerated_solver=allow_acc && (T(20)*this->_oldL/_nn > _mu);
if (_accelerated_solver) {
_gammak = MAX(_L/(_nn),_mu);
update_acceleration_parameters();
_xtilde.copy(x0);
_y.copy(x0);
_loss.grad(_xtilde,_gtilde);
} else {
if (_verbose && allow_acc)
cout << "Problem is well conditioned, switching to regular solver" << endl;
SVRG_Solver<loss_type>::solver_init(x0);
}
};
virtual void solver_aux(D& x) {
if (_accelerated_solver) {
for (int ii=0; ii<_nn; ++ii) {
x.copy(_y);
x.add(_gtilde,-_etak);
for (int jj=0; jj<_minibatch; ++jj) {
const int ind = _non_uniform_sampling ? this->nonu_sampling() : random() % _n;
const T scal = _non_uniform_sampling ? T(1.0)/(_qi[ind]*_n*_minibatch) : T(1.0)/_minibatch;
_loss.double_add_grad(_y,_xtilde,ind,x,-scal*_etak,scal*_etak);
}
_regul.prox(x,x,_etak);
const T alphak=_mu*_deltak/_gammak;
const T betak=_deltak/(_gammak*_etak);
const T a=(T(1.0)-alphak)/_thetak + alphak;
update_acceleration_parameters();
if (random() % _nn == 0) {
_y.add_scal(_xtilde,(T(1.0)-a)*_thetak,_thetak*(a-betak));
_y.add(x,betak*_thetak + T(1.0)-_thetak);
_xtilde.copy(x);
_loss.grad(_xtilde,_gtilde);
} else {
_y.add_scal(_xtilde,T(1.0)-_thetak*a,_thetak*(a-betak));
_y.add(x,betak*_thetak);
}
};
} else {
SVRG_Solver<loss_type>::solver_aux(x);
}
};
protected:
void print() const {
cout << "Accelerated SVRG Solver" << endl;
if (!_accelerated_solver)
cout << "Problem is well conditioned, switching to regular solver" << endl;
IncrementalSolver<loss_type>::print();
};
bool _accelerated_solver;
T _gammak, _mu, _deltak, _etak, _thetak;
D _y;
int _nn;
void update_acceleration_parameters() {
_deltak = MIN( solve_binomial(T(9.0)*_nn*_L/T(5.0), _gammak-_mu, -_gammak), T(1.0)/(3*_nn));
_gammak = (T(1.0)-_deltak)*_gammak+_mu*_deltak;
_etak = MIN(T(1.0)/(3*_L), T(1.0)/(15*_gammak*_nn));
_thetak=(3*_nn*_deltak-5*_mu*_etak)/(3-5*_mu*_etak);
};
};
template <typename loss_type, bool allow_acc=true>
class SVRG_Solver_FastRidge: public Acc_SVRG_Solver< loss_type, allow_acc > {
public:
USING_ACC_SVRG_SOLVER;
SVRG_Solver_FastRidge(const loss_type& loss, const Regularizer<D,I>& regul, const
ParamSolver<T>& param, const Vector<T>* Li = NULL) : Acc_SVRG_Solver<loss_type,allow_acc>(loss,regul,param,Li),
_is_lazy(loss_type::is_sparse()) {
if (param.minibatch > 1)
cerr << "Minibatch is not compatible with lazy updates" << endl;
_minibatch=1;
};
virtual void solver_init(const D& x0) {
Acc_SVRG_Solver<loss_type,allow_acc>::solver_init(x0);
if (_loss.id() == PPA) {
const T kappa = _loss.kappa();
_gtilde.add(_xtilde,-kappa);// now gtilde has the right value
}
};
/// define auxiliary solver ?
virtual void solver_aux(D& x) {
if (_accelerated_solver) {
const T lambda=_regul.lambda();
DoubleLazyVector<T,I>* lazyy = NULL;
Vector<I> indices;
if (_is_lazy) {
lazyy=new DoubleLazyVector<T,I>(_y,_xtilde,_gtilde,_n);
}
for (int ii=0; ii<_n; ++ii) {
const T alphak=_mu*_deltak/_gammak;
const T betak=_deltak/(_gammak*_etak);
const T a=(T(1.0)-alphak)/_thetak + alphak;
const T scalprox = T(1.0)/(T(1.0)+lambda*_etak);
const T eta=_etak;
const int ind = _non_uniform_sampling ? this->nonu_sampling() : random() % _n;
const T scaleta = _non_uniform_sampling ? eta/(_qi[ind]*_n) : eta;
this->update_acceleration_parameters();
const bool update_xtilde = random() % _n == 0;
const T coeffy=_thetak*(a-betak);
const T coeffx= update_xtilde ? betak*_thetak + T(1.0)-_thetak :betak*_thetak;
const T coeffxtilde = update_xtilde ? (T(1.0)-a)*_thetak : T(1.0)-_thetak*a;
if (update_xtilde || ii==_n-1) {
if (_is_lazy) lazyy->update();
x.copy(_y);
_loss.double_add_grad(_y,_xtilde,ind,x,-scaleta,scaleta);
x.add_scal(_gtilde,-scalprox*eta,scalprox);
_y.add_scal(_xtilde,coeffxtilde,coeffy);
_y.add(x,coeffx);
} else {
const T coeff_add_grad=scaleta * scalprox*coeffx/(coeffy+scalprox*coeffx);
if (_is_lazy) {
_loss.get_coordinates(ind, indices);
lazyy->update(indices);
}
_loss.double_add_grad(_y,_xtilde,ind,_y,-coeff_add_grad,coeff_add_grad);
if (_is_lazy) {
lazyy->add_scal(coeffxtilde,-scalprox*eta*coeffx,coeffy+scalprox*coeffx);
} else {
_y.add_scal(_gtilde,-scalprox*eta*coeffx,coeffy+scalprox*coeffx);
_y.add(_xtilde,coeffxtilde);
}
}
if (update_xtilde) {
_xtilde.copy(x);
_loss.grad(_xtilde,_gtilde);
}
};
if (_is_lazy)
delete(lazyy);
} else if (_loss.id() == PPA) {
/// we will optimize implicitly f(xtilde) - kappa <x , z> + (mu+kappa)/2|x|^2
/// meaning, we want gtilde to be Df(xtilde) - kappa z
LazyVector<T,I>* lazyx = NULL;
Vector<I> indices;
if (_is_lazy) {
//indices.resize(x.n());
lazyx=new LazyVector<T,I>(x,_gtilde,_n);
}
const T eta = T(1.0)/(3*(_L-_loss.kappa()));
const T lambda=_regul.lambda()+_loss.kappa(); // take care of 0.5(mu+kappa)|x|^2,
for (int ii = 0; ii<_n; ++ii) {
const int ind = _non_uniform_sampling ? this->nonu_sampling() : random() % _n;
const T scal = _non_uniform_sampling ? T(1.0)/(_qi[ind]*_n) : T(1.0);
if (_is_lazy) {
_loss.get_coordinates(ind, indices);
lazyx->update(indices);
_loss.double_add_grad(x,_xtilde,ind,x,-scal*eta,scal*eta,0);
lazyx->add_scal(-eta,T(1.0)/(T(1.0)+eta*lambda));
} else {
_loss.double_add_grad(x,_xtilde,ind,x,-scal*eta,scal*eta,0); // x <- x - s( D_i f(x) - D_i f(xtilde))
x.add_scal(_gtilde,-eta/(T(1.0)+eta*lambda),T(1.0)/(T(1.0)+eta*lambda));
}
if (random() % _n == 0) {
if (_is_lazy) lazyx->update();
_xtilde.copy(x);
_loss.grad(_xtilde,_gtilde);// gtilde will be equal to Df(xtilde) + kappa (xtilde- z)
_gtilde.add(_xtilde,-_loss.kappa());// now gtilde has the right value
}
}
if (_is_lazy) {
lazyx->update();
delete(lazyx);
}
} else {
LazyVector<T,I>* lazyx = NULL;
Vector<I> indices;
if (_is_lazy) {
//indices.resize(x.n());
lazyx=new LazyVector<T,I>(x,_gtilde,_n);
}
const T eta = T(1.0)/(3*_L);
const T lambda=_regul.lambda(); // replace by lazyprox ?
for (int ii = 0; ii<_n; ++ii) {
const int ind = _non_uniform_sampling ? this->nonu_sampling() : random() % _n;
const T scal = _non_uniform_sampling ? T(1.0)/(_qi[ind]*_n) : T(1.0);
if (_is_lazy) {
_loss.get_coordinates(ind, indices);
lazyx->update(indices);
_loss.double_add_grad(x,_xtilde,ind,x,-scal*eta,scal*eta);
lazyx->add_scal(-eta,T(1.0)/(T(1.0)+eta*lambda)); // replace by lazyprox ?
} else {
_loss.double_add_grad(x,_xtilde,ind,x,-scal*eta,scal*eta);
x.add_scal(_gtilde,-eta/(T(1.0)+eta*lambda),T(1.0)/(T(1.0)+eta*lambda));
}
if (random() % _n == 0) {
if (_is_lazy) lazyx->update();
_xtilde.copy(x);
_loss.grad(_xtilde,_gtilde);
}
}
if (_is_lazy) {
lazyx->update();
delete(lazyx);
}
}
};
protected:
void print() const {
if (_accelerated_solver) {
cout << "Accelerated SVRG Solver, ";
} else {
cout << "SVRG Solver, ";
}
if (_is_lazy) {
cout << "specialized for sparse matrices and L2 regularization" << endl;
} else {
cout << "specialized for L2 regularization" << endl;
}
IncrementalSolver<loss_type>::print();
};
private:
const bool _is_lazy;
};
template <typename loss_type>
Solver<loss_type>* get_solver(const loss_type& loss, const Regularizer<typename loss_type::variable_type, typename loss_type::index_type>& regul, const ParamSolver<typename loss_type::value_type>& param) {
typedef typename loss_type::value_type T;
Solver<loss_type>* solver;
solver_t solver_type=param.solver;
if (solver_type==AUTO) {
const T L=loss.lipschitz();
const int n = loss.n();
const T lambda=regul.strong_convexity();
if (n < 1000) {
solver_type=QNING_ISTA;
} else if (lambda < L/(100*n)) {
solver_type=QNING_MISO;
} else {
solver_type=CATALYST_MISO;
}
}
switch (solver_type) {
case ISTA: solver= new ISTA_Solver<loss_type>(loss,regul,param); break;
case QNING_ISTA: solver = new QNing< ISTA_Solver<loss_type> >(loss,regul,param); break;
case CATALYST_ISTA: solver = new Catalyst< ISTA_Solver<loss_type> >(loss,regul,param); break;
case FISTA: solver= new FISTA_Solver<loss_type>(loss,regul,param); break;
case SVRG: solver= new SVRG_Solver<loss_type>(loss,regul,param); break;
case MISO: solver= regul.strong_convexity() > 0 ?
new MISO_Solver<loss_type>(loss,regul,param) :
new Catalyst< MISO_Solver<loss_type> >(loss,regul,param);
break;
case SVRG_UNIFORM: {
ParamSolver<typename loss_type::value_type> param2=param;
param2.non_uniform_sampling=false;
solver= new SVRG_Solver<loss_type>(loss,regul,param2); break;
}
case CATALYST_SVRG: solver = new Catalyst< SVRG_Solver<loss_type> >(loss,regul,param); break;
case QNING_SVRG: solver = new QNing< SVRG_Solver<loss_type> >(loss,regul,param); break;
case CATALYST_MISO: solver = new Catalyst< MISO_Solver<loss_type> >(loss,regul,param); break;
case QNING_MISO: solver = new QNing< MISO_Solver<loss_type> >(loss,regul,param); break;
case ACC_SVRG: solver = new Acc_SVRG_Solver<loss_type>(loss,regul,param); break;
default: cerr << "Not implemented, performs nothing"; solver=NULL;
}
return solver;
};
template <typename M>
void simple_erm(const M& X, const Vector<typename M::value_type>& y, const Vector<typename M::value_type>& w0, Vector<typename M::value_type>& w, Vector<typename M::value_type>& dual_variable, Matrix<typename M::value_type>& optim_info, const ParamSolver<typename M::value_type>& param, const ParamModel<typename M::value_type>& model) {
init_omp(param.threads);
typedef typename M::value_type T;
typedef typename M::index_type I;
typedef Vector<T> D;
typedef LinearLossVec<M> loss_type;
if (model.intercept) {
if (X.m()+1 != w0.n()) {
cerr << "Dimension of initial point is not consistent. With intercept, if X is m x n, w0 should be (n+1)-dimensional." << endl;
return;
}
} else {
if (X.m() != w0.n()) {
cerr << "Dimension of initial point is not consistent. If X is m x n, w0 should be n-dimensional." << endl;
return;
}
}
DataLinear<M> data(X,model.intercept);
if (param.verbose)
data.print();
LinearLossVec<M>* loss;
switch (model.loss) {
case SQUARE: loss = new SquareLoss<M>(data,y); break;
case LOGISTIC: loss = new LogisticLoss<M>(data,y); break;
case SQHINGE: loss = new SquaredHingeLoss<M>(data,y); break;
//case HINGE: loss = new HingeLoss<M>(data,y); break;
case SAFE_LOGISTIC: loss = new SafeLogisticLoss<M>(data,y); break;
default: cerr << "Not implemented, square loss is chosen by default";
loss = new SquareLoss<M>(data,y);
}
Regularizer<D,I>* regul;
switch(model.regul) {
case L2: regul = new Ridge<D,I>(model); break;
case L1: regul = new Lasso<D,I>(model); break;
case L1BALL: regul = new L1Ball<D,I>(model); break;
case L2BALL: regul = new L2Ball<D,I>(model); break;
case FUSEDLASSO: regul = new FusedLasso<D,I>(model); break;
case ELASTICNET: regul = new ElasticNet<D,I>(model); break;
case NONE: regul = new None<D,I>(model); break;
default: cerr << "Not implemented, no regularization is chosen";
regul = new None<D,I>(model);
}
Solver<loss_type>* solver;
if (param.nepochs==0) {
ParamSolver<typename D::value_type> param2=param;
param2.verbose=false;
solver= new ISTA_Solver<loss_type>(*loss,*regul,param2);
solver->eval(w0);
w.copy(w0);
} else {
if (param.solver==SVRG && model.regul==L2 && !model.intercept) {
solver= new SVRG_Solver_FastRidge<loss_type,false>(*loss,*regul,param);
} else if (param.solver==ACC_SVRG && model.regul==L2 && !model.intercept) {
solver= new SVRG_Solver_FastRidge<loss_type,true>(*loss,*regul,param);
} else if (param.solver==CATALYST_SVRG && model.regul==L2 && !model.intercept) {
solver = new Catalyst< SVRG_Solver_FastRidge<loss_type,false> >(*loss,*regul,param);
} else if (param.solver==QNING_SVRG && model.regul==L2 && !model.intercept) {
solver = new QNing< SVRG_Solver_FastRidge<loss_type,false> >(*loss,*regul,param);
} else {
solver=get_solver<loss_type>(*loss,*regul,param);
if (!solver) {
w.copy(w0);
delete(loss);
delete(regul);
return;
}
}
D new_w0;
if (model.intercept) {
data.set_intercept(w0,new_w0);
} else {
new_w0.copyRef(w0);
}
if (dual_variable.n() != 0)
solver->set_dual_variable(dual_variable);
solver->solve(new_w0,w);
if (model.intercept) {
data.reverse_intercept(w);
}
}
if (model.regul==L1)
for (int ii=0; ii<w.n(); ++ii)
if (abs<T>(w[ii]) < EPSILON) w[ii]=0;
solver->get_optim_info(optim_info);
delete(solver);
delete(loss);
delete(regul);
};
template <typename T, typename I>
Regularizer<Matrix<T>,I>* get_regul_mat(const ParamModel<T>& model, const int nclass, const bool transpose) {
typedef Matrix<T> D;
typedef Vector<T> V;
Regularizer<D,I>* regul;
switch(model.regul) {
case L2: regul = transpose ? static_cast<Regularizer<D,I>*>(new RegVecToMat<Ridge<V,I> >(model))
: new RegMat<Ridge<V,I> >(model,nclass,transpose); break;
case L1: regul = transpose ? static_cast<Regularizer<D,I>*>(new RegVecToMat<Lasso<V,I> >(model))
: new RegMat<Lasso<V,I> >(model,nclass,transpose); break;
case ELASTICNET: regul = transpose ? static_cast<Regularizer<D,I>*>(new RegVecToMat<ElasticNet <V,I> >(model))
: new RegMat<ElasticNet<V,I> >(model,nclass,transpose); break;
case L1BALL: regul = new RegMat<L1Ball<V,I> >(model,nclass,transpose); break;
case L2BALL: regul = new RegMat<L2Ball<V,I> >(model,nclass,transpose); break;
case L1L2: regul = new MixedL1L2<T,I>(model,nclass,transpose); break;
case L1L2_L1: regul = new MixedL1L2_L1<T,I>(model,nclass,transpose); break;
case L1LINF: regul = new MixedL1Linf<T,I>(model,nclass,transpose); break;
case FUSEDLASSO: regul = new RegMat<FusedLasso<V,I> >(model,nclass,transpose); break;
case NONE: regul = new None<D,I>(model); break;
default: cerr << "Not implemented, no regularization is chosen";
regul = new None<D,I>(model);
}
return regul;
};
template <typename loss_type>
void solve_mat(loss_type& loss, const Regularizer<typename loss_type::variable_type, typename loss_type::index_type>& regul, const ParamSolver<typename loss_type::value_type>& param, const typename loss_type::variable_type& W0, typename loss_type::variable_type& W, Matrix<typename loss_type::value_type>& dual_variable, Matrix<typename loss_type::value_type>& optim_info) {
typedef typename loss_type::value_type T;
typedef typename loss_type::variable_type D;
Solver<loss_type>* solver;
if (param.nepochs==0) {
ParamSolver<T> param2=param;
param2.verbose=false;
solver= new ISTA_Solver<loss_type>(loss,regul,param2);
if (loss.transpose()) {
Matrix<T> W0T, WT;
W0.transpose(W0T);
solver->eval(W0T);
} else {
solver->eval(W0);
}
W.copy(W0);
} else {
solver=get_solver<loss_type>(loss,regul,param);
if (!solver) {
W.copy(W0);
return;
}
D new_W0;
if (loss.intercept()) {
loss.set_intercept(W0,new_W0);
} else {
new_W0.copyRef(W0);
}
if (dual_variable.n() != 0)
solver->set_dual_variable(dual_variable);
if (loss.transpose()) {
Matrix<T> W0T, WT;
new_W0.transpose(W0T);
solver->solve(W0T,WT);
WT.transpose(W);
} else {
solver->solve(new_W0,W);
}
if (loss.intercept()) {
loss.reverse_intercept(W);
}
}
if (regul.id()==L1)
for (INTM ii=0; ii<W.n(); ++ii)
for (INTM jj=0; jj<W.m(); ++jj)
if (abs<T>(W(jj,ii)) < EPSILON) W(jj,ii)=0;
solver->get_optim_info(optim_info);
delete(solver);
};
// X is p x n
// y is nclasses x n
// W0 is p x nclasses if no intercept (or p+1 x nclasses with intercept)
// prediction model is W0^T X gives nclasses x n
template <typename M>
void multivariate_erm(const M& X, const Matrix<typename M::value_type>& y, const Matrix<typename M::value_type>& W0, Matrix<typename M::value_type>& W, Matrix<typename M::value_type>& dual_variable, Matrix<typename M::value_type>& optim_info, const ParamSolver<typename M::value_type>& param, const ParamModel<typename M::value_type>& model) {
typedef typename M::value_type T;
typedef typename M::index_type I;
if ((model.intercept && X.m()+1 != W0.m()) || (!model.intercept && X.m() != W0.m())) {
cerr << "Dimension of initial point is not consistent." << endl;
return;
}
init_omp(param.threads);
typedef Matrix<T> D;
if (is_loss_for_matrices(model.loss) || is_regul_for_matrices(model.regul)) {
DataMatrixLinear<M> data(X,model.intercept);
if (param.verbose)
data.print();
LinearLossMat< M, Matrix<T> >* loss;
switch (model.loss) {
case SQUARE: loss = new SquareLossMat<M>(data,y); break;
case LOGISTIC: loss = new LossMat< LogisticLoss<M> >(data,y); break;
case SQHINGE: loss = new LossMat< SquaredHingeLoss<M> >(data,y); break;
//case HINGE: loss = new LossMat< HingeLoss<M> >(data,y); break;
case SAFE_LOGISTIC: loss = new LossMat<SafeLogisticLoss<M> >(data,y); break;
default: cerr << "Not implemented, square loss is chosen by default";
loss = new SquareLossMat<M>(data,y);
}
const int nclass=W0.n();
Regularizer<D,I>* regul = get_regul_mat<T,I>(model,nclass,loss->transpose());
solve_mat<LinearLossMat< M, Matrix<T> > >(*loss,*regul,param,W0,W,dual_variable,optim_info);
delete(regul);
delete(loss);
} else {
W.copy(W0);
const int nclass=W0.n();
const int it0=MAX(param.it0,1);
optim_info.resize(6,MAX(param.nepochs/it0,1));
optim_info.setZeros();
ParamSolver<T> param2=param;
param2.verbose=false;
if (param.verbose) {
DataMatrixLinear<M> data(X,model.intercept);
data.print();
}
Timer global_all;
global_all.start();
#pragma omp parallel for
for (int ii=0; ii<nclass; ++ii) {
Vector<T> w0col, wcol, ycol, dualcol;
Matrix<T> optim_info_col;
W0.refCol(ii,w0col);
W.refCol(ii,wcol);
y.copyRow(ii,ycol);
if (dual_variable.m() == nclass)
dual_variable.copyRow(ii,dualcol);
simple_erm(X,ycol,w0col,wcol,dualcol,optim_info_col,param2,model);
if (dual_variable.m() == nclass)
dual_variable.copyToRow(ii,dualcol);
#pragma omp critical
{
optim_info.add(optim_info_col);
if (param.verbose) {
const int noptim=optim_info_col.n()-1;
cout << "Solver " << ii << " has terminated after " << optim_info_col(0,noptim) << " epochs in " << optim_info_col(5,noptim) << " seconds" << endl;
if (optim_info_col(4,noptim)==0) {
cout << " Primal objective: " << optim_info_col(1,noptim) << ", relative duality gap: " << optim_info_col(3,noptim) << endl;
} else {
cout << " Primal objective: " << optim_info_col(1,noptim) << ", tol: " << optim_info_col(4,noptim) << endl;
}
}
}
}
global_all.stop();
if (param.verbose) {
cout << "Time for the one-vs-all strategy" << endl;
global_all.printElapsed();
}
}
};
template <typename M>
void multivariate_erm(const M& X, const Vector<int>& y, const Matrix<typename M::value_type>& W0, Matrix<typename M::value_type>& W, Matrix<typename M::value_type>& dual_variable, Matrix<typename M::value_type>& optim_info, const ParamSolver<typename M::value_type>& param, const ParamModel<typename M::value_type>& model) {
typedef typename M::value_type T;
typedef typename M::index_type I;
if ((model.intercept && X.m()+1 != W0.m()) || (!model.intercept && X.m() != W0.m())) {
cerr << "Dimension of initial point is not consistent." << endl;
return;
}
const int nclass=y.maxval()+1;
if ((is_regression_loss(model.loss) || !is_loss_for_matrices(model.loss))) {
const int n = y.n();
Matrix<typename M::value_type> labels(nclass,n);
labels.set(-(1.0));
for (int ii=0; ii<n; ++ii)
labels(y[ii],ii)=(1.0);
return multivariate_erm(X,labels,W0,W,dual_variable,optim_info,param,model);
}
init_omp(param.threads);
typedef Matrix<T> D;
DataMatrixLinear<M> data(X,model.intercept);
if (param.verbose)
data.print();
LinearLossMat<M, Vector<int> >* loss;
switch (model.loss) {
case MULTI_LOGISTIC: loss= new MultiClassLogisticLoss<M>(data,y); break;
default: cerr << "Not implemented, multilog loss is chosen by default";
loss= new MultiClassLogisticLoss<M>(data,y);
}
Regularizer<D,I>* regul = get_regul_mat<T,I>(model,nclass,loss->transpose());
solve_mat<LinearLossMat<M, Vector<int> > >(*loss,*regul,param,W0,W,dual_variable,optim_info);
delete(regul);
delete(loss);
};
#endif
|
GB_unop__identity_uint32_uint64.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_uint32_uint64)
// op(A') function: GB (_unop_tran__identity_uint32_uint64)
// C type: uint32_t
// A type: uint64_t
// cast: uint32_t cij = (uint32_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
uint64_t
#define GB_CTYPE \
uint32_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_CAST(z, aij) \
uint32_t z = (uint32_t) aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
uint64_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
uint32_t z = (uint32_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_UINT32 || GxB_NO_UINT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_uint32_uint64)
(
uint32_t *Cx, // Cx and Ax may be aliased
const uint64_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++)
{
uint64_t aij = Ax [p] ;
uint32_t z = (uint32_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 ;
uint64_t aij = Ax [p] ;
uint32_t z = (uint32_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_uint32_uint64)
(
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
|
convolution_sgemm.h
|
// Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2021 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 im2col_sgemm_neon(const Mat& bottom_im2col, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt)
{
// Mat bottom_im2col(size, maxk, inch, 4u, 1, opt.workspace_allocator);
const int size = bottom_im2col.w;
const int maxk = bottom_im2col.h;
const int inch = bottom_im2col.c;
const int outch = top_blob.c;
const float* bias = _bias;
// permute
Mat tmp;
#if __ARM_NEON
if (size >= 8)
tmp.create(8 * maxk, inch, size / 8 + (size % 8) / 4 + size % 4, 4u, 1, opt.workspace_allocator);
else if (size >= 4)
tmp.create(4 * maxk, inch, size / 4 + size % 4, 4u, 1, opt.workspace_allocator);
else
tmp.create(maxk, inch, size, 4u, 1, opt.workspace_allocator);
{
int nn_size = size >> 3;
int remain_size_start = 0;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = remain_size_start + ii * 8;
float* tmpptr = tmp.channel(i / 8);
for (int q = 0; q < inch; q++)
{
const float* img0 = (const float*)bottom_im2col.channel(q) + i;
for (int k = 0; k < maxk; k++)
{
vst1q_f32(tmpptr, vld1q_f32(img0));
vst1q_f32(tmpptr + 4, vld1q_f32(img0 + 4));
img0 += size;
tmpptr += 8;
}
}
}
remain_size_start += nn_size << 3;
nn_size = (size - remain_size_start) >> 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = remain_size_start + ii * 4;
float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4);
for (int q = 0; q < inch; q++)
{
const float* img0 = (const float*)bottom_im2col.channel(q) + i;
for (int k = 0; k < maxk; k++)
{
vst1q_f32(tmpptr, vld1q_f32(img0));
img0 += size;
tmpptr += 4;
}
}
}
remain_size_start += nn_size << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int i = remain_size_start; i < size; i++)
{
float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + i % 4);
for (int q = 0; q < inch; q++)
{
const float* img0 = (const float*)bottom_im2col.channel(q) + i;
for (int k = 0; k < maxk; k++)
{
tmpptr[0] = img0[0];
img0 += size;
tmpptr += 1;
}
}
}
}
#else // __ARM_NEON
tmp.create(maxk, inch, size, 4u, 1, opt.workspace_allocator);
{
#pragma omp parallel for num_threads(opt.num_threads)
for (int i = 0; i < size; i++)
{
float* tmpptr = tmp.channel(i);
for (int q = 0; q < inch; q++)
{
const float* img0 = (const float*)bottom_im2col.channel(q) + i;
for (int k = 0; k < maxk; k++)
{
tmpptr[0] = img0[0];
img0 += size;
tmpptr += 1;
}
}
}
}
#endif // __ARM_NEON
#if __ARM_NEON
int nn_outch = 0;
int remain_outch_start = 0;
#if __aarch64__
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 p = pp * 8;
float* outptr0 = top_blob.channel(p);
float* outptr1 = top_blob.channel(p + 1);
float* outptr2 = top_blob.channel(p + 2);
float* outptr3 = top_blob.channel(p + 3);
float* outptr4 = top_blob.channel(p + 4);
float* outptr5 = top_blob.channel(p + 5);
float* outptr6 = top_blob.channel(p + 6);
float* outptr7 = top_blob.channel(p + 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 + p : zeros;
int i = 0;
for (; i + 7 < size; i += 8)
{
const float* tmpptr = tmp.channel(i / 8);
const float* kptr = kernel.channel(p / 8);
int nn = inch * maxk; // inch always > 0
asm volatile(
"ld1 {v0.4s, v1.4s}, [%20] \n"
"dup v16.4s, v0.s[0] \n"
"dup v17.4s, v0.s[0] \n"
"dup v18.4s, v0.s[1] \n"
"dup v19.4s, v0.s[1] \n"
"dup v20.4s, v0.s[2] \n"
"dup v21.4s, v0.s[2] \n"
"dup v22.4s, v0.s[3] \n"
"dup v23.4s, v0.s[3] \n"
"dup v24.4s, v1.s[0] \n"
"dup v25.4s, v1.s[0] \n"
"dup v26.4s, v1.s[1] \n"
"dup v27.4s, v1.s[1] \n"
"dup v28.4s, v1.s[2] \n"
"dup v29.4s, v1.s[2] \n"
"dup v30.4s, v1.s[3] \n"
"dup v31.4s, v1.s[3] \n"
// inch loop
"lsr w4, %w21, #2 \n" // w4 = nn = inch >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"0: \n"
"prfm pldl1keep, [%8, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%8], #64 \n"
"prfm pldl1keep, [%9, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%9], #64 \n"
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v18.4s, v8.4s, v0.s[1] \n"
"fmla v20.4s, v8.4s, v0.s[2] \n"
"fmla v22.4s, v8.4s, v0.s[3] \n"
"fmla v17.4s, v9.4s, v0.s[0] \n"
"fmla v19.4s, v9.4s, v0.s[1] \n"
"fmla v21.4s, v9.4s, v0.s[2] \n"
"fmla v23.4s, v9.4s, v0.s[3] \n"
"fmla v24.4s, v8.4s, v1.s[0] \n"
"fmla v26.4s, v8.4s, v1.s[1] \n"
"fmla v28.4s, v8.4s, v1.s[2] \n"
"fmla v30.4s, v8.4s, v1.s[3] \n"
"fmla v25.4s, v9.4s, v1.s[0] \n"
"fmla v27.4s, v9.4s, v1.s[1] \n"
"fmla v29.4s, v9.4s, v1.s[2] \n"
"fmla v31.4s, v9.4s, v1.s[3] \n"
"prfm pldl1keep, [%8, #512] \n"
"ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%8], #64 \n"
"fmla v16.4s, v10.4s, v2.s[0] \n"
"fmla v18.4s, v10.4s, v2.s[1] \n"
"fmla v20.4s, v10.4s, v2.s[2] \n"
"fmla v22.4s, v10.4s, v2.s[3] \n"
"fmla v17.4s, v11.4s, v2.s[0] \n"
"fmla v19.4s, v11.4s, v2.s[1] \n"
"fmla v21.4s, v11.4s, v2.s[2] \n"
"fmla v23.4s, v11.4s, v2.s[3] \n"
"fmla v24.4s, v10.4s, v3.s[0] \n"
"fmla v26.4s, v10.4s, v3.s[1] \n"
"fmla v28.4s, v10.4s, v3.s[2] \n"
"fmla v30.4s, v10.4s, v3.s[3] \n"
"fmla v25.4s, v11.4s, v3.s[0] \n"
"fmla v27.4s, v11.4s, v3.s[1] \n"
"fmla v29.4s, v11.4s, v3.s[2] \n"
"fmla v31.4s, v11.4s, v3.s[3] \n"
"prfm pldl1keep, [%9, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%9], #64 \n"
"fmla v16.4s, v12.4s, v4.s[0] \n"
"fmla v18.4s, v12.4s, v4.s[1] \n"
"fmla v20.4s, v12.4s, v4.s[2] \n"
"fmla v22.4s, v12.4s, v4.s[3] \n"
"fmla v17.4s, v13.4s, v4.s[0] \n"
"fmla v19.4s, v13.4s, v4.s[1] \n"
"fmla v21.4s, v13.4s, v4.s[2] \n"
"fmla v23.4s, v13.4s, v4.s[3] \n"
"fmla v24.4s, v12.4s, v5.s[0] \n"
"fmla v26.4s, v12.4s, v5.s[1] \n"
"fmla v28.4s, v12.4s, v5.s[2] \n"
"fmla v30.4s, v12.4s, v5.s[3] \n"
"fmla v25.4s, v13.4s, v5.s[0] \n"
"fmla v27.4s, v13.4s, v5.s[1] \n"
"fmla v29.4s, v13.4s, v5.s[2] \n"
"fmla v31.4s, v13.4s, v5.s[3] \n"
"subs w4, w4, #1 \n"
"fmla v16.4s, v14.4s, v6.s[0] \n"
"fmla v18.4s, v14.4s, v6.s[1] \n"
"fmla v20.4s, v14.4s, v6.s[2] \n"
"fmla v22.4s, v14.4s, v6.s[3] \n"
"fmla v17.4s, v15.4s, v6.s[0] \n"
"fmla v19.4s, v15.4s, v6.s[1] \n"
"fmla v21.4s, v15.4s, v6.s[2] \n"
"fmla v23.4s, v15.4s, v6.s[3] \n"
"fmla v24.4s, v14.4s, v7.s[0] \n"
"fmla v26.4s, v14.4s, v7.s[1] \n"
"fmla v28.4s, v14.4s, v7.s[2] \n"
"fmla v30.4s, v14.4s, v7.s[3] \n"
"fmla v25.4s, v15.4s, v7.s[0] \n"
"fmla v27.4s, v15.4s, v7.s[1] \n"
"fmla v29.4s, v15.4s, v7.s[2] \n"
"fmla v31.4s, v15.4s, v7.s[3] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and w4, %w21, #3 \n" // w4 = remain = inch & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%8, #256] \n"
"ld1 {v8.4s, v9.4s}, [%8], #32 \n"
"prfm pldl1keep, [%9, #256] \n"
"ld1 {v0.4s, v1.4s}, [%9], #32 \n"
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v18.4s, v8.4s, v0.s[1] \n"
"fmla v20.4s, v8.4s, v0.s[2] \n"
"fmla v22.4s, v8.4s, v0.s[3] \n"
"fmla v17.4s, v9.4s, v0.s[0] \n"
"fmla v19.4s, v9.4s, v0.s[1] \n"
"fmla v21.4s, v9.4s, v0.s[2] \n"
"fmla v23.4s, v9.4s, v0.s[3] \n"
"subs w4, w4, #1 \n"
"fmla v24.4s, v8.4s, v1.s[0] \n"
"fmla v26.4s, v8.4s, v1.s[1] \n"
"fmla v28.4s, v8.4s, v1.s[2] \n"
"fmla v30.4s, v8.4s, v1.s[3] \n"
"fmla v25.4s, v9.4s, v1.s[0] \n"
"fmla v27.4s, v9.4s, v1.s[1] \n"
"fmla v29.4s, v9.4s, v1.s[2] \n"
"fmla v31.4s, v9.4s, v1.s[3] \n"
"bne 2b \n"
"3: \n"
"st1 {v16.4s, v17.4s}, [%0], #32 \n"
"st1 {v18.4s, v19.4s}, [%1], #32 \n"
"st1 {v20.4s, v21.4s}, [%2], #32 \n"
"st1 {v22.4s, v23.4s}, [%3], #32 \n"
"st1 {v24.4s, v25.4s}, [%4], #32 \n"
"st1 {v26.4s, v27.4s}, [%5], #32 \n"
"st1 {v28.4s, v29.4s}, [%6], #32 \n"
"st1 {v30.4s, v31.4s}, [%7], #32 \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(outptr2), // %2
"=r"(outptr3), // %3
"=r"(outptr4), // %4
"=r"(outptr5), // %5
"=r"(outptr6), // %6
"=r"(outptr7), // %7
"=r"(tmpptr), // %8
"=r"(kptr) // %9
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(outptr4),
"5"(outptr5),
"6"(outptr6),
"7"(outptr7),
"8"(tmpptr),
"9"(kptr),
"r"(biasptr), // %20
"r"(nn) // %21
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31");
}
for (; i + 3 < size; i += 4)
{
const float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4);
const float* kptr = kernel.channel(p / 8);
int nn = inch * maxk; // inch always > 0
asm volatile(
"ld1 {v0.4s, v1.4s}, [%20] \n"
"dup v16.4s, v0.s[0] \n"
"dup v17.4s, v0.s[1] \n"
"dup v18.4s, v0.s[2] \n"
"dup v19.4s, v0.s[3] \n"
"dup v20.4s, v1.s[0] \n"
"dup v21.4s, v1.s[1] \n"
"dup v22.4s, v1.s[2] \n"
"dup v23.4s, v1.s[3] \n"
// inch loop
"lsr w4, %w21, #2 \n" // w4 = nn = inch >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"0: \n"
"prfm pldl1keep, [%8, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%8], #64 \n"
"prfm pldl1keep, [%9, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%9], #64 \n"
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v8.4s, v0.s[1] \n"
"fmla v18.4s, v8.4s, v0.s[2] \n"
"fmla v19.4s, v8.4s, v0.s[3] \n"
"fmla v20.4s, v8.4s, v1.s[0] \n"
"fmla v21.4s, v8.4s, v1.s[1] \n"
"fmla v22.4s, v8.4s, v1.s[2] \n"
"fmla v23.4s, v8.4s, v1.s[3] \n"
"prfm pldl1keep, [%9, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%9], #64 \n"
"fmla v16.4s, v9.4s, v2.s[0] \n"
"fmla v17.4s, v9.4s, v2.s[1] \n"
"fmla v18.4s, v9.4s, v2.s[2] \n"
"fmla v19.4s, v9.4s, v2.s[3] \n"
"fmla v20.4s, v9.4s, v3.s[0] \n"
"fmla v21.4s, v9.4s, v3.s[1] \n"
"fmla v22.4s, v9.4s, v3.s[2] \n"
"fmla v23.4s, v9.4s, v3.s[3] \n"
"subs w4, w4, #1 \n"
"fmla v16.4s, v10.4s, v4.s[0] \n"
"fmla v17.4s, v10.4s, v4.s[1] \n"
"fmla v18.4s, v10.4s, v4.s[2] \n"
"fmla v19.4s, v10.4s, v4.s[3] \n"
"fmla v20.4s, v10.4s, v5.s[0] \n"
"fmla v21.4s, v10.4s, v5.s[1] \n"
"fmla v22.4s, v10.4s, v5.s[2] \n"
"fmla v23.4s, v10.4s, v5.s[3] \n"
"fmla v16.4s, v11.4s, v6.s[0] \n"
"fmla v17.4s, v11.4s, v6.s[1] \n"
"fmla v18.4s, v11.4s, v6.s[2] \n"
"fmla v19.4s, v11.4s, v6.s[3] \n"
"fmla v20.4s, v11.4s, v7.s[0] \n"
"fmla v21.4s, v11.4s, v7.s[1] \n"
"fmla v22.4s, v11.4s, v7.s[2] \n"
"fmla v23.4s, v11.4s, v7.s[3] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and w4, %w21, #3 \n" // w4 = remain = inch & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%8, #128] \n"
"ld1 {v8.4s}, [%8], #16 \n"
"prfm pldl1keep, [%9, #256] \n"
"ld1 {v0.4s, v1.4s}, [%9], #32 \n"
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v8.4s, v0.s[1] \n"
"fmla v18.4s, v8.4s, v0.s[2] \n"
"fmla v19.4s, v8.4s, v0.s[3] \n"
"subs w4, w4, #1 \n"
"fmla v20.4s, v8.4s, v1.s[0] \n"
"fmla v21.4s, v8.4s, v1.s[1] \n"
"fmla v22.4s, v8.4s, v1.s[2] \n"
"fmla v23.4s, v8.4s, v1.s[3] \n"
"bne 2b \n"
"3: \n"
"st1 {v16.4s}, [%0], #16 \n"
"st1 {v17.4s}, [%1], #16 \n"
"st1 {v18.4s}, [%2], #16 \n"
"st1 {v19.4s}, [%3], #16 \n"
"st1 {v20.4s}, [%4], #16 \n"
"st1 {v21.4s}, [%5], #16 \n"
"st1 {v22.4s}, [%6], #16 \n"
"st1 {v23.4s}, [%7], #16 \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(outptr2), // %2
"=r"(outptr3), // %3
"=r"(outptr4), // %4
"=r"(outptr5), // %5
"=r"(outptr6), // %6
"=r"(outptr7), // %7
"=r"(tmpptr), // %8
"=r"(kptr) // %9
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(outptr4),
"5"(outptr5),
"6"(outptr6),
"7"(outptr7),
"8"(tmpptr),
"9"(kptr),
"r"(biasptr), // %20
"r"(nn) // %21
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23");
}
for (; i < size; i++)
{
const float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + i % 4);
const float* kptr = kernel.channel(p / 8);
int nn = inch * maxk; // inch always > 0
asm volatile(
"ld1 {v24.4s, v25.4s}, [%20] \n"
// inch loop
"lsr w4, %w21, #2 \n" // w4 = nn = inch >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"eor v16.16b, v16.16b, v16.16b \n"
"eor v17.16b, v17.16b, v17.16b \n"
"eor v18.16b, v18.16b, v18.16b \n"
"eor v19.16b, v19.16b, v19.16b \n"
"eor v20.16b, v20.16b, v20.16b \n"
"eor v21.16b, v21.16b, v21.16b \n"
"eor v22.16b, v22.16b, v22.16b \n"
"eor v23.16b, v23.16b, v23.16b \n"
"0: \n"
"prfm pldl1keep, [%8, #128] \n"
"ld1 {v8.4s}, [%8], #16 \n"
"prfm pldl1keep, [%9, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%9], #64 \n"
"fmla v16.4s, v0.4s, v8.s[0] \n"
"fmla v17.4s, v1.4s, v8.s[0] \n"
"fmla v18.4s, v2.4s, v8.s[1] \n"
"fmla v19.4s, v3.4s, v8.s[1] \n"
"prfm pldl1keep, [%9, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%9], #64 \n"
"subs w4, w4, #1 \n"
"fmla v20.4s, v4.4s, v8.s[2] \n"
"fmla v21.4s, v5.4s, v8.s[2] \n"
"fmla v22.4s, v6.4s, v8.s[3] \n"
"fmla v23.4s, v7.4s, v8.s[3] \n"
"bne 0b \n"
"fadd v16.4s, v16.4s, v18.4s \n"
"fadd v17.4s, v17.4s, v19.4s \n"
"fadd v20.4s, v20.4s, v22.4s \n"
"fadd v21.4s, v21.4s, v23.4s \n"
"fadd v16.4s, v16.4s, v20.4s \n"
"fadd v17.4s, v17.4s, v21.4s \n"
"fadd v24.4s, v24.4s, v16.4s \n"
"fadd v25.4s, v25.4s, v17.4s \n"
"1: \n"
// remain loop
"and w4, %w21, #3 \n" // w4 = remain = inch & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%8, #32] \n"
"ld1r {v8.4s}, [%8], #4 \n"
"prfm pldl1keep, [%9, #256] \n"
"ld1 {v0.4s, v1.4s}, [%9], #32 \n"
"subs w4, w4, #1 \n"
"fmla v24.4s, v8.4s, v0.4s \n"
"fmla v25.4s, v8.4s, v1.4s \n"
"bne 2b \n"
"3: \n"
"st1 {v24.s}[0],[%0], #4 \n"
"st1 {v24.s}[1],[%1], #4 \n"
"st1 {v24.s}[2],[%2], #4 \n"
"st1 {v24.s}[3],[%3], #4 \n"
"st1 {v25.s}[0],[%4], #4 \n"
"st1 {v25.s}[1],[%5], #4 \n"
"st1 {v25.s}[2],[%6], #4 \n"
"st1 {v25.s}[3],[%7], #4 \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(outptr2), // %2
"=r"(outptr3), // %3
"=r"(outptr4), // %4
"=r"(outptr5), // %5
"=r"(outptr6), // %6
"=r"(outptr7), // %7
"=r"(tmpptr), // %8
"=r"(kptr) // %9
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(outptr4),
"5"(outptr5),
"6"(outptr6),
"7"(outptr7),
"8"(tmpptr),
"9"(kptr),
"r"(biasptr), // %20
"r"(nn) // %21
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25");
}
}
#endif // __aarch64__
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 p = remain_outch_start + pp * 4;
float* outptr0 = top_blob.channel(p);
float* outptr1 = top_blob.channel(p + 1);
float* outptr2 = top_blob.channel(p + 2);
float* outptr3 = top_blob.channel(p + 3);
const float zeros[4] = {0.f, 0.f, 0.f, 0.f};
const float* biasptr = bias ? bias + p : zeros;
int i = 0;
for (; i + 7 < size; i += 8)
{
const float* tmpptr = tmp.channel(i / 8);
#if __aarch64__
const float* kptr = kernel.channel(p / 8 + (p % 8) / 4);
#else
const float* kptr = kernel.channel(p / 4);
#endif
int nn = inch * maxk; // inch always > 0
#if __aarch64__
asm volatile(
"ld1 {v0.4s}, [%12] \n"
"dup v8.4s, v0.s[0] \n"
"dup v9.4s, v0.s[0] \n"
"dup v10.4s, v0.s[1] \n"
"dup v11.4s, v0.s[1] \n"
"dup v12.4s, v0.s[2] \n"
"dup v13.4s, v0.s[2] \n"
"dup v14.4s, v0.s[3] \n"
"dup v15.4s, v0.s[3] \n"
// inch loop
"lsr w4, %w13, #2 \n" // w4 = nn = inch >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"0: \n"
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%4], #64 \n"
"prfm pldl1keep, [%5, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%5], #64 \n"
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v10.4s, v4.4s, v0.s[1] \n"
"fmla v12.4s, v4.4s, v0.s[2] \n"
"fmla v14.4s, v4.4s, v0.s[3] \n"
"fmla v9.4s, v5.4s, v0.s[0] \n"
"fmla v11.4s, v5.4s, v0.s[1] \n"
"fmla v13.4s, v5.4s, v0.s[2] \n"
"fmla v15.4s, v5.4s, v0.s[3] \n"
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%4], #64 \n"
"fmla v8.4s, v6.4s, v1.s[0] \n"
"fmla v10.4s, v6.4s, v1.s[1] \n"
"fmla v12.4s, v6.4s, v1.s[2] \n"
"fmla v14.4s, v6.4s, v1.s[3] \n"
"fmla v9.4s, v7.4s, v1.s[0] \n"
"fmla v11.4s, v7.4s, v1.s[1] \n"
"fmla v13.4s, v7.4s, v1.s[2] \n"
"fmla v15.4s, v7.4s, v1.s[3] \n"
"subs w4, w4, #1 \n"
"fmla v8.4s, v16.4s, v2.s[0] \n"
"fmla v10.4s, v16.4s, v2.s[1] \n"
"fmla v12.4s, v16.4s, v2.s[2] \n"
"fmla v14.4s, v16.4s, v2.s[3] \n"
"fmla v9.4s, v17.4s, v2.s[0] \n"
"fmla v11.4s, v17.4s, v2.s[1] \n"
"fmla v13.4s, v17.4s, v2.s[2] \n"
"fmla v15.4s, v17.4s, v2.s[3] \n"
"fmla v8.4s, v18.4s, v3.s[0] \n"
"fmla v10.4s, v18.4s, v3.s[1] \n"
"fmla v12.4s, v18.4s, v3.s[2] \n"
"fmla v14.4s, v18.4s, v3.s[3] \n"
"fmla v9.4s, v19.4s, v3.s[0] \n"
"fmla v11.4s, v19.4s, v3.s[1] \n"
"fmla v13.4s, v19.4s, v3.s[2] \n"
"fmla v15.4s, v19.4s, v3.s[3] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and w4, %w13, #3 \n" // w4 = remain = inch & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%4, #256] \n"
"ld1 {v4.4s, v5.4s}, [%4], #32 \n"
"prfm pldl1keep, [%5, #128] \n"
"ld1 {v0.4s}, [%5], #16 \n"
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v10.4s, v4.4s, v0.s[1] \n"
"fmla v12.4s, v4.4s, v0.s[2] \n"
"fmla v14.4s, v4.4s, v0.s[3] \n"
"subs w4, w4, #1 \n"
"fmla v9.4s, v5.4s, v0.s[0] \n"
"fmla v11.4s, v5.4s, v0.s[1] \n"
"fmla v13.4s, v5.4s, v0.s[2] \n"
"fmla v15.4s, v5.4s, v0.s[3] \n"
"bne 2b \n"
"3: \n"
"st1 {v8.4s, v9.4s}, [%0], #32 \n"
"st1 {v10.4s, v11.4s}, [%1], #32 \n"
"st1 {v12.4s, v13.4s}, [%2], #32 \n"
"st1 {v14.4s, v15.4s}, [%3], #32 \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(outptr2), // %2
"=r"(outptr3), // %3
"=r"(tmpptr), // %4
"=r"(kptr) // %5
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(tmpptr),
"5"(kptr),
"r"(biasptr), // %12
"r"(nn) // %13
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19");
#else // __aarch64__
asm volatile(
"vld1.f32 {d0-d1}, [%12] \n"
"vdup.f32 q8, d0[0] \n"
"vdup.f32 q9, d0[0] \n"
"vdup.f32 q10, d0[1] \n"
"vdup.f32 q11, d0[1] \n"
"vdup.f32 q12, d1[0] \n"
"vdup.f32 q13, d1[0] \n"
"vdup.f32 q14, d1[1] \n"
"vdup.f32 q15, d1[1] \n"
// inch loop
"lsr r4, %13, #2 \n" // r4 = nn = inch >> 2
"cmp r4, #0 \n"
"beq 1f \n"
"0: \n"
"pld [%4, #512] \n"
"vldm %4!, {d8-d15} \n"
// "vld1.f32 {d8-d11}, [%4 :128]! \n"
// "vld1.f32 {d12-d15}, [%4 :128]! \n"
"pld [%5, #512] \n"
"vldm %5!, {d0-d7} \n"
// "vld1.f32 {d0-d3}, [%5 :128]! \n"
// "vld1.f32 {d4-d7}, [%5 :128]! \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q10, q4, d0[1] \n"
"vmla.f32 q12, q4, d1[0] \n"
"vmla.f32 q14, q4, d1[1] \n"
"vmla.f32 q9, q5, d0[0] \n"
"vmla.f32 q11, q5, d0[1] \n"
"vmla.f32 q13, q5, d1[0] \n"
"vmla.f32 q15, q5, d1[1] \n"
"vmla.f32 q8, q6, d2[0] \n"
"vmla.f32 q10, q6, d2[1] \n"
"vmla.f32 q12, q6, d3[0] \n"
"vmla.f32 q14, q6, d3[1] \n"
"vmla.f32 q9, q7, d2[0] \n"
"vmla.f32 q11, q7, d2[1] \n"
"vmla.f32 q13, q7, d3[0] \n"
"vmla.f32 q15, q7, d3[1] \n"
"pld [%4, #512] \n"
"vldm %4!, {d8-d15} \n"
// "vld1.f32 {d8-d11}, [%4 :128]! \n"
// "vld1.f32 {d12-d15}, [%4 :128]! \n"
"vmla.f32 q8, q4, d4[0] \n"
"vmla.f32 q10, q4, d4[1] \n"
"vmla.f32 q12, q4, d5[0] \n"
"vmla.f32 q14, q4, d5[1] \n"
"vmla.f32 q9, q5, d4[0] \n"
"vmla.f32 q11, q5, d4[1] \n"
"vmla.f32 q13, q5, d5[0] \n"
"vmla.f32 q15, q5, d5[1] \n"
"subs r4, r4, #1 \n"
"vmla.f32 q8, q6, d6[0] \n"
"vmla.f32 q10, q6, d6[1] \n"
"vmla.f32 q12, q6, d7[0] \n"
"vmla.f32 q14, q6, d7[1] \n"
"vmla.f32 q9, q7, d6[0] \n"
"vmla.f32 q11, q7, d6[1] \n"
"vmla.f32 q13, q7, d7[0] \n"
"vmla.f32 q15, q7, d7[1] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and r4, %13, #3 \n" // r4 = remain = inch & 3;
"cmp r4, #0 \n"
"beq 3f \n"
"2: \n"
"pld [%4, #256] \n"
"vld1.f32 {d8-d11}, [%4 :128]! \n"
"pld [%5, #128] \n"
"vld1.f32 {d0-d1}, [%5 :128]! \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q10, q4, d0[1] \n"
"vmla.f32 q12, q4, d1[0] \n"
"vmla.f32 q14, q4, d1[1] \n"
"subs r4, r4, #1 \n"
"vmla.f32 q9, q5, d0[0] \n"
"vmla.f32 q11, q5, d0[1] \n"
"vmla.f32 q13, q5, d1[0] \n"
"vmla.f32 q15, q5, d1[1] \n"
"bne 2b \n"
"3: \n"
"vst1.f32 {d16-d19}, [%0 :128]! \n"
"vst1.f32 {d20-d23}, [%1 :128]! \n"
"vst1.f32 {d24-d27}, [%2 :128]! \n"
"vst1.f32 {d28-d31}, [%3 :128]! \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(outptr2), // %2
"=r"(outptr3), // %3
"=r"(tmpptr), // %4
"=r"(kptr) // %5
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(tmpptr),
"5"(kptr),
"r"(biasptr), // %12
"r"(nn) // %13
: "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
#endif // __aarch64__
}
for (; i + 3 < size; i += 4)
{
const float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4);
#if __aarch64__
const float* kptr = kernel.channel(p / 8 + (p % 8) / 4);
#else
const float* kptr = kernel.channel(p / 4);
#endif
int nn = inch * maxk; // inch always > 0
#if __aarch64__
asm volatile(
"ld1 {v0.4s}, [%12] \n"
"dup v8.4s, v0.s[0] \n"
"dup v9.4s, v0.s[1] \n"
"dup v10.4s, v0.s[2] \n"
"dup v11.4s, v0.s[3] \n"
// inch loop
"lsr w4, %w13, #2 \n" // w4 = nn = inch >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"0: \n"
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%4], #64 \n"
"prfm pldl1keep, [%5, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%5], #64 \n"
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v9.4s, v4.4s, v0.s[1] \n"
"fmla v10.4s, v4.4s, v0.s[2] \n"
"fmla v11.4s, v4.4s, v0.s[3] \n"
"fmla v8.4s, v5.4s, v1.s[0] \n"
"fmla v9.4s, v5.4s, v1.s[1] \n"
"fmla v10.4s, v5.4s, v1.s[2] \n"
"fmla v11.4s, v5.4s, v1.s[3] \n"
"subs w4, w4, #1 \n"
"fmla v8.4s, v6.4s, v2.s[0] \n"
"fmla v9.4s, v6.4s, v2.s[1] \n"
"fmla v10.4s, v6.4s, v2.s[2] \n"
"fmla v11.4s, v6.4s, v2.s[3] \n"
"fmla v8.4s, v7.4s, v3.s[0] \n"
"fmla v9.4s, v7.4s, v3.s[1] \n"
"fmla v10.4s, v7.4s, v3.s[2] \n"
"fmla v11.4s, v7.4s, v3.s[3] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and w4, %w13, #3 \n" // w4 = remain = inch & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v4.4s}, [%4], #16 \n"
"prfm pldl1keep, [%5, #128] \n"
"ld1 {v0.4s}, [%5], #16 \n"
"subs w4, w4, #1 \n"
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v9.4s, v4.4s, v0.s[1] \n"
"fmla v10.4s, v4.4s, v0.s[2] \n"
"fmla v11.4s, v4.4s, v0.s[3] \n"
"bne 2b \n"
"3: \n"
"st1 {v8.4s}, [%0], #16 \n"
"st1 {v9.4s}, [%1], #16 \n"
"st1 {v10.4s}, [%2], #16 \n"
"st1 {v11.4s}, [%3], #16 \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(outptr2), // %2
"=r"(outptr3), // %3
"=r"(tmpptr), // %4
"=r"(kptr) // %5
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(tmpptr),
"5"(kptr),
"r"(biasptr), // %12
"r"(nn) // %13
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11");
#else // __aarch64__
asm volatile(
"vld1.f32 {d0-d1}, [%12] \n"
"vdup.f32 q8, d0[0] \n"
"vdup.f32 q9, d0[1] \n"
"vdup.f32 q10, d1[0] \n"
"vdup.f32 q11, d1[1] \n"
// inch loop
"lsr r4, %13, #2 \n" // r4 = nn = inch >> 2
"cmp r4, #0 \n"
"beq 1f \n"
"0: \n"
"pld [%4, #512] \n"
"vldm %4!, {d8-d15} \n"
// "vld1.f32 {d8-d11}, [%4 :128]! \n"
// "vld1.f32 {d12-d15}, [%4 :128]! \n"
"pld [%5, #512] \n"
"vldm %5!, {d0-d7} \n"
// "vld1.f32 {d0-d3}, [%5 :128]! \n"
// "vld1.f32 {d4-d7}, [%5 :128]! \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q9, q4, d0[1] \n"
"vmla.f32 q10, q4, d1[0] \n"
"vmla.f32 q11, q4, d1[1] \n"
"vmla.f32 q8, q5, d2[0] \n"
"vmla.f32 q9, q5, d2[1] \n"
"vmla.f32 q10, q5, d3[0] \n"
"vmla.f32 q11, q5, d3[1] \n"
"subs r4, r4, #1 \n"
"vmla.f32 q8, q6, d4[0] \n"
"vmla.f32 q9, q6, d4[1] \n"
"vmla.f32 q10, q6, d5[0] \n"
"vmla.f32 q11, q6, d5[1] \n"
"vmla.f32 q8, q7, d6[0] \n"
"vmla.f32 q9, q7, d6[1] \n"
"vmla.f32 q10, q7, d7[0] \n"
"vmla.f32 q11, q7, d7[1] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and r4, %13, #3 \n" // r4 = remain = inch & 3;
"cmp r4, #0 \n"
"beq 3f \n"
"2: \n"
"pld [%4, #128] \n"
"vld1.f32 {d8-d9}, [%4 :128]! \n"
"pld [%5, #128] \n"
"vld1.f32 {d0-d1}, [%5 :128]! \n"
"subs r4, r4, #1 \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q9, q4, d0[1] \n"
"vmla.f32 q10, q4, d1[0] \n"
"vmla.f32 q11, q4, d1[1] \n"
"bne 2b \n"
"3: \n"
"vst1.f32 {d16-d17}, [%0 :128]! \n"
"vst1.f32 {d18-d19}, [%1 :128]! \n"
"vst1.f32 {d20-d21}, [%2 :128]! \n"
"vst1.f32 {d22-d23}, [%3 :128]! \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(outptr2), // %2
"=r"(outptr3), // %3
"=r"(tmpptr), // %4
"=r"(kptr) // %5
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(tmpptr),
"5"(kptr),
"r"(biasptr), // %12
"r"(nn) // %13
: "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11");
#endif // __aarch64__
}
for (; i < size; i++)
{
const float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + i % 4);
#if __aarch64__
const float* kptr = kernel.channel(p / 8 + (p % 8) / 4);
#else
const float* kptr = kernel.channel(p / 4);
#endif
int nn = inch * maxk; // inch always > 0
#if __aarch64__
asm volatile(
"ld1 {v12.4s}, [%12] \n"
// inch loop
"lsr w4, %w13, #2 \n" // w4 = nn = inch >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"eor v8.16b, v8.16b, v8.16b \n"
"eor v9.16b, v9.16b, v9.16b \n"
"eor v10.16b, v10.16b, v10.16b \n"
"eor v11.16b, v11.16b, v11.16b \n"
"0: \n"
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v4.4s}, [%4], #16 \n"
"prfm pldl1keep, [%5, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%5], #64 \n"
"subs w4, w4, #1 \n"
"fmla v8.4s, v0.4s, v4.s[0] \n"
"fmla v9.4s, v1.4s, v4.s[1] \n"
"fmla v10.4s, v2.4s, v4.s[2] \n"
"fmla v11.4s, v3.4s, v4.s[3] \n"
"bne 0b \n"
"fadd v8.4s, v8.4s, v9.4s \n"
"fadd v10.4s, v10.4s, v11.4s \n"
"fadd v8.4s, v8.4s, v10.4s \n"
"fadd v12.4s, v12.4s, v8.4s \n"
"1: \n"
// remain loop
"and w4, %w13, #3 \n" // w4 = remain = inch & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%4, #32] \n"
"ld1r {v4.4s}, [%4], #4 \n"
"prfm pldl1keep, [%5, #128] \n"
"ld1 {v0.4s}, [%5], #16 \n"
"subs w4, w4, #1 \n"
"fmla v12.4s, v4.4s, v0.4s \n"
"bne 2b \n"
"3: \n"
"st1 {v12.s}[0], [%0], #4 \n"
"st1 {v12.s}[1], [%1], #4 \n"
"st1 {v12.s}[2], [%2], #4 \n"
"st1 {v12.s}[3], [%3], #4 \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(outptr2), // %2
"=r"(outptr3), // %3
"=r"(tmpptr), // %4
"=r"(kptr) // %5
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(tmpptr),
"5"(kptr),
"r"(biasptr), // %12
"r"(nn) // %13
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v8", "v9", "v10", "v11", "v12");
#else // __aarch64__
asm volatile(
"vld1.f32 {d24-d25}, [%12] \n"
// inch loop
"lsr r4, %13, #2 \n" // r4 = nn = inch >> 2
"cmp r4, #0 \n"
"beq 1f \n"
"veor q8, q8, q8 \n"
"veor q9, q9, q9 \n"
"veor q10, q10, q10 \n"
"veor q11, q11, q11 \n"
"0: \n"
"pld [%4, #128] \n"
"vld1.f32 {d8-d9}, [%4 :128]! \n"
"pld [%5, #512] \n"
"vldm %5!, {d0-d7} \n"
// "vld1.f32 {d0-d3}, [%5 :128]! \n"
// "vld1.f32 {d4-d7}, [%5 :128]! \n"
"subs r4, r4, #1 \n"
"vmla.f32 q8, q0, d8[0] \n"
"vmla.f32 q9, q1, d8[1] \n"
"vmla.f32 q10, q2, d9[0] \n"
"vmla.f32 q11, q3, d9[1] \n"
"bne 0b \n"
"vadd.f32 q8, q8, q9 \n"
"vadd.f32 q10, q10, q11 \n"
"vadd.f32 q8, q8, q10 \n"
"vadd.f32 q12, q12, q8 \n"
"1: \n"
// remain loop
"and r4, %13, #3 \n" // r4 = remain = inch & 3;
"cmp r4, #0 \n"
"beq 3f \n"
"2: \n"
"pld [%4, #32] \n"
"vld1.f32 {d8[],d9[]}, [%4]! \n"
"pld [%5, #128] \n"
"vld1.f32 {d0-d1}, [%5 :128]! \n"
"subs r4, r4, #1 \n"
"vmla.f32 q12, q4, q0 \n"
"bne 2b \n"
"3: \n"
"vst1.f32 {d24[0]}, [%0]! \n"
"vst1.f32 {d24[1]}, [%1]! \n"
"vst1.f32 {d25[0]}, [%2]! \n"
"vst1.f32 {d25[1]}, [%3]! \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(outptr2), // %2
"=r"(outptr3), // %3
"=r"(tmpptr), // %4
"=r"(kptr) // %5
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(tmpptr),
"5"(kptr),
"r"(biasptr), // %12
"r"(nn) // %13
: "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q8", "q9", "q10", "q11", "q12");
#endif // __aarch64__
}
}
remain_outch_start += nn_outch << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = remain_outch_start; p < outch; p++)
{
float* outptr0 = top_blob.channel(p);
const float bias0 = bias ? bias[p] : 0.f;
int i = 0;
for (; i + 7 < size; i += 8)
{
const float* tmpptr = tmp.channel(i / 8);
#if __aarch64__
const float* kptr = kernel.channel(p / 8 + (p % 8) / 4 + p % 4);
#else
const float* kptr = kernel.channel(p / 4 + p % 4);
#endif
int nn = inch * maxk; // inch always > 0
#if __aarch64__
asm volatile(
"dup v8.4s, %w6 \n"
"dup v9.4s, %w6 \n"
// inch loop
"lsr w4, %w7, #2 \n" // w4 = nn = inch >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"0: \n"
"prfm pldl1keep, [%1, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%1], #64 \n"
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v0.4s}, [%2], #16 \n"
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v9.4s, v5.4s, v0.s[0] \n"
"prfm pldl1keep, [%1, #512] \n"
"ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%1], #64 \n"
"fmla v8.4s, v6.4s, v0.s[1] \n"
"fmla v9.4s, v7.4s, v0.s[1] \n"
"subs w4, w4, #1 \n"
"fmla v8.4s, v12.4s, v0.s[2] \n"
"fmla v9.4s, v13.4s, v0.s[2] \n"
"fmla v8.4s, v14.4s, v0.s[3] \n"
"fmla v9.4s, v15.4s, v0.s[3] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and w4, %w7, #3 \n" // w4 = remain = inch & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%1, #256] \n"
"ld1 {v4.4s, v5.4s}, [%1], #32 \n"
"prfm pldl1keep, [%2, #32] \n"
"ld1r {v0.4s}, [%2], #4 \n"
"subs w4, w4, #1 \n"
"fmla v8.4s, v4.4s, v0.4s \n"
"fmla v9.4s, v5.4s, v0.4s \n"
"bne 2b \n"
"3: \n"
"st1 {v8.4s, v9.4s}, [%0], #32 \n"
: "=r"(outptr0), // %0
"=r"(tmpptr), // %1
"=r"(kptr) // %2
: "0"(outptr0),
"1"(tmpptr),
"2"(kptr),
"r"(bias0), // %6
"r"(nn) // %7
: "cc", "memory", "x4", "v0", "v4", "v5", "v6", "v7", "v8", "v9", "v12", "v13", "v14", "v15");
#else // __aarch64__
asm volatile(
"vdup.f32 q8, %6 \n"
"vdup.f32 q9, %6 \n"
// inch loop
"lsr r4, %7, #2 \n" // r4 = nn = inch >> 2
"cmp r4, #0 \n"
"beq 1f \n"
"0: \n"
"pld [%1, #512] \n"
"vldm %1!, {d8-d15} \n"
// "vld1.f32 {d8-d11}, [%1 :128]! \n"
// "vld1.f32 {d12-d15}, [%1 :128]! \n"
"pld [%2, #128] \n"
"vld1.f32 {d0-d1}, [%2 :128]! \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q9, q5, d0[0] \n"
"pld [%1, #512] \n"
"vldm %1!, {d24-d31} \n"
// "vld1.f32 {d24-d27}, [%1 :128]! \n"
// "vld1.f32 {d28-d31}, [%1 :128]! \n"
"vmla.f32 q8, q6, d0[1] \n"
"vmla.f32 q9, q7, d0[1] \n"
"subs r4, r4, #1 \n"
"vmla.f32 q8, q12, d1[0] \n"
"vmla.f32 q9, q13, d1[0] \n"
"vmla.f32 q8, q14, d1[1] \n"
"vmla.f32 q9, q15, d1[1] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and r4, %7, #3 \n" // r4 = remain = inch & 3;
"cmp r4, #0 \n"
"beq 3f \n"
"2: \n"
"pld [%1, #256] \n"
"vld1.f32 {d8-d11}, [%1 :128]! \n"
"pld [%2, #32] \n"
"vld1.f32 {d0[],d1[]}, [%2]! \n"
"subs r4, r4, #1 \n"
"vmla.f32 q8, q4, q0 \n"
"vmla.f32 q9, q5, q0 \n"
"bne 2b \n"
"3: \n"
"vst1.f32 {d16-d19}, [%0 :128]! \n"
: "=r"(outptr0), // %0
"=r"(tmpptr), // %1
"=r"(kptr) // %2
: "0"(outptr0),
"1"(tmpptr),
"2"(kptr),
"r"(bias0), // %6
"r"(nn) // %7
: "cc", "memory", "r4", "q0", "q4", "q5", "q6", "q7", "q8", "q9", "q12", "q13", "q14", "q15");
#endif // __aarch64__
}
for (; i + 3 < size; i += 4)
{
const float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4);
#if __aarch64__
const float* kptr = kernel.channel(p / 8 + (p % 8) / 4 + p % 4);
#else
const float* kptr = kernel.channel(p / 4 + p % 4);
#endif
int nn = inch * maxk; // inch always > 0
#if __aarch64__
asm volatile(
"dup v8.4s, %w6 \n"
// inch loop
"lsr w4, %w7, #2 \n" // w4 = nn = inch >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"0: \n"
"prfm pldl1keep, [%1, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%1], #64 \n"
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v0.4s}, [%2], #16 \n"
"subs w4, w4, #1 \n"
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v8.4s, v5.4s, v0.s[1] \n"
"fmla v8.4s, v6.4s, v0.s[2] \n"
"fmla v8.4s, v7.4s, v0.s[3] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and w4, %w7, #3 \n" // w4 = remain = inch & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%1, #128] \n"
"ld1 {v4.4s}, [%1], #16 \n"
"prfm pldl1keep, [%2, #32] \n"
"ld1r {v0.4s}, [%2], #4 \n"
"subs w4, w4, #1 \n"
"fmla v8.4s, v4.4s, v0.4s \n"
"bne 2b \n"
"3: \n"
"st1 {v8.4s}, [%0], #16 \n"
: "=r"(outptr0), // %0
"=r"(tmpptr), // %1
"=r"(kptr) // %2
: "0"(outptr0),
"1"(tmpptr),
"2"(kptr),
"r"(bias0), // %6
"r"(nn) // %7
: "cc", "memory", "x4", "v0", "v4", "v5", "v6", "v7", "v8");
#else // __aarch64__
asm volatile(
"vdup.f32 q8, %6 \n"
// inch loop
"lsr r4, %7, #2 \n" // r4 = nn = inch >> 2
"cmp r4, #0 \n"
"beq 1f \n"
"0: \n"
"pld [%1, #512] \n"
"vldm %1!, {d8-d15} \n"
// "vld1.f32 {d8-d11}, [%1 :128]! \n"
// "vld1.f32 {d12-d15}, [%1 :128]! \n"
"pld [%2, #128] \n"
"vld1.f32 {d0-d1}, [%2]! \n"
"subs r4, r4, #1 \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q8, q5, d0[1] \n"
"vmla.f32 q8, q6, d1[0] \n"
"vmla.f32 q8, q7, d1[1] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and r4, %7, #3 \n" // r4 = remain = inch & 3;
"cmp r4, #0 \n"
"beq 3f \n"
"2: \n"
"pld [%1, #128] \n"
"vld1.f32 {d8-d9}, [%1 :128]! \n"
"pld [%2, #32] \n"
"vld1.f32 {d0[],d1[]}, [%2]! \n"
"subs r4, r4, #1 \n"
"vmla.f32 q8, q4, q0 \n"
"bne 2b \n"
"3: \n"
"vst1.f32 {d16-d17}, [%0 :128]! \n"
: "=r"(outptr0), // %0
"=r"(tmpptr), // %1
"=r"(kptr) // %2
: "0"(outptr0),
"1"(tmpptr),
"2"(kptr),
"r"(bias0), // %6
"r"(nn) // %7
: "cc", "memory", "r4", "q0", "q4", "q5", "q6", "q7", "q8");
#endif // __aarch64__
}
for (; i < size; i++)
{
const float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + i % 4);
#if __aarch64__
const float* kptr = kernel.channel(p / 8 + (p % 8) / 4 + p % 4);
#else
const float* kptr = kernel.channel(p / 4 + p % 4);
#endif
int nn = inch * maxk; // inch always > 0
float32x4_t _sum0 = vdupq_n_f32(0.f);
int q = 0;
for (; q + 3 < nn; q += 4)
{
float32x4_t _p0 = vld1q_f32(tmpptr);
tmpptr += 4;
float32x4_t _k0 = vld1q_f32(kptr);
kptr += 4;
#if __aarch64__
_sum0 = vfmaq_f32(_sum0, _p0, _k0);
#else
_sum0 = vmlaq_f32(_sum0, _p0, _k0);
#endif
}
#if __aarch64__
float sum0 = bias0 + vaddvq_f32(_sum0);
#else
float32x2_t _ss = vadd_f32(vget_low_f32(_sum0), vget_high_f32(_sum0));
float sum0 = bias0 + vget_lane_f32(vpadd_f32(_ss, _ss), 0);
#endif
for (; q < nn; q++)
{
sum0 += tmpptr[0] * kptr[0];
tmpptr++;
kptr++;
}
outptr0[0] = sum0;
outptr0++;
}
}
#else // __ARM_NEON
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
float* outptr0 = top_blob.channel(p);
const float bias0 = bias ? bias[p] : 0.f;
for (int i = 0; i < size; i++)
{
const float* tmpptr = tmp.channel(i);
const float* kptr = kernel.channel(p);
int nn = inch * maxk; // inch always > 0
float sum0 = bias0;
for (int q = 0; q < nn; q++)
{
sum0 += tmpptr[0] * kptr[0];
tmpptr++;
kptr++;
}
outptr0[0] = sum0;
outptr0++;
}
}
#endif // __ARM_NEON
}
static void convolution_im2col_sgemm_transform_kernel_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_w, int kernel_h)
{
const int maxk = kernel_w * kernel_h;
// interleave
// src = maxk-inch-outch
// dst = 4b-4a-maxk-inch/4a-outch/4b
Mat kernel = _kernel.reshape(maxk, inch, outch);
#if __ARM_NEON
#if __aarch64__
kernel_tm.create(32 * maxk, inch / 4 + inch % 4, outch / 8 + (outch % 8) / 4 + outch % 4);
#else
kernel_tm.create(16 * maxk, inch / 4 + inch % 4, outch / 4 + outch % 4);
#endif
int q = 0;
#if __aarch64__
for (; q + 7 < outch; q += 8)
{
const Mat k0 = kernel.channel(q);
const Mat k1 = kernel.channel(q + 1);
const Mat k2 = kernel.channel(q + 2);
const Mat k3 = kernel.channel(q + 3);
const Mat k4 = kernel.channel(q + 4);
const Mat k5 = kernel.channel(q + 5);
const Mat k6 = kernel.channel(q + 6);
const Mat k7 = kernel.channel(q + 7);
float* g00 = kernel_tm.channel(q / 8);
for (int p = 0; p < inch; p++)
{
const float* k00 = k0.row(p);
const float* k10 = k1.row(p);
const float* k20 = k2.row(p);
const float* k30 = k3.row(p);
const float* k40 = k4.row(p);
const float* k50 = k5.row(p);
const float* k60 = k6.row(p);
const float* k70 = k7.row(p);
for (int k = 0; k < maxk; k++)
{
g00[0] = k00[k];
g00[1] = k10[k];
g00[2] = k20[k];
g00[3] = k30[k];
g00[4] = k40[k];
g00[5] = k50[k];
g00[6] = k60[k];
g00[7] = k70[k];
g00 += 8;
}
}
}
#endif // __aarch64__
for (; q + 3 < outch; q += 4)
{
const Mat k0 = kernel.channel(q);
const Mat k1 = kernel.channel(q + 1);
const Mat k2 = kernel.channel(q + 2);
const Mat k3 = kernel.channel(q + 3);
#if __aarch64__
float* g00 = kernel_tm.channel(q / 8 + (q % 8) / 4);
#else
float* g00 = kernel_tm.channel(q / 4);
#endif
for (int p = 0; p < inch; p++)
{
const float* k00 = k0.row(p);
const float* k10 = k1.row(p);
const float* k20 = k2.row(p);
const float* k30 = k3.row(p);
for (int k = 0; k < maxk; k++)
{
g00[0] = k00[k];
g00[1] = k10[k];
g00[2] = k20[k];
g00[3] = k30[k];
g00 += 4;
}
}
}
for (; q < outch; q++)
{
const Mat k0 = kernel.channel(q);
#if __aarch64__
float* g00 = kernel_tm.channel(q / 8 + (q % 8) / 4 + q % 4);
#else
float* g00 = kernel_tm.channel(q / 4 + q % 4);
#endif
for (int p = 0; p < inch; p++)
{
const float* k00 = k0.row(p);
for (int k = 0; k < maxk; k++)
{
g00[0] = k00[k];
g00 += 1;
}
}
}
#else
kernel_tm = kernel;
#endif // __ARM_NEON
}
static void convolution_im2col_sgemm_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, const Option& opt)
{
int w = bottom_blob.w;
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
const int size = outw * outh;
const int maxk = kernel_w * kernel_h;
// im2col
Mat bottom_im2col(size, maxk, inch, 4u, 1, opt.workspace_allocator);
{
const int gap = w * stride_h - outw * stride_w;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < inch; p++)
{
const Mat img = bottom_blob.channel(p);
float* ptr = bottom_im2col.channel(p);
for (int u = 0; u < kernel_h; u++)
{
for (int v = 0; v < kernel_w; v++)
{
const float* sptr = img.row<const float>(dilation_h * u) + dilation_w * v;
for (int i = 0; i < outh; i++)
{
int j = 0;
for (; j + 3 < outw; j += 4)
{
ptr[0] = sptr[0];
ptr[1] = sptr[stride_w];
ptr[2] = sptr[stride_w * 2];
ptr[3] = sptr[stride_w * 3];
sptr += stride_w * 4;
ptr += 4;
}
for (; j + 1 < outw; j += 2)
{
ptr[0] = sptr[0];
ptr[1] = sptr[stride_w];
sptr += stride_w * 2;
ptr += 2;
}
for (; j < outw; j++)
{
ptr[0] = sptr[0];
sptr += stride_w;
ptr += 1;
}
sptr += gap;
}
}
}
}
}
im2col_sgemm_neon(bottom_im2col, top_blob, kernel, _bias, opt);
}
|
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] = 24;
tile_size[1] = 24;
tile_size[2] = 16;
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;
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,12);t1++) {
lbp=max(ceild(t1,2),ceild(24*t1-Nt+3,24));
ubp=min(floord(Nt+Nz-4,24),floord(12*t1+Nz+9,24));
#pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8)
for (t2=lbp;t2<=ubp;t2++) {
for (t3=max(max(0,ceild(3*t1-3,4)),ceild(24*t2-Nz-12,16));t3<=min(min(min(floord(Nt+Ny-4,16),floord(12*t1+Ny+21,16)),floord(24*t2+Ny+20,16)),floord(24*t1-24*t2+Nz+Ny+19,16));t3++) {
for (t4=max(max(max(0,ceild(3*t1-31,32)),ceild(24*t2-Nz-124,128)),ceild(16*t3-Ny-124,128));t4<=min(min(min(min(floord(Nt+Nx-4,128),floord(12*t1+Nx+21,128)),floord(24*t2+Nx+20,128)),floord(16*t3+Nx+12,128)),floord(24*t1-24*t2+Nz+Nx+19,128));t4++) {
for (t5=max(max(max(max(max(0,12*t1),24*t1-24*t2+1),24*t2-Nz+2),16*t3-Ny+2),128*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,12*t1+23),24*t2+22),16*t3+14),128*t4+126),24*t1-24*t2+Nz+21);t5++) {
for (t6=max(max(24*t2,t5+1),-24*t1+24*t2+2*t5-23);t6<=min(min(24*t2+23,-24*t1+24*t2+2*t5),t5+Nz-2);t6++) {
for (t7=max(16*t3,t5+1);t7<=min(16*t3+15,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)] = ((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;
}
|
THTensorConv.c
|
#ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "generic/THTensorConv.c"
#else
/*
2D Input, 2D kernel : convolve given image with the given kernel.
*/
void THTensor_(validXCorr2Dptr)(real *r_,
real alpha,
real *t_, long ir, long ic,
real *k_, long kr, long kc,
long sr, long sc)
{
long or = (ir - kr) / sr + 1;
long oc = (ic - kc) / sc + 1;
long xx, yy, kx, ky;
if ((sc != 1) || (oc < 4)) {
/* regular convolution */
for(yy = 0; yy < or; yy++) {
for(xx = 0; xx < oc; xx++) {
/* Dot product in two dimensions... (between input image and the mask) */
real *pi_ = t_ + yy*sr*ic + xx*sc;
real *pw_ = k_;
real sum = 0;
for(ky = 0; ky < kr; ky++) {
for(kx = 0; kx < kc; kx++) {
sum += pi_[kx]*pw_[kx];
}
pi_ += ic; /* next input line */
pw_ += kc; /* next mask line */
}
/* Update output */
*r_++ += alpha*sum;
}
}
} else {
/* SSE-based convolution */
for(yy = 0; yy < or; yy++) {
real *pi_ = t_ + yy*sr*ic;
real *pw_ = k_;
for (ky = 0; ky < kr; ky++) {
real *pis_ = pi_;
for (kx = 0; kx < kc; kx++) {
THVector_(cadd)(r_, r_, pis_, alpha*pw_[kx], oc);
pis_++;
}
pi_ += ic; /* next input line */
pw_ += kc; /* next mask line */
}
r_ += oc;
}
}
}
/*
2D Input, 2D kernel : convolve given image with the given kernel.
*/
void THTensor_(validConv2Dptr)(real *r_,
real alpha,
real *t_, long ir, long ic,
real *k_, long kr, long kc,
long sr, long sc)
{
long or = (ir - kr) / sr + 1;
long oc = (ic - kc) / sc + 1;
long xx, yy, kx, ky;
if ((sc != 1) || (oc < 4)) {
/* regular convolution */
for(yy = 0; yy < or; yy++) {
for(xx = 0; xx < oc; xx++) {
/* Dot product in two dimensions... (between input image and the mask) */
real *pi_ = t_ + yy*sr*ic + xx*sc;
real *pw_ = k_ + kr*kc - 1;
real sum = 0;
for(ky = 0; ky < kr; ky++) {
for(kx = 0; kx < kc; kx++) {
sum += pi_[kx]*pw_[-kx];
}
pi_ += ic; /* next input line */
pw_ -= kc; /* next mask line */
}
/* Update output */
*r_++ += alpha*sum;
}
}
} else {
/* SSE-based convolution */
for(yy = 0; yy < or; yy++) {
real *pw_ = k_ + kr*kc - 1;
real *pi_ = t_ + yy*sr*ic;
for (ky = 0; ky < kr; ky++) {
real *pis_ = pi_;
for (kx = 0; kx < kc; kx++) {
THVector_(cadd)(r_, r_, pis_, alpha*pw_[-kx], oc);
pis_++;
}
pi_ += ic; /* next input line */
pw_ -= kc; /* next mask line */
}
r_ += oc;
}
}
}
/*
2D Input, 2D kernel : convolve given image with the given kernel, full convolution.
*/
void THTensor_(fullConv2Dptr)(real *r_,
real alpha,
real *t_, long ir, long ic,
real *k_, long kr, long kc,
long sr, long sc)
{
long oc = (ic - 1) * sc + kc;
long xx, yy, kx, ky;
if ((sc != 1) || (ic < 4)) {
/* regular convolution */
for(yy = 0; yy < ir; yy++) {
for(xx = 0; xx < ic; xx++) {
/* Outer product in two dimensions... (between input image and the mask) */
real *po_ = r_ + yy*sr*oc + xx*sc;
real *pw_ = k_;
for(ky = 0; ky < kr; ky++)
{
real z = *t_ * alpha;
for(kx = 0; kx < kc; kx++) {
po_[kx] += z * pw_[kx];
}
po_ += oc; /* next input line */
pw_ += kc; /* next mask line */
}
t_++;
}
}
} else {
/* SSE-based convolution */
for(yy = 0; yy < ir; yy++) {
real *po_ = r_ + yy*sr*oc;
real *pw_ = k_;
for (ky = 0; ky < kr; ky++) {
real *pos_ = po_;
for (kx = 0; kx < kc; kx++) {
THVector_(cadd)(pos_, pos_, t_, alpha*pw_[kx], ic);
pos_++;
}
po_ += oc; /* next input line */
pw_ += kc; /* next mask line */
}
t_ += ic;
}
}
}
/*
2D Input, 2D kernel : convolve given image with the given kernel, full convolution.
*/
void THTensor_(fullXCorr2Dptr)(real *r_,
real alpha,
real *t_, long ir, long ic,
real *k_, long kr, long kc,
long sr, long sc)
{
long oc = (ic - 1) * sc + kc;
long xx, yy, kx, ky;
if ((sc != 1) || (ic < 4)) {
/* regular convolution */
for(yy = 0; yy < ir; yy++) {
for(xx = 0; xx < ic; xx++) {
/* Outer product in two dimensions... (between input image and the mask) */
real *po_ = r_ + yy*sr*oc + xx*sc;
real *pw_ = k_ + kr*kc -1;
long kx, ky;
for(ky = 0; ky < kr; ky++)
{
real z = *t_ * alpha;
for(kx = 0; kx < kc; kx++) {
po_[kx] += z * pw_[-kx];
}
po_ += oc; /* next input line */
pw_ -= kc; /* next mask line */
}
t_++;
}
}
} else {
/* SSE-based convolution */
for(yy = 0; yy < ir; yy++) {
real *po_ = r_ + yy*sr*oc;
real *pw_ = k_ + kr*kc -1;
for (ky = 0; ky < kr; ky++) {
real *pos_ = po_;
for (kx = 0; kx < kc; kx++) {
THVector_(cadd)(pos_, pos_, t_, pw_[-kx]*alpha, ic);
pos_++;
}
po_ += oc; /* next input line */
pw_ -= kc; /* next mask line */
}
t_ += ic;
}
}
}
/*
2D Input, 2D kernel : convolve given image with the given kernel, valid convolution.
for sr,sc=1 this is equivalent to validXCorr2Dptr, but otherwise it is useful for
calculating derivatives wrt a kernel that is applied with stride sr,sc != 1
*/
void THTensor_(validXCorr2DRevptr)(real *r_,
real alpha,
real *t_, long ir, long ic,
real *k_, long kr, long kc,
long sr, long sc)
{
long or = ir - (kr - 1) * sr;
long oc = ic - (kc - 1) * sc;
long xx, yy, kx, ky;
if ((sc != 1) || (kc < 4)) {
/* regular convolution */
for(yy = 0; yy < kr; yy++) {
for(xx = 0; xx < kc; xx++) {
real *po_ = r_;
real *pi_ = t_ + yy*sr*ic + xx*sc;
real z = *k_++ * alpha;
for(ky = 0; ky < or; ky++) {
for(kx = 0; kx < oc; kx++)
po_[kx] += z * pi_[kx];
pi_ += ic;
po_ += oc;
}
}
}
} else {
/* SSE-based convolution */
for(yy = 0; yy < kr; yy++) {
for(xx = 0; xx < kc; xx++) {
real *po_ = r_;
real *pi_ = t_ + yy*sr*ic + xx*sc;
real z = *k_++ * alpha;
for(ky = 0; ky < or; ky++) {
THVector_(cadd)(po_, po_, pi_, z, oc);
pi_ += ic;
po_ += oc;
}
}
}
}
}
/*
3D Input, 3D kernel : convolve given volume with the given kernel.
*/
void THTensor_(validXCorr3Dptr)(real *r_,
real alpha,
real *t_, long it, long ir, long ic,
real *k_, long kt, long kr, long kc,
long st, long sr, long sc)
{
long ot = (it - kt) / st + 1;
long or = (ir - kr) / sr + 1;
long oc = (ic - kc) / sc + 1;
long zz, xx, yy;
for (zz = 0; zz < ot; zz++)
{
for(yy = 0; yy < or; yy++)
{
for(xx = 0; xx < oc; xx++)
{
/* Dot product in two dimensions... (between input image and the mask) */
real *pi_ = t_ + zz*st*ir*ic + yy*sr*ic + xx*sc;
real *pw_ = k_;
real sum = 0;
long kz, kx, ky;
for(kz = 0; kz < kt; kz++)
{
for(ky = 0; ky < kr; ky++)
{
for(kx = 0; kx < kc; kx++) {
sum += pi_[kx]*pw_[kx];
}
pi_ += ic; /* next input line */
pw_ += kc; /* next mask line */
}
pi_ += (ir-kr)*ic; /* next input slice */
}
/* Update output */
*r_++ += sum*alpha;
}
}
}
}
/*
3D Input, 3D kernel : convolve given volume with the given kernel.
*/
void THTensor_(validConv3Dptr)(real *r_,
real alpha,
real *t_, long it, long ir, long ic,
real *k_, long kt, long kr, long kc,
long st, long sr, long sc)
{
long ot = (it - kt) / st + 1;
long or = (ir - kr) / sr + 1;
long oc = (ic - kc) / sc + 1;
long zz, xx, yy;
for(zz = 0; zz < ot; zz++)
{
for(yy = 0; yy < or; yy++)
{
for(xx = 0; xx < oc; xx++)
{
/* Dot product in two dimensions... (between input image and the mask) */
real *pi_ = t_ + zz*st*ir*ic + yy*sr*ic + xx*sc;
real *pw_ = k_ + kt*kr*kc - 1;
real sum = 0;
long kz, kx, ky;
for(kz = 0; kz < kt; kz++)
{
for(ky = 0; ky < kr; ky++)
{
for(kx = 0; kx < kc; kx++) {
sum += pi_[kx]*pw_[-kx];
}
pi_ += ic; /* next input line */
pw_ -= kc; /* next mask line */
}
pi_ += (ir-kr)*ic; /* next input slice */
}
/* Update output */
*r_++ += alpha*sum;
}
}
}
}
/*
3D Input, 3D kernel : convolve given volume with the given kernel, full convolution.
*/
void THTensor_(fullConv3Dptr)(real *r_,
real alpha,
real *t_, long it, long ir, long ic,
real *k_, long kt, long kr, long kc,
long st, long sr, long sc)
{
long or = (ir - 1) * sr + kr;
long oc = (ic - 1) * sc + kc;
long zz, xx, yy;
for(zz = 0; zz < it; zz++)
{
for(yy = 0; yy < ir; yy++)
{
for(xx = 0; xx < ic; xx++)
{
/* Outer product in two dimensions... (between input image and the mask) */
real *po_ = r_ + zz*st*or*oc + yy*sr*oc + xx*sc;
real *pw_ = k_;
long kz, kx, ky;
/* printf("Output Plane : %ld,%ld,%ld, input val=%g\n",zz,yy,xx,*t_); */
for(kz = 0; kz < kt; kz++)
{
for(ky = 0; ky < kr; ky++)
{
real z = *t_ * alpha;
for(kx = 0; kx < kc; kx++) {
/* printf("o=%g,k=%g," , po_[kx],pw_[kx]); */
po_[kx] += z * pw_[kx];
/* printf("o=%g " , po_[kx]); */
}
/* printf("\n"); */
po_ += oc; /* next input line */
pw_ += kc; /* next mask line */
}
po_ += (or-kr)*oc; /* next output slice */
/* printf("\n"); */
}
t_++;
}
}
}
}
/*
3D Input, 3D kernel : convolve given volume with the given kernel, full convolution.
*/
void THTensor_(fullXCorr3Dptr)(real *r_,
real alpha,
real *t_, long it, long ir, long ic,
real *k_, long kt, long kr, long kc,
long st, long sr, long sc)
{
long or = (ir - 1) * sr + kr;
long oc = (ic - 1) * sc + kc;
long zz, xx, yy;
for(zz = 0; zz < it; zz++)
{
for(yy = 0; yy < ir; yy++)
{
for(xx = 0; xx < ic; xx++)
{
/* Outer product in two dimensions... (between input image and the mask) */
real *po_ = r_ + zz*st*or*oc + yy*sr*oc + xx*sc;
real *pw_ = k_ + kt*kr*kc -1;
long kz, kx, ky;
for(kz = 0; kz < kt; kz++)
{
for(ky = 0; ky < kr; ky++)
{
real z = *t_ * alpha;
for(kx = 0; kx < kc; kx++) {
po_[kx] += z * pw_[-kx];
}
po_ += oc; /* next input line */
pw_ -= kc; /* next mask line */
}
po_ += (or-kr)*oc; /* next output slice */
}
t_++;
}
}
}
}
/*
3D Input, 3D kernel : convolve given image with the given kernel, valid convolution.
for sr,sc=1 this is equivalent to validXCorr3Dptr, but otherwise it is useful for
calculating derivatives wrt a kernel that is applied with stride sr,sc != 1
*/
void THTensor_(validXCorr3DRevptr)(real *r_,
real alpha,
real *t_, long it, long ir, long ic,
real *k_, long kt, long kr, long kc,
long st, long sr, long sc)
{
long ot = it - (kt - 1) * st;
long or = ir - (kr - 1) * sr;
long oc = ic - (kc - 1) * sc;
long zz, xx, yy;
for(zz = 0; zz < kt; zz++)
{
for(yy = 0; yy < kr; yy++)
{
for(xx = 0; xx < kc; xx++)
{
real *po_ = r_;
real *pi_ = t_ + zz*st*ir*ic + yy*sr*ic + xx*sc;
real z = *k_++ * alpha;
long kz, kx, ky;
for(kz = 0; kz < ot; kz++)
{
for(ky = 0; ky < or; ky++)
{
for(kx = 0; kx < oc; kx++)
po_[kx] += z * pi_[kx];
pi_ += ic;
po_ += oc;
}
pi_ += (ir-or)*ic; /* next input slice */
}
}
}
}
}
void THTensor_(conv2d)(real* output_data,
real alpha,
real* ptr_input, long nInputRows, long nInputCols,
real* ptr_weight, long nKernelRows, long nKernelCols,
long srow, long scol,
const char *vf, const char *xc)
{
THArgCheck(*vf == 'V' || *vf == 'F', 7, "type of convolution can be 'V' or 'F'");
THArgCheck(*xc == 'C' || *xc == 'X', 7, "type of convolution can be 'X' or 'C'");
if (*vf == 'F')
if (*xc == 'X')
THTensor_(fullXCorr2Dptr)(output_data,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
else
THTensor_(fullConv2Dptr)(output_data,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
else
if (*xc == 'X')
THTensor_(validXCorr2Dptr)(output_data,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
else
THTensor_(validConv2Dptr)(output_data,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
}
void THTensor_(conv3d)(real* output_data,
real alpha,
real* ptr_input, long nInputDepth, long nInputRows, long nInputCols,
real* ptr_weight, long nKernelDepth, long nKernelRows, long nKernelCols,
long sdepth, long srow, long scol,
const char *vf, const char *xc)
{
THArgCheck(*vf == 'V' || *vf == 'F', 7, "type of convolution can be 'V' or 'F'");
THArgCheck(*xc == 'C' || *xc == 'X', 7, "type of convolution can be 'X' or 'C'");
if (*vf == 'F')
if (*xc == 'X')
THTensor_(fullXCorr3Dptr)(output_data,
alpha,
ptr_input, nInputDepth, nInputRows, nInputCols,
ptr_weight, nKernelDepth, nKernelRows, nKernelCols,
sdepth, srow, scol);
else
THTensor_(fullConv3Dptr)(output_data,
alpha,
ptr_input, nInputDepth, nInputRows, nInputCols,
ptr_weight, nKernelDepth, nKernelRows, nKernelCols,
sdepth, srow, scol);
else
if (*xc == 'X')
THTensor_(validXCorr3Dptr)(output_data,
alpha,
ptr_input, nInputDepth, nInputRows, nInputCols,
ptr_weight, nKernelDepth, nKernelRows, nKernelCols,
sdepth, srow, scol);
else
THTensor_(validConv3Dptr)(output_data,
alpha,
ptr_input, nInputDepth, nInputRows, nInputCols,
ptr_weight, nKernelDepth, nKernelRows, nKernelCols,
sdepth, srow, scol);
}
long THTensor_(convsize)(long x, long k, long s, const char* vf)
{
THArgCheck(*vf == 'V' || *vf == 'F', 1, "type of convolution can be 'V' or 'F'");
if (*vf == 'V')
return (x-k)/s + 1;
else
return (x-1)*s + k;
}
/*
3D input, 3D kernel, 4D output
like rank1 update
A <- xx' + beta*A
for sr,sc=1 this is equivalent to conv2Dger, but otherwise it is useful for
calculating derivatives wrt a kernel that is applied with stride sr,sc != 1
*/
void THTensor_(conv2DRevger)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_, long srow, long scol)
{
long nInputPlane, nInputRows, nInputCols;
long nKernelPlane, nKernelRows, nKernelCols;
long nOutputPlane, nOutputRows, nOutputCols;
long istride0, kstride0;
THTensor *input;
THTensor *kernel;
real *input_data;
real *weight_data;
real *output_data;
ptrdiff_t nelem;
long k;
THArgCheck(t_->nDimension == 3 , 3, "input: 3D Tensor expected");
THArgCheck(k_->nDimension == 3 , 4, "kernel: 3D Tensor expected");
THArgCheck(srow >= 1, 5, "Stride should be a positive integer");
THArgCheck(scol >= 1, 6, "Stride should be a positive integer");
input = THTensor_(newContiguous)(t_);
kernel = THTensor_(newContiguous)(k_);
nInputPlane = input->size[0];
istride0 = input->stride[0];
nInputRows = input->size[1];
nInputCols = input->size[2];
kstride0 = kernel->stride[0];
nKernelPlane = kernel->size[0];
nKernelRows = kernel->size[1];
nKernelCols = kernel->size[2];
nOutputPlane = nInputPlane * kernel->size[0];
THArgCheck(nInputRows >= nKernelRows && nInputCols >= nKernelCols , 2, "covn2DRevger : Input image is smaller than kernel");
nOutputRows = nInputRows - (nKernelRows - 1) * srow;
nOutputCols = nInputCols - (nKernelCols - 1) * scol;
nelem = THTensor_(nElement)(r_);
THTensor_(resize4d)(r_,nKernelPlane, nInputPlane, nOutputRows, nOutputCols);
input_data = THTensor_(data)(input);
weight_data = THTensor_(data)(kernel);
output_data = THTensor_(data)(r_);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
{
/*THTensor_(zero)(r_);*/
#pragma omp parallel for private(k)
for (k = 0; k < r_->size[0]*r_->size[1]; k++)
{
real* ptr_output = output_data + k*nOutputCols*nOutputRows;
long l;
for (l = 0; l < nOutputRows*nOutputCols; l++)
ptr_output[l] = 0.0;
}
}
else if (beta != 1)
{
/*THTensor_(mul)(r_, beta);*/
#pragma omp parallel for private(k)
for (k = 0; k < r_->size[0]*r_->size[1]; k++)
{
real* ptr_output = output_data + k*nOutputCols*nOutputRows;
long l;
for (l = 0; l < nOutputRows*nOutputCols; l++)
ptr_output[l] *= beta;
}
}
#pragma omp parallel for private(k)
for(k = 0; k < nKernelPlane; k++)
{
long i;
/* get kernel */
real *ptr_weight = weight_data+k*kstride0;
for(i = 0; i < nInputPlane; i++)
{
/* get output */
real *ptr_output = output_data + k*nInputPlane*nOutputCols*nOutputRows + i*nOutputCols*nOutputRows;
/* get input */
real *ptr_input = input_data+i*istride0;
/* do image, kernel convolution */
THTensor_(validXCorr2DRevptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
/* Next output plane */
/* output_data += nOutputCols*nOutputRows; */
}
}
THTensor_(free)(input);
THTensor_(free)(kernel);
}
/*
3D input, 3D kernel, 4D output
like rank1 update
A <- xx' + beta*A
for sr,sc=1 this is equivalent to conv2Dger, but otherwise it is useful for
calculating derivatives wrt a kernel that is applied with stride sr,sc != 1
*/
void THTensor_(conv2DRevgerm)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_, long srow, long scol)
{
long nbatch, nInputPlane, nInputRows, nInputCols;
long nKernelPlane, nKernelRows, nKernelCols;
long nOutputRows, nOutputCols;
long istride0, kstride0, istride1, kstride1;
THTensor *input;
THTensor *kernel;
real *input_data;
real *weight_data;
real *output_data;
ptrdiff_t nelem;
long k;
THArgCheck(t_->nDimension == 4 , 3, "input: 4D Tensor expected");
THArgCheck(k_->nDimension == 4 , 4, "kernel: 4D Tensor expected");
THArgCheck(srow >= 1, 5, "Stride should be a positive integer");
THArgCheck(scol >= 1, 6, "Stride should be a positive integer");
input = THTensor_(newContiguous)(t_);
kernel = THTensor_(newContiguous)(k_);
istride0 = input->stride[0];
istride1 = input->stride[1];
nbatch = input->size[0];
nInputPlane = input->size[1];
nInputRows = input->size[2];
nInputCols = input->size[3];
kstride0 = kernel->stride[0];
kstride1 = kernel->stride[1];
nKernelPlane = kernel->size[1];
nKernelRows = kernel->size[2];
nKernelCols = kernel->size[3];
THArgCheck(nInputRows >= nKernelRows && nInputCols >= nKernelCols , 2, "conv2DRevger : Input image is smaller than kernel");
THArgCheck(kernel->size[0] == input->size[0] , 2, "conv2DRevger : Input batch and kernel batch is not same size");
nOutputRows = nInputRows - (nKernelRows - 1) * srow;
nOutputCols = nInputCols - (nKernelCols - 1) * scol;
nelem = THTensor_(nElement)(r_);
THTensor_(resize4d)(r_,nKernelPlane, nInputPlane, nOutputRows, nOutputCols);
input_data = THTensor_(data)(input);
weight_data = THTensor_(data)(kernel);
output_data = THTensor_(data)(r_);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
{
/*THTensor_(zero)(r_);*/
#pragma omp parallel for private(k)
for (k = 0; k < r_->size[0]*r_->size[1]; k++)
{
real* ptr_output = output_data + k*nOutputCols*nOutputRows;
long l;
for (l = 0; l < nOutputRows*nOutputCols; l++)
ptr_output[l] = 0.0;
}
}
else if (beta != 1)
{
/*THTensor_(mul)(r_, beta);*/
#pragma omp parallel for private(k)
for (k = 0; k < r_->size[0]*r_->size[1]; k++)
{
real* ptr_output = output_data + k*nOutputCols*nOutputRows;
long l;
for (l = 0; l < nOutputRows*nOutputCols; l++)
ptr_output[l] *= beta;
}
}
#pragma omp parallel for private(k)
for(k = 0; k < nKernelPlane; k++)
{
long i;
for(i = 0; i < nInputPlane; i++)
{
long p;
for(p = 0; p < nbatch; p++)
{
/* get kernel */
real *ptr_weight = weight_data + p*kstride0 + k*kstride1;
/* get output */
real *ptr_output = output_data + k*nInputPlane*nOutputCols*nOutputRows + i*nOutputCols*nOutputRows;
/* get input */
real *ptr_input = input_data + p*istride0 + i*istride1;
/* do image, kernel convolution */
THTensor_(validXCorr2DRevptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
/* Next output plane */
/* output_data += nOutputCols*nOutputRows; */
}
}
}
THTensor_(free)(input);
THTensor_(free)(kernel);
}
/*
3D input, 3D kernel, 4D output
like rank1 update
A <- xx' + beta*A
*/
void THTensor_(conv2Dger)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_, long srow, long scol, const char *vf, const char *xc)
{
long nInputPlane, nInputRows, nInputCols;
long nKernelPlane, nKernelRows, nKernelCols;
long nOutputPlane, nOutputRows, nOutputCols;
long istride0, kstride0;
THTensor *input;
THTensor *kernel;
real *input_data;
real *weight_data;
real *output_data;
ptrdiff_t nelem;
long k;
THArgCheck(t_->nDimension == 3 , 3, "input: 3D Tensor expected");
THArgCheck(k_->nDimension == 3 , 4, "kernel: 3D Tensor expected");
THArgCheck(srow >= 1, 5, "Stride should be a positive integer");
THArgCheck(scol >= 1, 6, "Stride should be a positive integer");
THArgCheck(*vf == 'V' || *vf == 'F', 7, "type of convolution can 'V' or 'F'");
THArgCheck(*xc == 'C' || *xc == 'X', 7, "type of convolution can 'X' or 'C'");
input = THTensor_(newContiguous)(t_);
kernel = THTensor_(newContiguous)(k_);
nInputPlane = input->size[0];
istride0 = input->stride[0];
nInputRows = input->size[1];
nInputCols = input->size[2];
kstride0 = kernel->stride[0];
nKernelPlane = kernel->size[0];
nKernelRows = kernel->size[1];
nKernelCols = kernel->size[2];
nOutputPlane = nInputPlane * kernel->size[0];
THArgCheck((nInputRows >= nKernelRows && nInputCols >= nKernelCols) || *vf == 'F', 2, "conv2Dger : Input image is smaller than kernel");
if (*vf == 'F') {
nOutputRows = (nInputRows - 1) * srow + nKernelRows;
nOutputCols = (nInputCols - 1) * scol + nKernelCols;
} else { /* valid */
nOutputRows = (nInputRows - nKernelRows) / srow + 1;
nOutputCols = (nInputCols - nKernelCols) / scol + 1;
}
nelem = THTensor_(nElement)(r_);
THTensor_(resize4d)(r_, nKernelPlane, nInputPlane, nOutputRows, nOutputCols);
input_data = THTensor_(data)(input);
weight_data = THTensor_(data)(kernel);
output_data = THTensor_(data)(r_);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
{
/*THTensor_(zero)(r_);*/
#pragma omp parallel for private(k)
for (k = 0; k < r_->size[0]*r_->size[1]; k++)
{
real* ptr_output = output_data + k*nOutputCols*nOutputRows;
long l;
for (l = 0; l < nOutputRows*nOutputCols; l++)
ptr_output[l] = 0.0;
}
}
else if (beta != 1)
{
/*THTensor_(mul)(r_, beta);*/
#pragma omp parallel for private(k)
for (k = 0; k < r_->size[0]*r_->size[1]; k++)
{
real* ptr_output = output_data + k*nOutputCols*nOutputRows;
long l;
for (l = 0; l < nOutputRows*nOutputCols; l++)
ptr_output[l] *= beta;
}
}
#pragma omp parallel for private(k)
for(k = 0; k < nKernelPlane; k++)
{
long i;
/* get kernel */
real *ptr_weight = weight_data+k*kstride0;
for(i = 0; i < nInputPlane; i++)
{
/* get output */
real *ptr_output = output_data + k*nInputPlane*nOutputCols*nOutputRows + i*nOutputCols*nOutputRows;
/* get input */
real *ptr_input = input_data+i*istride0;
/* do image, kernel convolution */
if (*vf == 'F')
if (*xc == 'X')
THTensor_(fullXCorr2Dptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
else
THTensor_(fullConv2Dptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
else
if (*xc == 'X')
THTensor_(validXCorr2Dptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
else
THTensor_(validConv2Dptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
/* Next output plane */
/* output_data += nOutputCols*nOutputRows; */
}
}
THTensor_(free)(input);
THTensor_(free)(kernel);
}
/*
3D input, 4D kernel, 3D output
matrix vector product like
y <- Ax + beta*y
*/
void THTensor_(conv2Dmv)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_, long srow, long scol, const char *vf, const char *xc)
{
long nInputPlane, nInputRows, nInputCols;
long nKernelRows, nKernelCols;
long nOutputPlane, nOutputRows, nOutputCols;
long istride0, kstride0, kstride1;
THTensor *input;
THTensor* kernel;
real *input_data;
real *weight_data;
real *output_data;
ptrdiff_t nelem;
long k;
THArgCheck(t_->nDimension == 3 , 3, "input: 3D Tensor expected");
THArgCheck(k_->nDimension == 4 , 4, "kernel: 4D Tensor expected");
THArgCheck(srow >= 1, 5, "Stride should be a positive integer");
THArgCheck(scol >= 1, 6, "Stride should be a positive integer");
THArgCheck(*vf == 'V' || *vf == 'F', 7, "type of convolution can 'V' or 'F'");
THArgCheck(*xc == 'C' || *xc == 'X', 7, "type of convolution can 'X' or 'C'");
input = THTensor_(newContiguous)(t_);
if (!(k_->stride[3] == 1) || !(k_->stride[2] == k_->size[3])) {
kernel = THTensor_(newContiguous)(k_);
} else {
THTensor_(retain)(k_);
kernel = k_;
}
nInputPlane = input->size[0];
istride0 = input->stride[0];
nInputRows = input->size[1];
nInputCols = input->size[2];
kstride0 = kernel->stride[0];
kstride1 = kernel->stride[1];
nKernelRows = kernel->size[2];
nKernelCols = kernel->size[3];
nOutputPlane = kernel->size[0];
THArgCheck(kernel->size[1] == nInputPlane, 2, "invalid number of input planes");
THArgCheck( (nInputRows >= nKernelRows && nInputCols >= nKernelCols) || *vf == 'F', 2, "conv2Dmv : Input image is smaller than kernel");
if (*vf == 'F') {
nOutputRows = (nInputRows - 1) * srow + nKernelRows;
nOutputCols = (nInputCols - 1) * scol + nKernelCols;
} else { /* valid */
nOutputRows = (nInputRows - nKernelRows) / srow + 1;
nOutputCols = (nInputCols - nKernelCols) / scol + 1;
}
nelem = THTensor_(nElement)(r_);
THTensor_(resize3d)(r_, nOutputPlane, nOutputRows, nOutputCols);
input_data = THTensor_(data)(input);
weight_data = THTensor_(data)(kernel);
output_data = THTensor_(data)(r_);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
{
/*THTensor_(zero)(r_);*/
#pragma omp parallel for private(k)
for (k = 0; k < r_->size[0]; k++)
{
real* ptr_output = output_data + k*nOutputCols*nOutputRows;
long l;
for (l = 0; l < nOutputRows*nOutputCols; l++)
ptr_output[l] = 0.0;
}
}
else if (beta != 1)
{
/*THTensor_(mul)(r_, beta);*/
#pragma omp parallel for private(k)
for (k = 0; k < r_->size[0]; k++)
{
real* ptr_output = output_data + k*nOutputCols*nOutputRows;
long l;
for (l = 0; l < nOutputRows*nOutputCols; l++)
ptr_output[l] *= beta;
}
}
#pragma omp parallel for private(k)
for(k = 0; k < nOutputPlane; k++)
{
long i;
/* get output */
real *ptr_output = output_data + k*nOutputCols*nOutputRows;
for(i = 0; i < nInputPlane; i++)
{
/* get kernel */
real *ptr_weight = weight_data + k*kstride0 + i*kstride1;
/* get input */
real *ptr_input = input_data + i*istride0;
/* do image, kernel convolution */
if (*vf == 'F')
if (*xc == 'X')
THTensor_(fullXCorr2Dptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
else
THTensor_(fullConv2Dptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
else
if (*xc == 'X')
THTensor_(validXCorr2Dptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
else
THTensor_(validConv2Dptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
}
/* Next output plane */
/* output_data += nOutputCols*nOutputRows;*/
}
THTensor_(free)(input);
THTensor_(free)(kernel);
}
/*
3D input, 4D kernel, 3D output
matrix vector product like
y <- Ax + beta*y
*/
void THTensor_(conv2Dmm)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_, long srow, long scol, const char *vf, const char *xc)
{
long nInputPlane, nInputRows, nInputCols;
long nKernelRows, nKernelCols;
long nOutputPlane, nOutputRows, nOutputCols;
long kstride0, kstride1;
THTensor *input;
THTensor* kernel;
long nbatch;
ptrdiff_t nelem;
real *input_data;
real *weight_data;
real *output_data;
long p;
THArgCheck(t_->nDimension == 4 , 3, "input: 4D Tensor expected");
THArgCheck(k_->nDimension == 4 , 4, "kernel: 4D Tensor expected");
THArgCheck(srow >= 1, 5, "Stride should be a positive integer");
THArgCheck(scol >= 1, 6, "Stride should be a positive integer");
THArgCheck(*vf == 'V' || *vf == 'F', 7, "type of convolution can 'V' or 'F'");
THArgCheck(*xc == 'C' || *xc == 'X', 7, "type of convolution can 'X' or 'C'");
input = THTensor_(newContiguous)(t_);
if (!(k_->stride[3] == 1) || !(k_->stride[2] == k_->size[3])) {
kernel = THTensor_(newContiguous)(k_);
} else {
THTensor_(retain)(k_);
kernel = k_;
}
nbatch = input->size[0];
nInputPlane = input->size[1];
nInputRows = input->size[2];
nInputCols = input->size[3];
kstride0 = kernel->stride[0];
kstride1 = kernel->stride[1];
nKernelRows = kernel->size[2];
nKernelCols = kernel->size[3];
nOutputPlane = kernel->size[0];
THArgCheck(kernel->size[1] == nInputPlane, 2, "invalid number of input planes");
THArgCheck( (nInputRows >= nKernelRows && nInputCols >= nKernelCols) || *vf == 'F', 2, "conv2Dmv : Input image is smaller than kernel");
if (*vf == 'F') {
nOutputRows = (nInputRows - 1) * srow + nKernelRows;
nOutputCols = (nInputCols - 1) * scol + nKernelCols;
} else { /* valid */
nOutputRows = (nInputRows - nKernelRows) / srow + 1;
nOutputCols = (nInputCols - nKernelCols) / scol + 1;
}
nelem = THTensor_(nElement)(r_);
THTensor_(resize4d)(r_, nbatch, nOutputPlane, nOutputRows, nOutputCols);
input_data = THTensor_(data)(input);
weight_data = THTensor_(data)(kernel);
output_data = THTensor_(data)(r_);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
{
/*THTensor_(zero)(r_);*/
#pragma omp parallel for private(p)
for (p=0; p < r_->size[0]; p++)
{
long k;
for (k = 0; k < r_->size[1]; k++)
{
real* ptr_output = output_data + p*nOutputPlane*nOutputRows*nOutputCols + k*nOutputCols*nOutputRows;
long l;
for (l = 0; l < nOutputRows*nOutputCols; l++)
ptr_output[l] = 0.0;
}
}
}
else if (beta != 1)
{
/*THTensor_(mul)(r_, beta);*/
#pragma omp parallel for private(p)
for(p=0; p < r_->size[0]; p++)
{
long k;
for (k = 0; k < r_->size[1]; k++)
{
real* ptr_output = output_data + p*nOutputPlane*nOutputRows*nOutputCols + k*nOutputCols*nOutputRows;
long l;
for (l = 0; l < nOutputRows*nOutputCols; l++)
ptr_output[l] *= beta;
}
}
}
#pragma omp parallel for private(p)
for(p=0; p < nbatch; p++)
{
long k;
for(k = 0; k < nOutputPlane; k++)
{
long i;
/* get output */
real *ptr_output = output_data + p*nOutputPlane*nOutputCols*nOutputRows + k*nOutputCols*nOutputRows;
for(i = 0; i < nInputPlane; i++)
{
/* get kernel */
real *ptr_weight = weight_data + k*kstride0 + i*kstride1;
/* get input */
real *ptr_input = input_data + p*nInputPlane*nInputRows*nInputCols + i*nInputRows*nInputCols;
/* do image, kernel convolution */
if (*vf == 'F')
if (*xc == 'X')
THTensor_(fullXCorr2Dptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
else
THTensor_(fullConv2Dptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
else
if (*xc == 'X')
THTensor_(validXCorr2Dptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
else
THTensor_(validConv2Dptr)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol);
}
/* Next output plane */
/* output_data += nOutputCols*nOutputRows;*/
}
}
THTensor_(free)(input);
THTensor_(free)(kernel);
}
/*
2D input, 2D kernel, 2D output
scalar multiplication like
y <- x*y + beta*y
*/
void THTensor_(conv2Dmul)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_, long srow, long scol, const char *vf, const char *xc)
{
THTensor *input;
THTensor* kernel;
long nInputRows;
long nInputCols;
long nKernelRows;
long nKernelCols;
long nOutputRows, nOutputCols;
real *ptr_input;
real *ptr_weight;
real *output_data;
ptrdiff_t nelem;
THArgCheck(t_->nDimension == 2 , 3, "input: 2D Tensor expected");
THArgCheck(k_->nDimension == 2 , 4, "kernel: 2D Tensor expected");
THArgCheck(srow >= 1, 5, "Stride should be a positive integer");
THArgCheck(scol >= 1, 6, "Stride should be a positive integer");
input = THTensor_(newContiguous)(t_);
kernel = THTensor_(newContiguous)(k_);
nInputRows = input->size[0];
nInputCols = input->size[1];
nKernelRows = kernel->size[0];
nKernelCols = kernel->size[1];
THArgCheck((nInputRows >= nKernelRows && nInputCols >= nKernelCols) || *vf == 'F', 2, "conv2Dmul : Input image is smaller than kernel");
nOutputRows = THTensor_(convsize)(nInputRows, nKernelRows, srow, vf);
nOutputCols = THTensor_(convsize)(nInputCols, nKernelCols, scol, vf);
nelem = THTensor_(nElement)(r_);
THTensor_(resize2d)(r_, nOutputRows, nOutputCols);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
THTensor_(zero)(r_);
else if (beta != 1)
THTensor_(mul)(r_, r_, beta);
ptr_input = THTensor_(data)(input);
ptr_weight = THTensor_(data)(kernel);
output_data = THTensor_(data)(r_);
/* do image, kernel convolution */
THTensor_(conv2d)(output_data,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol, vf, xc);
THTensor_(free)(input);
THTensor_(free)(kernel);
}
/*
3D input, 3D kernel, 3D output
component wise multiplication like
y <- y.*x + beta*y
*/
void THTensor_(conv2Dcmul)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_, long srow, long scol, const char *vf, const char *xc)
{
long nInputPlane, nInputRows, nInputCols;
long nKernelRows, nKernelCols;
long nOutputPlane, nOutputRows, nOutputCols;
long istride0, kstride0;
THTensor *input;
THTensor *kernel;
real *input_data;
real *weight_data;
real *output_data;
ptrdiff_t nelem;
long k;
THArgCheck(t_->nDimension == 3 , 3, "input: 3D Tensor expected");
THArgCheck(k_->nDimension == 3 , 4, "kernel: 3D Tensor expected");
THArgCheck(srow >= 1, 5, "Stride should be a positive integer");
THArgCheck(scol >= 1, 6, "Stride should be a positive integer");
input = THTensor_(newContiguous)(t_);
kernel = THTensor_(newContiguous)(k_);
istride0 = input->stride[0];
nInputPlane = input->size[0];
nInputRows = input->size[1];
nInputCols = input->size[2];
kstride0 = kernel->stride[0];
nOutputPlane = kernel->size[0];
nKernelRows = kernel->size[1];
nKernelCols = kernel->size[2];
THArgCheck(nOutputPlane == nInputPlane, 2, "invalid number of input/kernel planes");
THArgCheck( (nInputRows >= nKernelRows && nInputCols >= nKernelCols) || *vf == 'F', 2, "conv2Dcmul : Input image is smaller than kernel");
nOutputRows = THTensor_(convsize)(nInputRows, nKernelRows, srow, vf);
nOutputCols = THTensor_(convsize)(nInputCols, nKernelCols, scol, vf);
nelem = THTensor_(nElement)(r_);
THTensor_(resize3d)(r_, nOutputPlane, nOutputRows, nOutputCols);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
{
THTensor_(zero)(r_);
}
else if (beta != 1)
THTensor_(mul)(r_, r_, beta);
input_data = THTensor_(data)(input);
weight_data = THTensor_(data)(kernel);
output_data = THTensor_(data)(r_);
for(k = 0; k < nOutputPlane; k++)
{
/* get kernel */
real *ptr_weight = weight_data + k*kstride0;
/* get input */
real *ptr_input = input_data + k*istride0;
/* do image, kernel convolution */
THTensor_(conv2d)(output_data,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol, vf, xc);
/* Next output plane */
output_data += nOutputCols*nOutputRows;
}
THTensor_(free)(input);
THTensor_(free)(kernel);
}
/*
3D input, 3D kernel, 3D output
component wise multiplication like with a permutation map
y <- y.*x + beta*y
*/
void THTensor_(conv2Dmap)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_, THTensor *map, long srow, long scol, const char *vf, const char *xc)
{
long nInputPlane, nInputRows, nInputCols;
long nKernelRows, nKernelCols;
long nOutputPlane, nOutputRows, nOutputCols;
long istride0, kstride0;
THTensor *input;
THTensor* kernel;
real *input_data;
real *weight_data;
real *output_data;
long nmaps;
ptrdiff_t nelem;
long k;
THArgCheck(t_->nDimension == 3 , 3, "input: 3D Tensor expected");
THArgCheck(k_->nDimension == 3 , 4, "kernel: 3D Tensor expected");
THArgCheck(map->nDimension == 2 , 4, "map: 2D Tensor expected");
THArgCheck(srow >= 1, 6, "Stride should be a positive integer");
THArgCheck(scol >= 1, 7, "Stride should be a positive integer");
input = THTensor_(newContiguous)(t_);
kernel = THTensor_(newContiguous)(k_);
istride0 = input->stride[0];
nInputPlane = input->size[0];
nInputRows = input->size[1];
nInputCols = input->size[2];
kstride0 = kernel->stride[0];
nOutputPlane = kernel->size[0];
nKernelRows = kernel->size[1];
nKernelCols = kernel->size[2];
THArgCheck(nOutputPlane == nInputPlane, 2, "invalid number of input/kernel planes");
THArgCheck( (nInputRows >= nKernelRows && nInputCols >= nKernelCols)
|| *vf == 'F', 2, "conv2Dmap : Input image is smaller than kernel");
nOutputRows = THTensor_(convsize)(nInputRows, nKernelRows, srow, vf);
nOutputCols = THTensor_(convsize)(nInputCols, nKernelCols, scol, vf);
nelem = THTensor_(nElement)(r_);
THTensor_(resize3d)(r_, nOutputPlane, nOutputRows, nOutputCols);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
{
THTensor_(zero)(r_);
}
else if (beta != 1)
THTensor_(mul)(r_, r_, beta);
input_data = THTensor_(data)(input);
weight_data = THTensor_(data)(kernel);
output_data = THTensor_(data)(r_);
nmaps = map->size[0];
for(k = 0; k < nmaps; k++)
{
/* get indices */
long from = (long)THTensor_(get2d)(map,k,0)-1;
long to = (long)THTensor_(get2d)(map,k,1)-1;
/* get kernel */
real *ptr_weight = weight_data + k*kstride0;
/* get input */
real *ptr_input = input_data + from*istride0;
/* get output */
real *ptr_output = output_data + to*nOutputRows*nOutputCols;
/* do image, kernel convolution */
THTensor_(conv2d)(ptr_output,
alpha,
ptr_input, nInputRows, nInputCols,
ptr_weight, nKernelRows, nKernelCols,
srow, scol, vf, xc);
}
THTensor_(free)(input);
THTensor_(free)(kernel);
}
/*
4D input, 4D kernel, 5D output
like rank1 update
A <- xx' + beta*A
for sr,sc=1 this is equivalent to xcorr2Dger, but otherwise it is useful for
calculating derivatives wrt a kernel that is applied with stride sr,sc != 1
*/
void THTensor_(conv3DRevger)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_,
long sdepth, long srow, long scol)
{
long nInputPlane, nInputDepth, nInputRows, nInputCols;
long nKernelPlane, nKernelDepth, nKernelRows, nKernelCols;
long nOutputPlane, nOutputDepth, nOutputRows, nOutputCols;
long istride0, kstride0;
THTensor *input;
THTensor *kernel;
real *input_data;
real *weight_data;
real *output_data;
ptrdiff_t nelem;
long k, i;
THArgCheck(t_->nDimension == 4 , 3, "input: 4D Tensor expected");
THArgCheck(k_->nDimension == 4 , 4, "kernel: 4D Tensor expected");
THArgCheck(sdepth >= 1, 5, "Stride should be a positive integer");
THArgCheck(srow >= 1, 6, "Stride should be a positive integer");
THArgCheck(scol >= 1, 7, "Stride should be a positive integer");
input = THTensor_(newContiguous)(t_);
kernel = THTensor_(newContiguous)(k_);
nInputPlane = input->size[0];
istride0 = input->stride[0];
nInputDepth = input->size[1];
nInputRows = input->size[2];
nInputCols = input->size[3];
kstride0 = kernel->stride[0];
nKernelPlane = kernel->size[0];
nKernelDepth= kernel->size[1];
nKernelRows = kernel->size[2];
nKernelCols = kernel->size[3];
nOutputPlane = nInputPlane * kernel->size[0];
THArgCheck(nInputDepth >= nKernelDepth && nInputRows >= nKernelRows && nInputCols >= nKernelCols , 2, "conv3DRevger : Input image is smaller than kernel");
nOutputDepth = nInputDepth - (nKernelDepth - 1) * sdepth;
nOutputRows = nInputRows - (nKernelRows - 1) * srow;
nOutputCols = nInputCols - (nKernelCols - 1) * scol;
nelem = THTensor_(nElement)(r_);
THTensor_(resize5d)(r_,nKernelPlane, nInputPlane, nOutputDepth, nOutputRows, nOutputCols);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
{
THTensor_(zero)(r_);
}
else if (beta != 1)
THTensor_(mul)(r_, r_, beta);
input_data = THTensor_(data)(input);
weight_data = THTensor_(data)(kernel);
output_data = THTensor_(data)(r_);
for(k = 0; k < nKernelPlane; k++)
{
/* get kernel */
real *ptr_weight = weight_data+k*kstride0;
for(i = 0; i < nInputPlane; i++)
{
/* get input */
real *ptr_input = input_data+i*istride0;
/* do image, kernel convolution */
THTensor_(validXCorr3DRevptr)(output_data,
alpha,
ptr_input, nInputDepth, nInputRows, nInputCols,
ptr_weight, nKernelDepth, nKernelRows, nKernelCols,
sdepth, srow, scol);
/* Next output plane */
output_data += nOutputDepth*nOutputCols*nOutputRows;
}
}
THTensor_(free)(input);
THTensor_(free)(kernel);
}
/*
4D input, 4D kernel, 5D output
like rank1 update
A <- xx' + beta*A
*/
void THTensor_(conv3Dger)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_,
long sdepth, long srow, long scol, const char *vf, const char *xc)
{
long nInputPlane, nInputDepth, nInputRows, nInputCols;
long nKernelPlane, nKernelDepth, nKernelRows, nKernelCols;
long nOutputPlane, nOutputDepth, nOutputRows, nOutputCols;
long istride0, kstride0;
THTensor *input;
THTensor *kernel;
real *input_data;
real *weight_data;
real *output_data;
ptrdiff_t nelem;
long k, i;
THArgCheck(t_->nDimension == 4 , 3, "input: 4D Tensor expected");
THArgCheck(k_->nDimension == 4 , 4, "kernel: 4D Tensor expected");
THArgCheck(sdepth >= 1, 5, "Stride should be a positive integer");
THArgCheck(srow >= 1, 6, "Stride should be a positive integer");
THArgCheck(scol >= 1, 7, "Stride should be a positive integer");
THArgCheck(*vf == 'V' || *vf == 'F', 8, "type of convolution can 'V' or 'F'");
THArgCheck(*xc == 'C' || *xc == 'X', 8, "type of convolution can 'X' or 'C'");
input = THTensor_(newContiguous)(t_);
kernel = THTensor_(newContiguous)(k_);
nInputPlane = input->size[0];
istride0 = input->stride[0];
nInputDepth = input->size[1];
nInputRows = input->size[2];
nInputCols = input->size[3];
kstride0 = kernel->stride[0];
nKernelPlane = kernel->size[0];
nKernelDepth = kernel->size[1];
nKernelRows = kernel->size[2];
nKernelCols = kernel->size[3];
nOutputPlane = nInputPlane * kernel->size[0];
THArgCheck((nInputDepth >= nKernelDepth
&& nInputRows >= nKernelRows
&& nInputCols >= nKernelCols)
|| *vf == 'F', 2, "conv3Dger : Input image is smaller than kernel");
nOutputDepth = THTensor_(convsize)(nInputDepth, nKernelDepth, sdepth, vf);
nOutputRows = THTensor_(convsize)(nInputRows, nKernelRows, srow, vf);
nOutputCols = THTensor_(convsize)(nInputCols, nKernelCols, scol, vf);
nelem = THTensor_(nElement)(r_);
THTensor_(resize5d)(r_,nKernelPlane, nInputPlane, nOutputDepth, nOutputRows, nOutputCols);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
{
THTensor_(zero)(r_);
}
else if (beta != 1)
THTensor_(mul)(r_, r_, beta);
input_data = THTensor_(data)(input);
weight_data = THTensor_(data)(kernel);
output_data = THTensor_(data)(r_);
for(k = 0; k < nKernelPlane; k++)
{
/* get kernel */
real *ptr_weight = weight_data+k*kstride0;
for(i = 0; i < nInputPlane; i++)
{
/* get input */
real *ptr_input = input_data+i*istride0;
/* do image, kernel convolution */
THTensor_(conv3d)(output_data,
alpha,
ptr_input, nInputDepth, nInputRows, nInputCols,
ptr_weight, nKernelDepth, nKernelRows, nKernelCols,
sdepth, srow, scol, vf, xc);
/* Next output plane */
output_data += nOutputDepth*nOutputCols*nOutputRows;
}
}
THTensor_(free)(input);
THTensor_(free)(kernel);
}
/*
4D input, 5D kernel, 4D output
matrix vector product like
y <- Ax + beta*y
*/
void THTensor_(conv3Dmv)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_,
long sdepth, long srow, long scol, const char *vf, const char *xc)
{
long nInputPlane, nInputDepth, nInputRows, nInputCols;
long nKernelDepth, nKernelRows, nKernelCols;
long nOutputPlane, nOutputDepth, nOutputRows, nOutputCols;
long istride0, kstride0, kstride1;
THTensor *input;
THTensor *kernel;
real *input_data;
real *weight_data;
real *output_data;
ptrdiff_t nelem;
long k, i;
THArgCheck(t_->nDimension == 4 , 3, "input: 4D Tensor expected");
THArgCheck(k_->nDimension == 5 , 4, "kernel: 5D Tensor expected");
THArgCheck(sdepth >= 1, 5, "Stride should be a positive integer");
THArgCheck(srow >= 1, 6, "Stride should be a positive integer");
THArgCheck(scol >= 1, 7, "Stride should be a positive integer");
THArgCheck(*vf == 'V' || *vf == 'F', 8, "type of convolution can 'V' or 'F'");
THArgCheck(*xc == 'C' || *xc == 'X', 8, "type of convolution can 'X' or 'C'");
input = THTensor_(newContiguous)(t_);
if (!(k_->stride[4] == 1) || !(k_->stride[3] == k_->size[4])) {
kernel = THTensor_(newContiguous)(k_);
} else {
THTensor_(retain)(k_);
kernel = k_;
}
nInputPlane = input->size[0];
istride0 = input->stride[0];
nInputDepth = input->size[1];
nInputRows = input->size[2];
nInputCols = input->size[3];
kstride0 = kernel->stride[0];
kstride1 = kernel->stride[1];
nKernelDepth = kernel->size[2];
nKernelRows = kernel->size[3];
nKernelCols = kernel->size[4];
nOutputPlane = kernel->size[0];
THArgCheck(kernel->size[1] == nInputPlane, 2, "invalid number of input planes");
THArgCheck( (nInputDepth >= nKernelDepth && nInputRows >= nKernelRows && nInputCols >= nKernelCols) || *vf == 'F', 2, "conv3Dmv : Input image is smaller than kernel");
nOutputDepth = THTensor_(convsize)(nInputDepth, nKernelDepth, sdepth, vf);
nOutputRows = THTensor_(convsize)(nInputRows, nKernelRows, srow, vf);
nOutputCols = THTensor_(convsize)(nInputCols, nKernelCols, scol, vf);
nelem = THTensor_(nElement)(r_);
THTensor_(resize4d)(r_, nOutputPlane, nOutputDepth, nOutputRows, nOutputCols);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
{
THTensor_(zero)(r_);
}
else if (beta != 1)
THTensor_(mul)(r_, r_, beta);
input_data = THTensor_(data)(input);
weight_data = THTensor_(data)(kernel);
output_data = THTensor_(data)(r_);
for(k = 0; k < nOutputPlane; k++)
{
for(i = 0; i < nInputPlane; i++)
{
/* get kernel */
real *ptr_weight = weight_data + k*kstride0 + i*kstride1;
/* get input */
real *ptr_input = input_data + i*istride0;
/* do image, kernel convolution */
THTensor_(conv3d)(output_data,
alpha,
ptr_input, nInputDepth, nInputRows, nInputCols,
ptr_weight, nKernelDepth, nKernelRows, nKernelCols,
sdepth, srow, scol, vf, xc);
}
/* Next output plane */
output_data += nOutputDepth*nOutputCols*nOutputRows;
}
THTensor_(free)(input);
THTensor_(free)(kernel);
}
/*
3D input, 3D kernel, 3D output
scalar multiplication like
y <- x*y + beta*y
*/
void THTensor_(conv3Dmul)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_,
long sdepth, long srow, long scol, const char *vf, const char *xc)
{
THTensor *input;
THTensor* kernel;
long nInputDepth;
long nInputRows;
long nInputCols;
long nKernelDepth;
long nKernelRows;
long nKernelCols;
long nOutputDepth, nOutputRows, nOutputCols;
real *ptr_input;
real *ptr_weight;
real *output_data;
ptrdiff_t nelem;
THArgCheck(t_->nDimension == 3 , 3, "input: 3D Tensor expected");
THArgCheck(k_->nDimension == 3 , 4, "kernel: 3D Tensor expected");
THArgCheck(sdepth >= 1, 5, "Stride should be a positive integer");
THArgCheck(srow >= 1, 6, "Stride should be a positive integer");
THArgCheck(scol >= 1, 7, "Stride should be a positive integer");
THArgCheck(*vf == 'V' || *vf == 'F', 8, "type of convolution can 'V' or 'F'");
THArgCheck(*xc == 'C' || *xc == 'X', 8, "type of convolution can 'X' or 'C'");
input = THTensor_(newContiguous)(t_);
kernel = THTensor_(newContiguous)(k_);
nInputDepth = input->size[0];
nInputRows = input->size[1];
nInputCols = input->size[2];
nKernelDepth = kernel->size[0];
nKernelRows = kernel->size[1];
nKernelCols = kernel->size[2];
THArgCheck((nInputDepth >= nKernelDepth && nInputRows >= nKernelRows && nInputCols >= nKernelCols) || *vf == 'F', 2, "conv3Dmul : Input image is smaller than kernel");
nOutputDepth = THTensor_(convsize)(nInputDepth, nKernelDepth, sdepth, vf);
nOutputRows = THTensor_(convsize)(nInputRows, nKernelRows, srow, vf);
nOutputCols = THTensor_(convsize)(nInputCols, nKernelCols, scol, vf);
nelem = THTensor_(nElement)(r_);
THTensor_(resize3d)(r_, nOutputDepth, nOutputRows, nOutputCols);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
THTensor_(zero)(r_);
else if (beta != 1)
THTensor_(mul)(r_, r_, beta);
ptr_input = THTensor_(data)(input);
ptr_weight = THTensor_(data)(kernel);
output_data = THTensor_(data)(r_);
/* do image, kernel convolution */
THTensor_(conv3d)(output_data,
alpha,
ptr_input, nInputDepth, nInputRows, nInputCols,
ptr_weight, nKernelDepth, nKernelRows, nKernelCols,
sdepth, srow, scol, vf, xc);
THTensor_(free)(input);
THTensor_(free)(kernel);
}
/*
4D input, 4D kernel, 4D output
component wise multiplication like
y <- y.*x + beta*y
*/
void THTensor_(conv3Dcmul)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_,
long sdepth, long srow, long scol, const char *vf, const char *xc)
{
long nInputPlane, nInputDepth, nInputRows, nInputCols;
long nKernelDepth, nKernelRows, nKernelCols;
long nOutputPlane, nOutputDepth, nOutputRows, nOutputCols;
long istride0, kstride0;
THTensor *input;
THTensor *kernel;
real *input_data;
real *weight_data;
real *output_data;
ptrdiff_t nelem;
long k;
THArgCheck(t_->nDimension == 4 , 3, "input: 3D Tensor expected");
THArgCheck(k_->nDimension == 4 , 4, "kernel: 3D Tensor expected");
THArgCheck(srow >= 1, 5, "Stride should be a positive integer");
THArgCheck(scol >= 1, 6, "Stride should be a positive integer");
THArgCheck(*vf == 'V' || *vf == 'F', 7, "type of convolution can 'V' or 'F'");
THArgCheck(*xc == 'C' || *xc == 'X', 7, "type of convolution can 'X' or 'C'");
input = THTensor_(newContiguous)(t_);
kernel = THTensor_(newContiguous)(k_);
istride0 = input->stride[0];
nInputPlane = input->size[0];
nInputDepth = input->size[1];
nInputRows = input->size[2];
nInputCols = input->size[3];
kstride0 = kernel->stride[0];
nOutputPlane = kernel->size[0];
nKernelDepth = kernel->size[1];
nKernelRows = kernel->size[2];
nKernelCols = kernel->size[3];
THArgCheck(nOutputPlane == nInputPlane, 2, "invalid number of input/kernel planes");
THArgCheck( (nInputDepth >= nKernelDepth && nInputRows >= nKernelRows && nInputCols >= nKernelCols) || *vf == 'F', 2, "conv3Dcmul : Input image is smaller than kernel");
nOutputDepth = THTensor_(convsize)(nInputDepth, nKernelDepth, sdepth, vf);
nOutputRows = THTensor_(convsize)(nInputRows, nKernelRows, srow, vf);
nOutputCols = THTensor_(convsize)(nInputCols, nKernelCols, scol, vf);
nelem = THTensor_(nElement)(r_);
THTensor_(resize4d)(r_, nOutputPlane, nOutputDepth, nOutputRows, nOutputCols);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
{
THTensor_(zero)(r_);
}
else if (beta != 1)
THTensor_(mul)(r_, r_, beta);
input_data = THTensor_(data)(input);
weight_data = THTensor_(data)(kernel);
output_data = THTensor_(data)(r_);
for(k = 0; k < nOutputPlane; k++)
{
/* get kernel */
real *ptr_weight = weight_data + k*kstride0;
/* get input */
real *ptr_input = input_data + k*istride0;
/* do image, kernel convolution */
THTensor_(conv3d)(output_data,
alpha,
ptr_input, nInputDepth, nInputRows, nInputCols,
ptr_weight, nKernelDepth, nKernelRows, nKernelCols,
sdepth, srow, scol, vf, xc);
/* Next output plane */
output_data += nOutputDepth*nOutputCols*nOutputRows;
}
THTensor_(free)(input);
THTensor_(free)(kernel);
}
/*
4D input, 4D kernel, 4D output
component wise multiplication like with a permutation map
y <- y.*x + beta*y
*/
void THTensor_(conv3Dmap)(THTensor *r_, real beta, real alpha, THTensor *t_, THTensor *k_, THTensor *map,
long sdepth, long srow, long scol, const char *vf, const char *xc)
{
long nInputPlane, nInputDepth, nInputRows, nInputCols;
long nKernelDepth, nKernelRows, nKernelCols;
long nOutputPlane, nOutputDepth, nOutputRows, nOutputCols;
long istride0, kstride0;
THTensor *input;
THTensor *kernel;
ptrdiff_t nelem;
real *input_data;
real *weight_data;
real *output_data;
long nmaps;
long k;
THArgCheck(t_->nDimension == 4 , 3, "input: 4D Tensor expected");
THArgCheck(k_->nDimension == 4 , 4, "kernel: 4D Tensor expected");
THArgCheck(map->nDimension == 2 , 4, "map: 2D Tensor expected");
THArgCheck(srow >= 1, 6, "Stride should be a positive integer");
THArgCheck(scol >= 1, 7, "Stride should be a positive integer");
THArgCheck(*vf == 'V' || *vf == 'F', 8, "type of convolution can 'V' or 'F'");
THArgCheck(*xc == 'C' || *xc == 'X', 8, "type of convolution can 'X' or 'C'");
input = THTensor_(newContiguous)(t_);
kernel = THTensor_(newContiguous)(k_);
istride0 = input->stride[0];
nInputPlane = input->size[0];
nInputDepth = input->size[1];
nInputRows = input->size[2];
nInputCols = input->size[3];
kstride0 = kernel->stride[0];
nOutputPlane = kernel->size[0];
nKernelDepth = kernel->size[1];
nKernelRows = kernel->size[2];
nKernelCols = kernel->size[3];
THArgCheck(nOutputPlane == nInputPlane, 2, "invalid number of input/kernel planes");
THArgCheck((nInputDepth >= nKernelDepth
&& nInputRows >= nKernelRows
&& nInputCols >= nKernelCols) || *vf == 'F',
2, "conv3Dmap : Input image is smaller than kernel");
nOutputDepth = THTensor_(convsize)(nInputDepth, nKernelDepth, sdepth, vf);
nOutputRows = THTensor_(convsize)(nInputRows, nKernelRows, srow, vf);
nOutputCols = THTensor_(convsize)(nInputCols, nKernelCols, scol, vf);
nelem = THTensor_(nElement)(r_);
THTensor_(resize4d)(r_, nOutputPlane, nOutputDepth, nOutputRows, nOutputCols);
if (nelem == 0 || beta == 0 || nelem != THTensor_(nElement)(r_))
{
THTensor_(zero)(r_);
}
else if (beta != 1)
THTensor_(mul)(r_, r_, beta);
input_data = THTensor_(data)(input);
weight_data = THTensor_(data)(kernel);
output_data = THTensor_(data)(r_);
nmaps = map->size[0];
for(k = 0; k < nmaps; k++)
{
/* get indices */
long from = (long)THTensor_(get2d)(map,k,0)-1;
long to = (long)THTensor_(get2d)(map,k,1)-1;
/* get kernel */
real *ptr_weight = weight_data + k*kstride0;
/* get input */
real *ptr_input = input_data + from*istride0;
/* get output */
real *ptr_output = output_data + to*nOutputDepth*nOutputRows*nOutputCols;
/* do image, kernel convolution */
THTensor_(conv3d)(ptr_output,
alpha,
ptr_input, nInputDepth, nInputRows, nInputCols,
ptr_weight, nKernelDepth, nKernelRows, nKernelCols,
sdepth, srow, scol, vf, xc);
}
THTensor_(free)(input);
THTensor_(free)(kernel);
}
#endif
|
conv_dw_kernel_x86.c
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* License); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (c) 2020, OPEN AI LAB
* Author: [email protected]
*/
#include <stdint.h>
#include <stdlib.h>
#include <math.h>
#include "conv_dw_kernel_x86.h"
#if __SSE2__
#include <emmintrin.h>
#endif
#if __AVX__
#include <immintrin.h>
#endif
#define max(a, b) ((a) > (b) ? (a) : (b))
#define min(a, b) ((a) < (b) ? (a) : (b))
static void relu(float* data, int size, int activation)
{
for (int i = 0; i < size; i++)
{
data[i] = max(data[i], ( float )0);
if (activation > 0)
{
data[i] = min(data[i], ( float )activation);
}
}
}
static void pad(float* input, float* output, int in_h, int in_w, int out_h, int out_w, int top, int left, float v)
{
float* ptr = input;
float* outptr = output;
int y = 0;
// fill top
for (; y < top; y++)
{
int x = 0;
for (; x < out_w; x++)
{
outptr[x] = v;
}
outptr += out_w;
}
// fill center
for (; y < (top + in_h); y++)
{
int x = 0;
for (; x < left; x++)
{
outptr[x] = v;
}
if (in_w < 12)
{
for (; x < (left + in_w); x++)
{
outptr[x] = ptr[x - left];
}
}
else
{
memcpy(outptr + left, ptr, in_w * sizeof(float));
x += in_w;
}
for (; x < out_w; x++)
{
outptr[x] = v;
}
ptr += in_w;
outptr += out_w;
}
// fill bottom
for (; y < out_h; y++)
{
int x = 0;
for (; x < out_w; x++)
{
outptr[x] = v;
}
outptr += out_w;
}
}
#if __AVX__
static void convdw3x3s1(float* output, float* img_data, float* kernel_data, float* bias_data, int inc, int inh, int inw,
int outh, int outw, int num_thread)
{
int inwh = inw * inh;
int outwh = outw * outh;
int channel_count = inc >> 3;
int channel_remain = inc - (channel_count << 3);
// generate the image tmp
float* img_tmp = ( float* )sys_malloc(8 * (unsigned long)inwh * (channel_count + 1) * sizeof(float));
float* kernel_tmp = ( float* )sys_malloc(8 * 9 * (channel_count + 1) * sizeof(float));
float* bias_tmp = ( float* )sys_malloc(8 * (channel_count + 1) * sizeof(float));
{
for (int i = 0; i < channel_count; i++)
{
int ii = i * 8;
const float* k0 = img_data + (ii + 0) * inwh;
const float* k1 = img_data + (ii + 1) * inwh;
const float* k2 = img_data + (ii + 2) * inwh;
const float* k3 = img_data + (ii + 3) * inwh;
const float* k4 = img_data + (ii + 4) * inwh;
const float* k5 = img_data + (ii + 5) * inwh;
const float* k6 = img_data + (ii + 6) * inwh;
const float* k7 = img_data + (ii + 7) * inwh;
const float* f0 = kernel_data + (ii + 0) * 9;
const float* f1 = kernel_data + (ii + 1) * 9;
const float* f2 = kernel_data + (ii + 2) * 9;
const float* f3 = kernel_data + (ii + 3) * 9;
const float* f4 = kernel_data + (ii + 4) * 9;
const float* f5 = kernel_data + (ii + 5) * 9;
const float* f6 = kernel_data + (ii + 6) * 9;
const float* f7 = kernel_data + (ii + 7) * 9;
const float* b0 = bias_data + (ii + 0);
const float* b1 = bias_data + (ii + 1);
const float* b2 = bias_data + (ii + 2);
const float* b3 = bias_data + (ii + 3);
const float* b4 = bias_data + (ii + 4);
const float* b5 = bias_data + (ii + 5);
const float* b6 = bias_data + (ii + 6);
const float* b7 = bias_data + (ii + 7);
float* tmp0 = img_tmp + ii * inwh;
float* tmp1 = kernel_tmp + ii * 9;
float* tmp2 = bias_tmp + ii;
for (int j = 0; j < inwh; j++)
{
tmp0[0] = k0[0];
tmp0[1] = k1[0];
tmp0[2] = k2[0];
tmp0[3] = k3[0];
tmp0[4] = k4[0];
tmp0[5] = k5[0];
tmp0[6] = k6[0];
tmp0[7] = k7[0];
tmp0 += 8;
k0++;
k1++;
k2++;
k3++;
k4++;
k5++;
k6++;
k7++;
}
for (int j = 0; j < 9; j++)
{
tmp1[0] = f0[0];
tmp1[1] = f1[0];
tmp1[2] = f2[0];
tmp1[3] = f3[0];
tmp1[4] = f4[0];
tmp1[5] = f5[0];
tmp1[6] = f6[0];
tmp1[7] = f7[0];
tmp1 += 8;
f0++;
f1++;
f2++;
f3++;
f4++;
f5++;
f6++;
f7++;
}
if (bias_data)
{
tmp2[0] = b0[0];
tmp2[1] = b1[0];
tmp2[2] = b2[0];
tmp2[3] = b3[0];
tmp2[4] = b4[0];
tmp2[5] = b5[0];
tmp2[6] = b6[0];
tmp2[7] = b7[0];
}
else
{
tmp2[0] = 0;
tmp2[1] = 0;
tmp2[2] = 0;
tmp2[3] = 0;
tmp2[4] = 0;
tmp2[5] = 0;
tmp2[6] = 0;
tmp2[7] = 0;
}
}
int i = 0;
for (; i + 3 < channel_remain; i += 4)
{
int ii = channel_count * 8 + i;
float* k0 = img_data + (ii + 0) * inwh;
float* k1 = img_data + (ii + 1) * inwh;
float* k2 = img_data + (ii + 2) * inwh;
float* k3 = img_data + (ii + 3) * inwh;
float* f0 = kernel_data + (ii + 0) * 9;
float* f1 = kernel_data + (ii + 1) * 9;
float* f2 = kernel_data + (ii + 2) * 9;
float* f3 = kernel_data + (ii + 3) * 9;
float* b0 = bias_data + (ii + 0);
float* b1 = bias_data + (ii + 1);
float* b2 = bias_data + (ii + 2);
float* b3 = bias_data + (ii + 3);
float* tmp0 = img_tmp + channel_count * 8 * inwh;
float* tmp1 = kernel_tmp + channel_count * 8 * 9;
float* tmp2 = bias_tmp + ii;
for (int j = 0; j < inwh; j++)
{
tmp0[0] = k0[0];
tmp0[1] = k1[0];
tmp0[2] = k2[0];
tmp0[3] = k3[0];
tmp0 += 8;
k0++;
k1++;
k2++;
k3++;
}
for (int j = 0; j < 9; j++)
{
tmp1[0] = f0[0];
tmp1[1] = f1[0];
tmp1[2] = f2[0];
tmp1[3] = f3[0];
tmp1 += 8;
f0++;
f1++;
f2++;
f3++;
}
if (bias_data)
{
tmp2[0] = b0[0];
tmp2[1] = b1[0];
tmp2[2] = b2[0];
tmp2[3] = b3[0];
}
else
{
tmp2[0] = 0;
tmp2[1] = 0;
tmp2[2] = 0;
tmp2[3] = 0;
}
}
for (; i < channel_remain; i++)
{
int ii = channel_count * 8 + i;
float* k0 = img_data + ii * inwh;
float* f0 = kernel_data + ii * 9;
float* b0 = bias_data + ii;
float* tmp0 = img_tmp + channel_count * 8 * inwh;
float* tmp1 = kernel_tmp + channel_count * 8 * 9;
float* tmp2 = bias_tmp + channel_count * 8;
for (int j = 0; j < inwh; j++)
{
tmp0[i] = k0[0];
tmp0 += 8;
k0++;
}
for (int j = 0; j < 9; j++)
{
tmp1[i] = f0[0];
tmp1 += 8;
f0++;
}
if (bias_data)
{
tmp2[i] = b0[0];
}
else
{
tmp2[i] = 0;
}
}
}
float* output_tmp = ( float* )sys_malloc((unsigned long)outwh * (channel_count + 1) * 8 * sizeof(float));
for (int c = 0; c < channel_count + 1; c++)
{
float* ktmp = kernel_tmp + c * 8 * 9;
float* btmp = bias_tmp + c * 8;
for (int i = 0; i < outh; i++)
{
int j = 0;
float* itmp0 = img_tmp + c * 8 * inwh + 8 * i * inw;
float* itmp1 = img_tmp + c * 8 * inwh + 8 * (i + 1) * inw;
float* itmp2 = img_tmp + c * 8 * inwh + 8 * (i + 2) * inw;
float* otmp = output_tmp + c * 8 * outwh + 8 * i * outw;
for (; j + 7 < outw; j += 8)
{
__m256 _sum0 = _mm256_loadu_ps(btmp);
__m256 _sum1 = _mm256_loadu_ps(btmp);
__m256 _sum2 = _mm256_loadu_ps(btmp);
__m256 _sum3 = _mm256_loadu_ps(btmp);
__m256 _sum4 = _mm256_loadu_ps(btmp);
__m256 _sum5 = _mm256_loadu_ps(btmp);
__m256 _sum6 = _mm256_loadu_ps(btmp);
__m256 _sum7 = _mm256_loadu_ps(btmp);
__m256 _va0 = _mm256_loadu_ps(itmp0);
__m256 _va1 = _mm256_loadu_ps(itmp0 + 8);
__m256 _va2 = _mm256_loadu_ps(itmp0 + 16);
__m256 _va3 = _mm256_loadu_ps(itmp0 + 24);
__m256 _va4 = _mm256_loadu_ps(itmp0 + 32);
__m256 _va5 = _mm256_loadu_ps(itmp0 + 40);
__m256 _va6 = _mm256_loadu_ps(itmp0 + 48);
__m256 _va7 = _mm256_loadu_ps(itmp0 + 56);
__m256 _va8 = _mm256_loadu_ps(itmp0 + 64);
__m256 _va9 = _mm256_loadu_ps(itmp0 + 72);
__m256 _vb0 = _mm256_loadu_ps(ktmp);
__m256 _vb1 = _mm256_loadu_ps(ktmp + 8);
__m256 _vb2 = _mm256_loadu_ps(ktmp + 16);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum2 = _mm256_fmadd_ps(_va2, _vb0, _sum2);
_sum3 = _mm256_fmadd_ps(_va3, _vb0, _sum3);
_sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1);
_sum2 = _mm256_fmadd_ps(_va3, _vb1, _sum2);
_sum3 = _mm256_fmadd_ps(_va4, _vb1, _sum3);
_sum4 = _mm256_fmadd_ps(_va4, _vb0, _sum4);
_sum2 = _mm256_fmadd_ps(_va4, _vb2, _sum2);
_sum3 = _mm256_fmadd_ps(_va5, _vb2, _sum3);
_sum5 = _mm256_fmadd_ps(_va5, _vb0, _sum5);
_sum4 = _mm256_fmadd_ps(_va5, _vb1, _sum4);
_sum5 = _mm256_fmadd_ps(_va6, _vb1, _sum5);
_sum4 = _mm256_fmadd_ps(_va6, _vb2, _sum4);
_sum6 = _mm256_fmadd_ps(_va6, _vb0, _sum6);
_sum7 = _mm256_fmadd_ps(_va7, _vb0, _sum7);
_sum5 = _mm256_fmadd_ps(_va7, _vb2, _sum5);
_sum6 = _mm256_fmadd_ps(_va7, _vb1, _sum6);
_sum7 = _mm256_fmadd_ps(_va8, _vb1, _sum7);
_sum6 = _mm256_fmadd_ps(_va8, _vb2, _sum6);
_sum7 = _mm256_fmadd_ps(_va9, _vb2, _sum7);
_va0 = _mm256_loadu_ps(itmp1);
_va1 = _mm256_loadu_ps(itmp1 + 8);
_va2 = _mm256_loadu_ps(itmp1 + 16);
_va3 = _mm256_loadu_ps(itmp1 + 24);
_va4 = _mm256_loadu_ps(itmp1 + 32);
_va5 = _mm256_loadu_ps(itmp1 + 40);
_va6 = _mm256_loadu_ps(itmp1 + 48);
_va7 = _mm256_loadu_ps(itmp1 + 56);
_va8 = _mm256_loadu_ps(itmp1 + 64);
_va9 = _mm256_loadu_ps(itmp1 + 72);
_vb0 = _mm256_loadu_ps(ktmp + 24);
_vb1 = _mm256_loadu_ps(ktmp + 32);
_vb2 = _mm256_loadu_ps(ktmp + 40);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum2 = _mm256_fmadd_ps(_va2, _vb0, _sum2);
_sum3 = _mm256_fmadd_ps(_va3, _vb0, _sum3);
_sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1);
_sum2 = _mm256_fmadd_ps(_va3, _vb1, _sum2);
_sum3 = _mm256_fmadd_ps(_va4, _vb1, _sum3);
_sum4 = _mm256_fmadd_ps(_va4, _vb0, _sum4);
_sum2 = _mm256_fmadd_ps(_va4, _vb2, _sum2);
_sum3 = _mm256_fmadd_ps(_va5, _vb2, _sum3);
_sum5 = _mm256_fmadd_ps(_va5, _vb0, _sum5);
_sum4 = _mm256_fmadd_ps(_va5, _vb1, _sum4);
_sum5 = _mm256_fmadd_ps(_va6, _vb1, _sum5);
_sum4 = _mm256_fmadd_ps(_va6, _vb2, _sum4);
_sum6 = _mm256_fmadd_ps(_va6, _vb0, _sum6);
_sum7 = _mm256_fmadd_ps(_va7, _vb0, _sum7);
_sum5 = _mm256_fmadd_ps(_va7, _vb2, _sum5);
_sum6 = _mm256_fmadd_ps(_va7, _vb1, _sum6);
_sum7 = _mm256_fmadd_ps(_va8, _vb1, _sum7);
_sum6 = _mm256_fmadd_ps(_va8, _vb2, _sum6);
_sum7 = _mm256_fmadd_ps(_va9, _vb2, _sum7);
_va0 = _mm256_loadu_ps(itmp2);
_va1 = _mm256_loadu_ps(itmp2 + 8);
_va2 = _mm256_loadu_ps(itmp2 + 16);
_va3 = _mm256_loadu_ps(itmp2 + 24);
_va4 = _mm256_loadu_ps(itmp2 + 32);
_va5 = _mm256_loadu_ps(itmp2 + 40);
_va6 = _mm256_loadu_ps(itmp2 + 48);
_va7 = _mm256_loadu_ps(itmp2 + 56);
_va8 = _mm256_loadu_ps(itmp2 + 64);
_va9 = _mm256_loadu_ps(itmp2 + 72);
_vb0 = _mm256_loadu_ps(ktmp + 48);
_vb1 = _mm256_loadu_ps(ktmp + 56);
_vb2 = _mm256_loadu_ps(ktmp + 64);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum2 = _mm256_fmadd_ps(_va2, _vb0, _sum2);
_sum3 = _mm256_fmadd_ps(_va3, _vb0, _sum3);
_sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1);
_sum2 = _mm256_fmadd_ps(_va3, _vb1, _sum2);
_sum3 = _mm256_fmadd_ps(_va4, _vb1, _sum3);
_sum4 = _mm256_fmadd_ps(_va4, _vb0, _sum4);
_sum2 = _mm256_fmadd_ps(_va4, _vb2, _sum2);
_sum3 = _mm256_fmadd_ps(_va5, _vb2, _sum3);
_sum5 = _mm256_fmadd_ps(_va5, _vb0, _sum5);
_sum4 = _mm256_fmadd_ps(_va5, _vb1, _sum4);
_sum5 = _mm256_fmadd_ps(_va6, _vb1, _sum5);
_sum4 = _mm256_fmadd_ps(_va6, _vb2, _sum4);
_sum6 = _mm256_fmadd_ps(_va6, _vb0, _sum6);
_sum7 = _mm256_fmadd_ps(_va7, _vb0, _sum7);
_sum5 = _mm256_fmadd_ps(_va7, _vb2, _sum5);
_sum6 = _mm256_fmadd_ps(_va7, _vb1, _sum6);
_sum7 = _mm256_fmadd_ps(_va8, _vb1, _sum7);
_sum6 = _mm256_fmadd_ps(_va8, _vb2, _sum6);
_sum7 = _mm256_fmadd_ps(_va9, _vb2, _sum7);
_mm256_storeu_ps(otmp, _sum0);
_mm256_storeu_ps(otmp + 8, _sum1);
_mm256_storeu_ps(otmp + 16, _sum2);
_mm256_storeu_ps(otmp + 24, _sum3);
_mm256_storeu_ps(otmp + 32, _sum4);
_mm256_storeu_ps(otmp + 40, _sum5);
_mm256_storeu_ps(otmp + 48, _sum6);
_mm256_storeu_ps(otmp + 56, _sum7);
itmp0 += 64;
itmp1 += 64;
itmp2 += 64;
otmp += 64;
}
for (; j + 3 < outw; j += 4)
{
__m256 _sum0 = _mm256_loadu_ps(btmp);
__m256 _sum1 = _mm256_loadu_ps(btmp);
__m256 _sum2 = _mm256_loadu_ps(btmp);
__m256 _sum3 = _mm256_loadu_ps(btmp);
__m256 _va0 = _mm256_loadu_ps(itmp0);
__m256 _va1 = _mm256_loadu_ps(itmp0 + 8);
__m256 _va2 = _mm256_loadu_ps(itmp0 + 16);
__m256 _va3 = _mm256_loadu_ps(itmp0 + 24);
__m256 _va4 = _mm256_loadu_ps(itmp0 + 32);
__m256 _va5 = _mm256_loadu_ps(itmp0 + 40);
__m256 _vb0 = _mm256_loadu_ps(ktmp);
__m256 _vb1 = _mm256_loadu_ps(ktmp + 8);
__m256 _vb2 = _mm256_loadu_ps(ktmp + 16);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum2 = _mm256_fmadd_ps(_va2, _vb0, _sum2);
_sum3 = _mm256_fmadd_ps(_va3, _vb0, _sum3);
_sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1);
_sum2 = _mm256_fmadd_ps(_va3, _vb1, _sum2);
_sum3 = _mm256_fmadd_ps(_va4, _vb1, _sum3);
_sum2 = _mm256_fmadd_ps(_va4, _vb2, _sum2);
_sum3 = _mm256_fmadd_ps(_va5, _vb2, _sum3);
_va0 = _mm256_loadu_ps(itmp1);
_va1 = _mm256_loadu_ps(itmp1 + 8);
_va2 = _mm256_loadu_ps(itmp1 + 16);
_va3 = _mm256_loadu_ps(itmp1 + 24);
_va4 = _mm256_loadu_ps(itmp1 + 32);
_va5 = _mm256_loadu_ps(itmp1 + 40);
_vb0 = _mm256_loadu_ps(ktmp + 24);
_vb1 = _mm256_loadu_ps(ktmp + 32);
_vb2 = _mm256_loadu_ps(ktmp + 40);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum2 = _mm256_fmadd_ps(_va2, _vb0, _sum2);
_sum3 = _mm256_fmadd_ps(_va3, _vb0, _sum3);
_sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1);
_sum2 = _mm256_fmadd_ps(_va3, _vb1, _sum2);
_sum3 = _mm256_fmadd_ps(_va4, _vb1, _sum3);
_sum2 = _mm256_fmadd_ps(_va4, _vb2, _sum2);
_sum3 = _mm256_fmadd_ps(_va5, _vb2, _sum3);
_va0 = _mm256_loadu_ps(itmp2);
_va1 = _mm256_loadu_ps(itmp2 + 8);
_va2 = _mm256_loadu_ps(itmp2 + 16);
_va3 = _mm256_loadu_ps(itmp2 + 24);
_va4 = _mm256_loadu_ps(itmp2 + 32);
_va5 = _mm256_loadu_ps(itmp2 + 40);
_vb0 = _mm256_loadu_ps(ktmp + 48);
_vb1 = _mm256_loadu_ps(ktmp + 56);
_vb2 = _mm256_loadu_ps(ktmp + 64);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum2 = _mm256_fmadd_ps(_va2, _vb0, _sum2);
_sum3 = _mm256_fmadd_ps(_va3, _vb0, _sum3);
_sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1);
_sum2 = _mm256_fmadd_ps(_va3, _vb1, _sum2);
_sum3 = _mm256_fmadd_ps(_va4, _vb1, _sum3);
_sum2 = _mm256_fmadd_ps(_va4, _vb2, _sum2);
_sum3 = _mm256_fmadd_ps(_va5, _vb2, _sum3);
_mm256_storeu_ps(otmp, _sum0);
_mm256_storeu_ps(otmp + 8, _sum1);
_mm256_storeu_ps(otmp + 16, _sum2);
_mm256_storeu_ps(otmp + 24, _sum3);
itmp0 += 32;
itmp1 += 32;
itmp2 += 32;
otmp += 32;
}
for (; j + 1 < outw; j += 2)
{
__m256 _sum0 = _mm256_loadu_ps(btmp);
__m256 _sum1 = _mm256_loadu_ps(btmp);
__m256 _va0 = _mm256_loadu_ps(itmp0);
__m256 _va1 = _mm256_loadu_ps(itmp0 + 8);
__m256 _va2 = _mm256_loadu_ps(itmp0 + 16);
__m256 _va3 = _mm256_loadu_ps(itmp0 + 24);
__m256 _vb0 = _mm256_loadu_ps(ktmp);
__m256 _vb1 = _mm256_loadu_ps(ktmp + 8);
__m256 _vb2 = _mm256_loadu_ps(ktmp + 16);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1);
_va0 = _mm256_loadu_ps(itmp1);
_va1 = _mm256_loadu_ps(itmp1 + 8);
_va2 = _mm256_loadu_ps(itmp1 + 16);
_va3 = _mm256_loadu_ps(itmp1 + 24);
_vb0 = _mm256_loadu_ps(ktmp + 24);
_vb1 = _mm256_loadu_ps(ktmp + 32);
_vb2 = _mm256_loadu_ps(ktmp + 40);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1);
_va0 = _mm256_loadu_ps(itmp2);
_va1 = _mm256_loadu_ps(itmp2 + 8);
_va2 = _mm256_loadu_ps(itmp2 + 16);
_va3 = _mm256_loadu_ps(itmp2 + 24);
_vb0 = _mm256_loadu_ps(ktmp + 48);
_vb1 = _mm256_loadu_ps(ktmp + 56);
_vb2 = _mm256_loadu_ps(ktmp + 64);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1);
_mm256_storeu_ps(otmp, _sum0);
_mm256_storeu_ps(otmp + 8, _sum1);
itmp0 += 16;
itmp1 += 16;
itmp2 += 16;
otmp += 16;
}
for (; j < outw; j++)
{
__m256 _sum0 = _mm256_loadu_ps(btmp);
__m256 _va0 = _mm256_loadu_ps(itmp0);
__m256 _va1 = _mm256_loadu_ps(itmp0 + 8);
__m256 _va2 = _mm256_loadu_ps(itmp0 + 16);
__m256 _vb0 = _mm256_loadu_ps(ktmp);
__m256 _vb1 = _mm256_loadu_ps(ktmp + 8);
__m256 _vb2 = _mm256_loadu_ps(ktmp + 16);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_va0 = _mm256_loadu_ps(itmp1);
_va1 = _mm256_loadu_ps(itmp1 + 8);
_va2 = _mm256_loadu_ps(itmp1 + 16);
_vb0 = _mm256_loadu_ps(ktmp + 24);
_vb1 = _mm256_loadu_ps(ktmp + 32);
_vb2 = _mm256_loadu_ps(ktmp + 40);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_va0 = _mm256_loadu_ps(itmp2);
_va1 = _mm256_loadu_ps(itmp2 + 8);
_va2 = _mm256_loadu_ps(itmp2 + 16);
_vb0 = _mm256_loadu_ps(ktmp + 48);
_vb1 = _mm256_loadu_ps(ktmp + 56);
_vb2 = _mm256_loadu_ps(ktmp + 64);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_mm256_storeu_ps(otmp, _sum0);
itmp0 += 8;
itmp1 += 8;
itmp2 += 8;
otmp += 8;
}
}
}
// load_data
{
for (int i = 0; i < channel_count; i++)
{
float* otmp = output_tmp + i * 8 * outwh;
float* tmp0 = output + i * 8 * outwh;
float* tmp1 = output + i * 8 * outwh + 1 * outwh;
float* tmp2 = output + i * 8 * outwh + 2 * outwh;
float* tmp3 = output + i * 8 * outwh + 3 * outwh;
float* tmp4 = output + i * 8 * outwh + 4 * outwh;
float* tmp5 = output + i * 8 * outwh + 5 * outwh;
float* tmp6 = output + i * 8 * outwh + 6 * outwh;
float* tmp7 = output + i * 8 * outwh + 7 * outwh;
for (int i = 0; i < outwh; i++)
{
tmp0[0] = otmp[0];
tmp1[0] = otmp[1];
tmp2[0] = otmp[2];
tmp3[0] = otmp[3];
tmp4[0] = otmp[4];
tmp5[0] = otmp[5];
tmp6[0] = otmp[6];
tmp7[0] = otmp[7];
otmp += 8;
tmp0++;
tmp1++;
tmp2++;
tmp3++;
tmp4++;
tmp5++;
tmp6++;
tmp7++;
}
}
int i = 0;
for (; i + 3 < channel_remain; i += 4)
{
int ii = channel_count * 8 + i;
float* otmp = output_tmp + ii * outwh;
float* tmp0 = output + ii * outwh;
float* tmp1 = output + ii * outwh + 1 * outwh;
float* tmp2 = output + ii * outwh + 2 * outwh;
float* tmp3 = output + ii * outwh + 3 * outwh;
for (int j = 0; j < outwh; j++)
{
tmp0[0] = otmp[0];
tmp1[0] = otmp[1];
tmp2[0] = otmp[2];
tmp3[0] = otmp[3];
otmp += 8;
tmp0++;
tmp1++;
tmp2++;
tmp3++;
}
}
for (; i < channel_remain; i++)
{
int ii = channel_count * 8 + i;
float* otmp = output_tmp + channel_count * 8 * outwh;
float* tmp0 = output + ii * outwh;
for (int j = 0; j < outwh; j++)
{
tmp0[0] = otmp[i];
otmp += 8;
tmp0++;
}
}
}
sys_free(output_tmp);
sys_free(img_tmp);
sys_free(kernel_tmp);
sys_free(bias_tmp);
}
static void convdw3x3s2(float* output, float* img_data, float* kernel_data, float* bias_data, int inc, int inh, int inw,
int outh, int outw, int num_thread)
{
int inwh = inw * inh;
int outwh = outw * outh;
int channel_count = inc >> 3;
int channel_remain = inc - (channel_count << 3);
// generate the image tmp
float* img_tmp = ( float* )sys_malloc(8 * (unsigned long)inwh * (channel_count + 1) * sizeof(float));
float* kernel_tmp = ( float* )sys_malloc(8 * 9 * (channel_count + 1) * sizeof(float));
float* bias_tmp = ( float* )sys_malloc(8 * (channel_count + 1) * sizeof(float));
{
for (int i = 0; i < channel_count; i++)
{
int ii = i * 8;
const float* k0 = img_data + (ii + 0) * inwh;
const float* k1 = img_data + (ii + 1) * inwh;
const float* k2 = img_data + (ii + 2) * inwh;
const float* k3 = img_data + (ii + 3) * inwh;
const float* k4 = img_data + (ii + 4) * inwh;
const float* k5 = img_data + (ii + 5) * inwh;
const float* k6 = img_data + (ii + 6) * inwh;
const float* k7 = img_data + (ii + 7) * inwh;
const float* f0 = kernel_data + (ii + 0) * 9;
const float* f1 = kernel_data + (ii + 1) * 9;
const float* f2 = kernel_data + (ii + 2) * 9;
const float* f3 = kernel_data + (ii + 3) * 9;
const float* f4 = kernel_data + (ii + 4) * 9;
const float* f5 = kernel_data + (ii + 5) * 9;
const float* f6 = kernel_data + (ii + 6) * 9;
const float* f7 = kernel_data + (ii + 7) * 9;
const float* b0 = bias_data + (ii + 0);
const float* b1 = bias_data + (ii + 1);
const float* b2 = bias_data + (ii + 2);
const float* b3 = bias_data + (ii + 3);
const float* b4 = bias_data + (ii + 4);
const float* b5 = bias_data + (ii + 5);
const float* b6 = bias_data + (ii + 6);
const float* b7 = bias_data + (ii + 7);
float* tmp0 = img_tmp + ii * inwh;
float* tmp1 = kernel_tmp + ii * 9;
float* tmp2 = bias_tmp + ii;
for (int j = 0; j < inwh; j++)
{
tmp0[0] = k0[0];
tmp0[1] = k1[0];
tmp0[2] = k2[0];
tmp0[3] = k3[0];
tmp0[4] = k4[0];
tmp0[5] = k5[0];
tmp0[6] = k6[0];
tmp0[7] = k7[0];
tmp0 += 8;
k0++;
k1++;
k2++;
k3++;
k4++;
k5++;
k6++;
k7++;
}
for (int j = 0; j < 9; j++)
{
tmp1[0] = f0[0];
tmp1[1] = f1[0];
tmp1[2] = f2[0];
tmp1[3] = f3[0];
tmp1[4] = f4[0];
tmp1[5] = f5[0];
tmp1[6] = f6[0];
tmp1[7] = f7[0];
tmp1 += 8;
f0++;
f1++;
f2++;
f3++;
f4++;
f5++;
f6++;
f7++;
}
if (bias_data)
{
tmp2[0] = b0[0];
tmp2[1] = b1[0];
tmp2[2] = b2[0];
tmp2[3] = b3[0];
tmp2[4] = b4[0];
tmp2[5] = b5[0];
tmp2[6] = b6[0];
tmp2[7] = b7[0];
}
else
{
tmp2[0] = 0;
tmp2[1] = 0;
tmp2[2] = 0;
tmp2[3] = 0;
tmp2[4] = 0;
tmp2[5] = 0;
tmp2[6] = 0;
tmp2[7] = 0;
}
}
int i = 0;
for (; i + 3 < channel_remain; i += 4)
{
int ii = channel_count * 8 + i;
float* k0 = img_data + (ii + 0) * inwh;
float* k1 = img_data + (ii + 1) * inwh;
float* k2 = img_data + (ii + 2) * inwh;
float* k3 = img_data + (ii + 3) * inwh;
float* f0 = kernel_data + (ii + 0) * 9;
float* f1 = kernel_data + (ii + 1) * 9;
float* f2 = kernel_data + (ii + 2) * 9;
float* f3 = kernel_data + (ii + 3) * 9;
float* b0 = bias_data + (ii + 0);
float* b1 = bias_data + (ii + 1);
float* b2 = bias_data + (ii + 2);
float* b3 = bias_data + (ii + 3);
float* tmp0 = img_tmp + channel_count * 8 * inwh;
float* tmp1 = kernel_tmp + channel_count * 8 * 9;
float* tmp2 = bias_tmp + ii;
for (int j = 0; j < inwh; j++)
{
tmp0[0] = k0[0];
tmp0[1] = k1[0];
tmp0[2] = k2[0];
tmp0[3] = k3[0];
tmp0 += 8;
k0++;
k1++;
k2++;
k3++;
}
for (int j = 0; j < 9; j++)
{
tmp1[0] = f0[0];
tmp1[1] = f1[0];
tmp1[2] = f2[0];
tmp1[3] = f3[0];
tmp1 += 8;
f0++;
f1++;
f2++;
f3++;
}
if (bias_data)
{
tmp2[0] = b0[0];
tmp2[1] = b1[0];
tmp2[2] = b2[0];
tmp2[3] = b3[0];
}
else
{
tmp2[0] = 0;
tmp2[1] = 0;
tmp2[2] = 0;
tmp2[3] = 0;
}
}
for (; i < channel_remain; i++)
{
int ii = channel_count * 8 + i;
float* k0 = img_data + ii * inwh;
float* f0 = kernel_data + ii * 9;
float* b0 = bias_data + ii;
float* tmp0 = img_tmp + channel_count * 8 * inwh;
float* tmp1 = kernel_tmp + channel_count * 8 * 9;
float* tmp2 = bias_tmp + channel_count * 8;
for (int j = 0; j < inwh; j++)
{
tmp0[i] = k0[0];
tmp0 += 8;
k0++;
}
for (int j = 0; j < 9; j++)
{
tmp1[i] = f0[0];
tmp1 += 8;
f0++;
}
if (bias_data)
{
tmp2[i] = b0[0];
}
else
{
tmp2[i] = 0;
}
}
}
float* output_tmp = ( float* )sys_malloc((unsigned long)outwh * (channel_count + 1) * 8 * sizeof(float));
for (int c = 0; c < channel_count + 1; c++)
{
float* ktmp = kernel_tmp + c * 8 * 9;
float* btmp = bias_tmp + c * 8;
for (int i = 0; i < outh; i++)
{
int j = 0;
float* itmp0 = img_tmp + c * 8 * inwh + 8 * i * 2 * inw;
float* itmp1 = img_tmp + c * 8 * inwh + 8 * (i * 2 + 1) * inw;
float* itmp2 = img_tmp + c * 8 * inwh + 8 * (i * 2 + 2) * inw;
float* otmp = output_tmp + c * 8 * outwh + 8 * i * outw;
for (; j + 3 < outw; j += 4)
{
__m256 _sum0 = _mm256_loadu_ps(btmp);
__m256 _sum1 = _mm256_loadu_ps(btmp);
__m256 _sum2 = _mm256_loadu_ps(btmp);
__m256 _sum3 = _mm256_loadu_ps(btmp);
__m256 _va0 = _mm256_loadu_ps(itmp0);
__m256 _va1 = _mm256_loadu_ps(itmp0 + 8);
__m256 _va2 = _mm256_loadu_ps(itmp0 + 16);
__m256 _va3 = _mm256_loadu_ps(itmp0 + 24);
__m256 _va4 = _mm256_loadu_ps(itmp0 + 32);
__m256 _va5 = _mm256_loadu_ps(itmp0 + 40);
__m256 _va6 = _mm256_loadu_ps(itmp0 + 48);
__m256 _va7 = _mm256_loadu_ps(itmp0 + 56);
__m256 _va8 = _mm256_loadu_ps(itmp0 + 64);
__m256 _vb0 = _mm256_loadu_ps(ktmp);
__m256 _vb1 = _mm256_loadu_ps(ktmp + 8);
__m256 _vb2 = _mm256_loadu_ps(ktmp + 16);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb0, _sum1);
_sum1 = _mm256_fmadd_ps(_va3, _vb1, _sum1);
_sum1 = _mm256_fmadd_ps(_va4, _vb2, _sum1);
_sum2 = _mm256_fmadd_ps(_va4, _vb0, _sum2);
_sum2 = _mm256_fmadd_ps(_va5, _vb1, _sum2);
_sum2 = _mm256_fmadd_ps(_va6, _vb2, _sum2);
_sum3 = _mm256_fmadd_ps(_va6, _vb0, _sum3);
_sum3 = _mm256_fmadd_ps(_va7, _vb1, _sum3);
_sum3 = _mm256_fmadd_ps(_va8, _vb2, _sum3);
_va0 = _mm256_loadu_ps(itmp1);
_va1 = _mm256_loadu_ps(itmp1 + 8);
_va2 = _mm256_loadu_ps(itmp1 + 16);
_va3 = _mm256_loadu_ps(itmp1 + 24);
_va4 = _mm256_loadu_ps(itmp1 + 32);
_va5 = _mm256_loadu_ps(itmp1 + 40);
_va6 = _mm256_loadu_ps(itmp1 + 48);
_va7 = _mm256_loadu_ps(itmp1 + 56);
_va8 = _mm256_loadu_ps(itmp1 + 64);
_vb0 = _mm256_loadu_ps(ktmp + 24);
_vb1 = _mm256_loadu_ps(ktmp + 32);
_vb2 = _mm256_loadu_ps(ktmp + 40);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb0, _sum1);
_sum1 = _mm256_fmadd_ps(_va3, _vb1, _sum1);
_sum1 = _mm256_fmadd_ps(_va4, _vb2, _sum1);
_sum2 = _mm256_fmadd_ps(_va4, _vb0, _sum2);
_sum2 = _mm256_fmadd_ps(_va5, _vb1, _sum2);
_sum2 = _mm256_fmadd_ps(_va6, _vb2, _sum2);
_sum3 = _mm256_fmadd_ps(_va6, _vb0, _sum3);
_sum3 = _mm256_fmadd_ps(_va7, _vb1, _sum3);
_sum3 = _mm256_fmadd_ps(_va8, _vb2, _sum3);
_va0 = _mm256_loadu_ps(itmp2);
_va1 = _mm256_loadu_ps(itmp2 + 8);
_va2 = _mm256_loadu_ps(itmp2 + 16);
_va3 = _mm256_loadu_ps(itmp2 + 24);
_va4 = _mm256_loadu_ps(itmp2 + 32);
_va5 = _mm256_loadu_ps(itmp2 + 40);
_va6 = _mm256_loadu_ps(itmp2 + 48);
_va7 = _mm256_loadu_ps(itmp2 + 56);
_va8 = _mm256_loadu_ps(itmp2 + 64);
_vb0 = _mm256_loadu_ps(ktmp + 48);
_vb1 = _mm256_loadu_ps(ktmp + 56);
_vb2 = _mm256_loadu_ps(ktmp + 64);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb0, _sum1);
_sum1 = _mm256_fmadd_ps(_va3, _vb1, _sum1);
_sum1 = _mm256_fmadd_ps(_va4, _vb2, _sum1);
_sum2 = _mm256_fmadd_ps(_va4, _vb0, _sum2);
_sum2 = _mm256_fmadd_ps(_va5, _vb1, _sum2);
_sum2 = _mm256_fmadd_ps(_va6, _vb2, _sum2);
_sum3 = _mm256_fmadd_ps(_va6, _vb0, _sum3);
_sum3 = _mm256_fmadd_ps(_va7, _vb1, _sum3);
_sum3 = _mm256_fmadd_ps(_va8, _vb2, _sum3);
_mm256_storeu_ps(otmp, _sum0);
_mm256_storeu_ps(otmp + 8, _sum1);
_mm256_storeu_ps(otmp + 16, _sum2);
_mm256_storeu_ps(otmp + 24, _sum3);
itmp0 += 64;
itmp1 += 64;
itmp2 += 64;
otmp += 32;
}
for (; j + 1 < outw; j += 2)
{
__m256 _sum0 = _mm256_loadu_ps(btmp);
__m256 _sum1 = _mm256_loadu_ps(btmp);
__m256 _va0 = _mm256_loadu_ps(itmp0);
__m256 _va1 = _mm256_loadu_ps(itmp0 + 8);
__m256 _va2 = _mm256_loadu_ps(itmp0 + 16);
__m256 _va3 = _mm256_loadu_ps(itmp0 + 24);
__m256 _va4 = _mm256_loadu_ps(itmp0 + 32);
__m256 _vb0 = _mm256_loadu_ps(ktmp);
__m256 _vb1 = _mm256_loadu_ps(ktmp + 8);
__m256 _vb2 = _mm256_loadu_ps(ktmp + 16);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb0, _sum1);
_sum1 = _mm256_fmadd_ps(_va3, _vb1, _sum1);
_sum1 = _mm256_fmadd_ps(_va4, _vb2, _sum1);
_va0 = _mm256_loadu_ps(itmp1);
_va1 = _mm256_loadu_ps(itmp1 + 8);
_va2 = _mm256_loadu_ps(itmp1 + 16);
_va3 = _mm256_loadu_ps(itmp1 + 24);
_va4 = _mm256_loadu_ps(itmp1 + 32);
_vb0 = _mm256_loadu_ps(ktmp + 24);
_vb1 = _mm256_loadu_ps(ktmp + 32);
_vb2 = _mm256_loadu_ps(ktmp + 40);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb0, _sum1);
_sum1 = _mm256_fmadd_ps(_va3, _vb1, _sum1);
_sum1 = _mm256_fmadd_ps(_va4, _vb2, _sum1);
_va0 = _mm256_loadu_ps(itmp2);
_va1 = _mm256_loadu_ps(itmp2 + 8);
_va2 = _mm256_loadu_ps(itmp2 + 16);
_va3 = _mm256_loadu_ps(itmp2 + 24);
_va4 = _mm256_loadu_ps(itmp2 + 32);
_vb0 = _mm256_loadu_ps(ktmp + 48);
_vb1 = _mm256_loadu_ps(ktmp + 56);
_vb2 = _mm256_loadu_ps(ktmp + 64);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_sum1 = _mm256_fmadd_ps(_va2, _vb0, _sum1);
_sum1 = _mm256_fmadd_ps(_va3, _vb1, _sum1);
_sum1 = _mm256_fmadd_ps(_va4, _vb2, _sum1);
_mm256_storeu_ps(otmp, _sum0);
_mm256_storeu_ps(otmp + 8, _sum1);
itmp0 += 32;
itmp1 += 32;
itmp2 += 32;
otmp += 16;
}
for (; j < outw; j++)
{
__m256 _sum0 = _mm256_loadu_ps(btmp);
__m256 _va0 = _mm256_loadu_ps(itmp0);
__m256 _va1 = _mm256_loadu_ps(itmp0 + 8);
__m256 _va2 = _mm256_loadu_ps(itmp0 + 16);
__m256 _vb0 = _mm256_loadu_ps(ktmp);
__m256 _vb1 = _mm256_loadu_ps(ktmp + 8);
__m256 _vb2 = _mm256_loadu_ps(ktmp + 16);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_va0 = _mm256_loadu_ps(itmp1);
_va1 = _mm256_loadu_ps(itmp1 + 8);
_va2 = _mm256_loadu_ps(itmp1 + 16);
_vb0 = _mm256_loadu_ps(ktmp + 24);
_vb1 = _mm256_loadu_ps(ktmp + 32);
_vb2 = _mm256_loadu_ps(ktmp + 40);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_va0 = _mm256_loadu_ps(itmp2);
_va1 = _mm256_loadu_ps(itmp2 + 8);
_va2 = _mm256_loadu_ps(itmp2 + 16);
_vb0 = _mm256_loadu_ps(ktmp + 48);
_vb1 = _mm256_loadu_ps(ktmp + 56);
_vb2 = _mm256_loadu_ps(ktmp + 64);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);
_sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0);
_sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0);
_mm256_storeu_ps(otmp, _sum0);
itmp0 += 16;
itmp1 += 16;
itmp2 += 16;
otmp += 8;
}
}
}
// load_data
{
for (int i = 0; i < channel_count; i++)
{
float* otmp = output_tmp + i * 8 * outwh;
float* tmp0 = output + i * 8 * outwh;
float* tmp1 = output + i * 8 * outwh + 1 * outwh;
float* tmp2 = output + i * 8 * outwh + 2 * outwh;
float* tmp3 = output + i * 8 * outwh + 3 * outwh;
float* tmp4 = output + i * 8 * outwh + 4 * outwh;
float* tmp5 = output + i * 8 * outwh + 5 * outwh;
float* tmp6 = output + i * 8 * outwh + 6 * outwh;
float* tmp7 = output + i * 8 * outwh + 7 * outwh;
for (int i = 0; i < outwh; i++)
{
tmp0[0] = otmp[0];
tmp1[0] = otmp[1];
tmp2[0] = otmp[2];
tmp3[0] = otmp[3];
tmp4[0] = otmp[4];
tmp5[0] = otmp[5];
tmp6[0] = otmp[6];
tmp7[0] = otmp[7];
otmp += 8;
tmp0++;
tmp1++;
tmp2++;
tmp3++;
tmp4++;
tmp5++;
tmp6++;
tmp7++;
}
}
int i = 0;
for (; i + 3 < channel_remain; i += 4)
{
int ii = channel_count * 8 + i;
float* otmp = output_tmp + ii * outwh;
float* tmp0 = output + ii * outwh;
float* tmp1 = output + ii * outwh + 1 * outwh;
float* tmp2 = output + ii * outwh + 2 * outwh;
float* tmp3 = output + ii * outwh + 3 * outwh;
for (int j = 0; j < outwh; j++)
{
tmp0[0] = otmp[0];
tmp1[0] = otmp[1];
tmp2[0] = otmp[2];
tmp3[0] = otmp[3];
otmp += 8;
tmp0++;
tmp1++;
tmp2++;
tmp3++;
}
}
for (; i < channel_remain; i++)
{
int ii = channel_count * 8 + i;
float* otmp = output_tmp + channel_count * 8 * outwh;
float* tmp0 = output + ii * outwh;
for (int j = 0; j < outwh; j++)
{
tmp0[0] = otmp[i];
otmp += 8;
tmp0++;
}
}
}
sys_free(output_tmp);
sys_free(img_tmp);
sys_free(kernel_tmp);
sys_free(bias_tmp);
}
#elif __SSE2__
static void convdw3x3s1(float* output, float* img_data, float* kernel_data, float* bias_data, int inc, int inh, int inw,
int outh, int outw, int num_thread)
{
int inwh = inw * inh;
int outwh = outw * outh;
int channel_count = inc >> 2;
int channel_remain = inc - (channel_count << 2);
// generate the image tmp
float* img_tmp = ( float* )sys_malloc(4 * inwh * (channel_count + 1) * sizeof(float));
float* kernel_tmp = ( float* )sys_malloc(4 * 9 * (channel_count + 1) * sizeof(float));
float* bias_tmp = ( float* )sys_malloc(4 * (channel_count + 1) * sizeof(float));
{
for (int i = 0; i < channel_count; i++)
{
int ii = i * 4;
float* k0 = img_data + (ii + 0) * inwh;
float* k1 = img_data + (ii + 1) * inwh;
float* k2 = img_data + (ii + 2) * inwh;
float* k3 = img_data + (ii + 3) * inwh;
float* f0 = kernel_data + (ii + 0) * 9;
float* f1 = kernel_data + (ii + 1) * 9;
float* f2 = kernel_data + (ii + 2) * 9;
float* f3 = kernel_data + (ii + 3) * 9;
float* b0 = bias_data + (ii + 0);
float* b1 = bias_data + (ii + 1);
float* b2 = bias_data + (ii + 2);
float* b3 = bias_data + (ii + 3);
float* tmp0 = img_tmp + ii * inwh;
float* tmp1 = kernel_tmp + ii * 9;
float* tmp2 = bias_tmp + ii;
for (int j = 0; j < inwh; j++)
{
tmp0[0] = k0[0];
tmp0[1] = k1[0];
tmp0[2] = k2[0];
tmp0[3] = k3[0];
tmp0 += 4;
k0++;
k1++;
k2++;
k3++;
}
for (int j = 0; j < 9; j++)
{
tmp1[0] = f0[0];
tmp1[1] = f1[0];
tmp1[2] = f2[0];
tmp1[3] = f3[0];
tmp1 += 4;
f0++;
f1++;
f2++;
f3++;
}
if (bias_data)
{
tmp2[0] = b0[0];
tmp2[1] = b1[0];
tmp2[2] = b2[0];
tmp2[3] = b3[0];
}
else
{
tmp2[0] = 0;
tmp2[1] = 0;
tmp2[2] = 0;
tmp2[3] = 0;
}
}
for (int i = 0; i < channel_remain; i++)
{
int ii = channel_count * 4 + i;
float* k0 = img_data + ii * inwh;
float* f0 = kernel_data + ii * 9;
float* b0 = bias_data + ii;
float* tmp0 = img_tmp + channel_count * 4 * inwh;
float* tmp1 = kernel_tmp + channel_count * 4 * 9;
float* tmp2 = bias_tmp + channel_count * 4;
for (int j = 0; j < inwh; j++)
{
tmp0[i] = k0[0];
tmp0 += 4;
k0++;
}
for (int j = 0; j < 9; j++)
{
tmp1[i] = f0[0];
tmp1 += 4;
f0++;
}
if (bias_data)
{
tmp2[i] = b0[0];
}
else
{
tmp2[i] = 0;
}
}
}
float* output_tmp = ( float* )sys_malloc(outwh * 4 * (channel_count + 1) * sizeof(float));
for (int c = 0; c < channel_count + 1; c++)
{
float* ktmp = kernel_tmp + c * 4 * 9;
float* btmp = bias_tmp + c * 4;
for (int i = 0; i < outh; i++)
{
int j = 0;
float* itmp0 = img_tmp + c * 4 * inwh + 4 * i * inw;
float* itmp1 = img_tmp + c * 4 * inwh + 4 * (i + 1) * inw;
float* itmp2 = img_tmp + c * 4 * inwh + 4 * (i + 2) * inw;
float* otmp = output_tmp + c * 4 * outwh + 4 * i * outw;
for (; j + 7 < outw; j += 8)
{
#if __SSE__
__m128 _sum0 = _mm_loadu_ps(btmp);
__m128 _sum1 = _mm_loadu_ps(btmp);
__m128 _sum2 = _mm_loadu_ps(btmp);
__m128 _sum3 = _mm_loadu_ps(btmp);
__m128 _sum4 = _mm_loadu_ps(btmp);
__m128 _sum5 = _mm_loadu_ps(btmp);
__m128 _sum6 = _mm_loadu_ps(btmp);
__m128 _sum7 = _mm_loadu_ps(btmp);
__m128 _va0 = _mm_loadu_ps(itmp0);
__m128 _va1 = _mm_loadu_ps(itmp0 + 4);
__m128 _va2 = _mm_loadu_ps(itmp0 + 8);
__m128 _va3 = _mm_loadu_ps(itmp0 + 12);
__m128 _va4 = _mm_loadu_ps(itmp0 + 16);
__m128 _va5 = _mm_loadu_ps(itmp0 + 20);
__m128 _va6 = _mm_loadu_ps(itmp0 + 24);
__m128 _va7 = _mm_loadu_ps(itmp0 + 28);
__m128 _va8 = _mm_loadu_ps(itmp0 + 32);
__m128 _va9 = _mm_loadu_ps(itmp0 + 36);
__m128 _vb0 = _mm_loadu_ps(ktmp);
__m128 _vb1 = _mm_loadu_ps(ktmp + 4);
__m128 _vb2 = _mm_loadu_ps(ktmp + 8);
_sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0);
_sum1 = _mm_add_ps(_mm_mul_ps(_va1, _vb0), _sum1);
_sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0);
_sum1 = _mm_add_ps(_mm_mul_ps(_va2, _vb1), _sum1);
_sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0);
_sum2 = _mm_add_ps(_mm_mul_ps(_va2, _vb0), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va3, _vb0), _sum3);
_sum1 = _mm_add_ps(_mm_mul_ps(_va3, _vb2), _sum1);
_sum2 = _mm_add_ps(_mm_mul_ps(_va3, _vb1), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va4, _vb1), _sum3);
_sum4 = _mm_add_ps(_mm_mul_ps(_va4, _vb0), _sum4);
_sum2 = _mm_add_ps(_mm_mul_ps(_va4, _vb2), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va5, _vb2), _sum3);
_sum5 = _mm_add_ps(_mm_mul_ps(_va5, _vb0), _sum5);
_sum4 = _mm_add_ps(_mm_mul_ps(_va5, _vb1), _sum4);
_sum5 = _mm_add_ps(_mm_mul_ps(_va6, _vb1), _sum5);
_sum4 = _mm_add_ps(_mm_mul_ps(_va6, _vb2), _sum4);
_sum6 = _mm_add_ps(_mm_mul_ps(_va6, _vb0), _sum6);
_sum7 = _mm_add_ps(_mm_mul_ps(_va7, _vb0), _sum7);
_sum5 = _mm_add_ps(_mm_mul_ps(_va7, _vb2), _sum5);
_sum6 = _mm_add_ps(_mm_mul_ps(_va7, _vb1), _sum6);
_sum7 = _mm_add_ps(_mm_mul_ps(_va8, _vb1), _sum7);
_sum6 = _mm_add_ps(_mm_mul_ps(_va8, _vb2), _sum6);
_sum7 = _mm_add_ps(_mm_mul_ps(_va9, _vb2), _sum7);
_va0 = _mm_loadu_ps(itmp1);
_va1 = _mm_loadu_ps(itmp1 + 4);
_va2 = _mm_loadu_ps(itmp1 + 8);
_va3 = _mm_loadu_ps(itmp1 + 12);
_va4 = _mm_loadu_ps(itmp1 + 16);
_va5 = _mm_loadu_ps(itmp1 + 20);
_va6 = _mm_loadu_ps(itmp1 + 24);
_va7 = _mm_loadu_ps(itmp1 + 28);
_va8 = _mm_loadu_ps(itmp1 + 32);
_va9 = _mm_loadu_ps(itmp1 + 36);
_vb0 = _mm_loadu_ps(ktmp + 12);
_vb1 = _mm_loadu_ps(ktmp + 16);
_vb2 = _mm_loadu_ps(ktmp + 20);
_sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0);
_sum1 = _mm_add_ps(_mm_mul_ps(_va1, _vb0), _sum1);
_sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0);
_sum1 = _mm_add_ps(_mm_mul_ps(_va2, _vb1), _sum1);
_sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0);
_sum2 = _mm_add_ps(_mm_mul_ps(_va2, _vb0), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va3, _vb0), _sum3);
_sum1 = _mm_add_ps(_mm_mul_ps(_va3, _vb2), _sum1);
_sum2 = _mm_add_ps(_mm_mul_ps(_va3, _vb1), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va4, _vb1), _sum3);
_sum4 = _mm_add_ps(_mm_mul_ps(_va4, _vb0), _sum4);
_sum2 = _mm_add_ps(_mm_mul_ps(_va4, _vb2), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va5, _vb2), _sum3);
_sum5 = _mm_add_ps(_mm_mul_ps(_va5, _vb0), _sum5);
_sum4 = _mm_add_ps(_mm_mul_ps(_va5, _vb1), _sum4);
_sum5 = _mm_add_ps(_mm_mul_ps(_va6, _vb1), _sum5);
_sum4 = _mm_add_ps(_mm_mul_ps(_va6, _vb2), _sum4);
_sum6 = _mm_add_ps(_mm_mul_ps(_va6, _vb0), _sum6);
_sum7 = _mm_add_ps(_mm_mul_ps(_va7, _vb0), _sum7);
_sum5 = _mm_add_ps(_mm_mul_ps(_va7, _vb2), _sum5);
_sum6 = _mm_add_ps(_mm_mul_ps(_va7, _vb1), _sum6);
_sum7 = _mm_add_ps(_mm_mul_ps(_va8, _vb1), _sum7);
_sum6 = _mm_add_ps(_mm_mul_ps(_va8, _vb2), _sum6);
_sum7 = _mm_add_ps(_mm_mul_ps(_va9, _vb2), _sum7);
_va0 = _mm_loadu_ps(itmp2);
_va1 = _mm_loadu_ps(itmp2 + 4);
_va2 = _mm_loadu_ps(itmp2 + 8);
_va3 = _mm_loadu_ps(itmp2 + 12);
_va4 = _mm_loadu_ps(itmp2 + 16);
_va5 = _mm_loadu_ps(itmp2 + 20);
_va6 = _mm_loadu_ps(itmp2 + 24);
_va7 = _mm_loadu_ps(itmp2 + 28);
_va8 = _mm_loadu_ps(itmp2 + 32);
_va9 = _mm_loadu_ps(itmp2 + 36);
_vb0 = _mm_loadu_ps(ktmp + 24);
_vb1 = _mm_loadu_ps(ktmp + 28);
_vb2 = _mm_loadu_ps(ktmp + 32);
_sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0);
_sum1 = _mm_add_ps(_mm_mul_ps(_va1, _vb0), _sum1);
_sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0);
_sum1 = _mm_add_ps(_mm_mul_ps(_va2, _vb1), _sum1);
_sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0);
_sum2 = _mm_add_ps(_mm_mul_ps(_va2, _vb0), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va3, _vb0), _sum3);
_sum1 = _mm_add_ps(_mm_mul_ps(_va3, _vb2), _sum1);
_sum2 = _mm_add_ps(_mm_mul_ps(_va3, _vb1), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va4, _vb1), _sum3);
_sum4 = _mm_add_ps(_mm_mul_ps(_va4, _vb0), _sum4);
_sum2 = _mm_add_ps(_mm_mul_ps(_va4, _vb2), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va5, _vb2), _sum3);
_sum5 = _mm_add_ps(_mm_mul_ps(_va5, _vb0), _sum5);
_sum4 = _mm_add_ps(_mm_mul_ps(_va5, _vb1), _sum4);
_sum5 = _mm_add_ps(_mm_mul_ps(_va6, _vb1), _sum5);
_sum4 = _mm_add_ps(_mm_mul_ps(_va6, _vb2), _sum4);
_sum6 = _mm_add_ps(_mm_mul_ps(_va6, _vb0), _sum6);
_sum7 = _mm_add_ps(_mm_mul_ps(_va7, _vb0), _sum7);
_sum5 = _mm_add_ps(_mm_mul_ps(_va7, _vb2), _sum5);
_sum6 = _mm_add_ps(_mm_mul_ps(_va7, _vb1), _sum6);
_sum7 = _mm_add_ps(_mm_mul_ps(_va8, _vb1), _sum7);
_sum6 = _mm_add_ps(_mm_mul_ps(_va8, _vb2), _sum6);
_sum7 = _mm_add_ps(_mm_mul_ps(_va9, _vb2), _sum7);
_mm_storeu_ps(otmp, _sum0);
_mm_storeu_ps(otmp + 4, _sum1);
_mm_storeu_ps(otmp + 8, _sum2);
_mm_storeu_ps(otmp + 12, _sum3);
_mm_storeu_ps(otmp + 16, _sum4);
_mm_storeu_ps(otmp + 20, _sum5);
_mm_storeu_ps(otmp + 24, _sum6);
_mm_storeu_ps(otmp + 28, _sum7);
#else
float sum0[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
float sum1[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
float sum2[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
float sum3[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
float sum4[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
float sum5[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
float sum6[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
float sum7[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
for (int k = 0; k < 4; k++)
{
sum0[k] += itmp0[k] * ktmp[k];
sum0[k] += itmp1[k] * ktmp[k + 12];
sum0[k] += itmp2[k] * ktmp[k + 24];
sum0[k] += itmp0[k + 4] * ktmp[k + 4];
sum0[k] += itmp1[k + 4] * ktmp[k + 16];
sum0[k] += itmp2[k + 4] * ktmp[k + 28];
sum0[k] += itmp0[k + 8] * ktmp[k + 8];
sum0[k] += itmp1[k + 8] * ktmp[k + 20];
sum0[k] += itmp2[k + 8] * ktmp[k + 32];
sum1[k] += itmp0[k + 4] * ktmp[k];
sum1[k] += itmp1[k + 4] * ktmp[k + 12];
sum1[k] += itmp2[k + 4] * ktmp[k + 24];
sum1[k] += itmp0[k + 8] * ktmp[k + 4];
sum1[k] += itmp1[k + 8] * ktmp[k + 16];
sum1[k] += itmp2[k + 8] * ktmp[k + 28];
sum1[k] += itmp0[k + 12] * ktmp[k + 8];
sum1[k] += itmp1[k + 12] * ktmp[k + 20];
sum1[k] += itmp2[k + 12] * ktmp[k + 32];
sum2[k] += itmp0[k + 8] * ktmp[k];
sum2[k] += itmp1[k + 8] * ktmp[k + 12];
sum2[k] += itmp2[k + 8] * ktmp[k + 24];
sum2[k] += itmp0[k + 12] * ktmp[k + 4];
sum2[k] += itmp1[k + 12] * ktmp[k + 16];
sum2[k] += itmp2[k + 12] * ktmp[k + 28];
sum2[k] += itmp0[k + 16] * ktmp[k + 8];
sum2[k] += itmp1[k + 16] * ktmp[k + 20];
sum2[k] += itmp2[k + 16] * ktmp[k + 32];
sum3[k] += itmp0[k + 12] * ktmp[k];
sum3[k] += itmp1[k + 12] * ktmp[k + 12];
sum3[k] += itmp2[k + 12] * ktmp[k + 24];
sum3[k] += itmp0[k + 16] * ktmp[k + 4];
sum3[k] += itmp1[k + 16] * ktmp[k + 16];
sum3[k] += itmp2[k + 16] * ktmp[k + 28];
sum3[k] += itmp0[k + 20] * ktmp[k + 8];
sum3[k] += itmp1[k + 20] * ktmp[k + 20];
sum3[k] += itmp2[k + 20] * ktmp[k + 32];
sum4[k] += itmp0[k + 16] * ktmp[k];
sum4[k] += itmp1[k + 16] * ktmp[k + 12];
sum4[k] += itmp2[k + 16] * ktmp[k + 24];
sum4[k] += itmp0[k + 20] * ktmp[k + 4];
sum4[k] += itmp1[k + 20] * ktmp[k + 16];
sum4[k] += itmp2[k + 20] * ktmp[k + 28];
sum4[k] += itmp0[k + 24] * ktmp[k + 8];
sum4[k] += itmp1[k + 24] * ktmp[k + 20];
sum4[k] += itmp2[k + 24] * ktmp[k + 32];
sum5[k] += itmp0[k + 20] * ktmp[k];
sum5[k] += itmp1[k + 20] * ktmp[k + 12];
sum5[k] += itmp2[k + 20] * ktmp[k + 24];
sum5[k] += itmp0[k + 24] * ktmp[k + 4];
sum5[k] += itmp1[k + 24] * ktmp[k + 16];
sum5[k] += itmp2[k + 24] * ktmp[k + 28];
sum5[k] += itmp0[k + 28] * ktmp[k + 8];
sum5[k] += itmp1[k + 28] * ktmp[k + 20];
sum5[k] += itmp2[k + 28] * ktmp[k + 32];
sum6[k] += itmp0[k + 24] * ktmp[k];
sum6[k] += itmp1[k + 24] * ktmp[k + 12];
sum6[k] += itmp2[k + 24] * ktmp[k + 24];
sum6[k] += itmp0[k + 28] * ktmp[k + 4];
sum6[k] += itmp1[k + 28] * ktmp[k + 16];
sum6[k] += itmp2[k + 28] * ktmp[k + 28];
sum6[k] += itmp0[k + 32] * ktmp[k + 8];
sum6[k] += itmp1[k + 32] * ktmp[k + 20];
sum6[k] += itmp2[k + 32] * ktmp[k + 32];
sum7[k] += itmp0[k + 28] * ktmp[k];
sum7[k] += itmp1[k + 28] * ktmp[k + 12];
sum7[k] += itmp2[k + 28] * ktmp[k + 24];
sum7[k] += itmp0[k + 32] * ktmp[k + 4];
sum7[k] += itmp1[k + 32] * ktmp[k + 16];
sum7[k] += itmp2[k + 32] * ktmp[k + 28];
sum7[k] += itmp0[k + 36] * ktmp[k + 8];
sum7[k] += itmp1[k + 36] * ktmp[k + 20];
sum7[k] += itmp2[k + 36] * ktmp[k + 32];
}
for (int k = 0; k < 4; k++)
{
otmp[k] = sum0[k];
otmp[k + 4] = sum1[k];
otmp[k + 8] = sum2[k];
otmp[k + 12] = sum3[k];
otmp[k + 16] = sum4[k];
otmp[k + 20] = sum5[k];
otmp[k + 24] = sum6[k];
otmp[k + 28] = sum7[k];
}
#endif
itmp0 += 32;
itmp1 += 32;
itmp2 += 32;
otmp += 32;
}
for (; j + 3 < outw; j += 4)
{
#if __SSE__
__m128 _sum0 = _mm_loadu_ps(btmp);
__m128 _sum1 = _mm_loadu_ps(btmp);
__m128 _sum2 = _mm_loadu_ps(btmp);
__m128 _sum3 = _mm_loadu_ps(btmp);
__m128 _va0 = _mm_loadu_ps(itmp0);
__m128 _va1 = _mm_loadu_ps(itmp0 + 4);
__m128 _va2 = _mm_loadu_ps(itmp0 + 8);
__m128 _va3 = _mm_loadu_ps(itmp0 + 12);
__m128 _va4 = _mm_loadu_ps(itmp0 + 16);
__m128 _va5 = _mm_loadu_ps(itmp0 + 20);
__m128 _vb0 = _mm_loadu_ps(ktmp);
__m128 _vb1 = _mm_loadu_ps(ktmp + 4);
__m128 _vb2 = _mm_loadu_ps(ktmp + 8);
_sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0);
_sum1 = _mm_add_ps(_mm_mul_ps(_va1, _vb0), _sum1);
_sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0);
_sum1 = _mm_add_ps(_mm_mul_ps(_va2, _vb1), _sum1);
_sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0);
_sum2 = _mm_add_ps(_mm_mul_ps(_va2, _vb0), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va3, _vb0), _sum3);
_sum1 = _mm_add_ps(_mm_mul_ps(_va3, _vb2), _sum1);
_sum2 = _mm_add_ps(_mm_mul_ps(_va3, _vb1), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va4, _vb1), _sum3);
_sum2 = _mm_add_ps(_mm_mul_ps(_va4, _vb2), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va5, _vb2), _sum3);
_va0 = _mm_loadu_ps(itmp1);
_va1 = _mm_loadu_ps(itmp1 + 4);
_va2 = _mm_loadu_ps(itmp1 + 8);
_va3 = _mm_loadu_ps(itmp1 + 12);
_va4 = _mm_loadu_ps(itmp1 + 16);
_va5 = _mm_loadu_ps(itmp1 + 20);
_vb0 = _mm_loadu_ps(ktmp + 12);
_vb1 = _mm_loadu_ps(ktmp + 16);
_vb2 = _mm_loadu_ps(ktmp + 20);
_sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0);
_sum1 = _mm_add_ps(_mm_mul_ps(_va1, _vb0), _sum1);
_sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0);
_sum1 = _mm_add_ps(_mm_mul_ps(_va2, _vb1), _sum1);
_sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0);
_sum2 = _mm_add_ps(_mm_mul_ps(_va2, _vb0), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va3, _vb0), _sum3);
_sum1 = _mm_add_ps(_mm_mul_ps(_va3, _vb2), _sum1);
_sum2 = _mm_add_ps(_mm_mul_ps(_va3, _vb1), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va4, _vb1), _sum3);
_sum2 = _mm_add_ps(_mm_mul_ps(_va4, _vb2), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va5, _vb2), _sum3);
_va0 = _mm_loadu_ps(itmp2);
_va1 = _mm_loadu_ps(itmp2 + 4);
_va2 = _mm_loadu_ps(itmp2 + 8);
_va3 = _mm_loadu_ps(itmp2 + 12);
_va4 = _mm_loadu_ps(itmp2 + 16);
_va5 = _mm_loadu_ps(itmp2 + 20);
_vb0 = _mm_loadu_ps(ktmp + 24);
_vb1 = _mm_loadu_ps(ktmp + 28);
_vb2 = _mm_loadu_ps(ktmp + 32);
_sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0);
_sum1 = _mm_add_ps(_mm_mul_ps(_va1, _vb0), _sum1);
_sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0);
_sum1 = _mm_add_ps(_mm_mul_ps(_va2, _vb1), _sum1);
_sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0);
_sum2 = _mm_add_ps(_mm_mul_ps(_va2, _vb0), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va3, _vb0), _sum3);
_sum1 = _mm_add_ps(_mm_mul_ps(_va3, _vb2), _sum1);
_sum2 = _mm_add_ps(_mm_mul_ps(_va3, _vb1), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va4, _vb1), _sum3);
_sum2 = _mm_add_ps(_mm_mul_ps(_va4, _vb2), _sum2);
_sum3 = _mm_add_ps(_mm_mul_ps(_va5, _vb2), _sum3);
_mm_storeu_ps(otmp, _sum0);
_mm_storeu_ps(otmp + 4, _sum1);
_mm_storeu_ps(otmp + 8, _sum2);
_mm_storeu_ps(otmp + 12, _sum3);
#else
float sum0[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
float sum1[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
float sum2[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
float sum3[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
for (int k = 0; k < 4; k++)
{
sum0[k] += itmp0[k] * ktmp[k];
sum0[k] += itmp1[k] * ktmp[k + 12];
sum0[k] += itmp2[k] * ktmp[k + 24];
sum0[k] += itmp0[k + 4] * ktmp[k + 4];
sum0[k] += itmp1[k + 4] * ktmp[k + 16];
sum0[k] += itmp2[k + 4] * ktmp[k + 28];
sum0[k] += itmp0[k + 8] * ktmp[k + 8];
sum0[k] += itmp1[k + 8] * ktmp[k + 20];
sum0[k] += itmp2[k + 8] * ktmp[k + 32];
sum1[k] += itmp0[k + 4] * ktmp[k];
sum1[k] += itmp1[k + 4] * ktmp[k + 12];
sum1[k] += itmp2[k + 4] * ktmp[k + 24];
sum1[k] += itmp0[k + 8] * ktmp[k + 4];
sum1[k] += itmp1[k + 8] * ktmp[k + 16];
sum1[k] += itmp2[k + 8] * ktmp[k + 28];
sum1[k] += itmp0[k + 12] * ktmp[k + 8];
sum1[k] += itmp1[k + 12] * ktmp[k + 20];
sum1[k] += itmp2[k + 12] * ktmp[k + 32];
sum2[k] += itmp0[k + 8] * ktmp[k];
sum2[k] += itmp1[k + 8] * ktmp[k + 12];
sum2[k] += itmp2[k + 8] * ktmp[k + 24];
sum2[k] += itmp0[k + 12] * ktmp[k + 4];
sum2[k] += itmp1[k + 12] * ktmp[k + 16];
sum2[k] += itmp2[k + 12] * ktmp[k + 28];
sum2[k] += itmp0[k + 16] * ktmp[k + 8];
sum2[k] += itmp1[k + 16] * ktmp[k + 20];
sum2[k] += itmp2[k + 16] * ktmp[k + 32];
sum3[k] += itmp0[k + 12] * ktmp[k];
sum3[k] += itmp1[k + 12] * ktmp[k + 12];
sum3[k] += itmp2[k + 12] * ktmp[k + 24];
sum3[k] += itmp0[k + 16] * ktmp[k + 4];
sum3[k] += itmp1[k + 16] * ktmp[k + 16];
sum3[k] += itmp2[k + 16] * ktmp[k + 28];
sum3[k] += itmp0[k + 20] * ktmp[k + 8];
sum3[k] += itmp1[k + 20] * ktmp[k + 20];
sum3[k] += itmp2[k + 20] * ktmp[k + 32];
}
for (int k = 0; k < 4; k++)
{
otmp[k] = sum0[k];
otmp[k + 4] = sum1[k];
otmp[k + 8] = sum2[k];
otmp[k + 12] = sum3[k];
}
#endif
itmp0 += 16;
itmp1 += 16;
itmp2 += 16;
otmp += 16;
}
for (; j < outw; j++)
{
#if __SSE__
__m128 _sum0 = _mm_loadu_ps(btmp);
__m128 _va0 = _mm_loadu_ps(itmp0);
__m128 _va1 = _mm_loadu_ps(itmp0 + 4);
__m128 _va2 = _mm_loadu_ps(itmp0 + 8);
__m128 _vb0 = _mm_loadu_ps(ktmp);
__m128 _vb1 = _mm_loadu_ps(ktmp + 4);
__m128 _vb2 = _mm_loadu_ps(ktmp + 8);
_sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0);
_sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0);
_sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0);
_va0 = _mm_loadu_ps(itmp1);
_va1 = _mm_loadu_ps(itmp1 + 4);
_va2 = _mm_loadu_ps(itmp1 + 8);
_vb0 = _mm_loadu_ps(ktmp + 12);
_vb1 = _mm_loadu_ps(ktmp + 16);
_vb2 = _mm_loadu_ps(ktmp + 20);
_sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0);
_sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0);
_sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0);
_va0 = _mm_loadu_ps(itmp2);
_va1 = _mm_loadu_ps(itmp2 + 4);
_va2 = _mm_loadu_ps(itmp2 + 8);
_vb0 = _mm_loadu_ps(ktmp + 24);
_vb1 = _mm_loadu_ps(ktmp + 28);
_vb2 = _mm_loadu_ps(ktmp + 32);
_sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0);
_sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0);
_sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0);
_mm_storeu_ps(otmp, _sum0);
#else
float sum0[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
for (int k = 0; k < 4; k++)
{
sum0[k] += itmp0[k] * ktmp[k];
sum0[k] += itmp1[k] * ktmp[k + 12];
sum0[k] += itmp2[k] * ktmp[k + 24];
sum0[k] += itmp0[k + 4] * ktmp[k + 4];
sum0[k] += itmp1[k + 4] * ktmp[k + 16];
sum0[k] += itmp2[k + 4] * ktmp[k + 28];
sum0[k] += itmp0[k + 8] * ktmp[k + 8];
sum0[k] += itmp1[k + 8] * ktmp[k + 20];
sum0[k] += itmp2[k + 8] * ktmp[k + 32];
}
for (int k = 0; k < 4; k++)
{
otmp[k] = sum0[k];
}
#endif
itmp0 += 4;
itmp1 += 4;
itmp2 += 4;
otmp += 4;
}
}
}
{
for (int i = 0; i < channel_count; i++)
{
float* otmp = output_tmp + i * 4 * outwh;
float* tmp0 = output + i * 4 * outwh;
float* tmp1 = output + i * 4 * outwh + 1 * outwh;
float* tmp2 = output + i * 4 * outwh + 2 * outwh;
float* tmp3 = output + i * 4 * outwh + 3 * outwh;
for (int i = 0; i < outwh; i++)
{
tmp0[0] = otmp[0];
tmp1[0] = otmp[1];
tmp2[0] = otmp[2];
tmp3[0] = otmp[3];
otmp += 4;
tmp0++;
tmp1++;
tmp2++;
tmp3++;
}
}
for (int i = 0; i < channel_remain; i++)
{
int ii = channel_count * 4 + i;
float* otmp = output_tmp + channel_count * 4 * outwh;
float* tmp0 = output + ii * outwh;
for (int j = 0; j < outwh; j++)
{
tmp0[0] = otmp[i];
otmp += 4;
tmp0++;
}
}
}
sys_free(output_tmp);
sys_free(img_tmp);
sys_free(kernel_tmp);
sys_free(bias_tmp);
}
static void convdw3x3s2(float* output, float* img_data, float* kernel_data, float* bias_data, int inc, int inh, int inw,
int outh, int outw, int num_thread)
{
int inwh = inw * inh;
int outwh = outw * outh;
int channel_count = inc >> 2;
int channel_remain = inc - (channel_count << 2);
// generate the image tmp
float* img_tmp = ( float* )sys_malloc(4 * inwh * (channel_count + 1) * sizeof(float));
float* kernel_tmp = ( float* )sys_malloc(4 * 9 * (channel_count + 1) * sizeof(float));
float* bias_tmp = ( float* )sys_malloc(4 * (channel_count + 1) * sizeof(float));
{
for (int i = 0; i < channel_count; i++)
{
int ii = i * 4;
float* k0 = img_data + (ii + 0) * inwh;
float* k1 = img_data + (ii + 1) * inwh;
float* k2 = img_data + (ii + 2) * inwh;
float* k3 = img_data + (ii + 3) * inwh;
float* f0 = kernel_data + (ii + 0) * 9;
float* f1 = kernel_data + (ii + 1) * 9;
float* f2 = kernel_data + (ii + 2) * 9;
float* f3 = kernel_data + (ii + 3) * 9;
float* b0 = bias_data + (ii + 0);
float* b1 = bias_data + (ii + 1);
float* b2 = bias_data + (ii + 2);
float* b3 = bias_data + (ii + 3);
float* tmp0 = img_tmp + ii * inwh;
float* tmp1 = kernel_tmp + ii * 9;
float* tmp2 = bias_tmp + ii;
for (int j = 0; j < inwh; j++)
{
tmp0[0] = k0[0];
tmp0[1] = k1[0];
tmp0[2] = k2[0];
tmp0[3] = k3[0];
tmp0 += 4;
k0++;
k1++;
k2++;
k3++;
}
for (int j = 0; j < 9; j++)
{
tmp1[0] = f0[0];
tmp1[1] = f1[0];
tmp1[2] = f2[0];
tmp1[3] = f3[0];
tmp1 += 4;
f0++;
f1++;
f2++;
f3++;
}
if (bias_data)
{
tmp2[0] = b0[0];
tmp2[1] = b1[0];
tmp2[2] = b2[0];
tmp2[3] = b3[0];
}
else
{
tmp2[0] = 0;
tmp2[1] = 0;
tmp2[2] = 0;
tmp2[3] = 0;
}
}
for (int i = 0; i < channel_remain; i++)
{
int ii = channel_count * 4 + i;
float* k0 = img_data + ii * inwh;
float* f0 = kernel_data + ii * 9;
float* b0 = bias_data + ii;
float* tmp0 = img_tmp + channel_count * 4 * inwh;
float* tmp1 = kernel_tmp + channel_count * 4 * 9;
float* tmp2 = bias_tmp + channel_count * 4;
for (int j = 0; j < inwh; j++)
{
tmp0[i] = k0[0];
tmp0 += 4;
k0++;
}
for (int j = 0; j < 9; j++)
{
tmp1[i] = f0[0];
tmp1 += 4;
f0++;
}
if (bias_data)
{
tmp2[i] = b0[0];
}
else
{
tmp2[i] = 0;
}
}
}
float* output_tmp = ( float* )sys_malloc(outwh * 4 * (channel_count + 1) * sizeof(float));
for (int c = 0; c < channel_count + 1; c++)
{
float* ktmp = kernel_tmp + c * 4 * 9;
float* btmp = bias_tmp + c * 4;
for (int i = 0; i < outh; i++)
{
int j = 0;
float* itmp0 = img_tmp + c * 4 * inwh + 4 * i * 2 * inw;
float* itmp1 = img_tmp + c * 4 * inwh + 4 * (i * 2 + 1) * inw;
float* itmp2 = img_tmp + c * 4 * inwh + 4 * (i * 2 + 2) * inw;
float* otmp = output_tmp + c * 4 * outwh + 4 * i * outw;
for (; j + 3 < outw; j += 4)
{
#if __SSE__
__m128 _sum0 = _mm_loadu_ps(btmp);
__m128 _sum1 = _mm_loadu_ps(btmp);
__m128 _sum2 = _mm_loadu_ps(btmp);
__m128 _sum3 = _mm_loadu_ps(btmp);
__m128 _va0 = _mm_loadu_ps(itmp0);
__m128 _va1 = _mm_loadu_ps(itmp0 + 4);
__m128 _va2 = _mm_loadu_ps(itmp0 + 8);
__m128 _va3 = _mm_loadu_ps(itmp0 + 12);
__m128 _va4 = _mm_loadu_ps(itmp0 + 16);
__m128 _va5 = _mm_loadu_ps(itmp0 + 20);
__m128 _va6 = _mm_loadu_ps(itmp0 + 24);
__m128 _va7 = _mm_loadu_ps(itmp0 + 28);
__m128 _va8 = _mm_loadu_ps(itmp0 + 32);
__m128 _vb0 = _mm_loadu_ps(ktmp);
__m128 _vb1 = _mm_loadu_ps(ktmp + 4);
__m128 _vb2 = _mm_loadu_ps(ktmp + 8);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va0, _vb0));
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va1, _vb1));
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va2, _vb2));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va2, _vb0));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va3, _vb1));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va4, _vb2));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va4, _vb0));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va5, _vb1));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va6, _vb2));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va6, _vb0));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va7, _vb1));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va8, _vb2));
_va0 = _mm_loadu_ps(itmp1);
_va1 = _mm_loadu_ps(itmp1 + 4);
_va2 = _mm_loadu_ps(itmp1 + 8);
_va3 = _mm_loadu_ps(itmp1 + 12);
_va4 = _mm_loadu_ps(itmp1 + 16);
_va5 = _mm_loadu_ps(itmp1 + 20);
_va6 = _mm_loadu_ps(itmp1 + 24);
_va7 = _mm_loadu_ps(itmp1 + 28);
_va8 = _mm_loadu_ps(itmp1 + 32);
_vb0 = _mm_loadu_ps(ktmp + 12);
_vb1 = _mm_loadu_ps(ktmp + 16);
_vb2 = _mm_loadu_ps(ktmp + 20);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va0, _vb0));
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va1, _vb1));
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va2, _vb2));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va2, _vb0));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va3, _vb1));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va4, _vb2));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va4, _vb0));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va5, _vb1));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va6, _vb2));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va6, _vb0));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va7, _vb1));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va8, _vb2));
_va0 = _mm_loadu_ps(itmp2);
_va1 = _mm_loadu_ps(itmp2 + 4);
_va2 = _mm_loadu_ps(itmp2 + 8);
_va3 = _mm_loadu_ps(itmp2 + 12);
_va4 = _mm_loadu_ps(itmp2 + 16);
_va5 = _mm_loadu_ps(itmp2 + 20);
_va6 = _mm_loadu_ps(itmp2 + 24);
_va7 = _mm_loadu_ps(itmp2 + 28);
_va8 = _mm_loadu_ps(itmp2 + 32);
_vb0 = _mm_loadu_ps(ktmp + 24);
_vb1 = _mm_loadu_ps(ktmp + 28);
_vb2 = _mm_loadu_ps(ktmp + 32);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va0, _vb0));
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va1, _vb1));
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va2, _vb2));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va2, _vb0));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va3, _vb1));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va4, _vb2));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va4, _vb0));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va5, _vb1));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va6, _vb2));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va6, _vb0));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va7, _vb1));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va8, _vb2));
_mm_storeu_ps(otmp, _sum0);
_mm_storeu_ps(otmp + 4, _sum1);
_mm_storeu_ps(otmp + 8, _sum2);
_mm_storeu_ps(otmp + 12, _sum3);
#else
float sum0[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
float sum1[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
float sum2[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
float sum3[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
for (int k = 0; k < 4; k++)
{
sum0[k] += itmp0[k] * ktmp[k];
sum0[k] += itmp1[k] * ktmp[k + 12];
sum0[k] += itmp2[k] * ktmp[k + 24];
sum0[k] += itmp0[k + 4] * ktmp[k + 4];
sum0[k] += itmp1[k + 4] * ktmp[k + 16];
sum0[k] += itmp2[k + 4] * ktmp[k + 28];
sum0[k] += itmp0[k + 8] * ktmp[k + 8];
sum0[k] += itmp1[k + 8] * ktmp[k + 20];
sum0[k] += itmp2[k + 8] * ktmp[k + 32];
sum1[k] += itmp0[k + 8] * ktmp[k];
sum1[k] += itmp1[k + 8] * ktmp[k + 12];
sum1[k] += itmp2[k + 8] * ktmp[k + 24];
sum1[k] += itmp0[k + 12] * ktmp[k + 4];
sum1[k] += itmp1[k + 12] * ktmp[k + 16];
sum1[k] += itmp2[k + 12] * ktmp[k + 28];
sum1[k] += itmp0[k + 16] * ktmp[k + 8];
sum1[k] += itmp1[k + 16] * ktmp[k + 20];
sum1[k] += itmp2[k + 16] * ktmp[k + 32];
sum2[k] += itmp0[k + 16] * ktmp[k];
sum2[k] += itmp1[k + 16] * ktmp[k + 12];
sum2[k] += itmp2[k + 16] * ktmp[k + 24];
sum2[k] += itmp0[k + 20] * ktmp[k + 4];
sum2[k] += itmp1[k + 20] * ktmp[k + 16];
sum2[k] += itmp2[k + 20] * ktmp[k + 28];
sum2[k] += itmp0[k + 24] * ktmp[k + 8];
sum2[k] += itmp1[k + 24] * ktmp[k + 20];
sum2[k] += itmp2[k + 24] * ktmp[k + 32];
sum3[k] += itmp0[k + 24] * ktmp[k];
sum3[k] += itmp1[k + 24] * ktmp[k + 12];
sum3[k] += itmp2[k + 24] * ktmp[k + 24];
sum3[k] += itmp0[k + 28] * ktmp[k + 4];
sum3[k] += itmp1[k + 28] * ktmp[k + 16];
sum3[k] += itmp2[k + 28] * ktmp[k + 28];
sum3[k] += itmp0[k + 32] * ktmp[k + 8];
sum3[k] += itmp1[k + 32] * ktmp[k + 20];
sum3[k] += itmp2[k + 32] * ktmp[k + 32];
}
for (int k = 0; k < 4; k++)
{
otmp[k] = sum0[k];
otmp[k + 4] = sum1[k];
otmp[k + 8] = sum2[k];
otmp[k + 12] = sum3[k];
}
#endif
itmp0 += 32;
itmp1 += 32;
itmp2 += 32;
otmp += 16;
}
for (; j < outw; j++)
{
#if __SSE__
__m128 _sum0 = _mm_loadu_ps(btmp);
__m128 _va0 = _mm_loadu_ps(itmp0);
__m128 _va1 = _mm_loadu_ps(itmp0 + 4);
__m128 _va2 = _mm_loadu_ps(itmp0 + 8);
__m128 _vb0 = _mm_loadu_ps(ktmp);
__m128 _vb1 = _mm_loadu_ps(ktmp + 4);
__m128 _vb2 = _mm_loadu_ps(ktmp + 8);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va0, _vb0));
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va1, _vb1));
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va2, _vb2));
_va0 = _mm_loadu_ps(itmp1);
_va1 = _mm_loadu_ps(itmp1 + 4);
_va2 = _mm_loadu_ps(itmp1 + 8);
_vb0 = _mm_loadu_ps(ktmp + 12);
_vb1 = _mm_loadu_ps(ktmp + 16);
_vb2 = _mm_loadu_ps(ktmp + 20);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va0, _vb0));
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va1, _vb1));
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va2, _vb2));
_va0 = _mm_loadu_ps(itmp2);
_va1 = _mm_loadu_ps(itmp2 + 4);
_va2 = _mm_loadu_ps(itmp2 + 8);
_vb0 = _mm_loadu_ps(ktmp + 24);
_vb1 = _mm_loadu_ps(ktmp + 28);
_vb2 = _mm_loadu_ps(ktmp + 32);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va0, _vb0));
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va1, _vb1));
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va2, _vb2));
_mm_storeu_ps(otmp, _sum0);
#else
float sum0[4] = {btmp[0], btmp[1], btmp[2], btmp[3]};
for (int k = 0; k < 4; k++)
{
sum0[k] += itmp0[k] * ktmp[k];
sum0[k] += itmp1[k] * ktmp[k + 12];
sum0[k] += itmp2[k] * ktmp[k + 24];
sum0[k] += itmp0[k + 4] * ktmp[k + 4];
sum0[k] += itmp1[k + 4] * ktmp[k + 16];
sum0[k] += itmp2[k + 4] * ktmp[k + 28];
sum0[k] += itmp0[k + 8] * ktmp[k + 8];
sum0[k] += itmp1[k + 8] * ktmp[k + 20];
sum0[k] += itmp2[k + 8] * ktmp[k + 32];
}
for (int k = 0; k < 4; k++)
{
otmp[k] = sum0[k];
}
#endif
itmp0 += 8;
itmp1 += 8;
itmp2 += 8;
otmp += 4;
}
}
}
{
for (int i = 0; i < channel_count; i++)
{
float* otmp = output_tmp + i * 4 * outwh;
float* tmp0 = output + i * 4 * outwh;
float* tmp1 = output + i * 4 * outwh + 1 * outwh;
float* tmp2 = output + i * 4 * outwh + 2 * outwh;
float* tmp3 = output + i * 4 * outwh + 3 * outwh;
for (int i = 0; i < outwh; i++)
{
tmp0[0] = otmp[0];
tmp1[0] = otmp[1];
tmp2[0] = otmp[2];
tmp3[0] = otmp[3];
otmp += 4;
tmp0++;
tmp1++;
tmp2++;
tmp3++;
}
}
for (int i = 0; i < channel_remain; i++)
{
int ii = channel_count * 4 + i;
float* otmp = output_tmp + channel_count * 4 * outwh;
float* tmp0 = output + ii * outwh;
for (int j = 0; j < outwh; j++)
{
tmp0[0] = otmp[i];
otmp += 4;
tmp0++;
}
}
}
sys_free(output_tmp);
sys_free(img_tmp);
sys_free(kernel_tmp);
sys_free(bias_tmp);
}
#else
static void convdw3x3s1(float* output, float* input, float* _kernel, float* _bias, int channel, int in_h, int in_w,
int out_h, int out_w, int num_thread)
{
int w = in_w;
int h = in_h;
int c_step_in = w * h;
int outw = out_w;
int outh = out_h;
int c_step_out = outw * outh;
const int group = channel;
const float* kernel = _kernel;
#pragma omp parallel for num_threads(num_thread)
for (int g = 0; g < group; g++)
{
float* out = output + g * c_step_out;
float* outptr = out;
float* outptr2 = outptr + outw;
const float bias0 = _bias ? _bias[g] : 0.f;
const float* kernel0 = kernel + g * 9;
const float* img0 = input + g * c_step_in;
const float* r0 = img0;
const float* r1 = img0 + w;
const float* r2 = img0 + w * 2;
const float* r3 = img0 + w * 3;
const float* k0 = kernel0;
const float* k1 = kernel0 + 3;
const float* k2 = kernel0 + 6;
int i = 0;
for (; i + 1 < outh; i += 2)
{
int remain = outw;
for (; remain > 0; remain--)
{
float sum = bias0;
sum += r0[0] * k0[0];
sum += r0[1] * k0[1];
sum += r0[2] * k0[2];
sum += r1[0] * k1[0];
sum += r1[1] * k1[1];
sum += r1[2] * k1[2];
sum += r2[0] * k2[0];
sum += r2[1] * k2[1];
sum += r2[2] * k2[2];
float sum2 = bias0;
sum2 += r1[0] * k0[0];
sum2 += r1[1] * k0[1];
sum2 += r1[2] * k0[2];
sum2 += r2[0] * k1[0];
sum2 += r2[1] * k1[1];
sum2 += r2[2] * k1[2];
sum2 += r3[0] * k2[0];
sum2 += r3[1] * k2[1];
sum2 += r3[2] * k2[2];
*outptr = sum;
*outptr2 = sum2;
r0++;
r1++;
r2++;
r3++;
outptr++;
outptr2++;
}
r0 += 2 + w;
r1 += 2 + w;
r2 += 2 + w;
r3 += 2 + w;
outptr += outw;
outptr2 += outw;
}
for (; i < outh; i++)
{
int remain = outw;
for (; remain > 0; remain--)
{
float sum = bias0;
sum += r0[0] * k0[0];
sum += r0[1] * k0[1];
sum += r0[2] * k0[2];
sum += r1[0] * k1[0];
sum += r1[1] * k1[1];
sum += r1[2] * k1[2];
sum += r2[0] * k2[0];
sum += r2[1] * k2[1];
sum += r2[2] * k2[2];
*outptr = sum;
r0++;
r1++;
r2++;
outptr++;
}
r0 += 2;
r1 += 2;
r2 += 2;
}
}
}
static void convdw3x3s2(float* output, float* input, float* _kernel, float* _bias, int channel, int in_h, int in_w,
int out_h, int out_w, int num_thread)
{
int w = in_w;
int h = in_h;
int c_step_in = w * h;
int outw = out_w;
int outh = out_h;
int c_step_out = outw * outh;
const int group = channel;
const int tailstep = w - 2 * outw + w;
const float* kernel = _kernel;
#pragma omp parallel for num_threads(num_thread)
for (int g = 0; g < group; g++)
{
float* out = output + g * c_step_out;
float* outptr = out;
const float* kernel0 = kernel + g * 9;
const float bias0 = _bias ? _bias[g] : 0.f;
const float* img0 = input + g * c_step_in;
const float* r0 = img0;
const float* r1 = img0 + w;
const float* r2 = img0 + w * 2;
const float* k0 = kernel0;
const float* k1 = kernel0 + 3;
const float* k2 = kernel0 + 6;
int i = 0;
for (; i < outh; i++)
{
int remain = outw;
for (; remain > 0; remain--)
{
float sum = bias0;
sum += r0[0] * k0[0];
sum += r0[1] * k0[1];
sum += r0[2] * k0[2];
sum += r1[0] * k1[0];
sum += r1[1] * k1[1];
sum += r1[2] * k1[2];
sum += r2[0] * k2[0];
sum += r2[1] * k2[1];
sum += r2[2] * k2[2];
*outptr = sum;
r0 += 2;
r1 += 2;
r2 += 2;
outptr++;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
}
}
}
#endif
int conv_dw_run(struct ir_tensor* input_tensor, struct ir_tensor* weight_tensor, struct ir_tensor* bias_tensor,
struct ir_tensor* output_tensor, struct conv_priv_info* conv_info, struct conv_param* param, int num_thread, int cpu_affinity)
{
float* input = ( float* )input_tensor->data;
float* output = ( float* )output_tensor->data;
float* kernel = ( float* )weight_tensor->data;
float* biases = NULL;
if (bias_tensor)
biases = ( float* )bias_tensor->data;
int batch_number = input_tensor->dims[0];
int inc = input_tensor->dims[1];
int inh = input_tensor->dims[2];
int inw = input_tensor->dims[3];
int in_chw = inc * inh * inw;
int outc = output_tensor->dims[1];
int outh = output_tensor->dims[2];
int outw = output_tensor->dims[3];
int out_hw = outh * outw;
int out_chw = out_hw * outc;
int ksize_h = param->kernel_h;
int ksize_w = param->kernel_w;
int pad_w = param->pad_w0;
int pad_h = param->pad_h0;
int stride_w = param->stride_w;
int stride_h = param->stride_h;
int dilation_w = param->dilation_w;
int dilation_h = param->dilation_h;
int group = param->group;
int activation = param->activation;
/* pading */
int inh_tmp = inh + pad_h + pad_h;
int inw_tmp = inw + pad_w + pad_w;
float* input_tmp = NULL;
if (inh_tmp == inh && inw_tmp == inw)
input_tmp = input;
else
{
input_tmp = ( float* )sys_malloc((unsigned long)inh_tmp * inw_tmp * group * sizeof(float));
#pragma omp parallel for num_threads(num_thread)
for (int g = 0; g < group; g++)
{
float* pad_in = input + g * inh * inw;
float* pad_out = input_tmp + g * inh_tmp * inw_tmp;
pad(pad_in, pad_out, inh, inw, inh_tmp, inw_tmp, pad_h, pad_w, 0.f);
}
}
/* process */
for (int i = 0; i < batch_number; i++)
{
if (stride_h == 1)
convdw3x3s1(output, input_tmp, kernel, biases, group, inh_tmp, inw_tmp, outh, outw, num_thread);
else
convdw3x3s2(output, input_tmp, kernel, biases, group, inh_tmp, inw_tmp, outh, outw, num_thread);
}
/* relu */
if (activation >= 0)
relu(output, batch_number * out_chw, activation);
if (!(inh_tmp == inh && inw_tmp == inw))
sys_free(input_tmp);
return 0;
}
|
GB_unaryop__lnot_bool_uint8.c
|
//------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__lnot_bool_uint8
// op(A') function: GB_tran__lnot_bool_uint8
// C type: bool
// A type: uint8_t
// cast: bool cij = (bool) aij
// unaryop: cij = !aij
#define GB_ATYPE \
uint8_t
#define GB_CTYPE \
bool
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint8_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) \
bool z = (bool) x ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (x, aij) ; \
GB_OP (GB_CX (pC), x) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_LNOT || GxB_NO_BOOL || GxB_NO_UINT8)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__lnot_bool_uint8
(
bool *restrict Cx,
const uint8_t *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__lnot_bool_uint8
(
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_uint8_uint16.c
|
//------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop_apply__identity_uint8_uint16
// op(A') function: GB_unop_tran__identity_uint8_uint16
// C type: uint8_t
// A type: uint16_t
// cast: uint8_t cij = (uint8_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
uint16_t
#define GB_CTYPE \
uint8_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint16_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
uint8_t z = (uint8_t) aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
uint16_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
uint8_t z = (uint8_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_UINT8 || GxB_NO_UINT16)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__identity_uint8_uint16
(
uint8_t *Cx, // Cx and Ax may be aliased
const uint16_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++)
{
uint16_t aij = Ax [p] ;
uint8_t z = (uint8_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_uint8_uint16
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
vectorOps.c
|
/*=======================
C Program Template
Evan William Gretok
Month D, YEAR
=======================*/
// Inclusions
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>
// Definitions
#define DEBUG 0
#define SIZE 100000000
// Main
int main( int argc, char *argv[ ] ) {
// Seed Your Random Number Generators
srand( time( NULL ) );
// Loop Iterator
int i = 0;
// Initialize Vector Memory Spaces
double *mainVector = malloc( SIZE * sizeof( double ) );
double *divVector = malloc( SIZE * sizeof( double ) );
double *solVector = malloc( SIZE * sizeof( double ) );
// Fill Vectors
double x = rand( );
printf( "%lf\n", x );
for( i = 0; i < SIZE; i++ ) {
mainVector[i] = ( rand( ) % 10000000 ) * 0.01;
divVector[i] = ( rand( ) % 1000 ) * 0.01;
solVector[i] = 0;
}
// DEBUG - Display Vectors
if( DEBUG ) {
for( i = 0; i < SIZE; i++ ) {
printf( " %5.2lf %1.2lf\n", mainVector[i], divVector[i] );
}
}
// Perform Processing
double start = omp_get_wtime( );
#pragma omp parallel for shared( mainVector, divVector, solVector ) \
private( i ) schedule( static, 10 ) num_threads( 4 )
for( i = 0; i < SIZE; i++ ) {
solVector[i] = mainVector[i] / divVector[i];
}
double end = omp_get_wtime( );
// DEBUG - Display Output
if( DEBUG ) {
for( i = 0; i < SIZE; i++ ) {
printf( " %1.2lf\n", solVector[i] );
}
}
// Display Timing
double solTime = end - start;
printf( "Vector Division Complete - %lf Seconds\n", solTime );
return 0;
}
// End .c - EWG SDG
|
Example_tasking.3.c
|
/*
* @@name: tasking.3c
* @@type: C
* @@compilable: yes
* @@linkable: no
* @@expect: success
* @@version: omp_3.0
*/
typedef struct node node;
struct node {
int data;
node * next;
};
void process(node * p)
{
/* do work here */
}
void increment_list_items(node * head)
{
#pragma omp parallel
{
#pragma omp single
{
node * p = head;
while (p) {
#pragma omp task
// p is firstprivate by default
process(p);
p = p->next;
}
}
}
}
|
C04Traversal.h
|
/**
* @file C04Traversal.h
* @author C.Menges, based on tchipevn (original source:
* ls1-mardyn/src/particleContainer/LinkedCellTraversals/C04CellPairTraversal.h)
* @date 15.06.2019
*/
#pragma once
#include "autopas/containers/cellPairTraversals/C08BasedTraversal.h"
#include "autopas/containers/linkedCells/traversals/C08CellHandler.h"
#include "autopas/containers/linkedCells/traversals/LinkedCellTraversalInterface.h"
#include "autopas/pairwiseFunctors/CellFunctor.h"
#include "autopas/utils/ArrayUtils.h"
#include "autopas/utils/ThreeDimensionalMapping.h"
#include "autopas/utils/WrapOpenMP.h"
namespace autopas {
/**
* This class provides the c04 traversal.
*
* The traversal uses the c04 base step performed on every single cell. Since
* these steps overlap a domain coloring with four colors is applied.
*
* @tparam ParticleCell the type of cells
* @tparam PairwiseFunctor The functor that defines the interaction of two particles.
* @tparam useSoA
* @tparam useNewton3
*/
template <class ParticleCell, class PairwiseFunctor, DataLayoutOption::Value dataLayout, bool useNewton3>
class C04Traversal : public C08BasedTraversal<ParticleCell, PairwiseFunctor, dataLayout, useNewton3>,
public LinkedCellTraversalInterface<ParticleCell> {
public:
/**
* Constructor of the c04 traversal.
* @param dims The dimensions of the cellblock, i.e. the number of cells in x,
* y and z direction.
* @param pairwiseFunctor The functor that defines the interaction of two particles.
* @param interactionLength Cutoff radius.
* @param cellLength cell length.
*/
C04Traversal(const std::array<unsigned long, 3> &dims, PairwiseFunctor *pairwiseFunctor,
const double interactionLength, const std::array<double, 3> &cellLength)
: C08BasedTraversal<ParticleCell, PairwiseFunctor, dataLayout, useNewton3>(dims, pairwiseFunctor,
interactionLength, cellLength),
_cellHandler(pairwiseFunctor, this->_cellsPerDimension, interactionLength, cellLength, this->_overlap),
_end(utils::ArrayMath::subScalar(utils::ArrayUtils::static_cast_array<long>(this->_cellsPerDimension), 1l)) {
computeOffsets32Pack();
}
void traverseParticlePairs() override;
TraversalOption getTraversalType() const override { return TraversalOption::c04; }
DataLayoutOption getDataLayout() const override { return dataLayout; }
bool getUseNewton3() const override { return useNewton3; }
/**
* C04 traversals are usable, if cellSizeFactor >= 1.0 and there are at least 3 cells for each dimension.
* @return
*/
bool isApplicable() const override {
if (dataLayout == DataLayoutOption::cuda) {
return false;
}
const double minLength = *std::min_element(this->_cellLength.cbegin(), this->_cellLength.cend());
const unsigned long minDim = *std::min_element(this->_cellsPerDimension.cbegin(), this->_cellsPerDimension.cend());
return minLength >= this->_interactionLength and minDim > 3;
}
private:
void traverseSingleColor(std::vector<ParticleCell> &cells, int color);
void processBasePack32(std::vector<ParticleCell> &cells, const std::array<long, 3> &base3DIndex);
constexpr void computeOffsets32Pack();
constexpr long parity(long x, long y, long z) const { return (x + y + z + 24) % 8; }
std::array<std::array<long, 3>, 32> _cellOffsets32Pack;
C08CellHandler<ParticleCell, PairwiseFunctor, dataLayout, useNewton3> _cellHandler;
const std::array<long, 3> _end;
};
template <class ParticleCell, class PairwiseFunctor, DataLayoutOption::Value dataLayout, bool useNewton3>
constexpr void C04Traversal<ParticleCell, PairwiseFunctor, dataLayout, useNewton3>::computeOffsets32Pack() {
using std::make_pair;
using utils::ThreeDimensionalMapping::threeToOneD;
unsigned int i = 0;
long z = 0l;
_cellOffsets32Pack[i++] = {1l, 1l, z};
_cellOffsets32Pack[i++] = {1l, 2l, z};
_cellOffsets32Pack[i++] = {2l, 1l, z};
_cellOffsets32Pack[i++] = {2l, 2l, z};
// z = 1ul; z = 2ul
for (z = 1l; z < 3l; ++z) {
for (long y = 0l; y < 4l; y++) {
for (long x = 0l; x < 4l; x++) {
if ((x == 0l and y == 0l) or (x == 3l and y == 0l) or (x == 0l and y == 3l) or (x == 3l and y == 3l)) {
continue;
}
_cellOffsets32Pack[i++] = {x, y, z};
}
}
}
z = 3ul;
_cellOffsets32Pack[i++] = {1l, 1l, z};
_cellOffsets32Pack[i++] = {1l, 2l, z};
_cellOffsets32Pack[i++] = {2l, 1l, z};
_cellOffsets32Pack[i++] = {2l, 2l, z};
if (i != 32) {
utils::ExceptionHandler::exception("Internal error: Wrong number of offsets (expected: 32, actual: {})", i);
}
}
template <class ParticleCell, class PairwiseFunctor, DataLayoutOption::Value dataLayout, bool useNewton3>
void C04Traversal<ParticleCell, PairwiseFunctor, dataLayout, useNewton3>::processBasePack32(
std::vector<ParticleCell> &cells, const std::array<long, 3> &base3DIndex) {
using utils::ThreeDimensionalMapping::threeToOneD;
std::array<long, 3> index;
const std::array<long, 3> signedDims = utils::ArrayUtils::static_cast_array<long>(this->_cellsPerDimension);
for (auto Offset32Pack : _cellOffsets32Pack) {
// compute 3D index
bool isIn = true;
for (int d = 0; d < 3; ++d) {
index[d] = base3DIndex[d] + Offset32Pack[d];
isIn &= (index[d] >= 0l) and (index[d] < _end[d]);
}
if (isIn) {
const unsigned long ulIndex = threeToOneD(index, signedDims);
_cellHandler.processBaseCell(cells, ulIndex);
}
}
}
template <class ParticleCell, class PairwiseFunctor, DataLayoutOption::Value dataLayout, bool useNewton3>
void C04Traversal<ParticleCell, PairwiseFunctor, dataLayout, useNewton3>::traverseParticlePairs() {
auto &cells = *(this->_cells);
#if defined(AUTOPAS_OPENMP)
#pragma omp parallel
#endif
{
for (int color = 0; color < 4; ++color) {
traverseSingleColor(cells, color);
#if defined(AUTOPAS_OPENMP)
if (color < 3) {
#pragma omp barrier
}
#endif
}
} // close parallel region
}
template <class ParticleCell, class PairwiseFunctor, DataLayoutOption::Value dataLayout, bool useNewton3>
void C04Traversal<ParticleCell, PairwiseFunctor, dataLayout, useNewton3>::traverseSingleColor(
std::vector<ParticleCell> &cells, int color) {
// we need to traverse one body-centered cubic (BCC) grid, which consists of two cartesian grids
// colors 0 and 2 form one cartesian grid
// colors 1 and 3 form another cartesian grid, whose origin is shifted by (2,2,2)
// determine a starting point of one of the grids
std::array<long, 3> startOfThisColor{};
switch (color % 2) {
case 0:
// colours 0 and 2
startOfThisColor = {-2l, -2l, -2l};
break;
case 1:
// colours 1 and 3
startOfThisColor = {0l, 0l, 0l};
break;
}
long correctParity = parity(startOfThisColor[0], startOfThisColor[1], startOfThisColor[2]);
if (color >= 2) {
correctParity += 4;
}
// to fix compiler complaints about perfectly nested loop.
const long startX = startOfThisColor[0], endX = _end[0];
const long startY = startOfThisColor[1], endY = _end[1];
const long startZ = startOfThisColor[2], endZ = _end[2];
// first cartesian grid
#if defined(AUTOPAS_OPENMP)
#pragma omp for schedule(dynamic, 1) collapse(3) nowait
#endif
for (long z = startZ; z < endZ; z += 4) {
for (long y = startY; y < endY; y += 4) {
for (long x = startX; x < endX; x += 4) {
const long par = parity(x, y, z);
if (par != correctParity) {
continue;
}
const std::array<long, 3> base3DIndex = {x, y, z};
processBasePack32(cells, base3DIndex);
}
}
}
}
} // namespace autopas
|
signalMachine.c
|
#include <getopt.h>
#include <string.h>
#include "signalMachineUtils.h"
#include "pairwiseAligner.h"
#include "fasta_handler.h"
#define ESTIMATE_PARAMS 1
#define ASSIGNMENT_THRESHOLD 0.1
typedef enum {
full = 0,
variantCaller = 1,
assignments = 2,
both = 3
} OutputFormat;
void usage() {
fprintf(stderr, "\n\tsignalMachine - Align ONT ionic current to a reference sequence\n\n");
fprintf(stderr, "--help: Display this super useful message and exit\n");
fprintf(stderr, "--sm3Hdp, -d: Flag, enable HMM-HDP model\n");
fprintf(stderr, "--twoD, -e: Flag, use 2D workflow (enables complement alignment)\n");
fprintf(stderr, "-s: Output format, 0=full, 1=variantCaller, 2=assignments\n");
fprintf(stderr, "-o: Degernate, 0=C/E, 1=C/E/O, 2=A/I, 3=A/C/G/T, 4=J/T, 5=A/F");
fprintf(stderr, "-T: Template HMM model\n");
fprintf(stderr, "-C: Complement HMM model\n");
fprintf(stderr, "-L: Read (output) label\n");
fprintf(stderr, "-q: NanoporeRead (in npRead format)\n");
fprintf(stderr, "-f: Forward reference to align to as a flat file\n");
fprintf(stderr, "-b: Backward reference to align to as a flat file\n");
fprintf(stderr, "-p: Guide alignment file, containing CIGARs in EXONERATE format\n");
fprintf(stderr, "-u: Posteriors (output) file path, place to put the output\n");
fprintf(stderr, "-v: TemplateHDP file\n");
fprintf(stderr, "-w: Complement HDP file\n");
fprintf(stderr, "-t: Template expectations (HMM transitions) output location\n");
fprintf(stderr, "-c: Complement expectations (HMM transitions) output location\n");
fprintf(stderr, "-x: Diagonal expansion, how much to expand the dynamic programming envelope\n");
fprintf(stderr, "-D: Posterior probability threshold, keep aligned pairs with posterior prob >= this\n");
fprintf(stderr, "-m: Constranint trim, how much to trim the guide alignment anchors by\n");
fprintf(stderr, "-g: traceBackDiagonals, how many backward diagonals to calculate during traceback\n");
fprintf(stderr, "-r: boolean option if read is RNA\n\n");
}
void printPairwiseAlignmentSummary(struct PairwiseAlignment *pA) {
st_uglyf("contig 1: %s\n", pA->contig1);
st_uglyf("strand 1: %lld\n", pA->strand1);
st_uglyf("start 1: %lld\n", pA->start1);
st_uglyf("end 1: %lld\n", pA->end1);
st_uglyf("contig 2: %s\n", pA->contig2);
st_uglyf("strand 2: %lld\n", pA->strand2);
st_uglyf("start 2: %lld\n", pA->start2);
st_uglyf("end 2: %lld\n", pA->end2);
}
static inline int64_t adjustReferenceCoordinate(int64_t x_i, int64_t referenceSeqOffset,
int64_t referenceLengthInKmers, int64_t referenceLength,
Strand strand, bool forward) {
if ((strand == template && forward) || (strand == complement && !forward)) {
return x_i + referenceSeqOffset;
} else {
return referenceLengthInKmers - (x_i + (referenceLength - referenceSeqOffset));
}
}
static inline char *makeReferenceKmer(const char *k_i, Strand strand, bool forward) {
if ((strand == template && forward) || (strand == complement && !forward)) {
return stString_copy(k_i);
} else {
return stString_reverseComplementString(k_i);
}
}
static inline char *kmerFromString(const char *string, int64_t start, int64_t kmerLength) {
char *k_i = st_malloc((kmerLength + 1) * sizeof(char));
for (int64_t i = 0; i < kmerLength; i++) {
k_i[i] = *(string + (start + i));
}
k_i[kmerLength] = '\0';
return k_i;
}
static inline int64_t adjustQueryPosition(int64_t unadjustedQueryPosition, int64_t kmerLength, Strand strand, bool forward) {
if ((strand == template && forward) || (strand == complement && !forward)) {
return unadjustedQueryPosition;
} else {
return (kmerLength - 1) - unadjustedQueryPosition;
}
}
void writePosteriorProbsFull(char *posteriorProbsFile, char *readLabel, StateMachine *sM,
NanoporeReadAdjustmentParameters npp, double *events, char *target, bool forward,
char *contig, int64_t eventSequenceOffset, int64_t referenceSequenceOffset,
stList *alignedPairs, Strand strand, bool rna) {
// label for tsv output
char *strandLabel = strand == template ? "t" : "c";
// open the file for output
FILE *fH = fopen(posteriorProbsFile, "a");
// get some lengths outside the loop
int64_t refLength = (int64_t )strlen(target);
int64_t refLengthInKmers = refLength - sM->kmerLength;
// printf("%" PRIu64 "\n", stList_length(alignedPairs));
for(int64_t i = 0; i < stList_length(alignedPairs); i++) {
// grab the aligned pair
stIntTuple *aPair = stList_get(alignedPairs, i);
if (stIntTuple_length(aPair) != 4) {
st_errAbort("Aligned pair tuples should have length 4, this one has length %lld\n",
stIntTuple_length(aPair));
}
// nucleotide sequence coordinate
int64_t x_i = stIntTuple_get(aPair, 1);
// adjust back to reference coordinates
int64_t x_adj = adjustReferenceCoordinate(x_i, referenceSequenceOffset, refLengthInKmers, refLength,
strand, forward);
// event index, adjust to to entire event sequence coordinates (event sequence is trimmed during alignment)
int64_t y = stIntTuple_get(aPair, 2) + eventSequenceOffset;
// posterior probability
double p = ((double)stIntTuple_get(aPair, 0)) / PAIR_ALIGNMENT_PROB_1;
// path (variant-called) kmer
char *pathKmer = (char *)stIntTuple_get(aPair, 3);
double eventMean = sequence_getEventMean(events, y);
double eventNoise = sequence_getEventNoise(events, y);
double eventDuration = sequence_getEventDuration(events, y);
// make the kmer string at the target index,
char *k_i = kmerFromString(target, x_i, sM->kmerLength);
int64_t targetKmerIndex = kmer_id(pathKmer, sM->alphabet, sM->alphabetSize, sM->kmerLength);
// get the expected event mean amplitude and noise
double E_mean = sM->EMISSION_MATCH_MATRIX[(targetKmerIndex * MODEL_PARAMS)];
double E_noise = sM->EMISSION_MATCH_MATRIX[(targetKmerIndex * MODEL_PARAMS + 2)];
double scaled_Emean = E_mean * npp.scale + npp.shift;
double scaled_Enoise = E_noise * npp.scale_sd;
double descaledEventMean = emissions_signal_descaleEventMean_JordanStyle(eventMean, E_mean,
npp.scale, npp.shift, npp.var);
// make reference kmer
char *refKmer = makeReferenceKmer(k_i, strand, forward);
if (rna){
refKmer = stString_reverseComplementString(refKmer);
}
// write to file
fprintf(fH, "%s\t%"PRId64"\t%s\t%s\t%s\t%"PRId64"\t%f\t%f\t%f\t%s\t%f\t%f\t%f\t%f\t%f\t%s\n",
contig, x_adj, refKmer, readLabel, strandLabel, y, eventMean, eventNoise, eventDuration, k_i,
scaled_Emean, scaled_Enoise, p, descaledEventMean, E_mean, pathKmer);
// cleanup
free(k_i);
free(refKmer);
}
fclose(fH);
}
void writePosteriorProbsVC(char *posteriorProbsFile, char *readLabel, StateMachine *sM, char *target, bool forward,
int64_t eventSequenceOffset, int64_t referenceSequenceOffset, stList *alignedPairs,
Strand strand, double posteriorScore, bool rna, char *contig) {
// label for tsv output
char *strandLabel = strand == template ? "t" : "c";
if (rna || strand != template){
forward = !forward;
}
char *forwardLabel = forward ? "forward" : "backward";
if (rna || strand != template){
forward = !forward;
}
// open the file for output
FILE *fH = fopen(posteriorProbsFile, "a");
// get some lengths outside the loop
int64_t refLength = (int64_t )strlen(target);
int64_t refLengthInKmers = refLength - sM->kmerLength;
for(int64_t i = 0; i < stList_length(alignedPairs); i++) {
// grab the aligned pair
stIntTuple *aPair = stList_get(alignedPairs, i);
if (stIntTuple_length(aPair) != 4) {
st_errAbort("Aligned pair tuples should have length 4, this one has length %lld\n",
stIntTuple_length(aPair));
}
// trimmed nucleotide sequence coordinate
int64_t x_i = stIntTuple_get(aPair, 1);
// make the kmer string at the target index,
char *k_i = kmerFromString(target, x_i, sM->kmerLength);
char *refKmer = makeReferenceKmer(k_i, strand, forward);
stList *queryPositions = path_findDegeneratePositions(refKmer, sM->kmerLength);
// check if this aligned pair reports on a query position
if (stList_length(queryPositions) == 0) {
free(k_i);
free(refKmer);
stList_destruct(queryPositions);
continue;
}
// adjust back to reference coordinates
int64_t x_adj = adjustReferenceCoordinate(x_i, referenceSequenceOffset, refLengthInKmers, refLength,
strand, forward);
// event index, adjust to to entire event sequence coordinates (event sequence is trimmed during alignment)
int64_t y = stIntTuple_get(aPair, 2) + eventSequenceOffset;
// posterior probability
double p = ((double)stIntTuple_get(aPair, 0)) / PAIR_ALIGNMENT_PROB_1;
// path (variant-called) kmer
char *pathKmer = (char *)stIntTuple_get(aPair, 3);
// get the base that was called in this aligned pair
int64_t nQueryPositions = stList_length(queryPositions);
for (int64_t q = 0; q < nQueryPositions; q++) {
// position in the reference kmer eg. AGXGG -> 2
int64_t unadjustedQueryPosition = *(int64_t *)stList_get(queryPositions, q);
// position in the pathKmer
int64_t queryPosition = adjustQueryPosition(unadjustedQueryPosition, sM->kmerLength,
strand, forward);
// called base
char base = pathKmer[queryPosition];
// position in the reference we're reporting on
int64_t reportPosition = x_adj + unadjustedQueryPosition;
fprintf(fH, "%"PRId64"\t%"PRId64"\t%c\t%f\t%s\t%s\t%s\t%f\t%s\n", y, reportPosition, base, p,
strandLabel, forwardLabel, readLabel, posteriorScore, contig);
}
free(k_i);
free(refKmer);
stList_destruct(queryPositions);
}
fclose(fH);
}
void writeAssignments(char *posteriorProbsFile, StateMachine *sM, double *events, int64_t eventSequenceOffset,
NanoporeReadAdjustmentParameters npp, stList *alignedPairs, Strand strand) {
// label for tsv output
char *strandLabel = strand == template ? "t" : "c";
// open the file for output
FILE *fH = fopen(posteriorProbsFile, "a");
for(int64_t i = 0; i < stList_length(alignedPairs); i++) {
// grab the aligned pair
stIntTuple *aPair = stList_get(alignedPairs, i);
if (stIntTuple_length(aPair) != 4) {
st_errAbort("Aligned pair tuples should have length 4, this one has length %lld\n",
stIntTuple_length(aPair));
}
// event index, adjust to to entire event sequence coordinates (event sequence is trimmed during alignment)
int64_t y = stIntTuple_get(aPair, 2) + eventSequenceOffset;
// posterior probability
double p = ((double)stIntTuple_get(aPair, 0)) / PAIR_ALIGNMENT_PROB_1;
// path (variant-called) kmer
char *pathKmer = (char *)stIntTuple_get(aPair, 3);
// get the observed event mean
double eventMean = sequence_getEventMean(events, y);
// get the kmer index
int64_t targetKmerIndex = kmer_id(pathKmer, sM->alphabet, sM->alphabetSize, sM->kmerLength);
// get the expected mean from the model
double E_mean = sM->EMISSION_MATCH_MATRIX[(targetKmerIndex * MODEL_PARAMS)];
// descale the observed mean
double descaledEventMean = emissions_signal_descaleEventMean_JordanStyle(eventMean, E_mean,
npp.scale, npp.shift, npp.var);
fprintf(fH, "%s\t%s\t%lf\t%lf\n", pathKmer, strandLabel, descaledEventMean, p);
}
fclose(fH);
}
void outputAlignment(
OutputFormat fmt,
char *posteriorProbsFile,
char *readLabel,
StateMachine *sM,
NanoporeReadAdjustmentParameters npp,
double *events,
char *target,
bool forward,
char *contig,
int64_t eventSequenceOffset,
int64_t referenceSequenceOffset,
stList *alignedPairs,
double posteriorScore,
Strand strand,
bool rna,
char *posteriorProbsFile2) {
switch (fmt) {
case full:
writePosteriorProbsFull(posteriorProbsFile, readLabel, sM, npp, events, target, forward, contig,
eventSequenceOffset, referenceSequenceOffset, alignedPairs, strand, rna);
break;
case variantCaller:
writePosteriorProbsVC(posteriorProbsFile, readLabel, sM, target, forward, eventSequenceOffset,
referenceSequenceOffset, alignedPairs, strand, posteriorScore, rna, contig);
break;
case assignments:
writeAssignments(posteriorProbsFile, sM, events, eventSequenceOffset, npp, alignedPairs, strand);
break;
case both:
writePosteriorProbsFull(posteriorProbsFile, readLabel, sM, npp, events, target, forward, contig,
eventSequenceOffset, referenceSequenceOffset, alignedPairs, strand, rna);
writePosteriorProbsVC(posteriorProbsFile2, readLabel, sM, target, forward, eventSequenceOffset,
referenceSequenceOffset, alignedPairs, strand, posteriorScore, rna, contig);
break;
default:
fprintf(stderr, "signalAlign - No valid output format provided\n");
return;
}
}
StateMachine *buildStateMachine(const char *modelFile, NanoporeReadAdjustmentParameters npp, StateMachineType type,
NanoporeHDP *nHdp) {
if ((type != threeState) && (type != threeStateHdp)) {
st_errAbort("signalAlign - incompatible stateMachine type request");
}
if (!stFile_exists(modelFile)) {
st_errAbort("signalAlign - ERROR: couldn't find model file here: %s\n", modelFile);
}
if (type == threeState) {
StateMachine *sM = getStateMachine3_descaled(modelFile, npp, !ESTIMATE_PARAMS);
return sM;
}
if (type == threeStateHdp) {
StateMachine *sM = getHdpStateMachine(nHdp, modelFile, npp);
return sM;
}
else {
st_errAbort("signalAlign - ERROR: buildStateMachine, didn't get correct input\n");
}
return 0;
}
inline void loadHmmRoutine(const char *hmmFile, StateMachine *sM, StateMachineType type, Hmm *expectations) {
if ((type != threeState) && (type != threeStateHdp)) {
st_errAbort("LoadSignalHmm : unupported stateMachineType");
}
hmmContinuous_loadSignalHmm(hmmFile, sM, type, expectations);
}
StateMachine *buildStateMachineAndLoadHmm(const char *modelFile, NanoporeReadAdjustmentParameters npp,
StateMachineType type, NanoporeHDP *nHdp) {
StateMachine *sM = buildStateMachine(modelFile, npp, type, nHdp);
// commented out because now the model file has the transitions and the event model, so no longer need to
// load the .hmm into the stateMachine
//if (HmmFile != NULL) {
// loadHmmRoutine(HmmFile, sM, sM->type, hmmExpectations);
//}
return sM;
}
void updateHdpFromAssignments(const char *nHdpFile, const char *expectationsFile, const char *nHdpOutFile) {
NanoporeHDP *nHdp = deserialize_nhdp(nHdpFile);
Hmm *hdpHmm = hdpHmm_loadFromFile(expectationsFile, threeStateHdp, nHdp);
hmmContinuous_destruct(hdpHmm, hdpHmm->type);
fprintf(stderr, "signalAlign - Running Gibbs on HDP\n");
execute_nhdp_gibbs_sampling(nHdp, 10000, 100000, 100, FALSE);
finalize_nhdp_distributions(nHdp);
fprintf(stderr, "signalAlign - Serializing HDP to %s\n", nHdpOutFile);
serialize_nhdp(nHdp, nHdpOutFile);
destroy_nanopore_hdp(nHdp);
}
static double totalScore(stList *alignedPairs) {
double score = 0.0;
for (int64_t i = 0; i < stList_length(alignedPairs); i++) {
stIntTuple *aPair = stList_get(alignedPairs, i);
score += stIntTuple_get(aPair, 0);
}
return score;
}
double scoreByPosteriorProbabilityIgnoringGaps(stList *alignedPairs) {
/*
* Gives the average posterior match probability per base of the two sequences, ignoring indels.
*/
return 100.0 * totalScore(alignedPairs) / ((double) stList_length(alignedPairs) * PAIR_ALIGNMENT_PROB_1);
}
stList *performSignalAlignment(StateMachine *sM, Sequence *eventSequence, int64_t *eventMap,
int64_t mapOffset, char *target, PairwiseAlignmentParameters *p,
stList *unmappedAnchors, DegenerateType degenerate) {
if ((sM->type != threeState) && (sM->type != threeStateHdp)) {
st_errAbort("signalAlign - You're trying to do the wrong king of alignment");
}
int64_t lX = sequence_correctSeqLength(strlen(target), kmer, sM->kmerLength);
// remap anchor pairs
stList *filteredRemappedAnchors = signalUtils_getRemappedAnchorPairs(unmappedAnchors, eventMap, mapOffset);
// make sequences
Sequence *sX = sequence_constructReferenceKmerSequence(lX, target, sequence_getKmer,
sequence_sliceNucleotideSequence, degenerate, kmer);
// do alignment
stList *alignedPairs = getAlignedPairsUsingAnchors(sM, sX, eventSequence, filteredRemappedAnchors, p,
diagonalCalculationPosteriorMatchProbs, 1, 1);
sequence_destruct(sX);
return alignedPairs;
}
Sequence *makeEventSequenceFromPairwiseAlignment(double *events, int64_t queryStart, int64_t queryEnd,
int64_t *eventMap) {
// find the event mapped to the start and end of the 2D read alignment
int64_t startIdx = eventMap[queryStart];
// We end up indexing past length of eventMap if we map to final base
int64_t endIdx = eventMap[queryEnd-1];
// move the event pointer to the first event
size_t elementSize = sizeof(double);
void *elements = (char *)events + ((startIdx * NB_EVENT_PARAMS) * elementSize);
// make the eventSequence
Sequence *eventS = sequence_constructEventSequence(endIdx - startIdx, elements);
return eventS;
}
void getSignalExpectations(StateMachine *sM, Hmm *hmmExpectations, Sequence *eventSequence,
int64_t *eventMap, int64_t mapOffset, char *trainingTarget, PairwiseAlignmentParameters *p,
stList *unmappedAnchors, DegenerateType degenerate) {
// correct sequence length
int64_t lX = sequence_correctSeqLength(strlen(trainingTarget), event, sM->kmerLength);
// remap the anchors
stList *filteredRemappedAnchors = signalUtils_getRemappedAnchorPairs(unmappedAnchors, eventMap, mapOffset);
Sequence *target = sequence_constructKmerSequence(
lX, trainingTarget, sequence_getKmer, sequence_sliceNucleotideSequence,
(degenerate == canonicalVariants ? CANONICAL_NUCLEOTIDES :
(degenerate == cytosineMethylation2 ? TWO_CYTOSINES : THREE_CYTOSINES)),
(degenerate == canonicalVariants ? NB_CANONICAL_BASES :
(degenerate == cytosineMethylation2 ? (NB_CYTOSINE_OPTIONS - 1) : NB_CYTOSINE_OPTIONS)),
kmer);
getExpectationsUsingAnchors(sM, hmmExpectations, target, eventSequence, filteredRemappedAnchors, p,
diagonalCalculation_Expectations, 1, 1);
}
int main(int argc, char *argv[]) {
StateMachineType sMtype = threeState;
int64_t j = 0;
int64_t diagExpansion = 50;
double threshold = 0.01;
int64_t constraintTrim = 14;
int64_t traceBackDiagonals = 50;
int64_t degenerate;
int64_t outFmt;
bool twoD = FALSE;
bool rna = FALSE;
char *templateModelFile = NULL;
char *complementModelFile = NULL;
char *readLabel = NULL;
char *npReadFile = NULL;
char *exonerateCigarFile= NULL;
char *posteriorProbsFile = NULL;
char *templateExpectationsFile = NULL;
char *complementExpectationsFile = NULL;
char *templateHdp = NULL;
char *complementHdp = NULL;
char *forward_reference_path = NULL;
char *backward_reference_path = NULL;
char *posteriorProbsFile2 = NULL;
const char *sequence_name = NULL;
int key;
while (1) {
static struct option long_options[] = {
{"help", no_argument, 0, 'h'},
{"sm3Hdp", no_argument, 0, 'd'},
{"sparse_output", no_argument, 0, 's'},
{"twoD", no_argument, 0, 'e'},
{"rna", no_argument, 0, 'r'},
{"degenerate", required_argument, 0, 'o'},
{"templateModel", required_argument, 0, 'T'},
{"complementModel", required_argument, 0, 'C'},
{"readLabel", required_argument, 0, 'L'},
{"npRead", required_argument, 0, 'q'},
{"exonerate_cigar_file", required_argument, 0, 'p'},
{"posteriors", required_argument, 0, 'u'},
{"templateHdp", required_argument, 0, 'v'},
{"complementHdp", required_argument, 0, 'w'},
{"templateExpectations", required_argument, 0, 't'},
{"complementExpectations", required_argument, 0, 'c'},
{"diagonalExpansion", required_argument, 0, 'x'},
{"threshold", required_argument, 0, 'D'},
{"constraintTrim", required_argument, 0, 'm'},
{"forward_reference_path", required_argument, 0, 'f'},
{"backward_reference_path", optional_argument, 0, 'b'},
{"sequence_name", required_argument, 0, 'n'},
{"traceBackDiagonals", optional_argument, 0, 'g'},
{"posteriorProbsFile2", optional_argument, 0, 'i'},
{0, 0, 0, 0} };
int option_index = 0;
key = getopt_long(argc, argv, "h:d:e:s:r:o:a:T:C:L:q:f:b:g:i:p:u:v:w:t:c:x:D:m:n:",
long_options, &option_index);
if (key == -1) {
//usage();
break;
}
switch (key) {
case 'h':
usage();
return 1;
case 's':
j = sscanf(optarg, "%" PRIi64 "", &outFmt);
assert (j == 1);
break;
case 'e':
twoD = TRUE;
break;
case 'r':
rna = TRUE;
break;
case 'o':
j = sscanf(optarg, "%" PRIi64 "", °enerate);
assert (j == 1);
break;
case 'd':
sMtype = threeStateHdp;
break;
case 'T':
templateModelFile = stString_copy(optarg);
break;
case 'C':
complementModelFile = stString_copy(optarg);
break;
case 'L':
readLabel = stString_copy(optarg);
break;
case 'q':
npReadFile = stString_copy(optarg);
break;
case 'p':
exonerateCigarFile = stString_copy(optarg);
break;
case 'u':
posteriorProbsFile = stString_copy(optarg);
break;
case 't':
templateExpectationsFile = stString_copy(optarg);
break;
case 'c':
complementExpectationsFile = stString_copy(optarg);
break;
case 'v':
templateHdp = stString_copy(optarg);
break;
case 'w':
complementHdp = stString_copy(optarg);
break;
case 'x':
j = sscanf(optarg, "%" PRIi64 "", &diagExpansion);
assert (j == 1);
assert (diagExpansion >= 0);
diagExpansion = (int64_t)diagExpansion;
break;
case 'D':
j = sscanf(optarg, "%lf", &threshold);
assert (j == 1);
assert (threshold >= 0);
break;
case 'm':
j = sscanf(optarg, "%" PRIi64 "", &constraintTrim);
assert (j == 1);
assert (constraintTrim >= 0);
constraintTrim = (int64_t)constraintTrim;
break;
case 'f':
forward_reference_path = stString_copy(optarg);
break;
case 'b':
backward_reference_path = stString_copy(optarg);
break;
case 'n':
sequence_name = stString_copy(optarg);
break;
case 'g':
j = sscanf(optarg, "%" PRIi64 "", &traceBackDiagonals);
assert (j == 1);
assert (traceBackDiagonals >= 0);
traceBackDiagonals = (int64_t)traceBackDiagonals;
break;
case 'i':
posteriorProbsFile2 = stString_copy(optarg);
break;
default:
usage();
return 1;
}
}
(void) j; // silence unused variable warning.
// check for models
if ((templateModelFile == NULL) || (complementModelFile == NULL && twoD)) {
st_errAbort("Missing model files, exiting\n");
return 1;
}
if ((outFmt == 3) & (posteriorProbsFile2 == NULL)) {
st_errAbort("Must pass in posteriorProbsFile2 if using 'both' outFmt\n");
return 1;
}
if (exonerateCigarFile == NULL) {
st_errAbort("[signalMachine]ERROR: Need to provide input guide alignments, exiting\n");
return 1;
}
// Anchors //
// get pairwise alignment from stdin, in exonerate CIGAR format
//FILE *fileHandleIn = stdin;
if (!stFile_exists(exonerateCigarFile)) {
st_errAbort("[signalMachine]ERROR: Didn't find input alignment file, looked %s\n", exonerateCigarFile);
} else {
st_uglyf("[signalMachine]NOTICE: Using guide alignments from %s\n", exonerateCigarFile);
}
FILE *fileHandleIn = fopen(exonerateCigarFile, "r");
// parse input CIGAR to get anchors
struct PairwiseAlignment *pA;
pA = cigarRead(fileHandleIn);
fclose(fileHandleIn);
// Alignment Parameters //
// make the pairwise alignment parameters
PairwiseAlignmentParameters *p = pairwiseAlignmentBandingParameters_construct();
p->threshold = threshold;
p->constraintDiagonalTrim = constraintTrim;
p->diagonalExpansion = diagExpansion;
p->traceBackDiagonals = traceBackDiagonals;
// HDP routines //
// load HDPs
NanoporeHDP *nHdpT, *nHdpC;
// check
if ((templateHdp != NULL) || (complementHdp != NULL)) {
if ((templateHdp == NULL) || (complementHdp == NULL && twoD)) {
st_errAbort("Need to have template and complement HDPs");
}
if (sMtype != threeStateHdp) {
sMtype = threeStateHdp;
fprintf(stderr, "[signalAlign] - Using threeStateHdp stateMachine since you pass in an HDP file\n");
} else {
fprintf(stderr, "[signalAlign] - using NanoporeHDPs\n");
}
}
#pragma omp parallel sections
{
{
nHdpT = (templateHdp == NULL) ? NULL : deserialize_nhdp(templateHdp);
}
#pragma omp section
{
nHdpC = (complementHdp == NULL) ? NULL : deserialize_nhdp(complementHdp);
}
}
// Nanopore Read //
// load nanopore read
NanoporeRead *npRead = nanopore_loadNanoporeReadFromFile(npReadFile);
if (rna){
int64_t tmp = pA->start2;
pA->start2 = npRead->templateReadLength - pA->end2;
pA->end2 = npRead->templateReadLength - tmp;
}
ReferenceSequence *R;
R = fastaHandler_ReferenceSequenceConstructFull(forward_reference_path, backward_reference_path, pA,
sequence_name, rna);
// constrain the event sequence to the positions given by the guide alignment
Sequence *tEventSequence = makeEventSequenceFromPairwiseAlignment(npRead->templateEvents,
pA->start2, pA->end2,
(twoD ? npRead->templateEventMap :
npRead->templateStrandEventMap));
Sequence *cEventSequence;
if (twoD) {
cEventSequence = makeEventSequenceFromPairwiseAlignment(npRead->complementEvents,
pA->start2, pA->end2,
npRead->complementEventMap);
} else {
cEventSequence = NULL;
}
// the aligned pairs start at (0,0) so we need to correct them based on the guide alignment later.
// record the pre-zeroed alignment start and end coordinates here
// for the events:
int64_t tCoordinateShift = twoD ? npRead->templateEventMap[pA->start2] : npRead->templateStrandEventMap[pA->start2];
int64_t cCoordinateShift = twoD ? npRead->complementEventMap[pA->start2] : 0;
// and for the reference:
int64_t rCoordinateShift_t = pA->start1;
int64_t rCoordinateShift_c = twoD ? pA->end1 : 0;
bool forward = pA->strand1; // keep track of whether this is a forward mapped read or not
stList *anchorPairs = signalUtils_guideAlignmentToRebasedAnchorPairs(pA, p); // pA gets modified here, no turning back
if ((templateExpectationsFile != NULL) || (complementExpectationsFile != NULL)) {
st_uglyf("Starting expectations routine\n");
// Expectation Routine //
StateMachine *sMt = buildStateMachine(templateModelFile, npRead->templateParams, sMtype, nHdpT);
// temporary way to 'turn off' estimates if I want to
if (ESTIMATE_PARAMS) { //todo remove threshold, not used
signalUtils_estimateNanoporeParams(sMt, npRead, &npRead->templateParams, ASSIGNMENT_THRESHOLD,
signalUtils_templateOneDAssignmentsFromRead,
nanopore_adjustTemplateEventsForDrift);
}
// make empty HMM to collect expectations
Hmm *templateExpectations = hmmContinuous_getExpectationsHmm(sMt, p->threshold, 0.001, 0.001);
// get expectations for template
fprintf(stderr, "signalAlign - getting expectations for template\n");
getSignalExpectations(sMt, templateExpectations, tEventSequence,
(twoD ? npRead->templateEventMap : npRead->templateStrandEventMap),
pA->start2,
R->getTemplateTargetSequence(R),
p, anchorPairs, degenerate);
if (sMtype == threeStateHdp) {
fprintf(stderr, "signalAlign - got %" PRId64 " template HDP assignments\n",
hmmContinuous_howManyAssignments(templateExpectations));
}
// write to file
fprintf(stderr, "signalAlign - writing expectations to file: %s\n", templateExpectationsFile);
hmmContinuous_writeToFile(templateExpectationsFile, templateExpectations, sMtype);
// get expectations for the complement
StateMachine *sMc;
Hmm *complementExpectations = NULL;
if (twoD) {
fprintf(stderr, "signalAlign - getting expectations for complement\n");
sMc = buildStateMachine(complementModelFile, npRead->complementParams, sMtype, nHdpC);
if (ESTIMATE_PARAMS) {
signalUtils_estimateNanoporeParams(sMc, npRead, &npRead->complementParams, ASSIGNMENT_THRESHOLD,
signalUtils_complementOneDAssignmentsFromRead,
nanopore_adjustComplementEventsForDrift);
}
complementExpectations = hmmContinuous_getExpectationsHmm(sMc, p->threshold, 0.001, 0.001);
getSignalExpectations(sMc, complementExpectations, cEventSequence, npRead->complementEventMap,
pA->start2,
R->getComplementTargetSequence(R),
p, anchorPairs, degenerate);
if (sMtype == threeStateHdp) {
fprintf(stderr, "signalAlign - got %"PRId64"complement HDP assignments\n",
hmmContinuous_howManyAssignments(complementExpectations));
}
// write to file
fprintf(stderr, "signalAlign - writing expectations to file: %s\n", complementExpectationsFile);
hmmContinuous_writeToFile(complementExpectationsFile, complementExpectations, sMtype);
}
stateMachine_destruct(sMt);
signalUtils_ReferenceSequenceDestruct(R);
hmmContinuous_destruct(templateExpectations, sMtype);
nanopore_nanoporeReadDestruct(npRead);
sequence_destruct(tEventSequence);
pairwiseAlignmentBandingParameters_destruct(p);
destructPairwiseAlignment(pA);
stList_destruct(anchorPairs);
if (twoD) {
stateMachine_destruct(sMc);
sequence_destruct(cEventSequence);
hmmContinuous_destruct(complementExpectations, sMtype);
}
fprintf(stderr, "signalAlign - SUCCESS: finished alignment of query %s, exiting\n", readLabel);
return 0;
} else {
// Alignment Procedure //
// Template alignment
fprintf(stderr, "signalAlign - starting template alignment\n");
// make template stateMachine
StateMachine *sMt = buildStateMachine(templateModelFile, npRead->templateParams, sMtype, nHdpT);
// re-estimate the nanoporeAdjustment parameters
if (ESTIMATE_PARAMS) {
signalUtils_estimateNanoporeParams(sMt, npRead, &npRead->templateParams, ASSIGNMENT_THRESHOLD,
signalUtils_templateOneDAssignmentsFromRead,
nanopore_adjustTemplateEventsForDrift);
}
if (sMtype == threeStateHdp) {
stateMachine3_setModelToHdpExpectedValues(sMt, nHdpT);
}
stList *templateAlignedPairs = performSignalAlignment(sMt, tEventSequence,
(twoD ? npRead->templateEventMap : npRead->templateStrandEventMap),
pA->start2, R->getTemplateTargetSequence(R),
p, anchorPairs,
degenerate);
double templatePosteriorScore = scoreByPosteriorProbabilityIgnoringGaps(templateAlignedPairs);
// sort
stList_sort(templateAlignedPairs, sortByXPlusYCoordinate2); //Ensure the coordinates are increasing
// write to file
if (posteriorProbsFile != NULL) {
outputAlignment(outFmt, posteriorProbsFile, readLabel, sMt, npRead->templateParams, npRead->templateEvents,
R->getTemplateTargetSequence(R), forward, pA->contig1, tCoordinateShift, rCoordinateShift_t,
templateAlignedPairs, templatePosteriorScore,template, rna, posteriorProbsFile2);
}
stList *complementAlignedPairs;
double complementPosteriorScore = 0.0;
StateMachine *sMc;
if (twoD) {
// Complement alignment
fprintf(stderr, "signalAlign - starting complement alignment\n");
sMc = buildStateMachine(complementModelFile, npRead->complementParams, sMtype, nHdpC);
if (ESTIMATE_PARAMS) {
signalUtils_estimateNanoporeParams(sMc, npRead, &npRead->complementParams, ASSIGNMENT_THRESHOLD,
signalUtils_complementOneDAssignmentsFromRead,
nanopore_adjustComplementEventsForDrift);
}
if (sMtype == threeStateHdp) {
stateMachine3_setModelToHdpExpectedValues(sMc, nHdpC);
}
complementAlignedPairs = performSignalAlignment(sMc, cEventSequence,
npRead->complementEventMap, pA->start2,
R->getComplementTargetSequence(R),
p, anchorPairs, degenerate);
complementPosteriorScore = scoreByPosteriorProbabilityIgnoringGaps(complementAlignedPairs);
// sort
stList_sort(complementAlignedPairs, sortByXPlusYCoordinate2); //Ensure the coordinates are increasing
// write to file
if (posteriorProbsFile != NULL) {
outputAlignment(outFmt, posteriorProbsFile, readLabel, sMc, npRead->complementParams,
npRead->complementEvents, R->getComplementTargetSequence(R), forward, pA->contig1,
cCoordinateShift, rCoordinateShift_c, complementAlignedPairs, complementPosteriorScore,
complement, rna, posteriorProbsFile2);
}
}
fprintf(stdout, "%s %"PRId64"\t%"PRId64"(%f)\t", readLabel, stList_length(anchorPairs),
stList_length(templateAlignedPairs), templatePosteriorScore);
if (twoD) {
fprintf(stdout, "%"PRId64"(%f)\n", stList_length(complementAlignedPairs), complementPosteriorScore);
} else {
fprintf(stdout, "\n");
}
// final alignment clean up
destructPairwiseAlignment(pA);
nanopore_nanoporeReadDestruct(npRead);
signalUtils_ReferenceSequenceDestruct(R);
stateMachine_destruct(sMt);
sequence_destruct(tEventSequence);
stList_destruct(templateAlignedPairs);
if (twoD) {
stateMachine_destruct(sMc);
sequence_destruct(cEventSequence);
stList_destruct(complementAlignedPairs);
}
fprintf(stderr, "signalAlign - SUCCESS: finished alignment of query %s, exiting\n", readLabel);
}
return 0;
}
|
sph_compute.c
|
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <sys/time.h>
#include <inttypes.h>
#include <omp.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_heapsort.h>
#include "sph_data_types.h"
#include "sph_linked_list.h"
#include "sph_compute.h"
extern const double fk_bspline_32[32];
extern const double fk_bspline_128[128];
extern const double fk_bspline_1024[1024];
#pragma omp declare simd
double w_bspline_3d(double r,double h){
const double A_d = 3./(2.*M_PI*h*h*h);
double q=0.;
if(r<0||h<=0.)
exit(10);
q = r/h;
if(q<=1)
return A_d*(2./3.-q*q + q*q*q/2.0);
else if((1.<=q)&&(q<2.))
return A_d*(1./6.)*(2.-q)*(2.-q)*(2.-q);
else
return 0.;
}
double w_bspline_3d_constant(double h){
return 3./(2.*M_PI*h*h*h);
}
#pragma omp declare simd
double w_bspline_3d_simd(double q){
double wq = 0.0;
double wq1 = (0.6666666666666666 - q*q + 0.5*q*q*q);
double wq2 = 0.16666666666666666*(2.-q)*(2.-q)*(2.-q);
if(q<2.)
wq = wq2;
if(q<1.)
wq = wq1;
return wq;
}
#pragma omp declare simd
double dwdq_bspline_3d_simd(double q){
double wq = 0.0;
double wq1 = (1.5*q*q - 2.*q);
double wq2 = -0.5*(2.-q)*(2.-q);
if(q<2.)
wq = wq2;
if(q<1.)
wq = wq1;
return wq;
}
// https://stackoverflow.com/questions/56417115/efficient-integer-floor-function-in-c
// 341.333333333 = 1024./3.
#pragma omp declare simd
double w_bspline_3d_LUT_1024(double q){
int kq = (int)(341.333333333*q);
double phi = q-kq*0.002929688;
double wq = phi*fk_bspline_1024[kq] + (1.-phi)*fk_bspline_1024[kq+1];
return wq;
}
#pragma omp declare simd
double w_bspline_3d_LUT_128(double q){
int kq = (int)(42.666666667*q);
double phi = q-kq*0.0234375;
double wq = phi*fk_bspline_128[kq] + (1.-phi)*fk_bspline_128[kq+1];
return wq;
}
#pragma omp declare simd
double w_bspline_3d_LUT_32(double q){
int kq = (int)(10.666666667*q);
double phi = q-kq*0.09375;
double wq = (1.-phi)*fk_bspline_32[kq] + phi*fk_bspline_32[kq+1];
return wq;
}
double dwdq_bspline_3d(double r,double h){
const double A_d = 3./(2.*M_PI*h*h*h*h);
double q=0.;
if(r<0||h<=0.)
exit(10);
q = r/h;
if(q<=1)
return A_d*q*(-2.+1.5*q);
else if((1.<=q)&&(q<2.))
return -A_d*0.5*(2.-q)*(2.-q);
else
return 0.;
}
double distance_2d(double xi,double yi,
double xj,double yj){
double dist = 0.0;
dist += (xi-xj)*(xi-xj);
dist += (yi-yj)*(yi-yj);
return sqrt(dist);
}
#pragma omp declare simd
double distance_3d(double xi,double yi,double zi,
double xj,double yj,double zj){
double dist = 0.0;
dist += (xi-xj)*(xi-xj);
dist += (yi-yj)*(yi-yj);
dist += (zi-zj)*(zi-zj);
return sqrt(dist);
}
/**********************************************************************/
int compute_density_3d_chunk(int64_t node_begin, int64_t node_end,
int64_t nb_begin, int64_t nb_end,double h,
double* restrict x, double* restrict y,
double* restrict z, double* restrict nu,
double* restrict rho){
const double inv_h = 1./h;
const double kernel_constant = w_bspline_3d_constant(h);
#pragma omp parallel for
for(int64_t ii=node_begin;ii<node_end;ii+=1){
double xii = x[ii];
double yii = y[ii];
double zii = z[ii];
double rhoii = 0.0;
#pragma omp simd reduction(+:rhoii) nontemporal(rhoii)
for(int64_t jj=nb_begin;jj<nb_end;jj+=1){
double q = 0.;
double xij = xii-x[jj];
double yij = yii-y[jj];
double zij = zii-z[jj];
q += xij*xij;
q += yij*yij;
q += zij*zij;
q = sqrt(q)*inv_h;
rhoii += nu[jj]*w_bspline_3d_simd(q);
//rhoii += nu[jj]*w_bspline_3d_LUT(q);
}
rho[ii] += rhoii*kernel_constant;
}
return 0;
}
int compute_density_3d_innerOmp(int N, double h, SPHparticle *lsph, linkedListBox *box){
int res;
double dist = 0.0;
khiter_t kbegin,kend;
int64_t node_hash=-1,node_begin=0, node_end=0;
int64_t nb_begin= 0, nb_end = 0;
int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)];
for (kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){
if (kh_exist(box->hbegin, kbegin)){
kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin));
node_hash = kh_key(box->hbegin, kbegin);
node_begin = kh_value(box->hbegin, kbegin);
node_end = kh_value(box->hend, kend);
for(int64_t ii=node_begin;ii<node_end;ii+=1)// this loop inside was the problem
lsph->rho[ii] = 0.0;
res = neighbour_hash_3d(node_hash,nblist,box->width,box);
for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){
if(nblist[j]>=0){
//nb_hash = nblist[j];
nb_begin = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) );
nb_end = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) );
compute_density_3d_chunk(node_begin,node_end,nb_begin,nb_end,h,
lsph->x,lsph->y,lsph->z,lsph->nu,lsph->rho);
}
}
}
}
return 0;
}
/**********************************************************************/
int compute_density_3d_chunk_noomp(int64_t node_begin, int64_t node_end,
int64_t nb_begin, int64_t nb_end,double h,
double* restrict x, double* restrict y,
double* restrict z, double* restrict nu,
double* restrict rho){
const double inv_h = 1./h;
const double kernel_constant = w_bspline_3d_constant(h);
for(int64_t ii=node_begin;ii<node_end;ii+=1){
double xii = x[ii];
double yii = y[ii];
double zii = z[ii];
double rhoii = 0.0;
#pragma omp simd reduction(+:rhoii)
for(int64_t jj=nb_begin;jj<nb_end;jj+=1){
double q = 0.;
double xij = xii-x[jj];
double yij = yii-y[jj];
double zij = zii-z[jj];
q += xij*xij;
q += yij*yij;
q += zij*zij;
q = sqrt(q)*inv_h;
rhoii += nu[jj]*w_bspline_3d_simd(q);
//rhoii += nu[jj]*w_bspline_3d_LUT(q);
}
rho[ii] += rhoii*kernel_constant;
}
return 0;
}
int compute_density_3d(int N, double h, SPHparticle *lsph, linkedListBox *box){
int64_t pair_count = 0;
const khint32_t num_boxes = kh_size(box->hbegin);
const khiter_t hbegin_start = kh_begin(box->hbegin), hbegin_finish = kh_end(box->hbegin);
//for (khint32_t kbegin = hbegin_start; kbegin != hbegin_finish; kbegin++)
#pragma omp parallel for num_threads(24)
for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){
int res;
int64_t node_hash=-1,node_begin=0, node_end=0;
int64_t nb_begin= 0, nb_end = 0;
int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)];
if (kh_exist(box->hbegin, kbegin)){ // I have to call this!
khint32_t kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin));
node_hash = kh_key(box->hbegin, kbegin);
node_begin = kh_value(box->hbegin, kbegin);
node_end = kh_value(box->hend, kend);
for(int64_t ii=node_begin;ii<node_end;ii+=1)
lsph->rho[ii] = 0.0;
res = neighbour_hash_3d(node_hash,nblist,box->width,box);
for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){
if(nblist[j]>=0){
//nb_hash = nblist[j];
nb_begin = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) );
nb_end = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) );
pair_count += (node_end-node_begin)*(nb_end-nb_begin);
compute_density_3d_chunk_noomp(node_begin,node_end,nb_begin,nb_end,h,
lsph->x,lsph->y,lsph->z,lsph->nu,lsph->rho);
}
}
}
//printf("thread %d - %lf %lf\n",i,lsph->rho[node_begin],lsph->rho[node_end-1]);
}
printf("pair_count = %ld\n",pair_count);
//for(int64_t i=0;i<N;i+=1000)
// printf("%ld - %lf\n",i,lsph->rho[i]);
return 0;
}
/**********************************************************************/
int compute_density_3d_chunk_loopswapped(int64_t node_begin, int64_t node_end,
int64_t node_hash,linkedListBox *box, double h,
double* restrict x, double* restrict y,
double* restrict z, double* restrict nu,
double* restrict rho)
{
int64_t pair_count;
int res=0,nb_count=0,fused_count=0;
//int64_t nb_begin= 0, nb_end = 0;
const double inv_h = 1./h;
const double kernel_constant = w_bspline_3d_constant(h);
int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)];
int64_t nb_begin[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)];
int64_t nb_end[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)];
res = neighbour_hash_3d(node_hash,nblist,box->width,box);
for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){
if(nblist[j]>=0){
nb_begin[nb_count] = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) );
nb_end[nb_count] = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) );
nb_count+=1;
}
else{
nb_begin[nb_count] = -1;
nb_end[nb_count] = -1;
}
}
qsort(nb_begin,nb_count,sizeof(int64_t),compare_int64_t);
qsort(nb_end ,nb_count,sizeof(int64_t),compare_int64_t);
fused_count = nb_count;
{
int64_t tmp;
unsigned int j=0;
while(j<nb_count-1){
if(nb_begin[j] < 0){
nb_begin[j] = nb_begin[nb_count-1]+1;
nb_end[j] = nb_end[nb_count-1]+1;
}
else if(nb_end[j]==nb_begin[j+1]){
//printf("%ld:%ld , %ld:%d",nb_begin[j],nb_begin[j+1]);
nb_end[j] = nb_end[j+1];
tmp = nb_begin[j];
nb_begin[j] = nb_begin[j+1];
nb_begin[j+1] = tmp;
tmp = nb_end[j];
nb_end[j] = nb_end[j+1];
nb_end[j+1] = tmp;
nb_begin[j] = nb_begin[nb_count-1]+1;
nb_end[j] = nb_end[nb_count-1]+1;
fused_count -= 1;
}
j+=1;
}
}
qsort(nb_begin,nb_count,sizeof(int64_t),compare_int64_t);
qsort(nb_end ,nb_count,sizeof(int64_t),compare_int64_t);
for(unsigned int j=0;j<fused_count;j+=1){
pair_count += (node_end-node_begin)*(nb_end[j]-nb_begin[j]);
for(int64_t ii=node_begin;ii<node_end;ii+=1){
double xii = x[ii];
double yii = y[ii];
double zii = z[ii];
#pragma omp simd
for(int64_t jj=nb_begin[j];jj<nb_end[j];jj+=1){
double q = 0.;
double xij = xii-x[jj];
double yij = yii-y[jj];
double zij = zii-z[jj];
q += xij*xij;
q += yij*yij;
q += zij*zij;
q = sqrt(q)*inv_h;
rho[ii] += nu[jj]*w_bspline_3d_simd(q);
}
}
}
for(int64_t ii=node_begin;ii<node_end;ii+=1)
rho[ii] *= kernel_constant;
return pair_count;
}
int compute_density_3d_loopswapped(int N, double h, SPHparticle *lsph, linkedListBox *box){
int64_t pair_count = 0, ppc;
const khint32_t num_boxes = kh_size(box->hbegin);
const khiter_t hbegin_start = kh_begin(box->hbegin), hbegin_finish = kh_end(box->hbegin);
//for (khint32_t kbegin = hbegin_start; kbegin != hbegin_finish; kbegin++)
#pragma omp parallel for num_threads(24)
for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){
int res;
int64_t node_hash=-1,node_begin=0, node_end=0;
if (kh_exist(box->hbegin, kbegin)){ // I have to call this!
khint32_t kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin));
node_hash = kh_key(box->hbegin, kbegin);
node_begin = kh_value(box->hbegin, kbegin);
node_end = kh_value(box->hend, kend);
for(int64_t ii=node_begin;ii<node_end;ii+=1)
lsph->rho[ii] = 0.0;
ppc = compute_density_3d_chunk_loopswapped(node_begin,node_end,node_hash,box,h,
lsph->x,lsph->y,lsph->z,lsph->nu,lsph->rho);
pair_count += ppc;
}
}
printf("pair_count = %ld\n",pair_count);
return 0;
}
/*******************************************************************/
int count_box_pairs(linkedListBox *box){
int64_t pair_count = 0, particle_pair_count = 0;
for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){
int res;
int64_t node_hash=-1,node_begin=0, node_end=0;
int64_t nb_begin= 0, nb_end = 0;
int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)];
if (kh_exist(box->hbegin, kbegin)){ // I have to call this!
khint32_t kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin));
node_hash = kh_key(box->hbegin, kbegin);
node_begin = kh_value(box->hbegin, kbegin);
node_end = kh_value(box->hend, kend);
res = neighbour_hash_3d(node_hash,nblist,box->width,box);
for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){
if(nblist[j]>=0){
//nb_hash = nblist[j];
nb_begin = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) );
nb_end = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) );
pair_count += 1;
particle_pair_count += (node_end-node_begin)*(nb_end-nb_begin);
}
}
}
}
printf("unique ordered particle_pair_count = %ld\n",particle_pair_count);
return pair_count;
}
int setup_box_pairs(linkedListBox *box,
int64_t *node_begin,int64_t *node_end,
int64_t *nb_begin,int64_t *nb_end)
{
int64_t pair_count = 0;
for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){
int res;
int64_t node_hash=-1;
int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)];
if (kh_exist(box->hbegin, kbegin)){ // I have to call this!
khint32_t kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin));
node_hash = kh_key(box->hbegin, kbegin);
res = neighbour_hash_3d(node_hash,nblist,box->width,box);
for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){
if(nblist[j]>=0){
//nb_hash = nblist[j];
node_begin[pair_count] = kh_value(box->hbegin, kbegin);
node_end[pair_count] = kh_value(box->hend, kend);
nb_begin[pair_count] = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) );
nb_end[pair_count] = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) );
pair_count += 1;//(node_end-node_begin)*(nb_end-nb_begin);
}
}
}
//printf("thread %d - %lf %lf\n",i,lsph->rho[node_begin],lsph->rho[node_end-1]);
}
return pair_count;
}
int compute_density_3d_chunk_noomp_shift(int64_t node_begin, int64_t node_end,
int64_t nb_begin, int64_t nb_end,double h,
double* restrict x, double* restrict y,
double* restrict z, double* restrict nu,
double* restrict rho){
const double inv_h = 1./h;
const double kernel_constant = w_bspline_3d_constant(h);
for(int64_t ii=node_begin;ii<node_end;ii+=1){
double xii = x[ii];
double yii = y[ii];
double zii = z[ii];
double rhoii = 0.0;
#pragma omp simd reduction(+:rhoii)
for(int64_t jj=nb_begin;jj<nb_end;jj+=1){
double q = 0.;
double xij = xii-x[jj];
double yij = yii-y[jj];
double zij = zii-z[jj];
q += xij*xij;
q += yij*yij;
q += zij*zij;
q = sqrt(q)*inv_h;
rhoii += nu[jj]*w_bspline_3d_simd(q);
}
rho[ii-node_begin] += rhoii*kernel_constant;
}
return 0;
}
int compute_density_3d_load_ballanced(int N, double h, SPHparticle *lsph, linkedListBox *box){
int64_t *node_begin,*node_end,*nb_begin,*nb_end;
int64_t max_box_pair_count = 0;
max_box_pair_count = count_box_pairs(box);
node_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t));
node_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t));
nb_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t));
nb_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t));
setup_box_pairs(box,node_begin,node_end,nb_begin,nb_end);
for(int64_t ii=0;ii<N;ii+=1)
lsph->rho[ii] = 0.0;
#pragma omp parallel for num_threads(24)
for(size_t i=0;i<max_box_pair_count;i+=1){
double local_rho[node_end[i]-node_begin[i]];
for(size_t ii=0;ii<node_end[i]-node_begin[i];ii+=1)
local_rho[ii] = 0.;
compute_density_3d_chunk_noomp_shift(node_begin[i],node_end[i],nb_begin[i],nb_end[i],
h,lsph->x,lsph->y,lsph->z,lsph->nu,local_rho);
#pragma omp critical
{
for(size_t ii=node_begin[i];ii<node_end[i];ii+=1)
lsph->rho[ii] += local_rho[ii - node_begin[i]];
}
}
free(node_begin);
free(node_end);
free(nb_begin);
free(nb_end);
//for(int64_t i=0;i<N;i+=1000)
// printf("%ld - %lf\n",i,lsph->rho[i]);
return 0;
}
/*******************************************************************/
/*******************************************************************/
/*
Pit from hell
*/
int compute_density_3d_chunk_symmetrical(int64_t node_begin, int64_t node_end,
int64_t nb_begin, int64_t nb_end,double h,
double* restrict x, double* restrict y,
double* restrict z, double* restrict nu,
double* restrict rhoi, double* restrict rhoj){
const double inv_h = 1./h;
for(int64_t ii=node_begin;ii<node_end;ii+=1){
double xii = x[ii];
double yii = y[ii];
double zii = z[ii];
#pragma omp simd
for(int64_t jj=nb_begin;jj<nb_end;jj+=1){
double q = 0.;
double xij = xii-x[jj];
double yij = yii-y[jj];
double zij = zii-z[jj];
q += xij*xij;
q += yij*yij;
q += zij*zij;
q = sqrt(q)*inv_h;
double wij = w_bspline_3d_simd(q);
rhoi[ii-node_begin] += nu[jj]*wij;
rhoj[jj-nb_begin] += nu[ii]*wij;
}
}
return 0;
}
#define min(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a < _b ? _a : _b; })
int compute_density_3d_chunk_symm_nlo(int64_t node_begin, int64_t node_end,
int64_t nb_begin, int64_t nb_end,double h,
double* restrict x, double* restrict y,
double* restrict z, double* restrict nu,
double* restrict rhoi, double* restrict rhoj){
const int64_t STRIP=512;
const double inv_h = 1./h;
/*
for(int64_t ii=node_begin;ii<node_end;ii+=1){
#pragma omp simd
for(int64_t jj=nb_begin;jj<nb_end;jj+=1){
double q = 0.;
double xii = x[ii];
double yii = y[ii];
double zii = z[ii];
double xij = xii-x[jj];
double yij = yii-y[jj];
double zij = zii-z[jj];
q += xij*xij;
q += yij*yij;
q += zij*zij;
q = sqrt(q)*inv_h;
double wij = w_bspline_3d_simd(q);
rhoi[ii-node_begin] += nu[jj]*wij;
rhoj[jj-nb_begin] += nu[ii]*wij;
}
}*/
for(int64_t i=0;i<(node_end-node_begin);i+=STRIP)
for(int64_t j=0;j<( nb_end - nb_begin );j+=STRIP)
for(int64_t ii=i;ii<min(node_end-node_begin,i+STRIP);ii+=1)
#pragma omp simd
for(int64_t jj=j;jj<min( nb_end - nb_begin ,j+STRIP);jj+=1){
double q = 0.;
double xij = x[ii+node_begin]-x[jj+nb_begin];
double yij = y[ii+node_begin]-y[jj+nb_begin];
double zij = z[ii+node_begin]-z[jj+nb_begin];
q += xij*xij;
q += yij*yij;
q += zij*zij;
q = sqrt(q)*inv_h;
double wij = w_bspline_3d_simd(q);
rhoi[ii] += nu[jj + nb_begin]*wij;
rhoj[jj] += nu[ii+node_begin]*wij;
}
return 0;
}
int compute_density_3d_chunk_symm_colapse(int64_t node_begin, int64_t node_end,
int64_t nb_begin, int64_t nb_end,double h,
double* restrict x, double* restrict y,
double* restrict z, double* restrict nu,
double* restrict rhoi, double* restrict rhoj){
const double inv_h = 1./h;
#pragma omp simd
for(int64_t ii=node_begin;ii<node_end;ii+=1){
for(int64_t jj=nb_begin;jj<nb_end;jj+=1){
double q = 0.;
double xij = x[ii]-x[jj];
double yij = y[ii]-y[jj];
double zij = z[ii]-z[jj];
q += xij*xij;
q += yij*yij;
q += zij*zij;
q = sqrt(q)*inv_h;
double wij = w_bspline_3d_simd(q);
rhoi[ii-node_begin] += nu[jj]*wij;
rhoj[jj-nb_begin] += nu[ii]*wij;
}
}
return 0;
}
int cpr_int64_t(const void *a, const void *b){
return ( *(int64_t*)a - *(int64_t*)b );
}
int unique_box_bounds(int64_t max_box_pair_count,
int64_t *node_begin, int64_t *node_end,
int64_t *nb_begin, int64_t *nb_end)
{
int64_t box_skip=0;
if(node_begin==NULL || node_end==NULL || nb_begin==NULL || nb_end==NULL)
return -1;
for(int64_t i=0;i<max_box_pair_count;i+=1){
if(node_begin[i]>=0){
for(int64_t j=i+1;j<max_box_pair_count;j+=1){
if((node_begin[j]==nb_begin[i]) && (nb_begin[j]==node_begin[i]) ){
node_begin[j] = -1; node_end[j] = -1;
nb_begin[j] = -1; nb_end[j] = -1;
//node_begin[j] -= -1; node_end[j] -= -1;
//nb_begin[j] -= -1; nb_end[j] -= -1;
box_skip += 1;
}
}
}
}
//qsort(node_begin,max_box_pair_count, sizeof(int64_t),cpr_int64_t);
//qsort(node_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t);
//qsort(nb_begin ,max_box_pair_count, sizeof(int64_t),cpr_int64_t);
//qsort(nb_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t);
/*
if(node_begin[i]<=nb_begin[i]){
box_keep +=1;
}
qsort(node_begin,max_box_pair_count, sizeof(int64_t),cpr_int64_t);
qsort(node_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t);
qsort(nb_begin ,max_box_pair_count, sizeof(int64_t),cpr_int64_t);
qsort(nb_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t);
max_box_pair_count = box_keep; //max_box_pair_count - box_subtract;
for(int64_t i=0;i<max_box_pair_count;i+=1){
node_begin[i] *= -1; node_end[i] *= -1;
nb_begin[i] *= -1; nb_end[i] *= -1;
}
qsort(node_begin,max_box_pair_count, sizeof(int64_t),cpr_int64_t);
qsort(node_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t);
qsort(nb_begin ,max_box_pair_count, sizeof(int64_t),cpr_int64_t);
qsort(nb_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t);*/
return box_skip;
}
int setup_unique_box_pairs(linkedListBox *box,
int64_t *node_begin,int64_t *node_end,
int64_t *nb_begin,int64_t *nb_end)
{
int64_t pair_count = 0;
for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){
int res;
int64_t node_hash=-1;
int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)];
if (kh_exist(box->hbegin, kbegin)){ // I have to call this!
khint32_t kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin));
node_hash = kh_key(box->hbegin, kbegin);
res = neighbour_hash_3d(node_hash,nblist,box->width,box);
for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){
if(nblist[j]>=0){
//nb_hash = nblist[j];
if(kh_value(box->hbegin, kbegin) <= kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) ))
{
node_begin[pair_count] = kh_value(box->hbegin, kbegin);
node_end[pair_count] = kh_value(box->hend, kend);
nb_begin[pair_count] = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) );
nb_end[pair_count] = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) );
pair_count += 1;//(node_end-node_begin)*(nb_end-nb_begin);
}
}
}
}
//printf("thread %d - %lf %lf\n",i,lsph->rho[node_begin],lsph->rho[node_end-1]);
}
return pair_count;
}
int compute_density_3d_symmetrical_load_ballance(int N, double h, SPHparticle *lsph, linkedListBox *box){
int64_t *node_begin,*node_end,*nb_begin,*nb_end;
int64_t max_box_pair_count = 0, particle_pair_count = 0;
int64_t box_skip = 0;
const double kernel_constant = w_bspline_3d_constant(h);
max_box_pair_count = count_box_pairs(box);
printf("max_box_pair_count = %ld\n",max_box_pair_count);
node_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t));
node_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t));
nb_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t));
nb_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t));
max_box_pair_count = setup_unique_box_pairs(box,node_begin,node_end,nb_begin,nb_end);//setup_box_pairs(box,node_begin,node_end,nb_begin,nb_end);
printf("unique max_box_pair_count = %ld\n",max_box_pair_count);
double avg_nb_len = 0.0;
for(int64_t i=0;i<max_box_pair_count;i+=1)
avg_nb_len += (nb_end[i]-nb_begin[i]);
avg_nb_len /= max_box_pair_count;
printf("avg_nb_len = %lf\n",avg_nb_len);
for(int64_t i=0;i<max_box_pair_count;i+=1)
particle_pair_count += (node_end[i]-node_begin[i])*(nb_end[i]-nb_begin[i]);
printf("unique unordered particle_pair_count = %ld\n",particle_pair_count);
//box_skip = unique_box_bounds(max_box_pair_count,node_begin,node_end,nb_begin,nb_end);
for(int64_t ii=0;ii<N;ii+=1)
lsph->rho[ii] = 0.0;
#pragma omp parallel for schedule(dynamic,5) proc_bind(master)
for(size_t i=0;i<max_box_pair_count;i+=1){
double local_rhoi[node_end[i] - node_begin[i]];
double local_rhoj[ nb_end[i] - nb_begin[i]];
for(size_t ii=0;ii<node_end[i]-node_begin[i];ii+=1)
local_rhoi[ii] = 0.;
for(size_t ii=0;ii<nb_end[i]-nb_begin[i];ii+=1)
local_rhoj[ii] = 0.;
compute_density_3d_chunk_symmetrical(node_begin[i],node_end[i],nb_begin[i],nb_end[i],h,
lsph->x,lsph->y,lsph->z,lsph->nu,local_rhoi,local_rhoj);
//compute_density_3d_chunk_symm_nlo(node_begin[i],node_end[i],nb_begin[i],nb_end[i],h,
// lsph->x,lsph->y,lsph->z,lsph->nu,local_rhoi,local_rhoj);
//compute_density_3d_chunk_symm_colapse(node_begin[i],node_end[i],nb_begin[i],nb_end[i],h,
// lsph->x,lsph->y,lsph->z,lsph->nu,local_rhoi,local_rhoj);
#pragma omp critical
{
for(size_t ii=node_begin[i];ii<node_end[i];ii+=1){
lsph->rho[ii] += kernel_constant*local_rhoi[ii - node_begin[i]];
}
if(node_begin[i] != nb_begin[i])
for(size_t ii=nb_begin[i];ii<nb_end[i];ii+=1){
lsph->rho[ii] += kernel_constant*local_rhoj[ii - nb_begin[i]];
}
}
}
free(node_begin);
free(node_end);
free(nb_begin);
free(nb_end);
return 0;
}
int compute_density_3d_symmetrical_lb_branching(int N, double h, SPHparticle *lsph, linkedListBox *box){
int64_t *node_begin,*node_end,*nb_begin,*nb_end;
int64_t max_box_pair_count = 0, particle_pair_count = 0;
int64_t box_skip = 0;
const double kernel_constant = w_bspline_3d_constant(h);
max_box_pair_count = count_box_pairs(box);
printf("max_box_pair_count = %ld\n",max_box_pair_count);
node_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t));
node_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t));
nb_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t));
nb_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t));
max_box_pair_count = setup_box_pairs(box,node_begin,node_end,nb_begin,nb_end);
box_skip = unique_box_bounds(max_box_pair_count,node_begin,node_end,nb_begin,nb_end);
for(int64_t i=0;i<max_box_pair_count;i+=1)
if(node_end[i] >= 0)
particle_pair_count += (node_end[i]-node_begin[i])*(nb_end[i]-nb_begin[i]);
printf("unique unordered particle_pair_count = %ld\n",particle_pair_count);
for(int64_t ii=0;ii<N;ii+=1)
lsph->rho[ii] = 0.0;
#pragma omp parallel for
for(size_t i=0;i<max_box_pair_count;i+=1){
if(node_end[i]<0)
continue;
double local_rhoi[node_end[i] - node_begin[i]];
double local_rhoj[ nb_end[i] - nb_begin[i]];
for(size_t ii=0;ii<node_end[i]-node_begin[i];ii+=1)
local_rhoi[ii] = 0.;
for(size_t ii=0;ii<nb_end[i]-nb_begin[i];ii+=1)
local_rhoj[ii] = 0.;
compute_density_3d_chunk_symmetrical(node_begin[i],node_end[i],nb_begin[i],nb_end[i],h,
lsph->x,lsph->y,lsph->z,lsph->nu,local_rhoi,local_rhoj);
#pragma omp critical
{
for(size_t ii=node_begin[i];ii<node_end[i];ii+=1)
lsph->rho[ii] += kernel_constant*local_rhoi[ii - node_begin[i]];
if(node_begin[i] != nb_begin[i])
for(size_t ii=nb_begin[i];ii<nb_end[i];ii+=1)
lsph->rho[ii] += kernel_constant*local_rhoj[ii - nb_begin[i]];
/*
if(node_begin[i]!=nb_begin[i])
for(size_t ii=nb_begin[i];ii<nb_end[i];ii+=1)
lsph->rho[ii] += kernel_constant*local_rhoj[ii - nb_begin[i]];*/
}
}
free(node_begin);
free(node_end);
free(nb_begin);
free(nb_end);
return 0;
}
/*******************************************************************/
/*******************************************************************/
/*
int compute_density_3d_chunk_symmetrical(int64_t node_begin, int64_t node_end,
int64_t nb_begin, int64_t nb_end,double h,
double* restrict x, double* restrict y,
double* restrict z, double* restrict nu,
double* restrict rho)
{
const double inv_h = 1./h;
const double kernel_constant = w_bspline_3d_constant(h);
double rhoi[node_end-node_begin];
double rhoj[nb_end-nb_begin];
for(int64_t ii=0;ii<node_end-node_begin;ii+=1)
rhoi[ii] = 0.;
for(int64_t jj=0;jj<nb_end-nb_begin;jj+=1)
rhoj[jj] = 0.;
for(int64_t ii=node_begin;ii<node_end;ii+=1){
double xii = x[ii];
double yii = y[ii];
double zii = z[ii];
#pragma omp simd
for(int64_t jj=nb_begin;jj<nb_end;jj+=1){
double q = 0.;
double xij = xii-x[jj];
double yij = yii-y[jj];
double zij = zii-z[jj];
q += xij*xij;
q += yij*yij;
q += zij*zij;
q = sqrt(q)*inv_h;
double wij = w_bspline_3d_simd(q);
rhoi[ii-node_begin] += nu[jj]*wij;
rhoj[jj-nb_begin] += nu[ii]*wij;
}
}
for(int64_t ii=node_begin;ii<node_end;ii+=1)
rho[ii] += rhoi[ii-node_begin]*kernel_constant;
if(nb_begin == node_begin)
return 0;
for(int64_t jj=nb_begin;jj<nb_end;jj+=1)
rho[jj] += rhoj[jj-nb_begin]*kernel_constant;
return 0;
}*/
/*
int cpr_int64_t(const void *a, const void *b){
return ( *(int64_t*)a - *(int64_t*)b );
} */
/*
int unique_box_bounds(int64_t max_box_pair_count,
int64_t *node_begin, int64_t *node_end,
int64_t *nb_begin, int64_t *nb_end)
{
int64_t box_keep=0;
if(node_begin==NULL || node_end==NULL || nb_begin==NULL || nb_end==NULL)
return -1;
for(int64_t i=0;i<max_box_pair_count;i+=1)
if(node_begin[i]<=nb_begin[i]){
node_begin[i] *= -1; node_end[i] *= -1;
nb_begin[i] *= -1; nb_end[i] *= -1;
box_keep +=1;
}
qsort(node_begin,max_box_pair_count, sizeof(int64_t),cpr_int64_t);
qsort(node_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t);
qsort(nb_begin ,max_box_pair_count, sizeof(int64_t),cpr_int64_t);
qsort(nb_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t);
max_box_pair_count = box_keep; //max_box_pair_count - box_subtract;
for(int64_t i=0;i<max_box_pair_count;i+=1){
node_begin[i] *= -1; node_end[i] *= -1;
nb_begin[i] *= -1; nb_end[i] *= -1;
}
qsort(node_begin,max_box_pair_count, sizeof(int64_t),cpr_int64_t);
qsort(node_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t);
qsort(nb_begin ,max_box_pair_count, sizeof(int64_t),cpr_int64_t);
qsort(nb_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t);
return max_box_pair_count;
}
int compute_density_3d_symmetrical_lb(int N, double h, SPHparticle *lsph, linkedListBox *box){
int64_t *node_begin,*node_end,*nb_begin,*nb_end;
int64_t max_box_pair_count = 0;
max_box_pair_count = count_box_pairs(box);
node_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t));
node_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t));
nb_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t));
nb_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t));
setup_box_pairs(box,node_begin,node_end,nb_begin,nb_end);
max_box_pair_count = unique_box_bounds(max_box_pair_count,node_begin,node_end,nb_begin,nb_end);
for(int64_t ii=0;ii<N;ii+=1)
lsph->rho[ii] = 0.0;
#pragma omp parallel for num_threads(24)
for(size_t i=0;i<max_box_pair_count;i+=1){
if(node_begin[i] > nb_begin[i])
continue;
compute_density_3d_chunk_symmetrical(node_begin[i],node_end[i],nb_begin[i],nb_end[i],
h,lsph->x,lsph->y,lsph->z,lsph->nu,lsph->rho);
}
free(node_begin);
free(node_end);
free(nb_begin);
free(nb_end);
//for(int64_t i=0;i<N;i+=1000)
// printf("%ld - %lf\n",i,lsph->rho[i]);
return 0;
}*/
/*******************************************************************/
/*******************************************************************/
/*******************************************************************/
#pragma omp declare simd
double pressure_from_density(double rho){
double p = cbrt(rho);
p = 0.5*p*rho;
return p;
}
#pragma omp declare simd
double gamma_from_u(double ux,double uy,double uz){
double gamma = 1.0;
gamma += ux*ux;
gamma += uy*uy;
gamma += uz*uz;
gamma = sqrt(gamma);
return gamma;
}
/*
int compute_force_3d(int N, double h, SPHparticle *lsph, linkedListBox *box){
int err, res;
double dist = 0.0;
khiter_t kbegin,kend;
int64_t node_hash=-1,node_begin=0, node_end=0;
int64_t nb_hash=-1 , nb_begin= 0, nb_end = 0;
int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)];
for (kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){
if (kh_exist(box->hbegin, kbegin)){
kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin));
node_hash = kh_key(box->hbegin, kbegin);
node_begin = kh_value(box->hbegin, kbegin);
node_end = kh_value(box->hend, kend);
for(int64_t ii=node_begin;ii<node_end;ii+=1)// this loop inside was the problem
lsph->rho[ii] = 0.0;
res = neighbour_hash_3d(node_hash,nblist,box->width,box);
for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){
if(nblist[j]>=0){
nb_hash = nblist[j];
nb_begin = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) );
nb_end = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) );
for(int64_t ii=node_begin;ii<node_end;ii+=1){ // this loop inside was the problem
for(int64_t jj=nb_begin;jj<nb_end;jj+=1){
dist = distance_3d(lsph->x[i],lsph->y[i],lsph->z[i],
lsph->x[j],lsph->y[j],lsph->z[j]);
lsph->rho[ii] += (lsph->nu[jj])*(box->w(dist,h));
}
}
}
}
}
}
return 0;
} */
/*
int compute_force_3d(int N, double h, SPHparticle *lsph, linkedListBox *box){
int err, res;
double dist = 0.0;
khiter_t kbegin,kend;
int64_t node_hash=-1,node_begin=0, node_end=0;
int64_t nb_hash=-1 , nb_begin= 0, nb_end = 0;
int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)];
for (kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){
if (kh_exist(box->hbegin, kbegin)){
kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin));
node_hash = kh_key(box->hbegin, kbegin);
node_begin = kh_value(box->hbegin, kbegin);
node_end = kh_value(box->hend, kend);
for(int64_t ii=node_begin;ii<node_end;ii+=1){
lsph[ii].F.x = 0.0;
lsph[ii].F.y = 0.0;
lsph[ii].F.z = 0.0;
}
res = neighbour_hash_3d(node_hash,nblist,box->width,box);
for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){
if(nblist[j]>=0){
nb_hash = nblist[j];
nb_begin = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) );
nb_end = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) );
for(int64_t ii=node_begin;ii<node_end;ii+=1){ // this loop inside was the problem
for(int64_t jj=nb_begin;jj<nb_end;jj+=1){
dist = double4_distance_3d(&(lsph[ii].r),&(lsph[jj].r));
= ();
lsph[ii].F.x += ((lsph[ii].r.x-lsph[jj].r.x)/dist);
lsph[ii].F.y += ;
lsph[ii].F.z += ;
}
}
}
}
}
}
return 0;
}
*/
const double fk_bspline_32[32] = {
6.66666667e-01, 6.57754579e-01, 6.32830944e-01, 5.94614705e-01,
5.45824802e-01, 4.89180177e-01, 4.27399774e-01, 3.63202533e-01,
2.99307397e-01, 2.38433308e-01, 1.83299207e-01, 1.36445011e-01,
9.83294731e-02, 6.80686561e-02, 4.47562463e-02, 2.74859298e-02,
1.53513925e-02, 7.44632048e-03, 2.86439976e-03, 6.99316348e-04,
4.47562463e-05, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00};
const double fk_bspline_128[128] = {
6.66666667e-01, 6.66115256e-01, 6.64487387e-01, 6.61822602e-01,
6.58160445e-01, 6.53540459e-01, 6.48002188e-01, 6.41585176e-01,
6.34328964e-01, 6.26273098e-01, 6.17457119e-01, 6.07920573e-01,
5.97703001e-01, 5.86843948e-01, 5.75382957e-01, 5.63359570e-01,
5.50813333e-01, 5.37783787e-01, 5.24310476e-01, 5.10432945e-01,
4.96190735e-01, 4.81623391e-01, 4.66770456e-01, 4.51671473e-01,
4.36365986e-01, 4.20893537e-01, 4.05293671e-01, 3.89605931e-01,
3.73869861e-01, 3.58125002e-01, 3.42410900e-01, 3.26767097e-01,
3.11233137e-01, 2.95848563e-01, 2.80652918e-01, 2.65685747e-01,
2.50986591e-01, 2.36594995e-01, 2.22550503e-01, 2.08892657e-01,
1.95661000e-01, 1.82895077e-01, 1.70634431e-01, 1.58916000e-01,
1.47746458e-01, 1.37112949e-01, 1.27002291e-01, 1.17401303e-01,
1.08296805e-01, 9.96756140e-02, 9.15245505e-02, 8.38304328e-02,
7.65800797e-02, 6.97603101e-02, 6.33579430e-02, 5.73597971e-02,
5.17526914e-02, 4.65234448e-02, 4.16588760e-02, 3.71458040e-02,
3.29710476e-02, 2.91214257e-02, 2.55837572e-02, 2.23448610e-02,
1.93915558e-02, 1.67106607e-02, 1.42889945e-02, 1.21133759e-02,
1.01706240e-02, 8.44755758e-03, 6.93099549e-03, 5.60775662e-03,
4.46465985e-03, 3.48852404e-03, 2.66616806e-03, 1.98441079e-03,
1.43007110e-03, 9.89967859e-04, 6.50919937e-04, 3.99746206e-04,
2.23265538e-04, 1.08296805e-04, 4.16588760e-05, 1.01706240e-05,
6.50919937e-07, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00};
const double fk_bspline_1024[1024] = {
6.66666667e-01, 6.66658079e-01, 6.66632368e-01, 6.66589608e-01,
6.66529876e-01, 6.66453246e-01, 6.66359796e-01, 6.66249599e-01,
6.66122732e-01, 6.65979271e-01, 6.65819291e-01, 6.65642868e-01,
6.65450077e-01, 6.65240994e-01, 6.65015696e-01, 6.64774257e-01,
6.64516753e-01, 6.64243260e-01, 6.63953853e-01, 6.63648609e-01,
6.63327602e-01, 6.62990909e-01, 6.62638605e-01, 6.62270765e-01,
6.61887466e-01, 6.61488783e-01, 6.61074792e-01, 6.60645569e-01,
6.60201188e-01, 6.59741726e-01, 6.59267259e-01, 6.58777861e-01,
6.58273610e-01, 6.57754579e-01, 6.57220846e-01, 6.56672485e-01,
6.56109573e-01, 6.55532184e-01, 6.54940396e-01, 6.54334282e-01,
6.53713920e-01, 6.53079384e-01, 6.52430750e-01, 6.51768095e-01,
6.51091493e-01, 6.50401020e-01, 6.49696752e-01, 6.48978765e-01,
6.48247134e-01, 6.47501935e-01, 6.46743244e-01, 6.45971135e-01,
6.45185686e-01, 6.44386971e-01, 6.43575066e-01, 6.42750048e-01,
6.41911990e-01, 6.41060970e-01, 6.40197063e-01, 6.39320344e-01,
6.38430889e-01, 6.37528774e-01, 6.36614075e-01, 6.35686866e-01,
6.34747225e-01, 6.33795226e-01, 6.32830944e-01, 6.31854457e-01,
6.30865839e-01, 6.29865166e-01, 6.28852514e-01, 6.27827959e-01,
6.26791575e-01, 6.25743439e-01, 6.24683626e-01, 6.23612213e-01,
6.22529274e-01, 6.21434885e-01, 6.20329123e-01, 6.19212062e-01,
6.18083778e-01, 6.16944347e-01, 6.15793845e-01, 6.14632348e-01,
6.13459930e-01, 6.12276668e-01, 6.11082637e-01, 6.09877913e-01,
6.08662571e-01, 6.07436688e-01, 6.06200339e-01, 6.04953599e-01,
6.03696545e-01, 6.02429251e-01, 6.01151794e-01, 5.99864249e-01,
5.98566692e-01, 5.97259199e-01, 5.95941844e-01, 5.94614705e-01,
5.93277856e-01, 5.91931373e-01, 5.90575332e-01, 5.89209808e-01,
5.87834877e-01, 5.86450616e-01, 5.85057098e-01, 5.83654401e-01,
5.82242599e-01, 5.80821769e-01, 5.79391986e-01, 5.77953326e-01,
5.76505864e-01, 5.75049676e-01, 5.73584838e-01, 5.72111425e-01,
5.70629514e-01, 5.69139179e-01, 5.67640496e-01, 5.66133541e-01,
5.64618390e-01, 5.63095118e-01, 5.61563801e-01, 5.60024515e-01,
5.58477335e-01, 5.56922337e-01, 5.55359597e-01, 5.53789190e-01,
5.52211192e-01, 5.50625678e-01, 5.49032725e-01, 5.47432408e-01,
5.45824802e-01, 5.44209983e-01, 5.42588027e-01, 5.40959010e-01,
5.39323007e-01, 5.37680094e-01, 5.36030346e-01, 5.34373840e-01,
5.32710650e-01, 5.31040853e-01, 5.29364524e-01, 5.27681738e-01,
5.25992573e-01, 5.24297102e-01, 5.22595402e-01, 5.20887548e-01,
5.19173617e-01, 5.17453683e-01, 5.15727823e-01, 5.13996112e-01,
5.12258626e-01, 5.10515440e-01, 5.08766630e-01, 5.07012271e-01,
5.05252441e-01, 5.03487213e-01, 5.01716663e-01, 4.99940869e-01,
4.98159904e-01, 4.96373845e-01, 4.94582767e-01, 4.92786746e-01,
4.90985857e-01, 4.89180177e-01, 4.87369781e-01, 4.85554745e-01,
4.83735144e-01, 4.81911054e-01, 4.80082550e-01, 4.78249708e-01,
4.76412605e-01, 4.74571315e-01, 4.72725914e-01, 4.70876478e-01,
4.69023083e-01, 4.67165804e-01, 4.65304717e-01, 4.63439897e-01,
4.61571420e-01, 4.59699362e-01, 4.57823799e-01, 4.55944806e-01,
4.54062459e-01, 4.52176833e-01, 4.50288004e-01, 4.48396048e-01,
4.46501040e-01, 4.44603057e-01, 4.42702173e-01, 4.40798465e-01,
4.38892008e-01, 4.36982877e-01, 4.35071149e-01, 4.33156899e-01,
4.31240203e-01, 4.29321136e-01, 4.27399774e-01, 4.25476193e-01,
4.23550468e-01, 4.21622675e-01, 4.19692890e-01, 4.17761188e-01,
4.15827645e-01, 4.13892336e-01, 4.11955338e-01, 4.10016726e-01,
4.08076576e-01, 4.06134962e-01, 4.04191962e-01, 4.02247650e-01,
4.00302103e-01, 3.98355395e-01, 3.96407603e-01, 3.94458803e-01,
3.92509069e-01, 3.90558477e-01, 3.88607104e-01, 3.86655025e-01,
3.84702315e-01, 3.82749050e-01, 3.80795307e-01, 3.78841159e-01,
3.76886684e-01, 3.74931957e-01, 3.72977053e-01, 3.71022048e-01,
3.69067018e-01, 3.67112038e-01, 3.65157185e-01, 3.63202533e-01,
3.61248159e-01, 3.59294138e-01, 3.57340545e-01, 3.55387457e-01,
3.53434949e-01, 3.51483097e-01, 3.49531976e-01, 3.47581662e-01,
3.45632230e-01, 3.43683758e-01, 3.41736319e-01, 3.39789989e-01,
3.37844845e-01, 3.35900962e-01, 3.33958416e-01, 3.32017282e-01,
3.30077636e-01, 3.28139553e-01, 3.26203110e-01, 3.24268382e-01,
3.22335444e-01, 3.20404373e-01, 3.18475243e-01, 3.16548131e-01,
3.14623112e-01, 3.12700262e-01, 3.10779657e-01, 3.08861372e-01,
3.06945483e-01, 3.05032065e-01, 3.03121194e-01, 3.01212946e-01,
2.99307397e-01, 2.97404622e-01, 2.95504697e-01, 2.93607697e-01,
2.91713698e-01, 2.89822776e-01, 2.87935006e-01, 2.86050465e-01,
2.84169227e-01, 2.82291369e-01, 2.80416966e-01, 2.78546093e-01,
2.76678827e-01, 2.74815243e-01, 2.72955417e-01, 2.71099424e-01,
2.69247340e-01, 2.67399241e-01, 2.65555202e-01, 2.63715299e-01,
2.61879608e-01, 2.60048204e-01, 2.58221163e-01, 2.56398561e-01,
2.54580473e-01, 2.52766975e-01, 2.50958142e-01, 2.49154051e-01,
2.47354777e-01, 2.45560395e-01, 2.43770982e-01, 2.41986612e-01,
2.40207362e-01, 2.38433308e-01, 2.36664524e-01, 2.34901086e-01,
2.33143071e-01, 2.31390554e-01, 2.29643610e-01, 2.27902316e-01,
2.26166746e-01, 2.24436977e-01, 2.22713084e-01, 2.20995143e-01,
2.19283229e-01, 2.17577418e-01, 2.15877786e-01, 2.14184409e-01,
2.12497361e-01, 2.10816720e-01, 2.09142560e-01, 2.07474956e-01,
2.05813986e-01, 2.04159724e-01, 2.02512246e-01, 2.00871628e-01,
1.99237945e-01, 1.97611273e-01, 1.95991688e-01, 1.94379265e-01,
1.92774080e-01, 1.91176209e-01, 1.89585728e-01, 1.88002711e-01,
1.86427235e-01, 1.84859375e-01, 1.83299207e-01, 1.81746806e-01,
1.80202249e-01, 1.78665611e-01, 1.77136968e-01, 1.75616394e-01,
1.74103967e-01, 1.72599761e-01, 1.71103853e-01, 1.69616317e-01,
1.68137230e-01, 1.66666667e-01, 1.65204687e-01, 1.63751281e-01,
1.62306426e-01, 1.60870094e-01, 1.59442261e-01, 1.58022902e-01,
1.56611992e-01, 1.55209505e-01, 1.53815416e-01, 1.52429700e-01,
1.51052331e-01, 1.49683285e-01, 1.48322536e-01, 1.46970060e-01,
1.45625830e-01, 1.44289821e-01, 1.42962009e-01, 1.41642368e-01,
1.40330873e-01, 1.39027499e-01, 1.37732220e-01, 1.36445011e-01,
1.35165848e-01, 1.33894704e-01, 1.32631555e-01, 1.31376375e-01,
1.30129139e-01, 1.28889822e-01, 1.27658399e-01, 1.26434845e-01,
1.25219133e-01, 1.24011240e-01, 1.22811140e-01, 1.21618807e-01,
1.20434217e-01, 1.19257343e-01, 1.18088162e-01, 1.16926648e-01,
1.15772775e-01, 1.14626518e-01, 1.13487852e-01, 1.12356752e-01,
1.11233193e-01, 1.10117149e-01, 1.09008596e-01, 1.07907507e-01,
1.06813859e-01, 1.05727624e-01, 1.04648779e-01, 1.03577299e-01,
1.02513157e-01, 1.01456328e-01, 1.00406788e-01, 9.93645117e-02,
9.83294731e-02, 9.73016473e-02, 9.62810090e-02, 9.52675330e-02,
9.42611942e-02, 9.32619673e-02, 9.22698271e-02, 9.12847483e-02,
9.03067058e-02, 8.93356743e-02, 8.83716286e-02, 8.74145435e-02,
8.64643938e-02, 8.55211542e-02, 8.45847996e-02, 8.36553047e-02,
8.27326442e-02, 8.18167931e-02, 8.09077259e-02, 8.00054177e-02,
7.91098430e-02, 7.82209767e-02, 7.73387936e-02, 7.64632684e-02,
7.55943760e-02, 7.47320911e-02, 7.38763885e-02, 7.30272430e-02,
7.21846293e-02, 7.13485223e-02, 7.05188966e-02, 6.96957272e-02,
6.88789888e-02, 6.80686561e-02, 6.72647039e-02, 6.64671071e-02,
6.56758404e-02, 6.48908785e-02, 6.41121963e-02, 6.33397686e-02,
6.25735701e-02, 6.18135756e-02, 6.10597598e-02, 6.03120976e-02,
5.95705638e-02, 5.88351331e-02, 5.81057803e-02, 5.73824802e-02,
5.66652075e-02, 5.59539371e-02, 5.52486438e-02, 5.45493022e-02,
5.38558872e-02, 5.31683736e-02, 5.24867361e-02, 5.18109496e-02,
5.11409888e-02, 5.04768285e-02, 4.98184434e-02, 4.91658084e-02,
4.85188982e-02, 4.78776876e-02, 4.72421515e-02, 4.66122645e-02,
4.59880014e-02, 4.53693371e-02, 4.47562463e-02, 4.41487038e-02,
4.35466844e-02, 4.29501628e-02, 4.23591138e-02, 4.17735123e-02,
4.11933330e-02, 4.06185507e-02, 4.00491401e-02, 3.94850760e-02,
3.89263333e-02, 3.83728867e-02, 3.78247109e-02, 3.72817808e-02,
3.67440712e-02, 3.62115568e-02, 3.56842123e-02, 3.51620127e-02,
3.46449326e-02, 3.41329469e-02, 3.36260303e-02, 3.31241576e-02,
3.26273035e-02, 3.21354430e-02, 3.16485507e-02, 3.11666014e-02,
3.06895699e-02, 3.02174310e-02, 2.97501595e-02, 2.92877301e-02,
2.88301177e-02, 2.83772970e-02, 2.79292427e-02, 2.74859298e-02,
2.70473328e-02, 2.66134267e-02, 2.61841863e-02, 2.57595862e-02,
2.53396013e-02, 2.49242063e-02, 2.45133761e-02, 2.41070854e-02,
2.37053089e-02, 2.33080216e-02, 2.29151981e-02, 2.25268132e-02,
2.21428418e-02, 2.17632586e-02, 2.13880383e-02, 2.10171558e-02,
2.06505858e-02, 2.02883032e-02, 1.99302826e-02, 1.95764990e-02,
1.92269270e-02, 1.88815414e-02, 1.85403171e-02, 1.82032287e-02,
1.78702512e-02, 1.75413592e-02, 1.72165275e-02, 1.68957310e-02,
1.65789443e-02, 1.62661424e-02, 1.59572999e-02, 1.56523917e-02,
1.53513925e-02, 1.50542771e-02, 1.47610203e-02, 1.44715968e-02,
1.41859815e-02, 1.39041492e-02, 1.36260745e-02, 1.33517323e-02,
1.30810974e-02, 1.28141446e-02, 1.25508485e-02, 1.22911841e-02,
1.20351261e-02, 1.17826493e-02, 1.15337284e-02, 1.12883382e-02,
1.10464536e-02, 1.08080492e-02, 1.05731000e-02, 1.03415805e-02,
1.01134657e-02, 9.88873037e-03, 9.66734920e-03, 9.44929700e-03,
9.23454856e-03, 9.02307866e-03, 8.81486208e-03, 8.60987360e-03,
8.40808799e-03, 8.20948005e-03, 8.01402454e-03, 7.82169626e-03,
7.63246998e-03, 7.44632048e-03, 7.26322254e-03, 7.08315094e-03,
6.90608047e-03, 6.73198590e-03, 6.56084202e-03, 6.39262360e-03,
6.22730542e-03, 6.06486228e-03, 5.90526893e-03, 5.74850018e-03,
5.59453079e-03, 5.44333554e-03, 5.29488923e-03, 5.14916663e-03,
5.00614251e-03, 4.86579166e-03, 4.72808886e-03, 4.59300890e-03,
4.46052654e-03, 4.33061658e-03, 4.20325378e-03, 4.07841294e-03,
3.95606884e-03, 3.83619624e-03, 3.71876994e-03, 3.60376471e-03,
3.49115534e-03, 3.38091660e-03, 3.27302328e-03, 3.16745016e-03,
3.06417201e-03, 2.96316362e-03, 2.86439976e-03, 2.76785523e-03,
2.67350479e-03, 2.58132323e-03, 2.49128533e-03, 2.40336587e-03,
2.31753963e-03, 2.23378139e-03, 2.15206594e-03, 2.07236804e-03,
1.99466249e-03, 1.91892406e-03, 1.84512753e-03, 1.77324769e-03,
1.70325931e-03, 1.63513718e-03, 1.56885607e-03, 1.50439077e-03,
1.44171605e-03, 1.38080670e-03, 1.32163749e-03, 1.26418322e-03,
1.20841865e-03, 1.15431857e-03, 1.10185776e-03, 1.05101100e-03,
1.00175307e-03, 9.54058747e-04, 9.07902817e-04, 8.63260059e-04,
8.20105252e-04, 7.78413178e-04, 7.38158617e-04, 6.99316348e-04,
6.61861154e-04, 6.25767814e-04, 5.91011108e-04, 5.57565818e-04,
5.25406723e-04, 4.94508604e-04, 4.64846242e-04, 4.36394418e-04,
4.09127910e-04, 3.83021501e-04, 3.58049970e-04, 3.34188099e-04,
3.11410666e-04, 2.89692454e-04, 2.69008242e-04, 2.49332811e-04,
2.30640942e-04, 2.12907414e-04, 1.96107009e-04, 1.80214506e-04,
1.65204687e-04, 1.51052331e-04, 1.37732220e-04, 1.25219133e-04,
1.13487852e-04, 1.02513157e-04, 9.22698271e-05, 8.27326442e-05,
7.38763885e-05, 6.56758404e-05, 5.81057803e-05, 5.11409888e-05,
4.47562463e-05, 3.89263333e-05, 3.36260303e-05, 2.88301177e-05,
2.45133761e-05, 2.06505858e-05, 1.72165275e-05, 1.41859815e-05,
1.15337284e-05, 9.23454856e-06, 7.26322254e-06, 5.59453079e-06,
4.20325378e-06, 3.06417201e-06, 2.15206594e-06, 1.44171605e-06,
9.07902817e-07, 5.25406723e-07, 2.69008242e-07, 1.13487852e-07,
3.36260303e-08, 4.20325378e-09, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00};
|
thapi.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
#include "thnets.h"
static int lasterror;
static short TB_YUR[256], TB_YUB[256], TB_YUGU[256], TB_YUGV[256], TB_Y[256];
static unsigned char TB_SAT[1024 + 1024 + 256];
int th_debug, th_profile, th_minmax;
#ifdef CUDNN
int cuda_maphostmem;
#endif
#define BYTE2FLOAT 0.003921568f // 1/255
static void rgb2float(float *dst, const unsigned char *src, int width, int height, int srcstride, int cp, const float *mean, const float *std)
{
int c, i, j;
float std1[3];
for(i = 0; i < cp; i++)
std1[i] = 1 / std[i];
#pragma omp parallel for private(c, i, j)
for(c = 0; c < cp; c++)
for(i = 0; i < height; i++)
for(j = 0; j < width; j++)
dst[j + (i + c * height) * width] = (src[c + cp*j + srcstride*i] * BYTE2FLOAT - mean[c]) * std1[c];
}
static void bgr2float(float *dst, const unsigned char *src, int width, int height, int srcstride, int cp, const float *mean, const float *std)
{
int c, i, j;
float std1[3];
for(i = 0; i < cp; i++)
std1[i] = 1 / std[i];
#pragma omp parallel for private(c, i, j)
for(c = 0; c < cp; c++)
for(i = 0; i < height; i++)
for(j = 0; j < width; j++)
dst[j + (i + c * height) * width] = (src[cp-1-c + cp*j + srcstride*i] * BYTE2FLOAT - mean[c]) * std1[c];
}
static void init_yuv2rgb()
{
int i;
/* calculate lookup table for yuv420p */
for (i = 0; i < 256; i++) {
TB_YUR[i] = 459 * (i-128) / 256;
TB_YUB[i] = 541 * (i-128) / 256;
TB_YUGU[i] = -137 * (i-128) / 256;
TB_YUGV[i] = - 55 * (i-128) / 256;
TB_Y[i] = (i-16) * 298 / 256;
}
for (i = 0; i < 1024; i++) {
TB_SAT[i] = 0;
TB_SAT[i + 1024 + 256] = 255;
}
for (i = 0; i < 256; i++)
TB_SAT[i + 1024] = i;
}
static void yuyv2fRGB(const unsigned char *frame, float *dst_float, int imgstride, int rowstride, int w, int h, const float *mean, const float *std)
{
int i, j, w2 = w / 2, c;
float std0 = 1/std[0];
float std1 = 1/std[1];
float std2 = 1/std[2];
#pragma omp parallel for private(c, i, j)
for(c = 0; c < 3; c++)
{
float *dst;
const unsigned char *src;
if(c == 0)
{
/* convert for R channel */
src = frame;
for (i = 0; i < h; i++) {
dst = dst_float + i * rowstride;
for (j = 0; j < w2; j++) {
*dst++ = (TB_SAT[ TB_Y[ src[0] ] + TB_YUR[ src[3] ] + 1024] * BYTE2FLOAT - mean[0]) * std0;
*dst++ = (TB_SAT[ TB_Y[ src[2] ] + TB_YUR[ src[3] ] + 1024] * BYTE2FLOAT - mean[0]) * std0;
src += 4;
}
}
} else if(c == 1)
{
/* convert for G channel */
src = frame;
for (i = 0; i < h; i++) {
dst = dst_float + i * rowstride + imgstride;
for (j = 0; j < w2; j++) {
*dst++ = (TB_SAT[ TB_Y[ src[0] ] + TB_YUGU[ src[1] ] + TB_YUGV[ src[3] ] + 1024] * BYTE2FLOAT - mean[1]) * std1;
*dst++ = (TB_SAT[ TB_Y[ src[2] ] + TB_YUGU[ src[1] ] + TB_YUGV[ src[3] ] + 1024] * BYTE2FLOAT - mean[1]) * std1;
src += 4;
}
}
} else if(c == 2)
{
/* convert for B channel */
src = frame;
for (i = 0; i < h; i++) {
dst = dst_float + i * rowstride + 2*imgstride;
for (j = 0; j < w2; j++) {
*dst++ = (TB_SAT[ TB_Y[ src[0] ] + TB_YUB[ src[1] ] + 1024] * BYTE2FLOAT - mean[2]) * std2;
*dst++ = (TB_SAT[ TB_Y[ src[2] ] + TB_YUB[ src[1] ] + 1024] * BYTE2FLOAT - mean[2]) * std2;
src += 4;
}
}
}
}
}
double th_seconds()
{
static double s;
#ifdef __MACH__
struct timeval tv;
struct timezone tz;
gettimeofday(&tv, &tz);
if(!s)
s = tv.tv_sec + tv.tv_usec * 1e-6;
return tv.tv_sec + tv.tv_usec * 1e-6 - s;
#else
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
if(!s)
s = ts.tv_sec + ts.tv_nsec * 1e-9;
return ts.tv_sec + ts.tv_nsec * 1e-9 - s;
#endif
}
void FindMinMax(THFloatTensor *t, float *min, float *max)
{
*min = THInf;
*max = -THInf;
float *data = THFloatTensor_data(t);
long i, n = THFloatTensor_nElement(t);
for(i = 0; i < n; i++)
{
if(data[i] > *max)
*max = data[i];
if(data[i] < *min)
*min = data[i];
}
}
double th_convtot, th_convflops;
THFloatTensor *forward(struct network *net, THFloatTensor *in)
{
int i;
double t = 0;
th_convtot = 0;
th_convflops = 0;
#ifdef OPENCL
if(net->engine == ENGINE_OPENCL)
OpenCL_Build(net, in);
#endif
for(i = 0; i < net->nelem; i++)
{
if(th_profile)
t = th_seconds();
#ifdef ONNX
// In case of ONNX the network is not sequential, but each module has the list of inputs,
// which are guaranteed to have been already calculated
if(net->modules[i].ninputs == 1 && net->modules[i].type != MT_JoinTable)
in = net->modules[i].updateOutput(&net->modules[i], net->modules[net->modules[i].inputs[0]].output);
else if(net->modules[i].ninputs >= 1)
{
// Nodes with multiple inputs expect a module of type ConcatTable instead of THFloatTensor as their input
struct module modules[net->modules[i].ninputs];
struct network subnet;
struct module m;
int j;
for(j = 0; j < net->modules[i].ninputs; j++)
modules[j].output = net->modules[net->modules[i].inputs[j]].output;
subnet.nelem = net->modules[i].ninputs;
subnet.modules = modules;
subnet.engine = net->engine;
m.ConcatTable.net = &subnet;
in = net->modules[i].updateOutput(&net->modules[i], (THFloatTensor *)&m);
} else
#endif
in = net->modules[i].updateOutput(&net->modules[i], in);
// You can remove these lines if you don't have problems with memory
// These lines free intermediate results
if(th_minmax)
{
float min, max;
FindMinMax(in, &min, &max);
printf("Layer %d output: min=%f, max=%f\n", i+1, min, max);
}
#ifndef ONNX
// In case of ONNX we cannot free an output, as we can still need it
if(i > 0)
{
THFloatTensor_free(net->modules[i-1].output);
net->modules[i-1].output = THFloatTensor_new();
}
#endif
if(th_profile)
{
#ifdef OPENCL
if(net->engine == ENGINE_OPENCLINIT)
clFinish(cl_queue);
#endif
t = th_seconds() - t;
if(net->modules[i].type == MT_SpatialConvolutionMM ||
net->modules[i].type == MT_SpatialConvolutionVirtMM ||
net->modules[i].type == MT_SpatialConvolution)
{
double flops = 2.0 * THFloatTensor_nElement(in) * net->modules[i].SpatialConvolution.nInputPlane *
net->modules[i].SpatialConvolution.kW * net->modules[i].SpatialConvolution.kH;
printf("%f seconds for module %d, %f Gflops/s\n", t, i+1, flops * 1e-9 / t);
th_convtot += t;
th_convflops += flops;
} else printf("%f seconds for module %d\n", t, i+1);
}
if(th_debug > 1)
printf("%d) %d %d %ld %ld %ld %ld\n", i+1, net->modules[i].type, in->nDimension, in->size[0], in->size[1], in->size[2], in->size[3]);
}
if(th_profile)
printf("%f seconds for convolutions %f Gflops/s\n", th_convtot, th_convflops * 1e-9 / th_convtot);
return in;
}
THFloatTensor *THForward(THNETWORK *net, THFloatTensor *in)
{
if(net->pynet)
return forward_pytorch(net->pynet, in, net->allpynodes);
else return forward(net->net, in);
}
THNETWORK *THLoadNetwork(const char *path)
{
char tmppath[255];
int i, longsize = 8;
THNETWORK *net;
net = calloc(1, sizeof(*net));
net->std[0] = net->std[1] = net->std[2] = 1;
net->mean[0] = net->mean[1] = net->mean[2] = 0;
// Try ONNX
#ifdef ONNX
if(!strcasecmp(path + strlen(path) - 3, ".pb") || !strcasecmp(path + strlen(path) - 6, ".proto") ||
!strcasecmp(path + strlen(path) - 5, ".onnx"))
{
net->net = loadonnx(path);
if(net->net)
return net;
}
#endif
// Try pytorch
net->allpynodes = calloc(MAXPYNODES, sizeof(*net->allpynodes));
net->pynet = loadpytorch(path, net->allpynodes);
if(net->pynet)
return net;
sprintf(tmppath, "%s/pymodel.net", path);
net->pynet = loadpytorch(tmppath, net->allpynodes);
if(net->pynet)
return net;
free(net->allpynodes);
net->allpynodes = 0;
// Try torch
sprintf(tmppath, "%s/model.net", path);
net->netobj = malloc(sizeof(*net->netobj));
lasterror = loadtorch(tmppath, net->netobj, longsize);
if(lasterror == ERR_CORRUPTED)
lasterror = loadtorch(tmppath, net->netobj, longsize = 4);
if(lasterror)
{
free(net->netobj);
free(net);
return 0;
}
if(th_debug)
printobject(net->netobj, 0);
if(net->netobj->type != TYPE_NNMODULE)
{
free(net->netobj);
free(net);
return 0;
}
net->net = Module2Network(net->netobj->nnmodule);
if(!net->net)
{
lasterror = ERR_WRONGOBJECT;
freeobject(net->netobj);
free(net->netobj);
free(net);
return 0;
}
sprintf(tmppath, "%s/stat.t7", path);
net->statobj = malloc(sizeof(*net->statobj));
lasterror = loadtorch(tmppath, net->statobj, longsize);
if(!lasterror)
{
if(net->statobj->type != TYPE_TABLE || net->statobj->table->nelem != 2)
{
lasterror = ERR_WRONGOBJECT;
freenetwork(net->net);
freeobject(net->netobj);
free(net->netobj);
freeobject(net->statobj);
free(net->statobj);
free(net);
return 0;
}
for(i = 0; i < net->statobj->table->nelem; i++)
if(net->statobj->table->records[i].name.type == TYPE_STRING)
{
if(!strcmp(net->statobj->table->records[i].name.string.data, "mean"))
memcpy(net->mean, net->statobj->table->records[i].value.tensor->storage->data, sizeof(net->mean));
else if(!strcmp(net->statobj->table->records[i].name.string.data, "std"))
memcpy(net->std, net->statobj->table->records[i].value.tensor->storage->data, sizeof(net->std));
}
} else {
free(net->statobj);
net->statobj = 0;
}
THUseSpatialConvolutionMM(net, 2);
return net;
}
void THInit()
{
static int init;
if(init)
return;
init_yuv2rgb();
#ifndef USEBLAS
blas_init();
#endif
init = 1;
#if defined CUDNN && defined USECUDAHOSTALLOC
// cuda_maphostmem = 1 requires that memory was allocated with cudaHostAlloc
// cuda_maphostmem = 2 will work with malloc, but Tegra TX1 does not support cudaHostRegister with cudaHostRegisterMapped
struct cudaDeviceProp prop;
cudaGetDeviceProperties(&prop, 0);
if(prop.canMapHostMemory)
{
errcheck(cudaSetDeviceFlags(cudaDeviceMapHost));
cuda_maphostmem = 1;
}
#endif
#ifdef OPENCL
thopencl_init();
#endif
}
int THProcessFloat(THNETWORK *network, float *data, int batchsize, int width, int height, int nplanes, float **result, int *outwidth, int *outheight)
{
int b, c, i;
THFloatTensor *t = THFloatTensor_new();
THFloatTensor *out;
t->nDimension = 4;
t->size[0] = batchsize;
t->size[1] = nplanes;
t->size[2] = height;
t->size[3] = width;
#ifdef USEQSML
t->stride[0] = nplanes * width * height;//batch
t->stride[1] = 1;//plane
t->stride[2] = nplanes * width;//row
t->stride[3] = nplanes;//col
#else
t->stride[0] = nplanes * width * height;//batch
t->stride[1] = width * height;//plane
t->stride[2] = width;//row
t->stride[3] = 1;//col
#endif
t->storage = THFloatStorage_newwithbuffer((float *)data);
if(t->stride[1] == 1){//row major-plane minor
#pragma omp parallel for private(b, i, c)
for(b = 0; b < batchsize; b++)
for(i = 0; i < width*height; i++)
for(c = 0; c < nplanes; c++)
data[b * t->stride[0] + c + i * t->stride[3]] =
(data[b * t->stride[0] + c + i * t->stride[3]] - network->mean[c]) / network->std[c];
}
else{//plane major
#pragma omp parallel for private(b, c, i)
for(b = 0; b < batchsize; b++)
for(c = 0; c < nplanes; c++)
for(i = 0; i < width*height; i++)
data[b * t->stride[0] + c * t->stride[1] + i] =
(data[b * t->stride[0] + c * t->stride[1] + i] - network->mean[c]) / network->std[c];
}
#ifdef CUDNN
if(network->net->engine == ENGINE_CUDA)
{
THFloatTensor *t2 = THCudaTensor_newFromFloatTensor(t);
out = THForward(network, t2);
THFloatTensor_free(t2);
if(network->out)
THFloatTensor_free(network->out);
network->out = THFloatTensor_newFromCudaTensor(out);
out = network->out;
} else
#endif
#ifdef OPENCL
if(network->net->engine == ENGINE_OPENCL || network->net->engine == ENGINE_OPENCLINIT)
{
THFloatTensor *t2 = THOpenCLTensor_newFromImageTensor(t);
out = THForward(network, t2);
THFloatTensor_free(t2);
if(network->out)
THFloatTensor_free(network->out);
network->out = THFloatTensor_newFromOpenCLImageTensor(out);
out = network->out;
} else
#endif
#ifdef LOWP
if(network->net->engine == ENGINE_LOWP)
{
THFloatTensor *t2 = THLowpTensor_newFromFloatTensor(t);
out = THForward(network, t2);
THFloatTensor_free(t2);
if(network->out)
THFloatTensor_free(network->out);
network->out = THFloatTensor_newFromLowpTensor(out);
out = network->out;
} else
#endif
out = THForward(network, t);
THFloatTensor_free(t);
*result = out->storage->data;
if(out->nDimension >= 3)
{
*outwidth = (int)out->size[out->nDimension - 1];
*outheight = (int)out->size[out->nDimension - 2];
} else *outwidth = *outheight = 1;
return (int)THFloatTensor_nElement(out);
}
int THProcessImages(THNETWORK *network, unsigned char **images, int batchsize, int width, int height, int stride, float **results, int *outwidth, int *outheight, int bgr)
{
int i, cp = 3;
THFloatTensor *out, *t = 0;
THFloatStorage *st;
if(stride < width*3)
cp = 1; // Guess color planes, if stride is less than 3*width, it cannot be 3 color planes, so assume grayscale
#ifdef CUDNN
if(network->net->engine == ENGINE_CUDA)
{
#ifdef HAVEFP16
if(floattype == CUDNN_DATA_HALF)
{
st = THCudaStorage_new(batchsize * (width * height * cp));
for(i = 0; i < batchsize; i++)
cuda_rgb2half((unsigned short *)st->data + i * (width * height * cp), images[i], width, height, stride, network->mean, network->std, bgr);
} else
#endif
{
st = THCudaStorage_new(batchsize * width * height * cp);
for(i = 0; i < batchsize; i++)
cuda_rgb2float(st->data + i * width * height * cp, images[i], width, height, stride, network->mean, network->std, bgr);
}
} else
#endif
#ifdef OPENCL
if(network->net->engine == ENGINE_OPENCL || network->net->engine == ENGINE_OPENCLINIT)
t = OpenCL_LoadImage(images[0], width, height, stride, network->mean, network->std, bgr);
else
#endif
#ifdef LOWP
if(network->net->engine == ENGINE_LOWP)
t = Lowp_LoadImages(images, batchsize, width, height, stride, network->mean, network->std, bgr);
else
#endif
{
st = THFloatStorage_new(batchsize * width * height * cp);
if(bgr)
#pragma omp parallel for if(batchsize>1) private(i)
for(i = 0; i < batchsize; i++)
bgr2float(st->data + i * width * height * cp, images[i], width, height, stride, cp, network->mean, network->std);
else
#pragma omp parallel for if(batchsize>1) private(i)
for(i = 0; i < batchsize; i++)
rgb2float(st->data + i * width * height * cp, images[i], width, height, stride, cp, network->mean, network->std);
}
if(!t)
{
t = THFloatTensor_new();
t->storage = st;
if(batchsize == 1)
{
t->nDimension = 3;
t->size[0] = cp;
t->size[1] = height;
t->size[2] = width;
t->stride[0] = width * height;
t->stride[1] = width;
t->stride[2] = 1;
} else {
t->nDimension = 4;
t->size[0] = batchsize;
t->size[1] = cp;
t->size[2] = height;
t->size[3] = width;
t->stride[0] = cp * width * height;
t->stride[1] = width * height;
t->stride[2] = width;
t->stride[3] = 1;
}
}
#ifdef CUDNN
if(network->net->engine == ENGINE_CUDA)
{
out = THForward(network, t);
if(network->out)
THFloatTensor_free(network->out);
#ifdef HAVEFP16
if(floattype == CUDNN_DATA_HALF)
network->out = THFloatTensor_newFromHalfCudaTensor(out);
else
#endif
network->out = THFloatTensor_newFromCudaTensor(out);
out = network->out;
} else
#endif
#ifdef OPENCL
if(network->net->engine == ENGINE_OPENCL || network->net->engine == ENGINE_OPENCLINIT)
{
out = THForward(network, t);
if(network->out)
THFloatTensor_free(network->out);
#ifdef HAVEFP16
if(cl_datasize == 2)
network->out = THFloatTensor_newFromHalfOpenCLImageTensor(out);
else
#endif
network->out = THFloatTensor_newFromOpenCLImageTensor(out);
out = network->out;
} else
#endif
#ifdef LOWP
if(network->net->engine == ENGINE_LOWP)
{
out = THForward(network, t);
if(network->out)
THFloatTensor_free(network->out);
network->out = THFloatTensor_newFromLowpTensor(out);
out = network->out;
} else
#endif
out = THForward(network, t);
THFloatTensor_free(t);
*results = out->storage->data;
if(out->nDimension >= 3)
{
*outwidth = (int)out->size[out->nDimension - 1];
*outheight = (int)out->size[out->nDimension - 2];
} else *outwidth = *outheight = 1;
return (int)THFloatTensor_nElement(out);
}
int THProcessYUYV(THNETWORK *network, unsigned char *image, int width, int height, float **results, int *outwidth, int *outheight)
{
THFloatTensor *out;
THFloatStorage *st;
#ifdef CUDNN
if(network->net->engine == ENGINE_CUDA)
THError("This function is not supported with CUDNN");
#endif
#ifdef OPENCL
if(network->net->engine == ENGINE_OPENCL || network->net->engine == ENGINE_OPENCLINIT)
THError("This function is not supported with OpenCL");
#endif
#ifdef LOWP
if(network->net->engine == ENGINE_LOWP)
THError("This function is not supported with Lowp");
#endif
st = THFloatStorage_new(width * height * 3);
yuyv2fRGB(image, st->data, width*height, width, width, height, network->mean, network->std);
THFloatTensor *t = THFloatTensor_new();
t->storage = st;
t->nDimension = 3;
t->size[0] = 3;
t->size[1] = height;
t->size[2] = width;
t->stride[0] = width * height;
t->stride[1] = width;
t->stride[2] = 1;
out = THForward(network, t);
THFloatTensor_free(t);
*results = out->storage->data;
if(out->nDimension >= 3)
{
*outwidth = (int)out->size[out->nDimension - 1];
*outheight = (int)out->size[out->nDimension - 2];
} else *outwidth = *outheight = 1;
return (int)THFloatTensor_nElement(out);
}
void THFreeNetwork(THNETWORK *network)
{
if(network->allpynodes)
free(network->allpynodes);
if(network->pynet)
freepynet(network->pynet);
if(network->net)
freenetwork(network->net);
if(network->netobj)
{
freeobject(network->netobj);
free(network->netobj);
}
if(network->statobj)
{
freeobject(network->statobj);
free(network->statobj);
}
if(network->out)
THFloatTensor_free(network->out);
free(network);
}
int THLastError()
{
return lasterror;
}
void THMakeSpatial(THNETWORK *network, int size)
{
int i, nInputPlane = 3;
for(i = 0; i < network->net->nelem; i++)
{
if(network->net->modules[i].type == MT_View || network->net->modules[i].type == MT_Reshape)
{
THFloatTensor_free(network->net->modules[i].output);
memmove(network->net->modules+i, network->net->modules+i+1, sizeof(*network->net->modules) * (network->net->nelem - i - 1));
network->net->nelem--;
i--;
} else if(network->net->modules[i].type == MT_Linear)
{
THFloatTensor_free(network->net->modules[i].Linear.addBuffer);
network->net->modules[i].updateOutput = nn_SpatialConvolutionMM_updateOutput;
#ifndef USEBLAS
network->net->modules[i].type = MT_SpatialConvolutionVirtMM;
#else
network->net->modules[i].type = MT_SpatialConvolutionMM;
#endif
struct SpatialConvolution *c = &network->net->modules[i].SpatialConvolution;
c->finput = THFloatTensor_new();
c->padW = c->padH = 0;
c->dW = c->dH = 1;
c->kW = c->kH = size;
c->nInputPlane = nInputPlane;
nInputPlane = c->nOutputPlane = (int)c->weight->size[0];
size = (size + 2*c->padW - c->kW) / c->dW + 1;
} else if(network->net->modules[i].type == MT_SpatialConvolution ||
network->net->modules[i].type == MT_SpatialConvolutionMM ||
network->net->modules[i].type == MT_SpatialConvolutionVirtMM)
{
struct SpatialConvolution *c = &network->net->modules[i].SpatialConvolution;
size = (size + 2*c->padW - c->kW) / c->dW + 1;
nInputPlane = network->net->modules[i].SpatialConvolution.nOutputPlane;
} else if(network->net->modules[i].type == MT_SpatialMaxPooling)
{
struct SpatialMaxPooling *c = &network->net->modules[i].SpatialMaxPooling;
if(c->ceil_mode)
size = (ceil((float)(size - c->kH + 2*c->padH) / c->dH)) + 1;
else size = (floor((float)(size - c->kH + 2*c->padH) / c->dH)) + 1;
} else if(network->net->modules[i].type == MT_SpatialZeroPadding)
{
struct SpatialZeroPadding *c = &network->net->modules[i].SpatialZeroPadding;
size += c->pad_l + c->pad_r;
}
}
}
int THUseSpatialConvolutionMM(THNETWORK *network, int mm_type)
{
int i;
int rc = 0;
if(!network->net)
return rc = ERR_NOTIMPLEMENTED;
for(i = 0; i < network->net->nelem; i++)
{
if(mm_type && network->net->modules[i].type == MT_SpatialConvolution)
{
struct SpatialConvolution *c = &network->net->modules[i].SpatialConvolution;
network->net->modules[i].type = MT_SpatialConvolutionMM;
network->net->modules[i].updateOutput = nn_SpatialConvolutionMM_updateOutput;
THFloatTensor_resize2d(c->weight, c->nOutputPlane, c->nInputPlane * c->kH * c->kW);
} else if(!mm_type && (network->net->modules[i].type == MT_SpatialConvolutionMM ||
network->net->modules[i].type == MT_SpatialConvolutionVirtMM))
{
struct SpatialConvolution *c = &network->net->modules[i].SpatialConvolution;
if(c->padW || c->padH)
{
rc = ERR_NOTIMPLEMENTED;
continue;
}
network->net->modules[i].type = MT_SpatialConvolution;
network->net->modules[i].updateOutput = nn_SpatialConvolution_updateOutput;
THFloatTensor_resize4d(c->weight, c->nOutputPlane, c->nInputPlane, c->kH, c->kW);
}
#ifndef USEBLAS
if(mm_type == 2 && network->net->modules[i].type == MT_SpatialConvolutionMM)
network->net->modules[i].type = MT_SpatialConvolutionVirtMM;
else if(mm_type == 1 && network->net->modules[i].type == MT_SpatialConvolutionVirtMM)
network->net->modules[i].type = MT_SpatialConvolutionMM;
#endif
}
return rc;
}
THNETWORK *THCreateCudaNetwork(THNETWORK *net)
{
#ifdef CUDNN
THNETWORK *nn = malloc(sizeof(*nn));
memcpy(nn, net, sizeof(*nn));
nn->netobj = 0;
nn->statobj = 0;
nn->net = THcudnn_ToCUDNN(net->net);
return nn;
#else
return 0;
#endif
}
int THCudaHalfFloat(int enable)
{
#if defined CUDNN && defined HAVEFP16
if(enable)
{
floattype = CUDNN_DATA_HALF;
} else floattype = CUDNN_DATA_FLOAT;
return 0;
#else
return ERR_NOTIMPLEMENTED;
#endif
}
int THOpenCLHalfFloat(int enable)
{
#if defined OPENCL && defined HAVEFP16
if(enable)
{
cl_datasize = 2;
} else cl_datasize = 4;
return 0;
#else
return ERR_NOTIMPLEMENTED;
#endif
}
THNETWORK *THCreateOpenCLNetwork(THNETWORK *net)
{
#ifdef OPENCL
THNETWORK *nn = malloc(sizeof(*nn));
memcpy(nn, net, sizeof(*nn));
nn->netobj = 0;
nn->statobj = 0;
nn->net = THOpenCL_ToOpenCL(net->net);
return nn;
#else
return 0;
#endif
}
THNETWORK *THCreateLowpNetwork(THNETWORK *net, float range)
{
#ifdef LOWP
THNETWORK *nn = malloc(sizeof(*nn));
memcpy(nn, net, sizeof(*nn));
nn->netobj = 0;
nn->statobj = 0;
nn->net = THLowp_ToLowp(net->net, range);
return nn;
#else
return 0;
#endif
}
|
1.c
|
#include <stdlib.h>
#include <stdio.h>
#include <omp.h>
int main() {
FILE *in = fopen("1_in.txt", "r");
FILE *out = fopen("1_out.txt", "w");
int n, p, q;
fscanf(in, "%d %d %d", &n, &p, &q);
double *A, *B, *C;
A = (double*) calloc(n * n, sizeof(double));
B = (double*) calloc(n * n, sizeof(double));
C = (double*) calloc(n * n, sizeof(double));
for(int x=0; x<p; x++){
int i, j;
double v;
fscanf(in, "%d %d %lf", &i, &j, &v);
i--;
j--;
A[i * n + j] = v;
}
for(int x=0; x<q; x++){
int i, j;
double v;
fscanf(in, "%d %d %lf", &i, &j, &v);
i--;
j--;
B[i * n + j] = v;
}
int i, j, k;
int c = 0;
for (i = 0; i < n; i++) {
#pragma omp parallel for private(j, k) reduction(+:c)
for (j = 0; j < n; j++) {
for (k = 0; k < n; k++) {
C[i * n + j] += A[i * n + k] * B[k * n + j];
}
if (C[i * n + j] != 0) {
c++;
}
}
}
fprintf(out, "%d %d\n", n, c);
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (C[i * n + j] != 0) {
fprintf(out, "%d %d %.4lf\n", i+1, j+1, C[i * n + j]);
}
}
}
free(A);
free(B);
free(C);
fclose(in);
fclose(out);
return 0;
}
|
ark_analytic_nonlin_ompdev.c
|
/*-----------------------------------------------------------------
* Programmer(s): Shelby Lockhart @ LLNL
*---------------------------------------------------------------
* This code is based on the serial code found in
* ark_analytic_nonlin.c developed by Daniel R. Reynolds
*---------------------------------------------------------------
* SUNDIALS Copyright Start
* Copyright (c) 2002-2021, 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
*---------------------------------------------------------------
* Example problem:
*
* The following is a simple example problem with analytical
* solution,
* dy/dt = (t+1)*exp(-y)
* for t in the interval [0.0, 10.0], with initial condition: y=0.
* This has analytical solution
* y(t) = log(0.5*t^2 + t + 1)
*
* This program solves the problem with the ERK method.
* Output is printed every 1.0 units of time (10 total).
* Run statistics (optional outputs) are printed at the end.
*-----------------------------------------------------------------*/
/* Header files */
#include <stdio.h>
#include <math.h>
#include <arkode/arkode_erkstep.h> /* prototypes for ERKStep fcts., consts */
#include <nvector/nvector_openmpdev.h> /* OpenMPDEV N_Vector types, fcts., macros */
#include <sundials/sundials_types.h> /* def. of type 'realtype' */
#include <sundials/sundials_math.h> /* def. of SUNRsqrt, etc. */
#ifdef _OPENMP
#include <omp.h> /* OpenMP functions */
#endif
#if defined(SUNDIALS_EXTENDED_PRECISION)
#define GSYM "Lg"
#define ESYM "Le"
#define FSYM "Lf"
#else
#define GSYM "g"
#define ESYM "e"
#define FSYM "f"
#endif
/* User-supplied Functions Called by the Solver */
static int f(realtype t, N_Vector y, N_Vector ydot, void *user_data);
/* Private function to check function return values */
static int check_flag(void *flagvalue, const char *funcname, int opt);
/* Main Program */
int main()
{
/* general problem parameters */
realtype T0 = RCONST(0.0); /* initial time */
realtype Tf = RCONST(10.0); /* final time */
realtype dTout = RCONST(1.0); /* time between outputs */
sunindextype NEQ = 1; /* number of dependent vars. */
realtype reltol = 1.0e-6; /* tolerances */
realtype abstol = 1.0e-10;
/* general problem variables */
int flag; /* reusable error-checking flag */
N_Vector y = NULL; /* empty vector for storing solution */
void *arkode_mem = NULL; /* empty ARKode memory structure */
FILE *UFID;
realtype t, tout;
long int nst, nst_a, nfe, netf;
realtype *y_data = NULL;
/* Create the SUNDIALS context object for this simulation */
SUNContext ctx;
flag = SUNContext_Create(NULL, &ctx);
if (check_flag(&flag, "SUNContext_Create", 1)) return 1;
/* Initial problem output */
printf("\nAnalytical ODE test problem:\n");
printf(" reltol = %.1"ESYM"\n", reltol);
printf(" abstol = %.1"ESYM"\n\n",abstol);
/* Initialize data structures */
y = N_VNew_OpenMPDEV(NEQ, ctx); /* Create OpenMPDEV vector for solution */
if (check_flag((void *)y, "N_VNew_OpenMPDEV", 0)) return 1;
y_data = N_VGetHostArrayPointer_OpenMPDEV(y);
y_data[0] = 0.0; /* Specify initial condition */
N_VCopyToDevice_OpenMPDEV(y); /* Copy to device */
arkode_mem = ERKStepCreate(f, T0, y, ctx); /* Create the solver memory */
if (check_flag((void *)arkode_mem, "ERKStepCreate", 0)) return 1;
/* Specify tolerances */
flag = ERKStepSStolerances(arkode_mem, reltol, abstol);
if (check_flag(&flag, "ERKStepSStolerances", 1)) return 1;
/* Open output stream for results, output comment line */
UFID = fopen("solution.txt","w");
fprintf(UFID,"# t u\n");
/* output initial condition to disk */
N_VCopyFromDevice_OpenMPDEV(y);
fprintf(UFID," %.16"ESYM" %.16"ESYM"\n", T0, y_data[0]);
/* Main time-stepping loop: calls ERKStep to perform the integration, then
prints results. Stops when the final time has been reached */
t = T0;
tout = T0+dTout;
printf(" t u\n");
printf(" ---------------------\n");
while (Tf - t > 1.0e-15) {
flag = ERKStepEvolve(arkode_mem, tout, y, &t, ARK_NORMAL); /* call integrator */
if (check_flag(&flag, "ERKStep", 1)) break;
N_VCopyFromDevice_OpenMPDEV(y);
printf(" %10.6"FSYM" %10.6"FSYM"\n", t, y_data[0]); /* access/print solution */
fprintf(UFID," %.16"ESYM" %.16"ESYM"\n", t, y_data[0]);
if (flag >= 0) { /* successful solve: update time */
tout += dTout;
tout = (tout > Tf) ? Tf : tout;
} else { /* unsuccessful solve: break */
fprintf(stderr,"Solver failure, stopping integration\n");
break;
}
}
printf(" ---------------------\n");
fclose(UFID);
/* Print some final statistics */
flag = ERKStepGetNumSteps(arkode_mem, &nst);
check_flag(&flag, "ERKStepGetNumSteps", 1);
flag = ERKStepGetNumStepAttempts(arkode_mem, &nst_a);
check_flag(&flag, "ERKStepGetNumStepAttempts", 1);
flag = ERKStepGetNumRhsEvals(arkode_mem, &nfe);
check_flag(&flag, "ERKStepGetNumRhsEvals", 1);
flag = ERKStepGetNumErrTestFails(arkode_mem, &netf);
check_flag(&flag, "ERKStepGetNumErrTestFails", 1);
printf("\nFinal Solver Statistics:\n");
printf(" Internal solver steps = %li (attempted = %li)\n", nst, nst_a);
printf(" Total RHS evals = %li\n", nfe);
printf(" Total number of error test failures = %li\n\n", netf);
/* Clean up and return with successful completion */
N_VDestroy(y); /* Free y vector */
ERKStepFree(&arkode_mem); /* Free integrator memory */
SUNContext_Free(&ctx); /* Free context */
return 0;
}
/*-------------------------------
* Functions called by the solver
*-------------------------------*/
/* f routine to compute the ODE RHS function f(t,y). */
static int f(realtype t, N_Vector y, N_Vector ydot, void *user_data)
{
int dev;
realtype *y_data = N_VGetDeviceArrayPointer_OpenMPDEV(y);
realtype *ydot_data = N_VGetDeviceArrayPointer_OpenMPDEV(ydot);
dev = omp_get_default_device();
#pragma omp target map(to:t) is_device_ptr(y_data, ydot_data) device(dev)
{
ydot_data[0] = (t+1.0)*SUNRexp(-1.0 * y_data[0]);
}
return 0;
}
/*-------------------------------
* Private helper functions
*-------------------------------*/
/* Check function return value...
opt == 0 means SUNDIALS function allocates memory so check if
returned NULL pointer
opt == 1 means SUNDIALS function returns a flag so check if
flag >= 0
opt == 2 means function allocates memory so check if returned
NULL pointer
*/
static int check_flag(void *flagvalue, const char *funcname, int opt)
{
int *errflag;
/* Check if SUNDIALS function returned NULL pointer - no memory allocated */
if (opt == 0 && flagvalue == NULL) {
fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed - returned NULL pointer\n\n",
funcname);
return 1; }
/* Check if flag < 0 */
else if (opt == 1) {
errflag = (int *) flagvalue;
if (*errflag < 0) {
fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed with flag = %d\n\n",
funcname, *errflag);
return 1; }}
/* Check if function returned NULL pointer - no memory allocated */
else if (opt == 2 && flagvalue == NULL) {
fprintf(stderr, "\nMEMORY_ERROR: %s() failed - returned NULL pointer\n\n",
funcname);
return 1; }
return 0;
}
/*---- end of file ----*/
|
OMP-Jacobi-1D-Naive-Parallel.test.c
|
#include <stdio.h>
#include <omp.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <omp.h>
#include <time.h>
#include <stdlib.h>
#include <assert.h>
bool initedJacobi = false;
int globalSeed = -1;
int cores = -1;
int problemSize = -1, T = -1, lowerBound = -1, upperBound = -1;
double* space[2] = { NULL, NULL }; // space[t][x] for (t,x) in { {0,1} X {lowerBound, ... , upperBound} };
int min( int a, int b){
return (a <= b)? a : b;
}
int max( int a, int b){
return (a >= b)? a : b;
}
void initJacobi(){
// if init has not already been called (preserve things like global seed.
if( ! initedJacobi ){
// note the convention someVar = ( someVar == -1 )? defaultValue : someVar ;
// this allows us to use the cmd line flags to set variables, AND have an init call.
// all values are initialized with -1 in global space, so if someVar == -1, then it has
// not been set, and and be given a default value.
// seed for random number generator.
// allows all initSpace calls to generate the same inital values
globalSeed = (globalSeed== -1)? time(NULL) : globalSeed;
// problemSpace parameters
T = (T == -1)? 100 : T;
problemSize = (problemSize == -1)? 1000000 : problemSize;
lowerBound = 1;
upperBound = lowerBound + problemSize - 1;
cores = (cores == -1)? omp_get_num_procs() : cores ;
omp_set_num_threads( cores );
// set initialization flag
initedJacobi = true;
}
}
// initialize space array
void initSpace(){
// if space has been previously allocated, free up space.
if( space[0] != NULL ){
free( space[0] );
}
if( space[1] != NULL ) {
free( space[1] );
}
/*
// allocate space
space = (double**) malloc( 2 * sizeof(double*) );
if( space == NULL ){
printf( "Could not allocate space array\n" );
exit(0);
}
*/
// allocate time-steps 0 and 1
space[0] = (double*) malloc( (problemSize + 2) * sizeof(double));
space[1] = (double*) malloc( (problemSize + 2) * sizeof(double));
if( space[0] == NULL || space[1] == NULL ){
printf( "Could not allocate space array\n" );
exit(0);
}
// use global seed to seed the random number gen (will be constant)
srand(globalSeed);
// seed the space.
int x;
for( x = lowerBound; x <= upperBound; ++x ){
space[0][x] = rand() / (double)rand();
}
// set halo values (sanity)
space[0][0] = 0;
space[0][upperBound+1] = 0;
space[1][0] = 0;
space[1][upperBound+1] = 0;
}
// stencil call.
void stencil( int read, int write, int x ){
// stencil operation
space[write][x] = (space[read][x-1] + space[read][x] + space[read][x+1])/3;
}
// parse int abstraction from strtol
int parseInt( char* string ){
return (int) strtol( string, NULL, 10 );
}
bool verifyResult( bool verbose ){
assert( space[0] != NULL && space[1] != NULL );
double* endSpace = (double*) malloc( (problemSize + 2) * sizeof(double) );
for( int x = 0; x < problemSize + 2; ++x ){
endSpace[x] = space[T & 1][x];
}
initSpace();
int read = 0, write = 1;
for( int t = 1; t <= T; ++t ){
for( int x = lowerBound; x <= upperBound; ++x ){
stencil(read, write, x);
}
read = write;
write = 1 - write;
}
bool failed = false;
for( int x = lowerBound; x <= upperBound; ++x ){
if( endSpace[x] != space[T & 1][x] ){
failed = true;
if( verbose ) printf( "FAILED\n"); //! %f != %f at %d\n", endSpace[x], space[T & 1][x], x );
break;
}
}
if( verbose && !failed ) printf( "SUCCESS\n" );
free( endSpace );
return !failed;
}
// naive parallel iteration test suite
double test_1(){
int t, x, read = 0, write = 1;
double start_time = omp_get_wtime();
for( t = 1; t <= T; ++t ){
#pragma omp parallel for private( x ) //schedule(dynamic)
for( x = lowerBound; x <= upperBound; ++x ){
stencil( read, write, x );
}
read = write;
write = 1 - write;
}
double end_time = omp_get_wtime();
return (end_time - start_time);
}
int main( int argc, char* argv[] ){
setbuf(stdout, NULL); // set buffer to null, so prints ALWAYS print (for debug purposes mainly)
bool verify = false;
bool printtime = true;
// Command line parsing
char c;
while ((c = getopt (argc, argv, "nc:s:p:T:hv")) != -1){
switch( c ) {
case 'n': // print time
printtime = false;
break;
case 'c': // cores
cores = parseInt( optarg );
if( cores <= 0 ){
fprintf(stderr, "cores must be greater than 0: %d\n", cores);
exit( 0 );
}
break;
case 'p': // problem size
problemSize = parseInt( optarg );
if( problemSize <= 0 ){
fprintf(stderr, "problemSize must be greater than 0: %d\n", problemSize);
exit( 0 );
}
break;
case 'T': // T (time steps)
T = parseInt( optarg );
if( T <= 0 ){
fprintf(stderr, "T must be greater than 0: %d\n", T);
exit( 0 );
}
break;
case 'h': // help
printf("usage: %s\n-n \t dont print time \n-p <problem size> \t problem size in elements \n-T <time steps>\t number of time steps\n-c <cores>\tnumber of threads\n-h\tthis dialogue\n-v\tverify output\n", argv[0]);
exit(0);
case 'v': // verify;
verify = true;
break;
case '?':
if (optopt == 'p')
fprintf (stderr, "Option -%c requires positive int argument: problem size.\n", optopt);
else if (optopt == 'T')
fprintf (stderr, "Option -%c requires positive int argument: T.\n", optopt);
else if (optopt == 's')
fprintf (stderr, "Option -%c requires int argument: subset_s.\n", optopt);
else if (optopt == 'c')
fprintf (stderr, "Option -%c requires int argument: number of cores.\n", optopt);
else if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt);
exit(0);
default:
exit(0);
}
}
initJacobi();
initSpace();
double time = test_1();
if( printtime ){
printf( "Time: %f\n", time );
}
if( verify ){
verifyResult( true );
}
}
|
ConstraintsContainerDms-impl.h
|
/**********************************************************************************************************************
This file is part of the Control Toolbox (https://adrlab.bitbucket.io/ct), copyright by ETH Zurich, Google Inc.
Authors: Michael Neunert, Markus Giftthaler, Markus Stäuble, Diego Pardo, Farbod Farshidian
Licensed under Apache2 license (see LICENSE file in main directory)
**********************************************************************************************************************/
template <size_t STATE_DIM, size_t CONTROL_DIM, typename SCALAR>
ConstraintsContainerDms<STATE_DIM, CONTROL_DIM, SCALAR>::ConstraintsContainerDms(
std::shared_ptr<OptVectorDms<STATE_DIM, CONTROL_DIM, SCALAR>> w,
std::shared_ptr<tpl::TimeGrid<SCALAR>> timeGrid,
std::vector<std::shared_ptr<ShotContainer<STATE_DIM, CONTROL_DIM, SCALAR>>> shotContainers,
std::shared_ptr<ConstraintDiscretizer<STATE_DIM, CONTROL_DIM, SCALAR>> discretizedConstraints,
const state_vector_t& x0,
const DmsSettings settings)
: settings_(settings), shotContainers_(shotContainers)
{
c_init_ = std::shared_ptr<InitStateConstraint<STATE_DIM, CONTROL_DIM, SCALAR>>(
new InitStateConstraint<STATE_DIM, CONTROL_DIM, SCALAR>(x0, w));
this->constraints_.push_back(c_init_);
for (size_t shotNr = 0; shotNr < settings_.N_; shotNr++)
{
std::shared_ptr<ContinuityConstraint<STATE_DIM, CONTROL_DIM, SCALAR>> c_i =
std::shared_ptr<ContinuityConstraint<STATE_DIM, CONTROL_DIM, SCALAR>>(
new ContinuityConstraint<STATE_DIM, CONTROL_DIM, SCALAR>(shotContainers[shotNr], w, shotNr, settings));
this->constraints_.push_back(c_i);
}
if (settings_.objectiveType_ == DmsSettings::OPTIMIZE_GRID)
{
std::shared_ptr<TimeHorizonEqualityConstraint<STATE_DIM, CONTROL_DIM, SCALAR>> c_horizon_equal =
std::shared_ptr<TimeHorizonEqualityConstraint<STATE_DIM, CONTROL_DIM, SCALAR>>(
new TimeHorizonEqualityConstraint<STATE_DIM, CONTROL_DIM, SCALAR>(w, timeGrid, settings));
this->constraints_.push_back(c_horizon_equal);
}
if (discretizedConstraints)
{
std::cout << "Adding discretized constraints" << std::endl;
this->constraints_.push_back(discretizedConstraints);
}
}
template <size_t STATE_DIM, size_t CONTROL_DIM, typename SCALAR>
void ConstraintsContainerDms<STATE_DIM, CONTROL_DIM, SCALAR>::prepareEvaluation()
{
#pragma omp parallel for num_threads(settings_.nThreads_)
for (auto shotContainer = shotContainers_.begin(); shotContainer < shotContainers_.end(); ++shotContainer)
{
(*shotContainer)->integrateShot();
}
}
template <size_t STATE_DIM, size_t CONTROL_DIM, typename SCALAR>
void ConstraintsContainerDms<STATE_DIM, CONTROL_DIM, SCALAR>::prepareJacobianEvaluation()
{
#pragma omp parallel for num_threads(settings_.nThreads_)
for (auto shotContainer = shotContainers_.begin(); shotContainer < shotContainers_.end(); ++shotContainer)
{
(*shotContainer)->integrateSensitivities();
}
}
template <size_t STATE_DIM, size_t CONTROL_DIM, typename SCALAR>
void ConstraintsContainerDms<STATE_DIM, CONTROL_DIM, SCALAR>::changeInitialConstraint(const state_vector_t& x0)
{
c_init_->updateConstraint(x0);
}
|
dvjsvd.c
|
#include "dvjsvd.h"
#include "dnormx.h"
#include "dscale.h"
#include "dnorm2.h"
#include "dznrm2.h"
#include "ddpscl.h"
//#include "dgsscl.h"
#include "dbjac2.h"
#include "djrotf.h"
#include "djrot.h"
#include "dswp.h"
#include "vecdef.h"
#include "defops.h"
#ifdef JTRACE
#include "timer.h"
#endif /* JTRACE */
#ifdef DBL_MAX_ROT_EXP
#error DBL_MAX_ROT_EXP already defined
#else /* !DBL_MAX_ROT_EXP */
#define DBL_MAX_ROT_EXP 1022
#endif /* ?DBL_MAX_ROT_EXP */
fint dvjsvd_(const fnat m[static restrict 1], const fnat n[static restrict 1], double G[static restrict VDL], const fnat ldG[static restrict 1], double V[static restrict VDL], const fnat ldV[static restrict 1], double eS[static restrict 1], double fS[static restrict 1], const unsigned js[static restrict 1], const unsigned stp[static restrict 1], const unsigned swp[static restrict 1], double work[static restrict VDL], unsigned iwork[static restrict 1])
{
const fnat n_2 = (*n >> 1u);
if (IS_NOT_VFPENV)
return -14;
if (!*n)
return 0;
if (*m < *n)
return -1;
if (*m & VDL_1)
return -1;
if (*n & 1u)
return -2;
if (n_2 & VDL_1)
return -2;
if (IS_NOT_ALIGNED(G))
return -3;
if (*ldG < *m)
return -4;
if (*ldG & VDL_1)
return -4;
if (IS_NOT_ALIGNED(V))
return -5;
if (*ldV < *n)
return -6;
if (*ldV & VDL_1)
return -6;
if (IS_NOT_ALIGNED(work))
return -12;
#ifdef JTRACE
FILE *const jtr = fopen((const char*)work, "w");
if (!jtr)
return -13;
(void)fprintf(jtr, "M=");
(void)fflush(jtr);
#endif /* JTRACE */
double M = dnormx_(m, n, G, ldG);
if (!(M <= DBL_MAX))
return -15;
if (copysign(1.0, M) == -1.0)
return -16;
#ifdef JTRACE
(void)fprintf(jtr, "%#.17e\n", M);
(void)fflush(jtr);
#endif /* JTRACE */
#ifdef _OPENMP
#pragma omp parallel for default(none) shared(n,V,ldV,eS,fS)
#endif /* _OPENMP */
for (fnat j = 0u; j < *n; ++j) {
register const VD z = _mm512_setzero_pd();
double *const Vj = V + j * (size_t)(*ldV);
for (fnat i = 0u; i < *n; i += VDL)
_mm512_store_pd((Vj + i), z);
fS[j] = Vj[j] = 1.0;
eS[j] = -HUGE_VAL;
}
if (M == 0.0)
return 0;
const double M_m = (DBL_MAX / (*m << 1u));
double es = 0.0, fs = 0.0;
dbl2ef(M_m, &es, &fs);
const int DBL_MAX_NRM_EXP = (int)es;
dbl2ef(M, &es, &fs);
int eM = (int)es;
int sR = DBL_MAX_ROT_EXP - eM;
int sN = DBL_MAX_NRM_EXP - eM - 1;
#ifdef JTRACE
(void)fprintf(jtr, "eM=%d, sR=%d, sN=%d, M=", eM, sR, sN);
(void)fflush(jtr);
#endif /* JTRACE */
if (sN) {
*(fint*)&es = sN;
if (dscale_(m, n, G, ldG, (const fint*)&es) < 0)
return -17;
M = scalbn(M, sN);
}
int sT = sN;
#ifdef JTRACE
(void)fprintf(jtr, "%#.17e\n", M);
(void)fflush(jtr);
#endif /* JTRACE */
const fnat n_16 = (n_2 >> VDLlg);
double *const a11 = work;
double *const a22 = a11 + n_2;
double *const a21 = a22 + n_2;
double *const c = a21 + n_2;
double *const at = c + n_2;
double *const l1 = at + n_2;
double *const l2 = l1 + n_2;
double *const w = l2 + n_2;
unsigned *const p = iwork;
unsigned *const pc = p + n_16;
#ifndef DGSSCL_H
if (*swp) {
#ifdef _OPENMP
#pragma omp parallel for default(none) shared(l1,n)
#endif /* _OPENMP */
for (fnat i = 0u; i < *n; ++i)
l1[i] = 1.0;
}
#endif /* !DGSSCL_H */
// see LAPACK's DGESVJ
const double tol = sqrt((double)(*m)) * scalbn(DBL_EPSILON, -1);
const double gst = scalb(tol, DBL_MAX_FIN_EXP);
unsigned sw = 0u;
#ifdef JTRACE
unsigned rd[2u] = { 0u, 0u };
const uint64_t hz = tsc_get_freq_hz_(rd);
long double Tn = 0.0L, Tp = 0.0L, Ta = 0.0L, Te = 0.0L, Tr = 0.0L;
uint64_t T = UINT64_C(0);
#endif /* JTRACE */
while (sw < *swp) {
size_t swt = 0u;
for (unsigned st = 0u; st < *stp; ++st) {
// rescale according to M if necessary and update M
dbl2ef(M, &es, &fs);
eM = (int)es;
sR = DBL_MAX_ROT_EXP - eM;
sN = DBL_MAX_NRM_EXP - eM - 1;
if (sR < 0) {
#ifdef JTRACE
(void)fprintf(jtr, "sweep=%u, step=%u, eM=%d, sR=%d, sN=%d, M=", sw, st, eM, sR, sN);
(void)fflush(jtr);
#endif /* JTRACE */
*(fint*)&es = sN;
if (dscale_(m, n, G, ldG, (const fint*)&es) < 0)
return -18;
M = scalbn(M, sN);
sT += sN;
#ifndef DGSSCL_H
#ifdef _OPENMP
#pragma omp parallel for default(none) shared(l1,n)
#endif /* _OPENMP */
for (fnat i = 0u; i < *n; ++i)
l1[i] = 1.0;
#endif /* !DGSSCL_H */
#ifdef JTRACE
(void)fprintf(jtr, "%#.17e\n", M);
(void)fflush(jtr);
#endif /* JTRACE */
}
// compute the norms, overflow-aware
const unsigned *const r = js + st * (size_t)(*n);
double nM = -0.0;
bool overflow = false;
do {
#ifdef JTRACE
T = rdtsc_beg(rd);
#endif /* JTRACE */
nM = 0.0;
#ifdef _OPENMP
#pragma omp parallel for default(none) shared(n,r,m,G,ldG,eS,fS,a11,a22,c,at,l1) reduction(max:nM)
#endif /* _OPENMP */
for (fnat pq = 0u; pq < *n; pq += 2u) {
const fnat _pq = (pq >> 1u);
if (!(nM <= DBL_MAX)) {
a11[_pq] = NAN;
a22[_pq] = NAN;
continue;
}
const fnat pq_ = pq + 1u;
const size_t _p = r[pq];
const size_t _q = r[pq_];
#ifndef DGSSCL_H
if (l1[_p] == 1.0) {
#endif /* !DGSSCL_H */
double *const Gp = G + _p * (*ldG);
nM = fmax(nM, fmin((a11[_pq] = dnorm2_(m, Gp, (eS + _p), (fS + _p), (c + _pq), (at + _pq))), HUGE_VAL));
if (!(nM <= DBL_MAX)) {
a22[_pq] = NAN;
continue;
}
#ifndef DGSSCL_H
}
if (l1[_q] == 1.0) {
#endif /* !DGSSCL_H */
double *const Gq = G + _q * (*ldG);
nM = fmax(nM, fmin((a22[_pq] = dnorm2_(m, Gq, (eS + _q), (fS + _q), (c + _pq), (at + _pq))), HUGE_VAL));
#ifndef DGSSCL_H
}
#endif /* !DGSSCL_H */
}
#ifdef JTRACE
Tn += tsc_lap(hz, T, rdtsc_end(rd));
#endif /* JTRACE */
if (overflow = !(nM <= DBL_MAX)) {
#ifdef JTRACE
(void)fprintf(jtr, "sweep=%u, step=%u, M=", sw, st);
(void)fflush(jtr);
#endif /* JTRACE */
*(fint*)&es = sN;
if (dscale_(m, n, G, ldG, (const fint*)&es) < 0)
return -19;
M = scalbn(M, sN);
sT += sN;
#ifndef DGSSCL_H
#ifdef _OPENMP
#pragma omp parallel for default(none) shared(l1,n)
#endif /* _OPENMP */
for (fnat i = 0u; i < *n; ++i)
l1[i] = 1.0;
#endif /* !DGSSCL_H */
#ifdef JTRACE
(void)fprintf(jtr, "%#.17e\n", M);
(void)fflush(jtr);
#endif /* JTRACE */
}
} while (overflow);
// scaled dot-products
#ifdef JTRACE
T = rdtsc_beg(rd);
#endif /* JTRACE */
nM = 0.0;
#ifdef _OPENMP
#pragma omp parallel for default(none) shared(n,r,m,G,ldG,eS,fS,w) reduction(min:nM)
#endif /* _OPENMP */
for (fnat pq = 0u; pq < *n; pq += 2u) {
const fnat _pq = (pq >> 1u);
if (!(nM >= 0.0)) {
w[_pq] = NAN;
continue;
}
const fnat pq_ = pq + 1u;
const size_t _p = r[pq];
const size_t _q = r[pq_];
// pack the norms
const double e2[2u] = { eS[_q], eS[_p] };
const double f2[2u] = { fS[_q], fS[_p] };
double *const Gp = G + _p * (*ldG);
double *const Gq = G + _q * (*ldG);
w[_pq] = ddpscl_(m, Gq, Gp, e2, f2);
if (!(isfinite(w[_pq])))
nM = fmin(nM, -20.0);
}
#ifdef JTRACE
Tp += tsc_lap(hz, T, rdtsc_end(rd));
#endif /* JTRACE */
if (!(nM >= 0.0)) {
#ifdef JTRACE
(void)fprintf(jtr, "sweep=%u, step=%u\n", sw, st);
(void)fflush(jtr);
#endif /* JTRACE */
return (fint)nM;
}
// repack data
#ifdef JTRACE
T = rdtsc_beg(rd);
#endif /* JTRACE */
#ifdef _OPENMP
#pragma omp parallel for default(none) shared(n,r,eS,fS,c,at,l1,l2)
#endif /* _OPENMP */
for (fnat pq = 0u; pq < *n; pq += 2u) {
const fnat pq_ = pq + 1u;
const fnat _pq = (pq >> 1u);
const size_t _p = r[pq];
const size_t _q = r[pq_];
c[_pq] = eS[_p];
at[_pq] = eS[_q];
l1[_pq] = fS[_p];
l2[_pq] = fS[_q];
}
fnat stt = 0u;
#ifdef _OPENMP
#pragma omp parallel for default(none) shared(n_2,a11,a22,a21,c,at,l1,l2,w,p,pc,tol,gst) reduction(+:stt)
#endif /* _OPENMP */
for (fnat i = 0u; i < n_2; i += VDL) {
const fnat j = (i >> VDLlg);
// convergence check
register VD _a21 = _mm512_load_pd(w + i);
register const VD _zero = _mm512_set1_pd(-0.0);
register const VD zero = _mm512_setzero_pd();
register const VD _tol = _mm512_set1_pd(tol);
register const VD _a21_ = VDABS(_a21);
pc[j] = MD2U(_mm512_cmple_pd_mask(_tol, _a21_));
if (p[j] = _mm_popcnt_u32(pc[j])) {
stt += p[j];
#ifdef DGSSCL_H
register VD _a11 = _mm512_load_pd(a11 + i);
register VD _a22 = _mm512_load_pd(a22 + i);
register const VD _gst = _mm512_set1_pd(gst);
// might not yet be sorted, so check both cases
pc[j] |= (MD2U(_mm512_cmplt_pd_mask(_mm512_mul_pd(_gst, _a22), _a11)) << VDL);
pc[j] |= (MD2U(_mm512_cmplt_pd_mask(_mm512_mul_pd(_gst, _a11), _a22)) << VDL2);
#endif /* DGSSCL_H */
// Grammian pre-scaling into the double precision range
register const VD f1 = _mm512_load_pd(l1 + i);
register const VD f2 = _mm512_load_pd(l2 + i);
register const VD e1 = _mm512_load_pd(c + i);
register const VD e2 = _mm512_load_pd(at + i);
register VD f12 = _mm512_div_pd(f1, f2);
register VD e12 = _mm512_sub_pd(e1, e2);
register VD f21 = _mm512_div_pd(f2, f1);
register VD e21 = _mm512_sub_pd(e2, e1);
e12 = _mm512_add_pd(e12, _mm512_getexp_pd(f12));
f12 = VDMANT(f12);
e21 = _mm512_add_pd(e21, _mm512_getexp_pd(f21));
f21 = VDMANT(f21);
register const MD c12 = VDEFLE(e12,e21,f12,f21);
register const VD mxe = _mm512_set1_pd(DBL_MAX_FIN_EXP);
register const VD E = _mm512_mask_blend_pd(c12, e12, e21);
register const VD d = _mm512_min_pd(_mm512_sub_pd(mxe, E), zero);
e12 = _mm512_add_pd(e12, d);
e21 = _mm512_add_pd(e21, d);
#ifdef DGSSCL_H
_a11 = _mm512_scalef_pd(f12, e12);
_a22 = _mm512_scalef_pd(f21, e21);
#else /* !DGSSCL_H */
register const VD _a11 = _mm512_scalef_pd(f12, e12);
register const VD _a22 = _mm512_scalef_pd(f21, e21);
#endif /* ?DGSSCL_H */
_a21 = _mm512_scalef_pd(_a21, d);
_mm512_store_pd((a11 + i), _a11);
_mm512_store_pd((a22 + i), _a22);
_mm512_store_pd((a21 + i), _a21);
}
}
swt += stt;
#ifdef JTRACE
Ta += tsc_lap(hz, T, rdtsc_end(rd));
T = rdtsc_beg(rd);
#endif /* JTRACE */
const fint _n_2 =
#ifdef USE_SECANTS
-(fint)n_2
#else /* !USE_SECANTS */
(fint)n_2
#endif /* ?USE_SECANTS */
;
if (dbjac2i(&_n_2, a11, a22, a21, c, at, l1, l2, p) < 0)
return -21;
#ifdef JTRACE
Te += tsc_lap(hz, T, rdtsc_end(rd));
T = rdtsc_beg(rd);
#endif /* JTRACE */
fnat np = 0u; // number of swaps
#ifdef _OPENMP
#pragma omp parallel for default(none) shared(a11,a22,a21,eS,fS,p,pc,r,n_2) reduction(+:np)
#endif /* _OPENMP */
for (fnat i = 0u; i < n_2; i += VDL) {
const fnat j = (i >> VDLlg);
unsigned gsp = ((pc[j] & 0xFF0000u) >> VDL2);
unsigned gsn = ((pc[j] & 0xFF00u) >> VDL);
unsigned trans = (pc[j] & 0xFFu);
unsigned perm = (p[j] & 0xFFu);
for (fnat k = 0u; k < VDL; ++k) {
const fnat l = (i + k);
const fnat pq = (l << 1u);
const uint64_t _p = r[pq];
const uint64_t _q = r[pq + 1u];
*(uint64_t*)(a11 + l) = _p;
*(uint64_t*)(a22 + l) = _q;
if (gsp & 1u) {
a21[l] = -3.0;
++np;
}
else if (gsn & 1u)
a21[l] = 3.0;
else if (trans & 1u) {
if (perm & 1u) {
a21[l] = -2.0;
++np;
}
else // no swap
a21[l] = 2.0;
}
else if (efcmp((eS + _p), (fS + _p), (eS + _q), (fS + _q)) < 0) {
a21[l] = eS[_p];
eS[_p] = eS[_q];
eS[_q] = a21[l];
a21[l] = fS[_p];
fS[_p] = fS[_q];
fS[_q] = a21[l];
a21[l] = -1.0;
++np;
}
else // no swap
a21[l] = 1.0;
gsp >>= 1u;
gsn >>= 1u;
trans >>= 1u;
perm >>= 1u;
}
}
nM = 0.0;
#ifdef _OPENMP
#pragma omp parallel for default(none) shared(m,n,G,ldG,V,ldV,a11,a22,a21,c,at,l1,w,eS,fS,n_2) reduction(max:nM)
#endif /* _OPENMP */
for (fnat i = 0u; i < n_2; ++i) {
const size_t _p = *(const uint64_t*)(a11 + i);
const size_t _q = *(const uint64_t*)(a22 + i);
#ifndef DGSSCL_H
l1[_q] = l1[_p] = 0.0;
#endif /* !DGSSCL_H */
if (!(nM <= DBL_MAX)) {
w[i] = NAN;
continue;
}
double _at, _c;
fint _m, _n;
#ifdef DGSSCL_H
if (a21[i] == -3.0) {
_m = -(fint)*m;
_n = -(fint)*n;
_at = w[i];
double e[2u] = { eS[_p], eS[_q] };
double f[2u] = { fS[_p], fS[_q] };
w[i] = dgsscl_(&_m, &_at, (G + _p * (*ldG)), (G + _q * (*ldG)), e, f);
if (!(w[i] >= 0.0) || !(w[i] <= DBL_MAX)) {
nM = w[i] = HUGE_VAL;
continue;
}
else // no overflow
nM = fmax(nM, w[i]);
// TODO: should V be transformed and how (very small \tan)?
continue;
}
else
#endif /* DGSSCL_H */
if (a21[i] == -2.0) {
_m = -(fint)*m;
_n = -(fint)*n;
_c = c[i];
_at = at[i];
}
else if (a21[i] == -1.0) {
double *const Gp = G + _p * (*ldG);
double *const Gq = G + _q * (*ldG);
if (_m = dswp_(m, Gp, Gq)) {
w[i] = (double)_m;
nM = HUGE_VAL;
continue;
}
double *const Vp = V + _p * (*ldV);
double *const Vq = V + _q * (*ldV);
if (_n = dswp_(n, Vp, Vq)) {
w[i] = (double)_n;
nM = HUGE_VAL;
continue;
}
nM = fmax(nM, (w[i] = 0.0));
continue;
}
else if (a21[i] == 1.0) {
nM = fmax(nM, (w[i] = 0.0));
continue;
}
else if (a21[i] == 2.0) {
_m = (fint)*m;
_n = (fint)*n;
_c = c[i];
_at = at[i];
}
#ifdef DGSSCL_H
else if (a21[i] == 3.0) {
_m = (fint)*m;
_n = (fint)*n;
_at = w[i];
double e[2u] = { eS[_p], eS[_q] };
double f[2u] = { fS[_p], fS[_q] };
w[i] = dgsscl_(&_m, &_at, (G + _p * (*ldG)), (G + _q * (*ldG)), e, f);
if (!(w[i] >= 0.0) || !(w[i] <= DBL_MAX)) {
nM = w[i] = HUGE_VAL;
continue;
}
else // no overflow
nM = fmax(nM, w[i]);
// TODO: should V be transformed and how (very small \tan)?
continue;
}
#endif /* DGSSCL_H */
else { // should never happen
w[i] = NAN;
nM = HUGE_VAL;
continue;
}
w[i] = djrot_(&_m, (G + _p * (*ldG)), (G + _q * (*ldG)), &_c, &_at);
if (!(w[i] >= 0.0) || !(w[i] <= DBL_MAX)) {
nM = w[i] = HUGE_VAL;
continue;
}
else // no overflow
nM = fmax(nM, w[i]);
if (_m = djrotf_(&_n, (V + _p * (*ldV)), (V + _q * (*ldV)), &_c, &_at)) {
w[i] = (double)_m;
nM = HUGE_VAL;
continue;
}
#ifndef DGSSCL_H
l1[_q] = l1[_p] = 1.0;
#endif /* !DGSSCL_H */
}
M = fmax(M, nM);
#ifdef JTRACE
Tr += tsc_lap(hz, T, rdtsc_end(rd));
#endif /* JTRACE */
if (!(M <= DBL_MAX)) {
#ifdef JTRACE
(void)fprintf(jtr, "sweep=%u, step=%u\n", sw, st);
(void)fflush(jtr);
#endif /* JTRACE */
return -22;
}
}
if (!swt)
break;
++sw;
}
if (sw < *swp) {
#ifdef _OPENMP
#pragma omp parallel for default(none) shared(m,n,G,ldG,eS,fS,sT)
#endif /* _OPENMP */
for (fnat j = 0u; j < *n; ++j) {
double *const Gj = G + j * (size_t)(*ldG);
register const VD _f = _mm512_set1_pd(fS[j]);
register const VD _s = _mm512_set1_pd(-(eS[j]));
for (fnat i = 0u; i < *m; i += VDL) {
double *const Gij = Gj + i;
_mm512_store_pd(Gij, _mm512_scalef_pd(_mm512_div_pd(_mm512_load_pd(Gij), _f), _s));
}
eS[j] -= sT;
}
}
#ifdef JTRACE
(void)fprintf(jtr, "sT=%d, M=%#.17e\n", sT, M);
(void)fprintf(jtr, "Tn=%15.9Lf, Tp=%15.9Lf, Ta=%15.9Lf, Te=%15.9Lf, Tr=%15.9Lf\n", Tn, Tp, Ta, Te, Tr);
(void)fclose(jtr);
#endif /* JTRACE */
return (fint)sw;
}
|
game_openmp.c
|
// To compile: make openmp
// To run: mpiexec -n [x] -f machines ./a.out [width] [height] [input_file]
#define _DEFAULT_SOURCE
#define GEN_LIMIT 1000
#define CHECK_SIMILARITY
#define SIMILARITY_FREQUENCY 3
#define THREADS 4
#define true 1
#define false 0
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include <mpi.h>
#include <time.h>
void perror_exit(const char *message)
{
perror(message);
exit(EXIT_FAILURE);
}
void evolve(char **local, char **new, int width_local, int height_local)
{
// Access the cells of the actual grid, leaving out the auxiliary cells
// around the grid, yet, taking them into account for the calculations
#pragma omp parallel for num_threads(THREADS) firstprivate(local, height_local, width_local)
for (int y = 1; y <= height_local; y++)
{
for (int x = 1; x <= width_local; x++)
{
int neighbors = 0;
// Add the value of each cell to neighbors variable
// Adds the ASCII value of each cell, '1' = 49, '0' = 48
neighbors = local[y - 1][x - 1] + local[y - 1][x] +
local[y - 1][x + 1] + local[y][x - 1] +
local[y][x + 1] + local[y + 1][x - 1] +
local[y + 1][x] + local[y + 1][x + 1];
// Determine if the current cell is going to be alive or not
// 387 means that it has 3 neighbors ( (3 * 49) + (5 * 48))
// 386 means that it has 2 neighbors ( (2 * 49) + (6 * 48))
if (neighbors == 387 || (neighbors == 386 && (local[y][x] == '1')))
new[y][x] = '1';
else
new[y][x] = '0';
}
}
}
int empty(char **local, int width_local, int height_local)
{
// Checks if local is empty or not (a.k.a. all the cells are dead)
int result = 0;
#pragma omp parallel for reduction(+ \
: result) num_threads(THREADS) schedule(dynamic) firstprivate(local, height_local, width_local)
for (int y = 1; y <= height_local; y++)
{
for (int x = 1; x <= width_local; x++)
{
if (local[y][x] == '1')
{
result++;
break;
}
}
}
return (!result);
}
int empty_all(char **local, int width_local, int height_local, MPI_Comm *new_comm, int comm_sz)
{
// Calculates if all subgrids are empty
int local_flag = empty(local, width_local, height_local),
global_sum;
MPI_Allreduce(&local_flag, &global_sum, 1, MPI_INT, MPI_SUM, *new_comm);
// Compare the number of instances that have an empty grid
// with the total amount of instances
return (global_sum == comm_sz);
}
int similarity(char **local, char **local_old, int width_local, int height_local)
{
// Check if the internal grid is the same with the previous generation
int result = 0;
#pragma omp parallel for reduction(+ \
: result) num_threads(THREADS) schedule(dynamic) firstprivate(local, local_old, height_local, width_local)
for (int y = 1; y <= height_local; y++)
{
for (int x = 1; x <= width_local; x++)
{
if (local_old[y][x] != local[y][x])
{
result++;
break;
}
}
}
return (!result);
}
int similarity_all(char **local, char **local_old, int width_local, int height_local, MPI_Comm *new_comm, int comm_sz)
{
// Calculates if every subgrid is the same as in the previous generation
int local_flag = similarity(local, local_old, width_local, height_local),
global_sum;
MPI_Allreduce(&local_flag, &global_sum, 1, MPI_INT, MPI_SUM, *new_comm);
// Compare the number of instances that have the same grid
// between generations, with the total number of instances
return (global_sum == comm_sz);
}
void game(int width, int height, char *fileArg)
{
int my_rank, comm_sz;
// Initialize the MPI
MPI_Init(NULL, NULL);
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);
MPI_Comm old_comm, new_comm;
int ndims, reorder, periods[2], dim_size[2];
old_comm = MPI_COMM_WORLD;
ndims = 2; // 2D matrix/grid
int rows_columns = (int)sqrt(comm_sz);
dim_size[0] = rows_columns; // number of rows
dim_size[1] = rows_columns; // number of columns
periods[0] = 1; // rows periodic (each column forms a ring)
periods[1] = 1; // columns periodic (each row forms a ring)
reorder = 1; // allows processes reordered for efficiency
// Create a fully periodic, 2D Cartesian topology
MPI_Cart_create(old_comm, ndims, dim_size, periods, reorder, &new_comm);
int me, coords[2];
MPI_Comm_rank(new_comm, &me);
MPI_Cart_coords(new_comm, me, ndims, coords);
int width_local, height_local;
// Calculate the local dimensions for the local subarrays
width_local = height_local = width / rows_columns;
// Allocate space in each instance for the local array(s)
char **local = malloc((width_local + 2) * sizeof(char *));
char *b = malloc((width_local + 2) * (height_local + 2) * sizeof(char));
if (local == NULL || b == NULL)
perror_exit("malloc: ");
for (int i = 0; i < (width_local + 2); i++)
local[i] = &b[i * (height_local + 2)];
// Allocate space for the new array which holds the next generation of the local grid
char **new = malloc((width_local + 2) * sizeof(char *));
char *a = malloc((width_local + 2) * (height_local + 2) * sizeof(char));
if (new == NULL || a == NULL)
perror_exit("malloc: ");
for (int i = 0; i < (width_local + 2); i++)
new[i] = &a[i * (height_local + 2)];
// Allocate space for the local_input array which holds the input from the shared file
char **local_input = malloc(height_local * sizeof(char *));
char *d = malloc(width_local * height_local * sizeof(char));
if (local_input == NULL || d == NULL)
perror_exit("malloc: ");
for (int i = 0; i < height_local; ++i)
local_input[i] = &d[i * width_local];
MPI_File fh;
MPI_Datatype sub_array;
MPI_Status status;
double t_start = MPI_Wtime();
int sub_size[2];
int whole_size[2];
int start_indices[2];
sub_size[0] = height_local; // Dimensions of the local array
sub_size[1] = width_local;
whole_size[0] = height; // Dimensions of the whole array (with an extra column holding newline chars)
whole_size[1] = width + 1;
start_indices[0] = coords[0] * height_local; // start indices of the local array
start_indices[1] = coords[1] * width_local;
// Creating a subarray datatype for the current process
MPI_Type_create_subarray(ndims, whole_size, sub_size, start_indices, MPI_ORDER_C, MPI_CHAR, &sub_array);
// Commiting the subarray datatype
MPI_Type_commit(&sub_array);
// Opening the file
MPI_File_open(new_comm, fileArg, MPI_MODE_RDONLY, MPI_INFO_NULL, &fh);
// Specifying the part of the file that is visible to the process
MPI_File_set_view(fh, 0, MPI_CHAR, sub_array, "native", MPI_INFO_NULL);
// Reading the part of the file that corresponds to this process and loading it into memory
MPI_File_read_all(fh, &local_input[0][0], (height_local * width_local), MPI_CHAR, &status);
// Closing the file
MPI_File_close(&fh);
// Freeing the memory type
MPI_Type_free(&sub_array);
double msecs = (MPI_Wtime() - t_start) * 1000;
if (me == 0)
printf("Reading file:\t%.2lf msecs\n", msecs);
// Populate the local array with the corresponding portion of the main grid with
// the help of the local_input array
for (int i = 0; i < height_local; i++)
{
for (int j = 0; j < width_local; j++)
{
local[i + 1][j + 1] = local_input[i][j];
}
}
free(local_input); // Freeing up no longer needed memory
free(d);
local_input = NULL;
d = NULL;
int generation = 1;
#ifdef CHECK_SIMILARITY
int counter = 0;
#endif
// Calculating the coordinates of the neighbours, relative to the current process ones
int north;
int south;
int east;
int west;
int north_coords[2];
int south_coords[2];
int west_coords[2];
int east_coords[2];
north_coords[0] = coords[0] + 1;
south_coords[0] = coords[0] - 1;
west_coords[0] = coords[0];
east_coords[0] = coords[0];
north_coords[1] = coords[1];
south_coords[1] = coords[1];
west_coords[1] = coords[1] - 1;
east_coords[1] = coords[1] + 1;
int north_west;
int north_east;
int south_west;
int south_east;
int north_west_coords[2];
int north_east_coords[2];
int south_west_coords[2];
int south_east_coords[2];
north_west_coords[0] = coords[0] - 1;
north_east_coords[0] = coords[0] - 1;
south_west_coords[0] = coords[0] + 1;
south_east_coords[0] = coords[0] + 1;
north_west_coords[1] = coords[1] - 1;
north_east_coords[1] = coords[1] + 1;
south_west_coords[1] = coords[1] - 1;
south_east_coords[1] = coords[1] + 1;
// Get the rank of each direction
MPI_Cart_rank(new_comm, north_coords, &north);
MPI_Cart_rank(new_comm, south_coords, &south);
MPI_Cart_rank(new_comm, west_coords, &west);
MPI_Cart_rank(new_comm, east_coords, &east);
MPI_Cart_rank(new_comm, north_west_coords, &north_west);
MPI_Cart_rank(new_comm, north_east_coords, &north_east);
MPI_Cart_rank(new_comm, south_west_coords, &south_west);
MPI_Cart_rank(new_comm, south_east_coords, &south_east);
// Vector datatype representing columns in an 2D array
MPI_Datatype vertical_type;
MPI_Type_vector(height_local, 1, width_local + 2, MPI_CHAR, &vertical_type);
MPI_Type_commit(&vertical_type);
MPI_Request requests_odd[16];
MPI_Request requests_even[16];
// Communication requests to exchange data from local array
MPI_Recv_init(&local[0][1], width_local, MPI_CHAR, north, 1, new_comm, &requests_odd[0]);
MPI_Send_init(&local[1][1], width_local, MPI_CHAR, north, 2, new_comm, &requests_odd[1]);
MPI_Recv_init(&local[height_local + 1][1], width_local, MPI_CHAR, south, 2, new_comm, &requests_odd[2]);
MPI_Send_init(&local[height_local][1], width_local, MPI_CHAR, south, 1, new_comm, &requests_odd[3]);
MPI_Recv_init(&local[1][width_local + 1], 1, vertical_type, east, 3, new_comm, &requests_odd[4]);
MPI_Send_init(&local[1][width_local], 1, vertical_type, east, 4, new_comm, &requests_odd[5]);
MPI_Recv_init(&local[1][0], 1, vertical_type, west, 4, new_comm, &requests_odd[6]);
MPI_Send_init(&local[1][1], 1, vertical_type, west, 3, new_comm, &requests_odd[7]);
MPI_Recv_init(&local[0][0], 1, MPI_CHAR, north_west, 5, new_comm, &requests_odd[8]);
MPI_Send_init(&local[1][1], 1, MPI_CHAR, north_west, 6, new_comm, &requests_odd[9]);
MPI_Recv_init(&local[0][width_local + 1], 1, MPI_CHAR, north_east, 7, new_comm, &requests_odd[10]);
MPI_Send_init(&local[1][width_local], 1, MPI_CHAR, north_east, 8, new_comm, &requests_odd[11]);
MPI_Recv_init(&local[height_local + 1][0], 1, MPI_CHAR, south_west, 8, new_comm, &requests_odd[12]);
MPI_Send_init(&local[height_local][1], 1, MPI_CHAR, south_west, 7, new_comm, &requests_odd[13]);
MPI_Recv_init(&local[height_local + 1][width_local + 1], 1, MPI_CHAR, south_east, 6, new_comm, &requests_odd[14]);
MPI_Send_init(&local[height_local][width_local], 1, MPI_CHAR, south_east, 5, new_comm, &requests_odd[15]);
// Communication requests to exchange data from new array
MPI_Recv_init(&new[0][1], width_local, MPI_CHAR, north, 1, new_comm, &requests_even[0]);
MPI_Send_init(&new[1][1], width_local, MPI_CHAR, north, 2, new_comm, &requests_even[1]);
MPI_Recv_init(&new[height_local + 1][1], width_local, MPI_CHAR, south, 2, new_comm, &requests_even[2]);
MPI_Send_init(&new[height_local][1], width_local, MPI_CHAR, south, 1, new_comm, &requests_even[3]);
MPI_Recv_init(&new[1][width_local + 1], 1, vertical_type, east, 3, new_comm, &requests_even[4]);
MPI_Send_init(&new[1][width_local], 1, vertical_type, east, 4, new_comm, &requests_even[5]);
MPI_Recv_init(&new[1][0], 1, vertical_type, west, 4, new_comm, &requests_even[6]);
MPI_Send_init(&new[1][1], 1, vertical_type, west, 3, new_comm, &requests_even[7]);
MPI_Recv_init(&new[0][0], 1, MPI_CHAR, north_west, 5, new_comm, &requests_even[8]);
MPI_Send_init(&new[1][1], 1, MPI_CHAR, north_west, 6, new_comm, &requests_even[9]);
MPI_Recv_init(&new[0][width_local + 1], 1, MPI_CHAR, north_east, 7, new_comm, &requests_even[10]);
MPI_Send_init(&new[1][width_local], 1, MPI_CHAR, north_east, 8, new_comm, &requests_even[11]);
MPI_Recv_init(&new[height_local + 1][0], 1, MPI_CHAR, south_west, 8, new_comm, &requests_even[12]);
MPI_Send_init(&new[height_local][1], 1, MPI_CHAR, south_west, 7, new_comm, &requests_even[13]);
MPI_Recv_init(&new[height_local + 1][width_local + 1], 1, MPI_CHAR, south_east, 6, new_comm, &requests_even[14]);
MPI_Send_init(&new[height_local][width_local], 1, MPI_CHAR, south_east, 5, new_comm, &requests_even[15]);
t_start = MPI_Wtime();
// The actual loop of Game of Life
while ((!empty_all(local, width_local, height_local, &new_comm, comm_sz)) && (generation <= GEN_LIMIT))
{
// Different requests for odd and even generations in order to compensate the pointer swap of local and new arrays
if ((generation % 2) == 1)
{
MPI_Startall(16, requests_odd);
MPI_Waitall(16, requests_odd, MPI_STATUSES_IGNORE);
}
else
{
MPI_Startall(16, requests_even);
MPI_Waitall(16, requests_even, MPI_STATUSES_IGNORE);
}
evolve(local, new, width_local, height_local);
// The pointer swap
char **temp_array = local;
local = new;
new = temp_array;
#ifdef CHECK_SIMILARITY
counter++;
if (counter == SIMILARITY_FREQUENCY)
{
if (similarity_all(local, new, width_local, height_local, &new_comm, comm_sz))
break;
counter = 0;
}
#endif
generation++;
} // end of while loop
msecs = (MPI_Wtime() - t_start) * 1000;
if (me == 0) // If I am not the master instance
printf("Generations:\t%d\nExecution time:\t%.2lf msecs\n", generation - 1, msecs);
free(a);
free(new);
a = NULL;
new = NULL;
MPI_Type_free(&vertical_type);
char **local_finished;
char *c;
if (coords[1] == rows_columns - 1) // If this subgrid is on the rightmost position of the cartesian grid
{
local_finished = malloc(height_local * sizeof(char *));
c = malloc((width_local + 1) * height_local * sizeof(char)); // Then it adds a column for the newline char
if (local_finished == NULL || c == NULL)
perror_exit("malloc: ");
for (int i = 0; i < height_local; ++i)
local_finished[i] = &c[i * (width_local + 1)];
for (int i = 0; i < height_local; i++)
local_finished[i][width_local] = '\n';
}
else
{
local_finished = malloc(height_local * sizeof(char *));
c = malloc(width_local * height_local * sizeof(char));
if (local_finished == NULL || c == NULL)
perror_exit("malloc: ");
for (int i = 0; i < height_local; ++i)
local_finished[i] = &c[i * width_local];
}
for (int i = 0; i < width_local; i++) // Copying the array to a new one with only the necessary width/height
{
for (int j = 0; j < height_local; j++)
{
local_finished[i][j] = local[i + 1][j + 1];
}
}
whole_size[0] = height; // Dimensions of the whole array (with an extra column holding newline chars)
whole_size[1] = width + 1;
start_indices[0] = coords[0] * height_local; // Start indices of the local array
start_indices[1] = coords[1] * width_local;
if (coords[1] == rows_columns - 1) // If this subgrid is on the rightmost position of the cartesian grid
width_local++; // then it adds a column for the newline char for the local array
sub_size[0] = height_local; // Dimensions of the local array
sub_size[1] = width_local;
t_start = MPI_Wtime();
MPI_Type_create_subarray(ndims, whole_size, sub_size, start_indices, MPI_ORDER_C, MPI_CHAR, &sub_array); //creating a subarray datatype for the current process
MPI_Type_commit(&sub_array); // Commiting the subarray datatype
int err = MPI_File_open(new_comm, "./openmp_output.out", MPI_MODE_CREATE | MPI_MODE_WRONLY | MPI_MODE_EXCL, MPI_INFO_NULL, &fh); //opening the file
if (err != MPI_SUCCESS) // If the file already exists
{
if (me == 0) // Then the master process deletes it
MPI_File_delete("./openmp_output.out", MPI_INFO_NULL);
MPI_File_open(new_comm, "./openmp_output.out", MPI_MODE_CREATE | MPI_MODE_WRONLY | MPI_MODE_EXCL, MPI_INFO_NULL, &fh); // and the file is opened again
}
// Specifying the part of the file that is visible to the process
MPI_File_set_view(fh, 0, MPI_CHAR, sub_array, "native", MPI_INFO_NULL);
// Writing the local array from memory to the file
MPI_File_write_all(fh, &local_finished[0][0], (height_local * width_local), MPI_CHAR, &status);
// Closing the file
MPI_File_close(&fh);
// Freeing the memory type
MPI_Type_free(&sub_array);
msecs = (MPI_Wtime() - t_start) * 1000;
if (me == 0)
printf("Writing file:\t%.2lf msecs\n", msecs);
// Deallocate space no longer needed
free(b);
free(local);
b = NULL;
local = NULL;
free(c);
free(local_finished);
c = NULL;
local_finished = NULL;
MPI_Finalize();
}
int main(int argc, char *argv[])
{
int width = 0, height = 0;
if (argc > 1)
width = atoi(argv[1]);
if (argc > 2)
height = atoi(argv[2]);
height = width;
if (width <= 0)
width = 30;
if (height <= 0)
height = 30;
if (argc > 3)
game(width, height, argv[3]);
//printf ("Finished\n");
//fflush (stdout);
return 0;
}
|
gene_bin.c
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <mpi.h>
#include "../headers/gene_bin.h"
#include <sys/types.h>
#ifndef __USE_MISC
#define __USE_MISC
#endif
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <errno.h>
#include <nmmintrin.h>
#include <immintrin.h>
int output;
int rank;
/***************************************/
/********** BINARIES FUNCTION **********/
/***************************************/
/**
* Retrieve one bit from the binary array sequence.
*
* in : seq_bin : sequence in binary array format
* in : pos : position of the requested bit (0 <= pos < size_seq * 2)
* out : int : the requested bit
*
* Shifts the seq_bin by pos.
*/
int get_binary_value(const long int *seq_bin, const int pos)
{
int new_pos = pos > int_SIZE ? pos / int_SIZE : 0;
return seq_bin[new_pos] & ((long)1 << (pos - new_pos)) ? 1 : 0;
}
/**
* Change one bit in the binary array sequence.
*
* in : seq_bin : sequence in binary array format
* in : pos : position of the bit to be replaced (0 <= pos < size_seq * 2)
* in : value : new bit value
* out : seq_bin : sequence in binary array format with the one bit changed
*
* Set the bit value of seq_bin at pos position to value
*/
long int *change_binary_value(long int *seq_bin, const int pos, const int value)
{
int new_pos = pos > int_SIZE ? pos / int_SIZE : 0;
if (value)
seq_bin[new_pos] |= ((long)1 << (pos - new_pos));
else
seq_bin[new_pos] &= ~((long)1 << (pos - new_pos));
return seq_bin;
}
/**
* Convert a char formated DNA sequence to its binary array format.
*
* in : seq_char : the DNA seq in it's char* mode
* in : seq_size : size of the array 'seq_char' (number of nucleotides)
* out : seq_bin : sequence in binary array format
*
* Iterates over seq_char and sets seq_bin bit values according to the nucleotide read.
* The non-ACGT nucleotides corresponding to several possible nucleotides are arbitrarily defined.
*/
long int *set_binary_array(const char *seq_char, const size_t seq_size)
{
// Number of bits needed to transform seq_char into a binary array.
int seq_bin_size = 2 * seq_size;
// Binary array new size
int nb = seq_bin_size / int_SIZE;
if (seq_bin_size % int_SIZE != 0)
nb++;
// Allocate memory and verify it has been allocated
long int *seq_bin = NULL;
seq_bin = calloc(nb, sizeof(long int));
if (!seq_bin)
return printf("ERROR: set_binary_array: cannot allocate memory.\n"), NULL;
int pos = 0;
// int bit1, bit2, c;
#pragma omp parallel default(shared)
{
#pragma omp for schedule(static, 64)
for (size_t i = 0; i < seq_size; ++i)
{
// Default char is put to A to handle the warning : wrong size input
// Add '00' bits in this case
int c = 0;
if (!seq_char[i])
printf("WARNING: set_binary_array: size input is different than the char sequence.\n");
else
c = seq_char[i] - 65;
// get the 2-bits value of char read
int bit1, bit2;
bit1 = L[c][0];
bit2 = L[c][1];
pos = 2 * i;
// Set seq_bin bit values according to the nucleotide read
change_binary_value(seq_bin, pos, bit1);
change_binary_value(seq_bin, pos + 1, bit2);
}
}
return seq_bin;
}
/**
* Xor two binary array sequences.
*
* in : seq_bin1 : first sequence in binary array format to xor
* in : seq_size1 : seq_bin1 length (number total of used bits)
* in : seq_bin2 : first sequence in binary array format to xor
* in : seq_size2 : seq_bin2 length (number total of used bits)
* out : xor : binary array sequence resulting from the xor operation between seq1 and seq2
*
* Iterates over sequences value per value.
* Xor the two sequences values since its value is the same length.
* If one sequence is larger than the other, shift the last value of the smaller sequence to xor it with the other value.
* Values from the largest binary array are assigned to the xor result. (x^0 = x)
*/
long int *xor_binary_array(const long int *seq_bin1, const int seq_size1,
const long int *seq_bin2, const int seq_size2)
{
// size of the binary array type used
long int intsize = int_SIZE + 1;
long int *s1, *s2;
long int ss1, ss2;
long int sbs1, sbs2;
// Find the greater binary array, and rename them
if (seq_size1 >= seq_size2)
{ // if s1 is greater or equal than s2
s1 = seq_bin1;
s2 = seq_bin2;
ss1 = seq_size1 / intsize + ((seq_size1 / intsize) % intsize != 0);
sbs1 = seq_size1;
ss2 = seq_size2 / intsize + ((seq_size2 / intsize) % intsize != 0);
sbs2 = seq_size2;
}
else
{ // else if s2 is greater or equal than s1
s1 = seq_bin2;
s2 = seq_bin1;
ss1 = seq_size2 / intsize + ((seq_size2 / intsize) % intsize != 0);
sbs1 = seq_size2;
ss2 = seq_size1 / intsize + ((seq_size1 / intsize) % intsize != 0);
sbs2 = seq_size1;
}
if (ss1 == 0)
ss1 = 1;
if (ss2 == 0)
ss2 = 1;
long int it = 0;
// Allocate memory and verify it has been allocated
long int * xor = NULL;
xor = calloc(ss1, sizeof(*xor));
if (!xor)
return printf("ERROR: xor_binary_array: cannot allocate memory.\n"), NULL;
#pragma omp parallel default(shared)
{
#pragma omp for schedule(static, 64)
for (it = 0; it < ss2 - 1; it++)
xor[it] = s1[it] ^ s2[it];
#pragma omp master
{
// If one sequence is larger than the other, shift the last value of the smaller sequence toxor it with the other value.
xor[ss2 - 1] = s1[ss2 - 1] ^ ((s2[ss2 - 1] << ((sbs1 - sbs2) % intsize)));
}
// Values from the largest binary array are assigned to the xor result. (x^0 = x)
#pragma omp for schedule(static, 64)
for (it = ss2; it < ss1; it++)
xor[it] = s1[it];
}
return xor;
}
/**
* Popcount a binary array sequence.
*
* in : seq_bin : sequence in binary array format
* in : seq_size : seq_bin length (number total of used bits)
* out : bin_popcount : popcount of the seq : number of '1'
*
* Iterates on seq_bin and for each value, adds its popcount to bin_popcount.
*/
int popcount_binary_array(const long int *seq_bin, const long int seq_size)
{
int bin_popcount = 0;
// Find the size of the binary array
long int array_size = seq_size / int_SIZE;
if (seq_size % int_SIZE != 0)
array_size++;
#pragma omp parallel default(shared)
{
#pragma omp for schedule(static, 64) reduction(+ \
: bin_popcount)
for (long i = 0; i < array_size; ++i)
bin_popcount += __builtin_popcount(seq_bin[i]);
}
return bin_popcount;
}
/**
* Retrieve a piece of the binary array sequence.
*
* in : seq_bin : sequence in binary array format
* in : size : size of the binary requested
* out : piece_seq_bin : the requested part of seq_bin, from pos_start and size.
*
* Iterates on seq_bin from pos_start, size times and gets for each iteration its binary value.
*/
long int *get_piece_binary_array(const long int *seq_bin, const unsigned long long pos_start, const unsigned long long pos_stop)
{
// Find the size of the output
long int array_size = (pos_stop - pos_start) / int_SIZE + ((pos_stop - pos_start) % int_SIZE != 0);
// Allocate memory and verify it has been allocated
long int *piece_seq_bin = NULL;
piece_seq_bin = calloc(array_size, sizeof(*seq_bin));
if (!piece_seq_bin)
return printf("ERROR: get_piece_binary_array: cannot allocate memory.\n"), NULL;
// stop position.
// Parse the binary array,
// from the bit at 'pos_start' position to 'pos_stop' position
#pragma omp parallel default(shared)
{
#pragma omp for schedule(static, 64)
for (int i = (int)pos_start; i < (int)pos_stop; i++)
{
int tmp = i - pos_start;
change_binary_value(piece_seq_bin, (int)tmp, get_binary_value(seq_bin, (int)i));
}
}
return piece_seq_bin;
}
/***************************************/
/******** DNA & GENES FUNCTION *********/
/***************************************/
//////////////// Convert to binary
/**
* Convert a DNA base sequence to its binary array format.
*
* in : dna_seq : DNA sequence in char array format
* in : size : dna_seq length = number of nucleotides (= number of letters)
* out : seq : DNA sequence in binary array format
*
* Calls set_binary_array.
*/
long int *convert_to_binary(const char *dna_seq, size_t size)
{
return set_binary_array(dna_seq, size);
}
//////////////// Convert binary aa to codon
/**
* Convert a DNA sequence in binary array format to its DNA bases.
*
* in : bin_dna_seq : DNA sequencDNA sequence in binary array format
* in : size : total number total of used bits in the sequence bin_dna_seq
* out : dna_seq : DNA sequence in char array format
*
* For each pair of bits in bin_dna_seq, append to dna_seq its corresponding nucleotide.
*/
char *binary_to_dna(long int *bin_dna_seq, const unsigned size)
{
if (size % 2 != 0)
{
printf("Error: binary_to_aa : wrong binary size (%d). Must be odd.\nExit.\n", size);
return NULL;
}
// Allocate memory and verify it has been allocated
char *dna_seq = calloc((size / 2) + 1, sizeof(*dna_seq));
if (!dna_seq)
return printf("ERROR: binary_to_dna: cannot allocate memory.\n"), NULL;
// Parse the binary array, two bits per iteration
unsigned i;
int nucl1, nucl2, index;
char value;
#pragma omp parallel shared(bin_dna_seq, size, dna_seq, i) private(nucl1, nucl2, index, value)
{
#pragma omp for schedule(static, 32)
for (i = 0; i < size; i += 2)
{
// nucleotides = A, T, G, C
nucl1 = get_binary_value(bin_dna_seq, i);
nucl2 = get_binary_value(bin_dna_seq, i + 1);
// get the ASCII value according to bits value
value = bitstocharDNA[nucl2 + 2 * nucl1];
index = i / 2;
dna_seq[index] = value;
}
}
return dna_seq;
}
//////////////// Generating mRNA
/**
* Convert a DNA sequence in binary array format to its mRNA sequence.
*
* in : gene_seq : DNA sequence in binary array format
* in : seq_size : number total of used bits in the sequence gene_seq
* out : rna_seq : resulting mRNA sequence in char array format
* Convert a binary DNA sequence to a string mRNA sequence
*
* For each pair of bits in bin_dna_seq, append to dna_seq its corresponding nucleotide in mRNA. (T -> U)
*/
char *generating_mRNA(const long int *gene_seq, const unsigned long long start_pos, const unsigned long long stop_pos)
{
// Check the input argument
if (!gene_seq)
return printf("ERROR: generating_mRNA: undefined sequence\n"), NULL;
// Allocate memory and verify it has been allocated
char *rna_seq = NULL;
rna_seq = malloc(sizeof(*rna_seq) * ((stop_pos - start_pos) / 2) + 2);
if (!rna_seq)
return printf("ERROR: generating_mRNA: cannot allocate memory\n"), NULL;
long int i;
int nucl1, nucl2;
char value;
long index;
#pragma omp parallel shared(gene_seq, start_pos, stop_pos, i) private(nucl1, nucl2, value, index)
{
// Parse the binary DNA sequence, two bits per iteration
#pragma omp for schedule(static, 32)
for (i = start_pos; i < stop_pos; i += 2)
{
// nucleotides = A, U, G, C
nucl1 = get_binary_value(gene_seq, i);
nucl2 = get_binary_value(gene_seq, i + 1);
index = (i + 1 - start_pos) / 2;
// get the ASCII value according to bits value
value = bitstocharmRNA[nucl2 + 2 * nucl1];
rna_seq[index] = value;
}
}
// rna_seq[stop_pos / 2] = '\0';
rna_seq[((stop_pos - start_pos) / 2) + 1] = '\0';
return rna_seq;
}
//////////////// Detecting genes
/**
* Detects genes in the mRNA sequence in binary array format and maps them.
*
* in : gene : mRNA sequence in binary array format
* in : gene_size : number total of used bits in the sequence gene
* in : gene_map : gene mapping struct
* out : void
*
* Iterates in the gene, and for each packet of 6 binary bits (corresponding to a nucleotide), searches for a start codon (AUG).
* If a start codon is found, iterate until a stop codon is found (UAA, UAG or UGA).
* If a stop codon is found, append to gene_map the gene length (from start to stop codon), its start position and stop one.
*
* NB : The gene in binary array form can correspond to an mRNA or DNA sequence, since it is stored in the same way.
*/
void detecting_genes(const long int *gene, const long int gene_size, gene_map_t *gene_map)
{
gene_map->genes_counter = 0;
// Check if memory ever have been allocated and allocate it if not
if (!gene_map->gene_start || !gene_map->gene_end)
{
gene_map->gene_start = malloc(sizeof(*gene_map->gene_start) * MAX_GENES);
gene_map->gene_end = malloc(sizeof(*gene_map->gene_end) * MAX_GENES);
if (!gene_map->gene_start || !gene_map->gene_end)
{
printf("ERROR: detecting_genes: cannot allocate memory\n");
return;
}
}
// Start codon
const __m128i AUG = _mm_set_epi16(0, 0, 1, 1, 0, 1, 0, 0);
// Stop codons
const __m128i UAA = _mm_set_epi16(1, 1, 0, 0, 0, 0, 0, 0);
const __m128i UGA = _mm_set_epi16(1, 1, 0, 1, 0, 0, 0, 0);
const __m128i UAG = _mm_set_epi16(1, 1, 0, 0, 0, 1, 0, 0);
__m128i codon_to_test = _mm_setzero_si128();
int start_pos = -1;
long int i = 0;
// Parse the binary array, and find all the start and stop codons
while ((i + 6) <= gene_size)
{
// Each nucleotides can be A, U, G or C
codon_to_test = _mm_set_epi16(get_binary_value(gene, i),
get_binary_value(gene, i + 1),
get_binary_value(gene, i + 2),
get_binary_value(gene, i + 3),
get_binary_value(gene, i + 4),
get_binary_value(gene, i + 5),
0, 0);
const __m128i cmp_AUG = _mm_xor_si128(codon_to_test, AUG);
const __m128i cmp_UAA = _mm_xor_si128(codon_to_test, UAA);
const __m128i cmp_UAG = _mm_xor_si128(codon_to_test, UAG);
const __m128i cmp_UGA = _mm_xor_si128(codon_to_test, UGA);
// If a start pos and a stop pos doesn't exist, search for AUG
if (_mm_testz_si128(cmp_AUG, cmp_AUG))
{
// if AUG, it's the start of a gene
start_pos = i;
i += 6;
}
else if ((start_pos != -1) && (_mm_testz_si128(cmp_UAA, cmp_UAA) || _mm_testz_si128(cmp_UAG, cmp_UAG) || _mm_testz_si128(cmp_UGA, cmp_UGA)))
{
// It's the end of a gene
// If a start pos and an stop pos has been found, a gene exists so we save it in the struc
gene_map->gene_start[gene_map->genes_counter] = start_pos;
gene_map->gene_end[gene_map->genes_counter] = i + 5;
gene_map->genes_counter++;
start_pos = -1;
i += 6;
}
else
i += 2;
}
}
/**
* Retrives amino acid chains in a mRNA sequence in binary array format.
*
* in : gene_seq : DNA sequence in binary array format
* in : seq_size : gene_seq length (number total of used bits)
* out : aa_seq : char array of proteins symbols.
*
* The program parses the mRNA sequence, verify its length (seq_size).
* Then iterates on gene_seq and for each packet of 6 binary bits (corresponding to a nucleotide), append to aa_seq its corresponding protein symbol.
*
* NB : The gene in binary array form can correspond to an mRNA or DNA sequence, since it is stored in the same way.
*/
char *generating_amino_acid_chain(const long int *gene_seq, const unsigned long long start_pos, const unsigned long long stop_pos)
{
long int codon_size = 6;
// Check the input argument
if (!gene_seq)
return printf("ERROR: generating_amino_acid_chain: undefined sequence\n"), NULL;
if ((stop_pos - start_pos) % 3 != 0)
return NULL;
// Allocate memory and verify it has been allocated
char *aa_seq = calloc(sizeof(char), sizeof(*aa_seq) * ((stop_pos - start_pos) / codon_size) + 1);
if (!aa_seq)
return printf("ERROR: generating_amino_acid_chain: cannot allocate memory\n"), NULL;
unsigned temp = 0;
long int k;
int tmp, pow_bit, get_bin;
long int i, size = stop_pos - start_pos;
#pragma omp parallel shared(gene_seq, start_pos, codon_size, size, aa_seq, i) private(k, temp, tmp, pow_bit, get_bin)
{
// Parse the binary array, six bits by six (to parse three nucleotides per three)
#pragma omp for schedule(static, 64 / codon_size)
for (i = start_pos; i < stop_pos; i += codon_size)
{
temp = (i - start_pos) / codon_size;
// Get the decimal value of the 6 bits
tmp = 0;
pow_bit = 5;
for (k = i; k < i + codon_size; k++)
{
get_bin = get_binary_value(gene_seq, k);
tmp += get_bin << pow_bit;
pow_bit--;
}
// Get the corresponding protein from the lookup table
aa_seq[temp] = LUT[tmp];
}
}
aa_seq[size / codon_size] = '\0';
return aa_seq;
}
/**
* Detects probable mutation areas.
*
* in : gene_seq : DNA sequence in binary array format
* in : size_sequence : gene_seq length (number total of used bits)
* in : mut_m : map of the possible mutation's areas
* out : void
*
* The algorithm scans a gene sequence and locates the high frequency of GC DNA bases in the sequence.
* Must be at least 1/5th of the gene length
* Precondition: gene_seq is of size size_sequence.
*
* NB : The gene in binary array form can correspond to an mRNA or DNA sequence, since it is stored in the same way.
*/
void detecting_mutations(const long int *gene_seq, const unsigned long long start_pos, const unsigned long long stop_pos,
mutation_map mut_m)
{
unsigned long long detect_mut = 0;
unsigned long long size_sequence = stop_pos - start_pos; // Counting size of GC sequence
unsigned short tmp_start_mut = 0; // stock start mutation
unsigned cmp = 0; // counter of all mutation zones
const __m128i G = _mm_set_epi64x((long)0, (long)1);
const __m128i C = _mm_set_epi64x((long)1, (long)0);
// long size = start_pos + size_sequence;
// Parse the binary array, from the 'start_pos' bit to the end
for (unsigned long long i = start_pos; i < stop_pos; i += 2)
{
// each nucleotides can be A, U, G or C
const long bit1 = (long)get_binary_value(gene_seq, i);
const long bit2 = (long)get_binary_value(gene_seq, i + 1);
const __m128i nucl = _mm_set_epi64x(bit1, bit2);
const __m128i cmp_G = _mm_xor_si128(nucl, G);
const __m128i cmp_C = _mm_xor_si128(nucl, C);
// Increment detect_mut if find a C or G nucl
if (_mm_testz_si128(cmp_G, cmp_G) || _mm_testz_si128(cmp_C, cmp_C))
{
if (detect_mut == 0)
tmp_start_mut = i - start_pos;
detect_mut += 2;
}
// Put detect_mut to 0 if find a A or T nucl
else
{
// Check if previous GC sequence is a probable mutation zone
if (detect_mut >= (size_sequence / 5))
{
mut_m.start_mut[cmp] = tmp_start_mut;
mut_m.end_mut[cmp] = (i)-start_pos;
mut_m.size[cmp] = detect_mut - 1;
cmp++;
}
detect_mut = 0;
}
}
// Check if ending sequence is a probable mutation zone
if (detect_mut >= (size_sequence / 5))
{
mut_m.start_mut[cmp] = tmp_start_mut;
mut_m.end_mut[cmp] = size_sequence;
mut_m.size[cmp] = detect_mut - 1;
cmp++;
}
}
#ifdef __AVX512VPOPCNTDQ__
__attribute__((target("avx512vpopcntdq", "avx512f"))) float calculating_matching_score(long int *seq1, const int seq_size1,
long int *seq2, const int seq_size2)
{
// Check the input argument
if (!seq1 || !seq2)
return printf("ERROR: calculating_matching_score: undefined sequence\n"), -1.0;
long int *big_seq = NULL, *small_seq = NULL;
int len_big = 0, len_small = 0, diff_len = 0;
// Find and rename the biggest/smallest sequences
// !! size = number of bits, length = size of the array (= size/int_SIZE)
if (seq_size1 >= seq_size2)
{
big_seq = seq1;
small_seq = seq2;
len_big = seq_size1 / int_SIZE;
if (seq_size1 % int_SIZE != 0)
len_big++;
len_small = seq_size2 / int_SIZE;
if (seq_size2 % int_SIZE != 0)
len_small++;
}
else
{
big_seq = seq2;
small_seq = seq1;
len_big = seq_size2 / int_SIZE;
if (seq_size2 % int_SIZE != 0)
len_big++;
len_small = seq_size1 / int_SIZE;
if (seq_size1 % int_SIZE != 0)
len_small++;
}
// Parse both seqences from the end
/**
* (Need to add some "0" at the beginning, if too small)
*
* big = l1 l2 l3 l4 l5
* small = 0 0 l3' l4' l5'
* ---------------------------------------------
* xor = l1 l2 l3^l3' l4^l4' l5^l5'
*/
int pop = 0;
int j = len_small;
for (int i = len_big; i > 0; i -= 8)
{
const long x0 = j >= 0 ? (long)small_seq[j - 1] : (long)0;
const long x1 = j - 1 >= 0 ? (long)small_seq[j - 2] : (long)0;
const long x2 = j - 2 >= 0 ? (long)small_seq[j - 3] : (long)0;
const long x3 = j - 3 >= 0 ? (long)small_seq[j - 4] : (long)0;
const long x4 = j - 4 >= 0 ? (long)small_seq[j - 5] : (long)0;
const long x5 = j - 5 >= 0 ? (long)small_seq[j - 6] : (long)0;
const long x6 = j - 6 >= 0 ? (long)small_seq[j - 7] : (long)0;
const long x7 = j - 7 >= 0 ? (long)small_seq[j - 8] : (long)0;
const long y0 = j >= 0 ? (long)big_seq[i - 1] : (long)0;
const long y1 = j - 1 >= 0 ? (long)big_seq[i - 2] : (long)0;
const long y2 = j - 2 >= 0 ? (long)big_seq[i - 3] : (long)0;
const long y3 = j - 3 >= 0 ? (long)big_seq[i - 4] : (long)0;
const long y4 = j - 4 >= 0 ? (long)big_seq[i - 5] : (long)0;
const long y5 = j - 5 >= 0 ? (long)big_seq[i - 6] : (long)0;
const long y6 = j - 6 >= 0 ? (long)big_seq[i - 7] : (long)0;
const long y7 = j - 7 >= 0 ? (long)big_seq[i - 8] : (long)0;
const __m512i xor = _mm512_xor_epi64(_mm512_set_epi64(y0, y1, y2, y3, y4, y5, y6, y7),
_mm512_set_epi64(x0, x1, x2, x3, x4, x5, x6, x7));
const __m512i popcnt = _mm512_popcnt_epi64(xor);
pop += _mm512_reduce_add_epi64(popcnt);
j -= 8;
}
const float denom = 1.0 / (float)(len_big * int_SIZE);
const float F = pop ? (float)pop * 100.0 * denom : 0.0;
return 100.0 - F;
}
#else
/**
* Calculates the matching score of two binary array sequences.
*
* in : seq1 : first sequence in binary
* in : sequence_size1 : number total of used bits in the sequence seq1
* in : seq2 : second sequence in binary
* in : sequence_size2 : number total of used bits in the sequence seq2
* out : float :
*
* The algorithms runs the hamming distance between two binary sequences, and return their matching score percentage
*/
float calculating_matching_score(long int *seq1, const int seq_size1,
long int *seq2, const int seq_size2)
{
// Check the input argument
if (!seq1 || !seq2)
return printf("ERROR: calculating_matching_score: undefined sequence\n"), -1.0;
// First step: apply the xor operation between both arrays
long int * xor = NULL;
xor = xor_binary_array(seq1, seq_size1, seq2, seq_size2);
// xor_size = max size between 'seq_size1' and 'seq_size2'
int xor_size = seq_size1 >= seq_size2 ? seq_size1 : seq_size2;
// Second step: count the number of bits whose value is 1 on the result
int pop = popcount_binary_array(xor, xor_size);
// Last step: compute the percentage
float y = ((float)pop * 100.0) / (float)xor_size;
return 100.0 - y;
}
#endif
#define MAX(x, y) ((x) > (y) ? (x) : (y))
//////////////// Print Similarity Matrix
/**
* Prints the similarity matrix
*
* in : F : The similarity matrix in COL MAJOR. Its dimensions are `m*n`.
* in : A : Horizontal char array. Its size is `m-1`
* in : B : Vertical char array. Its size is `n-1`
* in : m : Number of columns of `F`. Also the `A` length + 1
* in : n : Number of lines of `F`. Also the `B` length + 1
* in : k : Colors background of selected case in `F`, which position is `k` and `l`. Defaults it to 0 if not intended to use.
* in : l : Colors background of selected case in `F`, which position is `k` and `l`. Defaults it to 0 if not intended to use.
*/
void print_sim_mat(int* F, char A [], char B [], int m, int n, int k, int l) {
printf("%3s %3s ", "*", "-");
for (int j = 0; j < m; j++)
printf("%3c ", A[j]);
printf("\n");
for (int i = 0; i < n; i++) {
printf("%3c ", i == 0 ? '-' : B[i - 1]);
for (int j = 0; j < m; j++) {
if (i == k && j == l)
printf("\033[101m% 3d \033[0m", F[i * m + j]);
else
printf("% 3d ", F[i * m + j]);
}
printf("\n");
}
}
//////////////// Calculate Similarity Matrix (anti-diagonal)
/**
* Calculates the similarity matrix of two sequences.
* Iteration method is anti-diagonal
* Sequences are stored as char arrays.
* One extra space for the similarity matrix is required, its returned dimensions are (`A` length+1)*(`B` length+1`
*
* in : A : Horizontal char array.
* in : B : Vertical char array.
* in : match : Score for a match.
* in : mismatch : Score for a mismatch.
* in : gap : Score for a gap.
* out : F : The similarity matrix in COL MAJOR. <!> Its dimensions are (`A` length+1)*(`B` length+1).
*/
int* calculate_scoring_matrix_antidiag(char A [], char B [], int match, int mismatch, int gap) {
int m = strlen(A) + 1;
int n = strlen(B) + 1;
int* F = NULL;
F = (int*)calloc(m * n, sizeof(int));
int diag = 0;
int left = 0;
int up = 0;
// Setting F borders
for (int i = 0; i < m; i++)
F[i] = gap * i;
for (int j = 0; j < n; j++)
F[j * m] = gap * j;
int max_l, i, j;
for (int k = 1; k < m + n - 2; k++) {
if (k > (m - 1)) {
max_l = n - (k - (m - 1)) - 1;
if (max_l > m - 1) max_l = m - 1;
}
else max_l = k;
#pragma omp parallel for schedule(guided)
for (int l = 1; l <= max_l; l++) {
if (k > (m - 1)) {
i = k - (m - 1) + l;
j = (m - 1) - l + 1;
}
else {
i = l;
j = k - i + 1;
}
diag = F[(i - 1) * m + j - 1] + (A[j - 1] == B[i - 1] ? match : mismatch);
up = F[(i - 1) * m + j] + gap;
left = F[i * m + j - 1] + gap;
int var = MAX(MAX(diag, left), up);
F[i * m + j] = var;
}
}
return F;
}
//////////////// String Insert
/**
* Insert a char at beginning of a char array.
*
* in/out : dest : Destination string, to which we insert the `source` char
* in : source : Char to be inerted at beginning of `dest`.
*/
void string_insert(char** dest, char* source) {
if (*dest == NULL) {
*dest = calloc(sizeof(char), 2);
memcpy(*dest, source, 1);
return;
}
char* temp = calloc(sizeof(char), strlen(*dest) + 2);
memcpy(temp, source, 1);
strcat(temp, *dest);
free(*dest);
*dest = temp;
}
//////////////// Align
/**
* Backtrace the similarity matrix, and prints the two sequences aligned.
* Returns the max similarity score of the two sequences.
*
* in : F : The similarity matrix in COL MAJOR. Its dimensions are given by (`A` length + 1)*(`B` length + 1).
* in : A : Horizontal char array.
* in : B : Vertical char array.
* in : match : Score for a match.
* in : mismatch : Score for a mismatch.
* in : gap : Score for a gap.
* in : print : Enables (1) or Disables (0) alignment output. Returns max similarity score either ways.
* out : Max similarity score of the `A` and `B` sequences.
*/
int align(int* F, char A [], char B [], int match, int mismatch, int gap, int print) {
int m = strlen(A) + 1;
int n = strlen(B) + 1;
if (print) {
int i = m - 1;
int j = n - 1;
char* A_aligned = NULL;
char* B_aligned = NULL;
while (i > 0 || j > 0) {
if (i > 0 && j > 0 && F[i * m + j] == F[(i - 1) * m + j - 1] + (A[i - 1] == B[j - 1] ? match : mismatch)) {
string_insert(&A_aligned, A + (i - 1));
string_insert(&B_aligned, B + (j - 1));
i--;
j--;
}
else if (i > 0 && F[i * m + j] == F[(i - 1) * m + j] + gap) {
string_insert(&A_aligned, A + (i - 1));
string_insert(&B_aligned, "-");
i--;
}
else {
// else if (j > 0 && F[i * m + j] == F[i * m + j - 1] + gap) {
string_insert(&A_aligned, "-");
string_insert(&B_aligned, B + (j - 1));
j--;
}
}
printf("%s\n", A_aligned);
printf("%s\n", B_aligned);
}
return F[m * n - 1];
}
//////////////// Needleman-Wunsch (anti-diag)
/**
* Basic Needleman-Wunsch application.
* Given two char arrays, returns the maximum similarity score.
*
* in : A : Horizontal char array.
* in : B : Vertical char array.
* in : m : Length of `A`.
* in : n : Length of `B`.
* out : Max similarity score of the `A` and `B` sequences.
*/
int needleman_wunsch_antidiag(char A[], char B[]) {
int m = strlen(A);
int n = strlen(B);
int match = 1;
int mismatch = -1;
int gap = -1;
int* F = calculate_scoring_matrix_antidiag(A, B, match, mismatch, gap);
// int score = align(F, A, B, match, mismatch, gap, 1);
// printf("Max score : %d\n", score);
int score = F[(m + 1) * (n + 1) - 1];
free(F);
return score;
}
/* Count files in a directory
*
*/
int countfiles()
{
int count = 0;
struct dirent *entry;
DIR *dir = opendir("./fastas/");
while ((entry = readdir(dir)) != NULL)
{
if (strstr(entry->d_name, ".fasta"))
count++;
}
closedir(dir);
return count;
}
void insert_list(node_t **head, long int *data, int size)
{
if (data == NULL)
printf("Error data \n");
node_t *tmp_node = (node_t *)malloc(sizeof(node_t));
node_t *last = *head;
tmp_node->seq = malloc(sizeof(long) * (size));
for (int i = 0; i < size; i++)
{
tmp_node->seq[i] = data[i];
}
tmp_node->size = size;
tmp_node->next = NULL;
if (*head == NULL)
{
tmp_node->prev = NULL;
*head = tmp_node;
}
else
{
while (last->next != NULL)
last = last->next;
last->next = tmp_node;
tmp_node->prev = last;
}
}
int readfiles(int comm_size, int nbseq){
int align_rank = comm_size - 1;
int nb = countfiles();
char **content = malloc(sizeof(char *) * nb);
FILE *fp;
if (output == 1){
struct stat st = {0};
if (stat("./output/", &st) == -1)
mkdir("./output/", 0700);
fp = fopen("./output/rapport_bin.html", "w+");
if (fp == NULL){
printf("Cannot open file \n");
exit(0);
}
fprintf(fp, "<html>\n<head><style>\n th, td {\n font - size : 10px; \n}\n.title {\n font - size : 15px; \n}\ntable, th, td {\n border:\n 1px solid black;\n border - collapse : collapse;\n border - style : dashed;\n}\n.title {\n border - style : dashed dashed dashed solid;\n padding - left : 1 %% ;\n}\ntable {\n width:\n 90 %% ;\n margin - left : 5 %% ;\n}\n\n\ndetails > summary {\n padding:\n 4px;\n width:\n 200px;\n background - color : #eeeeee;\n border:\n none;\n box - shadow : 1px 1px 2px #bbbbbb;\n cursor:\n help;\n}\n</style>\n</head>\n");
}
DIR *dir;
FILE *input;
struct dirent *file;
char folder_name[50] = "./fastas/";
// Open the directory which contain all the fastas files
if ((dir = opendir(folder_name)) == NULL)
return printf("Error: Can't open fastas folder\n"), -1;
int i = 0;
node_t *head = NULL;
// Iterate if a file exists in this directory
while (((file = readdir(dir)) != NULL) && (i < nbseq)){
// Skip directories (linux)
if (file->d_type == DT_DIR)
continue;
if ((!strcmp(file->d_name, ".")) && (!strcmp(file->d_name, "..")))
continue;
printf("Reading file : %s\n", file->d_name);
// Get filepath
char *filepath = NULL;
filepath = malloc(sizeof(char) * (strlen(folder_name) + strlen(file->d_name)));
strcpy(filepath, folder_name);
strcat(filepath, file->d_name);
// Get file size (will be used for content allocation)
struct stat st;
stat(filepath, &st);
long filesize = st.st_size;
content[i] = (char *)malloc(filesize * sizeof(char));
// Open fasta file
if ((input = fopen(filepath, "r")) == NULL)
return printf("Error: Can't open fastas file %s\n", filepath), -1;
char *line;
size_t len = 0;
ssize_t read;
// Skipping first line, as it's only fasta's metadata.
read = getline(&line, &len, input);
// Init content[i] with second line (first data line)
content[i] = malloc((filesize - read - 1) * sizeof(char));
getline(&line, &len, input);
line[strcspn(line, "\n") - 1] = '\0';
strcpy(content[i], line);
// Concat each lines in content[i], while toggling newline.
while ((read = getline(&line, &len, input)) != -1){
line[strcspn(line, "\n") - 1] = '\0';
strcat(content[i], line);
}
free(line);
fclose(input);
int recv = i % (comm_size - 2) + 1;
if (output)
fprintf(fp, "<details><summary> %s </summary>\n<a href=\"sequences/rank_%d_%d_bin.html\"> %s </a></details>\n", file->d_name, recv, i / comm_size, file->d_name);
// printf("%d) sending to %d\n", rank, recv);
MPI_Send(content[i], strlen(content[i]), MPI_CHAR, recv, 0, MPI_COMM_WORLD);
// Sends seq for alignment purposes.
MPI_Send(content[i], strlen(content[i]), MPI_CHAR, align_rank, 4, MPI_COMM_WORLD);
i++;
}
if (closedir(dir) == -1)
return printf("Error close dir\n"), -1;
MPI_Send(&i, 1, MPI_INT, align_rank, 5, MPI_COMM_WORLD);
i = 0;
// Sends the sequence count to receiver. Ends communication from MASTER to receiver
for (int j = 1; j < comm_size - 1; j++)
MPI_Send(&i, 1, MPI_INT, j, 1, MPI_COMM_WORLD);
int cont = 1;
MPI_Status status;
// printf("%d) comm_size = %d", rank, comm_size);
// while (cont < comm_size) {
do
{
MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
if (status.MPI_TAG == 3)
{
MPI_Recv(&i, 1, MPI_INT, status.MPI_SOURCE, 3, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
cont++;
// printf("cont = %d comm_size = %d \n", cont, comm_size);
}
else
{
// printf("%d receive from %d | tag : %d\n", rank, status.MPI_SOURCE, status.MPI_TAG);
int count;
MPI_Get_count(&status, MPI_LONG, &count);
long int *tmp = malloc(sizeof(long int) * count);
MPI_Recv(tmp, count, MPI_LONG, status.MPI_SOURCE, 2, MPI_COMM_WORLD, &status);
insert_list(&head, tmp, count);
free(tmp);
}
} while (cont < comm_size - 1);
printf("Rank 0 ended receiving data\n");
node_t *seq1;
node_t *seq2;
seq1 = head;
// printf("%ld\n", seq1->seq[0]);
FILE *comp;
if (output)
{
fprintf(fp, "<details><summary> %s </summary>\n<a href=\"comp/comp_bin.html\"> Matching score </a></details>\n", "");
struct stat st = {0};
if (stat("./output/comp", &st) == -1)
{
mkdir("./output/comp", 0700);
}
comp = fopen("./output/comp_bin.html", "w+");
if (fp == NULL)
{
printf("Cannot open file \n");
exit(0);
}
fprintf(comp, "<html>\n<head><style>\n th, td {\n font - size : 10px; \n}\n.title {\n font - size : 15px; \n}\ntable, th, td {\n border:\n 1px solid black;\n border - collapse : collapse;\n border - style : dashed;\n}\n.title {\n border - style : dashed dashed dashed solid;\n padding - left : 1 %% ;\n}\ntable {\n width:\n 90 %% ;\n margin - left : 5 %% ;\n}\n\n\ndetails > summary {\n padding:\n 4px;\n width:\n 200px;\n background - color : #eeeeee;\n border:\n none;\n box - shadow : 1px 1px 2px #bbbbbb;\n cursor:\n help;\n}\n</style>\n</head>\n");
fprintf(comp, "<table>\n<tbody>\n<tr>\n<td class = \"title\">Sequence 1</td>\n<td class = \"title\">Sequence 2</td>\n<td class = \"title\">Score</td></tr>\n");
}
while (seq1 != NULL)
{
seq2 = seq1->next;
while (seq2 != NULL)
{
// printf("%ld\n", seq2->seq[0]);
float calc = calculating_matching_score(seq1->seq, seq1->size * 32, seq2->seq, seq2->size * 32);
if (output)
fprintf(comp, "<tr><td>%s</td><td>%s</td><td>%f</td></tr>", binary_to_dna(seq1->seq, seq1->size * 32), binary_to_dna(seq2->seq, seq2->size * 32), calc);
// printf("Matching score : %f\n", calc);
seq2 = seq2->next;
}
seq1 = seq1->next;
}
// Free everything
free(content);
if (output)
{
fprintf(comp, "</table> </body></html>");
fclose(comp);
fprintf(fp, "</html>");
fclose(fp);
}
printf("Rank 0 terminated\n");
return 0;
}
void alignment_work(int rank) {
int real_nb_seqs = 0;
MPI_Status sta;
char** seq = malloc(sizeof(char*) * 200);
int cont = 1;
int i = 0;
int flag;
while (cont) {
MPI_Status status;
MPI_Iprobe(0, MPI_ANY_TAG, MPI_COMM_WORLD, &flag, &status);
if (flag) {
if (status.MPI_TAG == 5) {
MPI_Status sta;
MPI_Recv(&real_nb_seqs, 1, MPI_INT, 0, 5, MPI_COMM_WORLD, &sta);
if (i == real_nb_seqs)
cont = 0;
}
else if (status.MPI_TAG == 4) {
int count = 0;
MPI_Get_count(&status, MPI_CHAR, &count);
seq[i] = (char*)malloc(sizeof(char) * count);
MPI_Recv(seq[i], count, MPI_CHAR, 0, 4, MPI_COMM_WORLD, &sta);
i++;
if (real_nb_seqs && i == real_nb_seqs)
cont = 0;
}
}
}
for (int i = 0; i < real_nb_seqs - 1; i++) {
needleman_wunsch_antidiag(seq[i], seq[i+1]);
// printf("*%d\tAlignment score (%d:%d) : %d\n", rank, i, i+1, score);
printf("Rank %d - %.0f%% (%d/%d)\n", rank, (float)(i + 1) / (real_nb_seqs-1) * 100, (i + 1), real_nb_seqs-1);
free(seq[i]);
}
free(seq[real_nb_seqs-1]);
free(seq);
}
void process_work(int rank)
{
int flag;
int cont = 1;
int nb = countfiles();
char *seq[nb];
int i = 0;
int count = 0;
while (cont)
{
MPI_Status status;
MPI_Iprobe(0, MPI_ANY_TAG, MPI_COMM_WORLD, &flag, &status);
if (flag)
{
if (status.MPI_TAG == 1)
{
MPI_Status sta;
MPI_Recv(&count, 1, MPI_INT, 0, 1, MPI_COMM_WORLD, &sta);
cont = 0;
}
else
{
MPI_Get_count(&status, MPI_CHAR, &count);
seq[i] = (char *)malloc(sizeof(char) * count);
MPI_Recv(seq[i], count, MPI_CHAR, 0, 0, MPI_COMM_WORLD, &status);
i++;
}
}
}
for (int j = 0; j < i; j++)
{
gene_map_t gene_map;
long *seq_bin;
long len_seq;
seq_bin = convert_to_binary(seq[j], strlen(seq[j]));
len_seq = strlen(seq[j]) * 2;
gene_map.gene_start = malloc(sizeof(*gene_map.gene_start) * strlen(seq[j]) * int_SIZE);
gene_map.gene_end = malloc(sizeof(*gene_map.gene_end) * strlen(seq[j]) * int_SIZE);
detecting_genes(seq_bin, len_seq, &gene_map);
// printf("*%d\tGenes detected : %lld\n", rank, gene_map.genes_counter);
FILE *fp;
if (output){
struct stat st = {0};
if (stat("./output/sequences", &st) == -1)
mkdir("./output/sequences", 0700);
char *rank_c, *nb_c;
char name_f[50];
asprintf(&rank_c, "%d", rank);
asprintf(&nb_c, "%d", j);
strcat(strcpy(name_f, "./output/sequences/rank_"), rank_c);
strcat(strcat(name_f, "_"), nb_c);
strcat(name_f, "_bin.html");
fp = fopen(name_f, "w+");
if (fp == NULL){
printf("Cannot open file \n");
exit(0);
}
fprintf(fp, "<html>\n<head><style>\n th, td {\n font - size : 10px; \n}\n.title {\n font - size : 15px; \n}\ntable, th, td {\n border:\n 1px solid black;\n border - collapse : collapse;\n border - style : dashed;\n}\n.title {\n border - style : dashed dashed dashed solid;\n padding - left : 1 %% ;\n}\ntable {\n width:\n 90 %% ;\n margin - left : 5 %% ;\n}\n\n\ndetails > summary {\n padding:\n 4px;\n width:\n 200px;\n background - color : #eeeeee;\n border:\n none;\n box - shadow : 1px 1px 2px #bbbbbb;\n cursor:\n help;\n}\n</style>\n</head>\n");
}
for (unsigned long long k = 0; k < gene_map.genes_counter; k++)
{
mutation_map mut_m;
long *genes = get_piece_binary_array(seq_bin, gene_map.gene_start[k], gene_map.gene_end[k]);
char *amino = generating_amino_acid_chain(seq_bin, gene_map.gene_start[k], gene_map.gene_end[k]);
// if (amino != NULL)
// printf("*%d\tamino acid chain = %s\n", rank, amino);
mut_m.size = malloc(sizeof(*mut_m.size) * ((gene_map.gene_end[k] - gene_map.gene_start[k]) / 5) * int_SIZE);
mut_m.start_mut = malloc(sizeof(*mut_m.start_mut) * ((gene_map.gene_end[k] - gene_map.gene_start[k]) / 5) * int_SIZE);
mut_m.end_mut = malloc(sizeof(*mut_m.end_mut) * ((gene_map.gene_end[k] - gene_map.gene_start[k]) / 5) * int_SIZE);
char *mrna = generating_mRNA(seq_bin, gene_map.gene_start[k], gene_map.gene_end[k]);
// printf("*%d\tMRNA = %s\n", rank, mrna);
detecting_mutations(seq_bin, gene_map.gene_start[k], gene_map.gene_end[k], mut_m);
int size_m = (gene_map.gene_end[k] - gene_map.gene_start[k]) / int_SIZE;
if (!size_m)
size_m = 1;
if (output)
{
fprintf(fp, "<table>\n<tbody>\n<tr>\n<td class = \"title\">Sequence</td>\n<td class = \"title\">MRNA</td>\n<td class = \"title\">Chain</td>\n<td class = \"title\">Mutation</td>\n</tr>\n");
fprintf(fp, "<tr><td>%s</td>", binary_to_dna(genes, (gene_map.gene_end[k] - gene_map.gene_start[k]) + 3));
fprintf(fp, "<td>%s</td>\n", mrna);
if (amino != NULL)
fprintf(fp, "<td>%s</td>\n", amino);
else
fprintf(fp, "<td>NONE</td>\n");
if (mut_m.size[0] == 0)
fprintf(fp, "<td>NONE</td>\n");
else
{
fprintf(fp, "<td>");
int c = 0;
while ((mut_m.size[0] != 0) && (c < 5))
{
fprintf(fp, "[%lu,%lu]", mut_m.start_mut[c], mut_m.end_mut[c]);
c++;
}
fprintf(fp, "</td>\n");
}
fprintf(fp, "</tbody>\n</table>\n");
}
// printf("*%d\tSending %d genes to 0\n", rank, gene_map.genes_counter);
MPI_Send(genes, size_m, MPI_LONG, 0, 2, MPI_COMM_WORLD);
free(mut_m.end_mut);
free(mut_m.size);
free(mut_m.start_mut);
}
if (output){
fprintf(fp, "</html>");
fclose(fp);
}
printf("Rank %d - %.0f%% (%d/%d)\n", rank, (float)(j + 1) / i*100, (j + 1), i);
}
MPI_Send(&cont, 1, MPI_INT, 0, 3, MPI_COMM_WORLD);
}
void launch(int affichage, int sequences)
{
output = affichage;
int RANK_MASTER = 0;
int initialized, finalized;
MPI_Initialized(&initialized);
if (!initialized)
MPI_Init(NULL, NULL);
// int rank;
int comm_size;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &comm_size);
if (rank == RANK_MASTER)
{
readfiles(comm_size, sequences);
}
else if (rank == comm_size - 1)
alignment_work(rank);
else
{
process_work(rank);
}
MPI_Finalized(&finalized);
if (!finalized)
MPI_Finalize();
}
|
GB_unop__identity_uint16_uint16.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_uint16_uint16
// op(A') function: GB_unop_tran__identity_uint16_uint16
// C type: uint16_t
// A type: uint16_t
// cast: uint16_t cij = aij
// unaryop: cij = aij
#define GB_ATYPE \
uint16_t
#define GB_CTYPE \
uint16_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint16_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
uint16_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
uint16_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
uint16_t z = aij ; \
Cx [pC] = z ; \
}
// true if operator is the identity op with no typecasting
#define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \
1
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_UINT16)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__identity_uint16_uint16
(
uint16_t *Cx, // Cx and Ax may be aliased
const uint16_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 (uint16_t), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
uint16_t aij = Ax [p] ;
uint16_t z = 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 ;
uint16_t aij = Ax [p] ;
uint16_t z = 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_uint16_uint16
(
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
|
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] = 16;
tile_size[1] = 16;
tile_size[2] = 24;
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;
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,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-15,16)),ceild(16*t2-Nz-124,128)),ceild(24*t3-Ny-124,128));t4<=min(min(min(min(floord(Nt+Nx-4,128),floord(8*t1+Nx+13,128)),floord(16*t2+Nx+12,128)),floord(24*t3+Nx+20,128)),floord(16*t1-16*t2+Nz+Nx+11,128));t4++) {
for (t5=max(max(max(max(max(0,8*t1),16*t1-16*t2+1),16*t2-Nz+2),24*t3-Ny+2),128*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,8*t1+15),16*t2+14),24*t3+22),128*t4+126),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(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)] = ((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;
}
|
Tanh.c
|
#ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "generic/Tanh.c"
#else
void THNN_(Tanh_updateOutput)(
THNNState *state,
THTensor *input,
THTensor *output)
{
THTensor_(tanh)(output, input);
}
void THNN_(Tanh_updateGradInput)(
THNNState *state,
THTensor *gradOutput,
THTensor *gradInput,
THTensor *output)
{
THNN_CHECK_SHAPE(output, gradOutput);
THTensor_(resizeAs)(gradInput, output);
if (THTensor_nDimensionLegacyAll(output) == 1 ||
!THTensor_(isContiguous)(output) ||
!THTensor_(isContiguous)(gradOutput) ||
!THTensor_(isContiguous)(gradInput))
{
TH_TENSOR_APPLY3(real, gradInput, real, gradOutput, real, output,
real z = *output_data; \
*gradInput_data = *gradOutput_data * (1. - z*z);
);
}
else
{
real* ptr_gradOutput = THTensor_(data)(gradOutput);
real* ptr_gradInput = THTensor_(data)(gradInput);
real* ptr_output = THTensor_(data)(output);
int64_t i;
#pragma omp parallel for private(i)
for (i = 0; i < THTensor_(nElement)(gradInput); i++)
{
real z = ptr_output[i];
ptr_gradInput[i] = ptr_gradOutput[i] * (1. - z*z);
}
}
}
#endif
|
GB_unop__sinh_fc64_fc64.c
|
//------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__sinh_fc64_fc64)
// op(A') function: GB (_unop_tran__sinh_fc64_fc64)
// C type: GxB_FC64_t
// A type: GxB_FC64_t
// cast: GxB_FC64_t cij = aij
// unaryop: cij = csinh (aij)
#define GB_ATYPE \
GxB_FC64_t
#define GB_CTYPE \
GxB_FC64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
GxB_FC64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = csinh (x) ;
// casting
#define GB_CAST(z, aij) \
GxB_FC64_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GxB_FC64_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
GxB_FC64_t z = aij ; \
Cx [pC] = csinh (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_SINH || GxB_NO_FC64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__sinh_fc64_fc64)
(
GxB_FC64_t *Cx, // Cx and Ax may be aliased
const GxB_FC64_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GxB_FC64_t aij = Ax [p] ;
GxB_FC64_t z = aij ;
Cx [p] = csinh (z) ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
GxB_FC64_t aij = Ax [p] ;
GxB_FC64_t z = aij ;
Cx [p] = csinh (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__sinh_fc64_fc64)
(
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
|
dense_pairwise.c
|
/* Copyright (c) 2016 Drew Schmidt
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.
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.
*/
// Functions for computing covariance, (pearson) correlation, and cosine similarity
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "utils/safeomp.h"
#include "coop.h"
#include "utils/fill.h"
#include "utils/inverse.h"
#include "utils/special_vals.h"
static inline void compute_sums(const int m, const size_t mi, const double * const restrict vec, const double * const restrict x, double *restrict sumx, double *restrict sumy, int *restrict len)
{
int k;
*sumx = 0;
*sumy = 0;
*len = 0;
PLEASE_VECTORIZE
for (k=0; k<m; k++)
{
if (!isnan(vec[k]) && !isnan(x[k + mi]))
{
*sumx += vec[k];
*sumy += x[k + mi];
(*len)++;
}
}
}
int coop_cosine_mat_inplace_pairwise(const bool inv, const int m, const int n, const double * const restrict x, double *restrict cos)
{
int check;
double *vec = malloc(m * sizeof(*vec));
CHECKMALLOC(vec);
for (int j=0; j<n; j++)
{
const size_t mj = (size_t)m*j;
memcpy(vec, x+mj, m*sizeof(*vec));
const size_t nj = (size_t)n*j;
#pragma omp parallel for shared(j, vec, cos) if(m*n > OMP_MIN_SIZE)
for (int i=j; i<n; i++)
{
const size_t mi = (size_t)m*i;
double xx, xy, yy;
xx = xy = yy = 0.0;
int len = 0;
SAFE_SIMD
for (int k=0; k<m; k++)
{
if (!isnan(vec[k]) && !isnan(x[k + mi]))
{
const double xval = vec[k];
const double yval = x[k + mi];
xx += xval * xval;
yy += yval * yval;
xy += xval * yval;
len++;
}
}
if (len == 0)
{
set_na_real(cos + (i + nj));
continue;
}
cos[i + nj] = xy / sqrt(xx * yy);
}
}
free(vec);
if (inv)
{
check = inv_sym_chol(n, cos);
CHECKRET(check);
}
symmetrize(n, cos);
return COOP_OK;
}
int coop_pcor_mat_inplace_pairwise(const bool inv, const int m, const int n, const double * const restrict x, double *restrict cor)
{
int check;
double *vec = malloc(m * sizeof(*vec));
CHECKMALLOC(vec);
for (int j=0; j<n; j++)
{
const size_t mj = (size_t)m*j;
memcpy(vec, x+mj, m*sizeof(*vec));
const size_t nj = (size_t)n*j;
#pragma omp parallel for shared(j, vec, cor) if(m*n > OMP_MIN_SIZE)
for (int i=j; i<n; i++)
{
const size_t mi = (size_t)m*i;
int len;
double meanx, meany;
compute_sums(m, mi, vec, x, &meanx, &meany, &len);
if (len == 0 || len == 1)
{
set_na_real(cor + (i + nj));
set_na_real(cor + (j + (size_t)n*i));
continue;
}
const double dlen = (double) len;
meanx /= dlen;
meany /= dlen;
double sdx = 0.;
double sdy = 0.;
SAFE_SIMD
for (int k=0; k<m; k++)
{
if (!isnan(vec[k]) && !isnan(x[k + mi]))
{
sdx += (vec[k] - meanx)*(vec[k] - meanx);
sdy += (x[k + mi] - meany)*(x[k + mi] - meany);
}
}
sdx = sqrt(sdx/(dlen-1.));
sdy = sqrt(sdy/(dlen-1.));
double mmcp = 0.0;
SAFE_SIMD
for (int k=0; k<m; k++)
{
if (!isnan(vec[k]) && !isnan(x[k + mi]))
mmcp += (vec[k] - meanx) * (x[k + mi] - meany);
}
cor[i + nj] = mmcp / sdx / sdy / (dlen - 1.0);;
}
}
free(vec);
if (inv)
{
check = inv_sym_chol(n, cor);
CHECKRET(check);
}
symmetrize(n, cor);
return COOP_OK;
}
int coop_covar_mat_inplace_pairwise(const bool inv, const int m, const int n, const double * const restrict x, double *restrict cov)
{
int check;
double *vec = malloc(m * sizeof(*vec));
CHECKMALLOC(vec);
for (int j=0; j<n; j++)
{
const size_t mj = (size_t)m*j;
memcpy(vec, x+mj, m*sizeof(*vec));
const size_t nj = (size_t)n*j;
#pragma omp parallel for shared(j, vec, cov) if(m*n > OMP_MIN_SIZE)
for (int i=j; i<n; i++)
{
const size_t mi = (size_t)m*i;
int len;
double meanx, meany;
compute_sums(m, mi, vec, x, &meanx, &meany, &len);
if (len == 0)
{
set_na_real(cov + (i + nj));
set_na_real(cov + (j + (size_t)n*i));
continue;
}
meanx /= (double) len;
meany /= (double) len;
double mmcp = 0.0;
SAFE_SIMD
for (int k=0; k<m; k++)
{
if (!isnan(vec[k]) && !isnan(x[k + mi]))
mmcp += (vec[k] - meanx) * (x[k + mi] - meany);
}
cov[i + nj] = mmcp * ((double) 1.0/(len-1));
}
}
free(vec);
if (inv)
{
check = inv_sym_chol(n, cov);
CHECKRET(check);
}
symmetrize(n, cov);
return COOP_OK;
}
|
main-omp.c
|
/* SPMD Single Program Multiple Data
* TransDNA com openMP
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <omp.h>
#include "transcription.h"
#include "io.h"
// Constantes
#define TAMANHO_CODON 3
#define NUM_THREADS 4 // Constante para numero Threads de ressalva
int main(int argc, char** argv) {
// Variáveis comuns a todas as threads
double tIni, tFim, tExecucao; // Controladoras de tempo
int codonsPorThread; // Quantidade de Codons que cada Thread tem direito
char** codonsDNA; // Vetor de Codons do DNA
char** codonsRNA; // Vetor de Codons do RNA
char** aminoacidos; // Vetor de Aminoácidos
int qtCodons; // Quantidade de Codons que a cadeia de DNA original possui
/*
* TODO Descomentar esse bloco caso o `export` padrão não funcione como descrito no README
* int qtThreads = NUM_THREADS; // Numero total de threads (definida pelo usuário no terminal)
* omp_set_num_threads(NUM_THREADS);
*/
int qtThreads = omp_get_max_threads(); // TODO Comentar essa declaração caso o `export` padrão não funcione como descrito no README
tIni = omp_get_wtime(); // Pega o tempo de início
// Lê a cadeia do arquivo de entrada e encontra o ponto inicial para transcrição
char *cadeiaDNAoriginal = ler("dna7.txt"); // TODO Alterar para ler o arquivo DNA desejado
printf("Processo: LEITURA NO ARQUIVO CONCLUIDA ");
char *cadeiaDNA = getCistron(cadeiaDNAoriginal);
int tamanhoCadeiaDNA = strlen(cadeiaDNA);
// Particiona a cadeia original em codons (substrings de tamanho 3)
codonsDNA = split(cadeiaDNA, TAMANHO_CODON);
qtCodons = tamanhoCadeiaDNA / TAMANHO_CODON;
codonsPorThread = qtCodons/qtThreads;
printf("\nProcesso: TAMANHO DA CADEIA LIDA = %lu", strlen(cadeiaDNAoriginal));
printf("\nProcesso: TAMANHO DO CISTRON = %i", tamanhoCadeiaDNA);
printf("\nProcesso: TOTAL DE CODONS = %i", qtCodons);
printf("\nProcesso: CODONS POR THREAD = %i", codonsPorThread);
free(cadeiaDNAoriginal);
free(cadeiaDNA);
// Inicia o tamanho dos vetores que armazenarão os codonsRNA e aminoácidos
codonsRNA = malloc(qtCodons * sizeof(char *));
aminoacidos = malloc(qtCodons * sizeof(char *));
// Início da seção paralela (threads)
#pragma omp parallel
{
// Variáveis únicas de cada thread
int idThread = omp_get_thread_num(); // ID da thread
int i; // Iterador padrão
int inicioAreaThread = codonsPorThread * idThread;
int fimAreaThread = codonsPorThread * (idThread + 1);
if((idThread == qtThreads-1) && (qtCodons % qtThreads != 0)){ // Número de threads não divide o número de códons
fimAreaThread = fimAreaThread + (qtCodons % qtThreads);
}
// Informa ao usuário o estado da aplicação
printf("\nThread %i: INICIOU ", idThread);
printf("\nThread %i: CODON INI %i", idThread, inicioAreaThread);
printf("\nThread %i: CODON FIM %i", idThread, fimAreaThread-1);
// Executa a sua parte específica e escreve os resultados na variável compartilhada entre as threads
for (i = inicioAreaThread; i < fimAreaThread; i++) {
codonsRNA[i] = transcription(codonsDNA[i], TAMANHO_CODON);
}
for (i = inicioAreaThread; i < fimAreaThread; i++) {
aminoacidos[i] = aminoacids(codonsRNA[i], TAMANHO_CODON);
}
}; // Fim da área paralela
// Mostra os resultados para o usuário e prepara string final para escrever no arquivo de saída
int i;
char *resultadoArquivo = malloc(tamanhoCadeiaDNA * 7 * sizeof(char));
strcat(resultadoArquivo, ".:RESULTADOS:.\nDNA RNA AMINO");
printf(COR_AZUL "\n .:RESULTADOS:. " COR_PADRAO);
printf(COR_AZUL "\n DNA RNA AMINO " COR_PADRAO);
for (i = 0; i < qtCodons; i++) {
printf(COR_AZUL "\n %s %s %s " COR_PADRAO, codonsDNA[i], codonsRNA[i], aminoacidos[i]);
char *novaLinha = malloc(TAMANHO_CODON * 7 * sizeof(char));
initialize(novaLinha, TAMANHO_CODON * 7);
strcat(novaLinha, "\n");
strcat(novaLinha, codonsDNA[i]);
strcat(novaLinha, " ");
strcat(novaLinha, codonsRNA[i]);
strcat(novaLinha, " ");
strcat(novaLinha, aminoacidos[i]);
strcat(resultadoArquivo, novaLinha);
free(novaLinha);
}
escrever(resultadoArquivo, "resultados-omp.txt");
free(codonsDNA);
free(codonsRNA);
free(aminoacidos);
free(resultadoArquivo);
printf(COR_VERDE "\nProcesso: ESCRITA DE RESULTADOS NO ARQUIVO CONCLUIDA " COR_PADRAO);
// Informa o tempo total de execução
tFim = omp_get_wtime(); // Pega o tempo de fim
tExecucao = tFim - tIni;
printf(COR_VERDE "\nTempo total: %fs\n" COR_PADRAO, tExecucao);
return 0;
}
|
wpapsk.h
|
/*
* This software is Copyright (c) 2012 Lukas Odzioba <lukas dot odzioba at gmail dot com>
* and Copyright (c) 2012-2014 magnum
* 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.
*
* hccap format was introduced by oclHashcat-plus, and it is described here: http://hashcat.net/wiki/hccap
* Code is based on Aircrack-ng source
*/
#ifndef _WPAPSK_H
#define _WPAPSK_H
#include "arch.h"
#include "common.h"
#include "johnswap.h"
#include "stdint.h"
#include <assert.h>
#include <openssl/hmac.h>
#define HCCAP_SIZE sizeof(hccap_t)
#define BINARY_SIZE sizeof(mic_t)
#define BINARY_ALIGN 4
#define PLAINTEXT_LENGTH 63 /* We can do 64 but spec. says 63 */
#define SALT_SIZE sizeof(hccap_t)
#define SALT_ALIGN MEM_ALIGN_NONE
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH -1
/** if you want to change hccap_t structure is also defined in hccap2john.c **/
typedef struct
{
char essid[36];
unsigned char mac1[6];
unsigned char mac2[6];
unsigned char nonce1[32];
unsigned char nonce2[32];
unsigned char eapol[256];
int eapol_size;
int keyver;
unsigned char keymic[16];
} hccap_t;
typedef struct
{
unsigned char keymic[16];
} mic_t;
typedef struct {
uint32_t length;
uint8_t v[PLAINTEXT_LENGTH + 1];
} wpapsk_password;
typedef struct {
uint32_t v[8];
} wpapsk_hash;
typedef struct {
uint32_t length;
#ifdef JOHN_OCL_WPAPSK
uint8_t eapol[256 + 64];
uint32_t eapol_size; // blocks
uint8_t data[64 + 12];
#endif
uint8_t salt[36]; // essid
} wpapsk_salt;
#ifndef _WPAPSK_CUDA_KERNEL
static struct fmt_tests tests[] = {
/* WPA2 testcase from http://wiki.wireshark.org/SampleCaptures */
{"$WPAPSK$Coherer#..l/Uf7J..qHUXMunTE3nfbMWSwxv27Ua0XutIOrfRSuv9gOCIugIVGlosMyXdNxfBZUAYmgKqeb6GBPxLiIZr56NtWTGR/Cp5ldAk61.5I0.Ec.2...........nTE3nfbMWSwxv27Ua0XutIOrfRSuv9gOCIugIVGlosM.................................................................3X.I.E..1uk0.E..1uk2.E..1uk0....................................................................................................................................................................................../t.....U...8FWdk8OpPckhewBwt4MXYI", "Induction"},
{"$WPAPSK$Harkonen#./FgTY0../B4zX6AKFO9kuLT4BQSyqEXwo.6XOiS4u8vlMNNs5grN91SVL.WK3GkF2rXfkPFGGi38MHkHDMbH.sm49Vc3pO4HPSUJE21.5I0.Ec.2........../KFO9kuLT4BQSyqEXwo.6XOiS4u8vlMNNs5grN91SVL..................................................................3X.I.E..1uk2.E..1uk2.E..1uk0.E..................................................................................................................................................................................../t.....U...BIpIs8sePU4r8yNnOxKHfM", "12345678"},
/* WPA, from aircrack-ng tests */
{"$WPAPSK$test#..qHuv0A..ZPYJBRzZwAKpEXUJwpza/b69itFaq4.OWoGHfonpc13zCAUsRIfQN2Zar6EXp2BYcRuSkWEJIWjEJJvb4DWZCspbZ51.21.3zy.EY.6........../zZwAKpEXUJwpza/b69itFaq4.OWoGHfonpc13zCAUsQ..................................................................BoK.31m.E2..31m.U2..31m.U2..31m.U................................................................................................................................................................................/X.....E...AkkDQmDg9837LBHG.dGlKA", "biscotte"},
/* Maximum length, 63 characters */
{"$WPAPSK$Greased Lighting#kA5.CDNB.07cofsOMXEEUwFTkO/RX2sQUaW9eteI8ynpFMwRgFZC6kk7bGqgvfcXnuF1f7L5fgn4fQMLmDrKjdBNjb6LClRmfLiTYk21.5I0.Ec............7MXEEUwFTkO/RX2sQUaW9eteI8ynpFMwRgFZC6kk7bGo.................................................................3X.I.E..1uk2.E..1uk2.E..1uk00...................................................................................................................................................................................../t.....U...D06LUdWVfGPaP1Oa3AV9Hg", "W*A5z&1?op2_L&Hla-OA$#5i_Lu@F+6d?je?u5!6+6766eluu7-l+jOEkIwLe90"},
{NULL}
};
#endif
/** Below are common variables used by wpapsk_fmt.c cuda_wpapsk_fmt.c and opencl_wpapsk_fmt.c **/
static hccap_t hccap; ///structure with hccap data
static wpapsk_salt currentsalt; ///structure for essid
static mic_t *mic; ///table for MIC keys
#ifndef JOHN_OCL_WPAPSK
static wpapsk_password *inbuffer; ///table for candidate passwords
static wpapsk_hash *outbuffer; ///table for PMK calculated by GPU
#endif
static const char wpapsk_prefix[] = "$WPAPSK$";
static int new_keys = 1;
static char last_ssid[sizeof(hccap.essid)];
/** Below are common functions used by wpapsk_fmt.c cuda_wpapsk_fmt.c and opencl_wpapsk_fmt.c **/
static hccap_t *decode_hccap(char *ciphertext)
{
static hccap_t hccap;
char *essid = ciphertext + strlen(wpapsk_prefix);
char *hash = strrchr(ciphertext, '#');
char *d = hccap.essid;
char *cap = hash + 1;
unsigned char tbuf[sizeof(hccap_t)];
unsigned char *dst = tbuf;
int i;
if (hash == NULL)
return &hccap;
while (essid != hash) { ///copy essid to hccap
*d++ = *essid++;
}
*d = '\0';
assert(*essid == '#');
for (i = 0; i < 118; i++) {
dst[0] =
(atoi64[ARCH_INDEX(cap[0])] << 2) |
(atoi64[ARCH_INDEX(cap[1])] >> 4);
dst[1] =
(atoi64[ARCH_INDEX(cap[1])] << 4) |
(atoi64[ARCH_INDEX(cap[2])] >> 2);
dst[2] =
(atoi64[ARCH_INDEX(cap[2])] << 6) |
(atoi64[ARCH_INDEX(cap[3])]);
dst += 3;
cap += 4;
}
dst[0] =
(atoi64[ARCH_INDEX(cap[0])] << 2) |
(atoi64[ARCH_INDEX(cap[1])] >> 4);
dst[1] =
(atoi64[ARCH_INDEX(cap[1])] << 4) |
(atoi64[ARCH_INDEX(cap[2])] >> 2);
/* This emits warnings on some compilers */
//memcpy(&hccap.mac1,tbuf,sizeof(hccap_t)-36);
memcpy(((char*)&hccap) + 36, tbuf, sizeof(hccap_t) - 36);
#if !ARCH_LITTLE_ENDIAN
hccap.eapol_size = JOHNSWAP(hccap.eapol_size);
hccap.keyver = JOHNSWAP(hccap.keyver);
#endif
return &hccap;
}
static void *binary(char *ciphertext)
{
static union {
unsigned char c[BINARY_SIZE];
ARCH_WORD_32 dummy;
} binary;
hccap_t *hccap = decode_hccap(ciphertext);
memcpy(binary.c, hccap->keymic, BINARY_SIZE);
return binary.c;
}
static void *salt(char *ciphertext)
{
static hccap_t s;
memcpy(&s, decode_hccap(ciphertext), SALT_SIZE);
return &s;
}
static int valid(char *ciphertext, struct fmt_main *self)
{
char *hash;
int hashlength = 0;
hccap_t *hccap;
if (strncmp(ciphertext, wpapsk_prefix, strlen(wpapsk_prefix)) != 0)
return 0;
hash = strrchr(ciphertext, '#');
if (hash == NULL || hash - (ciphertext + strlen(wpapsk_prefix)) > 32)
return 0;
hash++;
while (hash < ciphertext + strlen(ciphertext)) {
if (atoi64[ARCH_INDEX(*hash++)] == 0x7f)
return 0;
hashlength++;
}
if (hashlength != 475)
return 0;
hccap = decode_hccap(ciphertext);
if (strlen(hccap->essid) > 32) /* real life limit */
return 0;
if(hccap->eapol_size > 256)
return 0;
if(hccap->eapol_size < 0)
return 0;
return 1;
}
#ifndef JOHN_OCL_WPAPSK
static MAYBE_INLINE void prf_512(uint32_t * key, uint8_t * data, uint32_t * ret)
{
HMAC_CTX ctx;
char *text = (char*)"Pairwise key expansion";
unsigned char buff[100];
memcpy(buff, text, 22);
memcpy(buff + 23, data, 76);
buff[22] = 0;
buff[76 + 23] = 0;
HMAC_Init(&ctx, key, 32, EVP_sha1());
HMAC_Update(&ctx, buff, 100);
HMAC_Final(&ctx, (unsigned char *) ret, NULL);
HMAC_CTX_cleanup(&ctx);
}
#endif
static void insert_mac(uint8_t * data)
{
int k = memcmp(hccap.mac1, hccap.mac2, 6);
if (k > 0) {
memcpy(data, hccap.mac2, 6);
memcpy(data + 6, hccap.mac1, 6);
} else {
memcpy(data, hccap.mac1, 6);
memcpy(data + 6, hccap.mac2, 6);
}
}
static void insert_nonce(uint8_t * data)
{
int k = memcmp(hccap.nonce1, hccap.nonce2, 32);
if (k > 0) {
memcpy(data, hccap.nonce2, 32);
memcpy(data + 32, hccap.nonce1, 32);
} else {
memcpy(data, hccap.nonce1, 32);
memcpy(data + 32, hccap.nonce2, 32);
}
}
#ifdef WPAPSK_DEBUG
static char *tomac(unsigned char *p) {
static char buf[48];
sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X", p[0], p[1], p[2], p[3], p[4], p[5]);
return buf;
}
static char *hex(unsigned char *p, int len) {
static char buf[1024];
char *op=buf;
int i;
if (len > 32) {
do {
for (i = 0; i < 32; ++i) {
op += sprintf (op, "%02X", p[i]);
if (i<31&&i%4==3)
op += sprintf (op, " ");
if (i==15)
op += sprintf (op, ": ");
}
len -= 32;
p += 32;
op += sprintf (op, "\n ");
} while (len > 32);
}
for (i = 0; i < len; ++i) {
op += sprintf (op, "%02X", p[i]);
if (i<31&&i%4==3)
op += sprintf (op, " ");
if (i==15)
op += sprintf (op, ": ");
}
return buf;
}
static void Debug_hccap() {
printf("essid: %s\n", hccap.essid);
printf("mac1: %s\n", tomac(hccap.mac1));
printf("mac2: %s\n", tomac(hccap.mac2));
printf("nonce1: %s\n", hex(hccap.nonce1, 32));
printf("nonce2: %s\n", hex(hccap.nonce2, 32));
printf("eapol: %s\n", hex(hccap.eapol, 256));
printf("epol_sz: %d (0x%02X)\n", hccap.eapol_size, hccap.eapol_size);
printf("keyver: %d\n", hccap.keyver);
printf("keymic: %s\n", hex(hccap.keymic, 16));
}
#endif
static void set_salt(void *salt)
{
memcpy(&hccap, salt, SALT_SIZE);
strncpy((char*)currentsalt.salt, hccap.essid, sizeof(currentsalt.salt));
currentsalt.length = strlen(hccap.essid);
#ifdef JOHN_OCL_WPAPSK
currentsalt.eapol_size = 1 + (hccap.eapol_size + 8) / 64;
memcpy(currentsalt.eapol, hccap.eapol, hccap.eapol_size);
memset(currentsalt.eapol + hccap.eapol_size, 0x80, 1);
memset(currentsalt.eapol + hccap.eapol_size + 1, 0, 256 + 64 - hccap.eapol_size - 1);
if (hccap.keyver != 1)
alter_endianity(currentsalt.eapol, 256+56);
((unsigned int*)currentsalt.eapol)[16 * ((hccap.eapol_size + 8) / 64) + ((hccap.keyver == 1) ? 14 : 15)] = (64 + hccap.eapol_size) << 3;
insert_mac(currentsalt.data);
insert_nonce(currentsalt.data + 12);
alter_endianity(currentsalt.data, 64 + 12);
HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_salt, CL_FALSE, 0, sizeof(wpapsk_salt), ¤tsalt, 0, NULL, NULL), "Copy setting to gpu");
#endif
//Debug_hccap();
}
#ifndef JOHN_OCL_WPAPSK
static void clear_keys(void) {
new_keys = 1;
}
#undef set_key
static void set_key(char *key, int index)
{
uint8_t length = strlen(key);
if (length > PLAINTEXT_LENGTH)
length = PLAINTEXT_LENGTH;
inbuffer[index].length = length;
memcpy(inbuffer[index].v, key, length);
}
static char *get_key(int index)
{
static char ret[PLAINTEXT_LENGTH + 1];
uint8_t length = inbuffer[index].length;
memcpy(ret, inbuffer[index].v, length);
ret[length] = '\0';
return ret;
}
static void wpapsk_postprocess(int keys)
{
int i;
uint8_t data[64 + 12];
insert_mac(data);
insert_nonce(data + 12);
if (hccap.keyver == 1) {
#ifdef _OPENMP
#pragma omp parallel for default(none) private(i) shared(keys, outbuffer, data, hccap, mic)
#endif
for (i = 0; i < keys; i++) {
uint32_t prf[20/4];
prf_512(outbuffer[i].v, data, prf);
HMAC(EVP_md5(), prf, 16, hccap.eapol, hccap.eapol_size,
mic[i].keymic, NULL);
}
} else {
#ifdef _OPENMP
#pragma omp parallel for default(none) private(i) shared(keys, outbuffer, data, hccap, mic)
#endif
for (i = 0; i < keys; i++) {
uint32_t prf[20/4];
unsigned char keymic[20];
prf_512(outbuffer[i].v, data, prf);
HMAC(EVP_sha1(), prf, 16, hccap.eapol,
hccap.eapol_size, keymic, NULL);
memcpy(mic[i].keymic, keymic, 16);
}
}
}
#endif
static int binary_hash_0(void *binary)
{
#ifdef WPAPSK_DEBUG
puts("binary");
uint32_t i, *b = binary;
for (i = 0; i < 4; i++)
printf("%08x ", b[i]);
puts("");
#endif
return ((uint32_t *) binary)[0] & 0xf;
}
static int get_hash_0(int index)
{
#ifdef WPAPSK_DEBUG
int i;
puts("get_hash");
uint32_t *b = (uint32_t *)mic[index].keymic;
for (i = 0; i < 4; i++)
printf("%08x ", b[i]);
puts("");
#endif
uint32_t *h = (uint32_t *) mic[index].keymic;
return h[0] & 0xf;
}
static int get_hash_1(int index)
{
uint32_t *h = (uint32_t *) mic[index].keymic;
return h[0] & 0xff;
}
static int get_hash_2(int index)
{
uint32_t *h = (uint32_t *) mic[index].keymic;
return h[0] & 0xfff;
}
static int get_hash_3(int index)
{
uint32_t *h = (uint32_t *) mic[index].keymic;
return h[0] & 0xffff;
}
static int get_hash_4(int index)
{
uint32_t *h = (uint32_t *) mic[index].keymic;
return h[0] & 0xfffff;
}
static int get_hash_5(int index)
{
uint32_t *h = (uint32_t *) mic[index].keymic;
return h[0] & 0xffffff;
}
static int get_hash_6(int index)
{
uint32_t *h = (uint32_t *) mic[index].keymic;
return h[0] & 0x7ffffff;
}
static int cmp_all(void *binary, int count)
{
uint32_t i, b = ((uint32_t *) binary)[0];
for (i = 0; i < count; i++) {
uint32_t *m = (uint32_t*) mic[i].keymic;
if (b == m[0])
return 1;
}
return 0;
}
static int cmp_one(void *binary, int index)
{
uint8_t i;
uint32_t *b = (uint32_t*) binary;
uint32_t *m = (uint32_t*) mic[index].keymic;
for (i = 0; i < BINARY_SIZE / 4; i++)
if (b[i] != m[i])
return 0;
return 1;
}
static int cmp_exact(char *source, int count)
{
return 1;
}
#endif
|
hellomem.c
|
//
//
// hellomem
//
// A simple example that measures copy memory bandwidth on
// Intel(r) processors using openmp to scale
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <omp.h>
#include <sys/time.h>
// dtime - utility routine that returns the current wall clock time
double dtime()
{
double tseconds = 0.0;
struct timeval mytime;
gettimeofday(&mytime,(struct timezone*)0);
tseconds = (double)(mytime.tv_sec + mytime.tv_usec*1.0e-6);
return( tseconds );
}
// Set to float or double
#define REAL double
#define BW_ARRAY_SIZE (1000*1000*64)
#define BW_ITERS 1000
// number of mem ops each iteration
// 1 read + 1 write
#define OPS_PERITER 2
// define some arrays
// make sure they are 64 byte aligned - for fastest cache access
REAL fa[BW_ARRAY_SIZE] __attribute__((aligned(64)));
REAL fb[BW_ARRAY_SIZE] __attribute__((aligned(64)));
REAL fc[BW_ARRAY_SIZE] __attribute__((aligned(64)));
//
// Main program - array copy
//
int main(int argc, char *argv[] )
{
int i,j,k;
double tstart, tstop, ttime;
double gbytes = 0.0;
REAL a=1.1;
//
// initialize the compute arrays
//
printf("Initializing\r\n");
#pragma omp parallel for
for(i=0; i<BW_ARRAY_SIZE; i++)
{
fa[i] = (REAL)i + 0.1;
fb[i] = (REAL)i + 0.2;
fc[i] = (REAL)i + 0.3;
}
// print the # of threads to be used
// Just display from 1 thread - the "master"
#pragma omp parallel
#pragma omp master
printf("Starting BW Test on %d threads\r\n",omp_get_num_threads());
tstart = dtime();
// use omp to scale the test across
// the threads requested. Need to set environment
// variables OMP_NUM_THREADS and KMP_AFFINITY
for (i=0; i<BW_ITERS; i++)
{
//
// copy the arrays to/from memory (2 bw ops)
// use openmp to scale and get aggregate bw
//
#pragma omp parallel for
for(k=0; k<BW_ARRAY_SIZE; k++)
{
fa[k] = fb[k];
}
}
tstop = dtime();
// # of gigabytes we just moved
gbytes = (double)( 1.0e-9 * OPS_PERITER * BW_ITERS *
BW_ARRAY_SIZE*sizeof(REAL));
// elasped time
ttime = tstop - tstart;
//
// Print the results
//
if ((ttime) > 0.0)
{
printf("Gbytes = %10.3lf, Secs = %10.3lf, GBytes per sec = %10.3lf\r\n",
gbytes, ttime, gbytes/ttime);
}
}
|
GB_unop__identity_uint8_int16.c
|
//------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__identity_uint8_int16)
// op(A') function: GB (_unop_tran__identity_uint8_int16)
// C type: uint8_t
// A type: int16_t
// cast: uint8_t cij = (uint8_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
int16_t
#define GB_CTYPE \
uint8_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) \
uint8_t z = (uint8_t) aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
int16_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
uint8_t z = (uint8_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_UINT8 || GxB_NO_INT16)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_uint8_int16)
(
uint8_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] ;
uint8_t z = (uint8_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] ;
uint8_t z = (uint8_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_uint8_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
|
wand-view.c
|
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% W W AAA N N DDDD %
% W W A A NN N D D %
% W W W AAAAA N N N D D %
% WW WW A A N NN D D %
% W W A A N N DDDD %
% %
% V V IIIII EEEEE W W %
% V V I E W W %
% V V I EEE W W W %
% V V I E WW WW %
% V IIIII EEEEE W W %
% %
% %
% MagickWand Wand View Methods %
% %
% Software Design %
% John Cristy %
% March 2003 %
% %
% %
% 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 "wand/studio.h"
#include "wand/MagickWand.h"
#include "wand/magick-wand-private.h"
#include "wand/wand.h"
#include "magick/monitor-private.h"
#include "magick/thread-private.h"
/*
Define declarations.
*/
#define WandViewId "WandView"
/*
Typedef declarations.
*/
struct _WandView
{
size_t
id;
char
name[MaxTextExtent],
*description;
RectangleInfo
extent;
MagickWand
*wand;
CacheView
*view;
size_t
number_threads;
PixelWand
***pixel_wands;
ExceptionInfo
*exception;
MagickBooleanType
debug;
size_t
signature;
};
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e W a n d V i e w %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneWandView() makes a copy of the specified wand view.
%
% The format of the CloneWandView method is:
%
% WandView *CloneWandView(const WandView *wand_view)
%
% A description of each parameter follows:
%
% o wand_view: the wand view.
%
*/
WandExport WandView *CloneWandView(const WandView *wand_view)
{
WandView
*clone_view;
register ssize_t
i;
assert(wand_view != (WandView *) NULL);
assert(wand_view->signature == WandSignature);
if (wand_view->debug != MagickFalse)
(void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand_view->name);
clone_view=(WandView *) AcquireMagickMemory(sizeof(*clone_view));
if (clone_view == (WandView *) NULL)
ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed",
wand_view->name);
(void) ResetMagickMemory(clone_view,0,sizeof(*clone_view));
clone_view->id=AcquireWandId();
(void) FormatLocaleString(clone_view->name,MaxTextExtent,"%s-%.20g",
WandViewId,(double) clone_view->id);
clone_view->description=ConstantString(wand_view->description);
clone_view->view=CloneCacheView(wand_view->view);
clone_view->extent=wand_view->extent;
clone_view->number_threads=wand_view->number_threads;
clone_view->exception=AcquireExceptionInfo();
InheritException(clone_view->exception,wand_view->exception);
for (i=0; i < (ssize_t) wand_view->number_threads; i++)
clone_view->pixel_wands[i]=ClonePixelWands((const PixelWand **)
wand_view->pixel_wands[i],wand_view->extent.width);
clone_view->debug=wand_view->debug;
if (clone_view->debug != MagickFalse)
(void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",clone_view->name);
clone_view->signature=WandSignature;
return(clone_view);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y W a n d V i e w %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyWandView() deallocates memory associated with a wand view.
%
% The format of the DestroyWandView method is:
%
% WandView *DestroyWandView(WandView *wand_view)
%
% A description of each parameter follows:
%
% o wand_view: the wand view.
%
*/
static PixelWand ***DestroyPixelsThreadSet(PixelWand ***pixel_wands,
const size_t number_wands,const size_t number_threads)
{
register ssize_t
i;
assert(pixel_wands != (PixelWand ***) NULL);
for (i=0; i < (ssize_t) number_threads; i++)
if (pixel_wands[i] != (PixelWand **) NULL)
pixel_wands[i]=DestroyPixelWands(pixel_wands[i],number_wands);
pixel_wands=(PixelWand ***) RelinquishMagickMemory(pixel_wands);
return(pixel_wands);
}
WandExport WandView *DestroyWandView(WandView *wand_view)
{
assert(wand_view != (WandView *) NULL);
assert(wand_view->signature == WandSignature);
wand_view->pixel_wands=DestroyPixelsThreadSet(wand_view->pixel_wands,
wand_view->extent.width,wand_view->number_threads);
wand_view->view=DestroyCacheView(wand_view->view);
wand_view->exception=DestroyExceptionInfo(wand_view->exception);
wand_view->signature=(~WandSignature);
RelinquishWandId(wand_view->id);
wand_view=(WandView *) RelinquishMagickMemory(wand_view);
return(wand_view);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D u p l e x T r a n s f e r W a n d V i e w I t e r a t o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DuplexTransferWandViewIterator() iterates over three wand views in
% parallel and calls your transfer method for each scanline of the view. The
% source and duplex pixel extent is not confined to the image canvas-- that is
% you can include negative offsets or widths or heights that exceed the image
% dimension. However, the destination wand view is confined to the image
% canvas-- that is no negative offsets or widths or heights that exceed the
% image dimension are permitted.
%
% The callback signature is:
%
% MagickBooleanType DuplexTransferImageViewMethod(const WandView *source,
% const WandView *duplex,WandView *destination,const ssize_t y,
% const int thread_id,void *context)
%
% Use this pragma if the view is not single threaded:
%
% #pragma omp critical
%
% to define a section of code in your callback transfer method that must be
% executed by a single thread at a time.
%
% The format of the DuplexTransferWandViewIterator method is:
%
% MagickBooleanType DuplexTransferWandViewIterator(WandView *source,
% WandView *duplex,WandView *destination,
% DuplexTransferWandViewMethod transfer,void *context)
%
% A description of each parameter follows:
%
% o source: the source wand view.
%
% o duplex: the duplex wand view.
%
% o destination: the destination wand view.
%
% o transfer: the transfer callback method.
%
% o context: the user defined context.
%
*/
WandExport MagickBooleanType DuplexTransferWandViewIterator(WandView *source,
WandView *duplex,WandView *destination,DuplexTransferWandViewMethod transfer,
void *context)
{
ExceptionInfo
*exception;
Image
*destination_image,
*duplex_image,
*source_image;
MagickBooleanType
status;
MagickOffsetType
progress;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
size_t
height;
#endif
ssize_t
y;
assert(source != (WandView *) NULL);
assert(source->signature == WandSignature);
if (transfer == (DuplexTransferWandViewMethod) NULL)
return(MagickFalse);
source_image=source->wand->images;
duplex_image=duplex->wand->images;
destination_image=destination->wand->images;
if (SetImageStorageClass(destination_image,DirectClass) == MagickFalse)
return(MagickFalse);
status=MagickTrue;
progress=0;
exception=destination->exception;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
height=(size_t) (source->extent.height-source->extent.y);
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(source_image,destination_image,height,1)
#endif
for (y=source->extent.y; y < (ssize_t) source->extent.height; y++)
{
const int
id = GetOpenMPThreadId();
MagickBooleanType
sync;
register const IndexPacket
*restrict duplex_indexes,
*restrict indexes;
register const PixelPacket
*restrict duplex_pixels,
*restrict pixels;
register IndexPacket
*restrict destination_indexes;
register ssize_t
x;
register PixelPacket
*restrict destination_pixels;
if (status == MagickFalse)
continue;
pixels=GetCacheViewVirtualPixels(source->view,source->extent.x,y,
source->extent.width,1,source->exception);
if (pixels == (const PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(source->view);
for (x=0; x < (ssize_t) source->extent.width; x++)
PixelSetQuantumColor(source->pixel_wands[id][x],pixels+x);
if (source_image->colorspace == CMYKColorspace)
for (x=0; x < (ssize_t) source->extent.width; x++)
PixelSetBlackQuantum(source->pixel_wands[id][x],
GetPixelBlack(indexes+x));
if (source_image->storage_class == PseudoClass)
for (x=0; x < (ssize_t) source->extent.width; x++)
PixelSetIndex(source->pixel_wands[id][x],
GetPixelIndex(indexes+x));
duplex_pixels=GetCacheViewVirtualPixels(duplex->view,duplex->extent.x,y,
duplex->extent.width,1,duplex->exception);
if (duplex_pixels == (const PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
duplex_indexes=GetCacheViewVirtualIndexQueue(duplex->view);
for (x=0; x < (ssize_t) duplex->extent.width; x++)
PixelSetQuantumColor(duplex->pixel_wands[id][x],duplex_pixels+x);
if (duplex_image->colorspace == CMYKColorspace)
for (x=0; x < (ssize_t) duplex->extent.width; x++)
PixelSetBlackQuantum(duplex->pixel_wands[id][x],
GetPixelBlack(duplex_indexes+x));
if (duplex_image->storage_class == PseudoClass)
for (x=0; x < (ssize_t) duplex->extent.width; x++)
PixelSetIndex(duplex->pixel_wands[id][x],
GetPixelIndex(duplex_indexes+x));
destination_pixels=GetCacheViewAuthenticPixels(destination->view,
destination->extent.x,y,destination->extent.width,1,exception);
if (destination_pixels == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
destination_indexes=GetCacheViewAuthenticIndexQueue(destination->view);
for (x=0; x < (ssize_t) destination->extent.width; x++)
PixelSetQuantumColor(destination->pixel_wands[id][x],
destination_pixels+x);
if (destination_image->colorspace == CMYKColorspace)
for (x=0; x < (ssize_t) destination->extent.width; x++)
PixelSetBlackQuantum(destination->pixel_wands[id][x],
GetPixelBlack(destination_indexes+x));
if (destination_image->storage_class == PseudoClass)
for (x=0; x < (ssize_t) destination->extent.width; x++)
PixelSetIndex(destination->pixel_wands[id][x],
GetPixelIndex(destination_indexes+x));
if (transfer(source,duplex,destination,y,id,context) == MagickFalse)
status=MagickFalse;
for (x=0; x < (ssize_t) destination->extent.width; x++)
PixelGetQuantumColor(destination->pixel_wands[id][x],
destination_pixels+x);
if (destination_image->colorspace == CMYKColorspace)
for (x=0; x < (ssize_t) destination->extent.width; x++)
SetPixelBlack(destination_indexes+x,PixelGetBlackQuantum(
destination->pixel_wands[id][x]));
sync=SyncCacheViewAuthenticPixels(destination->view,exception);
if (sync == MagickFalse)
{
InheritException(destination->exception,GetCacheViewException(
source->view));
status=MagickFalse;
}
if (source_image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickWand_DuplexTransferWandViewIterator)
#endif
proceed=SetImageProgress(source_image,source->description,progress++,
source->extent.height);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
return(status == MagickFalse ? 0 : 1);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t W a n d V i e w E x c e p t i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetWandViewException() returns the severity, reason, and description of any
% error that occurs when utilizing a wand view.
%
% The format of the GetWandViewException method is:
%
% char *GetWandViewException(const WandView *wand_view,
% ExceptionType *severity)
%
% A description of each parameter follows:
%
% o wand_view: the pixel wand_view.
%
% o severity: the severity of the error is returned here.
%
*/
WandExport char *GetWandViewException(const WandView *wand_view,
ExceptionType *severity)
{
char
*description;
assert(wand_view != (const WandView *) NULL);
assert(wand_view->signature == WandSignature);
if (wand_view->debug != MagickFalse)
(void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand_view->name);
assert(severity != (ExceptionType *) NULL);
*severity=wand_view->exception->severity;
description=(char *) AcquireQuantumMemory(2UL*MaxTextExtent,
sizeof(*description));
if (description == (char *) NULL)
ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed",
wand_view->name);
*description='\0';
if (wand_view->exception->reason != (char *) NULL)
(void) CopyMagickString(description,GetLocaleExceptionMessage(
wand_view->exception->severity,wand_view->exception->reason),
MaxTextExtent);
if (wand_view->exception->description != (char *) NULL)
{
(void) ConcatenateMagickString(description," (",MaxTextExtent);
(void) ConcatenateMagickString(description,GetLocaleExceptionMessage(
wand_view->exception->severity,wand_view->exception->description),
MaxTextExtent);
(void) ConcatenateMagickString(description,")",MaxTextExtent);
}
return(description);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t W a n d V i e w E x t e n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetWandViewExtent() returns the wand view extent.
%
% The format of the GetWandViewExtent method is:
%
% RectangleInfo GetWandViewExtent(const WandView *wand_view)
%
% A description of each parameter follows:
%
% o wand_view: the wand view.
%
*/
WandExport RectangleInfo GetWandViewExtent(const WandView *wand_view)
{
assert(wand_view != (WandView *) NULL);
assert(wand_view->signature == WandSignature);
return(wand_view->extent);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t W a n d V i e w I t e r a t o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetWandViewIterator() iterates over the wand view in parallel and calls
% your get method for each scanline of the view. The pixel extent is
% not confined to the image canvas-- that is you can include negative offsets
% or widths or heights that exceed the image dimension. Any updates to
% the pixels in your callback are ignored.
%
% The callback signature is:
%
% MagickBooleanType GetImageViewMethod(const WandView *source,
% const ssize_t y,const int thread_id,void *context)
%
% Use this pragma if the view is not single threaded:
%
% #pragma omp critical
%
% to define a section of code in your callback get method that must be
% executed by a single thread at a time.
%
% The format of the GetWandViewIterator method is:
%
% MagickBooleanType GetWandViewIterator(WandView *source,
% GetWandViewMethod get,void *context)
%
% A description of each parameter follows:
%
% o source: the source wand view.
%
% o get: the get callback method.
%
% o context: the user defined context.
%
*/
WandExport MagickBooleanType GetWandViewIterator(WandView *source,
GetWandViewMethod get,void *context)
{
Image
*source_image;
MagickBooleanType
status;
MagickOffsetType
progress;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
size_t
height;
#endif
ssize_t
y;
assert(source != (WandView *) NULL);
assert(source->signature == WandSignature);
if (get == (GetWandViewMethod) NULL)
return(MagickFalse);
source_image=source->wand->images;
status=MagickTrue;
progress=0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
height=(size_t) (source->extent.height-source->extent.y);
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(source_image,source_image,height,1)
#endif
for (y=source->extent.y; y < (ssize_t) source->extent.height; y++)
{
const int
id = GetOpenMPThreadId();
register const IndexPacket
*indexes;
register const PixelPacket
*pixels;
register ssize_t
x;
if (status == MagickFalse)
continue;
pixels=GetCacheViewVirtualPixels(source->view,source->extent.x,y,
source->extent.width,1,source->exception);
if (pixels == (const PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(source->view);
for (x=0; x < (ssize_t) source->extent.width; x++)
PixelSetQuantumColor(source->pixel_wands[id][x],pixels+x);
if (source_image->colorspace == CMYKColorspace)
for (x=0; x < (ssize_t) source->extent.width; x++)
PixelSetBlackQuantum(source->pixel_wands[id][x],
GetPixelBlack(indexes+x));
if (source_image->storage_class == PseudoClass)
for (x=0; x < (ssize_t) source->extent.width; x++)
PixelSetIndex(source->pixel_wands[id][x],
GetPixelIndex(indexes+x));
if (get(source,y,id,context) == MagickFalse)
status=MagickFalse;
if (source_image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickWand_GetWandViewIterator)
#endif
proceed=SetImageProgress(source_image,source->description,progress++,
source->extent.height);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
return(status == MagickFalse ? 0 : 1);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t W a n d V i e w P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetWandViewPixels() returns the wand view pixel_wands.
%
% The format of the GetWandViewPixels method is:
%
% PixelWand *GetWandViewPixels(const WandView *wand_view)
%
% A description of each parameter follows:
%
% o wand_view: the wand view.
%
*/
WandExport PixelWand **GetWandViewPixels(const WandView *wand_view)
{
const int
id = GetOpenMPThreadId();
assert(wand_view != (WandView *) NULL);
assert(wand_view->signature == WandSignature);
return(wand_view->pixel_wands[id]);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t W a n d V i e w W a n d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetWandViewWand() returns the magick wand associated with the wand view.
%
% The format of the GetWandViewWand method is:
%
% MagickWand *GetWandViewWand(const WandView *wand_view)
%
% A description of each parameter follows:
%
% o wand_view: the wand view.
%
*/
WandExport MagickWand *GetWandViewWand(const WandView *wand_view)
{
assert(wand_view != (WandView *) NULL);
assert(wand_view->signature == WandSignature);
return(wand_view->wand);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s W a n d V i e w %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsWandView() returns MagickTrue if the the parameter is verified as a wand
% view object.
%
% The format of the IsWandView method is:
%
% MagickBooleanType IsWandView(const WandView *wand_view)
%
% A description of each parameter follows:
%
% o wand_view: the wand view.
%
*/
WandExport MagickBooleanType IsWandView(const WandView *wand_view)
{
size_t
length;
if (wand_view == (const WandView *) NULL)
return(MagickFalse);
if (wand_view->signature != WandSignature)
return(MagickFalse);
length=strlen(WandViewId);
if (LocaleNCompare(wand_view->name,WandViewId,length) != 0)
return(MagickFalse);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% N e w W a n d V i e w %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% NewWandView() returns a wand view required for all other methods in the
% Wand View API.
%
% The format of the NewWandView method is:
%
% WandView *NewWandView(MagickWand *wand)
%
% A description of each parameter follows:
%
% o wand: the wand.
%
*/
static PixelWand ***AcquirePixelsThreadSet(const size_t number_wands,
const size_t number_threads)
{
PixelWand
***pixel_wands;
register ssize_t
i;
pixel_wands=(PixelWand ***) AcquireQuantumMemory(number_threads,
sizeof(*pixel_wands));
if (pixel_wands == (PixelWand ***) NULL)
return((PixelWand ***) NULL);
(void) ResetMagickMemory(pixel_wands,0,number_threads*sizeof(*pixel_wands));
for (i=0; i < (ssize_t) number_threads; i++)
{
pixel_wands[i]=NewPixelWands(number_wands);
if (pixel_wands[i] == (PixelWand **) NULL)
return(DestroyPixelsThreadSet(pixel_wands,number_wands,number_threads));
}
return(pixel_wands);
}
WandExport WandView *NewWandView(MagickWand *wand)
{
WandView
*wand_view;
assert(wand != (MagickWand *) NULL);
assert(wand->signature == WandSignature);
wand_view=(WandView *) AcquireMagickMemory(sizeof(*wand_view));
if (wand_view == (WandView *) NULL)
ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed",
GetExceptionMessage(errno));
(void) ResetMagickMemory(wand_view,0,sizeof(*wand_view));
wand_view->id=AcquireWandId();
(void) FormatLocaleString(wand_view->name,MaxTextExtent,"%s-%.20g",
WandViewId,(double) wand_view->id);
wand_view->description=ConstantString("WandView");
wand_view->wand=wand;
wand_view->exception=AcquireExceptionInfo();
wand_view->view=AcquireVirtualCacheView(wand_view->wand->images,
wand_view->exception);
wand_view->extent.width=wand->images->columns;
wand_view->extent.height=wand->images->rows;
wand_view->number_threads=GetOpenMPMaximumThreads();
wand_view->pixel_wands=AcquirePixelsThreadSet(wand_view->extent.width,
wand_view->number_threads);
if (wand_view->pixel_wands == (PixelWand ***) NULL)
ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed",
GetExceptionMessage(errno));
wand_view->debug=IsEventLogging();
wand_view->signature=WandSignature;
return(wand_view);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% N e w W a n d V i e w E x t e n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% NewWandViewExtent() returns a wand view required for all other methods
% in the Wand View API.
%
% The format of the NewWandViewExtent method is:
%
% WandView *NewWandViewExtent(MagickWand *wand,const ssize_t x,
% const ssize_t y,const size_t width,const size_t height)
%
% A description of each parameter follows:
%
% o wand: the magick wand.
%
% o x,y,columns,rows: These values define the perimeter of a extent of
% pixel_wands view.
%
*/
WandExport WandView *NewWandViewExtent(MagickWand *wand,const ssize_t x,
const ssize_t y,const size_t width,const size_t height)
{
WandView
*wand_view;
assert(wand != (MagickWand *) NULL);
assert(wand->signature == WandSignature);
wand_view=(WandView *) AcquireMagickMemory(sizeof(*wand_view));
if (wand_view == (WandView *) NULL)
ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed",
GetExceptionMessage(errno));
(void) ResetMagickMemory(wand_view,0,sizeof(*wand_view));
wand_view->id=AcquireWandId();
(void) FormatLocaleString(wand_view->name,MaxTextExtent,"%s-%.20g",
WandViewId,(double) wand_view->id);
wand_view->description=ConstantString("WandView");
wand_view->exception=AcquireExceptionInfo();
wand_view->view=AcquireVirtualCacheView(wand_view->wand->images,
wand_view->exception);
wand_view->wand=wand;
wand_view->extent.width=width;
wand_view->extent.height=height;
wand_view->extent.x=x;
wand_view->extent.y=y;
wand_view->number_threads=GetOpenMPMaximumThreads();
wand_view->pixel_wands=AcquirePixelsThreadSet(wand_view->extent.width,
wand_view->number_threads);
if (wand_view->pixel_wands == (PixelWand ***) NULL)
ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed",
GetExceptionMessage(errno));
wand_view->debug=IsEventLogging();
wand_view->signature=WandSignature;
return(wand_view);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t W a n d V i e w D e s c r i p t i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetWandViewDescription() associates a description with an image view.
%
% The format of the SetWandViewDescription method is:
%
% void SetWandViewDescription(WandView *image_view,const char *description)
%
% A description of each parameter follows:
%
% o wand_view: the wand view.
%
% o description: the wand view description.
%
*/
MagickExport void SetWandViewDescription(WandView *wand_view,
const char *description)
{
assert(wand_view != (WandView *) NULL);
assert(wand_view->signature == WandSignature);
wand_view->description=ConstantString(description);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t W a n d V i e w I t e r a t o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetWandViewIterator() iterates over the wand view in parallel and calls
% your set method for each scanline of the view. The pixel extent is
% confined to the image canvas-- that is no negative offsets or widths or
% heights that exceed the image dimension. The pixels are initiallly
% undefined and any settings you make in the callback method are automagically
% synced back to your image.
%
% The callback signature is:
%
% MagickBooleanType SetImageViewMethod(ImageView *destination,
% const ssize_t y,const int thread_id,void *context)
%
% Use this pragma if the view is not single threaded:
%
% #pragma omp critical
%
% to define a section of code in your callback set method that must be
% executed by a single thread at a time.
%
% The format of the SetWandViewIterator method is:
%
% MagickBooleanType SetWandViewIterator(WandView *destination,
% SetWandViewMethod set,void *context)
%
% A description of each parameter follows:
%
% o destination: the wand view.
%
% o set: the set callback method.
%
% o context: the user defined context.
%
*/
WandExport MagickBooleanType SetWandViewIterator(WandView *destination,
SetWandViewMethod set,void *context)
{
ExceptionInfo
*exception;
Image
*destination_image;
MagickBooleanType
status;
MagickOffsetType
progress;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
size_t
height;
#endif
ssize_t
y;
assert(destination != (WandView *) NULL);
assert(destination->signature == WandSignature);
if (set == (SetWandViewMethod) NULL)
return(MagickFalse);
destination_image=destination->wand->images;
if (SetImageStorageClass(destination_image,DirectClass) == MagickFalse)
return(MagickFalse);
status=MagickTrue;
progress=0;
exception=destination->exception;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
height=(size_t) (destination->extent.height-destination->extent.y);
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(destination_image,destination_image,height,1)
#endif
for (y=destination->extent.y; y < (ssize_t) destination->extent.height; y++)
{
const int
id = GetOpenMPThreadId();
MagickBooleanType
sync;
register IndexPacket
*restrict indexes;
register ssize_t
x;
register PixelPacket
*restrict pixels;
if (status == MagickFalse)
continue;
pixels=GetCacheViewAuthenticPixels(destination->view,destination->extent.x,
y,destination->extent.width,1,exception);
if (pixels == (PixelPacket *) NULL)
{
InheritException(destination->exception,GetCacheViewException(
destination->view));
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(destination->view);
if (set(destination,y,id,context) == MagickFalse)
status=MagickFalse;
for (x=0; x < (ssize_t) destination->extent.width; x++)
PixelGetQuantumColor(destination->pixel_wands[id][x],pixels+x);
if (destination_image->colorspace == CMYKColorspace)
for (x=0; x < (ssize_t) destination->extent.width; x++)
SetPixelBlack(indexes+x,PixelGetBlackQuantum(
destination->pixel_wands[id][x]));
sync=SyncCacheViewAuthenticPixels(destination->view,exception);
if (sync == MagickFalse)
{
InheritException(destination->exception,GetCacheViewException(
destination->view));
status=MagickFalse;
}
if (destination_image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickWand_SetWandViewIterator)
#endif
proceed=SetImageProgress(destination_image,destination->description,
progress++,destination->extent.height);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
return(status == MagickFalse ? 0 : 1);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t W a n d V i e w T h r e a d s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetWandViewThreads() sets the number of threads in a thread team.
%
% The format of the SetWandViewDescription method is:
%
% void SetWandViewThreads(WandView *image_view,
% const size_t number_threads)
%
% A description of each parameter follows:
%
% o image_view: the image view.
%
% o number_threads: the number of threads in a thread team.
%
*/
MagickExport void SetWandViewThreads(WandView *image_view,
const size_t number_threads)
{
assert(image_view != (WandView *) NULL);
assert(image_view->signature == MagickSignature);
image_view->number_threads=number_threads;
if (number_threads > (size_t) GetMagickResourceLimit(ThreadResource))
image_view->number_threads=GetOpenMPMaximumThreads();
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r a n s f e r W a n d V i e w I t e r a t o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransferWandViewIterator() iterates over two wand views in parallel and
% calls your transfer method for each scanline of the view. The source pixel
% extent is not confined to the image canvas-- that is you can include
% negative offsets or widths or heights that exceed the image dimension.
% However, the destination wand view is confined to the image canvas-- that
% is no negative offsets or widths or heights that exceed the image dimension
% are permitted.
%
% The callback signature is:
%
% MagickBooleanType TransferImageViewMethod(const WandView *source,
% WandView *destination,const ssize_t y,const int thread_id,
% void *context)
%
% Use this pragma if the view is not single threaded:
%
% #pragma omp critical
%
% to define a section of code in your callback transfer method that must be
% executed by a single thread at a time.
%
% The format of the TransferWandViewIterator method is:
%
% MagickBooleanType TransferWandViewIterator(WandView *source,
% WandView *destination,TransferWandViewMethod transfer,void *context)
%
% A description of each parameter follows:
%
% o source: the source wand view.
%
% o destination: the destination wand view.
%
% o transfer: the transfer callback method.
%
% o context: the user defined context.
%
*/
WandExport MagickBooleanType TransferWandViewIterator(WandView *source,
WandView *destination,TransferWandViewMethod transfer,void *context)
{
ExceptionInfo
*exception;
Image
*destination_image,
*source_image;
MagickBooleanType
status;
MagickOffsetType
progress;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
size_t
height;
#endif
ssize_t
y;
assert(source != (WandView *) NULL);
assert(source->signature == WandSignature);
if (transfer == (TransferWandViewMethod) NULL)
return(MagickFalse);
source_image=source->wand->images;
destination_image=destination->wand->images;
if (SetImageStorageClass(destination_image,DirectClass) == MagickFalse)
return(MagickFalse);
status=MagickTrue;
progress=0;
exception=destination->exception;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
height=(size_t) (source->extent.height-source->extent.y);
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(source_image,destination_image,height,1)
#endif
for (y=source->extent.y; y < (ssize_t) source->extent.height; y++)
{
const int
id = GetOpenMPThreadId();
MagickBooleanType
sync;
register const IndexPacket
*restrict indexes;
register const PixelPacket
*restrict pixels;
register IndexPacket
*restrict destination_indexes;
register ssize_t
x;
register PixelPacket
*restrict destination_pixels;
if (status == MagickFalse)
continue;
pixels=GetCacheViewVirtualPixels(source->view,source->extent.x,y,
source->extent.width,1,source->exception);
if (pixels == (const PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(source->view);
for (x=0; x < (ssize_t) source->extent.width; x++)
PixelSetQuantumColor(source->pixel_wands[id][x],pixels+x);
if (source_image->colorspace == CMYKColorspace)
for (x=0; x < (ssize_t) source->extent.width; x++)
PixelSetBlackQuantum(source->pixel_wands[id][x],
GetPixelBlack(indexes+x));
if (source_image->storage_class == PseudoClass)
for (x=0; x < (ssize_t) source->extent.width; x++)
PixelSetIndex(source->pixel_wands[id][x],
GetPixelIndex(indexes+x));
destination_pixels=GetCacheViewAuthenticPixels(destination->view,
destination->extent.x,y,destination->extent.width,1,exception);
if (destination_pixels == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
destination_indexes=GetCacheViewAuthenticIndexQueue(destination->view);
for (x=0; x < (ssize_t) destination->extent.width; x++)
PixelSetQuantumColor(destination->pixel_wands[id][x],pixels+x);
if (destination_image->colorspace == CMYKColorspace)
for (x=0; x < (ssize_t) destination->extent.width; x++)
PixelSetBlackQuantum(destination->pixel_wands[id][x],
GetPixelBlack(indexes+x));
if (destination_image->storage_class == PseudoClass)
for (x=0; x < (ssize_t) destination->extent.width; x++)
PixelSetIndex(destination->pixel_wands[id][x],
GetPixelIndex(indexes+x));
if (transfer(source,destination,y,id,context) == MagickFalse)
status=MagickFalse;
for (x=0; x < (ssize_t) destination->extent.width; x++)
PixelGetQuantumColor(destination->pixel_wands[id][x],
destination_pixels+x);
if (destination_image->colorspace == CMYKColorspace)
for (x=0; x < (ssize_t) destination->extent.width; x++)
SetPixelBlack(destination_indexes+x,PixelGetBlackQuantum(
destination->pixel_wands[id][x]));
sync=SyncCacheViewAuthenticPixels(destination->view,exception);
if (sync == MagickFalse)
{
InheritException(destination->exception,GetCacheViewException(
source->view));
status=MagickFalse;
}
if (source_image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickWand_TransferWandViewIterator)
#endif
proceed=SetImageProgress(source_image,source->description,progress++,
source->extent.height);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
return(status == MagickFalse ? 0 : 1);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U p d a t e W a n d V i e w I t e r a t o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UpdateWandViewIterator() iterates over the wand view in parallel and calls
% your update method for each scanline of the view. The pixel extent is
% confined to the image canvas-- that is no negative offsets or widths or
% heights that exceed the image dimension are permitted. Updates to pixels
% in your callback are automagically synced back to the image.
%
% The callback signature is:
%
% MagickBooleanType UpdateImageViewMethod(WandView *source,const ssize_t y,
% const int thread_id,void *context)
%
% Use this pragma if the view is not single threaded:
%
% #pragma omp critical
%
% to define a section of code in your callback update method that must be
% executed by a single thread at a time.
%
% The format of the UpdateWandViewIterator method is:
%
% MagickBooleanType UpdateWandViewIterator(WandView *source,
% UpdateWandViewMethod update,void *context)
%
% A description of each parameter follows:
%
% o source: the source wand view.
%
% o update: the update callback method.
%
% o context: the user defined context.
%
*/
WandExport MagickBooleanType UpdateWandViewIterator(WandView *source,
UpdateWandViewMethod update,void *context)
{
ExceptionInfo
*exception;
Image
*source_image;
MagickBooleanType
status;
MagickOffsetType
progress;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
size_t
height;
#endif
ssize_t
y;
assert(source != (WandView *) NULL);
assert(source->signature == WandSignature);
if (update == (UpdateWandViewMethod) NULL)
return(MagickFalse);
source_image=source->wand->images;
if (SetImageStorageClass(source_image,DirectClass) == MagickFalse)
return(MagickFalse);
status=MagickTrue;
progress=0;
exception=source->exception;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
height=(size_t) (source->extent.height-source->extent.y);
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(source_image,source_image,height,1)
#endif
for (y=source->extent.y; y < (ssize_t) source->extent.height; y++)
{
const int
id = GetOpenMPThreadId();
register IndexPacket
*restrict indexes;
register ssize_t
x;
register PixelPacket
*restrict pixels;
if (status == MagickFalse)
continue;
pixels=GetCacheViewAuthenticPixels(source->view,source->extent.x,y,
source->extent.width,1,exception);
if (pixels == (PixelPacket *) NULL)
{
InheritException(source->exception,GetCacheViewException(
source->view));
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(source->view);
for (x=0; x < (ssize_t) source->extent.width; x++)
PixelSetQuantumColor(source->pixel_wands[id][x],pixels+x);
if (source_image->colorspace == CMYKColorspace)
for (x=0; x < (ssize_t) source->extent.width; x++)
PixelSetBlackQuantum(source->pixel_wands[id][x],
GetPixelBlack(indexes+x));
if (update(source,y,id,context) == MagickFalse)
status=MagickFalse;
for (x=0; x < (ssize_t) source->extent.width; x++)
PixelGetQuantumColor(source->pixel_wands[id][x],pixels+x);
if (source_image->colorspace == CMYKColorspace)
for (x=0; x < (ssize_t) source->extent.width; x++)
SetPixelBlack(indexes+x,PixelGetBlackQuantum(
source->pixel_wands[id][x]));
if (SyncCacheViewAuthenticPixels(source->view,exception) == MagickFalse)
{
InheritException(source->exception,GetCacheViewException(source->view));
status=MagickFalse;
}
if (source_image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickWand_UpdateWandViewIterator)
#endif
proceed=SetImageProgress(source_image,source->description,progress++,
source->extent.height);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
return(status == MagickFalse ? 0 : 1);
}
|
morn_matrix.c
|
/*
Copyright (C) 2019-2020 JingWeiZhangHuai <[email protected]>
Licensed under the Apache License, Version 2.0; you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
#include "morn_math.h"
struct HandleVectorCreate
{
MVector *vec;
MChain *property;
int64_t reserve[8];
int writeable;
int size;
MMemory *memory;
};
void endVectorCreate(struct HandleVectorCreate *handle)
{
mException((handle->vec==NULL),EXIT,"invalid vector");
if(handle->property!=NULL) mChainRelease(handle->property);
if(handle->memory != NULL) mMemoryRelease(handle->memory);
memset(handle->vec,0,sizeof(MVector));
mFree(((MList **)(handle->vec))-1);
}
#define HASH_VectorCreate 0xfc0b887c
MVector *VectorCreate(int size,float *data)
{
MList **phandle = (MList **)mMalloc(sizeof(MList *)+sizeof(MVector));
MVector *vec = (MVector *)(phandle+1);
memset(vec,0,sizeof(MVector));
if(size<0) size = 0;
vec->size = size;
*phandle = mHandleCreate();
MHandle *hdl=mHandle(vec,VectorCreate);
struct HandleVectorCreate *handle = (struct HandleVectorCreate *)(hdl->handle);
handle->vec = vec;
if(size==0)
{
mException((!INVALID_POINTER(data)),EXIT,"invalid input");
}
else if(INVALID_POINTER(data))
{
handle->memory = mMemoryCreate(1,size*sizeof(float),MORN_HOST);
handle->size = size;
vec->data = handle->memory->data[0];
}
else
vec->data = data;
mPropertyFunction(vec,"device",mornMemoryDevice,handle->memory);
return vec;
}
void mVectorRelease(MVector *vec)
{
mHandleRelease(vec);
}
void VectorRedefine(MVector *vec,int size,float *data)
{
mException(INVALID_POINTER(vec),EXIT,"invalid input");
if(size <= 0) size = vec->size;
if(size!=vec->size)mHandleReset(vec);
int same_size = (size <= vec->size);
int reuse = (data==vec->data);
int flag = (vec->size >0);
vec->size=size;
if(same_size&&reuse) return;
struct HandleVectorCreate *handle = (struct HandleVectorCreate *)(ObjHandle(vec,0)->handle);
if(same_size&&(data==NULL)&&(handle->size>0)) return;
mException(reuse&&flag&&(handle->size==0),EXIT,"invalid redefine");
handle->size=0;
if(size <= 0) {mException((data!=NULL)&&(!reuse),EXIT,"invalid input"); vec->data = NULL; return;}
if(reuse) data=NULL;
if(data!=NULL){vec->data = data; return;}
if(size>handle->size)
{
handle->size = size;
if(handle->memory==NULL)
{
handle->memory = mMemoryCreate(1,size*sizeof(float),MORN_HOST);
mPropertyFunction(vec,"device",mornMemoryDevice,handle->memory);
}
else mMemoryRedefine(handle->memory,1,size*sizeof(float),DFLT);
vec->data = handle->memory->data[0];
}
}
void PrintMat(MMatrix *mat)
{
printf("row=%d,col=%d:\n",mat->row,mat->col);
int i,j;
for(j=0;j<mat->row;j++)
{
for(i=0;i<mat->col;i++)
printf("%f\t",mat->data[j][i]);
printf("\n");
}
}
struct HandleMatrixCreate
{
MMatrix *mat;
MChain *property;
int64_t reserve[8];
int writeable;
int row;
int col;
float **index;
MMemory *memory;
};
void endMatrixCreate(struct HandleMatrixCreate *handle)
{
mException((handle->mat == NULL),EXIT,"invalid matrix");
if(handle->property!= NULL) mChainRelease(handle->property);
if(handle->index != NULL) mFree(handle->index);
if(handle->memory != NULL) mMemoryRelease(handle->memory);
memset(handle->mat,0,sizeof(MMatrix));
mFree(((MList **)(handle->mat))-1);
}
#define HASH_MatrixCreate 0xe48fad76
MMatrix *MatrixCreate(int row,int col,float **data)
{
MList **phandle = (MList **)mMalloc(sizeof(MList *)+sizeof(MMatrix));
MMatrix *mat = (MMatrix *)(phandle+1);
memset(mat,0,sizeof(MMatrix));
if(col <0) {col = 0;} mat->col = col;
if(row <0) {row = 0;} mat->row = row;
*phandle = mHandleCreate();
MHandle *hdl=mHandle(mat,MatrixCreate);
struct HandleMatrixCreate *handle = (struct HandleMatrixCreate *)(hdl->handle);
handle->mat = mat;
if(row == 0)
{
mException((!INVALID_POINTER(data)),EXIT,"invalid input");
return mat;
}
if(!INVALID_POINTER(data))
{
mat->data = data;
return mat;
}
handle->index = (float **)mMalloc(row*sizeof(float *));
handle->row = row;
if(col == 0)
{
mException((!INVALID_POINTER(data)),EXIT,"invalid input");
memset(handle->index,0,row*sizeof(float *));
}
else
{
if(handle->memory == NULL)handle->memory = mMemoryCreate(1,row*col*sizeof(float),MORN_HOST);
mException(handle->memory->num!=1,EXIT,"invalid image memory");
mMemoryIndex(handle->memory,row,col*sizeof(float),(void ***)(&(handle->index)),1);
handle->col = col;
}
mat->data = handle->index;
mPropertyFunction(mat,"device",mornMemoryDevice,handle->memory);
return mat;
}
MMemoryBlock *mMatrixMemory(MMatrix *mat)
{
int size = mat->row*mat->col*sizeof(float);
float *data = &(mat->data[0][0]);
struct HandleMatrixCreate *handle= (struct HandleMatrixCreate *)(ObjHandle(mat,0)->handle);
if(handle->memory == NULL)
{
handle->memory = mMemoryCreate(1,size,MORN_HOST);
mPropertyFunction(mat,"device",mornMemoryDevice,handle->memory);
}
MMemoryBlock *mem = handle->memory->data[0];
if(mem->size!=size)
mMemoryIndex(handle->memory,mat->row,mat->col*sizeof(float),(void ***)(&(handle->index)),1);
if(mem->data!=data) memcpy(mem->data,data,size);
return mem;
}
void mMatrixRelease(MMatrix *mat)
{
mHandleRelease(mat);
}
void MatrixRedefine(MMatrix *mat,int row,int col,float **data)
{
mException((INVALID_POINTER(mat)),EXIT,"invalid input");
if(row<=0) row = mat->row;
if(col<=0) col = mat->col;
if((row!=mat->row)||(col!=mat->col)) mHandleReset(mat);
int same_size=((row<=mat->row)&&(col<=mat->col));
int reuse = (data==mat->data);
int flag=(mat->row)&&(mat->col);
mat->row = row;
mat->col = col;
if(same_size&&reuse) return;
struct HandleMatrixCreate *handle= (struct HandleMatrixCreate *)(ObjHandle(mat,0)->handle);
if(same_size&&(data==NULL)&&(handle->col>0)) return;
mException(reuse&&flag&&(handle->col==0),EXIT,"invalid redefine");
handle->col=0;
if((row == 0)||(col==0)) {mException((data!=NULL)&&(!reuse),EXIT,"invalid input"); mat->data=NULL; return;}
if(reuse) data=NULL;
if(row>handle->row)
{
if(handle->index != NULL)
mFree(handle->index);
handle->index = NULL;
}
if(handle->index == NULL)
{
handle->index = (float **)mMalloc(row*sizeof(float *));
handle->row = row;
}
mat->data = handle->index;
if(!INVALID_POINTER(data)) {memcpy(handle->index,data,row*sizeof(float *));return;}
if(handle->memory == NULL)
{
handle->memory = mMemoryCreate(1,row*col*sizeof(float),MORN_HOST);
mPropertyFunction(mat,"device",mornMemoryDevice,handle->memory);
}
else mMemoryRedefine(handle->memory,1,row*col*sizeof(float),DFLT);
mMemoryIndex(handle->memory,row,col*sizeof(float),(void ***)(&(handle->index)),1);
handle->col = col;
}
void mUnitMatrix(MMatrix *mat,int size)
{
mException(mat==NULL,EXIT,"invalid input matrix");
if(size<0)
{
size = mat->row;
mException(size!=mat->col,EXIT,"invalid input");
}
else mMatrixRedefine(mat,size,size,mat->data,DFLT);
int i;
#pragma omp parallel for
for(i=0;i<size;i++)
{
memset(mat->data[i],0,size*sizeof(float));
mat->data[i][i] = 1.0f;
}
}
void mMatrixTranspose(MMatrix *mat,MMatrix *dst)
{
mException(mat==NULL,EXIT,"invalid input matrix");
int i,j;
int dst_col,dst_row;
MMatrix *p;
dst_col = mat->row;
dst_row = mat->col;
mException((INVALID_MAT(mat)),EXIT,"invalid input");
p = dst;
if((INVALID_POINTER(dst))||(dst==mat)) dst = mMatrixCreate(dst_row,dst_col,NULL);
else mMatrixRedefine(dst,dst_row,dst_col,dst->data);
for(i=0;i<dst_row-8;i=i+8)
{
for(j=0;j<dst_col;j++)
{
dst->data[i][j] = mat->data[j][i];
dst->data[i+1][j] = mat->data[j][i+1];
dst->data[i+2][j] = mat->data[j][i+2];
dst->data[i+3][j] = mat->data[j][i+3];
dst->data[i+4][j] = mat->data[j][i+4];
dst->data[i+5][j] = mat->data[j][i+5];
dst->data[i+6][j] = mat->data[j][i+6];
dst->data[i+7][j] = mat->data[j][i+7];
}
}
// #pragma omp parallel for
for(;i<dst_row;i++)
for(j=0;j<dst_col;j++)
dst->data[i][j] = mat->data[j][i];
if(p!=dst)
{
mObjectExchange(mat,dst,MMatrix);
mMatrixRelease(dst);
}
}
void VectorAdd(float *vec1,float *vec2,float *dst,int num)
{
int i;
for(i=0;i<num;i++)
dst[i] = vec1[i]+vec2[i];
}
void mVectorAdd(MVector *vec1,MVector *vec2,MVector *dst)
{
int i;
mException((INVALID_VEC(vec1)||INVALID_VEC(vec2)||(vec1->size !=vec2->size)),EXIT,"invalid input");
if(INVALID_POINTER(dst)) dst = vec1;
else mVectorRedefine(dst,vec1->size,dst->data,vec1->device);
for(i=0;i<vec1->size;i++)
dst->data[i] = vec1->data[i] + vec2->data[i];
}
void mMatrixAdd(MMatrix *mat1,MMatrix *mat2,MMatrix *dst)
{
int j;
mException(INVALID_MAT(mat1)||INVALID_MAT(mat2),EXIT,"invalid input");
mException((mat1->row!=mat2->row)||(mat1->col!=mat2->col),EXIT,"invalid input");
if(INVALID_POINTER(dst)) dst = mat1;
else mMatrixRedefine(dst,mat1->row,mat1->col,dst->data,DFLT);
#pragma omp parallel for
for(j=0;j<dst->row;j++)
for(int i=0;i<dst->col;i++)
dst->data[j][i] = mat1->data[j][i]+mat2->data[j][i];
}
void mMatrixSub(MMatrix *mat1,MMatrix *mat2,MMatrix *dst)
{
int j;
mException(INVALID_MAT(mat1)||INVALID_MAT(mat2),EXIT,"invalid input");
mException((mat1->row!=mat2->row)||(mat1->col!=mat2->col),EXIT,"invalid input");
if(INVALID_POINTER(dst)) dst = mat1;
else mMatrixRedefine(dst,mat1->row,mat1->col,dst->data,DFLT);
#pragma omp parallel for
for(j=0;j<dst->row;j++)
for(int i=0;i<dst->col;i++)
dst->data[j][i] = mat1->data[j][i]+mat2->data[j][i];
}
float VectorMul(float *vec1,float *vec2,int num)
{
int i;
float sum;
sum = 0.0f;
for(i=0;i<num;i++)
sum = sum + vec1[i]*vec2[i];
return sum;
}
float mVectorMul(MVector *vec1,MVector *vec2)
{
int i;
float result;
mException((INVALID_VEC(vec1)||INVALID_VEC(vec2)||(vec1->size !=vec2->size)),EXIT,"invalid input");
result = 0.0f;
for(i=0;i<vec1->size;i++)
result = result + vec1->data[i]*vec2->data[i];
return result;
}
void VectorScalarMul(float *vec1,float *vec2,float *dst,int num)
{
int i;
for(i=0;i<num;i++)
dst[i] = vec1[i]*vec2[i];
}
void mVectorScalarMul(MVector *vec1,MVector *vec2,MVector *dst)
{
int i;
mException((INVALID_VEC(vec1)||INVALID_VEC(vec2)||(vec1->size !=vec2->size)),EXIT,"invalid input");
if(INVALID_POINTER(dst)) dst = vec1;
else mVectorRedefine(dst,vec1->size,dst->data,vec1->device);
for(i=0;i<vec1->size;i++)
dst->data[i] = vec1->data[i] * vec2->data[i];
}
void MatrixVectorMul(MMatrix *mat,float *vec,float *dst)
{
int i,j;
int num_in,num_out;
num_in = mat->col;
num_out = mat->row;
memset(dst,0,num_out*sizeof(float));
for(i=0;i<num_out;i++)
for(j=0;j<num_in;j++)
dst[i] = dst[i] + vec[j]*mat->data[i][j];
}
void mMatrixVectorMul(MMatrix *mat,MVector *vec,MVector *dst)
{
int i,j;
int num_in;
int num_out;
MVector *p= dst;
mException((INVALID_MAT(mat)||INVALID_VEC(vec)),EXIT,"invalid input");
num_in = mat->col;
mException((vec->size != num_in),EXIT,"invalid input");
num_out = mat->row;
if(INVALID_POINTER(dst)||(dst == vec)) dst = mVectorCreate(num_out,NULL,vec->device);
else mVectorRedefine(dst,num_out,dst->data,vec->device);
for(i=0;i<num_out;i++)
{
dst->data[i] = 0.0f;
for(j=0;j<num_in;j++)
dst->data[i] = dst->data[i] + vec->data[j]*mat->data[i][j];
}
if(p!=dst)
{
mObjectExchange(dst,vec,MVector);
mVectorRelease(dst);
}
}
void VectorMatrixMul(float *vec,MMatrix *mat,float *dst)
{
int i,j;
int num_in,num_out;
num_in = mat->row;
num_out = mat->col;
memset(dst,0,num_out*sizeof(float));
for(j=0;j<num_in;j++)
for(i=0;i<num_out;i++)
dst[i] = dst[i] + vec[j]*mat->data[j][i];
}
void mVectorMatrixMul(MVector *vec,MMatrix *mat,MVector *dst)
{
int i,j;
int num_in;
int num_out;
MVector *p;
mException(((INVALID_MAT(mat))||(INVALID_VEC(vec))),EXIT,"invalid input");
p = dst;
num_in = mat->row;
mException((vec->size != num_in),EXIT,"invalid input");
num_out = mat->col;
if(INVALID_POINTER(dst)||(dst == vec)) dst = mVectorCreate(num_out,NULL,vec->device);
else mVectorRedefine(dst,num_out,dst->data,vec->device);
for(i=0;i<num_out;i++)
{
dst->data[i] = 0.0f;
for(j=0;j<num_in;j++)
dst->data[i] = dst->data[i] + vec->data[j]*mat->data[j][i];
}
if(p!=dst)
{
mObjectExchange(vec,dst,MVector);
mVectorRelease(dst);
}
}
void mMatrixScalar(MMatrix *src,MMatrix *dst,float k,float b)
{
mException((src==NULL),EXIT,"invalid input");
if(dst==NULL) dst=src;
for(int j=0;j<src->row;j++)for(int i=0;i<src->col;i++)
dst->data[j][i] = src->data[j][i]*k+b;
}
void mMatrixScalarMul(MMatrix *mat1,MMatrix *mat2,MMatrix *dst)
{
int i,j;
mException((INVALID_MAT(mat1)||INVALID_MAT(mat2)),EXIT,"invalid input");
mException((mat1->row != mat2->row)||(mat1->col != mat2->col),EXIT,"invalid input");
if(INVALID_POINTER(dst)) dst = mat1;
else mMatrixRedefine(dst,mat1->row,mat1->col,dst->data,DFLT);
for(j=0;j<mat1->row;j++)
for(i=0;i<mat1->col;i++)
dst->data[j][i] = mat1->data[j][i]*mat2->data[j][i];
}
/*
void mMatrixMul0(MMatrix *mat1,MMatrix *mat2,MMatrix *dst)
{
int i,j,k;
int dst_col,dst_row;
int num;
MMatrix *p;
float data;
float *psrc,*pdst;
mException((INVALID_MAT(mat1))||(INVALID_MAT(mat2)),EXIT,"invalid input");
mException((mat1->col != mat2->row),EXIT,"invalid operate");
num = mat1->col;
dst_col = mat2->col;
dst_row = mat1->row;
p = dst;
if((INVALID_POINTER(dst))||(dst==mat1)||(dst==mat2)) dst = mMatrixCreate(dst_row,dst_col,NULL);
else mMatrixRedefine(dst,dst_row,dst_col,dst->data);
for(j=0;j<dst_row;j++)
{
pdst = dst->data[j];
{
data = mat1->data[j][0];
psrc = mat2->data[0];
for(k=0;k<dst_col-8;k=k+8)
{
pdst[k] = data*psrc[k];
pdst[k+1] = data*psrc[k+1];
pdst[k+2] = data*psrc[k+2];
pdst[k+3] = data*psrc[k+3];
pdst[k+4] = data*psrc[k+4];
pdst[k+5] = data*psrc[k+5];
pdst[k+6] = data*psrc[k+6];
pdst[k+7] = data*psrc[k+7];
}
for(;k<dst_col;k++)
pdst[k] = data*psrc[k];
}
for(i=1;i<num;i++)
{
data = mat1->data[j][i];
psrc = mat2->data[i];
for(k=0;k<dst_col-8;k=k+8)
{
pdst[k] += data*psrc[k];
pdst[k+1] += data*psrc[k+1];
pdst[k+2] += data*psrc[k+2];
pdst[k+3] += data*psrc[k+3];
pdst[k+4] += data*psrc[k+4];
pdst[k+5] += data*psrc[k+5];
pdst[k+6] += data*psrc[k+6];
pdst[k+7] += data*psrc[k+7];
}
for(;k<dst_col;k++)
pdst[k] += data*psrc[k];
}
}
if(p != dst)
{
if(p == mat2)
{
mMatrixExchange(mat2,dst);
mMatrixRelease(dst);
}
else
{
mMatrixExchange(mat1,dst);
mMatrixRelease(dst);
}
}
}
*/
void mMatrixMul(MMatrix *mat1,MMatrix *mat2,MMatrix *dst)
{
mException((INVALID_MAT(mat1))||(INVALID_MAT(mat2)),EXIT,"invalid input");
mException((mat1->col != mat2->row),EXIT,"invalid operate");
int num = mat1->col;
int dst_col = mat2->col;
int dst_row = mat1->row;
MMatrix *p = dst;
if((INVALID_POINTER(dst))||(dst==mat1)||(dst==mat2)) dst = mMatrixCreate(dst_row,dst_col,NULL);
else mMatrixRedefine(dst,dst_row,dst_col,dst->data);
int flag = num&0x03; if(flag==0) flag = 4;
int i,j,k;
float data1,data2,data3,data4;
float *psrc1,*psrc2,*psrc3,*psrc4;
float *pdst;
#pragma omp parallel for
for(j=0;j<dst_row;j++)
{
pdst = dst->data[j];
data1 = mat1->data[j][0];
psrc1 = mat2->data[0];
for(k=0;k<dst_col;k++)
pdst[k] = data1*psrc1[k];
for(i=1;i<flag;i++)
{
data1 = mat1->data[j][i];
psrc1 = mat2->data[i];
for(k=0;k<dst_col;k++)
pdst[k] += data1*psrc1[k];
}
for(i=flag;i<num;i=i+4)
{
data1 = mat1->data[j][i];
psrc1 = mat2->data[i];
data2 = mat1->data[j][i+1];
psrc2 = mat2->data[i+1];
data3 = mat1->data[j][i+2];
psrc3 = mat2->data[i+2];
data4 = mat1->data[j][i+3];
psrc4 = mat2->data[i+3];
for(k=0;k<dst_col;k++)
pdst[k] += data1*psrc1[k]+data2*psrc2[k]+data3*psrc3[k]+data4*psrc4[k];
}
}
if(p != dst)
{
if(p == mat2)
{
mObjectExchange(mat2,dst,MMatrix);
mMatrixRelease(dst);
}
else
{
mObjectExchange(mat1,dst,MMatrix);
mMatrixRelease(dst);
}
}
}
float mMatrixDetValue(MMatrix *mat)
{
int i,j,k;
int num;
double *buff;
double w;
double value;
double **data;
mException((INVALID_MAT(mat)),EXIT,"invalid input");
num = mat->row;
mException((mat->col != num),EXIT,"invalid operate");
if(num == 1)
return mat->data[0][0];
if(num == 2)
{
value = mat->data[0][0]*mat->data[1][1]-mat->data[1][0]*mat->data[0][1];
return value;
}
if(num == 3)
{
value = mat->data[0][0]*(mat->data[1][1]*mat->data[2][2]-mat->data[1][2]*mat->data[2][1])
+ mat->data[0][1]*(mat->data[1][2]*mat->data[2][0]-mat->data[1][0]*mat->data[2][2])
+ mat->data[0][2]*(mat->data[1][0]*mat->data[2][1]-mat->data[1][1]*mat->data[2][0]);
return value;
}
data = (double **)mMalloc((num+1)*sizeof(double *));
data[0] = (double *)mMalloc(num*num*sizeof(double));
for(j=0;j<num;j++)
{
for(i=0;i<num;i++)
data[j][i] = (double)(mat->data[j][i]);
data[j+1] = data[j]+num;
}
// data = mMatrixCreate(num,num,NULL);
// for(j=0;j<num;j++)
// memcpy(data->data[j],mat->data[j],num*sizeof(float));
// PrintMat(data);
// #define DATA(y,x) (data[y][x])
value = 1.0;
// 高斯消元
for(k=0;k<num;k++)
{
if(data[k][k]==0)
{
for(j=k+1;j<num;j++)
if(data[j][k]!=0)
{
buff = data[k];
data[k] = data[j];
data[j] = buff;
value = 0-value;
break;
}
// 如果无解则返回0
if(j==num)
{
mFree(data);
mFree(data[0]);
return 0.0f;
}
}
value = value * data[k][k];
for(j=k+1;j<num;j++)
// if(data[j][k]!=0)
{
w = data[j][k]/data[k][k];
for(i=k+1;i<num;i++)
data[j][i] = data[j][i]-w*data[k][i];
}
// printf("aaaaaaaaaa %d:%f\n",k,data[k][k]);
// PrintMat(data);
}
mFree(data[0]);
mFree(data);
return (float)value;
}
int mMatrixInverse(MMatrix *mat,MMatrix *inv)
{
int i,j,k;
int num;
double *buff;
double w;
double **data;
// MMatrix *data;
MMatrix *p;
mException((INVALID_MAT(mat)),EXIT,"invalid input");
num = mat->row;
mException((mat->col != num),EXIT,"invalid operate");
p = inv;
if((INVALID_POINTER(inv))||(inv == mat)) inv = mMatrixCreate(num,num,NULL);
else mMatrixRedefine(inv,num,num,inv->data,DFLT);
data = (double **)mMalloc((num+1)*sizeof(double *));
data[0] = (double *)mMalloc((num+num)*num*sizeof(double));
for(j=0;j<num;j++)
{
for(i=0;i<num;i++)
data[j][i] = (double)(mat->data[j][i]);
memset(data[j]+num,0,num*sizeof(double));
data[j][num+j] = -1.0;
data[j+1] = data[j]+num+num;
}
// data = mMatrixCreate(num,num+num,NULL);
// for(j=0;j<num;j++)
// {
// memcpy(data->data[j],mat->data[j],num*sizeof(float));
// memset(data->data[j] + num,0,num*sizeof(float));
// data->data[j][num+j] = -1.0;
// }
// PrintMat(data);
// #define DATA(y,x) (data->data[y][x])
// 高斯消元
for(k=0;k<num;k++)
{
if(data[k][k]==0)
{
for(j=k+1;j<num;j++)
if(data[j][k]!=0)
{
buff = data[k];
data[k] = data[j];
data[j] = buff;
break;
}
// 如果无解则返回0
if(j==num)
{
mFree(data);
mFree(data[0]);
if(p!=inv)
mMatrixRelease(inv);
return 0.0;
}
}
for(j=k+1;j<num;j++)
if(data[j][k]!=0)
{
w = data[j][k]/data[k][k];
// data[j][k]=0;
for(i=k+1;i<num+num;i++)
data[j][i] = data[j][i]-w*data[k][i];
}
// printf("aaaaaaaaaa %d\n",k);
// PrintMat(data);
}
for(k=0;k<num;k++)
{
for(j=num-1;j>=0;j--)
{
data[j][num+k] = 0-data[j][num+k];
for(i=num-1;i>j;i--)
data[j][num+k] = data[j][num+k] - data[j][i]*data[i][num+k];
data[j][num+k] = data[j][num+k]/data[j][j];
inv->data[j][k] = (float)data[j][num+k];
}
}
mFree(data[0]);
mFree(data);
if(p!=inv)
{
mObjectExchange(inv,mat,MMatrix);
mMatrixRelease(inv);
}
return 1;
}
int mLinearEquation(MMatrix *mat,float *answer)
{
int i,j,k;
float *buff;
float w;
MMatrix *data;
mException((INVALID_MAT(mat))||(INVALID_POINTER(answer)),EXIT,"invalid input");
mException(((mat->col - mat->row)!=1),EXIT,"invalid operate");
int num = mat->row;
if(num == 1)
{
mException((mat->data[0][0]==0.0f),EXIT,"invalid input");
*answer = (0.0f-mat->data[0][1])/mat->data[0][0];
return 1;
}
data = mMatrixCreate(num,num+1,NULL);
for(j=0;j<num;j++)
memcpy(data->data[j],mat->data[j],(num+1)*sizeof(float));
#define DATA(y,x) (data->data[y][x])
// 高斯消元
for(k=0;k<num;k++)
{
if(DATA(k,k)==0)
{
for(j=k+1;j<num;j++)
if(DATA(j,k)!=0)
{
buff = data->data[k];
data->data[k] = data->data[j];
data->data[j] = buff;
break;
}
// 如果无解则返回0
if(j==num)
{
mMatrixRelease(data);
return 0;
}
}
for(j=k+1;j<num;j++)
if(DATA(j,k)!=0)
{
w = DATA(j,k)/DATA(k,k);
DATA(j,k)=0;
for(i=k+1;i<num+1;i++)
DATA(j,i) = DATA(j,i)-w*DATA(k,i);
}
}
// 答案求解
for(j=num-1;j>=0;j--)
{
answer[j] = 0-DATA(j,num);
for(i=num-1;i>j;i--)
answer[j] = answer[j] - DATA(j,i)*answer[i];
answer[j] = answer[j]/DATA(j,j);
}
mMatrixRelease(data);
return 1;
}
|
hypergeometric_distribution.c
|
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
#define TOLERANCE 0.000000001
#define MALICIOUS_RATE 0.9
void factorial(mpf_t res, int n)
{
int i;
mpf_t p;
mpf_init_set_ui(p,1);
for (i=1; i <= n ; ++i){
mpf_mul_ui(p,p,i);
}
mpf_set(res, p);
mpf_clear(p);
}
// Combination: factorial(n) / ( factorial(r) * factorial(n-r) )
void combination(mpf_t comb, int n, int r) {
mpf_t fact_n;
mpf_init(fact_n);
mpf_t fact_r;
mpf_init(fact_r);
mpf_t fact_n_minus_r;
mpf_init(fact_n_minus_r);
factorial(fact_n, n);
factorial(fact_r, r);
factorial(fact_n_minus_r, n - r);
mpf_t fact_r_mul_fact_r_minus_r;
mpf_init(fact_r_mul_fact_r_minus_r);
mpf_mul(fact_r, fact_r, fact_n_minus_r);
mpf_div(comb, fact_n, fact_r);
mpf_clear(fact_n);
mpf_clear(fact_r);
mpf_clear(fact_n_minus_r);
mpf_clear(fact_r_mul_fact_r_minus_r);
}
void hypergeometric_distribution(int nb_nodes) {
int nb_malicious = nb_nodes * MALICIOUS_RATE;
int nb_good = nb_nodes - nb_malicious;
int n = 1;
mpf_t tolerance;
mpf_init_set_d(tolerance, TOLERANCE);
int abort = 0;
#pragma omp parallel for schedule(dynamic) shared(abort)
for (n = 1; n <= nb_nodes; n++) {
#pragma omp flush(abort)
if (abort == 0) {
mpf_t sum;
mpf_t sum_minus_1;
mpf_init(sum);
mpf_init(sum_minus_1);
for (int k = 1; k <= nb_good; k++) {
if (abort == 0) {
if (n - k >= 0 && nb_good - k >= 0 && nb_malicious >= n - k) {
mpf_t comb_nb_good_with_k;
mpf_t comb_nb_malicious_with_n_minus_k;
mpf_t comb_nb_nodes_with_n;
mpf_init(comb_nb_good_with_k);
mpf_init(comb_nb_malicious_with_n_minus_k);
mpf_init(comb_nb_nodes_with_n);
// combination(nb_good, k) * combination(nb_malicious, n - k ) / combination(nb_nodes, n)
combination(comb_nb_good_with_k, nb_good, k);
combination(comb_nb_malicious_with_n_minus_k, nb_malicious, n - k);
mpf_mul(comb_nb_good_with_k, comb_nb_good_with_k, comb_nb_malicious_with_n_minus_k);
combination(comb_nb_nodes_with_n, nb_nodes, n);
mpf_div(comb_nb_good_with_k, comb_nb_good_with_k, comb_nb_nodes_with_n);
mpf_add(sum, sum, comb_nb_good_with_k);
mpf_ui_sub(sum_minus_1, 1, sum);
if (mpf_cmp(sum_minus_1, tolerance) == -1) {
#pragma omp critical
{
if (abort == 0) {
printf("%d\r\n", n);
#pragma omp atomic write
abort = 1;
#pragma omp cancel for
}
}
}
#pragma omp cancellation point for
}
}
}
}
}
}
int main(int argc, char *argv[]) {
if( argc == 2 ) {
int nb_nodes = atoi(argv[1]);
hypergeometric_distribution(nb_nodes);
}
return 0;
}
|
core_dgeqrt.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/core_blas/core_zgeqrt.c, normal z -> d, Fri Sep 28 17:38:20 2018
*
**/
#include <plasma_core_blas.h>
#include "plasma_types.h"
#include "plasma_internal.h"
#include "core_lapack.h"
#include <omp.h>
/***************************************************************************//**
*
* @ingroup core_geqrt
*
* Computes a QR factorization of an m-by-n tile A:
* The factorization has the form
* \f[
* A = Q \times R
* \f]
* The tile Q is represented as a product of elementary reflectors
* \f[
* Q = H(1) H(2) ... H(k),
* \f]
* where \f$ k = min(m,n) \f$.
*
* Each \f$ H(i) \f$ has the form
* \f[
* H(i) = I - \tau \times v \times v^T
* \f]
* where \f$ tau \f$ is a scalar, and \f$ v \f$ is a vector with
* v(1:i-1) = 0 and v(i) = 1; v(i+1:m) is stored on exit in A(i+1:m,i),
* and \f$ tau \f$ in tau(i).
*
*******************************************************************************
*
* @param[in] m
* The number of rows of the tile A. m >= 0.
*
* @param[in] n
* The number of columns of the tile A. n >= 0.
*
* @param[in] ib
* The inner-blocking size. ib >= 0.
*
* @param[in,out] A
* On entry, the m-by-n tile A.
* On exit, the elements on and above the diagonal of the array
* contain the min(m,n)-by-n upper trapezoidal tile R (R is
* upper triangular if m >= n); the elements below the diagonal,
* with the array tau, represent the orthogonal tile Q as a
* product of elementary reflectors (see Further Details).
*
* @param[in] lda
* The leading dimension of the array A. lda >= max(1,m).
*
* @param[out] T
* The ib-by-n triangular factor T of the block reflector.
* T is upper triangular by block (economic storage);
* The rest of the array is not referenced.
*
* @param[in] ldt
* The leading dimension of the array T. ldt >= ib.
*
* @param tau
* Auxiliary workspace array of length n.
*
* @param work
* Auxiliary workspace array of length ib*n.
*
* @param[in] lwork
* Size of the array work. Should be at least ib*n.
*
*******************************************************************************
*
* @retval PlasmaSuccess successful exit
* @retval < 0 if -i, the i-th argument had an illegal value
*
******************************************************************************/
__attribute__((weak))
int plasma_core_dgeqrt(int m, int n, int ib,
double *A, int lda,
double *T, int ldt,
double *tau,
double *work)
{
// Check input arguments.
if (m < 0) {
plasma_coreblas_error("illegal value of m");
return -1;
}
if (n < 0) {
plasma_coreblas_error("illegal value of n");
return -2;
}
if ((ib < 0) || ( (ib == 0) && (m > 0) && (n > 0) )) {
plasma_coreblas_error("illegal value of ib");
return -3;
}
if (A == NULL) {
plasma_coreblas_error("NULL A");
return -4;
}
if (lda < imax(1, m) && m > 0) {
plasma_coreblas_error("illegal value of lda");
return -5;
}
if (T == NULL) {
plasma_coreblas_error("NULL T");
return -6;
}
if (ldt < imax(1, ib) && ib > 0) {
plasma_coreblas_error("illegal value of ldt");
return -7;
}
if (tau == NULL) {
plasma_coreblas_error("NULL tau");
return -8;
}
if (work == NULL) {
plasma_coreblas_error("NULL work");
return -9;
}
// quick return
if (m == 0 || n == 0 || ib == 0)
return PlasmaSuccess;
int k = imin(m, n);
for (int i = 0; i < k; i += ib) {
int sb = imin(ib, k-i);
LAPACKE_dgeqr2_work(LAPACK_COL_MAJOR,
m-i, sb,
&A[lda*i+i], lda,
&tau[i], work);
LAPACKE_dlarft_work(LAPACK_COL_MAJOR,
lapack_const(PlasmaForward),
lapack_const(PlasmaColumnwise),
m-i, sb,
&A[lda*i+i], lda,
&tau[i],
&T[ldt*i], ldt);
if (n > i+sb) {
LAPACKE_dlarfb_work(LAPACK_COL_MAJOR,
lapack_const(PlasmaLeft),
lapack_const(PlasmaTrans),
lapack_const(PlasmaForward),
lapack_const(PlasmaColumnwise),
m-i, n-i-sb, sb,
&A[lda*i+i], lda,
&T[ldt*i], ldt,
&A[lda*(i+sb)+i], lda,
work, n-i-sb);
}
}
return PlasmaSuccess;
}
/******************************************************************************/
void plasma_core_omp_dgeqrt(int m, int n, int ib,
double *A, int lda,
double *T, int ldt,
plasma_workspace_t work,
plasma_sequence_t *sequence, plasma_request_t *request)
{
#pragma omp task depend(inout:A[0:lda*n]) \
depend(out:T[0:ib*n])
{
if (sequence->status == PlasmaSuccess) {
// Prepare workspaces.
int tid = omp_get_thread_num();
double *tau = ((double*)work.spaces[tid]);
// Call the kernel.
int info = plasma_core_dgeqrt(m, n, ib,
A, lda,
T, ldt,
tau,
tau+n);
if (info != PlasmaSuccess) {
plasma_error("core_dgeqrt() failed");
plasma_request_fail(sequence, request, PlasmaErrorInternal);
}
}
}
}
|
example_04-StructOfArrays-Naive-Omp-SIMD-Tiled.c
|
/*
* SPDX-License-Identifier: BSD-3-Clause
*
* example_04-StructOfArrays-Naive-Omp-SIMD-Tiled.c :
* Example of SPH Density Calculation using a
* naive implementation of the main density loop,
* no neighbours earch, and Struct of Arrays (SoA)
* data layout, OpenMP parallelization and SIMD
* directives on the kernel and density calculation.
* This incorporates strip mining and exchange to
* implement cache blocking and support performance
* for large number of particles that would otherwise
* be lost.
*
* (C) Copyright 2021 José Hugo Elsas
* Author: José Hugo Elsas <[email protected]>
*
* Command Line Options:
* -runs <int> : Set the number of repetitions (runs) for
* calculating the density. The value of
* the density is based on the last
* iteration.
* Default value: 1
* -run_seed <int>: Flag to set an alternative seed use for
* for the PRNG. Instead of feeding seed
* to the PRNG directly, it feeds
* seed + iteration, as to generate different
* configurations for each iteration.
* Default value: 0 - (possible 0/1)
* -seed <int>: Set the seed to use for the SPH particles
* uniform position generation in the box
* Default value: 123123123
*
* -N <int>: Set the number of SPH particles to be used
* Default value: 1e5 = 100,000
* -h <float>: Set the value of the smoothing kernel
* parameter h, which corresponds to half
* of the support of the kernel.
* Default value: 0.05
*
* -Nx <int>: Set the number of Cells in the X direction
* Default value: 10
* -Ny <int>: Set the number of Cells in the Y direction
* Default value: 10
* -Nz <int>: Set the number of Cells in the Z direction
* Default value: 10
*
* -Xmin <float>: Set the lower bound in the X direction for
* the Cell Linked List box
* Default value: 0.0
* -Ymin <float>: Set the lower bound in the Y direction for
* the Cell Linked List box
* Default value: 0.0
* -Zmin <float>: Set the lower bound in the Z direction for
* the Cell Linked List box
* Default value: 0.0
*
* -Xmax <float>: Set the upper bound in the X direction for
* the Cell Linked List box
* Default value: 1.0
* -Ymax <float>: Set the upper bound in the Y direction for
* the Cell Linked List box
* Default value: 1.0
* -Zmax <float>: Set the upper bound in the Z direction for
* the Cell Linked List box
* Default value: 1.0
*/
#include <math.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <unistd.h>
#include <stdbool.h>
#include <sys/time.h>
#include <inttypes.h>
#include <omp.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_heapsort.h>
#include "sph_data_types.h"
#include "sph_linked_list.h"
#include "sph_utils.h"
#ifndef M_PI
#define M_PI (3.14159265358979323846)
#endif
#define COMPUTE_BLOCKS 1
int main_loop(int run, bool run_seed, int64_t N, double h, long int seed,
void *swap_arr, linkedListBox *box, SPHparticle *lsph, double *times);
int compute_density_3d_naive_omp_simd_tiled(int N,double h,
double* restrict x, double* restrict y,
double* restrict z, double* restrict nu,
double* restrict rho);
double w_bspline_3d_constant(double h);
#pragma omp declare simd
double w_bspline_3d_simd(double q);
int main(int argc, char **argv){
bool run_seed = false; // By default the behavior is to use the same seed
int runs = 1; // By default the main loop only runs once
long int seed = 123123123; // The default seed is 123123123
int64_t N = 100000; // The default number of particles is N = 1e5 = 100,000
double h = 0.05; // The default kernel smoothing length is h = 0.05
linkedListBox *box; // Uninitialized Box containing the cells for the cell linked list method
SPHparticle *lsph; // Uninitialized array of SPH particles
box = (linkedListBox*)malloc(1*sizeof(linkedListBox)); // Create a box representing the entire 3d domain
// allow for command line customization of the run
arg_parse(argc,argv,&N,&h,&seed,&runs,&run_seed,box); // Parse the command line options
// line arguments and override default values
int err = SPHparticle_SoA_malloc(N,&lsph); // Create an arrays for the N particles
if(err)
fprintf(stderr,"error in SPHparticle_SoA_malloc\n");
void *swap_arr = malloc(N*sizeof(double));
double times[runs*COMPUTE_BLOCKS];
for(int run=0;run<runs;run+=1)
main_loop(run,run_seed,N,h,seed,swap_arr,box,lsph,times);
bool is_cll = false;
const char *prefix = "ex04,naive,SoA,omp,simd,tiled";
print_time_stats(prefix,is_cll,N,h,seed,runs,lsph,box,times);
print_sph_particles_density(prefix,is_cll,N,h,seed,runs,lsph,box);
SPHparticleSOA_safe_free(N,&lsph);
safe_free_box(box);
free(swap_arr);
return 0;
}
/*
* Function main_loop:
* Runs the main loop of the program, including the particle array generation,
* density calculation and the timings annotations.
*
* Arguments:
* run <int> : index (or value) or the present iteration
* run_seed <bool> : boolean defining whether to use run index for seed or not
* N <int> : Number of SPH particles to be used in the run
* h <double> : Smoothing Length for the Smoothing Kernel w_bspline
* seed <long int> : seed for GSL PRNG to generate particle positions
* box <linkedListBox> : Box of linked list cells, encapsulating the 3d domain
* lsph <SPHparticle> : Array (pointer) of SPH particles to be updated
* times <double> : Array to store the computation timings to be updated
* Returns:
* 0 : error code returned
* lsph <SPHparticle> : SPH particle array is updated in the rho field by reference
* times <double> : Times is updated by reference
*/
int main_loop(int run, bool run_seed, int64_t N, double h, long int seed,
void *swap_arr, linkedListBox *box, SPHparticle *lsph, double *times)
{
int err;
if(run_seed)
err = gen_unif_rdn_pos_box(N,seed+run,box,lsph);
else
err = gen_unif_rdn_pos_box(N,seed,box,lsph);
if(err)
fprintf(stderr,"error in gen_unif_rdn_pos\n");
// ------------------------------------------------------ //
double t0,t1;
t0 = omp_get_wtime();
compute_density_3d_naive_omp_simd_tiled(N,h,lsph->x,lsph->y, // Compute the density for all particles
lsph->z,lsph->nu,lsph->rho);
t1 = omp_get_wtime();
// ------------------------------------------------------ //
times[COMPUTE_BLOCKS*run+0] = t1-t0; // Only one component to measure time
return 0;
}
/*
* Function compute_density_3d_naive_omp_simd_tiled:
* Computes the SPH density from the particles implementing a strip mine and exchange
* strategy to re-use data in cache over the direct loop. It executes calculations
* in parallel for the outer-most loop using openMP and SIMD in inner-most loop,
* though SIMD only for limited success.
*
* Reference: https://en.wikipedia.org/wiki/Loop_nest_optimization
*
* Arguments:
* N <int> : Number of SPH particles to be used in the run
* h <double> : Smoothing Length for the Smoothing Kernel w_bspline
* x <double*> : X position array of the particles
* y <double*> : Y position array of the particles
* z <double*> : Z position array of the particles
* nu <double*> : nu position array of the particles
* Returns:
* 0 : error code returned
* rho <double> : rho position array
*/
int compute_density_3d_naive_omp_simd_tiled(int N,double h,
double* restrict x, double* restrict y,
double* restrict z, double* restrict nu,
double* restrict rho){
const double inv_h = 1./h; // Pre-invert the smoothing distance
const double kernel_constant = w_bspline_3d_constant(h); // Pre-compute the 3d normalization constant
const int64_t STRIP = 500; // Setting the size of the strip or block
memset(rho,(int)0,N*sizeof(double)); // Pre-initialize the density to zero
#pragma omp parallel for // Run the iteration in i in parallel
for(int64_t i=0;i<N;i+=STRIP){ // Breaking up the i and j iterations in blocks
for(int64_t j=0;j<N;j+=STRIP){ // of size STRIP to do data re-use and cache blocking
for(int64_t ii=i;ii < ((i+STRIP<N)?(i+STRIP):N); ii+=1){ // Iterate a block over ii
double xii = x[ii]; // Load the position in X for ii
double yii = y[ii]; // Load the position in Y for ii
double zii = z[ii]; // Load the position in Z for ii
double rhoii = 0.0; // Initialize partial density ii to zero
#pragma omp simd // Hint at the compiler to vectorize this loop
for(int64_t jj=j;jj < ((j+STRIP<N)?(j+STRIP):N); jj+=1 ){ // and iterate over the jj part of the block
double q = 0.; // initialize the distance variable
double xij = xii-x[jj]; // Load and subtract jj particle's X position component
double yij = yii-y[jj]; // Load and subtract jj particle's Y position component
double zij = zii-z[jj]; // Load and subtract jj particle's Z position component
q += xij*xij; // Add the jj contribution to the ii distance in X
q += yij*yij; // Add the jj contribution to the ii distance in Y
q += zij*zij; // Add the jj contribution to the ii distance in Z
q = sqrt(q)*inv_h; // Sqrt and normalizing the distance by the smoothing lengh
rhoii += nu[jj]*w_bspline_3d_simd(q); // Add up the contribution from the jj particle
} // to the intermediary density and then
rho[ii] += kernel_constant*rhoii; // add the intermediary density to the full density
}
}
}
return 0;
}
/*
* Function w_bspline_3d_constant:
* Returns the 3d normalization constant for the cubic b-spline SPH smoothing kernel
*
* Arguments:
* h <double> : Smoothing Length for the Smoothing Kernel w_bspline
* Returns:
* 3d bspline normalization density <double>
*/
double w_bspline_3d_constant(double h){
return 3./(2.*M_PI*h*h*h); // 3d normalization value for the b-spline kernel
}
/*
* Function w_bspline_3d_simd:
* Returns the un-normalized value of the cubic b-spline SPH smoothing kernel
*
* Arguments:
* q <double> : Distance between particles normalized by the smoothing length h
* Returns:
* wq <double> : Unnormalized value of the kernel
*
* Observation:
* Why not else if(q<2.)?
* Because if you use "else if", the compiler refuses to vectorize,
* This results in a large slowdown, as of 2.5x slower for example_04
*/
#pragma omp declare simd
double w_bspline_3d_simd(double q){ // Use as input the normalized distance
double wq=0;
double wq1 = (0.6666666666666666 - q*q + 0.5*q*q*q); // The first polynomial of the spline
double wq2 = 0.16666666666666666*(2.-q)*(2.-q)*(2.-q); // The second polynomial of the spline
if(q<2.) // If the distance is below 2
wq = wq2; // Use the 2nd polynomial for the spline
if(q<1.) // If the distance is below 1
wq = wq1; // Use the 1st polynomial for the spline
return wq; // return which ever value corresponds to the distance
}
|
GB_binop__min_int32.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__min_int32)
// A.*B function (eWiseMult): GB (_AemultB_08__min_int32)
// A.*B function (eWiseMult): GB (_AemultB_02__min_int32)
// A.*B function (eWiseMult): GB (_AemultB_04__min_int32)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__min_int32)
// A*D function (colscale): GB (_AxD__min_int32)
// D*A function (rowscale): GB (_DxB__min_int32)
// C+=B function (dense accum): GB (_Cdense_accumB__min_int32)
// C+=b function (dense accum): GB (_Cdense_accumb__min_int32)
// C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__min_int32)
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__min_int32)
// C=scalar+B GB (_bind1st__min_int32)
// C=scalar+B' GB (_bind1st_tran__min_int32)
// C=A+scalar GB (_bind2nd__min_int32)
// C=A'+scalar GB (_bind2nd_tran__min_int32)
// C type: int32_t
// A type: int32_t
// A pattern? 0
// B type: int32_t
// B pattern? 0
// BinaryOp: cij = GB_IMIN (aij, bij)
#define GB_ATYPE \
int32_t
#define GB_BTYPE \
int32_t
#define GB_CTYPE \
int32_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) \
int32_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) \
int32_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) \
int32_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_IMIN (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_MIN || GxB_NO_INT32 || GxB_NO_MIN_INT32)
//------------------------------------------------------------------------------
// 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__min_int32)
(
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__min_int32)
(
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__min_int32)
(
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__min_int32)
(
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 int32_t
int32_t bwork = (*((int32_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__min_int32)
(
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
int32_t *restrict Cx = (int32_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__min_int32)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t *restrict Cx = (int32_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__min_int32)
(
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) ;
int32_t alpha_scalar ;
int32_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((int32_t *) alpha_scalar_in)) ;
beta_scalar = (*((int32_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__min_int32)
(
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__min_int32)
(
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__min_int32)
(
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__min_int32)
(
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__min_int32)
(
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
int32_t *Cx = (int32_t *) Cx_output ;
int32_t x = (*((int32_t *) x_input)) ;
int32_t *Bx = (int32_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 ;
int32_t bij = GBX (Bx, p, false) ;
Cx [p] = GB_IMIN (x, bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__min_int32)
(
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 ;
int32_t *Cx = (int32_t *) Cx_output ;
int32_t *Ax = (int32_t *) Ax_input ;
int32_t y = (*((int32_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
int32_t aij = GBX (Ax, p, false) ;
Cx [p] = GB_IMIN (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) \
{ \
int32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_IMIN (x, aij) ; \
}
GrB_Info GB (_bind1st_tran__min_int32)
(
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 \
int32_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t x = (*((const int32_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
int32_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) \
{ \
int32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_IMIN (aij, y) ; \
}
GrB_Info GB (_bind2nd_tran__min_int32)
(
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
int32_t y = (*((const int32_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_AxB_saxpy3_cumsum.c
|
//------------------------------------------------------------------------------
// GB_AxB_saxpy3_cumsum: finalize nnz(C(:,j)) and find cumulative sum of Cp
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// phase3: fine tasks finalize their computation nnz(C(:,j))
// phase4: cumulative sum of C->p
#include "GB_AxB_saxpy3.h"
void GB_AxB_saxpy3_cumsum
(
GrB_Matrix C, // finalize C->p
GB_saxpy3task_struct *TaskList, // list of tasks, and workspace
int nfine, // number of fine tasks
double chunk, // chunk size
int nthreads // number of threads
)
{
//--------------------------------------------------------------------------
// get C
//--------------------------------------------------------------------------
ASSERT (!GB_IS_BITMAP (C)) ;
ASSERT (!GB_IS_FULL (C)) ;
int64_t *GB_RESTRICT Cp = C->p ;
const int64_t cvlen = C->vlen ;
const int64_t cnvec = C->nvec ;
//==========================================================================
// phase3: count nnz(C(:,j)) for fine tasks
//==========================================================================
int taskid ;
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1)
for (taskid = 0 ; taskid < nfine ; taskid++)
{
//----------------------------------------------------------------------
// get the task descriptor
//----------------------------------------------------------------------
// int64_t kk = TaskList [taskid].vector ;
int64_t hash_size = TaskList [taskid].hsize ;
bool use_Gustavson = (hash_size == cvlen) ;
int team_size = TaskList [taskid].team_size ;
int leader = TaskList [taskid].leader ;
int my_teamid = taskid - leader ;
int64_t my_cjnz = 0 ;
if (use_Gustavson)
{
//------------------------------------------------------------------
// phase3: fine Gustavson task, C=A*B, C<M>=A*B, or C<!M>=A*B
//------------------------------------------------------------------
// Hf [i] == 2 if C(i,j) is an entry in C(:,j)
int8_t *GB_RESTRICT Hf = (int8_t *GB_RESTRICT) TaskList [taskid].Hf;
int64_t istart, iend ;
GB_PARTITION (istart, iend, cvlen, my_teamid, team_size) ;
for (int64_t i = istart ; i < iend ; i++)
{
if (Hf [i] == 2)
{
my_cjnz++ ;
}
}
}
else
{
//------------------------------------------------------------------
// phase3: fine hash task, C=A*B, C<M>=A*B, or C<!M>=A*B
//------------------------------------------------------------------
// (Hf [hash] & 3) == 2 if C(i,j) is an entry in C(:,j),
// and the index i of the entry is (Hf [hash] >> 2) - 1.
int64_t *GB_RESTRICT
Hf = (int64_t *GB_RESTRICT) TaskList [taskid].Hf ;
int64_t mystart, myend ;
GB_PARTITION (mystart, myend, hash_size, my_teamid, team_size) ;
for (int64_t hash = mystart ; hash < myend ; hash++)
{
if ((Hf [hash] & 3) == 2)
{
my_cjnz++ ;
}
}
}
TaskList [taskid].my_cjnz = my_cjnz ; // count my nnz(C(:,j))
}
//==========================================================================
// phase4: compute Cp with cumulative sum
//==========================================================================
//--------------------------------------------------------------------------
// sum nnz (C (:,j)) for fine tasks
//--------------------------------------------------------------------------
// TaskList [taskid].my_cjnz is the # of unique entries found in C(:,j) by
// that task. Sum these terms to compute total # of entries in C(:,j).
for (taskid = 0 ; taskid < nfine ; taskid++)
{
int64_t kk = TaskList [taskid].vector ;
Cp [kk] = 0 ;
}
for (taskid = 0 ; taskid < nfine ; taskid++)
{
int64_t kk = TaskList [taskid].vector ;
int64_t my_cjnz = TaskList [taskid].my_cjnz ;
Cp [kk] += my_cjnz ;
ASSERT (my_cjnz <= cvlen) ;
}
//--------------------------------------------------------------------------
// cumulative sum for Cp (fine and coarse tasks)
//--------------------------------------------------------------------------
// Cp [kk] is now nnz (C (:,j)), for all vectors j, whether computed by
// fine tasks or coarse tasks, and where j == GBH (Bh, kk)
int nth = GB_nthreads (cnvec, chunk, nthreads) ;
GB_cumsum (Cp, cnvec, &(C->nvec_nonempty), nth) ;
//--------------------------------------------------------------------------
// cumulative sum of nnz (C (:,j)) for each team of fine tasks
//--------------------------------------------------------------------------
int64_t cjnz_sum = 0 ;
for (taskid = 0 ; taskid < nfine ; taskid++)
{
if (taskid == TaskList [taskid].leader)
{
cjnz_sum = 0 ;
// also find the max (C (:,j)) for any fine hash tasks
int64_t hash_size = TaskList [taskid].hsize ;
bool use_Gustavson = (hash_size == cvlen) ;
if (!use_Gustavson)
{
int64_t kk = TaskList [taskid].vector ;
int64_t cjnz = Cp [kk+1] - Cp [kk] ;
}
}
int64_t my_cjnz = TaskList [taskid].my_cjnz ;
TaskList [taskid].my_cjnz = cjnz_sum ;
cjnz_sum += my_cjnz ;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.