source
stringlengths
3
92
c
stringlengths
26
2.25M
lis_matrix_rco.c
/* Copyright (C) 2002-2012 The SSI Project. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the project 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 SCALABLE SOFTWARE INFRASTRUCTURE PROJECT ``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 SCALABLE SOFTWARE INFRASTRUCTURE PROJECT 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. */ #ifdef HAVE_CONFIG_H #include "lis_config.h" #else #ifdef HAVE_CONFIG_WIN32_H #include "lis_config_win32.h" #endif #endif #include <stdio.h> #include <stdlib.h> #ifdef HAVE_MALLOC_H #include <malloc.h> #endif #include <string.h> #include <stdarg.h> #include <math.h> #ifdef _OPENMP #include <omp.h> #endif #ifdef USE_MPI #include <mpi.h> #endif #include "lislib.h" /************************************************ * lis_matrix_malloc * lis_matrix_realloc ************************************************/ #undef __FUNC__ #define __FUNC__ "lis_matrix_create_rco" LIS_INT lis_matrix_create_rco(LIS_INT local_n, LIS_INT global_n, LIS_Comm comm, LIS_INT annz, LIS_INT *nnz, LIS_MATRIX *Amat) { LIS_INT nprocs,my_rank; LIS_INT is,ie,err; LIS_INT i,k; LIS_INT *ranges; LIS_DEBUG_FUNC_IN; *Amat = NULL; if( global_n>0 && local_n>global_n ) { LIS_SETERR2(LIS_ERR_ILL_ARG,"local n(=%d) is larger than global n(=%d)\n",local_n,global_n); return LIS_ERR_ILL_ARG; } if( local_n<0 || global_n<0 ) { LIS_SETERR2(LIS_ERR_ILL_ARG,"local n(=%d) or global n(=%d) are less than 0\n",local_n,global_n); return LIS_ERR_ILL_ARG; } if( local_n==0 && global_n==0 ) { LIS_SETERR2(LIS_ERR_ILL_ARG,"local n(=%d) and global n(=%d) are 0\n",local_n,global_n); return LIS_ERR_ILL_ARG; } *Amat = (LIS_MATRIX)lis_malloc( sizeof(struct LIS_MATRIX_STRUCT),"lis_matrix_create_rco::Amat" ); if( NULL==*Amat ) { LIS_SETERR_MEM(sizeof(struct LIS_MATRIX_STRUCT)); return LIS_OUT_OF_MEMORY; } lis_matrix_init(Amat); err = lis_ranges_create(comm,&local_n,&global_n,&ranges,&is,&ie,&nprocs,&my_rank); if( err ) { lis_matrix_destroy(*Amat); *Amat = NULL; return err; } (*Amat)->ranges = ranges; (*Amat)->w_nnz = (LIS_INT *)lis_malloc(local_n*sizeof(LIS_INT),"lis_matrix_create_rco::Amat->w_nnz"); if( (*Amat)->w_nnz==NULL ) { LIS_SETERR_MEM(local_n*sizeof(LIS_INT)); return LIS_OUT_OF_MEMORY; } if( nnz==NULL ) { (*Amat)->w_annz = annz; for(k=0;k<local_n;k++) (*Amat)->w_nnz[k] = (*Amat)->w_annz; } else { i = 0; for(k=0;k<local_n;k++) { (*Amat)->w_nnz[k] = nnz[k]; i += nnz[k]; } (*Amat)->w_annz = i/local_n; } err = lis_matrix_malloc_rco(local_n,(*Amat)->w_nnz,&(*Amat)->w_row,&(*Amat)->w_index,&(*Amat)->w_value); if( err ) { lis_free((*Amat)->w_nnz); return err; } (*Amat)->status = LIS_MATRIX_ASSEMBLING; (*Amat)->n = local_n; (*Amat)->gn = global_n; (*Amat)->np = local_n; (*Amat)->comm = comm; (*Amat)->my_rank = my_rank; (*Amat)->nprocs = nprocs; (*Amat)->is = is; (*Amat)->ie = ie; LIS_DEBUG_FUNC_OUT; return LIS_SUCCESS; } #undef __FUNC__ #define __FUNC__ "lis_matrix_malloc_rco" LIS_INT lis_matrix_malloc_rco(LIS_INT n, LIS_INT nnz[], LIS_INT **row, LIS_INT ***index, LIS_SCALAR ***value) { LIS_INT i,j; LIS_INT *w_row,**w_index; LIS_SCALAR **w_value; LIS_DEBUG_FUNC_IN; w_row = NULL; w_index = NULL; w_value = NULL; w_row = (LIS_INT *)lis_malloc( n*sizeof(LIS_INT),"lis_matrix_malloc_rco::w_row" ); if( w_row==NULL ) { LIS_SETERR_MEM(n*sizeof(LIS_INT)); return LIS_OUT_OF_MEMORY; } w_index = (LIS_INT **)lis_malloc( n*sizeof(LIS_INT *),"lis_matrix_malloc_rco::w_index" ); if( w_index==NULL ) { LIS_SETERR_MEM(n*sizeof(LIS_INT *)); lis_free2(3,w_row,w_index,w_value); return LIS_OUT_OF_MEMORY; } w_value = (LIS_SCALAR **)lis_malloc( n*sizeof(LIS_SCALAR *),"lis_matrix_malloc_rco::w_value" ); if( w_value==NULL ) { LIS_SETERR_MEM(n*sizeof(LIS_SCALAR *)); lis_free2(3,w_row,w_index,w_value); return LIS_OUT_OF_MEMORY; } if( nnz!=NULL ) { for(i=0;i<n;i++) { w_index[i] = NULL; w_value[i] = NULL; if( nnz[i]==0 ) continue; w_index[i] = (LIS_INT *)lis_malloc( nnz[i]*sizeof(LIS_INT),"lis_matrix_malloc_rco::w_index[i]" ); if( w_index[i]==NULL ) { LIS_SETERR_MEM(nnz[i]*sizeof(LIS_INT)); break; } w_value[i] = (LIS_SCALAR *)lis_malloc( nnz[i]*sizeof(LIS_SCALAR),"lis_matrix_malloc_rco::w_value[i]" ); if( w_value[i]==NULL ) { LIS_SETERR_MEM(nnz[i]*sizeof(LIS_SCALAR)); break; } } if(i<n) { for(j=0;j<i;j++) { if( w_index[i] ) lis_free(w_index[i]); if( w_value[i] ) lis_free(w_value[i]); } lis_free2(3,w_row,w_index,w_value); return LIS_OUT_OF_MEMORY; } } #ifdef _OPENMP #pragma omp parallel for private(i) #endif for(i=0;i<n;i++) w_row[i] = 0; *row = w_row; *index = w_index; *value = w_value; LIS_DEBUG_FUNC_OUT; return LIS_SUCCESS; } #undef __FUNC__ #define __FUNC__ "lis_matrix_realloc_rco" LIS_INT lis_matrix_realloc_rco(LIS_INT row, LIS_INT nnz, LIS_INT ***index, LIS_SCALAR ***value) { LIS_INT **w_index; LIS_SCALAR **w_value; LIS_DEBUG_FUNC_IN; w_index = *index; w_value = *value; w_index[row] = (LIS_INT *)lis_realloc(w_index[row],nnz*sizeof(LIS_INT)); if( w_index[row]==NULL ) { LIS_SETERR_MEM(nnz*sizeof(LIS_INT)); return LIS_OUT_OF_MEMORY; } w_value[row] = (LIS_SCALAR *)lis_realloc(w_value[row],nnz*sizeof(LIS_SCALAR)); if( w_value[row]==NULL ) { LIS_SETERR_MEM(nnz*sizeof(LIS_SCALAR)); return LIS_OUT_OF_MEMORY; } *index = w_index; *value = w_value; LIS_DEBUG_FUNC_OUT; return LIS_SUCCESS; } #undef __FUNC__ #define __FUNC__ "lis_matrix_convert_rco2crs" LIS_INT lis_matrix_convert_rco2crs(LIS_MATRIX Ain, LIS_MATRIX Aout) { LIS_INT i,j,k,n,nnz,err; LIS_INT *ptr,*index; LIS_SCALAR *value; LIS_DEBUG_FUNC_IN; ptr = NULL; index = NULL; value = NULL; n = Ain->n; nnz = 0; #ifdef _OPENMP #pragma omp parallel for reduction(+:nnz) private(i) #endif for(i=0;i<n;i++) { nnz += Ain->w_row[i]; } err = lis_matrix_malloc_crs(n,nnz,&ptr,&index,&value); if( err ) { return err; } #ifdef _NUMA #pragma omp parallel for private(i) for(i=0;i<n+1;i++) ptr[i] = 0; #else ptr[0] = 0; #endif for(i=0;i<n;i++) { ptr[i+1] = ptr[i] + Ain->w_row[i]; } #ifdef _OPENMP #pragma omp parallel for private(i,j,k) #endif for(i=0;i<n;i++) { k = ptr[i]; for(j=0;j<Ain->w_row[i];j++) { index[k] = Ain->w_index[i][j]; value[k] = Ain->w_value[i][j]; k++; } } err = lis_matrix_set_crs(nnz,ptr,index,value,Aout); if( err ) { lis_free2(3,ptr,index,value); return err; } err = lis_matrix_assemble(Aout); if( err ) { lis_matrix_storage_destroy(Aout); return err; } LIS_DEBUG_FUNC_OUT; return LIS_SUCCESS; } #undef __FUNC__ #define __FUNC__ "lis_matrix_convert_rco2bsr" LIS_INT lis_matrix_convert_rco2bsr(LIS_MATRIX Ain, LIS_MATRIX Aout) { LIS_INT i,j,k,n,gn,nnz,bnnz,nr,nc,bnr,bnc,err; LIS_INT ii,jj,kk,bj,jpos,ij,kv,bi; LIS_INT *iw,*iw2; LIS_INT *bptr,*bindex; LIS_SCALAR *value; LIS_Comm comm; LIS_DEBUG_FUNC_IN; bnr = Ain->conv_bnr; bnc = Ain->conv_bnc; n = Ain->n; gn = Ain->gn; comm = Ain->comm; nr = 1 + (n-1)/bnr; nc = 1 + (gn-1)/bnc; bptr = NULL; bindex = NULL; value = NULL; iw = NULL; iw2 = NULL; bptr = (LIS_INT *)lis_malloc( (nr+1)*sizeof(LIS_INT),"lis_matrix_convert_rco2bsr::bptr" ); if( bptr==NULL ) { LIS_SETERR_MEM((nr+1)*sizeof(LIS_INT)); lis_free2(5,bptr,bindex,value,iw,iw2); return LIS_OUT_OF_MEMORY; } #ifdef _OPENMP #pragma omp parallel private(i,k,ii,j,bj,kk,ij,jj,iw,iw2,kv,jpos) #endif { iw = (LIS_INT *)lis_malloc( nc*sizeof(LIS_INT),"lis_matrix_convert_rco2bsr::iw" ); iw2 = (LIS_INT *)lis_malloc( nc*sizeof(LIS_INT),"lis_matrix_convert_rco2bsr::iw2" ); memset(iw,0,nc*sizeof(LIS_INT)); #ifdef _OPENMP #pragma omp for #endif for(i=0;i<nr;i++) { k = 0; kk = bnr*i; jj = 0; for(ii=0;ii+kk<n&&ii<bnr;ii++) { for(j=0;j<Ain->w_row[kk+ii];j++) { bj = Ain->w_index[kk+ii][j]/bnc; jpos = iw[bj]; if( jpos==0 ) { iw[bj] = 1; iw2[jj] = bj; jj++; } } } for(bj=0;bj<jj;bj++) { k++; ii = iw2[bj]; iw[ii]=0; } bptr[i+1] = k; } lis_free(iw); lis_free(iw2); } bptr[0] = 0; for(i=0;i<nr;i++) { bptr[i+1] += bptr[i]; } bnnz = bptr[nr]; nnz = bnnz*bnr*bnc; bindex = (LIS_INT *)lis_malloc( bnnz*sizeof(LIS_INT),"lis_matrix_convert_rco2bsr::bindex" ); if( bindex==NULL ) { LIS_SETERR_MEM((nr+1)*sizeof(LIS_INT)); lis_free2(3,bptr,bindex,value); return LIS_OUT_OF_MEMORY; } value = (LIS_SCALAR *)lis_malloc( nnz*sizeof(LIS_SCALAR),"lis_matrix_convert_rco2bsr::value" ); if( value==NULL ) { LIS_SETERR_MEM(nnz*sizeof(LIS_SCALAR)); lis_free2(3,bptr,bindex,value); return LIS_OUT_OF_MEMORY; } /* convert bsr */ #ifdef _OPENMP #pragma omp parallel private(bi,i,ii,k,j,bj,jpos,kv,kk,ij,jj,iw) #endif { iw = (LIS_INT *)lis_malloc( nc*sizeof(LIS_INT),"lis_matrix_convert_rco2bsr::iw" ); memset(iw,0,nc*sizeof(LIS_INT)); #ifdef _OPENMP #pragma omp for #endif for(bi=0;bi<nr;bi++) { i = bi*bnr; ii = 0; kk = bptr[bi]; while( i+ii<n && ii<=bnr-1 ) { for( k=0;k<Ain->w_row[i+ii];k++) { j = Ain->w_index[i+ii][k]; bj = j/bnc; j = j%bnc; jpos = iw[bj]; if( jpos==0 ) { kv = kk * bnr * bnc; iw[bj] = kv+1; bindex[kk] = bj; for(jj=0;jj<bnr*bnc;jj++) value[kv+jj] = 0.0; ij = j*bnr + ii; value[kv+ij] = Ain->w_value[i+ii][k]; kk = kk+1; } else { ij = j*bnr + ii; value[jpos+ij-1] = Ain->w_value[i+ii][k]; } } ii = ii+1; } for(j=bptr[bi];j<bptr[bi+1];j++) { iw[bindex[j]] = 0; } } lis_free(iw); } err = lis_matrix_set_bsr(bnr,bnc,bnnz,bptr,bindex,value,Aout); if( err ) { lis_free2(3,bptr,bindex,value); return err; } err = lis_matrix_assemble(Aout); if( err ) { lis_matrix_storage_destroy(Aout); return err; } LIS_DEBUG_FUNC_OUT; return LIS_SUCCESS; } #undef __FUNC__ #define __FUNC__ "lis_matrix_convert_rco2ccs" LIS_INT lis_matrix_convert_rco2ccs(LIS_MATRIX Ain, LIS_MATRIX Aout) { LIS_INT i,j,k,l,n,nnz,err; LIS_INT *ptr,*index,*iw; LIS_SCALAR *value; LIS_DEBUG_FUNC_IN; ptr = NULL; index = NULL; value = NULL; iw = NULL; n = Ain->n; iw = (LIS_INT *)lis_malloc(n*sizeof(LIS_INT),"lis_matrix_convert_rco2ccs::iw"); if( iw==NULL ) { LIS_SETERR_MEM(n*sizeof(LIS_INT)); lis_free2(4,ptr,index,value,iw); return LIS_OUT_OF_MEMORY; } ptr = (LIS_INT *)lis_malloc((n+1)*sizeof(LIS_INT),"lis_matrix_convert_rco2ccs::ptr"); if( ptr==NULL ) { LIS_SETERR_MEM((n+1)*sizeof(LIS_INT)); lis_free2(4,ptr,index,value,iw); return LIS_OUT_OF_MEMORY; } for(i=0;i<n;i++) iw[i] = 0; for(i=0;i<n;i++) { for(j=0;j<Ain->w_row[i];j++) { iw[Ain->w_index[i][j]]++; } } ptr[0] = 0; for(i=0;i<n;i++) { ptr[i+1] = ptr[i] + iw[i]; iw[i] = ptr[i]; } nnz = ptr[n]; index = (LIS_INT *)lis_malloc( nnz*sizeof(LIS_INT),"lis_matrix_convert_rco2ccs::index" ); if( index==NULL ) { LIS_SETERR_MEM(nnz*sizeof(LIS_INT)); lis_free2(4,ptr,index,value,iw); return LIS_OUT_OF_MEMORY; } value = (LIS_SCALAR *)lis_malloc( nnz*sizeof(LIS_SCALAR),"lis_matrix_convert_rco2ccs::value" ); if( value==NULL ) { LIS_SETERR_MEM(nnz*sizeof(LIS_SCALAR)); lis_free2(4,ptr,index,value,iw); return LIS_OUT_OF_MEMORY; } for(i=0;i<n;i++) { for(j=0;j<Ain->w_row[i];j++) { k = Ain->w_index[i][j]; l = iw[k]; value[l] = Ain->w_value[i][j]; index[l] = i; iw[k]++; } } err = lis_matrix_set_ccs(nnz,ptr,index,value,Aout); if( err ) { lis_free2(4,ptr,index,value,iw); return err; } err = lis_matrix_assemble(Aout); if( err ) { lis_matrix_storage_destroy(Aout); return err; } lis_free(iw); LIS_DEBUG_FUNC_OUT; return LIS_SUCCESS; } /* #undef __FUNC__ #define __FUNC__ "lis_matrix_malloc_brco" LIS_INT lis_matrix_malloc_brco(LIS_INT n, LIS_INT **row, LIS_INT ***index, LIS_SCALAR ***value) { LIS_INT i,j; LIS_INT *w_row,**w_index; LIS_SCALAR **w_value; LIS_DEBUG_FUNC_IN; w_row = NULL; w_index = NULL; w_value = NULL; w_row = (LIS_INT *)lis_malloc( n*sizeof(LIS_INT),"lis_matrix_malloc_brco::w_row" ); if( w_row==NULL ) { LIS_SETERR_MEM(n*sizeof(LIS_INT)); return LIS_OUT_OF_MEMORY; } w_index = (LIS_INT **)lis_malloc( n*sizeof(LIS_INT *),"lis_matrix_malloc_brco::w_index" ); if( w_index==NULL ) { LIS_SETERR_MEM(n*sizeof(LIS_INT *)); lis_free2(3,w_row,w_index,w_value); return LIS_OUT_OF_MEMORY; } w_value = (LIS_SCALAR **)lis_malloc( n*sizeof(LIS_SCALAR *),"lis_matrix_malloc_brco::w_value" ); if( w_value==NULL ) { LIS_SETERR_MEM(n*sizeof(LIS_SCALAR *)); lis_free2(3,w_row,w_index,w_value); return LIS_OUT_OF_MEMORY; } #pragma omp parallel for private(i) for(i=0;i<n;i++) { w_row[i] = 0; w_index[i] = NULL; } *row = w_row; *index = w_index; *value = w_value; LIS_DEBUG_FUNC_OUT; return LIS_SUCCESS; } #undef __FUNC__ #define __FUNC__ "lis_matrix_malloc_vrco" LIS_INT lis_matrix_malloc_vrco(LIS_INT n, LIS_INT **nnz, LIS_INT **row, LIS_INT ***index, LIS_SCALAR ****value) { LIS_INT i,j; LIS_INT *w_nnz, *w_row, **w_index; LIS_SCALAR ***w_value; LIS_DEBUG_FUNC_IN; w_nnz = NULL; w_row = NULL; w_index = NULL; w_value = NULL; w_nnz = (LIS_INT *)lis_malloc( n*sizeof(LIS_INT),"lis_matrix_malloc_vrco::w_ptr" ); if( w_nnz==NULL ) { LIS_SETERR_MEM(n*sizeof(LIS_INT)); return LIS_OUT_OF_MEMORY; } w_row = (LIS_INT *)lis_malloc( (n+1)*sizeof(LIS_INT),"lis_matrix_malloc_vrco::w_row" ); if( w_row==NULL ) { LIS_SETERR_MEM((n+1)*sizeof(LIS_INT)); return LIS_OUT_OF_MEMORY; } w_index = (LIS_INT **)lis_malloc( n*sizeof(LIS_INT *),"lis_matrix_malloc_vrco::w_index" ); if( w_index==NULL ) { LIS_SETERR_MEM(n*sizeof(LIS_INT *)); lis_free2(3,w_row,w_index,w_value); return LIS_OUT_OF_MEMORY; } w_value = (LIS_SCALAR ***)lis_malloc( n*sizeof(LIS_SCALAR **),"lis_matrix_malloc_vrco::w_value" ); if( w_value==NULL ) { LIS_SETERR_MEM(n*sizeof(LIS_SCALAR **)); lis_free2(3,w_row,w_index,w_value); return LIS_OUT_OF_MEMORY; } #pragma omp parallel for private(i) for(i=0;i<n;i++) { w_nnz[i] = 0; w_index[i] = NULL; } *nnz = w_nnz; *row = w_row; *index = w_index; *value = w_value; LIS_DEBUG_FUNC_OUT; return LIS_SUCCESS; } */
GB_emult_phase0.c
//------------------------------------------------------------------------------ // GB_emult_phase0: find vectors of C to compute for C=A.*B or C<M>=A.*B //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // The eWise multiply of two matrices, C=A.*B, C<M>=A.*B, or C<!M>=A.*B starts // with this phase, which determines which vectors of C need to be computed. // On input, A and B are the two matrices being ewise multiplied, and M is the // optional mask matrix. If present, it is not complemented. // The M, A, and B matrices are sparse or hypersparse. C will be sparse // (if Ch is returned NULL) or hypersparse (if Ch is returned non-NULL). // Ch: the vectors to compute in C. Not allocated, but equal to either // A->h, B->h, or M->h, or NULL if C is not hypersparse. // C_to_A: if A is hypersparse, and Ch is not A->h, then C_to_A [k] = kA // if the kth vector j = Ch [k] is equal to Ah [kA]. If j does not appear // in A, then C_to_A [k] = -1. Otherwise, C_to_A is returned as NULL. // C is always hypersparse in this case. // C_to_B: if B is hypersparse, and Ch is not B->h, then C_to_B [k] = kB // if the kth vector j = Ch [k] is equal to Bh [kB]. If j does not appear // in B, then C_to_B [k] = -1. Otherwise, C_to_B is returned as NULL. // C is always hypersparse in this case. // C_to_M: if M is hypersparse, and Ch is not M->h, then C_to_M [k] = kM // if the kth vector j = GBH (Ch, k) is equal to Mh [kM]. // If j does not appear in M, then C_to_M [k] = -1. Otherwise, C_to_M is // returned as NULL. C is always hypersparse in this case. // FUTURE:: exploit A==M, B==M, and A==B aliases #include "GB_emult.h" GrB_Info GB_emult_phase0 // find vectors in C for C=A.*B or C<M>=A.*B ( int64_t *p_Cnvec, // # of vectors to compute in C const int64_t *GB_RESTRICT *Ch_handle, // Ch is M->h, A->h, B->h, or NULL int64_t *GB_RESTRICT *C_to_M_handle, // C_to_M: size Cnvec, or NULL int64_t *GB_RESTRICT *C_to_A_handle, // C_to_A: size Cnvec, or NULL int64_t *GB_RESTRICT *C_to_B_handle, // C_to_B: size Cnvec, or NULL int *C_sparsity, // sparsity structure of C // original input: const GrB_Matrix M, // optional mask, may be NULL const GrB_Matrix A, const GrB_Matrix B, GB_Context Context ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- // M, A, and B can be jumbled for this phase, but not phase1 or phase2 ASSERT (p_Cnvec != NULL) ; ASSERT (Ch_handle != NULL) ; ASSERT (C_to_A_handle != NULL) ; ASSERT (C_to_B_handle != NULL) ; ASSERT_MATRIX_OK_OR_NULL (M, "M for emult phase0", GB0) ; ASSERT (!GB_ZOMBIES (M)) ; ASSERT (GB_JUMBLED_OK (M)) ; // pattern not accessed ASSERT (!GB_PENDING (M)) ; ASSERT_MATRIX_OK (A, "A for emult phase0", GB0) ; ASSERT (!GB_ZOMBIES (A)) ; ASSERT (GB_JUMBLED_OK (B)) ; // pattern not accessed ASSERT (!GB_PENDING (A)) ; ASSERT_MATRIX_OK (B, "B for emult phase0", GB0) ; ASSERT (!GB_ZOMBIES (B)) ; ASSERT (GB_JUMBLED_OK (A)) ; // pattern not accessed ASSERT (!GB_PENDING (B)) ; ASSERT (A->vdim == B->vdim) ; ASSERT (A->vlen == B->vlen) ; ASSERT (GB_IMPLIES (M != NULL, A->vdim == M->vdim)) ; ASSERT (GB_IMPLIES (M != NULL, A->vlen == M->vlen)) ; //-------------------------------------------------------------------------- // initializations //-------------------------------------------------------------------------- (*p_Cnvec) = 0 ; (*Ch_handle) = NULL ; if (C_to_M_handle != NULL) { (*C_to_M_handle) = NULL ; } (*C_to_A_handle) = NULL ; (*C_to_B_handle) = NULL ; if ((*C_sparsity) == GxB_BITMAP || (*C_sparsity) == GxB_FULL) { // nothing to do in phase0 for C bitmap or full. C can be full only // for C=A.*B where A and B are full. C can be bitmap for C=A.*B, // C<M>=A.*B, or C<!M>=A.*B only if A, B, and M (if present) are all // bitmap or full. (*p_Cnvec) = A->vdim ; return (GrB_SUCCESS) ; } const int64_t *GB_RESTRICT Ch = NULL ; int64_t *GB_RESTRICT C_to_M = NULL ; int64_t *GB_RESTRICT C_to_A = NULL ; int64_t *GB_RESTRICT C_to_B = NULL ; //-------------------------------------------------------------------------- // get content of M, A, and B //-------------------------------------------------------------------------- int64_t n = A->vdim ; int64_t Anvec = A->nvec ; int64_t vlen = A->vlen ; const int64_t *GB_RESTRICT Ah = A->h ; bool A_is_hyper = (Ah != NULL) ; int64_t Bnvec = B->nvec ; const int64_t *GB_RESTRICT Bh = B->h ; bool B_is_hyper = (Bh != NULL) ; int64_t Mnvec = 0 ; const int64_t *GB_RESTRICT Mh = NULL ; bool M_is_hyper = false ; if (M != NULL) { Mnvec = M->nvec ; Mh = M->h ; M_is_hyper = (Mh != NULL) ; } //-------------------------------------------------------------------------- // determine how to construct the vectors of C //-------------------------------------------------------------------------- if (M != NULL) { //---------------------------------------------------------------------- // 8 cases to consider: A, B, M can each be hyper or sparse //---------------------------------------------------------------------- // Mask is present and not complemented if (A_is_hyper) { if (B_is_hyper) { if (M_is_hyper) { //---------------------------------------------------------- // (1) A hyper, B hyper, M hyper: C hyper //---------------------------------------------------------- // Ch = smaller of Mh, Bh, Ah int64_t nvec = GB_IMIN (Anvec, Bnvec) ; nvec = GB_IMIN (nvec, Mnvec) ; if (nvec == Anvec) { Ch = Ah ; } else if (nvec == Bnvec) { Ch = Bh ; } else // (nvec == Mnvec) { Ch = Mh ; } } else { //---------------------------------------------------------- // (2) A hyper, B hyper, M sparse: C hyper //---------------------------------------------------------- // Ch = smaller of Ah, Bh if (Anvec <= Bnvec) { Ch = Ah ; } else { Ch = Bh ; } } } else { if (M_is_hyper) { //---------------------------------------------------------- // (3) A hyper, B sparse, M hyper: C hyper //---------------------------------------------------------- // Ch = smaller of Mh, Ah if (Anvec <= Mnvec) { Ch = Ah ; } else { Ch = Mh ; } } else { //---------------------------------------------------------- // (4) A hyper, B sparse, M sparse: C hyper //---------------------------------------------------------- Ch = Ah ; } } } else { if (B_is_hyper) { if (M_is_hyper) { //---------------------------------------------------------- // (5) A sparse, B hyper, M hyper: C hyper //---------------------------------------------------------- // Ch = smaller of Mh, Bh if (Bnvec <= Mnvec) { Ch = Bh ; } else { Ch = Mh ; } } else { //---------------------------------------------------------- // (6) A sparse, B hyper, M sparse: C hyper //---------------------------------------------------------- Ch = Bh ; } } else { if (M_is_hyper) { //---------------------------------------------------------- // (7) A sparse, B sparse, M hyper: C hyper //---------------------------------------------------------- Ch = Mh ; } else { //---------------------------------------------------------- // (8) A sparse, B sparse, M sparse: C sparse //---------------------------------------------------------- Ch = NULL ; } } } } else { //---------------------------------------------------------------------- // 4 cases to consider: A, B can be hyper or sparse //---------------------------------------------------------------------- // Mask is not present, or present and complemented. if (A_is_hyper) { if (B_is_hyper) { //-------------------------------------------------------------- // (1) A hyper, B hyper: C hyper //-------------------------------------------------------------- // Ch = smaller of Ah, Bh if (Anvec <= Bnvec) { Ch = Ah ; } else { Ch = Bh ; } } else { //-------------------------------------------------------------- // (2) A hyper, B sparse: C hyper //-------------------------------------------------------------- Ch = Ah ; } } else { if (B_is_hyper) { //-------------------------------------------------------------- // (3) A sparse, B hyper: C hyper //-------------------------------------------------------------- Ch = Bh ; } else { //-------------------------------------------------------------- // (4) A sparse, B sparse: C sparse //-------------------------------------------------------------- Ch = NULL ; } } } //-------------------------------------------------------------------------- // find Cnvec //-------------------------------------------------------------------------- int64_t Cnvec ; if (Ch == NULL) { // C is sparse (*C_sparsity) = GxB_SPARSE ; Cnvec = n ; } else { // C is hypersparse; one of A, B, or M are hypersparse ASSERT (A_is_hyper || B_is_hyper || M_is_hyper) ; (*C_sparsity) = GxB_HYPERSPARSE ; if (Ch == Ah) { Cnvec = Anvec ; } else if (Ch == Bh) { Cnvec = Bnvec ; } else // (Ch == Mh) { Cnvec = Mnvec ; } } //-------------------------------------------------------------------------- // determine the number of threads to use //-------------------------------------------------------------------------- GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ; int nthreads = GB_nthreads (Cnvec, chunk, nthreads_max) ; //-------------------------------------------------------------------------- // construct C_to_M mapping //-------------------------------------------------------------------------- if (M_is_hyper && Ch != Mh) { // allocate C_to_M C_to_M = GB_MALLOC (Cnvec, int64_t) ; if (C_to_M == NULL) { // out of memory return (GrB_OUT_OF_MEMORY) ; } // compute C_to_M ASSERT (Ch != NULL) ; const int64_t *GB_RESTRICT Mp = M->p ; int64_t k ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (k = 0 ; k < Cnvec ; k++) { int64_t pM, pM_end, kM = 0 ; int64_t j = Ch [k] ; GB_lookup (true, Mh, Mp, vlen, &kM, Mnvec-1, j, &pM, &pM_end) ; C_to_M [k] = (pM < pM_end) ? kM : -1 ; } } //-------------------------------------------------------------------------- // construct C_to_A mapping //-------------------------------------------------------------------------- if (A_is_hyper && Ch != Ah) { // allocate C_to_A C_to_A = GB_MALLOC (Cnvec, int64_t) ; if (C_to_A == NULL) { // out of memory GB_FREE (C_to_M) ; return (GrB_OUT_OF_MEMORY) ; } // compute C_to_A ASSERT (Ch != NULL) ; const int64_t *GB_RESTRICT Ap = A->p ; int64_t k ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (k = 0 ; k < Cnvec ; k++) { int64_t pA, pA_end, kA = 0 ; int64_t j = Ch [k] ; GB_lookup (true, Ah, Ap, vlen, &kA, Anvec-1, j, &pA, &pA_end) ; C_to_A [k] = (pA < pA_end) ? kA : -1 ; } } //-------------------------------------------------------------------------- // construct C_to_B mapping //-------------------------------------------------------------------------- if (B_is_hyper && Ch != Bh) { // allocate C_to_B C_to_B = GB_MALLOC (Cnvec, int64_t) ; if (C_to_B == NULL) { // out of memory GB_FREE (C_to_M) ; GB_FREE (C_to_A) ; return (GrB_OUT_OF_MEMORY) ; } // compute C_to_B ASSERT (Ch != NULL) ; const int64_t *GB_RESTRICT Bp = B->p ; int64_t k ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (k = 0 ; k < Cnvec ; k++) { int64_t pB, pB_end, kB = 0 ; int64_t j = Ch [k] ; GB_lookup (true, Bh, Bp, vlen, &kB, Bnvec-1, j, &pB, &pB_end) ; C_to_B [k] = (pB < pB_end) ? kB : -1 ; } } //-------------------------------------------------------------------------- // return result //-------------------------------------------------------------------------- (*p_Cnvec) = Cnvec ; (*Ch_handle) = Ch ; if (C_to_M_handle != NULL) { (*C_to_M_handle) = C_to_M ; } (*C_to_A_handle) = C_to_A ; (*C_to_B_handle) = C_to_B ; //-------------------------------------------------------------------------- // The code below describes what the output contains: //-------------------------------------------------------------------------- #ifdef GB_DEBUG ASSERT (A != NULL) ; // A and B are always present ASSERT (B != NULL) ; int64_t jlast = -1 ; for (int64_t k = 0 ; k < Cnvec ; k++) { // C(:,j) is in the list, as the kth vector int64_t j ; if (Ch == NULL) { // C will be constructed as sparse j = k ; } else { // C will be constructed as hypersparse j = Ch [k] ; } // vectors j in Ch are sorted, and in the range 0:n-1 ASSERT (j >= 0 && j < n) ; ASSERT (j > jlast) ; jlast = j ; // see if A (:,j) exists if (C_to_A != NULL) { // A is hypersparse ASSERT (A_is_hyper) int64_t kA = C_to_A [k] ; ASSERT (kA >= -1 && kA < A->nvec) ; if (kA >= 0) { int64_t jA = A->h [kA] ; ASSERT (j == jA) ; } } else if (A_is_hyper) { // A is hypersparse, and Ch is a shallow copy of A->h ASSERT (Ch == A->h) ; } // see if B (:,j) exists if (C_to_B != NULL) { // B is hypersparse ASSERT (B_is_hyper) int64_t kB = C_to_B [k] ; ASSERT (kB >= -1 && kB < B->nvec) ; if (kB >= 0) { int64_t jB = B->h [kB] ; ASSERT (j == jB) ; } } else if (B_is_hyper) { // A is hypersparse, and Ch is a shallow copy of A->h ASSERT (Ch == B->h) ; } // see if M (:,j) exists if (Ch != NULL && M != NULL && Ch == M->h) { // Ch is the same as Mh ASSERT (M != NULL) ; ASSERT (M->h != NULL) ; ASSERT (Ch != NULL && M->h != NULL && Ch [k] == M->h [k]) ; ASSERT (C_to_M == NULL) ; } else if (C_to_M != NULL) { // M is present and hypersparse ASSERT (M != NULL) ; ASSERT (M->h != NULL) ; int64_t kM = C_to_M [k] ; ASSERT (kM >= -1 && kM < M->nvec) ; if (kM >= 0) { int64_t jM = M->h [kM] ; ASSERT (j == jM) ; } } else { // M is not present, or in sparse form ASSERT (M == NULL || M->h == NULL) ; } } #endif return (GrB_SUCCESS) ; }
reduction-clauseModificado2.c
#include <stdio.h> #include <stdlib.h> #ifdef _OPENMP #include <omp.h> #else #define omp_get_thread_num() 0 #endif int main(int argc, char **argv) { int i, n=20, a[n],suma=10; if(argc < 2) { fprintf(stderr,"Falta iteraciones\n"); exit(-1); } n = atoi(argv[1]); if (n>20) {n=20; printf("n=%d",n);} for (i=0; i<n; i++) a[i] = i; #pragma omp parallel { int suma_local = 0; #pragma omp for for (i=0; i<n; i++) suma_local += a[i]; #pragma omp atomic suma += suma_local; } printf("Tras 'parallel' suma=%d\n",suma); }
main.c
#include <stdio.h> #include <stdlib.h> #include <omp.h> #define NDEBUG #ifndef NDEBUG #define DEBUG(cmd) cmd; #else #define DEBUG(cmd) ; #endif #define N 100000 // size of array #define n_per_line 5 // how many numbers to print per line void init_array(double array[N]) { for (int i = 0; i < N; i++) { array[i] = i; } } void print_array(double array[N]) { for (int i = 0; i < N; i++) { printf("%.2lf ", array[i]); if (i % n_per_line == 0 && i != 0) { printf("\n"); } } } int main(int argc, char** argv) { double a[N] = {0}; // initial array double b[N] = {0}; // final array init_array(a); //printf("Initial array\n"); //print_array(a); #pragma omp parallel for schedule(static) for (int i = 0; i < N; i++) { DEBUG( int thread_id = omp_get_thread_num(); printf("[Thread %.2d] Calculate b[%d]\n", thread_id, i); ) // Let border condition to be zero if (i == 0 || i == N - 1) { b[i] = 0; } else { b[i] = (a[i - 1] * a[i] * a[i + 1]) / 3.0; } } printf("Result\n"); print_array(b); return 0; }
GiRaFFE_boundary_conditions.h
// Currently, we're using basic Cartesian boundary conditions, pending fixes by Zach. // Part P8a: Declare boundary condition FACE_UPDATE macro, // which updates a single face of the 3D grid cube // using quadratic polynomial extrapolation. // Basic extrapolation boundary conditions #define FACE_UPDATE(which_gf, i0min,i0max, i1min,i1max, i2min,i2max, FACEX0,FACEX1,FACEX2) \ for(int i2=i2min;i2<i2max;i2++) for(int i1=i1min;i1<i1max;i1++) for(int i0=i0min;i0<i0max;i0++) { \ gfs[IDX4(which_gf,i0,i1,i2)] = \ +2.0*gfs[IDX4(which_gf,i0+1*FACEX0,i1+1*FACEX1,i2+1*FACEX2)] \ -1.0*gfs[IDX4(which_gf,i0+2*FACEX0,i1+2*FACEX1,i2+2*FACEX2)]; \ } // +1.0*gfs[IDX4(which_gf,i0+3*FACEX0,i1+3*FACEX1,i2+3*FACEX2)]; \ // Basic Copy boundary conditions #define FACE_UPDATE_COPY(which_gf, i0min,i0max, i1min,i1max, i2min,i2max, FACEX0,FACEX1,FACEX2) \ for(int i2=i2min;i2<i2max;i2++) for(int i1=i1min;i1<i1max;i1++) for(int i0=i0min;i0<i0max;i0++) { \ gfs[IDX4(which_gf,i0,i1,i2)] = gfs[IDX4(which_gf,i0+1*FACEX0,i1+1*FACEX1,i2+1*FACEX2)]; \ } // Part P8b: Boundary condition driver routine: Apply BCs to all six // boundary faces of the cube, filling in the innermost // ghost zone first, and moving outward. const int MAXFACE = -1; const int NUL = +0; const int MINFACE = +1;// This macro acts differently in that it acts on an entire 3-vector of gfs, instead of 1. // which_gf_0 corresponds to the zeroth component of that vector. The if statements only // evaluate true if the velocity is directed inwards on the face in consideration. #define FACE_UPDATE_OUTFLOW(which_gf, i0min,i0max, i1min,i1max, i2min,i2max, FACEX0,FACEX1,FACEX2) \ for(int i2=i2min;i2<i2max;i2++) for(int i1=i1min;i1<i1max;i1++) for(int i0=i0min;i0<i0max;i0++) { \ aux_gfs[IDX4(which_gf,i0,i1,i2)] = \ +2.0*aux_gfs[IDX4(which_gf,i0+1*FACEX0,i1+1*FACEX1,i2+1*FACEX2)] \ -1.0*aux_gfs[IDX4(which_gf,i0+2*FACEX0,i1+2*FACEX1,i2+2*FACEX2)]; \ } /* aux_gfs[IDX4(which_gf_0+1,i0,i1,i2)] = \ +3.0*aux_gfs[IDX4(which_gf_0+1,i0+1*FACEX0,i1+1*FACEX1,i2+1*FACEX2)] \ -3.0*aux_gfs[IDX4(which_gf_0+1,i0+2*FACEX0,i1+2*FACEX1,i2+2*FACEX2)] \ +1.0*aux_gfs[IDX4(which_gf_0+1,i0+3*FACEX0,i1+3*FACEX1,i2+3*FACEX2)]; \ aux_gfs[IDX4(which_gf_0+2,i0,i1,i2)] = \ +3.0*aux_gfs[IDX4(which_gf_0+2,i0+1*FACEX0,i1+1*FACEX1,i2+1*FACEX2)] \ -3.0*aux_gfs[IDX4(which_gf_0+2,i0+2*FACEX0,i1+2*FACEX1,i2+2*FACEX2)] \ +1.0*aux_gfs[IDX4(which_gf_0+2,i0+3*FACEX0,i1+3*FACEX1,i2+3*FACEX2)]; \ if(FACEX0*aux_gfs[IDX4(which_gf_0+0,i0,i1,i2)] > 0.0) { \ aux_gfs[IDX4(which_gf_0+0,i0,i1,i2)] = 0.0; \ } \ if(FACEX1*aux_gfs[IDX4(which_gf_0+1,i0,i1,i2)] > 0.0) { \ aux_gfs[IDX4(which_gf_0+1,i0,i1,i2)] = 0.0; \ } \ if(FACEX2*aux_gfs[IDX4(which_gf_0+2,i0,i1,i2)] > 0.0) { \ aux_gfs[IDX4(which_gf_0+2,i0,i1,i2)] = 0.0; \ } \ */ void apply_bcs(const int Nxx[3],const int Nxx_plus_2NGHOSTS[3],REAL *gfs,REAL *aux_gfs) { // First, we apply extrapolation boundary conditions to AD #pragma omp parallel for for(int which_gf=0;which_gf<NUM_EVOL_GFS;which_gf++) { if(which_gf < STILDED0GF || which_gf > STILDED2GF) { int imin[3] = { NGHOSTS, NGHOSTS, NGHOSTS }; int imax[3] = { Nxx_plus_2NGHOSTS[0]-NGHOSTS, Nxx_plus_2NGHOSTS[1]-NGHOSTS, Nxx_plus_2NGHOSTS[2]-NGHOSTS }; for(int which_gz = 0; which_gz < NGHOSTS; which_gz++) { // After updating each face, adjust imin[] and imax[] // to reflect the newly-updated face extents. FACE_UPDATE(which_gf, imin[0]-1,imin[0], imin[1],imax[1], imin[2],imax[2], MINFACE,NUL,NUL); imin[0]--; FACE_UPDATE(which_gf, imax[0],imax[0]+1, imin[1],imax[1], imin[2],imax[2], MAXFACE,NUL,NUL); imax[0]++; FACE_UPDATE(which_gf, imin[0],imax[0], imin[1]-1,imin[1], imin[2],imax[2], NUL,MINFACE,NUL); imin[1]--; FACE_UPDATE(which_gf, imin[0],imax[0], imax[1],imax[1]+1, imin[2],imax[2], NUL,MAXFACE,NUL); imax[1]++; FACE_UPDATE(which_gf, imin[0],imax[0], imin[1],imax[1], imin[2]-1,imin[2], NUL,NUL,MINFACE); imin[2]--; FACE_UPDATE(which_gf, imin[0],imax[0], imin[1],imax[1], imax[2],imax[2]+1, NUL,NUL,MAXFACE); imax[2]++; } } } // Apply outflow/extrapolation boundary conditions to ValenciavU by passing VALENCIAVU0 as which_gf_0 for(int which_gf=VALENCIAVU0GF;which_gf<=VALENCIAVU2GF;which_gf++) { int imin[3] = { NGHOSTS, NGHOSTS, NGHOSTS }; int imax[3] = { Nxx_plus_2NGHOSTS[0]-NGHOSTS, Nxx_plus_2NGHOSTS[1]-NGHOSTS, Nxx_plus_2NGHOSTS[2]-NGHOSTS }; for(int which_gz = 0; which_gz < NGHOSTS; which_gz++) { FACE_UPDATE_OUTFLOW(which_gf, imin[0]-1,imin[0], imin[1],imax[1], imin[2],imax[2], MINFACE,NUL,NUL); imin[0]--; FACE_UPDATE_OUTFLOW(which_gf, imax[0],imax[0]+1, imin[1],imax[1], imin[2],imax[2], MAXFACE,NUL,NUL); imax[0]++; FACE_UPDATE_OUTFLOW(which_gf, imin[0],imax[0], imin[1]-1,imin[1], imin[2],imax[2], NUL,MINFACE,NUL); imin[1]--; FACE_UPDATE_OUTFLOW(which_gf, imin[0],imax[0], imax[1],imax[1]+1, imin[2],imax[2], NUL,MAXFACE,NUL); imax[1]++; FACE_UPDATE_OUTFLOW(which_gf, imin[0],imax[0], imin[1],imax[1], imin[2]-1,imin[2], NUL,NUL,MINFACE); imin[2]--; FACE_UPDATE_OUTFLOW(which_gf, imin[0],imax[0], imin[1],imax[1], imax[2],imax[2]+1, NUL,NUL,MAXFACE); imax[2]++; } } // Then, we apply copy boundary conditions to StildeD and psi6Phi /*#pragma omp parallel for for(int which_gf=3;which_gf<NUM_EVOL_GFS;which_gf++) { int imin[3] = { NGHOSTS, NGHOSTS, NGHOSTS }; int imax[3] = { Nxx_plus_2NGHOSTS[0]-NGHOSTS, Nxx_plus_2NGHOSTS[1]-NGHOSTS, Nxx_plus_2NGHOSTS[2]-NGHOSTS }; for(int which_gz = 0; which_gz < NGHOSTS; which_gz++) { // After updating each face, adjust imin[] and imax[] // to reflect the newly-updated face extents. FACE_UPDATE_COPY(which_gf, imin[0]-1,imin[0], imin[1],imax[1], imin[2],imax[2], MINFACE,NUL,NUL); imin[0]--; FACE_UPDATE_COPY(which_gf, imax[0],imax[0]+1, imin[1],imax[1], imin[2],imax[2], MAXFACE,NUL,NUL); imax[0]++; FACE_UPDATE_COPY(which_gf, imin[0],imax[0], imin[1]-1,imin[1], imin[2],imax[2], NUL,MINFACE,NUL); imin[1]--; FACE_UPDATE_COPY(which_gf, imin[0],imax[0], imax[1],imax[1]+1, imin[2],imax[2], NUL,MAXFACE,NUL); imax[1]++; FACE_UPDATE_COPY(which_gf, imin[0],imax[0], imin[1],imax[1], imin[2]-1,imin[2], NUL,NUL,MINFACE); imin[2]--; FACE_UPDATE_COPY(which_gf, imin[0],imax[0], imin[1],imax[1], imax[2],imax[2]+1, NUL,NUL,MAXFACE); imax[2]++; } }*/ }// A supplement to the boundary conditions for debugging. This will overwrite data with exact conditions void FACE_UPDATE_EXACT(const int Nxx[3],const int Nxx_plus_2NGHOSTS[3],REAL *xx[3], const int n, const REAL dt,REAL *out_gfs,REAL *aux_gfs, const int i0min,const int i0max, const int i1min,const int i1max, const int i2min,const int i2max, const int FACEX0,const int FACEX1,const int FACEX2) { for(int i2=i2min;i2<i2max;i2++) for(int i1=i1min;i1<i1max;i1++) for(int i0=i0min;i0<i0max;i0++) { REAL xx0 = xx[0][i0]-n*dt; REAL xx1 = xx[1][i1]; REAL xx2 = xx[2][i2]; if(xx0<=lbound) { #include "GiRaFFEfood_A_v_1D_tests_left.h" } else if (xx0<rbound) { #include "GiRaFFEfood_A_v_1D_tests_center.h" } else { #include "GiRaFFEfood_A_v_1D_tests_right.h" } out_gfs[IDX4(PSI6PHIGF, i0,i1,i2)] = 0.0; } }void apply_bcs_EXACT(const int Nxx[3],const int Nxx_plus_2NGHOSTS[3],REAL *xx[3], const int n, const REAL dt, REAL *out_gfs,REAL *aux_gfs) { int imin[3] = { NGHOSTS, NGHOSTS, NGHOSTS }; int imax[3] = { Nxx_plus_2NGHOSTS[0]-NGHOSTS, Nxx_plus_2NGHOSTS[1]-NGHOSTS, Nxx_plus_2NGHOSTS[2]-NGHOSTS }; for(int which_gz = 0; which_gz < NGHOSTS; which_gz++) { // After updating each face, adjust imin[] and imax[] // to reflect the newly-updated face extents. // Right now, we only want to update the xmin and xmax faces with the exact data. FACE_UPDATE_EXACT(Nxx,Nxx_plus_2NGHOSTS,xx,n,dt,out_gfs,aux_gfs,imin[0]-1,imin[0], imin[1],imax[1], imin[2],imax[2], MINFACE,NUL,NUL); imin[0]--; FACE_UPDATE_EXACT(Nxx,Nxx_plus_2NGHOSTS,xx,n,dt,out_gfs,aux_gfs,imax[0],imax[0]+1, imin[1],imax[1], imin[2],imax[2], MAXFACE,NUL,NUL); imax[0]++; FACE_UPDATE_EXACT(Nxx,Nxx_plus_2NGHOSTS,xx,n,dt,out_gfs,aux_gfs,imin[0],imax[0], imin[1]-1,imin[1], imin[2],imax[2], NUL,MINFACE,NUL); imin[1]--; FACE_UPDATE_EXACT(Nxx,Nxx_plus_2NGHOSTS,xx,n,dt,out_gfs,aux_gfs,imin[0],imax[0], imax[1],imax[1]+1, imin[2],imax[2], NUL,MAXFACE,NUL); imax[1]++; FACE_UPDATE_EXACT(Nxx,Nxx_plus_2NGHOSTS,xx,n,dt,out_gfs,aux_gfs,imin[0],imax[0], imin[1],imax[1], imin[2]-1,imin[2], NUL,NUL,MINFACE); imin[2]--; FACE_UPDATE_EXACT(Nxx,Nxx_plus_2NGHOSTS,xx,n,dt,out_gfs,aux_gfs,imin[0],imax[0], imin[1],imax[1], imax[2],imax[2]+1, NUL,NUL,MAXFACE); imax[2]++; } }// A supplement to the boundary conditions for debugging. This will overwrite data with exact conditions void FACE_UPDATE_EXACT_StildeD(const int Nxx[3],const int Nxx_plus_2NGHOSTS[3],REAL *xx[3], REAL *out_gfs,REAL *out_gfs_exact, const int i0min,const int i0max, const int i1min,const int i1max, const int i2min,const int i2max, const int FACEX0,const int FACEX1,const int FACEX2) { // This is currently modified to calculate more exact boundary conditions for StildeD. Rename if it works. /*for(int i2=i2min;i2<i2max;i2++) for(int i1=i1min;i1<i1max;i1++) for(int i0=i0min;i0<i0max;i0++) { #include "GiRaFFEfood_HO_Stilde.h" }*/ /*idx = IDX3(i0,i1,i2); out_gfs[IDX4pt(STILDED0GF,idx)] = out_gfs_exact[IDX4pt(STILDED0GF,idx)]; out_gfs[IDX4pt(STILDED1GF,idx)] = out_gfs_exact[IDX4pt(STILDED1GF,idx)]; out_gfs[IDX4pt(STILDED2GF,idx)] = out_gfs_exact[IDX4pt(STILDED2GF,idx)];*/ }void apply_bcs_EXACT_StildeD(const int Nxx[3],const int Nxx_plus_2NGHOSTS[3],REAL *xx[3], REAL *out_gfs,REAL *out_gfs_exact) { int imin[3] = { NGHOSTS, NGHOSTS, NGHOSTS }; int imax[3] = { Nxx_plus_2NGHOSTS[0]-NGHOSTS, Nxx_plus_2NGHOSTS[1]-NGHOSTS, Nxx_plus_2NGHOSTS[2]-NGHOSTS }; for(int which_gz = 0; which_gz < NGHOSTS; which_gz++) { // After updating each face, adjust imin[] and imax[] // to reflect the newly-updated face extents. // Right now, we only want to update the xmin and xmax faces with the exact data. FACE_UPDATE_EXACT_StildeD(Nxx,Nxx_plus_2NGHOSTS,xx,out_gfs,out_gfs_exact,imin[0]-1,imin[0], imin[1],imax[1], imin[2],imax[2], MINFACE,NUL,NUL); imin[0]--; FACE_UPDATE_EXACT_StildeD(Nxx,Nxx_plus_2NGHOSTS,xx,out_gfs,out_gfs_exact,imax[0],imax[0]+1, imin[1],imax[1], imin[2],imax[2], MAXFACE,NUL,NUL); imax[0]++; //FACE_UPDATE_EXACT_StildeD(Nxx,Nxx_plus_2NGHOSTS,xx,out_gfs,out_gfs_exact,imin[0],imax[0], imin[1]-1,imin[1], imin[2],imax[2], NUL,MINFACE,NUL); imin[1]--; //FACE_UPDATE_EXACT_StildeD(Nxx,Nxx_plus_2NGHOSTS,xx,out_gfs,out_gfs_exact,imin[0],imax[0], imax[1],imax[1]+1, imin[2],imax[2], NUL,MAXFACE,NUL); imax[1]++; //FACE_UPDATE_EXACT_StildeD(Nxx,Nxx_plus_2NGHOSTS,xx,out_gfs,out_gfs_exact,imin[0],imax[0], imin[1],imax[1], imin[2]-1,imin[2], NUL,NUL,MINFACE); imin[2]--; //FACE_UPDATE_EXACT_StildeD(Nxx,Nxx_plus_2NGHOSTS,xx,out_gfs,out_gfs_exact,imin[0],imax[0], imin[1],imax[1], imax[2],imax[2]+1, NUL,NUL,MAXFACE); imax[2]++; } }
segment.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS EEEEE GGGG M M EEEEE N N TTTTT % % SS E G MM MM E NN N T % % SSS EEE G GGG M M M EEE N N N T % % SS E G G M M E N NN T % % SSSSS EEEEE GGGG M M EEEEE N N T % % % % % % MagickCore Methods to Segment an Image with Thresholding Fuzzy c-Means % % % % Software Design % % Cristy % % April 1993 % % % % % % Copyright 1999-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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Segment segments an image by analyzing the histograms of the color % components and identifying units that are homogeneous with the fuzzy % c-means technique. The scale-space filter analyzes the histograms of % the three color components of the image and identifies a set of % classes. The extents of each class is used to coarsely segment the % image with thresholding. The color associated with each class is % determined by the mean color of all pixels within the extents of a % particular class. Finally, any unclassified pixels are assigned to % the closest class with the fuzzy c-means technique. % % The fuzzy c-Means algorithm can be summarized as follows: % % o Build a histogram, one for each color component of the image. % % o For each histogram, successively apply the scale-space filter and % build an interval tree of zero crossings in the second derivative % at each scale. Analyze this scale-space ''fingerprint'' to % determine which peaks and valleys in the histogram are most % predominant. % % o The fingerprint defines intervals on the axis of the histogram. % Each interval contains either a minima or a maxima in the original % signal. If each color component lies within the maxima interval, % that pixel is considered ''classified'' and is assigned an unique % class number. % % o Any pixel that fails to be classified in the above thresholding % pass is classified using the fuzzy c-Means technique. It is % assigned to one of the classes discovered in the histogram analysis % phase. % % The fuzzy c-Means technique attempts to cluster a pixel by finding % the local minima of the generalized within group sum of squared error % objective function. A pixel is assigned to the closest class of % which the fuzzy membership has a maximum value. % % Segment is strongly based on software written by Andy Gallo, % University of Delaware. % % The following reference was used in creating this program: % % Young Won Lim, Sang Uk Lee, "On The Color Image Segmentation % Algorithm Based on the Thresholding and the Fuzzy c-Means % Techniques", Pattern Recognition, Volume 23, Number 9, pages % 935-952, 1990. % % */ #include "MagickCore/studio.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/quantize.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/segment.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" /* Define declarations. */ #define MaxDimension 3 #define DeltaTau 0.5f #if defined(FastClassify) #define WeightingExponent 2.0 #define SegmentPower(ratio) (ratio) #else #define WeightingExponent 2.5 #define SegmentPower(ratio) pow(ratio,(double) (1.0/(weighting_exponent-1.0))); #endif #define Tau 5.2f /* Typedef declarations. */ typedef struct _ExtentPacket { double center; ssize_t index, left, right; } ExtentPacket; typedef struct _Cluster { struct _Cluster *next; ExtentPacket red, green, blue; ssize_t count, id; } Cluster; typedef struct _IntervalTree { double tau; ssize_t left, right; double mean_stability, stability; struct _IntervalTree *sibling, *child; } IntervalTree; typedef struct _ZeroCrossing { double tau, histogram[256]; short crossings[256]; } ZeroCrossing; /* Constant declarations. */ static const int Blue = 2, Green = 1, Red = 0, SafeMargin = 3, TreeLength = 600; /* Method prototypes. */ static double OptimalTau(const ssize_t *,const double,const double,const double, const double,short *); static ssize_t DefineRegion(const short *,ExtentPacket *); static void FreeNodes(IntervalTree *), InitializeHistogram(const Image *,ssize_t **,ExceptionInfo *), ScaleSpace(const ssize_t *,const double,double *), ZeroCrossHistogram(double *,const double,short *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l a s s i f y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Classify() defines one or more classes. Each pixel is thresholded to % determine which class it belongs to. If the class is not identified it is % assigned to the closest class based on the fuzzy c-Means technique. % % The format of the Classify method is: % % MagickBooleanType Classify(Image *image,short **extrema, % const double cluster_threshold, % const double weighting_exponent, % const MagickBooleanType verbose,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o extrema: Specifies a pointer to an array of integers. They % represent the peaks and valleys of the histogram for each color % component. % % o cluster_threshold: This double represents the minimum number of % pixels contained in a hexahedra before it can be considered valid % (expressed as a percentage). % % o weighting_exponent: Specifies the membership weighting exponent. % % o verbose: A value greater than zero prints detailed information about % the identified classes. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType Classify(Image *image,short **extrema, const double cluster_threshold, const double weighting_exponent,const MagickBooleanType verbose, ExceptionInfo *exception) { #define SegmentImageTag "Segment/Image" #define ThrowClassifyException(severity,tag,label) \ {\ for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster) \ { \ next_cluster=cluster->next; \ cluster=(Cluster *) RelinquishMagickMemory(cluster); \ } \ if (squares != (double *) NULL) \ { \ squares-=255; \ free_squares=squares; \ free_squares=(double *) RelinquishMagickMemory(free_squares); \ } \ ThrowBinaryException(severity,tag,label); \ } CacheView *image_view; Cluster *cluster, *head, *last_cluster, *next_cluster; ExtentPacket blue, green, red; MagickOffsetType progress; double *free_squares; MagickStatusType status; register ssize_t i; register double *squares; size_t number_clusters; ssize_t count, y; /* Form clusters. */ cluster=(Cluster *) NULL; head=(Cluster *) NULL; squares=(double *) NULL; (void) memset(&red,0,sizeof(red)); (void) memset(&green,0,sizeof(green)); (void) memset(&blue,0,sizeof(blue)); while (DefineRegion(extrema[Red],&red) != 0) { green.index=0; while (DefineRegion(extrema[Green],&green) != 0) { blue.index=0; while (DefineRegion(extrema[Blue],&blue) != 0) { /* Allocate a new class. */ if (head != (Cluster *) NULL) { cluster->next=(Cluster *) AcquireMagickMemory( sizeof(*cluster->next)); cluster=cluster->next; } else { cluster=(Cluster *) AcquireMagickMemory(sizeof(*cluster)); head=cluster; } if (cluster == (Cluster *) NULL) ThrowClassifyException(ResourceLimitError,"MemoryAllocationFailed", image->filename); /* Initialize a new class. */ cluster->count=0; cluster->red=red; cluster->green=green; cluster->blue=blue; cluster->next=(Cluster *) NULL; } } } if (head == (Cluster *) NULL) { /* No classes were identified-- create one. */ cluster=(Cluster *) AcquireMagickMemory(sizeof(*cluster)); if (cluster == (Cluster *) NULL) ThrowClassifyException(ResourceLimitError,"MemoryAllocationFailed", image->filename); /* Initialize a new class. */ cluster->count=0; cluster->red=red; cluster->green=green; cluster->blue=blue; cluster->next=(Cluster *) NULL; head=cluster; } /* Count the pixels for each cluster. */ status=MagickTrue; count=0; progress=0; image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) if (((ssize_t) ScaleQuantumToChar(GetPixelRed(image,p)) >= (cluster->red.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelRed(image,p)) <= (cluster->red.right+SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelGreen(image,p)) >= (cluster->green.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelGreen(image,p)) <= (cluster->green.right+SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelBlue(image,p)) >= (cluster->blue.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelBlue(image,p)) <= (cluster->blue.right+SafeMargin))) { /* Count this pixel. */ count++; cluster->red.center+=(double) ScaleQuantumToChar( GetPixelRed(image,p)); cluster->green.center+=(double) ScaleQuantumToChar( GetPixelGreen(image,p)); cluster->blue.center+=(double) ScaleQuantumToChar( GetPixelBlue(image,p)); cluster->count++; break; } p+=GetPixelChannels(image); } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,SegmentImageTag,progress,2*image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); /* Remove clusters that do not meet minimum cluster threshold. */ count=0; last_cluster=head; next_cluster=head; for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster) { next_cluster=cluster->next; if ((cluster->count > 0) && (cluster->count >= (count*cluster_threshold/100.0))) { /* Initialize cluster. */ cluster->id=count; cluster->red.center/=cluster->count; cluster->green.center/=cluster->count; cluster->blue.center/=cluster->count; count++; last_cluster=cluster; continue; } /* Delete cluster. */ if (cluster == head) head=next_cluster; else last_cluster->next=next_cluster; cluster=(Cluster *) RelinquishMagickMemory(cluster); } number_clusters=(size_t) count; if (verbose != MagickFalse) { /* Print cluster statistics. */ (void) FormatLocaleFile(stdout,"Fuzzy C-means Statistics\n"); (void) FormatLocaleFile(stdout,"===================\n\n"); (void) FormatLocaleFile(stdout,"\tCluster Threshold = %g\n",(double) cluster_threshold); (void) FormatLocaleFile(stdout,"\tWeighting Exponent = %g\n",(double) weighting_exponent); (void) FormatLocaleFile(stdout,"\tTotal Number of Clusters = %.20g\n\n", (double) number_clusters); /* Print the total number of points per cluster. */ (void) FormatLocaleFile(stdout,"\n\nNumber of Vectors Per Cluster\n"); (void) FormatLocaleFile(stdout,"=============================\n\n"); for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) (void) FormatLocaleFile(stdout,"Cluster #%.20g = %.20g\n",(double) cluster->id,(double) cluster->count); /* Print the cluster extents. */ (void) FormatLocaleFile(stdout, "\n\n\nCluster Extents: (Vector Size: %d)\n",MaxDimension); (void) FormatLocaleFile(stdout,"================"); for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) { (void) FormatLocaleFile(stdout,"\n\nCluster #%.20g\n\n",(double) cluster->id); (void) FormatLocaleFile(stdout, "%.20g-%.20g %.20g-%.20g %.20g-%.20g\n",(double) cluster->red.left,(double) cluster->red.right,(double) cluster->green.left,(double) cluster->green.right,(double) cluster->blue.left,(double) cluster->blue.right); } /* Print the cluster center values. */ (void) FormatLocaleFile(stdout, "\n\n\nCluster Center Values: (Vector Size: %d)\n",MaxDimension); (void) FormatLocaleFile(stdout,"====================="); for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) { (void) FormatLocaleFile(stdout,"\n\nCluster #%.20g\n\n",(double) cluster->id); (void) FormatLocaleFile(stdout,"%g %g %g\n",(double) cluster->red.center,(double) cluster->green.center,(double) cluster->blue.center); } (void) FormatLocaleFile(stdout,"\n"); } if (number_clusters > 256) ThrowClassifyException(ImageError,"TooManyClusters",image->filename); /* Speed up distance calculations. */ squares=(double *) AcquireQuantumMemory(513UL,sizeof(*squares)); if (squares == (double *) NULL) ThrowClassifyException(ResourceLimitError,"MemoryAllocationFailed", image->filename); squares+=255; for (i=(-255); i <= 255; i++) squares[i]=(double) i*(double) i; /* Allocate image colormap. */ if (AcquireImageColormap(image,number_clusters,exception) == MagickFalse) ThrowClassifyException(ResourceLimitError,"MemoryAllocationFailed", image->filename); i=0; for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) { image->colormap[i].red=(double) ScaleCharToQuantum((unsigned char) (cluster->red.center+0.5)); image->colormap[i].green=(double) ScaleCharToQuantum((unsigned char) (cluster->green.center+0.5)); image->colormap[i].blue=(double) ScaleCharToQuantum((unsigned char) (cluster->blue.center+0.5)); i++; } /* Do course grain classes. */ image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Cluster *clust; register const PixelInfo *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,(Quantum) 0,q); for (clust=head; clust != (Cluster *) NULL; clust=clust->next) { if (((ssize_t) ScaleQuantumToChar(GetPixelRed(image,q)) >= (clust->red.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelRed(image,q)) <= (clust->red.right+SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelGreen(image,q)) >= (clust->green.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelGreen(image,q)) <= (clust->green.right+SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelBlue(image,q)) >= (clust->blue.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelBlue(image,q)) <= (clust->blue.right+SafeMargin))) { /* Classify this pixel. */ SetPixelIndex(image,(Quantum) clust->id,q); break; } } if (clust == (Cluster *) NULL) { double distance_squared, local_minima, numerator, ratio, sum; register ssize_t j, k; /* Compute fuzzy membership. */ local_minima=0.0; for (j=0; j < (ssize_t) image->colors; j++) { sum=0.0; p=image->colormap+j; distance_squared=squares[(ssize_t) ScaleQuantumToChar( GetPixelRed(image,q))-(ssize_t) ScaleQuantumToChar(ClampToQuantum(p->red))]+squares[(ssize_t) ScaleQuantumToChar(GetPixelGreen(image,q))-(ssize_t) ScaleQuantumToChar(ClampToQuantum(p->green))]+squares[(ssize_t) ScaleQuantumToChar(GetPixelBlue(image,q))-(ssize_t) ScaleQuantumToChar(ClampToQuantum(p->blue))]; numerator=distance_squared; for (k=0; k < (ssize_t) image->colors; k++) { p=image->colormap+k; distance_squared=squares[(ssize_t) ScaleQuantumToChar( GetPixelRed(image,q))-(ssize_t) ScaleQuantumToChar(ClampToQuantum(p->red))]+squares[ (ssize_t) ScaleQuantumToChar(GetPixelGreen(image,q))-(ssize_t) ScaleQuantumToChar(ClampToQuantum(p->green))]+squares[ (ssize_t) ScaleQuantumToChar(GetPixelBlue(image,q))-(ssize_t) ScaleQuantumToChar(ClampToQuantum(p->blue))]; ratio=numerator/distance_squared; sum+=SegmentPower(ratio); } if ((sum != 0.0) && ((1.0/sum) > local_minima)) { /* Classify this pixel. */ local_minima=1.0/sum; SetPixelIndex(image,(Quantum) j,q); } } } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,SegmentImageTag,progress,2*image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); status&=SyncImage(image,exception); /* Relinquish resources. */ for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster) { next_cluster=cluster->next; cluster=(Cluster *) RelinquishMagickMemory(cluster); } squares-=255; free_squares=squares; free_squares=(double *) RelinquishMagickMemory(free_squares); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o n s o l i d a t e C r o s s i n g s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConsolidateCrossings() guarantees that an even number of zero crossings % always lie between two crossings. % % The format of the ConsolidateCrossings method is: % % ConsolidateCrossings(ZeroCrossing *zero_crossing, % const size_t number_crossings) % % A description of each parameter follows. % % o zero_crossing: Specifies an array of structures of type ZeroCrossing. % % o number_crossings: This size_t specifies the number of elements % in the zero_crossing array. % */ static void ConsolidateCrossings(ZeroCrossing *zero_crossing, const size_t number_crossings) { register ssize_t i, j, k, l; ssize_t center, correct, count, left, right; /* Consolidate zero crossings. */ for (i=(ssize_t) number_crossings-1; i >= 0; i--) for (j=0; j <= 255; j++) { if (zero_crossing[i].crossings[j] == 0) continue; /* Find the entry that is closest to j and still preserves the property that there are an even number of crossings between intervals. */ for (k=j-1; k > 0; k--) if (zero_crossing[i+1].crossings[k] != 0) break; left=MagickMax(k,0); center=j; for (k=j+1; k < 255; k++) if (zero_crossing[i+1].crossings[k] != 0) break; right=MagickMin(k,255); /* K is the zero crossing just left of j. */ for (k=j-1; k > 0; k--) if (zero_crossing[i].crossings[k] != 0) break; if (k < 0) k=0; /* Check center for an even number of crossings between k and j. */ correct=(-1); if (zero_crossing[i+1].crossings[j] != 0) { count=0; for (l=k+1; l < center; l++) if (zero_crossing[i+1].crossings[l] != 0) count++; if (((count % 2) == 0) && (center != k)) correct=center; } /* Check left for an even number of crossings between k and j. */ if (correct == -1) { count=0; for (l=k+1; l < left; l++) if (zero_crossing[i+1].crossings[l] != 0) count++; if (((count % 2) == 0) && (left != k)) correct=left; } /* Check right for an even number of crossings between k and j. */ if (correct == -1) { count=0; for (l=k+1; l < right; l++) if (zero_crossing[i+1].crossings[l] != 0) count++; if (((count % 2) == 0) && (right != k)) correct=right; } l=(ssize_t) zero_crossing[i].crossings[j]; zero_crossing[i].crossings[j]=0; if (correct != -1) zero_crossing[i].crossings[correct]=(short) l; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e f i n e R e g i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DefineRegion() defines the left and right boundaries of a peak region. % % The format of the DefineRegion method is: % % ssize_t DefineRegion(const short *extrema,ExtentPacket *extents) % % A description of each parameter follows. % % o extrema: Specifies a pointer to an array of integers. They % represent the peaks and valleys of the histogram for each color % component. % % o extents: This pointer to an ExtentPacket represent the extends % of a particular peak or valley of a color component. % */ static ssize_t DefineRegion(const short *extrema,ExtentPacket *extents) { /* Initialize to default values. */ extents->left=0; extents->center=0.0; extents->right=255; /* Find the left side (maxima). */ for ( ; extents->index <= 255; extents->index++) if (extrema[extents->index] > 0) break; if (extents->index > 255) return(MagickFalse); /* no left side - no region exists */ extents->left=extents->index; /* Find the right side (minima). */ for ( ; extents->index <= 255; extents->index++) if (extrema[extents->index] < 0) break; extents->right=extents->index-1; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e r i v a t i v e H i s t o g r a m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DerivativeHistogram() determines the derivative of the histogram using % central differencing. % % The format of the DerivativeHistogram method is: % % DerivativeHistogram(const double *histogram, % double *derivative) % % A description of each parameter follows. % % o histogram: Specifies an array of doubles representing the number % of pixels for each intensity of a particular color component. % % o derivative: This array of doubles is initialized by % DerivativeHistogram to the derivative of the histogram using central % differencing. % */ static void DerivativeHistogram(const double *histogram, double *derivative) { register ssize_t i, n; /* Compute endpoints using second order polynomial interpolation. */ n=255; derivative[0]=(-1.5*histogram[0]+2.0*histogram[1]-0.5*histogram[2]); derivative[n]=(0.5*histogram[n-2]-2.0*histogram[n-1]+1.5*histogram[n]); /* Compute derivative using central differencing. */ for (i=1; i < n; i++) derivative[i]=(histogram[i+1]-histogram[i-1])/2.0; return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e D y n a m i c T h r e s h o l d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageDynamicThreshold() returns the dynamic threshold for an image. % % The format of the GetImageDynamicThreshold method is: % % MagickBooleanType GetImageDynamicThreshold(const Image *image, % const double cluster_threshold,const double smooth_threshold, % PixelInfo *pixel,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o cluster_threshold: This double represents the minimum number of % pixels contained in a hexahedra before it can be considered valid % (expressed as a percentage). % % o smooth_threshold: the smoothing threshold eliminates noise in the second % derivative of the histogram. As the value is increased, you can expect a % smoother second derivative. % % o pixel: return the dynamic threshold here. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageDynamicThreshold(const Image *image, const double cluster_threshold,const double smooth_threshold, PixelInfo *pixel,ExceptionInfo *exception) { Cluster *background, *cluster, *object, *head, *last_cluster, *next_cluster; ExtentPacket blue, green, red; MagickBooleanType proceed; double threshold; register const Quantum *p; register ssize_t i, x; short *extrema[MaxDimension]; ssize_t count, *histogram[MaxDimension], y; /* Allocate histogram and extrema. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); GetPixelInfo(image,pixel); for (i=0; i < MaxDimension; i++) { histogram[i]=(ssize_t *) AcquireQuantumMemory(256UL,sizeof(**histogram)); extrema[i]=(short *) AcquireQuantumMemory(256UL,sizeof(**histogram)); if ((histogram[i] == (ssize_t *) NULL) || (extrema[i] == (short *) NULL)) { for (i-- ; i >= 0; i--) { extrema[i]=(short *) RelinquishMagickMemory(extrema[i]); histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]); } (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } } /* Initialize histogram. */ InitializeHistogram(image,histogram,exception); (void) OptimalTau(histogram[Red],Tau,0.2f,DeltaTau, (smooth_threshold == 0.0f ? 1.0f : smooth_threshold),extrema[Red]); (void) OptimalTau(histogram[Green],Tau,0.2f,DeltaTau, (smooth_threshold == 0.0f ? 1.0f : smooth_threshold),extrema[Green]); (void) OptimalTau(histogram[Blue],Tau,0.2f,DeltaTau, (smooth_threshold == 0.0f ? 1.0f : smooth_threshold),extrema[Blue]); /* Form clusters. */ cluster=(Cluster *) NULL; head=(Cluster *) NULL; (void) memset(&red,0,sizeof(red)); (void) memset(&green,0,sizeof(green)); (void) memset(&blue,0,sizeof(blue)); while (DefineRegion(extrema[Red],&red) != 0) { green.index=0; while (DefineRegion(extrema[Green],&green) != 0) { blue.index=0; while (DefineRegion(extrema[Blue],&blue) != 0) { /* Allocate a new class. */ if (head != (Cluster *) NULL) { cluster->next=(Cluster *) AcquireMagickMemory( sizeof(*cluster->next)); cluster=cluster->next; } else { cluster=(Cluster *) AcquireMagickMemory(sizeof(*cluster)); head=cluster; } if (cluster == (Cluster *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); return(MagickFalse); } /* Initialize a new class. */ cluster->count=0; cluster->red=red; cluster->green=green; cluster->blue=blue; cluster->next=(Cluster *) NULL; } } } if (head == (Cluster *) NULL) { /* No classes were identified-- create one. */ cluster=(Cluster *) AcquireMagickMemory(sizeof(*cluster)); if (cluster == (Cluster *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } /* Initialize a new class. */ cluster->count=0; cluster->red=red; cluster->green=green; cluster->blue=blue; cluster->next=(Cluster *) NULL; head=cluster; } /* Count the pixels for each cluster. */ count=0; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) if (((ssize_t) ScaleQuantumToChar(GetPixelRed(image,p)) >= (cluster->red.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelRed(image,p)) <= (cluster->red.right+SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelGreen(image,p)) >= (cluster->green.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelGreen(image,p)) <= (cluster->green.right+SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelBlue(image,p)) >= (cluster->blue.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelBlue(image,p)) <= (cluster->blue.right+SafeMargin))) { /* Count this pixel. */ count++; cluster->red.center+=(double) ScaleQuantumToChar( GetPixelRed(image,p)); cluster->green.center+=(double) ScaleQuantumToChar( GetPixelGreen(image,p)); cluster->blue.center+=(double) ScaleQuantumToChar( GetPixelBlue(image,p)); cluster->count++; break; } p+=GetPixelChannels(image); } proceed=SetImageProgress(image,SegmentImageTag,(MagickOffsetType) y, 2*image->rows); if (proceed == MagickFalse) break; } /* Remove clusters that do not meet minimum cluster threshold. */ count=0; last_cluster=head; next_cluster=head; for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster) { next_cluster=cluster->next; if ((cluster->count > 0) && (cluster->count >= (count*cluster_threshold/100.0))) { /* Initialize cluster. */ cluster->id=count; cluster->red.center/=cluster->count; cluster->green.center/=cluster->count; cluster->blue.center/=cluster->count; count++; last_cluster=cluster; continue; } /* Delete cluster. */ if (cluster == head) head=next_cluster; else last_cluster->next=next_cluster; cluster=(Cluster *) RelinquishMagickMemory(cluster); } object=head; background=head; if (count > 1) { object=head->next; for (cluster=object; cluster->next != (Cluster *) NULL; ) { if (cluster->count < object->count) object=cluster; cluster=cluster->next; } background=head->next; for (cluster=background; cluster->next != (Cluster *) NULL; ) { if (cluster->count > background->count) background=cluster; cluster=cluster->next; } } if (background != (Cluster *) NULL) { threshold=(background->red.center+object->red.center)/2.0; pixel->red=(double) ScaleCharToQuantum((unsigned char) (threshold+0.5)); threshold=(background->green.center+object->green.center)/2.0; pixel->green=(double) ScaleCharToQuantum((unsigned char) (threshold+0.5)); threshold=(background->blue.center+object->blue.center)/2.0; pixel->blue=(double) ScaleCharToQuantum((unsigned char) (threshold+0.5)); } /* Relinquish resources. */ for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster) { next_cluster=cluster->next; cluster=(Cluster *) RelinquishMagickMemory(cluster); } for (i=0; i < MaxDimension; i++) { extrema[i]=(short *) RelinquishMagickMemory(extrema[i]); histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]); } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I n i t i a l i z e H i s t o g r a m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InitializeHistogram() computes the histogram for an image. % % The format of the InitializeHistogram method is: % % InitializeHistogram(const Image *image,ssize_t **histogram) % % A description of each parameter follows. % % o image: Specifies a pointer to an Image structure; returned from % ReadImage. % % o histogram: Specifies an array of integers representing the number % of pixels for each intensity of a particular color component. % */ static void InitializeHistogram(const Image *image,ssize_t **histogram, ExceptionInfo *exception) { register const Quantum *p; register ssize_t i, x; ssize_t y; /* Initialize histogram. */ for (i=0; i <= 255; i++) { histogram[Red][i]=0; histogram[Green][i]=0; histogram[Blue][i]=0; } for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { histogram[Red][(ssize_t) ScaleQuantumToChar(GetPixelRed(image,p))]++; histogram[Green][(ssize_t) ScaleQuantumToChar(GetPixelGreen(image,p))]++; histogram[Blue][(ssize_t) ScaleQuantumToChar(GetPixelBlue(image,p))]++; p+=GetPixelChannels(image); } } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I n i t i a l i z e I n t e r v a l T r e e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InitializeIntervalTree() initializes an interval tree from the lists of % zero crossings. % % The format of the InitializeIntervalTree method is: % % InitializeIntervalTree(IntervalTree **list,ssize_t *number_nodes, % IntervalTree *node) % % A description of each parameter follows. % % o zero_crossing: Specifies an array of structures of type ZeroCrossing. % % o number_crossings: This size_t specifies the number of elements % in the zero_crossing array. % */ static void InitializeList(IntervalTree **list,ssize_t *number_nodes, IntervalTree *node) { if (node == (IntervalTree *) NULL) return; if (node->child == (IntervalTree *) NULL) list[(*number_nodes)++]=node; InitializeList(list,number_nodes,node->sibling); InitializeList(list,number_nodes,node->child); } static void MeanStability(IntervalTree *node) { register IntervalTree *child; if (node == (IntervalTree *) NULL) return; node->mean_stability=0.0; child=node->child; if (child != (IntervalTree *) NULL) { register ssize_t count; register double sum; sum=0.0; count=0; for ( ; child != (IntervalTree *) NULL; child=child->sibling) { sum+=child->stability; count++; } node->mean_stability=sum/(double) count; } MeanStability(node->sibling); MeanStability(node->child); } static void Stability(IntervalTree *node) { if (node == (IntervalTree *) NULL) return; if (node->child == (IntervalTree *) NULL) node->stability=0.0; else node->stability=node->tau-(node->child)->tau; Stability(node->sibling); Stability(node->child); } static IntervalTree *InitializeIntervalTree(const ZeroCrossing *zero_crossing, const size_t number_crossings) { IntervalTree *head, **list, *node, *root; register ssize_t i; ssize_t j, k, left, number_nodes; /* Allocate interval tree. */ list=(IntervalTree **) AcquireQuantumMemory((size_t) TreeLength, sizeof(*list)); if (list == (IntervalTree **) NULL) return((IntervalTree *) NULL); /* The root is the entire histogram. */ root=(IntervalTree *) AcquireCriticalMemory(sizeof(*root)); root->child=(IntervalTree *) NULL; root->sibling=(IntervalTree *) NULL; root->tau=0.0; root->left=0; root->right=255; root->mean_stability=0.0; root->stability=0.0; (void) memset(list,0,TreeLength*sizeof(*list)); for (i=(-1); i < (ssize_t) number_crossings; i++) { /* Initialize list with all nodes with no children. */ number_nodes=0; InitializeList(list,&number_nodes,root); /* Split list. */ for (j=0; j < number_nodes; j++) { head=list[j]; left=head->left; node=head; for (k=head->left+1; k < head->right; k++) { if (zero_crossing[i+1].crossings[k] != 0) { if (node == head) { node->child=(IntervalTree *) AcquireMagickMemory( sizeof(*node->child)); node=node->child; } else { node->sibling=(IntervalTree *) AcquireMagickMemory( sizeof(*node->sibling)); node=node->sibling; } if (node == (IntervalTree *) NULL) { list=(IntervalTree **) RelinquishMagickMemory(list); FreeNodes(root); return((IntervalTree *) NULL); } node->tau=zero_crossing[i+1].tau; node->child=(IntervalTree *) NULL; node->sibling=(IntervalTree *) NULL; node->left=left; node->right=k; left=k; } } if (left != head->left) { node->sibling=(IntervalTree *) AcquireMagickMemory( sizeof(*node->sibling)); node=node->sibling; if (node == (IntervalTree *) NULL) { list=(IntervalTree **) RelinquishMagickMemory(list); FreeNodes(root); return((IntervalTree *) NULL); } node->tau=zero_crossing[i+1].tau; node->child=(IntervalTree *) NULL; node->sibling=(IntervalTree *) NULL; node->left=left; node->right=head->right; } } } /* Determine the stability: difference between a nodes tau and its child. */ Stability(root->child); MeanStability(root->child); list=(IntervalTree **) RelinquishMagickMemory(list); return(root); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + O p t i m a l T a u % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimalTau() finds the optimal tau for each band of the histogram. % % The format of the OptimalTau method is: % % double OptimalTau(const ssize_t *histogram,const double max_tau, % const double min_tau,const double delta_tau, % const double smooth_threshold,short *extrema) % % A description of each parameter follows. % % o histogram: Specifies an array of integers representing the number % of pixels for each intensity of a particular color component. % % o extrema: Specifies a pointer to an array of integers. They % represent the peaks and valleys of the histogram for each color % component. % */ static void ActiveNodes(IntervalTree **list,ssize_t *number_nodes, IntervalTree *node) { if (node == (IntervalTree *) NULL) return; if (node->stability >= node->mean_stability) { list[(*number_nodes)++]=node; ActiveNodes(list,number_nodes,node->sibling); } else { ActiveNodes(list,number_nodes,node->sibling); ActiveNodes(list,number_nodes,node->child); } } static void FreeNodes(IntervalTree *node) { if (node == (IntervalTree *) NULL) return; FreeNodes(node->sibling); FreeNodes(node->child); node=(IntervalTree *) RelinquishMagickMemory(node); } static double OptimalTau(const ssize_t *histogram,const double max_tau, const double min_tau,const double delta_tau,const double smooth_threshold, short *extrema) { IntervalTree **list, *node, *root; MagickBooleanType peak; double average_tau, *derivative, *second_derivative, tau, value; register ssize_t i, x; size_t count, number_crossings; ssize_t index, j, k, number_nodes; ZeroCrossing *zero_crossing; /* Allocate interval tree. */ list=(IntervalTree **) AcquireQuantumMemory((size_t) TreeLength, sizeof(*list)); if (list == (IntervalTree **) NULL) return(0.0); /* Allocate zero crossing list. */ count=(size_t) ((max_tau-min_tau)/delta_tau)+2; zero_crossing=(ZeroCrossing *) AcquireQuantumMemory((size_t) count, sizeof(*zero_crossing)); if (zero_crossing == (ZeroCrossing *) NULL) { list=(IntervalTree **) RelinquishMagickMemory(list); return(0.0); } for (i=0; i < (ssize_t) count; i++) zero_crossing[i].tau=(-1.0); /* Initialize zero crossing list. */ derivative=(double *) AcquireCriticalMemory(256*sizeof(*derivative)); second_derivative=(double *) AcquireCriticalMemory(256* sizeof(*second_derivative)); i=0; for (tau=max_tau; tau >= min_tau; tau-=delta_tau) { zero_crossing[i].tau=tau; ScaleSpace(histogram,tau,zero_crossing[i].histogram); DerivativeHistogram(zero_crossing[i].histogram,derivative); DerivativeHistogram(derivative,second_derivative); ZeroCrossHistogram(second_derivative,smooth_threshold, zero_crossing[i].crossings); i++; } /* Add an entry for the original histogram. */ zero_crossing[i].tau=0.0; for (j=0; j <= 255; j++) zero_crossing[i].histogram[j]=(double) histogram[j]; DerivativeHistogram(zero_crossing[i].histogram,derivative); DerivativeHistogram(derivative,second_derivative); ZeroCrossHistogram(second_derivative,smooth_threshold, zero_crossing[i].crossings); number_crossings=(size_t) i; derivative=(double *) RelinquishMagickMemory(derivative); second_derivative=(double *) RelinquishMagickMemory(second_derivative); /* Ensure the scale-space fingerprints form lines in scale-space, not loops. */ ConsolidateCrossings(zero_crossing,number_crossings); /* Force endpoints to be included in the interval. */ for (i=0; i <= (ssize_t) number_crossings; i++) { for (j=0; j < 255; j++) if (zero_crossing[i].crossings[j] != 0) break; zero_crossing[i].crossings[0]=(-zero_crossing[i].crossings[j]); for (j=255; j > 0; j--) if (zero_crossing[i].crossings[j] != 0) break; zero_crossing[i].crossings[255]=(-zero_crossing[i].crossings[j]); } /* Initialize interval tree. */ root=InitializeIntervalTree(zero_crossing,number_crossings); if (root == (IntervalTree *) NULL) { zero_crossing=(ZeroCrossing *) RelinquishMagickMemory(zero_crossing); list=(IntervalTree **) RelinquishMagickMemory(list); return(0.0); } /* Find active nodes: stability is greater (or equal) to the mean stability of its children. */ number_nodes=0; ActiveNodes(list,&number_nodes,root->child); /* Initialize extrema. */ for (i=0; i <= 255; i++) extrema[i]=0; for (i=0; i < number_nodes; i++) { /* Find this tau in zero crossings list. */ k=0; node=list[i]; for (j=0; j <= (ssize_t) number_crossings; j++) if (zero_crossing[j].tau == node->tau) k=j; /* Find the value of the peak. */ peak=zero_crossing[k].crossings[node->right] == -1 ? MagickTrue : MagickFalse; index=node->left; value=zero_crossing[k].histogram[index]; for (x=node->left; x <= node->right; x++) { if (peak != MagickFalse) { if (zero_crossing[k].histogram[x] > value) { value=zero_crossing[k].histogram[x]; index=x; } } else if (zero_crossing[k].histogram[x] < value) { value=zero_crossing[k].histogram[x]; index=x; } } for (x=node->left; x <= node->right; x++) { if (index == 0) index=256; if (peak != MagickFalse) extrema[x]=(short) index; else extrema[x]=(short) (-index); } } /* Determine the average tau. */ average_tau=0.0; for (i=0; i < number_nodes; i++) average_tau+=list[i]->tau; average_tau*=PerceptibleReciprocal((double) number_nodes); /* Relinquish resources. */ FreeNodes(root); zero_crossing=(ZeroCrossing *) RelinquishMagickMemory(zero_crossing); list=(IntervalTree **) RelinquishMagickMemory(list); return(average_tau); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S c a l e S p a c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ScaleSpace() performs a scale-space filter on the 1D histogram. % % The format of the ScaleSpace method is: % % ScaleSpace(const ssize_t *histogram,const double tau, % double *scale_histogram) % % A description of each parameter follows. % % o histogram: Specifies an array of doubles representing the number % of pixels for each intensity of a particular color component. % */ static void ScaleSpace(const ssize_t *histogram,const double tau, double *scale_histogram) { double alpha, beta, *gamma, sum; register ssize_t u, x; gamma=(double *) AcquireQuantumMemory(256,sizeof(*gamma)); if (gamma == (double *) NULL) ThrowFatalException(ResourceLimitFatalError, "UnableToAllocateGammaMap"); alpha=PerceptibleReciprocal(tau*sqrt(2.0*MagickPI)); beta=(-1.0*PerceptibleReciprocal(2.0*tau*tau)); for (x=0; x <= 255; x++) gamma[x]=0.0; for (x=0; x <= 255; x++) { gamma[x]=exp((double) beta*x*x); if (gamma[x] < MagickEpsilon) break; } for (x=0; x <= 255; x++) { sum=0.0; for (u=0; u <= 255; u++) sum+=(double) histogram[u]*gamma[MagickAbsoluteValue(x-u)]; scale_histogram[x]=alpha*sum; } gamma=(double *) RelinquishMagickMemory(gamma); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e g m e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SegmentImage() segment an image by analyzing the histograms of the color % components and identifying units that are homogeneous with the fuzzy % C-means technique. % % The format of the SegmentImage method is: % % MagickBooleanType SegmentImage(Image *image, % const ColorspaceType colorspace,const MagickBooleanType verbose, % const double cluster_threshold,const double smooth_threshold, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o colorspace: Indicate the colorspace. % % o verbose: Set to MagickTrue to print detailed information about the % identified classes. % % o cluster_threshold: This represents the minimum number of pixels % contained in a hexahedra before it can be considered valid (expressed % as a percentage). % % o smooth_threshold: the smoothing threshold eliminates noise in the second % derivative of the histogram. As the value is increased, you can expect a % smoother second derivative. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SegmentImage(Image *image, const ColorspaceType colorspace,const MagickBooleanType verbose, const double cluster_threshold,const double smooth_threshold, ExceptionInfo *exception) { ColorspaceType previous_colorspace; MagickBooleanType status; register ssize_t i; short *extrema[MaxDimension]; ssize_t *histogram[MaxDimension]; /* Allocate histogram and extrema. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); for (i=0; i < MaxDimension; i++) { histogram[i]=(ssize_t *) AcquireQuantumMemory(256,sizeof(**histogram)); extrema[i]=(short *) AcquireQuantumMemory(256,sizeof(**extrema)); if ((histogram[i] == (ssize_t *) NULL) || (extrema[i] == (short *) NULL)) { for (i-- ; i >= 0; i--) { extrema[i]=(short *) RelinquishMagickMemory(extrema[i]); histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]); } ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename) } } /* Initialize histogram. */ previous_colorspace=image->colorspace; (void) TransformImageColorspace(image,colorspace,exception); InitializeHistogram(image,histogram,exception); (void) OptimalTau(histogram[Red],Tau,0.2,DeltaTau, smooth_threshold == 0.0 ? 1.0 : smooth_threshold,extrema[Red]); (void) OptimalTau(histogram[Green],Tau,0.2,DeltaTau, smooth_threshold == 0.0 ? 1.0 : smooth_threshold,extrema[Green]); (void) OptimalTau(histogram[Blue],Tau,0.2,DeltaTau, smooth_threshold == 0.0 ? 1.0 : smooth_threshold,extrema[Blue]); /* Classify using the fuzzy c-Means technique. */ status=Classify(image,extrema,cluster_threshold,WeightingExponent,verbose, exception); (void) TransformImageColorspace(image,previous_colorspace,exception); /* Relinquish resources. */ for (i=0; i < MaxDimension; i++) { extrema[i]=(short *) RelinquishMagickMemory(extrema[i]); histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]); } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Z e r o C r o s s H i s t o g r a m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ZeroCrossHistogram() find the zero crossings in a histogram and marks % directions as: 1 is negative to positive; 0 is zero crossing; and -1 % is positive to negative. % % The format of the ZeroCrossHistogram method is: % % ZeroCrossHistogram(double *second_derivative, % const double smooth_threshold,short *crossings) % % A description of each parameter follows. % % o second_derivative: Specifies an array of doubles representing the % second derivative of the histogram of a particular color component. % % o crossings: This array of integers is initialized with % -1, 0, or 1 representing the slope of the first derivative of the % of a particular color component. % */ static void ZeroCrossHistogram(double *second_derivative, const double smooth_threshold,short *crossings) { register ssize_t i; ssize_t parity; /* Merge low numbers to zero to help prevent noise. */ for (i=0; i <= 255; i++) if ((second_derivative[i] < smooth_threshold) && (second_derivative[i] >= -smooth_threshold)) second_derivative[i]=0.0; /* Mark zero crossings. */ parity=0; for (i=0; i <= 255; i++) { crossings[i]=0; if (second_derivative[i] < 0.0) { if (parity > 0) crossings[i]=(-1); parity=1; } else if (second_derivative[i] > 0.0) { if (parity < 0) crossings[i]=1; parity=(-1); } } }
test5.c
typedef signed char __int8_t; typedef unsigned char __uint8_t; typedef short __int16_t; typedef unsigned short __uint16_t; typedef int __int32_t; typedef unsigned int __uint32_t; typedef long long __int64_t; typedef unsigned long long __uint64_t; typedef long __darwin_intptr_t; typedef unsigned int __darwin_natural_t; typedef int __darwin_ct_rune_t; typedef union { char __mbstate8[128]; long long _mbstateL; } __mbstate_t; typedef __mbstate_t __darwin_mbstate_t; typedef long int __darwin_ptrdiff_t; typedef long unsigned int __darwin_size_t; typedef __builtin_va_list __darwin_va_list; typedef int __darwin_wchar_t; typedef __darwin_wchar_t __darwin_rune_t; typedef int __darwin_wint_t; typedef unsigned long __darwin_clock_t; typedef __uint32_t __darwin_socklen_t; typedef long __darwin_ssize_t; typedef long __darwin_time_t; typedef __int64_t __darwin_blkcnt_t; typedef __int32_t __darwin_blksize_t; typedef __int32_t __darwin_dev_t; typedef unsigned int __darwin_fsblkcnt_t; typedef unsigned int __darwin_fsfilcnt_t; typedef __uint32_t __darwin_gid_t; typedef __uint32_t __darwin_id_t; typedef __uint64_t __darwin_ino64_t; typedef __darwin_ino64_t __darwin_ino_t; typedef __darwin_natural_t __darwin_mach_port_name_t; typedef __darwin_mach_port_name_t __darwin_mach_port_t; typedef __uint16_t __darwin_mode_t; typedef __int64_t __darwin_off_t; typedef __int32_t __darwin_pid_t; typedef __uint32_t __darwin_sigset_t; typedef __int32_t __darwin_suseconds_t; typedef __uint32_t __darwin_uid_t; typedef __uint32_t __darwin_useconds_t; typedef unsigned char __darwin_uuid_t[16]; typedef char __darwin_uuid_string_t[37]; struct __darwin_pthread_handler_rec { void (*__routine)(void *); void *__arg; struct __darwin_pthread_handler_rec *__next; }; struct _opaque_pthread_attr_t { long __sig; char __opaque[56]; }; struct _opaque_pthread_cond_t { long __sig; char __opaque[40]; }; struct _opaque_pthread_condattr_t { long __sig; char __opaque[8]; }; struct _opaque_pthread_mutex_t { long __sig; char __opaque[56]; }; struct _opaque_pthread_mutexattr_t { long __sig; char __opaque[8]; }; struct _opaque_pthread_once_t { long __sig; char __opaque[8]; }; struct _opaque_pthread_rwlock_t { long __sig; char __opaque[192]; }; struct _opaque_pthread_rwlockattr_t { long __sig; char __opaque[16]; }; struct _opaque_pthread_t { long __sig; struct __darwin_pthread_handler_rec *__cleanup_stack; char __opaque[8176]; }; typedef struct _opaque_pthread_attr_t __darwin_pthread_attr_t; typedef struct _opaque_pthread_cond_t __darwin_pthread_cond_t; typedef struct _opaque_pthread_condattr_t __darwin_pthread_condattr_t; typedef unsigned long __darwin_pthread_key_t; typedef struct _opaque_pthread_mutex_t __darwin_pthread_mutex_t; typedef struct _opaque_pthread_mutexattr_t __darwin_pthread_mutexattr_t; typedef struct _opaque_pthread_once_t __darwin_pthread_once_t; typedef struct _opaque_pthread_rwlock_t __darwin_pthread_rwlock_t; typedef struct _opaque_pthread_rwlockattr_t __darwin_pthread_rwlockattr_t; typedef struct _opaque_pthread_t *__darwin_pthread_t; typedef int __darwin_nl_item; typedef int __darwin_wctrans_t; typedef __uint32_t __darwin_wctype_t; typedef enum { P_ALL, P_PID, P_PGID } idtype_t; typedef __darwin_pid_t pid_t; typedef __darwin_id_t id_t; typedef int sig_atomic_t; typedef signed char int8_t; typedef short int16_t; typedef int int32_t; typedef long long int64_t; typedef unsigned char u_int8_t; typedef unsigned short u_int16_t; typedef unsigned int u_int32_t; typedef unsigned long long u_int64_t; typedef int64_t register_t; typedef __darwin_intptr_t intptr_t; typedef unsigned long uintptr_t; typedef u_int64_t user_addr_t; typedef u_int64_t user_size_t; typedef int64_t user_ssize_t; typedef int64_t user_long_t; typedef u_int64_t user_ulong_t; typedef int64_t user_time_t; typedef int64_t user_off_t; typedef u_int64_t syscall_arg_t; struct __darwin_i386_thread_state { unsigned int __eax; unsigned int __ebx; unsigned int __ecx; unsigned int __edx; unsigned int __edi; unsigned int __esi; unsigned int __ebp; unsigned int __esp; unsigned int __ss; unsigned int __eflags; unsigned int __eip; unsigned int __cs; unsigned int __ds; unsigned int __es; unsigned int __fs; unsigned int __gs; }; struct __darwin_fp_control { unsigned short __invalid :1, __denorm :1, __zdiv :1, __ovrfl :1, __undfl :1, __precis :1, :2, __pc :2, __rc :2, :1, :3; }; typedef struct __darwin_fp_control __darwin_fp_control_t; struct __darwin_fp_status { unsigned short __invalid :1, __denorm :1, __zdiv :1, __ovrfl :1, __undfl :1, __precis :1, __stkflt :1, __errsumm :1, __c0 :1, __c1 :1, __c2 :1, __tos :3, __c3 :1, __busy :1; }; typedef struct __darwin_fp_status __darwin_fp_status_t; struct __darwin_mmst_reg { char __mmst_reg[10]; char __mmst_rsrv[6]; }; struct __darwin_xmm_reg { char __xmm_reg[16]; }; struct __darwin_ymm_reg { char __ymm_reg[32]; }; struct __darwin_zmm_reg { char __zmm_reg[64]; }; struct __darwin_opmask_reg { char __opmask_reg[8]; }; struct __darwin_i386_float_state { int __fpu_reserved[2]; struct __darwin_fp_control __fpu_fcw; struct __darwin_fp_status __fpu_fsw; __uint8_t __fpu_ftw; __uint8_t __fpu_rsrv1; __uint16_t __fpu_fop; __uint32_t __fpu_ip; __uint16_t __fpu_cs; __uint16_t __fpu_rsrv2; __uint32_t __fpu_dp; __uint16_t __fpu_ds; __uint16_t __fpu_rsrv3; __uint32_t __fpu_mxcsr; __uint32_t __fpu_mxcsrmask; struct __darwin_mmst_reg __fpu_stmm0; struct __darwin_mmst_reg __fpu_stmm1; struct __darwin_mmst_reg __fpu_stmm2; struct __darwin_mmst_reg __fpu_stmm3; struct __darwin_mmst_reg __fpu_stmm4; struct __darwin_mmst_reg __fpu_stmm5; struct __darwin_mmst_reg __fpu_stmm6; struct __darwin_mmst_reg __fpu_stmm7; struct __darwin_xmm_reg __fpu_xmm0; struct __darwin_xmm_reg __fpu_xmm1; struct __darwin_xmm_reg __fpu_xmm2; struct __darwin_xmm_reg __fpu_xmm3; struct __darwin_xmm_reg __fpu_xmm4; struct __darwin_xmm_reg __fpu_xmm5; struct __darwin_xmm_reg __fpu_xmm6; struct __darwin_xmm_reg __fpu_xmm7; char __fpu_rsrv4[14 * 16]; int __fpu_reserved1; }; struct __darwin_i386_avx_state { int __fpu_reserved[2]; struct __darwin_fp_control __fpu_fcw; struct __darwin_fp_status __fpu_fsw; __uint8_t __fpu_ftw; __uint8_t __fpu_rsrv1; __uint16_t __fpu_fop; __uint32_t __fpu_ip; __uint16_t __fpu_cs; __uint16_t __fpu_rsrv2; __uint32_t __fpu_dp; __uint16_t __fpu_ds; __uint16_t __fpu_rsrv3; __uint32_t __fpu_mxcsr; __uint32_t __fpu_mxcsrmask; struct __darwin_mmst_reg __fpu_stmm0; struct __darwin_mmst_reg __fpu_stmm1; struct __darwin_mmst_reg __fpu_stmm2; struct __darwin_mmst_reg __fpu_stmm3; struct __darwin_mmst_reg __fpu_stmm4; struct __darwin_mmst_reg __fpu_stmm5; struct __darwin_mmst_reg __fpu_stmm6; struct __darwin_mmst_reg __fpu_stmm7; struct __darwin_xmm_reg __fpu_xmm0; struct __darwin_xmm_reg __fpu_xmm1; struct __darwin_xmm_reg __fpu_xmm2; struct __darwin_xmm_reg __fpu_xmm3; struct __darwin_xmm_reg __fpu_xmm4; struct __darwin_xmm_reg __fpu_xmm5; struct __darwin_xmm_reg __fpu_xmm6; struct __darwin_xmm_reg __fpu_xmm7; char __fpu_rsrv4[14 * 16]; int __fpu_reserved1; char __avx_reserved1[64]; struct __darwin_xmm_reg __fpu_ymmh0; struct __darwin_xmm_reg __fpu_ymmh1; struct __darwin_xmm_reg __fpu_ymmh2; struct __darwin_xmm_reg __fpu_ymmh3; struct __darwin_xmm_reg __fpu_ymmh4; struct __darwin_xmm_reg __fpu_ymmh5; struct __darwin_xmm_reg __fpu_ymmh6; struct __darwin_xmm_reg __fpu_ymmh7; }; struct __darwin_i386_avx512_state { int __fpu_reserved[2]; struct __darwin_fp_control __fpu_fcw; struct __darwin_fp_status __fpu_fsw; __uint8_t __fpu_ftw; __uint8_t __fpu_rsrv1; __uint16_t __fpu_fop; __uint32_t __fpu_ip; __uint16_t __fpu_cs; __uint16_t __fpu_rsrv2; __uint32_t __fpu_dp; __uint16_t __fpu_ds; __uint16_t __fpu_rsrv3; __uint32_t __fpu_mxcsr; __uint32_t __fpu_mxcsrmask; struct __darwin_mmst_reg __fpu_stmm0; struct __darwin_mmst_reg __fpu_stmm1; struct __darwin_mmst_reg __fpu_stmm2; struct __darwin_mmst_reg __fpu_stmm3; struct __darwin_mmst_reg __fpu_stmm4; struct __darwin_mmst_reg __fpu_stmm5; struct __darwin_mmst_reg __fpu_stmm6; struct __darwin_mmst_reg __fpu_stmm7; struct __darwin_xmm_reg __fpu_xmm0; struct __darwin_xmm_reg __fpu_xmm1; struct __darwin_xmm_reg __fpu_xmm2; struct __darwin_xmm_reg __fpu_xmm3; struct __darwin_xmm_reg __fpu_xmm4; struct __darwin_xmm_reg __fpu_xmm5; struct __darwin_xmm_reg __fpu_xmm6; struct __darwin_xmm_reg __fpu_xmm7; char __fpu_rsrv4[14 * 16]; int __fpu_reserved1; char __avx_reserved1[64]; struct __darwin_xmm_reg __fpu_ymmh0; struct __darwin_xmm_reg __fpu_ymmh1; struct __darwin_xmm_reg __fpu_ymmh2; struct __darwin_xmm_reg __fpu_ymmh3; struct __darwin_xmm_reg __fpu_ymmh4; struct __darwin_xmm_reg __fpu_ymmh5; struct __darwin_xmm_reg __fpu_ymmh6; struct __darwin_xmm_reg __fpu_ymmh7; struct __darwin_opmask_reg __fpu_k0; struct __darwin_opmask_reg __fpu_k1; struct __darwin_opmask_reg __fpu_k2; struct __darwin_opmask_reg __fpu_k3; struct __darwin_opmask_reg __fpu_k4; struct __darwin_opmask_reg __fpu_k5; struct __darwin_opmask_reg __fpu_k6; struct __darwin_opmask_reg __fpu_k7; struct __darwin_ymm_reg __fpu_zmmh0; struct __darwin_ymm_reg __fpu_zmmh1; struct __darwin_ymm_reg __fpu_zmmh2; struct __darwin_ymm_reg __fpu_zmmh3; struct __darwin_ymm_reg __fpu_zmmh4; struct __darwin_ymm_reg __fpu_zmmh5; struct __darwin_ymm_reg __fpu_zmmh6; struct __darwin_ymm_reg __fpu_zmmh7; }; struct __darwin_i386_exception_state { __uint16_t __trapno; __uint16_t __cpu; __uint32_t __err; __uint32_t __faultvaddr; }; struct __darwin_x86_debug_state32 { unsigned int __dr0; unsigned int __dr1; unsigned int __dr2; unsigned int __dr3; unsigned int __dr4; unsigned int __dr5; unsigned int __dr6; unsigned int __dr7; }; struct __darwin_x86_thread_state64 { __uint64_t __rax; __uint64_t __rbx; __uint64_t __rcx; __uint64_t __rdx; __uint64_t __rdi; __uint64_t __rsi; __uint64_t __rbp; __uint64_t __rsp; __uint64_t __r8; __uint64_t __r9; __uint64_t __r10; __uint64_t __r11; __uint64_t __r12; __uint64_t __r13; __uint64_t __r14; __uint64_t __r15; __uint64_t __rip; __uint64_t __rflags; __uint64_t __cs; __uint64_t __fs; __uint64_t __gs; }; struct __darwin_x86_float_state64 { int __fpu_reserved[2]; struct __darwin_fp_control __fpu_fcw; struct __darwin_fp_status __fpu_fsw; __uint8_t __fpu_ftw; __uint8_t __fpu_rsrv1; __uint16_t __fpu_fop; __uint32_t __fpu_ip; __uint16_t __fpu_cs; __uint16_t __fpu_rsrv2; __uint32_t __fpu_dp; __uint16_t __fpu_ds; __uint16_t __fpu_rsrv3; __uint32_t __fpu_mxcsr; __uint32_t __fpu_mxcsrmask; struct __darwin_mmst_reg __fpu_stmm0; struct __darwin_mmst_reg __fpu_stmm1; struct __darwin_mmst_reg __fpu_stmm2; struct __darwin_mmst_reg __fpu_stmm3; struct __darwin_mmst_reg __fpu_stmm4; struct __darwin_mmst_reg __fpu_stmm5; struct __darwin_mmst_reg __fpu_stmm6; struct __darwin_mmst_reg __fpu_stmm7; struct __darwin_xmm_reg __fpu_xmm0; struct __darwin_xmm_reg __fpu_xmm1; struct __darwin_xmm_reg __fpu_xmm2; struct __darwin_xmm_reg __fpu_xmm3; struct __darwin_xmm_reg __fpu_xmm4; struct __darwin_xmm_reg __fpu_xmm5; struct __darwin_xmm_reg __fpu_xmm6; struct __darwin_xmm_reg __fpu_xmm7; struct __darwin_xmm_reg __fpu_xmm8; struct __darwin_xmm_reg __fpu_xmm9; struct __darwin_xmm_reg __fpu_xmm10; struct __darwin_xmm_reg __fpu_xmm11; struct __darwin_xmm_reg __fpu_xmm12; struct __darwin_xmm_reg __fpu_xmm13; struct __darwin_xmm_reg __fpu_xmm14; struct __darwin_xmm_reg __fpu_xmm15; char __fpu_rsrv4[6 * 16]; int __fpu_reserved1; }; struct __darwin_x86_avx_state64 { int __fpu_reserved[2]; struct __darwin_fp_control __fpu_fcw; struct __darwin_fp_status __fpu_fsw; __uint8_t __fpu_ftw; __uint8_t __fpu_rsrv1; __uint16_t __fpu_fop; __uint32_t __fpu_ip; __uint16_t __fpu_cs; __uint16_t __fpu_rsrv2; __uint32_t __fpu_dp; __uint16_t __fpu_ds; __uint16_t __fpu_rsrv3; __uint32_t __fpu_mxcsr; __uint32_t __fpu_mxcsrmask; struct __darwin_mmst_reg __fpu_stmm0; struct __darwin_mmst_reg __fpu_stmm1; struct __darwin_mmst_reg __fpu_stmm2; struct __darwin_mmst_reg __fpu_stmm3; struct __darwin_mmst_reg __fpu_stmm4; struct __darwin_mmst_reg __fpu_stmm5; struct __darwin_mmst_reg __fpu_stmm6; struct __darwin_mmst_reg __fpu_stmm7; struct __darwin_xmm_reg __fpu_xmm0; struct __darwin_xmm_reg __fpu_xmm1; struct __darwin_xmm_reg __fpu_xmm2; struct __darwin_xmm_reg __fpu_xmm3; struct __darwin_xmm_reg __fpu_xmm4; struct __darwin_xmm_reg __fpu_xmm5; struct __darwin_xmm_reg __fpu_xmm6; struct __darwin_xmm_reg __fpu_xmm7; struct __darwin_xmm_reg __fpu_xmm8; struct __darwin_xmm_reg __fpu_xmm9; struct __darwin_xmm_reg __fpu_xmm10; struct __darwin_xmm_reg __fpu_xmm11; struct __darwin_xmm_reg __fpu_xmm12; struct __darwin_xmm_reg __fpu_xmm13; struct __darwin_xmm_reg __fpu_xmm14; struct __darwin_xmm_reg __fpu_xmm15; char __fpu_rsrv4[6 * 16]; int __fpu_reserved1; char __avx_reserved1[64]; struct __darwin_xmm_reg __fpu_ymmh0; struct __darwin_xmm_reg __fpu_ymmh1; struct __darwin_xmm_reg __fpu_ymmh2; struct __darwin_xmm_reg __fpu_ymmh3; struct __darwin_xmm_reg __fpu_ymmh4; struct __darwin_xmm_reg __fpu_ymmh5; struct __darwin_xmm_reg __fpu_ymmh6; struct __darwin_xmm_reg __fpu_ymmh7; struct __darwin_xmm_reg __fpu_ymmh8; struct __darwin_xmm_reg __fpu_ymmh9; struct __darwin_xmm_reg __fpu_ymmh10; struct __darwin_xmm_reg __fpu_ymmh11; struct __darwin_xmm_reg __fpu_ymmh12; struct __darwin_xmm_reg __fpu_ymmh13; struct __darwin_xmm_reg __fpu_ymmh14; struct __darwin_xmm_reg __fpu_ymmh15; }; struct __darwin_x86_avx512_state64 { int __fpu_reserved[2]; struct __darwin_fp_control __fpu_fcw; struct __darwin_fp_status __fpu_fsw; __uint8_t __fpu_ftw; __uint8_t __fpu_rsrv1; __uint16_t __fpu_fop; __uint32_t __fpu_ip; __uint16_t __fpu_cs; __uint16_t __fpu_rsrv2; __uint32_t __fpu_dp; __uint16_t __fpu_ds; __uint16_t __fpu_rsrv3; __uint32_t __fpu_mxcsr; __uint32_t __fpu_mxcsrmask; struct __darwin_mmst_reg __fpu_stmm0; struct __darwin_mmst_reg __fpu_stmm1; struct __darwin_mmst_reg __fpu_stmm2; struct __darwin_mmst_reg __fpu_stmm3; struct __darwin_mmst_reg __fpu_stmm4; struct __darwin_mmst_reg __fpu_stmm5; struct __darwin_mmst_reg __fpu_stmm6; struct __darwin_mmst_reg __fpu_stmm7; struct __darwin_xmm_reg __fpu_xmm0; struct __darwin_xmm_reg __fpu_xmm1; struct __darwin_xmm_reg __fpu_xmm2; struct __darwin_xmm_reg __fpu_xmm3; struct __darwin_xmm_reg __fpu_xmm4; struct __darwin_xmm_reg __fpu_xmm5; struct __darwin_xmm_reg __fpu_xmm6; struct __darwin_xmm_reg __fpu_xmm7; struct __darwin_xmm_reg __fpu_xmm8; struct __darwin_xmm_reg __fpu_xmm9; struct __darwin_xmm_reg __fpu_xmm10; struct __darwin_xmm_reg __fpu_xmm11; struct __darwin_xmm_reg __fpu_xmm12; struct __darwin_xmm_reg __fpu_xmm13; struct __darwin_xmm_reg __fpu_xmm14; struct __darwin_xmm_reg __fpu_xmm15; char __fpu_rsrv4[6 * 16]; int __fpu_reserved1; char __avx_reserved1[64]; struct __darwin_xmm_reg __fpu_ymmh0; struct __darwin_xmm_reg __fpu_ymmh1; struct __darwin_xmm_reg __fpu_ymmh2; struct __darwin_xmm_reg __fpu_ymmh3; struct __darwin_xmm_reg __fpu_ymmh4; struct __darwin_xmm_reg __fpu_ymmh5; struct __darwin_xmm_reg __fpu_ymmh6; struct __darwin_xmm_reg __fpu_ymmh7; struct __darwin_xmm_reg __fpu_ymmh8; struct __darwin_xmm_reg __fpu_ymmh9; struct __darwin_xmm_reg __fpu_ymmh10; struct __darwin_xmm_reg __fpu_ymmh11; struct __darwin_xmm_reg __fpu_ymmh12; struct __darwin_xmm_reg __fpu_ymmh13; struct __darwin_xmm_reg __fpu_ymmh14; struct __darwin_xmm_reg __fpu_ymmh15; struct __darwin_opmask_reg __fpu_k0; struct __darwin_opmask_reg __fpu_k1; struct __darwin_opmask_reg __fpu_k2; struct __darwin_opmask_reg __fpu_k3; struct __darwin_opmask_reg __fpu_k4; struct __darwin_opmask_reg __fpu_k5; struct __darwin_opmask_reg __fpu_k6; struct __darwin_opmask_reg __fpu_k7; struct __darwin_ymm_reg __fpu_zmmh0; struct __darwin_ymm_reg __fpu_zmmh1; struct __darwin_ymm_reg __fpu_zmmh2; struct __darwin_ymm_reg __fpu_zmmh3; struct __darwin_ymm_reg __fpu_zmmh4; struct __darwin_ymm_reg __fpu_zmmh5; struct __darwin_ymm_reg __fpu_zmmh6; struct __darwin_ymm_reg __fpu_zmmh7; struct __darwin_ymm_reg __fpu_zmmh8; struct __darwin_ymm_reg __fpu_zmmh9; struct __darwin_ymm_reg __fpu_zmmh10; struct __darwin_ymm_reg __fpu_zmmh11; struct __darwin_ymm_reg __fpu_zmmh12; struct __darwin_ymm_reg __fpu_zmmh13; struct __darwin_ymm_reg __fpu_zmmh14; struct __darwin_ymm_reg __fpu_zmmh15; struct __darwin_zmm_reg __fpu_zmm16; struct __darwin_zmm_reg __fpu_zmm17; struct __darwin_zmm_reg __fpu_zmm18; struct __darwin_zmm_reg __fpu_zmm19; struct __darwin_zmm_reg __fpu_zmm20; struct __darwin_zmm_reg __fpu_zmm21; struct __darwin_zmm_reg __fpu_zmm22; struct __darwin_zmm_reg __fpu_zmm23; struct __darwin_zmm_reg __fpu_zmm24; struct __darwin_zmm_reg __fpu_zmm25; struct __darwin_zmm_reg __fpu_zmm26; struct __darwin_zmm_reg __fpu_zmm27; struct __darwin_zmm_reg __fpu_zmm28; struct __darwin_zmm_reg __fpu_zmm29; struct __darwin_zmm_reg __fpu_zmm30; struct __darwin_zmm_reg __fpu_zmm31; }; struct __darwin_x86_exception_state64 { __uint16_t __trapno; __uint16_t __cpu; __uint32_t __err; __uint64_t __faultvaddr; }; struct __darwin_x86_debug_state64 { __uint64_t __dr0; __uint64_t __dr1; __uint64_t __dr2; __uint64_t __dr3; __uint64_t __dr4; __uint64_t __dr5; __uint64_t __dr6; __uint64_t __dr7; }; struct __darwin_x86_cpmu_state64 { __uint64_t __ctrs [16]; }; struct __darwin_mcontext32 { struct __darwin_i386_exception_state __es; struct __darwin_i386_thread_state __ss; struct __darwin_i386_float_state __fs; }; struct __darwin_mcontext_avx32 { struct __darwin_i386_exception_state __es; struct __darwin_i386_thread_state __ss; struct __darwin_i386_avx_state __fs; }; struct __darwin_mcontext_avx512_32 { struct __darwin_i386_exception_state __es; struct __darwin_i386_thread_state __ss; struct __darwin_i386_avx512_state __fs; }; struct __darwin_mcontext64 { struct __darwin_x86_exception_state64 __es; struct __darwin_x86_thread_state64 __ss; struct __darwin_x86_float_state64 __fs; }; struct __darwin_mcontext_avx64 { struct __darwin_x86_exception_state64 __es; struct __darwin_x86_thread_state64 __ss; struct __darwin_x86_avx_state64 __fs; }; struct __darwin_mcontext_avx512_64 { struct __darwin_x86_exception_state64 __es; struct __darwin_x86_thread_state64 __ss; struct __darwin_x86_avx512_state64 __fs; }; typedef struct __darwin_mcontext64 *mcontext_t; typedef __darwin_pthread_attr_t pthread_attr_t; struct __darwin_sigaltstack { void *ss_sp; __darwin_size_t ss_size; int ss_flags; }; typedef struct __darwin_sigaltstack stack_t; struct __darwin_ucontext { int uc_onstack; __darwin_sigset_t uc_sigmask; struct __darwin_sigaltstack uc_stack; struct __darwin_ucontext *uc_link; __darwin_size_t uc_mcsize; struct __darwin_mcontext64 *uc_mcontext; }; typedef struct __darwin_ucontext ucontext_t; typedef __darwin_sigset_t sigset_t; typedef __darwin_size_t size_t; typedef __darwin_uid_t uid_t; union sigval { int sival_int; void *sival_ptr; }; struct sigevent { int sigev_notify; int sigev_signo; union sigval sigev_value; void (*sigev_notify_function)(union sigval); pthread_attr_t *sigev_notify_attributes; }; typedef struct __siginfo { int si_signo; int si_errno; int si_code; pid_t si_pid; uid_t si_uid; int si_status; void *si_addr; union sigval si_value; long si_band; unsigned long __pad[7]; } siginfo_t; union __sigaction_u { void (*__sa_handler)(int); void (*__sa_sigaction)(int, struct __siginfo *, void *); }; struct __sigaction { union __sigaction_u __sigaction_u; void (*sa_tramp)(void *, int, int, siginfo_t *, void *); sigset_t sa_mask; int sa_flags; }; struct sigaction { union __sigaction_u __sigaction_u; sigset_t sa_mask; int sa_flags; }; typedef void (*sig_t)(int); struct sigvec { void (*sv_handler)(int); int sv_mask; int sv_flags; }; struct sigstack { char *ss_sp; int ss_onstack; }; void (*signal(int, void (*)(int)))(int); typedef unsigned char uint8_t; typedef unsigned short uint16_t; typedef unsigned int uint32_t; typedef unsigned long long uint64_t; typedef int8_t int_least8_t; typedef int16_t int_least16_t; typedef int32_t int_least32_t; typedef int64_t int_least64_t; typedef uint8_t uint_least8_t; typedef uint16_t uint_least16_t; typedef uint32_t uint_least32_t; typedef uint64_t uint_least64_t; typedef int8_t int_fast8_t; typedef int16_t int_fast16_t; typedef int32_t int_fast32_t; typedef int64_t int_fast64_t; typedef uint8_t uint_fast8_t; typedef uint16_t uint_fast16_t; typedef uint32_t uint_fast32_t; typedef uint64_t uint_fast64_t; typedef long int intmax_t; typedef long unsigned int uintmax_t; struct timeval { __darwin_time_t tv_sec; __darwin_suseconds_t tv_usec; }; typedef __uint64_t rlim_t; struct rusage { struct timeval ru_utime; struct timeval ru_stime; long ru_maxrss; long ru_ixrss; long ru_idrss; long ru_isrss; long ru_minflt; long ru_majflt; long ru_nswap; long ru_inblock; long ru_oublock; long ru_msgsnd; long ru_msgrcv; long ru_nsignals; long ru_nvcsw; long ru_nivcsw; }; typedef void *rusage_info_t; struct rusage_info_v0 { uint8_t ri_uuid[16]; uint64_t ri_user_time; uint64_t ri_system_time; uint64_t ri_pkg_idle_wkups; uint64_t ri_interrupt_wkups; uint64_t ri_pageins; uint64_t ri_wired_size; uint64_t ri_resident_size; uint64_t ri_phys_footprint; uint64_t ri_proc_start_abstime; uint64_t ri_proc_exit_abstime; }; struct rusage_info_v1 { uint8_t ri_uuid[16]; uint64_t ri_user_time; uint64_t ri_system_time; uint64_t ri_pkg_idle_wkups; uint64_t ri_interrupt_wkups; uint64_t ri_pageins; uint64_t ri_wired_size; uint64_t ri_resident_size; uint64_t ri_phys_footprint; uint64_t ri_proc_start_abstime; uint64_t ri_proc_exit_abstime; uint64_t ri_child_user_time; uint64_t ri_child_system_time; uint64_t ri_child_pkg_idle_wkups; uint64_t ri_child_interrupt_wkups; uint64_t ri_child_pageins; uint64_t ri_child_elapsed_abstime; }; struct rusage_info_v2 { uint8_t ri_uuid[16]; uint64_t ri_user_time; uint64_t ri_system_time; uint64_t ri_pkg_idle_wkups; uint64_t ri_interrupt_wkups; uint64_t ri_pageins; uint64_t ri_wired_size; uint64_t ri_resident_size; uint64_t ri_phys_footprint; uint64_t ri_proc_start_abstime; uint64_t ri_proc_exit_abstime; uint64_t ri_child_user_time; uint64_t ri_child_system_time; uint64_t ri_child_pkg_idle_wkups; uint64_t ri_child_interrupt_wkups; uint64_t ri_child_pageins; uint64_t ri_child_elapsed_abstime; uint64_t ri_diskio_bytesread; uint64_t ri_diskio_byteswritten; }; struct rusage_info_v3 { uint8_t ri_uuid[16]; uint64_t ri_user_time; uint64_t ri_system_time; uint64_t ri_pkg_idle_wkups; uint64_t ri_interrupt_wkups; uint64_t ri_pageins; uint64_t ri_wired_size; uint64_t ri_resident_size; uint64_t ri_phys_footprint; uint64_t ri_proc_start_abstime; uint64_t ri_proc_exit_abstime; uint64_t ri_child_user_time; uint64_t ri_child_system_time; uint64_t ri_child_pkg_idle_wkups; uint64_t ri_child_interrupt_wkups; uint64_t ri_child_pageins; uint64_t ri_child_elapsed_abstime; uint64_t ri_diskio_bytesread; uint64_t ri_diskio_byteswritten; uint64_t ri_cpu_time_qos_default; uint64_t ri_cpu_time_qos_maintenance; uint64_t ri_cpu_time_qos_background; uint64_t ri_cpu_time_qos_utility; uint64_t ri_cpu_time_qos_legacy; uint64_t ri_cpu_time_qos_user_initiated; uint64_t ri_cpu_time_qos_user_interactive; uint64_t ri_billed_system_time; uint64_t ri_serviced_system_time; }; struct rusage_info_v4 { uint8_t ri_uuid[16]; uint64_t ri_user_time; uint64_t ri_system_time; uint64_t ri_pkg_idle_wkups; uint64_t ri_interrupt_wkups; uint64_t ri_pageins; uint64_t ri_wired_size; uint64_t ri_resident_size; uint64_t ri_phys_footprint; uint64_t ri_proc_start_abstime; uint64_t ri_proc_exit_abstime; uint64_t ri_child_user_time; uint64_t ri_child_system_time; uint64_t ri_child_pkg_idle_wkups; uint64_t ri_child_interrupt_wkups; uint64_t ri_child_pageins; uint64_t ri_child_elapsed_abstime; uint64_t ri_diskio_bytesread; uint64_t ri_diskio_byteswritten; uint64_t ri_cpu_time_qos_default; uint64_t ri_cpu_time_qos_maintenance; uint64_t ri_cpu_time_qos_background; uint64_t ri_cpu_time_qos_utility; uint64_t ri_cpu_time_qos_legacy; uint64_t ri_cpu_time_qos_user_initiated; uint64_t ri_cpu_time_qos_user_interactive; uint64_t ri_billed_system_time; uint64_t ri_serviced_system_time; uint64_t ri_logical_writes; uint64_t ri_lifetime_max_phys_footprint; uint64_t ri_instructions; uint64_t ri_cycles; uint64_t ri_billed_energy; uint64_t ri_serviced_energy; uint64_t ri_unused[2]; }; typedef struct rusage_info_v4 rusage_info_current; struct rlimit { rlim_t rlim_cur; rlim_t rlim_max; }; struct proc_rlimit_control_wakeupmon { uint32_t wm_flags; int32_t wm_rate; }; int getpriority(int, id_t); int getiopolicy_np(int, int); int getrlimit(int, struct rlimit *) __asm("_" "getrlimit" ); int getrusage(int, struct rusage *); int setpriority(int, id_t, int); int setiopolicy_np(int, int, int); int setrlimit(int, const struct rlimit *) __asm("_" "setrlimit" ); static inline __uint16_t _OSSwapInt16(__uint16_t _data) { return ((__uint16_t ) ((_data << 8) | (_data >> 8))); } static inline __uint32_t _OSSwapInt32(__uint32_t _data) { __asm__ ("bswap %0" : "+r" (_data)); return _data; } static inline __uint64_t _OSSwapInt64(__uint64_t _data) { __asm__ ("bswap %0" : "+r" (_data)); return _data; } union wait { int w_status; struct { unsigned int w_Termsig :7, w_Coredump :1, w_Retcode :8, w_Filler :16; } w_T; struct { unsigned int w_Stopval :8, w_Stopsig :8, w_Filler :16; } w_S; }; pid_t wait(int *) __asm("_" "wait" ); pid_t waitpid(pid_t, int *, int) __asm("_" "waitpid" ); int waitid(idtype_t, id_t, siginfo_t *, int) __asm("_" "waitid" ); pid_t wait3(int *, int, struct rusage *); pid_t wait4(pid_t, int *, int, struct rusage *); void *alloca(size_t); typedef __darwin_ct_rune_t ct_rune_t; typedef __darwin_rune_t rune_t; typedef __darwin_wchar_t wchar_t; typedef struct { int quot; int rem; } div_t; typedef struct { long quot; long rem; } ldiv_t; typedef struct { long long quot; long long rem; } lldiv_t; extern int __mb_cur_max; void abort(void) __attribute__((noreturn)); int abs(int) __attribute__((const)); int atexit(void (*)(void)); double atof(const char *); int atoi(const char *); long atol(const char *); long long atoll(const char *); void *bsearch(const void *__key, const void *__base, size_t __nel, size_t __width, int (*__compar)(const void *, const void *)); void *calloc(size_t __count, size_t __size) __attribute__((__warn_unused_result__)) __attribute__((alloc_size(1,2))); div_t div(int, int) __attribute__((const)); void exit(int) __attribute__((noreturn)); void free(void *); char *getenv(const char *); long labs(long) __attribute__((const)); ldiv_t ldiv(long, long) __attribute__((const)); long long llabs(long long); lldiv_t lldiv(long long, long long); void *malloc(size_t __size) __attribute__((__warn_unused_result__)) __attribute__((alloc_size(1))); int mblen(const char *__s, size_t __n); size_t mbstowcs(wchar_t * restrict, const char * restrict, size_t); int mbtowc(wchar_t * restrict, const char * restrict, size_t); int posix_memalign(void **__memptr, size_t __alignment, size_t __size); void qsort(void *__base, size_t __nel, size_t __width, int (*__compar)(const void *, const void *)); int rand(void); void *realloc(void *__ptr, size_t __size) __attribute__((__warn_unused_result__)) __attribute__((alloc_size(2))); void srand(unsigned); double strtod(const char *, char **) __asm("_" "strtod" ); float strtof(const char *, char **) __asm("_" "strtof" ); long strtol(const char *__str, char **__endptr, int __base); long double strtold(const char *, char **); long long strtoll(const char *__str, char **__endptr, int __base); unsigned long strtoul(const char *__str, char **__endptr, int __base); unsigned long long strtoull(const char *__str, char **__endptr, int __base); int system(const char *) __asm("_" "system" ); size_t wcstombs(char * restrict, const wchar_t * restrict, size_t); int wctomb(char *, wchar_t); void _Exit(int) __attribute__((noreturn)); long a64l(const char *); double drand48(void); char *ecvt(double, int, int *restrict, int *restrict); double erand48(unsigned short[3]); char *fcvt(double, int, int *restrict, int *restrict); char *gcvt(double, int, char *); int getsubopt(char **, char * const *, char **); int grantpt(int); char *initstate(unsigned, char *, size_t); long jrand48(unsigned short[3]); char *l64a(long); void lcong48(unsigned short[7]); long lrand48(void); char *mktemp(char *); int mkstemp(char *); long mrand48(void); long nrand48(unsigned short[3]); int posix_openpt(int); char *ptsname(int); int ptsname_r(int fildes, char *buffer, size_t buflen); int putenv(char *) __asm("_" "putenv" ); long random(void); int rand_r(unsigned *); char *realpath(const char * restrict, char * restrict) __asm("_" "realpath" "$DARWIN_EXTSN"); unsigned short *seed48(unsigned short[3]); int setenv(const char * __name, const char * __value, int __overwrite) __asm("_" "setenv" ); void setkey(const char *) __asm("_" "setkey" ); char *setstate(const char *); void srand48(long); void srandom(unsigned); int unlockpt(int); int unsetenv(const char *) __asm("_" "unsetenv" ); typedef __darwin_dev_t dev_t; typedef __darwin_mode_t mode_t; uint32_t arc4random(void); void arc4random_addrandom(unsigned char *, int) ; void arc4random_buf(void * __buf, size_t __nbytes); void arc4random_stir(void); uint32_t arc4random_uniform(uint32_t __upper_bound); char *cgetcap(char *, const char *, int); int cgetclose(void); int cgetent(char **, char **, const char *); int cgetfirst(char **, char **); int cgetmatch(const char *, const char *); int cgetnext(char **, char **); int cgetnum(char *, const char *, long *); int cgetset(const char *); int cgetstr(char *, const char *, char **); int cgetustr(char *, const char *, char **); int daemon(int, int) __asm("_" "daemon" "$1050") __attribute__((deprecated("Use posix_spawn APIs instead."))); char *devname(dev_t, mode_t); char *devname_r(dev_t, mode_t, char *buf, int len); char *getbsize(int *, long *); int getloadavg(double[], int); const char *getprogname(void); int heapsort(void *__base, size_t __nel, size_t __width, int (*__compar)(const void *, const void *)); int mergesort(void *__base, size_t __nel, size_t __width, int (*__compar)(const void *, const void *)); void psort(void *__base, size_t __nel, size_t __width, int (*__compar)(const void *, const void *)); void psort_r(void *__base, size_t __nel, size_t __width, void *, int (*__compar)(void *, const void *, const void *)); void qsort_r(void *__base, size_t __nel, size_t __width, void *, int (*__compar)(void *, const void *, const void *)); int radixsort(const unsigned char **__base, int __nel, const unsigned char *__table, unsigned __endbyte); void setprogname(const char *); int sradixsort(const unsigned char **__base, int __nel, const unsigned char *__table, unsigned __endbyte); void sranddev(void); void srandomdev(void); void *reallocf(void *__ptr, size_t __size) __attribute__((alloc_size(2))); long long strtoq(const char *__str, char **__endptr, int __base); unsigned long long strtouq(const char *__str, char **__endptr, int __base); extern char *suboptarg; void *valloc(size_t) __attribute__((alloc_size(1))); int foo() { return 100; } void bar(int ARG) { int **p; int u[100]; int v[100]; p = (int **) malloc(sizeof(int **) * 10); p[0] = u; p[1] = v; int X = 0; #pragma omp parallel { int i; int t1 = 15; int max = t1 + 85; int t2 = 100; int min = t2 - 100; int j; #pragma omp for for (i = 0; i < max; i += 1) { for (j = 0; j < 100; j++) { p[i][j] = 10; } } #pragma omp barrier #pragma omp for for (i = min; i < 100 + 1; i++) { for (j = 0; j < 100; j++) { X = p[i][j]; } } } } int main() { bar(100); }
GB_unaryop__abs_fp64_int64.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__abs_fp64_int64 // op(A') function: GB_tran__abs_fp64_int64 // C type: double // A type: int64_t // cast: double cij = (double) aij // unaryop: cij = fabs (aij) #define GB_ATYPE \ int64_t #define GB_CTYPE \ double // 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 = fabs (x) ; // casting #define GB_CASTING(z, x) \ double z = (double) 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_ABS || GxB_NO_FP64 || GxB_NO_INT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__abs_fp64_int64 ( double *restrict Cx, const int64_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__abs_fp64_int64 ( 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
DRB114-if-orig-yes.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* When if() evalutes to true, this program has data races due to true dependence within the loop at 65. Data race pair: a[i+1]@66:5 vs. a[i]@66:12 */ #include <stdlib.h> #include <stdio.h> #include <time.h> void task(int *a, int i) { a[i+1]=a[i]+1; } int main(int argc, char* argv[]) { int i; int len=100; int a[100]; #pragma omp parallel for private(i) for (i=0;i<len;i++) a[i]=i; srand(time(NULL)); for (i=0;i<len-1;i++) task(&a[0], i); printf("a[50]=%d\n", a[50]); return 0; }
pr38704.c
// RUN: %libomptarget-compile-run-and-check-generic // Clang 6.0 doesn't use the new map interface, undefined behavior when // the compiler emits "old" interface code for structures. // UNSUPPORTED: clang-6 #include <stdio.h> #include <stdlib.h> typedef struct { int *ptr1; int *ptr2; } StructWithPtrs; int main(int argc, char *argv[]) { StructWithPtrs s, s2; s.ptr1 = malloc(sizeof(int)); s.ptr2 = malloc(2 * sizeof(int)); s2.ptr1 = malloc(sizeof(int)); s2.ptr2 = malloc(2 * sizeof(int)); #pragma omp target enter data map(to: s2.ptr2[0:1]) #pragma omp target map(s.ptr1[0:1], s.ptr2[0:2]) { s.ptr1[0] = 1; s.ptr2[0] = 2; s.ptr2[1] = 3; } #pragma omp target exit data map(from: s2.ptr1[0:1], s2.ptr2[0:1]) // CHECK: s.ptr1[0] = 1 // CHECK: s.ptr2[0] = 2 // CHECK: s.ptr2[1] = 3 printf("s.ptr1[0] = %d\n", s.ptr1[0]); printf("s.ptr2[0] = %d\n", s.ptr2[0]); printf("s.ptr2[1] = %d\n", s.ptr2[1]); free(s.ptr1); free(s.ptr2); free(s2.ptr1); free(s2.ptr2); return 0; }
pr27573.c
/* PR middle-end/27573 */ /* { dg-do compile } */ /* { dg-require-profiling "-fprofile-generate" } */ /* { dg-options "-O2 -fopenmp -fprofile-generate" } */ extern int puts (const char *); int main (void) { int i, j = 8; #pragma omp parallel { puts ("foo"); for (i = 1; i < j - 1; i++) ; } return 0; }
target-5.c
#include <omp.h> #include <stdlib.h> int main () { int d_o = omp_get_dynamic (); int n_o = omp_get_nested (); omp_sched_t s_o; int c_o; omp_get_schedule (&s_o, &c_o); int m_o = omp_get_max_threads (); omp_set_dynamic (1); omp_set_nested (1); omp_set_schedule (omp_sched_static, 2); omp_set_num_threads (4); int d = omp_get_dynamic (); int n = omp_get_nested (); omp_sched_t s; int c; omp_get_schedule (&s, &c); int m = omp_get_max_threads (); if (!omp_is_initial_device ()) abort (); #pragma omp target if (0) { omp_sched_t s_c; int c_c; omp_get_schedule (&s_c, &c_c); if (d_o != omp_get_dynamic () || n_o != omp_get_nested () || s_o != s_c || c_o != c_c || m_o != omp_get_max_threads ()) abort (); omp_set_dynamic (0); omp_set_nested (0); omp_set_schedule (omp_sched_dynamic, 4); omp_set_num_threads (2); if (!omp_is_initial_device ()) abort (); } if (!omp_is_initial_device ()) abort (); omp_sched_t s_c; int c_c; omp_get_schedule (&s_c, &c_c); if (d != omp_get_dynamic () || n != omp_get_nested () || s != s_c || c != c_c || m != omp_get_max_threads ()) abort (); #pragma omp target if (0) #pragma omp teams { omp_sched_t s_c; int c_c; omp_get_schedule (&s_c, &c_c); if (d_o != omp_get_dynamic () || n_o != omp_get_nested () || s_o != s_c || c_o != c_c || m_o != omp_get_max_threads ()) abort (); omp_set_dynamic (0); omp_set_nested (0); omp_set_schedule (omp_sched_dynamic, 4); omp_set_num_threads (2); if (!omp_is_initial_device ()) abort (); } if (!omp_is_initial_device ()) abort (); omp_get_schedule (&s_c, &c_c); if (d != omp_get_dynamic () || n != omp_get_nested () || s != s_c || c != c_c || m != omp_get_max_threads ()) abort (); return 0; }
GB_unaryop__minv_fp64_int8.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_fp64_int8 // op(A') function: GB_tran__minv_fp64_int8 // C type: double // A type: int8_t // cast: double cij = (double) aij // unaryop: cij = 1./aij #define GB_ATYPE \ int8_t #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = 1./x ; // casting #define GB_CASTING(z, x) \ double z = (double) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_FP64 || GxB_NO_INT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_fp64_int8 ( double *restrict Cx, const int8_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__minv_fp64_int8 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
mpncpdq.c
/* $Header$ */ /* mpncpdq -- netCDF pack, re-dimension, query */ /* Purpose: Pack, re-dimension, query single netCDF file and output to a single file */ /* Copyright (C) 1995--present Charlie Zender This file is part of NCO, the netCDF Operators. NCO is free software. You may redistribute and/or modify NCO under the terms of the 3-Clause BSD License. You are permitted to link NCO with the HDF, netCDF, OPeNDAP, and UDUnits libraries and to distribute the resulting executables under the terms of the BSD, but in addition obeying the extra stipulations of the HDF, netCDF, OPeNDAP, and UDUnits licenses. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 3-Clause BSD License for more details. The original author of this software, Charlie Zender, seeks to improve it with your suggestions, contributions, bug-reports, and patches. Please contact the NCO project at http://nco.sf.net or write to Charlie Zender Department of Earth System Science University of California, Irvine Irvine, CA 92697-3100 */ /* Usage: ncpdq -O -D 3 -a lat,lev,lon -v three_dmn_var ~/nco/data/in.nc ~/foo.nc;ncks -P ~/foo.nc ncpdq -O -D 3 -a lon,lev,lat -v three_dmn_var ~/nco/data/in.nc ~/foo.nc;ncks -P ~/foo.nc ncpdq -O -D 3 -a lon,time -x -v three_double_dmn ~/nco/data/in.nc ~/foo.nc;ncks -P ~/foo.nc ncpdq -O -D 3 -P all_new ~/nco/data/in.nc ~/foo.nc ncpdq -O -D 3 -P all_xst ~/nco/data/in.nc ~/foo.nc ncpdq -O -D 3 -P xst_new ~/nco/data/in.nc ~/foo.nc ncpdq -O -D 3 -P upk ~/nco/data/in.nc ~/foo.nc */ #ifdef HAVE_CONFIG_H # include <config.h> /* Autotools tokens */ #endif /* !HAVE_CONFIG_H */ /* Standard C headers */ #include <math.h> /* sin cos cos sin 3.14159 */ #include <stdio.h> /* stderr, FILE, NULL, etc. */ #include <stdlib.h> /* atof, atoi, malloc, getopt */ #include <string.h> /* strcmp() */ #include <time.h> /* machine time */ #include <unistd.h> /* POSIX stuff */ #ifndef HAVE_GETOPT_LONG # include "nco_getopt.h" #else /* HAVE_GETOPT_LONG */ # ifdef HAVE_GETOPT_H # include <getopt.h> # endif /* !HAVE_GETOPT_H */ #endif /* HAVE_GETOPT_LONG */ /* 3rd party vendors */ #include <netcdf.h> /* netCDF definitions and C library */ #ifdef ENABLE_MPI #include <mpi.h> /* MPI definitions */ #include "nco_mpi.h" /* MPI utilities */ #endif /* !ENABLE_MPI */ /* #define MAIN_PROGRAM_FILE MUST precede #include libnco.h */ #define MAIN_PROGRAM_FILE #include "libnco.h" /* netCDF Operator (NCO) library */ int main(int argc,char **argv) { aed_sct *aed_lst_add_fst=NULL_CEWI; aed_sct *aed_lst_scl_fct=NULL_CEWI; char **dmn_rdr_lst_in=NULL_CEWI; /* Option a */ char **fl_lst_abb=NULL; /* Option n */ char **fl_lst_in=NULL_CEWI; char **var_lst_in=NULL_CEWI; char *cmd_ln; char *cnk_arg[NC_MAX_DIMS]; char *cnk_map_sng=NULL_CEWI; /* [sng] Chunking map */ char *cnk_plc_sng=NULL_CEWI; /* [sng] Chunking policy */ char *fl_in=NULL; char *fl_out=NULL; /* Option o */ char *fl_out_tmp=NULL_CEWI; char *fl_pth=NULL; /* Option p */ char *fl_pth_lcl=NULL; /* Option l */ char *lmt_arg[NC_MAX_DIMS]; char *nco_pck_plc_sng=NULL_CEWI; /* [sng] Packing policy Option P */ char *nco_pck_map_sng=NULL_CEWI; /* [sng] Packing map Option M */ char *opt_crr=NULL; /* [sng] String representation of current long-option name */ char *optarg_lcl=NULL; /* [sng] Local copy of system optarg */ char *rec_dmn_nm_in=NULL; /* [sng] Record dimension name, original */ char *rec_dmn_nm_out=NULL; /* [sng] Record dimension name, re-ordered */ char *rec_dmn_nm_out_crr=NULL; /* [sng] Name of record dimension, if any, required by re-order */ char *sng_cnv_rcd=NULL_CEWI; /* [sng] strtol()/strtoul() return code */ char add_fst_sng[]="add_offset"; /* [sng] Unidata standard string for add offset */ char scl_fct_sng[]="scale_factor"; /* [sng] Unidata standard string for scale factor */ const char * const CVS_Id="$Id$"; const char * const CVS_Revision="$Revision$"; const char * const opt_sht_lst="34567Aa:CcD:d:FhL:l:M:Oo:P:p:RrSt:v:Ux-:"; cnk_dmn_sct **cnk_dmn=NULL_CEWI; dmn_sct **dim=NULL_CEWI; dmn_sct **dmn_out; dmn_sct **dmn_rdr=NULL; /* [sct] Dimension structures to be re-ordered */ extern char *optarg; extern int optind; /* Using naked stdin/stdout/stderr in parallel region generates warning Copy appropriate filehandle to variable scoped shared in parallel clause */ FILE * const fp_stderr=stderr; /* [fl] stderr filehandle CEWI */ FILE * const fp_stdout=stdout; /* [fl] stdout filehandle CEWI */ int **dmn_idx_out_in=NULL; /* [idx] Dimension correspondence, output->input CEWI */ int *in_id_arr; int abb_arg_nbr=0; int cnk_map=nco_cnk_map_nil; /* [enm] Chunking map */ int cnk_nbr=0; /* [nbr] Number of chunk sizes */ int cnk_plc=nco_cnk_plc_nil; /* [enm] Chunking policy */ int dfl_lvl=NCO_DFL_LVL_UNDEFINED; /* [enm] Deflate level */ int dmn_out_idx; /* [idx] Index over output dimension list */ int dmn_out_idx_rec_in=NCO_REC_DMN_UNDEFINED; /* [idx] Record dimension index in output dimension list, original */ int dmn_rdr_nbr=0; /* [nbr] Number of dimension to re-order */ int dmn_rdr_nbr_in=0; /* [nbr] Original number of dimension to re-order */ int dmn_rdr_nbr_utl=0; /* [nbr] Number of dimension to re-order, utilized */ int fl_idx=int_CEWI; int fl_nbr=0; int fl_in_fmt; /* [enm] Input file format */ int fl_out_fmt=NCO_FORMAT_UNDEFINED; /* [enm] Output file format */ int fll_md_old; /* [enm] Old fill mode */ int gaa_nbr=0; /* [nbr] Number of global attributes to add */ int idx=int_CEWI; int idx_rdr=int_CEWI; int in_id; int lmt_nbr=0; /* Option d. NB: lmt_nbr gets incremented */ int log_lvl=0; /* [enm] netCDF library debugging verbosity [0..5] */ int md_open; /* [enm] Mode flag for nc_open() call */ int nbr_dmn_fl; int nbr_dmn_out; int nbr_dmn_xtr; int nbr_var_fix; /* nbr_var_fix gets incremented */ int nbr_var_fl; int nbr_var_prc; /* nbr_var_prc gets incremented */ int xtr_nbr=0; /* xtr_nbr won't otherwise be set for -c with no -v */ int nco_pck_map=nco_pck_map_flt_sht; /* [enm] Packing map */ int nco_pck_plc=nco_pck_plc_nil; /* [enm] Packing policy */ int opt; int out_id; int rcd=NC_NOERR; /* [rcd] Return code */ int rec_dmn_id_in=NCO_REC_DMN_UNDEFINED; /* [id] Record dimension ID in input file */ int thr_idx; /* [idx] Index of current thread */ int thr_nbr=int_CEWI; /* [nbr] Thread number Option t */ int var_lst_in_nbr=0; lmt_sct **aux=NULL_CEWI; /* Auxiliary coordinate limits */ lmt_sct **lmt=NULL_CEWI; lmt_all_sct **lmt_all_lst=NULL_CEWI; /* List of *lmt_all structures */ nco_bool **dmn_rvr_in=NULL; /* [flg] Reverse dimension */ nco_bool *dmn_rvr_rdr=NULL; /* [flg] Reverse dimension */ cnv_sct *cnv; /* [sct] Convention structure */ nco_bool EXCLUDE_INPUT_LIST=False; /* Option c */ nco_bool EXTRACT_ALL_COORDINATES=False; /* Option c */ nco_bool EXTRACT_ASSOCIATED_COORDINATES=True; /* Option C */ nco_bool FL_RTR_RMT_LCN; nco_bool FL_LST_IN_FROM_STDIN=False; /* [flg] fl_lst_in comes from stdin */ nco_bool FORCE_APPEND=False; /* Option A */ nco_bool FORCE_OVERWRITE=False; /* Option O */ nco_bool FORTRAN_IDX_CNV=False; /* Option F */ nco_bool HISTORY_APPEND=True; /* Option h */ nco_bool HPSS_TRY=False; /* [flg] Search HPSS for unfound files */ nco_bool REDEFINED_RECORD_DIMENSION=False; /* [flg] Re-defined record dimension */ nco_bool RAM_CREATE=False; /* [flg] Create file in RAM */ nco_bool RAM_OPEN=False; /* [flg] Open (netCDF3-only) file(s) in RAM */ nco_bool SHARE_CREATE=False; /* [flg] Create (netCDF3-only) file(s) with unbuffered I/O */ nco_bool SHARE_OPEN=False; /* [flg] Open (netCDF3-only) file(s) with unbuffered I/O */ nco_bool RM_RMT_FL_PST_PRC=True; /* Option R */ nco_bool WRT_TMP_FL=True; /* [flg] Write output to temporary file */ nco_bool flg_mmr_cln=False; /* [flg] Clean memory prior to exit */ nm_id_sct *dmn_lst; nm_id_sct *dmn_rdr_lst; nm_id_sct *xtr_lst=NULL; /* xtr_lst may be alloc()'d from NULL with -c option */ size_t bfr_sz_hnt=NC_SIZEHINT_DEFAULT; /* [B] Buffer size hint */ size_t cnk_csh_byt=NCO_CNK_CSH_BYT_DFL; /* [B] Chunk cache size */ size_t cnk_min_byt=NCO_CNK_SZ_MIN_BYT_DFL; /* [B] Minimize size of variable to chunk */ size_t cnk_sz_byt=0UL; /* [B] Chunk size in bytes */ size_t cnk_sz_scl=0UL; /* [nbr] Chunk size scalar */ size_t hdr_pad=0UL; /* [B] Pad at end of header section */ var_sct **var; var_sct **var_fix; var_sct **var_fix_out; var_sct **var_out; var_sct **var_prc; var_sct **var_prc_out; #ifdef ENABLE_MPI /* Declare all MPI-specific variables here */ MPI_Status mpi_stt; /* [enm] Status check to decode msg_tag_typ */ nco_bool TKN_WRT_FREE=True; /* [flg] Write-access to output file is available */ int fl_nm_lng; /* [nbr] Output file name length */ int msg_bfr[msg_bfr_lng]; /* [bfr] Buffer containing var, idx, tkn_wrt_rsp */ int jdx=0; /* [idx] For MPI indexing local variables */ /* csz: fxm why 60? make dynamic? */ int lcl_idx_lst[60]; /* [arr] Array containing indices of variables processed at each Worker */ int lcl_nbr_var=0; /* [nbr] Count of variables processes at each Worker */ int msg_tag_typ; /* [enm] MPI message tag type */ int prc_rnk; /* [idx] Process rank */ int prc_nbr=0; /* [nbr] Number of MPI processes */ int tkn_wrt_rsp; /* [enm] Response to request for write token */ int var_wrt_nbr=0; /* [nbr] Variables written to output file until now */ int rnk_wrk; /* [idx] Worker rank */ int wrk_id_bfr[wrk_id_bfr_lng]; /* [bfr] Buffer for rnk_wrk */ #endif /* !ENABLE_MPI */ static struct option opt_lng[]={ /* Structure ordered by short option key if possible */ /* Long options with no argument, no short option counterpart */ {"ram_all",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) in RAM */ {"create_ram",no_argument,0,0}, /* [flg] Create file in RAM */ {"open_ram",no_argument,0,0}, /* [flg] Open (netCDF3) file(s) in RAM */ {"diskless_all",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) in RAM */ {"share_all",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) with unbuffered I/O */ {"create_share",no_argument,0,0}, /* [flg] Create (netCDF3) file(s) with unbuffered I/O */ {"open_share",no_argument,0,0}, /* [flg] Open (netCDF3) file(s) with unbuffered I/O */ {"unbuffered_io",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) with unbuffered I/O */ {"uio",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) with unbuffered I/O */ {"wrt_tmp_fl",no_argument,0,0}, /* [flg] Write output to temporary file */ {"write_tmp_fl",no_argument,0,0}, /* [flg] Write output to temporary file */ {"no_tmp_fl",no_argument,0,0}, /* [flg] Do not write output to temporary file */ {"version",no_argument,0,0}, {"vrs",no_argument,0,0}, /* Long options with argument, no short option counterpart */ {"bfr_sz_hnt",required_argument,0,0}, /* [B] Buffer size hint */ {"buffer_size_hint",required_argument,0,0}, /* [B] Buffer size hint */ {"cnk_byt",required_argument,0,0}, /* [B] Chunk size in bytes */ {"chunk_byte",required_argument,0,0}, /* [B] Chunk size in bytes */ {"cnk_dmn",required_argument,0,0}, /* [nbr] Chunk size */ {"chunk_dimension",required_argument,0,0}, /* [nbr] Chunk size */ {"cnk_map",required_argument,0,0}, /* [nbr] Chunking map */ {"chunk_map",required_argument,0,0}, /* [nbr] Chunking map */ {"cnk_min",required_argument,0,0}, /* [B] Minimize size of variable to chunk */ {"chunk_min",required_argument,0,0}, /* [B] Minimize size of variable to chunk */ {"cnk_plc",required_argument,0,0}, /* [nbr] Chunking policy */ {"chunk_policy",required_argument,0,0}, /* [nbr] Chunking policy */ {"cnk_scl",required_argument,0,0}, /* [nbr] Chunk size scalar */ {"chunk_scalar",required_argument,0,0}, /* [nbr] Chunk size scalar */ {"fl_fmt",required_argument,0,0}, {"file_format",required_argument,0,0}, {"gaa",required_argument,0,0}, /* [sng] Global attribute add */ {"glb_att_add",required_argument,0,0}, /* [sng] Global attribute add */ {"hdr_pad",required_argument,0,0}, {"header_pad",required_argument,0,0}, {"log_lvl",required_argument,0,0}, /* [enm] netCDF library debugging verbosity [0..5] */ {"log_level",required_argument,0,0}, /* [enm] netCDF library debugging verbosity [0..5] */ /* Long options with short counterparts */ {"3",no_argument,0,'3'}, {"4",no_argument,0,'4'}, {"netcdf4",no_argument,0,'4'}, {"5",no_argument,0,'5'}, {"64bit_data",no_argument,0,'5'}, {"cdf5",no_argument,0,'5'}, {"pnetcdf",no_argument,0,'5'}, {"64bit_offset",no_argument,0,'6'}, {"7",no_argument,0,'7'}, {"append",no_argument,0,'A'}, {"arrange",required_argument,0,'a'}, {"permute",required_argument,0,'a'}, {"reorder",required_argument,0,'a'}, {"rdr",required_argument,0,'a'}, {"xtr_ass_var",no_argument,0,'c'}, {"xcl_ass_var",no_argument,0,'C'}, {"no_coords",no_argument,0,'C'}, {"no_crd",no_argument,0,'C'}, {"coords",no_argument,0,'c'}, {"crd",no_argument,0,'c'}, {"dbg_lvl",required_argument,0,'D'}, {"debug",required_argument,0,'D'}, {"nco_dbg_lvl",required_argument,0,'D'}, {"dimension",required_argument,0,'d'}, {"dmn",required_argument,0,'d'}, {"fortran",no_argument,0,'F'}, {"ftn",no_argument,0,'F'}, {"history",no_argument,0,'h'}, {"hst",no_argument,0,'h'}, {"dfl_lvl",required_argument,0,'L'}, /* [enm] Deflate level */ {"deflate",required_argument,0,'L'}, /* [enm] Deflate level */ {"local",required_argument,0,'l'}, {"lcl",required_argument,0,'l'}, {"pck_map",required_argument,0,'M'}, {"map",required_argument,0,'M'}, {"overwrite",no_argument,0,'O'}, {"ovr",no_argument,0,'O'}, {"output",required_argument,0,'o'}, {"fl_out",required_argument,0,'o'}, {"pack_policy",required_argument,0,'P'}, {"pck_plc",required_argument,0,'P'}, {"path",required_argument,0,'p'}, {"retain",no_argument,0,'R'}, {"rtn",no_argument,0,'R'}, {"revision",no_argument,0,'r'}, {"suspend", no_argument,0,'S'}, {"thr_nbr",required_argument,0,'t'}, {"threads",required_argument,0,'t'}, {"omp_num_threads",required_argument,0,'t'}, {"unpack",no_argument,0,'U'}, {"upk",no_argument,0,'U'}, {"variable",required_argument,0,'v'}, {"auxiliary",required_argument,0,'X'}, {"exclude",no_argument,0,'x'}, {"xcl",no_argument,0,'x'}, {"help",no_argument,0,'?'}, {"hlp",no_argument,0,'?'}, {0,0,0,0} }; /* end opt_lng */ int opt_idx=0; /* Index of current long option into opt_lng array */ #ifdef ENABLE_MPI /* MPI Initialization */ MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD,&prc_nbr); MPI_Comm_rank(MPI_COMM_WORLD,&prc_rnk); #endif /* !ENABLE_MPI */ /* Start clock and save command line */ cmd_ln=nco_cmd_ln_sng(argc,argv); /* Get program name and set program enum (e.g., nco_prg_id=ncra) */ nco_prg_nm=nco_prg_prs(argv[0],&nco_prg_id); /* Parse command line arguments */ while(1){ /* getopt_long_only() allows one dash to prefix long options */ opt=getopt_long(argc,argv,opt_sht_lst,opt_lng,&opt_idx); /* NB: access to opt_crr is only valid when long_opt is detected */ if(opt == EOF) break; /* Parse positional arguments once getopt_long() returns EOF */ opt_crr=(char *)strdup(opt_lng[opt_idx].name); /* Process long options without short option counterparts */ if(opt == 0){ if(!strcmp(opt_crr,"bfr_sz_hnt") || !strcmp(opt_crr,"buffer_size_hint")){ bfr_sz_hnt=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif cnk */ if(!strcmp(opt_crr,"cnk_byt") || !strcmp(opt_crr,"chunk_byte")){ cnk_sz_byt=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif cnk_byt */ if(!strcmp(opt_crr,"cnk_min") || !strcmp(opt_crr,"chunk_min")){ cnk_min_byt=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif cnk_min */ if(!strcmp(opt_crr,"cnk_dmn") || !strcmp(opt_crr,"chunk_dimension")){ /* Copy limit argument for later processing */ cnk_arg[cnk_nbr]=(char *)strdup(optarg); cnk_nbr++; } /* endif cnk */ if(!strcmp(opt_crr,"cnk_scl") || !strcmp(opt_crr,"chunk_scalar")){ cnk_sz_scl=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif cnk */ if(!strcmp(opt_crr,"cnk_map") || !strcmp(opt_crr,"chunk_map")){ /* Chunking map */ cnk_map_sng=(char *)strdup(optarg); cnk_map=nco_cnk_map_get(cnk_map_sng); } /* endif cnk */ if(!strcmp(opt_crr,"cnk_plc") || !strcmp(opt_crr,"chunk_policy")){ /* Chunking policy */ cnk_plc_sng=(char *)strdup(optarg); cnk_plc=nco_cnk_plc_get(cnk_plc_sng); } /* endif cnk */ if(!strcmp(opt_crr,"mmr_cln") || !strcmp(opt_crr,"clean")) flg_mmr_cln=True; /* [flg] Clean memory prior to exit */ if(!strcmp(opt_crr,"drt") || !strcmp(opt_crr,"mmr_drt") || !strcmp(opt_crr,"dirty")) flg_mmr_cln=False; /* [flg] Clean memory prior to exit */ if(!strcmp(opt_crr,"fl_fmt") || !strcmp(opt_crr,"file_format")) rcd=nco_create_mode_prs(optarg,&fl_out_fmt); if(!strcmp(opt_crr,"gaa") || !strcmp(opt_crr,"glb_att_add")){ gaa_arg=(char **)nco_realloc(gaa_arg,(gaa_nbr+1)*sizeof(char *)); gaa_arg[gaa_nbr++]=(char *)strdup(optarg); } /* endif gaa */ if(!strcmp(opt_crr,"hdr_pad") || !strcmp(opt_crr,"header_pad")){ hdr_pad=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif "hdr_pad" */ if(!strcmp(opt_crr,"log_lvl") || !strcmp(opt_crr,"log_level")){ log_lvl=(int)strtol(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtol",sng_cnv_rcd); nc_set_log_level(log_lvl); } /* !log_lvl */ if(!strcmp(opt_crr,"ram_all") || !strcmp(opt_crr,"create_ram") || !strcmp(opt_crr,"diskless_all")) RAM_CREATE=True; /* [flg] Create (netCDF3) file(s) in RAM */ if(!strcmp(opt_crr,"ram_all") || !strcmp(opt_crr,"open_ram") || !strcmp(opt_crr,"diskless_all")) RAM_OPEN=True; /* [flg] Open (netCDF3) file(s) in RAM */ if(!strcmp(opt_crr,"share_all") || !strcmp(opt_crr,"unbuffered_io") || !strcmp(opt_crr,"uio") || !strcmp(opt_crr,"create_share")) SHARE_CREATE=True; /* [flg] Create (netCDF3) file(s) with unbuffered I/O */ if(!strcmp(opt_crr,"share_all") || !strcmp(opt_crr,"unbuffered_io") || !strcmp(opt_crr,"uio") || !strcmp(opt_crr,"open_share")) SHARE_OPEN=True; /* [flg] Open (netCDF3) file(s) with unbuffered I/O */ if(!strcmp(opt_crr,"vrs") || !strcmp(opt_crr,"version")){ (void)nco_vrs_prn(CVS_Id,CVS_Revision); nco_exit(EXIT_SUCCESS); } /* endif "vrs" */ if(!strcmp(opt_crr,"wrt_tmp_fl") || !strcmp(opt_crr,"write_tmp_fl")) WRT_TMP_FL=True; if(!strcmp(opt_crr,"no_tmp_fl")) WRT_TMP_FL=False; } /* opt != 0 */ /* Process short options */ switch(opt){ case 0: /* Long options have already been processed, return */ break; case '3': /* Request netCDF3 output storage format */ fl_out_fmt=NC_FORMAT_CLASSIC; break; case '4': /* Request netCDF4 output storage format */ fl_out_fmt=NC_FORMAT_NETCDF4; break; case '5': /* Request netCDF3 64-bit offset+data storage (i.e., pnetCDF) format */ fl_out_fmt=NC_FORMAT_CDF5; break; case '6': /* Request netCDF3 64-bit offset output storage format */ fl_out_fmt=NC_FORMAT_64BIT_OFFSET; break; case '7': /* Request netCDF4-classic output storage format */ fl_out_fmt=NC_FORMAT_NETCDF4_CLASSIC; break; case 'A': /* Toggle FORCE_APPEND */ FORCE_APPEND=!FORCE_APPEND; break; case 'a': /* Re-order dimensions */ dmn_rdr_lst_in=nco_lst_prs_2D(optarg,",",&dmn_rdr_nbr_in); dmn_rdr_nbr=dmn_rdr_nbr_in; break; case 'C': /* Extract all coordinates associated with extracted variables? */ EXTRACT_ASSOCIATED_COORDINATES=False; break; case 'c': EXTRACT_ALL_COORDINATES=True; break; case 'D': /* Debugging level. Default is 0. */ nco_dbg_lvl=(unsigned short int)strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); break; case 'd': /* Copy limit argument for later processing */ lmt_arg[lmt_nbr]=(char *)strdup(optarg); lmt_nbr++; break; case 'F': /* Toggle index convention. Default is 0-based arrays (C-style). */ FORTRAN_IDX_CNV=!FORTRAN_IDX_CNV; break; case 'h': /* Toggle appending to history global attribute */ HISTORY_APPEND=!HISTORY_APPEND; break; case 'L': /* [enm] Deflate level. Default is 0. */ dfl_lvl=(int)strtol(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtol",sng_cnv_rcd); break; case 'l': /* Local path prefix for files retrieved from remote file system */ fl_pth_lcl=(char *)strdup(optarg); break; case 'M': /* Packing map */ nco_pck_map_sng=(char *)strdup(optarg); nco_pck_map=nco_pck_map_get(nco_pck_map_sng); break; case 'O': /* Toggle FORCE_OVERWRITE */ FORCE_OVERWRITE=!FORCE_OVERWRITE; break; case 'o': /* Name of output file */ fl_out=(char *)strdup(optarg); break; case 'P': /* Packing policy */ nco_pck_plc_sng=(char *)strdup(optarg); break; case 'p': /* Common file path */ fl_pth=(char *)strdup(optarg); break; case 'R': /* Toggle removal of remotely-retrieved-files. Default is True. */ RM_RMT_FL_PST_PRC=!RM_RMT_FL_PST_PRC; break; case 'r': /* Print CVS program information and copyright notice */ (void)nco_vrs_prn(CVS_Id,CVS_Revision); (void)nco_lbr_vrs_prn(); (void)nco_cpy_prn(); (void)nco_cnf_prn(); nco_exit(EXIT_SUCCESS); break; #ifdef ENABLE_MPI case 'S': /* Suspend with signal handler to facilitate debugging */ if(signal(SIGUSR1,nco_cnt_run) == SIG_ERR) (void)fprintf(fp_stdout,"%s: ERROR Could not install suspend handler.\n",nco_prg_nm); while(!nco_spn_lck_brk) usleep(nco_spn_lck_us); /* Spinlock. fxm: should probably insert a sched_yield */ break; #endif /* !ENABLE_MPI */ case 't': /* Thread number */ thr_nbr=(int)strtol(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtol",sng_cnv_rcd); break; case 'U': /* Unpacking switch */ nco_pck_plc_sng=(char *)strdup("upk"); break; case 'v': /* Variables to extract/exclude */ /* Replace commas with hashes when within braces (convert back later) */ optarg_lcl=(char *)strdup(optarg); (void)nco_rx_comma2hash(optarg_lcl); var_lst_in=nco_lst_prs_2D(optarg_lcl,",",&var_lst_in_nbr); optarg_lcl=(char *)nco_free(optarg_lcl); xtr_nbr=var_lst_in_nbr; break; case 'X': /* Copy auxiliary coordinate argument for later processing */ aux_arg[aux_nbr]=(char *)strdup(optarg); aux_nbr++; MSA_USR_RDR=True; /* [flg] Multi-Slab Algorithm returns hyperslabs in user-specified order */ break; case 'x': /* Exclude rather than extract variables specified with -v */ EXCLUDE_INPUT_LIST=True; break; case '?': /* Print proper usage */ (void)nco_usg_prn(); nco_exit(EXIT_SUCCESS); break; case '-': /* Long options are not allowed */ (void)fprintf(stderr,"%s: ERROR Long options are not available in this build. Use single letter options instead.\n",nco_prg_nm_get()); nco_exit(EXIT_FAILURE); break; default: /* Print proper usage */ (void)fprintf(stdout,"%s ERROR in command-line syntax/options. Please reformulate command accordingly.\n",nco_prg_nm_get()); (void)nco_usg_prn(); nco_exit(EXIT_FAILURE); break; } /* end switch */ if(opt_crr) opt_crr=(char *)nco_free(opt_crr); } /* end while loop */ /* Process positional arguments and fill-in filenames */ fl_lst_in=nco_fl_lst_mk(argv,argc,optind,&fl_nbr,&fl_out,&FL_LST_IN_FROM_STDIN,FORCE_OVERWRITE); /* Make uniform list of user-specified chunksizes */ if(cnk_nbr > 0) cnk_dmn=nco_cnk_prs(cnk_nbr,cnk_arg); /* Make uniform list of user-specified dimension limits */ lmt=nco_lmt_prs(lmt_nbr,lmt_arg); /* Initialize thread information */ thr_nbr=nco_openmp_ini(thr_nbr); in_id_arr=(int *)nco_malloc(thr_nbr*sizeof(int)); /* Parse filename */ fl_in=nco_fl_nm_prs(fl_in,0,&fl_nbr,fl_lst_in,abb_arg_nbr,fl_lst_abb,fl_pth); /* Make sure file is on local system and is readable or die trying */ fl_in=nco_fl_mk_lcl(fl_in,fl_pth_lcl,HPSS_TRY,&FL_RTR_RMT_LCN); /* Open file using appropriate buffer size hints and verbosity */ if(RAM_OPEN) md_open=NC_NOWRITE|NC_DISKLESS; else md_open=NC_NOWRITE; if(SHARE_OPEN) md_open=md_open|NC_SHARE; rcd+=nco_fl_open(fl_in,md_open,&bfr_sz_hnt,&in_id); /* Parse auxiliary coordinates */ if(aux_nbr > 0){ int aux_idx_nbr; aux=nco_aux_evl(in_id,aux_nbr,aux_arg,&aux_idx_nbr); if(aux_idx_nbr > 0){ lmt=(lmt_sct **)nco_realloc(lmt,(lmt_nbr+aux_idx_nbr)*sizeof(lmt_sct *)); int lmt_nbr_new=lmt_nbr+aux_idx_nbr; int aux_idx=0; for(int lmt_idx=lmt_nbr;lmt_idx<lmt_nbr_new;lmt_idx++) lmt[lmt_idx]=aux[aux_idx++]; lmt_nbr=lmt_nbr_new; } /* endif aux */ } /* endif aux_nbr */ /* Get number of variables, dimensions, and record dimension ID of input file */ (void)nco_inq(in_id,&nbr_dmn_fl,&nbr_var_fl,(int *)NULL,&rec_dmn_id_in); (void)nco_inq_format(in_id,&fl_in_fmt); /* Form initial extraction list which may include extended regular expressions */ xtr_lst=nco_var_lst_mk(in_id,nbr_var_fl,var_lst_in,EXCLUDE_INPUT_LIST,EXTRACT_ALL_COORDINATES,&xtr_nbr); /* Change included variables to excluded variables */ if(EXCLUDE_INPUT_LIST) xtr_lst=nco_var_lst_xcl(in_id,nbr_var_fl,xtr_lst,&xtr_nbr); /* Determine conventions (ARM/CCM/CCSM/CF/MPAS) for treating file */ cnv=nco_cnv_ini(in_id); /* Add all coordinate variables to extraction list */ if(EXTRACT_ALL_COORDINATES) xtr_lst=nco_var_lst_crd_add(in_id,nbr_dmn_fl,nbr_var_fl,xtr_lst,&xtr_nbr,cnv); /* Extract coordinates associated with extracted variables */ if(EXTRACT_ASSOCIATED_COORDINATES) xtr_lst=nco_var_lst_crd_ass_add(in_id,xtr_lst,&xtr_nbr,cnv); /* Sort extraction list by variable ID for fastest I/O */ if(xtr_nbr > 1) xtr_lst=nco_lst_srt_nm_id(xtr_lst,xtr_nbr,False); /* Find coordinate/dimension values associated with user-specified limits NB: nco_lmt_evl() with same nc_id contains OpenMP critical region */ for(idx=0;idx<lmt_nbr;idx++) (void)nco_lmt_evl(in_id,lmt[idx],0L,FORTRAN_IDX_CNV); /* Place all dimensions in lmt_all_lst */ lmt_all_lst=(lmt_all_sct **)nco_malloc(nbr_dmn_fl*sizeof(lmt_all_sct *)); /* Initialize lmt_all_sct's */ (void)nco_msa_lmt_all_ntl(in_id,MSA_USR_RDR,lmt_all_lst,nbr_dmn_fl,lmt,lmt_nbr); /* Find dimensions associated with variables to be extracted */ dmn_lst=nco_dmn_lst_ass_var(in_id,xtr_lst,xtr_nbr,&nbr_dmn_xtr); /* Fill-in dimension structure for all extracted dimensions */ dim=(dmn_sct **)nco_malloc(nbr_dmn_xtr*sizeof(dmn_sct *)); for(idx=0;idx<nbr_dmn_xtr;idx++) dim[idx]=nco_dmn_fll(in_id,dmn_lst[idx].id,dmn_lst[idx].nm); /* Dimension list no longer needed */ dmn_lst=nco_nm_id_lst_free(dmn_lst,nbr_dmn_xtr); /* Duplicate input dimension structures for output dimension structures */ nbr_dmn_out=nbr_dmn_xtr; dmn_out=(dmn_sct **)nco_malloc(nbr_dmn_out*sizeof(dmn_sct *)); for(idx=0;idx<nbr_dmn_out;idx++){ dmn_out[idx]=nco_dmn_dpl(dim[idx]); (void)nco_dmn_xrf(dim[idx],dmn_out[idx]); } /* end loop over idx */ /* Merge hyperslab limit information into dimension structures */ if(nbr_dmn_fl > 0) (void)nco_dmn_lmt_all_mrg(dmn_out,nbr_dmn_xtr,lmt_all_lst,nbr_dmn_fl); /* No re-order dimensions specified implies packing request */ if(dmn_rdr_nbr == 0){ if(nco_pck_plc == nco_pck_plc_nil) nco_pck_plc=nco_pck_plc_get(nco_pck_plc_sng); if(nco_dbg_lvl >= nco_dbg_scl) (void)fprintf(stderr,"%s: DEBUG Packing map is %s and packing policy is %s\n",nco_prg_nm_get(),nco_pck_map_sng_get(nco_pck_map),nco_pck_plc_sng_get(nco_pck_plc)); } /* endif */ /* From this point forward, assume ncpdq operator packs or re-orders, not both */ if(dmn_rdr_nbr > 0 && nco_pck_plc != nco_pck_plc_nil){ (void)fprintf(fp_stdout,"%s: ERROR %s does not support simultaneous dimension re-ordering (-a switch) and packing (-P switch).\nHINT: Invoke %s twice, once to re-order (with -a), and once to pack (with -P).\n",nco_prg_nm,nco_prg_nm,nco_prg_nm); nco_exit(EXIT_FAILURE); } /* end if */ if(dmn_rdr_nbr > 0){ /* NB: Same logic as in ncwa, perhaps combine into single function, nco_dmn_avg_rdr_prp()? */ /* Make list of user-specified dimension re-orders */ /* Create reversed dimension list */ dmn_rvr_rdr=(nco_bool *)nco_malloc(dmn_rdr_nbr*sizeof(nco_bool)); for(idx_rdr=0;idx_rdr<dmn_rdr_nbr;idx_rdr++){ if(dmn_rdr_lst_in[idx_rdr][0] == '-'){ dmn_rvr_rdr[idx_rdr]=True; /* Copy string to new memory one past negative sign to avoid losing byte */ optarg_lcl=dmn_rdr_lst_in[idx_rdr]; dmn_rdr_lst_in[idx_rdr]=(char *)strdup(optarg_lcl+1); optarg_lcl=(char *)nco_free(optarg_lcl); }else{ dmn_rvr_rdr[idx_rdr]=False; } /* end else */ } /* end loop over idx_rdr */ /* Create structured list of re-ordering dimension names and IDs */ dmn_rdr_lst=nco_dmn_lst_mk(in_id,dmn_rdr_lst_in,dmn_rdr_nbr); /* Form list of re-ordering dimensions from extracted input dimensions */ dmn_rdr=(dmn_sct **)nco_malloc(dmn_rdr_nbr*sizeof(dmn_sct *)); /* Loop over original number of re-order dimensions */ for(idx_rdr=0;idx_rdr<dmn_rdr_nbr;idx_rdr++){ for(idx=0;idx<nbr_dmn_xtr;idx++){ if(!strcmp(dmn_rdr_lst[idx_rdr].nm,dim[idx]->nm)) break; } /* end loop over idx_rdr */ if(idx != nbr_dmn_xtr) dmn_rdr[dmn_rdr_nbr_utl++]=dim[idx]; else if(nco_dbg_lvl >= nco_dbg_std) (void)fprintf(stderr,"%s: WARNING re-ordering dimension \"%s\" is not contained in any variable in extraction list\n",nco_prg_nm,dmn_rdr_lst[idx_rdr].nm); } /* end loop over idx_rdr */ dmn_rdr_nbr=dmn_rdr_nbr_utl; /* Collapse extra dimension structure space to prevent accidentally using it */ dmn_rdr=(dmn_sct **)nco_realloc(dmn_rdr,dmn_rdr_nbr*sizeof(dmn_sct *)); /* Dimension list in name-ID format is no longer needed */ dmn_rdr_lst=nco_nm_id_lst_free(dmn_rdr_lst,dmn_rdr_nbr); /* Make sure no re-ordering dimension is specified more than once */ for(idx=0;idx<dmn_rdr_nbr;idx++){ for(idx_rdr=0;idx_rdr<dmn_rdr_nbr;idx_rdr++){ if(idx_rdr != idx){ if(dmn_rdr[idx]->id == dmn_rdr[idx_rdr]->id){ (void)fprintf(fp_stdout,"%s: ERROR %s specified more than once in reducing list\n",nco_prg_nm,dmn_rdr[idx]->nm); nco_exit(EXIT_FAILURE); } /* end if */ } /* end if */ } /* end loop over idx_rdr */ } /* end loop over idx */ if(dmn_rdr_nbr > nbr_dmn_xtr){ (void)fprintf(fp_stdout,"%s: ERROR More re-ordering dimensions than extracted dimensions\n",nco_prg_nm); nco_exit(EXIT_FAILURE); } /* end if */ } /* dmn_rdr_nbr <= 0 */ /* Determine conventions (ARM/CCM/CCSM/CF/MPAS) for treating file */ cnv=nco_cnv_ini(in_id); /* Fill-in variable structure list for all extracted variables */ var=(var_sct **)nco_malloc(xtr_nbr*sizeof(var_sct *)); var_out=(var_sct **)nco_malloc(xtr_nbr*sizeof(var_sct *)); for(idx=0;idx<xtr_nbr;idx++){ var[idx]=nco_var_fll(in_id,xtr_lst[idx].id,xtr_lst[idx].nm,dim,nbr_dmn_xtr); var_out[idx]=nco_var_dpl(var[idx]); (void)nco_xrf_var(var[idx],var_out[idx]); (void)nco_xrf_dmn(var_out[idx]); } /* end loop over idx */ /* Extraction list no longer needed */ xtr_lst=nco_nm_id_lst_free(xtr_lst,xtr_nbr); /* Divide variable lists into lists of fixed variables and variables to be processed */ (void)nco_var_lst_dvd(var,var_out,xtr_nbr,cnv,True,nco_pck_map,nco_pck_plc,dmn_rdr,dmn_rdr_nbr,&var_fix,&var_fix_out,&nbr_var_fix,&var_prc,&var_prc_out,&nbr_var_prc); /* We now have final list of variables to extract. Phew. */ if(nco_dbg_lvl >= nco_dbg_var){ for(idx=0;idx<xtr_nbr;idx++) (void)fprintf(stderr,"var[%d]->nm = %s, ->id=[%d]\n",idx,var[idx]->nm,var[idx]->id); for(idx=0;idx<nbr_var_fix;idx++) (void)fprintf(stderr,"var_fix[%d]->nm = %s, ->id=[%d]\n",idx,var_fix[idx]->nm,var_fix[idx]->id); for(idx=0;idx<nbr_var_prc;idx++) (void)fprintf(stderr,"var_prc[%d]->nm = %s, ->id=[%d]\n",idx,var_prc[idx]->nm,var_prc[idx]->id); } /* end if */ #ifdef ENABLE_MPI if(prc_rnk == rnk_mgr){ /* MPI manager code */ #endif /* !ENABLE_MPI */ /* Make output and input files consanguinous */ if(fl_out_fmt == NCO_FORMAT_UNDEFINED) fl_out_fmt=fl_in_fmt; /* Verify output file format supports requested actions */ (void)nco_fl_fmt_vet(fl_out_fmt,cnk_nbr,dfl_lvl); /* Open output file */ fl_out_tmp=nco_fl_out_open(fl_out,&FORCE_APPEND,FORCE_OVERWRITE,fl_out_fmt,&bfr_sz_hnt,RAM_CREATE,RAM_OPEN,SHARE_CREATE,SHARE_OPEN,WRT_TMP_FL,&out_id); if(nco_dbg_lvl >= nco_dbg_sbr) (void)fprintf(stderr,"Input, output file IDs = %d, %d\n",in_id,out_id); /* Copy global attributes */ (void)nco_att_cpy(in_id,out_id,NC_GLOBAL,NC_GLOBAL,(nco_bool)True); /* Catenate time-stamped command line to "history" global attribute */ if(HISTORY_APPEND) (void)nco_hst_att_cat(out_id,cmd_ln); if(HISTORY_APPEND && FORCE_APPEND) (void)nco_prv_att_cat(fl_in,in_id,out_id); if(gaa_nbr > 0) (void)nco_glb_att_add(out_id,gaa_arg,gaa_nbr); if(HISTORY_APPEND) (void)nco_vrs_att_cat(out_id); if(thr_nbr > 1 && HISTORY_APPEND) (void)nco_thr_att_cat(out_id,thr_nbr); #ifdef ENABLE_MPI /* Initialize MPI task information */ if(prc_nbr > 0 && HISTORY_APPEND) (void)nco_mpi_att_cat(out_id,prc_nbr); } /* !prc_rnk == rnk_mgr */ #endif /* !ENABLE_MPI */ /* If re-ordering, then in files with record dimension... */ if(dmn_rdr_nbr > 0 && rec_dmn_id_in != NCO_REC_DMN_UNDEFINED){ /* ...which, if any, output dimension structure currently holds record dimension? */ for(dmn_out_idx=0;dmn_out_idx<nbr_dmn_out;dmn_out_idx++) if(dmn_out[dmn_out_idx]->is_rec_dmn) break; if(dmn_out_idx != nbr_dmn_out){ dmn_out_idx_rec_in=dmn_out_idx; /* Initialize output record dimension to input record dimension */ rec_dmn_nm_in=rec_dmn_nm_out=dmn_out[dmn_out_idx_rec_in]->nm; }else{ dmn_out_idx_rec_in=NCO_REC_DMN_UNDEFINED; } /* end else */ } /* end if file contains record dimension */ /* If re-ordering, determine and set new dimensionality in metadata of each re-ordered variable */ if(dmn_rdr_nbr > 0){ dmn_idx_out_in=(int **)nco_malloc(nbr_var_prc*sizeof(int *)); dmn_rvr_in=(nco_bool **)nco_malloc(nbr_var_prc*sizeof(nco_bool *)); for(idx=0;idx<nbr_var_prc;idx++){ dmn_idx_out_in[idx]=(int *)nco_malloc(var_prc[idx]->nbr_dim*sizeof(int)); dmn_rvr_in[idx]=(nco_bool *)nco_malloc(var_prc[idx]->nbr_dim*sizeof(nco_bool)); /* nco_var_dmn_rdr_mtd() does re-order heavy lifting */ rec_dmn_nm_out_crr=nco_var_dmn_rdr_mtd(var_prc[idx],var_prc_out[idx],dmn_rdr,dmn_rdr_nbr,dmn_idx_out_in[idx],dmn_rvr_rdr,dmn_rvr_in[idx]); /* If record dimension required by current variable re-order... ...and variable is multi-dimensional (one dimensional arrays cannot request record dimension changes)... */ if(rec_dmn_nm_out_crr && var_prc_out[idx]->nbr_dim > 1){ /* ...differs from input and current output record dimension(s)... */ if(strcmp(rec_dmn_nm_out_crr,rec_dmn_nm_in) && strcmp(rec_dmn_nm_out_crr,rec_dmn_nm_out)){ /* ...and current output record dimension already differs from input record dimension... */ if(REDEFINED_RECORD_DIMENSION){ /* ...then requested re-order requires multiple record dimensions... */ if(nco_dbg_lvl >= nco_dbg_std) (void)fprintf(fp_stdout,"%s: WARNING Re-order requests multiple record dimensions\n. Only first request will be honored (netCDF allows only one record dimension). Record dimensions involved [original,first change request (honored),latest change request (made by variable %s)]=[%s,%s,%s]\n",nco_prg_nm,var_prc[idx]->nm,rec_dmn_nm_in,rec_dmn_nm_out,rec_dmn_nm_out_crr); break; }else{ /* !REDEFINED_RECORD_DIMENSION */ /* ...otherwise, update output record dimension name... */ rec_dmn_nm_out=rec_dmn_nm_out_crr; /* ...and set new and un-set old record dimensions... */ var_prc_out[idx]->dim[0]->is_rec_dmn=True; dmn_out[dmn_out_idx_rec_in]->is_rec_dmn=False; /* ...and set flag that record dimension has been re-defined... */ REDEFINED_RECORD_DIMENSION=True; } /* !REDEFINED_RECORD_DIMENSION */ } /* endif new and old record dimensions differ */ } /* endif current variable is record variable */ } /* end loop over var_prc */ } /* endif dmn_rdr_nbr > 0 */ /* NB: Much of following logic is required by netCDF constraint that only one record variable is allowed per file. netCDF4 will relax this constraint. Hence making following logic prettier or funcionalizing is not high priority. Logic may need to be simplified/re-written once netCDF4 is released. */ if(REDEFINED_RECORD_DIMENSION){ if(nco_dbg_lvl >= nco_dbg_std) (void)fprintf(fp_stdout,"%s: INFO Requested re-order will change record dimension from %s to %s. netCDF allows only one record dimension. Hence %s will make %s record (least rapidly varying) dimension in all variables that contain it.\n",nco_prg_nm,rec_dmn_nm_in,rec_dmn_nm_out,nco_prg_nm,rec_dmn_nm_out); /* Changing record dimension may invalidate is_rec_var flag Updating is_rec_var flag to correct value, even if value is ignored, helps keep user appraised of unexpected dimension re-orders. is_rec_var may change both for "fixed" and "processed" variables When is_rec_var changes for processed variables, may also need to change ancillary information and to check for duplicate dimensions. Ancillary information (dmn_idx_out_in) is available only for var_prc! Hence must update is_rec_var flag for var_fix and var_prc separately */ /* Update is_rec_var flag for var_fix */ for(idx=0;idx<nbr_var_fix;idx++){ /* Search all dimensions in variable for new record dimension */ for(dmn_out_idx=0;dmn_out_idx<var_fix[idx]->nbr_dim;dmn_out_idx++) if(!strcmp(var_fix[idx]->dim[dmn_out_idx]->nm,rec_dmn_nm_out)) break; /* ...Will variable be record variable in output file?... */ if(dmn_out_idx == var_fix[idx]->nbr_dim){ /* ...No. Variable will be non-record---does this change its status?... */ if(nco_dbg_lvl >= nco_dbg_var) if(var_fix[idx]->is_rec_var == True) (void)fprintf(fp_stdout,"%s: INFO Requested re-order will change variable %s from record to non-record variable\n",nco_prg_nm,var_fix[idx]->nm); /* Assign record flag dictated by re-order */ var_fix[idx]->is_rec_var=False; }else{ /* ...otherwise variable will be record variable... */ /* ...Yes. Variable will be record... */ /* ...Will becoming record variable change its status?... */ if(var_fix[idx]->is_rec_var == False){ if(nco_dbg_lvl >= nco_dbg_var) (void)fprintf(fp_stdout,"%s: INFO Requested re-order will change variable %s from non-record to record variable\n",nco_prg_nm,var_fix[idx]->nm); /* Change record flag to status dictated by re-order */ var_fix[idx]->is_rec_var=True; } /* endif status changing from non-record to record */ } /* endif variable will be record variable */ } /* end loop over var_fix */ /* Update is_rec_var flag for var_prc */ for(idx=0;idx<nbr_var_prc;idx++){ /* Search all dimensions in variable for new record dimension */ for(dmn_out_idx=0;dmn_out_idx<var_prc_out[idx]->nbr_dim;dmn_out_idx++) if(!strcmp(var_prc_out[idx]->dim[dmn_out_idx]->nm,rec_dmn_nm_out)) break; /* ...Will variable be record variable in output file?... */ if(dmn_out_idx == var_prc_out[idx]->nbr_dim){ /* ...No. Variable will be non-record---does this change its status?... */ if(nco_dbg_lvl >= nco_dbg_var) if(var_prc_out[idx]->is_rec_var == True) (void)fprintf(fp_stdout,"%s: INFO Requested re-order will change variable %s from record to non-record variable\n",nco_prg_nm,var_prc_out[idx]->nm); /* Assign record flag dictated by re-order */ var_prc_out[idx]->is_rec_var=False; }else{ /* ...otherwise variable will be record variable... */ /* ...Yes. Variable will be record... */ /* ...must ensure new record dimension is not duplicate dimension... */ if(var_prc_out[idx]->has_dpl_dmn){ int dmn_dpl_idx; for(dmn_dpl_idx=1;dmn_dpl_idx<var_prc_out[idx]->nbr_dim;dmn_dpl_idx++){ /* NB: loop starts from 1 */ if(var_prc_out[idx]->dmn_id[0] == var_prc_out[idx]->dmn_id[dmn_dpl_idx]){ (void)fprintf(stdout,"%s: ERROR Requested re-order turns duplicate non-record dimension %s in variable %s into output record dimension. netCDF does not support duplicate record dimensions in a single variable.\n%s: HINT: Exclude variable %s from extraction list with \"-x -v %s\".\n",nco_prg_nm_get(),rec_dmn_nm_out,var_prc_out[idx]->nm,nco_prg_nm_get(),var_prc_out[idx]->nm,var_prc_out[idx]->nm); nco_exit(EXIT_FAILURE); } /* endif err */ } /* end loop over dmn_out */ } /* endif has_dpl_dmn */ /* ...Will becoming record variable change its status?... */ if(var_prc_out[idx]->is_rec_var == False){ if(nco_dbg_lvl >= nco_dbg_var) (void)fprintf(fp_stdout,"%s: INFO Requested re-order will change variable %s from non-record to record variable\n",nco_prg_nm,var_prc_out[idx]->nm); /* Change record flag to status dictated by re-order */ var_prc_out[idx]->is_rec_var=True; /* ...Swap dimension information for multi-dimensional variables... */ if(var_prc_out[idx]->nbr_dim > 1){ /* Swap dimension information when turning multi-dimensional non-record variable into record variable. Single dimensional non-record variables that turn into record variables already have correct dimension information */ dmn_sct *dmn_swp; /* [sct] Dimension structure for swapping */ int dmn_idx_rec_in; /* [idx] Record dimension index in input variable */ int dmn_idx_rec_out; /* [idx] Record dimension index in output variable */ int dmn_idx_swp; /* [idx] Dimension index for swapping */ /* If necessary, swap new record dimension to first position */ /* Label indices with standard names */ dmn_idx_rec_in=dmn_out_idx; dmn_idx_rec_out=0; /* Swap indices in map */ dmn_idx_swp=dmn_idx_out_in[idx][dmn_idx_rec_out]; dmn_idx_out_in[idx][dmn_idx_rec_out]=dmn_idx_rec_in; dmn_idx_out_in[idx][dmn_idx_rec_in]=dmn_idx_swp; /* Swap dimensions in list */ dmn_swp=var_prc_out[idx]->dim[dmn_idx_rec_out]; var_prc_out[idx]->dim[dmn_idx_rec_out]=var_prc_out[idx]->dim[dmn_idx_rec_in]; var_prc_out[idx]->dim[dmn_idx_rec_in]=dmn_swp; /* NB: Change dmn_id,cnt,srt,end,srd together to minimize chances of forgetting one */ /* Correct output variable structure copy of output record dimension information */ var_prc_out[idx]->dmn_id[dmn_idx_rec_out]=var_prc_out[idx]->dim[dmn_idx_rec_out]->id; var_prc_out[idx]->cnt[dmn_idx_rec_out]=var_prc_out[idx]->dim[dmn_idx_rec_out]->cnt; var_prc_out[idx]->srt[dmn_idx_rec_out]=var_prc_out[idx]->dim[dmn_idx_rec_out]->srt; var_prc_out[idx]->end[dmn_idx_rec_out]=var_prc_out[idx]->dim[dmn_idx_rec_out]->end; var_prc_out[idx]->srd[dmn_idx_rec_out]=var_prc_out[idx]->dim[dmn_idx_rec_out]->srd; /* Correct output variable structure copy of input record dimension information */ var_prc_out[idx]->dmn_id[dmn_idx_rec_in]=var_prc_out[idx]->dim[dmn_idx_rec_in]->id; var_prc_out[idx]->cnt[dmn_idx_rec_in]=var_prc_out[idx]->dim[dmn_idx_rec_in]->cnt; var_prc_out[idx]->srt[dmn_idx_rec_in]=var_prc_out[idx]->dim[dmn_idx_rec_in]->srt; var_prc_out[idx]->end[dmn_idx_rec_in]=var_prc_out[idx]->dim[dmn_idx_rec_in]->end; var_prc_out[idx]->srd[dmn_idx_rec_in]=var_prc_out[idx]->dim[dmn_idx_rec_in]->srd; } /* endif multi-dimensional */ } /* endif status changing from non-record to record */ } /* endif variable will be record variable */ } /* end loop over var_prc */ } /* !REDEFINED_RECORD_DIMENSION */ #ifdef ENABLE_MPI if(prc_rnk == rnk_mgr){ /* Defining dimension in output file done by Manager alone */ #endif /* !ENABLE_MPI */ /* Once new record dimension, if any, is known, define dimensions in output file */ (void)nco_dmn_dfn(fl_out,out_id,dmn_out,nbr_dmn_out); #ifdef ENABLE_MPI } /* prc_rnk != rnk_mgr */ #endif /* !ENABLE_MPI */ /* Alter metadata for variables that will be packed */ if(nco_pck_plc != nco_pck_plc_nil){ if(nco_pck_plc != nco_pck_plc_upk){ /* Allocate attribute list container for maximum number of entries */ aed_lst_add_fst=(aed_sct *)nco_malloc(nbr_var_prc*sizeof(aed_sct)); aed_lst_scl_fct=(aed_sct *)nco_malloc(nbr_var_prc*sizeof(aed_sct)); } /* endif packing */ for(idx=0;idx<nbr_var_prc;idx++){ nco_pck_mtd(var_prc[idx],var_prc_out[idx],nco_pck_map,nco_pck_plc); if(nco_pck_plc != nco_pck_plc_upk){ /* Use same copy of attribute name for all edits */ aed_lst_add_fst[idx].att_nm=add_fst_sng; aed_lst_scl_fct[idx].att_nm=scl_fct_sng; } /* endif packing */ } /* end loop over var_prc */ } /* nco_pck_plc == nco_pck_plc_nil */ #ifdef ENABLE_MPI if(prc_rnk == rnk_mgr){ /* MPI manager code */ #endif /* !ENABLE_MPI */ /* Define variables in output file, copy their attributes */ (void)nco_var_dfn(in_id,fl_out,out_id,var_out,xtr_nbr,(dmn_sct **)NULL,(int)0,nco_pck_map,nco_pck_plc,dfl_lvl); /* Set chunksize parameters */ if(fl_out_fmt == NC_FORMAT_NETCDF4 || fl_out_fmt == NC_FORMAT_NETCDF4_CLASSIC) (void)nco_cnk_sz_set(out_id,lmt_all_lst,nbr_dmn_fl,&cnk_map,&cnk_plc,cnk_sz_scl,cnk_dmn,cnk_nbr); /* Turn-off default filling behavior to enhance efficiency */ nco_set_fill(out_id,NC_NOFILL,&fll_md_old); /* Take output file out of define mode */ if(hdr_pad == 0UL){ (void)nco_enddef(out_id); }else{ (void)nco__enddef(out_id,hdr_pad); if(nco_dbg_lvl >= nco_dbg_scl) (void)fprintf(stderr,"%s: INFO Padding header with %lu extra bytes\n",nco_prg_nm_get(),(unsigned long)hdr_pad); } /* hdr_pad */ #ifdef ENABLE_MPI } /* prc_rnk != rnk_mgr */ /* Manager obtains output filename and broadcasts to workers */ if(prc_rnk == rnk_mgr) fl_nm_lng=(int)strlen(fl_out_tmp); MPI_Bcast(&fl_nm_lng,1,MPI_INT,0,MPI_COMM_WORLD); if(prc_rnk != rnk_mgr) fl_out_tmp=(char *)nco_malloc((fl_nm_lng+1)*sizeof(char)); MPI_Bcast(fl_out_tmp,fl_nm_lng+1,MPI_CHAR,0,MPI_COMM_WORLD); #endif /* !ENABLE_MPI */ /* Assign zero to start and unity to stride vectors in output variables */ (void)nco_var_srd_srt_set(var_out,xtr_nbr); #ifdef ENABLE_MPI if(prc_rnk == rnk_mgr){ /* MPI manager code */ TKN_WRT_FREE=False; #endif /* !ENABLE_MPI */ /* Copy variable data for non-processed variables */ (void)nco_msa_var_val_cpy(in_id,out_id,var_fix,nbr_var_fix,lmt_all_lst,nbr_dmn_fl); #ifdef ENABLE_MPI /* Close output file so workers can open it */ nco_close(out_id); TKN_WRT_FREE=True; } /* prc_rnk != rnk_mgr */ #endif /* !ENABLE_MPI */ /* Close first input netCDF file */ nco_close(in_id); /* Loop over input files (not currently used, fl_nbr == 1) */ for(fl_idx=0;fl_idx<fl_nbr;fl_idx++){ /* Parse filename */ if(fl_idx != 0) fl_in=nco_fl_nm_prs(fl_in,fl_idx,&fl_nbr,fl_lst_in,abb_arg_nbr,fl_lst_abb,fl_pth); if(nco_dbg_lvl >= nco_dbg_fl) (void)fprintf(stderr,"\nInput file %d is %s; ",fl_idx,fl_in); /* Make sure file is on local system and is readable or die trying */ if(fl_idx != 0) fl_in=nco_fl_mk_lcl(fl_in,fl_pth_lcl,HPSS_TRY,&FL_RTR_RMT_LCN); if(nco_dbg_lvl >= nco_dbg_fl) (void)fprintf(stderr,"local file %s:\n",fl_in); /* Open file once per thread to improve caching */ for(thr_idx=0;thr_idx<thr_nbr;thr_idx++) rcd+=nco_fl_open(fl_in,md_open,&bfr_sz_hnt,in_id_arr+thr_idx); #ifdef ENABLE_MPI if(prc_rnk == rnk_mgr){ /* MPI manager code */ /* Compensate for incrementing on each worker's first message */ var_wrt_nbr=-prc_nbr+1; idx=0; /* While variables remain to be processed or written... */ while(var_wrt_nbr < nbr_var_prc){ /* Receive message from any worker */ MPI_Recv(wrk_id_bfr,wrk_id_bfr_lng,MPI_INT,MPI_ANY_SOURCE,MPI_ANY_TAG,MPI_COMM_WORLD,&mpi_stt); /* Obtain MPI message tag type */ msg_tag_typ=mpi_stt.MPI_TAG; /* Get sender's prc_rnk */ rnk_wrk=wrk_id_bfr[0]; /* Allocate next variable, if any, to worker */ if(msg_tag_typ == msg_tag_wrk_rqs){ var_wrt_nbr++; /* [nbr] Number of variables written */ /* Worker closed output file before sending msg_tag_wrk_rqs */ TKN_WRT_FREE=True; if(idx > nbr_var_prc-1){ msg_bfr[0]=idx_all_wrk_ass; /* [enm] All variables already assigned */ msg_bfr[1]=out_id; /* Output file ID */ }else{ /* Tell requesting worker to allocate space for next variable */ msg_bfr[0]=idx; /* [idx] Variable to be processed */ msg_bfr[1]=out_id; /* Output file ID */ msg_bfr[2]=var_prc_out[idx]->id; /* [id] Variable ID in output file */ /* Point to next variable on list */ idx++; } /* endif idx */ MPI_Send(msg_bfr,msg_bfr_lng,MPI_INT,rnk_wrk,msg_tag_wrk_rsp,MPI_COMM_WORLD); /* msg_tag_typ != msg_tag_wrk_rqs */ }else if(msg_tag_typ == msg_tag_tkn_wrt_rqs){ /* Allocate token if free, else ask worker to try later */ if(TKN_WRT_FREE){ TKN_WRT_FREE=False; msg_bfr[0]=tkn_wrt_rqs_xcp; /* Accept request for write token */ }else{ msg_bfr[0]=tkn_wrt_rqs_dny; /* Deny request for write token */ } /* !TKN_WRT_FREE */ MPI_Send(msg_bfr,msg_bfr_lng,MPI_INT,rnk_wrk,msg_tag_tkn_wrt_rsp,MPI_COMM_WORLD); } /* msg_tag_typ != msg_tag_tkn_wrt_rqs */ } /* end while var_wrt_nbr < nbr_var_prc */ }else{ /* prc_rnk != rnk_mgr, end Manager code begin Worker code */ wrk_id_bfr[0]=prc_rnk; while(1){ /* While work remains... */ /* Send msg_tag_wrk_rqs */ wrk_id_bfr[0]=prc_rnk; MPI_Send(wrk_id_bfr,wrk_id_bfr_lng,MPI_INT,rnk_mgr,msg_tag_wrk_rqs,MPI_COMM_WORLD); /* Receive msg_tag_wrk_rsp */ MPI_Recv(msg_bfr,msg_bfr_lng,MPI_INT,0,msg_tag_wrk_rsp,MPI_COMM_WORLD,&mpi_stt); idx=msg_bfr[0]; out_id=msg_bfr[1]; if(idx == idx_all_wrk_ass) break; else{ lcl_idx_lst[lcl_nbr_var]=idx; /* storing the indices for subsequent processing by the worker */ lcl_nbr_var++; var_prc_out[idx]->id=msg_bfr[2]; /* Process this variable same as UP code */ #if 0 /* NB: Immediately preceding MPI else scope confounds Emacs indentation Fake end scope restores correct indentation, simplifies code-checking */ } /* fake end else */ #endif /* !0 */ #else /* !ENABLE_MPI */ #ifdef _OPENMP #pragma omp parallel for default(none) private(idx,in_id) shared(aed_lst_add_fst,aed_lst_scl_fct,nco_dbg_lvl,dmn_idx_out_in,dmn_rdr_nbr,dmn_rvr_in,in_id_arr,nbr_var_prc,nco_pck_map,nco_pck_plc,out_id,nco_prg_nm,rcd,var_prc,var_prc_out) #endif /* !_OPENMP */ /* UP and SMP codes main loop over variables */ for(idx=0;idx<nbr_var_prc;idx++){ /* Process all variables in current file */ #endif /* ENABLE_MPI */ in_id=in_id_arr[omp_get_thread_num()]; /* fxm TODO nco638 temporary fix? */ var_prc[idx]->nc_id=in_id; if(nco_dbg_lvl >= nco_dbg_var) rcd+=nco_var_prc_crr_prn(idx,var_prc[idx]->nm); if(nco_dbg_lvl >= nco_dbg_var) (void)fflush(fp_stderr); /* Retrieve variable from disk into memory */ /* NB: nco_var_get() with same nc_id contains OpenMP critical region */ (void)nco_msa_var_get(in_id,var_prc[idx],lmt_all_lst,nbr_dmn_fl); if(dmn_rdr_nbr > 0){ if((var_prc_out[idx]->val.vp=(void *)nco_malloc_flg(var_prc_out[idx]->sz*nco_typ_lng(var_prc_out[idx]->type))) == NULL){ (void)fprintf(fp_stdout,"%s: ERROR Unable to malloc() %ld*%lu bytes for value buffer for variable %s in main()\n",nco_prg_nm_get(),var_prc_out[idx]->sz,(unsigned long)nco_typ_lng(var_prc_out[idx]->type),var_prc_out[idx]->nm); nco_exit(EXIT_FAILURE); } /* endif err */ /* Change dimensionionality of values */ rcd=nco_var_dmn_rdr_val(var_prc[idx],var_prc_out[idx],dmn_idx_out_in[idx],dmn_rvr_in[idx]); /* Re-ordering required two value buffers, time to free input buffer */ var_prc[idx]->val.vp=nco_free(var_prc[idx]->val.vp); /* Free current dimension correspondence */ dmn_idx_out_in[idx]=nco_free(dmn_idx_out_in[idx]); dmn_rvr_in[idx]=nco_free(dmn_rvr_in[idx]); } /* endif dmn_rdr_nbr > 0 */ if(nco_pck_plc != nco_pck_plc_nil){ /* Copy input variable buffer to processed variable buffer */ /* fxm: this is dangerous and leads to double free()'ing variable buffer */ var_prc_out[idx]->val=var_prc[idx]->val; /* (Un-)Pack variable according to packing specification */ nco_pck_val(var_prc[idx],var_prc_out[idx],nco_pck_map,nco_pck_plc,aed_lst_add_fst+idx,aed_lst_scl_fct+idx); } /* endif dmn_rdr_nbr > 0 */ #ifdef ENABLE_MPI /* Obtain token and prepare to write */ while(1){ /* Send msg_tag_tkn_wrt_rqs repeatedly until token obtained */ wrk_id_bfr[0]=prc_rnk; MPI_Send(wrk_id_bfr,wrk_id_bfr_lng,MPI_INT,rnk_mgr,msg_tag_tkn_wrt_rqs,MPI_COMM_WORLD); MPI_Recv(msg_bfr,msg_bfr_lng,MPI_INT,rnk_mgr,msg_tag_tkn_wrt_rsp,MPI_COMM_WORLD,&mpi_stt); tkn_wrt_rsp=msg_bfr[0]; /* Wait then re-send request */ if(tkn_wrt_rsp == tkn_wrt_rqs_dny) sleep(tkn_wrt_rqs_ntv); else break; } /* end while loop waiting for write token */ /* Worker has token---prepare to write */ if(tkn_wrt_rsp == tkn_wrt_rqs_xcp){ if(RAM_OPEN) md_open=NC_WRITE|NC_SHARE|NC_DISKLESS; else md_open=NC_WRITE|NC_SHARE; rcd=nco_fl_open(fl_out_tmp,md_open,&bfr_sz_hnt,&out_id); /* Set chunksize parameters */ if(fl_out_fmt == NC_FORMAT_NETCDF4 || fl_out_fmt == NC_FORMAT_NETCDF4_CLASSIC) (void)nco_cnk_sz_set(out_id,lmt_all_lst,nbr_dmn_fl,&cnk_map,&cnk_plc,cnk_sz_scl,cnk_dmn,cnk_nbr); /* Turn-off default filling behavior to enhance efficiency */ nco_set_fill(out_id,NC_NOFILL,&fll_md_old); #else /* !ENABLE_MPI */ #ifdef _OPENMP #pragma omp critical #endif /* _OPENMP */ #endif /* !ENABLE_MPI */ { /* begin OpenMP critical */ /* Common code for UP, SMP, and MPI */ /* Copy variable to output file then free value buffer */ if(var_prc_out[idx]->nbr_dim == 0){ (void)nco_put_var1(out_id,var_prc_out[idx]->id,var_prc_out[idx]->srt,var_prc_out[idx]->val.vp,var_prc_out[idx]->type); }else{ /* end if variable is scalar */ (void)nco_put_vara(out_id,var_prc_out[idx]->id,var_prc_out[idx]->srt,var_prc_out[idx]->cnt,var_prc_out[idx]->val.vp,var_prc_out[idx]->type); } /* end if variable is array */ } /* end OpenMP critical */ /* Free current output buffer */ var_prc_out[idx]->val.vp=nco_free(var_prc_out[idx]->val.vp); #ifdef ENABLE_MPI /* Close output file and increment written counter */ nco_close(out_id); var_wrt_nbr++; } /* endif tkn_wrt_rqs_xcp */ } /* end else !idx_all_wrk_ass */ } /* end while loop requesting work/token */ } /* endif Worker */ #else /* !ENABLE_MPI */ } /* end (OpenMP parallel for) loop over idx */ #endif /* !ENABLE_MPI */ if(nco_dbg_lvl >= nco_dbg_fl) (void)fprintf(fp_stderr,"\n"); #ifdef ENABLE_MPI MPI_Barrier(MPI_COMM_WORLD); if(prc_rnk == rnk_mgr) { /* Manager only */ MPI_Send(msg_bfr,msg_bfr_lng,MPI_INT,prc_rnk+1,msg_tag_tkn_wrt_rsp,MPI_COMM_WORLD); } /* ! prc_rnk == rnk_mgr */ else{ /* Workers */ MPI_Recv(msg_bfr,msg_bfr_lng,MPI_INT,prc_rnk-1,msg_tag_tkn_wrt_rsp,MPI_COMM_WORLD,&mpi_stt); #endif /* !ENABLE_MPI */ /* Write/overwrite packing attributes for newly packed and re-packed variables Logic here should nearly mimic logic in nco_var_dfn() */ if(nco_pck_plc != nco_pck_plc_nil && nco_pck_plc != nco_pck_plc_upk){ nco_bool nco_pck_plc_alw; /* [flg] Packing policy allows packing nc_typ_in */ /* ...put file in define mode to allow metadata writing... */ if(RAM_OPEN) md_open=NC_WRITE|NC_DISKLESS; else md_open=NC_WRITE; rcd=nco_fl_open(fl_out_tmp,md_open,&bfr_sz_hnt,&out_id); (void)nco_redef(out_id); /* ...loop through all variables that may have been packed... */ #ifdef ENABLE_MPI for(jdx=0;jdx<lcl_nbr_var;jdx++){ idx=lcl_idx_lst[jdx]; #else /* !ENABLE_MPI */ for(idx=0;idx<nbr_var_prc;idx++){ #endif /* !ENABLE_MPI */ /* nco_var_dfn() pre-defined dummy packing attributes in output file only for input variables considered "packable" */ if((nco_pck_plc_alw=nco_pck_plc_typ_get(nco_pck_map,var_prc[idx]->typ_upk,(nc_type *)NULL))){ /* Verify input variable was newly packed by this operator Writing pre-existing (non-re-packed) attributes here would fail because nco_pck_dsk_inq() never fills in var->scl_fct.vp and var->add_fst.vp Logic is same as in nco_var_dfn() (except var_prc[] instead of var[]) If operator newly packed this particular variable... */ if( /* ...either because operator newly packs all variables... */ (nco_pck_plc == nco_pck_plc_all_new_att) || /* ...or because operator newly packs un-packed variables like this one... */ (nco_pck_plc == nco_pck_plc_all_xst_att && !var_prc[idx]->pck_ram) || /* ...or because operator re-packs packed variables like this one... */ (nco_pck_plc == nco_pck_plc_xst_new_att && var_prc[idx]->pck_ram) ){ /* Replace dummy packing attributes with final values, or delete them */ if(nco_dbg_lvl >= nco_dbg_io) (void)fprintf(stderr,"%s: main() replacing dummy packing attribute values for variable %s\n",nco_prg_nm,var_prc[idx]->nm); (void)nco_aed_prc(out_id,aed_lst_add_fst[idx].id,aed_lst_add_fst[idx]); (void)nco_aed_prc(out_id,aed_lst_scl_fct[idx].id,aed_lst_scl_fct[idx]); } /* endif variable is newly packed by this operator */ } /* endif nco_pck_plc_alw */ } /* end loop over var_prc */ (void)nco_enddef(out_id); #ifdef ENABLE_MPI nco_close(out_id); #endif /* !ENABLE_MPI */ } /* nco_pck_plc == nco_pck_plc_nil || nco_pck_plc == nco_pck_plc_upk */ #ifdef ENABLE_MPI if(prc_rnk == prc_nbr-1) /* Send Token to Manager */ MPI_Send(msg_bfr,msg_bfr_lng,MPI_INT,rnk_mgr,msg_tag_tkn_wrt_rsp,MPI_COMM_WORLD); else MPI_Send(msg_bfr,msg_bfr_lng,MPI_INT,prc_rnk+1,msg_tag_tkn_wrt_rsp,MPI_COMM_WORLD); } /* !Workers */ if(prc_rnk == rnk_mgr){ /* Only Manager */ MPI_Recv(msg_bfr,msg_bfr_lng,MPI_INT,prc_nbr-1,msg_tag_tkn_wrt_rsp,MPI_COMM_WORLD,&mpi_stt); } /* prc_rnk != rnk_mgr */ #endif /* !ENABLE_MPI */ /* Close input netCDF file */ for(thr_idx=0;thr_idx<thr_nbr;thr_idx++) nco_close(in_id_arr[thr_idx]); /* Remove local copy of file */ if(FL_RTR_RMT_LCN && RM_RMT_FL_PST_PRC) (void)nco_fl_rm(fl_in); } /* end loop over fl_idx */ #ifdef ENABLE_MPI MPI_Barrier(MPI_COMM_WORLD); /* Manager moves output file (closed by workers) from temporary to permanent location */ if(prc_rnk == rnk_mgr) (void)nco_fl_mv(fl_out_tmp,fl_out); #else /* !ENABLE_MPI */ /* Close output file and move it from temporary to permanent location */ (void)nco_fl_out_cls(fl_out,fl_out_tmp,out_id); #endif /* end !ENABLE_MPI */ /* Clean memory unless dirty memory allowed */ if(flg_mmr_cln){ /* ncpdq-specific memory cleanup */ if(dmn_rdr_nbr > 0){ /* Free dimension correspondence list */ for(idx=0;idx<nbr_var_prc;idx++){ dmn_idx_out_in[idx]=(int *)nco_free(dmn_idx_out_in[idx]); dmn_rvr_in[idx]=(nco_bool *)nco_free(dmn_rvr_in[idx]); } /* end loop over idx */ if(dmn_idx_out_in) dmn_idx_out_in=(int **)nco_free(dmn_idx_out_in); if(dmn_rvr_in) dmn_rvr_in=(nco_bool **)nco_free(dmn_rvr_in); if(dmn_rvr_rdr) dmn_rvr_rdr=(nco_bool *)nco_free(dmn_rvr_rdr); if(dmn_rdr_nbr_in > 0) dmn_rdr_lst_in=nco_sng_lst_free(dmn_rdr_lst_in,dmn_rdr_nbr_in); /* Free dimension list pointers */ dmn_rdr=(dmn_sct **)nco_free(dmn_rdr); /* Dimension structures in dmn_rdr are owned by dmn and dmn_out, free'd later */ } /* endif dmn_rdr_nbr > 0 */ if(nco_pck_plc != nco_pck_plc_nil){ if(nco_pck_plc_sng) nco_pck_plc_sng=(char *)nco_free(nco_pck_plc_sng); if(nco_pck_map_sng) nco_pck_map_sng=(char *)nco_free(nco_pck_map_sng); if(nco_pck_plc != nco_pck_plc_upk){ /* No need for loop over var_prc variables to free attribute values Variable structures and attribute edit lists share same attribute values Free them only once, and do it in nco_var_free() */ aed_lst_add_fst=(aed_sct *)nco_free(aed_lst_add_fst); aed_lst_scl_fct=(aed_sct *)nco_free(aed_lst_scl_fct); } /* nco_pck_plc == nco_pck_plc_upk */ } /* nco_pck_plc == nco_pck_plc_nil */ /* NB: lmt now referenced within lmt_all_lst[idx] */ for(idx=0;idx<nbr_dmn_fl;idx++) for(jdx=0;jdx< lmt_all_lst[idx]->lmt_dmn_nbr;jdx++) lmt_all_lst[idx]->lmt_dmn[jdx]=nco_lmt_free(lmt_all_lst[idx]->lmt_dmn[jdx]); if(nbr_dmn_fl > 0) lmt_all_lst=nco_lmt_all_lst_free(lmt_all_lst,nbr_dmn_fl); lmt=(lmt_sct**)nco_free(lmt); /* NCO-generic clean-up */ /* Free individual strings/arrays */ if(cmd_ln) cmd_ln=(char *)nco_free(cmd_ln); if(cnk_map_sng) cnk_map_sng=(char *)nco_free(cnk_map_sng); if(cnk_plc_sng) cnk_plc_sng=(char *)nco_free(cnk_plc_sng); if(fl_in) fl_in=(char *)nco_free(fl_in); if(fl_out) fl_out=(char *)nco_free(fl_out); if(fl_out_tmp) fl_out_tmp=(char *)nco_free(fl_out_tmp); if(fl_pth) fl_pth=(char *)nco_free(fl_pth); if(fl_pth_lcl) fl_pth_lcl=(char *)nco_free(fl_pth_lcl); if(in_id_arr) in_id_arr=(int *)nco_free(in_id_arr); /* Free lists of strings */ if(fl_lst_in && fl_lst_abb == NULL) fl_lst_in=nco_sng_lst_free(fl_lst_in,fl_nbr); if(fl_lst_in && fl_lst_abb) fl_lst_in=nco_sng_lst_free(fl_lst_in,1); if(fl_lst_abb) fl_lst_abb=nco_sng_lst_free(fl_lst_abb,abb_arg_nbr); if(gaa_nbr > 0) gaa_arg=nco_sng_lst_free(gaa_arg,gaa_nbr); if(var_lst_in_nbr > 0) var_lst_in=nco_sng_lst_free(var_lst_in,var_lst_in_nbr); /* Free limits */ for(idx=0;idx<lmt_nbr;idx++) lmt_arg[idx]=(char *)nco_free(lmt_arg[idx]); for(idx=0;idx<aux_nbr;idx++) aux_arg[idx]=(char *)nco_free(aux_arg[idx]); if(aux_nbr > 0) aux=(lmt_sct **)nco_free(aux); /* Free chunking information */ for(idx=0;idx<cnk_nbr;idx++) cnk_arg[idx]=(char *)nco_free(cnk_arg[idx]); if(cnk_nbr > 0) cnk_dmn=nco_cnk_lst_free(cnk_dmn,cnk_nbr); /* Free dimension lists */ if(nbr_dmn_xtr > 0) dim=nco_dmn_lst_free(dim,nbr_dmn_xtr); if(nbr_dmn_xtr > 0) dmn_out=nco_dmn_lst_free(dmn_out,nbr_dmn_xtr); /* Free variable lists */ if(xtr_nbr > 0) var=nco_var_lst_free(var,xtr_nbr); if(xtr_nbr > 0) var_out=nco_var_lst_free(var_out,xtr_nbr); var_prc=(var_sct **)nco_free(var_prc); var_prc_out=(var_sct **)nco_free(var_prc_out); var_fix=(var_sct **)nco_free(var_fix); var_fix_out=(var_sct **)nco_free(var_fix_out); } /* !flg_mmr_cln */ #ifdef ENABLE_MPI MPI_Finalize(); #endif /* !ENABLE_MPI */ nco_exit_gracefully(); return EXIT_SUCCESS; } /* end main() */
zgeinv.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @precisions normal z -> s d c * **/ #include "plasma.h" #include "plasma_async.h" #include "plasma_context.h" #include "plasma_descriptor.h" #include "plasma_internal.h" #include "plasma_tuning.h" #include "plasma_types.h" #include "plasma_workspace.h" /***************************************************************************//** * * @ingroup plasma_geinv * * Performs the LU inversion of a matrix A. * ******************************************************************************* * * @param[in] m * The number of rows in the matrix A. m >= 0 * * @param[in] n * The number of columns in the matrix A. n >= 0. * * @param[in,out] pA * On entry, the m-by-n matrix A to be inverted. * On exit, the inverse of A. * * @param[in] lda * The leading dimension of the array A. lda >= max(1,m). * * @param[out] ipiv * The pivot indices; for 1 <= i <= min(m,n), row i of the * matrix was interchanged with row ipiv(i). * ******************************************************************************* * * @retval PlasmaSuccess successful exit * @retval < 0 if -i, the i-th argument had an illegal value * @retval > 0 if i, the leading minor of order i of A is not * positive definite, so the factorization could not * be completed, and the solution has not been computed. * ******************************************************************************* * * @sa plasma_cgeinv * @sa plasma_dgeinv * @sa plasma_sgeinv * ******************************************************************************/ int plasma_zgeinv(int m, int n, plasma_complex64_t *pA, int lda, int *ipiv) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_fatal_error("PLASMA not initialized"); return PlasmaErrorNotInitialized; } // Check input arguments. if (m < 0) { plasma_error("illegal value of uplo"); return -1; } if (n < 0) { plasma_error("illegal value of n"); return -2; } if (lda < imax(1, n)) { plasma_error("illegal value of lda"); return -4; } // quick return if (imax(n, 0) == 0 || imax(m, 0) == 0) return PlasmaSuccess; // Tune parameters. if (plasma->tuning) plasma_tune_geinv(plasma, PlasmaComplexDouble, m, n); // Set tiling parameters. int nb = plasma->nb; // Initialize barrier. plasma_barrier_init(&plasma->barrier); // Create tile matrix. plasma_desc_t A; plasma_desc_t W; int retval; retval = plasma_desc_general_create(PlasmaComplexDouble, nb, nb, m, n, 0, 0, m, n, &A); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); return retval; } retval = plasma_desc_general_create(PlasmaComplexDouble, nb, nb, n, nb, 0, 0, n, nb, &W); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); plasma_desc_destroy(&A); return retval; } // Initialize sequence. plasma_sequence_t sequence; retval = plasma_sequence_init(&sequence); // Initialize request. plasma_request_t request; retval = plasma_request_init(&request); #pragma omp parallel #pragma omp master { // Translate to tile layout. plasma_omp_zge2desc(pA, lda, A, &sequence, &request); // Call the tile async function. plasma_omp_zgeinv(A, ipiv, W, &sequence, &request); // Translate back to LAPACK layout. plasma_omp_zdesc2ge(A, pA, lda, &sequence, &request); } // Free matrix A in tile layout. plasma_desc_destroy(&A); // Return status. int status = sequence.status; return status; } /***************************************************************************//** * * @ingroup plasma_geinv * * Computes the inverse of a complex Hermitian * positive definite matrix A using the Cholesky factorization. * ******************************************************************************* * * @param[in] A * On entry, the Hermitian positive definite matrix A. * On exit, the upper or lower triangle of the (Hermitian) * inverse of A, overwriting the input factor U or L. * * @param[out] ipiv * The pivot indices; for 1 <= i <= min(m,n), row i of the * matrix was interchanged with row ipiv(i). * * @param[out] W * Workspace of dimension (n, nb) * * @param[in] sequence * Identifies the sequence of function calls that this call belongs to * (for completion checks and exception handling purposes). Check * the sequence->status for errors. * * @param[out] request * Identifies this function call (for exception handling purposes). * * @retval void * Errors are returned by setting sequence->status and * request->status to error values. The sequence->status and * request->status should never be set to PlasmaSuccess (the * initial values) since another async call may be setting a * failure value at the same time. * ******************************************************************************* * * @sa plasma_zgeinv * @sa plasma_omp_zgeinv * @sa plasma_omp_cgeinv * @sa plasma_omp_dgeinv * @sa plasma_omp_sgeinv * ******************************************************************************/ void plasma_omp_zgeinv(plasma_desc_t A, int *ipiv, plasma_desc_t W, plasma_sequence_t *sequence, plasma_request_t *request) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_error("PLASMA not initialized"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // Check input arguments. if (plasma_desc_check(A) != PlasmaSuccess) { plasma_error("invalid A"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (sequence == NULL) { plasma_error("NULL sequence"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (request == NULL) { plasma_error("NULL request"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // quick return if ((A.m == 0) || (A.n == 0)) { return; } // Factorize A. plasma_pzgetrf(A, ipiv, sequence, request); // Invert triangular part. plasma_pztrtri(PlasmaUpper, PlasmaNonUnit, A, sequence, request); // Compute product of inverse of the upper and lower triangles. plasma_pzgetri_aux(A, W, sequence, request); // Apply pivot. plasma_pzgeswp(PlasmaColumnwise, A, ipiv, -1, sequence, request); }
XT_OffsetError.c
/* ============================================================================ * Copyright (c) 2015 K. Aditya Mohan (Purdue University) * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of K. Aditya Mohan, Purdue * University, nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ #include <stdio.h> #include "nrutil.h" #include "XT_Constants.h" #include "XT_Structures.h" #include <mpi.h> #include <math.h> #include "XT_IOMisc.h" #include "invert.h" #include "allocate.h" void gen_offset_constraint_windows (Sinogram* SinogramPtr, TomoInputs* TomoInputsPtr) { int32_t r_size, t_size, num = 0, i, j, k, l, dim[4], N_t_node, N_r, N_t, node_rank, node_num, node_idx, k_idx, l_idx; char constraint_file[100] = "proj_constraint"; node_rank = TomoInputsPtr->node_rank; node_num = TomoInputsPtr->node_num; N_r = SinogramPtr->N_r; N_t_node = SinogramPtr->N_t; N_t = N_t_node*node_num; r_size = 2*N_r/((int32_t)(sqrt(N_r) + 0.5)); t_size = 2*N_t/((int32_t)(sqrt(N_t) + 0.5)); for (i = 0; i <= N_r - r_size/2; i = i + r_size/2) for (j = 0; j <= N_t - t_size/2; j = j + t_size/2) num++; SinogramPtr->off_constraint = (Real_arr_t***)multialloc(sizeof(Real_arr_t), 3, num, N_r, N_t_node); memset(&(SinogramPtr->off_constraint[0][0][0]), 0, num*N_r*N_t_node*sizeof(Real_arr_t)); for (num = 0, i = 0; i <= N_r - r_size/2; i = i + r_size/2) for (j = 0; j <= N_t - t_size/2; j = j + t_size/2) { for (k = i; k < i + r_size; k++) for (l = j; l < j + t_size; l++) { node_idx = node_rank*N_t_node; k_idx = k % N_r; l_idx = l % N_t; if (l_idx >= node_idx && l_idx < node_idx + N_t_node) { SinogramPtr->off_constraint[num][k_idx][l_idx-node_idx] = (k-i) < r_size/2 ? (k-i+1): r_size-(k-i); SinogramPtr->off_constraint[num][k_idx][l_idx-node_idx] *= (l-j) < t_size/2 ? (l-j+1): t_size-(l-j); } } num++; } SinogramPtr->off_constraint_num = num; dim[0] = 1; dim[1] = num; dim[2] = SinogramPtr->N_r; dim[3] = SinogramPtr->N_t; sprintf(constraint_file, "%s_n%d", constraint_file, node_rank); if (TomoInputsPtr->Write2Tiff == 1) WriteMultiDimArray2Tiff (constraint_file, dim, 0, 1, 2, 3, &(SinogramPtr->off_constraint[0][0][0]), 0, TomoInputsPtr->debug_file_ptr); fprintf(TomoInputsPtr->debug_file_ptr, "gen_offset_constraint_windows: r_size = %d, t_size = %d, number of constraints = %d\n", r_size, t_size, SinogramPtr->off_constraint_num); /* SinogramPtr->off_constraint_size = SinogramPtr->N_r; SinogramPtr->off_constraint = (Real_t**)multialloc(sizeof(Real_t), 2, 1, SinogramPtr->N_r); for (j = 0; j < SinogramPtr->N_r; j++) SinogramPtr->off_constraint[0][j] = 1; SinogramPtr->off_constraint_num = 1;*/ } void constrained_quad_opt (Real_t** Lambda, Real_t** b, Real_arr_t*** A, Real_arr_t** x, int32_t Nr, int32_t Nt, int32_t M, TomoInputs* TomoInputsPtr) { Real_t **D, **Dinv; Real_t *temp, *temp2; int32_t i, j, k, l; D = (Real_t**)multialloc(sizeof(Real_t), 2, M, M); Dinv = (Real_t**)multialloc(sizeof(Real_t), 2, M, M); temp = (Real_t*)get_spc(M, sizeof(Real_t)); temp2 = (Real_t*)get_spc(M, sizeof(Real_t)); memset(&(D[0][0]), 0, M*M*sizeof(Real_t)); memset(&(Dinv[0][0]), 0, M*M*sizeof(Real_t)); #pragma omp parallel for collapse(2) private(k, l) for (i = 0; i < M; i++) for (j = 0; j < M; j++) for (k = 0; k < Nr; k++) for (l = 0; l < Nt; l++) { D[i][j] += A[i][k][l]*A[j][k][l]/Lambda[k][l]; /*sum += A[i][k]*A[j][k]/Lambda[k];*/ } /* TomoInputsPtr->t0_mpired1 = time(NULL); */ MPI_Allreduce(&(D[0][0]), &(Dinv[0][0]), M*M, MPI_REAL_DATATYPE, MPI_SUM, MPI_COMM_WORLD); /* TomoInputsPtr->time_mpired1 += difftime(time(NULL), TomoInputsPtr->t0_mpired1);*/ /* printf("Checksum is %f\n", sum);*/ invert2(Dinv, M); #pragma omp parallel for private(j, k) for (i = 0; i < M; i++) { temp[i] = 0; for (j = 0; j < Nr; j++) for (k = 0; k < Nt; k++) temp[i] += A[i][j][k]*b[j][k]/Lambda[j][k]; } /* TomoInputsPtr->t0_mpired1 = time(NULL);*/ MPI_Allreduce(&(temp[0]), &(temp2[0]), M, MPI_REAL_DATATYPE, MPI_SUM, MPI_COMM_WORLD); /* TomoInputsPtr->time_mpired1 += difftime(time(NULL), TomoInputsPtr->t0_mpired1);*/ #pragma omp parallel for private(j) for (i = 0; i < M; i++) { temp[i] = 0; for (j = 0; j < M; j++) temp[i] += Dinv[i][j]*temp2[j]; } /* TomoInputsPtr->t0_mpired1 = time(NULL); MPI_Allreduce(&(temp[0]), &(temp2[0]), M, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); TomoInputsPtr->time_mpired1 += difftime(time(NULL), TomoInputsPtr->t0_mpired1);*/ #pragma omp parallel for collapse(2) private(k) for (i = 0; i < Nr; i++) for (j = 0; j < Nt; j++) { x[i][j] = 0; for (k = 0; k < M; k++) x[i][j] += A[k][i][j]*temp[k]; } #pragma omp parallel for collapse(2) for (i = 0; i < Nr; i++) for (j = 0; j < Nt; j++) x[i][j] = (b[i][j] - x[i][j])/Lambda[i][j]; free(temp); free(temp2); multifree(D, 2); multifree(Dinv, 2); } void compute_d_constraint (Real_arr_t*** A, Real_arr_t **d, int32_t Nr, int32_t Nt, int32_t M, FILE* debug_file_ptr) { int32_t i, j, k; Real_t *temp, *val; temp = (Real_t*)get_spc(M, sizeof(Real_t)); val = (Real_t*)get_spc(M, sizeof(Real_t)); #pragma omp parallel for private(j, k) for (i = 0; i < M; i++) { temp[i] = 0; for (j = 0; j < Nr; j++) for (k = 0; k < Nt; k++) temp[i] += A[i][j][k]*d[j][k]; } MPI_Allreduce(&(temp[0]), &(val[0]), M, MPI_REAL_DATATYPE, MPI_SUM, MPI_COMM_WORLD); for (i = 0; i < M; i++) fprintf(debug_file_ptr, "compute_d_constraint: The i th constraint on offset error is %f\n", val[i]); free(temp); free(val); }
ex3_openmp.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <unistd.h> #include <math.h> #include <omp.h> #define N 100 long f[26]; char* file; void read_file(char* file) { char* line = NULL; size_t len = 0; ssize_t read; int i; FILE* in = fopen(file, "r"); while ((read = getline(&line, &len, in)) != -1) { // printf("Retrieved line of length %zu:\n", read); // printf("%s", line); for (i = 0; i < read; i++) { if (line[i] >= 'A' && line[i] <= 'Z') { f[line[i] - 'A']++; } } } fclose(in); } void printResult() { int i; for (i = 0; i < 26; i++) { printf("%c %ld\n", (char)(i + 65), f[i]); } } int main() { int i, tid, numThreads; double t1, t2; file = (char*) calloc(5, sizeof(char)); t1 = omp_get_wtime(); #pragma omp parallel default(shared) private(i, tid) { tid = omp_get_thread_num(); numThreads = omp_get_num_threads(); int start = tid * ceil((double)N / numThreads); int end = fmin(N , (tid + 1) * ceil((double)N / numThreads)); // printf("%d %d\n", start, end); for (i = start; i < end; i++) { #pragma omp critical { sprintf(file, "files/f%d", i); read_file(file); } } } t2 = omp_get_wtime(); printResult(); printf("Execution time %g\n", t2 - t1); return 0; }
opt_wave3d_4oa.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) #include <stdlib.h> #include <string.h> #include <stdio.h> #include <math.h> #include <sys/time.h> #include <stencil_config.h> #define NONUMA #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #if defined(_OPENMP) #endif double seconds() { struct timeval tv; gettimeofday(&tv,NULL); return (double)(tv.tv_sec)+1e-6*tv.tv_usec; } int malloc_error(const char* err) { fprintf(stderr,"Failed to allocate the field %s.\n",err); return EXIT_FAILURE; } int validate_results(int x_max,int y_max,int z_max,int T_MAX,void**** _opt_res) { double tim1;double tim2;double nFlops; int i;int j;int k;int t; int x;int y;int z; const double MIN=-1.f; const double MAX=1.f; const double DX=(MAX-MIN)/(x_max-3); const double DT=DX/2.0f; const double DT_DX_SQUARE=DT*DT/(DX*DX); double(*u)[x_max][y_max][z_max] = (double*)malloc(3*x_max*y_max*z_max*sizeof (double)); if (u==NULL) { return malloc_error("u"); } memset(u,0,3*x_max*sizeof (double)); for (k=2; k<z_max-2; k+=1) { for (j=2; j<y_max-2; j+=1) { for (i=2; i<x_max-2; i+=1) { double x=(i-1)*DX+MIN; double y=(j-1)*DX+MIN; double z=(k-1)*DX+MIN; if (k==2) { u[0][i][j][0] = 0; u[0][i][j][1] = 0; u[1][i][j][0] = 0; u[1][i][j][1] = 0; } if (k==z_max-3) { u[0][i][j][z_max-2] = 0; u[0][i][j][z_max-1] = 0; u[1][i][j][z_max-2] = 0; u[1][i][j][z_max-1] = 0; } if (j==2) { u[0][i][0][k] = 0; u[0][i][1][k] = 0; u[1][i][0][k] = 0; u[1][i][1][k] = 0; } if (j==y_max-3) { u[0][i][y_max-2][k] = 0; u[0][i][y_max-1][k] = 0; u[1][i][y_max-2][k] = 0; u[1][i][y_max-1][k] = 0; } if (i==2) { u[0][0][j][k] = 0; u[0][1][j][k] = 0; u[1][0][j][k] = 0; u[1][1][j][k] = 0; } if (i==x_max-3) { u[0][x_max-2][j][k] = 0; u[0][x_max-1][j][k] = 0; u[1][x_max-2][j][k] = 0; u[1][x_max-1][j][k] = 0; } u[1][i][j][k] = (double)(sin(2*M_PI*x)*sin(2*M_PI*y)*sin(2*M_PI*z)); u[0][i][j][k] = u[1][i][j][k]; } } } double sc1=1.0/12; double sc2=4.0/3.0; double sc3=5.0/2.0; tim1 = seconds(); for (t=0; t<T_MAX; t+=1) { for (i=2; i<x_max-2; i+=1) { for (j=2; j<y_max-2; j+=1) { for (k=2; k<z_max-2; k+=1) { u[(t+2)%3][i][j][k] = -sc1*u[(t+1)%3][i-2][j][k]+sc2*u[(t+1)%3][i-1][j][k]-sc3*u[(t+1)%3][i][j][k]+sc2*u[(t+1)%3][i+1][j][k]-sc1*u[(t+1)%3][i+2][j][k]+(-sc1*u[(t+1)%3][i][j-2][k]+sc2*u[(t+1)%3][i][j-1][k]-sc3*u[(t+1)%3][i][j][k]+sc2*u[(t+1)%3][i][j+1][k]-sc1*u[(t+1)%3][i][j+2][k])+(-sc1*u[(t+1)%3][i][j][k-2]+sc2*u[(t+1)%3][i][j][k-1]-sc3*u[(t+1)%3][i][j][k]+sc2*u[(t+1)%3][i][j][k+1]-sc1*u[(t+1)%3][i][j][k+2])+2*u[(t+1)%3][i][j][k]-u[t%3][i][j][k]; } } } } tim2 = seconds(); double(*opt_res)[x_max][y_max][z_max] = _opt_res; for (x=1; x<x_max-1; x+=1) { for (y=1; y<y_max-1; y+=1) { for (z=1; z<z_max-1; z+=1) { if (u[2][x][y][z]!=opt_res[2][x][y][z]) { fprintf(stderr,"Index (%d, %d, %d) differs by %.16lf",x,y,z,u[2][x][y][z]-opt_res[2][x][y][z]); exit(EXIT_FAILURE); } } } } printf("%s\n%s\n%s\n","---------------------------------------------------------","Opt stencil successfully validated against normal version","---------------------------------------------------------"); nFlops = (double)((x_max-4)*(double)((y_max-4)*(double)((z_max-4)*T_MAX*35.0))); printf("ORIGINAL FLOPs in stencil code: %e\n",nFlops); printf("ORIGINAL Time spent in stencil code: %f\n",tim2-tim1); printf("ORIGINAL Performance in GFlop/s: %f\n",nFlops/(1e9*(tim2-tim1))); free(u); return 0; } int main(int argc,char** argv) { int i=0;int j=0;int k=0;int t; double tim1;double tim2;double nFlops; if (argc!=5) { printf("Wrong number of parameters, <xmax> <ymax> <zmax> <timesteps>.\n",argv[0]); exit(-1); } int x_max=atoi(argv[1])+4; int y_max=atoi(argv[2])+4; int z_max=atoi(argv[3])+4; int T_MAX=atoi(argv[4]); const double MIN=-1.f; const double MAX=1.f; const double DX=(MAX-MIN)/(x_max-3); const double DT=DX/2.0f; const double DT_DX_SQUARE=DT*DT/(DX*DX); double(*u)[x_max][y_max][z_max] = (double*)malloc(3*x_max*y_max*z_max*sizeof (double)); if (u==NULL) { return malloc_error("u"); } memset(u,0,3*x_max*sizeof (double)); for (k=2; k<z_max-2; k+=1) { for (j=2; j<y_max-2; j+=1) { for (i=2; i<x_max-2; i+=1) { double x=(i-1)*DX+MIN; double y=(j-1)*DX+MIN; double z=(k-1)*DX+MIN; if (k==2) { u[0][i][j][0] = 0; u[0][i][j][1] = 0; u[1][i][j][0] = 0; u[1][i][j][1] = 0; } if (k==z_max-3) { u[0][i][j][z_max-2] = 0; u[0][i][j][z_max-1] = 0; u[1][i][j][z_max-2] = 0; u[1][i][j][z_max-1] = 0; } if (j==2) { u[0][i][0][k] = 0; u[0][i][1][k] = 0; u[1][i][0][k] = 0; u[1][i][1][k] = 0; } if (j==y_max-3) { u[0][i][y_max-2][k] = 0; u[0][i][y_max-1][k] = 0; u[1][i][y_max-2][k] = 0; u[1][i][y_max-1][k] = 0; } if (i==2) { u[0][0][j][k] = 0; u[0][1][j][k] = 0; u[1][0][j][k] = 0; u[1][1][j][k] = 0; } if (i==x_max-3) { u[0][x_max-2][j][k] = 0; u[0][x_max-1][j][k] = 0; u[1][x_max-2][j][k] = 0; u[1][x_max-1][j][k] = 0; } u[1][i][j][k] = (double)(sin(2*M_PI*x)*sin(2*M_PI*y)*sin(2*M_PI*z)); u[0][i][j][k] = u[1][i][j][k]; } } } double sc1=1.0/12; double sc2=4.0/3.0; double sc3=5.0/2.0; tim1 = seconds(); int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; if ((T_MAX >= 1) && (T_MAX <= 2147483646) && (x_max >= 5) && (y_max >= 5) && (z_max >= 5)) { for (t1=-1;t1<=floord(T_MAX-1,8);t1++) { lbp=max(ceild(t1,2),ceild(16*t1-T_MAX+2,16)); ubp=min(floord(16*t1+x_max+12,32),floord(x_max+2*T_MAX-5,32)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(t1-1,2)),ceild(32*t2-x_max-25,32));t3<=min(min(min(floord(16*t1+y_max+27,32),floord(32*t2+y_max+25,32)),floord(y_max+2*T_MAX-5,32)),floord(32*t1-32*t2+y_max+x_max+25,32));t3++) { for (t4=max(max(max(0,ceild(t1-1,2)),ceild(32*t2-x_max-25,32)),ceild(32*t3-y_max-25,32));t4<=min(min(min(min(floord(16*t1+z_max+27,32),floord(32*t2+z_max+25,32)),floord(32*t3+z_max+25,32)),floord(z_max+2*T_MAX-5,32)),floord(32*t1-32*t2+z_max+x_max+25,32));t4++) { for (t5=max(max(max(max(max(0,ceild(32*t2-x_max+3,2)),ceild(32*t3-y_max+3,2)),ceild(32*t4-z_max+3,2)),8*t1),16*t1-16*t2+1);t5<=min(min(min(min(min(floord(32*t1-32*t2+x_max+28,2),T_MAX-1),8*t1+15),16*t2+14),16*t3+14),16*t4+14);t5++) { for (t6=max(max(32*t2,2*t5+2),-32*t1+32*t2+4*t5-31);t6<=min(min(32*t2+31,-32*t1+32*t2+4*t5),2*t5+x_max-3);t6++) { for (t7=max(32*t3,2*t5+2);t7<=min(32*t3+31,2*t5+y_max-3);t7++) { lbv=max(32*t4,2*t5+2); ubv=min(32*t4+31,2*t5+z_max-3); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { u[(t5 + 2) % 3][(-2*t5+t6)][(-2*t5+t7)][(-2*t5+t8)] = ((((((((((-sc1) * u[(t5 + 1) % 3][(-2*t5+t6) - 2][(-2*t5+t7)][(-2*t5+t8)]) + (sc2 * u[(t5 + 1) % 3][(-2*t5+t6) - 1][(-2*t5+t7)][(-2*t5+t8)])) - (sc3 * u[(t5 + 1) % 3][(-2*t5+t6)][(-2*t5+t7)][(-2*t5+t8)])) + (sc2 * u[(t5 + 1) % 3][(-2*t5+t6) + 1][(-2*t5+t7)][(-2*t5+t8)])) - (sc1 * u[(t5 + 1) % 3][(-2*t5+t6) + 2][(-2*t5+t7)][(-2*t5+t8)])) + ((((((-sc1) * u[(t5 + 1) % 3][(-2*t5+t6)][(-2*t5+t7) - 2][(-2*t5+t8)]) + (sc2 * u[(t5 + 1) % 3][(-2*t5+t6)][(-2*t5+t7) - 1][(-2*t5+t8)])) - (sc3 * u[(t5 + 1) % 3][(-2*t5+t6)][(-2*t5+t7)][(-2*t5+t8)])) + (sc2 * u[(t5 + 1) % 3][(-2*t5+t6)][(-2*t5+t7) + 1][(-2*t5+t8)])) - (sc1 * u[(t5 + 1) % 3][(-2*t5+t6)][(-2*t5+t7) + 2][(-2*t5+t8)]))) + ((((((-sc1) * u[(t5 + 1) % 3][(-2*t5+t6)][(-2*t5+t7)][(-2*t5+t8) - 2]) + (sc2 * u[(t5 + 1) % 3][(-2*t5+t6)][(-2*t5+t7)][(-2*t5+t8) - 1])) - (sc3 * u[(t5 + 1) % 3][(-2*t5+t6)][(-2*t5+t7)][(-2*t5+t8)])) + (sc2 * u[(t5 + 1) % 3][(-2*t5+t6)][(-2*t5+t7)][(-2*t5+t8) + 1])) - (sc1 * u[(t5 + 1) % 3][(-2*t5+t6)][(-2*t5+t7)][(-2*t5+t8) + 2]))) + (2 * u[(t5 + 1) % 3][(-2*t5+t6)][(-2*t5+t7)][(-2*t5+t8)])) - u[t5 % 3][(-2*t5+t6)][(-2*t5+t7)][(-2*t5+t8)]);; } } } } } } } } } tim2 = seconds(); validate_results(x_max,y_max,z_max,T_MAX,u); nFlops = (double)((x_max-4)*(double)((y_max-4)*(double)((z_max-4)*T_MAX*35.0))); printf("\nOPTIMIZED FLOPs in stencil code: %e\n",nFlops); printf("OPTIMIZED Time spent in stencil code: %f\n",tim2-tim1); printf("OPTIMIZED Performance in GFlop/s: %f\n",nFlops/(1e9*(tim2-tim1))); free(u); return EXIT_SUCCESS; }
10.race1.c
// RUN: clang %loadLLOV %s -o /dev/null 2>&1 | FileCheck %s #include <omp.h> int main() { int x = 0; #pragma omp parallel num_threads(8) { #pragma omp sections // firstprivate(x) { { x = 1; } #pragma omp section { x = 2; } } } return x; } // CHECK: Data Race detected // END
nvptx_target_printf_codegen.c
// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --function-signature --include-generated-funcs --replace-value-regex "__omp_offloading_[0-9a-z]+_[0-9a-z]+" "reduction_size[.].+[.]" "pl_cond[.].+[.|,]" --prefix-filecheck-ir-name _ // Test target codegen - host bc file has to be created first. // RUN: %clang_cc1 -verify -fopenmp -x c -triple powerpc64le-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm-bc %s -o %t-ppc-host.bc // RUN: %clang_cc1 -verify -fopenmp -x c -triple nvptx64-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-64 // RUN: %clang_cc1 -verify -fopenmp -x c -triple i386-unknown-unknown -fopenmp-targets=nvptx-nvidia-cuda -emit-llvm-bc %s -o %t-x86-host.bc // RUN: %clang_cc1 -verify -fopenmp -x c -triple nvptx-unknown-unknown -fopenmp-targets=nvptx-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-32 // expected-no-diagnostics extern int printf(const char *, ...); // Check a simple call to printf end-to-end. int CheckSimple(void) { #pragma omp target { // printf in master-only basic block. const char* fmt = "%d %lld %f"; printf(fmt, 1, 2ll, 3.0); } return 0; } void CheckNoArgs(void) { #pragma omp target { // printf in master-only basic block. printf("hello, world!"); } } // Check that printf's alloca happens in the entry block, not inside the if // statement. int foo; void CheckAllocaIsInEntryBlock(void) { #pragma omp target { if (foo) { printf("%d", 42); } } } // // // // CHECK-64-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}_CheckSimple_l13 // CHECK-64-SAME: () #[[ATTR0:[0-9]+]] { // CHECK-64-NEXT: entry: // CHECK-64-NEXT: [[FMT:%.*]] = alloca i8*, align 8 // CHECK-64-NEXT: [[TMP:%.*]] = alloca [[PRINTF_ARGS:%.*]], align 8 // CHECK-64-NEXT: [[TMP0:%.*]] = call i32 @__kmpc_target_init(%struct.ident_t* @[[GLOB1:[0-9]+]], i8 1, i1 true, i1 true) // CHECK-64-NEXT: [[EXEC_USER_CODE:%.*]] = icmp eq i32 [[TMP0]], -1 // CHECK-64-NEXT: br i1 [[EXEC_USER_CODE]], label [[USER_CODE_ENTRY:%.*]], label [[WORKER_EXIT:%.*]] // CHECK-64: user_code.entry: // CHECK-64-NEXT: store i8* getelementptr inbounds ([11 x i8], [11 x i8]* @.str, i64 0, i64 0), i8** [[FMT]], align 8 // CHECK-64-NEXT: [[TMP1:%.*]] = load i8*, i8** [[FMT]], align 8 // CHECK-64-NEXT: [[TMP2:%.*]] = getelementptr inbounds [[PRINTF_ARGS]], %printf_args* [[TMP]], i32 0, i32 0 // CHECK-64-NEXT: store i32 1, i32* [[TMP2]], align 4 // CHECK-64-NEXT: [[TMP3:%.*]] = getelementptr inbounds [[PRINTF_ARGS]], %printf_args* [[TMP]], i32 0, i32 1 // CHECK-64-NEXT: store i64 2, i64* [[TMP3]], align 8 // CHECK-64-NEXT: [[TMP4:%.*]] = getelementptr inbounds [[PRINTF_ARGS]], %printf_args* [[TMP]], i32 0, i32 2 // CHECK-64-NEXT: store double 3.000000e+00, double* [[TMP4]], align 8 // CHECK-64-NEXT: [[TMP5:%.*]] = bitcast %printf_args* [[TMP]] to i8* // CHECK-64-NEXT: [[TMP6:%.*]] = call i32 @__llvm_omp_vprintf(i8* [[TMP1]], i8* [[TMP5]], i32 24) // CHECK-64-NEXT: call void @__kmpc_target_deinit(%struct.ident_t* @[[GLOB1]], i8 1, i1 true) // CHECK-64-NEXT: ret void // CHECK-64: worker.exit: // CHECK-64-NEXT: ret void // // // CHECK-64-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}_CheckNoArgs_l25 // CHECK-64-SAME: () #[[ATTR0]] { // CHECK-64-NEXT: entry: // CHECK-64-NEXT: [[TMP0:%.*]] = call i32 @__kmpc_target_init(%struct.ident_t* @[[GLOB1]], i8 1, i1 true, i1 true) // CHECK-64-NEXT: [[EXEC_USER_CODE:%.*]] = icmp eq i32 [[TMP0]], -1 // CHECK-64-NEXT: br i1 [[EXEC_USER_CODE]], label [[USER_CODE_ENTRY:%.*]], label [[WORKER_EXIT:%.*]] // CHECK-64: user_code.entry: // CHECK-64-NEXT: [[TMP1:%.*]] = call i32 @__llvm_omp_vprintf(i8* getelementptr inbounds ([14 x i8], [14 x i8]* @.str1, i64 0, i64 0), i8* null, i32 0) // CHECK-64-NEXT: call void @__kmpc_target_deinit(%struct.ident_t* @[[GLOB1]], i8 1, i1 true) // CHECK-64-NEXT: ret void // CHECK-64: worker.exit: // CHECK-64-NEXT: ret void // // // CHECK-64-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}_CheckAllocaIsInEntryBlock_l36 // CHECK-64-SAME: (i64 noundef [[FOO:%.*]]) #[[ATTR0]] { // CHECK-64-NEXT: entry: // CHECK-64-NEXT: [[FOO_ADDR:%.*]] = alloca i64, align 8 // CHECK-64-NEXT: [[TMP:%.*]] = alloca [[PRINTF_ARGS_0:%.*]], align 8 // CHECK-64-NEXT: store i64 [[FOO]], i64* [[FOO_ADDR]], align 8 // CHECK-64-NEXT: [[CONV:%.*]] = bitcast i64* [[FOO_ADDR]] to i32* // CHECK-64-NEXT: [[TMP0:%.*]] = call i32 @__kmpc_target_init(%struct.ident_t* @[[GLOB1]], i8 1, i1 true, i1 true) // CHECK-64-NEXT: [[EXEC_USER_CODE:%.*]] = icmp eq i32 [[TMP0]], -1 // CHECK-64-NEXT: br i1 [[EXEC_USER_CODE]], label [[USER_CODE_ENTRY:%.*]], label [[WORKER_EXIT:%.*]] // CHECK-64: user_code.entry: // CHECK-64-NEXT: [[TMP1:%.*]] = load i32, i32* [[CONV]], align 4 // CHECK-64-NEXT: [[TOBOOL:%.*]] = icmp ne i32 [[TMP1]], 0 // CHECK-64-NEXT: br i1 [[TOBOOL]], label [[IF_THEN:%.*]], label [[IF_END:%.*]] // CHECK-64: if.then: // CHECK-64-NEXT: [[TMP2:%.*]] = getelementptr inbounds [[PRINTF_ARGS_0]], %printf_args.0* [[TMP]], i32 0, i32 0 // CHECK-64-NEXT: store i32 42, i32* [[TMP2]], align 4 // CHECK-64-NEXT: [[TMP3:%.*]] = bitcast %printf_args.0* [[TMP]] to i8* // CHECK-64-NEXT: [[TMP4:%.*]] = call i32 @__llvm_omp_vprintf(i8* getelementptr inbounds ([3 x i8], [3 x i8]* @.str2, i64 0, i64 0), i8* [[TMP3]], i32 4) // CHECK-64-NEXT: br label [[IF_END]] // CHECK-64: worker.exit: // CHECK-64-NEXT: ret void // CHECK-64: if.end: // CHECK-64-NEXT: call void @__kmpc_target_deinit(%struct.ident_t* @[[GLOB1]], i8 1, i1 true) // CHECK-64-NEXT: ret void // // // // // // CHECK-32-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}_CheckSimple_l13 // CHECK-32-SAME: () #[[ATTR0:[0-9]+]] { // CHECK-32-NEXT: entry: // CHECK-32-NEXT: [[FMT:%.*]] = alloca i8*, align 4 // CHECK-32-NEXT: [[TMP:%.*]] = alloca [[PRINTF_ARGS:%.*]], align 8 // CHECK-32-NEXT: [[TMP0:%.*]] = call i32 @__kmpc_target_init(%struct.ident_t* @[[GLOB1:[0-9]+]], i8 1, i1 true, i1 true) // CHECK-32-NEXT: [[EXEC_USER_CODE:%.*]] = icmp eq i32 [[TMP0]], -1 // CHECK-32-NEXT: br i1 [[EXEC_USER_CODE]], label [[USER_CODE_ENTRY:%.*]], label [[WORKER_EXIT:%.*]] // CHECK-32: user_code.entry: // CHECK-32-NEXT: store i8* getelementptr inbounds ([11 x i8], [11 x i8]* @.str, i32 0, i32 0), i8** [[FMT]], align 4 // CHECK-32-NEXT: [[TMP1:%.*]] = load i8*, i8** [[FMT]], align 4 // CHECK-32-NEXT: [[TMP2:%.*]] = getelementptr inbounds [[PRINTF_ARGS]], %printf_args* [[TMP]], i32 0, i32 0 // CHECK-32-NEXT: store i32 1, i32* [[TMP2]], align 4 // CHECK-32-NEXT: [[TMP3:%.*]] = getelementptr inbounds [[PRINTF_ARGS]], %printf_args* [[TMP]], i32 0, i32 1 // CHECK-32-NEXT: store i64 2, i64* [[TMP3]], align 8 // CHECK-32-NEXT: [[TMP4:%.*]] = getelementptr inbounds [[PRINTF_ARGS]], %printf_args* [[TMP]], i32 0, i32 2 // CHECK-32-NEXT: store double 3.000000e+00, double* [[TMP4]], align 8 // CHECK-32-NEXT: [[TMP5:%.*]] = bitcast %printf_args* [[TMP]] to i8* // CHECK-32-NEXT: [[TMP6:%.*]] = call i32 @__llvm_omp_vprintf(i8* [[TMP1]], i8* [[TMP5]], i32 24) // CHECK-32-NEXT: call void @__kmpc_target_deinit(%struct.ident_t* @[[GLOB1]], i8 1, i1 true) // CHECK-32-NEXT: ret void // CHECK-32: worker.exit: // CHECK-32-NEXT: ret void // // // CHECK-32-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}_CheckNoArgs_l25 // CHECK-32-SAME: () #[[ATTR0]] { // CHECK-32-NEXT: entry: // CHECK-32-NEXT: [[TMP0:%.*]] = call i32 @__kmpc_target_init(%struct.ident_t* @[[GLOB1]], i8 1, i1 true, i1 true) // CHECK-32-NEXT: [[EXEC_USER_CODE:%.*]] = icmp eq i32 [[TMP0]], -1 // CHECK-32-NEXT: br i1 [[EXEC_USER_CODE]], label [[USER_CODE_ENTRY:%.*]], label [[WORKER_EXIT:%.*]] // CHECK-32: user_code.entry: // CHECK-32-NEXT: [[TMP1:%.*]] = call i32 @__llvm_omp_vprintf(i8* getelementptr inbounds ([14 x i8], [14 x i8]* @.str1, i32 0, i32 0), i8* null, i32 0) // CHECK-32-NEXT: call void @__kmpc_target_deinit(%struct.ident_t* @[[GLOB1]], i8 1, i1 true) // CHECK-32-NEXT: ret void // CHECK-32: worker.exit: // CHECK-32-NEXT: ret void // // // CHECK-32-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}_CheckAllocaIsInEntryBlock_l36 // CHECK-32-SAME: (i32 noundef [[FOO:%.*]]) #[[ATTR0]] { // CHECK-32-NEXT: entry: // CHECK-32-NEXT: [[FOO_ADDR:%.*]] = alloca i32, align 4 // CHECK-32-NEXT: [[TMP:%.*]] = alloca [[PRINTF_ARGS_0:%.*]], align 8 // CHECK-32-NEXT: store i32 [[FOO]], i32* [[FOO_ADDR]], align 4 // CHECK-32-NEXT: [[TMP0:%.*]] = call i32 @__kmpc_target_init(%struct.ident_t* @[[GLOB1]], i8 1, i1 true, i1 true) // CHECK-32-NEXT: [[EXEC_USER_CODE:%.*]] = icmp eq i32 [[TMP0]], -1 // CHECK-32-NEXT: br i1 [[EXEC_USER_CODE]], label [[USER_CODE_ENTRY:%.*]], label [[WORKER_EXIT:%.*]] // CHECK-32: user_code.entry: // CHECK-32-NEXT: [[TMP1:%.*]] = load i32, i32* [[FOO_ADDR]], align 4 // CHECK-32-NEXT: [[TOBOOL:%.*]] = icmp ne i32 [[TMP1]], 0 // CHECK-32-NEXT: br i1 [[TOBOOL]], label [[IF_THEN:%.*]], label [[IF_END:%.*]] // CHECK-32: if.then: // CHECK-32-NEXT: [[TMP2:%.*]] = getelementptr inbounds [[PRINTF_ARGS_0]], %printf_args.0* [[TMP]], i32 0, i32 0 // CHECK-32-NEXT: store i32 42, i32* [[TMP2]], align 4 // CHECK-32-NEXT: [[TMP3:%.*]] = bitcast %printf_args.0* [[TMP]] to i8* // CHECK-32-NEXT: [[TMP4:%.*]] = call i32 @__llvm_omp_vprintf(i8* getelementptr inbounds ([3 x i8], [3 x i8]* @.str2, i32 0, i32 0), i8* [[TMP3]], i32 4) // CHECK-32-NEXT: br label [[IF_END]] // CHECK-32: worker.exit: // CHECK-32-NEXT: ret void // CHECK-32: if.end: // CHECK-32-NEXT: call void @__kmpc_target_deinit(%struct.ident_t* @[[GLOB1]], i8 1, i1 true) // CHECK-32-NEXT: ret void //
ll_data_source.h
/* * ll_data_source.h * LLAMA Graph Analytics * * Copyright 2015 * The President and Fellows of Harvard College. * * Copyright 2014 * Oracle Labs. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University 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 UNIVERSITY 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 UNIVERSITY OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef LL_DATA_SOURCE_H_ #define LL_DATA_SOURCE_H_ #include "llama/ll_common.h" #include "llama/ll_mlcsr_graph.h" #include "llama/ll_writable_graph.h" #include "llama/loaders/ll_load_async_writable.h" #include <algorithm> #include <queue> #include <vector> /** * The pull-based data source */ class ll_data_source { public: /** * Create an instance of the data source wrapper */ inline ll_data_source() {} /** * Destroy the data source */ virtual ~ll_data_source() {} /** * Is this a simple data source? A simple data source has only edges with * predefined node IDs. * * A simple data source needs to additionally implement: * * next_edge() */ virtual bool simple() { return false; } /** * Load the next batch of data * * @param graph the writable graph * @param max_edges the maximum number of edges * @return true if data was loaded, false if there are no more data */ virtual bool pull(ll_writable_graph* graph, size_t max_edges) = 0; /** * Load the next batch of data to request queues * * @param request_queues the request queues * @param num_stripes the number of stripes (queues array length) * @param max_edges the maximum number of edges * @return true if data was loaded, false if there are no more data */ virtual bool pull(ll_la_request_queue** request_queues, size_t num_stripes, size_t max_edges) = 0; /** * Get the next edge * * @param o_tail the output for tail * @param o_head the output for head * @return true if the edge was loaded, false if EOF or error */ virtual bool next_edge(node_t* o_tail, node_t* o_head) { abort(); } }; /** * A simple pull-based data source */ class ll_simple_data_source : public ll_data_source { public: /** * Create an instance of the data source wrapper */ inline ll_simple_data_source() {} /** * Destroy the data source */ virtual ~ll_simple_data_source() {} /** * Is this a simple data source? A simple data source has only edges with * predefined node IDs. * * A simple data source needs to additionally implement: * * next_edge() */ virtual bool simple() { return true; } /** * Load the next batch of data * * @param graph the writable graph * @param max_edges the maximum number of edges * @return true if data was loaded, false if there are no more data */ virtual bool pull(ll_writable_graph* graph, size_t max_edges); /* { */ /* size_t num_stripes = omp_get_max_threads(); */ /* ll_la_request_queue* request_queues[num_stripes]; */ /* for (size_t i = 0; i < num_stripes; i++) { */ /* request_queues[i] = new ll_la_request_queue(); */ /* } */ /* bool loaded = false; */ /* size_t chunk = num_stripes <= 1 */ /* ? std::min<size_t>(10000ul, max_edges) */ /* : max_edges; */ /* while (true) { */ /* graph->tx_begin(); */ /* bool has_data = false; */ /* for (size_t i = 0; i < num_stripes; i++) */ /* request_queues[i]->shutdown_when_empty(false); */ /* #pragma omp parallel */ /* { */ /* if (omp_get_thread_num() == 0) { */ /* has_data = this->pull(request_queues, num_stripes, chunk); */ /* for (size_t i = 0; i < num_stripes; i++) */ /* request_queues[i]->shutdown_when_empty(); */ /* for (size_t i = 0; i < num_stripes; i++) */ /* request_queues[i]->run(*graph); */ /* } */ /* else { */ /* int t = omp_get_thread_num(); */ /* for (size_t i = 0; i < num_stripes; i++, t++) */ /* request_queues[t % num_stripes]->worker(*graph); */ /* } */ /* } */ /* graph->tx_commit(); */ /* if (has_data) */ /* loaded = true; */ /* else */ /* break; */ /* } */ /* for (size_t i = 0; i < num_stripes; i++) delete request_queues[i]; */ /* return loaded; */ /* } */ /** * Load the next batch of data to request queues * * @param request_queues the request queues * @param num_stripes the number of stripes (queues array length) * @param max_edges the maximum number of edges * @return true if data was loaded, false if there are no more data */ virtual bool pull(ll_la_request_queue** request_queues, size_t num_stripes, size_t max_edges) { node_t tail, head; size_t num_edges = 0; while (next_edge(&tail, &head)) { num_edges++; LL_D_NODE2_PRINT(tail, head, "%ld --> %ld\n", (long) tail, (long) head); ll_la_request_with_edge_properties* request; #ifdef LL_S_WEIGHTS_INSTEAD_OF_DUPLICATE_EDGES request = new ll_la_add_edge_for_streaming_with_weights<node_t>( tail, head); #else request = new ll_la_add_edge<node_t>(tail, head); #endif size_t stripe = (tail>>(LL_ENTRIES_PER_PAGE_BITS+3)) % num_stripes; request_queues[stripe]->enqueue(request); if (max_edges > 0 && num_edges >= max_edges) break; } return num_edges > 0; } }; /** * A serial concatenation of multiple data sources */ class ll_concat_data_source : public ll_data_source { std::queue<ll_data_source*> _data_sources; ll_spinlock_t _lock; bool _simple; public: /** * Create an instance of the concatenated data source */ ll_concat_data_source() { _lock = 0; _simple = true; } /** * Destroy the data source */ virtual ~ll_concat_data_source() { while (!_data_sources.empty()) { delete _data_sources.front(); _data_sources.pop(); } } /** * Add a data source * * @param data_source the data source */ void add(ll_data_source* data_source) { ll_spinlock_acquire(&_lock); _data_sources.push(data_source); _simple = _simple && data_source->simple(); ll_spinlock_release(&_lock); } /** * Is this a simple data source? */ virtual bool simple() { return _simple; } /** * Load the next batch of data * * @param graph the writable graph * @param max_edges the maximum number of edges * @return true if data was loaded, false if there are no more data */ virtual bool pull(ll_writable_graph* graph, size_t max_edges) { ll_spinlock_acquire(&_lock); if (_data_sources.empty()) { ll_spinlock_release(&_lock); return false; } ll_data_source* d = _data_sources.front(); ll_spinlock_release(&_lock); while (true) { bool r = d->pull(graph, max_edges); if (r) return r; ll_spinlock_acquire(&_lock); if (d != _data_sources.front()) { LL_E_PRINT("Race condition\n"); abort(); } delete d; _data_sources.pop(); if (_data_sources.empty()) { ll_spinlock_release(&_lock); return false; } d = _data_sources.front(); ll_spinlock_release(&_lock); } } /** * Load the next batch of data to request queues * * @param request_queues the request queues * @param num_stripes the number of stripes (queues array length) * @param max_edges the maximum number of edges * @return true if data was loaded, false if there are no more data */ virtual bool pull(ll_la_request_queue** request_queues, size_t num_stripes, size_t max_edges) { ll_spinlock_acquire(&_lock); if (_data_sources.empty()) { ll_spinlock_release(&_lock); return false; } ll_data_source* d = _data_sources.front(); ll_spinlock_release(&_lock); while (true) { bool r = d->pull(request_queues, num_stripes, max_edges); if (r) return r; ll_spinlock_acquire(&_lock); if (d != _data_sources.front()) { LL_E_PRINT("Race condition\n"); abort(); } delete d; _data_sources.pop(); if (_data_sources.empty()) { ll_spinlock_release(&_lock); return false; } d = _data_sources.front(); ll_spinlock_release(&_lock); } } /** * Get the next edge * * @param o_tail the output for tail * @param o_head the output for head * @return true if the edge was loaded, false if EOF or error */ virtual bool next_edge(node_t* o_tail, node_t* o_head) { ll_spinlock_acquire(&_lock); if (_data_sources.empty()) { ll_spinlock_release(&_lock); return false; } ll_data_source* d = _data_sources.front(); ll_spinlock_release(&_lock); while (true) { bool r = d->next_edge(o_tail, o_head); if (r) return r; ll_spinlock_acquire(&_lock); if (d != _data_sources.front()) { LL_E_PRINT("Race condition\n"); abort(); } delete d; _data_sources.pop(); if (_data_sources.empty()) { ll_spinlock_release(&_lock); return false; } d = _data_sources.front(); ll_spinlock_release(&_lock); } } }; /** * A generic pull-based data source */ template <typename input_t> class ll_generic_data_source { public: /** * Create an instance of class ll_generic_data_source */ inline ll_generic_data_source() {} /** * Destroy an instance of the class */ virtual ~ll_generic_data_source() {} /** * Get the next input item. The function returns a pointer to an internal * buffer that does not need (and should not be) freed by the caller. * * Depending on the implementation, this might or might not be thread safe. * * @return the pointer to the next item, or NULL if done */ virtual const input_t* next_input() = 0; }; /** * An adapter for a generic data source for LLAMA */ template <typename input_t> class ll_simple_data_source_adapter : public ll_simple_data_source { ll_generic_data_source<input_t>* _source; bool _own; std::queue<node_pair_t> _edge_buffer; ll_spinlock_t _edge_buffer_lock; size_t _num_inputs; public: /** * Create an instance of the data source adapter * * @param source the generic data source to wrap * @param own true to own the data source and destroy it at the end */ ll_simple_data_source_adapter(ll_generic_data_source<input_t>* source, bool own=false) { _source = source; _own = own; _edge_buffer_lock = 0; _num_inputs = 0; } /** * Destroy the instance of this class */ virtual ~ll_simple_data_source_adapter() { if (_own && _source != NULL) delete _source; } /** * Get the data source * * @return the data source */ inline ll_generic_data_source<input_t>* source() { return _source; } /** * Get the number of processed inputs * * @return the number of inputs */ inline size_t num_processed_inputs() { return _num_inputs; } /** * Get the next edge * * @param o_tail the output for tail * @param o_head the output for head * @return true if the edge was loaded, false if EOF or error */ virtual bool next_edge(node_t* o_tail, node_t* o_head) { ll_spinlock_acquire(&_edge_buffer_lock); while (_edge_buffer.empty()) { const input_t* input = _source->next_input(); if (input == NULL) { ll_spinlock_release(&_edge_buffer_lock); return false; } process_input(input); _num_inputs++; } node_pair_t e = _edge_buffer.front(); _edge_buffer.pop(); ll_spinlock_release(&_edge_buffer_lock); *o_tail = e.tail; *o_head = e.head; return true; } protected: /** * Add an edge to the buffer. * * Beware that this is intended to be only called from inside * process_input(). * * @param tail the tail * @param head the head */ void add_edge(node_t tail, node_t head) { // This is only called from process_input(), which is only called from // next_edge() -- and this happens only while the _edge_buffer_lock is // held. Note that we would need to revisit this if we want more than // one loading thread. node_pair_t e; e.tail = tail; e.head = head; _edge_buffer.push(e); } /** * Processs an input item and generate corresponding edges * * @param input the input item */ virtual void process_input(const input_t* input) = 0; }; #endif
sequences.c
#include "sequences.h" #define CHECK_FSCANF(x) if(!x) { fprintf(stderr, "fscanf failed on %s:%d\n", __FILE__,__LINE__); } /* preprocess_db function preprocess the database sequences named input_filename. The preprocessed database filenames start with out_filename. */ void preprocess_db (char * input_filename, char * out_filename, int n_procs) { unsigned long int sequences_count=0, D=0, disp, i; unsigned short int *sequences_lengths=NULL, * title_lengths=NULL, length=0; char ** sequences=NULL, **titles=NULL, buffer[BUFFER_SIZE], filename[BUFFER_SIZE], * res, *b=NULL, diff, new_line='\n'; FILE * sequences_file, *titles_file, *info_file, * bin_file; int max_title_length; double tick= dwalltime(); // open dabatase sequence filename sequences_file = fopen(input_filename,"r"); if (sequences_file == NULL) { printf("SWIMM: An error occurred while opening input sequence file.\n"); exit(2); } // Allocate memory for sequences_lengths array sequences_lengths = (unsigned short int *) malloc (ALLOCATION_CHUNK*sizeof(unsigned short int)); title_lengths = (unsigned short int *) malloc (ALLOCATION_CHUNK*sizeof(unsigned short int)); // Calculate number of sequences in database and its lengths sequences_count=0; res = fgets(buffer,BUFFER_SIZE,sequences_file); while (res != NULL) { length = 0; // read title while (strrchr(buffer,new_line) == NULL) { length += strlen(buffer); res = fgets(buffer,BUFFER_SIZE,sequences_file); } title_lengths[sequences_count] = length + strlen(buffer) + 1; // read sequence length = 0; res = fgets(buffer,BUFFER_SIZE,sequences_file); while ((res != NULL) && (buffer[0] != '>')) { length += strlen(buffer)-1; res = fgets(buffer,BUFFER_SIZE,sequences_file); } sequences_lengths[sequences_count] = length; (sequences_count)++; if ((sequences_count) % ALLOCATION_CHUNK == 0) { sequences_lengths = (unsigned short int *) realloc(sequences_lengths,((sequences_count)+ALLOCATION_CHUNK)*sizeof(unsigned short int)); title_lengths = (unsigned short int *) realloc(title_lengths,((sequences_count)+ALLOCATION_CHUNK)*sizeof(unsigned short int)); } } // Allocate memory for sequences array sequences = (char **) malloc(sequences_count*sizeof(char *)); if (sequences == NULL) { printf("SWIMM: An error occurred while allocating memory for sequences.\n"); exit(1); } for (i=0; i<sequences_count; i++ ) { sequences[i] = (char *) malloc(sequences_lengths[i]*sizeof(char)); if (sequences[i] == NULL) { printf("SWIMM: An error occurred while allocating memory.\n"); exit(1); } } // Rewind sequences database file rewind(sequences_file); // Read sequences from the database file and load them in sequences array i = 0; res = fgets(buffer,BUFFER_SIZE,sequences_file); while (res != NULL) { // read title while (strrchr(buffer,new_line) == NULL) res = fgets(buffer,BUFFER_SIZE,sequences_file); // read sequence length = 1; res = fgets(buffer,BUFFER_SIZE,sequences_file); while ((res != NULL) && (buffer[0] != '>')) { //printf("%s %d\n",buffer,strlen(buffer)); strncpy(sequences[i]+(length-1),buffer,strlen(buffer)-1); length += strlen(buffer)-1; res = fgets(buffer,BUFFER_SIZE,sequences_file); } i++; } // Rewind sequences database file rewind(sequences_file); // Allocate memory for titles array titles = (char **) malloc(sequences_count*sizeof(char *)); if (titles == NULL) { printf("SWIMM: An error occurred while allocating memory for sequence titles.\n"); exit(1); } for (i=0; i<sequences_count; i++ ) { titles[i] = (char *) malloc(title_lengths[i]*sizeof(char)); if (titles[i] == NULL) { printf("SWIMM: An error occurred while allocating memory for sequence titles.\n"); exit(1); } } // calculate max title length max_title_length = 0; for (i=0; i<sequences_count ; i++) max_title_length = (max_title_length > title_lengths[i] ? max_title_length : title_lengths[i]); // free memory free(title_lengths); // read sequence headers i = 0; res = fgets(buffer,BUFFER_SIZE,sequences_file); while (res != NULL) { // discard sequences while ((res != NULL) && (buffer[0] != '>')) res = fgets(buffer,BUFFER_SIZE,sequences_file); if (res != NULL){ // read header length = 1; do{ strncpy(titles[i]+(length-1),buffer,strlen(buffer)-1); length += strlen(buffer)-1; res = fgets(buffer,BUFFER_SIZE,sequences_file); } while (strrchr(buffer,new_line) == NULL); titles[i][length] = '\0'; i++; } } // Close sequences database file fclose(sequences_file); // Sort sequence array by length sort_sequences(sequences,titles,sequences_lengths, sequences_count, n_procs); // Create titles file: this text file contains the sequences description sprintf(filename,"%s.desc",out_filename); titles_file = fopen(filename,"w"); if (titles_file == NULL) { printf("SWIMM: An error occurred while opening sequence header file.\n"); exit(2); } // write titles for (i=0; i<sequences_count ; i++) fprintf(titles_file,"%s\n",titles[i]); // close titles file fclose(titles_file); // calculate total number of residues #pragma omp parallel for reduction(+:D) num_threads(n_procs) for (i=0; i< sequences_count; i++ ) D = D + sequences_lengths[i]; // transform bidimensional sequence array to a unidimensional one b = (char *) malloc(D*sizeof(char)); if (b == NULL) { printf("SWIMM: An error occurred while allocating memory for sequences.\n"); exit(1); } disp = 0; for (i=0; i< sequences_count; i++ ) { memcpy(b+disp,sequences[i],sequences_lengths[i]); disp += sequences_lengths[i]; } // Free memory for (i=0; i< sequences_count; i++ ) free(sequences[i]); free(sequences); // preprocess vect sequences DB // original alphabet: 'A'..'Z' => preprocessed alphabet: 0..24 (J, O and U are replaced with dummy symbol) #pragma omp parallel for private(diff) num_threads(n_procs) schedule(dynamic) for (i=0; i< D; i++) { b[i] = ((b[i] == 'J') ? DUMMY_ELEMENT : b[i]); b[i] = ((b[i] == 'O') ? DUMMY_ELEMENT : b[i]); b[i] = ((b[i] == 'U') ? DUMMY_ELEMENT : b[i]); diff = 'A'; diff = (b[i] > 'J' ? diff+1 : diff); diff = (b[i] > 'O' ? diff+1 : diff); diff = (b[i] > 'U' ? diff+1 : diff); b[i] -= diff; } // Create info file: this file contains sequences count, number of residues and the maximum title length sprintf(filename,"%s.info",out_filename); info_file = fopen(filename,"w"); if (info_file == NULL) { printf("SWIMM: An error occurred while opening info file.\n"); exit(2); } // Write info fprintf(info_file,"%ld %ld %d",sequences_count,D,max_title_length); // close info file fclose(info_file); // Create sequences binary file: this file contains first the sequences lengths and then the preprocessed sequences residues sprintf(filename,"%s.seq",out_filename); bin_file = fopen(filename,"wb"); if (bin_file == NULL) { printf("SWIMM: An error occurred while opening sequence file.\n"); exit(2); } // Write vectorized sequences lengths fwrite(sequences_lengths,sizeof(unsigned short int),sequences_count,bin_file); //Write sequences fwrite(b,sizeof(char),D,bin_file); // Close bin file fclose(bin_file); // free memory free(sequences_lengths); free(b); printf("\nSWIMM v%s\n\n",VERSION); printf("Database file:\t\t\t %s\n",input_filename); printf("Database size:\t\t\t%ld sequences (%ld residues) \n",sequences_count,D); printf("Preprocessed database name:\t%s\n",out_filename); printf("Preprocessing time:\t\t%lf seconds\n\n",dwalltime()-tick); } // Load query sequence from file in a void load_query_sequences(char * queries_filename, int execution_mode, char ** ptr_query_sequences, char *** ptr_query_headers, unsigned short int **ptr_query_sequences_lengths, unsigned short int **ptr_m, unsigned long int * query_sequences_count, unsigned long int * ptr_Q, unsigned int ** ptr_query_sequences_disp, int n_procs) { long int i; unsigned long int sequences_count=0, Q=0, disp; unsigned int * sequences_disp; unsigned short int *sequences_lengths, *m, * title_lengths, *tmp, length=0; char ** sequences=NULL, **titles, buffer[BUFFER_SIZE], * res, *a, diff, new_line='\n'; FILE * sequences_file; // open query sequence filename sequences_file = fopen(queries_filename,"r"); if (sequences_file == NULL) { printf("SWIMM: An error occurred while opening input sequence file.\n"); exit(2); } // Allocate memory for sequences_lengths array sequences_lengths = (unsigned short int *) malloc (ALLOCATION_CHUNK*sizeof(unsigned short int)); title_lengths = (unsigned short int *) malloc (ALLOCATION_CHUNK*sizeof(unsigned short int)); // Calculate number of sequences in database and its lengths sequences_count=0; res = fgets(buffer,BUFFER_SIZE,sequences_file); while (res != NULL) { length = 0; // read title while (strrchr(buffer,new_line) == NULL) { length += strlen(buffer); res = fgets(buffer,BUFFER_SIZE,sequences_file); } title_lengths[sequences_count] = length + strlen(buffer) + 1; // read sequence length = 0; res = fgets(buffer,BUFFER_SIZE,sequences_file); while ((res != NULL) && (buffer[0] != '>')) { length += strlen(buffer)-1; res = fgets(buffer,BUFFER_SIZE,sequences_file); } sequences_lengths[sequences_count] = length; (sequences_count)++; if ((sequences_count) % ALLOCATION_CHUNK == 0) { sequences_lengths = (unsigned short int *) realloc(sequences_lengths,((sequences_count)+ALLOCATION_CHUNK)*sizeof(unsigned short int)); title_lengths = (unsigned short int *) realloc(title_lengths,((sequences_count)+ALLOCATION_CHUNK)*sizeof(unsigned short int)); } } // copy lengths to aligned buffer tmp = sequences_lengths; m = (unsigned short int *) _mm_malloc (sequences_count*sizeof(unsigned short int), (execution_mode == CPU_ONLY ? 32 : 64)); sequences_lengths = (unsigned short int *) _mm_malloc (sequences_count*sizeof(unsigned short int), (execution_mode == CPU_ONLY ? 32 : 64)); memcpy(m,tmp,sequences_count*sizeof(unsigned short int)); memcpy(sequences_lengths,tmp,sequences_count*sizeof(unsigned short int)); free(tmp); // Allocate memory for sequences array sequences = (char **) malloc(sequences_count*sizeof(char *)); if (sequences == NULL) { printf("SWIMM: An error occurred while allocating memory for query sequences.\n"); exit(1); } for (i=0; i<sequences_count; i++ ) { sequences[i] = (char *) malloc(sequences_lengths[i]*sizeof(char)); if (sequences[i] == NULL) { printf("SWIMM: An error occurred while allocating memory.\n"); exit(1); } } // Rewind sequences database file rewind(sequences_file); // Read sequences from the database file and load them in sequences array i = 0; res = fgets(buffer,BUFFER_SIZE,sequences_file); while (res != NULL) { // read title while (strrchr(buffer,new_line) == NULL) res = fgets(buffer,BUFFER_SIZE,sequences_file); // read sequence length = 1; res = fgets(buffer,BUFFER_SIZE,sequences_file); while ((res != NULL) && (buffer[0] != '>')) { //printf("%s %d\n",buffer,strlen(buffer)); strncpy(sequences[i]+(length-1),buffer,strlen(buffer)-1); length += strlen(buffer)-1; res = fgets(buffer,BUFFER_SIZE,sequences_file); } i++; } // Rewind sequences database file rewind(sequences_file); // Allocate memory for titles array titles = (char **) malloc(sequences_count*sizeof(char *)); if (titles == NULL) { printf("SWIMM: An error occurred while allocating memory for sequence titles.\n"); exit(1); } for (i=0; i<sequences_count; i++ ) { titles[i] = (char *) malloc(title_lengths[i]*sizeof(char)); if (titles[i] == NULL) { printf("SWIMM: An error occurred while allocating memory for sequence titles.\n"); exit(1); } } i = 0; res = fgets(buffer,BUFFER_SIZE,sequences_file); while (res != NULL) { // discard sequences while ((res != NULL) && (buffer[0] != '>')) res = fgets(buffer,BUFFER_SIZE,sequences_file); if (res != NULL){ // read header length = 1; do{ strncpy(titles[i]+(length-1),buffer,strlen(buffer)-1); length += strlen(buffer)-1; res = fgets(buffer,BUFFER_SIZE,sequences_file); } while (strrchr(buffer,new_line) == NULL); titles[i][length] = '\0'; i++; } } // Close sequences database file fclose(sequences_file); // Sort sequence array by length sort_sequences(sequences,titles,sequences_lengths, sequences_count, n_procs); // make sequences length even for CPU and Hybrid computing if (execution_mode == MIC_ONLY){ // calculate total number of residues #pragma omp parallel for reduction(+:Q) num_threads(n_procs) for (i=0; i< sequences_count; i++ ) Q = Q + sequences_lengths[i]; *ptr_Q = Q; a = (char *) _mm_malloc(Q*sizeof(char), 64); if (a == NULL) { printf("SWIMM: An error occurred while allocating memory for sequences.\n"); exit(1); } disp = 0; for (i=0; i< sequences_count; i++ ) { // copy query sequence memcpy(a+disp,sequences[i],sequences_lengths[i]); disp += sequences_lengths[i]; } } else { // calculate total number of residues #pragma omp parallel for reduction(+:Q) num_threads(n_procs) for (i=0; i< sequences_count; i++ ) Q = Q + sequences_lengths[i] + (sequences_lengths[i]%2); *ptr_Q = Q; a = (char *) _mm_malloc(Q*sizeof(char), (execution_mode == CPU_ONLY ? 32 : 64)); if (a == NULL) { printf("SWIMM: An error occurred while allocating memory for sequences.\n"); exit(1); } disp = 0; for (i=0; i< sequences_count; i++ ) { // copy query sequence memcpy(a+disp,sequences[i],sequences_lengths[i]); // if length is odd then make it even and copy dummy element at last position if (sequences_lengths[i]%2==1){ a[disp+sequences_lengths[i]]=DUMMY_ELEMENT; m[i]++; } disp += m[i]; } } // process vect sequences DB #pragma omp parallel for private(diff) num_threads(n_procs) schedule(dynamic) for (i=0; i< Q; i++) { a[i] = ((a[i] == 'J') ? DUMMY_ELEMENT : a[i]); a[i] = ((a[i] == 'O') ? DUMMY_ELEMENT : a[i]); a[i] = ((a[i] == 'U') ? DUMMY_ELEMENT : a[i]); diff = 'A'; diff = (a[i] > 'J' ? diff+1 : diff); diff = (a[i] > 'O' ? diff+1 : diff); diff = (a[i] > 'U' ? diff+1 : diff); a[i] -= diff; } // Calculate displacement for current sequences db sequences_disp = (unsigned int *) _mm_malloc((sequences_count+1)*sizeof(unsigned int), (execution_mode == CPU_ONLY ? 32 : 64)); sequences_disp[0] = 0; for (i=1; i < sequences_count+1; i++) sequences_disp[i] = sequences_disp[i-1] + m[i-1]; *ptr_query_sequences = a; *ptr_query_sequences_lengths = sequences_lengths; *ptr_m = m; *ptr_query_sequences_disp = sequences_disp; *ptr_query_headers = titles; *query_sequences_count = sequences_count; // Free memory for (i=0; i< sequences_count; i++ ) free(sequences[i]); free(sequences); free(title_lengths); } void assemble_multiple_chunks_db (char * sequences_filename, int vector_length, unsigned long int max_chunk_size, unsigned long int * sequences_count, unsigned long int * D, unsigned short int * sequences_db_max_length, int * max_title_length, unsigned long int * vect_sequences_count, unsigned long int * vD, char ***ptr_chunk_vect_sequences_db, unsigned int * chunk_count, unsigned int ** ptr_chunk_vect_sequences_db_count, unsigned long int ** ptr_chunk_vD, unsigned short int *** ptr_chunk_vect_sequences_db_lengths, unsigned int *** ptr_chunk_vect_sequences_db_disp, int n_procs) { char ** sequences, *s, **chunk_vect_sequences_db, filename[200], *b; unsigned short int ** chunk_vect_sequences_db_lengths, * sequences_lengths, * vect_sequences_lengths; unsigned long int i, ii, j, jj, k, * chunk_vD, accum, aux_vD=0, offset, chunk_size, * vect_sequences_disp; unsigned int * chunk_vect_sequences_count, **chunk_vect_sequences_disp, c; FILE * sequences_file, * info_file; // Open info file sprintf(filename,"%s.info",sequences_filename); info_file = fopen(filename,"r"); if (info_file == NULL) { printf("SWIMM: An error occurred while opening info file.\n"); exit(2); } CHECK_FSCANF(fscanf(info_file,"%ld %ld %d",sequences_count,D,max_title_length)); fclose(info_file); // Open sequences file sprintf(filename,"%s.seq",sequences_filename); sequences_file = fopen(filename,"r"); if (sequences_file == NULL) { printf("SWIMM: An error occurred while opening info file.\n"); exit(2); } // Read sequences lengths sequences_lengths = (unsigned short int *) malloc((*sequences_count)*sizeof(unsigned short int)); fread(sequences_lengths,sizeof(unsigned short int),*sequences_count,sequences_file); // Read sequences s = (char *) malloc((*D)*sizeof(char)); fread(s,sizeof(char),*D,sequences_file); fclose(sequences_file); sequences = (char **) malloc((*sequences_count)*sizeof(char *)); sequences[0] = s; for (i=1; i<*sequences_count ; i++) sequences[i] = sequences[i-1] + sequences_lengths[i-1]; // calculate vect_sequences_count *vect_sequences_count = ceil( (double) (*sequences_count) / (double) vector_length); // Allocate memory for vect_sequences_lengths vect_sequences_lengths = (unsigned short int *) malloc((*vect_sequences_count)*sizeof(unsigned short int)); if (vect_sequences_lengths == NULL) { printf("SWIMM: An error occurred while allocating memory.\n"); exit(1); } vect_sequences_disp = (unsigned long int *) malloc((*vect_sequences_count+1)*sizeof(unsigned long int)); if (vect_sequences_disp == NULL) { printf("SWIMM: An error occurred while allocating memory.\n"); exit(1); } // calculate values for vect_sequences_lengths array for (i=0; i< *vect_sequences_count - 1; i++ ) vect_sequences_lengths[i] = sequences_lengths[(i+1)*vector_length-1]; vect_sequences_lengths[*vect_sequences_count-1] = sequences_lengths[*sequences_count-1]; // make length multiple of SEQ_LEN_MULT to allow manual loop unrolling for (i=0; i< *vect_sequences_count; i++ ) vect_sequences_lengths[i] = ceil( (double) vect_sequences_lengths[i] / (double) SEQ_LEN_MULT) * SEQ_LEN_MULT; // Calculate displacement for current sequences db vect_sequences_disp[0] = 0; for (k=1; k < *vect_sequences_count+1; k++) vect_sequences_disp[k] = vect_sequences_disp[k-1] + (vect_sequences_lengths[k-1]*vector_length); #pragma omp parallel for reduction(+:aux_vD) num_threads(n_procs) for (i=0; i< *vect_sequences_count; i++ ) aux_vD = aux_vD + vect_sequences_lengths[i]*vector_length; *vD = aux_vD; b = (char *) _mm_malloc((*vD)*sizeof(char),16); // Copy sequences db to host buffers reordering elements to get better locality when computing alignments for (i=0; i < *vect_sequences_count-1; i++) { for (j=0; j< vect_sequences_lengths[i]; j++ ) { for (k=0;k< vector_length; k++) if (j < sequences_lengths[i*vector_length+k]) *(b+vect_sequences_disp[i]+(j*vector_length)+k) = sequences[i*vector_length+k][j]; else *(b+vect_sequences_disp[i]+(j*vector_length)+k) = PREPROCESSED_DUMMY_ELEMENT; } } //rest = sequences_count % vector_length; for (i=*vect_sequences_count-1, j=0; j< vect_sequences_lengths[i]; j++ ) { for (k=0;k< vector_length; k++) if (i*vector_length+k < *sequences_count){ if (j < sequences_lengths[i*vector_length+k]) *(b+vect_sequences_disp[i]+(j*vector_length)+k) = sequences[i*vector_length+k][j]; else *(b+vect_sequences_disp[i]+(j*vector_length)+k) = PREPROCESSED_DUMMY_ELEMENT; } else *(b+vect_sequences_disp[i]+(j*vector_length)+k) = PREPROCESSED_DUMMY_ELEMENT; } // calculate chunks *chunk_count = 1; chunk_vect_sequences_count = (unsigned int *) malloc((*chunk_count)*sizeof(unsigned int)); if (chunk_vect_sequences_count == NULL) { printf("SWIMM: An error occurred while allocating memory.\n"); exit(1); } i = 0; c = 0; while (i< *vect_sequences_count) { // group sequences till reach max chunk size j = 0; chunk_size = 0; accum = vect_sequences_lengths[i]*vector_length*sizeof(char) + sizeof(unsigned short int) + sizeof(unsigned int); // secuencias + longitud + desplazamiento while ((i< *vect_sequences_count) && (chunk_size <= max_chunk_size)) { chunk_size += accum; j++; i++; if (i < *vect_sequences_count) accum = vect_sequences_lengths[i]*vector_length*sizeof(char) + sizeof(unsigned short int) + sizeof(unsigned int); // secuencias + longitud + desplazamiento } // number of sequences in chunk chunk_vect_sequences_count[c] = j; // increment chunk_count (*chunk_count)++; c++; chunk_vect_sequences_count = (unsigned int *) realloc(chunk_vect_sequences_count,(*chunk_count)*sizeof(unsigned int)); if (chunk_vect_sequences_count == NULL) { printf("SWIMM: An error occurred while allocating memory.\n"); exit(1); } } // update chunk count (*chunk_count)--; // calculate chunk_vect_sequences_db_lengths chunk_vect_sequences_db_lengths = (unsigned short int **) _mm_malloc((*chunk_count)*sizeof(unsigned short int *),64); if (chunk_vect_sequences_db_lengths == NULL) { printf("SWIMM: An error occurred while allocating memory.\n"); exit(1); } offset = 0; for (i=0; i< *chunk_count ; i++) { chunk_vect_sequences_db_lengths[i] = (unsigned short int *) _mm_malloc((chunk_vect_sequences_count[i])*sizeof(unsigned short int),64); memcpy(chunk_vect_sequences_db_lengths[i],vect_sequences_lengths+offset,(chunk_vect_sequences_count[i])*sizeof(unsigned short int)); offset += chunk_vect_sequences_count[i]; } // calculate chunk_vect_sequences_db_disp accum = 0; chunk_vect_sequences_disp = (unsigned int **) _mm_malloc((*chunk_count)*sizeof(unsigned int *),64); for (i=0; i< *chunk_count ; i++){ chunk_vect_sequences_disp[i] = (unsigned int *) _mm_malloc(chunk_vect_sequences_count[i]*sizeof(unsigned int),64); if (chunk_vect_sequences_disp[i] == NULL) { printf("SWIMM: An error occurred while allocating memory.\n"); exit(1); } // adapt sequence displacements to chunk offset = vect_sequences_disp[accum]; for ( j=0, jj=accum; j<chunk_vect_sequences_count[i] ; j++, jj++) chunk_vect_sequences_disp[i][j] = (unsigned int)(vect_sequences_disp[jj] - offset); accum += chunk_vect_sequences_count[i]; } // calculate chunk_vD chunk_vD = (unsigned long int *) malloc((*chunk_count)*sizeof(unsigned long int)); if (chunk_vD == NULL) { printf("SWIMM: An error occurred while allocating memory.\n"); exit(1); } offset = 0; for (i=0; i< *chunk_count; i++){ ii = offset + chunk_vect_sequences_count[i]; chunk_vD[i] = vect_sequences_disp[ii] - vect_sequences_disp[offset]; offset = ii; } // calculate chunk_vect_sequences_db chunk_vect_sequences_db = (char **) _mm_malloc((*chunk_count)*sizeof(char *), 64); if (chunk_vect_sequences_db == NULL) { printf("SWIMM: An error occurred while allocating memory.\n"); exit(1); } offset = 0; for (i=0; i< *chunk_count ; i++) { chunk_vect_sequences_db[i] = b + offset; offset += chunk_vD[i]; } *ptr_chunk_vect_sequences_db = chunk_vect_sequences_db; *ptr_chunk_vect_sequences_db_count = chunk_vect_sequences_count; *ptr_chunk_vD = chunk_vD; *ptr_chunk_vect_sequences_db_lengths = chunk_vect_sequences_db_lengths; *ptr_chunk_vect_sequences_db_disp = chunk_vect_sequences_disp; *sequences_db_max_length = sequences_lengths[*sequences_count-1]; free(s); free(sequences); free(sequences_lengths); free(vect_sequences_lengths); free(vect_sequences_disp); } void assemble_single_chunk_db (char * sequences_filename, int vector_length, unsigned long int * sequences_count, unsigned long int * D, unsigned short int * sequences_db_max_length, int * max_title_length, unsigned long int * vect_sequences_db_count, unsigned long int * vD, char **ptr_vect_sequences_db, unsigned short int ** ptr_vect_sequences_db_lengths, unsigned short int ** ptr_vect_sequences_db_blocks, unsigned long int ** ptr_vect_sequences_db_disp, int n_procs, int block_size) { char ** sequences, *s, filename[200], *b; unsigned short int * vect_sequences_lengths, * vect_sequences_blocks, * sequences_lengths; unsigned long int i, j, k, aux_vD=0, *vect_sequences_disp; FILE * sequences_file, * info_file; // Open info file sprintf(filename,"%s.info",sequences_filename); info_file = fopen(filename,"r"); if (info_file == NULL) { printf("SWIMM: An error occurred while opening info file.\n"); exit(2); } fscanf(info_file,"%ld %ld %d",sequences_count,D,max_title_length); fclose(info_file); // Open sequences file sprintf(filename,"%s.seq",sequences_filename); sequences_file = fopen(filename,"rb"); if (sequences_file == NULL) { printf("SWIMM: An error occurred while opening info file.\n"); exit(2); } // Read sequences lengths sequences_lengths = (unsigned short int *) malloc((*sequences_count)*sizeof(unsigned short int)); fread(sequences_lengths,sizeof(unsigned short int),*sequences_count,sequences_file); // Read sequences s = (char *) malloc((*D)*sizeof(char)); fread(s,sizeof(char),*D,sequences_file); fclose(sequences_file); sequences = (char **) malloc((*sequences_count)*sizeof(char *)); sequences[0] = s; for (i=1; i<*sequences_count ; i++) sequences[i] = sequences[i-1] + sequences_lengths[i-1]; // calculate vect_sequences_count *vect_sequences_db_count = ceil( (double) (*sequences_count) / (double) vector_length); // Allocate memory for vect_sequences_lengths vect_sequences_lengths = (unsigned short int *) _mm_malloc((*vect_sequences_db_count)*sizeof(unsigned short int),32); if (vect_sequences_lengths == NULL) { printf("SWIMM: An error occurred while allocating memory.\n"); exit(1); } vect_sequences_blocks = (unsigned short int *) _mm_malloc((*vect_sequences_db_count)*sizeof(unsigned short int),32); if (vect_sequences_blocks == NULL) { printf("SWIMM: An error occurred while allocating memory.\n"); exit(1); } vect_sequences_disp = (unsigned long int *) _mm_malloc((*vect_sequences_db_count+1)*sizeof(unsigned long int),32); if (vect_sequences_disp == NULL) { printf("SWIMM: An error occurred while allocating memory.\n"); exit(1); } // calculate values for vect_sequences_lengths array for (i=0; i< *vect_sequences_db_count - 1; i++ ) vect_sequences_lengths[i] = sequences_lengths[(i+1)*vector_length-1]; vect_sequences_lengths[*vect_sequences_db_count-1] = sequences_lengths[*sequences_count-1]; // make length multiple of SEQ_LEN_MULT to allow manual loop unrolling for (i=0; i< *vect_sequences_db_count; i++ ) vect_sequences_lengths[i] = ceil( (double) vect_sequences_lengths[i] / (double) SEQ_LEN_MULT) * SEQ_LEN_MULT; // calculate number of blocks for (i=0; i< *vect_sequences_db_count; i++ ) vect_sequences_blocks[i] = ceil((double) vect_sequences_lengths[i] / block_size); #pragma omp parallel for reduction(+:aux_vD) num_threads(n_procs) for (i=0; i< *vect_sequences_db_count; i++ ) aux_vD = aux_vD + vect_sequences_lengths[i]*vector_length; *vD = aux_vD; b = (char *) _mm_malloc((*vD)*sizeof(char),32); // Calculate displacement for current sequences db vect_sequences_disp[0] = 0; for (k=1; k < *vect_sequences_db_count+1; k++) vect_sequences_disp[k] = vect_sequences_disp[k-1] + (vect_sequences_lengths[k-1]*vector_length); // Copy sequences db to host buffers reordering elements to get better locality when computing alignments for (i=0; i < *vect_sequences_db_count-1; i++) { for (j=0; j< vect_sequences_lengths[i]; j++ ) { for (k=0;k< vector_length; k++) if (j < sequences_lengths[i*vector_length+k]) *(b+vect_sequences_disp[i]+(j*vector_length)+k) = sequences[i*vector_length+k][j]; else *(b+vect_sequences_disp[i]+(j*vector_length)+k) = PREPROCESSED_DUMMY_ELEMENT; } } //rest = sequences_count % vector_length; for (i=*vect_sequences_db_count-1, j=0; j< vect_sequences_lengths[i]; j++ ) { for (k=0;k< vector_length; k++) if (i*vector_length+k < *sequences_count){ if (j < sequences_lengths[i*vector_length+k]) *(b+vect_sequences_disp[i]+(j*vector_length)+k) = sequences[i*vector_length+k][j]; else *(b+vect_sequences_disp[i]+(j*vector_length)+k) = PREPROCESSED_DUMMY_ELEMENT; } else *(b+vect_sequences_disp[i]+(j*vector_length)+k) = PREPROCESSED_DUMMY_ELEMENT; } *ptr_vect_sequences_db = b; *ptr_vect_sequences_db_lengths = vect_sequences_lengths; *ptr_vect_sequences_db_blocks = vect_sequences_blocks; *ptr_vect_sequences_db_disp = vect_sequences_disp; *sequences_db_max_length = sequences_lengths[*sequences_count-1]; free(s); free(sequences); free(sequences_lengths); } void load_database_headers (char * sequences_filename, unsigned long int sequences_count, int max_title_length, char *** ptr_sequences_db_headers) { char ** sequences_db_headers, filename[200], * header; FILE * header_file; unsigned long int i; // Load sequence headers // Open header file sprintf(filename,"%s.desc",sequences_filename); header_file = fopen(filename,"r"); if (header_file == NULL) { printf("SWIMM: An error occurred while opening sequence description file.\n"); exit(3); } // Read sequences lengths sequences_db_headers = (char **) malloc(sequences_count*sizeof(char *)); header = (char *) malloc((max_title_length+1)*sizeof(char)); for (i=0; i<sequences_count; i++){ fgets(header,max_title_length,header_file); sequences_db_headers[i] = (char *) malloc((strlen(header)+1)*sizeof(char)); strcpy(sequences_db_headers[i],header); } fclose(header_file); free(header); *ptr_sequences_db_headers = sequences_db_headers; } void merge_sequences(char ** sequences, char ** titles, unsigned short int * sequences_lengths, unsigned long int size) { unsigned long int i1 = 0; unsigned long int i2 = size / 2; unsigned long int it = 0; // allocate memory for temporary buffers char ** tmp1 = (char **) malloc(size*sizeof(char *)); char ** tmp2 = (char **) malloc(size*sizeof(char *)); unsigned short int * tmp3 = (unsigned short int *) malloc (size*sizeof(unsigned short int)); while(i1 < size/2 && i2 < size) { if (sequences_lengths[i1] <= sequences_lengths[i2]) { tmp1[it] = sequences[i1]; tmp2[it] = titles[i1]; tmp3[it] = sequences_lengths[i1]; i1++; } else { tmp1[it] = sequences[i2]; tmp2[it] = titles[i2]; tmp3[it] = sequences_lengths[i2]; i2 ++; } it ++; } while (i1 < size/2) { tmp1[it] = sequences[i1]; tmp2[it] = titles[i1]; tmp3[it] = sequences_lengths[i1]; i1++; it++; } while (i2 < size) { tmp1[it] = sequences[i2]; tmp2[it] = titles[i2]; tmp3[it] = sequences_lengths[i2]; i2++; it++; } memcpy(sequences, tmp1, size*sizeof(char *)); memcpy(titles, tmp2, size*sizeof(char *)); memcpy(sequences_lengths, tmp3, size*sizeof(unsigned short int)); free(tmp1); free(tmp2); free(tmp3); } void mergesort_sequences_serial (char ** sequences, char ** titles, unsigned short int * sequences_lengths, unsigned long int size) { char * tmp_seq; unsigned short int tmp_seq_len; if (size == 2) { if (sequences_lengths[0] > sequences_lengths[1]) { // swap sequences tmp_seq = sequences[0]; sequences[0] = sequences[1]; sequences[1] = tmp_seq; // swap titles tmp_seq = titles[0]; titles[0] = titles[1]; titles[1] = tmp_seq; // swap sequences lengths tmp_seq_len = sequences_lengths[0]; sequences_lengths[0] = sequences_lengths[1]; sequences_lengths[1] = tmp_seq_len; return; } } else { if (size > 2){ mergesort_sequences_serial(sequences, titles, sequences_lengths, size/2); mergesort_sequences_serial(sequences + size/2, titles + size/2, sequences_lengths + size/2, size - size/2); merge_sequences(sequences, titles, sequences_lengths, size); } } } void sort_sequences (char ** sequences, char ** titles, unsigned short int * sequences_lengths, unsigned long int size, int threads) { if ( threads == 1) { mergesort_sequences_serial(sequences, titles, sequences_lengths, size); } else if (threads > 1) { #pragma omp parallel sections { #pragma omp section sort_sequences(sequences, titles, sequences_lengths, size/2, threads/2); #pragma omp section sort_sequences(sequences + size/2, titles + size/2, sequences_lengths + size/2, size-size/2, threads-threads/2); } merge_sequences(sequences, titles, sequences_lengths, size); } // threads > 1 }
parallel_for.h
/* * Copyright (c) 2021, Horance Liu and the respective contributors * All rights reserved. * * Use of this source code is governed by a Apache 2.0 license that can be found * in the LICENSE file. */ #pragma once #include <cassert> #include <cstdio> #include <limits> #include <string> #include <type_traits> #include <utility> #include <vector> #include "mnn/infra/config.h" #include "mnn/infra/aligned_allocator.h" #include "mnn/infra/mnn_error.h" #ifdef MNN_USE_TBB #ifndef NOMINMAX #define NOMINMAX // tbb includes windows.h in tbb/machine/windows_api.h #endif #include <tbb/task_group.h> #include <tbb/tbb.h> #endif #if !defined(MNN_USE_OMP) && !defined(MNN_SINGLE_THREAD) #include <future> // NOLINT #include <thread> // NOLINT #endif #if defined(MNN_USE_GCD) && !defined(MNN_SINGLE_THREAD) #include <dispatch/dispatch.h> #endif namespace mnn { #ifdef MNN_USE_TBB static tbb::task_scheduler_init tbbScheduler( tbb::task_scheduler_init::automatic); // tbb::task_scheduler_init::deferred); typedef tbb::BlockedRange<size_t> BlockedRange; template <typename Func> void parallel_for(size_t begin, size_t end, const Func &f, size_t grainsize) { assert(end >= begin); tbb::parallel_for( BlockedRange(begin, end, end - begin > grainsize ? grainsize : 1), f); } template <typename Func> void xparallel_for(size_t begin, size_t end, const Func &f) { f(BlockedRange(begin, end, 100)); } #else struct BlockedRange { typedef size_t const_iterator; BlockedRange(size_t begin, size_t end) : begin_(begin), end_(end) {} BlockedRange(int begin, int end) : begin_(begin), end_(end) {} const_iterator begin() const { return begin_; } const_iterator end() const { return end_; } private: size_t begin_; size_t end_; }; template <typename Func> void xparallel_for(size_t begin, size_t end, const Func &f) { BlockedRange r(begin, end); f(r); } #if defined(MNN_USE_OMP) template <typename Func> void parallel_for(size_t begin, size_t end, const Func &f, size_t /*grainsize*/) { assert(end >= begin); // unsigned index isn't allowed in OpenMP 2.0 #pragma omp parallel for for (int i = static_cast<int>(begin); i < static_cast<int>(end); ++i) f(BlockedRange(i, i + 1)); } #elif defined(MNN_USE_GCD) template <typename Func> void parallel_for(size_t begin, size_t end, const Func &f, size_t grainsize) { assert(end >= begin); size_t count = end - begin; size_t blockSize = grainsize; if (count < blockSize || blockSize == 0) { blockSize = 1; } size_t blockCount = (count + blockSize - 1) / blockSize; assert(blockCount > 0); dispatch_apply(blockCount, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), ^(size_t block) { size_t blockStart = block * blockSize; size_t blockEnd = blockStart + blockSize; if (blockEnd > end) { blockEnd = end; } assert(blockStart < blockEnd); f(BlockedRange(blockStart, blockEnd)); }); } #elif defined(MNN_SINGLE_THREAD) template <typename Func> void parallel_for(size_t begin, size_t end, const Func &f, size_t /*grainsize*/) { xparallel_for(begin, end, f); } #else template <typename Func> void parallel_for(size_t begin, size_t end, const Func &f, size_t /*grainsize*/) { assert(end >= begin); size_t nthreads = std::thread::hardware_concurrency(); size_t blockSize = (end - begin) / nthreads; if (blockSize * nthreads < end - begin) blockSize++; std::vector<std::future<void> > futures; size_t blockBegin = begin; size_t blockEnd = blockBegin + blockSize; if (blockEnd > end) blockEnd = end; for (size_t i = 0; i < nthreads; i++) { futures.push_back( std::move(std::async(std::launch::async, [blockBegin, blockEnd, &f] { f(BlockedRange(blockBegin, blockEnd)); }))); blockBegin += blockSize; blockEnd = blockBegin + blockSize; if (blockBegin >= end) break; if (blockEnd > end) blockEnd = end; } for (auto &future : futures) future.wait(); } #endif #endif // MNN_USE_TBB template <typename T, typename U> bool value_representation(U const &value) { return static_cast<U>(static_cast<T>(value)) == value; } template <typename T, typename Func> inline void for_( bool parallelize, size_t begin, T end, Func f, size_t grainsize = 100) { static_assert(std::is_integral<T>::value, "end must be integral type"); parallelize = parallelize && value_representation<size_t>(end); parallelize ? parallel_for(begin, end, f, grainsize) : xparallel_for(begin, end, f); } template <typename T, typename Func> inline void for_i(bool parallelize, T size, Func f, size_t grainsize = 100u) { #ifdef MNN_SINGLE_THREAD for (size_t i = 0; i < size; ++i) { f(i); } #else // #ifdef MNN_SINGLE_THREAD for_(parallelize, 0u, size, [&](const BlockedRange &r) { #ifdef MNN_USE_OMP #pragma omp parallel for for (int i = static_cast<int>(r.begin()); i < static_cast<int>(r.end()); i++) { f(i); } #else for (size_t i = r.begin(); i < r.end(); i++) { f(i); } #endif }, grainsize); #endif // #ifdef MNN_SINGLE_THREAD } template <typename T, typename Func> inline void for_i(T size, Func f, size_t grainsize = 100) { for_i(true, size, f, grainsize); } } // namespace mnn
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] = 8; tile_size[1] = 8; 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,4);t1++) { lbp=max(ceild(t1,2),ceild(8*t1-Nt+3,8)); ubp=min(floord(Nt+Nz-4,8),floord(4*t1+Nz+1,8)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(t1-5,6)),ceild(8*t2-Nz-20,24));t3<=min(min(min(floord(Nt+Ny-4,24),floord(4*t1+Ny+5,24)),floord(8*t2+Ny+4,24)),floord(8*t1-8*t2+Nz+Ny+3,24));t3++) { for (t4=max(max(max(0,ceild(t1-31,32)),ceild(8*t2-Nz-124,128)),ceild(24*t3-Ny-124,128));t4<=min(min(min(min(floord(Nt+Nx-4,128),floord(4*t1+Nx+5,128)),floord(8*t2+Nx+4,128)),floord(24*t3+Nx+20,128)),floord(8*t1-8*t2+Nz+Nx+3,128));t4++) { for (t5=max(max(max(max(max(0,4*t1),8*t1-8*t2+1),8*t2-Nz+2),24*t3-Ny+2),128*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,4*t1+7),8*t2+6),24*t3+22),128*t4+126),8*t1-8*t2+Nz+5);t5++) { for (t6=max(max(8*t2,t5+1),-8*t1+8*t2+2*t5-7);t6<=min(min(8*t2+7,-8*t1+8*t2+2*t5),t5+Nz-2);t6++) { for (t7=max(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; }
GB_resize.c
//------------------------------------------------------------------------------ // GB_resize: change the size of a matrix //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ #include "GB_select.h" #define GB_FREE_ALL \ { \ GB_FREE (&Ax_new, Ax_new_size) ; \ GB_FREE (&Ab_new, Ab_new_size) ; \ GB_phbix_free (A) ; \ } //------------------------------------------------------------------------------ // GB_resize: resize a GrB_Matrix //------------------------------------------------------------------------------ GrB_Info GB_resize // change the size of a matrix ( GrB_Matrix A, // matrix to modify const GrB_Index nrows_new, // new number of rows in matrix const GrB_Index ncols_new, // new number of columns in matrix GB_Context Context ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- GrB_Info info ; GB_void *restrict Ax_new = NULL ; size_t Ax_new_size = 0 ; int8_t *restrict Ab_new = NULL ; size_t Ab_new_size = 0 ; ASSERT_MATRIX_OK (A, "A to resize", GB0) ; //-------------------------------------------------------------------------- // handle the CSR/CSC format //-------------------------------------------------------------------------- int64_t vdim_old = A->vdim ; int64_t vlen_old = A->vlen ; int64_t vlen_new, vdim_new ; if (A->is_csc) { vlen_new = nrows_new ; vdim_new = ncols_new ; } else { vlen_new = ncols_new ; vdim_new = nrows_new ; } if (vdim_new == vdim_old && vlen_new == vlen_old) { // nothing to do return (GrB_SUCCESS) ; } //-------------------------------------------------------------------------- // delete any lingering zombies and assemble any pending tuples //-------------------------------------------------------------------------- // only do so if either dimension is shrinking, or if pending tuples exist // and vdim_old <= 1 and vdim_new > 1, since in that case, Pending->j has // not been allocated yet, but would be required in the resized matrix. // If A is jumbled, it must be sorted. if (vdim_new < vdim_old || vlen_new < vlen_old || A->jumbled || (GB_PENDING (A) && vdim_old <= 1 && vdim_new > 1)) { GB_MATRIX_WAIT (A) ; ASSERT_MATRIX_OK (A, "A to resize, wait", GB0) ; } ASSERT (!GB_JUMBLED (A)) ; //-------------------------------------------------------------------------- // resize the matrix //-------------------------------------------------------------------------- const bool A_is_bitmap = GB_IS_BITMAP (A) ; const bool A_is_full = GB_IS_FULL (A) ; const bool A_is_shrinking = (vdim_new <= vdim_old && vlen_new <= vlen_old) ; if ((A_is_full || A_is_bitmap) && A_is_shrinking) { //---------------------------------------------------------------------- // A is full or bitmap //---------------------------------------------------------------------- // get the old and new dimensions int64_t anz_new = 1 ; bool ok = GB_int64_multiply ((GrB_Index *) &anz_new, vlen_new, vdim_new) ; if (!ok) anz_new = 1 ; size_t nzmax_new = GB_IMAX (anz_new, 1) ; bool in_place = A_is_full && (vlen_new == vlen_old || vdim_new <= 1) ; size_t asize = A->type->size ; const bool A_iso = A->iso ; //---------------------------------------------------------------------- // allocate or reallocate A->x, unless A is iso //---------------------------------------------------------------------- ok = true ; if (!A_iso) { if (in_place) { // reallocate A->x in-place; no data movement needed GB_REALLOC (A->x, nzmax_new*asize, GB_void, &(A->x_size), &ok, Context) ; } else { // allocate new space for A->x Ax_new = GB_MALLOC (nzmax_new*asize, GB_void, &Ax_new_size) ; ok = (Ax_new != NULL) ; } } //---------------------------------------------------------------------- // allocate or reallocate A->b //---------------------------------------------------------------------- if (!in_place && A_is_bitmap) { // allocate new space for A->b Ab_new = GB_MALLOC (nzmax_new*asize, int8_t, &Ab_new_size) ; ok = ok && (Ab_new != NULL) ; } if (!ok) { // out of memory GB_FREE_ALL ; return (GrB_OUT_OF_MEMORY) ; } //---------------------------------------------------------------------- // move data if not in-place //---------------------------------------------------------------------- if (!in_place) { //------------------------------------------------------------------ // determine number of threads to use //------------------------------------------------------------------ GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ; int nthreads = GB_nthreads (anz_new, chunk, nthreads_max) ; //------------------------------------------------------------------ // resize Ax, unless A is iso //------------------------------------------------------------------ if (!A_iso) { GB_void *restrict Ax_old = (GB_void *) A->x ; int64_t j ; if (vdim_new <= 4*nthreads) { // use all threads for each vector for (j = 0 ; j < vdim_new ; j++) { GB_void *pdest = Ax_new + j * vlen_new * asize ; GB_void *psrc = Ax_old + j * vlen_old * asize ; GB_memcpy (pdest, psrc, vlen_new * asize, nthreads) ; } } else { // use a single thread for each vector #pragma omp parallel for num_threads(nthreads) \ schedule(static) for (j = 0 ; j < vdim_new ; j++) { GB_void *pdest = Ax_new + j * vlen_new * asize ; GB_void *psrc = Ax_old + j * vlen_old * asize ; memcpy (pdest, psrc, vlen_new * asize) ; } } GB_FREE (&Ax_old, A->x_size) ; A->x = Ax_new ; A->x_size = Ax_new_size ; } //------------------------------------------------------------------ // resize Ab if A is bitmap, and count the # of entries //------------------------------------------------------------------ if (A_is_bitmap) { int8_t *restrict Ab_old = A->b ; int64_t pnew ; int64_t anvals = 0 ; #pragma omp parallel for num_threads(nthreads) \ schedule(static) reduction(+:anvals) for (pnew = 0 ; pnew < anz_new ; pnew++) { int64_t i = pnew % vlen_new ; int64_t j = pnew / vlen_new ; int64_t pold = i + j * vlen_old ; int8_t ab = Ab_old [pold] ; Ab_new [pnew] = ab ; anvals += ab ; } A->nvals = anvals ; GB_FREE (&Ab_old, A->b_size) ; A->b = Ab_new ; A->b_size = Ab_new_size ; } } //---------------------------------------------------------------------- // adjust dimensions and return result //---------------------------------------------------------------------- A->vdim = vdim_new ; A->vlen = vlen_new ; A->nvec = vdim_new ; A->nvec_nonempty = (vlen_new == 0) ? 0 : vdim_new ; ASSERT_MATRIX_OK (A, "A bitmap/full shrunk", GB0) ; return (GrB_SUCCESS) ; } else { //---------------------------------------------------------------------- // convert A to hypersparse and resize it //---------------------------------------------------------------------- // convert to hypersparse GB_OK (GB_convert_any_to_hyper (A, Context)) ; ASSERT (GB_IS_HYPERSPARSE (A)) ; // resize the number of sparse vectors int64_t *restrict Ah = A->h ; int64_t *restrict Ap = A->p ; A->vdim = vdim_new ; if (vdim_new < A->plen) { // reduce the size of A->p and A->h; this cannot fail info = GB_hyper_realloc (A, vdim_new, Context) ; ASSERT (info == GrB_SUCCESS) ; Ap = A->p ; Ah = A->h ; } if (vdim_new < vdim_old) { // descrease A->nvec to delete the vectors outside the range // 0...vdim_new-1. int64_t pleft = 0 ; int64_t pright = GB_IMIN (A->nvec, vdim_new) - 1 ; bool found ; GB_SPLIT_BINARY_SEARCH (vdim_new, Ah, pleft, pright, found) ; A->nvec = pleft ; } if (vdim_new < vdim_old) { // number of vectors is decreasing, need to count the new number of // non-empty vectors: done during pruning or by selector, below. A->nvec_nonempty = -1 ; // recomputed just below } //---------------------------------------------------------------------- // resize the length of each vector //---------------------------------------------------------------------- // if vlen is shrinking, delete entries outside the new matrix if (vlen_new < vlen_old) { GB_OK (GB_selector ( NULL, // A in-place GB_ROWLE_idxunop_code, // use the opcode only NULL, // no operator, just opcode is needed false, // flipij is false A, // input/output matrix vlen_new-1, // ithunk NULL, // no Thunk GrB_Scalar Context)) ; } //---------------------------------------------------------------------- // vlen has been resized //---------------------------------------------------------------------- A->vlen = vlen_new ; ASSERT_MATRIX_OK (A, "A vlen resized", GB0) ; //---------------------------------------------------------------------- // conform the matrix to its desired sparsity structure //---------------------------------------------------------------------- info = GB_conform (A, Context) ; ASSERT (GB_IMPLIES (info == GrB_SUCCESS, A->nvec_nonempty >= 0)) ; return (info) ; } }
mufunc_object.c
/* * Python Universal Functions Object -- Math for all types, plus fast * arrays math * * Full description * * This supports mathematical (and Boolean) functions on arrays and other python * objects. Math on large arrays of basic C types is rather efficient. * * Travis E. Oliphant 2005, 2006 oliphant@ee.byu.edu (oliphant.travis@ieee.org) * Brigham Young University * * based on the * * Original Implementation: * Copyright (c) 1995, 1996, 1997 Jim Hugunin, hugunin@mit.edu * * with inspiration and code from * Numarray * Space Science Telescope Institute * J. Todd Miller * Perry Greenfield * Rick White * */ #define NPY_NO_DEPRECATED_API NPY_API_VERSION #include "Python.h" #include "npy_config.h" #define PY_ARRAY_UNIQUE_SYMBOL _mpy_umathmodule_ARRAY_API #define NO_IMPORT_ARRAY #define PY_UFUNC_UNIQUE_SYMBOL _mpy_umathmodule_UFUNC_API #define NO_IMPORT_UFUNC #include <numpy/npy_3kcompat.h> #include <numpy/arrayobject.h> #include <numpy/ufuncobject.h> #include <numpy/arrayscalars.h> #include <lowlevel_strided_loops.h> #define PyMicArray_API_UNIQUE_NAME _mpy_umathmodule_MICARRAY_API #define PyMicArray_NO_IMPORT #include <multiarray/arrayobject.h> #include <multiarray/multiarray_api.h> #include <multiarray/mpy_common.h> #include <multiarray/common.h> #define _MICARRAY_UMATHMODULE #include "mufunc_object.h" #include "output_creators.h" #include "reduction.h" /* Some useful macros */ #define CPU_DEVICE (omp_get_initial_device()) #define PyMicArray_TRIVIAL_PAIR_ITERATION_STRIDE(size, arr) ( \ size == 1 ? 0 : ((PyMicArray_NDIM(arr) == 1) ? \ PyMicArray_STRIDE(arr, 0) : \ PyMicArray_ITEMSIZE(arr))) #define PyMicArray_TRIVIALLY_ITERABLE(arr) \ PyArray_TRIVIALLY_ITERABLE((PyArrayObject *)arr) #define PyMicArray_PREPARE_TRIVIAL_ITERATION(arr, count, data, stride) \ count = PyMicArray_SIZE(arr); \ data = (npy_intp) PyMicArray_BYTES(arr); \ stride = ((PyMicArray_NDIM(arr) == 0) ? 0 : \ ((PyMicArray_NDIM(arr) == 1) ? \ PyMicArray_STRIDE(arr, 0) : \ PyMicArray_ITEMSIZE(arr))); #define PyMicArray_TRIVIALLY_ITERABLE_PAIR(arr1, arr2, arr1_read, arr2_read) \ PyArray_TRIVIALLY_ITERABLE_PAIR(\ (PyArrayObject *)arr1,(PyArrayObject *)arr2, arr1_read, arr2_read) #define PyMicArray_PREPARE_TRIVIAL_PAIR_ITERATION(arr1, arr2, \ count, \ data1, data2, \ stride1, stride2) { \ npy_intp size1 = PyMicArray_SIZE(arr1); \ npy_intp size2 = PyMicArray_SIZE(arr2); \ count = ((size1 > size2) || size1 == 0) ? size1 : size2; \ data1 = PyMicArray_BYTES(arr1); \ data2 = PyMicArray_BYTES(arr2); \ stride1 = PyMicArray_TRIVIAL_PAIR_ITERATION_STRIDE(size1, arr1); \ stride2 = PyMicArray_TRIVIAL_PAIR_ITERATION_STRIDE(size2, arr2); \ } #define PyMicArray_TRIVIALLY_ITERABLE_TRIPLE(arr1, arr2, arr3, arr1_read, arr2_read, arr3_read) \ PyArray_TRIVIALLY_ITERABLE_TRIPLE(\ (PyArrayObject *)arr1,\ (PyArrayObject *)arr2,\ (PyArrayObject *)arr3,\ arr1_read, arr2_read, arr3_read) #define PyMicArray_PREPARE_TRIVIAL_TRIPLE_ITERATION(arr1, arr2, arr3, \ count, \ data1, data2, data3, \ stride1, stride2, stride3) { \ npy_intp size1 = PyMicArray_SIZE(arr1); \ npy_intp size2 = PyMicArray_SIZE(arr2); \ npy_intp size3 = PyMicArray_SIZE(arr3); \ count = ((size1 > size2) || size1 == 0) ? size1 : size2; \ count = ((size3 > count) || size3 == 0) ? size3 : count; \ data1 = PyMicArray_BYTES(arr1); \ data2 = PyMicArray_BYTES(arr2); \ data3 = PyMicArray_BYTES(arr3); \ stride1 = PyMicArray_TRIVIAL_PAIR_ITERATION_STRIDE(size1, arr1); \ stride2 = PyMicArray_TRIVIAL_PAIR_ITERATION_STRIDE(size2, arr2); \ stride3 = PyMicArray_TRIVIAL_PAIR_ITERATION_STRIDE(size3, arr3); \ } /********** PRINTF DEBUG TRACING **************/ #define NPY_UF_DBG_TRACING 0 #if NPY_UF_DBG_TRACING #define NPY_UF_DBG_PRINT(s) {printf("%s", s);fflush(stdout);} #define NPY_UF_DBG_PRINT1(s, p1) {printf((s), (p1));fflush(stdout);} #define NPY_UF_DBG_PRINT2(s, p1, p2) {printf(s, p1, p2);fflush(stdout);} #define NPY_UF_DBG_PRINT3(s, p1, p2, p3) {printf(s, p1, p2, p3);fflush(stdout);} #else #define NPY_UF_DBG_PRINT(s) #define NPY_UF_DBG_PRINT1(s, p1) #define NPY_UF_DBG_PRINT2(s, p1, p2) #define NPY_UF_DBG_PRINT3(s, p1, p2, p3) #endif /**********************************************/ /********************/ #define USE_USE_DEFAULTS 1 /********************/ /* ---------------------------------------------------------------- */ static int _does_loop_use_arrays(void *data); static int _extract_pyvals(PyObject *ref, const char *name, int *bufsize, int *errmask, PyObject **errobj); static int assign_reduce_identity_zero(PyMicArrayObject *result, void *data); static int assign_reduce_identity_minusone(PyMicArrayObject *result, void *data); static int assign_reduce_identity_one(PyMicArrayObject *result, void *data); /* * Determine whether all array is on the same device * Return 0 on success and -1 when fail */ static int _on_same_device(PyUFuncObject *ufunc, PyMicArrayObject **op) { int nop = ufunc->nin + ufunc->nout; if (nop <= 0) { return -1; } int i; int device = PyMicArray_DEVICE(op[0]); for (i = 1; i < nop; ++i) { if (op[i] != NULL && PyMicArray_DEVICE(op[i]) != device) { return -1; } } return 0; } /* * fpstatus is the ufunc_formatted hardware status * errmask is the handling mask specified by the user. * errobj is a Python object with (string, callable object or None) * or NULL */ /* * 2. for each of the flags * determine whether to ignore, warn, raise error, or call Python function. * If ignore, do nothing * If warn, print a warning and continue * If raise return an error * If call, call a user-defined function with string */ #if USE_USE_DEFAULTS==1 static int PyUFunc_NUM_NODEFAULTS = 0; #endif static PyObject * get_global_ext_obj(void) { PyObject *thedict; PyObject *ref = NULL; #if USE_USE_DEFAULTS==1 if (PyUFunc_NUM_NODEFAULTS != 0) { #endif thedict = PyThreadState_GetDict(); if (thedict == NULL) { thedict = PyEval_GetBuiltins(); } ref = PyDict_GetItem(thedict, mpy_um_str_pyvals_name); #if USE_USE_DEFAULTS==1 } #endif return ref; } static int _get_bufsize_errmask(PyObject * extobj, const char *ufunc_name, int *buffersize, int *errormask) { /* Get the buffersize and errormask */ if (extobj == NULL) { extobj = get_global_ext_obj(); } if (_extract_pyvals(extobj, ufunc_name, buffersize, errormask, NULL) < 0) { return -1; } return 0; } static int _extract_pyvals(PyObject *ref, const char *name, int *bufsize, int *errmask, PyObject **errobj) { PyObject *retval; /* default errobj case, skips dictionary lookup */ if (ref == NULL) { if (errmask) { *errmask = UFUNC_ERR_DEFAULT; } if (errobj) { *errobj = Py_BuildValue("NO", PyBytes_FromString(name), Py_None); } if (bufsize) { *bufsize = NPY_BUFSIZE; } return 0; } if (!PyList_Check(ref) || (PyList_GET_SIZE(ref)!=3)) { PyErr_Format(PyExc_TypeError, "%s must be a length 3 list.", MUFUNC_PYVALS_NAME); return -1; } if (bufsize != NULL) { *bufsize = PyInt_AsLong(PyList_GET_ITEM(ref, 0)); if ((*bufsize == -1) && PyErr_Occurred()) { return -1; } if ((*bufsize < NPY_MIN_BUFSIZE) || (*bufsize > NPY_MAX_BUFSIZE) || (*bufsize % 16 != 0)) { PyErr_Format(PyExc_ValueError, "buffer size (%d) is not in range " "(%"NPY_INTP_FMT" - %"NPY_INTP_FMT") or not a multiple of 16", *bufsize, (npy_intp) NPY_MIN_BUFSIZE, (npy_intp) NPY_MAX_BUFSIZE); return -1; } } if (errmask != NULL) { *errmask = PyInt_AsLong(PyList_GET_ITEM(ref, 1)); if (*errmask < 0) { if (PyErr_Occurred()) { return -1; } PyErr_Format(PyExc_ValueError, "invalid error mask (%d)", *errmask); return -1; } } if (errobj != NULL) { *errobj = NULL; retval = PyList_GET_ITEM(ref, 2); if (retval != Py_None && !PyCallable_Check(retval)) { PyObject *temp; temp = PyObject_GetAttrString(retval, "write"); if (temp == NULL || !PyCallable_Check(temp)) { PyErr_SetString(PyExc_TypeError, "python object must be callable or have " \ "a callable write method"); Py_XDECREF(temp); return -1; } Py_DECREF(temp); } *errobj = Py_BuildValue("NO", PyBytes_FromString(name), retval); if (*errobj == NULL) { return -1; } } return 0; } /* Return the position of next non-white-space char in the string */ static int _next_non_white_space(const char* str, int offset) { int ret = offset; while (str[ret] == ' ' || str[ret] == '\t') { ret++; } return ret; } static int _is_alpha_underscore(char ch) { return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || ch == '_'; } static int _is_alnum_underscore(char ch) { return _is_alpha_underscore(ch) || (ch >= '0' && ch <= '9'); } /* * Return the ending position of a variable name */ static int _get_end_of_name(const char* str, int offset) { int ret = offset; while (_is_alnum_underscore(str[ret])) { ret++; } return ret; } /* * Returns 1 if the dimension names pointed by s1 and s2 are the same, * otherwise returns 0. */ static int _is_same_name(const char* s1, const char* s2) { while (_is_alnum_underscore(*s1) && _is_alnum_underscore(*s2)) { if (*s1 != *s2) { return 0; } s1++; s2++; } return !_is_alnum_underscore(*s1) && !_is_alnum_underscore(*s2); } /* * Checks if 'obj' is a valid output array for a ufunc, i.e. it is * either None or a writeable array, increments its reference count * and stores a pointer to it in 'store'. Returns 0 on success, sets * an exception and returns -1 on failure. */ static int _set_out_array(PyObject *obj, PyMicArrayObject **store) { if (obj == Py_None) { /* Translate None to NULL */ return 0; } if (PyMicArray_Check(obj)) { /* If it's an array, store it */ if (PyMicArray_FailUnlessWriteable((PyMicArrayObject *)obj, "output array") < 0) { return -1; } Py_INCREF(obj); *store = (PyMicArrayObject *)obj; return 0; } PyErr_SetString(PyExc_TypeError, "return arrays must be of ArrayType"); return -1; } static void ufunc_pre_typeresolver(PyUFuncObject *ufunc, PyMicArrayObject **op, void **ptrs, npy_longlong *buf, int bufsize) { int i; for (i = 0; i < ufunc->nin; ++i) { if (PyMicArray_NDIM(op[i]) == 0) { void *ptr = buf + (i * bufsize); ptrs[i] = PyMicArray_DATA(op[i]); target_memcpy(ptr, PyMicArray_DATA(op[i]), PyMicArray_ITEMSIZE(op[i]), CPU_DEVICE, PyMicArray_DEVICE(op[i])); } } /* Change array data to buffer address */ for (i = 0; i < ufunc->nin; ++i) { if (PyMicArray_NDIM(op[i]) == 0) { PyMicArray_DATA(op[i]) = &(buf[i*bufsize]); } } } static void ufunc_post_typeresolver(PyUFuncObject *ufunc, PyMicArrayObject **op, void **ptrs) { int i; for (i = 0; i < ufunc->nin; ++i) { if (PyMicArray_NDIM(op[i]) == 0) { PyMicArray_DATA(op[i]) = ptrs[i]; } } } /********* GENERIC UFUNC USING ITERATOR *********/ /* * Produce a name for the ufunc, if one is not already set * This is used in the PyUFunc_handlefperr machinery, and in error messages */ static const char* _get_ufunc_name(PyUFuncObject *ufunc) { return ufunc->name ? ufunc->name : "<unnamed ufunc>"; } /* * Parses the positional and keyword arguments for a generic ufunc call. * * Note that if an error is returned, the caller must free the * non-zero references in out_op. This * function does not do its own clean-up. */ static int get_ufunc_arguments(PyUFuncObject *ufunc, PyObject *args, PyObject *kwds, PyMicArrayObject **out_op, NPY_ORDER *out_order, NPY_CASTING *out_casting, PyObject **out_extobj, PyObject **out_typetup, int *out_subok, PyMicArrayObject **out_wheremask) { int i, nargs; int nin = ufunc->nin; int nout = ufunc->nout; PyObject *obj, *context; PyObject *str_key_obj = NULL; const char *ufunc_name = _get_ufunc_name(ufunc); int type_num, device; int any_flexible = 0, any_object = 0, any_flexible_userloops = 0; int has_sig = 0; ufunc_name = _get_ufunc_name(ufunc); *out_extobj = NULL; *out_typetup = NULL; if (out_wheremask != NULL) { *out_wheremask = NULL; } /* Check number of arguments */ nargs = PyTuple_Size(args); if ((nargs < nin) || (nargs > ufunc->nargs)) { PyErr_SetString(PyExc_ValueError, "invalid number of arguments"); return -1; } device = PyMicArray_GetCurrentDevice(); /* Get input arguments */ for (i = 0; i < nin; ++i) { obj = PyTuple_GET_ITEM(args, i); if (PyMicArray_Check(obj)) { PyMicArrayObject *obj_a = (PyMicArrayObject *)obj; device = PyMicArray_DEVICE(obj_a); // use for next op Py_INCREF(obj_a); out_op[i] = obj_a; } else if (PyArray_Check(obj)) { out_op[i] = (PyMicArrayObject *)PyMicArray_FromArray( (PyArrayObject *)obj, NULL, device, 0); } else { out_op[i] = (PyMicArrayObject *)PyMicArray_FromAny(device, obj, NULL, 0, 0, 0, NULL); } if (out_op[i] == NULL) { return -1; } type_num = PyMicArray_DESCR(out_op[i])->type_num; if (!any_flexible && PyTypeNum_ISFLEXIBLE(type_num)) { any_flexible = 1; } if (!any_object && PyTypeNum_ISOBJECT(type_num)) { any_object = 1; } /* * If any operand is a flexible dtype, check to see if any * struct dtype ufuncs are registered. A ufunc has been registered * for a struct dtype if ufunc's arg_dtypes array is not NULL. */ if (PyTypeNum_ISFLEXIBLE(type_num) && !any_flexible_userloops && ufunc->userloops != NULL) { PyUFunc_Loop1d *funcdata; PyObject *key, *obj; key = PyInt_FromLong(type_num); if (key == NULL) { continue; } obj = PyDict_GetItem(ufunc->userloops, key); Py_DECREF(key); if (obj == NULL) { continue; } funcdata = (PyUFunc_Loop1d *)NpyCapsule_AsVoidPtr(obj); while (funcdata != NULL) { if (funcdata->arg_dtypes != NULL) { any_flexible_userloops = 1; break; } funcdata = funcdata->next; } } } if (any_flexible && !any_flexible_userloops && !any_object) { /* Traditionally, we return -2 here (meaning "NotImplemented") anytime * we hit the above condition. * * This condition basically means "we are doomed", b/c the "flexible" * dtypes -- strings and void -- cannot have their own ufunc loops * registered (except via the special "flexible userloops" mechanism), * and they can't be cast to anything except object (and we only cast * to object if any_object is true). So really we should do nothing * here and continue and let the proper error be raised. But, we can't * quite yet, b/c of backcompat. * * Most of the time, this NotImplemented either got returned directly * to the user (who can't do anything useful with it), or got passed * back out of a special function like __mul__. And fortunately, for * almost all special functions, the end result of this was a * TypeError. Which is also what we get if we just continue without * this special case, so this special case is unnecessary. * * The only thing that actually depended on the NotImplemented is * array_richcompare, which did two things with it. First, it needed * to see this NotImplemented in order to implement the special-case * comparisons for * * string < <= == != >= > string * void == != void * * Now it checks for those cases first, before trying to call the * ufunc, so that's no problem. What it doesn't handle, though, is * cases like * * float < string * * or * * float == void * * For those, it just let the NotImplemented bubble out, and accepted * Python's default handling. And unfortunately, for comparisons, * Python's default is *not* to raise an error. Instead, it returns * something that depends on the operator: * * == return False * != return True * < <= >= > Python 2: use "fallback" (= weird and broken) ordering * Python 3: raise TypeError (hallelujah) * * In most cases this is straightforwardly broken, because comparison * of two arrays should always return an array, and here we end up * returning a scalar. However, there is an exception: if we are * comparing two scalars for equality, then it actually is correct to * return a scalar bool instead of raising an error. If we just * removed this special check entirely, then "np.float64(1) == 'foo'" * would raise an error instead of returning False, which is genuinely * wrong. * * The proper end goal here is: * 1) == and != should be implemented in a proper vectorized way for * all types. The short-term hack for this is just to add a * special case to PyUFunc_DefaultLegacyInnerLoopSelector where * if it can't find a comparison loop for the given types, and * the ufunc is np.equal or np.not_equal, then it returns a loop * that just fills the output array with False (resp. True). Then * array_richcompare could trust that whenever its special cases * don't apply, simply calling the ufunc will do the right thing, * even without this special check. * 2) < <= >= > should raise an error if no comparison function can * be found. array_richcompare already handles all string <> * string cases, and void dtypes don't have ordering, so again * this would mean that array_richcompare could simply call the * ufunc and it would do the right thing (i.e., raise an error), * again without needing this special check. * * So this means that for the transition period, our goal is: * == and != on scalars should simply return NotImplemented like * they always did, since everything ends up working out correctly * in this case only * == and != on arrays should issue a FutureWarning and then return * NotImplemented * < <= >= > on all flexible dtypes on py2 should raise a * DeprecationWarning, and then return NotImplemented. On py3 we * skip the warning, though, b/c it would just be immediately be * followed by an exception anyway. * * And for all other operations, we let things continue as normal. */ /* strcmp() is a hack but I think we can get away with it for this * temporary measure. */ if (!strcmp(ufunc_name, "equal") || !strcmp(ufunc_name, "not_equal")) { /* Warn on non-scalar, return NotImplemented regardless */ assert(nin == 2); if (PyMicArray_NDIM(out_op[0]) != 0 || PyMicArray_NDIM(out_op[1]) != 0) { if (DEPRECATE_FUTUREWARNING( "elementwise comparison failed; returning scalar " "instead, but in the future will perform elementwise " "comparison") < 0) { return -1; } } return -2; } else if (!strcmp(ufunc_name, "less") || !strcmp(ufunc_name, "less_equal") || !strcmp(ufunc_name, "greater") || !strcmp(ufunc_name, "greater_equal")) { #if !defined(NPY_PY3K) if (DEPRECATE("unorderable dtypes; returning scalar but in " "the future this will be an error") < 0) { return -1; } #endif return -2; } } /* Get positional output arguments */ for (i = nin; i < nargs; ++i) { obj = PyTuple_GET_ITEM(args, i); if (_set_out_array(obj, out_op + i) < 0) { return -1; } } /* * Get keyword output and other arguments. * Raise an error if anything else is present in the * keyword dictionary. */ if (kwds != NULL) { PyObject *key, *value; Py_ssize_t pos = 0; while (PyDict_Next(kwds, &pos, &key, &value)) { Py_ssize_t length = 0; char *str = NULL; int bad_arg = 1; #if defined(NPY_PY3K) Py_XDECREF(str_key_obj); str_key_obj = PyUnicode_AsASCIIString(key); if (str_key_obj != NULL) { key = str_key_obj; } #endif if (PyBytes_AsStringAndSize(key, &str, &length) < 0) { PyErr_Clear(); PyErr_SetString(PyExc_TypeError, "invalid keyword argument"); goto fail; } switch (str[0]) { case 'c': /* Provides a policy for allowed casting */ if (strcmp(str, "casting") == 0) { if (!PyArray_CastingConverter(value, out_casting)) { goto fail; } bad_arg = 0; } break; case 'd': /* Another way to specify 'sig' */ if (strcmp(str, "dtype") == 0) { /* Allow this parameter to be None */ PyArray_Descr *dtype; if (!PyArray_DescrConverter2(value, &dtype)) { goto fail; } if (dtype != NULL) { if (*out_typetup != NULL) { PyErr_SetString(PyExc_RuntimeError, "cannot specify both 'sig' and 'dtype'"); goto fail; } *out_typetup = Py_BuildValue("(N)", dtype); } bad_arg = 0; } break; case 'e': /* * Overrides the global parameters buffer size, * error mask, and error object */ if (strcmp(str, "extobj") == 0) { *out_extobj = value; bad_arg = 0; } break; case 'o': /* * Output arrays may be specified as a keyword argument, * either as a single array or None for single output * ufuncs, or as a tuple of arrays and Nones. */ if (strcmp(str, "out") == 0) { if (nargs > nin) { PyErr_SetString(PyExc_ValueError, "cannot specify 'out' as both a " "positional and keyword argument"); goto fail; } if (PyTuple_Check(value)) { if (PyTuple_GET_SIZE(value) != nout) { PyErr_SetString(PyExc_ValueError, "The 'out' tuple must have exactly " "one entry per ufunc output"); goto fail; } /* 'out' must be a tuple of arrays and Nones */ for(i = 0; i < nout; ++i) { PyObject *val = PyTuple_GET_ITEM(value, i); if (_set_out_array(val, out_op+nin+i) < 0) { goto fail; } } } else if (nout == 1) { /* Can be an array if it only has one output */ if (_set_out_array(value, out_op + nin) < 0) { goto fail; } } else { PyErr_SetString(PyExc_TypeError, nout > 1 ? "'out' must be a tuple " "of arrays" : "'out' must be an array or a " "tuple of a single array"); goto fail; } bad_arg = 0; } /* Allows the default output layout to be overridden */ else if (strcmp(str, "order") == 0) { if (!PyArray_OrderConverter(value, out_order)) { goto fail; } bad_arg = 0; } break; case 's': /* TODO: remove??? */ /* Allows a specific function inner loop to be selected */ if (strcmp(str, "sig") == 0 || strcmp(str, "signature") == 0) { if (has_sig == 1) { PyErr_SetString(PyExc_ValueError, "cannot specify both 'sig' and 'signature'"); goto fail; } if (*out_typetup != NULL) { PyErr_SetString(PyExc_RuntimeError, "cannot specify both 'sig' and 'dtype'"); goto fail; } *out_typetup = value; Py_INCREF(value); bad_arg = 0; has_sig = 1; } else if (strcmp(str, "subok") == 0) { if (!PyBool_Check(value)) { PyErr_SetString(PyExc_TypeError, "'subok' must be a boolean"); goto fail; } *out_subok = (value == Py_True); bad_arg = 0; } break; case 'w': /* * Provides a boolean array 'where=' mask if * out_wheremask is supplied. */ if (out_wheremask != NULL && strcmp(str, "where") == 0) { if (PyMicArray_Check(value) && PyMicArray_ISBOOL(value)) { *out_wheremask = (PyMicArrayObject *)value; } else { /* TODO: convert to mic array of bool */ PyArray_Descr *dtype; dtype = PyArray_DescrFromType(NPY_BOOL); if (dtype == NULL) { goto fail; } //*out_wheremask = (PyMicArrayObject *)PyMicArray_FromAny( // value, dtype, // 0, 0, 0, NULL); } if (*out_wheremask == NULL) { goto fail; } bad_arg = 0; } break; } if (bad_arg) { char *format = "'%s' is an invalid keyword to ufunc '%s'"; PyErr_Format(PyExc_TypeError, format, str, ufunc_name); goto fail; } } } Py_XDECREF(str_key_obj); return 0; fail: Py_XDECREF(str_key_obj); Py_XDECREF(*out_extobj); *out_extobj = NULL; Py_XDECREF(*out_typetup); *out_typetup = NULL; if (out_wheremask != NULL) { Py_XDECREF(*out_wheremask); *out_wheremask = NULL; } return -1; } /* * This checks whether a trivial loop is ok, * making copies of scalar and one dimensional operands if that will * help. * * Returns 1 if a trivial loop is ok, 0 if it is not, and * -1 if there is an error. */ static int check_for_trivial_loop(PyUFuncObject *ufunc, PyMicArrayObject **op, PyArray_Descr **dtype, npy_intp buffersize) { npy_intp i, nin = ufunc->nin, nop = nin + ufunc->nout; for (i = 0; i < nop; ++i) { /* * If the dtype doesn't match, or the array isn't aligned, * indicate that the trivial loop can't be done. */ if (op[i] != NULL && (!PyMicArray_ISALIGNED(op[i]) || !PyArray_EquivTypes(dtype[i], PyMicArray_DESCR(op[i])) )) { /* * If op[j] is a scalar or small one dimensional * array input, make a copy to keep the opportunity * for a trivial loop. */ if (i < nin && (PyMicArray_NDIM(op[i]) == 0 || (PyMicArray_NDIM(op[i]) == 1 && PyMicArray_DIM(op[i],0) <= buffersize))) { PyMicArrayObject *tmp; Py_INCREF(dtype[i]); tmp = (PyMicArrayObject *) PyMicArray_FromArray((PyArrayObject *)op[i], dtype[i], PyMicArray_DEVICE(op[i]), 0); if (tmp == NULL) { Py_DECREF(dtype[i]); return -1; } Py_DECREF(op[i]); op[i] = tmp; } else { return 0; } } } return 1; } static void trivial_two_operand_loop(PyMicArrayObject **op, PyUFuncGenericFunction innerloop, void *innerloopdata) { void *data0, *data1; npy_intp stride0, stride1; npy_intp count; int needs_api, device; MPY_TARGET_MIC PyUFuncGenericFunction offloop = innerloop; MPY_TARGET_MIC void (*offdata)(void) = innerloopdata; NPY_BEGIN_THREADS_DEF; needs_api = PyDataType_REFCHK(PyMicArray_DESCR(op[0])) || PyDataType_REFCHK(PyMicArray_DESCR(op[1])); device = PyMicArray_DEVICE(op[0]); PyMicArray_PREPARE_TRIVIAL_PAIR_ITERATION(op[0], op[1], count, data0, data1, stride0, stride1); NPY_UF_DBG_PRINT1("two operand loop count %d\n", (int)count); if (!needs_api) { NPY_BEGIN_THREADS_THRESHOLDED(count); } #pragma offload target(mic:device) in(offloop, offdata, count,\ data0, data1,\ stride0, stride1) { char *data[] = {data0, data1}; npy_intp stride[] = {stride0, stride1}; offloop(data, &count, stride, offdata); } NPY_END_THREADS; } static void trivial_three_operand_loop(PyMicArrayObject **op, PyUFuncGenericFunction innerloop, void *innerloopdata) { void *data0, *data1, *data2; npy_intp stride0, stride1, stride2; npy_intp count; int needs_api, device; MPY_TARGET_MIC PyUFuncGenericFunction offloop = innerloop; MPY_TARGET_MIC void (*offdata)(void) = innerloopdata; NPY_BEGIN_THREADS_DEF; needs_api = PyDataType_REFCHK(PyMicArray_DESCR(op[0])) || PyDataType_REFCHK(PyMicArray_DESCR(op[1])) || PyDataType_REFCHK(PyMicArray_DESCR(op[2])); device = PyMicArray_DEVICE(op[0]); PyMicArray_PREPARE_TRIVIAL_TRIPLE_ITERATION(op[0], op[1], op[2], count, data0, data1, data2, stride0, stride1, stride2); NPY_UF_DBG_PRINT1("three operand loop count %d\n", (int)count); if (!needs_api) { NPY_BEGIN_THREADS_THRESHOLDED(count); } #pragma offload target(mic:device) in(offloop, offdata, count,\ data0, data1, data2,\ stride0, stride1, stride2) { char *data[] = {data0, data1, data2}; npy_intp stride[] = {stride0, stride1, stride2}; offloop(data, &count, stride, offdata); } NPY_END_THREADS; } static int iterator_loop(PyUFuncObject *ufunc, PyMicArrayObject **op, PyArray_Descr **dtype, NPY_ORDER order, npy_intp buffersize, PyObject **arr_prep, PyObject *arr_prep_args, PyUFuncGenericFunction innerloop, void *innerloopdata) { npy_intp i, nin = ufunc->nin, nout = ufunc->nout; npy_intp nop = nin + nout; npy_uint32 op_flags[NPY_MAXARGS]; MpyIter *iter; char *baseptrs[NPY_MAXARGS]; MPY_TARGET_MIC MpyIter_IterNextFunc *iternext; MPY_TARGET_MIC PyUFuncGenericFunction offloop = innerloop; MPY_TARGET_MIC void (*offdata)(void) = innerloopdata; npy_intp *dataptr; npy_intp *stride; npy_intp *count_ptr; int device; PyMicArrayObject **op_it; int new_count = 0; npy_uint32 iter_flags; NPY_BEGIN_THREADS_DEF; /* Set up the flags */ for (i = 0; i < nin; ++i) { op_flags[i] = NPY_ITER_READONLY | NPY_ITER_ALIGNED | NPY_ITER_OVERLAP_ASSUME_ELEMENTWISE; /* * If READWRITE flag has been set for this operand, * then clear default READONLY flag */ op_flags[i] |= ufunc->op_flags[i]; if (op_flags[i] & (NPY_ITER_READWRITE | NPY_ITER_WRITEONLY)) { op_flags[i] &= ~NPY_ITER_READONLY; } } for (i = nin; i < nop; ++i) { op_flags[i] = NPY_ITER_WRITEONLY | NPY_ITER_ALIGNED | NPY_ITER_ALLOCATE | NPY_ITER_NO_BROADCAST | NPY_ITER_NO_SUBTYPE | NPY_ITER_OVERLAP_ASSUME_ELEMENTWISE; } iter_flags = ufunc->iter_flags | NPY_ITER_EXTERNAL_LOOP | NPY_ITER_REFS_OK | NPY_ITER_ZEROSIZE_OK | NPY_ITER_BUFFERED | NPY_ITER_GROWINNER | NPY_ITER_DELAY_BUFALLOC | NPY_ITER_COPY_IF_OVERLAP; /* * Allocate the iterator. Because the types of the inputs * were already checked, we use the casting rule 'unsafe' which * is faster to calculate. */ iter = MpyIter_AdvancedNew(nop, op, iter_flags, order, NPY_UNSAFE_CASTING, op_flags, dtype, -1, NULL, NULL, buffersize); if (iter == NULL) { return -1; } /* Copy any allocated outputs */ op_it = MpyIter_GetOperandArray(iter); for (i = 0; i < nout; ++i) { if (op[nin+i] == NULL) { op[nin+i] = op_it[nin+i]; Py_INCREF(op[nin+i]); /* Call the __array_prepare__ functions for the new array */ /*if (prepare_ufunc_output(ufunc, &op[nin+i], arr_prep[i], arr_prep_args, i) < 0) { NpyIter_Deallocate(iter); return -1; }*/ /* * In case __array_prepare__ returned a different array, put the * results directly there, ignoring the array allocated by the * iterator. * * Here, we assume the user-provided __array_prepare__ behaves * sensibly and doesn't return an array overlapping in memory * with other operands --- the op[nin+i] array passed to it is newly * allocated and doesn't have any overlap. */ baseptrs[nin+i] = PyMicArray_BYTES(op[nin+i]); } else { baseptrs[nin+i] = PyMicArray_BYTES(op_it[nin+i]); } } /* Only do the loop if the iteration size is non-zero */ if (MpyIter_GetIterSize(iter) != 0) { /* Reset the iterator with the base pointers from possible __array_prepare__ */ for (i = 0; i < nin; ++i) { baseptrs[i] = PyMicArray_BYTES(op_it[i]); } if (MpyIter_ResetBasePointers(iter, baseptrs, NULL) != NPY_SUCCEED) { MpyIter_Deallocate(iter); return -1; } /* Get the variables needed for the loop */ iternext = MpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { MpyIter_Deallocate(iter); return -1; } dataptr = (npy_intp *) MpyIter_GetDataPtrArray(iter); stride = MpyIter_GetInnerStrideArray(iter); count_ptr = MpyIter_GetInnerLoopSizePtr(iter); device = MpyIter_GetDevice(iter); MPY_BEGIN_THREADS_NDITER(iter); /* Execute the loop */ do { //NPY_UF_DBG_PRINT1("iterator loop count %d\n", (int)*count_ptr); #pragma omp target device(device) map(to: offloop, offdata, count_ptr[0:1],\ dataptr[0:nop], stride[0:nop]) offloop((char **)dataptr, count_ptr, stride, offdata); } while (iternext(iter)); NPY_END_THREADS; } MpyIter_Deallocate(iter); return 0; } /* * trivial_loop_ok - 1 if no alignment, data conversion, etc required * nin - number of inputs * nout - number of outputs * op - the operands (nin + nout of them) * order - the loop execution order/output memory order * buffersize - how big of a buffer to use * arr_prep - the __array_prepare__ functions for the outputs * innerloop - the inner loop function * innerloopdata - data to pass to the inner loop */ static int execute_legacy_ufunc_loop(PyUFuncObject *ufunc, int trivial_loop_ok, PyMicArrayObject **op, PyArray_Descr **dtypes, NPY_ORDER order, npy_intp buffersize, PyObject **arr_prep, PyObject *arr_prep_args) { npy_intp nin = ufunc->nin, nout = ufunc->nout; PyUFuncGenericFunction innerloop; void *innerloopdata; int needs_api = 0; if (ufunc->legacy_inner_loop_selector(ufunc, dtypes, &innerloop, &innerloopdata, &needs_api) < 0) { return -1; } /* If the loop wants the arrays, provide them. */ if (_does_loop_use_arrays(innerloopdata)) { innerloopdata = (void*)op; } /* First check for the trivial cases that don't need an iterator */ if (trivial_loop_ok) { if (nin == 1 && nout == 1) { if (op[1] == NULL && (order == NPY_ANYORDER || order == NPY_KEEPORDER) && PyMicArray_TRIVIALLY_ITERABLE(op[0])) { Py_INCREF(dtypes[1]); op[1] = (PyMicArrayObject *)PyMicArray_NewFromDescr( PyMicArray_DEVICE(op[0]), &PyMicArray_Type, dtypes[1], PyMicArray_NDIM(op[0]), PyMicArray_DIMS(op[0]), NULL, NULL, PyMicArray_ISFORTRAN(op[0]) ? NPY_ARRAY_F_CONTIGUOUS : 0, NULL); if (op[1] == NULL) { return -1; } NPY_UF_DBG_PRINT("trivial 1 input with allocated output\n"); trivial_two_operand_loop(op, innerloop, innerloopdata); return 0; } else if (op[1] != NULL && PyMicArray_NDIM(op[1]) >= PyMicArray_NDIM(op[0]) && PyMicArray_TRIVIALLY_ITERABLE_PAIR(op[0], op[1], PyArray_TRIVIALLY_ITERABLE_OP_READ, PyArray_TRIVIALLY_ITERABLE_OP_NOREAD)) { NPY_UF_DBG_PRINT("trivial 1 input\n"); trivial_two_operand_loop(op, innerloop, innerloopdata); return 0; } } else if (nin == 2 && nout == 1) { if (op[2] == NULL && (order == NPY_ANYORDER || order == NPY_KEEPORDER) && PyMicArray_TRIVIALLY_ITERABLE_PAIR(op[0], op[1], PyArray_TRIVIALLY_ITERABLE_OP_READ, PyArray_TRIVIALLY_ITERABLE_OP_READ)) { PyMicArrayObject *tmp; /* * Have to choose the input with more dimensions to clone, as * one of them could be a scalar. */ if (PyMicArray_NDIM(op[0]) >= PyMicArray_NDIM(op[1])) { tmp = op[0]; } else { tmp = op[1]; } Py_INCREF(dtypes[2]); op[2] = (PyMicArrayObject *)PyMicArray_NewFromDescr( PyMicArray_DEVICE(tmp), &PyMicArray_Type, dtypes[2], PyMicArray_NDIM(tmp), PyMicArray_DIMS(tmp), NULL, NULL, PyMicArray_ISFORTRAN(tmp) ? NPY_ARRAY_F_CONTIGUOUS : 0, NULL); if (op[2] == NULL) { return -1; } NPY_UF_DBG_PRINT("trivial 2 input with allocated output\n"); trivial_three_operand_loop(op, innerloop, innerloopdata); return 0; } else if (op[2] != NULL && PyMicArray_NDIM(op[2]) >= PyMicArray_NDIM(op[0]) && PyMicArray_NDIM(op[2]) >= PyMicArray_NDIM(op[1]) && PyMicArray_TRIVIALLY_ITERABLE_TRIPLE(op[0], op[1], op[2], PyArray_TRIVIALLY_ITERABLE_OP_READ, PyArray_TRIVIALLY_ITERABLE_OP_READ, PyArray_TRIVIALLY_ITERABLE_OP_NOREAD)) { NPY_UF_DBG_PRINT("trivial 2 input\n"); trivial_three_operand_loop(op, innerloop, innerloopdata); return 0; } } } /* * If no trivial loop matched, an iterator is required to * resolve broadcasting, etc */ NPY_UF_DBG_PRINT("iterator loop\n"); if (iterator_loop(ufunc, op, dtypes, order, buffersize, arr_prep, arr_prep_args, innerloop, innerloopdata) < 0) { return -1; } return 0; } /* * nin - number of inputs * nout - number of outputs * wheremask - if not NULL, the 'where=' parameter to the ufunc. * op - the operands (nin + nout of them) * order - the loop execution order/output memory order * buffersize - how big of a buffer to use * arr_prep - the __array_prepare__ functions for the outputs * innerloop - the inner loop function * innerloopdata - data to pass to the inner loop */ static int execute_fancy_ufunc_loop(PyUFuncObject *ufunc, PyMicArrayObject *wheremask, PyMicArrayObject **op, PyArray_Descr **dtypes, NPY_ORDER order, npy_intp buffersize, PyObject **arr_prep, PyObject *arr_prep_args) { int i, nin = ufunc->nin, nout = ufunc->nout; int nop = nin + nout; int nop_real; npy_uint32 op_flags[NPY_MAXARGS]; NpyIter *iter; int device; npy_intp default_op_in_flags = 0, default_op_out_flags = 0; NpyIter_IterNextFunc *iternext; char **dataptr; npy_intp *strides; npy_intp *countptr; PyArrayObject *op_npy[NPY_MAXARGS]; PyMicArrayObject *op_new[nop]; int count_new = 0; npy_uint32 iter_flags; device = PyMUFunc_GetCommonDevice(nin, op); if (wheremask != NULL) { if (nop + 1 > NPY_MAXARGS) { PyErr_SetString(PyExc_ValueError, "Too many operands when including where= parameter"); return -1; } op[nop] = wheremask; dtypes[nop] = NULL; default_op_out_flags |= NPY_ITER_WRITEMASKED; } /* Set up the flags */ for (i = 0; i < nin; ++i) { op_flags[i] = default_op_in_flags | NPY_ITER_READONLY | NPY_ITER_ALIGNED; /* * If READWRITE flag has been set for this operand, * then clear default READONLY flag */ op_flags[i] |= ufunc->op_flags[i]; if (op_flags[i] & (NPY_ITER_READWRITE | NPY_ITER_WRITEONLY)) { op_flags[i] &= ~NPY_ITER_READONLY; } } for (i = nin; i < nop; ++i) { op_flags[i] = default_op_out_flags | NPY_ITER_WRITEONLY | NPY_ITER_ALIGNED | NPY_ITER_NO_BROADCAST | NPY_ITER_NO_SUBTYPE; } if (wheremask != NULL) { op_flags[nop] = NPY_ITER_READONLY | NPY_ITER_ARRAYMASK; } NPY_UF_DBG_PRINT("Making iterator\n"); iter_flags = ufunc->iter_flags | NPY_ITER_EXTERNAL_LOOP | NPY_ITER_REFS_OK | NPY_ITER_ZEROSIZE_OK; /* Allocate output array */ for (i = nin; i < nop; ++i) { PyMicArrayObject *tmp; if (op[i] == NULL) { tmp = PyMUFunc_CreateArrayBroadcast(nin, op, dtypes[i]); if (tmp == NULL) { goto fail; } op[i] = tmp; op_new[count_new++] = tmp; } } /* Copy two array of PyArrayObject * */ for (i = 0; i < nop; ++i) { op_npy[i] = (PyArrayObject *) op[i]; } nop_real = nop + ((wheremask != NULL) ? 1 : 0); /* * Allocate the iterator. Because the types of the inputs * were already checked, we use the casting rule 'unsafe' which * is faster to calculate. */ iter = NpyIter_MultiNew(nop_real, op_npy, iter_flags, order, NPY_UNSAFE_CASTING, op_flags, dtypes); if (iter == NULL) { goto fail; } NPY_UF_DBG_PRINT("Made iterator\n"); /* Call the __array_prepare__ functions where necessary */ /* for (i = 0; i < nout; ++i) { if (prepare_ufunc_output(ufunc, &op[nin+i], arr_prep[i], arr_prep_args, i) < 0) { NpyIter_Deallocate(iter); return -1; } } */ /* Only do the loop if the iteration size is non-zero */ if (NpyIter_GetIterSize(iter) != 0) { PyUFunc_MaskedStridedInnerLoopFunc *innerloop; NpyAuxData *innerloopdata; npy_intp fixed_strides[2*NPY_MAXARGS]; PyArray_Descr **iter_dtypes; NPY_BEGIN_THREADS_DEF; /* Validate that the prepare_ufunc_output didn't mess with pointers */ /* for (i = nin; i < nop; ++i) { if (PyArray_BYTES(op[i]) != PyArray_BYTES(op_it[i])) { PyErr_SetString(PyExc_ValueError, "The __array_prepare__ functions modified the data " "pointer addresses in an invalid fashion"); NpyIter_Deallocate(iter); return -1; } } */ /* * Get the inner loop, with the possibility of specialization * based on the fixed strides. */ NpyIter_GetInnerFixedStrideArray(iter, fixed_strides); iter_dtypes = NpyIter_GetDescrArray(iter); if (ufunc->masked_inner_loop_selector(ufunc, dtypes, wheremask != NULL ? iter_dtypes[nop] : iter_dtypes[nop + nin], fixed_strides, wheremask != NULL ? fixed_strides[nop] : fixed_strides[nop + nin], &innerloop, &innerloopdata, 0) < 0) { NpyIter_Deallocate(iter); return -1; } /* Get the variables needed for the loop */ iternext = NpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { NpyIter_Deallocate(iter); return -1; } dataptr = NpyIter_GetDataPtrArray(iter); strides = NpyIter_GetInnerStrideArray(iter); countptr = NpyIter_GetInnerLoopSizePtr(iter); NPY_BEGIN_THREADS_NDITER(iter); NPY_UF_DBG_PRINT("Actual inner loop:\n"); /* Execute the loop */ do { NPY_UF_DBG_PRINT1("iterator loop count %d\n", (int)*countptr); npy_intp count = *countptr; #pragma omp target device(device) \ map(to: innerloop, count, innerloopdata,\ strides[0:nop_real]) innerloop(NULL, strides, NULL, strides[nop], count, innerloopdata); } while (iternext(iter)); NPY_END_THREADS; NPY_AUXDATA_FREE(innerloopdata); } NpyIter_Deallocate(iter); return 0; fail: for (i = 0; i < count_new; ++i) { Py_DECREF(op_new[i]); } return -1; } static PyObject * make_arr_prep_args(npy_intp nin, PyObject *args, PyObject *kwds) { PyObject *out = kwds ? PyDict_GetItem(kwds, mpy_um_str_out) : NULL; PyObject *arr_prep_args; if (out == NULL) { Py_INCREF(args); return args; } else { npy_intp i, nargs = PyTuple_GET_SIZE(args), n; n = nargs; if (n < nin + 1) { n = nin + 1; } arr_prep_args = PyTuple_New(n); if (arr_prep_args == NULL) { return NULL; } /* Copy the tuple, but set the nin-th item to the keyword arg */ for (i = 0; i < nin; ++i) { PyObject *item = PyTuple_GET_ITEM(args, i); Py_INCREF(item); PyTuple_SET_ITEM(arr_prep_args, i, item); } Py_INCREF(out); PyTuple_SET_ITEM(arr_prep_args, nin, out); for (i = nin+1; i < n; ++i) { PyObject *item = PyTuple_GET_ITEM(args, i); Py_INCREF(item); PyTuple_SET_ITEM(arr_prep_args, i, item); } return arr_prep_args; } } /* * check the floating point status * - errmask: mask of status to check * - extobj: ufunc pyvals object * may be null, in which case the thread global one is fetched * - ufunc_name: name of ufunc */ static int _check_ufunc_fperr(int errmask, PyObject *extobj, const char *ufunc_name) { int fperr; PyObject *errobj = NULL; int ret; int first = 1; if (!errmask) { return 0; } fperr = PyUFunc_getfperr(); if (!fperr) { return 0; } /* Get error object globals */ if (extobj == NULL) { extobj = get_global_ext_obj(); } if (_extract_pyvals(extobj, ufunc_name, NULL, NULL, &errobj) < 0) { Py_XDECREF(errobj); return -1; } ret = PyUFunc_handlefperr(errmask, errobj, fperr, &first); Py_XDECREF(errobj); return ret; } static int PyMUFunc_GeneralizedFunction(PyUFuncObject *ufunc, PyObject *args, PyObject *kwds, PyMicArrayObject **op) { int nin, nout; int i, j, idim, nop; const char *ufunc_name; int retval = -1, subok = 1; int needs_api = 0; PyArray_Descr *dtypes[NPY_MAXARGS]; /* Use remapped axes for generalized ufunc */ int broadcast_ndim, iter_ndim; int op_axes_arrays[NPY_MAXARGS][NPY_MAXDIMS]; int *op_axes[NPY_MAXARGS]; npy_uint32 op_flags[NPY_MAXARGS]; npy_intp iter_shape[NPY_MAXARGS]; NpyIter *iter = NULL; npy_uint32 iter_flags; npy_intp total_problem_size; PyArrayObject *op_npy[NPY_MAXARGS]; int device; /* These parameters come from extobj= or from a TLS global */ int buffersize = 0, errormask = 0; /* The selected inner loop */ PyUFuncGenericFunction innerloop = NULL; void *innerloopdata = NULL; /* The dimensions which get passed to the inner loop */ npy_intp inner_dimensions[NPY_MAXDIMS+1]; /* The strides which get passed to the inner loop */ npy_intp *inner_strides = NULL; /* The sizes of the core dimensions (# entries is ufunc->core_num_dim_ix) */ npy_intp *core_dim_sizes = inner_dimensions + 1; int core_dim_ixs_size; /* The __array_prepare__ function to call for each output */ PyObject *arr_prep[NPY_MAXARGS]; /* * This is either args, or args with the out= parameter from * kwds added appropriately. */ PyObject *arr_prep_args = NULL; NPY_ORDER order = NPY_KEEPORDER; /* Use the default assignment casting rule */ NPY_CASTING casting = NPY_DEFAULT_ASSIGN_CASTING; /* When provided, extobj and typetup contain borrowed references */ PyObject *extobj = NULL, *type_tup = NULL; /* backup data to make PyMicArray work with PyArray type resolver */ npy_longlong scal_buffer[4*ufunc->nin]; void *scal_ptrs[ufunc->nin]; if (ufunc == NULL) { PyErr_SetString(PyExc_ValueError, "function not supported"); return -1; } nin = ufunc->nin; nout = ufunc->nout; nop = nin + nout; ufunc_name = _get_ufunc_name(ufunc); NPY_UF_DBG_PRINT1("\nEvaluating ufunc %s\n", ufunc_name); /* Initialize all the operands and dtypes to NULL */ for (i = 0; i < nop; ++i) { op[i] = NULL; dtypes[i] = NULL; arr_prep[i] = NULL; } NPY_UF_DBG_PRINT("Getting arguments\n"); /* Get all the arguments */ retval = get_ufunc_arguments(ufunc, args, kwds, op, &order, &casting, &extobj, &type_tup, &subok, NULL); if (retval < 0) { goto fail; } /* * Figure out the number of iteration dimensions, which * is the broadcast result of all the input non-core * dimensions. */ broadcast_ndim = 0; for (i = 0; i < nin; ++i) { int n = PyMicArray_NDIM(op[i]) - ufunc->core_num_dims[i]; if (n > broadcast_ndim) { broadcast_ndim = n; } } /* * Figure out the number of iterator creation dimensions, * which is the broadcast dimensions + all the core dimensions of * the outputs, so that the iterator can allocate those output * dimensions following the rules of order='F', for example. */ iter_ndim = broadcast_ndim; for (i = nin; i < nop; ++i) { iter_ndim += ufunc->core_num_dims[i]; } if (iter_ndim > NPY_MAXDIMS) { PyErr_Format(PyExc_ValueError, "too many dimensions for generalized ufunc %s", ufunc_name); retval = -1; goto fail; } /* * Validate the core dimensions of all the operands, and collect all of * the labelled core dimensions into 'core_dim_sizes'. * * The behavior has been changed in NumPy 1.10.0, and the following * requirements must be fulfilled or an error will be raised: * * Arguments, both input and output, must have at least as many * dimensions as the corresponding number of core dimensions. In * previous versions, 1's were prepended to the shape as needed. * * Core dimensions with same labels must have exactly matching sizes. * In previous versions, core dimensions of size 1 would broadcast * against other core dimensions with the same label. * * All core dimensions must have their size specified by a passed in * input or output argument. In previous versions, core dimensions in * an output argument that were not specified in an input argument, * and whose size could not be inferred from a passed in output * argument, would have their size set to 1. */ for (i = 0; i < ufunc->core_num_dim_ix; ++i) { core_dim_sizes[i] = -1; } for (i = 0; i < nop; ++i) { if (op[i] != NULL) { int dim_offset = ufunc->core_offsets[i]; int num_dims = ufunc->core_num_dims[i]; int core_start_dim = PyMicArray_NDIM(op[i]) - num_dims; /* Check if operands have enough dimensions */ if (core_start_dim < 0) { PyErr_Format(PyExc_ValueError, "%s: %s operand %d does not have enough " "dimensions (has %d, gufunc core with " "signature %s requires %d)", ufunc_name, i < nin ? "Input" : "Output", i < nin ? i : i - nin, PyMicArray_NDIM(op[i]), ufunc->core_signature, num_dims); retval = -1; goto fail; } /* * Make sure every core dimension exactly matches all other core * dimensions with the same label. */ for (idim = 0; idim < num_dims; ++idim) { int core_dim_index = ufunc->core_dim_ixs[dim_offset+idim]; npy_intp op_dim_size = PyMicArray_DIM(op[i], core_start_dim+idim); if (core_dim_sizes[core_dim_index] == -1) { core_dim_sizes[core_dim_index] = op_dim_size; } else if (op_dim_size != core_dim_sizes[core_dim_index]) { PyErr_Format(PyExc_ValueError, "%s: %s operand %d has a mismatch in its " "core dimension %d, with gufunc " "signature %s (size %zd is different " "from %zd)", ufunc_name, i < nin ? "Input" : "Output", i < nin ? i : i - nin, idim, ufunc->core_signature, op_dim_size, core_dim_sizes[core_dim_index]); retval = -1; goto fail; } } } } /* * Make sure no core dimension is unspecified. */ for (i = 0; i < ufunc->core_num_dim_ix; ++i) { if (core_dim_sizes[i] == -1) { break; } } if (i != ufunc->core_num_dim_ix) { /* * There is at least one core dimension missing, find in which * operand it comes up first (it has to be an output operand). */ const int missing_core_dim = i; int out_op; for (out_op = nin; out_op < nop; ++out_op) { int first_idx = ufunc->core_offsets[out_op]; int last_idx = first_idx + ufunc->core_num_dims[out_op]; for (i = first_idx; i < last_idx; ++i) { if (ufunc->core_dim_ixs[i] == missing_core_dim) { break; } } if (i < last_idx) { /* Change index offsets for error message */ out_op -= nin; i -= first_idx; break; } } PyErr_Format(PyExc_ValueError, "%s: Output operand %d has core dimension %d " "unspecified, with gufunc signature %s", ufunc_name, out_op, i, ufunc->core_signature); retval = -1; goto fail; } /* Fill in the initial part of 'iter_shape' */ for (idim = 0; idim < broadcast_ndim; ++idim) { iter_shape[idim] = -1; } /* Fill in op_axes for all the operands */ j = broadcast_ndim; core_dim_ixs_size = 0; for (i = 0; i < nop; ++i) { int n; if (op[i]) { /* * Note that n may be negative if broadcasting * extends into the core dimensions. */ n = PyMicArray_NDIM(op[i]) - ufunc->core_num_dims[i]; } else { n = broadcast_ndim; } /* Broadcast all the unspecified dimensions normally */ for (idim = 0; idim < broadcast_ndim; ++idim) { if (idim >= broadcast_ndim - n) { op_axes_arrays[i][idim] = idim - (broadcast_ndim - n); } else { op_axes_arrays[i][idim] = -1; } } /* Any output core dimensions shape should be ignored */ for (idim = broadcast_ndim; idim < iter_ndim; ++idim) { op_axes_arrays[i][idim] = -1; } /* Except for when it belongs to this output */ if (i >= nin) { int dim_offset = ufunc->core_offsets[i]; int num_dims = ufunc->core_num_dims[i]; /* Fill in 'iter_shape' and 'op_axes' for this output */ for (idim = 0; idim < num_dims; ++idim) { iter_shape[j] = core_dim_sizes[ ufunc->core_dim_ixs[dim_offset + idim]]; op_axes_arrays[i][j] = n + idim; ++j; } } op_axes[i] = op_axes_arrays[i]; core_dim_ixs_size += ufunc->core_num_dims[i]; } /* Get the buffersize and errormask */ if (_get_bufsize_errmask(extobj, ufunc_name, &buffersize, &errormask) < 0) { retval = -1; goto fail; } NPY_UF_DBG_PRINT("Finding inner loop\n"); /* Work around to live with numpy type_resolver */ ufunc_pre_typeresolver(ufunc, op, scal_ptrs, scal_buffer, 4); retval = ufunc->type_resolver(ufunc, casting, (PyArrayObject **)op, type_tup, dtypes); ufunc_post_typeresolver(ufunc, op, scal_ptrs); if (retval < 0) { goto fail; } /* For the generalized ufunc, we get the loop right away too */ retval = ufunc->legacy_inner_loop_selector(ufunc, dtypes, &innerloop, &innerloopdata, &needs_api); if (retval < 0) { goto fail; } #if NPY_UF_DBG_TRACING printf("input types:\n"); for (i = 0; i < nin; ++i) { PyObject_Print((PyObject *)dtypes[i], stdout, 0); printf(" "); } printf("\noutput types:\n"); for (i = nin; i < nop; ++i) { PyObject_Print((PyObject *)dtypes[i], stdout, 0); printf(" "); } printf("\n"); #endif if (subok) { /* TODO: Do we really need subok? */ PyErr_SetString(PyExc_ValueError, "Do not support subok"); goto fail; /* * Get the appropriate __array_prepare__ function to call * for each output */ //_find_array_prepare(args, kwds, arr_prep, nin, nout, 0); /* Set up arr_prep_args if a prep function was needed */ /* for (i = 0; i < nout; ++i) { if (arr_prep[i] != NULL && arr_prep[i] != Py_None) { arr_prep_args = make_arr_prep_args(nin, args, kwds); break; } } */ } /* If the loop wants the arrays, provide them */ if (_does_loop_use_arrays(innerloopdata)) { innerloopdata = (void*)op; } /* * Set up the iterator per-op flags. For generalized ufuncs, we * can't do buffering, so must COPY or UPDATEIFCOPY. */ for (i = 0; i < nin; ++i) { op_flags[i] = NPY_ITER_READONLY | NPY_ITER_ALIGNED; /* * If READWRITE flag has been set for this operand, * then clear default READONLY flag */ op_flags[i] |= ufunc->op_flags[i]; if (op_flags[i] & (NPY_ITER_READWRITE | NPY_ITER_WRITEONLY)) { op_flags[i] &= ~NPY_ITER_READONLY; } } for (i = nin; i < nop; ++i) { op_flags[i] = NPY_ITER_READWRITE| //NPY_ITER_UPDATEIFCOPY| NPY_ITER_ALIGNED| //NPY_ITER_ALLOCATE| NPY_ITER_NO_BROADCAST; } iter_flags = ufunc->iter_flags | NPY_ITER_MULTI_INDEX | NPY_ITER_REFS_OK | NPY_ITER_REDUCE_OK | NPY_ITER_ZEROSIZE_OK; /* Find destination device */ device = PyMUFunc_GetCommonDevice(nin, op); /* Allocate output array */ for (i = nin; i < nop; ++i) { PyMicArrayObject *tmp; if (op[i] == NULL) { tmp = PyMUFunc_CreateArrayBroadcast(nin, op, dtypes[i]); if (tmp == NULL) { goto fail; } op[i] = tmp; } } /* Create temporary PyMicArrayObject * array */ /* TODO cleanup this step */ /* for (i = 0; i < nop; ++i) { op_npy[i] = (PyArrayObject *) op[i]; } */ /* Create the iterator */ iter = NpyIter_AdvancedNew(nop, (PyArrayObject **) op, iter_flags, order, NPY_UNSAFE_CASTING, op_flags, dtypes, iter_ndim, op_axes, iter_shape, 0); if (iter == NULL) { retval = -1; goto fail; } /* Fill in any allocated outputs */ /*for (i = nin; i < nop; ++i) { if (op[i] == NULL) { op[i] = NpyIter_GetOperandArray(iter)[i]; Py_INCREF(op[i]); } } */ /* * Set up the inner strides array. Because we're not doing * buffering, the strides are fixed throughout the looping. */ inner_strides = (npy_intp *)PyArray_malloc( NPY_SIZEOF_INTP * (nop+core_dim_ixs_size)); if (inner_strides == NULL) { PyErr_NoMemory(); retval = -1; goto fail; } /* Copy the strides after the first nop */ idim = nop; for (i = 0; i < nop; ++i) { int num_dims = ufunc->core_num_dims[i]; int core_start_dim = PyMicArray_NDIM(op[i]) - num_dims; /* * Need to use the arrays in the iterator, not op, because * a copy with a different-sized type may have been made. */ //PyArrayObject *arr = NpyIter_GetOperandArray(iter)[i]; PyMicArrayObject *arr = op[i]; npy_intp *shape = PyMicArray_SHAPE(arr); npy_intp *strides = PyMicArray_STRIDES(arr); for (j = 0; j < num_dims; ++j) { if (core_start_dim + j >= 0) { /* * Force the stride to zero when the shape is 1, sot * that the broadcasting works right. */ if (shape[core_start_dim + j] != 1) { inner_strides[idim++] = strides[core_start_dim + j]; } else { inner_strides[idim++] = 0; } } else { inner_strides[idim++] = 0; } } } total_problem_size = NpyIter_GetIterSize(iter); if (total_problem_size < 0) { /* * Only used for threading, if negative (this means that it is * larger then ssize_t before axes removal) assume that the actual * problem is large enough to be threaded usefully. */ total_problem_size = 1000; } /* Remove all the core output dimensions from the iterator */ for (i = broadcast_ndim; i < iter_ndim; ++i) { if (NpyIter_RemoveAxis(iter, broadcast_ndim) != NPY_SUCCEED) { retval = -1; goto fail; } } if (NpyIter_RemoveMultiIndex(iter) != NPY_SUCCEED) { retval = -1; goto fail; } if (NpyIter_EnableExternalLoop(iter) != NPY_SUCCEED) { retval = -1; goto fail; } /* * The first nop strides are for the inner loop (but only can * copy them after removing the core axes */ memcpy(inner_strides, NpyIter_GetInnerStrideArray(iter), NPY_SIZEOF_INTP * nop); #if 0 printf("strides: "); for (i = 0; i < nop+core_dim_ixs_size; ++i) { printf("%d ", (int)inner_strides[i]); } printf("\n"); #endif /* Start with the floating-point exception flags cleared */ PyUFunc_clearfperr(); NPY_UF_DBG_PRINT("Executing inner loop\n"); if (NpyIter_GetIterSize(iter) != 0) { /* Do the ufunc loop */ NpyIter_IterNextFunc *iternext; char **dataptr; npy_intp *count_ptr; NPY_BEGIN_THREADS_DEF; /* Get the variables needed for the loop */ iternext = NpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { retval = -1; goto fail; } dataptr = NpyIter_GetDataPtrArray(iter); count_ptr = NpyIter_GetInnerLoopSizePtr(iter); if (!needs_api && !NpyIter_IterationNeedsAPI(iter)) { NPY_BEGIN_THREADS_THRESHOLDED(total_problem_size); } do { inner_dimensions[0] = *count_ptr; #pragma omp target device(device) \ map(to: innerloop, innerloopdata,\ inner_dimensions[0:NPY_MAXDIMS+1],\ inner_strides[0:nop+core_dim_ixs_size]) innerloop(NULL, inner_dimensions, inner_strides, innerloopdata); } while (iternext(iter)); if (!needs_api && !NpyIter_IterationNeedsAPI(iter)) { NPY_END_THREADS; } } else { /** * For each output operand, check if it has non-zero size, * and assign the identity if it does. For example, a dot * product of two zero-length arrays will be a scalar, * which has size one. */ for (i = nin; i < nop; ++i) { if (PyMicArray_SIZE(op[i]) != 0) { switch (ufunc->identity) { case PyUFunc_Zero: assign_reduce_identity_zero(op[i], NULL); break; case PyUFunc_One: assign_reduce_identity_one(op[i], NULL); break; case PyUFunc_MinusOne: assign_reduce_identity_minusone(op[i], NULL); break; case PyUFunc_None: case PyUFunc_ReorderableNone: PyErr_Format(PyExc_ValueError, "ufunc %s ", ufunc_name); retval = -1; goto fail; default: PyErr_Format(PyExc_ValueError, "ufunc %s has an invalid identity for reduction", ufunc_name); retval = -1; goto fail; } } } } /* Check whether any errors occurred during the loop */ if (PyErr_Occurred() || _check_ufunc_fperr(errormask, extobj, ufunc_name) < 0) { retval = -1; goto fail; } PyArray_free(inner_strides); NpyIter_Deallocate(iter); /* The caller takes ownership of all the references in op */ for (i = 0; i < nop; ++i) { Py_XDECREF(dtypes[i]); Py_XDECREF(arr_prep[i]); } Py_XDECREF(type_tup); Py_XDECREF(arr_prep_args); NPY_UF_DBG_PRINT("Returning Success\n"); return 0; fail: NPY_UF_DBG_PRINT1("Returning failure code %d\n", retval); PyArray_free(inner_strides); NpyIter_Deallocate(iter); for (i = 0; i < nop; ++i) { Py_XDECREF(op[i]); op[i] = NULL; Py_XDECREF(dtypes[i]); Py_XDECREF(arr_prep[i]); } Py_XDECREF(type_tup); Py_XDECREF(arr_prep_args); return retval; } /*UFUNC_API * * This generic function is called with the ufunc object, the arguments to it, * and an array of (pointers to) PyMicArrayObjects which are NULL. * * 'op' is an array of at least NPY_MAXARGS PyMicArrayObject *. */ NPY_NO_EXPORT int PyMUFunc_GenericFunction(PyUFuncObject *ufunc, PyObject *args, PyObject *kwds, PyMicArrayObject **op) { int nin, nout; int i, nop; const char *ufunc_name; int retval = -1, subok = 0; int need_fancy = 0; PyArray_Descr *dtypes[NPY_MAXARGS]; /* These parameters come from extobj= or from a TLS global */ int buffersize = 0, errormask = 0; /* The mask provided in the 'where=' parameter */ PyMicArrayObject *wheremask = NULL; /* The __array_prepare__ function to call for each output */ PyObject *arr_prep[NPY_MAXARGS]; /* * This is either args, or args with the out= parameter from * kwds added appropriately. */ PyObject *arr_prep_args = NULL; /* backup data to make PyMicArray work with PyArray type resolver */ npy_longlong scal_buffer[4*ufunc->nin]; void *scal_ptrs[ufunc->nin]; int trivial_loop_ok = 0; NPY_ORDER order = NPY_KEEPORDER; /* Use the default assignment casting rule */ NPY_CASTING casting = NPY_DEFAULT_ASSIGN_CASTING; /* When provided, extobj and typetup contain borrowed references */ PyObject *extobj = NULL, *type_tup = NULL; if (ufunc == NULL) { PyErr_SetString(PyExc_ValueError, "function not supported"); return -1; } if (ufunc->core_enabled) { return PyMUFunc_GeneralizedFunction(ufunc, args, kwds, op); } nin = ufunc->nin; nout = ufunc->nout; nop = nin + nout; ufunc_name = _get_ufunc_name(ufunc); NPY_UF_DBG_PRINT1("\nEvaluating ufunc %s\n", ufunc_name); /* Initialize all the operands and dtypes to NULL */ for (i = 0; i < nop; ++i) { op[i] = NULL; dtypes[i] = NULL; arr_prep[i] = NULL; } NPY_UF_DBG_PRINT("Getting arguments\n"); /* Get all the arguments */ retval = get_ufunc_arguments(ufunc, args, kwds, op, &order, &casting, &extobj, &type_tup, &subok, &wheremask); if (retval < 0) { goto fail; } /* All array have to be in the same device */ retval = _on_same_device(ufunc, op); if (retval < 0) { PyErr_SetString(PyExc_ValueError, "All array have to be on the same device"); goto fail; } /* * Use the masked loop if a wheremask was specified. */ if (wheremask != NULL) { need_fancy = 1; } /* Get the buffersize and errormask */ if (_get_bufsize_errmask(extobj, ufunc_name, &buffersize, &errormask) < 0) { retval = -1; goto fail; } NPY_UF_DBG_PRINT("Finding inner loop\n"); /* Work around to live with numpy type_resolver */ ufunc_pre_typeresolver(ufunc, op, scal_ptrs, scal_buffer, 4); retval = ufunc->type_resolver(ufunc, casting, (PyArrayObject **)op, type_tup, dtypes); ufunc_post_typeresolver(ufunc, op, scal_ptrs); if (retval < 0) { goto fail; } /* Only do the trivial loop check for the unmasked version. */ if (!need_fancy) { /* * This checks whether a trivial loop is ok, making copies of * scalar and one dimensional operands if that will help. */ trivial_loop_ok = check_for_trivial_loop(ufunc, op, dtypes, buffersize); if (trivial_loop_ok < 0) { goto fail; } } #if NPY_UF_DBG_TRACING printf("input types:\n"); for (i = 0; i < nin; ++i) { PyObject_Print((PyObject *)dtypes[i], stdout, 0); printf(" "); } printf("\noutput types:\n"); for (i = nin; i < nop; ++i) { PyObject_Print((PyObject *)dtypes[i], stdout, 0); printf(" "); } printf("\n"); #endif if (subok) { PyErr_SetString(PyExc_ValueError, "does not support subok right now"); goto fail; } /* Start with the floating-point exception flags cleared */ PyUFunc_clearfperr(); /* Do the ufunc loop */ if (need_fancy) { NPY_UF_DBG_PRINT("Executing fancy inner loop\n"); retval = execute_fancy_ufunc_loop(ufunc, wheremask, op, dtypes, order, buffersize, arr_prep, arr_prep_args); } else { NPY_UF_DBG_PRINT("Executing legacy inner loop\n"); retval = execute_legacy_ufunc_loop(ufunc, trivial_loop_ok, op, dtypes, order, buffersize, arr_prep, arr_prep_args); } if (retval < 0) { goto fail; } /* Check whether any errors occurred during the loop */ if (PyErr_Occurred() || _check_ufunc_fperr(errormask, extobj, ufunc_name) < 0) { retval = -1; goto fail; } /* The caller takes ownership of all the references in op */ for (i = 0; i < nop; ++i) { Py_XDECREF(dtypes[i]); Py_XDECREF(arr_prep[i]); } Py_XDECREF(type_tup); Py_XDECREF(arr_prep_args); Py_XDECREF(wheremask); NPY_UF_DBG_PRINT("Returning Success\n"); return 0; fail: NPY_UF_DBG_PRINT1("Returning failure code %d\n", retval); for (i = 0; i < nop; ++i) { Py_XDECREF(op[i]); op[i] = NULL; Py_XDECREF(dtypes[i]); Py_XDECREF(arr_prep[i]); } Py_XDECREF(type_tup); Py_XDECREF(arr_prep_args); Py_XDECREF(wheremask); return retval; } /* * Given the output type, finds the specified binary op. The * ufunc must have nin==2 and nout==1. The function may modify * otype if the given type isn't found. * * Returns 0 on success, -1 on failure. */ static int get_binary_op_function(PyUFuncObject *ufunc, int *otype, PyUFuncGenericFunction *out_innerloop, void **out_innerloopdata) { int i; PyUFunc_Loop1d *funcdata; NPY_UF_DBG_PRINT1("Getting binary op function for type number %d\n", *otype); /* If the type is custom and there are userloops, search for it here */ if (ufunc->userloops != NULL && PyTypeNum_ISUSERDEF(*otype)) { PyObject *key, *obj; key = PyInt_FromLong(*otype); if (key == NULL) { return -1; } obj = PyDict_GetItem(ufunc->userloops, key); Py_DECREF(key); if (obj != NULL) { funcdata = (PyUFunc_Loop1d *)NpyCapsule_AsVoidPtr(obj); while (funcdata != NULL) { int *types = funcdata->arg_types; if (types[0] == *otype && types[1] == *otype && types[2] == *otype) { *out_innerloop = funcdata->func; *out_innerloopdata = funcdata->data; return 0; } funcdata = funcdata->next; } } } /* Search for a function with compatible inputs */ for (i = 0; i < ufunc->ntypes; ++i) { char *types = ufunc->types + i*ufunc->nargs; NPY_UF_DBG_PRINT3("Trying loop with signature %d %d -> %d\n", types[0], types[1], types[2]); if (PyArray_CanCastSafely(*otype, types[0]) && types[0] == types[1] && (*otype == NPY_OBJECT || types[0] != NPY_OBJECT)) { /* If the signature is "xx->x", we found the loop */ if (types[2] == types[0]) { *out_innerloop = ufunc->functions[i]; *out_innerloopdata = ufunc->data[i]; *otype = types[0]; return 0; } /* * Otherwise, we found the natural type of the reduction, * replace otype and search again */ else { *otype = types[2]; break; } } } /* Search for the exact function */ for (i = 0; i < ufunc->ntypes; ++i) { char *types = ufunc->types + i*ufunc->nargs; if (PyArray_CanCastSafely(*otype, types[0]) && types[0] == types[1] && types[1] == types[2] && (*otype == NPY_OBJECT || types[0] != NPY_OBJECT)) { /* Since the signature is "xx->x", we found the loop */ *out_innerloop = ufunc->functions[i]; *out_innerloopdata = ufunc->data[i]; *otype = types[0]; return 0; } } return -1; } static int reduce_type_resolver(PyUFuncObject *ufunc, PyMicArrayObject *arr, PyArray_Descr *odtype, PyArray_Descr **out_dtype) { int i, retcode; PyMicArrayObject *op[3] = {arr, arr, NULL}; PyArray_Descr *dtypes[3] = {NULL, NULL, NULL}; const char *ufunc_name = _get_ufunc_name(ufunc); PyObject *type_tup = NULL; void *ptrs[3]; npy_longlong buf[3*4]; *out_dtype = NULL; /* * If odtype is specified, make a type tuple for the type * resolution. */ if (odtype != NULL) { type_tup = PyTuple_Pack(3, odtype, odtype, Py_None); if (type_tup == NULL) { return -1; } } ufunc_pre_typeresolver(ufunc, op, ptrs, buf, 4); /* Use the type resolution function to find our loop */ retcode = ufunc->type_resolver( ufunc, NPY_UNSAFE_CASTING, (PyArrayObject **)op, type_tup, dtypes); ufunc_post_typeresolver(ufunc, op, ptrs); Py_DECREF(type_tup); if (retcode == -1) { return -1; } else if (retcode == -2) { PyErr_Format(PyExc_RuntimeError, "type resolution returned NotImplemented to " "reduce ufunc %s", ufunc_name); return -1; } /* * The first two type should be equivalent. Because of how * reduce has historically behaved in NumPy, the return type * could be different, and it is the return type on which the * reduction occurs. */ if (!PyArray_EquivTypes(dtypes[0], dtypes[1])) { for (i = 0; i < 3; ++i) { Py_DECREF(dtypes[i]); } PyErr_Format(PyExc_RuntimeError, "could not find a type resolution appropriate for " "reduce ufunc %s", ufunc_name); return -1; } Py_DECREF(dtypes[0]); Py_DECREF(dtypes[1]); *out_dtype = dtypes[2]; return 0; } static int assign_reduce_identity_zero(PyMicArrayObject *result, void *NPY_UNUSED(data)) { return PyMicArray_FillWithScalar(result, PyArrayScalar_False); } static int assign_reduce_identity_one(PyMicArrayObject *result, void *NPY_UNUSED(data)) { return PyMicArray_FillWithScalar(result, PyArrayScalar_True); } static int assign_reduce_identity_minusone(PyMicArrayObject *result, void *NPY_UNUSED(data)) { static PyObject *MinusOne = NULL; if (MinusOne == NULL) { if ((MinusOne = PyInt_FromLong(-1)) == NULL) { return -1; } } return PyMicArray_FillWithScalar(result, MinusOne); } static int reduce_loop(MpyIter *iter, npy_intp skip_first_count, PyUFuncObject *ufunc) { PyArray_Descr *dtypes[3], **iter_dtypes; npy_intp *dataptrs, *strides, *countptr; npy_intp dataptrs_copy[3]; npy_intp strides_copy[3]; int needs_api, device; /* The normal selected inner loop */ void *loopdata; MPY_TARGET_MIC PyUFuncGenericFunction innerloop = NULL; MPY_TARGET_MIC void (*innerloopdata)(void) = NULL; MPY_TARGET_MIC MpyIter_IterNextFunc *iternext = NULL; MPY_TARGET_MIC MpyIter_IsFirstVisitFunc *isfirstvisit; NPY_BEGIN_THREADS_DEF; /* Get the inner loop */ iter_dtypes = MpyIter_GetDescrArray(iter); dtypes[0] = iter_dtypes[0]; dtypes[1] = iter_dtypes[1]; dtypes[2] = iter_dtypes[0]; if (ufunc->legacy_inner_loop_selector(ufunc, dtypes, &innerloop, &loopdata, &needs_api) < 0) { return -1; } iternext = MpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { return -1; } innerloopdata = loopdata; isfirstvisit = &MpyIter_IsFirstVisit; dataptrs = (npy_intp *) MpyIter_GetDataPtrArray(iter); strides = MpyIter_GetInnerStrideArray(iter); countptr = MpyIter_GetInnerLoopSizePtr(iter); device = MpyIter_GetDevice(iter); MPY_BEGIN_THREADS_NDITER(iter); if (skip_first_count > 0) { do { npy_intp count = *countptr; /* Skip any first-visit elements */ if (MpyIter_IsFirstVisit(iter, 0)) { if (strides[0] == 0) { --count; --skip_first_count; dataptrs[1] += strides[1]; } else { skip_first_count -= count; count = 0; } } /* Turn the two items into three for the inner loop */ dataptrs_copy[0] = dataptrs[0]; dataptrs_copy[1] = dataptrs[1]; dataptrs_copy[2] = dataptrs[0]; strides_copy[0] = strides[0]; strides_copy[1] = strides[1]; strides_copy[2] = strides[0]; #pragma omp target device(device) map(to: dataptrs_copy, count,\ strides_copy,\ innerloop, innerloopdata) innerloop((char **)dataptrs_copy, &count, strides_copy, innerloopdata); /* Jump to the faster loop when skipping is done */ if (skip_first_count == 0) { if (iternext(iter)) { break; } else { goto finish_loop; } } } while (iternext(iter)); } do { /* Turn the two items into three for the inner loop */ dataptrs_copy[0] = dataptrs[0]; dataptrs_copy[1] = dataptrs[1]; dataptrs_copy[2] = dataptrs[0]; strides_copy[0] = strides[0]; strides_copy[1] = strides[1]; strides_copy[2] = strides[0]; #pragma omp target device(device) map(to: dataptrs_copy, strides_copy,\ innerloop, innerloopdata,\ countptr[0:1]) innerloop((char **) dataptrs_copy, countptr, strides_copy, innerloopdata); } while (iternext(iter)); finish_loop: NPY_END_THREADS; return (needs_api && PyErr_Occurred()) ? -1 : 0; } /* * The implementation of the reduction operators with the new iterator * turned into a bit of a long function here, but I think the design * of this part needs to be changed to be more like einsum, so it may * not be worth refactoring it too much. Consider this timing: * * >>> a = arange(10000) * * >>> timeit sum(a) * 10000 loops, best of 3: 17 us per loop * * >>> timeit einsum("i->",a) * 100000 loops, best of 3: 13.5 us per loop * * The axes must already be bounds-checked by the calling function, * this function does not validate them. */ static PyMicArrayObject * PyMUFunc_Reduce(PyUFuncObject *ufunc, PyMicArrayObject *arr, PyMicArrayObject *out, int naxes, int *axes, PyArray_Descr *odtype, int keepdims) { int iaxes, reorderable, ndim; npy_bool axis_flags[NPY_MAXDIMS]; PyArray_Descr *dtype; PyMicArrayObject *result; PyMicArray_AssignReduceIdentityFunc *assign_identity = NULL; const char *ufunc_name = _get_ufunc_name(ufunc); /* These parameters come from a TLS global */ int buffersize = 0, errormask = 0; NPY_UF_DBG_PRINT1("\nEvaluating ufunc %s.reduce\n", ufunc_name); ndim = PyMicArray_NDIM(arr); /* Create an array of flags for reduction */ memset(axis_flags, 0, ndim); for (iaxes = 0; iaxes < naxes; ++iaxes) { int axis = axes[iaxes]; if (axis_flags[axis]) { PyErr_SetString(PyExc_ValueError, "duplicate value in 'axis'"); return NULL; } axis_flags[axis] = 1; } switch (ufunc->identity) { case PyUFunc_Zero: assign_identity = &assign_reduce_identity_zero; reorderable = 1; /* * The identity for a dynamic dtype like * object arrays can't be used in general */ if (PyMicArray_ISOBJECT(arr) && PyMicArray_SIZE(arr) != 0) { assign_identity = NULL; } break; case PyUFunc_One: assign_identity = &assign_reduce_identity_one; reorderable = 1; /* * The identity for a dynamic dtype like * object arrays can't be used in general */ if (PyMicArray_ISOBJECT(arr) && PyMicArray_SIZE(arr) != 0) { assign_identity = NULL; } break; case PyUFunc_MinusOne: assign_identity = &assign_reduce_identity_minusone; reorderable = 1; /* * The identity for a dynamic dtype like * object arrays can't be used in general */ if (PyMicArray_ISOBJECT(arr) && PyMicArray_SIZE(arr) != 0) { assign_identity = NULL; } break; case PyUFunc_None: reorderable = 0; break; case PyUFunc_ReorderableNone: reorderable = 1; break; default: PyErr_Format(PyExc_ValueError, "ufunc %s has an invalid identity for reduction", ufunc_name); return NULL; } if (_get_bufsize_errmask(NULL, "reduce", &buffersize, &errormask) < 0) { return NULL; } /* Get the reduction dtype */ if (reduce_type_resolver(ufunc, arr, odtype, &dtype) < 0) { return NULL; } result = PyMUFunc_ReduceWrapper(arr, out, NULL, dtype, dtype, NPY_UNSAFE_CASTING, axis_flags, reorderable, keepdims, 0, assign_identity, reduce_loop, ufunc, buffersize, ufunc_name); Py_DECREF(dtype); return result; } static PyMicArrayObject * PyMUFunc_Accumulate(PyUFuncObject *ufunc, PyMicArrayObject *arr, PyMicArrayObject *out, int axis, int otype) { /* TODO:implement this */ return NULL; } /* * Reduceat performs a reduce over an axis using the indices as a guide * * op.reduceat(array,indices) computes * op.reduce(array[indices[i]:indices[i+1]] * for i=0..end with an implicit indices[i+1]=len(array) * assumed when i=end-1 * * if indices[i+1] <= indices[i]+1 * then the result is array[indices[i]] for that value * * op.accumulate(array) is the same as * op.reduceat(array,indices)[::2] * where indices is range(len(array)-1) with a zero placed in every other sample * indices = zeros(len(array)*2-1) * indices[1::2] = range(1,len(array)) * * output shape is based on the size of indices */ static PyMicArrayObject * PyMUFunc_Reduceat(PyUFuncObject *ufunc, PyMicArrayObject *arr, PyArrayObject *ind, PyMicArrayObject *out, int axis, int otype) { //TODO: Implement this return NULL; } /* * This code handles reduce, reduceat, and accumulate * (accumulate and reduce are special cases of the more general reduceat * but they are handled separately for speed) */ static PyObject * PyMUFunc_GenericReduction(PyUFuncObject *ufunc, PyObject *args, PyObject *kwds, int operation) { int i, naxes=0, ndim; int axes[NPY_MAXDIMS]; PyObject *axes_in = NULL; PyMicArrayObject *mp, *ret = NULL; PyObject *op, *res = NULL; PyObject *obj_ind, *context; PyArrayObject *indices = NULL; PyArray_Descr *otype = NULL; PyObject *out_obj = NULL; PyMicArrayObject *out = NULL; int keepdims = 0; static char *reduce_kwlist[] = { "array", "axis", "dtype", "out", "keepdims", NULL}; static char *accumulate_kwlist[] = { "array", "axis", "dtype", "out", "keepdims", NULL}; static char *reduceat_kwlist[] = { "array", "indices", "axis", "dtype", "out", NULL}; static char *_reduce_type[] = {"reduce", "accumulate", "reduceat", NULL}; if (ufunc == NULL) { PyErr_SetString(PyExc_ValueError, "function not supported"); return NULL; } if (ufunc->core_enabled) { PyErr_Format(PyExc_RuntimeError, "Reduction not defined on ufunc with signature"); return NULL; } if (ufunc->nin != 2) { PyErr_Format(PyExc_ValueError, "%s only supported for binary functions", _reduce_type[operation]); return NULL; } if (ufunc->nout != 1) { PyErr_Format(PyExc_ValueError, "%s only supported for functions " "returning a single value", _reduce_type[operation]); return NULL; } /* if there is a tuple of 1 for `out` in kwds, unpack it */ if (kwds != NULL) { PyObject *out_obj = PyDict_GetItem(kwds, mpy_um_str_out); if (out_obj != NULL && PyTuple_CheckExact(out_obj)) { if (PyTuple_GET_SIZE(out_obj) != 1) { PyErr_SetString(PyExc_ValueError, "The 'out' tuple must have exactly one entry"); return NULL; } out_obj = PyTuple_GET_ITEM(out_obj, 0); PyDict_SetItem(kwds, mpy_um_str_out, out_obj); } } if (operation == UFUNC_REDUCEAT) { PyArray_Descr *indtype; indtype = PyArray_DescrFromType(NPY_INTP); if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|OO&O&:reduceat", reduceat_kwlist, &op, &obj_ind, &axes_in, PyArray_DescrConverter2, &otype, PyMicArray_OutputConverter, &out)) { Py_XDECREF(otype); return NULL; } indices = (PyArrayObject *)PyArray_FromAny(obj_ind, indtype, 1, 1, NPY_ARRAY_CARRAY, NULL); if (indices == NULL) { Py_XDECREF(otype); return NULL; } } else if (operation == UFUNC_ACCUMULATE) { PyObject *bad_keepdimarg = NULL; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OO&O&O:accumulate", accumulate_kwlist, &op, &axes_in, PyArray_DescrConverter2, &otype, PyArray_OutputConverter, &out, &bad_keepdimarg)) { Py_XDECREF(otype); return NULL; } /* Until removed outright by https://github.com/numpy/numpy/pull/8187 */ if (bad_keepdimarg != NULL) { if (DEPRECATE_FUTUREWARNING( "keepdims argument has no effect on accumulate, and will be " "removed in future") < 0) { Py_XDECREF(otype); return NULL; } } } else { if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OO&O&i:reduce", reduce_kwlist, &op, &axes_in, PyArray_DescrConverter2, &otype, PyMicArray_OutputConverter, &out, &keepdims)) { Py_XDECREF(otype); return NULL; } } /* Ensure input is an array */ if (!PyMicArray_Check(op)) { PyErr_SetString(PyExc_TypeError, "array must be an MicArray"); Py_XDECREF(otype); return NULL; } Py_INCREF(op); mp = (PyMicArrayObject *)op; ndim = PyMicArray_NDIM(mp); /* Check to see that type (and otype) is not FLEXIBLE */ if (PyMicArray_ISFLEXIBLE(mp) || (otype && PyTypeNum_ISFLEXIBLE(otype->type_num))) { PyErr_Format(PyExc_TypeError, "cannot perform %s with flexible type", _reduce_type[operation]); Py_XDECREF(otype); Py_DECREF(mp); return NULL; } /* Convert the 'axis' parameter into a list of axes */ if (axes_in == NULL) { naxes = 1; axes[0] = 0; } /* Convert 'None' into all the axes */ else if (axes_in == Py_None) { naxes = ndim; for (i = 0; i < naxes; ++i) { axes[i] = i; } } else if (PyTuple_Check(axes_in)) { naxes = PyTuple_Size(axes_in); if (naxes < 0 || naxes > NPY_MAXDIMS) { PyErr_SetString(PyExc_ValueError, "too many values for 'axis'"); Py_XDECREF(otype); Py_DECREF(mp); return NULL; } for (i = 0; i < naxes; ++i) { PyObject *tmp = PyTuple_GET_ITEM(axes_in, i); int axis = PyArray_PyIntAsInt(tmp); if (axis == -1 && PyErr_Occurred()) { Py_XDECREF(otype); Py_DECREF(mp); return NULL; } if (check_and_adjust_axis(&axis, ndim) < 0) { Py_XDECREF(otype); Py_DECREF(mp); return NULL; } axes[i] = (int)axis; } } /* Try to interpret axis as an integer */ else { int axis = PyArray_PyIntAsInt(axes_in); /* TODO: PyNumber_Index would be good to use here */ if (axis == -1 && PyErr_Occurred()) { Py_XDECREF(otype); Py_DECREF(mp); return NULL; } /* Special case letting axis={0 or -1} slip through for scalars */ if (ndim == 0 && (axis == 0 || axis == -1)) { axis = 0; } else if (check_and_adjust_axis(&axis, ndim) < 0) { return NULL; } axes[0] = (int)axis; naxes = 1; } /* Check to see if input is zero-dimensional. */ if (ndim == 0) { /* * A reduction with no axes is still valid but trivial. * As a special case for backwards compatibility in 'sum', * 'prod', et al, also allow a reduction where axis=0, even * though this is technically incorrect. */ naxes = 0; if (!(operation == UFUNC_REDUCE && (naxes == 0 || (naxes == 1 && axes[0] == 0)))) { PyErr_Format(PyExc_TypeError, "cannot %s on a scalar", _reduce_type[operation]); Py_XDECREF(otype); Py_DECREF(mp); return NULL; } } /* * If out is specified it determines otype * unless otype already specified. */ if (otype == NULL && out != NULL) { otype = PyMicArray_DESCR(out); Py_INCREF(otype); } if (otype == NULL) { /* * For integer types --- make sure at least a long * is used for add and multiply reduction to avoid overflow */ int typenum = PyMicArray_TYPE(mp); if ((PyTypeNum_ISBOOL(typenum) || PyTypeNum_ISINTEGER(typenum)) && ((strcmp(ufunc->name,"add") == 0) || (strcmp(ufunc->name,"multiply") == 0))) { if (PyTypeNum_ISBOOL(typenum)) { typenum = NPY_LONG; } else if ((size_t)PyMicArray_DESCR(mp)->elsize < sizeof(long)) { if (PyTypeNum_ISUNSIGNED(typenum)) { typenum = NPY_ULONG; } else { typenum = NPY_LONG; } } } otype = PyArray_DescrFromType(typenum); } switch(operation) { case UFUNC_REDUCE: ret = PyMUFunc_Reduce(ufunc, mp, out, naxes, axes, otype, keepdims); break; case UFUNC_ACCUMULATE: if (naxes != 1) { PyErr_SetString(PyExc_ValueError, "accumulate does not allow multiple axes"); Py_XDECREF(otype); Py_DECREF(mp); return NULL; } ret = PyMUFunc_Accumulate(ufunc, mp, out, axes[0], otype->type_num); break; case UFUNC_REDUCEAT: if (naxes != 1) { PyErr_SetString(PyExc_ValueError, "reduceat does not allow multiple axes"); Py_XDECREF(otype); Py_DECREF(mp); return NULL; } ret = PyMUFunc_Reduceat(ufunc, mp, indices, out, axes[0], otype->type_num); Py_DECREF(indices); break; } Py_DECREF(mp); Py_DECREF(otype); if (ret == NULL) { return NULL; } /* If an output parameter was provided, don't wrap it */ if (out != NULL) { return (PyObject *)ret; } if (Py_TYPE(op) != Py_TYPE(ret)) { res = PyObject_CallMethod(op, "__array_wrap__", "O", ret); if (res == NULL) { PyErr_Clear(); } else if (res == Py_None) { Py_DECREF(res); } else { Py_DECREF(ret); return res; } } return PyMicArray_Return(ret); } /* * Returns an incref'ed pointer to the proper wrapping object for a * ufunc output argument, given the output argument 'out', and the * input's wrapping function, 'wrap'. */ static PyObject* _get_out_wrap(PyObject *out, PyObject *wrap) { PyObject *owrap; if (out == Py_None) { /* Iterator allocated outputs get the input's wrapping */ Py_XINCREF(wrap); return wrap; } if (PyMicArray_CheckExact(out) || PyArray_CheckExact(out)) { /* None signals to not call any wrapping */ Py_RETURN_NONE; } /* * For array subclasses use their __array_wrap__ method, or the * input's wrapping if not available */ owrap = PyObject_GetAttr(out, mpy_um_str_array_wrap); if (owrap == NULL || !PyCallable_Check(owrap)) { Py_XDECREF(owrap); owrap = wrap; Py_XINCREF(wrap); PyErr_Clear(); } return owrap; } /* * This function analyzes the input arguments * and determines an appropriate __array_wrap__ function to call * for the outputs. * * If an output argument is provided, then it is wrapped * with its own __array_wrap__ not with the one determined by * the input arguments. * * if the provided output argument is already an array, * the wrapping function is None (which means no wrapping will * be done --- not even PyArray_Return). * * A NULL is placed in output_wrap for outputs that * should just have PyArray_Return called. */ static void _find_array_wrap(PyObject *args, PyObject *kwds, PyObject **output_wrap, int nin, int nout) { Py_ssize_t nargs; int i, idx_offset, start_idx; int np = 0; PyObject *with_wrap[NPY_MAXARGS], *wraps[NPY_MAXARGS]; PyObject *obj, *wrap = NULL; /* * If a 'subok' parameter is passed and isn't True, don't wrap but put None * into slots with out arguments which means return the out argument */ if (kwds != NULL && (obj = PyDict_GetItem(kwds, mpy_um_str_subok)) != NULL) { if (obj != Py_True) { /* skip search for wrap members */ goto handle_out; } } for (i = 0; i < nin; i++) { obj = PyTuple_GET_ITEM(args, i); if (PyMicArray_CheckExact(obj) || PyArray_CheckExact(obj) || PyArray_IsAnyScalar(obj)) { continue; } wrap = PyObject_GetAttr(obj, mpy_um_str_array_wrap); if (wrap) { if (PyCallable_Check(wrap)) { with_wrap[np] = obj; wraps[np] = wrap; ++np; } else { Py_DECREF(wrap); wrap = NULL; } } else { PyErr_Clear(); } } if (np > 0) { /* If we have some wraps defined, find the one of highest priority */ wrap = wraps[0]; if (np > 1) { double maxpriority = PyArray_GetPriority(with_wrap[0], NPY_PRIORITY); for (i = 1; i < np; ++i) { double priority = PyArray_GetPriority(with_wrap[i], NPY_PRIORITY); if (priority > maxpriority) { maxpriority = priority; Py_DECREF(wrap); wrap = wraps[i]; } else { Py_DECREF(wraps[i]); } } } } /* * Here wrap is the wrapping function determined from the * input arrays (could be NULL). * * For all the output arrays decide what to do. * * 1) Use the wrap function determined from the input arrays * This is the default if the output array is not * passed in. * * 2) Use the __array_wrap__ method of the output object * passed in. -- this is special cased for * exact ndarray so that no PyArray_Return is * done in that case. */ handle_out: nargs = PyTuple_GET_SIZE(args); /* Default is using positional arguments */ obj = args; idx_offset = nin; start_idx = 0; if (nin == nargs && kwds != NULL) { /* There may be a keyword argument we can use instead */ obj = PyDict_GetItem(kwds, mpy_um_str_out); if (obj == NULL) { /* No, go back to positional (even though there aren't any) */ obj = args; } else { idx_offset = 0; if (PyTuple_Check(obj)) { /* If a tuple, must have all nout items */ nargs = nout; } else { /* If the kwarg is not a tuple then it is an array (or None) */ output_wrap[0] = _get_out_wrap(obj, wrap); start_idx = 1; nargs = 1; } } } for (i = start_idx; i < nout; ++i) { int j = idx_offset + i; if (j < nargs) { output_wrap[i] = _get_out_wrap(PyTuple_GET_ITEM(obj, j), wrap); } else { output_wrap[i] = wrap; Py_XINCREF(wrap); } } Py_XDECREF(wrap); return; } static PyObject * mufunc_generic_call(PyUFuncObject *ufunc, PyObject *args, PyObject *kwds) { int i; PyTupleObject *ret; PyMicArrayObject *mps[NPY_MAXARGS]; PyObject *retobj[NPY_MAXARGS]; PyObject *wraparr[NPY_MAXARGS]; PyObject *res; PyObject *override = NULL; int errval; /* * Initialize all array objects to NULL to make cleanup easier * if something goes wrong. */ for (i = 0; i < ufunc->nargs; i++) { mps[i] = NULL; } errval = PyMUFunc_GenericFunction(ufunc, args, kwds, mps); if (errval < 0) { for (i = 0; i < ufunc->nargs; i++) { PyArray_XDECREF_ERR((PyArrayObject *)mps[i]); } if (errval == -1) { return NULL; } else if (ufunc->nin == 2 && ufunc->nout == 1) { /* * For array_richcompare's benefit -- see the long comment in * get_ufunc_arguments. */ Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } else { PyErr_SetString(PyExc_TypeError, "XX can't happen, please report a bug XX"); return NULL; } } /* Free the input references */ for (i = 0; i < ufunc->nin; i++) { Py_XDECREF(mps[i]); } /* * Use __array_wrap__ on all outputs * if present on one of the input arguments. * If present for multiple inputs: * use __array_wrap__ of input object with largest * __array_priority__ (default = 0.0) * * Exception: we should not wrap outputs for items already * passed in as output-arguments. These items should either * be left unwrapped or wrapped by calling their own __array_wrap__ * routine. * * For each output argument, wrap will be either * NULL --- call PyArray_Return() -- default if no output arguments given * None --- array-object passed in don't call PyArray_Return * method --- the __array_wrap__ method to call. */ _find_array_wrap(args, kwds, wraparr, ufunc->nin, ufunc->nout); /* wrap outputs */ for (i = 0; i < ufunc->nout; i++) { int j = ufunc->nin+i; PyObject *wrap = wraparr[i]; if (wrap != NULL) { if (wrap == Py_None) { Py_DECREF(wrap); retobj[i] = (PyObject *)mps[j]; continue; } res = PyObject_CallFunction(wrap, "O(OOi)", mps[j], ufunc, args, i); /* Handle __array_wrap__ that does not accept a context argument */ if (res == NULL && PyErr_ExceptionMatches(PyExc_TypeError)) { PyErr_Clear(); res = PyObject_CallFunctionObjArgs(wrap, mps[j], NULL); } Py_DECREF(wrap); if (res == NULL) { goto fail; } else { Py_DECREF(mps[j]); retobj[i] = res; continue; } } else { /* default behavior */ retobj[i] = PyMicArray_Return(mps[j]); } } if (ufunc->nout == 1) { return retobj[0]; } else { ret = (PyTupleObject *)PyTuple_New(ufunc->nout); for (i = 0; i < ufunc->nout; i++) { PyTuple_SET_ITEM(ret, i, retobj[i]); } return (PyObject *)ret; } fail: for (i = ufunc->nin; i < ufunc->nargs; i++) { Py_XDECREF(mps[i]); } return NULL; } NPY_NO_EXPORT PyObject * ufunc_geterr(PyObject *NPY_UNUSED(dummy), PyObject *args) { PyObject *thedict; PyObject *res; if (!PyArg_ParseTuple(args, "")) { return NULL; } thedict = PyThreadState_GetDict(); if (thedict == NULL) { thedict = PyEval_GetBuiltins(); } res = PyDict_GetItem(thedict, mpy_um_str_pyvals_name); if (res != NULL) { Py_INCREF(res); return res; } /* Construct list of defaults */ res = PyList_New(3); if (res == NULL) { return NULL; } PyList_SET_ITEM(res, 0, PyInt_FromLong(NPY_BUFSIZE)); PyList_SET_ITEM(res, 1, PyInt_FromLong(UFUNC_ERR_DEFAULT)); PyList_SET_ITEM(res, 2, Py_None); Py_INCREF(Py_None); return res; } #if USE_USE_DEFAULTS==1 /* * This is a strategy to buy a little speed up and avoid the dictionary * look-up in the default case. It should work in the presence of * threads. If it is deemed too complicated or it doesn't actually work * it could be taken out. */ static int ufunc_update_use_defaults(void) { PyObject *errobj = NULL; int errmask, bufsize; int res; PyUFunc_NUM_NODEFAULTS += 1; res = PyUFunc_GetPyValues("test", &bufsize, &errmask, &errobj); PyUFunc_NUM_NODEFAULTS -= 1; if (res < 0) { Py_XDECREF(errobj); return -1; } if ((errmask != UFUNC_ERR_DEFAULT) || (bufsize != NPY_BUFSIZE) || (PyTuple_GET_ITEM(errobj, 1) != Py_None)) { PyUFunc_NUM_NODEFAULTS += 1; } else if (PyUFunc_NUM_NODEFAULTS > 0) { PyUFunc_NUM_NODEFAULTS -= 1; } Py_XDECREF(errobj); return 0; } #endif NPY_NO_EXPORT PyObject * ufunc_seterr(PyObject *NPY_UNUSED(dummy), PyObject *args) { PyObject *thedict; int res; PyObject *val; static char *msg = "Error object must be a list of length 3"; if (!PyArg_ParseTuple(args, "O", &val)) { return NULL; } if (!PyList_CheckExact(val) || PyList_GET_SIZE(val) != 3) { PyErr_SetString(PyExc_ValueError, msg); return NULL; } thedict = PyThreadState_GetDict(); if (thedict == NULL) { thedict = PyEval_GetBuiltins(); } res = PyDict_SetItem(thedict, mpy_um_str_pyvals_name, val); if (res < 0) { return NULL; } #if USE_USE_DEFAULTS==1 if (ufunc_update_use_defaults() < 0) { return NULL; } #endif Py_RETURN_NONE; } /*UFUNC_API*/ NPY_NO_EXPORT PyObject * PyMUFunc_FromFuncAndData(PyUFuncGenericFunction *func, void **data, char *types, int ntypes, int nin, int nout, int identity, const char *name, const char *doc, int unused) { return PyMUFunc_FromFuncAndDataAndSignature(func, data, types, ntypes, nin, nout, identity, name, doc, 0, NULL); } /*UFUNC_API*/ NPY_NO_EXPORT PyObject * PyMUFunc_FromFuncAndDataAndSignature(PyUFuncGenericFunction *func, void **data, char *types, int ntypes, int nin, int nout, int identity, const char *name, const char *doc, int unused, const char *signature) { PyUFuncObject *ufunc; ufunc = (PyUFuncObject *) PyUFunc_FromFuncAndDataAndSignature(func, data, types, ntypes, nin, nout, identity, name, doc, unused, signature); if (ufunc != NULL) { /* Modify objec_type to PyMUFunc_Type */ ufunc->ob_type = &PyMUFunc_Type; } return (PyObject *)ufunc; } static int _does_loop_use_arrays(void *data) { return (data == PyUFunc_SetUsesArraysAsData); } /* * This is the first-part of the CObject structure. * * I don't think this will change, but if it should, then * this needs to be fixed. The exposed C-API was insufficient * because I needed to replace the pointer and it wouldn't * let me with a destructor set (even though it works fine * with the destructor). */ typedef struct { PyObject_HEAD void *c_obj; } _simple_cobj; #define _SETCPTR(cobj, val) ((_simple_cobj *)(cobj))->c_obj = (val) /* return 1 if arg1 > arg2, 0 if arg1 == arg2, and -1 if arg1 < arg2 */ static int cmp_arg_types(int *arg1, int *arg2, int n) { for (; n > 0; n--, arg1++, arg2++) { if (PyArray_EquivTypenums(*arg1, *arg2)) { continue; } if (PyArray_CanCastSafely(*arg1, *arg2)) { return -1; } return 1; } return 0; } /* * This frees the linked-list structure when the CObject * is destroyed (removed from the internal dictionary) */ static NPY_INLINE void _free_loop1d_list(PyUFunc_Loop1d *data) { int i; while (data != NULL) { PyUFunc_Loop1d *next = data->next; PyArray_free(data->arg_types); if (data->arg_dtypes != NULL) { for (i = 0; i < data->nargs; i++) { Py_DECREF(data->arg_dtypes[i]); } PyArray_free(data->arg_dtypes); } PyArray_free(data); data = next; } } #if PY_VERSION_HEX >= 0x03000000 static void _loop1d_list_free(PyObject *ptr) { PyUFunc_Loop1d *data = (PyUFunc_Loop1d *)PyCapsule_GetPointer(ptr, NULL); _free_loop1d_list(data); } #else static void _loop1d_list_free(void *ptr) { PyUFunc_Loop1d *data = (PyUFunc_Loop1d *)ptr; _free_loop1d_list(data); } #endif #undef _SETCPTR static void mufunc_dealloc(PyUFuncObject *ufunc) { PyArray_free(ufunc->core_num_dims); PyArray_free(ufunc->core_dim_ixs); PyArray_free(ufunc->core_offsets); PyArray_free(ufunc->core_signature); PyArray_free(ufunc->ptr); PyArray_free(ufunc->op_flags); Py_XDECREF(ufunc->userloops); Py_XDECREF(ufunc->obj); PyArray_free(ufunc); } static PyObject * mufunc_repr(PyUFuncObject *ufunc) { return PyUString_FromFormat("<mufunc '%s'>", ufunc->name); } /****************************************************************************** *** UFUNC METHODS *** *****************************************************************************/ /* * op.outer(a,b) is equivalent to op(a[:,NewAxis,NewAxis,etc.],b) * where a has b.ndim NewAxis terms appended. * * The result has dimensions a.ndim + b.ndim */ static PyObject * mufunc_outer(PyUFuncObject *ufunc, PyObject *args, PyObject *kwds) { //TODO int i; int errval; PyObject *override = NULL; PyObject *ret; PyArrayObject *ap1 = NULL, *ap2 = NULL, *ap_new = NULL; PyObject *new_args, *tmp; PyObject *shape1, *shape2, *newshape; if (ufunc->core_enabled) { PyErr_Format(PyExc_TypeError, "method outer is not allowed in ufunc with non-trivial"\ " signature"); return NULL; } if (ufunc->nin != 2) { PyErr_SetString(PyExc_ValueError, "outer product only supported "\ "for binary functions"); return NULL; } if (PySequence_Length(args) != 2) { PyErr_SetString(PyExc_TypeError, "exactly two arguments expected"); return NULL; } tmp = PySequence_GetItem(args, 0); if (tmp == NULL) { return NULL; } ap1 = (PyArrayObject *) PyArray_FromObject(tmp, NPY_NOTYPE, 0, 0); Py_DECREF(tmp); if (ap1 == NULL) { return NULL; } tmp = PySequence_GetItem(args, 1); if (tmp == NULL) { return NULL; } ap2 = (PyArrayObject *)PyArray_FromObject(tmp, NPY_NOTYPE, 0, 0); Py_DECREF(tmp); if (ap2 == NULL) { Py_DECREF(ap1); return NULL; } /* Construct new shape tuple */ shape1 = PyTuple_New(PyArray_NDIM(ap1)); if (shape1 == NULL) { goto fail; } for (i = 0; i < PyArray_NDIM(ap1); i++) { PyTuple_SET_ITEM(shape1, i, PyLong_FromLongLong((npy_longlong)PyArray_DIMS(ap1)[i])); } shape2 = PyTuple_New(PyArray_NDIM(ap2)); for (i = 0; i < PyArray_NDIM(ap2); i++) { PyTuple_SET_ITEM(shape2, i, PyInt_FromLong((long) 1)); } if (shape2 == NULL) { Py_DECREF(shape1); goto fail; } newshape = PyNumber_Add(shape1, shape2); Py_DECREF(shape1); Py_DECREF(shape2); if (newshape == NULL) { goto fail; } ap_new = (PyArrayObject *)PyArray_Reshape(ap1, newshape); Py_DECREF(newshape); if (ap_new == NULL) { goto fail; } new_args = Py_BuildValue("(OO)", ap_new, ap2); Py_DECREF(ap1); Py_DECREF(ap2); Py_DECREF(ap_new); ret = mufunc_generic_call(ufunc, new_args, kwds); Py_DECREF(new_args); return ret; fail: Py_XDECREF(ap1); Py_XDECREF(ap2); Py_XDECREF(ap_new); return NULL; } static PyObject * mufunc_reduce(PyUFuncObject *ufunc, PyObject *args, PyObject *kwds) { int errval; PyObject *override = NULL; /* `nin`, the last arg, is unused. So we put 0. */ return PyMUFunc_GenericReduction(ufunc, args, kwds, UFUNC_REDUCE); } static PyObject * mufunc_accumulate(PyUFuncObject *ufunc, PyObject *args, PyObject *kwds) { int errval; PyObject *override = NULL; return PyMUFunc_GenericReduction(ufunc, args, kwds, UFUNC_ACCUMULATE); } static PyObject * mufunc_reduceat(PyUFuncObject *ufunc, PyObject *args, PyObject *kwds) { int errval; PyObject *override = NULL; return PyMUFunc_GenericReduction(ufunc, args, kwds, UFUNC_REDUCEAT); } /* Helper for ufunc_at, below */ static NPY_INLINE PyMicArrayObject * new_array_op(PyMicArrayObject *op_array, char *data) { npy_intp dims[1] = {1}; /* TODO: get default device */ PyObject *r = PyMicArray_NewFromDescr(-1, &PyMicArray_Type, PyMicArray_DESCR(op_array), 1, dims, NULL, data, NPY_ARRAY_WRITEABLE, NULL); return (PyMicArrayObject *)r; } /* * Call ufunc only on selected array items and store result in first operand. * For add ufunc, method call is equivalent to op1[idx] += op2 with no * buffering of the first operand. * Arguments: * op1 - First operand to ufunc * idx - Indices that are applied to first operand. Equivalent to op1[idx]. * op2 - Second operand to ufunc (if needed). Must be able to broadcast * over first operand. */ static PyObject * mufunc_at(PyUFuncObject *ufunc, PyObject *args) { //TODO return NULL; } //static: mic undefined symbol error if we set static here NPY_NO_EXPORT struct PyMethodDef mufunc_methods[] = { {"reduce", (PyCFunction)mufunc_reduce, METH_VARARGS | METH_KEYWORDS, NULL }, /*{"accumulate", (PyCFunction)mufunc_accumulate, METH_VARARGS | METH_KEYWORDS, NULL }, {"reduceat", (PyCFunction)mufunc_reduceat, METH_VARARGS | METH_KEYWORDS, NULL }, {"outer", (PyCFunction)mufunc_outer, METH_VARARGS | METH_KEYWORDS, NULL}, {"at", (PyCFunction)mufunc_at, METH_VARARGS, NULL},*/ {NULL, NULL, 0, NULL} /* sentinel */ }; /****************************************************************************** *** UFUNC GETSET *** *****************************************************************************/ /* construct the string y1,y2,...,yn */ static PyObject * _makeargs(int num, char *ltr, int null_if_none) { PyObject *str; int i; switch (num) { case 0: if (null_if_none) { return NULL; } return PyString_FromString(""); case 1: return PyString_FromString(ltr); } str = PyString_FromFormat("%s1, %s2", ltr, ltr); for (i = 3; i <= num; ++i) { PyString_ConcatAndDel(&str, PyString_FromFormat(", %s%d", ltr, i)); } return str; } static char _typecharfromnum(int num) { PyArray_Descr *descr; char ret; descr = PyArray_DescrFromType(num); ret = descr->type; Py_DECREF(descr); return ret; } static PyObject * ufunc_get_doc(PyUFuncObject *ufunc) { /* * Put docstring first or FindMethod finds it... could so some * introspection on name and nin + nout to automate the first part * of it the doc string shouldn't need the calling convention * construct name(x1, x2, ...,[ out1, out2, ...]) __doc__ */ PyObject *outargs, *inargs, *doc; outargs = _makeargs(ufunc->nout, "out", 1); inargs = _makeargs(ufunc->nin, "x", 0); if (ufunc->doc == NULL) { if (outargs == NULL) { doc = PyUString_FromFormat("%s(%s)\n\n", ufunc->name, PyString_AS_STRING(inargs)); } else { doc = PyUString_FromFormat("%s(%s[, %s])\n\n", ufunc->name, PyString_AS_STRING(inargs), PyString_AS_STRING(outargs)); Py_DECREF(outargs); } } else { if (outargs == NULL) { doc = PyUString_FromFormat("%s(%s)\n\n%s", ufunc->name, PyString_AS_STRING(inargs), ufunc->doc); } else { doc = PyUString_FromFormat("%s(%s[, %s])\n\n%s", ufunc->name, PyString_AS_STRING(inargs), PyString_AS_STRING(outargs), ufunc->doc); Py_DECREF(outargs); } } Py_DECREF(inargs); return doc; } static PyObject * ufunc_get_nin(PyUFuncObject *ufunc) { return PyInt_FromLong(ufunc->nin); } static PyObject * ufunc_get_nout(PyUFuncObject *ufunc) { return PyInt_FromLong(ufunc->nout); } static PyObject * ufunc_get_nargs(PyUFuncObject *ufunc) { return PyInt_FromLong(ufunc->nin + ufunc->nout); } static PyObject * ufunc_get_ntypes(PyUFuncObject *ufunc) { return PyInt_FromLong(ufunc->ntypes); } static PyObject * ufunc_get_types(PyUFuncObject *ufunc) { /* return a list with types grouped input->output */ PyObject *list; PyObject *str; int k, j, n, nt = ufunc->ntypes; int ni = ufunc->nin; int no = ufunc->nout; char *t; list = PyList_New(nt); if (list == NULL) { return NULL; } t = PyArray_malloc(no+ni+2); n = 0; for (k = 0; k < nt; k++) { for (j = 0; j<ni; j++) { t[j] = _typecharfromnum(ufunc->types[n]); n++; } t[ni] = '-'; t[ni+1] = '>'; for (j = 0; j < no; j++) { t[ni + 2 + j] = _typecharfromnum(ufunc->types[n]); n++; } str = PyUString_FromStringAndSize(t, no + ni + 2); PyList_SET_ITEM(list, k, str); } PyArray_free(t); return list; } static PyObject * ufunc_get_name(PyUFuncObject *ufunc) { return PyUString_FromString(ufunc->name); } static PyObject * ufunc_get_identity(PyUFuncObject *ufunc) { switch(ufunc->identity) { case PyUFunc_One: return PyInt_FromLong(1); case PyUFunc_Zero: return PyInt_FromLong(0); case PyUFunc_MinusOne: return PyInt_FromLong(-1); } Py_RETURN_NONE; } static PyObject * ufunc_get_signature(PyUFuncObject *ufunc) { if (!ufunc->core_enabled) { Py_RETURN_NONE; } return PyUString_FromString(ufunc->core_signature); } #undef _typecharfromnum /* * Docstring is now set from python * static char *Ufunctype__doc__ = NULL; */ //static: mic undefined symbol if we set static here NPY_NO_EXPORT PyGetSetDef mufunc_getset[] = { {"__doc__", (getter)ufunc_get_doc, NULL, NULL, NULL}, {"nin", (getter)ufunc_get_nin, NULL, NULL, NULL}, {"nout", (getter)ufunc_get_nout, NULL, NULL, NULL}, {"nargs", (getter)ufunc_get_nargs, NULL, NULL, NULL}, {"ntypes", (getter)ufunc_get_ntypes, NULL, NULL, NULL}, {"types", (getter)ufunc_get_types, NULL, NULL, NULL}, {"__name__", (getter)ufunc_get_name, NULL, NULL, NULL}, {"identity", (getter)ufunc_get_identity, NULL, NULL, NULL}, {"signature", (getter)ufunc_get_signature, NULL, NULL, NULL}, {NULL, NULL, NULL, NULL, NULL}, /* Sentinel */ }; /****************************************************************************** *** UFUNC TYPE OBJECT *** *****************************************************************************/ NPY_NO_EXPORT PyTypeObject PyMUFunc_Type = { #if defined(NPY_PY3K) PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif "micpy.mufunc", /* tp_name */ sizeof(PyUFuncObject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)mufunc_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ #if defined(NPY_PY3K) 0, /* tp_reserved */ #else 0, /* tp_compare */ #endif (reprfunc)mufunc_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ (ternaryfunc)mufunc_generic_call, /* tp_call */ (reprfunc)mufunc_repr, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ mufunc_methods, /* tp_methods */ 0, /* tp_members */ mufunc_getset, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ 0, /* tp_del */ 0, /* tp_version_tag */ }; /* End of code for ufunc objects */
omp_init_lock.c
// RUN: %libomp-compile-and-run // REQUIRES: dummy #include "omp_testsuite.h" #include <stdio.h> // This should be slightly less than KMP_I_LOCK_CHUNK, which is 1024 #define LOCKS_PER_ITER 1000 #define ITERATIONS (REPETITIONS + 1) // This tests concurrently using locks on one thread while initializing new // ones on another thread. This exercises the global lock pool. int test_omp_init_lock() { int i; omp_lock_t lcks[ITERATIONS * LOCKS_PER_ITER]; #pragma omp parallel for schedule(static) num_threads(NUM_TASKS) for (i = 0; i < ITERATIONS; i++) { int j; omp_lock_t *my_lcks = &lcks[i * LOCKS_PER_ITER]; for (j = 0; j < LOCKS_PER_ITER; j++) { omp_init_lock(&my_lcks[j]); } for (j = 0; j < LOCKS_PER_ITER * 100; j++) { omp_set_lock(&my_lcks[j % LOCKS_PER_ITER]); omp_unset_lock(&my_lcks[j % LOCKS_PER_ITER]); } } // Wait until all repititions are done. The test is exercising growth of // the global lock pool, which does not shrink when no locks are allocated. { int j; for (j = 0; j < ITERATIONS * LOCKS_PER_ITER; j++) { omp_destroy_lock(&lcks[j]); } } return 0; } int main() { // No use repeating this test, since it's exercising a private global pool // which is not reset between test iterations. return test_omp_init_lock(); }
mixed_tentusscher_myo_epi_2004_S2_20.c
// Scenario 2 - Mixed-Model TenTusscher 2004 (Myocardium + Epicardium) // (AP + max:dvdt) #include <stdio.h> #include "mixed_tentusscher_myo_epi_2004_S2_20.h" GET_CELL_MODEL_DATA(init_cell_model_data) { if(get_initial_v) cell_model->initial_v = INITIAL_V; if(get_neq) cell_model->number_of_ode_equations = NEQ; } SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu) { static bool first_call = true; if(first_call) { print_to_stdout_and_file("Using mixed version of TenTusscher 2004 myocardium + epicardium CPU model\n"); first_call = false; } // Get the mapping array uint32_t *mapping = NULL; if(extra_data) { mapping = (uint32_t*)extra_data; } else { print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n"); } // Initial conditions for TenTusscher myocardium if (mapping[sv_id] == 0) { // Default initial conditions /* sv[0] = INITIAL_V; // V; millivolt sv[1] = 0.f; //M sv[2] = 0.75; //H sv[3] = 0.75f; //J sv[4] = 0.f; //Xr1 sv[5] = 1.f; //Xr2 sv[6] = 0.f; //Xs sv[7] = 1.f; //S sv[8] = 0.f; //R sv[9] = 0.f; //D sv[10] = 1.f; //F sv[11] = 1.f; //FCa sv[12] = 1.f; //G sv[13] = 0.0002; //Cai sv[14] = 0.2f; //CaSR sv[15] = 11.6f; //Nai sv[16] = 138.3f; //Ki */ // Elnaz's steady-state initial conditions real sv_sst[]={-86.3965119057144,0.00133824305081220,0.775463576993407,0.775278393595599,0.000179499343643571,0.483303039835057,0.00297647859235379,0.999998290403642,1.98961879737287e-08,1.93486789479597e-05,0.999599147019885,1.00646342475688,0.999975178010127,5.97703651642618e-05,0.418325344820368,10.7429775420171,138.918155900633}; for (uint32_t i = 0; i < NEQ; i++) sv[i] = sv_sst[i]; } // Initial conditions for TenTusscher epicardium else { // Default initial conditions /* sv[0] = INITIAL_V; // V; millivolt sv[1] = 0.f; //M sv[2] = 0.75; //H sv[3] = 0.75f; //J sv[4] = 0.f; //Xr1 sv[5] = 1.f; //Xr2 sv[6] = 0.f; //Xs sv[7] = 1.f; //S sv[8] = 0.f; //R sv[9] = 0.f; //D sv[10] = 1.f; //F sv[11] = 1.f; //FCa sv[12] = 1.f; //G sv[13] = 0.0002; //Cai sv[14] = 0.2f; //CaSR sv[15] = 11.6f; //Nai sv[16] = 138.3f; //Ki */ // Elnaz's steady-state initial conditions real sv_sst[]={-86.5626314873864,0.00129162059588251,0.779565841868151,0.779314339768234,0.000174937390688145,0.485031353960147,0.00294149195344193,0.999998346418836,1.93534486766886e-08,1.89248872699741e-05,0.999775353607234,1.00753388054703,0.999999038303684,3.47610047822055e-05,1.00562825829621,9.46957015137721,139.869479747257}; for (uint32_t i = 0; i < NEQ; i++) sv[i] = sv_sst[i]; } } SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu) { // Get the mapping array uint32_t *mapping = NULL; if(extra_data) { mapping = (uint32_t*)extra_data; } else { print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n"); } uint32_t sv_id; int i; #pragma omp parallel for private(sv_id) for (i = 0; i < num_cells_to_solve; i++) { if(cells_to_solve) sv_id = cells_to_solve[i]; else sv_id = (uint32_t )i; for (int j = 0; j < num_steps; ++j) { if (mapping[i] == 0) solve_model_ode_cpu_myo(dt, sv + (sv_id * NEQ), stim_currents[i]); else solve_model_ode_cpu_epi(dt, sv + (sv_id * NEQ), stim_currents[i]); } } } void solve_model_ode_cpu_myo (real dt, real *sv, real stim_current) { real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu_myo(rY, rDY, stim_current, dt); for(int i = 0; i < NEQ; i++) sv[i] = rDY[i]; } void RHS_cpu_myo(const real *sv, real *rDY_, real stim_current, real dt) { // State variables real svolt = sv[0]; real sm = sv[1]; real sh = sv[2]; real sj = sv[3]; real sxr1 = sv[4]; real sxr2 = sv[5]; real sxs = sv[6]; real ss = sv[7]; real sr = sv[8]; real sd = sv[9]; real sf = sv[10]; real sfca = sv[11]; real sg = sv[12]; real Cai = sv[13]; real CaSR = sv[14]; real Nai = sv[15]; real Ki = sv[16]; //External concentrations real Ko=5.4; real Cao=2.0; real Nao=140.0; //Intracellular volumes real Vc=0.016404; real Vsr=0.001094; //Calcium dynamics real Bufc=0.15f; real Kbufc=0.001f; real Bufsr=10.f; real Kbufsr=0.3f; real taufca=2.f; real taug=2.f; real Vmaxup=0.000425f; real Kup=0.00025f; //Constants const real R = 8314.472f; const real F = 96485.3415f; const real T =310.0f; real RTONF =(R*T)/F; //Cellular capacitance real CAPACITANCE=0.185; //Parameters for currents //Parameters for IKr real Gkr=0.096; //Parameters for Iks real pKNa=0.03; // [!] Myocardium cell real Gks=0.062; //Parameters for Ik1 real GK1=5.405; //Parameters for Ito // [!] Myocardium cell real Gto=0.294; //Parameters for INa real GNa=14.838; //Parameters for IbNa real GbNa=0.00029; //Parameters for INaK real KmK=1.0; real KmNa=40.0; real knak=1.362; //Parameters for ICaL real GCaL=0.000175; //Parameters for IbCa real GbCa=0.000592; //Parameters for INaCa real knaca=1000; real KmNai=87.5; real KmCa=1.38; real ksat=0.1; real n=0.35; //Parameters for IpCa real GpCa=0.825; real KpCa=0.0005; //Parameters for IpK; real GpK=0.0146; real IKr; real IKs; real IK1; real Ito; real INa; real IbNa; real ICaL; real IbCa; real INaCa; real IpCa; real IpK; real INaK; real Irel; real Ileak; real dNai; real dKi; real dCai; real dCaSR; real A; // real BufferFactorc; // real BufferFactorsr; real SERCA; real Caisquare; real CaSRsquare; real CaCurrent; real CaSRCurrent; real fcaold; real gold; real Ek; real Ena; real Eks; real Eca; real CaCSQN; real bjsr; real cjsr; real CaBuf; real bc; real cc; real Ak1; real Bk1; real rec_iK1; real rec_ipK; real rec_iNaK; real AM; real BM; real AH_1; real BH_1; real AH_2; real BH_2; real AJ_1; real BJ_1; real AJ_2; real BJ_2; real M_INF; real H_INF; real J_INF; real TAU_M; real TAU_H; real TAU_J; real axr1; real bxr1; real axr2; real bxr2; real Xr1_INF; real Xr2_INF; real TAU_Xr1; real TAU_Xr2; real Axs; real Bxs; real Xs_INF; real TAU_Xs; real R_INF; real TAU_R; real S_INF; real TAU_S; real Ad; real Bd; real Cd; real TAU_D; real D_INF; real TAU_F; real F_INF; real FCa_INF; real G_INF; real inverseVcF2=1/(2*Vc*F); real inverseVcF=1./(Vc*F); real Kupsquare=Kup*Kup; // real BufcKbufc=Bufc*Kbufc; // real Kbufcsquare=Kbufc*Kbufc; // real Kbufc2=2*Kbufc; // real BufsrKbufsr=Bufsr*Kbufsr; // const real Kbufsrsquare=Kbufsr*Kbufsr; // const real Kbufsr2=2*Kbufsr; const real exptaufca=exp(-dt/taufca); const real exptaug=exp(-dt/taug); real sItot; //Needed to compute currents Ek=RTONF*(log((Ko/Ki))); Ena=RTONF*(log((Nao/Nai))); Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai))); Eca=0.5*RTONF*(log((Cao/Cai))); Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200))); Bk1=(3.*exp(0.0002*(svolt-Ek+100))+ exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek))); rec_iK1=Ak1/(Ak1+Bk1); rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T)))); rec_ipK=1./(1.+exp((25-svolt)/5.98)); //Compute currents INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena); ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))* (exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.); Ito=Gto*sr*ss*(svolt-Ek); IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek); IKs=Gks*sxs*sxs*(svolt-Eks); IK1=GK1*rec_iK1*(svolt-Ek); INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))* (1./(1+ksat*exp((n-1)*svolt*F/(R*T))))* (exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao- exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5); INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK; IpCa=GpCa*Cai/(KpCa+Cai); IpK=GpK*rec_ipK*(svolt-Ek); IbNa=GbNa*(svolt-Ena); IbCa=GbCa*(svolt-Eca); //Determine total current (sItot) = IKr + IKs + IK1 + Ito + INa + IbNa + ICaL + IbCa + INaK + INaCa + IpCa + IpK + stim_current; //update concentrations Caisquare=Cai*Cai; CaSRsquare=CaSR*CaSR; CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE; A=0.016464f*CaSRsquare/(0.0625f+CaSRsquare)+0.008232f; Irel=A*sd*sg; Ileak=0.00008f*(CaSR-Cai); SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare)); CaSRCurrent=SERCA-Irel-Ileak; CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr); dCaSR=dt*(Vc/Vsr)*CaSRCurrent; bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr; cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR); CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.; CaBuf=Bufc*Cai/(Cai+Kbufc); dCai=dt*(CaCurrent-CaSRCurrent); bc=Bufc-CaBuf-dCai-Cai+Kbufc; cc=Kbufc*(CaBuf+dCai+Cai); Cai=(sqrt(bc*bc+4*cc)-bc)/2; dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE; Nai+=dt*dNai; dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE; Ki+=dt*dKi; //compute steady state values and time constants AM=1./(1.+exp((-60.-svolt)/5.)); BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.)); TAU_M=AM*BM; M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03))); if (svolt>=-40.) { AH_1=0.; BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1)))); TAU_H= 1.0/(AH_1+BH_1); } else { AH_2=(0.057*exp(-(svolt+80.)/6.8)); BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt)); TAU_H=1.0/(AH_2+BH_2); } H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43))); if(svolt>=-40.) { AJ_1=0.; BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.)))); TAU_J= 1.0/(AJ_1+BJ_1); } else { AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)* exp(-0.04391*svolt))*(svolt+37.78)/ (1.+exp(0.311*(svolt+79.23)))); BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14)))); TAU_J= 1.0/(AJ_2+BJ_2); } J_INF=H_INF; Xr1_INF=1./(1.+exp((-26.-svolt)/7.)); axr1=450./(1.+exp((-45.-svolt)/10.)); bxr1=6./(1.+exp((svolt-(-30.))/11.5)); TAU_Xr1=axr1*bxr1; Xr2_INF=1./(1.+exp((svolt-(-88.))/24.)); axr2=3./(1.+exp((-60.-svolt)/20.)); bxr2=1.12/(1.+exp((svolt-60.)/20.)); TAU_Xr2=axr2*bxr2; Xs_INF=1./(1.+exp((-5.-svolt)/14.)); Axs=1100./(sqrt(1.+exp((-10.-svolt)/6))); Bxs=1./(1.+exp((svolt-60.)/20.)); TAU_Xs=Axs*Bxs; // [!] Myocardium cell R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; D_INF=1./(1.+exp((-5-svolt)/7.5)); Ad=1.4/(1.+exp((-35-svolt)/13))+0.25; Bd=1.4/(1.+exp((svolt+5)/5)); Cd=1./(1.+exp((50-svolt)/20)); TAU_D=Ad*Bd+Cd; F_INF=1./(1.+exp((svolt+20)/7)); //TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10)); TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML FCa_INF=(1./(1.+pow((Cai/0.000325),8))+ 0.1/(1.+exp((Cai-0.0005)/0.0001))+ 0.20/(1.+exp((Cai-0.00075)/0.0008))+ 0.23 )/1.46; if(Cai<0.00035) G_INF=1./(1.+pow((Cai/0.00035),6)); else G_INF=1./(1.+pow((Cai/0.00035),16)); //Update gates rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M); rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H); rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J); rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1); rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2); rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs); rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S); rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R); rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D); rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F); fcaold= sfca; sfca = FCa_INF-(FCa_INF-sfca)*exptaufca; if(sfca>fcaold && (svolt)>-37.0) sfca = fcaold; gold = sg; sg = G_INF-(G_INF-sg)*exptaug; if(sg>gold && (svolt)>-37.0) sg=gold; //update voltage rDY_[0] = svolt + dt*(-sItot); rDY_[11] = sfca; rDY_[12] = sg; rDY_[13] = Cai; rDY_[14] = CaSR; rDY_[15] = Nai; rDY_[16] = Ki; } void solve_model_ode_cpu_epi (real dt, real *sv, real stim_current) { real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu_epi(rY, rDY, stim_current, dt); for(int i = 0; i < NEQ; i++) sv[i] = rDY[i]; } void RHS_cpu_epi(const real *sv, real *rDY_, real stim_current, real dt) { // State variables real svolt = sv[0]; real sm = sv[1]; real sh = sv[2]; real sj = sv[3]; real sxr1 = sv[4]; real sxr2 = sv[5]; real sxs = sv[6]; real ss = sv[7]; real sr = sv[8]; real sd = sv[9]; real sf = sv[10]; real sfca = sv[11]; real sg = sv[12]; real Cai = sv[13]; real CaSR = sv[14]; real Nai = sv[15]; real Ki = sv[16]; //External concentrations real Ko=5.4; real Cao=2.0; real Nao=140.0; //Intracellular volumes real Vc=0.016404; real Vsr=0.001094; //Calcium dynamics real Bufc=0.15f; real Kbufc=0.001f; real Bufsr=10.f; real Kbufsr=0.3f; real taufca=2.f; real taug=2.f; real Vmaxup=0.000425f; real Kup=0.00025f; //Constants const real R = 8314.472f; const real F = 96485.3415f; const real T =310.0f; real RTONF =(R*T)/F; //Cellular capacitance real CAPACITANCE=0.185; //Parameters for currents //Parameters for IKr real Gkr=0.096; //Parameters for Iks real pKNa=0.03; // [!] Epicardium cell real Gks=0.245; //Parameters for Ik1 real GK1=5.405; //Parameters for Ito // [!] Epicardium cell real Gto=0.294; //Parameters for INa real GNa=14.838; //Parameters for IbNa real GbNa=0.00029; //Parameters for INaK real KmK=1.0; real KmNa=40.0; real knak=1.362; //Parameters for ICaL real GCaL=0.000175; //Parameters for IbCa real GbCa=0.000592; //Parameters for INaCa real knaca=1000; real KmNai=87.5; real KmCa=1.38; real ksat=0.1; real n=0.35; //Parameters for IpCa real GpCa=0.825; real KpCa=0.0005; //Parameters for IpK; real GpK=0.0146; real parameters []={13.9266422007604,0.000306211763267299,0.000130134845221041,0.000571745609978391,0.247335217693447,0.185194358577401,0.103790172036162,3.70853519439188,0.0133585353452839,2.20377995116952,1098.12344962390,0.000446735827598516,0.252881711351026,0.0117635663866967,0.00515418083406778,9.05330255534724e-06}; GNa=parameters[0]; GbNa=parameters[1]; GCaL=parameters[2]; GbCa=parameters[3]; Gto=parameters[4]; Gkr=parameters[5]; Gks=parameters[6]; GK1=parameters[7]; GpK=parameters[8]; knak=parameters[9]; knaca=parameters[10]; Vmaxup=parameters[11]; GpCa=parameters[12]; real arel=parameters[13]; real crel=parameters[14]; real Vleak=parameters[15]; real IKr; real IKs; real IK1; real Ito; real INa; real IbNa; real ICaL; real IbCa; real INaCa; real IpCa; real IpK; real INaK; real Irel; real Ileak; real dNai; real dKi; real dCai; real dCaSR; real A; // real BufferFactorc; // real BufferFactorsr; real SERCA; real Caisquare; real CaSRsquare; real CaCurrent; real CaSRCurrent; real fcaold; real gold; real Ek; real Ena; real Eks; real Eca; real CaCSQN; real bjsr; real cjsr; real CaBuf; real bc; real cc; real Ak1; real Bk1; real rec_iK1; real rec_ipK; real rec_iNaK; real AM; real BM; real AH_1; real BH_1; real AH_2; real BH_2; real AJ_1; real BJ_1; real AJ_2; real BJ_2; real M_INF; real H_INF; real J_INF; real TAU_M; real TAU_H; real TAU_J; real axr1; real bxr1; real axr2; real bxr2; real Xr1_INF; real Xr2_INF; real TAU_Xr1; real TAU_Xr2; real Axs; real Bxs; real Xs_INF; real TAU_Xs; real R_INF; real TAU_R; real S_INF; real TAU_S; real Ad; real Bd; real Cd; real TAU_D; real D_INF; real TAU_F; real F_INF; real FCa_INF; real G_INF; real inverseVcF2=1/(2*Vc*F); real inverseVcF=1./(Vc*F); real Kupsquare=Kup*Kup; // real BufcKbufc=Bufc*Kbufc; // real Kbufcsquare=Kbufc*Kbufc; // real Kbufc2=2*Kbufc; // real BufsrKbufsr=Bufsr*Kbufsr; // const real Kbufsrsquare=Kbufsr*Kbufsr; // const real Kbufsr2=2*Kbufsr; const real exptaufca=exp(-dt/taufca); const real exptaug=exp(-dt/taug); real sItot; //Needed to compute currents Ek=RTONF*(log((Ko/Ki))); Ena=RTONF*(log((Nao/Nai))); Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai))); Eca=0.5*RTONF*(log((Cao/Cai))); Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200))); Bk1=(3.*exp(0.0002*(svolt-Ek+100))+ exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek))); rec_iK1=Ak1/(Ak1+Bk1); rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T)))); rec_ipK=1./(1.+exp((25-svolt)/5.98)); //Compute currents INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena); ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))* (exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.); Ito=Gto*sr*ss*(svolt-Ek); IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek); IKs=Gks*sxs*sxs*(svolt-Eks); IK1=GK1*rec_iK1*(svolt-Ek); INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))* (1./(1+ksat*exp((n-1)*svolt*F/(R*T))))* (exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao- exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5); INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK; IpCa=GpCa*Cai/(KpCa+Cai); IpK=GpK*rec_ipK*(svolt-Ek); IbNa=GbNa*(svolt-Ena); IbCa=GbCa*(svolt-Eca); //Determine total current (sItot) = IKr + IKs + IK1 + Ito + INa + IbNa + ICaL + IbCa + INaK + INaCa + IpCa + IpK + stim_current; //update concentrations Caisquare=Cai*Cai; CaSRsquare=CaSR*CaSR; CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE; A=arel*CaSRsquare/(0.0625f+CaSRsquare)+crel; Irel=A*sd*sg; Ileak=Vleak*(CaSR-Cai); SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare)); CaSRCurrent=SERCA-Irel-Ileak; CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr); dCaSR=dt*(Vc/Vsr)*CaSRCurrent; bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr; cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR); CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.; CaBuf=Bufc*Cai/(Cai+Kbufc); dCai=dt*(CaCurrent-CaSRCurrent); bc=Bufc-CaBuf-dCai-Cai+Kbufc; cc=Kbufc*(CaBuf+dCai+Cai); Cai=(sqrt(bc*bc+4*cc)-bc)/2; dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE; Nai+=dt*dNai; dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE; Ki+=dt*dKi; //compute steady state values and time constants AM=1./(1.+exp((-60.-svolt)/5.)); BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.)); TAU_M=AM*BM; M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03))); if (svolt>=-40.) { AH_1=0.; BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1)))); TAU_H= 1.0/(AH_1+BH_1); } else { AH_2=(0.057*exp(-(svolt+80.)/6.8)); BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt)); TAU_H=1.0/(AH_2+BH_2); } H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43))); if(svolt>=-40.) { AJ_1=0.; BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.)))); TAU_J= 1.0/(AJ_1+BJ_1); } else { AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)* exp(-0.04391*svolt))*(svolt+37.78)/ (1.+exp(0.311*(svolt+79.23)))); BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14)))); TAU_J= 1.0/(AJ_2+BJ_2); } J_INF=H_INF; Xr1_INF=1./(1.+exp((-26.-svolt)/7.)); axr1=450./(1.+exp((-45.-svolt)/10.)); bxr1=6./(1.+exp((svolt-(-30.))/11.5)); TAU_Xr1=axr1*bxr1; Xr2_INF=1./(1.+exp((svolt-(-88.))/24.)); axr2=3./(1.+exp((-60.-svolt)/20.)); bxr2=1.12/(1.+exp((svolt-60.)/20.)); TAU_Xr2=axr2*bxr2; Xs_INF=1./(1.+exp((-5.-svolt)/14.)); Axs=1100./(sqrt(1.+exp((-10.-svolt)/6))); Bxs=1./(1.+exp((svolt-60.)/20.)); TAU_Xs=Axs*Bxs; R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; D_INF=1./(1.+exp((-5-svolt)/7.5)); Ad=1.4/(1.+exp((-35-svolt)/13))+0.25; Bd=1.4/(1.+exp((svolt+5)/5)); Cd=1./(1.+exp((50-svolt)/20)); TAU_D=Ad*Bd+Cd; F_INF=1./(1.+exp((svolt+20)/7)); //TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10)); TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML FCa_INF=(1./(1.+pow((Cai/0.000325),8))+ 0.1/(1.+exp((Cai-0.0005)/0.0001))+ 0.20/(1.+exp((Cai-0.00075)/0.0008))+ 0.23 )/1.46; if(Cai<0.00035) G_INF=1./(1.+pow((Cai/0.00035),6)); else G_INF=1./(1.+pow((Cai/0.00035),16)); //Update gates rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M); rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H); rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J); rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1); rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2); rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs); rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S); rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R); rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D); rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F); fcaold= sfca; sfca = FCa_INF-(FCa_INF-sfca)*exptaufca; if(sfca>fcaold && (svolt)>-37.0) sfca = fcaold; gold = sg; sg = G_INF-(G_INF-sg)*exptaug; if(sg>gold && (svolt)>-37.0) sg=gold; //update voltage rDY_[0] = svolt + dt*(-sItot); rDY_[11] = sfca; rDY_[12] = sg; rDY_[13] = Cai; rDY_[14] = CaSR; rDY_[15] = Nai; rDY_[16] = Ki; }
test.c
/* * Copyright (c) 2009, 2010, 2011, ETH Zurich. * All rights reserved. * * This file is distributed under the terms in the attached LICENSE file. * If you do not find this file, copies can be found by writing to: * ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group. */ #include <assert.h> #include <stdbool.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <assert.h> #include <stdint.h> #include <omp.h> #include <barrelfish/barrelfish.h> #include <bench/bench.h> #include <trace/trace.h> #include <trace_definitions/trace_defs.h> #include <inttypes.h> #define STACK_SIZE (64 * 1024) int main(int argc, char *argv[]) { volatile uint64_t workcnt = 0; int nthreads; bench_init(); #if CONFIG_TRACE errval_t err = trace_control(TRACE_EVENT(TRACE_SUBSYS_ROUTE, TRACE_EVENT_ROUTE_BENCH_START, 0), TRACE_EVENT(TRACE_SUBSYS_ROUTE, TRACE_EVENT_ROUTE_BENCH_STOP, 0), 0); assert(err_is_ok(err)); #endif if(argc == 2) { nthreads = atoi(argv[1]); backend_span_domain(nthreads, STACK_SIZE); bomp_custom_init(); omp_set_num_threads(nthreads); } else { assert(!"Specify number of threads"); } trace_event(TRACE_SUBSYS_ROUTE, TRACE_EVENT_ROUTE_BENCH_START, 0); uint64_t start = bench_tsc(); #pragma omp parallel while(rdtsc() < start + 805000000ULL) { workcnt++; } uint64_t end = bench_tsc(); trace_event(TRACE_SUBSYS_ROUTE, TRACE_EVENT_ROUTE_BENCH_STOP, 0); printf("done. time taken: %" PRIu64 " cycles.\n", end - start); #if CONFIG_TRACE char *buf = malloc(4096*4096); trace_dump(buf, 4096*4096, NULL); printf("%s\n", buf); #endif for(;;); return 0; }
ast-dump-openmp-atomic.c
// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fopenmp -ast-dump %s | FileCheck --match-full-lines -implicit-check-not=openmp_structured_block %s void test(int i) { #pragma omp atomic ++i; } // CHECK: TranslationUnitDecl {{.*}} <<invalid sloc>> <invalid sloc> // CHECK: `-FunctionDecl {{.*}} <{{.*}}ast-dump-openmp-atomic.c:3:1, line:6:1> line:3:6 test 'void (int)' // CHECK-NEXT: |-ParmVarDecl {{.*}} <col:11, col:15> col:15 used i 'int' // CHECK-NEXT: `-CompoundStmt {{.*}} <col:18, line:6:1> // CHECK-NEXT: `-OMPAtomicDirective {{.*}} <line:4:1, col:19> // CHECK-NEXT: `-CapturedStmt {{.*}} <line:5:3, col:5> // CHECK-NEXT: |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> // CHECK-NEXT: | |-UnaryOperator {{.*}} <col:3, col:5> openmp_structured_block 'int' prefix '++' // CHECK-NEXT: | | `-DeclRefExpr {{.*}} <col:5> 'int' lvalue ParmVar {{.*}} 'i' 'int' // CHECK-NEXT: | `-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-atomic.c:4:1) *const restrict' // CHECK-NEXT: `-DeclRefExpr {{.*}} <line:5:5> 'int' lvalue ParmVar {{.*}} 'i' 'int'
functions.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include "functions.h" //compute a*b mod p safely unsigned int modprod(unsigned int a, unsigned int b, unsigned int p) { unsigned int za = a; unsigned int ab = 0; while (b > 0) { if (b%2 == 1) ab = (ab + za) % p; za = (2 * za) % p; b /= 2; } return ab; } //compute a^b mod p safely unsigned int modExp(unsigned int a, unsigned int b, unsigned int p) { unsigned int z = a; unsigned int aExpb = 1; while (b > 0) { if (b%2 == 1) aExpb = modprod(aExpb, z, p); z = modprod(z, z, p); b /= 2; } return aExpb; } //returns either 0 or 1 randomly unsigned int randomBit() { return rand()%2; } //returns a random integer which is between 2^{n-1} and 2^{n} unsigned int randXbitInt(unsigned int n) { unsigned int r = 1; for (unsigned int i=0; i<n-1; i++) { r = r*2 + randomBit(); } return r; } //tests for primality and return 1 if N is probably prime and 0 if N is composite unsigned int isProbablyPrime(unsigned int N) { if (N%2==0) return 0; //not interested in even numbers (including 2) unsigned int NsmallPrimes = 168; unsigned int smallPrimeList[168] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997}; //before using a probablistic primality check, check directly using the small primes list for (unsigned int n=1;n<NsmallPrimes;n++) { if (N==smallPrimeList[n]) return 1; //true if (N%smallPrimeList[n]==0) return 0; //false } //if we're testing a large number switch to Miller-Rabin primality test unsigned int r = 0; unsigned int d = N-1; while (d%2 == 0) { d /= 2; r += 1; } for (unsigned int n=0;n<NsmallPrimes;n++) { unsigned int k = smallPrimeList[n]; unsigned int x = modExp(k,d,N); if ((x==1) || (x==N-1)) continue; for (unsigned int i=1;i<r-1;i++) { x = modprod(x,x,N); if (x == 1) return 0; //false if (x == N-1) break; } // see whether we left the loop becasue x==N-1 if (x == N-1) continue; return 0; //false } return 1; //true } //Finds a generator of Z_p using the assumption that p=2*q+1 unsigned int findGenerator(unsigned int p) { unsigned int g; unsigned int q = (p-1)/2; do { //make a random number 1<= g < p g = randXbitInt(32)%p; //could also have passed n to findGenerator } while (g==0 || (modExp(g,q,p)==1) || (modExp(g,2,p)==1)); return g; } void setupElGamal(unsigned int n, unsigned int *p, unsigned int *g, unsigned int *h, unsigned int *x) { /* Use isProbablyPrime and randomXbitInt to find a new random n-bit prime number which satisfies p=2*q+1 where q is also prime */ unsigned int q; do { *p = randXbitInt(n); q = (*p-1)/2; } while (!isProbablyPrime(*p) || !isProbablyPrime(q)); /* Use the fact that p=2*q+1 to quickly find a generator */ *g = findGenerator(*p); //pick a secret key, x *x = randXbitInt(n)%(*p); //compute h *h = modExp(*g,*x,*p); printf("ElGamal Setup successful.\n"); printf("p = %u. \n", *p); printf("g = %u is a generator of Z_%u \n", *g, *p); printf("Secret key: x = %u \n", *x); printf("h = g^x = %u\n", *h); printf("\n"); } void ElGamalEncrypt(unsigned int *m, unsigned int *a, unsigned int Nints, unsigned int p, unsigned int g, unsigned int h) { /* Q2.1 Parallelize this function with OpenMP */ for (unsigned int i=0; i<Nints;i++) { //pick y in Z_p randomly unsigned int y; do { y = randXbitInt(32)%p; } while (y==0); //dont allow y=0 //compute a = g^y a[i] = modExp(g,y,p); //compute s = h^y unsigned int s = modExp(h,y,p); //encrypt m by multiplying with s m[i] = modprod(m[i],s,p); } } void ElGamalDecrypt(unsigned int *m, unsigned int *a, unsigned int Nints, unsigned int p, unsigned int x) { /* Q2.1 Parallelize this function with OpenMP */ for (unsigned int i=0; i<Nints;i++) { //compute s = a^x unsigned int s = modExp(a[i],x,p); //compute s^{-1} = s^{p-2} unsigned int invS = modExp(s,p-2,p); //decrypt message by multplying by invS m[i] = modprod(m[i],invS,p); } } //Pad the end of string so its length is divisible by Nchars // Assume there is enough allocated storage for the padded string void padString(unsigned char* string, unsigned int charsPerInt) { /* Q1.2 Complete this function */ while((strlen(string)) % charsPerInt != 0){ string[strlen(string)] = ' '; } string[strlen(string)] = '\0'; } void convertStringToZ(unsigned char *string, unsigned int Nchars, unsigned int *Z, unsigned int Nints) { /* Q1.3 Complete this function */ int CPI = Nchars/Nints; #pragma omp parallel for for (int x = 0; x <Nints; x++){ for(int t =0; t < CPI; t++){ int hold = string[x*CPI+t]; hold = hold << 8*t; Z[x] += hold; } } /* Q2.2 Parallelize this function with OpenMP */ } void convertZToString(unsigned int *Z, unsigned int Nints, unsigned char *string, unsigned int Nchars) { int CPI = Nchars/Nints; /* Q1.4 Complete this function */ #pragma omp parallel for for (int i = 0; i < Nints; i++){ for(int n = 0; n< CPI; n++){ int letter = string[i*CPI+n]; letter = Z[i]&(0xFF); Z[i]= Z[i] >> 8*n; } } /* Q2.2 Parallelize this function with OpenMP */ }
aspl.c
#include "common.h" static uint64_t *_A, *_B; static int _nodes, _degree, _symmetries, _kind, _height = -1; static int* _num_degrees = NULL, *_itable = NULL; static int* _frontier = NULL, *_distance = NULL, *_next = NULL; static char* _bitmap = NULL; static unsigned int _elements, _times; static double _mem_usage, _elapsed_time; static bool _enable_avx2 = false, _is_profile = false, _enable_grid_s = false; extern bool ODP_Check_profile(); extern double ODP_Get_time(); extern void ODP_Create_itable(const int width, const int height, const int symmetries, int *_itable); extern int ODP_LOCAL_INDEX_GRID(const int x, const int width, const int height, const int symmetries); extern int ODP_ROTATE(const int v, const int width, const int height, const int symmetries, const int degree); extern void ODP_Profile(const char* name, const int kind, const int symmetries, const double mem_usage, const double elapsed_time, const unsigned int times, const int procs); extern int ODP_Get_kind(const int nodes, const int degree, const int* num_degrees, const int symmetries, const int procs, const bool is_cpu, const bool enable_grid_s); extern double ODP_Get_mem_usage(const int kind, const int nodes, const int degree, const int symmetries, const int *num_degrees, const int procs, const bool is_cpu, const bool enable_grid_s); extern void ODP_Matmul(const uint64_t *restrict A, uint64_t *restrict B, const int nodes, const int height, const int degree, const int *restrict num_degrees, const int *restrict adjacency, const int *itable, const int elements, const int symmetries, const bool enable_avx2); extern void ODP_Matmul_CHUNK(const uint64_t *restrict A, uint64_t *restrict B, const int nodes, const int height, const int degree, const int *num_degrees, const int *restrict adjacency, const int *itable, const int symmetries, const bool enable_avx2); extern void ODP_Malloc(uint64_t **a, const size_t s, const bool enable_avx2); extern void ODP_Free(uint64_t *a, const bool enable_avx2); extern int ODP_top_down_step(const int level, const int num_frontier, const int* restrict adjacency, const int nodes, const int degree, const int* restrict num_degrees, const bool enable_grid_s, const int height, const int symmetries, int* restrict frontier, int* restrict next, int* restrict distance, char* restrict bitmap); static void aspl_mat(const int* restrict adjacency, int *diameter, long *sum, double *ASPL) { #pragma omp parallel for for(int i=0;i<_nodes*_elements;i++) _A[i] = _B[i] = 0; #pragma omp parallel for for(int i=0;i<_nodes/_symmetries;i++){ unsigned int offset = i*_elements+i/UINT64_BITS; _A[offset] = _B[offset] = (0x1ULL << (i%UINT64_BITS)); } *sum = (long)_nodes * (_nodes - 1); *diameter = 1; for(int kk=0;kk<_nodes;kk++){ ODP_Matmul(_A, _B, _nodes, _height, _degree, _num_degrees, adjacency, _itable, _elements, _symmetries, _enable_avx2); uint64_t num = 0; #ifndef __FUGAKU #pragma omp parallel for reduction(+:num) #endif for(int i=0;i<_elements*_nodes;i++) num += POPCNT(_B[i]); num *= _symmetries; if(num == (uint64_t)_nodes*_nodes) break; // swap A <-> B uint64_t* tmp = _A; _A = _B; _B = tmp; *sum += (long)_nodes * _nodes - num; (*diameter) += 1; } *ASPL = *sum / (((double)_nodes-1)*_nodes); *sum /= 2.0; } static void aspl_mat_saving(const int* restrict adjacency, int *diameter, long *sum, double *ASPL) { int parsize = (_elements+(CPU_CHUNK-1))/CPU_CHUNK; *sum = (long)_nodes * (_nodes - 1); *diameter = 1; for(int t=0;t<parsize;t++){ unsigned int kk, l; #pragma omp parallel for for(int i=0;i<_nodes*CPU_CHUNK;i++) _A[i] = _B[i] = 0; for(l=0; l<UINT64_BITS*CPU_CHUNK && UINT64_BITS*t*CPU_CHUNK+l<_nodes/_symmetries; l++){ unsigned int offset = (UINT64_BITS*t*CPU_CHUNK+l)*CPU_CHUNK+l/UINT64_BITS; _A[offset] = _B[offset] = (0x1ULL<<(l%UINT64_BITS)); } for(kk=0;kk<_nodes;kk++){ ODP_Matmul_CHUNK(_A, _B, _nodes, _height, _degree, _num_degrees, adjacency, _itable, _symmetries, _enable_avx2); uint64_t num = 0; #ifndef __FUGAKU #pragma omp parallel for reduction(+:num) #endif for(int i=0;i<CPU_CHUNK*_nodes;i++) num += POPCNT(_B[i]); if(num == (uint64_t)_nodes*l) break; // swap A <-> B uint64_t* tmp = _A; _A = _B; _B = tmp; *sum += ((long)_nodes * l - num) * _symmetries; } *diameter = MAX(*diameter, kk+1); } *ASPL = *sum / (((double)_nodes-1)*_nodes); *sum /= 2.0; } static void init_aspl_s(const int nodes, const int degree, const int* num_degrees, const int symmetries) { if(nodes % symmetries != 0) ERROR("nodes(%d) must be divisible by symmetries(%d)\n", nodes, symmetries); else if(CPU_CHUNK % 4 != 0) ERROR("CPU_CHUNK(%d) in parameter.h must be multiple of 4\n", CPU_CHUNK); _kind = ODP_Get_kind(nodes, degree, num_degrees, symmetries, 1, true, _enable_grid_s); _mem_usage = ODP_Get_mem_usage(_kind, nodes, degree, symmetries, num_degrees, 1, true, _enable_grid_s); _elements = (nodes/symmetries+(UINT64_BITS-1))/UINT64_BITS; #ifdef __AVX2__ if(_elements >= 4){ // For performance _enable_avx2 = true; _elements = ((_elements+3)/4)*4; // _elements must be multiple of 4 } #endif if(_kind == ASPL_MATRIX || _kind == ASPL_MATRIX_SAVING){ size_t s = (_kind == ASPL_MATRIX)? _elements : CPU_CHUNK; ODP_Malloc(&_A, nodes*s*sizeof(uint64_t), _enable_avx2); // uint64_t A[nodes][s]; ODP_Malloc(&_B, nodes*s*sizeof(uint64_t), _enable_avx2); // uint64_t B[nodes][s]; } else{ // _kind == ASPL_BFS _bitmap = malloc(sizeof(char) * nodes); _frontier = malloc(sizeof(int) * nodes); _distance = malloc(sizeof(int) * nodes); _next = malloc(sizeof(int) * nodes); #ifdef _OPENMP ODP_declare_local_frontier(nodes); #endif } _nodes = nodes; _degree = degree; _symmetries = symmetries; _is_profile = ODP_Check_profile(); _elapsed_time = 0; _times = 0; if(num_degrees){ _num_degrees = malloc(sizeof(int) * nodes); memcpy(_num_degrees, num_degrees, sizeof(int) * nodes); } } static void aspl_bfs(const int* restrict adjacency, int* diameter, long *sum, double* ASPL) { int based_nodes = _nodes/_symmetries; bool reached = true; *diameter = 0; *sum = 0; for(int s=0;s<based_nodes;s++){ int num_frontier = 1, level = 0; for(int i=0;i<_nodes;i++) _bitmap[i] = NOT_VISITED; if(_enable_grid_s && _symmetries == 4){ int based_height = _height/2; int ss = (s/based_height) * _height + (s%based_height); _frontier[0] = ss; _distance[ss] = level; _bitmap[ss] = VISITED; } else{ _frontier[0] = s; _distance[s] = level; _bitmap[s] = VISITED; } while(1){ num_frontier = ODP_top_down_step(level++, num_frontier, adjacency, _nodes, _degree, _num_degrees, _enable_grid_s, _height, _symmetries, _frontier, _next, _distance, _bitmap); if(num_frontier == 0) break; int *tmp = _frontier; _frontier = _next; _next = tmp; } *diameter = MAX(*diameter, level-1); if(s == 0){ for(int i=1;i<_nodes;i++) if(_bitmap[i] == NOT_VISITED) reached = false; if(!reached){ *diameter = INT_MAX; return; } } for(int i=0;i<_nodes;i++) *sum += (_distance[i] + 1) * _symmetries; } *sum = (*sum - _nodes)/2; *ASPL = *sum / (((double)_nodes-1)*_nodes) * 2; } void ODP_Init_aspl_general(const int nodes, const int degree, const int* num_degrees) { init_aspl_s(nodes, degree, num_degrees, 1); } void ODP_Init_aspl_general_s(const int nodes, const int degree, const int* num_degrees, const int symmetries) { if(num_degrees){ int *tmp_num_degrees = malloc(sizeof(int) * nodes); int based_nodes = nodes/symmetries; for(int i=0;i<symmetries;i++) for(int j=0;j<based_nodes;j++) tmp_num_degrees[i*based_nodes+j] = num_degrees[j]; init_aspl_s(nodes, degree, tmp_num_degrees, symmetries); free(tmp_num_degrees); } else{ init_aspl_s(nodes, degree, NULL, symmetries); } } void ODP_Init_aspl_grid(const int width, const int height, const int degree, const int* num_degrees) { int nodes = width * height; _height = height; init_aspl_s(nodes, degree, num_degrees, 1); } void ODP_Init_aspl_grid_s(const int width, const int height, const int degree, const int* num_degrees, const int symmetries) { int nodes = width * height; _height = height; if(symmetries == 2 || symmetries == 4){ _enable_grid_s = true; _itable = malloc(sizeof(int) * nodes); ODP_Create_itable(width, height, symmetries, _itable); } if(num_degrees){ int *tmp_num_degrees = malloc(sizeof(int) * nodes); int based_nodes = nodes/symmetries; if(symmetries == 2){ for(int i=0;i<based_nodes;i++){ tmp_num_degrees[i] = num_degrees[i]; tmp_num_degrees[ODP_ROTATE(i, width, height, symmetries, 180)] = num_degrees[i]; } } else if(symmetries == 4){ for(int i=0;i<based_nodes;i++){ int v = ODP_LOCAL_INDEX_GRID(i,width,height,symmetries); tmp_num_degrees[v] = num_degrees[i]; tmp_num_degrees[ODP_ROTATE(v, width, height, symmetries, 90)] = num_degrees[i]; tmp_num_degrees[ODP_ROTATE(v, width, height, symmetries, 180)] = num_degrees[i]; tmp_num_degrees[ODP_ROTATE(v, width, height, symmetries, 270)] = num_degrees[i]; } } init_aspl_s(nodes, degree, tmp_num_degrees, symmetries); free(tmp_num_degrees); } else{ init_aspl_s(nodes, degree, NULL, symmetries); } } void ODP_Finalize_aspl() { if(_kind == ASPL_MATRIX || _kind == ASPL_MATRIX_SAVING){ ODP_Free(_A, _enable_avx2); ODP_Free(_B, _enable_avx2); if(_num_degrees) free(_num_degrees); if(_itable) free(_itable); } else{ // _kind == ASPL_BFS free(_bitmap); free(_frontier); free(_distance); free(_next); #ifdef _OPENMP ODP_free_local_frontier(); #endif } if(_is_profile){ #ifdef _OPENMP ODP_Profile("THREADS", _kind, _symmetries, _mem_usage, _elapsed_time, _times, 1); #else ODP_Profile("SERIAL", _kind, _symmetries, _mem_usage, _elapsed_time, _times, 1); #endif } } void ODP_Set_aspl(const int* restrict adjacency, int *diameter, long *sum, double *ASPL) { double t = ODP_Get_time(); if(_kind == ASPL_MATRIX) aspl_mat (adjacency, diameter, sum, ASPL); else if(_kind == ASPL_MATRIX_SAVING) aspl_mat_saving(adjacency, diameter, sum, ASPL); else // _kind == ASPL_MATRIX_BFS aspl_bfs(adjacency, diameter, sum, ASPL); _elapsed_time += ODP_Get_time() - t; if(*diameter > _nodes){ *diameter = INT_MAX; *sum = LONG_MAX; *ASPL = DBL_MAX; } _times++; }
kernels.h
void compute_probs( const double* __restrict alphas, const double* __restrict rands, double* __restrict probs, int n, int K, int M, int threads, int blocks) { #pragma omp target teams distribute parallel for \ num_teams(blocks) thread_limit(threads) for (int i = 0; i < n; i++) { double maxval; int m, k; int maxind; double M_d = (double) M; double w[21]; // w[K] for(k = 0; k < K; ++k){ // initialize probs (though already done on CPU) probs[i*K + k] = 0.0; } // core computations for(m = 0; m < M; ++m){ // loop over Monte Carlo iterations for(k = 0; k < K; ++k){ // generate W ~ N(alpha, 1) w[k] = alphas[i*K + k] + rands[m*K + k]; } // determine which category has max W maxind = K-1; maxval = w[K-1]; for(k = 0; k < (K-1); ++k){ if(w[k] > maxval){ maxind = k; maxval = w[k]; } } probs[i*K + maxind] += 1.0; } // compute final proportions for(k = 0; k < K; ++k) { probs[i*K + k] /= M_d; } } } void compute_probs_unitStrides( const double* __restrict alphas, const double* __restrict rands, double* __restrict probs, int n, int K, int M, int threads, int blocks) { #pragma omp target teams distribute parallel for \ num_teams(blocks) thread_limit(threads) for (int i = 0; i < n; i++) { double maxval; int m, k; int maxind; double M_d = (double) M; double w[21]; // w[K] for(k = 0; k < K; ++k){ // initialize probs (though already done on CPU) probs[k*n + i] = 0.0; } // core computations for(m = 0; m < M; ++m){ // loop over Monte Carlo iterations for(k = 0; k < K; ++k){ // generate W ~ N(alpha, 1) // with +i we now have unit strides in inner loop w[k] = alphas[k*n + i] + rands[k*M + m]; } // determine which category has max W maxind = K-1; maxval = w[K-1]; for(k = 0; k < (K-1); ++k){ if(w[k] > maxval){ maxind = k; maxval = w[k]; } } probs[maxind*n + i] += 1.0; } // compute final proportions for(k = 0; k < K; ++k) { // unit strides probs[k*n + i] /= M_d; } } } void compute_probs_unitStrides_sharedMem( const double* __restrict alphas, const double* __restrict rands, double* __restrict probs, int n, int K, int M, int threads, int blocks) { #pragma omp target teams num_teams(blocks) thread_limit(threads) { double shared[21 * 96 * 2]; // static #pragma omp parallel { int threadIdx_x = omp_get_thread_num(); int threads_per_block = threads; int i = omp_get_team_num() * threads + threadIdx_x; if (i < n) { // set up shared memory: half for probs and half for w double* probs_shared = shared; // shared mem is one big block, so need to index into latter portion of it to use for w double* w = &shared[K*threads_per_block]; double maxval; int m, k; int maxind; double M_d = (double) M; // initialize shared memory probs for(k = 0; k < K; ++k) { probs_shared[k*threads_per_block + threadIdx_x] = 0.0; } // core computation for(m = 0; m < M; ++m){ // loop over Monte Carlo iterations for(k = 0; k < K; ++k){ // generate W ~ N(alpha, 1) w[k*threads_per_block + threadIdx_x] = alphas[k*n + i] + rands[k*M + m]; } maxind = K-1; maxval = w[(K-1)*threads_per_block + threadIdx_x]; for(k = 0; k < (K-1); ++k){ if(w[k*threads_per_block + threadIdx_x] > maxval){ maxind = k; maxval = w[k*threads_per_block + threadIdx_x]; } } probs_shared[maxind*threads_per_block + threadIdx_x] += 1.0; } for(k = 0; k < K; ++k) { probs_shared[k*threads_per_block + threadIdx_x] /= M_d; } // copy to device memory so can be returned to CPU for(k = 0; k < K; ++k) { probs[k*n + i] = probs_shared[k*threads_per_block + threadIdx_x]; } } } } }
3d7pt.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-1, 3D 7 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 4; tile_size[1] = 4; tile_size[2] = 24; tile_size[3] = 2048; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; const double alpha = 0.0876; const double beta = 0.0765; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 2) && (Nx >= 3) && (Ny >= 3) && (Nz >= 3)) { for (t1=-1;t1<=floord(Nt-2,2);t1++) { lbp=max(ceild(t1,2),ceild(4*t1-Nt+3,4)); ubp=min(floord(Nt+Nz-4,4),floord(2*t1+Nz-1,4)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(t1-11,12)),ceild(4*t2-Nz-20,24));t3<=min(min(min(floord(4*t2+Ny,24),floord(Nt+Ny-4,24)),floord(2*t1+Ny+1,24)),floord(4*t1-4*t2+Nz+Ny-1,24));t3++) { for (t4=max(max(max(0,ceild(t1-1023,1024)),ceild(4*t2-Nz-2044,2048)),ceild(24*t3-Ny-2044,2048));t4<=min(min(min(min(floord(4*t2+Nx,2048),floord(Nt+Nx-4,2048)),floord(2*t1+Nx+1,2048)),floord(24*t3+Nx+20,2048)),floord(4*t1-4*t2+Nz+Nx-1,2048));t4++) { for (t5=max(max(max(max(max(0,2*t1),4*t1-4*t2+1),4*t2-Nz+2),24*t3-Ny+2),2048*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,2*t1+3),4*t2+2),24*t3+22),2048*t4+2046),4*t1-4*t2+Nz+1);t5++) { for (t6=max(max(4*t2,t5+1),-4*t1+4*t2+2*t5-3);t6<=min(min(4*t2+3,-4*t1+4*t2+2*t5),t5+Nz-2);t6++) { for (t7=max(24*t3,t5+1);t7<=min(24*t3+23,t5+Ny-2);t7++) { lbv=max(2048*t4,t5+1); ubv=min(2048*t4+2047,t5+Nx-2); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = ((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; }
Parallel.h
#pragma once #include <ATen/ATen.h> #include <cstddef> #ifdef _OPENMP #include <omp.h> #endif namespace at { namespace internal { // This parameter is heuristically chosen to determine the minimum number of // work that warrants paralellism. For example, when summing an array, it is // deemed inefficient to parallelise over arrays shorter than 32768. Further, // no parallel algorithm (such as parallel_reduce) should split work into // smaller than GRAIN_SIZE chunks. constexpr int64_t GRAIN_SIZE = 32768; } // namespace internal inline int64_t divup(int64_t x, int64_t y) { return (x + y - 1) / y; } template <class F> inline void parallel_for( const int64_t begin, const int64_t end, const int64_t grain_size, const F& f) { #ifdef _OPENMP #pragma omp parallel if ((end - begin) >= grain_size) { int64_t num_threads = omp_get_num_threads(); int64_t tid = omp_get_thread_num(); int64_t chunk_size = divup((end - begin), num_threads); int64_t begin_tid = begin + tid * chunk_size; if (begin_tid < end) f(begin_tid, std::min(end, chunk_size + begin_tid)); } #else if (begin < end) { f(begin, end); } #endif } template <class scalar_t, class F, class SF> inline scalar_t parallel_reduce( const int64_t begin, const int64_t end, const int64_t grain_size, const scalar_t ident, const F f, const SF sf) { if (get_num_threads() == 1) { return f(begin, end, ident); } else { const int64_t num_results = divup((end - begin), grain_size); std::vector<scalar_t> results(num_results); scalar_t* results_data = results.data(); #pragma omp parallel for if ((end - begin) >= grain_size) for (int64_t id = 0; id < num_results; id++) { int64_t i = begin + id * grain_size; results_data[id] = f(i, i + std::min(end - i, grain_size), ident); } return std::accumulate( results_data, results_data + results.size(), ident, sf); } } } // namespace at
integral_solution_parallel.c
// integral_solution_parallel.c // compile with: /openmp /* ############################################################################# ## DESCRIPTION: Integral Solutin in Parallel using OpenMP - PI Value. ## NAME: integral_solution_parallel.c ## AUTHOR: Lucca Pessoa da Silva Matos ## DATE: 10.04.2020 ## VERSION: 1.0 ## EXEMPLE: ## PS C:\> gcc -fopenmp -o integral_solution_parallel integral_solution_parallel.c ##############################################################################*/ // ============================================================================= // LIBRARYS // ============================================================================= #include <omp.h> #include <math.h> #include <stdio.h> #include <locale.h> #include <stdlib.h> // ============================================================================= // MACROS // ============================================================================= #define STEPS 100000000 #define NUM_THREADS 12 #define LOOP(i, n) for(int i = 0; i < n; i++) // ============================================================================= // CALL FUNCTIONS // ============================================================================= void cabecalho(); void set_portuguese(); double step; // ============================================================================= // MAIN // ============================================================================= int main(int argc, char const *argv[]){ set_portuguese(); cabecalho(); printf("\nHey! Nesse script iremos calcular o valor de PI com base em calculos de integral."); int i; double x, pi, sum = 0.0, tempo_inicial, tempo_final; printf("\n\nSetando o numero de Threads para %d\n", NUM_THREADS); omp_set_num_threads(NUM_THREADS); step = 1.0/(double) STEPS; tempo_inicial = omp_get_wtime(); printf("\n1 - Estamos fora do contexto paralelo. Entrando...\n"); #pragma omp parallel for default(none) shared(x, step) reduction(+:sum) LOOP(i, STEPS){ sum += 4.0 / (1.0 + pow((i + 0.5) * step, 2)); } printf("\n2 - Estamos fora do contexto paralelo. Saindo...\n"); tempo_final = omp_get_wtime() - tempo_inicial; printf("\nO tempo gasto no contexto paralelo foi de: %lf\n", tempo_final); pi = sum * step; printf("\nO valor de PI = %f\n\n", pi); return 0; } // ============================================================================= // FUNCTIONS // ============================================================================= void set_portuguese(){ setlocale(LC_ALL, "Portuguese"); } void cabecalho(){ printf("\n**************************************************"); printf("\n* *"); printf("\n* *"); printf("\n* PROGRAMACAO PARALELA COM OPENMP - LUCCA PESSOA *"); printf("\n* *"); printf("\n* *"); printf("\n**************************************************\n"); }
GB_binop__islt_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__islt_int32) // A.*B function (eWiseMult): GB (_AemultB_08__islt_int32) // A.*B function (eWiseMult): GB (_AemultB_02__islt_int32) // A.*B function (eWiseMult): GB (_AemultB_04__islt_int32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__islt_int32) // A*D function (colscale): GB (_AxD__islt_int32) // D*A function (rowscale): GB (_DxB__islt_int32) // C+=B function (dense accum): GB (_Cdense_accumB__islt_int32) // C+=b function (dense accum): GB (_Cdense_accumb__islt_int32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__islt_int32) // C=scalar+B GB (_bind1st__islt_int32) // C=scalar+B' GB (_bind1st_tran__islt_int32) // C=A+scalar GB (_bind2nd__islt_int32) // C=A'+scalar GB (_bind2nd_tran__islt_int32) // C type: int32_t // A type: int32_t // B,b type: int32_t // BinaryOp: cij = (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) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int32_t bij = GBX (Bx, pB, B_iso) // 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 = (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_ISLT || GxB_NO_INT32 || GxB_NO_ISLT_INT32) //------------------------------------------------------------------------------ // 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__islt_int32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__islt_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__islt_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__islt_int32) ( 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 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__islt_int32) ( 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 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__islt_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 Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__islt_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__islt_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__islt_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__islt_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__islt_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] = (x < bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__islt_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] = (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] = (x < aij) ; \ } GrB_Info GB (_bind1st_tran__islt_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] = (aij < y) ; \ } GrB_Info GB (_bind2nd_tran__islt_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
displacement_lagrangemultiplier_contact_criteria.h
// KRATOS ______ __ __ _____ __ __ __ // / ____/___ ____ / /_____ ______/ /_/ ___// /________ _______/ /___ ___________ _/ / // / / / __ \/ __ \/ __/ __ `/ ___/ __/\__ \/ __/ ___/ / / / ___/ __/ / / / ___/ __ `/ / // / /___/ /_/ / / / / /_/ /_/ / /__/ /_ ___/ / /_/ / / /_/ / /__/ /_/ /_/ / / / /_/ / / // \____/\____/_/ /_/\__/\__,_/\___/\__//____/\__/_/ \__,_/\___/\__/\__,_/_/ \__,_/_/ MECHANICS // // License: BSD License // license: ContactStructuralMechanicsApplication/license.txt // // Main authors: Vicente Mataix Ferrandiz // #if !defined(KRATOS_DISPLACEMENT_LAGRANGE_MULTIPLIER_CONTACT_CRITERIA_H) #define KRATOS_DISPLACEMENT_LAGRANGE_MULTIPLIER_CONTACT_CRITERIA_H /* System includes */ /* External includes */ /* Project includes */ #include "utilities/table_stream_utility.h" #include "solving_strategies/convergencecriterias/convergence_criteria.h" #include "utilities/color_utilities.h" #include "utilities/constraint_utilities.h" namespace Kratos { ///@addtogroup ContactStructuralMechanicsApplication ///@{ ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@name Kratos Classes ///@{ /** * @class DisplacementLagrangeMultiplierContactCriteria * @ingroup ContactStructuralMechanicsApplication * @brief Convergence criteria for contact problems * @details This class implements a convergence control based on nodal displacement and * lagrange multiplier values. The error is evaluated separately for each of them, and * relative and absolute tolerances for both must be specified. * @author Vicente Mataix Ferrandiz */ template< class TSparseSpace, class TDenseSpace > class DisplacementLagrangeMultiplierContactCriteria : public ConvergenceCriteria< TSparseSpace, TDenseSpace > { public: ///@name Type Definitions ///@{ /// Pointer definition of DisplacementLagrangeMultiplierContactCriteria KRATOS_CLASS_POINTER_DEFINITION( DisplacementLagrangeMultiplierContactCriteria ); /// Local Flags KRATOS_DEFINE_LOCAL_FLAG( ENSURE_CONTACT ); KRATOS_DEFINE_LOCAL_FLAG( PRINTING_OUTPUT ); KRATOS_DEFINE_LOCAL_FLAG( TABLE_IS_INITIALIZED ); KRATOS_DEFINE_LOCAL_FLAG( ROTATION_DOF_IS_CONSIDERED ); /// The base class definition typedef ConvergenceCriteria< TSparseSpace, TDenseSpace > BaseType; /// The definition of the current class typedef DisplacementLagrangeMultiplierContactCriteria< TSparseSpace, TDenseSpace > ClassType; /// The dofs array type typedef typename BaseType::DofsArrayType DofsArrayType; /// The sparse matrix type typedef typename BaseType::TSystemMatrixType TSystemMatrixType; /// The dense vector type typedef typename BaseType::TSystemVectorType TSystemVectorType; /// The sparse space used typedef TSparseSpace SparseSpaceType; /// The table stream definition TODO: Replace by logger typedef TableStreamUtility::Pointer TablePrinterPointerType; /// The index type definition typedef std::size_t IndexType; /// The epsilon tolerance definition static constexpr double Tolerance = std::numeric_limits<double>::epsilon(); ///@} ///@name Life Cycle ///@{ /** * @brief Default constructor. */ explicit DisplacementLagrangeMultiplierContactCriteria() : BaseType() { } /** * @brief Default constructor. (with parameters) * @param ThisParameters The configuration parameters */ explicit DisplacementLagrangeMultiplierContactCriteria(Kratos::Parameters ThisParameters) : BaseType() { // Validate and assign defaults ThisParameters = this->ValidateAndAssignParameters(ThisParameters, this->GetDefaultParameters()); this->AssignSettings(ThisParameters); } /** * @brief Default Constructor. * @param DispRatioTolerance Relative tolerance for displacement error * @param DispAbsTolerance Absolute tolerance for displacement error * @param RotRatioTolerance Relative tolerance for rotation error * @param RotAbsTolerance Absolute tolerance for rotation error * @param LMRatioTolerance Relative tolerance for lagrange multiplier error * @param LMAbsTolerance Absolute tolerance for lagrange multiplier error * @param EnsureContact To check if the contact is lost * @param pTable The pointer to the output r_table * @param PrintingOutput If the output is going to be printed in a txt file */ explicit DisplacementLagrangeMultiplierContactCriteria( const double DispRatioTolerance, const double DispAbsTolerance, const double RotRatioTolerance, const double RotAbsTolerance, const double LMRatioTolerance, const double LMAbsTolerance, const bool EnsureContact = false, const bool PrintingOutput = false ) : BaseType() { // Set local flags mOptions.Set(DisplacementLagrangeMultiplierContactCriteria::ENSURE_CONTACT, EnsureContact); mOptions.Set(DisplacementLagrangeMultiplierContactCriteria::PRINTING_OUTPUT, PrintingOutput); mOptions.Set(DisplacementLagrangeMultiplierContactCriteria::TABLE_IS_INITIALIZED, false); mOptions.Set(DisplacementLagrangeMultiplierContactCriteria::ROTATION_DOF_IS_CONSIDERED, false); // The displacement solution mDispRatioTolerance = DispRatioTolerance; mDispAbsTolerance = DispAbsTolerance; // The rotation solution mRotRatioTolerance = RotRatioTolerance; mRotAbsTolerance = RotAbsTolerance; // The contact solution mLMRatioTolerance = LMRatioTolerance; mLMAbsTolerance = LMAbsTolerance; } // Copy constructor. DisplacementLagrangeMultiplierContactCriteria( DisplacementLagrangeMultiplierContactCriteria const& rOther ) :BaseType(rOther) ,mOptions(rOther.mOptions) ,mDispRatioTolerance(rOther.mDispRatioTolerance) ,mDispAbsTolerance(rOther.mDispAbsTolerance) ,mRotRatioTolerance(rOther.mRotRatioTolerance) ,mRotAbsTolerance(rOther.mRotAbsTolerance) ,mLMRatioTolerance(rOther.mLMRatioTolerance) ,mLMAbsTolerance(rOther.mLMAbsTolerance) { } /// Destructor. ~DisplacementLagrangeMultiplierContactCriteria() override = default; ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ /** * @brief Create method * @param ThisParameters The configuration parameters */ typename BaseType::Pointer Create(Parameters ThisParameters) const override { return Kratos::make_shared<ClassType>(ThisParameters); } /** * @brief Compute relative and absolute error. * @param rModelPart Reference to the ModelPart containing the contact problem. * @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver) * @param rA System matrix (unused) * @param rDx Vector of results (variations on nodal variables) * @param rb RHS vector (residual) * @return true if convergence is achieved, false otherwise */ bool PostCriteria( ModelPart& rModelPart, DofsArrayType& rDofSet, const TSystemMatrixType& rA, const TSystemVectorType& rDx, const TSystemVectorType& rb ) override { if (SparseSpaceType::Size(rDx) != 0) { //if we are solving for something // Initialize double disp_solution_norm = 0.0, rot_solution_norm = 0.0, lm_solution_norm = 0.0, disp_increase_norm = 0.0, rot_increase_norm = 0.0, lm_increase_norm = 0.0; IndexType disp_dof_num(0),rot_dof_num(0),lm_dof_num(0); // First iterator const auto it_dof_begin = rDofSet.begin(); // Auxiliar values std::size_t dof_id = 0; double dof_value = 0.0, dof_incr = 0.0; // The number of active dofs const std::size_t number_active_dofs = rb.size(); // Auxiliar displacement DoF check const std::function<bool(const VariableData&)> check_without_rot = [](const VariableData& rCurrVar) -> bool {return true;}; const std::function<bool(const VariableData&)> check_with_rot = [](const VariableData& rCurrVar) -> bool {return ((rCurrVar == DISPLACEMENT_X) || (rCurrVar == DISPLACEMENT_Y) || (rCurrVar == DISPLACEMENT_Z));}; const auto* p_check_disp = (mOptions.Is(DisplacementLagrangeMultiplierContactCriteria::ROTATION_DOF_IS_CONSIDERED)) ? &check_with_rot : &check_without_rot; // Loop over Dofs #pragma omp parallel for firstprivate(dof_id, dof_value ,dof_incr) reduction(+:disp_solution_norm, rot_solution_norm, lm_solution_norm, disp_increase_norm, rot_increase_norm, lm_increase_norm, disp_dof_num, rot_dof_num, lm_dof_num) for (int i = 0; i < static_cast<int>(rDofSet.size()); i++) { auto it_dof = it_dof_begin + i; dof_id = it_dof->EquationId(); // Check dof id is solved if (dof_id < number_active_dofs) { if (mActiveDofs[dof_id] == 1) { dof_value = it_dof->GetSolutionStepValue(0); dof_incr = rDx[dof_id]; const auto& r_curr_var = it_dof->GetVariable(); if ((r_curr_var == VECTOR_LAGRANGE_MULTIPLIER_X) || (r_curr_var == VECTOR_LAGRANGE_MULTIPLIER_Y) || (r_curr_var == VECTOR_LAGRANGE_MULTIPLIER_Z) || (r_curr_var == LAGRANGE_MULTIPLIER_CONTACT_PRESSURE)) { lm_solution_norm += std::pow(dof_value, 2); lm_increase_norm += std::pow(dof_incr, 2); ++lm_dof_num; } else if ((*p_check_disp)(r_curr_var)) { disp_solution_norm += std::pow(dof_value, 2); disp_increase_norm += std::pow(dof_incr, 2); ++disp_dof_num; } else { // We will assume is rotation dof KRATOS_DEBUG_ERROR_IF_NOT((r_curr_var == ROTATION_X) || (r_curr_var == ROTATION_Y) || (r_curr_var == ROTATION_Z)) << "Variable must be a ROTATION and it is: " << r_curr_var.Name() << std::endl; rot_solution_norm += std::pow(dof_value, 2); rot_increase_norm += std::pow(dof_incr, 2); ++rot_dof_num; } } } } if(disp_increase_norm < Tolerance) disp_increase_norm = 1.0; if(rot_increase_norm < Tolerance) rot_increase_norm = 1.0; if(lm_increase_norm < Tolerance) lm_increase_norm = 1.0; if(disp_solution_norm < Tolerance) disp_solution_norm = 1.0; KRATOS_ERROR_IF(mOptions.Is(DisplacementLagrangeMultiplierContactCriteria::ENSURE_CONTACT) && lm_solution_norm < Tolerance) << "WARNING::CONTACT LOST::ARE YOU SURE YOU ARE SUPPOSED TO HAVE CONTACT?" << std::endl; const double disp_ratio = std::sqrt(disp_increase_norm/disp_solution_norm); const double rot_ratio = std::sqrt(rot_increase_norm/rot_solution_norm); const double lm_ratio = lm_solution_norm > Tolerance ? std::sqrt(lm_increase_norm/lm_solution_norm) : 0.0; const double disp_abs = std::sqrt(disp_increase_norm)/static_cast<double>(disp_dof_num); const double rot_abs = std::sqrt(rot_increase_norm)/static_cast<double>(rot_dof_num); const double lm_abs = std::sqrt(lm_increase_norm)/static_cast<double>(lm_dof_num); // The process info of the model part ProcessInfo& r_process_info = rModelPart.GetProcessInfo(); // We print the results // TODO: Replace for the new log if (rModelPart.GetCommunicator().MyPID() == 0 && this->GetEchoLevel() > 0) { if (r_process_info.Has(TABLE_UTILITY)) { std::cout.precision(4); TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY]; auto& r_table = p_table->GetTable(); if (mOptions.Is(DisplacementLagrangeMultiplierContactCriteria::ROTATION_DOF_IS_CONSIDERED)) { r_table << disp_ratio << mDispRatioTolerance << disp_abs << mDispAbsTolerance << rot_ratio << mRotRatioTolerance << rot_abs << mRotAbsTolerance << lm_ratio << mLMRatioTolerance << lm_abs << mLMAbsTolerance; } else { r_table << disp_ratio << mDispRatioTolerance << disp_abs << mDispAbsTolerance << lm_ratio << mLMRatioTolerance << lm_abs << mLMAbsTolerance; } } else { std::cout.precision(4); if (mOptions.IsNot(DisplacementLagrangeMultiplierContactCriteria::PRINTING_OUTPUT)) { KRATOS_INFO("DisplacementLagrangeMultiplierContactCriteria") << BOLDFONT("DoF ONVERGENCE CHECK") << "\tSTEP: " << r_process_info[STEP] << "\tNL ITERATION: " << r_process_info[NL_ITERATION_NUMBER] << std::endl; KRATOS_INFO("DisplacementLagrangeMultiplierContactCriteria") << BOLDFONT("\tDISPLACEMENT: RATIO = ") << disp_ratio << BOLDFONT(" EXP.RATIO = ") << mDispRatioTolerance << BOLDFONT(" ABS = ") << disp_abs << BOLDFONT(" EXP.ABS = ") << mDispAbsTolerance << std::endl; if (mOptions.Is(DisplacementLagrangeMultiplierContactCriteria::ROTATION_DOF_IS_CONSIDERED)) { KRATOS_INFO("DisplacementLagrangeMultiplierContactCriteria") << BOLDFONT("\tROTATION: RATIO = ") << rot_ratio << BOLDFONT(" EXP.RATIO = ") << mRotRatioTolerance << BOLDFONT(" ABS = ") << rot_abs << BOLDFONT(" EXP.ABS = ") << mRotAbsTolerance << std::endl; } KRATOS_INFO("DisplacementLagrangeMultiplierContactCriteria") << BOLDFONT(" LAGRANGE MUL:\tRATIO = ") << lm_ratio << BOLDFONT(" EXP.RATIO = ") << mLMRatioTolerance << BOLDFONT(" ABS = ") << lm_abs << BOLDFONT(" EXP.ABS = ") << mLMAbsTolerance << std::endl; } else { KRATOS_INFO("DisplacementLagrangeMultiplierContactCriteria") << "DoF ONVERGENCE CHECK" << "\tSTEP: " << r_process_info[STEP] << "\tNL ITERATION: " << r_process_info[NL_ITERATION_NUMBER] << std::endl; KRATOS_INFO("DisplacementLagrangeMultiplierContactCriteria") << "\tDISPLACEMENT: RATIO = " << disp_ratio << " EXP.RATIO = " << mDispRatioTolerance << " ABS = " << disp_abs << " EXP.ABS = " << mDispAbsTolerance << std::endl; if (mOptions.Is(DisplacementLagrangeMultiplierContactCriteria::ROTATION_DOF_IS_CONSIDERED)) { KRATOS_INFO("DisplacementLagrangeMultiplierContactCriteria") << "\tROTATION: RATIO = " << rot_ratio << " EXP.RATIO = " << mRotRatioTolerance << " ABS = " << rot_abs << " EXP.ABS = " << mRotAbsTolerance << std::endl; } KRATOS_INFO("DisplacementLagrangeMultiplierContactCriteria") << " LAGRANGE MUL:\tRATIO = " << lm_ratio << " EXP.RATIO = " << mLMRatioTolerance << " ABS = " << lm_abs << " EXP.ABS = " << mLMAbsTolerance << std::endl; } } } // We check if converged const bool disp_converged = (disp_ratio <= mDispRatioTolerance || disp_abs <= mDispAbsTolerance); const bool rot_converged = (mOptions.Is(DisplacementLagrangeMultiplierContactCriteria::ROTATION_DOF_IS_CONSIDERED)) ? (rot_ratio <= mRotRatioTolerance || rot_abs <= mRotAbsTolerance) : true; const bool lm_converged = (mOptions.IsNot(DisplacementLagrangeMultiplierContactCriteria::ENSURE_CONTACT) && lm_solution_norm < Tolerance) ? true : (lm_ratio <= mLMRatioTolerance || lm_abs <= mLMAbsTolerance); if (disp_converged && rot_converged && lm_converged) { if (rModelPart.GetCommunicator().MyPID() == 0 && this->GetEchoLevel() > 0) { if (r_process_info.Has(TABLE_UTILITY)) { TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY]; auto& r_table = p_table->GetTable(); if (mOptions.IsNot(DisplacementLagrangeMultiplierContactCriteria::PRINTING_OUTPUT)) r_table << BOLDFONT(FGRN(" Achieved")); else r_table << "Achieved"; } else { if (mOptions.IsNot(DisplacementLagrangeMultiplierContactCriteria::PRINTING_OUTPUT)) KRATOS_INFO("DisplacementLagrangeMultiplierContactCriteria") << BOLDFONT("\tDoF") << " convergence is " << BOLDFONT(FGRN("achieved")) << std::endl; else KRATOS_INFO("DisplacementLagrangeMultiplierContactCriteria") << "\tDoF convergence is achieved" << std::endl; } } return true; } else { if (rModelPart.GetCommunicator().MyPID() == 0 && this->GetEchoLevel() > 0) { if (r_process_info.Has(TABLE_UTILITY)) { TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY]; auto& r_table = p_table->GetTable(); if (mOptions.IsNot(DisplacementLagrangeMultiplierContactCriteria::PRINTING_OUTPUT)) r_table << BOLDFONT(FRED(" Not achieved")); else r_table << "Not achieved"; } else { if (mOptions.IsNot(DisplacementLagrangeMultiplierContactCriteria::PRINTING_OUTPUT)) KRATOS_INFO("DisplacementLagrangeMultiplierContactCriteria") << BOLDFONT("\tDoF") << " convergence is " << BOLDFONT(FRED(" not achieved")) << std::endl; else KRATOS_INFO("DisplacementLagrangeMultiplierContactCriteria") << "\tDoF convergence is not achieved" << std::endl; } } return false; } } else // In this case all the displacements are imposed! return true; } /** * @brief This function initialize the convergence criteria * @param rModelPart Reference to the ModelPart containing the contact problem. (unused) */ void Initialize( ModelPart& rModelPart ) override { // Initialize BaseType::mConvergenceCriteriaIsInitialized = true; // Check rotation dof mOptions.Set(DisplacementLagrangeMultiplierContactCriteria::ROTATION_DOF_IS_CONSIDERED, ContactUtilities::CheckModelPartHasRotationDoF(rModelPart)); // Initialize header ProcessInfo& r_process_info = rModelPart.GetProcessInfo(); if (r_process_info.Has(TABLE_UTILITY) && mOptions.IsNot(DisplacementLagrangeMultiplierContactCriteria::TABLE_IS_INITIALIZED)) { TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY]; auto& r_table = p_table->GetTable(); r_table.AddColumn("DP RATIO", 10); r_table.AddColumn("EXP. RAT", 10); r_table.AddColumn("ABS", 10); r_table.AddColumn("EXP. ABS", 10); if (mOptions.Is(DisplacementLagrangeMultiplierContactCriteria::ROTATION_DOF_IS_CONSIDERED)) { r_table.AddColumn("RT RATIO", 10); r_table.AddColumn("EXP. RAT", 10); r_table.AddColumn("ABS", 10); r_table.AddColumn("EXP. ABS", 10); } r_table.AddColumn("LM RATIO", 10); r_table.AddColumn("EXP. RAT", 10); r_table.AddColumn("ABS", 10); r_table.AddColumn("EXP. ABS", 10); r_table.AddColumn("CONVERGENCE", 15); mOptions.Set(DisplacementLagrangeMultiplierContactCriteria::TABLE_IS_INITIALIZED, true); } } /** * @brief This function initializes the solution step * @param rModelPart Reference to the ModelPart containing the contact problem. * @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver) * @param rA System matrix (unused) * @param rDx Vector of results (variations on nodal variables) * @param rb RHS vector (residual) */ void InitializeSolutionStep( ModelPart& rModelPart, DofsArrayType& rDofSet, const TSystemMatrixType& rA, const TSystemVectorType& rDx, const TSystemVectorType& rb ) override { // Filling mActiveDofs when MPC exist ConstraintUtilities::ComputeActiveDofs(rModelPart, mActiveDofs, rDofSet); } /** * @brief This method provides the defaults parameters to avoid conflicts between the different constructors * @return The default parameters */ Parameters GetDefaultParameters() const override { Parameters default_parameters = Parameters(R"( { "name" : "displacement_lagrangemultiplier_contact_criteria", "ensure_contact" : false, "print_convergence_criterion" : false, "displacement_relative_tolerance" : 1.0e-4, "displacement_absolute_tolerance" : 1.0e-9, "rotation_relative_tolerance" : 1.0e-4, "rotation_absolute_tolerance" : 1.0e-9, "contact_displacement_relative_tolerance" : 1.0e-4, "contact_displacement_absolute_tolerance" : 1.0e-9 })"); // Getting base class default parameters const Parameters base_default_parameters = BaseType::GetDefaultParameters(); default_parameters.RecursivelyAddMissingParameters(base_default_parameters); return default_parameters; } /** * @brief Returns the name of the class as used in the settings (snake_case format) * @return The name of the class */ static std::string Name() { return "displacement_lagrangemultiplier_contact_criteria"; } ///@} ///@name Acces ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. std::string Info() const override { return "DisplacementLagrangeMultiplierContactCriteria"; } /// Print information about this object. void PrintInfo(std::ostream& rOStream) const override { rOStream << Info(); } /// Print object's data. void PrintData(std::ostream& rOStream) const override { rOStream << Info(); } ///@} ///@name Friends ///@{ protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ /** * @brief This method assigns settings to member variables * @param ThisParameters Parameters that are assigned to the member variables */ void AssignSettings(const Parameters ThisParameters) override { BaseType::AssignSettings(ThisParameters); // The displacement solution mDispRatioTolerance = ThisParameters["displacement_relative_tolerance"].GetDouble(); mDispAbsTolerance = ThisParameters["displacement_absolute_tolerance"].GetDouble(); // The rotation solution mRotRatioTolerance = ThisParameters["rotation_relative_tolerance"].GetDouble(); mRotAbsTolerance = ThisParameters["rotation_absolute_tolerance"].GetDouble(); // The contact solution mLMRatioTolerance = ThisParameters["contact_displacement_relative_tolerance"].GetDouble(); mLMAbsTolerance = ThisParameters["contact_displacement_absolute_tolerance"].GetDouble(); // Set local flags mOptions.Set(DisplacementLagrangeMultiplierContactCriteria::ENSURE_CONTACT, ThisParameters["ensure_contact"].GetBool()); mOptions.Set(DisplacementLagrangeMultiplierContactCriteria::PRINTING_OUTPUT, ThisParameters["print_convergence_criterion"].GetBool()); mOptions.Set(DisplacementLagrangeMultiplierContactCriteria::TABLE_IS_INITIALIZED, false); mOptions.Set(DisplacementLagrangeMultiplierContactCriteria::ROTATION_DOF_IS_CONSIDERED, false); } ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ Flags mOptions; /// Local flags double mDispRatioTolerance; /// The ratio threshold for the norm of the displacement double mDispAbsTolerance; /// The absolute value threshold for the norm of the displacement double mRotRatioTolerance; /// The ratio threshold for the norm of the rotation double mRotAbsTolerance; /// The absolute value threshold for the norm of the rotation double mLMRatioTolerance; /// The ratio threshold for the norm of the LM double mLMAbsTolerance; /// The absolute value threshold for the norm of the LM std::vector<int> mActiveDofs; /// This vector contains the dofs that are active ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@} ///@name Serialization ///@{ ///@name Private Inquiry ///@{ ///@} ///@name Unaccessible methods ///@{ ///@} }; // Kratos DisplacementLagrangeMultiplierContactCriteria ///@name Local flags creation ///@{ /// Local Flags template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierContactCriteria<TSparseSpace, TDenseSpace>::ENSURE_CONTACT(Kratos::Flags::Create(0)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierContactCriteria<TSparseSpace, TDenseSpace>::PRINTING_OUTPUT(Kratos::Flags::Create(1)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierContactCriteria<TSparseSpace, TDenseSpace>::TABLE_IS_INITIALIZED(Kratos::Flags::Create(2)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierContactCriteria<TSparseSpace, TDenseSpace>::ROTATION_DOF_IS_CONSIDERED(Kratos::Flags::Create(3)); } #endif /* KRATOS_DISPLACEMENT_LAGRANGE_MULTIPLIER_CONTACT_CRITERIA_H */
rawSHA384_fmt_plug.c
/* * This file is part of John the Ripper password cracker, * Copyright (c) 2010 by Solar Designer * based on rawMD4_fmt.c code, with trivial changes by groszek. * * Rewritten Spring 2013, JimF. SSE code added and released with the following terms: * No copyright is claimed, and the software is hereby placed in the public domain. * In case this attempt to disclaim copyright and place the software in the public * domain is deemed null and void, then the software is Copyright (c) 2011 JimF * and it is hereby released to the general public under the following * terms: * * This software may be modified, redistributed, and used for any * purpose, in source and binary forms, with or without modification. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_rawSHA384; #elif FMT_REGISTERS_H john_register_one(&fmt_rawSHA384); #else #include "arch.h" #include "sha2.h" #include "stdint.h" #include "params.h" #include "common.h" #include "johnswap.h" #include "formats.h" #ifdef _OPENMP #ifdef MMX_COEF_SHA512 #define OMP_SCALE 1024 #else #define OMP_SCALE 2048 #endif #include <omp.h> #endif #include "sse-intrinsics.h" #include "memdbg.h" #define FORMAT_LABEL "Raw-SHA384" #define FORMAT_NAME "" #define FORMAT_TAG "$SHA384$" #define TAG_LENGTH (sizeof(FORMAT_TAG) - 1) #ifdef MMX_COEF_SHA512 #define ALGORITHM_NAME SHA512_ALGORITHM_NAME #else #define ALGORITHM_NAME "32/" ARCH_BITS_STR " " SHA2_LIB #endif #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #ifdef MMX_COEF_SHA512 #define PLAINTEXT_LENGTH 111 #else #define PLAINTEXT_LENGTH 125 #endif #define CIPHERTEXT_LENGTH 96 #define BINARY_SIZE 48 #define BINARY_ALIGN MEM_ALIGN_WORD #define SALT_SIZE 0 #define SALT_ALIGN 1 #define MIN_KEYS_PER_CRYPT 1 #ifdef MMX_COEF_SHA512 #define MAX_KEYS_PER_CRYPT MMX_COEF_SHA512 #else #define MAX_KEYS_PER_CRYPT 1 #endif static struct fmt_tests tests[] = { {"a8b64babd0aca91a59bdbb7761b421d4f2bb38280d3a75ba0f21f2bebc45583d446c598660c94ce680c47d19c30783a7", "password"}, {"$SHA384$a8b64babd0aca91a59bdbb7761b421d4f2bb38280d3a75ba0f21f2bebc45583d446c598660c94ce680c47d19c30783a7", "password"}, {"$SHA384$8cafed2235386cc5855e75f0d34f103ccc183912e5f02446b77c66539f776e4bf2bf87339b4518a7cb1c2441c568b0f8", "12345678"}, {"$SHA384$38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b", ""}, {NULL} }; #ifdef MMX_COEF_SHA512 #define GETPOS(i, index) ( (index&(MMX_COEF_SHA512-1))*8 + ((i)&(0xffffffff-7))*MMX_COEF_SHA512 + (7-((i)&7)) + (index>>(MMX_COEF_SHA512>>1))*SHA512_BUF_SIZ*MMX_COEF_SHA512*8 ) static ARCH_WORD_64 (*saved_key)[SHA512_BUF_SIZ*MMX_COEF_SHA512]; static ARCH_WORD_64 (*crypt_out)[8*MMX_COEF_SHA512]; #else static int (*saved_key_length); static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static ARCH_WORD_32 (*crypt_out) [(BINARY_SIZE + sizeof(ARCH_WORD_32) - 1) / sizeof(ARCH_WORD_32)]; #endif static void init(struct fmt_main *self) { #ifdef _OPENMP int omp_t; omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt = omp_t * MIN_KEYS_PER_CRYPT; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt = omp_t * MAX_KEYS_PER_CRYPT; #endif #ifndef MMX_COEF_SHA512 saved_key_length = mem_calloc_tiny(sizeof(*saved_key_length) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); saved_key = mem_calloc_tiny(sizeof(*saved_key) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); crypt_out = mem_calloc_tiny(sizeof(*crypt_out) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); #else saved_key = mem_calloc_tiny(sizeof(*saved_key) * self->params.max_keys_per_crypt/MMX_COEF_SHA512, MEM_ALIGN_SIMD); crypt_out = mem_calloc_tiny(sizeof(*crypt_out) * self->params.max_keys_per_crypt/MMX_COEF_SHA512, MEM_ALIGN_SIMD); #endif } static int valid(char *ciphertext, struct fmt_main *self) { char *p, *q; p = ciphertext; if (!strncmp(p, FORMAT_TAG, TAG_LENGTH)) p += 8; q = p; while (atoi16[ARCH_INDEX(*q)] != 0x7F) q++; return !*q && q - p == CIPHERTEXT_LENGTH; } static char *split(char *ciphertext, int index, struct fmt_main *self) { static char out[TAG_LENGTH + CIPHERTEXT_LENGTH + 1]; if (!strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH)) return ciphertext; memcpy(out, FORMAT_TAG, TAG_LENGTH); memcpy(out + TAG_LENGTH, ciphertext, CIPHERTEXT_LENGTH + 1); strlwr(out + TAG_LENGTH); return out; } static void *binary(char *ciphertext) { static unsigned char *out; int i; if (!out) out = mem_alloc_tiny(BINARY_SIZE, MEM_ALIGN_WORD); ciphertext += TAG_LENGTH; for (i = 0; i < BINARY_SIZE; i++) { out[i] = atoi16[ARCH_INDEX(ciphertext[i*2])] * 16 + atoi16[ARCH_INDEX(ciphertext[i*2 + 1])]; } #ifdef MMX_COEF_SHA512 alter_endianity_to_BE64 (out, BINARY_SIZE/8); #endif return out; } #ifdef MMX_COEF_SHA512 static int get_hash_0 (int index) { return crypt_out[index>>(MMX_COEF_SHA512>>1)][index&(MMX_COEF_SHA512-1)] & 0xf; } static int get_hash_1 (int index) { return crypt_out[index>>(MMX_COEF_SHA512>>1)][index&(MMX_COEF_SHA512-1)] & 0xff; } static int get_hash_2 (int index) { return crypt_out[index>>(MMX_COEF_SHA512>>1)][index&(MMX_COEF_SHA512-1)] & 0xfff; } static int get_hash_3 (int index) { return crypt_out[index>>(MMX_COEF_SHA512>>1)][index&(MMX_COEF_SHA512-1)] & 0xffff; } static int get_hash_4 (int index) { return crypt_out[index>>(MMX_COEF_SHA512>>1)][index&(MMX_COEF_SHA512-1)] & 0xfffff; } static int get_hash_5 (int index) { return crypt_out[index>>(MMX_COEF_SHA512>>1)][index&(MMX_COEF_SHA512-1)] & 0xffffff; } static int get_hash_6 (int index) { return crypt_out[index>>(MMX_COEF_SHA512>>1)][index&(MMX_COEF_SHA512-1)] & 0x7ffffff; } #else static int get_hash_0(int index) { return crypt_out[index][0] & 0xf; } static int get_hash_1(int index) { return crypt_out[index][0] & 0xff; } static int get_hash_2(int index) { return crypt_out[index][0] & 0xfff; } static int get_hash_3(int index) { return crypt_out[index][0] & 0xffff; } static int get_hash_4(int index) { return crypt_out[index][0] & 0xfffff; } static int get_hash_5(int index) { return crypt_out[index][0] & 0xffffff; } static int get_hash_6(int index) { return crypt_out[index][0] & 0x7ffffff; } #endif #ifdef MMX_COEF_SHA512 static void set_key(char *key, int index) { const ARCH_WORD_64 *wkey = (ARCH_WORD_64*)key; ARCH_WORD_64 *keybuffer = &((ARCH_WORD_64 *)saved_key)[(index&(MMX_COEF_SHA512-1)) + (index>>(MMX_COEF_SHA512>>1))*SHA512_BUF_SIZ*MMX_COEF_SHA512]; ARCH_WORD_64 *keybuf_word = keybuffer; unsigned int len; ARCH_WORD_64 temp; len = 0; while((unsigned char)(temp = *wkey++)) { if (!(temp & 0xff00)) { *keybuf_word = JOHNSWAP64((temp & 0xff) | (0x80 << 8)); len++; goto key_cleaning; } if (!(temp & 0xff0000)) { *keybuf_word = JOHNSWAP64((temp & 0xffff) | (0x80 << 16)); len+=2; goto key_cleaning; } if (!(temp & 0xff000000)) { *keybuf_word = JOHNSWAP64((temp & 0xffffff) | (0x80ULL << 24)); len+=3; goto key_cleaning; } if (!(temp & 0xff00000000ULL)) { *keybuf_word = JOHNSWAP64((temp & 0xffffffff) | (0x80ULL << 32)); len+=4; goto key_cleaning; } if (!(temp & 0xff0000000000ULL)) { *keybuf_word = JOHNSWAP64((temp & 0xffffffffffULL) | (0x80ULL << 40)); len+=5; goto key_cleaning; } if (!(temp & 0xff000000000000ULL)) { *keybuf_word = JOHNSWAP64((temp & 0xffffffffffffULL) | (0x80ULL << 48)); len+=6; goto key_cleaning; } if (!(temp & 0xff00000000000000ULL)) { *keybuf_word = JOHNSWAP64((temp & 0xffffffffffffffULL) | (0x80ULL << 56)); len+=7; goto key_cleaning; } *keybuf_word = JOHNSWAP64(temp); len += 8; keybuf_word += MMX_COEF_SHA512; } *keybuf_word = 0x8000000000000000ULL; key_cleaning: keybuf_word += MMX_COEF_SHA512; while(*keybuf_word) { *keybuf_word = 0; keybuf_word += MMX_COEF_SHA512; } keybuffer[15*MMX_COEF_SHA512] = len << 3; } #else static void set_key(char *key, int index) { int len = strlen(key); saved_key_length[index] = len; memcpy(saved_key[index], key, len); } #endif #ifdef MMX_COEF_SHA512 static char *get_key(int index) { unsigned i; ARCH_WORD_64 s; static char out[PLAINTEXT_LENGTH + 1]; char *wucp = (char*)saved_key; s = ((ARCH_WORD_64 *)saved_key)[15*MMX_COEF_SHA512 + (index&(MMX_COEF_SHA512-1)) + (index>>(MMX_COEF_SHA512>>1))*SHA512_BUF_SIZ*MMX_COEF_SHA512] >> 3; for(i=0;i<(unsigned)s;i++) out[i] = wucp[ GETPOS(i, index) ]; out[i] = 0; return out; } #else static char *get_key(int index) { saved_key[index][saved_key_length[index]] = 0; return saved_key[index]; } #endif static int crypt_all(int *pcount, struct db_salt *salt) { int count = *pcount; int index = 0; #ifdef _OPENMP #ifdef MMX_COEF_SHA512 int inc = MMX_COEF_SHA512; #else int inc = 1; #endif #pragma omp parallel for for (index = 0; index < count; index += inc) #endif { #ifdef MMX_COEF_SHA512 SSESHA512body(&saved_key[index/MMX_COEF_SHA512], crypt_out[index/MMX_COEF_SHA512], NULL, SSEi_MIXED_IN|SSEi_CRYPT_SHA384); #else SHA512_CTX ctx; SHA384_Init(&ctx); SHA384_Update(&ctx, saved_key[index], saved_key_length[index]); SHA384_Final((unsigned char *)crypt_out[index], &ctx); #endif } return count; } static int cmp_all(void *binary, int count) { int index; for (index = 0; index < count; index++) #ifdef MMX_COEF_SHA512 if (((ARCH_WORD_64 *) binary)[0] == crypt_out[index>>(MMX_COEF_SHA512>>1)][index&(MMX_COEF_SHA512-1)]) #else if ( ((ARCH_WORD_32*)binary)[0] == crypt_out[index][0] ) #endif return 1; return 0; } static int cmp_one(void *binary, int index) { #ifdef MMX_COEF_SHA512 int i; for (i = 0; i < BINARY_SIZE/sizeof(ARCH_WORD_64); i++) if (((ARCH_WORD_64 *) binary)[i] != crypt_out[index>>(MMX_COEF_SHA512>>1)][(index&(MMX_COEF_SHA512-1))+i*MMX_COEF_SHA512]) return 0; return 1; #else return !memcmp(binary, crypt_out[index], BINARY_SIZE); #endif } static int cmp_exact(char *source, int index) { return 1; } struct fmt_main fmt_rawSHA384 = { { FORMAT_LABEL, FORMAT_NAME, "SHA384 " ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 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 | FMT_SPLIT_UNIFIES_CASE, #if FMT_MAIN_VERSION > 11 { NULL }, #endif tests }, { init, fmt_default_done, fmt_default_reset, fmt_default_prepare, valid, split, binary, fmt_default_salt, #if FMT_MAIN_VERSION > 11 { NULL }, #endif 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 }, fmt_default_salt_hash, fmt_default_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 */
zgbmm.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @precisions normal z -> s d c * **/ #include "plasma.h" #include "plasma_async.h" #include "plasma_context.h" #include "plasma_descriptor.h" #include "plasma_internal.h" #include "plasma_tuning.h" #include "plasma_types.h" #include "plasma_workspace.h" /***************************************************************************//** * * @ingroup plasma_gbmm * * Performs one of the matrix-matrix operations * * \f[ C = \alpha [op( A )\times op( B )] + \beta C, \f] * * where op( X ) is one of: * \f[ op( X ) = X, \f] * \f[ op( X ) = X^T, \f] * \f[ op( X ) = X^H, \f] * * alpha and beta are scalars, and A, B and C are matrices, with op( A ) * an m-by-k band matrix, op( B ) a k-by-n matrix and C an m-by-n matrix. * ******************************************************************************* * * @param[in] transa * - PlasmaNoTrans: A is not transposed, * - PlasmaTrans: A is transposed, * - PlasmaConjTrans: A is conjugate transposed. * * @param[in] transb * - PlasmaNoTrans: B is not transposed, * - PlasmaTrans: B is transposed, * - PlasmaConjTrans: B is conjugate transposed. * * @param[in] m * The number of rows of the matrix op( A ) and of the matrix C. * m >= 0. * * @param[in] n * The number of columns of the matrix op( B ) and of the matrix C. * n >= 0. * * @param[in] k * The number of columns of the matrix op( A ) and the number of rows * of the matrix op( B ). k >= 0. * * @param[in] kl * the lower bandwidth (below diagonal) of band matrix A * * @param[in] ku * the upper bandwidth (above diagonal) of band matrix A * * @param[in] alpha * The scalar alpha. * * @param[in] pA * An lda-by-ka matrix, where ka is k when transa = PlasmaNoTrans, * and is m otherwise. * * @param[in] lda * The leading dimension of the array A. * When transa = PlasmaNoTrans, lda >= max(1,m), * otherwise, lda >= max(1,k). * * @param[in] pB * An ldb-by-kb matrix, where kb is n when transb = PlasmaNoTrans, * and is k otherwise. * * @param[in] ldb * The leading dimension of the array B. * When transb = PlasmaNoTrans, ldb >= max(1,k), * otherwise, ldb >= max(1,n). * * @param[in] beta * The scalar beta. * * @param[in,out] pC * An ldc-by-n matrix. On exit, the array is overwritten by the m-by-n * matrix ( alpha*op( A )*op( B ) + beta*C ). * * @param[in] ldc * The leading dimension of the array C. ldc >= max(1,m). * ******************************************************************************* * * @retval PlasmaSuccess successful exit * ******************************************************************************* * * @sa plasma_omp_zgbmm * @sa plasma_cgbmm * @sa plasma_dgbmm * @sa plasma_sgbmm * ******************************************************************************/ int plasma_zgbmm(plasma_enum_t transa, plasma_enum_t transb, int m, int n, int k, int kl, int ku, plasma_complex64_t alpha, plasma_complex64_t *pA, int lda, plasma_complex64_t *pB, int ldb, plasma_complex64_t beta, plasma_complex64_t *pC, int ldc) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_error("PLASMA not initialized"); return PlasmaErrorNotInitialized; } // Check input arguments. if ((transa != PlasmaNoTrans) && (transa != PlasmaTrans) && (transa != PlasmaConjTrans)) { plasma_error("illegal value of transa"); return -1; } if ((transb != PlasmaNoTrans) && (transb != PlasmaTrans) && (transb != PlasmaConjTrans)) { plasma_error("illegal value of transb"); return -2; } if (m < 0) { plasma_error("illegal value of m"); return -3; } if (n < 0) { plasma_error("illegal value of n"); return -4; } if (k < 0) { plasma_error("illegal value of k"); return -5; } if ((kl < 0) || (kl > m-1)) { plasma_error("illegal value of kl"); return -6; } if ((ku < 0) || (ku > k-1)) { plasma_error("illegal value of ku"); return -7; } int am, an; int bm, bn; if (transa == PlasmaNoTrans) { am = m; an = k; } else { am = k; an = m; } if (transb == PlasmaNoTrans) { bm = k; bn = n; } else { bm = n; bn = k; } if (lda < imax(1, am)) { plasma_error("illegal value of lda"); return -8; } if (ldb < imax(1, bm)) { plasma_error("illegal value of ldb"); return -10; } if (ldc < imax(1, m)) { plasma_error("illegal value of ldc"); return -13; } // quick return if (m == 0 || n == 0 || ((alpha == 0.0 || k == 0) && beta == 1.0)) return PlasmaSuccess; // Tune parameters. if (plasma->tuning) plasma_tune_gbmm(plasma, PlasmaComplexDouble, m, n, k, kl, ku); // Set tiling parameters. int nb = plasma->nb; // Create tile matrices. plasma_desc_t A; plasma_desc_t B; plasma_desc_t C; int retval; int tku = (ku+kl+nb-1)/nb; /* number of tiles in upper band above diagonal PLASMA conventions allow extra space for tku for this application, could replace am with smaller number of rows (( (ku+nb-1)/nb )) */ int tkl = (kl+nb-1)/nb; // number of tiles in lower band below diagonal int lm = (tku+tkl+1)*nb; // reduced number of "rows" in the matrix retval = plasma_desc_general_band_create(PlasmaComplexDouble,PlasmaGeneral, nb,nb, lm, an, 0, 0, am, an, kl, ku, &A); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); return retval; } retval = plasma_desc_general_create(PlasmaComplexDouble, nb, nb, bm, bn, 0, 0, bm, bn, &B); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); plasma_desc_destroy(&A); return retval; } retval = plasma_desc_general_create(PlasmaComplexDouble, nb, nb, m, n, 0, 0, m, n, &C); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); plasma_desc_destroy(&A); plasma_desc_destroy(&B); return retval; } // Initialize sequence. plasma_sequence_t sequence; retval = plasma_sequence_init(&sequence); // Initialize request. plasma_request_t request; retval = plasma_request_init(&request); // asynchronous block #pragma omp parallel #pragma omp master { // Translate to tile layout. plasma_omp_zgb2desc(pA, lda, A, &sequence, &request); plasma_omp_zgb2desc(pB, ldb, B, &sequence, &request); plasma_omp_zgb2desc(pC, ldc, C, &sequence, &request); // Call the tile async function. plasma_omp_zgbmm(transa, transb, alpha, A, B, beta, C, &sequence, &request); // Translate back to LAPACK layout. plasma_omp_zdesc2ge(C, pC, ldc, &sequence, &request); } // implicit synchronization // Free matrices in tile layout. plasma_desc_destroy(&A); plasma_desc_destroy(&B); plasma_desc_destroy(&C); // Return status. int status = sequence.status; return status; } /***************************************************************************//** * * @ingroup plasma_gbmm * * Performs matrix multiplication. * Non-blocking tile version of plasma_zgbmm(). * May return before the computation is finished. * Operates on matrices stored by tiles. * All matrices are passed through descriptors. * All dimensions are taken from the descriptors. * Allows for pipelining of operations at runtime. * ******************************************************************************* * * @param[in] transa * - PlasmaNoTrans: A is not transposed, * - PlasmaTrans: A is transposed, * - PlasmaConjTrans: A is conjugate transposed. * * @param[in] transb * - PlasmaNoTrans: B is not transposed, * - PlasmaTrans: B is transposed, * - PlasmaConjTrans: B is conjugate transposed. * * @param[in] alpha * The scalar alpha. * * @param[in] A * Descriptor of matrix A. * * @param[in] B * Descriptor of matrix B. * * @param[in] beta * The scalar beta. * * @param[in,out] C * Descriptor of matrix C. * * @param[in] sequence * Identifies the sequence of function calls that this call belongs to * (for completion checks and exception handling purposes). Check * the sequence->status for errors. * * @param[out] request * Identifies this function call (for exception handling purposes). * * @retval void * Errors are returned by setting sequence->status and * request->status to error values. The sequence->status and * request->status should never be set to PlasmaSuccess (the * initial values) since another async call may be setting a * failure value at the same time. * ******************************************************************************* * * @sa plasma_zgbmm * @sa plasma_omp_cgbmm * @sa plasma_omp_dgbmm * @sa plasma_omp_sgbmm * ******************************************************************************/ void plasma_omp_zgbmm(plasma_enum_t transa, plasma_enum_t transb, plasma_complex64_t alpha, plasma_desc_t A, plasma_desc_t B, plasma_complex64_t beta, plasma_desc_t C, plasma_sequence_t *sequence, plasma_request_t *request) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_error("PLASMA not initialized"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // Check input arguments. if ((transa != PlasmaNoTrans) && (transa != PlasmaTrans) && (transa != PlasmaConjTrans)) { plasma_error("illegal value of transa"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if ((transb != PlasmaNoTrans) && (transb != PlasmaTrans) && (transb != PlasmaConjTrans)) { plasma_error("illegal value of transb"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(A) != PlasmaSuccess) { plasma_error("invalid A"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(B) != PlasmaSuccess) { plasma_error("invalid B"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(C) != PlasmaSuccess) { plasma_error("invalid C"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (sequence == NULL) { plasma_error("NULL sequence"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (request == NULL) { plasma_error("NULL request"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // quick return int k = transa == PlasmaNoTrans ? A.n : A.m; if (C.m == 0 || C.n == 0 || ((alpha == 0.0 || k == 0) && beta == 1.0)) return; // Call the parallel function. // general band is part of this function: no need to create pzgbmm. plasma_pzgemm(transa, transb, alpha, A, B, beta, C, sequence, request); }
SpatialAveragePooling.c
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "THNN/generic/SpatialAveragePooling.c" #else #include <THNN/generic/pooling_shape.h> #include <algorithm> static inline void THNN_(SpatialAveragePooling_shapeCheck)( THTensor *input, THTensor *gradOutput, int kH, int kW, int dH, int dW, int padH, int padW, bool ceil_mode) { THArgCheck(kW > 0 && kH > 0, 5, "kernel size should be greater than zero, but got kH: %d kW: %d", kH, kW); THArgCheck(dW > 0 && dH > 0, 8, "stride should be greater than zero, but got dH: %d dW: %d", dH, dW); int ndim = input->dim(); int dimf = 0; int dimh = 1; int dimw = 2; if (ndim == 4) { dimf++; dimh++; dimw++; } THNN_ARGCHECK(!input->is_empty() && (ndim == 3 || ndim == 4), 2, input, "non-empty 3D or 4D input tensor expected but got: %s"); THArgCheck(kW/2 >= padW && kH/2 >= padH, 2, "pad should be smaller than half of kernel size, but got " "padW = %d, padH = %d, kW = %d, kH = %d", padW, padH, kW, kH); int64_t nInputPlane = input->size(dimh-1); int64_t inputHeight = input->size(dimh); int64_t inputWidth = input->size(dimw); int64_t nOutputPlane = nInputPlane; int64_t outputHeight = pooling_output_shape<int64_t>(inputHeight, kH, padH, dH, 1, ceil_mode); int64_t outputWidth = pooling_output_shape<int64_t>(inputWidth, kW, padW, dW, 1, ceil_mode); if (outputWidth < 1 || outputHeight < 1) THError("Given input size: (%dx%dx%d). " "Calculated output size: (%dx%dx%d). Output size is too small", nInputPlane,inputHeight,inputWidth,nInputPlane,outputHeight,outputWidth); if (gradOutput != NULL) { THNN_CHECK_DIM_SIZE(gradOutput, ndim, dimf, nOutputPlane); THNN_CHECK_DIM_SIZE(gradOutput, ndim, dimh, outputHeight); THNN_CHECK_DIM_SIZE(gradOutput, ndim, dimw, outputWidth); } } void THNN_(SpatialAveragePooling_updateOutput)( THNNState *state, THTensor *input, THTensor *output, int kW, int kH, int dW, int dH, int padW, int padH, bool ceil_mode, bool count_include_pad) { scalar_t *output_data; scalar_t *input_data; int dimw = 2; int dimh = 1; int dimc = 0; int64_t nbatch = 1; int64_t inputWidth; int64_t inputHeight; int64_t outputWidth; int64_t outputHeight; int64_t nInputPlane; // number of channels (or colors) int64_t k; THNN_(SpatialAveragePooling_shapeCheck) (input, NULL, kH, kW, dH, dW, padH, padW, ceil_mode); if (input->dim() == 4) { nbatch = input->size(0); dimw++; dimh++; dimc++; } inputWidth = input->size(dimw); inputHeight = input->size(dimh); nInputPlane = input->size(dimc); outputWidth = pooling_output_shape<int64_t>(inputWidth, kW, padW, dW, 1, ceil_mode); outputHeight = pooling_output_shape<int64_t>(inputHeight, kH, padH, dH, 1, ceil_mode); if (input->dim() == 3) THTensor_(resize3d)(output, nInputPlane, outputHeight, outputWidth); else THTensor_(resize4d)(output, input->size(0), nInputPlane, outputHeight, outputWidth); input = THTensor_(newContiguous)(input); THArgCheck(THTensor_(isContiguous)(output), 3, "output must be contiguous"); input_data = input->data<scalar_t>(); output_data = output->data<scalar_t>(); #pragma omp parallel for private(k) for(k = 0; k < nInputPlane; k++) { int64_t p; for(p = 0; p < nbatch; p++) { int64_t xx, yy; /* For all output pixels... */ scalar_t *ptr_output = output_data + p*nInputPlane*outputWidth*outputHeight + k*outputWidth*outputHeight; scalar_t *ptr_input = input_data + p*nInputPlane*inputWidth*inputHeight + k*inputWidth*inputHeight; int64_t i; for(i = 0; i < outputWidth*outputHeight; i++) ptr_output[i] = 0; for(yy = 0; yy < outputHeight; yy++) { for(xx = 0; xx < outputWidth; xx++) { /* Compute the mean of the input image... */ int64_t hstart = yy * dH - padH; int64_t wstart = xx * dW - padW; int64_t hend = std::min(hstart + kH, inputHeight + padH); int64_t wend = std::min(wstart + kW, inputWidth + padW); int pool_size = (hend - hstart) * (wend - wstart); hstart = std::max(hstart, (int64_t) 0); wstart = std::max(wstart, (int64_t) 0); hend = std::min(hend, inputHeight); wend = std::min(wend, inputWidth); scalar_t sum = 0; int divide_factor; if(count_include_pad) divide_factor = pool_size; else divide_factor = (hend - hstart) * (wend - wstart); int64_t kx, ky; for(ky = hstart; ky < hend; ky++) { for(kx = wstart; kx < wend; kx++) sum += ptr_input[ky*inputWidth + kx]; } /* Update output */ *ptr_output++ += sum/divide_factor; } } } } c10::raw::intrusive_ptr::decref(input); } void THNN_(SpatialAveragePooling_updateGradInput)( THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradInput, int kW, int kH, int dW, int dH, int padW, int padH, bool ceil_mode, bool count_include_pad) { int dimw = 2; int dimh = 1; int dimc = 0; int64_t nbatch = 1; int64_t ndim = 3; int64_t inputWidth; int64_t inputHeight; int64_t outputWidth; int64_t outputHeight; int64_t nInputPlane; // number of channels (or colors) scalar_t *gradOutput_data; scalar_t *gradInput_data; int64_t k; THNN_(SpatialAveragePooling_shapeCheck) (input, gradOutput, kH, kW, dH, dW, padH, padW, ceil_mode); if (input->dim() == 4) { nbatch = input->size(0); dimw++; dimh++; dimc++; ndim = 4; } inputWidth = input->size(dimw); inputHeight = input->size(dimh); nInputPlane = input->size(dimc); outputWidth = pooling_output_shape<int64_t>(inputWidth, kW, padW, dW, 1, ceil_mode); outputHeight = pooling_output_shape<int64_t>(inputHeight, kH, padH, dH, 1, ceil_mode); THNN_CHECK_DIM_SIZE(gradOutput, ndim, dimh, outputHeight); THNN_CHECK_DIM_SIZE(gradOutput, ndim, dimw, outputWidth); THTensor_(resizeAs)(gradInput, input); gradOutput = THTensor_(newContiguous)(gradOutput); THArgCheck(THTensor_(isContiguous)(gradInput), 4, "gradInput must be contiguous"); gradInput_data = gradInput->data<scalar_t>(); gradOutput_data = gradOutput->data<scalar_t>(); #pragma omp parallel for private(k) for(k = 0; k < nInputPlane; k++) { int64_t p; for(p = 0; p < nbatch; p++) { scalar_t *ptr_gradOutput = gradOutput_data + p*nInputPlane*outputHeight*outputWidth + k*outputWidth*outputHeight; int64_t xx, yy; scalar_t* ptr_gi = gradInput_data + p*nInputPlane*inputWidth*inputHeight + k*inputWidth*inputHeight; scalar_t *ptr_gradInput = gradInput_data + p*nInputPlane*inputWidth*inputHeight + k*inputWidth*inputHeight; int64_t i; for(i=0; i<inputWidth*inputHeight; i++) ptr_gi[i] = 0.0; for(yy = 0; yy < outputHeight; yy++) { for(xx = 0; xx < outputWidth; xx++) { int64_t hstart = yy * dH - padH; int64_t wstart = xx * dW - padW; int64_t hend = std::min(hstart + kH, inputHeight + padH); int64_t wend = std::min(wstart + kW, inputWidth + padW); int pool_size = (hend - hstart) * (wend - wstart); hstart = std::max(hstart, (int64_t) 0); wstart = std::max(wstart, (int64_t) 0); hend = std::min(hend, inputHeight); wend = std::min(wend, inputWidth); scalar_t z = *ptr_gradOutput++; int divide_factor; if(count_include_pad) divide_factor = pool_size; else divide_factor = (hend - hstart) * (wend - wstart); int64_t kx, ky; for(ky = hstart ; ky < hend; ky++) { for(kx = wstart; kx < wend; kx++) ptr_gradInput[ky*inputWidth + kx] += z/divide_factor; } } } } } c10::raw::intrusive_ptr::decref(gradOutput); } #endif
GnatNearestNeighbors.h
// // Copyright (c) 2009, Markus Rickert // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #ifndef RL_MATH_GNATNEARESTNEIGHBORS_H #define RL_MATH_GNATNEARESTNEIGHBORS_H #include <algorithm> #include <iterator> #include <limits> #include <random> #include <type_traits> #include <utility> #include <vector> #include <boost/optional.hpp> namespace rl { namespace math { /** * Geometric Near-Neighbor Access Tree (GNAT). * * Sergey Brin. Near neighbor search in large metric spaces. In Proceedings of * the International Conference on Very Large Data Bases, pages 574-584, * Zurich, Switzerland, September, 1985. * * http://www.vldb.org/conf/1995/P574.PDF */ template<typename MetricT> class GnatNearestNeighbors { private: struct Node; public: typedef const typename MetricT::Value& const_reference; typedef ::std::ptrdiff_t difference_type; typedef typename MetricT::Value& reference; typedef ::std::size_t size_type; typedef typename MetricT::Value value_type; typedef typename MetricT::Distance Distance; typedef MetricT Metric; typedef typename MetricT::Value Value; typedef ::std::pair<Distance, Value> Neighbor; explicit GnatNearestNeighbors(const Metric& metric) : checks(), generator(::std::random_device()()), metric(metric), nodeDataMax(50), nodeDegree(8), nodeDegreeMax(12), nodeDegreeMin(4), root(0, 0, nodeDegree, nodeDataMax, true), values(0) { } explicit GnatNearestNeighbors(Metric&& metric = Metric()) : checks(), generator(::std::random_device()()), metric(::std::move(metric)), nodeDataMax(50), nodeDegree(8), nodeDegreeMax(12), nodeDegreeMin(4), root(0, 0, nodeDegree, nodeDataMax, true), values(0) { } template<typename InputIterator> GnatNearestNeighbors(InputIterator first, InputIterator last, const Metric& metric) : checks(), generator(::std::random_device()()), metric(metric), nodeDataMax(50), nodeDegree(8), nodeDegreeMax(12), nodeDegreeMin(4), root(first, last, 0, 0, nodeDegree, nodeDataMax, true), values(::std::distance(first, last)) { if (this->root.data.size() > this->nodeDataMax && this->root.data.size() > this->root.degree) { this->split(this->root); } } template<typename InputIterator> GnatNearestNeighbors(InputIterator first, InputIterator last, Metric&& metric = Metric()) : checks(), generator(::std::random_device()()), metric(::std::move(metric)), nodeDataMax(50), nodeDegree(8), nodeDegreeMax(12), nodeDegreeMin(4), root(first, last, nullptr, 0, 0, nodeDegree, nodeDataMax, true), values(::std::distance(first, last)) { if (this->root.data.size() > this->nodeDataMax && this->root.data.size() > this->root.degree) { this->split(this->root); } } ~GnatNearestNeighbors() { } void clear() { this->root.children.clear(); this->root.children.reserve(this->nodeDegree); this->root.data.clear(); this->root.data.reserve(this->nodeDataMax + 1); this->values = 0; } ::std::vector<Value> data() const { ::std::vector<Value> data; data.reserve(this->values); this->data(this->root, data); return data; } bool empty() const { return this->root.removed && this->root.data.empty() && this->root.children.empty(); } ::boost::optional< ::std::size_t> getChecks() const { return this->checks; } ::std::size_t getNodeDataMax() const { return this->nodeDataMax; } ::std::size_t getNodeDegree() const { return this->nodeDegree; } ::std::size_t getNodeDegreeMax() const { return this->nodeDegreeMax; } ::std::size_t getNodeDegreeMin() const { return this->nodeDegreeMin; } template<typename InputIterator> void insert(InputIterator first, InputIterator last) { if (this->empty()) { this->root.data.insert(this->root.data.end(), first, last); if (this->root.data.size() > this->nodeDataMax && this->root.data.size() > this->root.degree) { this->split(this->root); } this->values += ::std::distance(first, last); } else { for (InputIterator i = first; i != last; ++i) { this->push(*i); } } } ::std::vector<Neighbor> nearest(const Value& query, const ::std::size_t& k, const bool& sorted = true) const { return this->search(query, &k, nullptr, sorted); } void push(const Value& value) { this->push(this->root, value); ++this->values; } ::std::vector<Neighbor> radius(const Value& query, const Distance& radius, const bool& sorted = true) const { return this->search(query, nullptr, &radius, sorted); } void seed(const ::std::mt19937::result_type& value) { this->generator.seed(value); } void setChecks(const ::boost::optional< ::std::size_t>& checks) { this->checks = checks; } void setNodeDataMax(const ::std::size_t& nodeDataMax) { this->nodeDataMax = nodeDataMax; } void setNodeDegree(const ::std::size_t& nodeDegree) { this->nodeDegree = nodeDegree; } void setNodeDegreeMax(const ::std::size_t& nodeDegreeMax) { this->nodeDegreeMax = nodeDegreeMax; } void setNodeDegreeMin(const ::std::size_t& nodeDegreeMin) { this->nodeDegreeMin = nodeDegreeMin; } ::std::size_t size() const { return this->values; } void swap(GnatNearestNeighbors& other) { using ::std::swap; swap(this->generator, other.generator); swap(this->metric, other.metric); swap(this->nodeDegree, other.nodeDegree); swap(this->nodeDegreeMax, other.nodeDegreeMax); swap(this->nodeDegreeMin, other.nodeDegreeMin); swap(this->nodeDataMax, other.nodeDataMax); swap(this->root, other.root); swap(this->values, other.values); } friend void swap(GnatNearestNeighbors& lhs, GnatNearestNeighbors& rhs) { lhs.swap(rhs); } protected: private: typedef ::std::pair<Distance, const Node*> Branch; struct BranchCompare { bool operator()(const Branch& lhs, const Branch& rhs) const { return lhs.first - lhs.second->max[lhs.second->index] > rhs.first - rhs.second->max[rhs.second->index]; } }; struct NeighborCompare { bool operator()(const Neighbor& lhs, const Neighbor& rhs) const { return lhs.first < rhs.first; } }; struct Node { Node(const ::std::size_t& index, const ::std::size_t& siblings, const ::std::size_t& degree, const ::std::size_t& capacity, const bool& removed = false) : children(), data(), degree(degree), index(index), max(siblings + 1, -::std::numeric_limits<Distance>::infinity()), min(siblings + 1, ::std::numeric_limits<Distance>::infinity()), pivot(), removed(removed) { this->children.reserve(degree); this->data.reserve(capacity + 1); } template<typename InputIterator> Node(InputIterator first, InputIterator last, const ::std::size_t& index, const ::std::size_t& siblings, const ::std::size_t& degree, const ::std::size_t& capacity, const bool& removed = false) : children(), data(first, last), degree(degree), index(index), max(siblings + 1, -::std::numeric_limits<Distance>::infinity()), min(siblings + 1, ::std::numeric_limits<Distance>::infinity()), pivot(), removed(removed) { this->children.reserve(degree); this->data.reserve(capacity + 1); } ~Node() { } void swap(Node& other) { using ::std::swap; swap(this->children, other.children); swap(this->data, other.data); swap(this->degree, other.degree); swap(this->index, other.index); swap(this->max, other.max); swap(this->min, other.min); swap(this->pivot, other.pivot); swap(this->removed, other.removed); } friend void swap(Node& lhs, Node& rhs) { lhs.swap(rhs); } ::std::vector<Node> children; ::std::vector<Value> data; ::std::size_t degree; ::std::size_t index; ::std::vector<Distance> max; ::std::vector<Distance> min; Value pivot; bool removed; }; void choose(const Node& node, ::std::vector< ::std::size_t>& centers, ::std::vector< ::std::vector<Distance>>& distances) { ::std::size_t k = node.degree; ::std::vector<Distance> min(node.data.size(), ::std::numeric_limits<Distance>::infinity()); ::std::uniform_int_distribution< ::std::size_t> distribution(0, node.data.size() - 1); centers[0] = distribution(this->generator); for (::std::size_t i = 0; i < k - 1; ++i) { Distance max = Distance(); for (::std::size_t j = 0; j < node.data.size(); ++j) { distances[i][j] = j != centers[i] ? this->metric(node.data[j], node.data[centers[i]]) : 0; min[j] = ::std::min(min[j], distances[i][j]); if (min[j] > max) { max = min[j]; centers[i + 1] = j; } } } for (::std::size_t j = 0; j < node.data.size(); ++j) { distances[k - 1][j] = this->metric(node.data[j], node.data[centers[k - 1]]); } } void data(const Node& node, ::std::vector<Value>& data) const { data.insert(data.end(), node.data.begin(), node.data.end()); for (::std::size_t i = 0; i < node.children.size(); ++i) { data.push_back(node.children[i].pivot); this->data(node.children[i], data); } } void push(Node& node, const Value& value) { if (node.children.empty()) { node.data.push_back(value); if (node.data.size() > this->nodeDataMax && node.data.size() > node.degree) { this->split(node); } } else { ::std::vector<Distance> distances(node.children.size()); ::std::size_t index = 0; Distance min = ::std::numeric_limits<Distance>::infinity(); for (::std::size_t i = 0; i < node.children.size(); ++i) { distances[i] = this->metric(value, node.children[i].pivot); if (distances[i] < min) { index = i; min = distances[i]; } } for (::std::size_t i = 0; i < node.children.size(); ++i) { node.children[i].max[index] = ::std::max(node.children[i].max[index], distances[i]); node.children[i].min[index] = ::std::min(node.children[i].min[index], distances[i]); } this->push(node.children[index], value); } } ::std::vector<Neighbor> search(const Value& query, const ::std::size_t* k, const Distance* radius, const bool& sorted) const { ::std::vector<Neighbor> neighbors; neighbors.reserve(nullptr != k ? *k : this->values); ::std::size_t checks = 0; ::std::vector<Branch> branches; this->search(this->root, query, k, radius, branches, neighbors, checks); while (!branches.empty() && (!this->checks || checks < this->checks)) { Branch branch = branches.front(); ::std::pop_heap(branches.begin(), branches.end(), BranchCompare()); branches.pop_back(); if (nullptr == k || *k == neighbors.size()) { Distance distance = nullptr != radius ? *radius : neighbors.front().first; if (branch.first - distance > branch.second->max[branch.second->index] || branch.first + distance < branch.second->min[branch.second->index]) { continue; } } this->search(*branch.second, query, k, radius, branches, neighbors, checks); } if (sorted) { ::std::sort_heap(neighbors.begin(), neighbors.end(), NeighborCompare()); } if (nullptr == k) { neighbors.shrink_to_fit(); } return neighbors; } void search(const Node& node, const Value& query, const ::std::size_t* k, const Distance* radius, ::std::vector<Branch>& branches, ::std::vector<Neighbor>& neighbors, ::std::size_t& checks) const { if (node.children.empty()) { for (::std::size_t i = 0; i < node.data.size(); ++i) { Distance distance = this->metric(query, node.data[i]); if (nullptr == k || neighbors.size() < *k || distance < neighbors.front().first) { if (nullptr == radius || distance < *radius) { if (nullptr != k && *k == neighbors.size()) { ::std::pop_heap(neighbors.begin(), neighbors.end(), NeighborCompare()); neighbors.pop_back(); } #if (defined(_MSC_VER) && _MSC_VER < 1800) || (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ < 8) neighbors.push_back(::std::make_pair(distance, node.data[i])); #else neighbors.emplace_back(::std::piecewise_construct, ::std::forward_as_tuple(distance), ::std::forward_as_tuple(node.data[i])); #endif ::std::push_heap(neighbors.begin(), neighbors.end(), NeighborCompare()); } } if (this->checks && ++checks > this->checks) { return; } } } else { ::std::vector<Distance> distances(node.children.size()); ::std::vector<bool> removed(node.children.size(), false); for (::std::size_t i = 0; i < node.children.size(); ++i) { if (!removed[i]) { distances[i] = this->metric(query, node.children[i].pivot); if (!node.children[i].removed) { if (nullptr == k || neighbors.size() < *k || distances[i] < neighbors.front().first) { if (nullptr == radius || distances[i] < *radius) { if (nullptr != k && *k == neighbors.size()) { ::std::pop_heap(neighbors.begin(), neighbors.end(), NeighborCompare()); neighbors.pop_back(); } #if (defined(_MSC_VER) && _MSC_VER < 1800) || (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ < 8) neighbors.push_back(::std::make_pair(distances[i], node.children[i].pivot)); #else neighbors.emplace_back(::std::piecewise_construct, ::std::forward_as_tuple(distances[i]), ::std::forward_as_tuple(node.children[i].pivot)); #endif ::std::push_heap(neighbors.begin(), neighbors.end(), NeighborCompare()); } } } if (nullptr == k || *k == neighbors.size()) { Distance distance = nullptr != radius ? *radius : neighbors.front().first; for (::std::size_t j = 0; j < node.children.size(); ++j) { if (i != j && !removed[j]) { if (distances[i] - distance > node.children[i].max[j] || distances[i] + distance < node.children[i].min[j]) { removed[j] = true; } } } } if (this->checks && ++checks > this->checks) { return; } } } for (::std::size_t i = 0; i < node.children.size(); ++i) { if (!removed[i]) { Distance distance = nullptr != radius ? *radius : neighbors.front().first; if (distances[i] - distance <= node.children[i].max[i] && distances[i] + distance >= node.children[i].min[i]) { #if defined(_MSC_VER) && _MSC_VER < 1800 branches.push_back(::std::make_pair(distances[i], &node.children[i])); #else branches.emplace_back(distances[i], &node.children[i]); #endif ::std::push_heap(branches.begin(), branches.end(), BranchCompare()); } } } } } void split(Node& node) { ::std::vector< ::std::vector<Distance>> distances(node.degree, ::std::vector<Distance>(node.data.size())); ::std::vector< ::std::size_t> centers(node.degree); this->choose(node, centers, distances); for (::std::size_t i = 0; i < centers.size(); ++i) { #if defined(_MSC_VER) && _MSC_VER < 1800 node.children.push_back(Node(i, node.degree - 1, this->nodeDegree, this->nodeDataMax)); #else node.children.emplace_back(i, node.degree - 1, this->nodeDegree, this->nodeDataMax); #endif node.children[i].pivot = ::std::move(node.data[centers[i]]); } for (::std::size_t i = 0; i < node.data.size(); ++i) { ::std::size_t index = 0; Distance min = ::std::numeric_limits<Distance>::infinity(); for (::std::size_t j = 0; j < centers.size(); ++j) { Distance distance = distances[j][i]; if (distance < min) { index = j; min = distance; } } for (::std::size_t j = 0; j < centers.size(); ++j) { if (i != centers[j]) { node.children[j].max[index] = ::std::max(node.children[j].max[index], distances[j][i]); node.children[j].min[index] = ::std::min(node.children[j].min[index], distances[j][i]); } } if (i != centers[index]) { node.children[index].data.push_back(::std::move(node.data[i])); } } for (::std::size_t i = 0; i < node.children.size(); ++i) { node.children[i].degree = ::std::min(::std::max(this->nodeDegree * node.children[i].data.size() / node.data.size(), this->nodeDegreeMin), this->nodeDegreeMax); if (node.children[i].data.empty()) { node.children[i].max[i] = Distance(); node.children[i].min[i] = Distance(); } } ::std::size_t size = node.data.size(); node.data.clear(); node.data.shrink_to_fit(); #pragma omp parallel for if (size > 2 * this->nodeDataMax) #if defined(_OPENMP) && _OPENMP < 200805 for (::std::ptrdiff_t i = 0; i < node.children.size(); ++i) #else for (::std::size_t i = 0; i < node.children.size(); ++i) #endif { if (node.children[i].data.size() > this->nodeDataMax && node.children[i].data.size() > node.children[i].degree) { this->split(node.children[i]); } } } ::boost::optional< ::std::size_t> checks; ::std::mt19937 generator; Metric metric; ::std::size_t nodeDataMax; ::std::size_t nodeDegree; ::std::size_t nodeDegreeMax; ::std::size_t nodeDegreeMin; Node root; ::std::size_t values; }; } } #endif // RL_MATH_GNATNEARESTNEIGHBORS_H
clean.h
/**************************************************************************** * VCGLib o o * * Visual and Computer Graphics Library o o * * _ O _ * * Copyright(C) 2004 \/)\/ * * Visual Computing Lab /\/| * * ISTI - Italian National Research Council | * * \ * * All rights reserved. * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License (http://www.gnu.org/licenses/gpl.txt) * * for more details. * * * ****************************************************************************/ #ifndef __VCGLIB_CLEAN #define __VCGLIB_CLEAN // VCG headers #include <vcg/complex/complex.h> #include <vcg/simplex/face/pos.h> #include <vcg/simplex/face/topology.h> #include <vcg/simplex/edge/topology.h> #include <vcg/complex/algorithms/closest.h> #include <vcg/space/index/grid_static_ptr.h> #include <vcg/space/index/spatial_hashing.h> #include <vcg/complex/algorithms/update/selection.h> #include <vcg/complex/algorithms/update/flag.h> #include <vcg/complex/algorithms/update/normal.h> #include <vcg/complex/algorithms/update/topology.h> #include <vcg/space/triangle3.h> namespace vcg { namespace tri{ template <class ConnectedMeshType> class ConnectedComponentIterator { public: typedef ConnectedMeshType MeshType; typedef typename MeshType::VertexType VertexType; typedef typename MeshType::VertexPointer VertexPointer; typedef typename MeshType::VertexIterator VertexIterator; typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::FaceType FaceType; typedef typename MeshType::FacePointer FacePointer; typedef typename MeshType::FaceIterator FaceIterator; typedef typename MeshType::ConstFaceIterator ConstFaceIterator; typedef typename MeshType::FaceContainer FaceContainer; public: void operator ++() { FacePointer fpt=sf.top(); sf.pop(); for(int j=0;j<3;++j) if( !face::IsBorder(*fpt,j) ) { FacePointer l=fpt->FFp(j); if( !tri::IsMarked(*mp,l) ) { tri::Mark(*mp,l); sf.push(l); } } } void start(MeshType &m, FacePointer p) { tri::RequirePerFaceMark(m); mp=&m; while(!sf.empty()) sf.pop(); UnMarkAll(m); assert(p); assert(!p->IsD()); tri::Mark(m,p); sf.push(p); } bool completed() { return sf.empty(); } FacePointer operator *() { return sf.top(); } private: std::stack<FacePointer> sf; MeshType *mp; }; /// /** \addtogroup trimesh */ /*@{*/ /// Class of static functions to clean//restore meshs. template <class CleanMeshType> class Clean { public: typedef CleanMeshType MeshType; typedef typename MeshType::VertexType VertexType; typedef typename MeshType::VertexPointer VertexPointer; typedef typename MeshType::VertexIterator VertexIterator; typedef typename MeshType::ConstVertexIterator ConstVertexIterator; typedef typename MeshType::EdgeIterator EdgeIterator; typedef typename MeshType::EdgePointer EdgePointer; typedef typename MeshType::CoordType CoordType; typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::FaceType FaceType; typedef typename MeshType::FacePointer FacePointer; typedef typename MeshType::FaceIterator FaceIterator; typedef typename MeshType::ConstFaceIterator ConstFaceIterator; typedef typename MeshType::FaceContainer FaceContainer; typedef typename vcg::Box3<ScalarType> Box3Type; typedef GridStaticPtr<FaceType, ScalarType > TriMeshGrid; /* classe di confronto per l'algoritmo di eliminazione vertici duplicati*/ class RemoveDuplicateVert_Compare{ public: inline bool operator()(VertexPointer const &a, VertexPointer const &b) { return ((*a).cP() == (*b).cP()) ? (a<b): ((*a).cP() < (*b).cP()); } }; /** This function removes all duplicate vertices of the mesh by looking only at their spatial positions. * Note that it does not update any topology relation that could be affected by this like the VT or TT relation. * the reason this function is usually performed BEFORE building any topology information. */ static int RemoveDuplicateVertex( MeshType & m, bool RemoveDegenerateFlag=true) // V1.0 { if(m.vert.size()==0 || m.vn==0) return 0; std::map<VertexPointer, VertexPointer> mp; size_t i,j; VertexIterator vi; int deleted=0; int k=0; size_t num_vert = m.vert.size(); std::vector<VertexPointer> perm(num_vert); for(vi=m.vert.begin(); vi!=m.vert.end(); ++vi, ++k) perm[k] = &(*vi); RemoveDuplicateVert_Compare c_obj; std::sort(perm.begin(),perm.end(),c_obj); j = 0; i = j; mp[perm[i]] = perm[j]; ++i; for(;i!=num_vert;) { if( (! (*perm[i]).IsD()) && (! (*perm[j]).IsD()) && (*perm[i]).P() == (*perm[j]).cP() ) { VertexPointer t = perm[i]; mp[perm[i]] = perm[j]; ++i; Allocator<MeshType>::DeleteVertex(m,*t); deleted++; } else { j = i; ++i; } } for(FaceIterator fi = m.face.begin(); fi!=m.face.end(); ++fi) if( !(*fi).IsD() ) for(k = 0; k < (*fi).VN(); ++k) if( mp.find( (typename MeshType::VertexPointer)(*fi).V(k) ) != mp.end() ) { (*fi).V(k) = &*mp[ (*fi).V(k) ]; } for(EdgeIterator ei = m.edge.begin(); ei!=m.edge.end(); ++ei) if( !(*ei).IsD() ) for(k = 0; k < 2; ++k) if( mp.find( (typename MeshType::VertexPointer)(*ei).V(k) ) != mp.end() ) { (*ei).V(k) = &*mp[ (*ei).V(k) ]; } if(RemoveDegenerateFlag) RemoveDegenerateFace(m); if(RemoveDegenerateFlag && m.en>0) { RemoveDegenerateEdge(m); RemoveDuplicateEdge(m); } return deleted; } class SortedPair { public: SortedPair() {} SortedPair(unsigned int v0, unsigned int v1, EdgePointer _fp) { v[0]=v0;v[1]=v1; fp=_fp; if(v[0]>v[1]) std::swap(v[0],v[1]); } bool operator < (const SortedPair &p) const { return (v[1]!=p.v[1])?(v[1]<p.v[1]): (v[0]<p.v[0]); } bool operator == (const SortedPair &s) const { if( (v[0]==s.v[0]) && (v[1]==s.v[1]) ) return true; return false; } unsigned int v[2]; EdgePointer fp; }; class SortedTriple { public: SortedTriple() {} SortedTriple(unsigned int v0, unsigned int v1, unsigned int v2,FacePointer _fp) { v[0]=v0;v[1]=v1;v[2]=v2; fp=_fp; std::sort(v,v+3); } bool operator < (const SortedTriple &p) const { return (v[2]!=p.v[2])?(v[2]<p.v[2]): (v[1]!=p.v[1])?(v[1]<p.v[1]): (v[0]<p.v[0]); } bool operator == (const SortedTriple &s) const { if( (v[0]==s.v[0]) && (v[1]==s.v[1]) && (v[2]==s.v[2]) ) return true; return false; } unsigned int v[3]; FacePointer fp; }; /** This function removes all duplicate faces of the mesh by looking only at their vertex reference. So it should be called after unification of vertices. Note that it does not update any topology relation that could be affected by this like the VT or TT relation. the reason this function is usually performed BEFORE building any topology information. */ static int RemoveDuplicateFace( MeshType & m) // V1.0 { std::vector<SortedTriple> fvec; for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi) if(!(*fi).IsD()) { fvec.push_back(SortedTriple( tri::Index(m,(*fi).V(0)), tri::Index(m,(*fi).V(1)), tri::Index(m,(*fi).V(2)), &*fi)); } assert (size_t(m.fn) == fvec.size()); std::sort(fvec.begin(),fvec.end()); int total=0; for(int i=0;i<int(fvec.size())-1;++i) { if(fvec[i]==fvec[i+1]) { total++; tri::Allocator<MeshType>::DeleteFace(m, *(fvec[i].fp) ); } } return total; } /** This function removes all duplicate faces of the mesh by looking only at their vertex reference. So it should be called after unification of vertices. Note that it does not update any topology relation that could be affected by this like the VT or TT relation. the reason this function is usually performed BEFORE building any topology information. */ static int RemoveDuplicateEdge( MeshType & m) // V1.0 { if (m.en==0) return 0; std::vector<SortedPair> eVec; for(EdgeIterator ei=m.edge.begin();ei!=m.edge.end();++ei) if(!(*ei).IsD()) { eVec.push_back(SortedPair( tri::Index(m,(*ei).V(0)), tri::Index(m,(*ei).V(1)), &*ei)); } assert (size_t(m.en) == eVec.size()); //for(int i=0;i<fvec.size();++i) qDebug("fvec[%i] = (%i %i %i)(%i)",i,fvec[i].v[0],fvec[i].v[1],fvec[i].v[2],tri::Index(m,fvec[i].fp)); std::sort(eVec.begin(),eVec.end()); int total=0; for(int i=0;i<int(eVec.size())-1;++i) { if(eVec[i]==eVec[i+1]) { total++; tri::Allocator<MeshType>::DeleteEdge(m, *(eVec[i].fp) ); //qDebug("deleting face %i (pos in fvec %i)",tri::Index(m,fvec[i].fp) ,i); } } return total; } static int CountUnreferencedVertex( MeshType& m) { return RemoveUnreferencedVertex(m,false); } /** This function removes that are not referenced by any face. The function updates the vn counter. @param m The mesh @return The number of removed vertices */ static int RemoveUnreferencedVertex( MeshType& m, bool DeleteVertexFlag=true) // V1.0 { FaceIterator fi; EdgeIterator ei; VertexIterator vi; int referredBit = VertexType::NewBitFlag(); int j; int deleted = 0; for(vi=m.vert.begin();vi!=m.vert.end();++vi) (*vi).ClearUserBit(referredBit); for(fi=m.face.begin();fi!=m.face.end();++fi) if( !(*fi).IsD() ) for(j=0;j<(*fi).VN();++j) (*fi).V(j)->SetUserBit(referredBit); for(ei=m.edge.begin();ei!=m.edge.end();++ei) if( !(*ei).IsD() ){ (*ei).V(0)->SetUserBit(referredBit); (*ei).V(1)->SetUserBit(referredBit); } for(vi=m.vert.begin();vi!=m.vert.end();++vi) if( (!(*vi).IsD()) && (!(*vi).IsUserBit(referredBit))) { if(DeleteVertexFlag) Allocator<MeshType>::DeleteVertex(m,*vi); ++deleted; } VertexType::DeleteBitFlag(referredBit); return deleted; } /** Degenerate vertices are vertices that have coords with invalid floating point values, All the faces incident on deleted vertices are also deleted */ static int RemoveDegenerateVertex(MeshType& m) { VertexIterator vi; int count_vd = 0; for(vi=m.vert.begin(); vi!=m.vert.end();++vi) if(math::IsNAN( (*vi).P()[0]) || math::IsNAN( (*vi).P()[1]) || math::IsNAN( (*vi).P()[2]) ) { count_vd++; Allocator<MeshType>::DeleteVertex(m,*vi); } FaceIterator fi; int count_fd = 0; for(fi=m.face.begin(); fi!=m.face.end();++fi) if(!(*fi).IsD()) if( (*fi).V(0)->IsD() || (*fi).V(1)->IsD() || (*fi).V(2)->IsD() ) { count_fd++; Allocator<MeshType>::DeleteFace(m,*fi); } return count_vd; } /** Degenerate faces are faces that are Topologically degenerate, i.e. have two or more vertex reference that link the same vertex (and not only two vertexes with the same coordinates). All Degenerate faces are zero area faces BUT not all zero area faces are degenerate. We do not take care of topology because when we have degenerate faces the topology calculation functions crash. */ static int RemoveDegenerateFace(MeshType& m) { int count_fd = 0; for(FaceIterator fi=m.face.begin(); fi!=m.face.end();++fi) if(!(*fi).IsD()) { if((*fi).V(0) == (*fi).V(1) || (*fi).V(0) == (*fi).V(2) || (*fi).V(1) == (*fi).V(2) ) { count_fd++; Allocator<MeshType>::DeleteFace(m,*fi); } } return count_fd; } static int RemoveDegenerateEdge(MeshType& m) { int count_ed = 0; for(EdgeIterator ei=m.edge.begin(); ei!=m.edge.end();++ei) if(!(*ei).IsD()) { if((*ei).V(0) == (*ei).V(1) ) { count_ed++; Allocator<MeshType>::DeleteEdge(m,*ei); } } return count_ed; } static int RemoveNonManifoldVertex(MeshType& m) { CountNonManifoldVertexFF(m,true); tri::UpdateSelection<MeshType>::FaceFromVertexLoose(m); int count_removed = 0; FaceIterator fi; for(fi=m.face.begin(); fi!=m.face.end();++fi) if(!(*fi).IsD() && (*fi).IsS()) Allocator<MeshType>::DeleteFace(m,*fi); VertexIterator vi; for(vi=m.vert.begin(); vi!=m.vert.end();++vi) if(!(*vi).IsD() && (*vi).IsS()) { ++count_removed; Allocator<MeshType>::DeleteVertex(m,*vi); } return count_removed; } static int SplitSelectedVertexOnEdgeMesh(MeshType& m) { tri::RequireCompactness(m); tri::UpdateFlags<MeshType>::VertexClearV(m); for(size_t i=0;i<m.edge.size();++i) { for(int j=0;j<2;++j) { VertexPointer vp = m.edge[i].V(j); if(vp->IsS()) { if(!vp->IsV()) m.edge[i].V(j) = &*(tri::Allocator<MeshType>::AddVertex(m,vp->P())); else vp->SetV(); } } } } static void SelectNonManifoldVertexOnEdgeMesh(MeshType &m) { tri::RequireCompactness(m); tri::UpdateSelection<MeshType>::VertexClear(m); std::vector<int> cnt(m.vn,0); for(size_t i=0;i<m.edge.size();++i) { cnt[tri::Index(m,m.edge[i].V(0))]++; cnt[tri::Index(m,m.edge[i].V(1))]++; } for(size_t i=0;i<m.vert.size();++i) if(cnt[i]>2) m.vert[i].SetS(); } static void SelectCreaseVertexOnEdgeMesh(MeshType &m, ScalarType AngleRadThr) { tri::RequireCompactness(m); tri::RequireVEAdjacency(m); tri::UpdateTopology<MeshType>::VertexEdge(m); for(size_t i=0;i<m.vert.size();++i) { std::vector<VertexPointer> VVStarVec; edge::VVStarVE<typename MeshType::EdgeType>(&(m.vert[i]),VVStarVec); if(VVStarVec.size()==2) { CoordType v0 = m.vert[i].P() - VVStarVec[0]->P(); CoordType v1 = m.vert[i].P() - VVStarVec[1]->P(); float angle = M_PI-vcg::Angle(v0,v1); if(angle > AngleRadThr) m.vert[i].SetS(); } } } /// Removal of faces that were incident on a non manifold edge. // Given a mesh with FF adjacency // it search for non manifold vertices and duplicate them. // Duplicated vertices are moved apart according to the move threshold param. // that is a percentage of the average vector from the non manifold vertex to the barycenter of the incident faces. static int SplitNonManifoldVertex(MeshType& m, ScalarType moveThreshold) { RequireFFAdjacency(m); typedef std::pair<FacePointer,int> FaceInt; // a face and the index of the vertex that we have to change // std::vector<std::pair<VertexPointer, std::vector<FaceInt> > >ToSplitVec; SelectionStack<MeshType> ss(m); ss.push(); CountNonManifoldVertexFF(m,true); UpdateFlags<MeshType>::VertexClearV(m); for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { for(int i=0;i<3;i++) if((*fi).V(i)->IsS() && !(*fi).V(i)->IsV()) { (*fi).V(i)->SetV(); face::Pos<FaceType> startPos(&*fi,i); face::Pos<FaceType> curPos = startPos; std::set<FaceInt> faceSet; do { faceSet.insert(std::make_pair(curPos.F(),curPos.VInd())); curPos.NextE(); } while (curPos != startPos); ToSplitVec.push_back(make_pair((*fi).V(i),std::vector<FaceInt>())); typename std::set<FaceInt>::const_iterator iii; for(iii=faceSet.begin();iii!=faceSet.end();++iii) ToSplitVec.back().second.push_back(*iii); } } ss.pop(); // Second step actually add new vertices and split them. typename tri::Allocator<MeshType>::template PointerUpdater<VertexPointer> pu; VertexIterator firstVp = tri::Allocator<MeshType>::AddVertices(m,ToSplitVec.size(),pu); for(size_t i =0;i<ToSplitVec.size();++i) { // qDebug("Splitting Vertex %i",ToSplitVec[i].first-&*m.vert.begin()); VertexPointer np=ToSplitVec[i].first; pu.Update(np); firstVp->ImportData(*np); // loop on the face to be changed, and also compute the movement vector; CoordType delta(0,0,0); for(size_t j=0;j<ToSplitVec[i].second.size();++j) { FaceInt ff=ToSplitVec[i].second[j]; ff.first->V(ff.second)=&*firstVp; delta+=Barycenter(*(ff.first))-np->cP(); } delta /= ToSplitVec[i].second.size(); firstVp->P() = firstVp->P() + delta * moveThreshold; firstVp++; } return ToSplitVec.size(); } // Auxiliary function for sorting the non manifold faces according to their area. Used in RemoveNonManifoldFace struct CompareAreaFP { bool operator ()(FacePointer const& f1, FacePointer const& f2) const { return DoubleArea(*f1) < DoubleArea(*f2); } }; /// Removal of faces that were incident on a non manifold edge. static int RemoveNonManifoldFace(MeshType& m) { FaceIterator fi; int count_fd = 0; std::vector<FacePointer> ToDelVec; for(fi=m.face.begin(); fi!=m.face.end();++fi) if (!fi->IsD()) { if ((!IsManifold(*fi,0))|| (!IsManifold(*fi,1))|| (!IsManifold(*fi,2))) ToDelVec.push_back(&*fi); } std::sort(ToDelVec.begin(),ToDelVec.end(),CompareAreaFP()); for(size_t i=0;i<ToDelVec.size();++i) { if(!ToDelVec[i]->IsD()) { FaceType &ff= *ToDelVec[i]; if ((!IsManifold(ff,0))|| (!IsManifold(ff,1))|| (!IsManifold(ff,2))) { for(int j=0;j<3;++j) if(!face::IsBorder<FaceType>(ff,j)) vcg::face::FFDetach<FaceType>(ff,j); Allocator<MeshType>::DeleteFace(m,ff); count_fd++; } } } return count_fd; } /* The following functions remove faces that are geometrically "bad" according to edges and area criteria. They remove the faces that are out of a given range of area or edges (e.g. faces too large or too small, or with edges too short or too long) but that could be topologically correct. These functions can optionally take into account only the selected faces. */ template<bool Selected> static int RemoveFaceOutOfRangeAreaSel(MeshType& m, ScalarType MinAreaThr=0, ScalarType MaxAreaThr=(std::numeric_limits<ScalarType>::max)()) { FaceIterator fi; int count_fd = 0; MinAreaThr*=2; MaxAreaThr*=2; for(fi=m.face.begin(); fi!=m.face.end();++fi) if(!(*fi).IsD()) if(!Selected || (*fi).IsS()) { const ScalarType doubleArea=DoubleArea<FaceType>(*fi); if((doubleArea<=MinAreaThr) || (doubleArea>=MaxAreaThr) ) { Allocator<MeshType>::DeleteFace(m,*fi); count_fd++; } } return count_fd; } // alias for the old style. Kept for backward compatibility static int RemoveZeroAreaFace(MeshType& m) { return RemoveFaceOutOfRangeArea(m);} // Aliases for the functions that do not look at selection static int RemoveFaceOutOfRangeArea(MeshType& m, ScalarType MinAreaThr=0, ScalarType MaxAreaThr=(std::numeric_limits<ScalarType>::max)()) { return RemoveFaceOutOfRangeAreaSel<false>(m,MinAreaThr,MaxAreaThr); } /** * Is the mesh only composed by quadrilaterals? */ static bool IsBitQuadOnly(const MeshType &m) { typedef typename MeshType::FaceType F; tri::RequirePerFaceFlags(m); for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { unsigned int tmp = fi->Flags()&(F::FAUX0|F::FAUX1|F::FAUX2); if ( tmp != F::FAUX0 && tmp != F::FAUX1 && tmp != F::FAUX2) return false; } return true; } static bool IsFaceFauxConsistent(MeshType &m) { RequirePerFaceFlags(m); RequireFFAdjacency(m); for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi) if(!(*fi).IsD()) { for(int z=0;z<(*fi).VN();++z) { FacePointer fp = fi->FFp(z); int zp = fi->FFi(z); if(fi->IsF(z) != fp->IsF(zp)) return false; } } return true; } /** * Is the mesh only composed by triangles? (non polygonal faces) */ static bool IsBitTriOnly(const MeshType &m) { tri::RequirePerFaceFlags(m); for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) { if ( !fi->IsD() && fi->IsAnyF() ) return false; } return true; } static bool IsBitPolygonal(const MeshType &m){ return !IsBitTriOnly(m); } /** * Is the mesh only composed by quadrilaterals and triangles? (no pentas, etc) * It assumes that the bits are consistent. In that case there can be only a single faux edge. */ static bool IsBitTriQuadOnly(const MeshType &m) { tri::RequirePerFaceFlags(m); typedef typename MeshType::FaceType F; for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { unsigned int tmp = fi->cFlags()&(F::FAUX0|F::FAUX1|F::FAUX2); if ( tmp!=F::FAUX0 && tmp!=F::FAUX1 && tmp!=F::FAUX2 && tmp!=0 ) return false; } return true; } /** * How many quadrilaterals? * It assumes that the bits are consistent. In that case we count the tris with a single faux edge and divide by two. */ static int CountBitQuads(const MeshType &m) { tri::RequirePerFaceFlags(m); typedef typename MeshType::FaceType F; int count=0; for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { unsigned int tmp = fi->cFlags()&(F::FAUX0|F::FAUX1|F::FAUX2); if ( tmp==F::FAUX0 || tmp==F::FAUX1 || tmp==F::FAUX2) count++; } return count / 2; } /** * How many triangles? (non polygonal faces) */ static int CountBitTris(const MeshType &m) { tri::RequirePerFaceFlags(m); int count=0; for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { if (!(fi->IsAnyF())) count++; } return count; } /** * How many polygons of any kind? (including triangles) * it assumes that there are no faux vertexes (e.g vertices completely surrounded by faux edges) */ static int CountBitPolygons(const MeshType &m) { tri::RequirePerFaceFlags(m); int count = 0; for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { if (fi->IsF(0)) count++; if (fi->IsF(1)) count++; if (fi->IsF(2)) count++; } return m.fn - count/2; } /** * The number of polygonal faces is * FN - EN_f (each faux edge hides exactly one triangular face or in other words a polygon of n edges has n-3 faux edges.) * In the general case where a The number of polygonal faces is * FN - EN_f + VN_f * where: * EN_f is the number of faux edges. * VN_f is the number of faux vertices (e.g vertices completely surrounded by faux edges) * as a intuitive proof think to a internal vertex that is collapsed onto a border of a polygon: * it deletes 2 faces, 1 faux edges and 1 vertex so to keep the balance you have to add back the removed vertex. */ static int CountBitLargePolygons(MeshType &m) { tri::RequirePerFaceFlags(m); UpdateFlags<MeshType>::VertexSetV(m); // First loop Clear all referenced vertices for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) for(int i=0;i<3;++i) fi->V(i)->ClearV(); // Second Loop, count (twice) faux edges and mark all vertices touched by non faux edges // (e.g vertexes on the boundary of a polygon) int countE = 0; for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { for(int i=0;i<3;++i) { if (fi->IsF(i)) countE++; else { fi->V0(i)->SetV(); fi->V1(i)->SetV(); } } } // Third Loop, count the number of referenced vertexes that are completely surrounded by faux edges. int countV = 0; for (VertexIterator vi = m.vert.begin(); vi != m.vert.end(); ++vi) if (!vi->IsD() && !vi->IsV()) countV++; return m.fn - countE/2 + countV ; } /** * Checks that the mesh has consistent per-face faux edges * (the ones that merges triangles into larger polygons). * A border edge should never be faux, and faux edges should always be * reciprocated by another faux edges. * It requires FF adjacency. */ static bool HasConsistentPerFaceFauxFlag(const MeshType &m) { RequireFFAdjacency(m); RequirePerFaceFlags(m); for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if(!(*fi).IsD()) for (int k=0; k<3; k++) if( ( fi->IsF(k) != fi->cFFp(k)->IsF(fi->cFFi(k)) ) || ( fi->IsF(k) && face::IsBorder(*fi,k)) ) { return false; } return true; } /** * Count the number of non manifold edges in a polylinemesh, e.g. the edges where there are more than 2 incident faces. * */ static int CountNonManifoldEdgeEE( MeshType & m, bool SelectFlag=false) { assert(m.fn == 0 && m.en >0); // just to be sure we are using an edge mesh... RequireEEAdjacency(m); tri::UpdateTopology<MeshType>::EdgeEdge(m); if(SelectFlag) UpdateSelection<MeshType>::VertexClear(m); int nonManifoldCnt=0; SimpleTempData<typename MeshType::VertContainer, int > TD(m.vert,0); // First Loop, just count how many faces are incident on a vertex and store it in the TemporaryData Counter. EdgeIterator ei; for (ei = m.edge.begin(); ei != m.edge.end(); ++ei) if (!ei->IsD()) { TD[(*ei).V(0)]++; TD[(*ei).V(1)]++; } tri::UpdateFlags<MeshType>::VertexClearV(m); // Second Loop, Check that each vertex have been seen 1 or 2 times. for (VertexIterator vi = m.vert.begin(); vi != m.vert.end(); ++vi) if (!vi->IsD()) { if( TD[vi] >2 ) { if(SelectFlag) (*vi).SetS(); nonManifoldCnt++; } } return nonManifoldCnt; } /** * Count the number of non manifold edges in a mesh, e.g. the edges where there are more than 2 incident faces. * * Note that this test is not enough to say that a mesh is two manifold, * you have to count also the non manifold vertexes. */ static int CountNonManifoldEdgeFF( MeshType & m, bool SelectFlag=false) { RequireFFAdjacency(m); int nmfBit[3]; nmfBit[0]= FaceType::NewBitFlag(); nmfBit[1]= FaceType::NewBitFlag(); nmfBit[2]= FaceType::NewBitFlag(); UpdateFlags<MeshType>::FaceClear(m,nmfBit[0]+nmfBit[1]+nmfBit[2]); if(SelectFlag){ UpdateSelection<MeshType>::VertexClear(m); UpdateSelection<MeshType>::FaceClear(m); } int edgeCnt = 0; for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) { if (!fi->IsD()) { for(int i=0;i<3;++i) if(!IsManifold(*fi,i)) { if(!(*fi).IsUserBit(nmfBit[i])) { ++edgeCnt; if(SelectFlag) { (*fi).V0(i)->SetS(); (*fi).V1(i)->SetS(); } // follow the ring of faces incident on edge i; face::Pos<FaceType> nmf(&*fi,i); do { if(SelectFlag) nmf.F()->SetS(); nmf.F()->SetUserBit(nmfBit[nmf.E()]); nmf.NextF(); } while(nmf.f != &*fi); } } } } return edgeCnt; } /** Count (and eventually select) non 2-Manifold vertexes of a mesh * e.g. the vertices with a non 2-manif. neighbourhood but that do not belong to not 2-manif edges. * typical situation two cones connected by one vertex. */ static int CountNonManifoldVertexFF( MeshType & m, bool selectVert = true ) { RequireFFAdjacency(m); if(selectVert) UpdateSelection<MeshType>::VertexClear(m); int nonManifoldCnt=0; SimpleTempData<typename MeshType::VertContainer, int > TD(m.vert,0); // First Loop, just count how many faces are incident on a vertex and store it in the TemporaryData Counter. FaceIterator fi; for (fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { TD[(*fi).V(0)]++; TD[(*fi).V(1)]++; TD[(*fi).V(2)]++; } tri::UpdateFlags<MeshType>::VertexClearV(m); // Second Loop. // mark out of the game the vertexes that are incident on non manifold edges. for (fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { for(int i=0;i<3;++i) if (!IsManifold(*fi,i)) { (*fi).V0(i)->SetV(); (*fi).V1(i)->SetV(); } } // Third Loop, for safe vertexes, check that the number of faces that you can reach starting // from it and using FF is the same of the previously counted. for (fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { for(int i=0;i<3;i++) if(!(*fi).V(i)->IsV()){ (*fi).V(i)->SetV(); face::Pos<FaceType> pos(&(*fi),i); int starSizeFF = pos.NumberOfIncidentFaces(); if (starSizeFF != TD[(*fi).V(i)]) { if(selectVert) (*fi).V(i)->SetS(); nonManifoldCnt++; } } } return nonManifoldCnt; } /// Very simple test of water tightness. No boundary and no non manifold edges. /// Assume that it is orientable. /// It could be debated if a closed non orientable surface is watertight or not. /// /// The rationale of not testing orientability here is that /// it requires FFAdj while this test do not require any adjacency. /// static bool IsWaterTight(MeshType & m) { int edgeNum=0,edgeBorderNum=0,edgeNonManifNum=0; CountEdgeNum(m, edgeNum, edgeBorderNum,edgeNonManifNum); return (edgeBorderNum==0) && (edgeNonManifNum==0); } static void CountEdgeNum( MeshType & m, int &total_e, int &boundary_e, int &non_manif_e ) { std::vector< typename tri::UpdateTopology<MeshType>::PEdge > edgeVec; tri::UpdateTopology<MeshType>::FillEdgeVector(m,edgeVec,true); sort(edgeVec.begin(), edgeVec.end()); // Lo ordino per vertici total_e=0; boundary_e=0; non_manif_e=0; size_t f_on_cur_edge =1; for(size_t i=0;i<edgeVec.size();++i) { if(( (i+1) == edgeVec.size()) || !(edgeVec[i] == edgeVec[i+1])) { ++total_e; if(f_on_cur_edge==1) ++boundary_e; if(f_on_cur_edge>2) ++non_manif_e; f_on_cur_edge=1; } else { ++f_on_cur_edge; } } // end for } static int CountHoles( MeshType & m) { int numholev=0; FaceIterator fi; FaceIterator gi; vcg::face::Pos<FaceType> he; vcg::face::Pos<FaceType> hei; std::vector< std::vector<CoordType> > holes; //indices of vertices vcg::tri::UpdateFlags<MeshType>::VertexClearS(m); gi=m.face.begin(); fi=gi; for(fi=m.face.begin();fi!=m.face.end();fi++)//for all faces do { for(int j=0;j<3;j++)//for all edges { if(fi->V(j)->IsS()) continue; if(face::IsBorder(*fi,j))//found an unvisited border edge { he.Set(&(*fi),j,fi->V(j)); //set the face-face iterator to the current face, edge and vertex std::vector<CoordType> hole; //start of a new hole hole.push_back(fi->P(j)); // including the first vertex numholev++; he.v->SetS(); //set the current vertex as selected he.NextB(); //go to the next boundary edge while(fi->V(j) != he.v)//will we do not encounter the first boundary edge. { CoordType newpoint = he.v->P(); //select its vertex. if(he.v->IsS())//check if this vertex was selected already, because then we have an additional hole. { //cut and paste the additional hole. std::vector<CoordType> hole2; int index = static_cast<int>(find(hole.begin(),hole.end(),newpoint) - hole.begin()); for(unsigned int i=index; i<hole.size(); i++) hole2.push_back(hole[i]); hole.resize(index); if(hole2.size()!=0) //annoying in degenerate cases holes.push_back(hole2); } hole.push_back(newpoint); numholev++; he.v->SetS(); //set the current vertex as selected he.NextB(); //go to the next boundary edge } holes.push_back(hole); } } } return static_cast<int>(holes.size()); } /* Compute the set of connected components of a given mesh it fills a vector of pair < int , faceptr > with, for each connecteed component its size and a represnant */ static int CountConnectedComponents(MeshType &m) { std::vector< std::pair<int,FacePointer> > CCV; return ConnectedComponents(m,CCV); } static int ConnectedComponents(MeshType &m, std::vector< std::pair<int,FacePointer> > &CCV) { tri::RequireFFAdjacency(m); CCV.clear(); tri::UpdateSelection<MeshType>::FaceClear(m); std::stack<FacePointer> sf; FacePointer fpt=&*(m.face.begin()); for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi) { if(!((*fi).IsD()) && !(*fi).IsS()) { (*fi).SetS(); CCV.push_back(std::make_pair(0,&*fi)); sf.push(&*fi); while (!sf.empty()) { fpt=sf.top(); ++CCV.back().first; sf.pop(); for(int j=0;j<3;++j) { if( !face::IsBorder(*fpt,j) ) { FacePointer l = fpt->FFp(j); if( !(*l).IsS() ) { (*l).SetS(); sf.push(l); } } } } } } return int(CCV.size()); } static void ComputeValence( MeshType &m, typename MeshType::PerVertexIntHandle &h) { for(VertexIterator vi=m.vert.begin(); vi!= m.vert.end();++vi) h[vi]=0; for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi) { if(!((*fi).IsD())) for(int j=0;j<fi->VN();j++) ++h[tri::Index(m,fi->V(j))]; } } /** GENUS. A topologically invariant property of a surface defined as the largest number of non-intersecting simple closed curves that can be drawn on the surface without separating it. Roughly speaking, it is the number of holes in a surface. The genus g of a closed surface, also called the geometric genus, is related to the Euler characteristic by the relation $chi$ by $chi==2-2g$. The genus of a connected, orientable surface is an integer representing the maximum number of cuttings along closed simple curves without rendering the resultant manifold disconnected. It is equal to the number of handles on it. For general polyhedra the <em>Euler Formula</em> is: V - E + F = 2 - 2G - B where V is the number of vertices, F is the number of faces, E is the number of edges, G is the genus and B is the number of <em>boundary polygons</em>. The above formula is valid for a mesh with one single connected component. By considering multiple connected components the formula becomes: V - E + F = 2C - 2Gs - B -> 2Gs = - ( V-E+F +B -2C) where C is the number of connected components and Gs is the sum of the genus of all connected components. Note that in the case of a mesh with boundaries the intuitive meaning of Genus is less intuitive that it could seem. A closed sphere, a sphere with one hole (e.g. a disk) and a sphere with two holes (e.g. a tube) all of them have Genus == 0 */ static int MeshGenus(int nvert,int nedges,int nfaces, int numholes, int numcomponents) { return -((nvert + nfaces - nedges + numholes - 2 * numcomponents) / 2); } static int MeshGenus(MeshType &m) { int nvert=m.vn; int nfaces=m.fn; int boundary_e,total_e,nonmanif_e; CountEdgeNum(m,total_e,boundary_e,nonmanif_e); int numholes=CountHoles(m); int numcomponents=CountConnectedComponents(m); int G=MeshGenus(nvert,total_e,nfaces,numholes,numcomponents); return G; } /** * Check if the given mesh is regular, semi-regular or irregular. * * Each vertex of a \em regular mesh has valence 6 except for border vertices * which have valence 4. * * A \em semi-regular mesh is derived from an irregular one applying * 1-to-4 subdivision recursively. (not checked for now) * * All other meshes are \em irregular. */ static void IsRegularMesh(MeshType &m, bool &Regular, bool &Semiregular) { RequireVFAdjacency(m); Regular = true; VertexIterator vi; // for each vertex the number of edges are count for (vi = m.vert.begin(); vi != m.vert.end(); ++vi) { if (!vi->IsD()) { face::Pos<FaceType> he((*vi).VFp(), &*vi); face::Pos<FaceType> ht = he; int n=0; bool border=false; do { ++n; ht.NextE(); if (ht.IsBorder()) border=true; } while (ht != he); if (border) n = n/2; if ((n != 6)&&(!border && n != 4)) { Regular = false; break; } } } if (!Regular) Semiregular = false; else { // For now we do not account for semi-regularity Semiregular = false; } } static bool IsCoherentlyOrientedMesh(MeshType &m) { for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) for(int i=0;i<3;++i) if(!face::CheckOrientation(*fi,i)) return false; return true; } static void OrientCoherentlyMesh(MeshType &m, bool &Oriented, bool &Orientable) { RequireFFAdjacency(m); assert(&Oriented != &Orientable); assert(m.face.back().FFp(0)); // This algorithms require FF topology initialized Orientable = true; Oriented = true; tri::UpdateSelection<MeshType>::FaceClear(m); std::stack<FacePointer> faces; for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) { if (!fi->IsD() && !fi->IsS()) { // each face put in the stack is selected (and oriented) fi->SetS(); faces.push(&(*fi)); // empty the stack while (!faces.empty()) { FacePointer fp = faces.top(); faces.pop(); // make consistently oriented the adjacent faces for (int j = 0; j < 3; j++) { // get one of the adjacent face FacePointer fpaux = fp->FFp(j); int iaux = fp->FFi(j); if (!fpaux->IsD() && fpaux != fp && face::IsManifold<FaceType>(*fp, j)) { if (!CheckOrientation(*fpaux, iaux)) { Oriented = false; if (!fpaux->IsS()) { face::SwapEdge<FaceType,true>(*fpaux, iaux); assert(CheckOrientation(*fpaux, iaux)); } else { Orientable = false; break; } } // put the oriented face into the stack if (!fpaux->IsS()) { fpaux->SetS(); faces.push(fpaux); } } } } } if (!Orientable) break; } } /// Flip the orientation of the whole mesh flipping all the faces (by swapping the first two vertices) static void FlipMesh(MeshType &m, bool selected=false) { for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if(!(*fi).IsD()) if(!selected || (*fi).IsS()) { face::SwapEdge<FaceType,false>((*fi), 0); if (HasPerWedgeTexCoord(m)) std::swap((*fi).WT(0),(*fi).WT(1)); } } /// Flip a mesh so that its normals are orented outside. /// Just for safety it uses a voting scheme. /// It assumes that /// mesh has already has coherent normals. /// mesh is watertight and signle component. static bool FlipNormalOutside(MeshType &m) { if(m.vert.empty()) return false; tri::UpdateNormal<MeshType>::PerVertexAngleWeighted(m); tri::UpdateNormal<MeshType>::NormalizePerVertex(m); std::vector< VertexPointer > minVertVec; std::vector< VertexPointer > maxVertVec; // The set of directions to be choosen std::vector< CoordType > dirVec; dirVec.push_back(CoordType(1,0,0)); dirVec.push_back(CoordType(0,1,0)); dirVec.push_back(CoordType(0,0,1)); dirVec.push_back(CoordType( 1, 1,1)); dirVec.push_back(CoordType(-1, 1,1)); dirVec.push_back(CoordType(-1,-1,1)); dirVec.push_back(CoordType( 1,-1,1)); for(size_t i=0;i<dirVec.size();++i) { Normalize(dirVec[i]); minVertVec.push_back(&*m.vert.begin()); maxVertVec.push_back(&*m.vert.begin()); } for (VertexIterator vi = m.vert.begin(); vi != m.vert.end(); ++vi) if(!(*vi).IsD()) { for(size_t i=0;i<dirVec.size();++i) { if( (*vi).cP().dot(dirVec[i]) < minVertVec[i]->P().dot(dirVec[i])) minVertVec[i] = &*vi; if( (*vi).cP().dot(dirVec[i]) > maxVertVec[i]->P().dot(dirVec[i])) maxVertVec[i] = &*vi; } } int voteCount=0; ScalarType angleThreshold = cos(math::ToRad(85.0)); for(size_t i=0;i<dirVec.size();++i) { // qDebug("Min vert along (%f %f %f) is %f %f %f",dirVec[i][0],dirVec[i][1],dirVec[i][2],minVertVec[i]->P()[0],minVertVec[i]->P()[1],minVertVec[i]->P()[2]); // qDebug("Max vert along (%f %f %f) is %f %f %f",dirVec[i][0],dirVec[i][1],dirVec[i][2],maxVertVec[i]->P()[0],maxVertVec[i]->P()[1],maxVertVec[i]->P()[2]); if(minVertVec[i]->N().dot(dirVec[i]) > angleThreshold ) voteCount++; if(maxVertVec[i]->N().dot(dirVec[i]) < -angleThreshold ) voteCount++; } // qDebug("votecount = %i",voteCount); if(voteCount < int(dirVec.size())/2) return false; FlipMesh(m); return true; } // Search and remove small single triangle folds // - a face has normal opposite to all other faces // - choose the edge that brings to the face f1 containing the vertex opposite to that edge. static int RemoveFaceFoldByFlip(MeshType &m, float normalThresholdDeg=175, bool repeat=true) { RequireFFAdjacency(m); RequirePerVertexMark(m); //Counters for logging and convergence int count, total = 0; do { tri::UpdateTopology<MeshType>::FaceFace(m); tri::UnMarkAll(m); count = 0; ScalarType NormalThrRad = math::ToRad(normalThresholdDeg); ScalarType eps = 0.0001; // this epsilon value is in absolute value. It is a distance from edge in baricentric coords. //detection stage for(FaceIterator fi=m.face.begin();fi!= m.face.end();++fi ) if(!(*fi).IsV()) { Point3<ScalarType> NN = vcg::TriangleNormal((*fi)).Normalize(); if( vcg::AngleN(NN,TriangleNormal(*(*fi).FFp(0)).Normalize()) > NormalThrRad && vcg::AngleN(NN,TriangleNormal(*(*fi).FFp(1)).Normalize()) > NormalThrRad && vcg::AngleN(NN,TriangleNormal(*(*fi).FFp(2)).Normalize()) > NormalThrRad ) { (*fi).SetS(); //(*fi).C()=Color4b(Color4b::Red); // now search the best edge to flip for(int i=0;i<3;i++) { Point3<ScalarType> &p=(*fi).P2(i); Point3<ScalarType> L; bool ret = vcg::InterpolationParameters((*(*fi).FFp(i)),TriangleNormal(*(*fi).FFp(i)),p,L); if(ret && L[0]>eps && L[1]>eps && L[2]>eps) { (*fi).FFp(i)->SetS(); (*fi).FFp(i)->SetV(); //(*fi).FFp(i)->C()=Color4b(Color4b::Green); if(face::CheckFlipEdge<FaceType>( *fi, i )) { face::FlipEdge<FaceType>( *fi, i ); ++count; ++total; } } } } } // tri::UpdateNormal<MeshType>::PerFace(m); } while( repeat && count ); return total; } static int RemoveTVertexByFlip(MeshType &m, float threshold=40, bool repeat=true) { RequireFFAdjacency(m); RequirePerVertexMark(m); //Counters for logging and convergence int count, total = 0; do { tri::UpdateTopology<MeshType>::FaceFace(m); tri::UnMarkAll(m); count = 0; //detection stage for(unsigned int index = 0 ; index < m.face.size(); ++index ) { FacePointer f = &(m.face[index]); float sides[3]; CoordType dummy; sides[0] = Distance(f->P(0), f->P(1)); sides[1] = Distance(f->P(1), f->P(2)); sides[2] = Distance(f->P(2), f->P(0)); // Find largest triangle side int i = std::find(sides, sides+3, std::max( std::max(sides[0],sides[1]), sides[2])) - (sides); if( tri::IsMarked(m,f->V2(i) )) continue; if( PSDist(f->P2(i),f->P(i),f->P1(i),dummy)*threshold <= sides[i] ) { tri::Mark(m,f->V2(i)); if(face::CheckFlipEdge<FaceType>( *f, i )) { // Check if EdgeFlipping improves quality FacePointer g = f->FFp(i); int k = f->FFi(i); Triangle3<ScalarType> t1(f->P(i), f->P1(i), f->P2(i)), t2(g->P(k), g->P1(k), g->P2(k)), t3(f->P(i), g->P2(k), f->P2(i)), t4(g->P(k), f->P2(i), g->P2(k)); if ( std::min( QualityFace(t1), QualityFace(t2) ) < std::min( QualityFace(t3), QualityFace(t4) )) { face::FlipEdge<FaceType>( *f, i ); ++count; ++total; } } } } // tri::UpdateNormal<MeshType>::PerFace(m); } while( repeat && count ); return total; } static int RemoveTVertexByCollapse(MeshType &m, float threshold=40, bool repeat=true) { RequirePerVertexMark(m); //Counters for logging and convergence int count, total = 0; do { tri::UnMarkAll(m); count = 0; //detection stage for(unsigned int index = 0 ; index < m.face.size(); ++index ) { FacePointer f = &(m.face[index]); float sides[3]; CoordType dummy; sides[0] = Distance(f->P(0), f->P(1)); sides[1] = Distance(f->P(1), f->P(2)); sides[2] = Distance(f->P(2), f->P(0)); int i = std::find(sides, sides+3, std::max( std::max(sides[0],sides[1]), sides[2])) - (sides); if( tri::IsMarked(m,f->V2(i) )) continue; if( PSDist(f->P2(i),f->P(i),f->P1(i),dummy)*threshold <= sides[i] ) { tri::Mark(m,f->V2(i)); int j = Distance(dummy,f->P(i))<Distance(dummy,f->P1(i))?i:(i+1)%3; f->P2(i) = f->P(j); tri::Mark(m,f->V(j)); ++count; ++total; } } tri::Clean<MeshType>::RemoveDuplicateVertex(m); tri::Allocator<MeshType>::CompactFaceVector(m); tri::Allocator<MeshType>::CompactVertexVector(m); } while( repeat && count ); return total; } static bool SelfIntersections(MeshType &m, std::vector<FaceType*> &ret) { RequirePerFaceMark(m); ret.clear(); int referredBit = FaceType::NewBitFlag(); tri::UpdateFlags<MeshType>::FaceClear(m,referredBit); TriMeshGrid gM; gM.Set(m.face.begin(),m.face.end()); for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi) if(!(*fi).IsD()) { (*fi).SetUserBit(referredBit); Box3< ScalarType> bbox; (*fi).GetBBox(bbox); std::vector<FaceType*> inBox; vcg::tri::GetInBoxFace(m, gM, bbox,inBox); bool Intersected=false; typename std::vector<FaceType*>::iterator fib; for(fib=inBox.begin();fib!=inBox.end();++fib) { if(!(*fib)->IsUserBit(referredBit) && (*fib != &*fi) ) if(Clean<MeshType>::TestFaceFaceIntersection(&*fi,*fib)){ ret.push_back(*fib); if(!Intersected) { ret.push_back(&*fi); Intersected=true; } } } inBox.clear(); } FaceType::DeleteBitFlag(referredBit); return (ret.size()>0); } /** This function simply test that the vn and fn counters be consistent with the size of the containers and the number of deleted simplexes. */ static bool IsSizeConsistent(MeshType &m) { int DeletedVertNum=0; for (VertexIterator vi = m.vert.begin(); vi != m.vert.end(); ++vi) if((*vi).IsD()) DeletedVertNum++; int DeletedEdgeNum=0; for (EdgeIterator ei = m.edge.begin(); ei != m.edge.end(); ++ei) if((*ei).IsD()) DeletedEdgeNum++; int DeletedFaceNum=0; for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if((*fi).IsD()) DeletedFaceNum++; if(size_t(m.vn+DeletedVertNum) != m.vert.size()) return false; if(size_t(m.en+DeletedEdgeNum) != m.edge.size()) return false; if(size_t(m.fn+DeletedFaceNum) != m.face.size()) return false; return true; } /** This function simply test that all the faces have a consistent face-face topology relation. useful for checking that a topology modifying algorithm does not mess something. */ static bool IsFFAdjacencyConsistent(MeshType &m) { RequireFFAdjacency(m); for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if(!(*fi).IsD()) { for(int i=0;i<3;++i) if(!FFCorrectness(*fi, i)) return false; } return true; } /** This function simply test that a mesh has some reasonable tex coord. */ static bool HasConsistentPerWedgeTexCoord(MeshType &m) { tri::RequirePerFaceWedgeTexCoord(m); for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if(!(*fi).IsD()) { FaceType &f=(*fi); if( ! ( (f.WT(0).N() == f.WT(1).N()) && (f.WT(0).N() == (*fi).WT(2).N()) ) ) return false; // all the vertices must have the same index. if((*fi).WT(0).N() <0) return false; // no undefined texture should be allowed } return true; } /** Simple check that there are no face with all collapsed tex coords. */ static bool HasZeroTexCoordFace(MeshType &m) { tri::RequirePerFaceWedgeTexCoord(m); for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if(!(*fi).IsD()) { if( (*fi).WT(0).P() == (*fi).WT(1).P() && (*fi).WT(0).P() == (*fi).WT(2).P() ) return false; } return true; } /** This function test if two triangular faces of a mesh intersect. It assumes that the faces (as storage) are different (e.g different address) If the two faces are different but coincident (same set of vertexes) return true. if the faces share an edge no test is done. if the faces share only a vertex, the opposite edge is tested against the face */ static bool TestFaceFaceIntersection(FaceType *f0,FaceType *f1) { assert(f0!=f1); int sv = face::CountSharedVertex(f0,f1); if(sv==3) return true; if(sv==0) return (vcg::IntersectionTriangleTriangle<FaceType>((*f0),(*f1))); // if the faces share only a vertex, the opposite edge (as a segment) is tested against the face // to avoid degenerate cases where the two triangles have the opposite edge on a common plane // we offset the segment to test toward the shared vertex if(sv==1) { int i0,i1; ScalarType a,b; face::FindSharedVertex(f0,f1,i0,i1); CoordType shP = f0->V(i0)->P()*0.5; if(vcg::IntersectionSegmentTriangle(Segment3<ScalarType>((*f0).V1(i0)->P()*0.5+shP,(*f0).V2(i0)->P()*0.5+shP), *f1, a, b) ) { // a,b are the param coords of the intersection point of the segment. if(a+b>=1 || a<=EPSIL || b<=EPSIL ) return false; return true; } if(vcg::IntersectionSegmentTriangle(Segment3<ScalarType>((*f1).V1(i1)->P()*0.5+shP,(*f1).V2(i1)->P()*0.5+shP), *f0, a, b) ) { // a,b are the param coords of the intersection point of the segment. if(a+b>=1 || a<=EPSIL || b<=EPSIL ) return false; return true; } } return false; } /** This function merge all the vertices that are closer than the given radius */ static int MergeCloseVertex(MeshType &m, const ScalarType radius) { int mergedCnt=0; mergedCnt = ClusterVertex(m,radius); RemoveDuplicateVertex(m,true); return mergedCnt; } static int ClusterVertex(MeshType &m, const ScalarType radius) { if(m.vn==0) return 0; // some spatial indexing structure does not work well with deleted vertices... tri::Allocator<MeshType>::CompactVertexVector(m); typedef vcg::SpatialHashTable<VertexType, ScalarType> SampleSHT; SampleSHT sht; tri::EmptyTMark<MeshType> markerFunctor; std::vector<VertexType*> closests; int mergedCnt=0; sht.Set(m.vert.begin(), m.vert.end()); UpdateFlags<MeshType>::VertexClearV(m); for(VertexIterator viv = m.vert.begin(); viv!= m.vert.end(); ++viv) if(!(*viv).IsD() && !(*viv).IsV()) { (*viv).SetV(); Point3<ScalarType> p = viv->cP(); Box3<ScalarType> bb(p-Point3<ScalarType>(radius,radius,radius),p+Point3<ScalarType>(radius,radius,radius)); GridGetInBox(sht, markerFunctor, bb, closests); // qDebug("Vertex %i has %i closest", &*viv - &*m.vert.begin(),closests.size()); for(size_t i=0; i<closests.size(); ++i) { ScalarType dist = Distance(p,closests[i]->cP()); if(dist < radius && !closests[i]->IsV()) { // printf("%f %f \n",dist,radius); mergedCnt++; closests[i]->SetV(); closests[i]->P()=p; } } } return mergedCnt; } static std::pair<int,int> RemoveSmallConnectedComponentsSize(MeshType &m, int maxCCSize) { std::vector< std::pair<int, typename MeshType::FacePointer> > CCV; int TotalCC=ConnectedComponents(m, CCV); int DeletedCC=0; ConnectedComponentIterator<MeshType> ci; for(unsigned int i=0;i<CCV.size();++i) { std::vector<typename MeshType::FacePointer> FPV; if(CCV[i].first<maxCCSize) { DeletedCC++; for(ci.start(m,CCV[i].second);!ci.completed();++ci) FPV.push_back(*ci); typename std::vector<typename MeshType::FacePointer>::iterator fpvi; for(fpvi=FPV.begin(); fpvi!=FPV.end(); ++fpvi) Allocator<MeshType>::DeleteFace(m,(**fpvi)); } } return std::make_pair(TotalCC,DeletedCC); } /// Remove the connected components smaller than a given diameter // it returns a pair with the number of connected components and the number of deleted ones. static std::pair<int,int> RemoveSmallConnectedComponentsDiameter(MeshType &m, ScalarType maxDiameter) { std::vector< std::pair<int, typename MeshType::FacePointer> > CCV; int TotalCC=ConnectedComponents(m, CCV); int DeletedCC=0; tri::ConnectedComponentIterator<MeshType> ci; for(unsigned int i=0;i<CCV.size();++i) { Box3<ScalarType> bb; std::vector<typename MeshType::FacePointer> FPV; for(ci.start(m,CCV[i].second);!ci.completed();++ci) { FPV.push_back(*ci); bb.Add((*ci)->P(0)); bb.Add((*ci)->P(1)); bb.Add((*ci)->P(2)); } if(bb.Diag()<maxDiameter) { DeletedCC++; typename std::vector<typename MeshType::FacePointer>::iterator fpvi; for(fpvi=FPV.begin(); fpvi!=FPV.end(); ++fpvi) tri::Allocator<MeshType>::DeleteFace(m,(**fpvi)); } } return std::make_pair(TotalCC,DeletedCC); } /// Remove the connected components greater than a given diameter // it returns a pair with the number of connected components and the number of deleted ones. static std::pair<int,int> RemoveHugeConnectedComponentsDiameter(MeshType &m, ScalarType minDiameter) { std::vector< std::pair<int, typename MeshType::FacePointer> > CCV; int TotalCC=ConnectedComponents(m, CCV); int DeletedCC=0; tri::ConnectedComponentIterator<MeshType> ci; for(unsigned int i=0;i<CCV.size();++i) { Box3f bb; std::vector<typename MeshType::FacePointer> FPV; for(ci.start(m,CCV[i].second);!ci.completed();++ci) { FPV.push_back(*ci); bb.Add((*ci)->P(0)); bb.Add((*ci)->P(1)); bb.Add((*ci)->P(2)); } if(bb.Diag()>minDiameter) { DeletedCC++; typename std::vector<typename MeshType::FacePointer>::iterator fpvi; for(fpvi=FPV.begin(); fpvi!=FPV.end(); ++fpvi) tri::Allocator<MeshType>::DeleteFace(m,(**fpvi)); } } return std::make_pair(TotalCC,DeletedCC); } /** Select the folded faces using an angle threshold on the face normal. The face is selected if the dot product between the face normal and the normal of the plane fitted using the vertices of the one ring faces is below the cosThreshold. The cosThreshold requires a negative cosine value (a positive value is clamp to zero). */ static void SelectFoldedFaceFromOneRingFaces(MeshType &m, ScalarType cosThreshold) { tri::RequireVFAdjacency(m); tri::RequirePerFaceNormal(m); tri::RequirePerVertexNormal(m); vcg::tri::UpdateSelection<MeshType>::FaceClear(m); vcg::tri::UpdateNormal<MeshType>::PerFaceNormalized(m); vcg::tri::UpdateNormal<MeshType>::PerVertexNormalized(m); vcg::tri::UpdateTopology<MeshType>::VertexFace(m); if (cosThreshold > 0) cosThreshold = 0; #pragma omp parallel for schedule(dynamic, 10) for (int i = 0; i < m.face.size(); i++) { std::vector<typename MeshType::VertexPointer> nearVertex; std::vector<typename MeshType::CoordType> point; typename MeshType::FacePointer f = &m.face[i]; for (int j = 0; j < 3; j++) { std::vector<typename MeshType::VertexPointer> temp; vcg::face::VVStarVF<typename MeshType::FaceType>(f->V(j), temp); typename std::vector<typename MeshType::VertexPointer>::iterator iter = temp.begin(); for (; iter != temp.end(); iter++) { if ((*iter) != f->V1(j) && (*iter) != f->V2(j)) { nearVertex.push_back((*iter)); point.push_back((*iter)->P()); } } nearVertex.push_back(f->V(j)); point.push_back(f->P(j)); } if (point.size() > 3) { vcg::Plane3<typename MeshType::ScalarType> plane; vcg::FitPlaneToPointSet(point, plane); float avgDot = 0; for (int j = 0; j < nearVertex.size(); j++) avgDot += plane.Direction().dot(nearVertex[j]->N()); avgDot /= nearVertex.size(); typename MeshType::VertexType::NormalType normal; if (avgDot < 0) normal = -plane.Direction(); else normal = plane.Direction(); if (normal.dot(f->N()) < cosThreshold) f->SetS(); } } } }; // end class /*@}*/ } //End Namespace Tri } // End Namespace vcg #endif
DilationFilter.h
/* * ErosionFilter.h * * Created on: 13.06.2016 * Author: Darius Malysiak */ #ifndef IMAGEPROCESSING_DILATIONFILTER_H_ #define IMAGEPROCESSING_DILATIONFILTER_H_ #include "../BaseObject.h" #include "../DataStructures/Matrix.h" #include "../DataStructures/Image.h" namespace Lazarus { template<typename T> class DilationFilter: public Lazarus::BaseObject { public: static const Lazarus::Matrix2<double>* get_DILATION3x3_KERNEL(double val) { static Lazarus::Matrix2<double> _EROSION_KERNEL; _EROSION_KERNEL.initMatrix(3,3); _EROSION_KERNEL.setData(0,0,val); _EROSION_KERNEL.setData(0,1,val); _EROSION_KERNEL.setData(0,2,val); _EROSION_KERNEL.setData(1,0,val); _EROSION_KERNEL.setData(1,1,val); _EROSION_KERNEL.setData(1,2,val); _EROSION_KERNEL.setData(2,0,val); _EROSION_KERNEL.setData(2,1,val); _EROSION_KERNEL.setData(2,2,val); return &_EROSION_KERNEL; } static const Lazarus::Matrix2<double>* get_DILATION_KERNEL(double val, unsigned int size) { Lazarus::Matrix2<double>* _EROSION_KERNEL = new Lazarus::Matrix2<double>(); _EROSION_KERNEL->initMatrix(size,size); _EROSION_KERNEL->globalSetMatrixVal(val); return _EROSION_KERNEL; } DilationFilter() { mp_filter_mask = NULL; } virtual ~DilationFilter(){} void setDilationKernel(const Lazarus::Matrix2<double>* filter) { this->mp_filter_mask = filter; } /** * We assume a kernel with odd dimensions. The erosion will be computed on an extended image with black borders * such that the kernel can be positioned onto the first image pixel. * Returns the filtered image in case of success otherwise NULL. **/ Lazarus::Image<T>* filterImage( Lazarus::Image<T>* image, double clamping_val=255.0 ) { unsigned int offset_x = (mp_filter_mask->getColumnCount()-1)/2; unsigned int offset_y = (mp_filter_mask->getRowCount()-1)/2; unsigned int image_width = image->getm_width(); unsigned int image_heigth = image->getm_height(); unsigned int channel_count = image->getm_channel_count(); unsigned int filter_width = mp_filter_mask->getColumnCount(); unsigned int filter_height = mp_filter_mask->getRowCount(); if(filter_width % 2 != 1) { printf("filter width %d is not odd\n",filter_width); return NULL; } if(filter_height % 2 != 1) { printf("filter height %d is not odd\n",filter_height); return NULL; } Lazarus::Image<T>* output = new Lazarus::Image<T>( image_width, image_heigth, image->getm_data_alignment() ); Lazarus::Image<T>* temporary = new Lazarus::Image<T>( image_width + 2*offset_x, image_heigth + 2*offset_y, image->getm_data_alignment() ); //fill the output and temp image with black Lazarus::FastKTuple<T> color(channel_count); for(unsigned int i=0; i< channel_count; i++) { color.setElement(i,0); } output->fillImageFast( &color ); temporary->fillImageFast( &color ); //copy the input image into the temp buffer; for(unsigned int i=0; i<image_width; i++) { for(unsigned int j=0; j<image_heigth; j++) { image->getPixelFast( &color,i,j ); temporary->setPixelFast(&color,offset_x + i,offset_y + j); } } //start the convolution process //over every pixel unsigned int c_limit = 0; if(channel_count > 3) c_limit = 3; else c_limit = channel_count; double dmin = std::numeric_limits<double>::min(); #pragma omp parallel for for(unsigned int i=offset_x; i<image_width+(offset_x); i++) { double temp_value = dmin; double filter_value = 0; Lazarus::FastKTuple<T> new_color(channel_count); Lazarus::FastKTuple<T> color_(channel_count); for(unsigned int j=offset_y; j<image_heigth+(offset_y); j++) { //over every color channel for(unsigned int c=0; c<c_limit; c++) { //erosion for(int k=-offset_x; k<=(int)offset_x; ++k) { for(int l=-offset_y; l<=(int)offset_y; ++l) { temporary->getPixelFast(&color_, (unsigned int)((int)i+k), (unsigned int)((int)j+l)); filter_value = mp_filter_mask->getData((unsigned int)((int)offset_x+k), (unsigned int)((int)offset_y+l) ); if( (double)(color_.getElement(c)) + filter_value > temp_value ) { temp_value = (double)(color_.getElement(c))-filter_value; } } } new_color.setElement(c,(T)std::min(std::max(temp_value,(double)std::numeric_limits<T>::min()),clamping_val)); temp_value=std::numeric_limits<double>::min();//reset } //set the alpha value to the image value if(channel_count>3) { new_color.setElement(3,color_.getElement(3)); } output->setPixelFast(&new_color,i-(offset_x),j-(offset_y)); } } //delete the temporary image delete temporary; return output; } /** * We assume a kernel with odd dimensions. The erosion will be computed on an extended image with black borders * such that the kernel can be positioned onto the first image pixel. * Returns the filtered image in case of success otherwise NULL. **/ Lazarus::Image<T>* filterImageBW( Lazarus::Image<T>* image, double white=255.0 ) { unsigned int offset_x = (mp_filter_mask->getColumnCount()-1)/2; unsigned int offset_y = (mp_filter_mask->getRowCount()-1)/2; unsigned int image_width = image->getm_width(); unsigned int image_heigth = image->getm_height(); unsigned int channel_count = image->getm_channel_count(); unsigned int filter_width = mp_filter_mask->getColumnCount(); unsigned int filter_height = mp_filter_mask->getRowCount(); if(filter_width % 2 != 1) { printf("filter width %d is not odd\n",filter_width); return NULL; } if(filter_height % 2 != 1) { printf("filter height %d is not odd\n",filter_height); return NULL; } Lazarus::Image<T>* output = new Lazarus::Image<T>( image_width, image_heigth, image->getm_data_alignment() ); Lazarus::Image<T>* temporary = new Lazarus::Image<T>( image_width + 2*offset_x, image_heigth + 2*offset_y, image->getm_data_alignment() ); //fill the output and temp image with black Lazarus::FastKTuple<T> color(channel_count); for(unsigned int i=0; i< channel_count; i++) { color.setElement(i,0); } output->fillImageFast( &color ); temporary->fillImageFast( &color ); //copy the input image into the temp buffer; for(unsigned int i=0; i<image_width; i++) { for(unsigned int j=0; j<image_heigth; j++) { image->getPixelFast( &color,i,j ); temporary->setPixelFast(&color,offset_x + i,offset_y + j); } } //start the convolution process //over every pixel #pragma omp parallel for for(unsigned int i=offset_x; i<image_width+(offset_x); i++) { bool match = false; double filter_value = 0; Lazarus::FastKTuple<T> new_color(channel_count); Lazarus::FastKTuple<T> color_(channel_count); unsigned int c_limit = std::max(channel_count,(unsigned int)3); for(unsigned int j=offset_y; j<image_heigth+(offset_y); j++) { //over every color channel for(unsigned int c=0; c<c_limit; c++) { //erosion for(int k=-offset_x; k<=(int)offset_x; ++k) { for(int l=-offset_y; l<=(int)offset_y; ++l) { temporary->getPixelFast(&color_, (unsigned int)((int)i+k), (unsigned int)((int)j+l)); filter_value = mp_filter_mask->getData((unsigned int)((int)offset_x+k), (unsigned int)((int)offset_y+l) ); if( color_.getElement(c) == filter_value ) { match = true; break; } } if(match == true)//early break out of outer loop { break; } } if(match == true) { new_color.setElement(c,(T)white); } match=false;//reset } //set the alpha value to the image value if(channel_count>3) { new_color.setElement(3,color_.getElement(3)); } output->setPixelFast(&new_color,i-(offset_x),j-(offset_y)); } } //delete the temporary image delete temporary; return output; } private: const Lazarus::Matrix2<double>* mp_filter_mask; }; } #endif /* IMAGEPROCESSING_EROSIONFILTER_H_ */
rose_firstprivate2.c
#include <omp.h> void goo(double *o1,double *c,int **idx,int len) { int i; for (i = 0; i <= len - 1; i += 1) { int ii; const int *lidx = idx[i]; double volnew_o8 = 0.5 * c[i]; #pragma omp parallel for private (ii) firstprivate (volnew_o8) for (ii = 0; ii <= 5; ii += 1) { int llidx = lidx[ii]; o1[lidx[ii]] += volnew_o8; } } }
mmgraph-exp.h
#ifndef MGRAPH_H #define MGRAPH_H #include "network.h" #include "networkmp.h" template<class TNode> class TMNet; class TSVNode { private: TInt TypeId; TInt Id; TVec<TIntV > InEIdVV, OutEIdVV; TInt InDeg, OutDeg; public: TSVNode() : TypeId(-1), Id(-1), InEIdVV(), OutEIdVV(), InDeg(0), OutDeg(0) { } TSVNode(const int& NTypeId, const int& NId) : TypeId(NTypeId), Id(NId), InEIdVV(), OutEIdVV(), InDeg(0), OutDeg(0) { } TSVNode(const TSVNode& Node) : TypeId(Node.TypeId), Id(Node.Id), InEIdVV(Node.InEIdVV), OutEIdVV(Node.OutEIdVV), InDeg(Node.InDeg), OutDeg(Node.OutDeg) { } TSVNode(const TSVNode& Node, const TIntV& InETypeIdV, const TIntV& OutETypeIdV) : TypeId(Node.TypeId), Id(Node.Id), InEIdVV(Node.InEIdVV.Len()), OutEIdVV(Node.OutEIdVV.Len()), InDeg(0), OutDeg(0) { for (int i = 0; i < InETypeIdV.Len(); i++) { int ETypeId = InETypeIdV[i]; InEIdVV[ETypeId] = Node.InEIdVV[ETypeId]; InDeg += Node.InEIdVV[ETypeId].Len(); } for (int i = 0; i < OutETypeIdV.Len(); i++) { int ETypeId = OutETypeIdV[i]; OutEIdVV[ETypeId] = Node.OutEIdVV[ETypeId]; OutDeg += Node.OutEIdVV[ETypeId].Len(); } } TSVNode(TSIn& SIn) : TypeId(SIn), Id(SIn), InEIdVV(SIn), OutEIdVV(SIn), InDeg(0), OutDeg(0) { } void Save(TSOut& SOut) const { TypeId.Save(SOut); Id.Save(SOut); InEIdVV.Save(SOut); OutEIdVV.Save(SOut); InDeg.Save(SOut); OutDeg.Save(SOut); } int GetTypeId() const { return TypeId; } int GetId() const { return Id; } int GetDeg() const { return GetInDeg() + GetOutDeg(); } int GetInDeg(const int& ETypeId) const {return InEIdVV[ETypeId].Len();} int GetInDeg() const { return InDeg; } int GetOutDeg(int ETypeId) const {return OutEIdVV[ETypeId].Len();} int GetOutDeg() const { return OutDeg; } void AddInETypeIds(const TIntV& ETypeIds) { int MxETypeId = -1; for (int i = 0; i < ETypeIds.Len(); i++) { if (MxETypeId < ETypeIds[i]) { MxETypeId = ETypeIds[i]; } } InEIdVV.Reserve(MxETypeId+1, MxETypeId+1); for (int i = 0; i < ETypeIds.Len(); i++) { InEIdVV[ETypeIds[i]] = TIntV(); } } void AddOutETypeIds(const TIntV& ETypeIds) { int MxETypeId = -1; for (int i = 0; i < ETypeIds.Len(); i++) { if (MxETypeId < ETypeIds[i]) { MxETypeId = ETypeIds[i]; } } OutEIdVV.Reserve(MxETypeId+1, MxETypeId+1); for (int i = 0; i < ETypeIds.Len(); i++) { OutEIdVV[ETypeIds[i]] = TIntV(); } } void AddInNbr(const int& ETypeId, const int& EId) { InEIdVV[ETypeId].Add(EId); InDeg++; } void AddOutNbr(const int& ETypeId, const int& EId) { OutEIdVV[ETypeId].Add(EId); OutDeg++; } void DelInNbr(const int& ETypeId, const int& EId) { InEIdVV[ETypeId].DelIfIn(EId); InDeg--; } void DelOutNbr(const int& ETypeId, const int& EId) { OutEIdVV[ETypeId].DelIfIn(EId); OutDeg--; } int GetInEId(const int& EdgeN) const { int CumSum = 0; int ETypeId = 0; for (; ETypeId < InEIdVV.Len(); ETypeId++) { CumSum += InEIdVV[ETypeId].Len(); if (CumSum > EdgeN) { CumSum -= InEIdVV[ETypeId].Len(); break; } } return InEIdVV[ETypeId][EdgeN-CumSum]; } int GetOutEId(const int& EdgeN) const { int CumSum = 0; int ETypeId = 0; for (; ETypeId < OutEIdVV.Len(); ETypeId++) { CumSum += OutEIdVV[ETypeId].Len(); if (CumSum > EdgeN) { CumSum -= OutEIdVV[ETypeId].Len(); break; } } return OutEIdVV[ETypeId][EdgeN-CumSum]; } void GetInEIdV(TIntV& EIdV) const { EIdV.Gen(InDeg, 0); for (int i = 0; i < InEIdVV.Len(); i++) { EIdV.AddV(InEIdVV[i]); } } void GetOutEIdV(TIntV& EIdV) const { EIdV.Gen(OutDeg, 0); for (int i = 0; i < OutEIdVV.Len(); i++) { EIdV.AddV(OutEIdVV[i]); } } void GetInEIdV(const TInt ETypeId, TIntV& EIdV) const { EIdV = InEIdVV[ETypeId.Val]; } void GetOutEIdV(const TInt ETypeId, TIntV& EIdV) const { EIdV = OutEIdVV[ETypeId.Val]; } void GetInEIdV(const TIntV& ETypeIdV, TIntV& EIdV) const { EIdV.Reserve(InDeg, 0); for (int k = 0; k < ETypeIdV.Len(); k++) { EIdV.AddV(InEIdVV[ETypeIdV[k].Val]); } } void GetOutEIdV(const TIntV& ETypeIdV, TIntV& EIdV) const { EIdV.Reserve(OutDeg, 0); for (int k = 0; k < ETypeIdV.Len(); k++) { EIdV.AddV(OutEIdVV[ETypeIdV[k].Val]); } } friend class TMNet<TSVNode>; }; class TMVNode { private: TInt TypeId; // Node type ID TInt Id; // Get global ID TIntV InEIdV, OutEIdV; // Vectors of EIds TIntV InETypeIdV, OutETypeIdV; // Vectors of ETypeIds public: TMVNode() : TypeId(-1), Id(-1), InEIdV(), OutEIdV(), InETypeIdV(), OutETypeIdV() { } TMVNode(const int& NTypeId, const int& NId) : TypeId(NTypeId), Id(NId), InEIdV(), OutEIdV(), InETypeIdV(), OutETypeIdV() { } TMVNode(const TMVNode& Node) : TypeId(Node.TypeId), Id(Node.Id), InEIdV(Node.InEIdV), OutEIdV(Node.OutEIdV), InETypeIdV(Node.InETypeIdV), OutETypeIdV(Node.OutETypeIdV) { } TMVNode(const TMVNode& Node, const TIntV& InETypeIdV, const TIntV& OutETypeIdV) : TypeId(Node.TypeId), Id(Node.Id), InEIdV(Node.InEIdV.Len()), OutEIdV(Node.OutEIdV.Len()), InETypeIdV(Node.InETypeIdV.Len()), OutETypeIdV(Node.OutETypeIdV.Len()) { TIntSet InETypeIdSet(InETypeIdV); for (int i = 0; i < Node.InEIdV.Len(); i++) { if (InETypeIdSet.IsKey(Node.InETypeIdV[i])) { InEIdV.Add(Node.InEIdV[i]); } } TIntSet OutETypeIdSet(OutETypeIdV); for (int i = 0; i < Node.OutEIdV.Len(); i++) { if (OutETypeIdSet.IsKey(Node.OutETypeIdV[i])) { OutEIdV.Add(Node.OutEIdV[i]); } } } TMVNode(TSIn& SIn) : TypeId(SIn), Id(SIn), InEIdV(SIn), OutEIdV(SIn), InETypeIdV(SIn), OutETypeIdV(SIn) { } void Save(TSOut& SOut) const { TypeId.Save(SOut); Id.Save(SOut); InEIdV.Save(SOut); OutEIdV.Save(SOut); InETypeIdV.Save(SOut); OutETypeIdV.Save(SOut); } int GetTypeId() const { return TypeId; } int GetId() const { return Id; } int GetDeg() const { return GetInDeg() + GetOutDeg(); } int GetInDeg() const { return InEIdV.Len(); } int GetOutDeg() const { return OutEIdV.Len(); } int GetInEId(const int& EdgeN) const { return InEIdV[EdgeN]; } int GetOutEId(const int& EdgeN) const { return OutEIdV[EdgeN]; } int GetNbrEId(const int& EdgeN) const { return EdgeN<GetOutDeg()?GetOutEId(EdgeN):GetInEId(EdgeN-GetOutDeg()); } void GetInEIdV(TIntV& EIdV) const { EIdV = InEIdV; } void GetOutEIdV(TIntV& EIdV) const { EIdV = OutEIdV; } bool IsInEId(const int& EId) const { return InEIdV.SearchForw(EId) != -1; } bool IsOutEId(const int& EId) const { return OutEIdV.SearchForw(EId) != -1; } void AddInETypeIds(const TIntV& ETypeIds) { } // Do nothing. void AddOutETypeIds(const TIntV& ETypeIds) { } // Do nothing. void AddInNbr(const int& ETypeId, const int& EId) { InETypeIdV.Add(ETypeId); InEIdV.Add(EId); } void AddOutNbr(const int& ETypeId, const int& EId) { OutETypeIdV.Add(ETypeId); OutEIdV.Add(EId); } void DelInNbr(const int& ETypeId, const int& EId) { int EIdN = InEIdV.SearchBack(EId); InETypeIdV.Del(EIdN); InEIdV.Del(EIdN); } void DelOutNbr(const int& ETypeId, const int& EId) { int EIdN = OutEIdV.SearchBack(EId); OutETypeIdV.Del(EIdN); OutEIdV.Del(EIdN); } void GetInEIdV(const TInt& ETypeId, TIntV& EIdV) const { EIdV.Reduce(0); // Clear for (int i = 0; i < InEIdV.Len(); i++) { if (InETypeIdV[i] == ETypeId) { EIdV.Add(InEIdV[i]); } } } void GetOutEIdV(const TInt& ETypeId, TIntV& EIdV) const { EIdV.Reduce(0); // Clear for (int i = 0; i < OutEIdV.Len(); i++) { if (OutETypeIdV[i] == ETypeId) { EIdV.Add(OutEIdV[i]); } } } void GetInEIdV(const TIntV& ETypeIdV, TIntV& EIdV) const { EIdV.Reserve(InEIdV.Len(), 0); for (int k = 0; k < ETypeIdV.Len(); k++) { TInt ETypeId = ETypeIdV[k]; for (int i = 0; i < InETypeIdV.Len(); i++) { if (InETypeIdV[i] == ETypeId) { EIdV.Add(InEIdV[i]); } } } } void GetOutEIdV(const TIntV& ETypeIdV, TIntV& EIdV) const { EIdV.Reserve(OutEIdV.Len(), 0); for (int k = 0; k < ETypeIdV.Len(); k++) { TInt ETypeId = ETypeIdV[k]; for (int i = 0; i < OutETypeIdV.Len(); i++) { if (OutETypeIdV[i] == ETypeId) { EIdV.Add(OutEIdV[i]); } } } } friend class TMNet<TMVNode>; }; class TCVNode { public: static const int DEF_WEIGHT; static const int DEF_WEIGHT_COEFF; static const int DEF_EXPAND_RATIO; private: static void RedistributeEIds(const TIntV& Weights, TIntV& EIdV, TIntV& TypeIndexV, TIntV& TypeDegV) { IAssertR(TypeIndexV.Len() == TypeDegV.Len(), TStr::Fmt("The node is in inconsistent state.")); // Get new TypeIndex int NTypes = Weights.Len(); TIntV NewTypeIndexV(NTypes); // number of types int CumSum = 0; // cumulative sum of weights for (int ETypeId = 0; ETypeId < NTypes; ETypeId++) { NewTypeIndexV[ETypeId] = CumSum; CumSum += Weights[ETypeId] * DEF_WEIGHT_COEFF; } TIntV NewEIdV(CumSum); // Copy data from old positions to new positions for (int ETypeId = TypeIndexV.Len() - 1; ETypeId >= 0; ETypeId--) { IAssertR(CumSum >= NewTypeIndexV[ETypeId] + TypeDegV[ETypeId], TStr::Fmt("The node is in inconsistent state.")); for (int i = 0; i < TypeDegV[ETypeId]; i++) { NewEIdV[NewTypeIndexV[ETypeId] + i] = EIdV[TypeIndexV[ETypeId] + i]; } } TypeDegV.Reserve(NTypes, NTypes); TypeIndexV = NewTypeIndexV; EIdV = NewEIdV; } private: TInt TypeId; // Node type ID TInt Id; // Get global ID TIntV InEIdV, OutEIdV; TInt InDeg, OutDeg; TIntV InTypeIndexV, OutTypeIndexV; TIntV InTypeDegV, OutTypeDegV; public: TCVNode() : TypeId(-1), Id(-1), InEIdV(), OutEIdV(), InDeg(0), OutDeg(0), InTypeIndexV(), OutTypeIndexV(), InTypeDegV(), OutTypeDegV() { } TCVNode(const int& NTypeId, const int& NId) : TypeId(NTypeId), Id(NId), InEIdV(), OutEIdV(), InDeg(0), OutDeg(0), InTypeIndexV(), OutTypeIndexV(), InTypeDegV(), OutTypeDegV() { } TCVNode(const TCVNode& Node) : TypeId(Node.TypeId), Id(Node.Id), InEIdV(Node.InEIdV), OutEIdV(Node.OutEIdV), InDeg(Node.InDeg), OutDeg(Node.OutDeg), InTypeIndexV(Node.InTypeIndexV), OutTypeIndexV(Node.OutTypeIndexV), InTypeDegV(Node.InTypeDegV), OutTypeDegV(Node.OutTypeDegV) { } TCVNode(const TCVNode& Node, const TIntV& InETypeIdV, const TIntV& OutETypeIdV) : TypeId(Node.TypeId), Id(Node.Id), InDeg(0), OutDeg(0), InTypeIndexV(Node.InTypeIndexV.Len()), OutTypeIndexV(Node.OutTypeIndexV.Len()), InTypeDegV(Node.InTypeDegV.Len()), OutTypeDegV(Node.OutTypeDegV.Len()) { for (TIntV::TIter iter = InETypeIdV.BegI(); iter < InETypeIdV.EndI(); iter++) { InDeg += Node.InTypeDegV[*iter]; InTypeDegV[*iter] = Node.InTypeDegV[*iter]; } int index = 0; InEIdV.Gen(InDeg); TIntSet InETypeIdSet(InETypeIdV); for (int ETypeId = 0; ETypeId < InTypeIndexV.Len(); ETypeId++) { InTypeIndexV[ETypeId] = index; if (InETypeIdSet.IsKey(ETypeId)) { for (int i = Node.InTypeIndexV[ETypeId]; i < Node.InTypeIndexV[ETypeId] + Node.InTypeDegV[ETypeId]; i++) { InEIdV[index++] = Node.InEIdV[i]; } } } IAssert(index == InDeg); for (TIntV::TIter iter = OutETypeIdV.BegI(); iter < OutETypeIdV.EndI(); iter++) { OutDeg += Node.OutTypeDegV[*iter]; OutTypeDegV[*iter] = Node.OutTypeDegV[*iter]; } index = 0; OutEIdV.Gen(OutDeg); TIntSet OutETypeIdSet(OutETypeIdV); for (int ETypeId = 0; ETypeId < OutTypeIndexV.Len(); ETypeId++) { OutTypeIndexV[ETypeId] = index; if (OutETypeIdSet.IsKey(ETypeId)) { for (int i = Node.OutTypeIndexV[ETypeId]; i < Node.OutTypeIndexV[ETypeId] + Node.OutTypeDegV[ETypeId]; i++) { OutEIdV[index++] = Node.OutEIdV[i]; } } } IAssert(index == OutDeg); } TCVNode(TSIn& SIn) : TypeId(SIn), Id(SIn), InEIdV(SIn), OutEIdV(SIn), InDeg(SIn), OutDeg(SIn), InTypeIndexV(SIn), OutTypeIndexV(SIn), InTypeDegV(SIn), OutTypeDegV(SIn) { } void Save(TSOut& SOut) const { TypeId.Save(SOut); Id.Save(SOut); InEIdV.Save(SOut); OutEIdV.Save(SOut); InDeg.Save(SOut); OutDeg.Save(SOut); InTypeIndexV.Save(SOut); OutTypeIndexV.Save(SOut); InTypeDegV.Save(SOut); OutTypeDegV.Save(SOut); } int GetTypeId() const { return TypeId; } int GetId() const { return Id; } int GetDeg() const { return InDeg + OutDeg; } int GetInDeg() const { return InDeg; } int GetOutDeg() const { return OutDeg; } int GetInDeg(const int& ETypeId) const { return InTypeDegV[ETypeId]; } int GetOutDeg(const int& ETypeId) const { return OutTypeDegV[ETypeId]; } int GetInEId(const int& EdgeN) const { int CumSum = 0; int ETypeId = 0; for (; ETypeId < InTypeDegV.Len(); ETypeId++) { CumSum += InTypeDegV[ETypeId]; if (CumSum > EdgeN) { CumSum -= InTypeDegV[ETypeId]; break; } } return InEIdV[InTypeIndexV[ETypeId] + EdgeN - CumSum]; } int GetOutEId(const int& EdgeN) const { int CumSum = 0; int ETypeId = 0; for (; ETypeId < OutTypeDegV.Len(); ETypeId++) { CumSum += OutTypeDegV[ETypeId]; if (CumSum > EdgeN) { CumSum -= OutTypeDegV[ETypeId]; break; } } return OutEIdV[OutTypeIndexV[ETypeId] + EdgeN - CumSum]; } int GetNbrEId(const int& EdgeN) const { return EdgeN<GetOutDeg()?GetOutEId(EdgeN):GetInEId(EdgeN-GetOutDeg()); } void GetInEIdV(TIntV& EIdV) const { EIdV.Gen(InDeg, 0); for (int ETypeId = 0; ETypeId < InTypeDegV.Len(); ETypeId++) { for (int i = InTypeIndexV[ETypeId]; i < InTypeIndexV[ETypeId] + InTypeDegV[ETypeId]; i++) { EIdV.Add(InEIdV[i]); } } } void GetOutEIdV(TIntV& EIdV) const { EIdV.Gen(OutDeg, 0); for (int ETypeId = 0; ETypeId < OutTypeDegV.Len(); ETypeId++) { for (int i = OutTypeIndexV[ETypeId]; i < OutTypeIndexV[ETypeId] + OutTypeDegV[ETypeId]; i++) { EIdV.Add(OutEIdV[i]); } } } //bool IsInEId(const int& EId) const { return InEIdV.SearchBin(EId) != -1; } //bool IsOutEId(const int& EId) const { return OutEIdV.SearchBin(EId) != -1; } void AddInETypeIds(const TIntV& ETypeIds) { if (ETypeIds.Len() == 0) { return; } int MxETypeId = InTypeIndexV.Len() - 1; for (TIntV::TIter iter = ETypeIds.BegI(); iter < ETypeIds.EndI(); iter++) { if (MxETypeId < *iter) { MxETypeId = *iter; } } TIntV InWeights(MxETypeId + 1); for (int ETypeId = 0; ETypeId < InTypeDegV.Len(); ETypeId++) { InWeights[ETypeId] = InTypeDegV[ETypeId]; } for (TIntV::TIter iter = ETypeIds.BegI(); iter < ETypeIds.EndI(); iter++) { InWeights[*iter] = DEF_WEIGHT; } RedistributeEIds(InWeights, InEIdV, InTypeIndexV, InTypeDegV); } void AddOutETypeIds(const TIntV& ETypeIds) { if (ETypeIds.Len() == 0) { return; } int MxETypeId = OutTypeIndexV.Len() - 1; for (TIntV::TIter iter = ETypeIds.BegI(); iter < ETypeIds.EndI(); iter++) { if (MxETypeId < *iter) { MxETypeId = *iter; } } TIntV OutWeights(MxETypeId + 1); for (int ETypeId = 0; ETypeId < OutTypeDegV.Len(); ETypeId++) { OutWeights[ETypeId] = OutTypeDegV[ETypeId]; } for (TIntV::TIter iter = ETypeIds.BegI(); iter < ETypeIds.EndI(); iter++) { OutWeights[*iter] = DEF_WEIGHT; } RedistributeEIds(OutWeights, OutEIdV, OutTypeIndexV, OutTypeDegV); } void AddInNbr(const int& ETypeId, const int& EId) { int Deg = InTypeDegV[ETypeId]; int Capacity = (ETypeId == (InTypeIndexV.Len()-1)) ? InEIdV.Len() : InTypeIndexV[ETypeId+1].Val; Capacity -= InTypeIndexV[ETypeId]; if (Deg >= Capacity) { IAssertR(Deg == Capacity, TStr::Fmt("The node is in inconsistent state.")); TIntV Weights(InTypeDegV); Weights[ETypeId] = (Weights[ETypeId] + 4) * DEF_EXPAND_RATIO; RedistributeEIds(Weights, InEIdV, InTypeIndexV, InTypeDegV); } InEIdV[InTypeIndexV[ETypeId] + Deg] = EId; InTypeDegV[ETypeId]++; InDeg++; } void AddOutNbr(const int& ETypeId, const int& EId) { int Deg = OutTypeDegV[ETypeId]; int Capacity = (ETypeId == (OutTypeIndexV.Len()-1)) ? OutEIdV.Len() : OutTypeIndexV[ETypeId+1].Val; Capacity -= OutTypeIndexV[ETypeId]; if (Deg >= Capacity) { IAssertR(Deg == Capacity, TStr::Fmt("The node is in inconsistent state.")); TIntV Weights(OutTypeDegV); Weights[ETypeId] = (Weights[ETypeId] + 4) * DEF_EXPAND_RATIO; // + 4 to avoid 0 RedistributeEIds(Weights, OutEIdV, OutTypeIndexV, OutTypeDegV); } OutEIdV[OutTypeIndexV[ETypeId] + Deg] = EId; OutTypeDegV[ETypeId]++; OutDeg++; } /// Delete an edge with ID EId and type ETypeId. void DelInNbr(const int& ETypeId, const int& EId) { int ValN = InEIdV.SearchForw(EId, InTypeIndexV[ETypeId]); for (int MValN=ValN+1; MValN<InTypeIndexV[ETypeId]+InTypeDegV[ETypeId]; MValN++){ InEIdV[MValN-1]=InEIdV[MValN]; } InDeg--; InTypeDegV[ETypeId]--; } void DelOutNbr(const int& ETypeId, const int& EId) { int ValN = OutEIdV.SearchForw(EId, OutTypeIndexV[ETypeId]); for (int MValN=ValN+1; MValN<OutTypeIndexV[ETypeId]+OutTypeDegV[ETypeId]; MValN++){ OutEIdV[MValN-1]=OutEIdV[MValN]; } OutDeg--; OutTypeDegV[ETypeId]--; } void GetInEIdV(const TInt& ETypeId, TIntV& EIdV) const { int Sz = InTypeDegV[ETypeId].Val; EIdV.Reserve(Sz, Sz); int Ind = InTypeIndexV[ETypeId].Val; for (int i = 0; i < Sz; i++) { EIdV[i] = InEIdV[Ind+i]; } } void GetOutEIdV(const TInt& ETypeId, TIntV& EIdV) const { int Sz = OutTypeDegV[ETypeId].Val; EIdV.Reserve(Sz, Sz); int Ind = OutTypeIndexV[ETypeId].Val; for (int i = 0; i < Sz; i++) { EIdV[i] = OutEIdV[Ind+i]; } } void GetInEIdV(const TIntV& ETypeIdV, TIntV& EIdV) const { int Sz = 0; for (int k = 0; k < ETypeIdV.Len(); k++) { Sz += InTypeDegV[ETypeIdV[k]].Val; } EIdV.Reserve(Sz, 0); int Ind; for (int k = 0; k < ETypeIdV.Len(); k++) { Ind = InTypeIndexV[ETypeIdV[k]].Val; for (int i = 0; i < InTypeDegV[ETypeIdV[k]]; i++) { EIdV.Add(InEIdV[Ind]); } } } void GetOutEIdV(const TIntV& ETypeIdV, TIntV& EIdV) const { int Sz = 0; for (int k = 0; k < ETypeIdV.Len(); k++) { Sz += OutTypeDegV[ETypeIdV[k]].Val; } EIdV.Reserve(Sz, 0); int Ind; for (int k = 0; k < ETypeIdV.Len(); k++) { Ind = OutTypeIndexV[ETypeIdV[k]].Val; for (int i = 0; i < OutTypeDegV[ETypeIdV[k]]; i++) { EIdV.Add(OutEIdV[Ind]); } } } friend class TMNet<TCVNode>; }; //#////////////////////////////////////////////// /// Directed multigraph with node edge attributes. template<class TNode> class TMNet { public: typedef TMNet TNet; typedef TPt<TMNet> PNet; public: class TEdge { private: TInt TypeId, Id, SrcNId, DstNId; public: TEdge() : TypeId(-1), Id(-1), SrcNId(-1), DstNId(-1) { } TEdge(const int& ETypeId, const int& EId, const int& SourceNId, const int& DestNId) : TypeId(ETypeId), Id(EId), SrcNId(SourceNId), DstNId(DestNId) { } TEdge(const TEdge& Edge) : TypeId(Edge.TypeId), Id(Edge.Id), SrcNId(Edge.SrcNId), DstNId(Edge.DstNId) { } TEdge(TSIn& SIn) : TypeId(SIn), Id(SIn), SrcNId(SIn), DstNId(SIn) { } void Save(TSOut& SOut) const { TypeId.Save(SOut), Id.Save(SOut); SrcNId.Save(SOut); DstNId.Save(SOut); } int GetTypeId() const { return TypeId; } int GetId() const { return Id; } int GetSrcNId() const { return SrcNId; } int GetDstNId() const { return DstNId; } friend class TMNet; }; class TNodeType { private: TInt Id; TStr Name; TInt MxNId; THash<TInt, TNode> NodeH; public: TNodeType() : Id(-1), Name(), MxNId(0), NodeH(){ } TNodeType(const int& NTypeId, const TStr& NTypeName) : Id(NTypeId), Name(NTypeName), MxNId(0), NodeH(){ } TNodeType(const TNodeType& NodeType) : Id(NodeType.Id), Name(NodeType.Name), MxNId(NodeType.MxNId), NodeH(NodeType.NodeH) { } TNodeType(const TNodeType& NodeType, const TIntV& InETypeIdV, const TIntV& OutETypeIdV) : Id(NodeType.Id), Name(NodeType.Name), MxNId(NodeType.MxNId), NodeH(NodeType.NodeH.Len()) { for (typename THash<TInt,TNode>::TIter iter = NodeType.NodeH.BegI(); iter < NodeType.NodeH.EndI(); iter++) { TNode NewNode(iter.GetDat(), InETypeIdV, OutETypeIdV); NodeH.AddDat(iter.GetKey(), NewNode); } } TNodeType(TSIn& SIn) : Id(SIn), Name(SIn), MxNId(SIn), NodeH(SIn) { } void Save(TSOut& SOut) const { Id.Save(SOut); Name.Save(SOut); MxNId.Save(SOut); NodeH.Save(SOut); } int GetId() const { return Id; } TStr GetName() const { return Name; } int GetMxNId() const { return MxNId; } friend class TMNet; }; /// Node iterator. Only forward iteration (operator++) is supported. template<class TEdge> class TMNodeI { private: typedef typename THash<TInt, TNode>::TIter THashIter; typedef typename TVec<TNodeType>::TIter TTypeIter; TTypeIter VecI; TTypeIter VecEndI; THashIter HashI; const TMNet *Graph; private: THashIter VecElemBegI() { return (*VecI).NodeH.BegI(); } void FindNextNonEmptyHashI() { while (HashI.IsEnd() && VecI < VecEndI) { VecI++; HashI = VecElemBegI(); } } public: TMNodeI() : VecI(), VecEndI(), HashI(), Graph(NULL) { } TMNodeI(const TTypeIter& TypeIter, const THashIter& NodeIter, const TMNet* GraphPt) : VecI(TypeIter), VecEndI(GraphPt->TypeNodeV.EndI()), HashI(NodeIter), Graph(GraphPt) { } TMNodeI(const TTypeIter& TypeIter, const TMNet* GraphPt) : VecI(TypeIter), VecEndI(GraphPt->TypeNodeV.EndI()), Graph(GraphPt) { if (VecI < VecEndI) { HashI = VecElemBegI(); FindNextNonEmptyHashI(); } else { HashI = THashIter(); } } TMNodeI(const TMNodeI& NodeI) : VecI(NodeI.VecI), VecEndI(NodeI.VecEndI), HashI(NodeI.HashI), Graph(NodeI.Graph) { } TMNodeI& operator = (const TMNodeI& NodeI) { VecI=NodeI.VecI; VecEndI=NodeI.VecEndI; HashI=NodeI.HashI; Graph=NodeI.Graph; return *this; } /// Increment iterator. TMNodeI& operator++ (int) { HashI++; FindNextNonEmptyHashI(); return *this; } bool operator < (const TMNodeI& NodeI) const { return VecI < NodeI.VecI || HashI < NodeI.HashI; } bool operator == (const TMNodeI& NodeI) const { return VecI == NodeI.VecI && HashI == NodeI.HashI; } /// Returns ID of the current node. int GetId() const { return HashI.GetDat().GetId(); } /// Returns the type-wise ID of the current node. int GetLocalId() const { return TMNet::GetLocalNId(GetId()); } /// Returns type ID of the current node. int GetTypeId() const { return HashI.GetDat().GetTypeId(); } /// Returns degree of the current node, the sum of in-degree and out-degree. int GetDeg() const { return HashI.GetDat().GetDeg(); } /// Returns in-degree of the current node. int GetInDeg() const { return HashI.GetDat().GetInDeg(); } /// Returns out-degree of the current node. int GetOutDeg() const { return HashI.GetDat().GetOutDeg(); } /// Returns ID of EdgeN-th in-node (the node pointing to the current node). int GetInNId(const int& EdgeN) const { return Graph->GetEdge(HashI.GetDat().GetInEId(EdgeN)).GetSrcNId(); } /// Returns ID of EdgeN-th out-node (the node the current node points to). int GetOutNId(const int& EdgeN) const { return Graph->GetEdge(HashI.GetDat().GetOutEId(EdgeN)).GetDstNId(); } /// Returns ID of EdgeN-th neighboring node. int GetNbrNId(const int& EdgeN) const { const TEdge& E = Graph->GetEdge(HashI.GetDat().GetNbrEId(EdgeN)); return GetId()==E.GetSrcNId() ? E.GetDstNId():E.GetSrcNId(); } /// Tests whether node with ID NId points to the current node. bool IsInNId(const int& NId) const { const TNode& Node = HashI.GetDat(); for (int edge = 0; edge < Node.GetInDeg(); edge++) { if (NId == Graph->GetEdge(Node.GetInEId(edge)).GetSrcNId()) { return true; } } return false; } /// Tests whether the current node points to node with ID NId. bool IsOutNId(const int& NId) const { const TNode& Node = HashI.GetDat(); for (int edge = 0; edge < Node.GetOutDeg(); edge++) { if (NId == Graph->GetEdge(Node.GetOutEId(edge)).GetDstNId()) { return true; } } return false; } /// Tests whether node with ID NId is a neighbor of the current node. bool IsNbrNId(const int& NId) const { return IsOutNId(NId) || IsInNId(NId); } /// Returns ID of EdgeN-th in-edge. int GetInEId(const int& EdgeN) const { return HashI.GetDat().GetInEId(EdgeN); } /// Returns ID of EdgeN-th out-edge. int GetOutEId(const int& EdgeN) const { return HashI.GetDat().GetOutEId(EdgeN); } /// Returns ID of EdgeN-th in or out-edge. int GetNbrEId(const int& EdgeN) const { return HashI.GetDat().GetNbrEId(EdgeN); } /// Tests whether the edge with ID EId is an in-edge of current node. bool IsInEId(const int& EId) const { return HashI.GetDat().IsInEId(EId); } /// Tests whether the edge with ID EId is an out-edge of current node. bool IsOutEId(const int& EId) const { return HashI.GetDat().IsOutEId(EId); } /// Tests whether the edge with ID EId is an in or out-edge of current node. bool IsNbrEId(const int& EId) const { return IsInEId(EId) || IsOutEId(EId); } /* /// Gets vector of attribute names. void GetAttrNames(TStrV& Names) const { Graph->AttrNameNI(GetId(), Names); } /// Gets vector of attribute values. void GetAttrVal(TStrV& Val) const { Graph->AttrValueNI(GetId(), Val); } /// Gets vector of int attribute names. void GetIntAttrNames(TStrV& Names) const { Graph->IntAttrNameNI(GetId(), Names); } /// Gets vector of int attribute values. void GetIntAttrVal(TIntV& Val) const { Graph->IntAttrValueNI(GetId(), Val); } /// Gets vector of str attribute names. void GetStrAttrNames(TStrV& Names) const { Graph->StrAttrNameNI(GetId(), Names); } /// Gets vector of str attribute values. void GetStrAttrVal(TStrV& Val) const { Graph->StrAttrValueNI(GetId(), Val); } /// Gets vector of flt attribute names. void GetFltAttrNames(TStrV& Names) const { Graph->FltAttrNameNI(GetId(), Names); } /// Gets vector of flt attribute values. void GetFltAttrVal(TFltV& Val) const { Graph->FltAttrValueNI(GetId(), Val); } */ }; typedef TMNodeI<TEdge> TNodeI; /// Edge iterator. Only forward iteration (operator++) is supported. class TEdgeI { private: typedef typename THash<TInt, TEdge>::TIter THashIter; THashIter EdgeHI; const TMNet *Graph; public: TEdgeI() : EdgeHI(), Graph(NULL) { } TEdgeI(const THashIter& EdgeHIter, const TMNet *GraphPt) : EdgeHI(EdgeHIter), Graph(GraphPt) { } TEdgeI(const TEdgeI& EdgeI) : EdgeHI(EdgeI.EdgeHI), Graph(EdgeI.Graph) { } TEdgeI& operator = (const TEdgeI& EdgeI) { if (this!=&EdgeI) { EdgeHI=EdgeI.EdgeHI; Graph=EdgeI.Graph; } return *this; } /// Increment iterator. TEdgeI& operator++ (int) { EdgeHI++; return *this; } bool operator < (const TEdgeI& EdgeI) const { return EdgeHI < EdgeI.EdgeHI; } bool operator == (const TEdgeI& EdgeI) const { return EdgeHI == EdgeI.EdgeHI; } /// Returns edge ID. int GetId() const { return EdgeHI.GetDat().GetId(); } /// Returns edge's type ID int GetTypeId() const { return EdgeHI.GetDat().GetTypeId(); } /// Returns the source of the edge. int GetSrcNId() const { return EdgeHI.GetDat().GetSrcNId(); } /// Returns the destination of the edge. int GetDstNId() const { return EdgeHI.GetDat().GetDstNId(); } /* /// Gets vector of attribute names. void GetAttrNames(TStrV& Names) const { Graph->AttrNameEI(GetId(), Names); } /// Gets vector of attribute values. void GetAttrVal(TStrV& Val) const { Graph->AttrValueEI(GetId(), Val); } /// Gets vector of int attribute names. void GetIntAttrNames(TStrV& Names) const { Graph->IntAttrNameEI(GetId(), Names); } /// Gets vector of int attribute values. void GetIntAttrVal(TIntV& Val) const { Graph->IntAttrValueEI(GetId(), Val); } /// Gets vector of str attribute names. void GetStrAttrNames(TStrV& Names) const { Graph->StrAttrNameEI(GetId(), Names); } /// Gets vector of str attribute values. void GetStrAttrVal(TStrV& Val) const { Graph->StrAttrValueEI(GetId(), Val); } /// Gets vector of flt attribute names. void GetFltAttrNames(TStrV& Names) const { Graph->FltAttrNameEI(GetId(), Names); } /// Gets vector of flt attribute values. void GetFltAttrVal(TFltV& Val) const { Graph->FltAttrValueEI(GetId(), Val); } */ friend class TMNet; }; private: static const int NTYPEID_NBITS = 3; // The number of types must be at most 2^NTYPEID_NBITS static const int NTYPEID_FLAG = (1 << NTYPEID_NBITS) - 1; static int GetGlobalNId(const int& NTypeId, const int& NId) { return (NId << NTYPEID_NBITS) + NTypeId;} private: TCRef CRef; TInt MxNId; TInt MxEId; THash<TStr, int> NTypeH; THash<TStr, int> ETypeH; TVec<TNodeType> TypeNodeV; TIntV EdgeSzV; // maintain the number of edges of each type THash<TInt, TEdge> EdgeH; int Sz; TVec<TIntV> InETypes; TVec<TIntV> OutETypes; /// KeyToIndexType[N|E]: Key->(Type,Index). TStrIntPrH KeyToIndexTypeN, KeyToIndexTypeE; enum { IntType, StrType, FltType }; private: TNode& GetNode(const int&NId) { int NTypeId = GetNTypeId(NId); int LocalNId = GetLocalNId(NId); return GetNode(NTypeId, LocalNId); } const TNode& GetNode(const int&NId) const { int NTypeId = GetNTypeId(NId); int LocalNId = GetLocalNId(NId); return GetNode(NTypeId, LocalNId); } TNode& GetNode(const int& NTypeId, const int& NId) { return TypeNodeV[NTypeId].NodeH.GetDat(NId); } const TNode& GetNode(const int& NTypeId, const int& NId) const { return TypeNodeV[NTypeId].NodeH.GetDat(NId); } TEdge& GetEdge(const int& EId) { return EdgeH.GetDat(EId); } const TEdge& GetEdge(const int& EId) const { return EdgeH.GetDat(EId); } void AssertNTypeId(const int NTypeId) const { IAssertR(IsNTypeId(NTypeId), TStr::Fmt("NodeTypeId %d does not exist", NTypeId)); } public: TMNet() : CRef(), MxEId(0), NTypeH(), ETypeH(), TypeNodeV(), EdgeH(), Sz(0), InETypes(), OutETypes(), KeyToIndexTypeN(), KeyToIndexTypeE() { } TMNet(const TMNet& Graph) : MxEId(Graph.MxEId), NTypeH(Graph.NTypeH), ETypeH(Graph.ETypeH), TypeNodeV(Graph.TypeNodeV), EdgeH(Graph.EdgeH), Sz(Graph.Sz), InETypes(Graph.InETypes), OutETypes(Graph.OutETypes), KeyToIndexTypeN(), KeyToIndexTypeE() { } /// Static cons returns pointer to graph. Ex: PNEANet Graph=TNEANet::New(). static TPt<TMNet<TNode> > New() { return TPt<TMNet<TNode> >(new TMNet()); } TMNet& operator = (const TMNet& Graph) { if (this!=&Graph) { MxEId=Graph.MxEId; NTypeH=Graph.NTypeH; ETypeH=Graph.ETypeH; TypeNodeV=Graph.TypeNodeV; EdgeH=Graph.EdgeH; Sz=Graph.Sz; InETypes=Graph.InETypes; OutETypes=Graph.OutETypes; KeyToIndexTypeN=Graph.KeyToIndexTypeN; KeyToIndexTypeE=Graph.KeyToIndexTypeE;} return *this; } bool HasFlag(const TGraphFlag& Flag) const { if (Flag == gfDirected) { return true; } else if (Flag == gfMultiGraph) { return true; } else return false; } /// Gets the NTypeId static int GetNTypeId(const int& NId) { return NId & NTYPEID_FLAG; } // Assuming that GlobalNId is positive here static int GetLocalNId(const int& GlobalNId) { return GlobalNId >> NTYPEID_NBITS; } /// Returns an ID that is larger than any node type ID in the network. int GetMxNTypeId() const { return TypeNodeV.Len(); } /// Adds a new type with the given string into the graph. int AddNType(const TStr& NTypeName) { int KeyId = NTypeH.GetKeyId(NTypeName); // Has the type been added? if (KeyId == -1) { // Not added. int NTypeId = GetMxNTypeId(); NTypeH.AddDat(NTypeName, NTypeId); TypeNodeV.Add(TNodeType(NTypeId, NTypeName)); IAssertR(NTypeId == InETypes.Len(), TStr::Fmt("InETypes has inconsistent length.")); IAssertR(NTypeId == OutETypes.Len(), TStr::Fmt("OutETypes has inconsistent length.")); InETypes.Add(TIntV()); OutETypes.Add(TIntV()); return NTypeId; } else { // Added. Return the stored id. TStr TempKey; int NTypeId; NTypeH.GetKeyDat(KeyId, TempKey, NTypeId); return NTypeId; } } /// Gets the typeId of a type int GetNTypeId(const TStr& NTypeStr) { return NTypeH.GetDat(NTypeStr); } /// Gets the type name TStr GetNTypeName(const int NTypeId) { AssertNTypeId(NTypeId); return TypeNodeV[NTypeId].Name; } /// Validates the TypeId bool IsNTypeId(const int NTypeId) const { return NTypeId >= 0 && NTypeId < TypeNodeV.Len(); } /// Returns the number of nodes in the graph. int GetNodes() const { return Sz; } /// Returns the number of nodes of a specific type in the graph. int GetNodes(const int& NTypeId) const { return TypeNodeV[NTypeId].NodeH.Len(); } /// Returns an ID that is larger than any node ID in the network. int GetMxNId() const { return MxNId; } /// Returns an ID that is larger than any node ID of the given type in the network. int GetMxNId(const int& NTypeId) const { AssertNTypeId(NTypeId); return TypeNodeV[NTypeId].MxNId; } /// Adds a node of ID NId to the graph. int AddNode(const int& NTypeId, int NId = -1) { AssertNTypeId(NTypeId); TNodeType* NodeType = &TypeNodeV[NTypeId]; if (NId == -1) { NId = NodeType->MxNId; NodeType->MxNId++; } else { IAssertR(!IsNode(NTypeId, NId), TStr::Fmt("NodeId %d with type %d already exists", NId, NTypeId)); NodeType->MxNId = TMath::Mx(NId+1, NodeType->GetMxNId()); } TNode NewNode(NTypeId, GetGlobalNId(NTypeId, NId)); NewNode.AddInETypeIds(InETypes[NTypeId]); NewNode.AddOutETypeIds(OutETypes[NTypeId]); NodeType->NodeH.AddDat(NId, NewNode); int GlobalNId = GetGlobalNId(NTypeId, NId); MxNId = TMath::Mx(GlobalNId+1, MxNId()); Sz++; return GlobalNId; } int AddNode(const TStr& NTypeStr) { return AddNode(GetNTypeId(NTypeStr)); } /// Adds a node of ID NodeI.GetId() to the graph. int AddNode(const TNodeI& NodeId) { return AddNode(NodeId.GetTypeId(), NodeId.GetId()); } /// Validates the global NId bool IsNode(const int& NId) const { return IsNode(GetNTypeId(NId), GetLocalNId(NId)); } /// Validates the NTypeId and NId bool IsNode(const int& NTypeId, const int& NId) const { if (!IsNTypeId(NTypeId)) { return false; } return TypeNodeV[NTypeId].NodeH.IsKey(NId); } void DelNode(const int& NTypeId, const int& NId) { const TNode& Node = GetNode(NTypeId, NId); TIntV EIdV; Node.GetOutEIdV(EIdV); for (int out = 0; out < EIdV.Len(); out++) { DelEdge(EIdV[out]); } Node.GetInEIdV(EIdV); for (int in = 0; in < EIdV.Len(); in++) { DelEdge(EIdV[in]); } TypeNodeV[NTypeId].NodeH.DelKey(NId); Sz--; } /// Deletes node of ID NId from the graph. void DelNode(const int& NId) { DelNode(GetNTypeId(NId), GetLocalNId(NId)); } /// Deletes node of ID NodeI.GetId() from the graph. void DelNode(const TNode& NodeI) { DelNode(NodeI.GetTypeId(), NodeI.GetId()); } /// Returns an iterator referring to the first node in the graph. TNodeI BegNI() const { return TNodeI(TypeNodeV.BegI(), this); } /// Returns an iterator referring to the past-the-end node in the graph. TNodeI EndNI() const { return TNodeI(TypeNodeV.EndI(), this); } /// Returns an iterator referring to the node of ID NId in the graph. TNodeI GetNI(const int& NId) const { int NTypeId = GetNTypeId(NId); int LocalNId = GetLocalNId(NId); return GetNI(NTypeId, LocalNId); } TNodeI BegNI(const int& NTypeId) const { return TNodeI(TypeNodeV.GetI(NTypeId), this); } TNodeI EndNI(const int& NTypeId) const { return TNodeI(TypeNodeV.GetI(NTypeId), TypeNodeV[NTypeId].NodeH.EndI(), this); } TNodeI GetNI(const int& NTypeId, const int& NId) const { return TNodeI(TypeNodeV.GetI(NTypeId), TypeNodeV[NTypeId].NodeH.GetI(NId), this); } void GetNIdV(TIntV& NIdV) const { NIdV.Gen(GetNodes(), 0); for (TNodeI NI = BegNI(); NI < EndNI(); NI++) { NIdV.Add(NI.GetId()); } } int AddEType(const TStr& ETypeName, const TStr& SrcNTypeName, const TStr& DstNTypeName) { int KeyId = ETypeH.GetKeyId(ETypeName); // Has the type been added? if (KeyId == -1) { // Not added. int ETypeId = ETypeH.Len(); ETypeH.AddDat(ETypeName, ETypeId); InETypes[GetNTypeId(DstNTypeName)].Add(ETypeId); OutETypes[GetNTypeId(SrcNTypeName)].Add(ETypeId); EdgeSzV.Reserve(ETypeId+1, ETypeId+1); EdgeSzV[ETypeId] = 0; return ETypeId; } else { // Added. Return the stored id. TStr TempKey; int ETypeId; ETypeH.GetKeyDat(KeyId, TempKey, ETypeId); return ETypeId; } } /// Gets the typeId of an edge type int GetETypeId(const TStr& ETypeStr) { return ETypeH.GetDat(ETypeStr); } /// Returns an ID that is larger than any edge ID in the network. int GetMxEId() const { return MxEId; } /// Returns the number of edges in the graph. int GetEdges() const { return EdgeH.Len(); } /// Returns the number of edges of a specific type in the graph. int GetEdges(const int& ETypeId) const { return EdgeSzV[ETypeId].Val; } /// Adds an edge with ID EId between node IDs SrcNId and DstNId to the graph. int AddEdge(const int& SrcNId, const int& DstNId, const int& ETypeId, int EId = -1) { if (EId == -1) { EId = MxEId; MxEId++; } else { MxEId = TMath::Mx(EId+1, MxEId()); } IAssertR(!IsEdge(EId), TStr::Fmt("EdgeId %d already exists", EId)); IAssertR(IsNode(SrcNId) && IsNode(DstNId), TStr::Fmt("%d or %d not a node.", SrcNId, DstNId).CStr()); EdgeH.AddDat(EId, TEdge(ETypeId, EId, SrcNId, DstNId)); GetNode(SrcNId).AddOutNbr(ETypeId, EId); GetNode(DstNId).AddInNbr(ETypeId, EId); EdgeSzV[ETypeId] += 1; return EId; } int AddEdge(const int& SrcNId, const int& DstNId, const TStr& ETypeStr) { return AddEdge(SrcNId, DstNId, GetETypeId(ETypeStr)); } /// Adds an edge between EdgeI.GetSrcNId() and EdgeI.GetDstNId() to the graph. int AddEdge(const TEdgeI& EdgeI) { return AddEdge(EdgeI.GetSrcNId(), EdgeI.GetDstNId(), EdgeI.GetTypeId(), EdgeI.GetId()); } /// Deletes an edge with edge ID EId from the graph. void DelEdge(const int& EId) { IAssert(IsEdge(EId)); TEdge Edge = GetEdge(EId); int ETypeId = Edge.GetTypeId(); const int SrcNId = Edge.GetSrcNId(); const int DstNId = Edge.GetDstNId(); GetNode(SrcNId).DelOutNbr(ETypeId, EId); GetNode(DstNId).DelInNbr(ETypeId, EId); EdgeH.DelKey(EId); EdgeSzV[ETypeId] -= 1; } /// Deletes all edges between node IDs SrcNId and DstNId from the graph. void DelEdge(const int& SrcNId, const int& DstNId, const bool& IsDir = true) { int EId; IAssert(IsEdge(SrcNId, DstNId, EId, IsDir)); // there is at least one edge while (IsEdge(SrcNId, DstNId, EId, IsDir)) { DelEdge(EId); } } /// Tests whether an edge with edge ID EId exists in the graph. bool IsEdge(const int& EId) const { return EdgeH.IsKey(EId); } /// Tests whether an edge between node IDs SrcNId and DstNId exists in the graph. bool IsEdge(const int& SrcNId, const int& DstNId, const bool& IsDir = true) const { int EId; return IsEdge(SrcNId, DstNId, EId, IsDir); } /// Tests whether an edge between node IDs SrcNId and DstNId exists in the graph. if an edge exists, return its edge ID in EId bool IsEdge(const int& SrcNId, const int& DstNId, int& EId, const bool& IsDir = true) const { const TNode& SrcNode = GetNode(SrcNId); for (int edge = 0; edge < SrcNode.GetOutDeg(); edge++) { const TEdge& Edge = GetEdge(SrcNode.GetOutEId(edge)); if (DstNId == Edge.GetDstNId()) { EId = Edge.GetId(); return true; } } if (! IsDir) { for (int edge = 0; edge < SrcNode.GetInDeg(); edge++) { const TEdge& Edge = GetEdge(SrcNode.GetInEId(edge)); if (DstNId == Edge.GetSrcNId()) { EId = Edge.GetId(); return true; } } } return false; } /// Returns an edge ID between node IDs SrcNId and DstNId, if such an edge exists. Otherwise, return -1. int GetEId(const int& SrcNId, const int& DstNId) const { int EId; return IsEdge(SrcNId, DstNId, EId)?EId:-1; } /// Returns an iterator referring to the first edge in the graph. TEdgeI BegEI() const { return TEdgeI(EdgeH.BegI(), this); } /// Returns an iterator referring to the past-the-end edge in the graph. TEdgeI EndEI() const { return TEdgeI(EdgeH.EndI(), this); } /// Returns an iterator referring to edge with edge ID EId. TEdgeI GetEI(const int& EId) const { return TEdgeI(EdgeH.GetI(EId), this); } /// Returns an iterator referring to edge (SrcNId, DstNId) in the graph. TEdgeI GetEI(const int& SrcNId, const int& DstNId) const { return GetEI(GetEId(SrcNId, DstNId)); } /// Returns an ID of a random node in the graph. int GetRndNId(TRnd& Rnd=TInt::Rnd) { int RandN = Rnd.GetUniDevInt(Sz); int Ct = 0; int NTypeId = 0; for (; NTypeId < TypeNodeV.Len(); NTypeId++) { Ct += TypeNodeV[NTypeId].NodeH.Len(); if (Ct > RandN) { break; } } return GetRndNId(NTypeId, Rnd); } /// Returns an iterator referring to a random node in the graph. TNodeI GetRndNI(TRnd& Rnd=TInt::Rnd) { return GetNI(GetRndNId(Rnd)); } /// Returns an ID of a random node with the given type in the graph. int GetRndNId(const int& NTypeId, TRnd& Rnd=TInt::Rnd) { return TypeNodeV[NTypeId].NodeH.GetKey(TypeNodeV[NTypeId].NodeH.GetRndKeyId(Rnd, 0.8)); } /// Returns an iterator referring to a random node with the given type in the graph. TNodeI GetRndNI(const int& NTypeId, TRnd& Rnd=TInt::Rnd) { return GetNI(GetRndNId(NTypeId, Rnd)); } /// Returns an ID of a random edge in the graph. int GetRndEId(TRnd& Rnd=TInt::Rnd) { return EdgeH.GetKey(EdgeH.GetRndKeyId(Rnd, 0.8)); } /// Returns an iterator referring to a random edge in the graph. TEdgeI GetRndEI(TRnd& Rnd=TInt::Rnd) { return GetEI(GetRndEId(Rnd)); } /* /// Tests whether the graph is empty (has zero nodes). bool Empty() const { return GetNodes()==0; } /// Deletes all nodes and edges from the graph. void Clr() { MxNId=0; MxEId=0; NodeH.Clr(); EdgeH.Clr(), KeyToIndexTypeN.Clr(), KeyToIndexTypeE.Clr(), IntDefaultsN.Clr(), IntDefaultsE.Clr(), StrDefaultsN.Clr(), StrDefaultsE.Clr(), FltDefaultsN.Clr(), FltDefaultsE.Clr(), VecOfIntVecsN.Clr(), VecOfIntVecsE.Clr(), VecOfStrVecsN.Clr(), VecOfStrVecsE.Clr(), VecOfFltVecsN.Clr(), VecOfFltVecsE.Clr();} /// Reserves memory for a graph of Nodes nodes and Edges edges. void Reserve(const int& Nodes, const int& Edges) { if (Nodes>0) { NodeH.Gen(Nodes/2); } if (Edges>0) { EdgeH.Gen(Edges/2); } } /// Defragments the graph. void Defrag(const bool& OnlyNodeLinks=false); /// Checks the graph data structure for internal consistency. bool IsOk(const bool& ThrowExcept=true) const; /// Print the graph in a human readable form to an output stream OutF. void Dump(FILE *OutF=stdout) const; // Get the sum of the weights of all the outgoing edges of the node. TFlt GetWeightOutEdges(const TNodeI& NI, const TStr& attr); // Check if there is an edge attribute with name attr. bool IsFltAttrE(const TStr& attr); // Check if there is an edge attribute with name attr. bool IsIntAttrE(const TStr& attr); // Check if there is an edge attribute with name attr. bool IsStrAttrE(const TStr& attr); // Get Vector for the Flt Attribute attr. TVec<TFlt>& GetFltAttrVecE(const TStr& attr); // Get keyid for edge with id EId. int GetFltKeyIdE(const int& EId); //Fills OutWeights with the outgoing weight from each node. void GetWeightOutEdgesV(TFltV& OutWeights, const TFltV& AttrVal) ; */ TPt<TMNet<TNode> > GetSubGraph(const TIntV& NTypeIdV) { TPt<TMNet<TNode> > PNewGraph = New(); TMNet<TNode>& NewGraph = *PNewGraph; TIntSet NTypeIdSet(NTypeIdV); // Initialize node types for (typename THash<TStr,int>::TIter iter = NTypeH.BegI(); iter < NTypeH.EndI(); iter++) { if (NTypeIdSet.IsKey(TInt(iter.GetDat()))) { NewGraph.NTypeH.AddDat(iter.GetKey(), iter.GetDat()); } } // Find relevant edges TIntIntH EdgeCounter; for (int i = 0; i < InETypes.Len(); i++) { if (!NTypeIdSet.IsKey(TInt(i))) { continue; } for (int j = 0; j < InETypes[i].Len(); j++) { EdgeCounter.AddDat(InETypes[i][j], TInt(1)); } } for (int i = 0; i < OutETypes.Len(); i++) { if (!NTypeIdSet.IsKey(TInt(i))) { continue; } for (int j = 0; j < OutETypes[i].Len(); j++) { if (EdgeCounter.IsKey(OutETypes[i][j])) { EdgeCounter.AddDat(OutETypes[i][j], TInt(2)); } } } TIntSet ETypeIdSet; for (typename TIntIntH::TIter iter = EdgeCounter.BegI(); iter < EdgeCounter.EndI(); iter++) { if (iter.GetDat().Val == 2) { ETypeIdSet.AddKey(iter.GetKey()); } } for (typename THash<TStr,int>::TIter iter = ETypeH.BegI(); iter < ETypeH.EndI(); iter++) { if (ETypeIdSet.IsKey(TInt(iter.GetDat()))) { NewGraph.ETypeH.AddDat(iter.GetKey(), iter.GetDat()); } } NewGraph.InETypes.Gen(InETypes.Len()); for (int i = 0; i < InETypes.Len(); i++) { for (int j = 0; j < InETypes[i].Len(); j++) { int ETypeId = InETypes[i][j]; if (ETypeIdSet.IsKey(ETypeId)) { NewGraph.InETypes[i].Add(ETypeId); } } } NewGraph.OutETypes.Gen(OutETypes.Len()); for (int i = 0; i < OutETypes.Len(); i++) { for (int j = 0; j < OutETypes[i].Len(); j++) { int ETypeId = OutETypes[i][j]; if (ETypeIdSet.IsKey(ETypeId)) { NewGraph.OutETypes[i].Add(ETypeId); } } } NewGraph.Sz = 0; NewGraph.TypeNodeV.Gen(TypeNodeV.Len()); for (int NTypeId = 0; NTypeId < TypeNodeV.Len(); NTypeId++) { if (NTypeIdSet.IsKey(NTypeId)) { NewGraph.TypeNodeV[NTypeId] = TNodeType(TypeNodeV[NTypeId], NewGraph.InETypes[NTypeId], NewGraph.OutETypes[NTypeId]); NewGraph.Sz += NewGraph.TypeNodeV[NTypeId].NodeH.Len(); } else { NewGraph.TypeNodeV[NTypeId] = TNodeType(TypeNodeV[NTypeId].GetId(), TypeNodeV[NTypeId].GetName()); } } NewGraph.MxNId = MxNId; int MaxEId = 0; for (TEdgeI iter = BegEI(); iter < EndEI(); iter++) { if (!ETypeIdSet.IsKey(iter.GetTypeId())) { continue; } int EId = iter.GetId(); NewGraph.EdgeH.AddDat(EId, TEdge(iter.GetTypeId(), EId, iter.GetSrcNId(), iter.GetDstNId())); if (MaxEId < EId) { MaxEId = EId; } } NewGraph.MxEId = MaxEId + 1; return PNewGraph; } TPt<TMNet<TNode> > GetSubGraph(const TStrV& NTypeNameV) { TIntV NTypeIdV; for (int i = 0; i < NTypeNameV.Len(); i++) { NTypeIdV.Add(NTypeH.GetDat(NTypeNameV[i])); } return GetSubGraph(NTypeIdV); } PNEANet GetSubGraphTNEANet(const TIntV& NTypeIdV) { // Find relevant edge types TIntSet NTypeIdSet(NTypeIdV); TIntIntH EdgeCounter; for (int i = 0; i < InETypes.Len(); i++) { if (!NTypeIdSet.IsKey(TInt(i))) { continue; } for (int j = 0; j < InETypes[i].Len(); j++) { EdgeCounter.AddDat(InETypes[i][j], TInt(1)); } } for (int i = 0; i < OutETypes.Len(); i++) { if (!NTypeIdSet.IsKey(TInt(i))) { continue; } for (int j = 0; j < OutETypes[i].Len(); j++) { if (EdgeCounter.IsKey(OutETypes[i][j])) { EdgeCounter.AddDat(OutETypes[i][j], TInt(2)); } } } TIntV ETypeIdV; for (typename TIntIntH::TIter iter = EdgeCounter.BegI(); iter < EdgeCounter.EndI(); iter++) { if (iter.GetDat().Val == 2) { ETypeIdV.Add(iter.GetKey()); } } return GetSubGraphTNEANet2(NTypeIdV, ETypeIdV); } /// Extracts the subgraph by scanning and filtering all edges (edge-based) PNEANet GetSubGraphTNEANet(const TIntV& NTypeIdV, const TIntV& ETypeIdV) { PNEANet PNewGraph = PNEANet::New(); for (int i = 0; i < NTypeIdV.Len(); i++) { TInt NTypeId = NTypeIdV[i]; for (typename THash<TInt,TNode>::TIter iter = TypeNodeV[NTypeId].NodeH.BegI(); iter < TypeNodeV[NTypeId].NodeH.EndI(); iter++) { PNewGraph->AddNode(GetGlobalNId(NTypeId, iter.GetKey().Val)); } } TIntSet ETypeIdSet(ETypeIdV); // Add edges for (TEdgeI iter = BegEI(); iter < EndEI(); iter++) { if (ETypeIdSet.IsKey(iter.GetTypeId())) { PNewGraph->AddEdge(iter.GetSrcNId(), iter.GetDstNId(), iter.GetId()); } } return PNewGraph; } /// Extracts the subgraph by finding the nodes and then finding all neighbors (node-based) PNEANet GetSubGraphTNEANet2(const TIntV& NTypeIdV, const TIntV& ETypeIdV) { PNEANet PNewGraph = PNEANet::New(); // Add nodes for (int i = 0; i < NTypeIdV.Len(); i++) { TInt NTypeId = NTypeIdV[i]; for (typename THash<TInt,TNode>::TIter iter = TypeNodeV[NTypeId].NodeH.BegI(); iter < TypeNodeV[NTypeId].NodeH.EndI(); iter++) { PNewGraph->AddNode(GetGlobalNId(NTypeId, iter.GetKey().Val)); } } // Add edges TIntSet ETypeIdSet(ETypeIdV); TIntV EIdV; // Use same vector to save memory for (int i = 0; i < NTypeIdV.Len(); i++) { TInt NTypeId = NTypeIdV[i]; TIntV* POutETypes = &(OutETypes[NTypeId]); TIntV OutETypeIdV; for (TIntV::TIter iter = POutETypes->BegI(); iter < POutETypes->EndI(); iter++) { if (ETypeIdSet.IsKey(*iter)) { OutETypeIdV.Add(*iter); } } for (typename THash<TInt,TNode>::TIter iter = TypeNodeV[NTypeId].NodeH.BegI(); iter < TypeNodeV[NTypeId].NodeH.EndI(); iter++) { TNode* PNode = &(iter.GetDat()); for (int j = 0; j < OutETypeIdV.Len(); j++) { PNode->GetOutEIdV(OutETypeIdV.GetVal(j).Val, EIdV); for (int k = 0; k < EIdV.Len(); k++) { TInt EId = EIdV[k]; PNewGraph->AddEdge(PNode->GetId(), GetEdge(EId).GetDstNId(), EId); } } } } return PNewGraph; } #ifdef GCC_ATOMIC PNEANetMP GetSubGraphTNEANetMP2(const TIntV& NTypeIdV) { TStopwatch* Sw = TStopwatch::GetInstance(); Sw->Start(TStopwatch::ComputeETypes); // Find relevant edge types TIntSet NTypeIdSet(NTypeIdV); TIntIntH EdgeCounter; for (int i = 0; i < InETypes.Len(); i++) { if (!NTypeIdSet.IsKey(TInt(i))) { continue; } for (int j = 0; j < InETypes[i].Len(); j++) { EdgeCounter.AddDat(InETypes[i][j], TInt(1)); } } for (int i = 0; i < OutETypes.Len(); i++) { if (!NTypeIdSet.IsKey(TInt(i))) { continue; } for (int j = 0; j < OutETypes[i].Len(); j++) { if (EdgeCounter.IsKey(OutETypes[i][j])) { EdgeCounter.AddDat(OutETypes[i][j], TInt(2)); } } } TIntV ETypeIdV; for (typename TIntIntH::TIter iter = EdgeCounter.BegI(); iter < EdgeCounter.EndI(); iter++) { if (iter.GetDat().Val == 2) { ETypeIdV.Add(iter.GetKey()); } } Sw->Stop(TStopwatch::ComputeETypes); return GetSubGraphTNEANetMP2(NTypeIdV, ETypeIdV); } /// Extracts the subgraph by finding the nodes and then finding all neighbors (node-based) PNEANetMP GetSubGraphTNEANetMP(const TIntV& NTypeIdV, const TIntV& ETypeIdV) { TStopwatch* Sw = TStopwatch::GetInstance(); Sw->Start(TStopwatch::EstimateSizes); int SubgraphSz = 0; for (TIntV::TIter iter = NTypeIdV.BegI(); iter < NTypeIdV.EndI(); iter++) { SubgraphSz += GetNodes((*iter).Val); } int SubgraphEdgeSz = 0; for (TIntV::TIter iter = ETypeIdV.BegI(); iter < ETypeIdV.EndI(); iter++) { SubgraphEdgeSz += GetEdges((*iter).Val); } Sw->Stop(TStopwatch::EstimateSizes); Sw->Start(TStopwatch::InitGraph); PNEANetMP PNewGraph = TNEANetMP::New(SubgraphSz, SubgraphEdgeSz); TIntSet ETypeIdSet(ETypeIdV); Sw->Stop(TStopwatch::InitGraph); TIntV OutETypeIdVV[NTypeIdV.Len()]; TIntV InETypeIdVV[NTypeIdV.Len()]; Sw->Start(TStopwatch::ExtractNbrETypes); #pragma omp parallel for schedule(static) for (int i = 0; i < NTypeIdV.Len(); i++) { TInt NTypeId = NTypeIdV[i]; TIntV* POutETypes = &(OutETypes[NTypeId]); for (TIntV::TIter iter = POutETypes->BegI(); iter < POutETypes->EndI(); iter++) { if (ETypeIdSet.IsKey(*iter)) { OutETypeIdVV[i].Add(*iter); } } TIntV* PInETypes = &(InETypes[NTypeId]); for (TIntV::TIter iter = PInETypes->BegI(); iter < PInETypes->EndI(); iter++) { if (ETypeIdSet.IsKey(*iter)) { InETypeIdVV[i].Add(*iter); } } } Sw->Stop(TStopwatch::ExtractNbrETypes); TIntV Offsets(NTypeIdV.Len()+1); Offsets[0] = 0; for (int i = 0; i < NTypeIdV.Len(); i++) { Offsets[i+1] = Offsets[i] + TypeNodeV[NTypeIdV[i]].NodeH.GetMxKeyIds(); } Sw->Start(TStopwatch::PopulateGraph); #pragma omp parallel for schedule(static) for (int j = 0; j < Offsets[NTypeIdV.Len()]; j++) { int i; Offsets.SearchBinLeft(j, i); THash<TInt,TNode> *NodeHPtr = &(TypeNodeV[NTypeIdV[i]].NodeH); int KeyId = j - Offsets[i]; if (!NodeHPtr->IsKeyId(KeyId)) { continue; } TNode* PNode = &((*NodeHPtr)[KeyId]); int NId = PNode->GetId(); TIntV EIdV; TIntV OutEIdV; for (TIntV::TIter iter = OutETypeIdVV[i].BegI(); iter < OutETypeIdVV[i].EndI(); iter++) { PNode->GetOutEIdV((*iter).Val, EIdV); OutEIdV.AddV(EIdV); } TIntV InEIdV; for (TIntV::TIter iter = InETypeIdVV[i].BegI(); iter < InETypeIdVV[i].EndI(); iter++) { PNode->GetInEIdV((*iter).Val, EIdV); InEIdV.AddV(EIdV); } PNewGraph->AddNodeWithEdges(NId, InEIdV, OutEIdV); for (TIntV::TIter iter = OutEIdV.BegI(); iter < OutEIdV.EndI(); iter++) { PNewGraph->AddEdgeUnchecked((*iter), NId, GetEdge(*iter).GetDstNId()); } } Sw->Stop(TStopwatch::PopulateGraph); PNewGraph->SetNodes(SubgraphSz); PNewGraph->SetEdges(SubgraphEdgeSz); return PNewGraph; } /// Extracts the subgraph by finding the nodes and then finding all neighbors (node-based) PNEANetMP GetSubGraphTNEANetMP2(const TIntV& NTypeIdV, const TIntV& ETypeIdV) { TStopwatch* Sw = TStopwatch::GetInstance(); Sw->Start(TStopwatch::EstimateSizes); int SubgraphSz = 0; for (TIntV::TIter iter = NTypeIdV.BegI(); iter < NTypeIdV.EndI(); iter++) { SubgraphSz += GetNodes((*iter).Val); } int SubgraphEdgeSz = 0; for (TIntV::TIter iter = ETypeIdV.BegI(); iter < ETypeIdV.EndI(); iter++) { SubgraphEdgeSz += GetEdges((*iter).Val); } Sw->Stop(TStopwatch::EstimateSizes); Sw->Start(TStopwatch::InitGraph); PNEANetMP PNewGraph = TNEANetMP::New(SubgraphSz, SubgraphEdgeSz); TIntSet ETypeIdSet(ETypeIdV); Sw->Stop(TStopwatch::InitGraph); // int NThreads = omp_get_max_threads(); // TIntV VectorPool[2*NThreads]; for (int i = 0; i < NTypeIdV.Len(); i++) { Sw->Start(TStopwatch::ExtractNbrETypes); TInt NTypeId = NTypeIdV[i]; TIntV* POutETypes = &(OutETypes[NTypeId]); TIntV OutETypeIdV; for (TIntV::TIter iter = POutETypes->BegI(); iter < POutETypes->EndI(); iter++) { if (ETypeIdSet.IsKey(*iter)) { OutETypeIdV.Add(*iter); } } TIntV* PInETypes = &(InETypes[NTypeId]); TIntV InETypeIdV; for (TIntV::TIter iter = PInETypes->BegI(); iter < PInETypes->EndI(); iter++) { if (ETypeIdSet.IsKey(*iter)) { InETypeIdV.Add(*iter); } } Sw->Stop(TStopwatch::ExtractNbrETypes); Sw->Start(TStopwatch::PopulateGraph); THash<TInt,TNode> *NodeHPtr = &(TypeNodeV[NTypeId].NodeH); // omp_set_num_threads(NThreads); #pragma omp parallel for schedule(static) for (int KeyId = 0; KeyId < NodeHPtr->GetMxKeyIds(); KeyId++) { if (!NodeHPtr->IsKeyId(KeyId)) { continue; } TIntV OutEIdV; TIntV InEIdV; // Sw->Start(TStopwatch::ExtractEdges); TNode* PNode = &((*NodeHPtr)[KeyId]); int NId = PNode->GetId(); //Sw->Start(TStopwatch::ExtractEdges); // OutEIdV.Reduce(0); // for (TIntV::TIter iter = OutETypeIdV.BegI(); iter < OutETypeIdV.EndI(); iter++) { // PNode->GetOutEIdV((*iter).Val, *EIdV); // OutEIdV->AddV(*EIdV); // } // InEIdV.Reduce(0); // for (TIntV::TIter iter = InETypeIdV.BegI(); iter < InETypeIdV.EndI(); iter++) { // PNode->GetInEIdV((*iter).Val, *EIdV); // InEIdV->AddV(*EIdV); // } PNode->GetOutEIdV(OutETypeIdV, OutEIdV); PNode->GetInEIdV(InETypeIdV, InEIdV); // Sw->Stop(TStopwatch::ExtractEdges); // Sw->Start(TStopwatch::BuildSubgraph); PNewGraph->AddNodeWithEdges(NId, InEIdV, OutEIdV); for (TIntV::TIter iter = OutEIdV.BegI(); iter < OutEIdV.EndI(); iter++) { PNewGraph->AddEdgeUnchecked((*iter), NId, GetEdge(*iter).GetDstNId()); } // Sw->Stop(TStopwatch::BuildSubgraph); } Sw->Stop(TStopwatch::PopulateGraph); } PNewGraph->SetNodes(SubgraphSz); PNewGraph->SetEdges(SubgraphEdgeSz); return PNewGraph; } #endif // GCC_ATOMIC friend class TPt<TMNet>; }; typedef TMNet<TSVNode> TSVNet; typedef TPt<TSVNet> PSVNet; typedef TMNet<TMVNode> TMVNet; typedef TPt<TMVNet> PMVNet; typedef TMNet<TCVNode> TCVNet; typedef TPt<TCVNet> PCVNet; #endif // MGRAPH_H
ASTMatchers.h
//===- ASTMatchers.h - Structural query framework ---------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements matchers to be used together with the MatchFinder to // match AST nodes. // // Matchers are created by generator functions, which can be combined in // a functional in-language DSL to express queries over the C++ AST. // // For example, to match a class with a certain name, one would call: // cxxRecordDecl(hasName("MyClass")) // which returns a matcher that can be used to find all AST nodes that declare // a class named 'MyClass'. // // For more complicated match expressions we're often interested in accessing // multiple parts of the matched AST nodes once a match is found. In that case, // call `.bind("name")` on match expressions that match the nodes you want to // access. // // For example, when we're interested in child classes of a certain class, we // would write: // cxxRecordDecl(hasName("MyClass"), has(recordDecl().bind("child"))) // When the match is found via the MatchFinder, a user provided callback will // be called with a BoundNodes instance that contains a mapping from the // strings that we provided for the `.bind()` calls to the nodes that were // matched. // In the given example, each time our matcher finds a match we get a callback // where "child" is bound to the RecordDecl node of the matching child // class declaration. // // See ASTMatchersInternal.h for a more in-depth explanation of the // implementation details of the matcher framework. // // See ASTMatchFinder.h for how to use the generated matchers to run over // an AST. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H #define LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H #include "clang/AST/ASTContext.h" #include "clang/AST/ASTTypeTraits.h" #include "clang/AST/Attr.h" #include "clang/AST/CXXInheritance.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclFriend.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/LambdaCapture.h" #include "clang/AST/NestedNameSpecifier.h" #include "clang/AST/OpenMPClause.h" #include "clang/AST/OperationKinds.h" #include "clang/AST/ParentMapContext.h" #include "clang/AST/Stmt.h" #include "clang/AST/StmtCXX.h" #include "clang/AST/StmtObjC.h" #include "clang/AST/StmtOpenMP.h" #include "clang/AST/TemplateBase.h" #include "clang/AST/TemplateName.h" #include "clang/AST/Type.h" #include "clang/AST/TypeLoc.h" #include "clang/ASTMatchers/ASTMatchersInternal.h" #include "clang/ASTMatchers/ASTMatchersMacros.h" #include "clang/Basic/AttrKinds.h" #include "clang/Basic/ExceptionSpecificationType.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/LLVM.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/Specifiers.h" #include "clang/Basic/TypeTraits.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Casting.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Regex.h" #include <cassert> #include <cstddef> #include <iterator> #include <limits> #include <string> #include <utility> #include <vector> namespace clang { namespace ast_matchers { /// Maps string IDs to AST nodes matched by parts of a matcher. /// /// The bound nodes are generated by calling \c bind("id") on the node matchers /// of the nodes we want to access later. /// /// The instances of BoundNodes are created by \c MatchFinder when the user's /// callbacks are executed every time a match is found. class BoundNodes { public: /// Returns the AST node bound to \c ID. /// /// Returns NULL if there was no node bound to \c ID or if there is a node but /// it cannot be converted to the specified type. template <typename T> const T *getNodeAs(StringRef ID) const { return MyBoundNodes.getNodeAs<T>(ID); } /// Type of mapping from binding identifiers to bound nodes. This type /// is an associative container with a key type of \c std::string and a value /// type of \c clang::DynTypedNode using IDToNodeMap = internal::BoundNodesMap::IDToNodeMap; /// Retrieve mapping from binding identifiers to bound nodes. const IDToNodeMap &getMap() const { return MyBoundNodes.getMap(); } private: friend class internal::BoundNodesTreeBuilder; /// Create BoundNodes from a pre-filled map of bindings. BoundNodes(internal::BoundNodesMap &MyBoundNodes) : MyBoundNodes(MyBoundNodes) {} internal::BoundNodesMap MyBoundNodes; }; /// Types of matchers for the top-level classes in the AST class /// hierarchy. /// @{ using DeclarationMatcher = internal::Matcher<Decl>; using StatementMatcher = internal::Matcher<Stmt>; using TypeMatcher = internal::Matcher<QualType>; using TypeLocMatcher = internal::Matcher<TypeLoc>; using NestedNameSpecifierMatcher = internal::Matcher<NestedNameSpecifier>; using NestedNameSpecifierLocMatcher = internal::Matcher<NestedNameSpecifierLoc>; using CXXBaseSpecifierMatcher = internal::Matcher<CXXBaseSpecifier>; using CXXCtorInitializerMatcher = internal::Matcher<CXXCtorInitializer>; using TemplateArgumentMatcher = internal::Matcher<TemplateArgument>; using TemplateArgumentLocMatcher = internal::Matcher<TemplateArgumentLoc>; using AttrMatcher = internal::Matcher<Attr>; /// @} /// Matches any node. /// /// Useful when another matcher requires a child matcher, but there's no /// additional constraint. This will often be used with an explicit conversion /// to an \c internal::Matcher<> type such as \c TypeMatcher. /// /// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g., /// \code /// "int* p" and "void f()" in /// int* p; /// void f(); /// \endcode /// /// Usable as: Any Matcher inline internal::TrueMatcher anything() { return internal::TrueMatcher(); } /// Matches the top declaration context. /// /// Given /// \code /// int X; /// namespace NS { /// int Y; /// } // namespace NS /// \endcode /// decl(hasDeclContext(translationUnitDecl())) /// matches "int X", but not "int Y". extern const internal::VariadicDynCastAllOfMatcher<Decl, TranslationUnitDecl> translationUnitDecl; /// Matches typedef declarations. /// /// Given /// \code /// typedef int X; /// using Y = int; /// \endcode /// typedefDecl() /// matches "typedef int X", but not "using Y = int" extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefDecl> typedefDecl; /// Matches typedef name declarations. /// /// Given /// \code /// typedef int X; /// using Y = int; /// \endcode /// typedefNameDecl() /// matches "typedef int X" and "using Y = int" extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefNameDecl> typedefNameDecl; /// Matches type alias declarations. /// /// Given /// \code /// typedef int X; /// using Y = int; /// \endcode /// typeAliasDecl() /// matches "using Y = int", but not "typedef int X" extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasDecl> typeAliasDecl; /// Matches type alias template declarations. /// /// typeAliasTemplateDecl() matches /// \code /// template <typename T> /// using Y = X<T>; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasTemplateDecl> typeAliasTemplateDecl; /// Matches AST nodes that were expanded within the main-file. /// /// Example matches X but not Y /// (matcher = cxxRecordDecl(isExpansionInMainFile()) /// \code /// #include <Y.h> /// class X {}; /// \endcode /// Y.h: /// \code /// class Y {}; /// \endcode /// /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc> AST_POLYMORPHIC_MATCHER(isExpansionInMainFile, AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) { auto &SourceManager = Finder->getASTContext().getSourceManager(); return SourceManager.isInMainFile( SourceManager.getExpansionLoc(Node.getBeginLoc())); } /// Matches AST nodes that were expanded within system-header-files. /// /// Example matches Y but not X /// (matcher = cxxRecordDecl(isExpansionInSystemHeader()) /// \code /// #include <SystemHeader.h> /// class X {}; /// \endcode /// SystemHeader.h: /// \code /// class Y {}; /// \endcode /// /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc> AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader, AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) { auto &SourceManager = Finder->getASTContext().getSourceManager(); auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc()); if (ExpansionLoc.isInvalid()) { return false; } return SourceManager.isInSystemHeader(ExpansionLoc); } /// Matches AST nodes that were expanded within files whose name is /// partially matching a given regex. /// /// Example matches Y but not X /// (matcher = cxxRecordDecl(isExpansionInFileMatching("AST.*")) /// \code /// #include "ASTMatcher.h" /// class X {}; /// \endcode /// ASTMatcher.h: /// \code /// class Y {}; /// \endcode /// /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc> AST_POLYMORPHIC_MATCHER_REGEX(isExpansionInFileMatching, AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc), RegExp) { auto &SourceManager = Finder->getASTContext().getSourceManager(); auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc()); if (ExpansionLoc.isInvalid()) { return false; } auto FileEntry = SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc)); if (!FileEntry) { return false; } auto Filename = FileEntry->getName(); return RegExp->match(Filename); } /// Matches statements that are (transitively) expanded from the named macro. /// Does not match if only part of the statement is expanded from that macro or /// if different parts of the the statement are expanded from different /// appearances of the macro. AST_POLYMORPHIC_MATCHER_P(isExpandedFromMacro, AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc), std::string, MacroName) { // Verifies that the statement' beginning and ending are both expanded from // the same instance of the given macro. auto& Context = Finder->getASTContext(); llvm::Optional<SourceLocation> B = internal::getExpansionLocOfMacro(MacroName, Node.getBeginLoc(), Context); if (!B) return false; llvm::Optional<SourceLocation> E = internal::getExpansionLocOfMacro(MacroName, Node.getEndLoc(), Context); if (!E) return false; return *B == *E; } /// Matches declarations. /// /// Examples matches \c X, \c C, and the friend declaration inside \c C; /// \code /// void X(); /// class C { /// friend X; /// }; /// \endcode extern const internal::VariadicAllOfMatcher<Decl> decl; /// Matches decomposition-declarations. /// /// Examples matches the declaration node with \c foo and \c bar, but not /// \c number. /// (matcher = declStmt(has(decompositionDecl()))) /// /// \code /// int number = 42; /// auto [foo, bar] = std::make_pair{42, 42}; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, DecompositionDecl> decompositionDecl; /// Matches binding declarations /// Example matches \c foo and \c bar /// (matcher = bindingDecl() /// /// \code /// auto [foo, bar] = std::make_pair{42, 42}; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, BindingDecl> bindingDecl; /// Matches a declaration of a linkage specification. /// /// Given /// \code /// extern "C" {} /// \endcode /// linkageSpecDecl() /// matches "extern "C" {}" extern const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl> linkageSpecDecl; /// Matches a declaration of anything that could have a name. /// /// Example matches \c X, \c S, the anonymous union type, \c i, and \c U; /// \code /// typedef int X; /// struct S { /// union { /// int i; /// } U; /// }; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl; /// Matches a declaration of label. /// /// Given /// \code /// goto FOO; /// FOO: bar(); /// \endcode /// labelDecl() /// matches 'FOO:' extern const internal::VariadicDynCastAllOfMatcher<Decl, LabelDecl> labelDecl; /// Matches a declaration of a namespace. /// /// Given /// \code /// namespace {} /// namespace test {} /// \endcode /// namespaceDecl() /// matches "namespace {}" and "namespace test {}" extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl> namespaceDecl; /// Matches a declaration of a namespace alias. /// /// Given /// \code /// namespace test {} /// namespace alias = ::test; /// \endcode /// namespaceAliasDecl() /// matches "namespace alias" but not "namespace test" extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceAliasDecl> namespaceAliasDecl; /// Matches class, struct, and union declarations. /// /// Example matches \c X, \c Z, \c U, and \c S /// \code /// class X; /// template<class T> class Z {}; /// struct S {}; /// union U {}; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, RecordDecl> recordDecl; /// Matches C++ class declarations. /// /// Example matches \c X, \c Z /// \code /// class X; /// template<class T> class Z {}; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXRecordDecl> cxxRecordDecl; /// Matches C++ class template declarations. /// /// Example matches \c Z /// \code /// template<class T> class Z {}; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, ClassTemplateDecl> classTemplateDecl; /// Matches C++ class template specializations. /// /// Given /// \code /// template<typename T> class A {}; /// template<> class A<double> {}; /// A<int> a; /// \endcode /// classTemplateSpecializationDecl() /// matches the specializations \c A<int> and \c A<double> extern const internal::VariadicDynCastAllOfMatcher< Decl, ClassTemplateSpecializationDecl> classTemplateSpecializationDecl; /// Matches C++ class template partial specializations. /// /// Given /// \code /// template<class T1, class T2, int I> /// class A {}; /// /// template<class T, int I> /// class A<T, T*, I> {}; /// /// template<> /// class A<int, int, 1> {}; /// \endcode /// classTemplatePartialSpecializationDecl() /// matches the specialization \c A<T,T*,I> but not \c A<int,int,1> extern const internal::VariadicDynCastAllOfMatcher< Decl, ClassTemplatePartialSpecializationDecl> classTemplatePartialSpecializationDecl; /// Matches declarator declarations (field, variable, function /// and non-type template parameter declarations). /// /// Given /// \code /// class X { int y; }; /// \endcode /// declaratorDecl() /// matches \c int y. extern const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl> declaratorDecl; /// Matches parameter variable declarations. /// /// Given /// \code /// void f(int x); /// \endcode /// parmVarDecl() /// matches \c int x. extern const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl> parmVarDecl; /// Matches C++ access specifier declarations. /// /// Given /// \code /// class C { /// public: /// int a; /// }; /// \endcode /// accessSpecDecl() /// matches 'public:' extern const internal::VariadicDynCastAllOfMatcher<Decl, AccessSpecDecl> accessSpecDecl; /// Matches class bases. /// /// Examples matches \c public virtual B. /// \code /// class B {}; /// class C : public virtual B {}; /// \endcode extern const internal::VariadicAllOfMatcher<CXXBaseSpecifier> cxxBaseSpecifier; /// Matches constructor initializers. /// /// Examples matches \c i(42). /// \code /// class C { /// C() : i(42) {} /// int i; /// }; /// \endcode extern const internal::VariadicAllOfMatcher<CXXCtorInitializer> cxxCtorInitializer; /// Matches template arguments. /// /// Given /// \code /// template <typename T> struct C {}; /// C<int> c; /// \endcode /// templateArgument() /// matches 'int' in C<int>. extern const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument; /// Matches template arguments (with location info). /// /// Given /// \code /// template <typename T> struct C {}; /// C<int> c; /// \endcode /// templateArgumentLoc() /// matches 'int' in C<int>. extern const internal::VariadicAllOfMatcher<TemplateArgumentLoc> templateArgumentLoc; /// Matches template name. /// /// Given /// \code /// template <typename T> class X { }; /// X<int> xi; /// \endcode /// templateName() /// matches 'X' in X<int>. extern const internal::VariadicAllOfMatcher<TemplateName> templateName; /// Matches non-type template parameter declarations. /// /// Given /// \code /// template <typename T, int N> struct C {}; /// \endcode /// nonTypeTemplateParmDecl() /// matches 'N', but not 'T'. extern const internal::VariadicDynCastAllOfMatcher<Decl, NonTypeTemplateParmDecl> nonTypeTemplateParmDecl; /// Matches template type parameter declarations. /// /// Given /// \code /// template <typename T, int N> struct C {}; /// \endcode /// templateTypeParmDecl() /// matches 'T', but not 'N'. extern const internal::VariadicDynCastAllOfMatcher<Decl, TemplateTypeParmDecl> templateTypeParmDecl; /// Matches template template parameter declarations. /// /// Given /// \code /// template <template <typename> class Z, int N> struct C {}; /// \endcode /// templateTypeParmDecl() /// matches 'Z', but not 'N'. extern const internal::VariadicDynCastAllOfMatcher<Decl, TemplateTemplateParmDecl> templateTemplateParmDecl; /// Matches public C++ declarations and C++ base specifers that specify public /// inheritance. /// /// Examples: /// \code /// class C { /// public: int a; // fieldDecl(isPublic()) matches 'a' /// protected: int b; /// private: int c; /// }; /// \endcode /// /// \code /// class Base {}; /// class Derived1 : public Base {}; // matches 'Base' /// struct Derived2 : Base {}; // matches 'Base' /// \endcode AST_POLYMORPHIC_MATCHER(isPublic, AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, CXXBaseSpecifier)) { return getAccessSpecifier(Node) == AS_public; } /// Matches protected C++ declarations and C++ base specifers that specify /// protected inheritance. /// /// Examples: /// \code /// class C { /// public: int a; /// protected: int b; // fieldDecl(isProtected()) matches 'b' /// private: int c; /// }; /// \endcode /// /// \code /// class Base {}; /// class Derived : protected Base {}; // matches 'Base' /// \endcode AST_POLYMORPHIC_MATCHER(isProtected, AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, CXXBaseSpecifier)) { return getAccessSpecifier(Node) == AS_protected; } /// Matches private C++ declarations and C++ base specifers that specify private /// inheritance. /// /// Examples: /// \code /// class C { /// public: int a; /// protected: int b; /// private: int c; // fieldDecl(isPrivate()) matches 'c' /// }; /// \endcode /// /// \code /// struct Base {}; /// struct Derived1 : private Base {}; // matches 'Base' /// class Derived2 : Base {}; // matches 'Base' /// \endcode AST_POLYMORPHIC_MATCHER(isPrivate, AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, CXXBaseSpecifier)) { return getAccessSpecifier(Node) == AS_private; } /// Matches non-static data members that are bit-fields. /// /// Given /// \code /// class C { /// int a : 2; /// int b; /// }; /// \endcode /// fieldDecl(isBitField()) /// matches 'int a;' but not 'int b;'. AST_MATCHER(FieldDecl, isBitField) { return Node.isBitField(); } /// Matches non-static data members that are bit-fields of the specified /// bit width. /// /// Given /// \code /// class C { /// int a : 2; /// int b : 4; /// int c : 2; /// }; /// \endcode /// fieldDecl(hasBitWidth(2)) /// matches 'int a;' and 'int c;' but not 'int b;'. AST_MATCHER_P(FieldDecl, hasBitWidth, unsigned, Width) { return Node.isBitField() && Node.getBitWidthValue(Finder->getASTContext()) == Width; } /// Matches non-static data members that have an in-class initializer. /// /// Given /// \code /// class C { /// int a = 2; /// int b = 3; /// int c; /// }; /// \endcode /// fieldDecl(hasInClassInitializer(integerLiteral(equals(2)))) /// matches 'int a;' but not 'int b;'. /// fieldDecl(hasInClassInitializer(anything())) /// matches 'int a;' and 'int b;' but not 'int c;'. AST_MATCHER_P(FieldDecl, hasInClassInitializer, internal::Matcher<Expr>, InnerMatcher) { const Expr *Initializer = Node.getInClassInitializer(); return (Initializer != nullptr && InnerMatcher.matches(*Initializer, Finder, Builder)); } /// Determines whether the function is "main", which is the entry point /// into an executable program. AST_MATCHER(FunctionDecl, isMain) { return Node.isMain(); } /// Matches the specialized template of a specialization declaration. /// /// Given /// \code /// template<typename T> class A {}; #1 /// template<> class A<int> {}; #2 /// \endcode /// classTemplateSpecializationDecl(hasSpecializedTemplate(classTemplateDecl())) /// matches '#2' with classTemplateDecl() matching the class template /// declaration of 'A' at #1. AST_MATCHER_P(ClassTemplateSpecializationDecl, hasSpecializedTemplate, internal::Matcher<ClassTemplateDecl>, InnerMatcher) { const ClassTemplateDecl* Decl = Node.getSpecializedTemplate(); return (Decl != nullptr && InnerMatcher.matches(*Decl, Finder, Builder)); } /// Matches an entity that has been implicitly added by the compiler (e.g. /// implicit default/copy constructors). AST_POLYMORPHIC_MATCHER(isImplicit, AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Attr)) { return Node.isImplicit(); } /// Matches classTemplateSpecializations, templateSpecializationType and /// functionDecl that have at least one TemplateArgument matching the given /// InnerMatcher. /// /// Given /// \code /// template<typename T> class A {}; /// template<> class A<double> {}; /// A<int> a; /// /// template<typename T> f() {}; /// void func() { f<int>(); }; /// \endcode /// /// \endcode /// classTemplateSpecializationDecl(hasAnyTemplateArgument( /// refersToType(asString("int")))) /// matches the specialization \c A<int> /// /// functionDecl(hasAnyTemplateArgument(refersToType(asString("int")))) /// matches the specialization \c f<int> AST_POLYMORPHIC_MATCHER_P( hasAnyTemplateArgument, AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl, TemplateSpecializationType, FunctionDecl), internal::Matcher<TemplateArgument>, InnerMatcher) { ArrayRef<TemplateArgument> List = internal::getTemplateSpecializationArgs(Node); return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder, Builder) != List.end(); } /// Causes all nested matchers to be matched with the specified traversal kind. /// /// Given /// \code /// void foo() /// { /// int i = 3.0; /// } /// \endcode /// The matcher /// \code /// traverse(TK_IgnoreUnlessSpelledInSource, /// varDecl(hasInitializer(floatLiteral().bind("init"))) /// ) /// \endcode /// matches the variable declaration with "init" bound to the "3.0". template <typename T> internal::Matcher<T> traverse(TraversalKind TK, const internal::Matcher<T> &InnerMatcher) { return internal::DynTypedMatcher::constructRestrictedWrapper( new internal::TraversalMatcher<T>(TK, InnerMatcher), InnerMatcher.getID().first) .template unconditionalConvertTo<T>(); } template <typename T> internal::BindableMatcher<T> traverse(TraversalKind TK, const internal::BindableMatcher<T> &InnerMatcher) { return internal::BindableMatcher<T>( internal::DynTypedMatcher::constructRestrictedWrapper( new internal::TraversalMatcher<T>(TK, InnerMatcher), InnerMatcher.getID().first) .template unconditionalConvertTo<T>()); } template <typename... T> internal::TraversalWrapper<internal::VariadicOperatorMatcher<T...>> traverse(TraversalKind TK, const internal::VariadicOperatorMatcher<T...> &InnerMatcher) { return internal::TraversalWrapper<internal::VariadicOperatorMatcher<T...>>( TK, InnerMatcher); } template <template <typename ToArg, typename FromArg> class ArgumentAdapterT, typename T, typename ToTypes> internal::TraversalWrapper< internal::ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T, ToTypes>> traverse(TraversalKind TK, const internal::ArgumentAdaptingMatcherFuncAdaptor< ArgumentAdapterT, T, ToTypes> &InnerMatcher) { return internal::TraversalWrapper< internal::ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T, ToTypes>>(TK, InnerMatcher); } template <template <typename T, typename... P> class MatcherT, typename... P, typename ReturnTypesF> internal::TraversalWrapper< internal::PolymorphicMatcher<MatcherT, ReturnTypesF, P...>> traverse(TraversalKind TK, const internal::PolymorphicMatcher<MatcherT, ReturnTypesF, P...> &InnerMatcher) { return internal::TraversalWrapper< internal::PolymorphicMatcher<MatcherT, ReturnTypesF, P...>>(TK, InnerMatcher); } template <typename... T> internal::Matcher<typename internal::GetClade<T...>::Type> traverse(TraversalKind TK, const internal::MapAnyOfHelper<T...> &InnerMatcher) { return traverse(TK, InnerMatcher.with()); } /// Matches expressions that match InnerMatcher after any implicit AST /// nodes are stripped off. /// /// Parentheses and explicit casts are not discarded. /// Given /// \code /// class C {}; /// C a = C(); /// C b; /// C c = b; /// \endcode /// The matchers /// \code /// varDecl(hasInitializer(ignoringImplicit(cxxConstructExpr()))) /// \endcode /// would match the declarations for a, b, and c. /// While /// \code /// varDecl(hasInitializer(cxxConstructExpr())) /// \endcode /// only match the declarations for b and c. AST_MATCHER_P(Expr, ignoringImplicit, internal::Matcher<Expr>, InnerMatcher) { return InnerMatcher.matches(*Node.IgnoreImplicit(), Finder, Builder); } /// Matches expressions that match InnerMatcher after any implicit casts /// are stripped off. /// /// Parentheses and explicit casts are not discarded. /// Given /// \code /// int arr[5]; /// int a = 0; /// char b = 0; /// const int c = a; /// int *d = arr; /// long e = (long) 0l; /// \endcode /// The matchers /// \code /// varDecl(hasInitializer(ignoringImpCasts(integerLiteral()))) /// varDecl(hasInitializer(ignoringImpCasts(declRefExpr()))) /// \endcode /// would match the declarations for a, b, c, and d, but not e. /// While /// \code /// varDecl(hasInitializer(integerLiteral())) /// varDecl(hasInitializer(declRefExpr())) /// \endcode /// only match the declarations for a. AST_MATCHER_P(Expr, ignoringImpCasts, internal::Matcher<Expr>, InnerMatcher) { return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder); } /// Matches expressions that match InnerMatcher after parentheses and /// casts are stripped off. /// /// Implicit and non-C Style casts are also discarded. /// Given /// \code /// int a = 0; /// char b = (0); /// void* c = reinterpret_cast<char*>(0); /// char d = char(0); /// \endcode /// The matcher /// varDecl(hasInitializer(ignoringParenCasts(integerLiteral()))) /// would match the declarations for a, b, c, and d. /// while /// varDecl(hasInitializer(integerLiteral())) /// only match the declaration for a. AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) { return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder); } /// Matches expressions that match InnerMatcher after implicit casts and /// parentheses are stripped off. /// /// Explicit casts are not discarded. /// Given /// \code /// int arr[5]; /// int a = 0; /// char b = (0); /// const int c = a; /// int *d = (arr); /// long e = ((long) 0l); /// \endcode /// The matchers /// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral()))) /// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr()))) /// would match the declarations for a, b, c, and d, but not e. /// while /// varDecl(hasInitializer(integerLiteral())) /// varDecl(hasInitializer(declRefExpr())) /// would only match the declaration for a. AST_MATCHER_P(Expr, ignoringParenImpCasts, internal::Matcher<Expr>, InnerMatcher) { return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder); } /// Matches types that match InnerMatcher after any parens are stripped. /// /// Given /// \code /// void (*fp)(void); /// \endcode /// The matcher /// \code /// varDecl(hasType(pointerType(pointee(ignoringParens(functionType()))))) /// \endcode /// would match the declaration for fp. AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher<QualType>, InnerMatcher, 0) { return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder); } /// Overload \c ignoringParens for \c Expr. /// /// Given /// \code /// const char* str = ("my-string"); /// \endcode /// The matcher /// \code /// implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral()))) /// \endcode /// would match the implicit cast resulting from the assignment. AST_MATCHER_P_OVERLOAD(Expr, ignoringParens, internal::Matcher<Expr>, InnerMatcher, 1) { const Expr *E = Node.IgnoreParens(); return InnerMatcher.matches(*E, Finder, Builder); } /// Matches expressions that are instantiation-dependent even if it is /// neither type- nor value-dependent. /// /// In the following example, the expression sizeof(sizeof(T() + T())) /// is instantiation-dependent (since it involves a template parameter T), /// but is neither type- nor value-dependent, since the type of the inner /// sizeof is known (std::size_t) and therefore the size of the outer /// sizeof is known. /// \code /// template<typename T> /// void f(T x, T y) { sizeof(sizeof(T() + T()); } /// \endcode /// expr(isInstantiationDependent()) matches sizeof(sizeof(T() + T()) AST_MATCHER(Expr, isInstantiationDependent) { return Node.isInstantiationDependent(); } /// Matches expressions that are type-dependent because the template type /// is not yet instantiated. /// /// For example, the expressions "x" and "x + y" are type-dependent in /// the following code, but "y" is not type-dependent: /// \code /// template<typename T> /// void add(T x, int y) { /// x + y; /// } /// \endcode /// expr(isTypeDependent()) matches x + y AST_MATCHER(Expr, isTypeDependent) { return Node.isTypeDependent(); } /// Matches expression that are value-dependent because they contain a /// non-type template parameter. /// /// For example, the array bound of "Chars" in the following example is /// value-dependent. /// \code /// template<int Size> int f() { return Size; } /// \endcode /// expr(isValueDependent()) matches return Size AST_MATCHER(Expr, isValueDependent) { return Node.isValueDependent(); } /// Matches classTemplateSpecializations, templateSpecializationType and /// functionDecl where the n'th TemplateArgument matches the given InnerMatcher. /// /// Given /// \code /// template<typename T, typename U> class A {}; /// A<bool, int> b; /// A<int, bool> c; /// /// template<typename T> void f() {} /// void func() { f<int>(); }; /// \endcode /// classTemplateSpecializationDecl(hasTemplateArgument( /// 1, refersToType(asString("int")))) /// matches the specialization \c A<bool, int> /// /// functionDecl(hasTemplateArgument(0, refersToType(asString("int")))) /// matches the specialization \c f<int> AST_POLYMORPHIC_MATCHER_P2( hasTemplateArgument, AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl, TemplateSpecializationType, FunctionDecl), unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) { ArrayRef<TemplateArgument> List = internal::getTemplateSpecializationArgs(Node); if (List.size() <= N) return false; return InnerMatcher.matches(List[N], Finder, Builder); } /// Matches if the number of template arguments equals \p N. /// /// Given /// \code /// template<typename T> struct C {}; /// C<int> c; /// \endcode /// classTemplateSpecializationDecl(templateArgumentCountIs(1)) /// matches C<int>. AST_POLYMORPHIC_MATCHER_P( templateArgumentCountIs, AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl, TemplateSpecializationType), unsigned, N) { return internal::getTemplateSpecializationArgs(Node).size() == N; } /// Matches a TemplateArgument that refers to a certain type. /// /// Given /// \code /// struct X {}; /// template<typename T> struct A {}; /// A<X> a; /// \endcode /// classTemplateSpecializationDecl(hasAnyTemplateArgument( /// refersToType(class(hasName("X"))))) /// matches the specialization \c A<X> AST_MATCHER_P(TemplateArgument, refersToType, internal::Matcher<QualType>, InnerMatcher) { if (Node.getKind() != TemplateArgument::Type) return false; return InnerMatcher.matches(Node.getAsType(), Finder, Builder); } /// Matches a TemplateArgument that refers to a certain template. /// /// Given /// \code /// template<template <typename> class S> class X {}; /// template<typename T> class Y {}; /// X<Y> xi; /// \endcode /// classTemplateSpecializationDecl(hasAnyTemplateArgument( /// refersToTemplate(templateName()))) /// matches the specialization \c X<Y> AST_MATCHER_P(TemplateArgument, refersToTemplate, internal::Matcher<TemplateName>, InnerMatcher) { if (Node.getKind() != TemplateArgument::Template) return false; return InnerMatcher.matches(Node.getAsTemplate(), Finder, Builder); } /// Matches a canonical TemplateArgument that refers to a certain /// declaration. /// /// Given /// \code /// struct B { int next; }; /// template<int(B::*next_ptr)> struct A {}; /// A<&B::next> a; /// \endcode /// classTemplateSpecializationDecl(hasAnyTemplateArgument( /// refersToDeclaration(fieldDecl(hasName("next"))))) /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching /// \c B::next AST_MATCHER_P(TemplateArgument, refersToDeclaration, internal::Matcher<Decl>, InnerMatcher) { if (Node.getKind() == TemplateArgument::Declaration) return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder); return false; } /// Matches a sugar TemplateArgument that refers to a certain expression. /// /// Given /// \code /// struct B { int next; }; /// template<int(B::*next_ptr)> struct A {}; /// A<&B::next> a; /// \endcode /// templateSpecializationType(hasAnyTemplateArgument( /// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next")))))))) /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching /// \c B::next AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) { if (Node.getKind() == TemplateArgument::Expression) return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder); return false; } /// Matches a TemplateArgument that is an integral value. /// /// Given /// \code /// template<int T> struct C {}; /// C<42> c; /// \endcode /// classTemplateSpecializationDecl( /// hasAnyTemplateArgument(isIntegral())) /// matches the implicit instantiation of C in C<42> /// with isIntegral() matching 42. AST_MATCHER(TemplateArgument, isIntegral) { return Node.getKind() == TemplateArgument::Integral; } /// Matches a TemplateArgument that refers to an integral type. /// /// Given /// \code /// template<int T> struct C {}; /// C<42> c; /// \endcode /// classTemplateSpecializationDecl( /// hasAnyTemplateArgument(refersToIntegralType(asString("int")))) /// matches the implicit instantiation of C in C<42>. AST_MATCHER_P(TemplateArgument, refersToIntegralType, internal::Matcher<QualType>, InnerMatcher) { if (Node.getKind() != TemplateArgument::Integral) return false; return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder); } /// Matches a TemplateArgument of integral type with a given value. /// /// Note that 'Value' is a string as the template argument's value is /// an arbitrary precision integer. 'Value' must be euqal to the canonical /// representation of that integral value in base 10. /// /// Given /// \code /// template<int T> struct C {}; /// C<42> c; /// \endcode /// classTemplateSpecializationDecl( /// hasAnyTemplateArgument(equalsIntegralValue("42"))) /// matches the implicit instantiation of C in C<42>. AST_MATCHER_P(TemplateArgument, equalsIntegralValue, std::string, Value) { if (Node.getKind() != TemplateArgument::Integral) return false; return toString(Node.getAsIntegral(), 10) == Value; } /// Matches an Objective-C autorelease pool statement. /// /// Given /// \code /// @autoreleasepool { /// int x = 0; /// } /// \endcode /// autoreleasePoolStmt(stmt()) matches the declaration of "x" /// inside the autorelease pool. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAutoreleasePoolStmt> autoreleasePoolStmt; /// Matches any value declaration. /// /// Example matches A, B, C and F /// \code /// enum X { A, B, C }; /// void F(); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl; /// Matches C++ constructor declarations. /// /// Example matches Foo::Foo() and Foo::Foo(int) /// \code /// class Foo { /// public: /// Foo(); /// Foo(int); /// int DoSomething(); /// }; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConstructorDecl> cxxConstructorDecl; /// Matches explicit C++ destructor declarations. /// /// Example matches Foo::~Foo() /// \code /// class Foo { /// public: /// virtual ~Foo(); /// }; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl> cxxDestructorDecl; /// Matches enum declarations. /// /// Example matches X /// \code /// enum X { /// A, B, C /// }; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl; /// Matches enum constants. /// /// Example matches A, B, C /// \code /// enum X { /// A, B, C /// }; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumConstantDecl> enumConstantDecl; /// Matches tag declarations. /// /// Example matches X, Z, U, S, E /// \code /// class X; /// template<class T> class Z {}; /// struct S {}; /// union U {}; /// enum E { /// A, B, C /// }; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, TagDecl> tagDecl; /// Matches method declarations. /// /// Example matches y /// \code /// class X { void y(); }; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> cxxMethodDecl; /// Matches conversion operator declarations. /// /// Example matches the operator. /// \code /// class X { operator int() const; }; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl> cxxConversionDecl; /// Matches user-defined and implicitly generated deduction guide. /// /// Example matches the deduction guide. /// \code /// template<typename T> /// class X { X(int) }; /// X(int) -> X<int>; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDeductionGuideDecl> cxxDeductionGuideDecl; /// Matches variable declarations. /// /// Note: this does not match declarations of member variables, which are /// "field" declarations in Clang parlance. /// /// Example matches a /// \code /// int a; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl; /// Matches field declarations. /// /// Given /// \code /// class X { int m; }; /// \endcode /// fieldDecl() /// matches 'm'. extern const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl; /// Matches indirect field declarations. /// /// Given /// \code /// struct X { struct { int a; }; }; /// \endcode /// indirectFieldDecl() /// matches 'a'. extern const internal::VariadicDynCastAllOfMatcher<Decl, IndirectFieldDecl> indirectFieldDecl; /// Matches function declarations. /// /// Example matches f /// \code /// void f(); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl> functionDecl; /// Matches C++ function template declarations. /// /// Example matches f /// \code /// template<class T> void f(T t) {} /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionTemplateDecl> functionTemplateDecl; /// Matches friend declarations. /// /// Given /// \code /// class X { friend void foo(); }; /// \endcode /// friendDecl() /// matches 'friend void foo()'. extern const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl; /// Matches statements. /// /// Given /// \code /// { ++a; } /// \endcode /// stmt() /// matches both the compound statement '{ ++a; }' and '++a'. extern const internal::VariadicAllOfMatcher<Stmt> stmt; /// Matches declaration statements. /// /// Given /// \code /// int a; /// \endcode /// declStmt() /// matches 'int a'. extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclStmt> declStmt; /// Matches member expressions. /// /// Given /// \code /// class Y { /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; } /// int a; static int b; /// }; /// \endcode /// memberExpr() /// matches this->x, x, y.x, a, this->b extern const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr; /// Matches unresolved member expressions. /// /// Given /// \code /// struct X { /// template <class T> void f(); /// void g(); /// }; /// template <class T> void h() { X x; x.f<T>(); x.g(); } /// \endcode /// unresolvedMemberExpr() /// matches x.f<T> extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedMemberExpr> unresolvedMemberExpr; /// Matches member expressions where the actual member referenced could not be /// resolved because the base expression or the member name was dependent. /// /// Given /// \code /// template <class T> void f() { T t; t.g(); } /// \endcode /// cxxDependentScopeMemberExpr() /// matches t.g extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDependentScopeMemberExpr> cxxDependentScopeMemberExpr; /// Matches call expressions. /// /// Example matches x.y() and y() /// \code /// X x; /// x.y(); /// y(); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr; /// Matches call expressions which were resolved using ADL. /// /// Example matches y(x) but not y(42) or NS::y(x). /// \code /// namespace NS { /// struct X {}; /// void y(X); /// } /// /// void y(...); /// /// void test() { /// NS::X x; /// y(x); // Matches /// NS::y(x); // Doesn't match /// y(42); // Doesn't match /// using NS::y; /// y(x); // Found by both unqualified lookup and ADL, doesn't match // } /// \endcode AST_MATCHER(CallExpr, usesADL) { return Node.usesADL(); } /// Matches lambda expressions. /// /// Example matches [&](){return 5;} /// \code /// [&](){return 5;} /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr; /// Matches member call expressions. /// /// Example matches x.y() /// \code /// X x; /// x.y(); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr> cxxMemberCallExpr; /// Matches ObjectiveC Message invocation expressions. /// /// The innermost message send invokes the "alloc" class method on the /// NSString class, while the outermost message send invokes the /// "initWithString" instance method on the object returned from /// NSString's "alloc". This matcher should match both message sends. /// \code /// [[NSString alloc] initWithString:@"Hello"] /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCMessageExpr> objcMessageExpr; /// Matches Objective-C interface declarations. /// /// Example matches Foo /// \code /// @interface Foo /// @end /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCInterfaceDecl> objcInterfaceDecl; /// Matches Objective-C implementation declarations. /// /// Example matches Foo /// \code /// @implementation Foo /// @end /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCImplementationDecl> objcImplementationDecl; /// Matches Objective-C protocol declarations. /// /// Example matches FooDelegate /// \code /// @protocol FooDelegate /// @end /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCProtocolDecl> objcProtocolDecl; /// Matches Objective-C category declarations. /// /// Example matches Foo (Additions) /// \code /// @interface Foo (Additions) /// @end /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryDecl> objcCategoryDecl; /// Matches Objective-C category definitions. /// /// Example matches Foo (Additions) /// \code /// @implementation Foo (Additions) /// @end /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryImplDecl> objcCategoryImplDecl; /// Matches Objective-C method declarations. /// /// Example matches both declaration and definition of -[Foo method] /// \code /// @interface Foo /// - (void)method; /// @end /// /// @implementation Foo /// - (void)method {} /// @end /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCMethodDecl> objcMethodDecl; /// Matches block declarations. /// /// Example matches the declaration of the nameless block printing an input /// integer. /// /// \code /// myFunc(^(int p) { /// printf("%d", p); /// }) /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, BlockDecl> blockDecl; /// Matches Objective-C instance variable declarations. /// /// Example matches _enabled /// \code /// @implementation Foo { /// BOOL _enabled; /// } /// @end /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCIvarDecl> objcIvarDecl; /// Matches Objective-C property declarations. /// /// Example matches enabled /// \code /// @interface Foo /// @property BOOL enabled; /// @end /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCPropertyDecl> objcPropertyDecl; /// Matches Objective-C \@throw statements. /// /// Example matches \@throw /// \code /// @throw obj; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtThrowStmt> objcThrowStmt; /// Matches Objective-C @try statements. /// /// Example matches @try /// \code /// @try {} /// @catch (...) {} /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtTryStmt> objcTryStmt; /// Matches Objective-C @catch statements. /// /// Example matches @catch /// \code /// @try {} /// @catch (...) {} /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtCatchStmt> objcCatchStmt; /// Matches Objective-C @finally statements. /// /// Example matches @finally /// \code /// @try {} /// @finally {} /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtFinallyStmt> objcFinallyStmt; /// Matches expressions that introduce cleanups to be run at the end /// of the sub-expression's evaluation. /// /// Example matches std::string() /// \code /// const std::string str = std::string(); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups> exprWithCleanups; /// Matches init list expressions. /// /// Given /// \code /// int a[] = { 1, 2 }; /// struct B { int x, y; }; /// B b = { 5, 6 }; /// \endcode /// initListExpr() /// matches "{ 1, 2 }" and "{ 5, 6 }" extern const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr> initListExpr; /// Matches the syntactic form of init list expressions /// (if expression have it). AST_MATCHER_P(InitListExpr, hasSyntacticForm, internal::Matcher<Expr>, InnerMatcher) { const Expr *SyntForm = Node.getSyntacticForm(); return (SyntForm != nullptr && InnerMatcher.matches(*SyntForm, Finder, Builder)); } /// Matches C++ initializer list expressions. /// /// Given /// \code /// std::vector<int> a({ 1, 2, 3 }); /// std::vector<int> b = { 4, 5 }; /// int c[] = { 6, 7 }; /// std::pair<int, int> d = { 8, 9 }; /// \endcode /// cxxStdInitializerListExpr() /// matches "{ 1, 2, 3 }" and "{ 4, 5 }" extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStdInitializerListExpr> cxxStdInitializerListExpr; /// Matches implicit initializers of init list expressions. /// /// Given /// \code /// point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; /// \endcode /// implicitValueInitExpr() /// matches "[0].y" (implicitly) extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr> implicitValueInitExpr; /// Matches paren list expressions. /// ParenListExprs don't have a predefined type and are used for late parsing. /// In the final AST, they can be met in template declarations. /// /// Given /// \code /// template<typename T> class X { /// void f() { /// X x(*this); /// int a = 0, b = 1; int i = (a, b); /// } /// }; /// \endcode /// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b) /// has a predefined type and is a ParenExpr, not a ParenListExpr. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr> parenListExpr; /// Matches substitutions of non-type template parameters. /// /// Given /// \code /// template <int N> /// struct A { static const int n = N; }; /// struct B : public A<42> {}; /// \endcode /// substNonTypeTemplateParmExpr() /// matches "N" in the right-hand side of "static const int n = N;" extern const internal::VariadicDynCastAllOfMatcher<Stmt, SubstNonTypeTemplateParmExpr> substNonTypeTemplateParmExpr; /// Matches using declarations. /// /// Given /// \code /// namespace X { int x; } /// using X::x; /// \endcode /// usingDecl() /// matches \code using X::x \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl; /// Matches using-enum declarations. /// /// Given /// \code /// namespace X { enum x {...}; } /// using enum X::x; /// \endcode /// usingEnumDecl() /// matches \code using enum X::x \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingEnumDecl> usingEnumDecl; /// Matches using namespace declarations. /// /// Given /// \code /// namespace X { int x; } /// using namespace X; /// \endcode /// usingDirectiveDecl() /// matches \code using namespace X \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDirectiveDecl> usingDirectiveDecl; /// Matches reference to a name that can be looked up during parsing /// but could not be resolved to a specific declaration. /// /// Given /// \code /// template<typename T> /// T foo() { T a; return a; } /// template<typename T> /// void bar() { /// foo<T>(); /// } /// \endcode /// unresolvedLookupExpr() /// matches \code foo<T>() \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedLookupExpr> unresolvedLookupExpr; /// Matches unresolved using value declarations. /// /// Given /// \code /// template<typename X> /// class C : private X { /// using X::x; /// }; /// \endcode /// unresolvedUsingValueDecl() /// matches \code using X::x \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, UnresolvedUsingValueDecl> unresolvedUsingValueDecl; /// Matches unresolved using value declarations that involve the /// typename. /// /// Given /// \code /// template <typename T> /// struct Base { typedef T Foo; }; /// /// template<typename T> /// struct S : private Base<T> { /// using typename Base<T>::Foo; /// }; /// \endcode /// unresolvedUsingTypenameDecl() /// matches \code using Base<T>::Foo \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, UnresolvedUsingTypenameDecl> unresolvedUsingTypenameDecl; /// Matches a constant expression wrapper. /// /// Example matches the constant in the case statement: /// (matcher = constantExpr()) /// \code /// switch (a) { /// case 37: break; /// } /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConstantExpr> constantExpr; /// Matches parentheses used in expressions. /// /// Example matches (foo() + 1) /// \code /// int foo() { return 1; } /// int a = (foo() + 1); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr; /// Matches constructor call expressions (including implicit ones). /// /// Example matches string(ptr, n) and ptr within arguments of f /// (matcher = cxxConstructExpr()) /// \code /// void f(const string &a, const string &b); /// char *ptr; /// int n; /// f(string(ptr, n), ptr); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstructExpr> cxxConstructExpr; /// Matches unresolved constructor call expressions. /// /// Example matches T(t) in return statement of f /// (matcher = cxxUnresolvedConstructExpr()) /// \code /// template <typename T> /// void f(const T& t) { return T(t); } /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXUnresolvedConstructExpr> cxxUnresolvedConstructExpr; /// Matches implicit and explicit this expressions. /// /// Example matches the implicit this expression in "return i". /// (matcher = cxxThisExpr()) /// \code /// struct foo { /// int i; /// int f() { return i; } /// }; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr> cxxThisExpr; /// Matches nodes where temporaries are created. /// /// Example matches FunctionTakesString(GetStringByValue()) /// (matcher = cxxBindTemporaryExpr()) /// \code /// FunctionTakesString(GetStringByValue()); /// FunctionTakesStringByPointer(GetStringPointer()); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBindTemporaryExpr> cxxBindTemporaryExpr; /// Matches nodes where temporaries are materialized. /// /// Example: Given /// \code /// struct T {void func();}; /// T f(); /// void g(T); /// \endcode /// materializeTemporaryExpr() matches 'f()' in these statements /// \code /// T u(f()); /// g(f()); /// f().func(); /// \endcode /// but does not match /// \code /// f(); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, MaterializeTemporaryExpr> materializeTemporaryExpr; /// Matches new expressions. /// /// Given /// \code /// new X; /// \endcode /// cxxNewExpr() /// matches 'new X'. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr; /// Matches delete expressions. /// /// Given /// \code /// delete X; /// \endcode /// cxxDeleteExpr() /// matches 'delete X'. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr> cxxDeleteExpr; /// Matches noexcept expressions. /// /// Given /// \code /// bool a() noexcept; /// bool b() noexcept(true); /// bool c() noexcept(false); /// bool d() noexcept(noexcept(a())); /// bool e = noexcept(b()) || noexcept(c()); /// \endcode /// cxxNoexceptExpr() /// matches `noexcept(a())`, `noexcept(b())` and `noexcept(c())`. /// doesn't match the noexcept specifier in the declarations a, b, c or d. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNoexceptExpr> cxxNoexceptExpr; /// Matches array subscript expressions. /// /// Given /// \code /// int i = a[1]; /// \endcode /// arraySubscriptExpr() /// matches "a[1]" extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArraySubscriptExpr> arraySubscriptExpr; /// Matches the value of a default argument at the call site. /// /// Example matches the CXXDefaultArgExpr placeholder inserted for the /// default value of the second parameter in the call expression f(42) /// (matcher = cxxDefaultArgExpr()) /// \code /// void f(int x, int y = 0); /// f(42); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDefaultArgExpr> cxxDefaultArgExpr; /// Matches overloaded operator calls. /// /// Note that if an operator isn't overloaded, it won't match. Instead, use /// binaryOperator matcher. /// Currently it does not match operators such as new delete. /// FIXME: figure out why these do not match? /// /// Example matches both operator<<((o << b), c) and operator<<(o, b) /// (matcher = cxxOperatorCallExpr()) /// \code /// ostream &operator<< (ostream &out, int i) { }; /// ostream &o; int b = 1, c = 1; /// o << b << c; /// \endcode /// See also the binaryOperation() matcher for more-general matching of binary /// uses of this AST node. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXOperatorCallExpr> cxxOperatorCallExpr; /// Matches rewritten binary operators /// /// Example matches use of "<": /// \code /// #include <compare> /// struct HasSpaceshipMem { /// int a; /// constexpr auto operator<=>(const HasSpaceshipMem&) const = default; /// }; /// void compare() { /// HasSpaceshipMem hs1, hs2; /// if (hs1 < hs2) /// return; /// } /// \endcode /// See also the binaryOperation() matcher for more-general matching /// of this AST node. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXRewrittenBinaryOperator> cxxRewrittenBinaryOperator; /// Matches expressions. /// /// Example matches x() /// \code /// void f() { x(); } /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr; /// Matches expressions that refer to declarations. /// /// Example matches x in if (x) /// \code /// bool x; /// if (x) {} /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr> declRefExpr; /// Matches a reference to an ObjCIvar. /// /// Example: matches "a" in "init" method: /// \code /// @implementation A { /// NSString *a; /// } /// - (void) init { /// a = @"hello"; /// } /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCIvarRefExpr> objcIvarRefExpr; /// Matches a reference to a block. /// /// Example: matches "^{}": /// \code /// void f() { ^{}(); } /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, BlockExpr> blockExpr; /// Matches if statements. /// /// Example matches 'if (x) {}' /// \code /// if (x) {} /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt; /// Matches for statements. /// /// Example matches 'for (;;) {}' /// \code /// for (;;) {} /// int i[] = {1, 2, 3}; for (auto a : i); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt; /// Matches the increment statement of a for loop. /// /// Example: /// forStmt(hasIncrement(unaryOperator(hasOperatorName("++")))) /// matches '++x' in /// \code /// for (x; x < N; ++x) { } /// \endcode AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>, InnerMatcher) { const Stmt *const Increment = Node.getInc(); return (Increment != nullptr && InnerMatcher.matches(*Increment, Finder, Builder)); } /// Matches the initialization statement of a for loop. /// /// Example: /// forStmt(hasLoopInit(declStmt())) /// matches 'int x = 0' in /// \code /// for (int x = 0; x < N; ++x) { } /// \endcode AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>, InnerMatcher) { const Stmt *const Init = Node.getInit(); return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder)); } /// Matches range-based for statements. /// /// cxxForRangeStmt() matches 'for (auto a : i)' /// \code /// int i[] = {1, 2, 3}; for (auto a : i); /// for(int j = 0; j < 5; ++j); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt> cxxForRangeStmt; /// Matches the initialization statement of a for loop. /// /// Example: /// forStmt(hasLoopVariable(anything())) /// matches 'int x' in /// \code /// for (int x : a) { } /// \endcode AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>, InnerMatcher) { const VarDecl *const Var = Node.getLoopVariable(); return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder)); } /// Matches the range initialization statement of a for loop. /// /// Example: /// forStmt(hasRangeInit(anything())) /// matches 'a' in /// \code /// for (int x : a) { } /// \endcode AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>, InnerMatcher) { const Expr *const Init = Node.getRangeInit(); return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder)); } /// Matches while statements. /// /// Given /// \code /// while (true) {} /// \endcode /// whileStmt() /// matches 'while (true) {}'. extern const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt; /// Matches do statements. /// /// Given /// \code /// do {} while (true); /// \endcode /// doStmt() /// matches 'do {} while(true)' extern const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt; /// Matches break statements. /// /// Given /// \code /// while (true) { break; } /// \endcode /// breakStmt() /// matches 'break' extern const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt; /// Matches continue statements. /// /// Given /// \code /// while (true) { continue; } /// \endcode /// continueStmt() /// matches 'continue' extern const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt> continueStmt; /// Matches co_return statements. /// /// Given /// \code /// while (true) { co_return; } /// \endcode /// coreturnStmt() /// matches 'co_return' extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoreturnStmt> coreturnStmt; /// Matches return statements. /// /// Given /// \code /// return 1; /// \endcode /// returnStmt() /// matches 'return 1' extern const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt; /// Matches goto statements. /// /// Given /// \code /// goto FOO; /// FOO: bar(); /// \endcode /// gotoStmt() /// matches 'goto FOO' extern const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt; /// Matches label statements. /// /// Given /// \code /// goto FOO; /// FOO: bar(); /// \endcode /// labelStmt() /// matches 'FOO:' extern const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt; /// Matches address of label statements (GNU extension). /// /// Given /// \code /// FOO: bar(); /// void *ptr = &&FOO; /// goto *bar; /// \endcode /// addrLabelExpr() /// matches '&&FOO' extern const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr> addrLabelExpr; /// Matches switch statements. /// /// Given /// \code /// switch(a) { case 42: break; default: break; } /// \endcode /// switchStmt() /// matches 'switch(a)'. extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt; /// Matches case and default statements inside switch statements. /// /// Given /// \code /// switch(a) { case 42: break; default: break; } /// \endcode /// switchCase() /// matches 'case 42:' and 'default:'. extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase; /// Matches case statements inside switch statements. /// /// Given /// \code /// switch(a) { case 42: break; default: break; } /// \endcode /// caseStmt() /// matches 'case 42:'. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt; /// Matches default statements inside switch statements. /// /// Given /// \code /// switch(a) { case 42: break; default: break; } /// \endcode /// defaultStmt() /// matches 'default:'. extern const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt> defaultStmt; /// Matches compound statements. /// /// Example matches '{}' and '{{}}' in 'for (;;) {{}}' /// \code /// for (;;) {{}} /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt> compoundStmt; /// Matches catch statements. /// /// \code /// try {} catch(int i) {} /// \endcode /// cxxCatchStmt() /// matches 'catch(int i)' extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt> cxxCatchStmt; /// Matches try statements. /// /// \code /// try {} catch(int i) {} /// \endcode /// cxxTryStmt() /// matches 'try {}' extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt; /// Matches throw expressions. /// /// \code /// try { throw 5; } catch(int i) {} /// \endcode /// cxxThrowExpr() /// matches 'throw 5' extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr> cxxThrowExpr; /// Matches null statements. /// /// \code /// foo();; /// \endcode /// nullStmt() /// matches the second ';' extern const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt; /// Matches asm statements. /// /// \code /// int i = 100; /// __asm("mov al, 2"); /// \endcode /// asmStmt() /// matches '__asm("mov al, 2")' extern const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt; /// Matches bool literals. /// /// Example matches true /// \code /// true /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBoolLiteralExpr> cxxBoolLiteral; /// Matches string literals (also matches wide string literals). /// /// Example matches "abcd", L"abcd" /// \code /// char *s = "abcd"; /// wchar_t *ws = L"abcd"; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, StringLiteral> stringLiteral; /// Matches character literals (also matches wchar_t). /// /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral), /// though. /// /// Example matches 'a', L'a' /// \code /// char ch = 'a'; /// wchar_t chw = L'a'; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CharacterLiteral> characterLiteral; /// Matches integer literals of all sizes / encodings, e.g. /// 1, 1L, 0x1 and 1U. /// /// Does not match character-encoded integers such as L'a'. extern const internal::VariadicDynCastAllOfMatcher<Stmt, IntegerLiteral> integerLiteral; /// Matches float literals of all sizes / encodings, e.g. /// 1.0, 1.0f, 1.0L and 1e10. /// /// Does not match implicit conversions such as /// \code /// float a = 10; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, FloatingLiteral> floatLiteral; /// Matches imaginary literals, which are based on integer and floating /// point literals e.g.: 1i, 1.0i extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImaginaryLiteral> imaginaryLiteral; /// Matches fixed point literals extern const internal::VariadicDynCastAllOfMatcher<Stmt, FixedPointLiteral> fixedPointLiteral; /// Matches user defined literal operator call. /// /// Example match: "foo"_suffix extern const internal::VariadicDynCastAllOfMatcher<Stmt, UserDefinedLiteral> userDefinedLiteral; /// Matches compound (i.e. non-scalar) literals /// /// Example match: {1}, (1, 2) /// \code /// int array[4] = {1}; /// vector int myvec = (vector int)(1, 2); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundLiteralExpr> compoundLiteralExpr; /// Matches co_await expressions. /// /// Given /// \code /// co_await 1; /// \endcode /// coawaitExpr() /// matches 'co_await 1' extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoawaitExpr> coawaitExpr; /// Matches co_await expressions where the type of the promise is dependent extern const internal::VariadicDynCastAllOfMatcher<Stmt, DependentCoawaitExpr> dependentCoawaitExpr; /// Matches co_yield expressions. /// /// Given /// \code /// co_yield 1; /// \endcode /// coyieldExpr() /// matches 'co_yield 1' extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoyieldExpr> coyieldExpr; /// Matches nullptr literal. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNullPtrLiteralExpr> cxxNullPtrLiteralExpr; /// Matches GNU __builtin_choose_expr. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ChooseExpr> chooseExpr; /// Matches GNU __null expression. extern const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr> gnuNullExpr; /// Matches C11 _Generic expression. extern const internal::VariadicDynCastAllOfMatcher<Stmt, GenericSelectionExpr> genericSelectionExpr; /// Matches atomic builtins. /// Example matches __atomic_load_n(ptr, 1) /// \code /// void foo() { int *ptr; __atomic_load_n(ptr, 1); } /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr; /// Matches statement expression (GNU extension). /// /// Example match: ({ int X = 4; X; }) /// \code /// int C = ({ int X = 4; X; }); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr; /// Matches binary operator expressions. /// /// Example matches a || b /// \code /// !(a || b) /// \endcode /// See also the binaryOperation() matcher for more-general matching. extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryOperator> binaryOperator; /// Matches unary operator expressions. /// /// Example matches !a /// \code /// !a || b /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryOperator> unaryOperator; /// Matches conditional operator expressions. /// /// Example matches a ? b : c /// \code /// (a ? b : c) + 42 /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConditionalOperator> conditionalOperator; /// Matches binary conditional operator expressions (GNU extension). /// /// Example matches a ?: b /// \code /// (a ?: b) + 42; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryConditionalOperator> binaryConditionalOperator; /// Matches opaque value expressions. They are used as helpers /// to reference another expressions and can be met /// in BinaryConditionalOperators, for example. /// /// Example matches 'a' /// \code /// (a ?: c) + 42; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, OpaqueValueExpr> opaqueValueExpr; /// Matches a C++ static_assert declaration. /// /// Example: /// staticAssertExpr() /// matches /// static_assert(sizeof(S) == sizeof(int)) /// in /// \code /// struct S { /// int x; /// }; /// static_assert(sizeof(S) == sizeof(int)); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, StaticAssertDecl> staticAssertDecl; /// Matches a reinterpret_cast expression. /// /// Either the source expression or the destination type can be matched /// using has(), but hasDestinationType() is more specific and can be /// more readable. /// /// Example matches reinterpret_cast<char*>(&p) in /// \code /// void* p = reinterpret_cast<char*>(&p); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXReinterpretCastExpr> cxxReinterpretCastExpr; /// Matches a C++ static_cast expression. /// /// \see hasDestinationType /// \see reinterpretCast /// /// Example: /// cxxStaticCastExpr() /// matches /// static_cast<long>(8) /// in /// \code /// long eight(static_cast<long>(8)); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStaticCastExpr> cxxStaticCastExpr; /// Matches a dynamic_cast expression. /// /// Example: /// cxxDynamicCastExpr() /// matches /// dynamic_cast<D*>(&b); /// in /// \code /// struct B { virtual ~B() {} }; struct D : B {}; /// B b; /// D* p = dynamic_cast<D*>(&b); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDynamicCastExpr> cxxDynamicCastExpr; /// Matches a const_cast expression. /// /// Example: Matches const_cast<int*>(&r) in /// \code /// int n = 42; /// const int &r(n); /// int* p = const_cast<int*>(&r); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstCastExpr> cxxConstCastExpr; /// Matches a C-style cast expression. /// /// Example: Matches (int) 2.2f in /// \code /// int i = (int) 2.2f; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CStyleCastExpr> cStyleCastExpr; /// Matches explicit cast expressions. /// /// Matches any cast expression written in user code, whether it be a /// C-style cast, a functional-style cast, or a keyword cast. /// /// Does not match implicit conversions. /// /// Note: the name "explicitCast" is chosen to match Clang's terminology, as /// Clang uses the term "cast" to apply to implicit conversions as well as to /// actual cast expressions. /// /// \see hasDestinationType. /// /// Example: matches all five of the casts in /// \code /// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42))))) /// \endcode /// but does not match the implicit conversion in /// \code /// long ell = 42; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExplicitCastExpr> explicitCastExpr; /// Matches the implicit cast nodes of Clang's AST. /// /// This matches many different places, including function call return value /// eliding, as well as any type conversions. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitCastExpr> implicitCastExpr; /// Matches any cast nodes of Clang's AST. /// /// Example: castExpr() matches each of the following: /// \code /// (int) 3; /// const_cast<Expr *>(SubExpr); /// char c = 0; /// \endcode /// but does not match /// \code /// int i = (0); /// int k = 0; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr; /// Matches functional cast expressions /// /// Example: Matches Foo(bar); /// \code /// Foo f = bar; /// Foo g = (Foo) bar; /// Foo h = Foo(bar); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFunctionalCastExpr> cxxFunctionalCastExpr; /// Matches functional cast expressions having N != 1 arguments /// /// Example: Matches Foo(bar, bar) /// \code /// Foo h = Foo(bar, bar); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTemporaryObjectExpr> cxxTemporaryObjectExpr; /// Matches predefined identifier expressions [C99 6.4.2.2]. /// /// Example: Matches __func__ /// \code /// printf("%s", __func__); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, PredefinedExpr> predefinedExpr; /// Matches C99 designated initializer expressions [C99 6.7.8]. /// /// Example: Matches { [2].y = 1.0, [0].x = 1.0 } /// \code /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 }; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, DesignatedInitExpr> designatedInitExpr; /// Matches designated initializer expressions that contain /// a specific number of designators. /// /// Example: Given /// \code /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 }; /// point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }; /// \endcode /// designatorCountIs(2) /// matches '{ [2].y = 1.0, [0].x = 1.0 }', /// but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'. AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) { return Node.size() == N; } /// Matches \c QualTypes in the clang AST. extern const internal::VariadicAllOfMatcher<QualType> qualType; /// Matches \c Types in the clang AST. extern const internal::VariadicAllOfMatcher<Type> type; /// Matches \c TypeLocs in the clang AST. extern const internal::VariadicAllOfMatcher<TypeLoc> typeLoc; /// Matches if any of the given matchers matches. /// /// Unlike \c anyOf, \c eachOf will generate a match result for each /// matching submatcher. /// /// For example, in: /// \code /// class A { int a; int b; }; /// \endcode /// The matcher: /// \code /// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")), /// has(fieldDecl(hasName("b")).bind("v")))) /// \endcode /// will generate two results binding "v", the first of which binds /// the field declaration of \c a, the second the field declaration of /// \c b. /// /// Usable as: Any Matcher extern const internal::VariadicOperatorMatcherFunc< 2, std::numeric_limits<unsigned>::max()> eachOf; /// Matches if any of the given matchers matches. /// /// Usable as: Any Matcher extern const internal::VariadicOperatorMatcherFunc< 2, std::numeric_limits<unsigned>::max()> anyOf; /// Matches if all given matchers match. /// /// Usable as: Any Matcher extern const internal::VariadicOperatorMatcherFunc< 2, std::numeric_limits<unsigned>::max()> allOf; /// Matches any node regardless of the submatcher. /// /// However, \c optionally will retain any bindings generated by the submatcher. /// Useful when additional information which may or may not present about a main /// matching node is desired. /// /// For example, in: /// \code /// class Foo { /// int bar; /// } /// \endcode /// The matcher: /// \code /// cxxRecordDecl( /// optionally(has( /// fieldDecl(hasName("bar")).bind("var") /// ))).bind("record") /// \endcode /// will produce a result binding for both "record" and "var". /// The matcher will produce a "record" binding for even if there is no data /// member named "bar" in that class. /// /// Usable as: Any Matcher extern const internal::VariadicOperatorMatcherFunc<1, 1> optionally; /// Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL) /// /// Given /// \code /// Foo x = bar; /// int y = sizeof(x) + alignof(x); /// \endcode /// unaryExprOrTypeTraitExpr() /// matches \c sizeof(x) and \c alignof(x) extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr; /// Matches any of the \p NodeMatchers with InnerMatchers nested within /// /// Given /// \code /// if (true); /// for (; true; ); /// \endcode /// with the matcher /// \code /// mapAnyOf(ifStmt, forStmt).with( /// hasCondition(cxxBoolLiteralExpr(equals(true))) /// ).bind("trueCond") /// \endcode /// matches the \c if and the \c for. It is equivalent to: /// \code /// auto trueCond = hasCondition(cxxBoolLiteralExpr(equals(true))); /// anyOf( /// ifStmt(trueCond).bind("trueCond"), /// forStmt(trueCond).bind("trueCond") /// ); /// \endcode /// /// The with() chain-call accepts zero or more matchers which are combined /// as-if with allOf() in each of the node matchers. /// Usable as: Any Matcher template <typename T, typename... U> auto mapAnyOf(internal::VariadicDynCastAllOfMatcher<T, U> const &...) { return internal::MapAnyOfHelper<U...>(); } /// Matches nodes which can be used with binary operators. /// /// The code /// \code /// var1 != var2; /// \endcode /// might be represented in the clang AST as a binaryOperator, a /// cxxOperatorCallExpr or a cxxRewrittenBinaryOperator, depending on /// /// * whether the types of var1 and var2 are fundamental (binaryOperator) or at /// least one is a class type (cxxOperatorCallExpr) /// * whether the code appears in a template declaration, if at least one of the /// vars is a dependent-type (binaryOperator) /// * whether the code relies on a rewritten binary operator, such as a /// spaceship operator or an inverted equality operator /// (cxxRewrittenBinaryOperator) /// /// This matcher elides details in places where the matchers for the nodes are /// compatible. /// /// Given /// \code /// binaryOperation( /// hasOperatorName("!="), /// hasLHS(expr().bind("lhs")), /// hasRHS(expr().bind("rhs")) /// ) /// \endcode /// matches each use of "!=" in: /// \code /// struct S{ /// bool operator!=(const S&) const; /// }; /// /// void foo() /// { /// 1 != 2; /// S() != S(); /// } /// /// template<typename T> /// void templ() /// { /// 1 != 2; /// T() != S(); /// } /// struct HasOpEq /// { /// bool operator==(const HasOpEq &) const; /// }; /// /// void inverse() /// { /// HasOpEq s1; /// HasOpEq s2; /// if (s1 != s2) /// return; /// } /// /// struct HasSpaceship /// { /// bool operator<=>(const HasOpEq &) const; /// }; /// /// void use_spaceship() /// { /// HasSpaceship s1; /// HasSpaceship s2; /// if (s1 != s2) /// return; /// } /// \endcode extern const internal::MapAnyOfMatcher<BinaryOperator, CXXOperatorCallExpr, CXXRewrittenBinaryOperator> binaryOperation; /// Matches function calls and constructor calls /// /// Because CallExpr and CXXConstructExpr do not share a common /// base class with API accessing arguments etc, AST Matchers for code /// which should match both are typically duplicated. This matcher /// removes the need for duplication. /// /// Given code /// \code /// struct ConstructorTakesInt /// { /// ConstructorTakesInt(int i) {} /// }; /// /// void callTakesInt(int i) /// { /// } /// /// void doCall() /// { /// callTakesInt(42); /// } /// /// void doConstruct() /// { /// ConstructorTakesInt cti(42); /// } /// \endcode /// /// The matcher /// \code /// invocation(hasArgument(0, integerLiteral(equals(42)))) /// \endcode /// matches the expression in both doCall and doConstruct extern const internal::MapAnyOfMatcher<CallExpr, CXXConstructExpr> invocation; /// Matches unary expressions that have a specific type of argument. /// /// Given /// \code /// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c); /// \endcode /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int")) /// matches \c sizeof(a) and \c alignof(c) AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType, internal::Matcher<QualType>, InnerMatcher) { const QualType ArgumentType = Node.getTypeOfArgument(); return InnerMatcher.matches(ArgumentType, Finder, Builder); } /// Matches unary expressions of a certain kind. /// /// Given /// \code /// int x; /// int s = sizeof(x) + alignof(x) /// \endcode /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf)) /// matches \c sizeof(x) /// /// If the matcher is use from clang-query, UnaryExprOrTypeTrait parameter /// should be passed as a quoted string. e.g., ofKind("UETT_SizeOf"). AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) { return Node.getKind() == Kind; } /// Same as unaryExprOrTypeTraitExpr, but only matching /// alignof. inline internal::BindableMatcher<Stmt> alignOfExpr( const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) { return stmt(unaryExprOrTypeTraitExpr( allOf(anyOf(ofKind(UETT_AlignOf), ofKind(UETT_PreferredAlignOf)), InnerMatcher))); } /// Same as unaryExprOrTypeTraitExpr, but only matching /// sizeof. inline internal::BindableMatcher<Stmt> sizeOfExpr( const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) { return stmt(unaryExprOrTypeTraitExpr( allOf(ofKind(UETT_SizeOf), InnerMatcher))); } /// Matches NamedDecl nodes that have the specified name. /// /// Supports specifying enclosing namespaces or classes by prefixing the name /// with '<enclosing>::'. /// Does not match typedefs of an underlying type with the given name. /// /// Example matches X (Name == "X") /// \code /// class X; /// \endcode /// /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X") /// \code /// namespace a { namespace b { class X; } } /// \endcode inline internal::Matcher<NamedDecl> hasName(StringRef Name) { return internal::Matcher<NamedDecl>( new internal::HasNameMatcher({std::string(Name)})); } /// Matches NamedDecl nodes that have any of the specified names. /// /// This matcher is only provided as a performance optimization of hasName. /// \code /// hasAnyName(a, b, c) /// \endcode /// is equivalent to, but faster than /// \code /// anyOf(hasName(a), hasName(b), hasName(c)) /// \endcode extern const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef, internal::hasAnyNameFunc> hasAnyName; /// Matches NamedDecl nodes whose fully qualified names contain /// a substring matched by the given RegExp. /// /// Supports specifying enclosing namespaces or classes by /// prefixing the name with '<enclosing>::'. Does not match typedefs /// of an underlying type with the given name. /// /// Example matches X (regexp == "::X") /// \code /// class X; /// \endcode /// /// Example matches X (regexp is one of "::X", "^foo::.*X", among others) /// \code /// namespace foo { namespace bar { class X; } } /// \endcode AST_MATCHER_REGEX(NamedDecl, matchesName, RegExp) { std::string FullNameString = "::" + Node.getQualifiedNameAsString(); return RegExp->match(FullNameString); } /// Matches overloaded operator names. /// /// Matches overloaded operator names specified in strings without the /// "operator" prefix: e.g. "<<". /// /// Given: /// \code /// class A { int operator*(); }; /// const A &operator<<(const A &a, const A &b); /// A a; /// a << a; // <-- This matches /// \endcode /// /// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the /// specified line and /// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*"))) /// matches the declaration of \c A. /// /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl> inline internal::PolymorphicMatcher< internal::HasOverloadedOperatorNameMatcher, AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl), std::vector<std::string>> hasOverloadedOperatorName(StringRef Name) { return internal::PolymorphicMatcher< internal::HasOverloadedOperatorNameMatcher, AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl), std::vector<std::string>>({std::string(Name)}); } /// Matches overloaded operator names. /// /// Matches overloaded operator names specified in strings without the /// "operator" prefix: e.g. "<<". /// /// hasAnyOverloadedOperatorName("+", "-") /// Is equivalent to /// anyOf(hasOverloadedOperatorName("+"), hasOverloadedOperatorName("-")) extern const internal::VariadicFunction< internal::PolymorphicMatcher<internal::HasOverloadedOperatorNameMatcher, AST_POLYMORPHIC_SUPPORTED_TYPES( CXXOperatorCallExpr, FunctionDecl), std::vector<std::string>>, StringRef, internal::hasAnyOverloadedOperatorNameFunc> hasAnyOverloadedOperatorName; /// Matches template-dependent, but known, member names. /// /// In template declarations, dependent members are not resolved and so can /// not be matched to particular named declarations. /// /// This matcher allows to match on the known name of members. /// /// Given /// \code /// template <typename T> /// struct S { /// void mem(); /// }; /// template <typename T> /// void x() { /// S<T> s; /// s.mem(); /// } /// \endcode /// \c cxxDependentScopeMemberExpr(hasMemberName("mem")) matches `s.mem()` AST_MATCHER_P(CXXDependentScopeMemberExpr, hasMemberName, std::string, N) { return Node.getMember().getAsString() == N; } /// Matches template-dependent, but known, member names against an already-bound /// node /// /// In template declarations, dependent members are not resolved and so can /// not be matched to particular named declarations. /// /// This matcher allows to match on the name of already-bound VarDecl, FieldDecl /// and CXXMethodDecl nodes. /// /// Given /// \code /// template <typename T> /// struct S { /// void mem(); /// }; /// template <typename T> /// void x() { /// S<T> s; /// s.mem(); /// } /// \endcode /// The matcher /// @code /// \c cxxDependentScopeMemberExpr( /// hasObjectExpression(declRefExpr(hasType(templateSpecializationType( /// hasDeclaration(classTemplateDecl(has(cxxRecordDecl(has( /// cxxMethodDecl(hasName("mem")).bind("templMem") /// ))))) /// )))), /// memberHasSameNameAsBoundNode("templMem") /// ) /// @endcode /// first matches and binds the @c mem member of the @c S template, then /// compares its name to the usage in @c s.mem() in the @c x function template AST_MATCHER_P(CXXDependentScopeMemberExpr, memberHasSameNameAsBoundNode, std::string, BindingID) { auto MemberName = Node.getMember().getAsString(); return Builder->removeBindings( [this, MemberName](const BoundNodesMap &Nodes) { const auto &BN = Nodes.getNode(this->BindingID); if (const auto *ND = BN.get<NamedDecl>()) { if (!isa<FieldDecl, CXXMethodDecl, VarDecl>(ND)) return true; return ND->getName() != MemberName; } return true; }); } /// Matches C++ classes that are directly or indirectly derived from a class /// matching \c Base, or Objective-C classes that directly or indirectly /// subclass a class matching \c Base. /// /// Note that a class is not considered to be derived from itself. /// /// Example matches Y, Z, C (Base == hasName("X")) /// \code /// class X; /// class Y : public X {}; // directly derived /// class Z : public Y {}; // indirectly derived /// typedef X A; /// typedef A B; /// class C : public B {}; // derived from a typedef of X /// \endcode /// /// In the following example, Bar matches isDerivedFrom(hasName("X")): /// \code /// class Foo; /// typedef Foo X; /// class Bar : public Foo {}; // derived from a type that X is a typedef of /// \endcode /// /// In the following example, Bar matches isDerivedFrom(hasName("NSObject")) /// \code /// @interface NSObject @end /// @interface Bar : NSObject @end /// \endcode /// /// Usable as: Matcher<CXXRecordDecl>, Matcher<ObjCInterfaceDecl> AST_POLYMORPHIC_MATCHER_P( isDerivedFrom, AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl), internal::Matcher<NamedDecl>, Base) { // Check if the node is a C++ struct/union/class. if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node)) return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/false); // The node must be an Objective-C class. const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node); return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder, /*Directly=*/false); } /// Overloaded method as shortcut for \c isDerivedFrom(hasName(...)). AST_POLYMORPHIC_MATCHER_P_OVERLOAD( isDerivedFrom, AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl), std::string, BaseName, 1) { if (BaseName.empty()) return false; const auto M = isDerivedFrom(hasName(BaseName)); if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node)) return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder); const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node); return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder); } /// Matches C++ classes that have a direct or indirect base matching \p /// BaseSpecMatcher. /// /// Example: /// matcher hasAnyBase(hasType(cxxRecordDecl(hasName("SpecialBase")))) /// \code /// class Foo; /// class Bar : Foo {}; /// class Baz : Bar {}; /// class SpecialBase; /// class Proxy : SpecialBase {}; // matches Proxy /// class IndirectlyDerived : Proxy {}; //matches IndirectlyDerived /// \endcode /// // FIXME: Refactor this and isDerivedFrom to reuse implementation. AST_MATCHER_P(CXXRecordDecl, hasAnyBase, internal::Matcher<CXXBaseSpecifier>, BaseSpecMatcher) { return internal::matchesAnyBase(Node, BaseSpecMatcher, Finder, Builder); } /// Matches C++ classes that have a direct base matching \p BaseSpecMatcher. /// /// Example: /// matcher hasDirectBase(hasType(cxxRecordDecl(hasName("SpecialBase")))) /// \code /// class Foo; /// class Bar : Foo {}; /// class Baz : Bar {}; /// class SpecialBase; /// class Proxy : SpecialBase {}; // matches Proxy /// class IndirectlyDerived : Proxy {}; // doesn't match /// \endcode AST_MATCHER_P(CXXRecordDecl, hasDirectBase, internal::Matcher<CXXBaseSpecifier>, BaseSpecMatcher) { return Node.hasDefinition() && llvm::any_of(Node.bases(), [&](const CXXBaseSpecifier &Base) { return BaseSpecMatcher.matches(Base, Finder, Builder); }); } /// Similar to \c isDerivedFrom(), but also matches classes that directly /// match \c Base. AST_POLYMORPHIC_MATCHER_P_OVERLOAD( isSameOrDerivedFrom, AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl), internal::Matcher<NamedDecl>, Base, 0) { const auto M = anyOf(Base, isDerivedFrom(Base)); if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node)) return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder); const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node); return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder); } /// Overloaded method as shortcut for /// \c isSameOrDerivedFrom(hasName(...)). AST_POLYMORPHIC_MATCHER_P_OVERLOAD( isSameOrDerivedFrom, AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl), std::string, BaseName, 1) { if (BaseName.empty()) return false; const auto M = isSameOrDerivedFrom(hasName(BaseName)); if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node)) return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder); const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node); return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder); } /// Matches C++ or Objective-C classes that are directly derived from a class /// matching \c Base. /// /// Note that a class is not considered to be derived from itself. /// /// Example matches Y, C (Base == hasName("X")) /// \code /// class X; /// class Y : public X {}; // directly derived /// class Z : public Y {}; // indirectly derived /// typedef X A; /// typedef A B; /// class C : public B {}; // derived from a typedef of X /// \endcode /// /// In the following example, Bar matches isDerivedFrom(hasName("X")): /// \code /// class Foo; /// typedef Foo X; /// class Bar : public Foo {}; // derived from a type that X is a typedef of /// \endcode AST_POLYMORPHIC_MATCHER_P_OVERLOAD( isDirectlyDerivedFrom, AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl), internal::Matcher<NamedDecl>, Base, 0) { // Check if the node is a C++ struct/union/class. if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node)) return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/true); // The node must be an Objective-C class. const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node); return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder, /*Directly=*/true); } /// Overloaded method as shortcut for \c isDirectlyDerivedFrom(hasName(...)). AST_POLYMORPHIC_MATCHER_P_OVERLOAD( isDirectlyDerivedFrom, AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl), std::string, BaseName, 1) { if (BaseName.empty()) return false; const auto M = isDirectlyDerivedFrom(hasName(BaseName)); if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node)) return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder); const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node); return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder); } /// Matches the first method of a class or struct that satisfies \c /// InnerMatcher. /// /// Given: /// \code /// class A { void func(); }; /// class B { void member(); }; /// \endcode /// /// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of /// \c A but not \c B. AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>, InnerMatcher) { BoundNodesTreeBuilder Result(*Builder); auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.method_begin(), Node.method_end(), Finder, &Result); if (MatchIt == Node.method_end()) return false; if (Finder->isTraversalIgnoringImplicitNodes() && (*MatchIt)->isImplicit()) return false; *Builder = std::move(Result); return true; } /// Matches the generated class of lambda expressions. /// /// Given: /// \code /// auto x = []{}; /// \endcode /// /// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of /// \c decltype(x) AST_MATCHER(CXXRecordDecl, isLambda) { return Node.isLambda(); } /// Matches AST nodes that have child AST nodes that match the /// provided matcher. /// /// Example matches X, Y /// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X"))) /// \code /// class X {}; // Matches X, because X::X is a class of name X inside X. /// class Y { class X {}; }; /// class Z { class Y { class X {}; }; }; // Does not match Z. /// \endcode /// /// ChildT must be an AST base type. /// /// Usable as: Any Matcher /// Note that has is direct matcher, so it also matches things like implicit /// casts and paren casts. If you are matching with expr then you should /// probably consider using ignoringParenImpCasts like: /// has(ignoringParenImpCasts(expr())). extern const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> has; /// Matches AST nodes that have descendant AST nodes that match the /// provided matcher. /// /// Example matches X, Y, Z /// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X"))))) /// \code /// class X {}; // Matches X, because X::X is a class of name X inside X. /// class Y { class X {}; }; /// class Z { class Y { class X {}; }; }; /// \endcode /// /// DescendantT must be an AST base type. /// /// Usable as: Any Matcher extern const internal::ArgumentAdaptingMatcherFunc< internal::HasDescendantMatcher> hasDescendant; /// Matches AST nodes that have child AST nodes that match the /// provided matcher. /// /// Example matches X, Y, Y::X, Z::Y, Z::Y::X /// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X"))) /// \code /// class X {}; /// class Y { class X {}; }; // Matches Y, because Y::X is a class of name X /// // inside Y. /// class Z { class Y { class X {}; }; }; // Does not match Z. /// \endcode /// /// ChildT must be an AST base type. /// /// As opposed to 'has', 'forEach' will cause a match for each result that /// matches instead of only on the first one. /// /// Usable as: Any Matcher extern const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher> forEach; /// Matches AST nodes that have descendant AST nodes that match the /// provided matcher. /// /// Example matches X, A, A::X, B, B::C, B::C::X /// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X"))))) /// \code /// class X {}; /// class A { class X {}; }; // Matches A, because A::X is a class of name /// // X inside A. /// class B { class C { class X {}; }; }; /// \endcode /// /// DescendantT must be an AST base type. /// /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for /// each result that matches instead of only on the first one. /// /// Note: Recursively combined ForEachDescendant can cause many matches: /// cxxRecordDecl(forEachDescendant(cxxRecordDecl( /// forEachDescendant(cxxRecordDecl()) /// ))) /// will match 10 times (plus injected class name matches) on: /// \code /// class A { class B { class C { class D { class E {}; }; }; }; }; /// \endcode /// /// Usable as: Any Matcher extern const internal::ArgumentAdaptingMatcherFunc< internal::ForEachDescendantMatcher> forEachDescendant; /// Matches if the node or any descendant matches. /// /// Generates results for each match. /// /// For example, in: /// \code /// class A { class B {}; class C {}; }; /// \endcode /// The matcher: /// \code /// cxxRecordDecl(hasName("::A"), /// findAll(cxxRecordDecl(isDefinition()).bind("m"))) /// \endcode /// will generate results for \c A, \c B and \c C. /// /// Usable as: Any Matcher template <typename T> internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) { return eachOf(Matcher, forEachDescendant(Matcher)); } /// Matches AST nodes that have a parent that matches the provided /// matcher. /// /// Given /// \code /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } } /// \endcode /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }". /// /// Usable as: Any Matcher extern const internal::ArgumentAdaptingMatcherFunc< internal::HasParentMatcher, internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>, internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>> hasParent; /// Matches AST nodes that have an ancestor that matches the provided /// matcher. /// /// Given /// \code /// void f() { if (true) { int x = 42; } } /// void g() { for (;;) { int x = 43; } } /// \endcode /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43. /// /// Usable as: Any Matcher extern const internal::ArgumentAdaptingMatcherFunc< internal::HasAncestorMatcher, internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>, internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>> hasAncestor; /// Matches if the provided matcher does not match. /// /// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X")))) /// \code /// class X {}; /// class Y {}; /// \endcode /// /// Usable as: Any Matcher extern const internal::VariadicOperatorMatcherFunc<1, 1> unless; /// Matches a node if the declaration associated with that node /// matches the given matcher. /// /// The associated declaration is: /// - for type nodes, the declaration of the underlying type /// - for CallExpr, the declaration of the callee /// - for MemberExpr, the declaration of the referenced member /// - for CXXConstructExpr, the declaration of the constructor /// - for CXXNewExpr, the declaration of the operator new /// - for ObjCIvarExpr, the declaration of the ivar /// /// For type nodes, hasDeclaration will generally match the declaration of the /// sugared type. Given /// \code /// class X {}; /// typedef X Y; /// Y y; /// \endcode /// in varDecl(hasType(hasDeclaration(decl()))) the decl will match the /// typedefDecl. A common use case is to match the underlying, desugared type. /// This can be achieved by using the hasUnqualifiedDesugaredType matcher: /// \code /// varDecl(hasType(hasUnqualifiedDesugaredType( /// recordType(hasDeclaration(decl()))))) /// \endcode /// In this matcher, the decl will match the CXXRecordDecl of class X. /// /// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>, /// Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>, /// Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>, /// Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>, /// Matcher<TagType>, Matcher<TemplateSpecializationType>, /// Matcher<TemplateTypeParmType>, Matcher<TypedefType>, /// Matcher<UnresolvedUsingType> inline internal::PolymorphicMatcher< internal::HasDeclarationMatcher, void(internal::HasDeclarationSupportedTypes), internal::Matcher<Decl>> hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) { return internal::PolymorphicMatcher< internal::HasDeclarationMatcher, void(internal::HasDeclarationSupportedTypes), internal::Matcher<Decl>>( InnerMatcher); } /// Matches a \c NamedDecl whose underlying declaration matches the given /// matcher. /// /// Given /// \code /// namespace N { template<class T> void f(T t); } /// template <class T> void g() { using N::f; f(T()); } /// \endcode /// \c unresolvedLookupExpr(hasAnyDeclaration( /// namedDecl(hasUnderlyingDecl(hasName("::N::f"))))) /// matches the use of \c f in \c g() . AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>, InnerMatcher) { const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl(); return UnderlyingDecl != nullptr && InnerMatcher.matches(*UnderlyingDecl, Finder, Builder); } /// Matches on the implicit object argument of a member call expression, after /// stripping off any parentheses or implicit casts. /// /// Given /// \code /// class Y { public: void m(); }; /// Y g(); /// class X : public Y {}; /// void z(Y y, X x) { y.m(); (g()).m(); x.m(); } /// \endcode /// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y"))))) /// matches `y.m()` and `(g()).m()`. /// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("X"))))) /// matches `x.m()`. /// cxxMemberCallExpr(on(callExpr())) /// matches `(g()).m()`. /// /// FIXME: Overload to allow directly matching types? AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>, InnerMatcher) { const Expr *ExprNode = Node.getImplicitObjectArgument() ->IgnoreParenImpCasts(); return (ExprNode != nullptr && InnerMatcher.matches(*ExprNode, Finder, Builder)); } /// Matches on the receiver of an ObjectiveC Message expression. /// /// Example /// matcher = objCMessageExpr(hasReceiverType(asString("UIWebView *"))); /// matches the [webView ...] message invocation. /// \code /// NSString *webViewJavaScript = ... /// UIWebView *webView = ... /// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript]; /// \endcode AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>, InnerMatcher) { const QualType TypeDecl = Node.getReceiverType(); return InnerMatcher.matches(TypeDecl, Finder, Builder); } /// Returns true when the Objective-C method declaration is a class method. /// /// Example /// matcher = objcMethodDecl(isClassMethod()) /// matches /// \code /// @interface I + (void)foo; @end /// \endcode /// but not /// \code /// @interface I - (void)bar; @end /// \endcode AST_MATCHER(ObjCMethodDecl, isClassMethod) { return Node.isClassMethod(); } /// Returns true when the Objective-C method declaration is an instance method. /// /// Example /// matcher = objcMethodDecl(isInstanceMethod()) /// matches /// \code /// @interface I - (void)bar; @end /// \endcode /// but not /// \code /// @interface I + (void)foo; @end /// \endcode AST_MATCHER(ObjCMethodDecl, isInstanceMethod) { return Node.isInstanceMethod(); } /// Returns true when the Objective-C message is sent to a class. /// /// Example /// matcher = objcMessageExpr(isClassMessage()) /// matches /// \code /// [NSString stringWithFormat:@"format"]; /// \endcode /// but not /// \code /// NSString *x = @"hello"; /// [x containsString:@"h"]; /// \endcode AST_MATCHER(ObjCMessageExpr, isClassMessage) { return Node.isClassMessage(); } /// Returns true when the Objective-C message is sent to an instance. /// /// Example /// matcher = objcMessageExpr(isInstanceMessage()) /// matches /// \code /// NSString *x = @"hello"; /// [x containsString:@"h"]; /// \endcode /// but not /// \code /// [NSString stringWithFormat:@"format"]; /// \endcode AST_MATCHER(ObjCMessageExpr, isInstanceMessage) { return Node.isInstanceMessage(); } /// Matches if the Objective-C message is sent to an instance, /// and the inner matcher matches on that instance. /// /// For example the method call in /// \code /// NSString *x = @"hello"; /// [x containsString:@"h"]; /// \endcode /// is matched by /// objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x")))))) AST_MATCHER_P(ObjCMessageExpr, hasReceiver, internal::Matcher<Expr>, InnerMatcher) { const Expr *ReceiverNode = Node.getInstanceReceiver(); return (ReceiverNode != nullptr && InnerMatcher.matches(*ReceiverNode->IgnoreParenImpCasts(), Finder, Builder)); } /// Matches when BaseName == Selector.getAsString() /// /// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:")); /// matches the outer message expr in the code below, but NOT the message /// invocation for self.bodyView. /// \code /// [self.bodyView loadHTMLString:html baseURL:NULL]; /// \endcode AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) { Selector Sel = Node.getSelector(); return BaseName.compare(Sel.getAsString()) == 0; } /// Matches when at least one of the supplied string equals to the /// Selector.getAsString() /// /// matcher = objCMessageExpr(hasSelector("methodA:", "methodB:")); /// matches both of the expressions below: /// \code /// [myObj methodA:argA]; /// [myObj methodB:argB]; /// \endcode extern const internal::VariadicFunction<internal::Matcher<ObjCMessageExpr>, StringRef, internal::hasAnySelectorFunc> hasAnySelector; /// Matches ObjC selectors whose name contains /// a substring matched by the given RegExp. /// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?")); /// matches the outer message expr in the code below, but NOT the message /// invocation for self.bodyView. /// \code /// [self.bodyView loadHTMLString:html baseURL:NULL]; /// \endcode AST_MATCHER_REGEX(ObjCMessageExpr, matchesSelector, RegExp) { std::string SelectorString = Node.getSelector().getAsString(); return RegExp->match(SelectorString); } /// Matches when the selector is the empty selector /// /// Matches only when the selector of the objCMessageExpr is NULL. This may /// represent an error condition in the tree! AST_MATCHER(ObjCMessageExpr, hasNullSelector) { return Node.getSelector().isNull(); } /// Matches when the selector is a Unary Selector /// /// matcher = objCMessageExpr(matchesSelector(hasUnarySelector()); /// matches self.bodyView in the code below, but NOT the outer message /// invocation of "loadHTMLString:baseURL:". /// \code /// [self.bodyView loadHTMLString:html baseURL:NULL]; /// \endcode AST_MATCHER(ObjCMessageExpr, hasUnarySelector) { return Node.getSelector().isUnarySelector(); } /// Matches when the selector is a keyword selector /// /// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame /// message expression in /// /// \code /// UIWebView *webView = ...; /// CGRect bodyFrame = webView.frame; /// bodyFrame.size.height = self.bodyContentHeight; /// webView.frame = bodyFrame; /// // ^---- matches here /// \endcode AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) { return Node.getSelector().isKeywordSelector(); } /// Matches when the selector has the specified number of arguments /// /// matcher = objCMessageExpr(numSelectorArgs(0)); /// matches self.bodyView in the code below /// /// matcher = objCMessageExpr(numSelectorArgs(2)); /// matches the invocation of "loadHTMLString:baseURL:" but not that /// of self.bodyView /// \code /// [self.bodyView loadHTMLString:html baseURL:NULL]; /// \endcode AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) { return Node.getSelector().getNumArgs() == N; } /// Matches if the call expression's callee expression matches. /// /// Given /// \code /// class Y { void x() { this->x(); x(); Y y; y.x(); } }; /// void f() { f(); } /// \endcode /// callExpr(callee(expr())) /// matches this->x(), x(), y.x(), f() /// with callee(...) /// matching this->x, x, y.x, f respectively /// /// Note: Callee cannot take the more general internal::Matcher<Expr> /// because this introduces ambiguous overloads with calls to Callee taking a /// internal::Matcher<Decl>, as the matcher hierarchy is purely /// implemented in terms of implicit casts. AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>, InnerMatcher) { const Expr *ExprNode = Node.getCallee(); return (ExprNode != nullptr && InnerMatcher.matches(*ExprNode, Finder, Builder)); } /// Matches if the call expression's callee's declaration matches the /// given matcher. /// /// Example matches y.x() (matcher = callExpr(callee( /// cxxMethodDecl(hasName("x"))))) /// \code /// class Y { public: void x(); }; /// void z() { Y y; y.x(); } /// \endcode AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher, 1) { return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder); } /// Matches if the expression's or declaration's type matches a type /// matcher. /// /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X"))))) /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X"))))) /// and U (matcher = typedefDecl(hasType(asString("int"))) /// and friend class X (matcher = friendDecl(hasType("X")) /// and public virtual X (matcher = cxxBaseSpecifier(hasType( /// asString("class X"))) /// \code /// class X {}; /// void y(X &x) { x; X z; } /// typedef int U; /// class Y { friend class X; }; /// class Z : public virtual X {}; /// \endcode AST_POLYMORPHIC_MATCHER_P_OVERLOAD( hasType, AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, TypedefNameDecl, ValueDecl, CXXBaseSpecifier), internal::Matcher<QualType>, InnerMatcher, 0) { QualType QT = internal::getUnderlyingType(Node); if (!QT.isNull()) return InnerMatcher.matches(QT, Finder, Builder); return false; } /// Overloaded to match the declaration of the expression's or value /// declaration's type. /// /// In case of a value declaration (for example a variable declaration), /// this resolves one layer of indirection. For example, in the value /// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of /// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the /// declaration of x. /// /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X"))))) /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X"))))) /// and friend class X (matcher = friendDecl(hasType("X")) /// and public virtual X (matcher = cxxBaseSpecifier(hasType( /// cxxRecordDecl(hasName("X")))) /// \code /// class X {}; /// void y(X &x) { x; X z; } /// class Y { friend class X; }; /// class Z : public virtual X {}; /// \endcode /// /// Example matches class Derived /// (matcher = cxxRecordDecl(hasAnyBase(hasType(cxxRecordDecl(hasName("Base")))))) /// \code /// class Base {}; /// class Derived : Base {}; /// \endcode /// /// Usable as: Matcher<Expr>, Matcher<FriendDecl>, Matcher<ValueDecl>, /// Matcher<CXXBaseSpecifier> AST_POLYMORPHIC_MATCHER_P_OVERLOAD( hasType, AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, ValueDecl, CXXBaseSpecifier), internal::Matcher<Decl>, InnerMatcher, 1) { QualType QT = internal::getUnderlyingType(Node); if (!QT.isNull()) return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder); return false; } /// Matches if the type location of a node matches the inner matcher. /// /// Examples: /// \code /// int x; /// \endcode /// declaratorDecl(hasTypeLoc(loc(asString("int")))) /// matches int x /// /// \code /// auto x = int(3); /// \code /// cxxTemporaryObjectExpr(hasTypeLoc(loc(asString("int")))) /// matches int(3) /// /// \code /// struct Foo { Foo(int, int); }; /// auto x = Foo(1, 2); /// \code /// cxxFunctionalCastExpr(hasTypeLoc(loc(asString("struct Foo")))) /// matches Foo(1, 2) /// /// Usable as: Matcher<BlockDecl>, Matcher<CXXBaseSpecifier>, /// Matcher<CXXCtorInitializer>, Matcher<CXXFunctionalCastExpr>, /// Matcher<CXXNewExpr>, Matcher<CXXTemporaryObjectExpr>, /// Matcher<CXXUnresolvedConstructExpr>, /// Matcher<ClassTemplateSpecializationDecl>, Matcher<CompoundLiteralExpr>, /// Matcher<DeclaratorDecl>, Matcher<ExplicitCastExpr>, /// Matcher<ObjCPropertyDecl>, Matcher<TemplateArgumentLoc>, /// Matcher<TypedefNameDecl> AST_POLYMORPHIC_MATCHER_P( hasTypeLoc, AST_POLYMORPHIC_SUPPORTED_TYPES( BlockDecl, CXXBaseSpecifier, CXXCtorInitializer, CXXFunctionalCastExpr, CXXNewExpr, CXXTemporaryObjectExpr, CXXUnresolvedConstructExpr, ClassTemplateSpecializationDecl, CompoundLiteralExpr, DeclaratorDecl, ExplicitCastExpr, ObjCPropertyDecl, TemplateArgumentLoc, TypedefNameDecl), internal::Matcher<TypeLoc>, Inner) { TypeSourceInfo *source = internal::GetTypeSourceInfo(Node); if (source == nullptr) { // This happens for example for implicit destructors. return false; } return Inner.matches(source->getTypeLoc(), Finder, Builder); } /// Matches if the matched type is represented by the given string. /// /// Given /// \code /// class Y { public: void x(); }; /// void z() { Y* y; y->x(); } /// \endcode /// cxxMemberCallExpr(on(hasType(asString("class Y *")))) /// matches y->x() AST_MATCHER_P(QualType, asString, std::string, Name) { return Name == Node.getAsString(); } /// Matches if the matched type is a pointer type and the pointee type /// matches the specified matcher. /// /// Example matches y->x() /// (matcher = cxxMemberCallExpr(on(hasType(pointsTo /// cxxRecordDecl(hasName("Y"))))))) /// \code /// class Y { public: void x(); }; /// void z() { Y *y; y->x(); } /// \endcode AST_MATCHER_P( QualType, pointsTo, internal::Matcher<QualType>, InnerMatcher) { return (!Node.isNull() && Node->isAnyPointerType() && InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); } /// Overloaded to match the pointee type's declaration. AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>, InnerMatcher, 1) { return pointsTo(qualType(hasDeclaration(InnerMatcher))) .matches(Node, Finder, Builder); } /// Matches if the matched type matches the unqualified desugared /// type of the matched node. /// /// For example, in: /// \code /// class A {}; /// using B = A; /// \endcode /// The matcher type(hasUnqualifiedDesugaredType(recordType())) matches /// both B and A. AST_MATCHER_P(Type, hasUnqualifiedDesugaredType, internal::Matcher<Type>, InnerMatcher) { return InnerMatcher.matches(*Node.getUnqualifiedDesugaredType(), Finder, Builder); } /// Matches if the matched type is a reference type and the referenced /// type matches the specified matcher. /// /// Example matches X &x and const X &y /// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X")))))) /// \code /// class X { /// void a(X b) { /// X &x = b; /// const X &y = b; /// } /// }; /// \endcode AST_MATCHER_P(QualType, references, internal::Matcher<QualType>, InnerMatcher) { return (!Node.isNull() && Node->isReferenceType() && InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); } /// Matches QualTypes whose canonical type matches InnerMatcher. /// /// Given: /// \code /// typedef int &int_ref; /// int a; /// int_ref b = a; /// \endcode /// /// \c varDecl(hasType(qualType(referenceType()))))) will not match the /// declaration of b but \c /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does. AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>, InnerMatcher) { if (Node.isNull()) return false; return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder); } /// Overloaded to match the referenced type's declaration. AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>, InnerMatcher, 1) { return references(qualType(hasDeclaration(InnerMatcher))) .matches(Node, Finder, Builder); } /// Matches on the implicit object argument of a member call expression. Unlike /// `on`, matches the argument directly without stripping away anything. /// /// Given /// \code /// class Y { public: void m(); }; /// Y g(); /// class X : public Y { void g(); }; /// void z(Y y, X x) { y.m(); x.m(); x.g(); (g()).m(); } /// \endcode /// cxxMemberCallExpr(onImplicitObjectArgument(hasType( /// cxxRecordDecl(hasName("Y"))))) /// matches `y.m()`, `x.m()` and (g()).m(), but not `x.g()`. /// cxxMemberCallExpr(on(callExpr())) /// does not match `(g()).m()`, because the parens are not ignored. /// /// FIXME: Overload to allow directly matching types? AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument, internal::Matcher<Expr>, InnerMatcher) { const Expr *ExprNode = Node.getImplicitObjectArgument(); return (ExprNode != nullptr && InnerMatcher.matches(*ExprNode, Finder, Builder)); } /// Matches if the type of the expression's implicit object argument either /// matches the InnerMatcher, or is a pointer to a type that matches the /// InnerMatcher. /// /// Given /// \code /// class Y { public: void m(); }; /// class X : public Y { void g(); }; /// void z() { Y y; y.m(); Y *p; p->m(); X x; x.m(); x.g(); } /// \endcode /// cxxMemberCallExpr(thisPointerType(hasDeclaration( /// cxxRecordDecl(hasName("Y"))))) /// matches `y.m()`, `p->m()` and `x.m()`. /// cxxMemberCallExpr(thisPointerType(hasDeclaration( /// cxxRecordDecl(hasName("X"))))) /// matches `x.g()`. AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType, internal::Matcher<QualType>, InnerMatcher, 0) { return onImplicitObjectArgument( anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))) .matches(Node, Finder, Builder); } /// Overloaded to match the type's declaration. AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType, internal::Matcher<Decl>, InnerMatcher, 1) { return onImplicitObjectArgument( anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))) .matches(Node, Finder, Builder); } /// Matches a DeclRefExpr that refers to a declaration that matches the /// specified matcher. /// /// Example matches x in if(x) /// (matcher = declRefExpr(to(varDecl(hasName("x"))))) /// \code /// bool x; /// if (x) {} /// \endcode AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>, InnerMatcher) { const Decl *DeclNode = Node.getDecl(); return (DeclNode != nullptr && InnerMatcher.matches(*DeclNode, Finder, Builder)); } /// Matches a \c DeclRefExpr that refers to a declaration through a /// specific using shadow declaration. /// /// Given /// \code /// namespace a { void f() {} } /// using a::f; /// void g() { /// f(); // Matches this .. /// a::f(); // .. but not this. /// } /// \endcode /// declRefExpr(throughUsingDecl(anything())) /// matches \c f() AST_MATCHER_P(DeclRefExpr, throughUsingDecl, internal::Matcher<UsingShadowDecl>, InnerMatcher) { const NamedDecl *FoundDecl = Node.getFoundDecl(); if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl)) return InnerMatcher.matches(*UsingDecl, Finder, Builder); return false; } /// Matches an \c OverloadExpr if any of the declarations in the set of /// overloads matches the given matcher. /// /// Given /// \code /// template <typename T> void foo(T); /// template <typename T> void bar(T); /// template <typename T> void baz(T t) { /// foo(t); /// bar(t); /// } /// \endcode /// unresolvedLookupExpr(hasAnyDeclaration( /// functionTemplateDecl(hasName("foo")))) /// matches \c foo in \c foo(t); but not \c bar in \c bar(t); AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>, InnerMatcher) { return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(), Node.decls_end(), Finder, Builder) != Node.decls_end(); } /// Matches the Decl of a DeclStmt which has a single declaration. /// /// Given /// \code /// int a, b; /// int c; /// \endcode /// declStmt(hasSingleDecl(anything())) /// matches 'int c;' but not 'int a, b;'. AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) { if (Node.isSingleDecl()) { const Decl *FoundDecl = Node.getSingleDecl(); return InnerMatcher.matches(*FoundDecl, Finder, Builder); } return false; } /// Matches a variable declaration that has an initializer expression /// that matches the given matcher. /// /// Example matches x (matcher = varDecl(hasInitializer(callExpr()))) /// \code /// bool y() { return true; } /// bool x = y(); /// \endcode AST_MATCHER_P( VarDecl, hasInitializer, internal::Matcher<Expr>, InnerMatcher) { const Expr *Initializer = Node.getAnyInitializer(); return (Initializer != nullptr && InnerMatcher.matches(*Initializer, Finder, Builder)); } /// \brief Matches a static variable with local scope. /// /// Example matches y (matcher = varDecl(isStaticLocal())) /// \code /// void f() { /// int x; /// static int y; /// } /// static int z; /// \endcode AST_MATCHER(VarDecl, isStaticLocal) { return Node.isStaticLocal(); } /// Matches a variable declaration that has function scope and is a /// non-static local variable. /// /// Example matches x (matcher = varDecl(hasLocalStorage()) /// \code /// void f() { /// int x; /// static int y; /// } /// int z; /// \endcode AST_MATCHER(VarDecl, hasLocalStorage) { return Node.hasLocalStorage(); } /// Matches a variable declaration that does not have local storage. /// /// Example matches y and z (matcher = varDecl(hasGlobalStorage()) /// \code /// void f() { /// int x; /// static int y; /// } /// int z; /// \endcode AST_MATCHER(VarDecl, hasGlobalStorage) { return Node.hasGlobalStorage(); } /// Matches a variable declaration that has automatic storage duration. /// /// Example matches x, but not y, z, or a. /// (matcher = varDecl(hasAutomaticStorageDuration()) /// \code /// void f() { /// int x; /// static int y; /// thread_local int z; /// } /// int a; /// \endcode AST_MATCHER(VarDecl, hasAutomaticStorageDuration) { return Node.getStorageDuration() == SD_Automatic; } /// Matches a variable declaration that has static storage duration. /// It includes the variable declared at namespace scope and those declared /// with "static" and "extern" storage class specifiers. /// /// \code /// void f() { /// int x; /// static int y; /// thread_local int z; /// } /// int a; /// static int b; /// extern int c; /// varDecl(hasStaticStorageDuration()) /// matches the function declaration y, a, b and c. /// \endcode AST_MATCHER(VarDecl, hasStaticStorageDuration) { return Node.getStorageDuration() == SD_Static; } /// Matches a variable declaration that has thread storage duration. /// /// Example matches z, but not x, z, or a. /// (matcher = varDecl(hasThreadStorageDuration()) /// \code /// void f() { /// int x; /// static int y; /// thread_local int z; /// } /// int a; /// \endcode AST_MATCHER(VarDecl, hasThreadStorageDuration) { return Node.getStorageDuration() == SD_Thread; } /// Matches a variable declaration that is an exception variable from /// a C++ catch block, or an Objective-C \@catch statement. /// /// Example matches x (matcher = varDecl(isExceptionVariable()) /// \code /// void f(int y) { /// try { /// } catch (int x) { /// } /// } /// \endcode AST_MATCHER(VarDecl, isExceptionVariable) { return Node.isExceptionVariable(); } /// Checks that a call expression or a constructor call expression has /// a specific number of arguments (including absent default arguments). /// /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2))) /// \code /// void f(int x, int y); /// f(0, 0); /// \endcode AST_POLYMORPHIC_MATCHER_P(argumentCountIs, AST_POLYMORPHIC_SUPPORTED_TYPES( CallExpr, CXXConstructExpr, CXXUnresolvedConstructExpr, ObjCMessageExpr), unsigned, N) { unsigned NumArgs = Node.getNumArgs(); if (!Finder->isTraversalIgnoringImplicitNodes()) return NumArgs == N; while (NumArgs) { if (!isa<CXXDefaultArgExpr>(Node.getArg(NumArgs - 1))) break; --NumArgs; } return NumArgs == N; } /// Matches the n'th argument of a call expression or a constructor /// call expression. /// /// Example matches y in x(y) /// (matcher = callExpr(hasArgument(0, declRefExpr()))) /// \code /// void x(int) { int y; x(y); } /// \endcode AST_POLYMORPHIC_MATCHER_P2(hasArgument, AST_POLYMORPHIC_SUPPORTED_TYPES( CallExpr, CXXConstructExpr, CXXUnresolvedConstructExpr, ObjCMessageExpr), unsigned, N, internal::Matcher<Expr>, InnerMatcher) { if (N >= Node.getNumArgs()) return false; const Expr *Arg = Node.getArg(N); if (Finder->isTraversalIgnoringImplicitNodes() && isa<CXXDefaultArgExpr>(Arg)) return false; return InnerMatcher.matches(*Arg->IgnoreParenImpCasts(), Finder, Builder); } /// Matches the n'th item of an initializer list expression. /// /// Example matches y. /// (matcher = initListExpr(hasInit(0, expr()))) /// \code /// int x{y}. /// \endcode AST_MATCHER_P2(InitListExpr, hasInit, unsigned, N, ast_matchers::internal::Matcher<Expr>, InnerMatcher) { return N < Node.getNumInits() && InnerMatcher.matches(*Node.getInit(N), Finder, Builder); } /// Matches declaration statements that contain a specific number of /// declarations. /// /// Example: Given /// \code /// int a, b; /// int c; /// int d = 2, e; /// \endcode /// declCountIs(2) /// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'. AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) { return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N; } /// Matches the n'th declaration of a declaration statement. /// /// Note that this does not work for global declarations because the AST /// breaks up multiple-declaration DeclStmt's into multiple single-declaration /// DeclStmt's. /// Example: Given non-global declarations /// \code /// int a, b = 0; /// int c; /// int d = 2, e; /// \endcode /// declStmt(containsDeclaration( /// 0, varDecl(hasInitializer(anything())))) /// matches only 'int d = 2, e;', and /// declStmt(containsDeclaration(1, varDecl())) /// \code /// matches 'int a, b = 0' as well as 'int d = 2, e;' /// but 'int c;' is not matched. /// \endcode AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N, internal::Matcher<Decl>, InnerMatcher) { const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end()); if (N >= NumDecls) return false; DeclStmt::const_decl_iterator Iterator = Node.decl_begin(); std::advance(Iterator, N); return InnerMatcher.matches(**Iterator, Finder, Builder); } /// Matches a C++ catch statement that has a catch-all handler. /// /// Given /// \code /// try { /// // ... /// } catch (int) { /// // ... /// } catch (...) { /// // ... /// } /// \endcode /// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int). AST_MATCHER(CXXCatchStmt, isCatchAll) { return Node.getExceptionDecl() == nullptr; } /// Matches a constructor initializer. /// /// Given /// \code /// struct Foo { /// Foo() : foo_(1) { } /// int foo_; /// }; /// \endcode /// cxxRecordDecl(has(cxxConstructorDecl( /// hasAnyConstructorInitializer(anything()) /// ))) /// record matches Foo, hasAnyConstructorInitializer matches foo_(1) AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer, internal::Matcher<CXXCtorInitializer>, InnerMatcher) { auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.init_begin(), Node.init_end(), Finder, Builder); if (MatchIt == Node.init_end()) return false; return (*MatchIt)->isWritten() || !Finder->isTraversalIgnoringImplicitNodes(); } /// Matches the field declaration of a constructor initializer. /// /// Given /// \code /// struct Foo { /// Foo() : foo_(1) { } /// int foo_; /// }; /// \endcode /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer( /// forField(hasName("foo_")))))) /// matches Foo /// with forField matching foo_ AST_MATCHER_P(CXXCtorInitializer, forField, internal::Matcher<FieldDecl>, InnerMatcher) { const FieldDecl *NodeAsDecl = Node.getAnyMember(); return (NodeAsDecl != nullptr && InnerMatcher.matches(*NodeAsDecl, Finder, Builder)); } /// Matches the initializer expression of a constructor initializer. /// /// Given /// \code /// struct Foo { /// Foo() : foo_(1) { } /// int foo_; /// }; /// \endcode /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer( /// withInitializer(integerLiteral(equals(1))))))) /// matches Foo /// with withInitializer matching (1) AST_MATCHER_P(CXXCtorInitializer, withInitializer, internal::Matcher<Expr>, InnerMatcher) { const Expr* NodeAsExpr = Node.getInit(); return (NodeAsExpr != nullptr && InnerMatcher.matches(*NodeAsExpr, Finder, Builder)); } /// Matches a constructor initializer if it is explicitly written in /// code (as opposed to implicitly added by the compiler). /// /// Given /// \code /// struct Foo { /// Foo() { } /// Foo(int) : foo_("A") { } /// string foo_; /// }; /// \endcode /// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten())) /// will match Foo(int), but not Foo() AST_MATCHER(CXXCtorInitializer, isWritten) { return Node.isWritten(); } /// Matches a constructor initializer if it is initializing a base, as /// opposed to a member. /// /// Given /// \code /// struct B {}; /// struct D : B { /// int I; /// D(int i) : I(i) {} /// }; /// struct E : B { /// E() : B() {} /// }; /// \endcode /// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer())) /// will match E(), but not match D(int). AST_MATCHER(CXXCtorInitializer, isBaseInitializer) { return Node.isBaseInitializer(); } /// Matches a constructor initializer if it is initializing a member, as /// opposed to a base. /// /// Given /// \code /// struct B {}; /// struct D : B { /// int I; /// D(int i) : I(i) {} /// }; /// struct E : B { /// E() : B() {} /// }; /// \endcode /// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer())) /// will match D(int), but not match E(). AST_MATCHER(CXXCtorInitializer, isMemberInitializer) { return Node.isMemberInitializer(); } /// Matches any argument of a call expression or a constructor call /// expression, or an ObjC-message-send expression. /// /// Given /// \code /// void x(int, int, int) { int y; x(1, y, 42); } /// \endcode /// callExpr(hasAnyArgument(declRefExpr())) /// matches x(1, y, 42) /// with hasAnyArgument(...) /// matching y /// /// For ObjectiveC, given /// \code /// @interface I - (void) f:(int) y; @end /// void foo(I *i) { [i f:12]; } /// \endcode /// objcMessageExpr(hasAnyArgument(integerLiteral(equals(12)))) /// matches [i f:12] AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, AST_POLYMORPHIC_SUPPORTED_TYPES( CallExpr, CXXConstructExpr, CXXUnresolvedConstructExpr, ObjCMessageExpr), internal::Matcher<Expr>, InnerMatcher) { for (const Expr *Arg : Node.arguments()) { if (Finder->isTraversalIgnoringImplicitNodes() && isa<CXXDefaultArgExpr>(Arg)) break; BoundNodesTreeBuilder Result(*Builder); if (InnerMatcher.matches(*Arg, Finder, &Result)) { *Builder = std::move(Result); return true; } } return false; } /// Matches any capture of a lambda expression. /// /// Given /// \code /// void foo() { /// int x; /// auto f = [x](){}; /// } /// \endcode /// lambdaExpr(hasAnyCapture(anything())) /// matches [x](){}; AST_MATCHER_P_OVERLOAD(LambdaExpr, hasAnyCapture, internal::Matcher<VarDecl>, InnerMatcher, 0) { for (const LambdaCapture &Capture : Node.captures()) { if (Capture.capturesVariable()) { BoundNodesTreeBuilder Result(*Builder); if (InnerMatcher.matches(*Capture.getCapturedVar(), Finder, &Result)) { *Builder = std::move(Result); return true; } } } return false; } /// Matches any capture of 'this' in a lambda expression. /// /// Given /// \code /// struct foo { /// void bar() { /// auto f = [this](){}; /// } /// } /// \endcode /// lambdaExpr(hasAnyCapture(cxxThisExpr())) /// matches [this](){}; AST_MATCHER_P_OVERLOAD(LambdaExpr, hasAnyCapture, internal::Matcher<CXXThisExpr>, InnerMatcher, 1) { return llvm::any_of(Node.captures(), [](const LambdaCapture &LC) { return LC.capturesThis(); }); } /// Matches a constructor call expression which uses list initialization. AST_MATCHER(CXXConstructExpr, isListInitialization) { return Node.isListInitialization(); } /// Matches a constructor call expression which requires /// zero initialization. /// /// Given /// \code /// void foo() { /// struct point { double x; double y; }; /// point pt[2] = { { 1.0, 2.0 } }; /// } /// \endcode /// initListExpr(has(cxxConstructExpr(requiresZeroInitialization())) /// will match the implicit array filler for pt[1]. AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) { return Node.requiresZeroInitialization(); } /// Matches the n'th parameter of a function or an ObjC method /// declaration or a block. /// /// Given /// \code /// class X { void f(int x) {} }; /// \endcode /// cxxMethodDecl(hasParameter(0, hasType(varDecl()))) /// matches f(int x) {} /// with hasParameter(...) /// matching int x /// /// For ObjectiveC, given /// \code /// @interface I - (void) f:(int) y; @end /// \endcode // /// the matcher objcMethodDecl(hasParameter(0, hasName("y"))) /// matches the declaration of method f with hasParameter /// matching y. AST_POLYMORPHIC_MATCHER_P2(hasParameter, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, ObjCMethodDecl, BlockDecl), unsigned, N, internal::Matcher<ParmVarDecl>, InnerMatcher) { return (N < Node.parameters().size() && InnerMatcher.matches(*Node.parameters()[N], Finder, Builder)); } /// Matches all arguments and their respective ParmVarDecl. /// /// Given /// \code /// void f(int i); /// int y; /// f(y); /// \endcode /// callExpr( /// forEachArgumentWithParam( /// declRefExpr(to(varDecl(hasName("y")))), /// parmVarDecl(hasType(isInteger())) /// )) /// matches f(y); /// with declRefExpr(...) /// matching int y /// and parmVarDecl(...) /// matching int i AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam, AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr, CXXConstructExpr), internal::Matcher<Expr>, ArgMatcher, internal::Matcher<ParmVarDecl>, ParamMatcher) { BoundNodesTreeBuilder Result; // The first argument of an overloaded member operator is the implicit object // argument of the method which should not be matched against a parameter, so // we skip over it here. BoundNodesTreeBuilder Matches; unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl())) .matches(Node, Finder, &Matches) ? 1 : 0; int ParamIndex = 0; bool Matched = false; for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) { BoundNodesTreeBuilder ArgMatches(*Builder); if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()), Finder, &ArgMatches)) { BoundNodesTreeBuilder ParamMatches(ArgMatches); if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl( hasParameter(ParamIndex, ParamMatcher)))), callExpr(callee(functionDecl( hasParameter(ParamIndex, ParamMatcher)))))) .matches(Node, Finder, &ParamMatches)) { Result.addMatch(ParamMatches); Matched = true; } } ++ParamIndex; } *Builder = std::move(Result); return Matched; } /// Matches all arguments and their respective types for a \c CallExpr or /// \c CXXConstructExpr. It is very similar to \c forEachArgumentWithParam but /// it works on calls through function pointers as well. /// /// The difference is, that function pointers do not provide access to a /// \c ParmVarDecl, but only the \c QualType for each argument. /// /// Given /// \code /// void f(int i); /// int y; /// f(y); /// void (*f_ptr)(int) = f; /// f_ptr(y); /// \endcode /// callExpr( /// forEachArgumentWithParamType( /// declRefExpr(to(varDecl(hasName("y")))), /// qualType(isInteger()).bind("type) /// )) /// matches f(y) and f_ptr(y) /// with declRefExpr(...) /// matching int y /// and qualType(...) /// matching int AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParamType, AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr, CXXConstructExpr), internal::Matcher<Expr>, ArgMatcher, internal::Matcher<QualType>, ParamMatcher) { BoundNodesTreeBuilder Result; // The first argument of an overloaded member operator is the implicit object // argument of the method which should not be matched against a parameter, so // we skip over it here. BoundNodesTreeBuilder Matches; unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl())) .matches(Node, Finder, &Matches) ? 1 : 0; const FunctionProtoType *FProto = nullptr; if (const auto *Call = dyn_cast<CallExpr>(&Node)) { if (const auto *Value = dyn_cast_or_null<ValueDecl>(Call->getCalleeDecl())) { QualType QT = Value->getType().getCanonicalType(); // This does not necessarily lead to a `FunctionProtoType`, // e.g. K&R functions do not have a function prototype. if (QT->isFunctionPointerType()) FProto = QT->getPointeeType()->getAs<FunctionProtoType>(); if (QT->isMemberFunctionPointerType()) { const auto *MP = QT->getAs<MemberPointerType>(); assert(MP && "Must be member-pointer if its a memberfunctionpointer"); FProto = MP->getPointeeType()->getAs<FunctionProtoType>(); assert(FProto && "The call must have happened through a member function " "pointer"); } } } int ParamIndex = 0; bool Matched = false; unsigned NumArgs = Node.getNumArgs(); if (FProto && FProto->isVariadic()) NumArgs = std::min(NumArgs, FProto->getNumParams()); for (; ArgIndex < NumArgs; ++ArgIndex, ++ParamIndex) { BoundNodesTreeBuilder ArgMatches(*Builder); if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()), Finder, &ArgMatches)) { BoundNodesTreeBuilder ParamMatches(ArgMatches); // This test is cheaper compared to the big matcher in the next if. // Therefore, please keep this order. if (FProto) { QualType ParamType = FProto->getParamType(ParamIndex); if (ParamMatcher.matches(ParamType, Finder, &ParamMatches)) { Result.addMatch(ParamMatches); Matched = true; continue; } } if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl( hasParameter(ParamIndex, hasType(ParamMatcher))))), callExpr(callee(functionDecl( hasParameter(ParamIndex, hasType(ParamMatcher))))))) .matches(Node, Finder, &ParamMatches)) { Result.addMatch(ParamMatches); Matched = true; continue; } } } *Builder = std::move(Result); return Matched; } /// Matches the ParmVarDecl nodes that are at the N'th position in the parameter /// list. The parameter list could be that of either a block, function, or /// objc-method. /// /// /// Given /// /// \code /// void f(int a, int b, int c) { /// } /// \endcode /// /// ``parmVarDecl(isAtPosition(0))`` matches ``int a``. /// /// ``parmVarDecl(isAtPosition(1))`` matches ``int b``. AST_MATCHER_P(ParmVarDecl, isAtPosition, unsigned, N) { const clang::DeclContext *Context = Node.getParentFunctionOrMethod(); if (const auto *Decl = dyn_cast_or_null<FunctionDecl>(Context)) return N < Decl->param_size() && Decl->getParamDecl(N) == &Node; if (const auto *Decl = dyn_cast_or_null<BlockDecl>(Context)) return N < Decl->param_size() && Decl->getParamDecl(N) == &Node; if (const auto *Decl = dyn_cast_or_null<ObjCMethodDecl>(Context)) return N < Decl->param_size() && Decl->getParamDecl(N) == &Node; return false; } /// Matches any parameter of a function or an ObjC method declaration or a /// block. /// /// Does not match the 'this' parameter of a method. /// /// Given /// \code /// class X { void f(int x, int y, int z) {} }; /// \endcode /// cxxMethodDecl(hasAnyParameter(hasName("y"))) /// matches f(int x, int y, int z) {} /// with hasAnyParameter(...) /// matching int y /// /// For ObjectiveC, given /// \code /// @interface I - (void) f:(int) y; @end /// \endcode // /// the matcher objcMethodDecl(hasAnyParameter(hasName("y"))) /// matches the declaration of method f with hasParameter /// matching y. /// /// For blocks, given /// \code /// b = ^(int y) { printf("%d", y) }; /// \endcode /// /// the matcher blockDecl(hasAnyParameter(hasName("y"))) /// matches the declaration of the block b with hasParameter /// matching y. AST_POLYMORPHIC_MATCHER_P(hasAnyParameter, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, ObjCMethodDecl, BlockDecl), internal::Matcher<ParmVarDecl>, InnerMatcher) { return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(), Node.param_end(), Finder, Builder) != Node.param_end(); } /// Matches \c FunctionDecls and \c FunctionProtoTypes that have a /// specific parameter count. /// /// Given /// \code /// void f(int i) {} /// void g(int i, int j) {} /// void h(int i, int j); /// void j(int i); /// void k(int x, int y, int z, ...); /// \endcode /// functionDecl(parameterCountIs(2)) /// matches \c g and \c h /// functionProtoType(parameterCountIs(2)) /// matches \c g and \c h /// functionProtoType(parameterCountIs(3)) /// matches \c k AST_POLYMORPHIC_MATCHER_P(parameterCountIs, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, FunctionProtoType), unsigned, N) { return Node.getNumParams() == N; } /// Matches \c FunctionDecls that have a noreturn attribute. /// /// Given /// \code /// void nope(); /// [[noreturn]] void a(); /// __attribute__((noreturn)) void b(); /// struct c { [[noreturn]] c(); }; /// \endcode /// functionDecl(isNoReturn()) /// matches all of those except /// \code /// void nope(); /// \endcode AST_MATCHER(FunctionDecl, isNoReturn) { return Node.isNoReturn(); } /// Matches the return type of a function declaration. /// /// Given: /// \code /// class X { int f() { return 1; } }; /// \endcode /// cxxMethodDecl(returns(asString("int"))) /// matches int f() { return 1; } AST_MATCHER_P(FunctionDecl, returns, internal::Matcher<QualType>, InnerMatcher) { return InnerMatcher.matches(Node.getReturnType(), Finder, Builder); } /// Matches extern "C" function or variable declarations. /// /// Given: /// \code /// extern "C" void f() {} /// extern "C" { void g() {} } /// void h() {} /// extern "C" int x = 1; /// extern "C" int y = 2; /// int z = 3; /// \endcode /// functionDecl(isExternC()) /// matches the declaration of f and g, but not the declaration of h. /// varDecl(isExternC()) /// matches the declaration of x and y, but not the declaration of z. AST_POLYMORPHIC_MATCHER(isExternC, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl)) { return Node.isExternC(); } /// Matches variable/function declarations that have "static" storage /// class specifier ("static" keyword) written in the source. /// /// Given: /// \code /// static void f() {} /// static int i = 0; /// extern int j; /// int k; /// \endcode /// functionDecl(isStaticStorageClass()) /// matches the function declaration f. /// varDecl(isStaticStorageClass()) /// matches the variable declaration i. AST_POLYMORPHIC_MATCHER(isStaticStorageClass, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl)) { return Node.getStorageClass() == SC_Static; } /// Matches deleted function declarations. /// /// Given: /// \code /// void Func(); /// void DeletedFunc() = delete; /// \endcode /// functionDecl(isDeleted()) /// matches the declaration of DeletedFunc, but not Func. AST_MATCHER(FunctionDecl, isDeleted) { return Node.isDeleted(); } /// Matches defaulted function declarations. /// /// Given: /// \code /// class A { ~A(); }; /// class B { ~B() = default; }; /// \endcode /// functionDecl(isDefaulted()) /// matches the declaration of ~B, but not ~A. AST_MATCHER(FunctionDecl, isDefaulted) { return Node.isDefaulted(); } /// Matches weak function declarations. /// /// Given: /// \code /// void foo() __attribute__((__weakref__("__foo"))); /// void bar(); /// \endcode /// functionDecl(isWeak()) /// matches the weak declaration "foo", but not "bar". AST_MATCHER(FunctionDecl, isWeak) { return Node.isWeak(); } /// Matches functions that have a dynamic exception specification. /// /// Given: /// \code /// void f(); /// void g() noexcept; /// void h() noexcept(true); /// void i() noexcept(false); /// void j() throw(); /// void k() throw(int); /// void l() throw(...); /// \endcode /// functionDecl(hasDynamicExceptionSpec()) and /// functionProtoType(hasDynamicExceptionSpec()) /// match the declarations of j, k, and l, but not f, g, h, or i. AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, FunctionProtoType)) { if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node)) return FnTy->hasDynamicExceptionSpec(); return false; } /// Matches functions that have a non-throwing exception specification. /// /// Given: /// \code /// void f(); /// void g() noexcept; /// void h() throw(); /// void i() throw(int); /// void j() noexcept(false); /// \endcode /// functionDecl(isNoThrow()) and functionProtoType(isNoThrow()) /// match the declarations of g, and h, but not f, i or j. AST_POLYMORPHIC_MATCHER(isNoThrow, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, FunctionProtoType)) { const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node); // If the function does not have a prototype, then it is assumed to be a // throwing function (as it would if the function did not have any exception // specification). if (!FnTy) return false; // Assume the best for any unresolved exception specification. if (isUnresolvedExceptionSpec(FnTy->getExceptionSpecType())) return true; return FnTy->isNothrow(); } /// Matches constexpr variable and function declarations, /// and if constexpr. /// /// Given: /// \code /// constexpr int foo = 42; /// constexpr int bar(); /// void baz() { if constexpr(1 > 0) {} } /// \endcode /// varDecl(isConstexpr()) /// matches the declaration of foo. /// functionDecl(isConstexpr()) /// matches the declaration of bar. /// ifStmt(isConstexpr()) /// matches the if statement in baz. AST_POLYMORPHIC_MATCHER(isConstexpr, AST_POLYMORPHIC_SUPPORTED_TYPES(VarDecl, FunctionDecl, IfStmt)) { return Node.isConstexpr(); } /// Matches selection statements with initializer. /// /// Given: /// \code /// void foo() { /// if (int i = foobar(); i > 0) {} /// switch (int i = foobar(); i) {} /// for (auto& a = get_range(); auto& x : a) {} /// } /// void bar() { /// if (foobar() > 0) {} /// switch (foobar()) {} /// for (auto& x : get_range()) {} /// } /// \endcode /// ifStmt(hasInitStatement(anything())) /// matches the if statement in foo but not in bar. /// switchStmt(hasInitStatement(anything())) /// matches the switch statement in foo but not in bar. /// cxxForRangeStmt(hasInitStatement(anything())) /// matches the range for statement in foo but not in bar. AST_POLYMORPHIC_MATCHER_P(hasInitStatement, AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, SwitchStmt, CXXForRangeStmt), internal::Matcher<Stmt>, InnerMatcher) { const Stmt *Init = Node.getInit(); return Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder); } /// Matches the condition expression of an if statement, for loop, /// switch statement or conditional operator. /// /// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true)))) /// \code /// if (true) {} /// \endcode AST_POLYMORPHIC_MATCHER_P( hasCondition, AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, ForStmt, WhileStmt, DoStmt, SwitchStmt, AbstractConditionalOperator), internal::Matcher<Expr>, InnerMatcher) { const Expr *const Condition = Node.getCond(); return (Condition != nullptr && InnerMatcher.matches(*Condition, Finder, Builder)); } /// Matches the then-statement of an if statement. /// /// Examples matches the if statement /// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true))))) /// \code /// if (false) true; else false; /// \endcode AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) { const Stmt *const Then = Node.getThen(); return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder)); } /// Matches the else-statement of an if statement. /// /// Examples matches the if statement /// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true))))) /// \code /// if (false) false; else true; /// \endcode AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) { const Stmt *const Else = Node.getElse(); return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder)); } /// Matches if a node equals a previously bound node. /// /// Matches a node if it equals the node previously bound to \p ID. /// /// Given /// \code /// class X { int a; int b; }; /// \endcode /// cxxRecordDecl( /// has(fieldDecl(hasName("a"), hasType(type().bind("t")))), /// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t")))))) /// matches the class \c X, as \c a and \c b have the same type. /// /// Note that when multiple matches are involved via \c forEach* matchers, /// \c equalsBoundNodes acts as a filter. /// For example: /// compoundStmt( /// forEachDescendant(varDecl().bind("d")), /// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))) /// will trigger a match for each combination of variable declaration /// and reference to that variable declaration within a compound statement. AST_POLYMORPHIC_MATCHER_P(equalsBoundNode, AST_POLYMORPHIC_SUPPORTED_TYPES(Stmt, Decl, Type, QualType), std::string, ID) { // FIXME: Figure out whether it makes sense to allow this // on any other node types. // For *Loc it probably does not make sense, as those seem // unique. For NestedNameSepcifier it might make sense, as // those also have pointer identity, but I'm not sure whether // they're ever reused. internal::NotEqualsBoundNodePredicate Predicate; Predicate.ID = ID; Predicate.Node = DynTypedNode::create(Node); return Builder->removeBindings(Predicate); } /// Matches the condition variable statement in an if statement. /// /// Given /// \code /// if (A* a = GetAPointer()) {} /// \endcode /// hasConditionVariableStatement(...) /// matches 'A* a = GetAPointer()'. AST_MATCHER_P(IfStmt, hasConditionVariableStatement, internal::Matcher<DeclStmt>, InnerMatcher) { const DeclStmt* const DeclarationStatement = Node.getConditionVariableDeclStmt(); return DeclarationStatement != nullptr && InnerMatcher.matches(*DeclarationStatement, Finder, Builder); } /// Matches the index expression of an array subscript expression. /// /// Given /// \code /// int i[5]; /// void f() { i[1] = 42; } /// \endcode /// arraySubscriptExpression(hasIndex(integerLiteral())) /// matches \c i[1] with the \c integerLiteral() matching \c 1 AST_MATCHER_P(ArraySubscriptExpr, hasIndex, internal::Matcher<Expr>, InnerMatcher) { if (const Expr* Expression = Node.getIdx()) return InnerMatcher.matches(*Expression, Finder, Builder); return false; } /// Matches the base expression of an array subscript expression. /// /// Given /// \code /// int i[5]; /// void f() { i[1] = 42; } /// \endcode /// arraySubscriptExpression(hasBase(implicitCastExpr( /// hasSourceExpression(declRefExpr())))) /// matches \c i[1] with the \c declRefExpr() matching \c i AST_MATCHER_P(ArraySubscriptExpr, hasBase, internal::Matcher<Expr>, InnerMatcher) { if (const Expr* Expression = Node.getBase()) return InnerMatcher.matches(*Expression, Finder, Builder); return false; } /// Matches a 'for', 'while', 'do while' statement or a function /// definition that has a given body. Note that in case of functions /// this matcher only matches the definition itself and not the other /// declarations of the same function. /// /// Given /// \code /// for (;;) {} /// \endcode /// hasBody(compoundStmt()) /// matches 'for (;;) {}' /// with compoundStmt() /// matching '{}' /// /// Given /// \code /// void f(); /// void f() {} /// \endcode /// hasBody(functionDecl()) /// matches 'void f() {}' /// with compoundStmt() /// matching '{}' /// but does not match 'void f();' AST_POLYMORPHIC_MATCHER_P(hasBody, AST_POLYMORPHIC_SUPPORTED_TYPES(DoStmt, ForStmt, WhileStmt, CXXForRangeStmt, FunctionDecl), internal::Matcher<Stmt>, InnerMatcher) { if (Finder->isTraversalIgnoringImplicitNodes() && isDefaultedHelper(&Node)) return false; const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node); return (Statement != nullptr && InnerMatcher.matches(*Statement, Finder, Builder)); } /// Matches a function declaration that has a given body present in the AST. /// Note that this matcher matches all the declarations of a function whose /// body is present in the AST. /// /// Given /// \code /// void f(); /// void f() {} /// void g(); /// \endcode /// functionDecl(hasAnyBody(compoundStmt())) /// matches both 'void f();' /// and 'void f() {}' /// with compoundStmt() /// matching '{}' /// but does not match 'void g();' AST_MATCHER_P(FunctionDecl, hasAnyBody, internal::Matcher<Stmt>, InnerMatcher) { const Stmt *const Statement = Node.getBody(); return (Statement != nullptr && InnerMatcher.matches(*Statement, Finder, Builder)); } /// Matches compound statements where at least one substatement matches /// a given matcher. Also matches StmtExprs that have CompoundStmt as children. /// /// Given /// \code /// { {}; 1+2; } /// \endcode /// hasAnySubstatement(compoundStmt()) /// matches '{ {}; 1+2; }' /// with compoundStmt() /// matching '{}' AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement, AST_POLYMORPHIC_SUPPORTED_TYPES(CompoundStmt, StmtExpr), internal::Matcher<Stmt>, InnerMatcher) { const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node); return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(), CS->body_end(), Finder, Builder) != CS->body_end(); } /// Checks that a compound statement contains a specific number of /// child statements. /// /// Example: Given /// \code /// { for (;;) {} } /// \endcode /// compoundStmt(statementCountIs(0))) /// matches '{}' /// but does not match the outer compound statement. AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) { return Node.size() == N; } /// Matches literals that are equal to the given value of type ValueT. /// /// Given /// \code /// f('\0', false, 3.14, 42); /// \endcode /// characterLiteral(equals(0)) /// matches '\0' /// cxxBoolLiteral(equals(false)) and cxxBoolLiteral(equals(0)) /// match false /// floatLiteral(equals(3.14)) and floatLiteral(equals(314e-2)) /// match 3.14 /// integerLiteral(equals(42)) /// matches 42 /// /// Note that you cannot directly match a negative numeric literal because the /// minus sign is not part of the literal: It is a unary operator whose operand /// is the positive numeric literal. Instead, you must use a unaryOperator() /// matcher to match the minus sign: /// /// unaryOperator(hasOperatorName("-"), /// hasUnaryOperand(integerLiteral(equals(13)))) /// /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteralExpr>, /// Matcher<FloatingLiteral>, Matcher<IntegerLiteral> template <typename ValueT> internal::PolymorphicMatcher<internal::ValueEqualsMatcher, void(internal::AllNodeBaseTypes), ValueT> equals(const ValueT &Value) { return internal::PolymorphicMatcher<internal::ValueEqualsMatcher, void(internal::AllNodeBaseTypes), ValueT>( Value); } AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals, AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral, CXXBoolLiteralExpr, IntegerLiteral), bool, Value, 0) { return internal::ValueEqualsMatcher<NodeType, ParamT>(Value) .matchesNode(Node); } AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals, AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral, CXXBoolLiteralExpr, IntegerLiteral), unsigned, Value, 1) { return internal::ValueEqualsMatcher<NodeType, ParamT>(Value) .matchesNode(Node); } AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals, AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral, CXXBoolLiteralExpr, FloatingLiteral, IntegerLiteral), double, Value, 2) { return internal::ValueEqualsMatcher<NodeType, ParamT>(Value) .matchesNode(Node); } /// Matches the operator Name of operator expressions (binary or /// unary). /// /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||"))) /// \code /// !(a || b) /// \endcode AST_POLYMORPHIC_MATCHER_P( hasOperatorName, AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr, CXXRewrittenBinaryOperator, UnaryOperator), std::string, Name) { if (Optional<StringRef> OpName = internal::getOpName(Node)) return *OpName == Name; return false; } /// Matches operator expressions (binary or unary) that have any of the /// specified names. /// /// hasAnyOperatorName("+", "-") /// Is equivalent to /// anyOf(hasOperatorName("+"), hasOperatorName("-")) extern const internal::VariadicFunction< internal::PolymorphicMatcher<internal::HasAnyOperatorNameMatcher, AST_POLYMORPHIC_SUPPORTED_TYPES( BinaryOperator, CXXOperatorCallExpr, CXXRewrittenBinaryOperator, UnaryOperator), std::vector<std::string>>, StringRef, internal::hasAnyOperatorNameFunc> hasAnyOperatorName; /// Matches all kinds of assignment operators. /// /// Example 1: matches a += b (matcher = binaryOperator(isAssignmentOperator())) /// \code /// if (a == b) /// a += b; /// \endcode /// /// Example 2: matches s1 = s2 /// (matcher = cxxOperatorCallExpr(isAssignmentOperator())) /// \code /// struct S { S& operator=(const S&); }; /// void x() { S s1, s2; s1 = s2; } /// \endcode AST_POLYMORPHIC_MATCHER( isAssignmentOperator, AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr, CXXRewrittenBinaryOperator)) { return Node.isAssignmentOp(); } /// Matches comparison operators. /// /// Example 1: matches a == b (matcher = binaryOperator(isComparisonOperator())) /// \code /// if (a == b) /// a += b; /// \endcode /// /// Example 2: matches s1 < s2 /// (matcher = cxxOperatorCallExpr(isComparisonOperator())) /// \code /// struct S { bool operator<(const S& other); }; /// void x(S s1, S s2) { bool b1 = s1 < s2; } /// \endcode AST_POLYMORPHIC_MATCHER( isComparisonOperator, AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr, CXXRewrittenBinaryOperator)) { return Node.isComparisonOp(); } /// Matches the left hand side of binary operator expressions. /// /// Example matches a (matcher = binaryOperator(hasLHS())) /// \code /// a || b /// \endcode AST_POLYMORPHIC_MATCHER_P(hasLHS, AST_POLYMORPHIC_SUPPORTED_TYPES( BinaryOperator, CXXOperatorCallExpr, CXXRewrittenBinaryOperator, ArraySubscriptExpr), internal::Matcher<Expr>, InnerMatcher) { const Expr *LeftHandSide = internal::getLHS(Node); return (LeftHandSide != nullptr && InnerMatcher.matches(*LeftHandSide, Finder, Builder)); } /// Matches the right hand side of binary operator expressions. /// /// Example matches b (matcher = binaryOperator(hasRHS())) /// \code /// a || b /// \endcode AST_POLYMORPHIC_MATCHER_P(hasRHS, AST_POLYMORPHIC_SUPPORTED_TYPES( BinaryOperator, CXXOperatorCallExpr, CXXRewrittenBinaryOperator, ArraySubscriptExpr), internal::Matcher<Expr>, InnerMatcher) { const Expr *RightHandSide = internal::getRHS(Node); return (RightHandSide != nullptr && InnerMatcher.matches(*RightHandSide, Finder, Builder)); } /// Matches if either the left hand side or the right hand side of a /// binary operator matches. AST_POLYMORPHIC_MATCHER_P( hasEitherOperand, AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr, CXXRewrittenBinaryOperator), internal::Matcher<Expr>, InnerMatcher) { return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()( anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher))) .matches(Node, Finder, Builder); } /// Matches if both matchers match with opposite sides of the binary operator. /// /// Example matcher = binaryOperator(hasOperands(integerLiteral(equals(1), /// integerLiteral(equals(2))) /// \code /// 1 + 2 // Match /// 2 + 1 // Match /// 1 + 1 // No match /// 2 + 2 // No match /// \endcode AST_POLYMORPHIC_MATCHER_P2( hasOperands, AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr, CXXRewrittenBinaryOperator), internal::Matcher<Expr>, Matcher1, internal::Matcher<Expr>, Matcher2) { return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()( anyOf(allOf(hasLHS(Matcher1), hasRHS(Matcher2)), allOf(hasLHS(Matcher2), hasRHS(Matcher1)))) .matches(Node, Finder, Builder); } /// Matches if the operand of a unary operator matches. /// /// Example matches true (matcher = hasUnaryOperand( /// cxxBoolLiteral(equals(true)))) /// \code /// !true /// \endcode AST_POLYMORPHIC_MATCHER_P(hasUnaryOperand, AST_POLYMORPHIC_SUPPORTED_TYPES(UnaryOperator, CXXOperatorCallExpr), internal::Matcher<Expr>, InnerMatcher) { const Expr *const Operand = internal::getSubExpr(Node); return (Operand != nullptr && InnerMatcher.matches(*Operand, Finder, Builder)); } /// Matches if the cast's source expression /// or opaque value's source expression matches the given matcher. /// /// Example 1: matches "a string" /// (matcher = castExpr(hasSourceExpression(cxxConstructExpr()))) /// \code /// class URL { URL(string); }; /// URL url = "a string"; /// \endcode /// /// Example 2: matches 'b' (matcher = /// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr()))) /// \code /// int a = b ?: 1; /// \endcode AST_POLYMORPHIC_MATCHER_P(hasSourceExpression, AST_POLYMORPHIC_SUPPORTED_TYPES(CastExpr, OpaqueValueExpr), internal::Matcher<Expr>, InnerMatcher) { const Expr *const SubExpression = internal::GetSourceExpressionMatcher<NodeType>::get(Node); return (SubExpression != nullptr && InnerMatcher.matches(*SubExpression, Finder, Builder)); } /// Matches casts that has a given cast kind. /// /// Example: matches the implicit cast around \c 0 /// (matcher = castExpr(hasCastKind(CK_NullToPointer))) /// \code /// int *p = 0; /// \endcode /// /// If the matcher is use from clang-query, CastKind parameter /// should be passed as a quoted string. e.g., hasCastKind("CK_NullToPointer"). AST_MATCHER_P(CastExpr, hasCastKind, CastKind, Kind) { return Node.getCastKind() == Kind; } /// Matches casts whose destination type matches a given matcher. /// /// (Note: Clang's AST refers to other conversions as "casts" too, and calls /// actual casts "explicit" casts.) AST_MATCHER_P(ExplicitCastExpr, hasDestinationType, internal::Matcher<QualType>, InnerMatcher) { const QualType NodeType = Node.getTypeAsWritten(); return InnerMatcher.matches(NodeType, Finder, Builder); } /// Matches implicit casts whose destination type matches a given /// matcher. /// /// FIXME: Unit test this matcher AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType, internal::Matcher<QualType>, InnerMatcher) { return InnerMatcher.matches(Node.getType(), Finder, Builder); } /// Matches TagDecl object that are spelled with "struct." /// /// Example matches S, but not C, U or E. /// \code /// struct S {}; /// class C {}; /// union U {}; /// enum E {}; /// \endcode AST_MATCHER(TagDecl, isStruct) { return Node.isStruct(); } /// Matches TagDecl object that are spelled with "union." /// /// Example matches U, but not C, S or E. /// \code /// struct S {}; /// class C {}; /// union U {}; /// enum E {}; /// \endcode AST_MATCHER(TagDecl, isUnion) { return Node.isUnion(); } /// Matches TagDecl object that are spelled with "class." /// /// Example matches C, but not S, U or E. /// \code /// struct S {}; /// class C {}; /// union U {}; /// enum E {}; /// \endcode AST_MATCHER(TagDecl, isClass) { return Node.isClass(); } /// Matches TagDecl object that are spelled with "enum." /// /// Example matches E, but not C, S or U. /// \code /// struct S {}; /// class C {}; /// union U {}; /// enum E {}; /// \endcode AST_MATCHER(TagDecl, isEnum) { return Node.isEnum(); } /// Matches the true branch expression of a conditional operator. /// /// Example 1 (conditional ternary operator): matches a /// \code /// condition ? a : b /// \endcode /// /// Example 2 (conditional binary operator): matches opaqueValueExpr(condition) /// \code /// condition ?: b /// \endcode AST_MATCHER_P(AbstractConditionalOperator, hasTrueExpression, internal::Matcher<Expr>, InnerMatcher) { const Expr *Expression = Node.getTrueExpr(); return (Expression != nullptr && InnerMatcher.matches(*Expression, Finder, Builder)); } /// Matches the false branch expression of a conditional operator /// (binary or ternary). /// /// Example matches b /// \code /// condition ? a : b /// condition ?: b /// \endcode AST_MATCHER_P(AbstractConditionalOperator, hasFalseExpression, internal::Matcher<Expr>, InnerMatcher) { const Expr *Expression = Node.getFalseExpr(); return (Expression != nullptr && InnerMatcher.matches(*Expression, Finder, Builder)); } /// Matches if a declaration has a body attached. /// /// Example matches A, va, fa /// \code /// class A {}; /// class B; // Doesn't match, as it has no body. /// int va; /// extern int vb; // Doesn't match, as it doesn't define the variable. /// void fa() {} /// void fb(); // Doesn't match, as it has no body. /// @interface X /// - (void)ma; // Doesn't match, interface is declaration. /// @end /// @implementation X /// - (void)ma {} /// @end /// \endcode /// /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>, /// Matcher<ObjCMethodDecl> AST_POLYMORPHIC_MATCHER(isDefinition, AST_POLYMORPHIC_SUPPORTED_TYPES(TagDecl, VarDecl, ObjCMethodDecl, FunctionDecl)) { return Node.isThisDeclarationADefinition(); } /// Matches if a function declaration is variadic. /// /// Example matches f, but not g or h. The function i will not match, even when /// compiled in C mode. /// \code /// void f(...); /// void g(int); /// template <typename... Ts> void h(Ts...); /// void i(); /// \endcode AST_MATCHER(FunctionDecl, isVariadic) { return Node.isVariadic(); } /// Matches the class declaration that the given method declaration /// belongs to. /// /// FIXME: Generalize this for other kinds of declarations. /// FIXME: What other kind of declarations would we need to generalize /// this to? /// /// Example matches A() in the last line /// (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl( /// ofClass(hasName("A")))))) /// \code /// class A { /// public: /// A(); /// }; /// A a = A(); /// \endcode AST_MATCHER_P(CXXMethodDecl, ofClass, internal::Matcher<CXXRecordDecl>, InnerMatcher) { ASTChildrenNotSpelledInSourceScope RAII(Finder, false); const CXXRecordDecl *Parent = Node.getParent(); return (Parent != nullptr && InnerMatcher.matches(*Parent, Finder, Builder)); } /// Matches each method overridden by the given method. This matcher may /// produce multiple matches. /// /// Given /// \code /// class A { virtual void f(); }; /// class B : public A { void f(); }; /// class C : public B { void f(); }; /// \endcode /// cxxMethodDecl(ofClass(hasName("C")), /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d") /// matches once, with "b" binding "A::f" and "d" binding "C::f" (Note /// that B::f is not overridden by C::f). /// /// The check can produce multiple matches in case of multiple inheritance, e.g. /// \code /// class A1 { virtual void f(); }; /// class A2 { virtual void f(); }; /// class C : public A1, public A2 { void f(); }; /// \endcode /// cxxMethodDecl(ofClass(hasName("C")), /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d") /// matches twice, once with "b" binding "A1::f" and "d" binding "C::f", and /// once with "b" binding "A2::f" and "d" binding "C::f". AST_MATCHER_P(CXXMethodDecl, forEachOverridden, internal::Matcher<CXXMethodDecl>, InnerMatcher) { BoundNodesTreeBuilder Result; bool Matched = false; for (const auto *Overridden : Node.overridden_methods()) { BoundNodesTreeBuilder OverriddenBuilder(*Builder); const bool OverriddenMatched = InnerMatcher.matches(*Overridden, Finder, &OverriddenBuilder); if (OverriddenMatched) { Matched = true; Result.addMatch(OverriddenBuilder); } } *Builder = std::move(Result); return Matched; } /// Matches declarations of virtual methods and C++ base specifers that specify /// virtual inheritance. /// /// Example: /// \code /// class A { /// public: /// virtual void x(); // matches x /// }; /// \endcode /// /// Example: /// \code /// class Base {}; /// class DirectlyDerived : virtual Base {}; // matches Base /// class IndirectlyDerived : DirectlyDerived, Base {}; // matches Base /// \endcode /// /// Usable as: Matcher<CXXMethodDecl>, Matcher<CXXBaseSpecifier> AST_POLYMORPHIC_MATCHER(isVirtual, AST_POLYMORPHIC_SUPPORTED_TYPES(CXXMethodDecl, CXXBaseSpecifier)) { return Node.isVirtual(); } /// Matches if the given method declaration has an explicit "virtual". /// /// Given /// \code /// class A { /// public: /// virtual void x(); /// }; /// class B : public A { /// public: /// void x(); /// }; /// \endcode /// matches A::x but not B::x AST_MATCHER(CXXMethodDecl, isVirtualAsWritten) { return Node.isVirtualAsWritten(); } /// Matches if the given method or class declaration is final. /// /// Given: /// \code /// class A final {}; /// /// struct B { /// virtual void f(); /// }; /// /// struct C : B { /// void f() final; /// }; /// \endcode /// matches A and C::f, but not B, C, or B::f AST_POLYMORPHIC_MATCHER(isFinal, AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, CXXMethodDecl)) { return Node.template hasAttr<FinalAttr>(); } /// Matches if the given method declaration is pure. /// /// Given /// \code /// class A { /// public: /// virtual void x() = 0; /// }; /// \endcode /// matches A::x AST_MATCHER(CXXMethodDecl, isPure) { return Node.isPure(); } /// Matches if the given method declaration is const. /// /// Given /// \code /// struct A { /// void foo() const; /// void bar(); /// }; /// \endcode /// /// cxxMethodDecl(isConst()) matches A::foo() but not A::bar() AST_MATCHER(CXXMethodDecl, isConst) { return Node.isConst(); } /// Matches if the given method declaration declares a copy assignment /// operator. /// /// Given /// \code /// struct A { /// A &operator=(const A &); /// A &operator=(A &&); /// }; /// \endcode /// /// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not /// the second one. AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) { return Node.isCopyAssignmentOperator(); } /// Matches if the given method declaration declares a move assignment /// operator. /// /// Given /// \code /// struct A { /// A &operator=(const A &); /// A &operator=(A &&); /// }; /// \endcode /// /// cxxMethodDecl(isMoveAssignmentOperator()) matches the second method but not /// the first one. AST_MATCHER(CXXMethodDecl, isMoveAssignmentOperator) { return Node.isMoveAssignmentOperator(); } /// Matches if the given method declaration overrides another method. /// /// Given /// \code /// class A { /// public: /// virtual void x(); /// }; /// class B : public A { /// public: /// virtual void x(); /// }; /// \endcode /// matches B::x AST_MATCHER(CXXMethodDecl, isOverride) { return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>(); } /// Matches method declarations that are user-provided. /// /// Given /// \code /// struct S { /// S(); // #1 /// S(const S &) = default; // #2 /// S(S &&) = delete; // #3 /// }; /// \endcode /// cxxConstructorDecl(isUserProvided()) will match #1, but not #2 or #3. AST_MATCHER(CXXMethodDecl, isUserProvided) { return Node.isUserProvided(); } /// Matches member expressions that are called with '->' as opposed /// to '.'. /// /// Member calls on the implicit this pointer match as called with '->'. /// /// Given /// \code /// class Y { /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; } /// template <class T> void f() { this->f<T>(); f<T>(); } /// int a; /// static int b; /// }; /// template <class T> /// class Z { /// void x() { this->m; } /// }; /// \endcode /// memberExpr(isArrow()) /// matches this->x, x, y.x, a, this->b /// cxxDependentScopeMemberExpr(isArrow()) /// matches this->m /// unresolvedMemberExpr(isArrow()) /// matches this->f<T>, f<T> AST_POLYMORPHIC_MATCHER( isArrow, AST_POLYMORPHIC_SUPPORTED_TYPES(MemberExpr, UnresolvedMemberExpr, CXXDependentScopeMemberExpr)) { return Node.isArrow(); } /// Matches QualType nodes that are of integer type. /// /// Given /// \code /// void a(int); /// void b(long); /// void c(double); /// \endcode /// functionDecl(hasAnyParameter(hasType(isInteger()))) /// matches "a(int)", "b(long)", but not "c(double)". AST_MATCHER(QualType, isInteger) { return Node->isIntegerType(); } /// Matches QualType nodes that are of unsigned integer type. /// /// Given /// \code /// void a(int); /// void b(unsigned long); /// void c(double); /// \endcode /// functionDecl(hasAnyParameter(hasType(isUnsignedInteger()))) /// matches "b(unsigned long)", but not "a(int)" and "c(double)". AST_MATCHER(QualType, isUnsignedInteger) { return Node->isUnsignedIntegerType(); } /// Matches QualType nodes that are of signed integer type. /// /// Given /// \code /// void a(int); /// void b(unsigned long); /// void c(double); /// \endcode /// functionDecl(hasAnyParameter(hasType(isSignedInteger()))) /// matches "a(int)", but not "b(unsigned long)" and "c(double)". AST_MATCHER(QualType, isSignedInteger) { return Node->isSignedIntegerType(); } /// Matches QualType nodes that are of character type. /// /// Given /// \code /// void a(char); /// void b(wchar_t); /// void c(double); /// \endcode /// functionDecl(hasAnyParameter(hasType(isAnyCharacter()))) /// matches "a(char)", "b(wchar_t)", but not "c(double)". AST_MATCHER(QualType, isAnyCharacter) { return Node->isAnyCharacterType(); } /// Matches QualType nodes that are of any pointer type; this includes /// the Objective-C object pointer type, which is different despite being /// syntactically similar. /// /// Given /// \code /// int *i = nullptr; /// /// @interface Foo /// @end /// Foo *f; /// /// int j; /// \endcode /// varDecl(hasType(isAnyPointer())) /// matches "int *i" and "Foo *f", but not "int j". AST_MATCHER(QualType, isAnyPointer) { return Node->isAnyPointerType(); } /// Matches QualType nodes that are const-qualified, i.e., that /// include "top-level" const. /// /// Given /// \code /// void a(int); /// void b(int const); /// void c(const int); /// void d(const int*); /// void e(int const) {}; /// \endcode /// functionDecl(hasAnyParameter(hasType(isConstQualified()))) /// matches "void b(int const)", "void c(const int)" and /// "void e(int const) {}". It does not match d as there /// is no top-level const on the parameter type "const int *". AST_MATCHER(QualType, isConstQualified) { return Node.isConstQualified(); } /// Matches QualType nodes that are volatile-qualified, i.e., that /// include "top-level" volatile. /// /// Given /// \code /// void a(int); /// void b(int volatile); /// void c(volatile int); /// void d(volatile int*); /// void e(int volatile) {}; /// \endcode /// functionDecl(hasAnyParameter(hasType(isVolatileQualified()))) /// matches "void b(int volatile)", "void c(volatile int)" and /// "void e(int volatile) {}". It does not match d as there /// is no top-level volatile on the parameter type "volatile int *". AST_MATCHER(QualType, isVolatileQualified) { return Node.isVolatileQualified(); } /// Matches QualType nodes that have local CV-qualifiers attached to /// the node, not hidden within a typedef. /// /// Given /// \code /// typedef const int const_int; /// const_int i; /// int *const j; /// int *volatile k; /// int m; /// \endcode /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k. /// \c i is const-qualified but the qualifier is not local. AST_MATCHER(QualType, hasLocalQualifiers) { return Node.hasLocalQualifiers(); } /// Matches a member expression where the member is matched by a /// given matcher. /// /// Given /// \code /// struct { int first, second; } first, second; /// int i(second.first); /// int j(first.second); /// \endcode /// memberExpr(member(hasName("first"))) /// matches second.first /// but not first.second (because the member name there is "second"). AST_MATCHER_P(MemberExpr, member, internal::Matcher<ValueDecl>, InnerMatcher) { return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder); } /// Matches a member expression where the object expression is matched by a /// given matcher. Implicit object expressions are included; that is, it matches /// use of implicit `this`. /// /// Given /// \code /// struct X { /// int m; /// int f(X x) { x.m; return m; } /// }; /// \endcode /// memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X"))))) /// matches `x.m`, but not `m`; however, /// memberExpr(hasObjectExpression(hasType(pointsTo( // cxxRecordDecl(hasName("X")))))) /// matches `m` (aka. `this->m`), but not `x.m`. AST_POLYMORPHIC_MATCHER_P( hasObjectExpression, AST_POLYMORPHIC_SUPPORTED_TYPES(MemberExpr, UnresolvedMemberExpr, CXXDependentScopeMemberExpr), internal::Matcher<Expr>, InnerMatcher) { if (const auto *E = dyn_cast<UnresolvedMemberExpr>(&Node)) if (E->isImplicitAccess()) return false; if (const auto *E = dyn_cast<CXXDependentScopeMemberExpr>(&Node)) if (E->isImplicitAccess()) return false; return InnerMatcher.matches(*Node.getBase(), Finder, Builder); } /// Matches any using shadow declaration. /// /// Given /// \code /// namespace X { void b(); } /// using X::b; /// \endcode /// usingDecl(hasAnyUsingShadowDecl(hasName("b")))) /// matches \code using X::b \endcode AST_MATCHER_P(BaseUsingDecl, hasAnyUsingShadowDecl, internal::Matcher<UsingShadowDecl>, InnerMatcher) { return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(), Node.shadow_end(), Finder, Builder) != Node.shadow_end(); } /// Matches a using shadow declaration where the target declaration is /// matched by the given matcher. /// /// Given /// \code /// namespace X { int a; void b(); } /// using X::a; /// using X::b; /// \endcode /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl()))) /// matches \code using X::b \endcode /// but not \code using X::a \endcode AST_MATCHER_P(UsingShadowDecl, hasTargetDecl, internal::Matcher<NamedDecl>, InnerMatcher) { return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder); } /// Matches template instantiations of function, class, or static /// member variable template instantiations. /// /// Given /// \code /// template <typename T> class X {}; class A {}; X<A> x; /// \endcode /// or /// \code /// template <typename T> class X {}; class A {}; template class X<A>; /// \endcode /// or /// \code /// template <typename T> class X {}; class A {}; extern template class X<A>; /// \endcode /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation()) /// matches the template instantiation of X<A>. /// /// But given /// \code /// template <typename T> class X {}; class A {}; /// template <> class X<A> {}; X<A> x; /// \endcode /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation()) /// does not match, as X<A> is an explicit template specialization. /// /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl> AST_POLYMORPHIC_MATCHER(isTemplateInstantiation, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl, CXXRecordDecl)) { return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation || Node.getTemplateSpecializationKind() == TSK_ExplicitInstantiationDefinition || Node.getTemplateSpecializationKind() == TSK_ExplicitInstantiationDeclaration); } /// Matches declarations that are template instantiations or are inside /// template instantiations. /// /// Given /// \code /// template<typename T> void A(T t) { T i; } /// A(0); /// A(0U); /// \endcode /// functionDecl(isInstantiated()) /// matches 'A(int) {...};' and 'A(unsigned) {...}'. AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) { auto IsInstantiation = decl(anyOf(cxxRecordDecl(isTemplateInstantiation()), functionDecl(isTemplateInstantiation()))); return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation))); } /// Matches statements inside of a template instantiation. /// /// Given /// \code /// int j; /// template<typename T> void A(T t) { T i; j += 42;} /// A(0); /// A(0U); /// \endcode /// declStmt(isInTemplateInstantiation()) /// matches 'int i;' and 'unsigned i'. /// unless(stmt(isInTemplateInstantiation())) /// will NOT match j += 42; as it's shared between the template definition and /// instantiation. AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) { return stmt( hasAncestor(decl(anyOf(cxxRecordDecl(isTemplateInstantiation()), functionDecl(isTemplateInstantiation()))))); } /// Matches explicit template specializations of function, class, or /// static member variable template instantiations. /// /// Given /// \code /// template<typename T> void A(T t) { } /// template<> void A(int N) { } /// \endcode /// functionDecl(isExplicitTemplateSpecialization()) /// matches the specialization A<int>(). /// /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl> AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl, CXXRecordDecl)) { return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization); } /// Matches \c TypeLocs for which the given inner /// QualType-matcher matches. AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc, internal::Matcher<QualType>, InnerMatcher, 0) { return internal::BindableMatcher<TypeLoc>( new internal::TypeLocTypeMatcher(InnerMatcher)); } /// Matches type \c bool. /// /// Given /// \code /// struct S { bool func(); }; /// \endcode /// functionDecl(returns(booleanType())) /// matches "bool func();" AST_MATCHER(Type, booleanType) { return Node.isBooleanType(); } /// Matches type \c void. /// /// Given /// \code /// struct S { void func(); }; /// \endcode /// functionDecl(returns(voidType())) /// matches "void func();" AST_MATCHER(Type, voidType) { return Node.isVoidType(); } template <typename NodeType> using AstTypeMatcher = internal::VariadicDynCastAllOfMatcher<Type, NodeType>; /// Matches builtin Types. /// /// Given /// \code /// struct A {}; /// A a; /// int b; /// float c; /// bool d; /// \endcode /// builtinType() /// matches "int b", "float c" and "bool d" extern const AstTypeMatcher<BuiltinType> builtinType; /// Matches all kinds of arrays. /// /// Given /// \code /// int a[] = { 2, 3 }; /// int b[4]; /// void f() { int c[a[0]]; } /// \endcode /// arrayType() /// matches "int a[]", "int b[4]" and "int c[a[0]]"; extern const AstTypeMatcher<ArrayType> arrayType; /// Matches C99 complex types. /// /// Given /// \code /// _Complex float f; /// \endcode /// complexType() /// matches "_Complex float f" extern const AstTypeMatcher<ComplexType> complexType; /// Matches any real floating-point type (float, double, long double). /// /// Given /// \code /// int i; /// float f; /// \endcode /// realFloatingPointType() /// matches "float f" but not "int i" AST_MATCHER(Type, realFloatingPointType) { return Node.isRealFloatingType(); } /// Matches arrays and C99 complex types that have a specific element /// type. /// /// Given /// \code /// struct A {}; /// A a[7]; /// int b[7]; /// \endcode /// arrayType(hasElementType(builtinType())) /// matches "int b[7]" /// /// Usable as: Matcher<ArrayType>, Matcher<ComplexType> AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasElementType, getElement, AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType, ComplexType)); /// Matches C arrays with a specified constant size. /// /// Given /// \code /// void() { /// int a[2]; /// int b[] = { 2, 3 }; /// int c[b[0]]; /// } /// \endcode /// constantArrayType() /// matches "int a[2]" extern const AstTypeMatcher<ConstantArrayType> constantArrayType; /// Matches nodes that have the specified size. /// /// Given /// \code /// int a[42]; /// int b[2 * 21]; /// int c[41], d[43]; /// char *s = "abcd"; /// wchar_t *ws = L"abcd"; /// char *w = "a"; /// \endcode /// constantArrayType(hasSize(42)) /// matches "int a[42]" and "int b[2 * 21]" /// stringLiteral(hasSize(4)) /// matches "abcd", L"abcd" AST_POLYMORPHIC_MATCHER_P(hasSize, AST_POLYMORPHIC_SUPPORTED_TYPES(ConstantArrayType, StringLiteral), unsigned, N) { return internal::HasSizeMatcher<NodeType>::hasSize(Node, N); } /// Matches C++ arrays whose size is a value-dependent expression. /// /// Given /// \code /// template<typename T, int Size> /// class array { /// T data[Size]; /// }; /// \endcode /// dependentSizedArrayType /// matches "T data[Size]" extern const AstTypeMatcher<DependentSizedArrayType> dependentSizedArrayType; /// Matches C arrays with unspecified size. /// /// Given /// \code /// int a[] = { 2, 3 }; /// int b[42]; /// void f(int c[]) { int d[a[0]]; }; /// \endcode /// incompleteArrayType() /// matches "int a[]" and "int c[]" extern const AstTypeMatcher<IncompleteArrayType> incompleteArrayType; /// Matches C arrays with a specified size that is not an /// integer-constant-expression. /// /// Given /// \code /// void f() { /// int a[] = { 2, 3 } /// int b[42]; /// int c[a[0]]; /// } /// \endcode /// variableArrayType() /// matches "int c[a[0]]" extern const AstTypeMatcher<VariableArrayType> variableArrayType; /// Matches \c VariableArrayType nodes that have a specific size /// expression. /// /// Given /// \code /// void f(int b) { /// int a[b]; /// } /// \endcode /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to( /// varDecl(hasName("b"))))))) /// matches "int a[b]" AST_MATCHER_P(VariableArrayType, hasSizeExpr, internal::Matcher<Expr>, InnerMatcher) { return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder); } /// Matches atomic types. /// /// Given /// \code /// _Atomic(int) i; /// \endcode /// atomicType() /// matches "_Atomic(int) i" extern const AstTypeMatcher<AtomicType> atomicType; /// Matches atomic types with a specific value type. /// /// Given /// \code /// _Atomic(int) i; /// _Atomic(float) f; /// \endcode /// atomicType(hasValueType(isInteger())) /// matches "_Atomic(int) i" /// /// Usable as: Matcher<AtomicType> AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasValueType, getValue, AST_POLYMORPHIC_SUPPORTED_TYPES(AtomicType)); /// Matches types nodes representing C++11 auto types. /// /// Given: /// \code /// auto n = 4; /// int v[] = { 2, 3 } /// for (auto i : v) { } /// \endcode /// autoType() /// matches "auto n" and "auto i" extern const AstTypeMatcher<AutoType> autoType; /// Matches types nodes representing C++11 decltype(<expr>) types. /// /// Given: /// \code /// short i = 1; /// int j = 42; /// decltype(i + j) result = i + j; /// \endcode /// decltypeType() /// matches "decltype(i + j)" extern const AstTypeMatcher<DecltypeType> decltypeType; /// Matches \c AutoType nodes where the deduced type is a specific type. /// /// Note: There is no \c TypeLoc for the deduced type and thus no /// \c getDeducedLoc() matcher. /// /// Given /// \code /// auto a = 1; /// auto b = 2.0; /// \endcode /// autoType(hasDeducedType(isInteger())) /// matches "auto a" /// /// Usable as: Matcher<AutoType> AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType, AST_POLYMORPHIC_SUPPORTED_TYPES(AutoType)); /// Matches \c DecltypeType nodes to find out the underlying type. /// /// Given /// \code /// decltype(1) a = 1; /// decltype(2.0) b = 2.0; /// \endcode /// decltypeType(hasUnderlyingType(isInteger())) /// matches the type of "a" /// /// Usable as: Matcher<DecltypeType> AST_TYPE_TRAVERSE_MATCHER(hasUnderlyingType, getUnderlyingType, AST_POLYMORPHIC_SUPPORTED_TYPES(DecltypeType)); /// Matches \c FunctionType nodes. /// /// Given /// \code /// int (*f)(int); /// void g(); /// \endcode /// functionType() /// matches "int (*f)(int)" and the type of "g". extern const AstTypeMatcher<FunctionType> functionType; /// Matches \c FunctionProtoType nodes. /// /// Given /// \code /// int (*f)(int); /// void g(); /// \endcode /// functionProtoType() /// matches "int (*f)(int)" and the type of "g" in C++ mode. /// In C mode, "g" is not matched because it does not contain a prototype. extern const AstTypeMatcher<FunctionProtoType> functionProtoType; /// Matches \c ParenType nodes. /// /// Given /// \code /// int (*ptr_to_array)[4]; /// int *array_of_ptrs[4]; /// \endcode /// /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not /// \c array_of_ptrs. extern const AstTypeMatcher<ParenType> parenType; /// Matches \c ParenType nodes where the inner type is a specific type. /// /// Given /// \code /// int (*ptr_to_array)[4]; /// int (*ptr_to_func)(int); /// \endcode /// /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches /// \c ptr_to_func but not \c ptr_to_array. /// /// Usable as: Matcher<ParenType> AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType, AST_POLYMORPHIC_SUPPORTED_TYPES(ParenType)); /// Matches block pointer types, i.e. types syntactically represented as /// "void (^)(int)". /// /// The \c pointee is always required to be a \c FunctionType. extern const AstTypeMatcher<BlockPointerType> blockPointerType; /// Matches member pointer types. /// Given /// \code /// struct A { int i; } /// A::* ptr = A::i; /// \endcode /// memberPointerType() /// matches "A::* ptr" extern const AstTypeMatcher<MemberPointerType> memberPointerType; /// Matches pointer types, but does not match Objective-C object pointer /// types. /// /// Given /// \code /// int *a; /// int &b = *a; /// int c = 5; /// /// @interface Foo /// @end /// Foo *f; /// \endcode /// pointerType() /// matches "int *a", but does not match "Foo *f". extern const AstTypeMatcher<PointerType> pointerType; /// Matches an Objective-C object pointer type, which is different from /// a pointer type, despite being syntactically similar. /// /// Given /// \code /// int *a; /// /// @interface Foo /// @end /// Foo *f; /// \endcode /// pointerType() /// matches "Foo *f", but does not match "int *a". extern const AstTypeMatcher<ObjCObjectPointerType> objcObjectPointerType; /// Matches both lvalue and rvalue reference types. /// /// Given /// \code /// int *a; /// int &b = *a; /// int &&c = 1; /// auto &d = b; /// auto &&e = c; /// auto &&f = 2; /// int g = 5; /// \endcode /// /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f. extern const AstTypeMatcher<ReferenceType> referenceType; /// Matches lvalue reference types. /// /// Given: /// \code /// int *a; /// int &b = *a; /// int &&c = 1; /// auto &d = b; /// auto &&e = c; /// auto &&f = 2; /// int g = 5; /// \endcode /// /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is /// matched since the type is deduced as int& by reference collapsing rules. extern const AstTypeMatcher<LValueReferenceType> lValueReferenceType; /// Matches rvalue reference types. /// /// Given: /// \code /// int *a; /// int &b = *a; /// int &&c = 1; /// auto &d = b; /// auto &&e = c; /// auto &&f = 2; /// int g = 5; /// \endcode /// /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not /// matched as it is deduced to int& by reference collapsing rules. extern const AstTypeMatcher<RValueReferenceType> rValueReferenceType; /// Narrows PointerType (and similar) matchers to those where the /// \c pointee matches a given matcher. /// /// Given /// \code /// int *a; /// int const *b; /// float const *f; /// \endcode /// pointerType(pointee(isConstQualified(), isInteger())) /// matches "int const *b" /// /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>, /// Matcher<PointerType>, Matcher<ReferenceType> AST_TYPELOC_TRAVERSE_MATCHER_DECL( pointee, getPointee, AST_POLYMORPHIC_SUPPORTED_TYPES(BlockPointerType, MemberPointerType, PointerType, ReferenceType)); /// Matches typedef types. /// /// Given /// \code /// typedef int X; /// \endcode /// typedefType() /// matches "typedef int X" extern const AstTypeMatcher<TypedefType> typedefType; /// Matches enum types. /// /// Given /// \code /// enum C { Green }; /// enum class S { Red }; /// /// C c; /// S s; /// \endcode // /// \c enumType() matches the type of the variable declarations of both \c c and /// \c s. extern const AstTypeMatcher<EnumType> enumType; /// Matches template specialization types. /// /// Given /// \code /// template <typename T> /// class C { }; /// /// template class C<int>; // A /// C<char> var; // B /// \endcode /// /// \c templateSpecializationType() matches the type of the explicit /// instantiation in \c A and the type of the variable declaration in \c B. extern const AstTypeMatcher<TemplateSpecializationType> templateSpecializationType; /// Matches C++17 deduced template specialization types, e.g. deduced class /// template types. /// /// Given /// \code /// template <typename T> /// class C { public: C(T); }; /// /// C c(123); /// \endcode /// \c deducedTemplateSpecializationType() matches the type in the declaration /// of the variable \c c. extern const AstTypeMatcher<DeducedTemplateSpecializationType> deducedTemplateSpecializationType; /// Matches types nodes representing unary type transformations. /// /// Given: /// \code /// typedef __underlying_type(T) type; /// \endcode /// unaryTransformType() /// matches "__underlying_type(T)" extern const AstTypeMatcher<UnaryTransformType> unaryTransformType; /// Matches record types (e.g. structs, classes). /// /// Given /// \code /// class C {}; /// struct S {}; /// /// C c; /// S s; /// \endcode /// /// \c recordType() matches the type of the variable declarations of both \c c /// and \c s. extern const AstTypeMatcher<RecordType> recordType; /// Matches tag types (record and enum types). /// /// Given /// \code /// enum E {}; /// class C {}; /// /// E e; /// C c; /// \endcode /// /// \c tagType() matches the type of the variable declarations of both \c e /// and \c c. extern const AstTypeMatcher<TagType> tagType; /// Matches types specified with an elaborated type keyword or with a /// qualified name. /// /// Given /// \code /// namespace N { /// namespace M { /// class D {}; /// } /// } /// class C {}; /// /// class C c; /// N::M::D d; /// \endcode /// /// \c elaboratedType() matches the type of the variable declarations of both /// \c c and \c d. extern const AstTypeMatcher<ElaboratedType> elaboratedType; /// Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier, /// matches \c InnerMatcher if the qualifier exists. /// /// Given /// \code /// namespace N { /// namespace M { /// class D {}; /// } /// } /// N::M::D d; /// \endcode /// /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))) /// matches the type of the variable declaration of \c d. AST_MATCHER_P(ElaboratedType, hasQualifier, internal::Matcher<NestedNameSpecifier>, InnerMatcher) { if (const NestedNameSpecifier *Qualifier = Node.getQualifier()) return InnerMatcher.matches(*Qualifier, Finder, Builder); return false; } /// Matches ElaboratedTypes whose named type matches \c InnerMatcher. /// /// Given /// \code /// namespace N { /// namespace M { /// class D {}; /// } /// } /// N::M::D d; /// \endcode /// /// \c elaboratedType(namesType(recordType( /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable /// declaration of \c d. AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>, InnerMatcher) { return InnerMatcher.matches(Node.getNamedType(), Finder, Builder); } /// Matches types that represent the result of substituting a type for a /// template type parameter. /// /// Given /// \code /// template <typename T> /// void F(T t) { /// int i = 1 + t; /// } /// \endcode /// /// \c substTemplateTypeParmType() matches the type of 't' but not '1' extern const AstTypeMatcher<SubstTemplateTypeParmType> substTemplateTypeParmType; /// Matches template type parameter substitutions that have a replacement /// type that matches the provided matcher. /// /// Given /// \code /// template <typename T> /// double F(T t); /// int i; /// double j = F(i); /// \endcode /// /// \c substTemplateTypeParmType(hasReplacementType(type())) matches int AST_TYPE_TRAVERSE_MATCHER( hasReplacementType, getReplacementType, AST_POLYMORPHIC_SUPPORTED_TYPES(SubstTemplateTypeParmType)); /// Matches template type parameter types. /// /// Example matches T, but not int. /// (matcher = templateTypeParmType()) /// \code /// template <typename T> void f(int i); /// \endcode extern const AstTypeMatcher<TemplateTypeParmType> templateTypeParmType; /// Matches injected class name types. /// /// Example matches S s, but not S<T> s. /// (matcher = parmVarDecl(hasType(injectedClassNameType()))) /// \code /// template <typename T> struct S { /// void f(S s); /// void g(S<T> s); /// }; /// \endcode extern const AstTypeMatcher<InjectedClassNameType> injectedClassNameType; /// Matches decayed type /// Example matches i[] in declaration of f. /// (matcher = valueDecl(hasType(decayedType(hasDecayedType(pointerType()))))) /// Example matches i[1]. /// (matcher = expr(hasType(decayedType(hasDecayedType(pointerType()))))) /// \code /// void f(int i[]) { /// i[1] = 0; /// } /// \endcode extern const AstTypeMatcher<DecayedType> decayedType; /// Matches the decayed type, whoes decayed type matches \c InnerMatcher AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>, InnerType) { return InnerType.matches(Node.getDecayedType(), Finder, Builder); } /// Matches declarations whose declaration context, interpreted as a /// Decl, matches \c InnerMatcher. /// /// Given /// \code /// namespace N { /// namespace M { /// class D {}; /// } /// } /// \endcode /// /// \c cxxRcordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the /// declaration of \c class \c D. AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) { const DeclContext *DC = Node.getDeclContext(); if (!DC) return false; return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder); } /// Matches nested name specifiers. /// /// Given /// \code /// namespace ns { /// struct A { static void f(); }; /// void A::f() {} /// void g() { A::f(); } /// } /// ns::A a; /// \endcode /// nestedNameSpecifier() /// matches "ns::" and both "A::" extern const internal::VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier; /// Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc. extern const internal::VariadicAllOfMatcher<NestedNameSpecifierLoc> nestedNameSpecifierLoc; /// Matches \c NestedNameSpecifierLocs for which the given inner /// NestedNameSpecifier-matcher matches. AST_MATCHER_FUNCTION_P_OVERLOAD( internal::BindableMatcher<NestedNameSpecifierLoc>, loc, internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) { return internal::BindableMatcher<NestedNameSpecifierLoc>( new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>( InnerMatcher)); } /// Matches nested name specifiers that specify a type matching the /// given \c QualType matcher without qualifiers. /// /// Given /// \code /// struct A { struct B { struct C {}; }; }; /// A::B::C c; /// \endcode /// nestedNameSpecifier(specifiesType( /// hasDeclaration(cxxRecordDecl(hasName("A"))) /// )) /// matches "A::" AST_MATCHER_P(NestedNameSpecifier, specifiesType, internal::Matcher<QualType>, InnerMatcher) { if (!Node.getAsType()) return false; return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder); } /// Matches nested name specifier locs that specify a type matching the /// given \c TypeLoc. /// /// Given /// \code /// struct A { struct B { struct C {}; }; }; /// A::B::C c; /// \endcode /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type( /// hasDeclaration(cxxRecordDecl(hasName("A"))))))) /// matches "A::" AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc, internal::Matcher<TypeLoc>, InnerMatcher) { return Node && Node.getNestedNameSpecifier()->getAsType() && InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder); } /// Matches on the prefix of a \c NestedNameSpecifier. /// /// Given /// \code /// struct A { struct B { struct C {}; }; }; /// A::B::C c; /// \endcode /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and /// matches "A::" AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix, internal::Matcher<NestedNameSpecifier>, InnerMatcher, 0) { const NestedNameSpecifier *NextNode = Node.getPrefix(); if (!NextNode) return false; return InnerMatcher.matches(*NextNode, Finder, Builder); } /// Matches on the prefix of a \c NestedNameSpecifierLoc. /// /// Given /// \code /// struct A { struct B { struct C {}; }; }; /// A::B::C c; /// \endcode /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A"))))) /// matches "A::" AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix, internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher, 1) { NestedNameSpecifierLoc NextNode = Node.getPrefix(); if (!NextNode) return false; return InnerMatcher.matches(NextNode, Finder, Builder); } /// Matches nested name specifiers that specify a namespace matching the /// given namespace matcher. /// /// Given /// \code /// namespace ns { struct A {}; } /// ns::A a; /// \endcode /// nestedNameSpecifier(specifiesNamespace(hasName("ns"))) /// matches "ns::" AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace, internal::Matcher<NamespaceDecl>, InnerMatcher) { if (!Node.getAsNamespace()) return false; return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder); } /// Matches attributes. /// Attributes may be attached with a variety of different syntaxes (including /// keywords, C++11 attributes, GNU ``__attribute``` and MSVC `__declspec``, /// and ``#pragma``s). They may also be implicit. /// /// Given /// \code /// struct [[nodiscard]] Foo{}; /// void bar(int * __attribute__((nonnull)) ); /// __declspec(noinline) void baz(); /// /// #pragma omp declare simd /// int min(); /// \endcode /// attr() /// matches "nodiscard", "nonnull", "noinline", and the whole "#pragma" line. extern const internal::VariadicAllOfMatcher<Attr> attr; /// Overloads for the \c equalsNode matcher. /// FIXME: Implement for other node types. /// @{ /// Matches if a node equals another node. /// /// \c Decl has pointer identity in the AST. AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) { return &Node == Other; } /// Matches if a node equals another node. /// /// \c Stmt has pointer identity in the AST. AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) { return &Node == Other; } /// Matches if a node equals another node. /// /// \c Type has pointer identity in the AST. AST_MATCHER_P_OVERLOAD(Type, equalsNode, const Type*, Other, 2) { return &Node == Other; } /// @} /// Matches each case or default statement belonging to the given switch /// statement. This matcher may produce multiple matches. /// /// Given /// \code /// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } } /// \endcode /// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s") /// matches four times, with "c" binding each of "case 1:", "case 2:", /// "case 3:" and "case 4:", and "s" respectively binding "switch (1)", /// "switch (1)", "switch (2)" and "switch (2)". AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>, InnerMatcher) { BoundNodesTreeBuilder Result; // FIXME: getSwitchCaseList() does not necessarily guarantee a stable // iteration order. We should use the more general iterating matchers once // they are capable of expressing this matcher (for example, it should ignore // case statements belonging to nested switch statements). bool Matched = false; for (const SwitchCase *SC = Node.getSwitchCaseList(); SC; SC = SC->getNextSwitchCase()) { BoundNodesTreeBuilder CaseBuilder(*Builder); bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder); if (CaseMatched) { Matched = true; Result.addMatch(CaseBuilder); } } *Builder = std::move(Result); return Matched; } /// Matches each constructor initializer in a constructor definition. /// /// Given /// \code /// class A { A() : i(42), j(42) {} int i; int j; }; /// \endcode /// cxxConstructorDecl(forEachConstructorInitializer( /// forField(decl().bind("x")) /// )) /// will trigger two matches, binding for 'i' and 'j' respectively. AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer, internal::Matcher<CXXCtorInitializer>, InnerMatcher) { BoundNodesTreeBuilder Result; bool Matched = false; for (const auto *I : Node.inits()) { if (Finder->isTraversalIgnoringImplicitNodes() && !I->isWritten()) continue; BoundNodesTreeBuilder InitBuilder(*Builder); if (InnerMatcher.matches(*I, Finder, &InitBuilder)) { Matched = true; Result.addMatch(InitBuilder); } } *Builder = std::move(Result); return Matched; } /// Matches constructor declarations that are copy constructors. /// /// Given /// \code /// struct S { /// S(); // #1 /// S(const S &); // #2 /// S(S &&); // #3 /// }; /// \endcode /// cxxConstructorDecl(isCopyConstructor()) will match #2, but not #1 or #3. AST_MATCHER(CXXConstructorDecl, isCopyConstructor) { return Node.isCopyConstructor(); } /// Matches constructor declarations that are move constructors. /// /// Given /// \code /// struct S { /// S(); // #1 /// S(const S &); // #2 /// S(S &&); // #3 /// }; /// \endcode /// cxxConstructorDecl(isMoveConstructor()) will match #3, but not #1 or #2. AST_MATCHER(CXXConstructorDecl, isMoveConstructor) { return Node.isMoveConstructor(); } /// Matches constructor declarations that are default constructors. /// /// Given /// \code /// struct S { /// S(); // #1 /// S(const S &); // #2 /// S(S &&); // #3 /// }; /// \endcode /// cxxConstructorDecl(isDefaultConstructor()) will match #1, but not #2 or #3. AST_MATCHER(CXXConstructorDecl, isDefaultConstructor) { return Node.isDefaultConstructor(); } /// Matches constructors that delegate to another constructor. /// /// Given /// \code /// struct S { /// S(); // #1 /// S(int) {} // #2 /// S(S &&) : S() {} // #3 /// }; /// S::S() : S(0) {} // #4 /// \endcode /// cxxConstructorDecl(isDelegatingConstructor()) will match #3 and #4, but not /// #1 or #2. AST_MATCHER(CXXConstructorDecl, isDelegatingConstructor) { return Node.isDelegatingConstructor(); } /// Matches constructor, conversion function, and deduction guide declarations /// that have an explicit specifier if this explicit specifier is resolved to /// true. /// /// Given /// \code /// template<bool b> /// struct S { /// S(int); // #1 /// explicit S(double); // #2 /// operator int(); // #3 /// explicit operator bool(); // #4 /// explicit(false) S(bool) // # 7 /// explicit(true) S(char) // # 8 /// explicit(b) S(S) // # 9 /// }; /// S(int) -> S<true> // #5 /// explicit S(double) -> S<false> // #6 /// \endcode /// cxxConstructorDecl(isExplicit()) will match #2 and #8, but not #1, #7 or #9. /// cxxConversionDecl(isExplicit()) will match #4, but not #3. /// cxxDeductionGuideDecl(isExplicit()) will match #6, but not #5. AST_POLYMORPHIC_MATCHER(isExplicit, AST_POLYMORPHIC_SUPPORTED_TYPES( CXXConstructorDecl, CXXConversionDecl, CXXDeductionGuideDecl)) { return Node.isExplicit(); } /// Matches the expression in an explicit specifier if present in the given /// declaration. /// /// Given /// \code /// template<bool b> /// struct S { /// S(int); // #1 /// explicit S(double); // #2 /// operator int(); // #3 /// explicit operator bool(); // #4 /// explicit(false) S(bool) // # 7 /// explicit(true) S(char) // # 8 /// explicit(b) S(S) // # 9 /// }; /// S(int) -> S<true> // #5 /// explicit S(double) -> S<false> // #6 /// \endcode /// cxxConstructorDecl(hasExplicitSpecifier(constantExpr())) will match #7, #8 and #9, but not #1 or #2. /// cxxConversionDecl(hasExplicitSpecifier(constantExpr())) will not match #3 or #4. /// cxxDeductionGuideDecl(hasExplicitSpecifier(constantExpr())) will not match #5 or #6. AST_MATCHER_P(FunctionDecl, hasExplicitSpecifier, internal::Matcher<Expr>, InnerMatcher) { ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(&Node); if (!ES.getExpr()) return false; ASTChildrenNotSpelledInSourceScope RAII(Finder, false); return InnerMatcher.matches(*ES.getExpr(), Finder, Builder); } /// Matches function and namespace declarations that are marked with /// the inline keyword. /// /// Given /// \code /// inline void f(); /// void g(); /// namespace n { /// inline namespace m {} /// } /// \endcode /// functionDecl(isInline()) will match ::f(). /// namespaceDecl(isInline()) will match n::m. AST_POLYMORPHIC_MATCHER(isInline, AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl, FunctionDecl)) { // This is required because the spelling of the function used to determine // whether inline is specified or not differs between the polymorphic types. if (const auto *FD = dyn_cast<FunctionDecl>(&Node)) return FD->isInlineSpecified(); else if (const auto *NSD = dyn_cast<NamespaceDecl>(&Node)) return NSD->isInline(); llvm_unreachable("Not a valid polymorphic type"); } /// Matches anonymous namespace declarations. /// /// Given /// \code /// namespace n { /// namespace {} // #1 /// } /// \endcode /// namespaceDecl(isAnonymous()) will match #1 but not ::n. AST_MATCHER(NamespaceDecl, isAnonymous) { return Node.isAnonymousNamespace(); } /// Matches declarations in the namespace `std`, but not in nested namespaces. /// /// Given /// \code /// class vector {}; /// namespace foo { /// class vector {}; /// namespace std { /// class vector {}; /// } /// } /// namespace std { /// inline namespace __1 { /// class vector {}; // #1 /// namespace experimental { /// class vector {}; /// } /// } /// } /// \endcode /// cxxRecordDecl(hasName("vector"), isInStdNamespace()) will match only #1. AST_MATCHER(Decl, isInStdNamespace) { return Node.isInStdNamespace(); } /// If the given case statement does not use the GNU case range /// extension, matches the constant given in the statement. /// /// Given /// \code /// switch (1) { case 1: case 1+1: case 3 ... 4: ; } /// \endcode /// caseStmt(hasCaseConstant(integerLiteral())) /// matches "case 1:" AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>, InnerMatcher) { if (Node.getRHS()) return false; return InnerMatcher.matches(*Node.getLHS(), Finder, Builder); } /// Matches declaration that has a given attribute. /// /// Given /// \code /// __attribute__((device)) void f() { ... } /// \endcode /// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of /// f. If the matcher is used from clang-query, attr::Kind parameter should be /// passed as a quoted string. e.g., hasAttr("attr::CUDADevice"). AST_MATCHER_P(Decl, hasAttr, attr::Kind, AttrKind) { for (const auto *Attr : Node.attrs()) { if (Attr->getKind() == AttrKind) return true; } return false; } /// Matches the return value expression of a return statement /// /// Given /// \code /// return a + b; /// \endcode /// hasReturnValue(binaryOperator()) /// matches 'return a + b' /// with binaryOperator() /// matching 'a + b' AST_MATCHER_P(ReturnStmt, hasReturnValue, internal::Matcher<Expr>, InnerMatcher) { if (const auto *RetValue = Node.getRetValue()) return InnerMatcher.matches(*RetValue, Finder, Builder); return false; } /// Matches CUDA kernel call expression. /// /// Example matches, /// \code /// kernel<<<i,j>>>(); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CUDAKernelCallExpr> cudaKernelCallExpr; /// Matches expressions that resolve to a null pointer constant, such as /// GNU's __null, C++11's nullptr, or C's NULL macro. /// /// Given: /// \code /// void *v1 = NULL; /// void *v2 = nullptr; /// void *v3 = __null; // GNU extension /// char *cp = (char *)0; /// int *ip = 0; /// int i = 0; /// \endcode /// expr(nullPointerConstant()) /// matches the initializer for v1, v2, v3, cp, and ip. Does not match the /// initializer for i. AST_MATCHER_FUNCTION(internal::Matcher<Expr>, nullPointerConstant) { return anyOf( gnuNullExpr(), cxxNullPtrLiteralExpr(), integerLiteral(equals(0), hasParent(expr(hasType(pointerType()))))); } /// Matches the DecompositionDecl the binding belongs to. /// /// For example, in: /// \code /// void foo() /// { /// int arr[3]; /// auto &[f, s, t] = arr; /// /// f = 42; /// } /// \endcode /// The matcher: /// \code /// bindingDecl(hasName("f"), /// forDecomposition(decompositionDecl()) /// \endcode /// matches 'f' in 'auto &[f, s, t]'. AST_MATCHER_P(BindingDecl, forDecomposition, internal::Matcher<ValueDecl>, InnerMatcher) { if (const ValueDecl *VD = Node.getDecomposedDecl()) return InnerMatcher.matches(*VD, Finder, Builder); return false; } /// Matches the Nth binding of a DecompositionDecl. /// /// For example, in: /// \code /// void foo() /// { /// int arr[3]; /// auto &[f, s, t] = arr; /// /// f = 42; /// } /// \endcode /// The matcher: /// \code /// decompositionDecl(hasBinding(0, /// bindingDecl(hasName("f").bind("fBinding")))) /// \endcode /// matches the decomposition decl with 'f' bound to "fBinding". AST_MATCHER_P2(DecompositionDecl, hasBinding, unsigned, N, internal::Matcher<BindingDecl>, InnerMatcher) { if (Node.bindings().size() <= N) return false; return InnerMatcher.matches(*Node.bindings()[N], Finder, Builder); } /// Matches any binding of a DecompositionDecl. /// /// For example, in: /// \code /// void foo() /// { /// int arr[3]; /// auto &[f, s, t] = arr; /// /// f = 42; /// } /// \endcode /// The matcher: /// \code /// decompositionDecl(hasAnyBinding(bindingDecl(hasName("f").bind("fBinding")))) /// \endcode /// matches the decomposition decl with 'f' bound to "fBinding". AST_MATCHER_P(DecompositionDecl, hasAnyBinding, internal::Matcher<BindingDecl>, InnerMatcher) { return llvm::any_of(Node.bindings(), [&](const auto *Binding) { return InnerMatcher.matches(*Binding, Finder, Builder); }); } /// Matches declaration of the function the statement belongs to. /// /// Deprecated. Use forCallable() to correctly handle the situation when /// the declaration is not a function (but a block or an Objective-C method). /// forFunction() not only fails to take non-functions into account but also /// may match the wrong declaration in their presence. /// /// Given: /// \code /// F& operator=(const F& o) { /// std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; }); /// return *this; /// } /// \endcode /// returnStmt(forFunction(hasName("operator="))) /// matches 'return *this' /// but does not match 'return v > 0' AST_MATCHER_P(Stmt, forFunction, internal::Matcher<FunctionDecl>, InnerMatcher) { const auto &Parents = Finder->getASTContext().getParents(Node); llvm::SmallVector<DynTypedNode, 8> Stack(Parents.begin(), Parents.end()); while (!Stack.empty()) { const auto &CurNode = Stack.back(); Stack.pop_back(); if (const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) { if (InnerMatcher.matches(*FuncDeclNode, Finder, Builder)) { return true; } } else if (const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) { if (InnerMatcher.matches(*LambdaExprNode->getCallOperator(), Finder, Builder)) { return true; } } else { for (const auto &Parent : Finder->getASTContext().getParents(CurNode)) Stack.push_back(Parent); } } return false; } /// Matches declaration of the function, method, or block the statement /// belongs to. /// /// Given: /// \code /// F& operator=(const F& o) { /// std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; }); /// return *this; /// } /// \endcode /// returnStmt(forCallable(functionDecl(hasName("operator=")))) /// matches 'return *this' /// but does not match 'return v > 0' /// /// Given: /// \code /// -(void) foo { /// int x = 1; /// dispatch_sync(queue, ^{ int y = 2; }); /// } /// \endcode /// declStmt(forCallable(objcMethodDecl())) /// matches 'int x = 1' /// but does not match 'int y = 2'. /// whereas declStmt(forCallable(blockDecl())) /// matches 'int y = 2' /// but does not match 'int x = 1'. AST_MATCHER_P(Stmt, forCallable, internal::Matcher<Decl>, InnerMatcher) { const auto &Parents = Finder->getASTContext().getParents(Node); llvm::SmallVector<DynTypedNode, 8> Stack(Parents.begin(), Parents.end()); while (!Stack.empty()) { const auto &CurNode = Stack.back(); Stack.pop_back(); if (const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) { if (InnerMatcher.matches(*FuncDeclNode, Finder, Builder)) { return true; } } else if (const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) { if (InnerMatcher.matches(*LambdaExprNode->getCallOperator(), Finder, Builder)) { return true; } } else if (const auto *ObjCMethodDeclNode = CurNode.get<ObjCMethodDecl>()) { if (InnerMatcher.matches(*ObjCMethodDeclNode, Finder, Builder)) { return true; } } else if (const auto *BlockDeclNode = CurNode.get<BlockDecl>()) { if (InnerMatcher.matches(*BlockDeclNode, Finder, Builder)) { return true; } } else { for (const auto &Parent : Finder->getASTContext().getParents(CurNode)) Stack.push_back(Parent); } } return false; } /// Matches a declaration that has external formal linkage. /// /// Example matches only z (matcher = varDecl(hasExternalFormalLinkage())) /// \code /// void f() { /// int x; /// static int y; /// } /// int z; /// \endcode /// /// Example matches f() because it has external formal linkage despite being /// unique to the translation unit as though it has internal likage /// (matcher = functionDecl(hasExternalFormalLinkage())) /// /// \code /// namespace { /// void f() {} /// } /// \endcode AST_MATCHER(NamedDecl, hasExternalFormalLinkage) { return Node.hasExternalFormalLinkage(); } /// Matches a declaration that has default arguments. /// /// Example matches y (matcher = parmVarDecl(hasDefaultArgument())) /// \code /// void x(int val) {} /// void y(int val = 0) {} /// \endcode /// /// Deprecated. Use hasInitializer() instead to be able to /// match on the contents of the default argument. For example: /// /// \code /// void x(int val = 7) {} /// void y(int val = 42) {} /// \endcode /// parmVarDecl(hasInitializer(integerLiteral(equals(42)))) /// matches the parameter of y /// /// A matcher such as /// parmVarDecl(hasInitializer(anything())) /// is equivalent to parmVarDecl(hasDefaultArgument()). AST_MATCHER(ParmVarDecl, hasDefaultArgument) { return Node.hasDefaultArg(); } /// Matches array new expressions. /// /// Given: /// \code /// MyClass *p1 = new MyClass[10]; /// \endcode /// cxxNewExpr(isArray()) /// matches the expression 'new MyClass[10]'. AST_MATCHER(CXXNewExpr, isArray) { return Node.isArray(); } /// Matches placement new expression arguments. /// /// Given: /// \code /// MyClass *p1 = new (Storage, 16) MyClass(); /// \endcode /// cxxNewExpr(hasPlacementArg(1, integerLiteral(equals(16)))) /// matches the expression 'new (Storage, 16) MyClass()'. AST_MATCHER_P2(CXXNewExpr, hasPlacementArg, unsigned, Index, internal::Matcher<Expr>, InnerMatcher) { return Node.getNumPlacementArgs() > Index && InnerMatcher.matches(*Node.getPlacementArg(Index), Finder, Builder); } /// Matches any placement new expression arguments. /// /// Given: /// \code /// MyClass *p1 = new (Storage) MyClass(); /// \endcode /// cxxNewExpr(hasAnyPlacementArg(anything())) /// matches the expression 'new (Storage, 16) MyClass()'. AST_MATCHER_P(CXXNewExpr, hasAnyPlacementArg, internal::Matcher<Expr>, InnerMatcher) { return llvm::any_of(Node.placement_arguments(), [&](const Expr *Arg) { return InnerMatcher.matches(*Arg, Finder, Builder); }); } /// Matches array new expressions with a given array size. /// /// Given: /// \code /// MyClass *p1 = new MyClass[10]; /// \endcode /// cxxNewExpr(hasArraySize(integerLiteral(equals(10)))) /// matches the expression 'new MyClass[10]'. AST_MATCHER_P(CXXNewExpr, hasArraySize, internal::Matcher<Expr>, InnerMatcher) { return Node.isArray() && *Node.getArraySize() && InnerMatcher.matches(**Node.getArraySize(), Finder, Builder); } /// Matches a class declaration that is defined. /// /// Example matches x (matcher = cxxRecordDecl(hasDefinition())) /// \code /// class x {}; /// class y; /// \endcode AST_MATCHER(CXXRecordDecl, hasDefinition) { return Node.hasDefinition(); } /// Matches C++11 scoped enum declaration. /// /// Example matches Y (matcher = enumDecl(isScoped())) /// \code /// enum X {}; /// enum class Y {}; /// \endcode AST_MATCHER(EnumDecl, isScoped) { return Node.isScoped(); } /// Matches a function declared with a trailing return type. /// /// Example matches Y (matcher = functionDecl(hasTrailingReturn())) /// \code /// int X() {} /// auto Y() -> int {} /// \endcode AST_MATCHER(FunctionDecl, hasTrailingReturn) { if (const auto *F = Node.getType()->getAs<FunctionProtoType>()) return F->hasTrailingReturn(); return false; } /// Matches expressions that match InnerMatcher that are possibly wrapped in an /// elidable constructor and other corresponding bookkeeping nodes. /// /// In C++17, elidable copy constructors are no longer being generated in the /// AST as it is not permitted by the standard. They are, however, part of the /// AST in C++14 and earlier. So, a matcher must abstract over these differences /// to work in all language modes. This matcher skips elidable constructor-call /// AST nodes, `ExprWithCleanups` nodes wrapping elidable constructor-calls and /// various implicit nodes inside the constructor calls, all of which will not /// appear in the C++17 AST. /// /// Given /// /// \code /// struct H {}; /// H G(); /// void f() { /// H D = G(); /// } /// \endcode /// /// ``varDecl(hasInitializer(ignoringElidableConstructorCall(callExpr())))`` /// matches ``H D = G()`` in C++11 through C++17 (and beyond). AST_MATCHER_P(Expr, ignoringElidableConstructorCall, ast_matchers::internal::Matcher<Expr>, InnerMatcher) { // E tracks the node that we are examining. const Expr *E = &Node; // If present, remove an outer `ExprWithCleanups` corresponding to the // underlying `CXXConstructExpr`. This check won't cover all cases of added // `ExprWithCleanups` corresponding to `CXXConstructExpr` nodes (because the // EWC is placed on the outermost node of the expression, which this may not // be), but, it still improves the coverage of this matcher. if (const auto *CleanupsExpr = dyn_cast<ExprWithCleanups>(&Node)) E = CleanupsExpr->getSubExpr(); if (const auto *CtorExpr = dyn_cast<CXXConstructExpr>(E)) { if (CtorExpr->isElidable()) { if (const auto *MaterializeTemp = dyn_cast<MaterializeTemporaryExpr>(CtorExpr->getArg(0))) { return InnerMatcher.matches(*MaterializeTemp->getSubExpr(), Finder, Builder); } } } return InnerMatcher.matches(Node, Finder, Builder); } //----------------------------------------------------------------------------// // OpenMP handling. //----------------------------------------------------------------------------// /// Matches any ``#pragma omp`` executable directive. /// /// Given /// /// \code /// #pragma omp parallel /// #pragma omp parallel default(none) /// #pragma omp taskyield /// \endcode /// /// ``ompExecutableDirective()`` matches ``omp parallel``, /// ``omp parallel default(none)`` and ``omp taskyield``. extern const internal::VariadicDynCastAllOfMatcher<Stmt, OMPExecutableDirective> ompExecutableDirective; /// Matches standalone OpenMP directives, /// i.e., directives that can't have a structured block. /// /// Given /// /// \code /// #pragma omp parallel /// {} /// #pragma omp taskyield /// \endcode /// /// ``ompExecutableDirective(isStandaloneDirective()))`` matches /// ``omp taskyield``. AST_MATCHER(OMPExecutableDirective, isStandaloneDirective) { return Node.isStandaloneDirective(); } /// Matches the structured-block of the OpenMP executable directive /// /// Prerequisite: the executable directive must not be standalone directive. /// If it is, it will never match. /// /// Given /// /// \code /// #pragma omp parallel /// ; /// #pragma omp parallel /// {} /// \endcode /// /// ``ompExecutableDirective(hasStructuredBlock(nullStmt()))`` will match ``;`` AST_MATCHER_P(OMPExecutableDirective, hasStructuredBlock, internal::Matcher<Stmt>, InnerMatcher) { if (Node.isStandaloneDirective()) return false; // Standalone directives have no structured blocks. return InnerMatcher.matches(*Node.getStructuredBlock(), Finder, Builder); } /// Matches any clause in an OpenMP directive. /// /// Given /// /// \code /// #pragma omp parallel /// #pragma omp parallel default(none) /// \endcode /// /// ``ompExecutableDirective(hasAnyClause(anything()))`` matches /// ``omp parallel default(none)``. AST_MATCHER_P(OMPExecutableDirective, hasAnyClause, internal::Matcher<OMPClause>, InnerMatcher) { ArrayRef<OMPClause *> Clauses = Node.clauses(); return matchesFirstInPointerRange(InnerMatcher, Clauses.begin(), Clauses.end(), Finder, Builder) != Clauses.end(); } /// Matches OpenMP ``default`` clause. /// /// Given /// /// \code /// #pragma omp parallel default(none) /// #pragma omp parallel default(shared) /// #pragma omp parallel default(firstprivate) /// #pragma omp parallel /// \endcode /// /// ``ompDefaultClause()`` matches ``default(none)``, ``default(shared)``, and /// ``default(firstprivate)`` extern const internal::VariadicDynCastAllOfMatcher<OMPClause, OMPDefaultClause> ompDefaultClause; /// Matches if the OpenMP ``default`` clause has ``none`` kind specified. /// /// Given /// /// \code /// #pragma omp parallel /// #pragma omp parallel default(none) /// #pragma omp parallel default(shared) /// #pragma omp parallel default(firstprivate) /// \endcode /// /// ``ompDefaultClause(isNoneKind())`` matches only ``default(none)``. AST_MATCHER(OMPDefaultClause, isNoneKind) { return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_none; } /// Matches if the OpenMP ``default`` clause has ``shared`` kind specified. /// /// Given /// /// \code /// #pragma omp parallel /// #pragma omp parallel default(none) /// #pragma omp parallel default(shared) /// #pragma omp parallel default(firstprivate) /// \endcode /// /// ``ompDefaultClause(isSharedKind())`` matches only ``default(shared)``. AST_MATCHER(OMPDefaultClause, isSharedKind) { return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_shared; } /// Matches if the OpenMP ``default`` clause has ``firstprivate`` kind /// specified. /// /// Given /// /// \code /// #pragma omp parallel /// #pragma omp parallel default(none) /// #pragma omp parallel default(shared) /// #pragma omp parallel default(firstprivate) /// \endcode /// /// ``ompDefaultClause(isFirstPrivateKind())`` matches only /// ``default(firstprivate)``. AST_MATCHER(OMPDefaultClause, isFirstPrivateKind) { return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_firstprivate; } /// Matches if the OpenMP directive is allowed to contain the specified OpenMP /// clause kind. /// /// Given /// /// \code /// #pragma omp parallel /// #pragma omp parallel for /// #pragma omp for /// \endcode /// /// `ompExecutableDirective(isAllowedToContainClause(OMPC_default))`` matches /// ``omp parallel`` and ``omp parallel for``. /// /// If the matcher is use from clang-query, ``OpenMPClauseKind`` parameter /// should be passed as a quoted string. e.g., /// ``isAllowedToContainClauseKind("OMPC_default").`` AST_MATCHER_P(OMPExecutableDirective, isAllowedToContainClauseKind, OpenMPClauseKind, CKind) { return llvm::omp::isAllowedClauseForDirective( Node.getDirectiveKind(), CKind, Finder->getASTContext().getLangOpts().OpenMP); } //----------------------------------------------------------------------------// // End OpenMP handling. //----------------------------------------------------------------------------// } // namespace ast_matchers } // namespace clang #endif // LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
DRB054-inneronly2-orig-no.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* Example with loop-carried data dependence at the outer level loop. The inner level loop can be parallelized. */ #include <omp.h> int main() { int i; int j; int n = 100; int m = 100; double b[n][m]; #pragma omp parallel for private (i,j) for (i = 0; i <= n - 1; i += 1) { #pragma omp parallel for private (j) for (j = 0; j <= n - 1; j += 1) { b[i][j] = ((double )(i * j)); } } for (i = 1; i <= n - 1; i += 1) { #pragma omp parallel for private (j) for (j = 1; j <= m - 1; j += 1) { b[i][j] = b[i - 1][j - 1]; } } for (i = 0; i <= n - 1; i += 1) { for (j = 0; j <= n - 1; j += 1) { printf("%lf\n",b[i][j]); } } return 0; }
ark_brusselator1D_omp.c
/*--------------------------------------------------------------- * Programmer(s): Daniel R. Reynolds @ SMU *--------------------------------------------------------------- * SUNDIALS Copyright Start * Copyright (c) 2002-2019, 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 test simulates a brusselator problem from chemical * kinetics. This is n PDE system with 3 components, Y = [u,v,w], * satisfying the equations, * u_t = du*u_xx + a - (w+1)*u + v*u^2 * v_t = dv*v_xx + w*u - v*u^2 * w_t = dw*w_xx + (b-w)/ep - w*u * for t in [0, 80], x in [0, 1], with initial conditions * u(0,x) = a + 0.1*sin(pi*x) * v(0,x) = b/a + 0.1*sin(pi*x) * w(0,x) = b + 0.1*sin(pi*x), * and with stationary boundary conditions, i.e. * u_t(t,0) = u_t(t,1) = 0, * v_t(t,0) = v_t(t,1) = 0, * w_t(t,0) = w_t(t,1) = 0. * Note: these can also be implemented as Dirichlet boundary * conditions with values identical to the initial conditions. * * The spatial derivatives are computed using second-order * centered differences, with the data distributed over N points * on a uniform spatial grid. * * This program solves the problem with the DIRK method, using a * Newton iteration with the band linear solver, and a * user-supplied Jacobian routine. This example uses the OpenMP * vector kernel, and employs OpenMP threading within the * right-hand side and Jacobian construction functions. * * 100 outputs are printed at equal intervals, and run statistics * are printed at the end. *---------------------------------------------------------------*/ /* Header files */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <arkode/arkode_arkstep.h> /* prototypes for ARKStep fcts., consts */ #include <nvector/nvector_openmp.h> /* access to OpenMP N_Vector */ #include <sunmatrix/sunmatrix_band.h> /* access to band SUNMatrix */ #include <sunlinsol/sunlinsol_band.h> /* access to band SUNLinearSolver */ #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 /* accessor macros between (x,v) location and 1D NVector array */ #define IDX(x,v) (3*(x)+v) /* user data structure */ typedef struct { sunindextype N; /* number of intervals */ int nthreads; /* number of OpenMP threads */ realtype dx; /* mesh spacing */ realtype a; /* constant forcing on u */ realtype b; /* steady-state value of w */ realtype du; /* diffusion coeff for u */ realtype dv; /* diffusion coeff for v */ realtype dw; /* diffusion coeff for w */ realtype ep; /* stiffness parameter */ } *UserData; /* User-supplied Functions Called by the Solver */ static int f(realtype t, N_Vector y, N_Vector ydot, void *user_data); static int Jac(realtype t, N_Vector y, N_Vector fy, SUNMatrix J, void *user_data, N_Vector tmp1, N_Vector tmp2, N_Vector tmp3); /* Private helper functions */ static int LaplaceMatrix(realtype c, SUNMatrix Jac, UserData udata); static int ReactionJac(realtype c, N_Vector y, SUNMatrix Jac, UserData udata); /* Private function to check function return values */ static int check_flag(void *flagvalue, const char *funcname, int opt); /* Main Program */ int main(int argc, char *argv[]) { /* general problem parameters */ realtype T0 = RCONST(0.0); /* initial time */ realtype Tf = RCONST(10.0); /* final time */ int Nt = 100; /* total number of output times */ int Nvar = 3; /* number of solution fields */ UserData udata = NULL; realtype *data; sunindextype N = 201; /* spatial mesh size */ realtype a = 0.6; /* problem parameters */ realtype b = 2.0; realtype du = 0.025; realtype dv = 0.025; realtype dw = 0.025; realtype ep = 1.0e-5; /* stiffness parameter */ realtype reltol = 1.0e-6; /* tolerances */ realtype abstol = 1.0e-10; sunindextype NEQ, i; /* general problem variables */ int flag; /* reusable error-checking flag */ N_Vector y = NULL; /* empty vector for storing solution */ N_Vector umask = NULL; /* empty mask vectors for viewing solution components */ N_Vector vmask = NULL; N_Vector wmask = NULL; SUNMatrix A = NULL; /* empty matrix for linear solver */ SUNLinearSolver LS = NULL; /* empty linear solver structure */ void *arkode_mem = NULL; /* empty ARKode memory structure */ realtype pi, t, dTout, tout, u, v, w; FILE *FID, *UFID, *VFID, *WFID; int iout, num_threads; long int nst, nst_a, nfe, nfi, nsetups, nje, nfeLS, nni, ncfn, netf; /* allocate udata structure */ udata = (UserData) malloc(sizeof(*udata)); if (check_flag((void *) udata, "malloc", 2)) return 1; /* set the number of threads to use */ num_threads = 1; /* default value */ #ifdef _OPENMP num_threads = omp_get_max_threads(); /* overwrite with OMP_NUM_THREADS environment variable */ #endif if (argc > 1) /* overwrite with command line value, if supplied */ num_threads = strtol(argv[1], NULL, 0); /* store the inputs in the UserData structure */ udata->N = N; udata->a = a; udata->b = b; udata->du = du; udata->dv = dv; udata->dw = dw; udata->ep = ep; udata->nthreads = num_threads; /* set total allocated vector length */ NEQ = Nvar*udata->N; /* Initial problem output */ printf("\n1D Brusselator PDE test problem:\n"); printf(" N = %li, NEQ = %li\n", (long int) udata->N, (long int) NEQ); printf(" num_threads = %i\n", num_threads); printf(" problem parameters: a = %"GSYM", b = %"GSYM", ep = %"GSYM"\n", udata->a, udata->b, udata->ep); printf(" diffusion coefficients: du = %"GSYM", dv = %"GSYM", dw = %"GSYM"\n", udata->du, udata->dv, udata->dw); printf(" reltol = %.1"ESYM", abstol = %.1"ESYM"\n\n", reltol, abstol); /* Initialize vector data structures */ y = N_VNew_OpenMP(NEQ, num_threads); /* Create vector for solution */ if (check_flag((void *)y, "N_VNew_OpenMP", 0)) return 1; udata->dx = RCONST(1.0)/(N-1); /* set spatial mesh spacing */ data = N_VGetArrayPointer(y); /* Access data array for new NVector y */ if (check_flag((void *)data, "N_VGetArrayPointer", 0)) return 1; umask = N_VNew_OpenMP(NEQ, num_threads); /* Create vector masks */ if (check_flag((void *)umask, "N_VNew_OpenMP", 0)) return 1; vmask = N_VNew_OpenMP(NEQ, num_threads); if (check_flag((void *)vmask, "N_VNew_OpenMP", 0)) return 1; wmask = N_VNew_OpenMP(NEQ, num_threads); if (check_flag((void *)wmask, "N_VNew_OpenMP", 0)) return 1; /* Set initial conditions into y */ pi = RCONST(4.0)*atan(RCONST(1.0)); for (i=0; i<N; i++) { data[IDX(i,0)] = a + RCONST(0.1)*sin(pi*i*udata->dx); /* u */ data[IDX(i,1)] = b/a + RCONST(0.1)*sin(pi*i*udata->dx); /* v */ data[IDX(i,2)] = b + RCONST(0.1)*sin(pi*i*udata->dx); /* w */ } /* Set mask array values for each solution component */ N_VConst(0.0, umask); data = N_VGetArrayPointer(umask); if (check_flag((void *) data, "N_VGetArrayPointer", 0)) return 1; for (i=0; i<N; i++) data[IDX(i,0)] = RCONST(1.0); N_VConst(0.0, vmask); data = N_VGetArrayPointer(vmask); if (check_flag((void *) data, "N_VGetArrayPointer", 0)) return 1; for (i=0; i<N; i++) data[IDX(i,1)] = RCONST(1.0); N_VConst(0.0, wmask); data = N_VGetArrayPointer(wmask); if (check_flag((void *) data, "N_VGetArrayPointer", 0)) return 1; for (i=0; i<N; i++) data[IDX(i,2)] = RCONST(1.0); /* Initialize matrix and linear solver data structures */ A = SUNBandMatrix(NEQ, 4, 4); if (check_flag((void *)A, "SUNBandMatrix", 0)) return 1; LS = SUNLinSol_Band(y, A); if (check_flag((void *)LS, "SUNLinSol_Band", 0)) return 1; /* Call ARKStepCreate to initialize the ARK timestepper module and specify the right-hand side function in y'=f(t,y), the inital time T0, and the initial dependent variable vector y. Note: since this problem is fully implicit, we set f_E to NULL and f_I to f. */ arkode_mem = ARKStepCreate(NULL, f, T0, y); if (check_flag((void *)arkode_mem, "ARKStepCreate", 0)) return 1; /* Set routines */ flag = ARKStepSetUserData(arkode_mem, (void *) udata); /* Pass udata to user functions */ if (check_flag(&flag, "ARKStepSetUserData", 1)) return 1; flag = ARKStepSStolerances(arkode_mem, reltol, abstol); /* Specify tolerances */ if (check_flag(&flag, "ARKStepSStolerances", 1)) return 1; /* Linear solver specification */ flag = ARKStepSetLinearSolver(arkode_mem, LS, A); /* Attach matrix and linear solver */ if (check_flag(&flag, "ARKStepSetLinearSolver", 1)) return 1; flag = ARKStepSetJacFn(arkode_mem, Jac); /* Set the Jacobian routine */ if (check_flag(&flag, "ARKStepSetJacFn", 1)) return 1; /* output spatial mesh to disk */ FID=fopen("bruss_mesh.txt","w"); for (i=0; i<N; i++) fprintf(FID," %.16"ESYM"\n", udata->dx*i); fclose(FID); /* Open output stream for results, access data arrays */ UFID=fopen("bruss_u.txt","w"); VFID=fopen("bruss_v.txt","w"); WFID=fopen("bruss_w.txt","w"); /* output initial condition to disk */ data = N_VGetArrayPointer(y); if (check_flag((void *)data, "N_VGetArrayPointer", 0)) return 1; for (i=0; i<N; i++) fprintf(UFID," %.16"ESYM, data[IDX(i,0)]); for (i=0; i<N; i++) fprintf(VFID," %.16"ESYM, data[IDX(i,1)]); for (i=0; i<N; i++) fprintf(WFID," %.16"ESYM, data[IDX(i,2)]); fprintf(UFID,"\n"); fprintf(VFID,"\n"); fprintf(WFID,"\n"); /* Main time-stepping loop: calls ARKStepEvolve to perform the integration, then prints results. Stops when the final time has been reached */ t = T0; dTout = (Tf-T0)/Nt; tout = T0+dTout; printf(" t ||u||_rms ||v||_rms ||w||_rms\n"); printf(" ----------------------------------------------\n"); for (iout=0; iout<Nt; iout++) { flag = ARKStepEvolve(arkode_mem, tout, y, &t, ARK_NORMAL); /* call integrator */ if (check_flag(&flag, "ARKStepEvolve", 1)) break; u = N_VWL2Norm(y,umask); /* access/print solution statistics */ u = SUNRsqrt(u*u/N); v = N_VWL2Norm(y,vmask); v = SUNRsqrt(v*v/N); w = N_VWL2Norm(y,wmask); w = SUNRsqrt(w*w/N); printf(" %10.6"FSYM" %10.6"FSYM" %10.6"FSYM" %10.6"FSYM"\n", t, u, v, w); if (flag >= 0) { /* successful solve: update output time */ tout += dTout; tout = (tout > Tf) ? Tf : tout; } else { /* unsuccessful solve: break */ fprintf(stderr,"Solver failure, stopping integration\n"); break; } /* output results to disk */ for (i=0; i<N; i++) fprintf(UFID," %.16"ESYM, data[IDX(i,0)]); for (i=0; i<N; i++) fprintf(VFID," %.16"ESYM, data[IDX(i,1)]); for (i=0; i<N; i++) fprintf(WFID," %.16"ESYM, data[IDX(i,2)]); fprintf(UFID,"\n"); fprintf(VFID,"\n"); fprintf(WFID,"\n"); } printf(" ----------------------------------------------\n"); fclose(UFID); fclose(VFID); fclose(WFID); /* Print some final statistics */ flag = ARKStepGetNumSteps(arkode_mem, &nst); check_flag(&flag, "ARKStepGetNumSteps", 1); flag = ARKStepGetNumStepAttempts(arkode_mem, &nst_a); check_flag(&flag, "ARKStepGetNumStepAttempts", 1); flag = ARKStepGetNumRhsEvals(arkode_mem, &nfe, &nfi); check_flag(&flag, "ARKStepGetNumRhsEvals", 1); flag = ARKStepGetNumLinSolvSetups(arkode_mem, &nsetups); check_flag(&flag, "ARKStepGetNumLinSolvSetups", 1); flag = ARKStepGetNumErrTestFails(arkode_mem, &netf); check_flag(&flag, "ARKStepGetNumErrTestFails", 1); flag = ARKStepGetNumNonlinSolvIters(arkode_mem, &nni); check_flag(&flag, "ARKStepGetNumNonlinSolvIters", 1); flag = ARKStepGetNumNonlinSolvConvFails(arkode_mem, &ncfn); check_flag(&flag, "ARKStepGetNumNonlinSolvConvFails", 1); flag = ARKStepGetNumJacEvals(arkode_mem, &nje); check_flag(&flag, "ARKStepGetNumJacEvals", 1); flag = ARKStepGetNumLinRhsEvals(arkode_mem, &nfeLS); check_flag(&flag, "ARKStepGetNumLinRhsEvals", 1); printf("\nFinal Solver Statistics:\n"); printf(" Internal solver steps = %li (attempted = %li)\n", nst, nst_a); printf(" Total RHS evals: Fe = %li, Fi = %li\n", nfe, nfi); printf(" Total linear solver setups = %li\n", nsetups); printf(" Total RHS evals for setting up the linear system = %li\n", nfeLS); printf(" Total number of Jacobian evaluations = %li\n", nje); printf(" Total number of Newton iterations = %li\n", nni); printf(" Total number of nonlinear solver convergence failures = %li\n", ncfn); printf(" Total number of error test failures = %li\n\n", netf); /* Clean up and return with successful completion */ free(udata); /* Free user data */ ARKStepFree(&arkode_mem); /* Free integrator memory */ SUNLinSolFree(LS); /* Free linear solver */ SUNMatDestroy(A); /* Free matrix */ N_VDestroy_OpenMP(y); /* Free vectors */ N_VDestroy_OpenMP(umask); N_VDestroy_OpenMP(vmask); N_VDestroy_OpenMP(wmask); 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) { UserData udata = (UserData) user_data; /* access problem data */ sunindextype N = udata->N; /* set variable shortcuts */ realtype a = udata->a; realtype b = udata->b; realtype ep = udata->ep; realtype du = udata->du; realtype dv = udata->dv; realtype dw = udata->dw; realtype dx = udata->dx; realtype *Ydata=NULL, *dYdata=NULL; realtype uconst, vconst, wconst, u, ul, ur, v, vl, vr, w, wl, wr; sunindextype i; /* clear out ydot (to be careful) */ N_VConst(0.0, ydot); Ydata = N_VGetArrayPointer(y); /* access data arrays */ if (check_flag((void *)Ydata, "N_VGetArrayPointer", 0)) return 1; dYdata = N_VGetArrayPointer(ydot); if (check_flag((void *)dYdata, "N_VGetArrayPointer", 0)) return 1; N_VConst(0.0, ydot); /* initialize ydot to zero */ /* iterate over domain, computing all equations */ uconst = du/dx/dx; vconst = dv/dx/dx; wconst = dw/dx/dx; #pragma omp parallel for default(shared) private(i,u,ul,ur,v,vl,vr,w,wl,wr) schedule(static) num_threads(udata->nthreads) for (i=1; i<N-1; i++) { /* set shortcuts */ u = Ydata[IDX(i,0)]; ul = Ydata[IDX(i-1,0)]; ur = Ydata[IDX(i+1,0)]; v = Ydata[IDX(i,1)]; vl = Ydata[IDX(i-1,1)]; vr = Ydata[IDX(i+1,1)]; w = Ydata[IDX(i,2)]; wl = Ydata[IDX(i-1,2)]; wr = Ydata[IDX(i+1,2)]; /* u_t = du*u_xx + a - (w+1)*u + v*u^2 */ dYdata[IDX(i,0)] = (ul - RCONST(2.0)*u + ur)*uconst + a - (w+RCONST(1.0))*u + v*u*u; /* v_t = dv*v_xx + w*u - v*u^2 */ dYdata[IDX(i,1)] = (vl - RCONST(2.0)*v + vr)*vconst + w*u - v*u*u; /* w_t = dw*w_xx + (b-w)/ep - w*u */ dYdata[IDX(i,2)] = (wl - RCONST(2.0)*w + wr)*wconst + (b-w)/ep - w*u; } /* enforce stationary boundaries */ dYdata[IDX(0,0)] = dYdata[IDX(0,1)] = dYdata[IDX(0,2)] = 0.0; dYdata[IDX(N-1,0)] = dYdata[IDX(N-1,1)] = dYdata[IDX(N-1,2)] = 0.0; return 0; } /* Jacobian routine to compute J(t,y) = df/dy. */ static int Jac(realtype t, N_Vector y, N_Vector fy, SUNMatrix J, void *user_data, N_Vector tmp1, N_Vector tmp2, N_Vector tmp3) { UserData udata = (UserData) user_data; /* access problem data */ SUNMatZero(J); /* Initialize Jacobian to zero */ /* Fill in the Laplace matrix */ if (LaplaceMatrix(RCONST(1.0), J, udata)) { printf("Jacobian calculation error in calling LaplaceMatrix!\n"); return 1; } /* Add in the Jacobian of the reaction terms matrix */ if (ReactionJac(RCONST(1.0), y, J, udata)) { printf("Jacobian calculation error in calling ReactionJac!\n"); return 1; } return 0; } /*------------------------------- * Private helper functions *-------------------------------*/ /* Routine to compute the stiffness matrix from (L*y), scaled by the factor c. We add the result into Jac and do not erase what was already there */ static int LaplaceMatrix(realtype c, SUNMatrix Jac, UserData udata) { sunindextype N = udata->N; /* set shortcuts */ realtype dx = udata->dx; sunindextype i; realtype uconst = c*udata->du/dx/dx; realtype vconst = c*udata->dv/dx/dx; realtype wconst = c*udata->dw/dx/dx; /* iterate over intervals, filling in Jacobian entries */ #pragma omp parallel for default(shared) private(i) schedule(static) num_threads(udata->nthreads) for (i=1; i<N-1; i++) { /* Jacobian of (L*y) at this node */ SM_ELEMENT_B(Jac,IDX(i,0),IDX(i-1,0)) += uconst; SM_ELEMENT_B(Jac,IDX(i,1),IDX(i-1,1)) += vconst; SM_ELEMENT_B(Jac,IDX(i,2),IDX(i-1,2)) += wconst; SM_ELEMENT_B(Jac,IDX(i,0),IDX(i,0)) -= RCONST(2.0)*uconst; SM_ELEMENT_B(Jac,IDX(i,1),IDX(i,1)) -= RCONST(2.0)*vconst; SM_ELEMENT_B(Jac,IDX(i,2),IDX(i,2)) -= RCONST(2.0)*wconst; SM_ELEMENT_B(Jac,IDX(i,0),IDX(i+1,0)) += uconst; SM_ELEMENT_B(Jac,IDX(i,1),IDX(i+1,1)) += vconst; SM_ELEMENT_B(Jac,IDX(i,2),IDX(i+1,2)) += wconst; } return 0; } /* Routine to compute the Jacobian matrix from R(y), scaled by the factor c. We add the result into Jac and do not erase what was already there */ static int ReactionJac(realtype c, N_Vector y, SUNMatrix Jac, UserData udata) { sunindextype N = udata->N; /* set shortcuts */ realtype ep = udata->ep; sunindextype i; realtype u, v, w; realtype *Ydata = N_VGetArrayPointer(y); /* access solution array */ if (check_flag((void *)Ydata, "N_VGetArrayPointer", 0)) return 1; /* iterate over nodes, filling in Jacobian entries */ #pragma omp parallel for default(shared) private(i,u,v,w) schedule(static) num_threads(udata->nthreads) for (i=1; i<N-1; i++) { /* set nodal value shortcuts (shifted index due to start at first interior node) */ u = Ydata[IDX(i,0)]; v = Ydata[IDX(i,1)]; w = Ydata[IDX(i,2)]; /* all vars wrt u */ SM_ELEMENT_B(Jac,IDX(i,0),IDX(i,0)) += c*(RCONST(2.0)*u*v-(w+RCONST(1.0))); SM_ELEMENT_B(Jac,IDX(i,1),IDX(i,0)) += c*(w - RCONST(2.0)*u*v); SM_ELEMENT_B(Jac,IDX(i,2),IDX(i,0)) += c*(-w); /* all vars wrt v */ SM_ELEMENT_B(Jac,IDX(i,0),IDX(i,1)) += c*(u*u); SM_ELEMENT_B(Jac,IDX(i,1),IDX(i,1)) += c*(-u*u); /* all vars wrt w */ SM_ELEMENT_B(Jac,IDX(i,0),IDX(i,2)) += c*(-u); SM_ELEMENT_B(Jac,IDX(i,1),IDX(i,2)) += c*(u); SM_ELEMENT_B(Jac,IDX(i,2),IDX(i,2)) += c*(-RCONST(1.0)/ep - u); } return 0; } /* 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 ----*/
GB_unaryop__identity_uint8_int64.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__identity_uint8_int64 // op(A') function: GB_tran__identity_uint8_int64 // C type: uint8_t // A type: int64_t // cast: uint8_t cij = (uint8_t) aij // unaryop: cij = aij #define GB_ATYPE \ int64_t #define GB_CTYPE \ uint8_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_CASTING(z, x) \ uint8_t z = (uint8_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_UINT8 || GxB_NO_INT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_uint8_int64 ( uint8_t *restrict Cx, const int64_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__identity_uint8_int64 ( 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
openmpsimulator.h
#ifndef LIBGEODECOMP_PARALLELIZATION_OPENMPSIMULATOR_H #define LIBGEODECOMP_PARALLELIZATION_OPENMPSIMULATOR_H // include this file first to avoid clashes of Intel MPI with stdio.h. #include <libgeodecomp/misc/apitraits.h> #include <libgeodecomp/communication/hpxserializationwrapper.h> #include <libgeodecomp/io/writer.h> #include <libgeodecomp/parallelization/serialsimulator.h> #include <libgeodecomp/storage/gridtypeselector.h> #include <libgeodecomp/storage/updatefunctor.h> namespace LibGeoDecomp { /** * OpenMPSimulator is based on SerialSimulator, but is capable of * threading via OpenMP. */ template<typename CELL_TYPE> class OpenMPSimulator : public SerialSimulator<CELL_TYPE> { public: friend class OpenMPSimulatorTest; typedef typename MonolithicSimulator<CELL_TYPE>::GridType GridBaseType; typedef typename MonolithicSimulator<CELL_TYPE>::Topology Topology; typedef typename MonolithicSimulator<CELL_TYPE>::WriterVector WriterVector; typedef typename APITraits::SelectSoA<CELL_TYPE>::Value SupportsSoA; typedef typename GridTypeSelector<CELL_TYPE, Topology, false, SupportsSoA>::Value GridType; typedef typename Steerer<CELL_TYPE>::SteererFeedback SteererFeedback; static const int DIM = Topology::DIM; using SerialSimulator<CELL_TYPE>::NANO_STEPS; using SerialSimulator<CELL_TYPE>::chronometer; using SerialSimulator<CELL_TYPE>::curGrid; using SerialSimulator<CELL_TYPE>::initializer; using SerialSimulator<CELL_TYPE>::newGrid; using SerialSimulator<CELL_TYPE>::simArea; using SerialSimulator<CELL_TYPE>::steerers; using SerialSimulator<CELL_TYPE>::stepNum; using SerialSimulator<CELL_TYPE>::writers; using SerialSimulator<CELL_TYPE>::getStep; using SerialSimulator<CELL_TYPE>::gridDim; /** * creates a OpenMPSimulator with the given initializer. */ explicit OpenMPSimulator( Initializer<CELL_TYPE> *initializer, bool enableFineGrainedParallelism = false) : SerialSimulator<CELL_TYPE>(initializer), enableFineGrainedParallelism(enableFineGrainedParallelism) {} protected: bool enableFineGrainedParallelism; void nanoStep(unsigned nanoStep) { using std::swap; TimeCompute t(&chronometer); UpdateFunctor<CELL_TYPE, UpdateFunctorHelpers::ConcurrencyEnableOpenMP>()( simArea, Coord<DIM>(), Coord<DIM>(), *curGrid, newGrid, nanoStep, UpdateFunctorHelpers::ConcurrencyEnableOpenMP(true, enableFineGrainedParallelism)); swap(curGrid, newGrid); } /** * notifies all registered Writers */ void handleOutput(WriterEvent event) { TimeOutput t(&chronometer); #pragma omp parallel for schedule(dynamic) for (unsigned i = 0; i < writers.size(); i++) { if ((event != WRITER_STEP_FINISHED) || ((getStep() % writers[i]->getPeriod()) == 0)) { writers[i]->stepFinished( *curGrid, getStep(), event); } } } /** * notifies all registered Steerers */ void handleInput(SteererEvent event, SteererFeedback *feedback) { TimeInput t(&chronometer); #pragma omp parallel for schedule(dynamic) for (unsigned i = 0; i < steerers.size(); ++i) { if ((event != STEERER_NEXT_STEP) || (stepNum % steerers[i]->getPeriod() == 0)) { steerers[i]->nextStep(curGrid, simArea, gridDim, getStep(), event, 0, true, feedback); } } } }; } #endif
cpu_ctc.h
#pragma once #include <tuple> #include <cmath> #include <limits> #include <algorithm> #include <numeric> #if !defined(CTC_DISABLE_OMP) && !defined(APPLE) #include <omp.h> #endif #include "ctc_helper.h" template<typename ProbT> class CpuCTC { public: // Noncopyable CpuCTC(int alphabet_size, int minibatch, void* workspace, int num_threads, int blank_label) : alphabet_size_(alphabet_size), minibatch_(minibatch), num_threads_(num_threads), workspace_(workspace), blank_label_(blank_label) { #if defined(CTC_DISABLE_OMP) || defined(APPLE) #else if (num_threads > 0) { omp_set_num_threads(num_threads); } else { num_threads_ = omp_get_max_threads(); } #endif }; CpuCTC(const CpuCTC&) = delete; CpuCTC& operator=(const CpuCTC&) = delete; ctcStatus_t cost_and_grad(const ProbT* const activations, ProbT *grads, ProbT* costs, const int* const flat_labels, const int* const label_lengths, const int* const input_lengths); ctcStatus_t score_forward(const ProbT* const activations, ProbT* costs, const int* const flat_labels, const int* const label_lengths, const int* const input_lengths); private: class CpuCTC_metadata { private: int setup_labels(const int* const labels, int blank_label, int L, int S); public: CpuCTC_metadata(int L, int S, int T, int mb, int alphabet_size, void* workspace, size_t bytes_used, int blank_label, const int* const labels); ProbT* alphas; ProbT* betas; int* labels_w_blanks; int* e_inc; int* s_inc; ProbT* output; int repeats; }; int alphabet_size_; // Number of characters plus blank int minibatch_; int num_threads_; int blank_label_; void* workspace_; void softmax(const ProbT* const activations, ProbT* probs, const int* const input_lengths); std::tuple<ProbT, bool> cost_and_grad_kernel(ProbT *grad, const ProbT* const probs, const int* const labels, int T, int L, int mb, size_t bytes_used); ProbT compute_alphas(const ProbT* probs, int repeats, int S, int T, const int* const e_inc, const int* const s_inc, const int* const labels, ProbT* alphas); ProbT compute_betas_and_grad(ProbT* grad, const ProbT* const probs, ProbT log_partition, int repeats, int S, int T, const int* const e_inc, const int* const s_inc, const int* const labels, ProbT* alphas, ProbT* betas, ProbT* output); }; template<typename ProbT> CpuCTC<ProbT>::CpuCTC_metadata::CpuCTC_metadata(int L, int S, int T, int mb, int alphabet_size, void* workspace, size_t bytes_used, int blank_label, const int* const labels) { alphas = reinterpret_cast<ProbT *>(static_cast<char *>(workspace) + bytes_used); bytes_used += sizeof(ProbT) * S * T; std::fill(alphas, alphas + S * T, ctc_helper::neg_inf<ProbT>()); betas = reinterpret_cast<ProbT *>(static_cast<char *>(workspace) + bytes_used); bytes_used += sizeof(ProbT) * S; std::fill(betas, betas + S, ctc_helper::neg_inf<ProbT>()); labels_w_blanks = reinterpret_cast<int *>(static_cast<char *>(workspace) + bytes_used); bytes_used += sizeof(int) * S; e_inc = reinterpret_cast<int *>(static_cast<char *>(workspace) + bytes_used); bytes_used += sizeof(int) * S; s_inc = reinterpret_cast<int *>(static_cast<char *>(workspace) + bytes_used); bytes_used += sizeof(int) * S; output = reinterpret_cast<ProbT *>(static_cast<char *>(workspace) + bytes_used); bytes_used += sizeof(ProbT) * alphabet_size; repeats = setup_labels(labels, blank_label, L, S); } template<typename ProbT> int CpuCTC<ProbT>::CpuCTC_metadata::setup_labels(const int* const labels, int blank_label, int L, int S) { int e_counter = 0; int s_counter = 0; s_inc[s_counter++] = 1; int repeats = 0; for (int i = 1; i < L; ++i) { if (labels[i-1] == labels[i]) { s_inc[s_counter++] = 1; s_inc[s_counter++] = 1; e_inc[e_counter++] = 1; e_inc[e_counter++] = 1; ++repeats; } else { s_inc[s_counter++] = 2; e_inc[e_counter++] = 2; } } e_inc[e_counter++] = 1; for (int i = 0; i < L; ++i) { labels_w_blanks[2 * i] = blank_label; labels_w_blanks[2 * i + 1] = labels[i]; } labels_w_blanks[S - 1] = blank_label; return repeats; } template<typename ProbT> void CpuCTC<ProbT>::softmax(const ProbT* const activations, ProbT* probs, const int* const input_lengths) { #pragma omp parallel for for (int mb = 0; mb < minibatch_; ++mb) { for(int c = 0; c < input_lengths[mb]; ++c) { int col_offset = (mb + minibatch_ * c) * alphabet_size_; ProbT max_activation = -std::numeric_limits<ProbT>::infinity(); for(int r = 0; r < alphabet_size_; ++r) max_activation = std::max(max_activation, activations[r + col_offset]); ProbT denom = ProbT(0.); for(int r = 0; r < alphabet_size_; ++r) { probs[r + col_offset] = std::exp(activations[r + col_offset] - max_activation); denom += probs[r + col_offset]; } for(int r = 0; r < alphabet_size_; ++r) { probs[r + col_offset] /= denom; } } } } template<typename ProbT> std::tuple<ProbT, bool> CpuCTC<ProbT>::cost_and_grad_kernel(ProbT *grad, const ProbT* const probs, const int* const labels, int T, int L, int mb, size_t bytes_used) { const int S = 2*L + 1; // Number of labels with blanks CpuCTC_metadata ctcm(L, S, T, mb, alphabet_size_, workspace_, bytes_used, blank_label_, labels); bool over_threshold = false; if (L + ctcm.repeats > T) { return std::make_tuple(ProbT(0), over_threshold); // TODO, not right to return 0 } ProbT llForward = compute_alphas(probs, ctcm.repeats, S, T, ctcm.e_inc, ctcm.s_inc, ctcm.labels_w_blanks, ctcm.alphas); ProbT llBackward = compute_betas_and_grad(grad, probs, llForward, ctcm.repeats, S, T, ctcm.e_inc, ctcm.s_inc, ctcm.labels_w_blanks, ctcm.alphas, ctcm.betas, ctcm.output); ProbT diff = std::abs(llForward - llBackward); if (diff > ctc_helper::threshold) { over_threshold = true; } return std::make_tuple(-llForward, over_threshold); } // Computes forward probabilities template<typename ProbT> ProbT CpuCTC<ProbT>::compute_alphas(const ProbT* probs, int repeats, int S, int T, const int* const e_inc, const int* const s_inc, const int* const labels, ProbT* alphas) { int start = (((S /2) + repeats - T) < 0) ? 0 : 1, end = S > 1 ? 2 : 1; for (int i = start; i < end; ++i) { alphas[i] = std::log(probs[labels[i]]); } for(int t = 1; t < T; ++t) { int remain = (S / 2) + repeats - (T - t); if(remain >= 0) start += s_inc[remain]; if(t <= (S / 2) + repeats) end += e_inc[t - 1]; int startloop = start; int idx1 = t * S, idx2 = (t - 1) * S, idx3 = t * (alphabet_size_ * minibatch_); if (start == 0) { alphas[idx1] = alphas[idx2] + std::log(probs[blank_label_ + idx3]); startloop += 1; } for(int i = startloop; i < end; ++i) { ProbT prev_sum = ctc_helper::log_plus<ProbT>()(alphas[i + idx2], alphas[(i-1) + idx2]); // Skip two if not on blank and not on repeat. if (labels[i] != blank_label_ && i != 1 && labels[i] != labels[i-2]) prev_sum = ctc_helper::log_plus<ProbT>()(prev_sum, alphas[(i-2) + idx2]); alphas[i + idx1] = prev_sum + std::log(probs[labels[i] + idx3]); } } ProbT loglike = ctc_helper::neg_inf<ProbT>(); for(int i = start; i < end; ++i) { loglike = ctc_helper::log_plus<ProbT>()(loglike, alphas[i + (T - 1) * S]); } return loglike; } // Starting from T, we sweep backward over the alpha array computing one column // of betas as we go. At each position we can update product alpha * beta and then // sum into the gradient associated with each label. // NOTE computes gradient w.r.t UNNORMALIZED final layer activations. // Assumed passed in grads are already zeroed! template<typename ProbT> ProbT CpuCTC<ProbT>::compute_betas_and_grad(ProbT* grad, const ProbT* const probs, ProbT log_partition, int repeats, int S, int T, const int* const e_inc, const int* const s_inc, const int* const labels, ProbT* alphas, ProbT* betas, ProbT* output) { int start = S > 1 ? (S - 2) : 0, end = (T > (S / 2) + repeats) ? S : S-1; std::fill(output, output + alphabet_size_, ctc_helper::neg_inf<ProbT>()); //set the starting values in the beta column at the very right edge for (int i = start; i < end; ++i) { betas[i] = std::log(probs[labels[i] + (T - 1) * (alphabet_size_ * minibatch_)]); //compute alpha * beta in log space at this position in (S, T) space alphas[i + (T - 1) * S] += betas[i]; //update the gradient associated with this label //essentially performing a reduce-by-key in a sequential manner output[labels[i]] = ctc_helper::log_plus<ProbT>()(alphas[i + (T - 1) * S], output[labels[i]]); } //update the gradient wrt to each unique label for (int i = 0; i < alphabet_size_; ++i) { int idx3 = (T - 1) * alphabet_size_ * minibatch_ + i; if (output[i] == 0.0 || output[i] == ctc_helper::neg_inf<ProbT>() || probs[idx3] == 0.0) { grad[idx3] = probs[idx3]; } else { grad[idx3] = probs[idx3] - std::exp(output[i] - std::log(probs[idx3]) - log_partition); } } //loop from the second to last column all the way to the left for(int t = T - 2; t >= 0; --t) { int remain = (S / 2) + repeats - (T - t); if(remain >= -1) start -= s_inc[remain + 1]; if(t < (S / 2) + repeats) end -= e_inc[t]; int endloop = end == S ? end - 1 : end; int idx1 = t * S, idx3 = t * (alphabet_size_ * minibatch_); std::fill(output, output + alphabet_size_, ctc_helper::neg_inf<ProbT>()); for(int i = start; i < endloop; ++i) { ProbT next_sum = ctc_helper::log_plus<ProbT>()(betas[i], betas[(i+1)]); // Skip two if not on blank and not on repeat. if (labels[i] != blank_label_ && i != (S-2) && labels[i] != labels[i+2]){ next_sum = ctc_helper::log_plus<ProbT>()(next_sum, betas[(i+2)]); } betas[i] = next_sum + std::log(probs[labels[i] + idx3]); //compute alpha * beta in log space alphas[i + idx1] += betas[i]; //update the gradient associated with this label output[labels[i]] = ctc_helper::log_plus<ProbT>()(alphas[i + idx1], output[labels[i]]); } if (end == S) { betas[(S-1)] = betas[(S-1)] + std::log(probs[blank_label_ + idx3]); alphas[(S-1) + idx1] += betas[(S-1)]; output[labels[S-1]] = ctc_helper::log_plus<ProbT>()(alphas[S-1 + idx1], output[labels[S-1]]); } //go over the unique labels and compute the final grad // wrt to each one at this time step for (int i = 0; i < alphabet_size_; ++i) { if (output[i] == 0.0 || output[i] == ctc_helper::neg_inf<ProbT>() || probs[idx3] == 0.0) { grad[idx3] = probs[idx3]; } else { grad[idx3] = probs[idx3] - std::exp(output[i] - std::log(probs[idx3]) - log_partition); } ++idx3; } } ProbT loglike = ctc_helper::neg_inf<ProbT>(); for(int i = start; i < end; ++i) { loglike = ctc_helper::log_plus<ProbT>()(loglike, betas[i]); } return loglike; } template<typename ProbT> ctcStatus_t CpuCTC<ProbT>::cost_and_grad(const ProbT* const activations, ProbT *grads, ProbT *costs, const int* const flat_labels, const int* const label_lengths, const int* const input_lengths) { if (activations == nullptr || grads == nullptr || costs == nullptr || flat_labels == nullptr || label_lengths == nullptr || input_lengths == nullptr ) return CTC_STATUS_INVALID_VALUE; ProbT* probs = static_cast<ProbT *>(workspace_); int maxT = *std::max_element(input_lengths, input_lengths + minibatch_); size_t bytes_used = sizeof(ProbT) * minibatch_ * alphabet_size_ * maxT; //per minibatch memory size_t per_minibatch_bytes = 0; int maxL = *std::max_element(label_lengths, label_lengths + minibatch_);; int maxS = 2 * maxL + 1; //output per_minibatch_bytes += sizeof(float) * alphabet_size_; //alphas per_minibatch_bytes += sizeof(float) * maxS * maxT; //betas per_minibatch_bytes += sizeof(float) * maxS; //labels w/blanks, e_inc, s_inc per_minibatch_bytes += 3 * sizeof(int) * maxS; softmax(activations, probs, input_lengths); #pragma omp parallel for for (int mb = 0; mb < minibatch_; ++mb) { const int T = input_lengths[mb]; // Length of utterance (time) const int L = label_lengths[mb]; // Number of labels in transcription bool mb_status; std::tie(costs[mb], mb_status) = cost_and_grad_kernel(grads + mb * alphabet_size_, probs + mb * alphabet_size_, flat_labels + std::accumulate(label_lengths, label_lengths + mb, 0), T, L, mb, bytes_used + mb * per_minibatch_bytes); } return CTC_STATUS_SUCCESS; } template<typename ProbT> ctcStatus_t CpuCTC<ProbT>::score_forward(const ProbT* const activations, ProbT* costs, const int* const flat_labels, const int* const label_lengths, const int* const input_lengths) { if (activations == nullptr || costs == nullptr || flat_labels == nullptr || label_lengths == nullptr || input_lengths == nullptr ) return CTC_STATUS_INVALID_VALUE; ProbT* probs = static_cast<ProbT *>(workspace_); int maxT = *std::max_element(input_lengths, input_lengths + minibatch_); size_t bytes_used = sizeof(ProbT) * minibatch_ * alphabet_size_ * maxT; //per minibatch memory size_t per_minibatch_bytes = 0; int maxL = *std::max_element(label_lengths, label_lengths + minibatch_); int maxS = 2 * maxL + 1; //output per_minibatch_bytes += sizeof(float) * alphabet_size_; //alphas per_minibatch_bytes += sizeof(float) * maxS * maxT; //betas per_minibatch_bytes += sizeof(float) * maxS; //labels w/blanks, e_inc, s_inc per_minibatch_bytes += 3 * sizeof(int) * maxS; softmax(activations, probs, input_lengths); #pragma omp parallel for for (int mb = 0; mb < minibatch_; ++mb) { const int T = input_lengths[mb]; // Length of utterance (time) const int L = label_lengths[mb]; // Number of labels in transcription const int S = 2*L + 1; // Number of labels with blanks CpuCTC_metadata ctcm(L, S, T, mb, alphabet_size_, workspace_, bytes_used + mb * per_minibatch_bytes, blank_label_, flat_labels + std::accumulate(label_lengths, label_lengths + mb, 0)); if (L + ctcm.repeats > T) costs[mb] = ProbT(0); else { costs[mb] = -compute_alphas(probs + mb * alphabet_size_, ctcm.repeats, S, T, ctcm.e_inc, ctcm.s_inc, ctcm.labels_w_blanks, ctcm.alphas); } } return CTC_STATUS_SUCCESS; }
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] = 16; tile_size[3] = 1024; 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-1,2)),ceild(16*t2-Nz-12,16));t3<=min(min(min(floord(Nt+Ny-4,16),floord(8*t1+Ny+13,16)),floord(16*t2+Ny+12,16)),floord(16*t1-16*t2+Nz+Ny+11,16));t3++) { for (t4=max(max(max(0,ceild(t1-127,128)),ceild(16*t2-Nz-1020,1024)),ceild(16*t3-Ny-1020,1024));t4<=min(min(min(min(floord(Nt+Nx-4,1024),floord(8*t1+Nx+13,1024)),floord(16*t2+Nx+12,1024)),floord(16*t3+Nx+12,1024)),floord(16*t1-16*t2+Nz+Nx+11,1024));t4++) { for (t5=max(max(max(max(max(0,8*t1),16*t1-16*t2+1),16*t2-Nz+2),16*t3-Ny+2),1024*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,8*t1+15),16*t2+14),16*t3+14),1024*t4+1022),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(16*t3,t5+1);t7<=min(16*t3+15,t5+Ny-2);t7++) { lbv=max(1024*t4,t5+1); ubv=min(1024*t4+1023,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; }
buggy_version.c
#include<stdio.h> int main(){ int sum = 1; int i =1; // increase sum by one each iteratiob using openmp #pragma omp parallel for private(i) reduction( + : sum ) for (int j = i; j < 100; j++) { sum +=1; } printf("sum is %d\n",sum); }
iRCCE_atomic.c
//*************************************************************************************** // Functions for handling Atomic Increment Registers (AIR). //*************************************************************************************** // // Copyright 2012, Chair for Operating Systems, RWTH Aachen University // // 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 "iRCCE_lib.h" #ifdef AIR //-------------------------------------------------------------------------------------- // FUNCTION: iRCCE_atomic_alloc //-------------------------------------------------------------------------------------- // Allocates a new AIR register; returns iRCCE_ERRO if all AIRs are already allocated //-------------------------------------------------------------------------------------- int iRCCE_atomic_alloc(iRCCE_AIR** reg) { if(iRCCE_atomic_alloc_counter < 2 * RCCE_NP) { int next_reg = RC_COREID[iRCCE_atomic_alloc_counter]; if(iRCCE_atomic_alloc_counter > RCCE_NP) next_reg += RCCE_MAXNP; (*reg) = &iRCCE_atomic_inc_regs[next_reg]; #ifdef _OPENMP #pragma omp master { iRCCE_atomic_alloc_counter++; } #pragma omp barrier #else iRCCE_atomic_alloc_counter++; #endif iRCCE_atomic_write((*reg), 0); return iRCCE_SUCCESS; } else { return iRCCE_ERROR; } } //-------------------------------------------------------------------------------------- // FUNCTION: iRCCE_atomic_inc //-------------------------------------------------------------------------------------- // Increments an AIR register and returns its privious content //-------------------------------------------------------------------------------------- int iRCCE_atomic_inc(iRCCE_AIR* reg, int* value) { int _value; if(value == NULL) value = &value; #ifndef _OPENMP (*value) = (*reg->counter); #else #pragma omp critical { (*value) = reg->counter; reg->counter++; reg->init = reg->counter; } #endif return iRCCE_SUCCESS; } //-------------------------------------------------------------------------------------- // FUNCTION: iRCCE_atomic_read //-------------------------------------------------------------------------------------- // Returns the current value of an AIR register //-------------------------------------------------------------------------------------- int iRCCE_atomic_read(iRCCE_AIR* reg, int* value) { #ifndef _OPENMP (*value) = (*reg->init); #else #pragma omp critical { (*value) =reg->init; } #endif return iRCCE_SUCCESS; } //-------------------------------------------------------------------------------------- // FUNCTION: iRCCE_atomic_write //-------------------------------------------------------------------------------------- // Initializes an AIR register by writing a start value //-------------------------------------------------------------------------------------- int iRCCE_atomic_write(iRCCE_AIR* reg, int value) { #ifndef _OPENMP (*reg->init) = value; #else #pragma omp critical { reg->init = value; reg->counter = value; } #endif return iRCCE_SUCCESS; } //-------------------------------------------------------------------------------------- // FUNCTION: iRCCE_barrier //-------------------------------------------------------------------------------------- // A barrier version based on the Atomic Increment Registers (AIR); if AIRs are not // supported, the function makes a fall-back to the common RCCE_barrier(). //-------------------------------------------------------------------------------------- static void RC_wait(int wait) { #ifndef _OPENMP asm volatile( "movl %%eax,%%ecx\n\t" "test:nop\n\t" "loop test" : /* no output registers */ : "a" (wait) : "%ecx" ); #endif return; } static int idx = 0; static unsigned int rnd = 0; #ifdef _OPENMP #pragma omp threadprivate (idx, rnd) #endif int iRCCE_barrier(RCCE_COMM *comm) { int backoff = BACKOFF_MIN, wait, i = 0; int counter; if(comm == NULL) comm = &RCCE_COMM_WORLD; if (comm == &RCCE_COMM_WORLD) { iRCCE_atomic_inc(iRCCE_atomic_barrier[idx], &counter); if (counter < (comm->size-1)) { iRCCE_atomic_read(iRCCE_atomic_barrier[idx], &counter); while (counter > 0) { rnd = rnd * 1103515245u + 12345u; wait = BACKOFF_MIN + (rnd % (backoff << i)); RC_wait(wait); if (wait < BACKOFF_MAX) i++; iRCCE_atomic_read(iRCCE_atomic_barrier[idx], &counter); } } else { iRCCE_atomic_write(iRCCE_atomic_barrier[idx], 0); } idx = !idx; return(RCCE_SUCCESS); } else { return RCCE_barrier(comm); } } #else // !AIR int iRCCE_barrier(RCCE_COMM *comm) { if(comm == NULL) return RCCE_barrier(&RCCE_COMM_WORLD); else return RCCE_barrier(comm); } #endif // !AIR
blackscholes.c
// Copyright (c) 2007 Intel Corp. // Black-Scholes // Analytical method for calculating European Options // // // Reference Source: Options, Futures, and Other Derivatives, 3rd Edition, Prentice // Hall, John C. Hull, #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #ifdef ENABLE_PARSEC_HOOKS #include <hooks.h> #endif // Multi-threaded pthreads header #ifdef ENABLE_THREADS // Add the following line so that icc 9.0 is compatible with pthread lib. #define __thread __threadp MAIN_ENV #undef __thread #endif // Multi-threaded OpenMP header #ifdef ENABLE_OPENMP #include <omp.h> #endif #ifdef ENABLE_TBB #include "tbb/blocked_range.h" #include "tbb/parallel_for.h" #include "tbb/task_scheduler_init.h" #include "tbb/tick_count.h" using namespace std; using namespace tbb; #endif //ENABLE_TBB // Multi-threaded header for Windows #ifdef WIN32 #pragma warning(disable : 4305) #pragma warning(disable : 4244) #include <windows.h> #endif //Precision to use for calculations #define fptype float #define NUM_RUNS 100 typedef struct OptionData_ { fptype s; // spot price fptype strike; // strike price fptype r; // risk-free interest rate fptype divq; // dividend rate fptype v; // volatility fptype t; // time to maturity or option expiration in years // (1yr = 1.0, 6mos = 0.5, 3mos = 0.25, ..., etc) char OptionType; // Option type. "P"=PUT, "C"=CALL fptype divs; // dividend vals (not used in this test) fptype DGrefval; // DerivaGem Reference Value } OptionData; OptionData *data; fptype *prices; int numOptions; int * otype; fptype * sptprice; fptype * strike; fptype * rate; fptype * volatility; fptype * otime; int numError = 0; int nThreads; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Cumulative Normal Distribution Function // See Hull, Section 11.8, P.243-244 #define inv_sqrt_2xPI 0.39894228040143270286 fptype CNDF ( fptype InputX ) { int sign; fptype OutputX; fptype xInput; fptype xNPrimeofX; fptype expValues; fptype xK2; fptype xK2_2, xK2_3; fptype xK2_4, xK2_5; fptype xLocal, xLocal_1; fptype xLocal_2, xLocal_3; // Check for negative value of InputX if (InputX < 0.0) { InputX = -InputX; sign = 1; } else sign = 0; xInput = InputX; // Compute NPrimeX term common to both four & six decimal accuracy calcs expValues = exp(-0.5f * InputX * InputX); xNPrimeofX = expValues; xNPrimeofX = xNPrimeofX * inv_sqrt_2xPI; xK2 = 0.2316419 * xInput; xK2 = 1.0 + xK2; xK2 = 1.0 / xK2; xK2_2 = xK2 * xK2; xK2_3 = xK2_2 * xK2; xK2_4 = xK2_3 * xK2; xK2_5 = xK2_4 * xK2; xLocal_1 = xK2 * 0.319381530; xLocal_2 = xK2_2 * (-0.356563782); xLocal_3 = xK2_3 * 1.781477937; xLocal_2 = xLocal_2 + xLocal_3; xLocal_3 = xK2_4 * (-1.821255978); xLocal_2 = xLocal_2 + xLocal_3; xLocal_3 = xK2_5 * 1.330274429; xLocal_2 = xLocal_2 + xLocal_3; xLocal_1 = xLocal_2 + xLocal_1; xLocal = xLocal_1 * xNPrimeofX; xLocal = 1.0 - xLocal; OutputX = xLocal; if (sign) { OutputX = 1.0 - OutputX; } return OutputX; } ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// fptype BlkSchlsEqEuroNoDiv( fptype sptprice, fptype strike, fptype rate, fptype volatility, fptype time, int otype, float timet ) { fptype OptionPrice; // local private working variables for the calculation fptype xStockPrice; fptype xStrikePrice; fptype xRiskFreeRate; fptype xVolatility; fptype xTime; fptype xSqrtTime; fptype logValues; fptype xLogTerm; fptype xD1; fptype xD2; fptype xPowerTerm; fptype xDen; fptype d1; fptype d2; fptype FutureValueX; fptype NofXd1; fptype NofXd2; fptype NegNofXd1; fptype NegNofXd2; xStockPrice = sptprice; xStrikePrice = strike; xRiskFreeRate = rate; xVolatility = volatility; xTime = time; xSqrtTime = sqrt(xTime); logValues = log( sptprice / strike ); xLogTerm = logValues; xPowerTerm = xVolatility * xVolatility; xPowerTerm = xPowerTerm * 0.5; xD1 = xRiskFreeRate + xPowerTerm; xD1 = xD1 * xTime; xD1 = xD1 + xLogTerm; xDen = xVolatility * xSqrtTime; xD1 = xD1 / xDen; xD2 = xD1 - xDen; d1 = xD1; d2 = xD2; NofXd1 = CNDF( d1 ); NofXd2 = CNDF( d2 ); FutureValueX = strike * ( exp( -(rate)*(time) ) ); if (otype == 0) { OptionPrice = (sptprice * NofXd1) - (FutureValueX * NofXd2); } else { NegNofXd1 = (1.0 - NofXd1); NegNofXd2 = (1.0 - NofXd2); OptionPrice = (FutureValueX * NegNofXd2) - (sptprice * NegNofXd1); } return OptionPrice; } #ifdef ENABLE_TBB struct mainWork { mainWork() {} mainWork(mainWork &w, tbb::split) {} void operator()(const tbb::blocked_range<int> &range) const { fptype price; int begin = range.begin(); int end = range.end(); for (int i=begin; i!=end; i++) { /* Calling main function to calculate option value based on * Black & Scholes's equation. */ price = BlkSchlsEqEuroNoDiv( sptprice[i], strike[i], rate[i], volatility[i], otime[i], otype[i], 0); prices[i] = price; #ifdef ERR_CHK fptype priceDelta = data[i].DGrefval - price; if( fabs(priceDelta) >= 1e-5 ){ fprintf(stderr,"Error on %d. Computed=%.5f, Ref=%.5f, Delta=%.5f\n", i, price, data[i].DGrefval, priceDelta); numError ++; } #endif } } }; #endif // ENABLE_TBB ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// #ifdef ENABLE_TBB int bs_thread(void *tid_ptr) { int j; tbb::affinity_partitioner a; mainWork doall; for (j=0; j<NUM_RUNS; j++) { tbb::parallel_for(tbb::blocked_range<int>(0, numOptions), doall, a); } return 0; } #else // !ENABLE_TBB #ifdef WIN32 DWORD WINAPI bs_thread(LPVOID tid_ptr){ #else int bs_thread(void *tid_ptr) { #endif int i, j; fptype price; fptype priceDelta; int tid = *(int *)tid_ptr; int start = tid * (numOptions / nThreads); int end = start + (numOptions / nThreads); for (j=0; j<NUM_RUNS; j++) { #ifdef ENABLE_OPENMP #pragma omp parallel for private(i, price, priceDelta) for (i=0; i<numOptions; i++) { #else //ENABLE_OPENMP for (i=start; i<end; i++) { #endif //ENABLE_OPENMP /* Calling main function to calculate option value based on * Black & Scholes's equation. */ price = BlkSchlsEqEuroNoDiv( sptprice[i], strike[i], rate[i], volatility[i], otime[i], otype[i], 0); prices[i] = price; #ifdef ERR_CHK priceDelta = data[i].DGrefval - price; if( fabs(priceDelta) >= 1e-4 ){ printf("Error on %d. Computed=%.5f, Ref=%.5f, Delta=%.5f\n", i, price, data[i].DGrefval, priceDelta); numError ++; } #endif } } return 0; } #endif //ENABLE_TBB int main (int argc, char **argv) { FILE *file; int i; int loopnum; fptype * buffer; int * buffer2; int rv; #ifdef PARSEC_VERSION #define __PARSEC_STRING(x) #x #define __PARSEC_XSTRING(x) __PARSEC_STRING(x) printf("PARSEC Benchmark Suite Version "__PARSEC_XSTRING(PARSEC_VERSION)"\n"); fflush(NULL); #else printf("PARSEC Benchmark Suite\n"); fflush(NULL); #endif //PARSEC_VERSION #ifdef ENABLE_PARSEC_HOOKS __parsec_bench_begin(__parsec_blackscholes); #endif if (argc != 4) { printf("Usage:\n\t%s <nthreads> <inputFile> <outputFile>\n", argv[0]); exit(1); } nThreads = atoi(argv[1]); char *inputFile = argv[2]; char *outputFile = argv[3]; //Read input data from file file = fopen(inputFile, "r"); if(file == NULL) { printf("ERROR: Unable to open file `%s'.\n", inputFile); exit(1); } rv = fscanf(file, "%i", &numOptions); if(rv != 1) { printf("ERROR: Unable to read from file `%s'.\n", inputFile); fclose(file); exit(1); } if(nThreads > numOptions) { printf("WARNING: Not enough work, reducing number of threads to match number of options.\n"); nThreads = numOptions; } #if !defined(ENABLE_THREADS) && !defined(ENABLE_OPENMP) && !defined(ENABLE_TBB) if(nThreads != 1) { printf("Error: <nthreads> must be 1 (serial version)\n"); exit(1); } #endif // alloc spaces for the option data data = (OptionData*)malloc(numOptions*sizeof(OptionData)); prices = (fptype*)malloc(numOptions*sizeof(fptype)); for ( loopnum = 0; loopnum < numOptions; ++ loopnum ) { rv = fscanf(file, "%f %f %f %f %f %f %c %f %f", &data[loopnum].s, &data[loopnum].strike, &data[loopnum].r, &data[loopnum].divq, &data[loopnum].v, &data[loopnum].t, &data[loopnum].OptionType, &data[loopnum].divs, &data[loopnum].DGrefval); if(rv != 9) { printf("ERROR: Unable to read from file `%s'.\n", inputFile); fclose(file); exit(1); } } rv = fclose(file); if(rv != 0) { printf("ERROR: Unable to close file `%s'.\n", inputFile); exit(1); } #ifdef ENABLE_THREADS MAIN_INITENV(,8000000,nThreads); #endif printf("Num of Options: %d\n", numOptions); printf("Num of Runs: %d\n", NUM_RUNS); #define PAD 256 #define LINESIZE 64 buffer = (fptype *) malloc(5 * numOptions * sizeof(fptype) + PAD); sptprice = (fptype *) (((unsigned long long)buffer + PAD) & ~(LINESIZE - 1)); strike = sptprice + numOptions; rate = strike + numOptions; volatility = rate + numOptions; otime = volatility + numOptions; buffer2 = (int *) malloc(numOptions * sizeof(fptype) + PAD); otype = (int *) (((unsigned long long)buffer2 + PAD) & ~(LINESIZE - 1)); for (i=0; i<numOptions; i++) { otype[i] = (data[i].OptionType == 'P') ? 1 : 0; sptprice[i] = data[i].s; strike[i] = data[i].strike; rate[i] = data[i].r; volatility[i] = data[i].v; otime[i] = data[i].t; } printf("Size of data: %d\n", numOptions * (sizeof(OptionData) + sizeof(int))); #ifdef ENABLE_PARSEC_HOOKS __parsec_roi_begin(); #endif #ifdef ENABLE_THREADS #ifdef WIN32 HANDLE *threads; int *nums; threads = (HANDLE *) malloc (nThreads * sizeof(HANDLE)); nums = (int *) malloc (nThreads * sizeof(int)); for(i=0; i<nThreads; i++) { nums[i] = i; threads[i] = CreateThread(0, 0, bs_thread, &nums[i], 0, 0); } WaitForMultipleObjects(nThreads, threads, TRUE, INFINITE); free(threads); free(nums); #else int *tids; tids = (int *) malloc (nThreads * sizeof(int)); for(i=0; i<nThreads; i++) { tids[i]=i; CREATE_WITH_ARG(bs_thread, &tids[i]); } WAIT_FOR_END(nThreads); free(tids); #endif //WIN32 #else //ENABLE_THREADS #ifdef ENABLE_OPENMP { int tid=0; omp_set_num_threads(nThreads); bs_thread(&tid); } #else //ENABLE_OPENMP #ifdef ENABLE_TBB tbb::task_scheduler_init init(nThreads); int tid=0; bs_thread(&tid); #else //ENABLE_TBB //serial version int tid=0; bs_thread(&tid); #endif //ENABLE_TBB #endif //ENABLE_OPENMP #endif //ENABLE_THREADS #ifdef ENABLE_PARSEC_HOOKS __parsec_roi_end(); #endif //Write prices to output file file = fopen(outputFile, "w"); if(file == NULL) { printf("ERROR: Unable to open file `%s'.\n", outputFile); exit(1); } rv = fprintf(file, "%i\n", numOptions); if(rv < 0) { printf("ERROR: Unable to write to file `%s'.\n", outputFile); fclose(file); exit(1); } for(i=0; i<numOptions; i++) { rv = fprintf(file, "%.18f\n", prices[i]); if(rv < 0) { printf("ERROR: Unable to write to file `%s'.\n", outputFile); fclose(file); exit(1); } } rv = fclose(file); if(rv != 0) { printf("ERROR: Unable to close file `%s'.\n", outputFile); exit(1); } #ifdef ERR_CHK printf("Num Errors: %d\n", numError); #endif free(data); free(prices); #ifdef ENABLE_PARSEC_HOOKS __parsec_bench_end(); #endif return 0; }
GB_unaryop__abs_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__abs_bool_uint8 // op(A') function: GB_tran__abs_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_ABS || GxB_NO_BOOL || GxB_NO_UINT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__abs_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__abs_bool_uint8 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
threading-funneled-solution.c
#include "mpi.h" #include <stdio.h> void compute_row(int row_index, float input[6][8], float output[6][8]) { for (int j = 0; j < 8; j = j + 1) { /* Here is the 5-point stencil */ const int right_column_index = (j + 1) % 8; const int left_column_index = (j + 8 - 1) % 8; const int top_row_index = row_index-1; const int bottom_row_index = row_index+1; output[row_index][j] = (input[row_index][j] + input[row_index][left_column_index] + input[row_index][right_column_index] + input[top_row_index][j] + input[bottom_row_index][j]); } } int main(int argc, char **argv) { /* ==== CHALLENGE ==== * * Uncomment the line and fix the MPI call to make this code work! * We want to use fork-join parallelism, so pick a more suitable * threading mode */ /* Initialize the MPI environment and check */ int provided, required = MPI_THREAD_FUNNELED; MPI_Init_thread(NULL, NULL, required, &provided); MPI_Comm comm = MPI_COMM_WORLD; /* If the program can't run, stop running */ if (required != provided) { printf("Sorry, the MPI library does not provide " "this threading level! Aborting!\n"); MPI_Abort(comm, 1); } int rank, size; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); if (size != 2) { if (rank == 0) { printf("Only two ranks is supported for this exercise, " "please re-run with two ranks\n"); } MPI_Finalize(); return 0; } /* Prepare the initial values for this process */ float local_data_set[4][8]; printf("Local data set on rank %d was:\n", rank); for (int i = 0; i < 4; i = i + 1) { printf(" [ "); for (int j = 0; j < 8; j = j + 1) { /* Make sure the local data on each rank is different, so * that we see the communication works properly. */ local_data_set[i][j] = 1*(rank + 1); if (j != 0) { printf(", "); } printf("%g", local_data_set[i][j]); } printf(" ]\n"); } float working_data_set[6][8]; for (int i = 0; i < 4; i = i + 1) { for (int j = 0; j < 8; j = j + 1) { /* Initialize the local part of the working data set */ working_data_set[i+1][j] = local_data_set[i][j]; } } /* Prepare to report whether the code is correct */ int success = 1; /* Do the loop over heat-propagation steps */ float next_working_data_set[6][8]; float total, local_total, temporary_total; const int total_root_rank = 0; MPI_Request total_request = MPI_REQUEST_NULL; const int max_step = 10; for (int step = 0; step < max_step; step = step + 1) { int send_up_tag = 0, send_down_tag = 1; /* Prepare to receive the halo data */ int source_rank = size-rank-1; MPI_Request sent_from_source[2]; MPI_Irecv(working_data_set[5], 8, MPI_FLOAT, source_rank, send_up_tag, comm, &sent_from_source[0]); MPI_Irecv(working_data_set[0], 8, MPI_FLOAT, source_rank, send_down_tag, comm, &sent_from_source[1]); /* Prepare to send the border data */ int destination_rank = size-rank-1; MPI_Request sent_to_destination[2]; MPI_Isend(working_data_set[1], 8, MPI_FLOAT, destination_rank, send_up_tag, comm, &sent_to_destination[0]); MPI_Isend(working_data_set[4], 8, MPI_FLOAT, destination_rank, send_down_tag, comm, &sent_to_destination[1]); /* ==== CHALLENGE ==== * * Uncomment and fix the arguments to the MPI call to make * this code work! * * Pass parameters to compute_row() in a way that each * iteration of the for loop does an equal part of the * local_work, ie rows 2 and 3 of the working_data_set. You * may need to consult the parameter names of compute_row(). */ /* Do the local computation. OpenMP will distribute each * iteration to a different thread. */ int local_work[] = {2, 3}; #pragma omp parallel for for (int k = 0; k != 2; k = k + 1) { compute_row(local_work[k], working_data_set, next_working_data_set); } /* Implied thread barrier here */ /* Wait for the halo-exchange receives to complete */ MPI_Wait(&sent_from_source[0], MPI_STATUS_IGNORE); MPI_Wait(&sent_from_source[1], MPI_STATUS_IGNORE); /* ==== CHALLENGE ==== * * Uncomment and fix the arguments to the MPI call to make * this code work! * * Pass parameters to compute_row() in a way that each * iteration of the for loop does an equal part of the * local_work, ie rows 1 and 4 of the working_data_set. You * may need to consult the parameter names of compute_row(). */ /* Do the non-local computation. OpenMP will distribute each * iteration to a different thread. */ int non_local_work[] = {1, 4}; #pragma omp parallel for for (int k = 0; k != 2; k = k + 1) { compute_row(non_local_work[k], working_data_set, next_working_data_set); } /* Implied thread barrier here */ /* Compute the total heat via non-blocking reduction */ if (step % 5 == 4) { local_total = 0; for (int i = 1; i < 5; i = i + 1) { for (int j = 0; j < 8; j = j + 1) { local_total += next_working_data_set[i][j]; } } fprintf(stderr, "Doing an non-blocking reduction on step %d\n", step); MPI_Ireduce(&local_total, &temporary_total, 1, MPI_FLOAT, MPI_SUM, total_root_rank, comm, &total_request); } /* Wait for the most recent total heat reduction, 4 steps after it was started */ if (step % 5 == 3 && total_request != MPI_REQUEST_NULL) { MPI_Wait(&total_request, MPI_STATUS_IGNORE); total = temporary_total; if (rank == total_root_rank) { fprintf(stderr, "Total after waiting at step %d was %g\n", step, total); } } if (rank == total_root_rank) { const float expected_total_value = (step < 8) ? 0 : 300000; if (total != expected_total_value) { success = 0; printf("Failed on step %d with total %g not matching expected %g\n", step, total, expected_total_value); } } /* Wait for the halo-exchange sends to complete */ MPI_Wait(&sent_to_destination[0], MPI_STATUS_IGNORE); MPI_Wait(&sent_to_destination[1], MPI_STATUS_IGNORE); /* Prepare to iterate */ for (int i = 1; i < 5; i = i + 1) { for (int j = 0; j < 8; j = j + 1) { /* copy the output back to the input array */ working_data_set[i][j] = next_working_data_set[i][j]; } } } /* Now that we have left the main loop, we should wait for * the most recent total heat reduction to complete. */ if (total_request != MPI_REQUEST_NULL) { MPI_Wait(&total_request, MPI_STATUS_IGNORE); total = temporary_total; if (rank == total_root_rank) { fprintf(stderr, "Total after waiting at step %d was %g\n", max_step - 1, total); } } if (rank == total_root_rank) { const float expected_total_value = 9.375e+08; if (total != expected_total_value) { success = 0; printf("Failed on step %d with total %g not matching expected %g\n", max_step - 1, total, expected_total_value); } } /* Report whether the code is correct */ if (rank == total_root_rank) { if (success) { printf("SUCCESS on rank %d!\n", rank); } else { printf("Improvement needed before rank %d can report success!\n", rank); } } /* Clean up and exit */ MPI_Finalize(); return 0; }
util.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> void read_matrix(int** index, int** matrix, double scaling, int N_kw, char* input_fileName) { FILE *fp = fopen(input_fileName, "r"); fscanf(fp, "%*[^\n]\n"); for (int ii = 0; ii < N_kw; ii++) fscanf(fp, "%d,", &((*index)[ii])); fscanf(fp, "%*[^\n]\n"); int tmp; for (int ii = 0; ii < N_kw; ii++) { for (int jj = 0; jj < N_kw; jj++) { fscanf(fp, "%d,", &tmp); (*matrix)[ii*N_kw + jj] = (int) (scaling * tmp); } fscanf(fp, "%*[^\n]\n"); } fclose(fp); } void pad_matrix(int** matrix_padded, int** matrix, int N_kw, int N_doc, int freq_max) { // Initialising RNG const gsl_rng_type * T; gsl_rng * r; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc(T); // perform padding on the keywords int ii, jj; #pragma omp parallel for private(ii) for (int ii = 0; ii < N_kw; ii++) (*matrix_padded)[ii*N_kw + ii] = 2*freq_max; // perform padding #pragma omp parallel for private(ii, jj) for (ii = 0; ii < N_kw; ii++) { for (jj = 0; jj < N_kw; jj++) { if (ii > jj) { int n1 = 2*freq_max - (*matrix)[ii*N_kw + ii]; int n2 = 2*freq_max - (*matrix)[jj*N_kw + jj]; int x1 = gsl_ran_hypergeometric(r, n1, 2*N_doc-n1, (*matrix_padded)[jj*N_kw + jj]); int x2 = gsl_ran_hypergeometric(r, n2, 2*N_doc-n2, (*matrix_padded)[ii*N_kw + ii]); (*matrix_padded)[ii*N_kw + jj] = (*matrix)[ii*N_kw + jj] + x1 + x2; (*matrix_padded)[jj*N_kw + ii] = (*matrix_padded)[ii*N_kw + jj]; } } } gsl_rng_free(r); } void observe_matrix(gsl_matrix* matrix_obs, int** matrix_padded, int N_kw) { // perform observed count generation for (int ii = 0; ii < N_kw; ii++) for (int jj = 0; jj < N_kw; jj++) gsl_matrix_set(matrix_obs, ii, jj, (double) ((*matrix_padded)[ii*N_kw + jj])); } void permutation_generation(int* idx1, int* idx2, int** permutation_tmp, int** permutation, int** permutation_inv, int N_kw, int N_obs) { *idx1 = rand() % N_obs; *idx2 = -1; int idx_old = (*permutation)[*idx1]; int idx_new = rand() % N_kw; (*permutation_tmp)[*idx1] = idx_new; if ((*permutation_inv)[idx_new] >= 0) { *idx2 = (*permutation_inv)[idx_new]; (*permutation_tmp)[*idx2] = idx_old; } }
chebyshev.c
//------------------------------------------------------------------------------------------------------------------------------ // Samuel Williams // SWWilliams@lbl.gov // Lawrence Berkeley National Lab //------------------------------------------------------------------------------------------------------------------------------ // Based on Yousef Saad's Iterative Methods for Sparse Linear Algebra, Algorithm 12.1, page 399 //------------------------------------------------------------------------------------------------------------------------------ void smooth(level_type * level, int x_id, int rhs_id, double a, double b){ if( (level->dominant_eigenvalue_of_DinvA<=0.0) && (level->my_rank==0) )printf("dominant_eigenvalue_of_DinvA <= 0.0 !\n"); if((CHEBYSHEV_DEGREE*NUM_SMOOTHS)&1){ printf("error... CHEBYSHEV_DEGREE*NUM_SMOOTHS must be even for the chebyshev smoother...\n"); exit(0); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - int box,s; int ghosts = level->box_ghosts; int radius = STENCIL_RADIUS; int communicationAvoiding = ghosts > radius; // compute the Chebyshev coefficients... double beta = 1.000*level->dominant_eigenvalue_of_DinvA; //double alpha = 0.300000*beta; //double alpha = 0.250000*beta; //double alpha = 0.166666*beta; double alpha = 0.125000*beta; double theta = 0.5*(beta+alpha); // center of the spectral ellipse double delta = 0.5*(beta-alpha); // major axis? double sigma = theta/delta; double rho_n = 1/sigma; // rho_0 double chebyshev_c1[CHEBYSHEV_DEGREE]; // + c1*(x_n-x_nm1) == rho_n*rho_nm1 double chebyshev_c2[CHEBYSHEV_DEGREE]; // + c2*(b-Ax_n) chebyshev_c1[0] = 0.0; chebyshev_c2[0] = 1/theta; for(s=1;s<CHEBYSHEV_DEGREE;s++){ double rho_nm1 = rho_n; rho_n = 1.0/(2.0*sigma - rho_nm1); chebyshev_c1[s] = rho_n*rho_nm1; chebyshev_c2[s] = rho_n*2.0/delta; } // if communication-avoiding, need updated RHS for stencils in ghost zones if(communicationAvoiding)exchange_boundary(level,rhs_id,0); for(s=0;s<CHEBYSHEV_DEGREE*NUM_SMOOTHS;s+=ghosts){ // Chebyshev ping pongs between x_id and VECTOR_TEMP if((s&1)==0){exchange_boundary(level, x_id,STENCIL_IS_STAR_SHAPED && !communicationAvoiding);apply_BCs(level, x_id);} else{exchange_boundary(level,VECTOR_TEMP,STENCIL_IS_STAR_SHAPED && !communicationAvoiding);apply_BCs(level,VECTOR_TEMP);} // now do ghosts communication-avoiding smooths on each box... uint64_t _timeStart = CycleTime(); #pragma omp parallel for private(box) OMP_THREAD_ACROSS_BOXES(level->concurrent_boxes) for(box=0;box<level->num_my_boxes;box++){ int i,j,k,ss; const int jStride = level->my_boxes[box].jStride; const int kStride = level->my_boxes[box].kStride; const int dim = level->my_boxes[box].dim; const double h2inv = 1.0/(level->h*level->h); const double * __restrict__ rhs = level->my_boxes[box].vectors[ rhs_id] + ghosts*(1+jStride+kStride); const double * __restrict__ alpha = level->my_boxes[box].vectors[VECTOR_ALPHA ] + ghosts*(1+jStride+kStride); const double * __restrict__ beta_i = level->my_boxes[box].vectors[VECTOR_BETA_I] + ghosts*(1+jStride+kStride); const double * __restrict__ beta_j = level->my_boxes[box].vectors[VECTOR_BETA_J] + ghosts*(1+jStride+kStride); const double * __restrict__ beta_k = level->my_boxes[box].vectors[VECTOR_BETA_K] + ghosts*(1+jStride+kStride); const double * __restrict__ Dinv = level->my_boxes[box].vectors[VECTOR_DINV ] + ghosts*(1+jStride+kStride); const double * __restrict__ valid = level->my_boxes[box].vectors[VECTOR_VALID ] + ghosts*(1+jStride+kStride); // cell is inside the domain int ghostsToOperateOn=ghosts-1; for(ss=s;ss<s+ghosts;ss++,ghostsToOperateOn--){ double * __restrict__ x_np1; const double * __restrict__ x_n; const double * __restrict__ x_nm1; if((ss&1)==0){x_n = level->my_boxes[box].vectors[ x_id] + ghosts*(1+jStride+kStride); x_nm1 = level->my_boxes[box].vectors[VECTOR_TEMP] + ghosts*(1+jStride+kStride); x_np1 = level->my_boxes[box].vectors[VECTOR_TEMP] + ghosts*(1+jStride+kStride);} else{x_n = level->my_boxes[box].vectors[VECTOR_TEMP] + ghosts*(1+jStride+kStride); x_nm1 = level->my_boxes[box].vectors[ x_id] + ghosts*(1+jStride+kStride); x_np1 = level->my_boxes[box].vectors[ x_id] + ghosts*(1+jStride+kStride);} const double c1 = chebyshev_c1[ss%CHEBYSHEV_DEGREE]; // limit polynomial to degree CHEBYSHEV_DEGREE. const double c2 = chebyshev_c2[ss%CHEBYSHEV_DEGREE]; // limit polynomial to degree CHEBYSHEV_DEGREE. #pragma omp parallel for private(k,j,i) OMP_THREAD_WITHIN_A_BOX(level->threads_per_box) for(k=0-ghostsToOperateOn;k<dim+ghostsToOperateOn;k++){ for(j=0-ghostsToOperateOn;j<dim+ghostsToOperateOn;j++){ for(i=0-ghostsToOperateOn;i<dim+ghostsToOperateOn;i++){ int ijk = i + j*jStride + k*kStride; // According to Saad... but his was missing a Dinv[ijk] == D^{-1} !!! // x_{n+1} = x_{n} + rho_{n} [ rho_{n-1}(x_{n} - x_{n-1}) + (2/delta)(b-Ax_{n}) ] // x_temp[ijk] = x_n[ijk] + c1*(x_n[ijk]-x_temp[ijk]) + c2*Dinv[ijk]*(rhs[ijk]-Ax_n); double Ax_n = apply_op_ijk(x_n); double lambda = Dinv_ijk(); x_np1[ijk] = x_n[ijk] + c1*(x_n[ijk]-x_nm1[ijk]) + c2*lambda*(rhs[ijk]-Ax_n); }}} } // ss-loop } // box-loop level->cycles.smooth += (uint64_t)(CycleTime()-_timeStart); } // s-loop }
Parallel Programming in C - Selection Sort.c
#include <stdio.h> #include <stdlib.h> #include <time.h> #include "omp.h" /* OpenMP implementation example Details of implementation/tutorial can be found here: http://madhugnadig.com/articles/parallel-processing/2017/02/25/parallel-computing-in-c-using-openMP.html */ clock_t t, end; double cpu_time_used; // Structure for enabling reduction on the index of elements struct Compare { int val; int index; }; // Custom reduction for finding hte index of the max element. #pragma omp declare reduction(maximum : struct Compare : omp_out = omp_in.val > omp_out.val ? omp_in : omp_out) void swap(int* a, int* b); void selectionSort(int* A, int n); void verify(int* A, int n); int main(){ int number, iter =0; int* Arr; Arr = (int *)malloc( number * sizeof(int)); scanf("%d", &number); for(; iter<number; iter++){ scanf("%d", &Arr[iter]); } t = clock(); selectionSort(Arr, number); t = clock()-t; for(int iter=0; iter<number;iter++){ printf("%d ", Arr[iter]); } cpu_time_used = ((double)t)/CLOCKS_PER_SEC; // Verify if the algorithm works as advised verify(Arr, number); printf("\nTime taken for sort: %f", cpu_time_used); return 0; } void selectionSort(int* A, int n){ for(int startpos =0; startpos < n; startpos++){ // Declare the structure required for reduction struct Compare max; // Initialize the variables max.val = A[startpos]; max.index = startpos; // Parallel for loop with custom reduction, at the end of the loop, max will have the max element and its index. #pragma omp parallel for reduction(maximum:max) for(int i=startpos +1; i< n; ++i){ if(A[i] > max.val){ max.val = A[i]; max.index = i; } } swap(&A[startpos], &A[max.index]); } } // Verification function void verify(int* A, int n){ int failcount = 0; for(int iter = 0; iter < n-1; iter++){ if(A[iter] < A[iter+1]){ failcount++; } } printf("\nFail count: %d\n", failcount); } //Swap function void swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp; }
IJVector_parcsr.c
/****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * IJVector_Par interface * *****************************************************************************/ #include "_hypre_IJ_mv.h" #include "../HYPRE.h" /****************************************************************************** * * hypre_IJVectorCreatePar * * creates ParVector if necessary, and leaves a pointer to it as the * hypre_IJVector object * *****************************************************************************/ HYPRE_Int hypre_IJVectorCreatePar(hypre_IJVector *vector, HYPRE_BigInt *IJpartitioning) { MPI_Comm comm = hypre_IJVectorComm(vector); HYPRE_Int num_procs, j; HYPRE_BigInt global_n, *partitioning, jmin; hypre_MPI_Comm_size(comm, &num_procs); jmin = hypre_IJVectorGlobalFirstRow(vector); global_n = hypre_IJVectorGlobalNumRows(vector); partitioning = hypre_CTAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST); /* Shift to zero-based partitioning for ParVector object */ for (j = 0; j < 2; j++) { partitioning[j] = IJpartitioning[j] - jmin; } hypre_IJVectorObject(vector) = hypre_ParVectorCreate(comm, global_n, (HYPRE_BigInt *) partitioning); return hypre_error_flag; } /****************************************************************************** * * hypre_IJVectorDestroyPar * * frees ParVector local storage of an IJVectorPar * *****************************************************************************/ HYPRE_Int hypre_IJVectorDestroyPar(hypre_IJVector *vector) { return hypre_ParVectorDestroy((hypre_ParVector*)hypre_IJVectorObject(vector)); } /****************************************************************************** * * hypre_IJVectorInitializePar * * initializes ParVector of IJVectorPar * *****************************************************************************/ HYPRE_Int hypre_IJVectorInitializePar(hypre_IJVector *vector) { return hypre_IJVectorInitializePar_v2(vector, hypre_IJVectorMemoryLocation(vector)); } HYPRE_Int hypre_IJVectorInitializePar_v2(hypre_IJVector *vector, HYPRE_MemoryLocation memory_location) { hypre_ParVector *par_vector = (hypre_ParVector*) hypre_IJVectorObject(vector); hypre_AuxParVector *aux_vector = (hypre_AuxParVector*) hypre_IJVectorTranslator(vector); HYPRE_BigInt *partitioning = hypre_ParVectorPartitioning(par_vector); hypre_Vector *local_vector = hypre_ParVectorLocalVector(par_vector); HYPRE_Int print_level = hypre_IJVectorPrintLevel(vector); HYPRE_Int my_id; MPI_Comm comm = hypre_IJVectorComm(vector); hypre_MPI_Comm_rank(comm, &my_id); HYPRE_MemoryLocation memory_location_aux = hypre_GetExecPolicy1(memory_location) == HYPRE_EXEC_HOST ? HYPRE_MEMORY_HOST : HYPRE_MEMORY_DEVICE; if (!partitioning) { if (print_level) { hypre_printf("No ParVector partitioning for initialization -- "); hypre_printf("hypre_IJVectorInitializePar\n"); } hypre_error_in_arg(1); return hypre_error_flag; } hypre_VectorSize(local_vector) = (HYPRE_Int)(partitioning[1] - partitioning[0]); hypre_ParVectorInitialize_v2(par_vector, memory_location); if (!aux_vector) { hypre_AuxParVectorCreate(&aux_vector); hypre_IJVectorTranslator(vector) = aux_vector; } hypre_AuxParVectorInitialize_v2(aux_vector, memory_location_aux); return hypre_error_flag; } /****************************************************************************** * * hypre_IJVectorSetMaxOffProcElmtsPar * *****************************************************************************/ HYPRE_Int hypre_IJVectorSetMaxOffProcElmtsPar(hypre_IJVector *vector, HYPRE_Int max_off_proc_elmts) { hypre_AuxParVector *aux_vector; aux_vector = (hypre_AuxParVector*) hypre_IJVectorTranslator(vector); if (!aux_vector) { hypre_AuxParVectorCreate(&aux_vector); hypre_IJVectorTranslator(vector) = aux_vector; } hypre_AuxParVectorMaxOffProcElmts(aux_vector) = max_off_proc_elmts; #if defined(HYPRE_USING_CUDA) hypre_AuxParVectorUsrOffProcElmts(aux_vector) = max_off_proc_elmts; #endif return hypre_error_flag; } /****************************************************************************** * * hypre_IJVectorDistributePar * * takes an IJVector generated for one processor and distributes it * across many processors according to vec_starts, * if vec_starts is NULL, it distributes them evenly? * *****************************************************************************/ HYPRE_Int hypre_IJVectorDistributePar(hypre_IJVector *vector, const HYPRE_Int *vec_starts) { hypre_ParVector *old_vector = (hypre_ParVector*) hypre_IJVectorObject(vector); hypre_ParVector *par_vector; HYPRE_Int print_level = hypre_IJVectorPrintLevel(vector); if (!old_vector) { if (print_level) { hypre_printf("old_vector == NULL -- "); hypre_printf("hypre_IJVectorDistributePar\n"); hypre_printf("**** Vector storage is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } par_vector = hypre_VectorToParVector(hypre_ParVectorComm(old_vector), hypre_ParVectorLocalVector(old_vector), (HYPRE_BigInt *)vec_starts); if (!par_vector) { if (print_level) { hypre_printf("par_vector == NULL -- "); hypre_printf("hypre_IJVectorDistributePar\n"); hypre_printf("**** Vector storage is unallocated ****\n"); } hypre_error_in_arg(1); } hypre_ParVectorDestroy(old_vector); hypre_IJVectorObject(vector) = par_vector; return hypre_error_flag; } /****************************************************************************** * * hypre_IJVectorZeroValuesPar * * zeroes all local components of an IJVectorPar * *****************************************************************************/ HYPRE_Int hypre_IJVectorZeroValuesPar(hypre_IJVector *vector) { HYPRE_Int my_id; HYPRE_BigInt vec_start, vec_stop; hypre_ParVector *par_vector = (hypre_ParVector*) hypre_IJVectorObject(vector); MPI_Comm comm = hypre_IJVectorComm(vector); HYPRE_BigInt *partitioning; hypre_Vector *local_vector; HYPRE_Int print_level = hypre_IJVectorPrintLevel(vector); hypre_MPI_Comm_rank(comm, &my_id); /* If par_vector == NULL or partitioning == NULL or local_vector == NULL let user know of catastrophe and exit */ if (!par_vector) { if (print_level) { hypre_printf("par_vector == NULL -- "); hypre_printf("hypre_IJVectorZeroValuesPar\n"); hypre_printf("**** Vector storage is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } partitioning = hypre_ParVectorPartitioning(par_vector); local_vector = hypre_ParVectorLocalVector(par_vector); if (!partitioning) { if (print_level) { hypre_printf("partitioning == NULL -- "); hypre_printf("hypre_IJVectorZeroValuesPar\n"); hypre_printf("**** Vector partitioning is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } if (!local_vector) { if (print_level) { hypre_printf("local_vector == NULL -- "); hypre_printf("hypre_IJVectorZeroValuesPar\n"); hypre_printf("**** Vector local data is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } vec_start = partitioning[0]; vec_stop = partitioning[1]; if (vec_start > vec_stop) { if (print_level) { hypre_printf("vec_start > vec_stop -- "); hypre_printf("hypre_IJVectorZeroValuesPar\n"); hypre_printf("**** This vector partitioning should not occur ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } hypre_assert(hypre_VectorSize(local_vector) == (HYPRE_Int)(vec_stop - vec_start)); hypre_SeqVectorSetConstantValues(local_vector, 0.0); return hypre_error_flag; } /****************************************************************************** * * hypre_IJVectorSetValuesPar * * sets a potentially noncontiguous set of components of an IJVectorPar * *****************************************************************************/ HYPRE_Int hypre_IJVectorSetValuesPar(hypre_IJVector *vector, HYPRE_Int num_values, const HYPRE_BigInt *indices, const HYPRE_Complex *values) { HYPRE_Int my_id; HYPRE_Int j, k; HYPRE_BigInt i, vec_start, vec_stop; HYPRE_Complex *data; HYPRE_Int print_level = hypre_IJVectorPrintLevel(vector); HYPRE_BigInt *IJpartitioning = hypre_IJVectorPartitioning(vector); hypre_ParVector *par_vector = (hypre_ParVector*) hypre_IJVectorObject(vector); MPI_Comm comm = hypre_IJVectorComm(vector); hypre_Vector *local_vector; /* If no components are to be set, perform no checking and return */ if (num_values < 1) return 0; hypre_MPI_Comm_rank(comm, &my_id); /* If par_vector == NULL or partitioning == NULL or local_vector == NULL let user know of catastrophe and exit */ if (!par_vector) { if (print_level) { hypre_printf("par_vector == NULL -- "); hypre_printf("hypre_IJVectorSetValuesPar\n"); hypre_printf("**** Vector storage is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } local_vector = hypre_ParVectorLocalVector(par_vector); if (!IJpartitioning) { if (print_level) { hypre_printf("IJpartitioning == NULL -- "); hypre_printf("hypre_IJVectorSetValuesPar\n"); hypre_printf("**** IJVector partitioning is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } if (!local_vector) { if (print_level) { hypre_printf("local_vector == NULL -- "); hypre_printf("hypre_IJVectorSetValuesPar\n"); hypre_printf("**** Vector local data is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } vec_start = IJpartitioning[0]; vec_stop = IJpartitioning[1]-1; if (vec_start > vec_stop) { if (print_level) { hypre_printf("vec_start > vec_stop -- "); hypre_printf("hypre_IJVectorSetValuesPar\n"); hypre_printf("**** This vector partitioning should not occur ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } /* Determine whether indices points to local indices only, and if not, store indices and values in auxiliary vector structure. If indices == NULL, assume that num_values components are to be set in a block starting at vec_start. NOTE: If indices == NULL off proc values are ignored!!! */ data = hypre_VectorData(local_vector); if (indices) { for (j = 0; j < num_values; j++) { i = indices[j]; if (i >= vec_start && i <= vec_stop) { k = (HYPRE_Int)( i- vec_start); data[k] = values[j]; } } } else { if (num_values > (HYPRE_Int)(vec_stop - vec_start) + 1) { if (print_level) { hypre_printf("Warning! Indices beyond local range not identified!\n "); hypre_printf("Off processor values have been ignored!\n"); } num_values = (HYPRE_Int)(vec_stop - vec_start) +1; } #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_values; j++) data[j] = values[j]; } return hypre_error_flag; } /****************************************************************************** * * hypre_IJVectorAddToValuesPar * * adds to a potentially noncontiguous set of IJVectorPar components * *****************************************************************************/ HYPRE_Int hypre_IJVectorAddToValuesPar(hypre_IJVector *vector, HYPRE_Int num_values, const HYPRE_BigInt *indices, const HYPRE_Complex *values) { HYPRE_Int my_id; HYPRE_Int i, j, vec_start, vec_stop; HYPRE_Complex *data; HYPRE_Int print_level = hypre_IJVectorPrintLevel(vector); HYPRE_BigInt *IJpartitioning = hypre_IJVectorPartitioning(vector); hypre_ParVector *par_vector = (hypre_ParVector*) hypre_IJVectorObject(vector); hypre_AuxParVector *aux_vector = (hypre_AuxParVector*) hypre_IJVectorTranslator(vector); MPI_Comm comm = hypre_IJVectorComm(vector); hypre_Vector *local_vector; /* If no components are to be retrieved, perform no checking and return */ if (num_values < 1) return 0; hypre_MPI_Comm_rank(comm, &my_id); /* If par_vector == NULL or partitioning == NULL or local_vector == NULL let user know of catastrophe and exit */ if (!par_vector) { if (print_level) { hypre_printf("par_vector == NULL -- "); hypre_printf("hypre_IJVectorAddToValuesPar\n"); hypre_printf("**** Vector storage is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } local_vector = hypre_ParVectorLocalVector(par_vector); if (!IJpartitioning) { if (print_level) { hypre_printf("IJpartitioning == NULL -- "); hypre_printf("hypre_IJVectorAddToValuesPar\n"); hypre_printf("**** IJVector partitioning is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } if (!local_vector) { if (print_level) { hypre_printf("local_vector == NULL -- "); hypre_printf("hypre_IJVectorAddToValuesPar\n"); hypre_printf("**** Vector local data is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } vec_start = IJpartitioning[0]; vec_stop = IJpartitioning[1]-1; if (vec_start > vec_stop) { if (print_level) { hypre_printf("vec_start > vec_stop -- "); hypre_printf("hypre_IJVectorAddToValuesPar\n"); hypre_printf("**** This vector partitioning should not occur ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } data = hypre_VectorData(local_vector); if (indices) { HYPRE_Int current_num_elmts = hypre_AuxParVectorCurrentOffProcElmts(aux_vector); HYPRE_Int max_off_proc_elmts = hypre_AuxParVectorMaxOffProcElmts(aux_vector); HYPRE_BigInt *off_proc_i = hypre_AuxParVectorOffProcI(aux_vector); HYPRE_Complex *off_proc_data = hypre_AuxParVectorOffProcData(aux_vector); HYPRE_Int k; for (j = 0; j < num_values; j++) { i = indices[j]; if (i < vec_start || i > vec_stop) { /* if elements outside processor boundaries, store in off processor stash */ if (!max_off_proc_elmts) { max_off_proc_elmts = 100; hypre_AuxParVectorMaxOffProcElmts(aux_vector) = max_off_proc_elmts; hypre_AuxParVectorOffProcI(aux_vector) = hypre_CTAlloc(HYPRE_BigInt, max_off_proc_elmts, HYPRE_MEMORY_HOST); hypre_AuxParVectorOffProcData(aux_vector) = hypre_CTAlloc(HYPRE_Complex, max_off_proc_elmts, HYPRE_MEMORY_HOST); off_proc_i = hypre_AuxParVectorOffProcI(aux_vector); off_proc_data = hypre_AuxParVectorOffProcData(aux_vector); } else if (current_num_elmts + 1 > max_off_proc_elmts) { max_off_proc_elmts += 10; off_proc_i = hypre_TReAlloc(off_proc_i, HYPRE_BigInt, max_off_proc_elmts, HYPRE_MEMORY_HOST); off_proc_data = hypre_TReAlloc(off_proc_data, HYPRE_Complex, max_off_proc_elmts, HYPRE_MEMORY_HOST); hypre_AuxParVectorMaxOffProcElmts(aux_vector) = max_off_proc_elmts; hypre_AuxParVectorOffProcI(aux_vector) = off_proc_i; hypre_AuxParVectorOffProcData(aux_vector) = off_proc_data; } off_proc_i[current_num_elmts] = i; off_proc_data[current_num_elmts++] = values[j]; hypre_AuxParVectorCurrentOffProcElmts(aux_vector)=current_num_elmts; } else /* local values are added to the vector */ { k = (HYPRE_Int)(i - vec_start); data[k] += values[j]; } } } else { if (num_values > (HYPRE_Int)(vec_stop - vec_start) + 1) { if (print_level) { hypre_printf("Warning! Indices beyond local range not identified!\n "); hypre_printf("Off processor values have been ignored!\n"); } num_values = (HYPRE_Int)(vec_stop - vec_start) +1; } #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_values; j++) data[j] += values[j]; } return hypre_error_flag; } /****************************************************************************** * * hypre_IJVectorAssemblePar * * currently tests existence of of ParVector object and its partitioning * *****************************************************************************/ HYPRE_Int hypre_IJVectorAssemblePar(hypre_IJVector *vector) { HYPRE_BigInt *IJpartitioning = hypre_IJVectorPartitioning(vector); hypre_ParVector *par_vector = (hypre_ParVector*) hypre_IJVectorObject(vector); hypre_AuxParVector *aux_vector = (hypre_AuxParVector*) hypre_IJVectorTranslator(vector); HYPRE_BigInt *partitioning; MPI_Comm comm = hypre_IJVectorComm(vector); HYPRE_Int print_level = hypre_IJVectorPrintLevel(vector); if (!par_vector) { if (print_level) { hypre_printf("par_vector == NULL -- "); hypre_printf("hypre_IJVectorAssemblePar\n"); hypre_printf("**** Vector storage is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); } partitioning = hypre_ParVectorPartitioning(par_vector); if (!IJpartitioning) { if (print_level) { hypre_printf("IJpartitioning == NULL -- "); hypre_printf("hypre_IJVectorAssemblePar\n"); hypre_printf("**** IJVector partitioning is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); } if (!partitioning) { if (print_level) { hypre_printf("partitioning == NULL -- "); hypre_printf("hypre_IJVectorAssemblePar\n"); hypre_printf("**** ParVector partitioning is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); } if (aux_vector) { HYPRE_Int off_proc_elmts, current_num_elmts; HYPRE_Int max_off_proc_elmts; HYPRE_BigInt *off_proc_i; HYPRE_Complex *off_proc_data; current_num_elmts = hypre_AuxParVectorCurrentOffProcElmts(aux_vector); hypre_MPI_Allreduce(&current_num_elmts,&off_proc_elmts,1,HYPRE_MPI_INT, hypre_MPI_SUM,comm); if (off_proc_elmts) { max_off_proc_elmts=hypre_AuxParVectorMaxOffProcElmts(aux_vector); off_proc_i=hypre_AuxParVectorOffProcI(aux_vector); off_proc_data=hypre_AuxParVectorOffProcData(aux_vector); hypre_IJVectorAssembleOffProcValsPar(vector, max_off_proc_elmts, current_num_elmts, HYPRE_MEMORY_HOST, off_proc_i, off_proc_data); hypre_TFree(hypre_AuxParVectorOffProcI(aux_vector), HYPRE_MEMORY_HOST); hypre_TFree(hypre_AuxParVectorOffProcData(aux_vector), HYPRE_MEMORY_HOST); hypre_AuxParVectorMaxOffProcElmts(aux_vector) = 0; hypre_AuxParVectorCurrentOffProcElmts(aux_vector) = 0; } } return hypre_error_flag; } /****************************************************************************** * * hypre_IJVectorGetValuesPar * * get a potentially noncontiguous set of IJVectorPar components * *****************************************************************************/ HYPRE_Int hypre_IJVectorGetValuesPar(hypre_IJVector *vector, HYPRE_Int num_values, const HYPRE_BigInt *indices, HYPRE_Complex *values) { HYPRE_Int my_id; MPI_Comm comm = hypre_IJVectorComm(vector); HYPRE_BigInt *IJpartitioning = hypre_IJVectorPartitioning(vector); HYPRE_BigInt vec_start; HYPRE_BigInt vec_stop; hypre_ParVector *par_vector = (hypre_ParVector*) hypre_IJVectorObject(vector); HYPRE_Int print_level = hypre_IJVectorPrintLevel(vector); /* If no components are to be retrieved, perform no checking and return */ if (num_values < 1) { return 0; } hypre_MPI_Comm_rank(comm, &my_id); /* If par_vector == NULL or partitioning == NULL or local_vector == NULL let user know of catastrophe and exit */ if (!par_vector) { if (print_level) { hypre_printf("par_vector == NULL -- "); hypre_printf("hypre_IJVectorGetValuesPar\n"); hypre_printf("**** Vector storage is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } if (!IJpartitioning) { if (print_level) { hypre_printf("IJpartitioning == NULL -- "); hypre_printf("hypre_IJVectorGetValuesPar\n"); hypre_printf("**** IJVector partitioning is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } hypre_Vector *local_vector = hypre_ParVectorLocalVector(par_vector); if (!local_vector) { if (print_level) { hypre_printf("local_vector == NULL -- "); hypre_printf("hypre_IJVectorGetValuesPar\n"); hypre_printf("**** Vector local data is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } vec_start = IJpartitioning[0]; vec_stop = IJpartitioning[1]; if (vec_start > vec_stop) { if (print_level) { hypre_printf("vec_start > vec_stop -- "); hypre_printf("hypre_IJVectorGetValuesPar\n"); hypre_printf("**** This vector partitioning should not occur ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } hypre_assert(vec_start == hypre_ParVectorFirstIndex(par_vector)); hypre_assert(vec_stop == hypre_ParVectorLastIndex(par_vector) + 1); hypre_ParVectorGetValues(par_vector, num_values, (HYPRE_BigInt *) indices, values); return hypre_error_flag; } /****************************************************************************** * hypre_IJVectorAssembleOffProcValsPar * * This is for handling set and get values calls to off-proc. entries - it is * called from assemble. There is an alternate version for when the assumed * partition is being used. *****************************************************************************/ HYPRE_Int hypre_IJVectorAssembleOffProcValsPar( hypre_IJVector *vector, HYPRE_Int max_off_proc_elmts, HYPRE_Int current_num_elmts, HYPRE_MemoryLocation memory_location, HYPRE_BigInt *off_proc_i, HYPRE_Complex *off_proc_data) { HYPRE_Int myid; HYPRE_BigInt global_first_row, global_num_rows; HYPRE_Int i, j, in, k; HYPRE_Int proc_id, last_proc, prev_id, tmp_id; HYPRE_Int max_response_size; HYPRE_Int ex_num_contacts = 0; HYPRE_BigInt range_start, range_end; HYPRE_Int storage; HYPRE_Int indx; HYPRE_BigInt row; HYPRE_Int num_ranges, row_count; HYPRE_Int num_recvs; HYPRE_Int counter; HYPRE_BigInt upper_bound; HYPRE_Int num_real_procs; HYPRE_BigInt *row_list=NULL; HYPRE_Int *a_proc_id=NULL, *orig_order=NULL; HYPRE_Int *real_proc_id = NULL, *us_real_proc_id = NULL; HYPRE_Int *ex_contact_procs = NULL, *ex_contact_vec_starts = NULL; HYPRE_Int *recv_starts=NULL; HYPRE_BigInt *response_buf = NULL; HYPRE_Int *response_buf_starts=NULL; HYPRE_Int *num_rows_per_proc = NULL; HYPRE_Int tmp_int; HYPRE_Int obj_size_bytes, big_int_size, complex_size; HYPRE_Int first_index; void *void_contact_buf = NULL; void *index_ptr; void *recv_data_ptr; HYPRE_Complex tmp_complex; HYPRE_BigInt *ex_contact_buf=NULL; HYPRE_Complex *vector_data; HYPRE_Complex value; hypre_DataExchangeResponse response_obj1, response_obj2; hypre_ProcListElements send_proc_obj; MPI_Comm comm = hypre_IJVectorComm(vector); hypre_ParVector *par_vector = (hypre_ParVector*) hypre_IJVectorObject(vector); hypre_IJAssumedPart *apart; hypre_MPI_Comm_rank(comm, &myid); global_num_rows = hypre_IJVectorGlobalNumRows(vector); global_first_row = hypre_IJVectorGlobalFirstRow(vector); if (memory_location == HYPRE_MEMORY_DEVICE) { HYPRE_BigInt *off_proc_i_h = hypre_TAlloc(HYPRE_BigInt, current_num_elmts, HYPRE_MEMORY_HOST); HYPRE_Complex *off_proc_data_h = hypre_TAlloc(HYPRE_Complex, current_num_elmts, HYPRE_MEMORY_HOST); hypre_TMemcpy(off_proc_i_h, off_proc_i, HYPRE_BigInt, current_num_elmts, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE); hypre_TMemcpy(off_proc_data_h, off_proc_data, HYPRE_Complex, current_num_elmts, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE); off_proc_i = off_proc_i_h; off_proc_data = off_proc_data_h; } /* call hypre_IJVectorAddToValuesParCSR directly inside this function * with one chunk of data */ HYPRE_Int off_proc_nelm_recv_cur = 0; HYPRE_Int off_proc_nelm_recv_max = 0; HYPRE_BigInt *off_proc_i_recv = NULL; HYPRE_Complex *off_proc_data_recv = NULL; HYPRE_BigInt *off_proc_i_recv_d = NULL; HYPRE_Complex *off_proc_data_recv_d = NULL; /* verify that we have created the assumed partition */ if (hypre_IJVectorAssumedPart(vector) == NULL) { hypre_IJVectorCreateAssumedPartition(vector); } apart = (hypre_IJAssumedPart*) hypre_IJVectorAssumedPart(vector); /* get the assumed processor id for each row */ a_proc_id = hypre_CTAlloc(HYPRE_Int, current_num_elmts, HYPRE_MEMORY_HOST); orig_order = hypre_CTAlloc(HYPRE_Int, current_num_elmts, HYPRE_MEMORY_HOST); real_proc_id = hypre_CTAlloc(HYPRE_Int, current_num_elmts, HYPRE_MEMORY_HOST); row_list = hypre_CTAlloc(HYPRE_BigInt, current_num_elmts, HYPRE_MEMORY_HOST); if (current_num_elmts > 0) { for (i=0; i < current_num_elmts; i++) { row = off_proc_i[i]; row_list[i] = row; hypre_GetAssumedPartitionProcFromRow(comm, row, global_first_row, global_num_rows, &proc_id); a_proc_id[i] = proc_id; orig_order[i] = i; } /* now we need to find the actual order of each row - sort on row - this will result in proc ids sorted also...*/ hypre_BigQsortb2i(row_list, a_proc_id, orig_order, 0, current_num_elmts -1); /* calculate the number of contacts */ ex_num_contacts = 1; last_proc = a_proc_id[0]; for (i=1; i < current_num_elmts; i++) { if (a_proc_id[i] > last_proc) { ex_num_contacts++; last_proc = a_proc_id[i]; } } } /* now we will go through a create a contact list - need to contact assumed processors and find out who the actual row owner is - we will contact with a range (2 numbers) */ ex_contact_procs = hypre_CTAlloc(HYPRE_Int, ex_num_contacts, HYPRE_MEMORY_HOST); ex_contact_vec_starts = hypre_CTAlloc(HYPRE_Int, ex_num_contacts+1, HYPRE_MEMORY_HOST); ex_contact_buf = hypre_CTAlloc(HYPRE_BigInt, ex_num_contacts*2, HYPRE_MEMORY_HOST); counter = 0; range_end = -1; for (i=0; i< current_num_elmts; i++) { if (row_list[i] > range_end) { /* assumed proc */ proc_id = a_proc_id[i]; /* end of prev. range */ if (counter > 0) ex_contact_buf[counter*2 - 1] = row_list[i-1]; /*start new range*/ ex_contact_procs[counter] = proc_id; ex_contact_vec_starts[counter] = counter*2; ex_contact_buf[counter*2] = row_list[i]; counter++; hypre_GetAssumedPartitionRowRange(comm, proc_id, global_first_row, global_num_rows, &range_start, &range_end); } } /*finish the starts*/ ex_contact_vec_starts[counter] = counter*2; /*finish the last range*/ if (counter > 0) ex_contact_buf[counter*2 - 1] = row_list[current_num_elmts - 1]; /* create response object - can use same fill response as used in the commpkg routine */ response_obj1.fill_response = hypre_RangeFillResponseIJDetermineRecvProcs; response_obj1.data1 = apart; /* this is necessary so we can fill responses*/ response_obj1.data2 = NULL; max_response_size = 6; /* 6 means we can fit 3 ranges*/ hypre_DataExchangeList(ex_num_contacts, ex_contact_procs, ex_contact_buf, ex_contact_vec_starts, sizeof(HYPRE_BigInt), sizeof(HYPRE_BigInt), &response_obj1, max_response_size, 4, comm, (void**) &response_buf, &response_buf_starts); /* now response_buf contains a proc_id followed by an upper bound for the range. */ hypre_TFree(ex_contact_procs, HYPRE_MEMORY_HOST); hypre_TFree(ex_contact_buf, HYPRE_MEMORY_HOST); hypre_TFree(ex_contact_vec_starts, HYPRE_MEMORY_HOST); hypre_TFree(a_proc_id, HYPRE_MEMORY_HOST); a_proc_id = NULL; /*how many ranges were returned?*/ num_ranges = response_buf_starts[ex_num_contacts]; num_ranges = num_ranges/2; prev_id = -1; j = 0; counter = 0; num_real_procs = 0; /* loop through ranges - create a list of actual processor ids*/ for (i=0; i<num_ranges; i++) { upper_bound = response_buf[i*2+1]; counter = 0; tmp_id = (HYPRE_Int)response_buf[i*2]; /* loop through row_list entries - counting how many are in the range */ while (j < current_num_elmts && row_list[j] <= upper_bound) { real_proc_id[j] = tmp_id; j++; counter++; } if (counter > 0 && tmp_id != prev_id) { num_real_procs++; } prev_id = tmp_id; } /* now we have the list of real procesors ids (real_proc_id) - and the number of distinct ones - so now we can set up data to be sent - we have HYPRE_Int and HYPRE_Complex data. (row number and value) - we will send everything as a void since we may not know the rel sizes of ints and doubles */ /* first find out how many elements to send per proc - so we can do storage */ complex_size = sizeof(HYPRE_Complex); big_int_size = sizeof(HYPRE_BigInt); obj_size_bytes = hypre_max(big_int_size, complex_size); ex_contact_procs = hypre_CTAlloc(HYPRE_Int, num_real_procs, HYPRE_MEMORY_HOST); num_rows_per_proc = hypre_CTAlloc(HYPRE_Int, num_real_procs, HYPRE_MEMORY_HOST); counter = 0; if (num_real_procs > 0 ) { ex_contact_procs[0] = real_proc_id[0]; num_rows_per_proc[0] = 1; /* loop through real procs - these are sorted (row_list is sorted also)*/ for (i=1; i < current_num_elmts; i++) { if (real_proc_id[i] == ex_contact_procs[counter]) /* same processor */ { num_rows_per_proc[counter] += 1; /*another row */ } else /* new processor */ { counter++; ex_contact_procs[counter] = real_proc_id[i]; num_rows_per_proc[counter] = 1; } } } /* calculate total storage and make vec_starts arrays */ storage = 0; ex_contact_vec_starts = hypre_CTAlloc(HYPRE_Int, num_real_procs + 1, HYPRE_MEMORY_HOST); ex_contact_vec_starts[0] = -1; for (i=0; i < num_real_procs; i++) { storage += 1 + 2* num_rows_per_proc[i]; ex_contact_vec_starts[i+1] = -storage-1; /* need negative for next loop */ } /*void_contact_buf = hypre_MAlloc(storage*obj_size_bytes);*/ void_contact_buf = hypre_CTAlloc(char, storage*obj_size_bytes, HYPRE_MEMORY_HOST); index_ptr = void_contact_buf; /* step through with this index */ /* set up data to be sent to send procs */ /* for each proc, ex_contact_buf_d contains #rows, row #, data, etc. */ /* un-sort real_proc_id - we want to access data arrays in order */ us_real_proc_id = hypre_CTAlloc(HYPRE_Int, current_num_elmts, HYPRE_MEMORY_HOST); for (i=0; i < current_num_elmts; i++) { us_real_proc_id[orig_order[i]] = real_proc_id[i]; } hypre_TFree(real_proc_id, HYPRE_MEMORY_HOST); prev_id = -1; for (i=0; i < current_num_elmts; i++) { proc_id = us_real_proc_id[i]; /* can't use row list[i] - you loose the negative signs that differentiate add/set values */ row = off_proc_i[i]; /* find position of this processor */ indx = hypre_BinarySearch(ex_contact_procs, proc_id, num_real_procs); in = ex_contact_vec_starts[indx]; index_ptr = (void *) ((char *) void_contact_buf + in*obj_size_bytes); /* first time for this processor - add the number of rows to the buffer */ if (in < 0) { in = -in - 1; /* re-calc. index_ptr since in_i was negative */ index_ptr = (void *) ((char *) void_contact_buf + in*obj_size_bytes); tmp_int = num_rows_per_proc[indx]; hypre_TMemcpy( index_ptr, &tmp_int, HYPRE_Int, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); index_ptr = (void *) ((char *) index_ptr + obj_size_bytes); in++; } /* add row # */ hypre_TMemcpy( index_ptr, &row, HYPRE_BigInt,1 , HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); index_ptr = (void *) ((char *) index_ptr + obj_size_bytes); in++; /* add value */ tmp_complex = off_proc_data[i]; hypre_TMemcpy( index_ptr, &tmp_complex, HYPRE_Complex, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); index_ptr = (void *) ((char *) index_ptr + obj_size_bytes); in++; /* increment the indexes to keep track of where we are - fix later */ ex_contact_vec_starts[indx] = in; } /* some clean up */ hypre_TFree(response_buf, HYPRE_MEMORY_HOST); hypre_TFree(response_buf_starts, HYPRE_MEMORY_HOST); hypre_TFree(us_real_proc_id, HYPRE_MEMORY_HOST); hypre_TFree(orig_order, HYPRE_MEMORY_HOST); hypre_TFree(row_list, HYPRE_MEMORY_HOST); hypre_TFree(num_rows_per_proc, HYPRE_MEMORY_HOST); for (i=num_real_procs; i > 0; i--) { ex_contact_vec_starts[i] = ex_contact_vec_starts[i-1]; } ex_contact_vec_starts[0] = 0; /* now send the data */ /***********************************/ /* now get the info in send_proc_obj_d */ /* the response we expect is just a confirmation*/ response_buf = NULL; response_buf_starts = NULL; /*build the response object*/ /* use the send_proc_obj for the info kept from contacts */ /*estimate inital storage allocation */ send_proc_obj.length = 0; send_proc_obj.storage_length = num_real_procs + 5; send_proc_obj.id = NULL; /* don't care who sent it to us */ send_proc_obj.vec_starts = hypre_CTAlloc(HYPRE_Int, send_proc_obj.storage_length + 1, HYPRE_MEMORY_HOST); send_proc_obj.vec_starts[0] = 0; send_proc_obj.element_storage_length = storage + 20; send_proc_obj.v_elements = hypre_TAlloc(char, obj_size_bytes*send_proc_obj.element_storage_length, HYPRE_MEMORY_HOST); response_obj2.fill_response = hypre_FillResponseIJOffProcVals; response_obj2.data1 = NULL; response_obj2.data2 = &send_proc_obj; max_response_size = 0; hypre_DataExchangeList(num_real_procs, ex_contact_procs, void_contact_buf, ex_contact_vec_starts, obj_size_bytes, 0, &response_obj2, max_response_size, 5, comm, (void **) &response_buf, &response_buf_starts); /***********************************/ hypre_TFree(response_buf, HYPRE_MEMORY_HOST); hypre_TFree(response_buf_starts, HYPRE_MEMORY_HOST); hypre_TFree(ex_contact_procs, HYPRE_MEMORY_HOST); hypre_TFree(void_contact_buf, HYPRE_MEMORY_HOST); hypre_TFree(ex_contact_vec_starts, HYPRE_MEMORY_HOST); /* Now we can unpack the send_proc_objects and either set or add to the vector data */ num_recvs = send_proc_obj.length; /* alias */ recv_data_ptr = send_proc_obj.v_elements; recv_starts = send_proc_obj.vec_starts; vector_data = hypre_VectorData(hypre_ParVectorLocalVector(par_vector)); first_index = hypre_ParVectorFirstIndex(par_vector); for (i=0; i < num_recvs; i++) { indx = recv_starts[i]; /* get the number of rows for this recv */ hypre_TMemcpy( &row_count, recv_data_ptr, HYPRE_Int, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); recv_data_ptr = (void *) ((char *)recv_data_ptr + obj_size_bytes); indx++; for (j=0; j < row_count; j++) /* for each row: unpack info */ { /* row # */ hypre_TMemcpy( &row, recv_data_ptr, HYPRE_BigInt, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); recv_data_ptr = (void *) ((char *)recv_data_ptr + obj_size_bytes); indx++; /* value */ hypre_TMemcpy( &value, recv_data_ptr, HYPRE_Complex, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); recv_data_ptr = (void *) ((char *)recv_data_ptr + obj_size_bytes); indx++; if (memory_location == HYPRE_MEMORY_HOST) { k = (HYPRE_Int)(row - first_index - global_first_row); vector_data[k] += value; } else { if (off_proc_nelm_recv_cur >= off_proc_nelm_recv_max) { off_proc_nelm_recv_max = 2 * (off_proc_nelm_recv_cur + 1); off_proc_i_recv = hypre_TReAlloc(off_proc_i_recv, HYPRE_BigInt, off_proc_nelm_recv_max, HYPRE_MEMORY_HOST); off_proc_data_recv = hypre_TReAlloc(off_proc_data_recv, HYPRE_Complex, off_proc_nelm_recv_max, HYPRE_MEMORY_HOST); } off_proc_i_recv[off_proc_nelm_recv_cur] = row; off_proc_data_recv[off_proc_nelm_recv_cur] = value; off_proc_nelm_recv_cur ++; } } } if (memory_location == HYPRE_MEMORY_DEVICE) { off_proc_i_recv_d = hypre_TAlloc(HYPRE_BigInt, off_proc_nelm_recv_cur, HYPRE_MEMORY_DEVICE); off_proc_data_recv_d = hypre_TAlloc(HYPRE_Complex, off_proc_nelm_recv_cur, HYPRE_MEMORY_DEVICE); hypre_TMemcpy(off_proc_i_recv_d, off_proc_i_recv, HYPRE_BigInt, off_proc_nelm_recv_cur, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_HOST); hypre_TMemcpy(off_proc_data_recv_d, off_proc_data_recv, HYPRE_Complex, off_proc_nelm_recv_cur, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_HOST); #if defined(HYPRE_USING_CUDA) hypre_IJVectorSetAddValuesParDevice(vector, off_proc_nelm_recv_cur, off_proc_i_recv_d, off_proc_data_recv_d, "add"); #endif } hypre_TFree(send_proc_obj.v_elements, HYPRE_MEMORY_HOST); hypre_TFree(send_proc_obj.vec_starts, HYPRE_MEMORY_HOST); if (memory_location == HYPRE_MEMORY_DEVICE) { hypre_TFree(off_proc_i, HYPRE_MEMORY_HOST); hypre_TFree(off_proc_data, HYPRE_MEMORY_HOST); } hypre_TFree(off_proc_i_recv, HYPRE_MEMORY_HOST); hypre_TFree(off_proc_data_recv, HYPRE_MEMORY_HOST); hypre_TFree(off_proc_i_recv_d, HYPRE_MEMORY_DEVICE); hypre_TFree(off_proc_data_recv_d, HYPRE_MEMORY_DEVICE); return hypre_error_flag; }
image_random-inl.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. */ /*! * \file image_random-inl.h * \brief * \author */ #ifndef MXNET_OPERATOR_IMAGE_IMAGE_RANDOM_INL_H_ #define MXNET_OPERATOR_IMAGE_IMAGE_RANDOM_INL_H_ #include <algorithm> #include <cmath> #include <limits> #include <tuple> #include <utility> #include <vector> #include "mxnet/base.h" #include "../mxnet_op.h" #include "../operator_common.h" #if MXNET_USE_OPENCV #include <opencv2/opencv.hpp> #endif // MXNET_USE_OPENCV namespace mxnet { namespace op { namespace image { using namespace mshadow; #if MXNET_USE_CUDA // NOTE: Kernel launch/map was extremely costly. // Hence, we use separate CUDA kernels for these operators. template<typename DType, typename T1, typename T2> void ToTensorImplCUDA(mshadow::Stream<gpu> *s, const T1 input, const T2 output, const int req, const float normalize_factor); template<typename DType> void NormalizeImplCUDA(mshadow::Stream<gpu> *s, const DType *input, DType *output, const int req, const int N, const int C, const int H, const int W, const float mean_d0, const float mean_d1, const float mean_d2, const float std_d0, const float std_d1, const float std_d2); template<typename DType> void NormalizeBackwardImplCUDA(mshadow::Stream<gpu> *s, const DType *out_grad, DType *in_grad, const int req, const int N, const int C, const int H, const int W, const float std_d0, const float std_d1, const float std_d2); #endif // MXNET_USE_CUDA // Shape and Type inference for image to tensor operator inline bool ToTensorShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { CHECK_EQ(in_attrs->size(), 1U); CHECK_EQ(out_attrs->size(), 1U); mxnet::TShape &shp = (*in_attrs)[0]; if (!shape_is_known(shp)) return false; CHECK((shp.ndim() == 3) || (shp.ndim() == 4)) << "Input image must have shape (height, width, channels), or " << "(N, height, width, channels) but got " << shp; if (shp.ndim() == 3) { SHAPE_ASSIGN_CHECK(*out_attrs, 0, mxnet::TShape({shp[2], shp[0], shp[1]})); } else if (shp.ndim() == 4) { SHAPE_ASSIGN_CHECK(*out_attrs, 0, mxnet::TShape({shp[0], shp[3], shp[1], shp[2]})); } return true; } inline bool ToTensorType(const nnvm::NodeAttrs& attrs, std::vector<int> *in_attrs, std::vector<int> *out_attrs) { CHECK_EQ(in_attrs->size(), 1U); CHECK_EQ(out_attrs->size(), 1U); TYPE_ASSIGN_CHECK(*out_attrs, 0, mshadow::kFloat32); return (*in_attrs)[0] != -1; } // Operator Implementation template<typename DType, int req> inline void ToTensor(float* out_data, const DType* in_data, const int length, const int channels, const float normalize_factor, const int step) { // Microsoft Visual C++ compiler does not support omp collapse #ifdef _MSC_VER #pragma omp parallel for #else #pragma omp parallel for collapse(2) #endif // _MSC_VER for (int c = 0; c < channels; ++c) { for (int i = 0; i < length; ++i) { KERNEL_ASSIGN(out_data[step + c*length + i], req, (in_data[step + i*channels + c]) / normalize_factor); } } } inline void ToTensorImpl(const std::vector<TBlob> &inputs, const std::vector<TBlob> &outputs, const std::vector<OpReqType> &req, const int length, const int channel, const float normalize_factor, const int step) { MSHADOW_TYPE_SWITCH(inputs[0].type_flag_, DType, { MXNET_ASSIGN_REQ_SWITCH(req[0], req_type, { float* output = outputs[0].dptr<float>(); DType* input = inputs[0].dptr<DType>(); ToTensor<DType, req_type>(output, input, length, channel, normalize_factor, step); }); }); } template<typename xpu> void ToTensorOpForward(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { CHECK_EQ(inputs.size(), 1U); CHECK_EQ(outputs.size(), 1U); CHECK_EQ(req.size(), 1U); // We do not use temp buffer when performance the operation. // Hence, this check is necessary. CHECK_EQ(req[0], kWriteTo) << "`to_tensor` does not support inplace updates"; const float normalize_factor = 255.0f; if (std::is_same<xpu, gpu>::value) { #if MXNET_USE_CUDA mshadow::Stream<gpu> *s = ctx.get_stream<gpu>(); MSHADOW_TYPE_SWITCH(inputs[0].type_flag_, DType, { MXNET_ASSIGN_REQ_SWITCH(req[0], req_type, { if (inputs[0].ndim() == 3) { Tensor<gpu, 3, DType> input = inputs[0].get<gpu, 3, DType>(s); Tensor<gpu, 3, float> output = outputs[0].get<gpu, 3, float>(s); ToTensorImplCUDA<DType, Tensor<gpu, 3, DType>, Tensor<gpu, 3, float>> (s, input, output, req_type, normalize_factor); } else { Tensor<gpu, 4, DType> input = inputs[0].get<gpu, 4, DType>(s); Tensor<gpu, 4, float> output = outputs[0].get<gpu, 4, float>(s); ToTensorImplCUDA<DType, Tensor<gpu, 4, DType>, Tensor<gpu, 4, float>> (s, input, output, req_type, normalize_factor); } }); }); #else LOG(FATAL) << "Compile with USE_CUDA=1 to use ToTensor operator on GPU."; #endif // MXNET_USE_CUDA } else if (inputs[0].ndim() == 3) { // 3D Input - (h, w, c) const int length = inputs[0].shape_[0] * inputs[0].shape_[1]; const int channel = static_cast<int>(inputs[0].shape_[2]); const int step = 0; ToTensorImpl(inputs, outputs, req, length, channel, normalize_factor, step); } else if (inputs[0].ndim() == 4) { // 4D input (n, h, w, c) const int batch_size = inputs[0].shape_[0]; const int length = inputs[0].shape_[1] * inputs[0].shape_[2]; const int channel = static_cast<int>(inputs[0].shape_[3]); const int step = channel * length; #pragma omp parallel for for (auto n = 0; n < batch_size; ++n) { ToTensorImpl(inputs, outputs, req, length, channel, normalize_factor, n*step); } } } struct NormalizeParam : public dmlc::Parameter<NormalizeParam> { mxnet::Tuple<float> mean; mxnet::Tuple<float> std; DMLC_DECLARE_PARAMETER(NormalizeParam) { DMLC_DECLARE_FIELD(mean) .set_default(mxnet::Tuple<float> {0.0f, 0.0f, 0.0f, 0.0f}) .describe("Sequence of means for each channel. " "Default value is 0."); DMLC_DECLARE_FIELD(std) .set_default(mxnet::Tuple<float> {1.0f, 1.0f, 1.0f, 1.0f}) .describe("Sequence of standard deviations for each channel. " "Default value is 1."); } }; // Shape and Type inference for image Normalize operator // Shape inference inline bool NormalizeOpShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { const NormalizeParam &param = nnvm::get<NormalizeParam>(attrs.parsed); const auto& dshape = (*in_attrs)[0]; if (!dshape.ndim()) return false; CHECK((dshape.ndim() == 3) || (dshape.ndim() == 4)) << "Input tensor must have shape (channels, height, width), or " << "(N, channels, height, width), but got " << dshape; int nchannels = 0; if (dshape.ndim() == 3) { nchannels = dshape[0]; CHECK(nchannels == 3 || nchannels == 1) << "The first dimension of input tensor must be the channel dimension with " << "either 1 or 3 elements, but got input with shape " << dshape; } else if (dshape.ndim() == 4) { nchannels = dshape[1]; CHECK(nchannels == 3 || nchannels == 1) << "The second dimension of input tensor must be the channel dimension with " << "either 1 or 3 elements, but got input with shape " << dshape; } CHECK((param.mean.ndim() == 1) || (param.mean.ndim() == nchannels)) << "Invalid mean for input with shape " << dshape << ". mean must have either 1 or " << nchannels << " elements, but got " << param.mean; CHECK(param.std.ndim() == 1 || param.std.ndim() == nchannels) << "Invalid std for input with shape " << dshape << ". std must have either 1 or " << nchannels << " elements, but got " << param.std; SHAPE_ASSIGN_CHECK(*out_attrs, 0, dshape); return true; } // Type Inference inline bool NormalizeOpType(const nnvm::NodeAttrs& attrs, std::vector<int>* in_attrs, std::vector<int>* out_attrs) { CHECK_EQ(in_attrs->size(), 1U); CHECK_EQ(out_attrs->size(), 1U); TYPE_ASSIGN_CHECK(*out_attrs, 0, in_attrs->at(0)); TYPE_ASSIGN_CHECK(*in_attrs, 0, out_attrs->at(0)); return out_attrs->at(0) != -1; } template<typename DType, int req> inline void Normalize(DType* out_data, const DType* in_data, const int length, const int channels, const int step, const std::vector<float> mean, const std::vector<float> std) { // Microsoft Visual C++ compiler does not support omp collapse #ifdef _MSC_VER #pragma omp parallel for #else #pragma omp parallel for collapse(2) #endif // _MSC_VER for (int c = 0; c < channels; ++c) { for (int i = 0; i < length; ++i) { KERNEL_ASSIGN(out_data[step + c*length + i], req, (in_data[step + c*length + i] - mean[c]) / std[c]); } } } inline void NormalizeImpl(const std::vector<TBlob> &inputs, const std::vector<TBlob> &outputs, const std::vector<OpReqType> &req, const int length, const int channels, const int step, const std::vector<float> mean, const std::vector<float> std) { MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { MXNET_ASSIGN_REQ_SWITCH(req[0], req_type, { DType* input = inputs[0].dptr<DType>(); DType* output = outputs[0].dptr<DType>(); Normalize<DType, req_type>(output, input, length, channels, step, mean, std); }); }); } template<typename xpu> void NormalizeOpForward(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { CHECK_EQ(inputs.size(), 1U); CHECK_EQ(outputs.size(), 1U); CHECK_EQ(req.size(), 1U); const NormalizeParam &param = nnvm::get<NormalizeParam>(attrs.parsed); // Mean and Std can be 1 or 3D only. std::vector<float> mean(3); std::vector<float> std(3); if (param.mean.ndim() == 1) { mean[0] = mean[1] = mean[3] = param.mean[0]; } else { mean[0] = param.mean[0]; mean[1] = param.mean[1]; mean[2] = param.mean[2]; } if (param.std.ndim() == 1) { std[0] = std[1] = std[2] = param.std[0]; } else { std[0] = param.std[0]; std[1] = param.std[1]; std[2] = param.std[2]; } if (std::is_same<xpu, gpu>::value) { #if MXNET_USE_CUDA mshadow::Stream<gpu> *s = ctx.get_stream<gpu>(); MSHADOW_TYPE_SWITCH(inputs[0].type_flag_, DType, { MXNET_ASSIGN_REQ_SWITCH(req[0], req_type, { int N, C, H, W; DType *input = nullptr; DType *output = nullptr; if (inputs[0].ndim() == 3) { N = 1; C = static_cast<int>(inputs[0].shape_[0]); H = static_cast<int>(inputs[0].shape_[1]); W = static_cast<int>(inputs[0].shape_[2]); input = (inputs[0].get<gpu, 3, DType>(s)).dptr_; output = (outputs[0].get<gpu, 3, DType>(s)).dptr_; } else { N = static_cast<int>(inputs[0].shape_[0]); C = static_cast<int>(inputs[0].shape_[1]); H = static_cast<int>(inputs[0].shape_[2]); W = static_cast<int>(inputs[0].shape_[3]); input = (inputs[0].get<gpu, 4, DType>(s)).dptr_; output = (outputs[0].get<gpu, 4, DType>(s)).dptr_; } NormalizeImplCUDA<DType>(s, input, output, req_type, N, C, H, W, mean[0], mean[1], mean[2], std[0], std[1], std[2]); }); }); #else LOG(FATAL) << "Compile with USE_CUDA=1 to use Normalize operator on GPU."; #endif // MXNET_USE_CUDA } else if (inputs[0].ndim() == 3) { // 3D input (c, h, w) const int length = inputs[0].shape_[1] * inputs[0].shape_[2]; const int channel = static_cast<int>(inputs[0].shape_[0]); const int step = 0; NormalizeImpl(inputs, outputs, req, length, channel, step, mean, std); } else if (inputs[0].ndim() == 4) { // 4D input (n, c, h, w) const int batch_size = inputs[0].shape_[0]; const int length = inputs[0].shape_[2] * inputs[0].shape_[3]; const int channel = static_cast<int>(inputs[0].shape_[1]); const int step = channel * length; #pragma omp parallel for for (auto n = 0; n < batch_size; ++n) { NormalizeImpl(inputs, outputs, req, length, channel, n*step, mean, std); } } } // Backward function template<typename DType, int req> inline void NormalizeBackward(const DType* out_grad, DType* in_grad, const int length, const int channels, const int step, const std::vector<float> std) { // Microsoft Visual C++ compiler does not support omp collapse #ifdef _MSC_VER #pragma omp parallel for #else #pragma omp parallel for collapse(2) #endif // _MSC_VER for (int c = 0; c < channels; ++c) { for (int i = 0; i < length; ++i) { KERNEL_ASSIGN(in_grad[step + c*length + i], req, out_grad[step + c*length + i] * (1.0 / std[c])); } } } inline void NormalizeBackwardImpl(const std::vector<TBlob> &inputs, const std::vector<TBlob> &outputs, const std::vector<OpReqType> &req, const int length, const int channels, const int step, const std::vector<float> std ) { MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { MXNET_ASSIGN_REQ_SWITCH(req[0], req_type, { DType* out_grad = inputs[0].dptr<DType>(); DType* in_grad = outputs[0].dptr<DType>(); NormalizeBackward<DType, req_type>(out_grad, in_grad, length, channels, step, std); }); }); } template<typename xpu> void NormalizeOpBackward(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { CHECK_EQ(inputs.size(), 2U); CHECK_EQ(outputs.size(), 1U); CHECK_EQ(req.size(), 1U); const NormalizeParam &param = nnvm::get<NormalizeParam>(attrs.parsed); // Std can be 1 or 3D only. std::vector<float> std(3); if (param.std.ndim() == 1) { std[0] = std[1] = std[2] = param.std[0]; } else { std[0] = param.std[0]; std[1] = param.std[1]; std[2] = param.std[2]; } // Note: inputs[0] is out_grad const TBlob& in_data = inputs[1]; if (std::is_same<xpu, gpu>::value) { #if MXNET_USE_CUDA mshadow::Stream<gpu> *s = ctx.get_stream<gpu>(); MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { MXNET_ASSIGN_REQ_SWITCH(req[0], req_type, { int N, C, H, W; DType *in_grad = nullptr; DType *out_grad = nullptr; if (in_data.ndim() == 3) { N = 1; C = static_cast<int>(in_data.shape_[0]); H = static_cast<int>(in_data.shape_[1]); W = static_cast<int>(in_data.shape_[2]); out_grad = (inputs[0].get<gpu, 3, DType>(s)).dptr_; in_grad = (outputs[0].get<gpu, 3, DType>(s)).dptr_; } else { N = static_cast<int>(in_data.shape_[0]); C = static_cast<int>(in_data.shape_[1]); H = static_cast<int>(in_data.shape_[2]); W = static_cast<int>(in_data.shape_[3]); out_grad = (inputs[0].get<gpu, 4, DType>(s)).dptr_; in_grad = (outputs[0].get<gpu, 4, DType>(s)).dptr_; } NormalizeBackwardImplCUDA<DType>(s, out_grad, in_grad, req_type, N, C, H, W, std[0], std[1], std[2]); }); }); #else LOG(FATAL) << "Compile with USE_CUDA=1 to use Normalize backward operator on GPU."; #endif // MXNET_USE_CUDA } else if (in_data.ndim() == 3) { // 3D input (c, h, w) const int length = in_data.shape_[1] * in_data.shape_[2]; const int channel = static_cast<int>(in_data.shape_[0]); const int step = 0; NormalizeBackwardImpl(inputs, outputs, req, length, channel, step, std); } else if (in_data.ndim() == 4) { // 4D input (n, c, h, w) const int batch_size = in_data.shape_[0]; const int length = in_data.shape_[2] * in_data.shape_[3]; const int channel = static_cast<int>(in_data.shape_[1]); const int step = channel * length; #pragma omp parallel for for (auto n = 0; n < batch_size; ++n) { NormalizeBackwardImpl(inputs, outputs, req, length, channel, n*step, std); } } } template<typename DType> inline DType saturate_cast(const float& src) { return static_cast<DType>(src); } template<> inline uint8_t saturate_cast(const float& src) { return std::min(std::max(src, 0.f), 255.f); } inline bool ImageShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { mxnet::TShape& dshape = (*in_attrs)[0]; CHECK_EQ(dshape.ndim(), 3) << "Input image must have shape (height, width, channels), but got " << dshape; auto nchannels = dshape[dshape.ndim()-1]; CHECK(nchannels == 3 || nchannels == 1) << "The last dimension of input image must be the channel dimension with " << "either 1 or 3 elements, but got input with shape " << dshape; SHAPE_ASSIGN_CHECK(*out_attrs, 0, dshape); return true; } template<typename DType, int axis> void FlipImpl(const mxnet::TShape &shape, DType *src, DType *dst) { int head = 1, mid = shape[axis], tail = 1; for (int i = 0; i < axis; ++i) head *= shape[i]; for (int i = axis+1; i < shape.ndim(); ++i) tail *= shape[i]; for (int i = 0; i < head; ++i) { for (int j = 0; j < (mid >> 1); ++j) { int idx1 = (i*mid + j) * tail; int idx2 = idx1 + (mid-(j << 1)-1) * tail; for (int k = 0; k < tail; ++k, ++idx1, ++idx2) { DType tmp = src[idx1]; dst[idx1] = src[idx2]; dst[idx2] = tmp; } } } } inline void FlipLeftRight(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mshadow; MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { FlipImpl<DType, 1>(inputs[0].shape_, inputs[0].dptr<DType>(), outputs[0].dptr<DType>()); }); } inline void FlipTopBottom(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mshadow; MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { FlipImpl<DType, 0>(inputs[0].shape_, inputs[0].dptr<DType>(), outputs[0].dptr<DType>()); }); } inline void RandomFlipLeftRight( const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mshadow; Stream<cpu> *s = ctx.get_stream<cpu>(); Random<cpu> *prnd = ctx.requested[0].get_random<cpu, float>(s); MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { if (std::bernoulli_distribution()(prnd->GetRndEngine())) { if (outputs[0].dptr_ != inputs[0].dptr_) { std::memcpy(outputs[0].dptr_, inputs[0].dptr_, inputs[0].Size() * sizeof(DType)); } } else { FlipImpl<DType, 1>(inputs[0].shape_, inputs[0].dptr<DType>(), outputs[0].dptr<DType>()); } }); } inline void RandomFlipTopBottom( const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mshadow; Stream<cpu> *s = ctx.get_stream<cpu>(); Random<cpu> *prnd = ctx.requested[0].get_random<cpu, float>(s); MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { if (std::bernoulli_distribution()(prnd->GetRndEngine())) { if (outputs[0].dptr_ != inputs[0].dptr_) { std::memcpy(outputs[0].dptr_, inputs[0].dptr_, inputs[0].Size() * sizeof(DType)); } } else { FlipImpl<DType, 0>(inputs[0].shape_, inputs[0].dptr<DType>(), outputs[0].dptr<DType>()); } }); } struct RandomEnhanceParam : public dmlc::Parameter<RandomEnhanceParam> { float min_factor; float max_factor; DMLC_DECLARE_PARAMETER(RandomEnhanceParam) { DMLC_DECLARE_FIELD(min_factor) .set_lower_bound(0.0) .describe("Minimum factor."); DMLC_DECLARE_FIELD(max_factor) .set_lower_bound(0.0) .describe("Maximum factor."); } }; inline void AdjustBrightnessImpl(const float& alpha_b, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mshadow; int length = inputs[0].Size(); MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { DType* output = outputs[0].dptr<DType>(); DType* input = inputs[0].dptr<DType>(); for (int l = 0; l < length; ++l) { float val = static_cast<float>(input[l]) * alpha_b; output[l] = saturate_cast<DType>(val); } }); } inline void RandomBrightness(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mshadow; const RandomEnhanceParam &param = nnvm::get<RandomEnhanceParam>(attrs.parsed); Stream<cpu> *s = ctx.get_stream<cpu>(); Random<cpu> *prnd = ctx.requested[0].get_random<cpu, float>(s); float alpha_b = std::uniform_real_distribution<float>( param.min_factor, param.max_factor)(prnd->GetRndEngine()); AdjustBrightnessImpl(alpha_b, ctx, inputs, req, outputs); } inline void AdjustContrastImpl(const float& alpha_c, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mshadow; static const float coef[] = { 0.299f, 0.587f, 0.114f }; int length = inputs[0].shape_[0] * inputs[0].shape_[1]; int nchannels = inputs[0].shape_[2]; MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { DType* output = outputs[0].dptr<DType>(); DType* input = inputs[0].dptr<DType>(); float sum = 0.f; if (nchannels > 1) { for (int l = 0; l < length; ++l) { for (int c = 0; c < 3; ++c) sum += input[l*3 + c] * coef[c]; } } else { for (int l = 0; l < length; ++l) sum += input[l]; } float gray_mean = sum / static_cast<float>(length); float beta = (1 - alpha_c) * gray_mean; for (int l = 0; l < length * nchannels; ++l) { float val = input[l] * alpha_c + beta; output[l] = saturate_cast<DType>(val); } }); } inline void RandomContrast(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mshadow; const RandomEnhanceParam &param = nnvm::get<RandomEnhanceParam>(attrs.parsed); Stream<cpu> *s = ctx.get_stream<cpu>(); Random<cpu> *prnd = ctx.requested[0].get_random<cpu, real_t>(s); float alpha_c = std::uniform_real_distribution<float>( param.min_factor, param.max_factor)(prnd->GetRndEngine()); AdjustContrastImpl(alpha_c, ctx, inputs, req, outputs); } inline void AdjustSaturationImpl(const float& alpha_s, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { static const float coef[] = { 0.299f, 0.587f, 0.114f }; int length = inputs[0].shape_[0] * inputs[0].shape_[1]; int nchannels = inputs[0].shape_[2]; float alpha_o = 1.f - alpha_s; MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { DType* output = outputs[0].dptr<DType>(); DType* input = inputs[0].dptr<DType>(); if (nchannels == 1) { for (int l = 0; l < length; ++l) output[l] = input[l]; return; } for (int l = 0; l < length; ++l) { float gray = 0.f; for (int c = 0; c < 3; ++c) { gray = input[l*3 + c] * coef[c]; } gray *= alpha_o; for (int c = 0; c < 3; ++c) { float val = gray + input[l*3 + c] * alpha_s; output[l*3 + c] = saturate_cast<DType>(val); } } }); } inline void RandomSaturation(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mshadow; const RandomEnhanceParam &param = nnvm::get<RandomEnhanceParam>(attrs.parsed); Stream<cpu> *s = ctx.get_stream<cpu>(); Random<cpu> *prnd = ctx.requested[0].get_random<cpu, real_t>(s); float alpha_s = std::uniform_real_distribution<float>( param.min_factor, param.max_factor)(prnd->GetRndEngine()); AdjustSaturationImpl(alpha_s, ctx, inputs, req, outputs); } inline void RGB2HLSConvert(const float& src_r, const float& src_g, const float& src_b, float *dst_h, float *dst_l, float *dst_s) { float b = src_b / 255.f, g = src_g / 255.f, r = src_r / 255.f; float h = 0.f, s = 0.f, l; float vmin; float vmax; float diff; vmax = vmin = r; vmax = std::fmax(vmax, g); vmax = std::fmax(vmax, b); vmin = std::fmin(vmin, g); vmin = std::fmin(vmin, b); diff = vmax - vmin; l = (vmax + vmin) * 0.5f; if (diff > std::numeric_limits<float>::epsilon()) { s = (l < 0.5f) * diff / (vmax + vmin); s += (l >= 0.5f) * diff / (2.0f - vmax - vmin); diff = 60.f / diff; h = (vmax == r) * (g - b) * diff; h += (vmax != r && vmax == g) * ((b - r) * diff + 120.f); h += (vmax != r && vmax != g) * ((r - g) * diff + 240.f); h += (h < 0.f) * 360.f; } *dst_h = h; *dst_l = l; *dst_s = s; } inline void HLS2RGBConvert(const float& src_h, const float& src_l, const float& src_s, float *dst_r, float *dst_g, float *dst_b) { static const int c_HlsSectorData[6][3] = { { 1, 3, 0 }, { 1, 0, 2 }, { 3, 0, 1 }, { 0, 2, 1 }, { 0, 1, 3 }, { 2, 1, 0 } }; float h = src_h, l = src_l, s = src_s; float b = l, g = l, r = l; if (s != 0) { float p2 = (l <= 0.5f) * l * (1 + s); p2 += (l > 0.5f) * (l + s - l * s); float p1 = 2 * l - p2; h *= 1.f / 60.f; if (h < 0) { do { h += 6; } while (h < 0); } else if (h >= 6) { do { h -= 6; } while (h >= 6); } int sector = static_cast<int>(h); h -= sector; float tab[4]; tab[0] = p2; tab[1] = p1; tab[2] = p1 + (p2 - p1) * (1 - h); tab[3] = p1 + (p2 - p1) * h; b = tab[c_HlsSectorData[sector][0]]; g = tab[c_HlsSectorData[sector][1]]; r = tab[c_HlsSectorData[sector][2]]; } *dst_b = b * 255.f; *dst_g = g * 255.f; *dst_r = r * 255.f; } inline void AdjustHueImpl(float alpha, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { int length = inputs[0].shape_[0] * inputs[0].shape_[1]; if (inputs[0].shape_[2] == 1) return; MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { DType* input = inputs[0].dptr<DType>(); DType* output = outputs[0].dptr<DType>(); for (int i = 0; i < length; ++i) { float h, l, s; float r = static_cast<float>(*(input++)); float g = static_cast<float>(*(input++)); float b = static_cast<float>(*(input++)); RGB2HLSConvert(r, g, b, &h, &l, &s); h += alpha * 360.f; HLS2RGBConvert(h, l, s, &r, &g, &b); *(output++) = saturate_cast<DType>(r); *(output++) = saturate_cast<DType>(g); *(output++) = saturate_cast<DType>(b); } }); } inline void RandomHue(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mshadow; const RandomEnhanceParam &param = nnvm::get<RandomEnhanceParam>(attrs.parsed); Stream<cpu> *s = ctx.get_stream<cpu>(); Random<cpu> *prnd = ctx.requested[0].get_random<cpu, real_t>(s); float alpha = std::uniform_real_distribution<float>( param.min_factor, param.max_factor)(prnd->GetRndEngine()); AdjustHueImpl(alpha, ctx, inputs, req, outputs); } struct RandomColorJitterParam : public dmlc::Parameter<RandomColorJitterParam> { float brightness; float contrast; float saturation; float hue; DMLC_DECLARE_PARAMETER(RandomColorJitterParam) { DMLC_DECLARE_FIELD(brightness) .describe("How much to jitter brightness."); DMLC_DECLARE_FIELD(contrast) .describe("How much to jitter contrast."); DMLC_DECLARE_FIELD(saturation) .describe("How much to jitter saturation."); DMLC_DECLARE_FIELD(hue) .describe("How much to jitter hue."); } }; inline void RandomColorJitter(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mshadow; const RandomColorJitterParam &param = nnvm::get<RandomColorJitterParam>(attrs.parsed); Stream<cpu> *s = ctx.get_stream<cpu>(); Random<cpu> *prnd = ctx.requested[0].get_random<cpu, real_t>(s); int order[4] = {0, 1, 2, 3}; std::shuffle(order, order + 4, prnd->GetRndEngine()); bool flag = false; for (int i = 0; i < 4; ++i) { switch (order[i]) { case 0: if (param.brightness > 0) { float alpha_b = 1.0 + std::uniform_real_distribution<float>( -param.brightness, param.brightness)(prnd->GetRndEngine()); AdjustBrightnessImpl(alpha_b, ctx, flag ? outputs : inputs, req, outputs); flag = true; } break; case 1: if (param.contrast > 0) { float alpha_c = 1.0 + std::uniform_real_distribution<float>( -param.contrast, param.contrast)(prnd->GetRndEngine()); AdjustContrastImpl(alpha_c, ctx, flag ? outputs : inputs, req, outputs); flag = true; } break; case 2: if (param.saturation > 0) { float alpha_s = 1.f + std::uniform_real_distribution<float>( -param.saturation, param.saturation)(prnd->GetRndEngine()); AdjustSaturationImpl(alpha_s, ctx, flag ? outputs : inputs, req, outputs); flag = true; } break; case 3: if (param.hue > 0) { float alpha_h = std::uniform_real_distribution<float>( -param.hue, param.hue)(prnd->GetRndEngine()); AdjustHueImpl(alpha_h, ctx, flag ? outputs : inputs, req, outputs); flag = true; } break; } } } struct AdjustLightingParam : public dmlc::Parameter<AdjustLightingParam> { mxnet::Tuple<float> alpha; DMLC_DECLARE_PARAMETER(AdjustLightingParam) { DMLC_DECLARE_FIELD(alpha) .describe("The lighting alphas for the R, G, B channels."); } }; struct RandomLightingParam : public dmlc::Parameter<RandomLightingParam> { float alpha_std; DMLC_DECLARE_PARAMETER(RandomLightingParam) { DMLC_DECLARE_FIELD(alpha_std) .set_default(0.05) .describe("Level of the lighting noise."); } }; inline void AdjustLightingImpl(const mxnet::Tuple<float>& alpha, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { static const float eig[3][3] = { { 55.46 * -0.5675, 4.794 * 0.7192, 1.148 * 0.4009 }, { 55.46 * -0.5808, 4.794 * -0.0045, 1.148 * -0.8140 }, { 55.46 * -0.5836, 4.794 * -0.6948, 1.148 * 0.4203 } }; int length = inputs[0].shape_[0] * inputs[0].shape_[1]; int channels = inputs[0].shape_[2]; if (channels == 1) return; float pca_r = eig[0][0] * alpha[0] + eig[0][1] * alpha[1] + eig[0][2] * alpha[2]; float pca_g = eig[1][0] * alpha[0] + eig[1][1] * alpha[1] + eig[1][2] * alpha[2]; float pca_b = eig[2][0] * alpha[0] + eig[2][1] * alpha[1] + eig[2][2] * alpha[2]; MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { DType* output = outputs[0].dptr<DType>(); DType* input = inputs[0].dptr<DType>(); for (int i = 0; i < length; i++) { int base_ind = 3 * i; float in_r = static_cast<float>(input[base_ind]); float in_g = static_cast<float>(input[base_ind + 1]); float in_b = static_cast<float>(input[base_ind + 2]); output[base_ind] = saturate_cast<DType>(in_r + pca_r); output[base_ind + 1] = saturate_cast<DType>(in_g + pca_g); output[base_ind + 2] = saturate_cast<DType>(in_b + pca_b); } }); } inline void AdjustLighting(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mshadow; const AdjustLightingParam &param = nnvm::get<AdjustLightingParam>(attrs.parsed); AdjustLightingImpl(param.alpha, ctx, inputs, req, outputs); } inline void RandomLighting(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mshadow; const RandomLightingParam &param = nnvm::get<RandomLightingParam>(attrs.parsed); Stream<cpu> *s = ctx.get_stream<cpu>(); Random<cpu> *prnd = ctx.requested[0].get_random<cpu, float>(s); std::normal_distribution<float> dist(0, param.alpha_std); float alpha_r = dist(prnd->GetRndEngine()); float alpha_g = dist(prnd->GetRndEngine()); float alpha_b = dist(prnd->GetRndEngine()); AdjustLightingImpl({alpha_r, alpha_g, alpha_b}, ctx, inputs, req, outputs); } #define MXNET_REGISTER_IMAGE_AUG_OP(name) \ NNVM_REGISTER_OP(name) \ .set_num_inputs(1) \ .set_num_outputs(1) \ .set_attr<nnvm::FInplaceOption>("FInplaceOption", \ [](const NodeAttrs& attrs){ \ return std::vector<std::pair<int, int> >{{0, 0}}; \ }) \ .set_attr<mxnet::FInferShape>("FInferShape", ImageShape) \ .set_attr<nnvm::FInferType>("FInferType", ElemwiseType<1, 1>) \ .set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseNone{ "_copy" }) \ .add_argument("data", "NDArray-or-Symbol", "The input.") #define MXNET_REGISTER_IMAGE_RND_AUG_OP(name) \ MXNET_REGISTER_IMAGE_AUG_OP(name) \ .set_attr<FResourceRequest>("FResourceRequest", \ [](const NodeAttrs& attrs) { \ return std::vector<ResourceRequest>{ResourceRequest::kRandom}; \ }) } // namespace image } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_IMAGE_IMAGE_RANDOM_INL_H_
SwathFile.h
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2016. // // This software is released under a three-clause BSD license: // * 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 any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // 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 ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #ifndef OPENMS_FORMAT_SWATHFILE_H #define OPENMS_FORMAT_SWATHFILE_H #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/FORMAT/MzMLFile.h> #include <OpenMS/FORMAT/MzXMLFile.h> #ifdef OPENMS_FORMAT_SWATHFILE_MZXMLSUPPORT #include <OpenMS/FORMAT/MzXMLFile.h> #endif #include <OpenMS/FORMAT/DATAACCESS/SwathFileConsumer.h> namespace OpenMS { /** * @brief File adapter for Swath files. * * This class can load SWATH files in different storage versions. The most * convenient file is a single MzML file which contains one experiment. * However, also the loading of a list of files is supported (loadSplit) * where it is assumed that each individual file only contains scans from one * precursor isolation window (one SWATH). Finally, experimental support for * mzXML is available but needs to be selected with a specific compile flag * (this is not for everyday use). * */ class OPENMS_DLLAPI SwathFile : public ProgressLogger { public: /// Loads a Swath run from a list of split mzML files std::vector<OpenSwath::SwathMap> loadSplit(StringList file_list, String tmp, boost::shared_ptr<ExperimentalSettings>& exp_meta, String readoptions = "normal") { int progress = 0; startProgress(0, file_list.size(), "Loading data"); std::vector<OpenSwath::SwathMap> swath_maps(file_list.size()); #ifdef _OPENMP #pragma omp parallel for #endif for (SignedSize i = 0; i < boost::numeric_cast<SignedSize>(file_list.size()); ++i) { #ifdef _OPENMP #pragma omp critical (OPENMS_SwathFile_loadSplit) #endif { std::cout << "Loading file " << i << " with name " << file_list[i] << " using readoptions " << readoptions << std::endl; } String tmp_fname = "openswath_tmpfile_" + String(i) + ".mzML"; boost::shared_ptr<MSExperiment<Peak1D> > exp(new MSExperiment<Peak1D>); OpenSwath::SpectrumAccessPtr spectra_ptr; // Populate meta-data if (i == 0) { exp_meta = populateMetaData_(file_list[i]); } if (readoptions == "normal") { MzMLFile().load(file_list[i], *exp.get()); spectra_ptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(exp); } else if (readoptions == "cache") { // Cache and load the exp (metadata only) file again spectra_ptr = doCacheFile_(file_list[i], tmp, tmp_fname, exp); } else { throw Exception::IllegalArgument(__FILE__, __LINE__, __PRETTY_FUNCTION__, "Unknown option " + readoptions); } OpenSwath::SwathMap swath_map; bool ms1 = false; double upper = -1, lower = -1; if (exp->size() == 0) { std::cerr << "WARNING: File " << file_list[i] << "\n does not have any scans - I will skip it" << std::endl; continue; } if (exp->getSpectra()[0].getPrecursors().size() == 0) { std::cout << "NOTE: File " << file_list[i] << "\n does not have any precursors - I will assume it is the MS1 scan." << std::endl; ms1 = true; } else { // Checks that this is really a SWATH map and extracts upper/lower window OpenSwathHelper::checkSwathMap(*exp.get(), lower, upper); } swath_map.sptr = spectra_ptr; swath_map.lower = lower; swath_map.upper = upper; swath_map.ms1 = ms1; #ifdef _OPENMP #pragma omp critical (OPENMS_SwathFile_loadSplit) #endif { LOG_DEBUG << "Adding Swath file " << file_list[i] << " with " << swath_map.lower << " to " << swath_map.upper << std::endl; swath_maps[i] = swath_map; setProgress(progress++); } } endProgress(); return swath_maps; } /// Loads a Swath run from a single mzML file std::vector<OpenSwath::SwathMap> loadMzML(String file, String tmp, boost::shared_ptr<ExperimentalSettings>& exp_meta, String readoptions = "normal") { std::cout << "Loading mzML file " << file << " using readoptions " << readoptions << std::endl; String tmp_fname = "openswath_tmpfile"; startProgress(0, 1, "Loading metadata file " + file); boost::shared_ptr<MSExperiment<Peak1D> > experiment_metadata = populateMetaData_(file); exp_meta = experiment_metadata; // First pass through the file -> get the meta data std::cout << "Will analyze the metadata first to determine the number of SWATH windows and the window sizes." << std::endl; std::vector<int> swath_counter; int nr_ms1_spectra; std::vector<OpenSwath::SwathMap> known_window_boundaries; countScansInSwath_(experiment_metadata->getSpectra(), swath_counter, nr_ms1_spectra, known_window_boundaries); std::cout << "Determined there to be " << swath_counter.size() << " SWATH windows and in total " << nr_ms1_spectra << " MS1 spectra" << std::endl; endProgress(); FullSwathFileConsumer* dataConsumer; boost::shared_ptr<MSExperiment<Peak1D> > exp(new MSExperiment<Peak1D>); startProgress(0, 1, "Loading data file " + file); if (readoptions == "normal") { dataConsumer = new RegularSwathFileConsumer(known_window_boundaries); MzMLFile().transform(file, dataConsumer, *exp.get()); } else if (readoptions == "cache") { dataConsumer = new CachedSwathFileConsumer(known_window_boundaries, tmp, tmp_fname, nr_ms1_spectra, swath_counter); MzMLFile().transform(file, dataConsumer, *exp.get()); } else { throw Exception::IllegalArgument(__FILE__, __LINE__, __PRETTY_FUNCTION__, "Unknown or unsupported option " + readoptions); } LOG_DEBUG << "Finished parsing Swath file " << std::endl; std::vector<OpenSwath::SwathMap> swath_maps; dataConsumer->retrieveSwathMaps(swath_maps); delete dataConsumer; endProgress(); return swath_maps; } /// Loads a Swath run from a single mzXML file std::vector<OpenSwath::SwathMap> loadMzXML(String file, String tmp, boost::shared_ptr<ExperimentalSettings>& exp_meta, String readoptions = "normal") { std::cout << "Loading mzXML file " << file << " using readoptions " << readoptions << std::endl; String tmp_fname = "openswath_tmpfile"; startProgress(0, 1, "Loading metadata file " + file); boost::shared_ptr<MSExperiment<Peak1D> > experiment_metadata(new MSExperiment<Peak1D>); MzXMLFile f; f.getOptions().setAlwaysAppendData(true); f.getOptions().setFillData(false); f.load(file, *experiment_metadata); exp_meta = experiment_metadata; // First pass through the file -> get the meta data std::cout << "Will analyze the metadata first to determine the number of SWATH windows and the window sizes." << std::endl; std::vector<int> swath_counter; int nr_ms1_spectra; std::vector<OpenSwath::SwathMap> known_window_boundaries; countScansInSwath_(experiment_metadata->getSpectra(), swath_counter, nr_ms1_spectra, known_window_boundaries); std::cout << "Determined there to be " << swath_counter.size() << " SWATH windows and in total " << nr_ms1_spectra << " MS1 spectra" << std::endl; endProgress(); FullSwathFileConsumer* dataConsumer; boost::shared_ptr<MSExperiment<Peak1D> > exp(new MSExperiment<Peak1D>); startProgress(0, 1, "Loading data file " + file); if (readoptions == "normal") { dataConsumer = new RegularSwathFileConsumer(known_window_boundaries); MzXMLFile().transform(file, dataConsumer, *exp.get()); } else if (readoptions == "cache") { dataConsumer = new CachedSwathFileConsumer(known_window_boundaries, tmp, tmp_fname, nr_ms1_spectra, swath_counter); MzXMLFile().transform(file, dataConsumer, *exp.get()); } else { throw Exception::IllegalArgument(__FILE__, __LINE__, __PRETTY_FUNCTION__, "Unknown or unsupported option " + readoptions); } LOG_DEBUG << "Finished parsing Swath file " << std::endl; std::vector<OpenSwath::SwathMap> swath_maps; dataConsumer->retrieveSwathMaps(swath_maps); delete dataConsumer; endProgress(); return swath_maps; } protected: /// Cache a file to disk OpenSwath::SpectrumAccessPtr doCacheFile_(String in, String tmp, String tmp_fname, boost::shared_ptr<MSExperiment<Peak1D> > experiment_metadata) { String cached_file = tmp + tmp_fname + ".cached"; String meta_file = tmp + tmp_fname; // Create new consumer, transform infile, write out metadata MSDataCachedConsumer* cachedConsumer = new MSDataCachedConsumer(cached_file, true); MzMLFile().transform(in, cachedConsumer, *experiment_metadata.get()); CachedmzML().writeMetadata(*experiment_metadata.get(), meta_file, true); delete cachedConsumer; // ensure that filestream gets closed boost::shared_ptr<MSExperiment<Peak1D> > exp(new MSExperiment<Peak1D>); MzMLFile().load(meta_file, *exp.get()); return SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(exp); } /// Only read the meta data from a file and use it to populate exp_meta boost::shared_ptr< MSExperiment<Peak1D> > populateMetaData_(String file) { boost::shared_ptr<MSExperiment<Peak1D> > experiment_metadata(new MSExperiment<Peak1D>); MzMLFile f; f.getOptions().setAlwaysAppendData(true); f.getOptions().setFillData(false); f.load(file, *experiment_metadata); return experiment_metadata; } /// Counts the number of scans in a full Swath file (e.g. concatenated non-split file) void countScansInSwath_(const std::vector<MSSpectrum<> > exp, std::vector<int>& swath_counter, int& nr_ms1_spectra, std::vector<OpenSwath::SwathMap>& known_window_boundaries) { int ms1_counter = 0; for (Size i = 0; i < exp.size(); i++) { const MSSpectrum<>& s = exp[i]; { if (s.getMSLevel() == 1) { ms1_counter++; } else { if (s.getPrecursors().empty()) { throw Exception::InvalidParameter(__FILE__, __LINE__, __PRETTY_FUNCTION__, "Found SWATH scan (MS level 2 scan) without a precursor. Cannot determine SWATH window."); } const std::vector<Precursor> prec = s.getPrecursors(); double center = prec[0].getMZ(); bool found = false; for (Size j = 0; j < known_window_boundaries.size(); j++) { // We group by the precursor mz (center of the window) since this // should be present if (std::fabs(center - known_window_boundaries[j].center) < 1e-6) { found = true; swath_counter[j]++; } } if (!found) { // we found a new SWATH scan swath_counter.push_back(1); double lower = prec[0].getMZ() - prec[0].getIsolationWindowLowerOffset(); double upper = prec[0].getMZ() + prec[0].getIsolationWindowUpperOffset(); OpenSwath::SwathMap boundary; boundary.lower = lower; boundary.upper = upper; boundary.center = center; known_window_boundaries.push_back(boundary); LOG_DEBUG << "Adding Swath centered at " << center << " m/z with an isolation window of " << lower << " to " << upper << " m/z." << std::endl; } } } } nr_ms1_spectra = ms1_counter; std::cout << "Determined there to be " << swath_counter.size() << " SWATH windows and in total " << nr_ms1_spectra << " MS1 spectra" << std::endl; } }; } #endif
omp-maxof-elements-lock.c
/*********************************************************************************** Example 3.2 : omp-maxof-elements-lock.c Objective : Write an OpenMP program to print Largest of an element in an array This example demonstrates the use of omp_init_lock(),omp_set_lock(),omp_unset_lock(), omp_destroy_lock() which are known as LOCK functions. Input : Number of threads Number of elements of the array Input Output : Each thread checks with its available iterations and finally Master thread prints the maximum value in the array,Time taken to find the Max Element and also the threads . Created :Aug 2011. Author : RarchK ****************************************************************************/ #include <stdio.h> #include <omp.h> #include <stdlib.h> #include <sys/time.h> #define MINUS_INFINITY -9999 #define MAXIMUM_VALUE 65535 /* Main Program */ main(int argc,char **argv) { int *array, i, Noofelements, cur_max, current_value,Noofthreads; struct timeval TimeValue_Start; struct timezone TimeZone_Start; struct timeval TimeValue_Final; struct timezone TimeZone_Final; long time_start, time_end; double time_overhead; omp_lock_t MAXLOCK; printf("\n\t\t---------------------------------------------------------------------------"); printf("\n\t\t Email : RarchK"); printf("\n\t\t---------------------------------------------------------------------------"); printf("\n\t\t Objective : Finding Maximum element of an Array "); printf("\n\t\t This example demonstrates the use of OpenMP Lock routines such as : omp_init_lock()"); printf("\n\t\t omp_set_lock(),omp_unset_lock(), omp_destroy_lock(). "); printf("\n\t\t..........................................................................\n"); /* Checking for command line arguments */ if( argc != 3 ){ printf("\t\t Very Few Arguments\n "); printf("\t\t Syntax : exec <Threads> <No. of elements> \n"); exit(-1); } Noofthreads=atoi(argv[1]); if ((Noofthreads!=1) && (Noofthreads!=2) && (Noofthreads!=4) && (Noofthreads!=8) && (Noofthreads!= 16) ) { printf("\n Number of threads should be 1,2,4,8 or 16 for the execution of program. \n\n"); exit(-1); } Noofelements=atoi(argv[2]); /* printf("\n\t\t Enter the number of elements\n"); scanf("%d", &Noofelements);*/ printf("\n\t\t Threads : %d",Noofthreads); printf("\n\t\t Number of elements in Array : %d \n ",Noofelements); if (Noofelements <= 0) { printf("\n\t\t The array elements cannot be stored\n"); exit(1); } /* Dynamic Memory Allocation */ array = (int *) malloc(sizeof(int) * Noofelements); /* Allocating Random Number To Array Elements */ srand(MAXIMUM_VALUE); for (i = 0; i < Noofelements; i++) array[i] = rand(); if (Noofelements == 1) { printf("\n\t\t The Largest Element In The Array Is %d", array[0]); exit(1); } gettimeofday(&TimeValue_Start, &TimeZone_Start); /* set the no. of threads */ omp_set_num_threads(Noofthreads); /* Initialize the lock variable */ omp_init_lock(&MAXLOCK); cur_max = MINUS_INFINITY; /* OpenMP Parallel For Directive And Lock Functions : Fork the team of threads */ #pragma omp parallel for for (i = 0; i < Noofelements; i = i + 1) { if (array[i] > cur_max) { omp_set_lock(&MAXLOCK); if (array[i] > cur_max) cur_max = array[i]; omp_unset_lock(&MAXLOCK); } } /* End of the parallel section */ /* Destroying The Lock */ omp_destroy_lock(&MAXLOCK); gettimeofday(&TimeValue_Final, &TimeZone_Final); /* calculate the timing for the computation */ time_start = TimeValue_Start.tv_sec * 1000000 + TimeValue_Start.tv_usec; time_end = TimeValue_Final.tv_sec * 1000000 + TimeValue_Final.tv_usec; time_overhead = (time_end - time_start)/1000000.0; /* Serial Calculation */ current_value = array[0]; for (i = 1; i < Noofelements; i++) if (array[i] > current_value) current_value = array[i]; /* Checking For Output Validity */ if (current_value == cur_max) printf("\n\n\t\t The Max Value Is Same For Serial And Using Parallel OpenMP Directive\n"); else { printf("\n\n\t\t The Max Value Is Not Same In Serial And Using Parallel OpenMP Directive\n"); exit(-1); } /* Freeing Allocated Memory */ free(array); printf("\n\t\t The Largest Number Of The Array Is %d\n", cur_max); printf("\n\t\t Time in Seconds (T) : %lf Seconds \n",time_overhead); printf("\n\t\t..........................................................................\n"); }
integral_serial.c
#include<stdio.h> #include<omp.h> #define NUM_THREADS 4 static long num_steps = 100000; double step; int main(){ int i, nthreads; double pi = 0.0, init_time, finish_time; step = 1.0 / (double)num_steps; init_time = omp_get_wtime(); omp_set_num_threads(NUM_THREADS); #pragma omp parallel { int i, id, nthrds; double x, sum = 0.0; id = omp_get_thread_num(); nthrds = omp_get_num_threads(); if (id == 0) nthreads = nthrds; for (i=id ; i<num_steps ; i=i+nthrds){ x = (i+0.5)*step; #pragma omp critical sum += 4.0/(1.0+x*x); } pi += sum*step; } finish_time = omp_get_wtime()-init_time; printf("PI = %f\n", pi); printf("Time = %f\n", finish_time); }
MD5_std.c
/* * This file is part of John the Ripper password cracker, * Copyright (c) 1996-2001,2003,2006,2011 by Solar Designer * * Redistribution and use in source and binary forms, with or without * modification, are permitted. * * There's ABSOLUTELY NO WARRANTY, express or implied. * * This implementation of FreeBSD-style MD5-based crypt(3) password hashing * supports passwords of up to 15 characters long only since this lets us use a * significantly faster algorithm. -- SD */ #include <string.h> #include "arch.h" #include "common.h" #include "MD5_std.h" #include "cryptmd5_common.h" #if MD5_std_mt #include <omp.h> int MD5_std_min_kpc, MD5_std_max_kpc; int MD5_std_nt; MD5_std_combined *MD5_std_all_p = NULL; static char saved_salt[9]; static int salt_changed; #else MD5_std_combined CC_CACHE_ALIGN MD5_std_all; #endif #include "memdbg.h" #if !MD5_IMM static const MD5_data MD5_data_init = { { 0xd76aa477, 0xf8fa0bcc, 0xbcdb4dd9, 0xb18b7a77, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 }, { 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476 }, { 0x77777777, 0x00ff00ff } }; #endif #if !MD5_ASM #define S11 7 #define S12 12 #define S13 17 #define S14 22 #define S21 5 #define S22 9 #define S23 14 #define S24 20 #define S31 4 #define S32 11 #define S33 16 #define S34 23 #define S41 6 #define S42 10 #define S43 15 #define S44 21 #if MD5_IMM /* * Using immediate values is good for CISC. */ #define AC1 0xd76aa477 #define AC2pCd 0xf8fa0bcc #define AC3pCc 0xbcdb4dd9 #define AC4pCb 0xb18b7a77 #define AC5 0xf57c0faf #define AC6 0x4787c62a #define AC7 0xa8304613 #define AC8 0xfd469501 #define AC9 0x698098d8 #define AC10 0x8b44f7af #define AC11 0xffff5bb1 #define AC12 0x895cd7be #define AC13 0x6b901122 #define AC14 0xfd987193 #define AC15 0xa679438e #define AC16 0x49b40821 #define AC17 0xf61e2562 #define AC18 0xc040b340 #define AC19 0x265e5a51 #define AC20 0xe9b6c7aa #define AC21 0xd62f105d #define AC22 0x02441453 #define AC23 0xd8a1e681 #define AC24 0xe7d3fbc8 #define AC25 0x21e1cde6 #define AC26 0xc33707d6 #define AC27 0xf4d50d87 #define AC28 0x455a14ed #define AC29 0xa9e3e905 #define AC30 0xfcefa3f8 #define AC31 0x676f02d9 #define AC32 0x8d2a4c8a #define AC33 0xfffa3942 #define AC34 0x8771f681 #define AC35 0x6d9d6122 #define AC36 0xfde5380c #define AC37 0xa4beea44 #define AC38 0x4bdecfa9 #define AC39 0xf6bb4b60 #define AC40 0xbebfbc70 #define AC41 0x289b7ec6 #define AC42 0xeaa127fa #define AC43 0xd4ef3085 #define AC44 0x04881d05 #define AC45 0xd9d4d039 #define AC46 0xe6db99e5 #define AC47 0x1fa27cf8 #define AC48 0xc4ac5665 #define AC49 0xf4292244 #define AC50 0x432aff97 #define AC51 0xab9423a7 #define AC52 0xfc93a039 #define AC53 0x655b59c3 #define AC54 0x8f0ccc92 #define AC55 0xffeff47d #define AC56 0x85845dd1 #define AC57 0x6fa87e4f #define AC58 0xfe2ce6e0 #define AC59 0xa3014314 #define AC60 0x4e0811a1 #define AC61 0xf7537e82 #define AC62 0xbd3af235 #define AC63 0x2ad7d2bb #define AC64 0xeb86d391 #define Ca 0x67452301 #define Cb 0xefcdab89 #define Cc 0x98badcfe #define Cd 0x10325476 #define MASK1 0x77777777 #define OOFFOOFF 0x00ff00ff #else /* * If we used immediate values on RISC with 32-bit instruction size, it would * take about twice more instructions to load all the values. */ #define MD5_AC MD5_std_all.data.AC #define AC1 MD5_AC[0] #define AC2pCd MD5_AC[1] #define AC3pCc MD5_AC[2] #define AC4pCb MD5_AC[3] #define AC5 MD5_AC[4] #define AC6 MD5_AC[5] #define AC7 MD5_AC[6] #define AC8 MD5_AC[7] #define AC9 MD5_AC[8] #define AC10 MD5_AC[9] #define AC11 MD5_AC[10] #define AC12 MD5_AC[11] #define AC13 MD5_AC[12] #define AC14 MD5_AC[13] #define AC15 MD5_AC[14] #define AC16 MD5_AC[15] #define AC17 MD5_AC[16] #define AC18 MD5_AC[17] #define AC19 MD5_AC[18] #define AC20 MD5_AC[19] #define AC21 MD5_AC[20] #define AC22 MD5_AC[21] #define AC23 MD5_AC[22] #define AC24 MD5_AC[23] #define AC25 MD5_AC[24] #define AC26 MD5_AC[25] #define AC27 MD5_AC[26] #define AC28 MD5_AC[27] #define AC29 MD5_AC[28] #define AC30 MD5_AC[29] #define AC31 MD5_AC[30] #define AC32 MD5_AC[31] #define AC33 MD5_AC[32] #define AC34 MD5_AC[33] #define AC35 MD5_AC[34] #define AC36 MD5_AC[35] #define AC37 MD5_AC[36] #define AC38 MD5_AC[37] #define AC39 MD5_AC[38] #define AC40 MD5_AC[39] #define AC41 MD5_AC[40] #define AC42 MD5_AC[41] #define AC43 MD5_AC[42] #define AC44 MD5_AC[43] #define AC45 MD5_AC[44] #define AC46 MD5_AC[45] #define AC47 MD5_AC[46] #define AC48 MD5_AC[47] #define AC49 MD5_AC[48] #define AC50 MD5_AC[49] #define AC51 MD5_AC[50] #define AC52 MD5_AC[51] #define AC53 MD5_AC[52] #define AC54 MD5_AC[53] #define AC55 MD5_AC[54] #define AC56 MD5_AC[55] #define AC57 MD5_AC[56] #define AC58 MD5_AC[57] #define AC59 MD5_AC[58] #define AC60 MD5_AC[59] #define AC61 MD5_AC[60] #define AC62 MD5_AC[61] #define AC63 MD5_AC[62] #define AC64 MD5_AC[63] #define MD5_IV MD5_std_all.data.IV #define Ca MD5_IV[0] #define Cb MD5_IV[1] #define Cc MD5_IV[2] #define Cd MD5_IV[3] #define MASK1 MD5_std_all.data.masks[0] #define OOFFOOFF MD5_std_all.data.masks[1] #endif /* * F, G, H and I are basic MD5 functions. */ #define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z)))) #define G(x, y, z) ((y) ^ ((z) & ((x) ^ (y)))) #define H(x, y, z) (((x) ^ (y)) ^ (z)) #define H2(x, y, z) ((x) ^ ((y) ^ (z))) #define I(x, y, z) ((y) ^ ((x) | ~(z))) /* * ROTATE_LEFT rotates x left n bits. */ #define ROTATE_LEFT(x, n) \ (x) = (((x) << (n)) | ((MD5_word)(x) >> (32 - (n)))) /* * FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. * Rotation is separate from addition to prevent recomputation. */ #define FF(a, b, c, d, x, s, ac) \ (a) += F ((b), (c), (d)) + (x) + (ac); \ ROTATE_LEFT ((a), (s)); \ (a) += (b); #define GG(a, b, c, d, x, s, ac) \ (a) += G ((b), (c), (d)) + (x) + (ac); \ ROTATE_LEFT ((a), (s)); \ (a) += (b); #define HH(a, b, c, d, x, s, ac) \ (a) += H ((b), (c), (d)) + (x) + (ac); \ ROTATE_LEFT ((a), (s)); \ (a) += (b); #define HH2(a, b, c, d, x, s, ac) \ (a) += H2 ((b), (c), (d)) + (x) + (ac); \ ROTATE_LEFT ((a), (s)); \ (a) += (b); #define II(a, b, c, d, x, s, ac) \ (a) += I ((b), (c), (d)) + (x) + (ac); \ ROTATE_LEFT ((a), (s)); \ (a) += (b); #endif static const unsigned char PADDING[56] = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; #if ARCH_LITTLE_ENDIAN #define MD5_swap(dst, src, count) #else #define MD5_swap(dst, src, count) \ { \ MD5_word *dptr = (dst), *sptr = (src); \ int loop_count = (count); \ MD5_word mask = OOFFOOFF; \ do { \ MD5_word tmp = *sptr++; \ ROTATE_LEFT(tmp, 16); \ *dptr++ = ((tmp & mask) << 8) | ((tmp >> 8) & mask); \ tmp = *sptr++; \ ROTATE_LEFT(tmp, 16); \ *dptr++ = ((tmp & mask) << 8) | ((tmp >> 8) & mask); \ } while ((loop_count -= 2)); \ } #endif #define order MD5_std_all._order #define pool MD5_std_all._pool #define block MD5_std_all._block #define prefix MD5_std_all.prefix #define prelen MD5_std_all.prelen void MD5_std_init(struct fmt_main *self) { int index; MD5_pool *current; #if MD5_std_mt int t, n; // Note, $dynamic_n$ will call here for setup. If set are !MD5_IMM, // $dynamic_n$ will NOT be able to use the MD5 functions. // but since I do not know if this function can be called multiple // times, I simply added a static, so the init WILL get run, but // only 1 time. static int bFirst = 1; if (!bFirst) return; bFirst = 0; if (!MD5_std_all_p) { n = omp_get_max_threads(); if (n < 1) n = 1; if (n > MD5_std_mt_max) n = MD5_std_mt_max; MD5_std_min_kpc = n * MD5_N; { int max = n * MD5_std_cpt; while (max > MD5_std_mt_max) max -= n; n = max; } MD5_std_max_kpc = n * MD5_N; /* * The array of MD5_std_all's is not exactly tiny, but we use mem_alloc_tiny() * for its alignment support and error checking. We do not need to free() this * memory anyway. */ MD5_std_all_p = mem_alloc_tiny(n * MD5_std_all_size, MEM_ALIGN_PAGE); MD5_std_nt = n; } #endif for_each_t(MD5_std_nt) { #if !MD5_IMM MD5_std_all.data = MD5_data_init; #endif current = pool; for (index = 0; index < MD5_N; index++) { #define init_line(line, init_even, init_odd) \ order[line][index].even = init_even; \ order[line][index].odd = init_odd; init_line(0, &current->e.p, &current->o.psp); init_line(1, &current->e.spp, &current->o.pp); init_line(2, &current->e.spp, &current->o.psp); init_line(3, &current->e.pp, &current->o.ps); init_line(4, &current->e.spp, &current->o.pp); init_line(5, &current->e.spp, &current->o.psp); init_line(6, &current->e.pp, &current->o.psp); init_line(7, &current->e.sp, &current->o.pp); init_line(8, &current->e.spp, &current->o.psp); init_line(9, &current->e.pp, &current->o.psp); init_line(10, &current->e.spp, &current->o.p); init_line(11, &current->e.spp, &current->o.psp); init_line(12, &current->e.pp, &current->o.psp); init_line(13, &current->e.spp, &current->o.pp); init_line(14, &current->e.sp, &current->o.psp); init_line(15, &current->e.pp, &current->o.psp); init_line(16, &current->e.spp, &current->o.pp); init_line(17, &current->e.spp, &current->o.ps); init_line(18, &current->e.pp, &current->o.psp); init_line(19, &current->e.spp, &current->o.pp); init_line(20, &current->e.spp, &current->o.psp); #undef init_line current++; } } } #if MD5_std_mt static MAYBE_INLINE void MD5_std_set_salt_for_thread(int t, char *salt) #else void MD5_std_set_salt(char *salt) #endif { int length; for (length = 0; length < 8 && salt[length]; length++); memcpy(pool[0].s, salt, pool[0].l.s = length); #if MD5_X2 memcpy(pool[1].s, salt, pool[1].l.s = length); #endif if (salt[8] == MD5_TYPE_STD) { prefix = md5_salt_prefix; prelen = md5_salt_prefix_len; } else if (salt[8] == MD5_TYPE_APACHE) { prefix = apr1_salt_prefix; prelen = apr1_salt_prefix_len; } else if (salt[8] == MD5_TYPE_AIX) { prefix = ""; prelen = 0; } } #if MD5_std_mt void MD5_std_set_salt(char *salt) { memcpy(saved_salt, salt, sizeof(saved_salt)); salt_changed = 1; } #endif void MD5_std_set_key(char *key, int index) { int length; MD5_pool *current; init_t(); for (length = 0; key[length] && length < 15; length++); current = &pool[index]; memcpy(current->o.p.b, key, current->l.p = length); memcpy(&current->o.p.b[length + 16], PADDING, 40 - length); current->o.p.w[14] = (length + 16) << 3; memcpy(current->o.pp.b, key, length); memcpy(&current->o.pp.b[length], key, length); current->l.pp = length << 1; memcpy(&current->o.pp.b[current->l.pp + 16], PADDING, 40 - current->l.pp); current->o.pp.w[14] = (current->l.pp + 16) << 3; memcpy(&current->e.p.b[16], key, length); memcpy(&current->e.p.b[16 + length], PADDING, 40 - length); current->e.p.w[14] = (length + 16) << 3; MD5_swap(current->e.p.w, current->e.p.w, 14); memcpy(&current->e.pp.b[16], current->o.pp.b, current->l.pp); memcpy(&current->e.pp.b[16 + current->l.pp], PADDING, 40 - current->l.pp); current->e.pp.w[14] = (current->l.pp + 16) << 3; MD5_swap(current->e.pp.w, current->e.pp.w, 14); order[1][index].length = current->l.pp; order[4][index].length = current->l.pp; order[7][index].length = current->l.pp; order[10][index].length = length; order[13][index].length = current->l.pp; order[16][index].length = current->l.pp; order[19][index].length = current->l.pp; } #if MD5_ASM extern void MD5_body(MD5_word x[15], MD5_word out[4]); #else /* * x86-64 implies a fairly recent CPU, so presumably its L1 instruction cache * is large enough. */ #ifdef __x86_64__ #define MAYBE_INLINE_BODY MAYBE_INLINE #else #define MAYBE_INLINE_BODY #endif #if !MD5_X2 #if MD5_std_mt #define MD5_body(x, out) \ MD5_body_for_thread(t, x, out) MAYBE_INLINE_BODY void MD5_body_for_thread(int t, MD5_word x[15], MD5_word out[4]) #else MAYBE_INLINE_BODY void MD5_body(MD5_word x[15], MD5_word out[4]) #endif { MD5_word a, b = Cb, c = Cc, d; /* Round 1 */ a = AC1 + x[0]; ROTATE_LEFT (a, S11); a += b; /* 1 */ d = (c ^ (a & MASK1)) + x[1] + AC2pCd; ROTATE_LEFT (d, S12); d += a; /* 2 */ c = F(d, a, b) + x[2] + AC3pCc; ROTATE_LEFT(c, S13); c += d; /* 3 */ b = F(c, d, a) + x[3] + AC4pCb; ROTATE_LEFT(b, S14); b += c; /* 4 */ FF (a, b, c, d, x[ 4], S11, AC5); /* 5 */ FF (d, a, b, c, x[ 5], S12, AC6); /* 6 */ FF (c, d, a, b, x[ 6], S13, AC7); /* 7 */ FF (b, c, d, a, x[ 7], S14, AC8); /* 8 */ FF (a, b, c, d, x[ 8], S11, AC9); /* 9 */ FF (d, a, b, c, x[ 9], S12, AC10); /* 10 */ FF (c, d, a, b, x[10], S13, AC11); /* 11 */ FF (b, c, d, a, x[11], S14, AC12); /* 12 */ FF (a, b, c, d, x[12], S11, AC13); /* 13 */ FF (d, a, b, c, x[13], S12, AC14); /* 14 */ FF (c, d, a, b, x[14], S13, AC15); /* 15 */ b += F (c, d, a) + AC16; ROTATE_LEFT (b, S14); b += c; /* 16 */ /* Round 2 */ GG (a, b, c, d, x[ 1], S21, AC17); /* 17 */ GG (d, a, b, c, x[ 6], S22, AC18); /* 18 */ GG (c, d, a, b, x[11], S23, AC19); /* 19 */ GG (b, c, d, a, x[ 0], S24, AC20); /* 20 */ GG (a, b, c, d, x[ 5], S21, AC21); /* 21 */ GG (d, a, b, c, x[10], S22, AC22); /* 22 */ c += G (d, a, b) + AC23; ROTATE_LEFT (c, S23); c += d; /* 23 */ GG (b, c, d, a, x[ 4], S24, AC24); /* 24 */ GG (a, b, c, d, x[ 9], S21, AC25); /* 25 */ GG (d, a, b, c, x[14], S22, AC26); /* 26 */ GG (c, d, a, b, x[ 3], S23, AC27); /* 27 */ GG (b, c, d, a, x[ 8], S24, AC28); /* 28 */ GG (a, b, c, d, x[13], S21, AC29); /* 29 */ GG (d, a, b, c, x[ 2], S22, AC30); /* 30 */ GG (c, d, a, b, x[ 7], S23, AC31); /* 31 */ GG (b, c, d, a, x[12], S24, AC32); /* 32 */ /* Round 3 */ HH (a, b, c, d, x[ 5], S31, AC33); /* 33 */ HH2 (d, a, b, c, x[ 8], S32, AC34); /* 34 */ HH (c, d, a, b, x[11], S33, AC35); /* 35 */ HH2 (b, c, d, a, x[14], S34, AC36); /* 36 */ HH (a, b, c, d, x[ 1], S31, AC37); /* 37 */ HH2 (d, a, b, c, x[ 4], S32, AC38); /* 38 */ HH (c, d, a, b, x[ 7], S33, AC39); /* 39 */ HH2 (b, c, d, a, x[10], S34, AC40); /* 40 */ HH (a, b, c, d, x[13], S31, AC41); /* 41 */ HH2 (d, a, b, c, x[ 0], S32, AC42); /* 42 */ HH (c, d, a, b, x[ 3], S33, AC43); /* 43 */ HH2 (b, c, d, a, x[ 6], S34, AC44); /* 44 */ HH (a, b, c, d, x[ 9], S31, AC45); /* 45 */ HH2 (d, a, b, c, x[12], S32, AC46); /* 46 */ c += H (d, a, b) + AC47; ROTATE_LEFT (c, S33); c += d; /* 47 */ HH2 (b, c, d, a, x[ 2], S34, AC48); /* 48 */ /* Round 4 */ II (a, b, c, d, x[ 0], S41, AC49); /* 49 */ II (d, a, b, c, x[ 7], S42, AC50); /* 50 */ II (c, d, a, b, x[14], S43, AC51); /* 51 */ II (b, c, d, a, x[ 5], S44, AC52); /* 52 */ II (a, b, c, d, x[12], S41, AC53); /* 53 */ II (d, a, b, c, x[ 3], S42, AC54); /* 54 */ II (c, d, a, b, x[10], S43, AC55); /* 55 */ II (b, c, d, a, x[ 1], S44, AC56); /* 56 */ II (a, b, c, d, x[ 8], S41, AC57); /* 57 */ d += I (a, b, c) + AC58; ROTATE_LEFT (d, S42); d += a; /* 58 */ II (c, d, a, b, x[ 6], S43, AC59); /* 59 */ II (b, c, d, a, x[13], S44, AC60); /* 60 */ II (a, b, c, d, x[ 4], S41, AC61); /* 61 */ II (d, a, b, c, x[11], S42, AC62); /* 62 */ II (c, d, a, b, x[ 2], S43, AC63); /* 63 */ II (b, c, d, a, x[ 9], S44, AC64); /* 64 */ out[0] = Ca + a; out[1] = Cb + b; out[2] = Cc + c; out[3] = Cd + d; } #else #if MD5_std_mt #define MD5_body(x0, x1, out0, out1) \ MD5_body_for_thread(t, x0, x1, out0, out1) MAYBE_INLINE_BODY void MD5_body_for_thread(int t, MD5_word x0[15], MD5_word x1[15], MD5_word out0[4], MD5_word out1[4]) #else MAYBE_INLINE_BODY void MD5_body(MD5_word x0[15], MD5_word x1[15], MD5_word out0[4], MD5_word out1[4]) #endif { MD5_word a0, b0 = Cb, c0 = Cc, d0; MD5_word a1, b1, c1, d1; MD5_word u, v; /* Round 1 */ a0 = (u = AC1) + x0[0]; ROTATE_LEFT (a0, S11); a0 += b0; /* 1 */ a1 = u + x1[0]; ROTATE_LEFT (a1, S11); a1 += b0; /* 1 */ d0 = (c0 ^ (a0 & (u = MASK1))) + x0[1] + (v = AC2pCd); ROTATE_LEFT (d0, S12); d0 += a0; /* 2 */ d1 = (c0 ^ (a1 & u)) + x1[1] + v; ROTATE_LEFT (d1, S12); d1 += a1; /* 2 */ c0 = F(d0, a0, b0) + x0[2] + (u = AC3pCc); ROTATE_LEFT(c0, S13); c0 += d0; /* 3 */ c1 = F(d1, a1, b0) + x1[2] + u; ROTATE_LEFT(c1, S13); c1 += d1; /* 3 */ b0 = F(c0, d0, a0) + x0[3] + (u = AC4pCb); ROTATE_LEFT(b0, S14); b0 += c0; /* 4 */ b1 = F(c1, d1, a1) + x1[3] + u; ROTATE_LEFT(b1, S14); b1 += c1; /* 4 */ FF (a0, b0, c0, d0, x0[ 4], S11, (u = AC5)); /* 5 */ FF (a1, b1, c1, d1, x1[ 4], S11, u); /* 5 */ FF (d0, a0, b0, c0, x0[ 5], S12, (u = AC6)); /* 6 */ FF (d1, a1, b1, c1, x1[ 5], S12, u); /* 6 */ FF (c0, d0, a0, b0, x0[ 6], S13, (u = AC7)); /* 7 */ FF (c1, d1, a1, b1, x1[ 6], S13, u); /* 7 */ FF (b0, c0, d0, a0, x0[ 7], S14, (u = AC8)); /* 8 */ FF (b1, c1, d1, a1, x1[ 7], S14, u); /* 8 */ FF (a0, b0, c0, d0, x0[ 8], S11, (u = AC9)); /* 9 */ FF (a1, b1, c1, d1, x1[ 8], S11, u); /* 9 */ FF (d0, a0, b0, c0, x0[ 9], S12, (u = AC10)); /* 10 */ FF (d1, a1, b1, c1, x1[ 9], S12, u); /* 10 */ FF (c0, d0, a0, b0, x0[10], S13, (u = AC11)); /* 11 */ FF (c1, d1, a1, b1, x1[10], S13, u); /* 11 */ FF (b0, c0, d0, a0, x0[11], S14, (u = AC12)); /* 12 */ FF (b1, c1, d1, a1, x1[11], S14, u); /* 12 */ FF (a0, b0, c0, d0, x0[12], S11, (u = AC13)); /* 13 */ FF (a1, b1, c1, d1, x1[12], S11, u); /* 13 */ FF (d0, a0, b0, c0, x0[13], S12, (u = AC14)); /* 14 */ FF (d1, a1, b1, c1, x1[13], S12, u); /* 14 */ FF (c0, d0, a0, b0, x0[14], S13, (u = AC15)); /* 15 */ FF (c1, d1, a1, b1, x1[14], S13, u); /* 15 */ b0 += F (c0, d0, a0) + (u = AC16); ROTATE_LEFT (b0, S14); b0 += c0; /* 16 */ b1 += F (c1, d1, a1) + u; ROTATE_LEFT (b1, S14); b1 += c1; /* 16 */ /* Round 2 */ GG (a0, b0, c0, d0, x0[ 1], S21, (u = AC17)); /* 17 */ GG (a1, b1, c1, d1, x1[ 1], S21, u); /* 17 */ GG (d0, a0, b0, c0, x0[ 6], S22, (u = AC18)); /* 18 */ GG (d1, a1, b1, c1, x1[ 6], S22, u); /* 18 */ GG (c0, d0, a0, b0, x0[11], S23, (u = AC19)); /* 19 */ GG (c1, d1, a1, b1, x1[11], S23, u); /* 19 */ GG (b0, c0, d0, a0, x0[ 0], S24, (u = AC20)); /* 20 */ GG (b1, c1, d1, a1, x1[ 0], S24, u); /* 20 */ GG (a0, b0, c0, d0, x0[ 5], S21, (u = AC21)); /* 21 */ GG (a1, b1, c1, d1, x1[ 5], S21, u); /* 21 */ GG (d0, a0, b0, c0, x0[10], S22, (u = AC22)); /* 22 */ GG (d1, a1, b1, c1, x1[10], S22, u); /* 22 */ c0 += G (d0, a0, b0) + (u = AC23); ROTATE_LEFT (c0, S23); c0 += d0; /* 23 */ c1 += G (d1, a1, b1) + u; ROTATE_LEFT (c1, S23); c1 += d1; /* 23 */ GG (b0, c0, d0, a0, x0[ 4], S24, (u = AC24)); /* 24 */ GG (b1, c1, d1, a1, x1[ 4], S24, u); /* 24 */ GG (a0, b0, c0, d0, x0[ 9], S21, (u = AC25)); /* 25 */ GG (a1, b1, c1, d1, x1[ 9], S21, u); /* 25 */ GG (d0, a0, b0, c0, x0[14], S22, (u = AC26)); /* 26 */ GG (d1, a1, b1, c1, x1[14], S22, u); /* 26 */ GG (c0, d0, a0, b0, x0[ 3], S23, (u = AC27)); /* 27 */ GG (c1, d1, a1, b1, x1[ 3], S23, u); /* 27 */ GG (b0, c0, d0, a0, x0[ 8], S24, (u = AC28)); /* 28 */ GG (b1, c1, d1, a1, x1[ 8], S24, u); /* 28 */ GG (a0, b0, c0, d0, x0[13], S21, (u = AC29)); /* 29 */ GG (a1, b1, c1, d1, x1[13], S21, u); /* 29 */ GG (d0, a0, b0, c0, x0[ 2], S22, (u = AC30)); /* 30 */ GG (d1, a1, b1, c1, x1[ 2], S22, u); /* 30 */ GG (c0, d0, a0, b0, x0[ 7], S23, (u = AC31)); /* 31 */ GG (c1, d1, a1, b1, x1[ 7], S23, u); /* 31 */ GG (b0, c0, d0, a0, x0[12], S24, (u = AC32)); /* 32 */ GG (b1, c1, d1, a1, x1[12], S24, u); /* 32 */ /* Round 3 */ HH (a0, b0, c0, d0, x0[ 5], S31, (u = AC33)); /* 33 */ HH (a1, b1, c1, d1, x1[ 5], S31, u); /* 33 */ HH (d0, a0, b0, c0, x0[ 8], S32, (u = AC34)); /* 34 */ HH (d1, a1, b1, c1, x1[ 8], S32, u); /* 34 */ HH (c0, d0, a0, b0, x0[11], S33, (u = AC35)); /* 35 */ HH (c1, d1, a1, b1, x1[11], S33, u); /* 35 */ HH (b0, c0, d0, a0, x0[14], S34, (u = AC36)); /* 36 */ HH (b1, c1, d1, a1, x1[14], S34, u); /* 36 */ HH (a0, b0, c0, d0, x0[ 1], S31, (u = AC37)); /* 37 */ HH (a1, b1, c1, d1, x1[ 1], S31, u); /* 37 */ HH (d0, a0, b0, c0, x0[ 4], S32, (u = AC38)); /* 38 */ HH (d1, a1, b1, c1, x1[ 4], S32, u); /* 38 */ HH (c0, d0, a0, b0, x0[ 7], S33, (u = AC39)); /* 39 */ HH (c1, d1, a1, b1, x1[ 7], S33, u); /* 39 */ HH (b0, c0, d0, a0, x0[10], S34, (u = AC40)); /* 40 */ HH (b1, c1, d1, a1, x1[10], S34, u); /* 40 */ HH (a0, b0, c0, d0, x0[13], S31, (u = AC41)); /* 41 */ HH (a1, b1, c1, d1, x1[13], S31, u); /* 41 */ HH (d0, a0, b0, c0, x0[ 0], S32, (u = AC42)); /* 42 */ HH (d1, a1, b1, c1, x1[ 0], S32, u); /* 42 */ HH (c0, d0, a0, b0, x0[ 3], S33, (u = AC43)); /* 43 */ HH (c1, d1, a1, b1, x1[ 3], S33, u); /* 43 */ HH (b0, c0, d0, a0, x0[ 6], S34, (u = AC44)); /* 44 */ HH (b1, c1, d1, a1, x1[ 6], S34, u); /* 44 */ HH (a0, b0, c0, d0, x0[ 9], S31, (u = AC45)); /* 45 */ HH (a1, b1, c1, d1, x1[ 9], S31, u); /* 45 */ HH (d0, a0, b0, c0, x0[12], S32, (u = AC46)); /* 46 */ HH (d1, a1, b1, c1, x1[12], S32, u); /* 46 */ c0 += H (d0, a0, b0) + (u = AC47); ROTATE_LEFT (c0, S33); c0 += d0; /* 47 */ c1 += H (d1, a1, b1) + u; ROTATE_LEFT (c1, S33); c1 += d1; /* 47 */ HH (b0, c0, d0, a0, x0[ 2], S34, (u = AC48)); /* 48 */ HH (b1, c1, d1, a1, x1[ 2], S34, u); /* 48 */ /* Round 4 */ II (a0, b0, c0, d0, x0[ 0], S41, (u = AC49)); /* 49 */ II (a1, b1, c1, d1, x1[ 0], S41, u); /* 49 */ II (d0, a0, b0, c0, x0[ 7], S42, (u = AC50)); /* 50 */ II (d1, a1, b1, c1, x1[ 7], S42, u); /* 50 */ II (c0, d0, a0, b0, x0[14], S43, (u = AC51)); /* 51 */ II (c1, d1, a1, b1, x1[14], S43, u); /* 51 */ II (b0, c0, d0, a0, x0[ 5], S44, (u = AC52)); /* 52 */ II (b1, c1, d1, a1, x1[ 5], S44, u); /* 52 */ II (a0, b0, c0, d0, x0[12], S41, (u = AC53)); /* 53 */ II (a1, b1, c1, d1, x1[12], S41, u); /* 53 */ II (d0, a0, b0, c0, x0[ 3], S42, (u = AC54)); /* 54 */ II (d1, a1, b1, c1, x1[ 3], S42, u); /* 54 */ II (c0, d0, a0, b0, x0[10], S43, (u = AC55)); /* 55 */ II (c1, d1, a1, b1, x1[10], S43, u); /* 55 */ II (b0, c0, d0, a0, x0[ 1], S44, (u = AC56)); /* 56 */ II (b1, c1, d1, a1, x1[ 1], S44, u); /* 56 */ II (a0, b0, c0, d0, x0[ 8], S41, (u = AC57)); /* 57 */ II (a1, b1, c1, d1, x1[ 8], S41, u); /* 57 */ d0 += I (a0, b0, c0) + (u = AC58); ROTATE_LEFT (d0, S42); d0 += a0; /* 58 */ d1 += I (a1, b1, c1) + u; ROTATE_LEFT (d1, S42); d1 += a1; /* 58 */ II (c0, d0, a0, b0, x0[ 6], S43, (u = AC59)); /* 59 */ II (c1, d1, a1, b1, x1[ 6], S43, u); /* 59 */ II (b0, c0, d0, a0, x0[13], S44, (u = AC60)); /* 60 */ II (b1, c1, d1, a1, x1[13], S44, u); /* 60 */ II (a0, b0, c0, d0, x0[ 4], S41, (u = AC61)); /* 61 */ II (a1, b1, c1, d1, x1[ 4], S41, u); /* 61 */ II (d0, a0, b0, c0, x0[11], S42, (u = AC62)); /* 62 */ II (d1, a1, b1, c1, x1[11], S42, u); /* 62 */ II (c0, d0, a0, b0, x0[ 2], S43, (u = AC63)); /* 63 */ II (c1, d1, a1, b1, x1[ 2], S43, u); /* 63 */ II (b0, c0, d0, a0, x0[ 9], S44, (u = AC64)); /* 64 */ II (b1, c1, d1, a1, x1[ 9], S44, u); /* 64 */ out1[3] = Cd + d1; out0[0] = Ca + a0; out0[1] = Cb + b0; out0[2] = Cc + c0; out0[3] = Cd + d0; out1[0] = Ca + a1; out1[1] = Cb + b1; out1[2] = Cc + c1; } #endif #endif #if MD5_std_mt static MAYBE_INLINE void MD5_std_crypt_for_thread(int t) #else void MD5_std_crypt(int count) #endif { int length, index, mask; MD5_pattern *line; #if ARCH_LITTLE_ENDIAN MD5_word *last0; #endif #if MD5_X2 MD5_pool *key; #if ARCH_LITTLE_ENDIAN MD5_word *last1; #endif #endif #if MD5_X2 for (index = 0, key = pool; index < MD5_N; index++, key++) { #else #define index 0 #define key pool #endif memcpy(key->o.ps.b, key->o.p.b, key->l.p); memcpy(&key->o.ps.b[key->l.p], key->s, key->l.s); key->l.ps = key->l.p + key->l.s; memcpy(&key->o.ps.b[key->l.ps + 16], PADDING, 40 - key->l.ps); key->o.ps.w[14] = (key->l.ps + 16) << 3; memcpy(key->o.psp.b, key->o.ps.b, key->l.ps); memcpy(&key->o.psp.b[key->l.ps], key->o.p.b, key->l.p); key->l.psp = key->l.ps + key->l.p; memcpy(&key->o.psp.b[key->l.psp + 16], PADDING, 40 - key->l.psp); key->o.psp.w[14] = (key->l.psp + 16) << 3; memcpy(&key->e.sp.b[16], key->s, key->l.s); memcpy(&key->e.sp.b[16 + key->l.s], key->o.p.b, key->l.p); memcpy(&key->e.sp.b[16 + key->l.ps], PADDING, 40 - key->l.ps); key->e.sp.w[14] = (key->l.ps + 16) << 3; MD5_swap(key->e.sp.w, key->e.sp.w, 14); memcpy(&key->e.spp.b[16], key->s, key->l.s); memcpy(&key->e.spp.b[16 + key->l.s], key->o.pp.b, key->l.pp); memcpy(&key->e.spp.b[16 + key->l.psp], PADDING, 40 - key->l.psp); key->e.spp.w[14] = (key->l.psp + 16) << 3; MD5_swap(key->e.spp.w, key->e.spp.w, 14); order[0][index].length = key->l.psp; order[2][index].length = key->l.psp; order[3][index].length = key->l.ps; order[5][index].length = key->l.psp; order[6][index].length = key->l.psp; order[8][index].length = key->l.psp; order[9][index].length = key->l.psp; order[11][index].length = key->l.psp; order[12][index].length = key->l.psp; order[14][index].length = key->l.psp; order[15][index].length = key->l.psp; order[17][index].length = key->l.ps; order[18][index].length = key->l.psp; order[20][index].length = key->l.psp; memcpy(&block[index], key->o.psp.b, key->l.psp); memcpy(&block[index].b[key->l.psp], PADDING, 56 - key->l.psp); block[index].w[14] = key->l.psp << 3; MD5_swap(block[index].w, block[index].w, 14); #if MD5_X2 } MD5_body(block[0].w, block[1].w, MD5_out[0], MD5_out[1]); MD5_swap(MD5_out[0], MD5_out[0], 8); #else MD5_body(block[0].w, MD5_out[0]); MD5_swap(MD5_out[0], MD5_out[0], 4); #endif #if MD5_X2 for (index = 0, key = pool; index < MD5_N; index++, key++) { #endif memcpy(&block[index], key->o.p.b, key->l.p); memcpy(&block[index].b[key->l.p], prefix, prelen); memcpy(&block[index].b[key->l.p + prelen], key->s, key->l.s); memcpy(&block[index].b[key->l.ps + prelen], MD5_out[index], key->l.p); length = key->l.psp + prelen; if ((mask = key->l.p)) do { block[index].b[length++] = (mask & 1) ? 0 : key->o.p.b[0]; } while (mask >>= 1); memcpy(&block[index].b[length], PADDING, 56 - length); block[index].w[14] = length << 3; MD5_swap(block[index].w, block[index].w, 14); #if MD5_X2 } #else #undef index #undef key #endif #if MD5_X2 MD5_body(block[0].w, block[1].w, order[0][0].even->w, order[0][1].even->w); #else MD5_body(block[0].w, order[0][0].even->w); #endif index = 500; line = order[0]; do { #if ARCH_LITTLE_ENDIAN #if ARCH_ALLOWS_UNALIGNED #if MD5_X2 MD5_body(line[0].even->w, line[1].even->w, (MD5_word *)&line[0].odd->b[line[0].length], (MD5_word *)&line[1].odd->b[line[1].length]); #else MD5_body(line[0].even->w, (MD5_word *)&line[0].odd->b[line[0].length]); #endif #else #if MD5_X2 MD5_body(line[0].even->w, line[1].even->w, MD5_out[0], MD5_out[1]); memcpy(&line[0].odd->b[line[0].length], MD5_out[0], 16); memcpy(&line[1].odd->b[line[1].length], MD5_out[1], 16); #else if (((ARCH_WORD)&line[0].odd->b[line[0].length]) & 3) { MD5_body(line[0].even->w, MD5_out[0]); memcpy(&line[0].odd->b[line[0].length], MD5_out[0], 16); } else { MD5_body(line[0].even->w, (MD5_word *)&line[0].odd->b[line[0].length]); } #endif #endif last0 = line[0].odd->w; #if MD5_X2 last1 = line[1].odd->w; if ((line += 2) > &order[20][MD5_N - 1]) line = order[0]; MD5_body(last0, last1, line[0].even->w, line[1].even->w); #else if (++line > &order[20][0]) line = order[0]; MD5_body(last0, line[0].even->w); #endif #else #if MD5_X2 MD5_body(line[0].even->w, line[1].even->w, MD5_out[0], MD5_out[1]); MD5_swap(MD5_out[0], MD5_out[0], 8); #else MD5_body(line[0].even->w, MD5_out[0]); MD5_swap(MD5_out[0], MD5_out[0], 4); #endif memcpy(&line[0].odd->b[line[0].length], MD5_out[0], 16); #if MD5_X2 memcpy(&line[1].odd->b[line[1].length], MD5_out[1], 16); #endif MD5_swap(block[0].w, line[0].odd->w, 14); block[0].w[14] = line[0].odd->w[14]; #if MD5_X2 MD5_swap(block[1].w, line[1].odd->w, 14); block[1].w[14] = line[1].odd->w[14]; if ((line += 2) > &order[20][MD5_N - 1]) line = order[0]; MD5_body(block[0].w, block[1].w, line[0].even->w, line[1].even->w); #else if (++line > &order[20][0]) line = order[0]; MD5_body(block[0].w, line[0].even->w); #endif #endif } while (--index); memcpy(MD5_out[0], line[0].even, 16); #if MD5_X2 memcpy(MD5_out[1], line[1].even, 16); #endif } #if MD5_std_mt void MD5_std_crypt(int count) { #if MD5_std_mt int t, n = (count + (MD5_N - 1)) / MD5_N; #endif #ifdef _OPENMP #pragma omp parallel for default(none) private(t) shared(n, salt_changed, saved_salt) #endif for_each_t(n) { /* * We could move the salt_changed check out of the parallel region (and have * two specialized parallel regions instead), but MD5_std_crypt_for_thread() * does so much work that the salt_changed check is negligible. */ if (salt_changed) MD5_std_set_salt_for_thread(t, saved_salt); MD5_std_crypt_for_thread(t); } salt_changed = 0; } #endif char *MD5_std_get_salt(char *ciphertext) { static char out[9]; char *p, *q; int i; if (!strncmp(ciphertext, apr1_salt_prefix, apr1_salt_prefix_len)) { out[8] = MD5_TYPE_APACHE; p = ciphertext + apr1_salt_prefix_len; } else if (!strncmp(ciphertext, smd5_salt_prefix, smd5_salt_prefix_len)) { out[8] = MD5_TYPE_AIX; p = ciphertext + smd5_salt_prefix_len; } else { out[8] = MD5_TYPE_STD; p = ciphertext + md5_salt_prefix_len; } q = out; for (i = 0; *p != '$' && i < 8; i++) *q++ = *p++; while (i++ < 8) *q++ = 0; return out; } #define TO_BINARY(b1, b2, b3) \ value = \ (MD5_word)atoi64[ARCH_INDEX(pos[0])] | \ ((MD5_word)atoi64[ARCH_INDEX(pos[1])] << 6) | \ ((MD5_word)atoi64[ARCH_INDEX(pos[2])] << 12) | \ ((MD5_word)atoi64[ARCH_INDEX(pos[3])] << 18); \ pos += 4; \ out.b[b1] = value >> 16; \ out.b[b2] = value >> 8; \ out.b[b3] = value; MD5_word *MD5_std_get_binary(char *ciphertext) { static union { MD5_binary w; char b[16]; } out; char *pos; MD5_word value; pos = ciphertext + md5_salt_prefix_len; if (!strncmp(ciphertext, apr1_salt_prefix, apr1_salt_prefix_len) || !strncmp(ciphertext, smd5_salt_prefix, smd5_salt_prefix_len)) pos = ciphertext + apr1_salt_prefix_len; while (*pos++ != '$'); TO_BINARY(0, 6, 12); TO_BINARY(1, 7, 13); TO_BINARY(2, 8, 14); TO_BINARY(3, 9, 15); TO_BINARY(4, 10, 5); out.b[11] = (MD5_word)atoi64[ARCH_INDEX(pos[0])] | ((MD5_word)atoi64[ARCH_INDEX(pos[1])] << 6); #undef OOFFOOFF #define OOFFOOFF 0x00ff00ff MD5_swap(out.w, out.w, 4); #undef OOFFOOFF return out.w; }
strMdataBinary.c
// // strMdataBinary.c // pstock // // Created by takayoshi on 2016/01/26. // Copyright © 2016年 pgostation. All rights reserved. // #include <stdio.h> #include <sys/stat.h> #include <apr-1/apr_file_io.h> #include <libiomp/omp.h> #include "strMdataBinary.h" extern void strMdataBinary_loadData(const char* path, strMdata* data) { char filePathBinary[MAX_THREAD_COUNT][256]; apr_pool_t* pool[MAX_THREAD_COUNT]; apr_initialize(); for(int i=0; i<MAX_THREAD_COUNT; i++) { apr_pool_create(&pool[i], NULL); } apr_status_t status; apr_file_t* file = NULL; apr_finfo_t finfo; apr_off_t fileLen; int* buf; int i; #pragma omp parallel for private(status,file,finfo,fileLen,buf,i) for(int codeIndex=0; codeIndex<data->count; codeIndex++) { snprintf(filePathBinary[omp_get_thread_num()], 256-1, "%s_dailydataBinary/%d", path, data->codes[codeIndex]); //ファイルを開いて、データをバッファに読み込む { status = apr_file_open(&file, filePathBinary[omp_get_thread_num()], APR_READ | APR_BUFFERED, APR_OS_DEFAULT, pool[omp_get_thread_num()]); if (status != APR_SUCCESS) { continue; } apr_file_info_get(&finfo, APR_FINFO_SIZE, file); fileLen = finfo.size; buf = apr_palloc(pool[omp_get_thread_num()], fileLen+1); apr_size_t len = fileLen; if (APR_SUCCESS != apr_file_read(file, buf, &len)) { apr_file_close(file); continue; } apr_file_close(file); } data->dailys[codeIndex].count = (int)(fileLen/6/sizeof(int)); //メモリ確保 { //data->dailys[codeIndex].date = malloc(fileLen/6); data->dailys[codeIndex].start = malloc(fileLen/6); data->dailys[codeIndex].end = malloc(fileLen/6); data->dailys[codeIndex].max = malloc(fileLen/6); data->dailys[codeIndex].min = malloc(fileLen/6); data->dailys[codeIndex].volume = malloc(fileLen/6); } //配列に代入する { for(i=0; i<fileLen/sizeof(int); i+=6) { //data->dailys[codeIndex].date[i/6] = buf[i+0]; data->dailys[codeIndex].start[i/6] = buf[i+1]; data->dailys[codeIndex].end[i/6] = buf[i+2]; data->dailys[codeIndex].max[i/6] = buf[i+3]; data->dailys[codeIndex].min[i/6] = buf[i+4]; data->dailys[codeIndex].volume[i/6] = buf[i+5]; } } if(data->codes[codeIndex]==9984) { data->dailys[MAX_DATA_COUNT-1].count = (int)(fileLen/6/sizeof(int)); //メモリ確保 { data->date = malloc(fileLen/6); //data->dailys[MAX_DATA_COUNT-1].date = malloc(fileLen/6); data->dailys[MAX_DATA_COUNT-1].start = malloc(fileLen/6); data->dailys[MAX_DATA_COUNT-1].end = malloc(fileLen/6); data->dailys[MAX_DATA_COUNT-1].max = malloc(fileLen/6); data->dailys[MAX_DATA_COUNT-1].min = malloc(fileLen/6); data->dailys[MAX_DATA_COUNT-1].volume = malloc(fileLen/6); } //配列に代入する { for(i=0; i<fileLen/sizeof(int); i+=6) { data->date[i/6] = buf[i+0]; data->dailys[MAX_DATA_COUNT-1].start[i/6] = buf[i+1]; data->dailys[MAX_DATA_COUNT-1].end[i/6] = buf[i+2]; data->dailys[MAX_DATA_COUNT-1].max[i/6] = buf[i+3]; data->dailys[MAX_DATA_COUNT-1].min[i/6] = buf[i+4]; data->dailys[MAX_DATA_COUNT-1].volume[i/6] = buf[i+5]; } } } if(data->codes[codeIndex]==1321) { data->dailys[MAX_DATA_COUNT-2].count = (int)(fileLen/6/sizeof(int)); //メモリ確保 { //data->dailys[MAX_DATA_COUNT-2].date = malloc(fileLen/6); data->dailys[MAX_DATA_COUNT-2].start = malloc(fileLen/6); data->dailys[MAX_DATA_COUNT-2].end = malloc(fileLen/6); data->dailys[MAX_DATA_COUNT-2].max = malloc(fileLen/6); data->dailys[MAX_DATA_COUNT-2].min = malloc(fileLen/6); data->dailys[MAX_DATA_COUNT-2].volume = malloc(fileLen/6); } //配列に代入する { for(i=0; i<fileLen/sizeof(int); i+=6) { //data->dailys[MAX_DATA_COUNT-2].date[i/6] = buf[i+0]; data->dailys[MAX_DATA_COUNT-2].start[i/6] = buf[i+1]; data->dailys[MAX_DATA_COUNT-2].end[i/6] = buf[i+2]; data->dailys[MAX_DATA_COUNT-2].max[i/6] = buf[i+3]; data->dailys[MAX_DATA_COUNT-2].min[i/6] = buf[i+4]; data->dailys[MAX_DATA_COUNT-2].volume[i/6] = buf[i+5]; } } } } for(int i=0; i<MAX_THREAD_COUNT; i++) { apr_pool_destroy(pool[i]); } } extern void strMdataBinary_saveData(const char* path, strMdata* data) { char filePathBinary[MAX_THREAD_COUNT][256]; //ディレクトリ作る snprintf(filePathBinary[0], 256-1, "%s_dailydataBinary", path); mkdir(filePathBinary[0], 0777); apr_pool_t* pool[MAX_THREAD_COUNT]; apr_initialize(); for(int i=0; i<MAX_THREAD_COUNT; i++) { apr_pool_create(&pool[i], NULL); } apr_size_t len; int* buf; int count_max; int i; apr_status_t status; apr_file_t* file; #pragma omp parallel for private(len,buf,count_max,i,status,file) for(int codeIndex=0; codeIndex<data->count; codeIndex++) { if(data->codes[codeIndex]==0){ continue; } snprintf(filePathBinary[omp_get_thread_num()], 256-1, "%s_dailydataBinary/%d", path, data->codes[codeIndex]); len = sizeof(int) * 6 * data->dailys[codeIndex].count; buf = malloc(len); //データ用のバッファにフォーマット { count_max = 6 * data->dailys[codeIndex].count; for(i=0; i<count_max; i+=6) { buf[i+0] = data->date[i/6]; buf[i+1] = data->dailys[codeIndex].start[i/6]; buf[i+2] = data->dailys[codeIndex].end[i/6]; buf[i+3] = data->dailys[codeIndex].max[i/6]; buf[i+4] = data->dailys[codeIndex].min[i/6]; buf[i+5] = data->dailys[codeIndex].volume[i/6]; } } //ファイルに書き込み { status = apr_file_open(&file, filePathBinary[omp_get_thread_num()], APR_FOPEN_CREATE | APR_WRITE | APR_BUFFERED, APR_OS_DEFAULT, pool[omp_get_thread_num()]); if (status != APR_SUCCESS) { continue; } apr_file_write(file, buf, &len); apr_file_close(file); } free(buf); } }
sp.c
/*-------------------------------------------------------------------- NAS Parallel Benchmarks 3.0 structured OpenMP C versions - SP This benchmark is an OpenMP C version of the NPB SP code. The OpenMP C 2.3 versions are derived by RWCP from the serial Fortran versions in "NPB 2.3-serial" developed by NAS. 3.0 translation is performed by the UVSQ. Permission to use, copy, distribute and modify this software for any purpose with or without fee is hereby granted. This software is provided "as is" without express or implied warranty. Information on OpenMP activities at RWCP is available at: http://pdplab.trc.rwcp.or.jp/pdperf/Omni/ Information on NAS Parallel Benchmarks 2.3 is available at: http://www.nas.nasa.gov/NAS/NPB/ --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- Author: R. Van der Wijngaart W. Saphir OpenMP C version: S. Satoh 3.0 structure translation: M. Popov --------------------------------------------------------------------*/ // #include "npb-C.h" /* global variables */ #include "header.h" #include <stdint.h> #include "../common/perf.h" // #define WITH_POSIT_32 // #define PFDEBUG #ifdef PFDEBUG #include <stdio.h> #endif // constants element_t zero, one, two, three, four, five, six, ten, hundred, thousand, c_epsilon, c_dtref; #if defined WITH_POSIT_32 /* // posit(32,2) uint32_t posit_zero = 0x00000000; uint32_t posit_one = 0x40000000; uint32_t posit_two = 0x48000000; */ // posit(32,3) uint32_t posit_zero = 0x00000000; uint32_t posit_one = 0x40000000; uint32_t posit_two = 0x44000000; uint32_t posit_three = 0x46000000; uint32_t posit_four = 0x48000000; uint32_t posit_five = 0x49000000; uint32_t posit_six = 0x4a000000; uint32_t posit_ten = 0x4d000000; uint32_t posit_hundred = 0x5a400000; uint32_t posit_thousand = 0x63e80000; uint32_t posit_01 = 0x251eb851; uint32_t posit_001 = 0x1c0c49ba; uint32_t posit_0001 = 0x1546dc5d; uint32_t posit_00001 = 0xf4f8b58; #elif (defined WITH_POSIT_16) uint32_t posit_zero = 0x00000000; uint32_t posit_one = 0x00004000; uint32_t posit_two = 0x00004800; uint32_t posit_three = 0x00004c00; uint32_t posit_four = 0x00005000; uint32_t posit_five = 0x00005200; uint32_t posit_six = 0x00005400; uint32_t posit_ten = 0x00005a00; uint32_t posit_hundred = 0x00006a40; uint32_t posit_thousand = 0x000073e8; uint32_t posit_1 = 0x000024cc; uint32_t posit_01 = 0x0000151e; uint32_t posit_001 = 0x00000c0c; uint32_t posit_0001 = 0x000006a3; uint32_t posit_00001 = 0x000003a7; #elif (defined WITH_POSIT_8) uint32_t posit_zero = 0x00000000; uint32_t posit_one = 0x00000040; uint32_t posit_two = 0x00000050; uint32_t posit_three = 0x00000058; uint32_t posit_four = 0x00000060; uint32_t posit_five = 0x00000062; uint32_t posit_six = 0x00000064; uint32_t posit_ten = 0x0000006a; uint32_t posit_hundred = 0x00000079; uint32_t posit_thousand = 0x0000007d; uint32_t posit_1 = 0x00000014; uint32_t posit_01 = 0x00000006; uint32_t posit_001 = 0x00000002; #else uint32_t fp32_zero = 0x00000000; uint32_t fp32_one = 0x3f800000; uint32_t fp32_two = 0x40000000; uint32_t fp32_three = 0x40400000; uint32_t fp32_four = 0x40800000; uint32_t fp32_five = 0x40a00000; uint32_t fp32_six = 0x40c00000; uint32_t fp32_ten = 0x41200000; uint32_t fp32_hundred = 0x42c80000; uint32_t fp32_thousand = 0x447a0000; uint32_t fp32_01 = 0x3c23d70a; uint32_t fp32_001 = 0x3a83126f; uint32_t fp32_0001 = 0x38d1b717; uint32_t fp32_00001 = 0x3727c5ac; #endif /* WITH_POSIT */ void init_constants() { #if (defined WITH_POSIT_8 || defined WITH_POSIT_16 || defined WITH_POSIT_32) *((uint32_t*)&zero) = posit_zero; *((uint32_t*)&one) = posit_one; *((uint32_t*)&two) = posit_two; *((uint32_t*)&three) = posit_three; *((uint32_t*)&four) = posit_four; *((uint32_t*)&five) = posit_five; *((uint32_t*)&six) = posit_six; *((uint32_t*)&ten) = posit_ten; *((uint32_t*)&hundred) = posit_hundred; *((uint32_t*)&thousand) = posit_thousand; *((uint32_t*)&c_epsilon) = one; *((uint32_t*)&c_dtref) = posit_01; #else *((uint32_t*)&zero) = fp32_zero; *((uint32_t*)&one) = fp32_one; *((uint32_t*)&two) = fp32_two; *((uint32_t*)&three) = fp32_three; *((uint32_t*)&four) = fp32_four; *((uint32_t*)&five) = fp32_five; *((uint32_t*)&six) = fp32_six; *((uint32_t*)&ten) = fp32_ten; *((uint32_t*)&hundred) = fp32_hundred; *((uint32_t*)&thousand) = fp32_thousand; *((uint32_t*)&c_epsilon) = fp32_0001; *((uint32_t*)&c_dtref) = fp32_01; #endif /* WITH_POSIT */ } #define DT_DEFAULT (three * five / (thousand)) float sqrt_asm(float x) { float res; #if defined(__x86_64__) asm("fsqrt" : "=t" (res) : "0" (x)); #else asm("fsqrt.s %0,%1\n\t" : "=f" (res) : "f" (x) : "cc"); #endif return res; } element_t my_fabs(element_t x) { if (x < zero) return -x; return x; } #define max(a,b) (((a) > (b)) ? (a) : (b)) #define min(a,b) (((a) < (b)) ? (a) : (b)) #define pow2(a) ((a)*(a)) /* function declarations */ static void add(void); static void adi(void); static void error_norm(element_t rms[5]); static void rhs_norm(element_t rms[5]); static void exact_rhs(void); static void exact_solution(element_t xi, element_t eta, element_t zeta, element_t dtemp[5]); static void initialize(void); static void lhsinit(void); static void lhsx(void); static void lhsy(void); static void lhsz(void); static void ninvr(void); static void pinvr(void); static void compute_rhs(void); static void set_constants(void); static void txinvr(void); static void tzetar(void); static void verify(int no_time_steps, char *class, boolean *verified); static void x_solve(void); static void y_solve(void); static void z_solve(void); /*-------------------------------------------------------------------- program SP c-------------------------------------------------------------------*/ int main(int argc, char **argv) { int niter, step; element_t mflops, tmax; int nthreads = 1; boolean verified; char class; init_constants(); /*-------------------------------------------------------------------- c Read input file (if it exists), else take c defaults from parameters c-------------------------------------------------------------------*/ #ifdef PFDEBUG printf("\n\n NAS Parallel Benchmarks 3.0 structured OpenMP C version" " - SP Benchmark\n\n"); #endif niter = NITER_DEFAULT; dt = DT_DEFAULT; grid_points[0] = PROBLEM_SIZE; grid_points[1] = PROBLEM_SIZE; grid_points[2] = PROBLEM_SIZE; #ifdef PFDEBUG printf(" Size: %3dx%3dx%3d\n", grid_points[0], grid_points[1], grid_points[2]); printf(" Iterations: %3d dt: %10.6f\n", niter, dt); #endif if ( (grid_points[0] > IMAX) || (grid_points[1] > JMAX) || (grid_points[2] > KMAX) ) { #ifdef PFDEBUG printf("%d, %d, %d\n", grid_points[0], grid_points[1], grid_points[2]); printf(" Problem size too big for compiled array sizes\n"); #endif return -1; } unsigned long long startc = read_cycles(); set_constants(); initialize(); lhsinit(); exact_rhs(); /*-------------------------------------------------------------------- c do one time step to touch all code, and reinitialize c-------------------------------------------------------------------*/ adi(); initialize(); for (step = 1; step <= niter; step++) { #ifdef PFDEBUG if (step % 20 == 0 || step == 1) { printf(" Time step %4d\n", step); } #endif adi(); } #pragma omp parallel { #if defined(_OPENMP) #pragma omp master nthreads = omp_get_num_threads(); #endif /* _OPENMP */ } /* end parallel */ verify(niter, &class, &verified); unsigned long long endc = read_cycles(); endc = endc - startc; #ifdef PFDEBUG printf("Cycles %lu\n", endc); #endif #ifdef PFDEBUG if (verified) printf("Verification: SUCCESS\n"); else printf("Verification: FAILED\n"); #endif return verified; } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void add(void) { int i, j, k, m; /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c addition of update to the vector u c-------------------------------------------------------------------*/ #pragma omp for for (m = 0; m < 5; m++) { for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { u[m][i][j][k] = u[m][i][j][k] + rhs[m][i][j][k]; } } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void adi(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ compute_rhs(); txinvr(); x_solve(); y_solve(); z_solve(); add(); } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void error_norm(element_t rms[5]) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c this function computes the norm of the difference between the c computed solution and the exact solution c-------------------------------------------------------------------*/ int i, j, k, m, d; element_t xi, eta, zeta, u_exact[5], add; for (m = 0; m < 5; m++) { rms[m] = zero; } for (i = 0; i <= grid_points[0]-1; i++) { xi = (element_t)i * dnxm1; for (j = 0; j <= grid_points[1]-1; j++) { eta = (element_t)j * dnym1; for (k = 0; k <= grid_points[2]-1; k++) { zeta = (element_t)k * dnzm1; exact_solution(xi, eta, zeta, u_exact); for (m = 0; m < 5; m++) { add = u[m][i][j][k] - u_exact[m]; rms[m] = rms[m] + add*add; } } } } for (m = 0; m < 5; m++) { for (d = 0; d < 3; d++) { rms[m] = rms[m] / (element_t)(grid_points[d]-2); } rms[m] = sqrt_asm(rms[m]); } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void rhs_norm(element_t rms[5]) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ int i, j, k, d, m; element_t add; for (m = 0; m < 5; m++) { rms[m] = zero; } for (i = 0; i <= grid_points[0]-2; i++) { for (j = 0; j <= grid_points[1]-2; j++) { for (k = 0; k <= grid_points[2]-2; k++) { for (m = 0; m < 5; m++) { add = rhs[m][i][j][k]; rms[m] = rms[m] + add*add; } } } } for (m = 0; m < 5; m++) { for (d = 0; d < 3; d++) { rms[m] = rms[m] / (element_t)(grid_points[d]-2); } rms[m] = sqrt_asm(rms[m]); } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void exact_rhs(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c compute the right hand side based on exact solution c-------------------------------------------------------------------*/ element_t dtemp[5], xi, eta, zeta, dtpp; int m, i, j, k, ip1, im1, jp1, jm1, km1, kp1; /*-------------------------------------------------------------------- c initialize c-------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { for (i = 0; i <= grid_points[0]-1; i++) { for (j = 0; j <= grid_points[1]-1; j++) { for (k= 0; k <= grid_points[2]-1; k++) { forcing[m][i][j][k] = zero; } } } } /*-------------------------------------------------------------------- c xi-direction flux differences c-------------------------------------------------------------------*/ for (k = 1; k <= grid_points[2]-2; k++) { zeta = (element_t)k * dnzm1; for (j = 1; j <= grid_points[1]-2; j++) { eta = (element_t)j * dnym1; for (i = 0; i <= grid_points[0]-1; i++) { xi = (element_t)i * dnxm1; exact_solution(xi, eta, zeta, dtemp); for (m = 0; m < 5; m++) { ue[m][i] = dtemp[m]; } dtpp = one / dtemp[0]; for (m = 1; m < 5; m++) { buf[m][i] = dtpp * dtemp[m]; } cuf[i] = buf[1][i] * buf[1][i]; buf[0][i] = cuf[i] + buf[2][i] * buf[2][i] + buf[3][i] * buf[3][i]; q[i] = five/ten * (buf[1][i]*ue[1][i] + buf[2][i]*ue[2][i] + buf[3][i]*ue[3][i]); } for (i = 1; i <= grid_points[0]-2; i++) { im1 = i-1; ip1 = i+1; forcing[0][i][j][k] = forcing[0][i][j][k] - tx2*( ue[1][ip1]-ue[1][im1] )+ dx1tx1*(ue[0][ip1]-two*ue[0][i]+ue[0][im1]); forcing[1][i][j][k] = forcing[1][i][j][k] - tx2 * ((ue[1][ip1]*buf[1][ip1]+c2*(ue[4][ip1]-q[ip1]))- (ue[1][im1]*buf[1][im1]+c2*(ue[4][im1]-q[im1])))+ xxcon1*(buf[1][ip1]-two*buf[1][i]+buf[1][im1])+ dx2tx1*( ue[1][ip1]-two* ue[1][i]+ue[1][im1]); forcing[2][i][j][k] = forcing[2][i][j][k] - tx2 * (ue[2][ip1]*buf[1][ip1]-ue[2][im1]*buf[1][im1])+ xxcon2*(buf[2][ip1]-two*buf[2][i]+buf[2][im1])+ dx3tx1*( ue[2][ip1]-two*ue[2][i] +ue[2][im1]); forcing[3][i][j][k] = forcing[3][i][j][k] - tx2*(ue[3][ip1]*buf[1][ip1]-ue[3][im1]*buf[1][im1])+ xxcon2*(buf[3][ip1]-two*buf[3][i]+buf[3][im1])+ dx4tx1*( ue[3][ip1]-two* ue[3][i]+ ue[3][im1]); forcing[4][i][j][k] = forcing[4][i][j][k] - tx2*(buf[1][ip1]*(c1*ue[4][ip1]-c2*q[ip1])- buf[1][im1]*(c1*ue[4][im1]-c2*q[im1]))+ five/ten*xxcon3*(buf[0][ip1]-two*buf[0][i]+ buf[0][im1])+ xxcon4*(cuf[ip1]-two*cuf[i]+cuf[im1])+ xxcon5*(buf[4][ip1]-two*buf[4][i]+buf[4][im1])+ dx5tx1*( ue[4][ip1]-two* ue[4][i]+ ue[4][im1]); } /*-------------------------------------------------------------------- c Fourth-order dissipation c-------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { i = 1; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (five*ue[m][i] - four*ue[m][i+1] +ue[m][i+2]); i = 2; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (-four*ue[m][i-1] + six*ue[m][i] - four*ue[m][i+1] + ue[m][i+2]); } for (m = 0; m < 5; m++) { for (i = 3; i <= grid_points[0]-4; i++) { forcing[m][i][j][k] = forcing[m][i][j][k] - dssp* (ue[m][i-2] - four*ue[m][i-1] + six*ue[m][i] - four*ue[m][i+1] + ue[m][i+2]); } } for (m = 0; m < 5; m++) { i = grid_points[0]-3; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (ue[m][i-2] - four*ue[m][i-1] + six*ue[m][i] - four*ue[m][i+1]); i = grid_points[0]-2; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (ue[m][i-2] - four*ue[m][i-1] + five*ue[m][i]); } } } /*-------------------------------------------------------------------- c eta-direction flux differences c-------------------------------------------------------------------*/ for (k = 1; k <= grid_points[2]-2; k++) { zeta = (element_t)k * dnzm1; for (i = 1; i <= grid_points[0]-2; i++) { xi = (element_t)i * dnxm1; for (j = 0; j <= grid_points[1]-1; j++) { eta = (element_t)j * dnym1; exact_solution(xi, eta, zeta, dtemp); for (m = 0; m < 5; m++) { ue[m][j] = dtemp[m]; } dtpp = one/dtemp[0]; for (m = 1; m < 5; m++) { buf[m][j] = dtpp * dtemp[m]; } cuf[j] = buf[2][j] * buf[2][j]; buf[0][j] = cuf[j] + buf[1][j] * buf[1][j] + buf[3][j] * buf[3][j]; q[j] = five/ten*(buf[1][j]*ue[1][j] + buf[2][j]*ue[2][j] + buf[3][j]*ue[3][j]); } for (j = 1; j <= grid_points[1]-2; j++) { jm1 = j-1; jp1 = j+1; forcing[0][i][j][k] = forcing[0][i][j][k] - ty2*( ue[2][jp1]-ue[2][jm1] )+ dy1ty1*(ue[0][jp1]-two*ue[0][j]+ue[0][jm1]); forcing[1][i][j][k] = forcing[1][i][j][k] - ty2*(ue[1][jp1]*buf[2][jp1]-ue[1][jm1]*buf[2][jm1])+ yycon2*(buf[1][jp1]-two*buf[1][j]+buf[1][jm1])+ dy2ty1*( ue[1][jp1]-two* ue[1][j]+ ue[1][jm1]); forcing[2][i][j][k] = forcing[2][i][j][k] - ty2*((ue[2][jp1]*buf[2][jp1]+c2*(ue[4][jp1]-q[jp1]))- (ue[2][jm1]*buf[2][jm1]+c2*(ue[4][jm1]-q[jm1])))+ yycon1*(buf[2][jp1]-two*buf[2][j]+buf[2][jm1])+ dy3ty1*( ue[2][jp1]-two*ue[2][j] +ue[2][jm1]); forcing[3][i][j][k] = forcing[3][i][j][k] - ty2*(ue[3][jp1]*buf[2][jp1]-ue[3][jm1]*buf[2][jm1])+ yycon2*(buf[3][jp1]-two*buf[3][j]+buf[3][jm1])+ dy4ty1*( ue[3][jp1]-two*ue[3][j]+ ue[3][jm1]); forcing[4][i][j][k] = forcing[4][i][j][k] - ty2*(buf[2][jp1]*(c1*ue[4][jp1]-c2*q[jp1])- buf[2][jm1]*(c1*ue[4][jm1]-c2*q[jm1]))+ five/ten*yycon3*(buf[0][jp1]-two*buf[0][j]+ buf[0][jm1])+ yycon4*(cuf[jp1]-two*cuf[j]+cuf[jm1])+ yycon5*(buf[4][jp1]-two*buf[4][j]+buf[4][jm1])+ dy5ty1*(ue[4][jp1]-two*ue[4][j]+ue[4][jm1]); } /*-------------------------------------------------------------------- c Fourth-order dissipation c-------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { j = 1; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (five*ue[m][j] - four*ue[m][j+1] +ue[m][j+2]); j = 2; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (-four*ue[m][j-1] + six*ue[m][j] - four*ue[m][j+1] + ue[m][j+2]); } for (m = 0; m < 5; m++) { for (j = 3; j <= grid_points[1]-4; j++) { forcing[m][i][j][k] = forcing[m][i][j][k] - dssp* (ue[m][j-2] - four*ue[m][j-1] + six*ue[m][j] - four*ue[m][j+1] + ue[m][j+2]); } } for (m = 0; m < 5; m++) { j = grid_points[1]-3; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (ue[m][j-2] - four*ue[m][j-1] + six*ue[m][j] - four*ue[m][j+1]); j = grid_points[1]-2; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (ue[m][j-2] - four*ue[m][j-1] + five*ue[m][j]); } } } /*-------------------------------------------------------------------- c zeta-direction flux differences c-------------------------------------------------------------------*/ for (j = 1; j <= grid_points[1]-2; j++) { eta = (element_t)j * dnym1; for (i = 1; i <= grid_points[0]-2; i++) { xi = (element_t)i * dnxm1; for (k = 0; k <= grid_points[2]-1; k++) { zeta = (element_t)k * dnzm1; exact_solution(xi, eta, zeta, dtemp); for (m = 0; m < 5; m++) { ue[m][k] = dtemp[m]; } dtpp = one/dtemp[0]; for (m = 1; m < 5; m++) { buf[m][k] = dtpp * dtemp[m]; } cuf[k] = buf[3][k] * buf[3][k]; buf[0][k] = cuf[k] + buf[1][k] * buf[1][k] + buf[2][k] * buf[2][k]; q[k] = five/ten*(buf[1][k]*ue[1][k] + buf[2][k]*ue[2][k] + buf[3][k]*ue[3][k]); } for (k = 1; k <= grid_points[2]-2; k++) { km1 = k-1; kp1 = k+1; forcing[0][i][j][k] = forcing[0][i][j][k] - tz2*( ue[3][kp1]-ue[3][km1] )+ dz1tz1*(ue[0][kp1]-two*ue[0][k]+ue[0][km1]); forcing[1][i][j][k] = forcing[1][i][j][k] - tz2 * (ue[1][kp1]*buf[3][kp1]-ue[1][km1]*buf[3][km1])+ zzcon2*(buf[1][kp1]-two*buf[1][k]+buf[1][km1])+ dz2tz1*( ue[1][kp1]-two* ue[1][k]+ ue[1][km1]); forcing[2][i][j][k] = forcing[2][i][j][k] - tz2 * (ue[2][kp1]*buf[3][kp1]-ue[2][km1]*buf[3][km1])+ zzcon2*(buf[2][kp1]-two*buf[2][k]+buf[2][km1])+ dz3tz1*(ue[2][kp1]-two*ue[2][k]+ue[2][km1]); forcing[3][i][j][k] = forcing[3][i][j][k] - tz2 * ((ue[3][kp1]*buf[3][kp1]+c2*(ue[4][kp1]-q[kp1]))- (ue[3][km1]*buf[3][km1]+c2*(ue[4][km1]-q[km1])))+ zzcon1*(buf[3][kp1]-two*buf[3][k]+buf[3][km1])+ dz4tz1*( ue[3][kp1]-two*ue[3][k] +ue[3][km1]); forcing[4][i][j][k] = forcing[4][i][j][k] - tz2 * (buf[3][kp1]*(c1*ue[4][kp1]-c2*q[kp1])- buf[3][km1]*(c1*ue[4][km1]-c2*q[km1]))+ five/ten*zzcon3*(buf[0][kp1]-two*buf[0][k] +buf[0][km1])+ zzcon4*(cuf[kp1]-two*cuf[k]+cuf[km1])+ zzcon5*(buf[4][kp1]-two*buf[4][k]+buf[4][km1])+ dz5tz1*( ue[4][kp1]-two*ue[4][k]+ ue[4][km1]); } /*-------------------------------------------------------------------- c Fourth-order dissipation c-------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { k = 1; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (five*ue[m][k] - four*ue[m][k+1] +ue[m][k+2]); k = 2; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (-four*ue[m][k-1] + six*ue[m][k] - four*ue[m][k+1] + ue[m][k+2]); } for (m = 0; m < 5; m++) { for (k = 3; k <= grid_points[2]-4; k++) { forcing[m][i][j][k] = forcing[m][i][j][k] - dssp* (ue[m][k-2] - four*ue[m][k-1] + six*ue[m][k] - four*ue[m][k+1] + ue[m][k+2]); } } for (m = 0; m < 5; m++) { k = grid_points[2]-3; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (ue[m][k-2] - four*ue[m][k-1] + six*ue[m][k] - four*ue[m][k+1]); k = grid_points[2]-2; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (ue[m][k-2] - four*ue[m][k-1] + five*ue[m][k]); } } } /*-------------------------------------------------------------------- c now change the sign of the forcing function, c-------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { forcing[m][i][j][k] = -one * forcing[m][i][j][k]; } } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void exact_solution(element_t xi, element_t eta, element_t zeta, element_t dtemp[5]) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c this function returns the exact solution at point xi, eta, zeta c-------------------------------------------------------------------*/ int m; for (m = 0; m < 5; m++) { dtemp[m] = ce[0][m] + xi*(ce[1][m] + xi*(ce[4][m] + xi*(ce[7][m] + xi*ce[10][m]))) + eta*(ce[2][m] + eta*(ce[5][m] + eta*(ce[8][m] + eta*ce[11][m])))+ zeta*(ce[3][m] + zeta*(ce[6][m] + zeta*(ce[9][m] + zeta*ce[12][m]))); } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void initialize(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c This subroutine initializes the field variable u using c tri-linear transfinite interpolation of the boundary values c-------------------------------------------------------------------*/ int i, j, k, m, ix, iy, iz; element_t xi, eta, zeta, Pface[2][3][5], Pxi, Peta, Pzeta, temp[5]; /*-------------------------------------------------------------------- c Later (in compute_rhs) we compute 1/u for every element. A few of c the corner elements are not used, but it convenient (and faster) c to compute the whole thing with a simple loop. Make sure those c values are nonzero by initializing the whole thing here. c-------------------------------------------------------------------*/ for (i = 0; i <= IMAX-1; i++) { for (j = 0; j <= IMAX-1; j++) { for (k = 0; k <= IMAX-1; k++) { u[0][i][j][k] = one; u[1][i][j][k] = zero; u[2][i][j][k] = zero; u[3][i][j][k] = zero; u[4][i][j][k] = one; } } } /*-------------------------------------------------------------------- c first store the "interpolated" values everywhere on the grid c-------------------------------------------------------------------*/ for (i = 0; i <= grid_points[0]-1; i++) { xi = (element_t)i * dnxm1; for (j = 0; j <= grid_points[1]-1; j++) { eta = (element_t)j * dnym1; for (k = 0; k <= grid_points[2]-1; k++) { zeta = (element_t)k * dnzm1; for (ix = 0; ix < 2; ix++) { exact_solution((element_t)ix, eta, zeta, &Pface[ix][0][0]); } for (iy = 0; iy < 2; iy++) { exact_solution(xi, (element_t)iy , zeta, &Pface[iy][1][0]); } for (iz = 0; iz < 2; iz++) { exact_solution(xi, eta, (element_t)iz, &Pface[iz][2][0]); } for (m = 0; m < 5; m++) { Pxi = xi * Pface[1][0][m] + (one-xi) * Pface[0][0][m]; Peta = eta * Pface[1][1][m] + (one-eta) * Pface[0][1][m]; Pzeta = zeta * Pface[1][2][m] + (one-zeta) * Pface[0][2][m]; u[m][i][j][k] = Pxi + Peta + Pzeta - Pxi*Peta - Pxi*Pzeta - Peta*Pzeta + Pxi*Peta*Pzeta; } } } } /*-------------------------------------------------------------------- c now store the exact values on the boundaries c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c west face c-------------------------------------------------------------------*/ xi = zero; i = 0; for (j = 0; j < grid_points[1]; j++) { eta = (element_t)j * dnym1; for (k = 0; k < grid_points[2]; k++) { zeta = (element_t)k * dnzm1; exact_solution(xi, eta, zeta, temp); for (m = 0; m < 5; m++) { u[m][i][j][k] = temp[m]; } } } /*-------------------------------------------------------------------- c east face c-------------------------------------------------------------------*/ xi = one; i = grid_points[0]-1; for (j = 0; j < grid_points[1]; j++) { eta = (element_t)j * dnym1; for (k = 0; k < grid_points[2]; k++) { zeta = (element_t)k * dnzm1; exact_solution(xi, eta, zeta, temp); for (m = 0; m < 5; m++) { u[m][i][j][k] = temp[m]; } } } /*-------------------------------------------------------------------- c south face c-------------------------------------------------------------------*/ eta = zero; j = 0; for (i = 0; i < grid_points[0]; i++) { xi = (element_t)i * dnxm1; for (k = 0; k < grid_points[2]; k++) { zeta = (element_t)k * dnzm1; exact_solution(xi, eta, zeta, temp); for (m = 0; m < 5; m++) { u[m][i][j][k] = temp[m]; } } } /*-------------------------------------------------------------------- c north face c-------------------------------------------------------------------*/ eta = one; j = grid_points[1]-1; for (i = 0; i < grid_points[0]; i++) { xi = (element_t)i * dnxm1; for (k = 0; k < grid_points[2]; k++) { zeta = (element_t)k * dnzm1; exact_solution(xi, eta, zeta, temp); for (m = 0; m < 5; m++) { u[m][i][j][k] = temp[m]; } } } /*-------------------------------------------------------------------- c bottom face c-------------------------------------------------------------------*/ zeta = zero; k = 0; for (i = 0; i < grid_points[0]; i++) { xi = (element_t)i *dnxm1; for (j = 0; j < grid_points[1]; j++) { eta = (element_t)j * dnym1; exact_solution(xi, eta, zeta, temp); for (m = 0; m < 5; m++) { u[m][i][j][k] = temp[m]; } } } /*-------------------------------------------------------------------- c top face c-------------------------------------------------------------------*/ zeta = one; k = grid_points[2]-1; for (i = 0; i < grid_points[0]; i++) { xi = (element_t)i * dnxm1; for (j = 0; j < grid_points[1]; j++) { eta = (element_t)j * dnym1; exact_solution(xi, eta, zeta, temp); for (m = 0; m < 5; m++) { u[m][i][j][k] = temp[m]; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void lhsinit(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ int i, j, k, n; /*-------------------------------------------------------------------- c zap the whole left hand side for starters c-------------------------------------------------------------------*/ for (n = 0; n < 15; n++) { #pragma omp for nowait for (i = 0; i < grid_points[0]; i++) { for (j = 0; j < grid_points[1]; j++) { for (k = 0; k < grid_points[2]; k++) { lhs[n][i][j][k] = zero; } } } } #pragma omp barrier /*-------------------------------------------------------------------- c next, set all diagonal values to 1. This is overkill, but c convenient c-------------------------------------------------------------------*/ for (n = 0; n < 3; n++) { #pragma omp for for (i = 0; i < grid_points[0]; i++) { for (j = 0; j < grid_points[1]; j++) { for (k = 0; k < grid_points[2]; k++) { lhs[5*n+2][i][j][k] = one; } } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void lhsx(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c This function computes the left hand side for the three x-factors c-------------------------------------------------------------------*/ element_t ru1; int i, j, k; /*-------------------------------------------------------------------- c first fill the lhs for the u-eigenvalue c-------------------------------------------------------------------*/ for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { #pragma omp for for (i = 0; i <= grid_points[0]-1; i++) { ru1 = c3c4*rho_i[i][j][k]; cv[i] = us[i][j][k]; rhon[i] = max(dx2+con43*ru1, max(dx5+c1c5*ru1, max(dxmax+ru1, dx1))); } #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { lhs[0][i][j][k] = zero; lhs[1][i][j][k] = - dttx2 * cv[i-1] - dttx1 * rhon[i-1]; lhs[2][i][j][k] = one + c2dttx1 * rhon[i]; lhs[3][i][j][k] = dttx2 * cv[i+1] - dttx1 * rhon[i+1]; lhs[4][i][j][k] = zero; } } } /*-------------------------------------------------------------------- c add fourth order dissipation c-------------------------------------------------------------------*/ i = 1; #pragma omp for nowait for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[2][i][j][k] = lhs[2][i][j][k] + comz5; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[4][i][j][k] = lhs[4][i][j][k] + comz1; lhs[1][i+1][j][k] = lhs[1][i+1][j][k] - comz4; lhs[2][i+1][j][k] = lhs[2][i+1][j][k] + comz6; lhs[3][i+1][j][k] = lhs[3][i+1][j][k] - comz4; lhs[4][i+1][j][k] = lhs[4][i+1][j][k] + comz1; } } #pragma omp for nowait for (i = 3; i <= grid_points[0]-4; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[0][i][j][k] = lhs[0][i][j][k] + comz1; lhs[1][i][j][k] = lhs[1][i][j][k] - comz4; lhs[2][i][j][k] = lhs[2][i][j][k] + comz6; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[4][i][j][k] = lhs[4][i][j][k] + comz1; } } } i = grid_points[0]-3; #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[0][i][j][k] = lhs[0][i][j][k] + comz1; lhs[1][i][j][k] = lhs[1][i][j][k] - comz4; lhs[2][i][j][k] = lhs[2][i][j][k] + comz6; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[0][i+1][j][k] = lhs[0][i+1][j][k] + comz1; lhs[1][i+1][j][k] = lhs[1][i+1][j][k] - comz4; lhs[2][i+1][j][k] = lhs[2][i+1][j][k] + comz5; } } /*-------------------------------------------------------------------- c subsequently, fill the other factors (u+c), (u-c) by adding to c the first c-------------------------------------------------------------------*/ #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[0+5][i][j][k] = lhs[0][i][j][k]; lhs[1+5][i][j][k] = lhs[1][i][j][k] - dttx2 * speed[i-1][j][k]; lhs[2+5][i][j][k] = lhs[2][i][j][k]; lhs[3+5][i][j][k] = lhs[3][i][j][k] + dttx2 * speed[i+1][j][k]; lhs[4+5][i][j][k] = lhs[4][i][j][k]; lhs[0+10][i][j][k] = lhs[0][i][j][k]; lhs[1+10][i][j][k] = lhs[1][i][j][k] + dttx2 * speed[i-1][j][k]; lhs[2+10][i][j][k] = lhs[2][i][j][k]; lhs[3+10][i][j][k] = lhs[3][i][j][k] - dttx2 * speed[i+1][j][k]; lhs[4+10][i][j][k] = lhs[4][i][j][k]; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void lhsy(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c This function computes the left hand side for the three y-factors c-------------------------------------------------------------------*/ element_t ru1; int i, j, k; /*-------------------------------------------------------------------- c first fill the lhs for the u-eigenvalue c-------------------------------------------------------------------*/ for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { #pragma omp for for (j = 0; j <= grid_points[1]-1; j++) { ru1 = c3c4*rho_i[i][j][k]; cv[j] = vs[i][j][k]; rhoq[j] = max(dy3 + con43 * ru1, max(dy5 + c1c5*ru1, max(dymax + ru1, dy1))); } #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { lhs[0][i][j][k] = zero; lhs[1][i][j][k] = -dtty2 * cv[j-1] - dtty1 * rhoq[j-1]; lhs[2][i][j][k] = one + c2dtty1 * rhoq[j]; lhs[3][i][j][k] = dtty2 * cv[j+1] - dtty1 * rhoq[j+1]; lhs[4][i][j][k] = zero; } } } /*-------------------------------------------------------------------- c add fourth order dissipation c-------------------------------------------------------------------*/ j = 1; #pragma omp for nowait for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[2][i][j][k] = lhs[2][i][j][k] + comz5; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[4][i][j][k] = lhs[4][i][j][k] + comz1; lhs[1][i][j+1][k] = lhs[1][i][j+1][k] - comz4; lhs[2][i][j+1][k] = lhs[2][i][j+1][k] + comz6; lhs[3][i][j+1][k] = lhs[3][i][j+1][k] - comz4; lhs[4][i][j+1][k] = lhs[4][i][j+1][k] + comz1; } } #pragma omp for nowait for (i = 1; i <= grid_points[0]-2; i++) { for (j = 3; j <= grid_points[1]-4; j++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[0][i][j][k] = lhs[0][i][j][k] + comz1; lhs[1][i][j][k] = lhs[1][i][j][k] - comz4; lhs[2][i][j][k] = lhs[2][i][j][k] + comz6; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[4][i][j][k] = lhs[4][i][j][k] + comz1; } } } j = grid_points[1]-3; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[0][i][j][k] = lhs[0][i][j][k] + comz1; lhs[1][i][j][k] = lhs[1][i][j][k] - comz4; lhs[2][i][j][k] = lhs[2][i][j][k] + comz6; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[0][i][j+1][k] = lhs[0][i][j+1][k] + comz1; lhs[1][i][j+1][k] = lhs[1][i][j+1][k] - comz4; lhs[2][i][j+1][k] = lhs[2][i][j+1][k] + comz5; } } /*-------------------------------------------------------------------- c subsequently, do the other two factors c-------------------------------------------------------------------*/ #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[0+5][i][j][k] = lhs[0][i][j][k]; lhs[1+5][i][j][k] = lhs[1][i][j][k] - dtty2 * speed[i][j-1][k]; lhs[2+5][i][j][k] = lhs[2][i][j][k]; lhs[3+5][i][j][k] = lhs[3][i][j][k] + dtty2 * speed[i][j+1][k]; lhs[4+5][i][j][k] = lhs[4][i][j][k]; lhs[0+10][i][j][k] = lhs[0][i][j][k]; lhs[1+10][i][j][k] = lhs[1][i][j][k] + dtty2 * speed[i][j-1][k]; lhs[2+10][i][j][k] = lhs[2][i][j][k]; lhs[3+10][i][j][k] = lhs[3][i][j][k] - dtty2 * speed[i][j+1][k]; lhs[4+10][i][j][k] = lhs[4][i][j][k]; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void lhsz(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c This function computes the left hand side for the three z-factors c-------------------------------------------------------------------*/ element_t ru1; int i, j, k; /*-------------------------------------------------------------------- c first fill the lhs for the u-eigenvalue c-------------------------------------------------------------------*/ for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { #pragma omp for for (k = 0; k <= grid_points[2]-1; k++) { ru1 = c3c4*rho_i[i][j][k]; cv[k] = ws[i][j][k]; rhos[k] = max(dz4 + con43 * ru1, max(dz5 + c1c5 * ru1, max(dzmax + ru1, dz1))); } #pragma omp for for (k = 1; k <= grid_points[2]-2; k++) { lhs[0][i][j][k] = zero; lhs[1][i][j][k] = -dttz2 * cv[k-1] - dttz1 * rhos[k-1]; lhs[2][i][j][k] = one + c2dttz1 * rhos[k]; lhs[3][i][j][k] = dttz2 * cv[k+1] - dttz1 * rhos[k+1]; lhs[4][i][j][k] = zero; } } } /*-------------------------------------------------------------------- c add fourth order dissipation c-------------------------------------------------------------------*/ k = 1; #pragma omp for nowait for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { lhs[2][i][j][k] = lhs[2][i][j][k] + comz5; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[4][i][j][k] = lhs[4][i][j][k] + comz1; lhs[1][i][j][k+1] = lhs[1][i][j][k+1] - comz4; lhs[2][i][j][k+1] = lhs[2][i][j][k+1] + comz6; lhs[3][i][j][k+1] = lhs[3][i][j][k+1] - comz4; lhs[4][i][j][k+1] = lhs[4][i][j][k+1] + comz1; } } #pragma omp for nowait for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 3; k <= grid_points[2]-4; k++) { lhs[0][i][j][k] = lhs[0][i][j][k] + comz1; lhs[1][i][j][k] = lhs[1][i][j][k] - comz4; lhs[2][i][j][k] = lhs[2][i][j][k] + comz6; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[4][i][j][k] = lhs[4][i][j][k] + comz1; } } } k = grid_points[2]-3; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { lhs[0][i][j][k] = lhs[0][i][j][k] + comz1; lhs[1][i][j][k] = lhs[1][i][j][k] - comz4; lhs[2][i][j][k] = lhs[2][i][j][k] + comz6; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[0][i][j][k+1] = lhs[0][i][j][k+1] + comz1; lhs[1][i][j][k+1] = lhs[1][i][j][k+1] - comz4; lhs[2][i][j][k+1] = lhs[2][i][j][k+1] + comz5; } } /*-------------------------------------------------------------------- c subsequently, fill the other factors (u+c), (u-c) c-------------------------------------------------------------------*/ #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[0+5][i][j][k] = lhs[0][i][j][k]; lhs[1+5][i][j][k] = lhs[1][i][j][k] - dttz2 * speed[i][j][k-1]; lhs[2+5][i][j][k] = lhs[2][i][j][k]; lhs[3+5][i][j][k] = lhs[3][i][j][k] + dttz2 * speed[i][j][k+1]; lhs[4+5][i][j][k] = lhs[4][i][j][k]; lhs[0+10][i][j][k] = lhs[0][i][j][k]; lhs[1+10][i][j][k] = lhs[1][i][j][k] + dttz2 * speed[i][j][k-1]; lhs[2+10][i][j][k] = lhs[2][i][j][k]; lhs[3+10][i][j][k] = lhs[3][i][j][k] - dttz2 * speed[i][j][k+1]; lhs[4+10][i][j][k] = lhs[4][i][j][k]; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void ninvr(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c block-diagonal matrix-vector multiplication c-------------------------------------------------------------------*/ int i, j, k; element_t r1, r2, r3, r4, r5, t1, t2; #pragma omp parallel for default(shared) private(i,j,k,r1,r2,r3,r4,r5,t1,t2) for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { r1 = rhs[0][i][j][k]; r2 = rhs[1][i][j][k]; r3 = rhs[2][i][j][k]; r4 = rhs[3][i][j][k]; r5 = rhs[4][i][j][k]; t1 = bt * r3; t2 = five/ten * ( r4 + r5 ); rhs[0][i][j][k] = -r2; rhs[1][i][j][k] = r1; rhs[2][i][j][k] = bt * ( r4 - r5 ); rhs[3][i][j][k] = -t1 + t2; rhs[4][i][j][k] = t1 + t2; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void pinvr(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c block-diagonal matrix-vector multiplication c-------------------------------------------------------------------*/ int i, j, k; element_t r1, r2, r3, r4, r5, t1, t2; #pragma omp parallel for default(shared) private(i,j,k,r1,r2,r3,r4,r5,t1,t2) for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { r1 = rhs[0][i][j][k]; r2 = rhs[1][i][j][k]; r3 = rhs[2][i][j][k]; r4 = rhs[3][i][j][k]; r5 = rhs[4][i][j][k]; t1 = bt * r1; t2 = five/ten * ( r4 + r5 ); rhs[0][i][j][k] = bt * ( r4 - r5 ); rhs[1][i][j][k] = -r3; rhs[2][i][j][k] = r2; rhs[3][i][j][k] = -t1 + t2; rhs[4][i][j][k] = t1 + t2; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void compute_rhs(void) { #pragma omp parallel { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ int i, j, k, m; element_t aux, rho_inv, uijk, up1, um1, vijk, vp1, vm1, wijk, wp1, wm1; /*-------------------------------------------------------------------- c compute the reciprocal of density, and the kinetic energy, c and the speed of sound. c-------------------------------------------------------------------*/ #pragma omp for nowait for (i = 0; i <= grid_points[0]-1; i++) { for (j = 0; j <= grid_points[1]-1; j++) { for (k = 0; k <= grid_points[2]-1; k++) { rho_inv = one/u[0][i][j][k]; rho_i[i][j][k] = rho_inv; us[i][j][k] = u[1][i][j][k] * rho_inv; vs[i][j][k] = u[2][i][j][k] * rho_inv; ws[i][j][k] = u[3][i][j][k] * rho_inv; square[i][j][k] = five/ten* (u[1][i][j][k]*u[1][i][j][k] + u[2][i][j][k]*u[2][i][j][k] + u[3][i][j][k]*u[3][i][j][k] ) * rho_inv; qs[i][j][k] = square[i][j][k] * rho_inv; /*-------------------------------------------------------------------- c (do not need speed and ainx until the lhs computation) c-------------------------------------------------------------------*/ aux = c1c2*rho_inv* (u[4][i][j][k] - square[i][j][k]); aux = sqrt_asm(aux); speed[i][j][k] = aux; ainv[i][j][k] = one/aux; } } } /*-------------------------------------------------------------------- c copy the exact forcing term to the right hand side; because c this forcing term is known, we can store it on the whole grid c including the boundary c-------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { #pragma omp for for (i = 0; i <= grid_points[0]-1; i++) { for (j = 0; j <= grid_points[1]-1; j++) { for (k = 0; k <= grid_points[2]-1; k++) { rhs[m][i][j][k] = forcing[m][i][j][k]; } } } } /*-------------------------------------------------------------------- c compute xi-direction fluxes c-------------------------------------------------------------------*/ #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { uijk = us[i][j][k]; up1 = us[i+1][j][k]; um1 = us[i-1][j][k]; rhs[0][i][j][k] = rhs[0][i][j][k] + dx1tx1 * (u[0][i+1][j][k] - two*u[0][i][j][k] + u[0][i-1][j][k]) - tx2 * (u[1][i+1][j][k] - u[1][i-1][j][k]); rhs[1][i][j][k] = rhs[1][i][j][k] + dx2tx1 * (u[1][i+1][j][k] - two*u[1][i][j][k] + u[1][i-1][j][k]) + xxcon2*con43 * (up1 - two*uijk + um1) - tx2 * (u[1][i+1][j][k]*up1 - u[1][i-1][j][k]*um1 + (u[4][i+1][j][k]- square[i+1][j][k]- u[4][i-1][j][k]+ square[i-1][j][k])* c2); rhs[2][i][j][k] = rhs[2][i][j][k] + dx3tx1 * (u[2][i+1][j][k] - two*u[2][i][j][k] + u[2][i-1][j][k]) + xxcon2 * (vs[i+1][j][k] - two*vs[i][j][k] + vs[i-1][j][k]) - tx2 * (u[2][i+1][j][k]*up1 - u[2][i-1][j][k]*um1); rhs[3][i][j][k] = rhs[3][i][j][k] + dx4tx1 * (u[3][i+1][j][k] - two*u[3][i][j][k] + u[3][i-1][j][k]) + xxcon2 * (ws[i+1][j][k] - two*ws[i][j][k] + ws[i-1][j][k]) - tx2 * (u[3][i+1][j][k]*up1 - u[3][i-1][j][k]*um1); rhs[4][i][j][k] = rhs[4][i][j][k] + dx5tx1 * (u[4][i+1][j][k] - two*u[4][i][j][k] + u[4][i-1][j][k]) + xxcon3 * (qs[i+1][j][k] - two*qs[i][j][k] + qs[i-1][j][k]) + xxcon4 * (up1*up1 - two*uijk*uijk + um1*um1) + xxcon5 * (u[4][i+1][j][k]*rho_i[i+1][j][k] - two*u[4][i][j][k]*rho_i[i][j][k] + u[4][i-1][j][k]*rho_i[i-1][j][k]) - tx2 * ( (c1*u[4][i+1][j][k] - c2*square[i+1][j][k])*up1 - (c1*u[4][i-1][j][k] - c2*square[i-1][j][k])*um1 ); } } } /*-------------------------------------------------------------------- c add fourth order xi-direction dissipation c-------------------------------------------------------------------*/ i = 1; for (m = 0; m < 5; m++) { #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k]- dssp * ( five*u[m][i][j][k] - four*u[m][i+1][j][k] + u[m][i+2][j][k]); } } } i = 2; for (m = 0; m < 5; m++) { #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * (-four*u[m][i-1][j][k] + six*u[m][i][j][k] - four*u[m][i+1][j][k] + u[m][i+2][j][k]); } } } for (m = 0; m < 5; m++) { #pragma omp for for (i = 3*1; i <= grid_points[0]-3*1-1; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i-2][j][k] - four*u[m][i-1][j][k] + six*u[m][i][j][k] - four*u[m][i+1][j][k] + u[m][i+2][j][k] ); } } } } i = grid_points[0]-3; for (m = 0; m < 5; m++) { #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i-2][j][k] - four*u[m][i-1][j][k] + six*u[m][i][j][k] - four*u[m][i+1][j][k] ); } } } i = grid_points[0]-2; for (m = 0; m < 5; m++) { #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i-2][j][k] - four*u[m][i-1][j][k] + five*u[m][i][j][k] ); } } } #pragma omp barrier /*-------------------------------------------------------------------- c compute eta-direction fluxes c-------------------------------------------------------------------*/ #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { vijk = vs[i][j][k]; vp1 = vs[i][j+1][k]; vm1 = vs[i][j-1][k]; rhs[0][i][j][k] = rhs[0][i][j][k] + dy1ty1 * (u[0][i][j+1][k] - two*u[0][i][j][k] + u[0][i][j-1][k]) - ty2 * (u[2][i][j+1][k] - u[2][i][j-1][k]); rhs[1][i][j][k] = rhs[1][i][j][k] + dy2ty1 * (u[1][i][j+1][k] - two*u[1][i][j][k] + u[1][i][j-1][k]) + yycon2 * (us[i][j+1][k] - two*us[i][j][k] + us[i][j-1][k]) - ty2 * (u[1][i][j+1][k]*vp1 - u[1][i][j-1][k]*vm1); rhs[2][i][j][k] = rhs[2][i][j][k] + dy3ty1 * (u[2][i][j+1][k] - two*u[2][i][j][k] + u[2][i][j-1][k]) + yycon2*con43 * (vp1 - two*vijk + vm1) - ty2 * (u[2][i][j+1][k]*vp1 - u[2][i][j-1][k]*vm1 + (u[4][i][j+1][k] - square[i][j+1][k] - u[4][i][j-1][k] + square[i][j-1][k]) *c2); rhs[3][i][j][k] = rhs[3][i][j][k] + dy4ty1 * (u[3][i][j+1][k] - two*u[3][i][j][k] + u[3][i][j-1][k]) + yycon2 * (ws[i][j+1][k] - two*ws[i][j][k] + ws[i][j-1][k]) - ty2 * (u[3][i][j+1][k]*vp1 - u[3][i][j-1][k]*vm1); rhs[4][i][j][k] = rhs[4][i][j][k] + dy5ty1 * (u[4][i][j+1][k] - two*u[4][i][j][k] + u[4][i][j-1][k]) + yycon3 * (qs[i][j+1][k] - two*qs[i][j][k] + qs[i][j-1][k]) + yycon4 * (vp1*vp1 - two*vijk*vijk + vm1*vm1) + yycon5 * (u[4][i][j+1][k]*rho_i[i][j+1][k] - two*u[4][i][j][k]*rho_i[i][j][k] + u[4][i][j-1][k]*rho_i[i][j-1][k]) - ty2 * ((c1*u[4][i][j+1][k] - c2*square[i][j+1][k]) * vp1 - (c1*u[4][i][j-1][k] - c2*square[i][j-1][k]) * vm1); } } } /*-------------------------------------------------------------------- c add fourth order eta-direction dissipation c-------------------------------------------------------------------*/ j = 1; for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k]- dssp * ( five*u[m][i][j][k] - four*u[m][i][j+1][k] + u[m][i][j+2][k]); } } } j = 2; for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * (-four*u[m][i][j-1][k] + six*u[m][i][j][k] - four*u[m][i][j+1][k] + u[m][i][j+2][k]); } } } for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 3*1; j <= grid_points[1]-3*1-1; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i][j-2][k] - four*u[m][i][j-1][k] + six*u[m][i][j][k] - four*u[m][i][j+1][k] + u[m][i][j+2][k] ); } } } } j = grid_points[1]-3; for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i][j-2][k] - four*u[m][i][j-1][k] + six*u[m][i][j][k] - four*u[m][i][j+1][k] ); } } } j = grid_points[1]-2; for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i][j-2][k] - four*u[m][i][j-1][k] + five*u[m][i][j][k] ); } } } #pragma omp barrier /*-------------------------------------------------------------------- c compute zeta-direction fluxes c-------------------------------------------------------------------*/ #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { wijk = ws[i][j][k]; wp1 = ws[i][j][k+1]; wm1 = ws[i][j][k-1]; rhs[0][i][j][k] = rhs[0][i][j][k] + dz1tz1 * (u[0][i][j][k+1] - two*u[0][i][j][k] + u[0][i][j][k-1]) - tz2 * (u[3][i][j][k+1] - u[3][i][j][k-1]); rhs[1][i][j][k] = rhs[1][i][j][k] + dz2tz1 * (u[1][i][j][k+1] - two*u[1][i][j][k] + u[1][i][j][k-1]) + zzcon2 * (us[i][j][k+1] - two*us[i][j][k] + us[i][j][k-1]) - tz2 * (u[1][i][j][k+1]*wp1 - u[1][i][j][k-1]*wm1); rhs[2][i][j][k] = rhs[2][i][j][k] + dz3tz1 * (u[2][i][j][k+1] - two*u[2][i][j][k] + u[2][i][j][k-1]) + zzcon2 * (vs[i][j][k+1] - two*vs[i][j][k] + vs[i][j][k-1]) - tz2 * (u[2][i][j][k+1]*wp1 - u[2][i][j][k-1]*wm1); rhs[3][i][j][k] = rhs[3][i][j][k] + dz4tz1 * (u[3][i][j][k+1] - two*u[3][i][j][k] + u[3][i][j][k-1]) + zzcon2*con43 * (wp1 - two*wijk + wm1) - tz2 * (u[3][i][j][k+1]*wp1 - u[3][i][j][k-1]*wm1 + (u[4][i][j][k+1] - square[i][j][k+1] - u[4][i][j][k-1] + square[i][j][k-1]) *c2); rhs[4][i][j][k] = rhs[4][i][j][k] + dz5tz1 * (u[4][i][j][k+1] - two*u[4][i][j][k] + u[4][i][j][k-1]) + zzcon3 * (qs[i][j][k+1] - two*qs[i][j][k] + qs[i][j][k-1]) + zzcon4 * (wp1*wp1 - two*wijk*wijk + wm1*wm1) + zzcon5 * (u[4][i][j][k+1]*rho_i[i][j][k+1] - two*u[4][i][j][k]*rho_i[i][j][k] + u[4][i][j][k-1]*rho_i[i][j][k-1]) - tz2 * ( (c1*u[4][i][j][k+1] - c2*square[i][j][k+1])*wp1 - (c1*u[4][i][j][k-1] - c2*square[i][j][k-1])*wm1); } } } /*-------------------------------------------------------------------- c add fourth order zeta-direction dissipation c-------------------------------------------------------------------*/ k = 1; for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { rhs[m][i][j][k] = rhs[m][i][j][k]- dssp * ( five*u[m][i][j][k] - four*u[m][i][j][k+1] + u[m][i][j][k+2]); } } } k = 2; for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * (-four*u[m][i][j][k-1] + six*u[m][i][j][k] - four*u[m][i][j][k+1] + u[m][i][j][k+2]); } } } for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 3*1; k <= grid_points[2]-3*1-1; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i][j][k-2] - four*u[m][i][j][k-1] + six*u[m][i][j][k] - four*u[m][i][j][k+1] + u[m][i][j][k+2] ); } } } } k = grid_points[2]-3; for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i][j][k-2] - four*u[m][i][j][k-1] + six*u[m][i][j][k] - four*u[m][i][j][k+1] ); } } } k = grid_points[2]-2; for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i][j][k-2] - four*u[m][i][j][k-1] + five*u[m][i][j][k] ); } } } for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] * dt; } } } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void set_constants(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ ce[0][0] = two; ce[1][0] = zero; ce[2][0] = zero; ce[3][0] = four; ce[4][0] = five; ce[5][0] = three; ce[6][0] = five/ten; ce[7][0] = two/hundred; ce[8][0] = one/hundred; ce[9][0] = three/hundred; ce[10][0] = five/ten; ce[11][0] = four/ten; ce[12][0] = three/ten; ce[0][1] = one; ce[1][1] = zero; ce[2][1] = zero; ce[3][1] = zero; ce[4][1] = one; ce[5][1] = two; ce[6][1] = three; ce[7][1] = one/hundred; ce[8][1] = three/hundred; ce[9][1] = two/hundred; ce[10][1] = four/ten; ce[11][1] = three/ten; ce[12][1] = five/ten; ce[0][2] = two; ce[1][2] = two; ce[2][2] = zero; ce[3][2] = zero; ce[4][2] = zero; ce[5][2] = two; ce[6][2] = three; ce[7][2] = four/hundred; ce[8][2] = three/hundred; ce[9][2] = five/hundred; ce[10][2] = three/ten; ce[11][2] = five/ten; ce[12][2] = four/ten; ce[0][3] = two; ce[1][3] = two; ce[2][3] = zero; ce[3][3] = zero; ce[4][3] = zero; ce[5][3] = two; ce[6][3] = three; ce[7][3] = three/hundred; ce[8][3] = five/hundred; ce[9][3] = four/hundred; ce[10][3] = two/ten; ce[11][3] = one/ten; ce[12][3] = three/ten; ce[0][4] = five; ce[1][4] = four; ce[2][4] = three; ce[3][4] = two; ce[4][4] = one/ten; ce[5][4] = four/ten; ce[6][4] = three/ten; ce[7][4] = five/hundred; ce[8][4] = four/hundred; ce[9][4] = three/hundred; ce[10][4] = one/ten; ce[11][4] = three/ten; ce[12][4] = two/ten; c1 = one + four/ten; c2 = four/ten; c3 = one/ten; c4 = one; c5 = one + four/ten; bt = sqrt_asm(five/ten); dnxm1 = one / (element_t)(grid_points[0]-1); dnym1 = one / (element_t)(grid_points[1]-1); dnzm1 = one / (element_t)(grid_points[2]-1); c1c2 = c1 * c2; c1c5 = c1 * c5; c3c4 = c3 * c4; c1345 = c1c5 * c3c4; conz1 = (one-c1c5); tx1 = one / (dnxm1 * dnxm1); tx2 = one / (two * dnxm1); tx3 = one / dnxm1; ty1 = one / (dnym1 * dnym1); ty2 = one / (two * dnym1); ty3 = one / dnym1; tz1 = one / (dnzm1 * dnzm1); tz2 = one / (two * dnzm1); tz3 = one / dnzm1; dx1 = three/four; dx2 = three/four; dx3 = three/four; dx4 = three/four; dx5 = three/four; dy1 = three/four; dy2 = three/four; dy3 = three/four; dy4 = three/four; dy5 = three/four; dz1 = one; dz2 = one; dz3 = one; dz4 = one; dz5 = one; dxmax = max(dx3, dx4); dymax = max(dy2, dy4); dzmax = max(dz2, dz3); dssp = one/four * max(dx1, max(dy1, dz1) ); c4dssp = four * dssp; c5dssp = five * dssp; dttx1 = dt*tx1; dttx2 = dt*tx2; dtty1 = dt*ty1; dtty2 = dt*ty2; dttz1 = dt*tz1; dttz2 = dt*tz2; c2dttx1 = two*dttx1; c2dtty1 = two*dtty1; c2dttz1 = two*dttz1; dtdssp = dt*dssp; comz1 = dtdssp; comz4 = four*dtdssp; comz5 = five*dtdssp; comz6 = six*dtdssp; c3c4tx3 = c3c4*tx3; c3c4ty3 = c3c4*ty3; c3c4tz3 = c3c4*tz3; dx1tx1 = dx1*tx1; dx2tx1 = dx2*tx1; dx3tx1 = dx3*tx1; dx4tx1 = dx4*tx1; dx5tx1 = dx5*tx1; dy1ty1 = dy1*ty1; dy2ty1 = dy2*ty1; dy3ty1 = dy3*ty1; dy4ty1 = dy4*ty1; dy5ty1 = dy5*ty1; dz1tz1 = dz1*tz1; dz2tz1 = dz2*tz1; dz3tz1 = dz3*tz1; dz4tz1 = dz4*tz1; dz5tz1 = dz5*tz1; c2iv = five/two; con43 = four/three; con16 = one/six; xxcon1 = c3c4tx3*con43*tx3; xxcon2 = c3c4tx3*tx3; xxcon3 = c3c4tx3*conz1*tx3; xxcon4 = c3c4tx3*con16*tx3; xxcon5 = c3c4tx3*c1c5*tx3; yycon1 = c3c4ty3*con43*ty3; yycon2 = c3c4ty3*ty3; yycon3 = c3c4ty3*conz1*ty3; yycon4 = c3c4ty3*con16*ty3; yycon5 = c3c4ty3*c1c5*ty3; zzcon1 = c3c4tz3*con43*tz3; zzcon2 = c3c4tz3*tz3; zzcon3 = c3c4tz3*conz1*tz3; zzcon4 = c3c4tz3*con16*tz3; zzcon5 = c3c4tz3*c1c5*tz3; } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void txinvr(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c block-diagonal matrix-vector multiplication --------------------------------------------------------------------*/ int i, j, k; element_t t1, t2, t3, ac, ru1, uu, vv, ww, r1, r2, r3, r4, r5, ac2inv; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { ru1 = rho_i[i][j][k]; uu = us[i][j][k]; vv = vs[i][j][k]; ww = ws[i][j][k]; ac = speed[i][j][k]; ac2inv = ainv[i][j][k]*ainv[i][j][k]; r1 = rhs[0][i][j][k]; r2 = rhs[1][i][j][k]; r3 = rhs[2][i][j][k]; r4 = rhs[3][i][j][k]; r5 = rhs[4][i][j][k]; t1 = c2 * ac2inv * ( qs[i][j][k]*r1 - uu*r2 - vv*r3 - ww*r4 + r5 ); t2 = bt * ru1 * ( uu * r1 - r2 ); t3 = ( bt * ru1 * ac ) * t1; rhs[0][i][j][k] = r1 - t1; rhs[1][i][j][k] = - ru1 * ( ww*r1 - r4 ); rhs[2][i][j][k] = ru1 * ( vv*r1 - r3 ); rhs[3][i][j][k] = - t2 + t3; rhs[4][i][j][k] = t2 + t3; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void tzetar(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c block-diagonal matrix-vector multiplication c-------------------------------------------------------------------*/ int i, j, k; element_t t1, t2, t3, ac, xvel, yvel, zvel, r1, r2, r3, r4, r5, btuz, acinv, ac2u, uzik1; #pragma omp for private(i,j,k,t1,t2,t3,ac,xvel,yvel,zvel,r1,r2,r3,r4,r5,btuz,ac2u,uzik1) for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { xvel = us[i][j][k]; yvel = vs[i][j][k]; zvel = ws[i][j][k]; ac = speed[i][j][k]; acinv = ainv[i][j][k]; ac2u = ac*ac; r1 = rhs[0][i][j][k]; r2 = rhs[1][i][j][k]; r3 = rhs[2][i][j][k]; r4 = rhs[3][i][j][k]; r5 = rhs[4][i][j][k]; uzik1 = u[0][i][j][k]; btuz = bt * uzik1; t1 = btuz*acinv * (r4 + r5); t2 = r3 + t1; t3 = btuz * (r4 - r5); rhs[0][i][j][k] = t2; rhs[1][i][j][k] = -uzik1*r2 + xvel*t2; rhs[2][i][j][k] = uzik1*r1 + yvel*t2; rhs[3][i][j][k] = zvel*t2 + t3; rhs[4][i][j][k] = uzik1*(-xvel*r2 + yvel*r1) + qs[i][j][k]*t2 + c2iv*ac2u*t1 + zvel*t3; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void verify(int no_time_steps, char *class, boolean *verified) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c verification routine --------------------------------------------------------------------*/ element_t xcrref[5],xceref[5],xcrdif[5],xcedif[5], epsilon, xce[5], xcr[5], dtref; int m; /*-------------------------------------------------------------------- c tolerance level --------------------------------------------------------------------*/ epsilon = c_epsilon; /*-------------------------------------------------------------------- c compute the error norm and the residual norm, and exit if not printing --------------------------------------------------------------------*/ error_norm(xce); compute_rhs(); rhs_norm(xcr); for (m = 0; m < 5; m++) { xcr[m] = xcr[m] / dt; } *class = 'U'; *verified = TRUE; for (m = 0; m < 5; m++) { xcrref[m] = one; xceref[m] = one; } /*-------------------------------------------------------------------- c reference data for 12X12X12 grids after 100 time steps, with DT = 1.50d-02 --------------------------------------------------------------------*/ if ( grid_points[0] == 12 && grid_points[1] == 12 && grid_points[2] == 12 && no_time_steps == 100) { *class = 'S'; dtref = three/(two * hundred); /*-------------------------------------------------------------------- c Reference values of RMS-norms of residual. --------------------------------------------------------------------*/ #ifdef WITH_POSIT_32 *((uint32_t*)&xcrref[0]) = 0x2b084b6a; *((uint32_t*)&xcrref[1]) = 0x254e00f8; *((uint32_t*)&xcrref[2]) = 0x2828069a; *((uint32_t*)&xcrref[3]) = 0x280e2073; *((uint32_t*)&xcrref[4]) = 0x2c75eef0; #else xcrref[0] = 2.7470315451339479e-02; xcrref[1] = 1.0360746705285417e-02; xcrref[2] = 1.6235745065095532e-02; xcrref[3] = 1.5840557224455615e-02; xcrref[4] = 3.4849040609362460e-02; #endif /*-------------------------------------------------------------------- c Reference values of RMS-norms of solution error. --------------------------------------------------------------------*/ #ifdef WITH_POSIT_32 *((uint32_t*)&xceref[0]) = 0x1193acf2; *((uint32_t*)&xceref[1]) = 0xf5bc5eb; *((uint32_t*)&xceref[2]) = 0x101e10a9; *((uint32_t*)&xceref[3]) = 0x10108186; *((uint32_t*)&xceref[4]) = 0x123d67f5; #else xceref[0] = 2.7289258557377227e-05; xceref[1] = 1.0364446640837285e-05; xceref[2] = 1.6154798287166471e-05; xceref[3] = 1.5750704994480102e-05; xceref[4] = 3.4177666183390531e-05; #endif } /* //-------------------------------------------------------------------- // reference data for 36X36X36 grids after 400 time steps, with DT = 1.5d-03 //-------------------------------------------------------------------- } else if (grid_points[0] == 36 && grid_points[1] == 36 && grid_points[2] == 36 && no_time_steps == 400) { *class = 'W'; dtref = 1.5e-3; //-------------------------------------------------------------------- // Reference values of RMS-norms of residual. //-------------------------------------------------------------------- xcrref[0] = 0.1893253733584e-02; xcrref[1] = 0.1717075447775e-03; xcrref[2] = 0.2778153350936e-03; xcrref[3] = 0.2887475409984e-03; xcrref[4] = 0.3143611161242e-02; //-------------------------------------------------------------------- // Reference values of RMS-norms of solution error. //-------------------------------------------------------------------- xceref[0] = 0.7542088599534e-04; xceref[1] = 0.6512852253086e-05; xceref[2] = 0.1049092285688e-04; xceref[3] = 0.1128838671535e-04; xceref[4] = 0.1212845639773e-03; //-------------------------------------------------------------------- // reference data for 64X64X64 grids after 400 time steps, with DT = 1.5d-03 //-------------------------------------------------------------------- } else if (grid_points[0] == 64 && grid_points[1] == 64 && grid_points[2] == 64 && no_time_steps == 400 ) { *class = 'A'; dtref = 1.5e-3; //-------------------------------------------------------------------- // Reference values of RMS-norms of residual. //-------------------------------------------------------------------- xcrref[0] = 2.4799822399300195; xcrref[1] = 1.1276337964368832; xcrref[2] = 1.5028977888770491; xcrref[3] = 1.4217816211695179; xcrref[4] = 2.1292113035138280; //-------------------------------------------------------------------- // Reference values of RMS-norms of solution error. //-------------------------------------------------------------------- xceref[0] = 1.0900140297820550e-04; xceref[1] = 3.7343951769282091e-05; xceref[2] = 5.0092785406541633e-05; xceref[3] = 4.7671093939528255e-05; xceref[4] = 1.3621613399213001e-04; //-------------------------------------------------------------------- // reference data for 102X102X102 grids after 400 time steps, // with DT = 1.0d-03 //-------------------------------------------------------------------- } else if (grid_points[0] == 102 && grid_points[1] == 102 && grid_points[2] == 102 && no_time_steps == 400) { *class = 'B'; dtref = 1.0e-3; //-------------------------------------------------------------------- // Reference values of RMS-norms of residual. //-------------------------------------------------------------------- xcrref[0] = 0.6903293579998e+02; xcrref[1] = 0.3095134488084e+02; xcrref[2] = 0.4103336647017e+02; xcrref[3] = 0.3864769009604e+02; xcrref[4] = 0.5643482272596e+02; //-------------------------------------------------------------------- // Reference values of RMS-norms of solution error. //-------------------------------------------------------------------- xceref[0] = 0.9810006190188e-02; xceref[1] = 0.1022827905670e-02; xceref[2] = 0.1720597911692e-02; xceref[3] = 0.1694479428231e-02; xceref[4] = 0.1847456263981e-01; //-------------------------------------------------------------------- // reference data for 162X162X162 grids after 400 time steps, // with DT = 0.67d-03 //-------------------------------------------------------------------- } else if (grid_points[0] == 162 && grid_points[1] == 162 && grid_points[2] == 162 && no_time_steps == 400) { *class = 'C'; dtref = 0.67e-3; //-------------------------------------------------------------------- // Reference values of RMS-norms of residual. //-------------------------------------------------------------------- xcrref[0] = 0.5881691581829e+03; xcrref[1] = 0.2454417603569e+03; xcrref[2] = 0.3293829191851e+03; xcrref[3] = 0.3081924971891e+03; xcrref[4] = 0.4597223799176e+03; //-------------------------------------------------------------------- // Reference values of RMS-norms of solution error. //-------------------------------------------------------------------- xceref[0] = 0.2598120500183e+00; xceref[1] = 0.2590888922315e-01; xceref[2] = 0.5132886416320e-01; xceref[3] = 0.4806073419454e-01; xceref[4] = 0.5483377491301e+00; } else { *verified = FALSE; } */ //-------------------------------------------------------------------- // verification test for residuals if gridsize is either 12X12X12 or // 64X64X64 or 102X102X102 or 162X162X162 //-------------------------------------------------------------------- /*-------------------------------------------------------------------- c Compute the difference of solution values and the known reference values. --------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { xcrdif[m] = my_fabs((xcr[m]-xcrref[m])/xcrref[m]) ; xcedif[m] = my_fabs((xce[m]-xceref[m])/xceref[m]); } /*-------------------------------------------------------------------- c Output the comparison of computed results to known cases. --------------------------------------------------------------------*/ if (*class != 'U') { #ifdef PFDEBUG printf(" Verification being performed for class %1c\n", *class); printf(" accuracy setting for epsilon = %20.13e\n", epsilon); #endif if (my_fabs(dt-dtref) > epsilon) { *verified = FALSE; *class = 'U'; #ifdef PFDEBUG printf(" DT does not match the reference value of %15.8e\n", dtref); #endif } } #ifdef PFDEBUG else { printf(" Unknown class\n"); } #endif #ifdef PFDEBUG if (*class != 'U') { printf(" Comparison of RMS-norms of residual\n"); } else { printf(" RMS-norms of residual\n"); } #endif for (m = 0; m < 5; m++) { if (*class == 'U') { #ifdef PFDEBUG printf(" %2d%20.13e\n", m, xcr[m]); #endif } else if (xcrdif[m] > epsilon) { *verified = FALSE; #ifdef PFDEBUG printf(" FAILURE: %2d%20.13e%20.13e%20.13e\n", m,xcr[m],xcrref[m],xcrdif[m]); #endif } else { #ifdef PFDEBUG printf(" %2d%20.13e%20.13e%20.13e\n", m,xcr[m],xcrref[m],xcrdif[m]); #endif } } #ifdef PFDEBUG if (*class != 'U') { printf(" Comparison of RMS-norms of solution error\n"); } else { printf(" RMS-norms of solution error\n"); } #endif for (m = 0; m < 5; m++) { if (*class == 'U') { #ifdef PFDEBUG printf(" %2d%20.13e\n", m, xce[m]); #endif } else if (xcedif[m] > epsilon) { *verified = FALSE; #ifdef PFDEBUG printf(" FAILURE: %2d%20.13e%20.13e%20.13e\n", m,xce[m],xceref[m],xcedif[m]); #endif } else { #ifdef PFDEBUG printf(" %2d%20.13e%20.13e%20.13e\n", m,xce[m],xceref[m],xcedif[m]); #endif } } #ifdef PFDEBUG if (*class == 'U') { printf(" No reference values provided\n"); printf(" No verification performed\n"); } else if (*verified) { printf(" Verification Successful\n"); } else { printf(" Verification failed\n"); } #endif } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void x_solve(void) { #pragma omp parallel { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c this function performs the solution of the approximate factorization c step in the x-direction for all five matrix components c simultaneously. The Thomas algorithm is employed to solve the c systems for the x-lines. Boundary conditions are non-periodic --------------------------------------------------------------------*/ int i, j, k, n, i1, i2, m; element_t fac1, fac2; /*-------------------------------------------------------------------- c FORWARD ELIMINATION --------------------------------------------------------------------*/ lhsx(); /*-------------------------------------------------------------------- c perform the Thomas algorithm; first, FORWARD ELIMINATION --------------------------------------------------------------------*/ n = 0; for (i = 0; i <= grid_points[0]-3; i++) { i1 = i + 1; i2 = i + 2; #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { fac1 = one/lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; } lhs[n+2][i1][j][k] = lhs[n+2][i1][j][k] - lhs[n+1][i1][j][k]*lhs[n+3][i][j][k]; lhs[n+3][i1][j][k] = lhs[n+3][i1][j][k] - lhs[n+1][i1][j][k]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i1][j][k] = rhs[m][i1][j][k] - lhs[n+1][i1][j][k]*rhs[m][i][j][k]; } lhs[n+1][i2][j][k] = lhs[n+1][i2][j][k] - lhs[n+0][i2][j][k]*lhs[n+3][i][j][k]; lhs[n+2][i2][j][k] = lhs[n+2][i2][j][k] - lhs[n+0][i2][j][k]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i2][j][k] = rhs[m][i2][j][k] - lhs[n+0][i2][j][k]*rhs[m][i][j][k]; } } } } /*-------------------------------------------------------------------- c The last two rows in this grid block are a bit different, c since they do not have two more rows available for the c elimination of off-diagonal entries --------------------------------------------------------------------*/ i = grid_points[0]-2; i1 = grid_points[0]-1; #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { fac1 = one/lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; } lhs[n+2][i1][j][k] = lhs[n+2][i1][j][k] - lhs[n+1][i1][j][k]*lhs[n+3][i][j][k]; lhs[n+3][i1][j][k] = lhs[n+3][i1][j][k] - lhs[n+1][i1][j][k]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i1][j][k] = rhs[m][i1][j][k] - lhs[n+1][i1][j][k]*rhs[m][i][j][k]; } /*-------------------------------------------------------------------- c scale the last row immediately --------------------------------------------------------------------*/ fac2 = one/lhs[n+2][i1][j][k]; for (m = 0; m < 3; m++) { rhs[m][i1][j][k] = fac2*rhs[m][i1][j][k]; } } } /*-------------------------------------------------------------------- c do the u+c and the u-c factors --------------------------------------------------------------------*/ for (m = 3; m < 5; m++) { n = (m-3+1)*5; for (i = 0; i <= grid_points[0]-3; i++) { i1 = i + 1; i2 = i + 2; #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { fac1 = one/lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; lhs[n+2][i1][j][k] = lhs[n+2][i1][j][k] - lhs[n+1][i1][j][k]*lhs[n+3][i][j][k]; lhs[n+3][i1][j][k] = lhs[n+3][i1][j][k] - lhs[n+1][i1][j][k]*lhs[n+4][i][j][k]; rhs[m][i1][j][k] = rhs[m][i1][j][k] - lhs[n+1][i1][j][k]*rhs[m][i][j][k]; lhs[n+1][i2][j][k] = lhs[n+1][i2][j][k] - lhs[n+0][i2][j][k]*lhs[n+3][i][j][k]; lhs[n+2][i2][j][k] = lhs[n+2][i2][j][k] - lhs[n+0][i2][j][k]*lhs[n+4][i][j][k]; rhs[m][i2][j][k] = rhs[m][i2][j][k] - lhs[n+0][i2][j][k]*rhs[m][i][j][k]; } } } /*-------------------------------------------------------------------- c And again the last two rows separately --------------------------------------------------------------------*/ i = grid_points[0]-2; i1 = grid_points[0]-1; #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { fac1 = one/lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; lhs[n+2][i1][j][k] = lhs[n+2][i1][j][k] - lhs[n+1][i1][j][k]*lhs[n+3][i][j][k]; lhs[n+3][i1][j][k] = lhs[n+3][i1][j][k] - lhs[n+1][i1][j][k]*lhs[n+4][i][j][k]; rhs[m][i1][j][k] = rhs[m][i1][j][k] - lhs[n+1][i1][j][k]*rhs[m][i][j][k]; /*-------------------------------------------------------------------- c Scale the last row immediately --------------------------------------------------------------------*/ fac2 = one/lhs[n+2][i1][j][k]; rhs[m][i1][j][k] = fac2*rhs[m][i1][j][k]; } } } /*-------------------------------------------------------------------- c BACKSUBSTITUTION --------------------------------------------------------------------*/ i = grid_points[0]-2; i1 = grid_points[0]-1; n = 0; for (m = 0; m < 3; m++) { #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i1][j][k]; } } } for (m = 3; m < 5; m++) { #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { n = (m-3+1)*5; rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i1][j][k]; } } } /*-------------------------------------------------------------------- c The first three factors --------------------------------------------------------------------*/ n = 0; for (i = grid_points[0]-3; i >= 0; i--) { i1 = i + 1; i2 = i + 2; #pragma omp for for (m = 0; m < 3; m++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i1][j][k] - lhs[n+4][i][j][k]*rhs[m][i2][j][k]; } } } } /*-------------------------------------------------------------------- c And the remaining two --------------------------------------------------------------------*/ for (m = 3; m < 5; m++) { n = (m-3+1)*5; for (i = grid_points[0]-3; i >= 0; i--) { i1 = i + 1; i2 = i + 2; #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i1][j][k] - lhs[n+4][i][j][k]*rhs[m][i2][j][k]; } } } } } /*-------------------------------------------------------------------- c Do the block-diagonal inversion --------------------------------------------------------------------*/ ninvr(); } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void y_solve(void) { #pragma omp parallel { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c this function performs the solution of the approximate factorization c step in the y-direction for all five matrix components c simultaneously. The Thomas algorithm is employed to solve the c systems for the y-lines. Boundary conditions are non-periodic --------------------------------------------------------------------*/ int i, j, k, n, j1, j2, m; element_t fac1, fac2; /*-------------------------------------------------------------------- c FORWARD ELIMINATION --------------------------------------------------------------------*/ lhsy(); n = 0; for (j = 0; j <= grid_points[1]-3; j++) { j1 = j + 1; j2 = j + 2; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { fac1 = one/lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; } lhs[n+2][i][j1][k] = lhs[n+2][i][j1][k] - lhs[n+1][i][j1][k]*lhs[n+3][i][j][k]; lhs[n+3][i][j1][k] = lhs[n+3][i][j1][k] - lhs[n+1][i][j1][k]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j1][k] = rhs[m][i][j1][k] - lhs[n+1][i][j1][k]*rhs[m][i][j][k]; } lhs[n+1][i][j2][k] = lhs[n+1][i][j2][k] - lhs[n+0][i][j2][k]*lhs[n+3][i][j][k]; lhs[n+2][i][j2][k] = lhs[n+2][i][j2][k] - lhs[n+0][i][j2][k]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j2][k] = rhs[m][i][j2][k] - lhs[n+0][i][j2][k]*rhs[m][i][j][k]; } } } } /*-------------------------------------------------------------------- c The last two rows in this grid block are a bit different, c since they do not have two more rows available for the c elimination of off-diagonal entries --------------------------------------------------------------------*/ j = grid_points[1]-2; j1 = grid_points[1]-1; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { fac1 = one/lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; } lhs[n+2][i][j1][k] = lhs[n+2][i][j1][k] - lhs[n+1][i][j1][k]*lhs[n+3][i][j][k]; lhs[n+3][i][j1][k] = lhs[n+3][i][j1][k] - lhs[n+1][i][j1][k]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j1][k] = rhs[m][i][j1][k] - lhs[n+1][i][j1][k]*rhs[m][i][j][k]; } /*-------------------------------------------------------------------- c scale the last row immediately --------------------------------------------------------------------*/ fac2 = one/lhs[n+2][i][j1][k]; for (m = 0; m < 3; m++) { rhs[m][i][j1][k] = fac2*rhs[m][i][j1][k]; } } } /*-------------------------------------------------------------------- c do the u+c and the u-c factors --------------------------------------------------------------------*/ for (m = 3; m < 5; m++) { n = (m-3+1)*5; for (j = 0; j <= grid_points[1]-3; j++) { j1 = j + 1; j2 = j + 2; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { fac1 = one/lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; lhs[n+2][i][j1][k] = lhs[n+2][i][j1][k] - lhs[n+1][i][j1][k]*lhs[n+3][i][j][k]; lhs[n+3][i][j1][k] = lhs[n+3][i][j1][k] - lhs[n+1][i][j1][k]*lhs[n+4][i][j][k]; rhs[m][i][j1][k] = rhs[m][i][j1][k] - lhs[n+1][i][j1][k]*rhs[m][i][j][k]; lhs[n+1][i][j2][k] = lhs[n+1][i][j2][k] - lhs[n+0][i][j2][k]*lhs[n+3][i][j][k]; lhs[n+2][i][j2][k] = lhs[n+2][i][j2][k] - lhs[n+0][i][j2][k]*lhs[n+4][i][j][k]; rhs[m][i][j2][k] = rhs[m][i][j2][k] - lhs[n+0][i][j2][k]*rhs[m][i][j][k]; } } } /*-------------------------------------------------------------------- c And again the last two rows separately --------------------------------------------------------------------*/ j = grid_points[1]-2; j1 = grid_points[1]-1; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { fac1 = one/lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; lhs[n+2][i][j1][k] = lhs[n+2][i][j1][k] - lhs[n+1][i][j1][k]*lhs[n+3][i][j][k]; lhs[n+3][i][j1][k] = lhs[n+3][i][j1][k] - lhs[n+1][i][j1][k]*lhs[n+4][i][j][k]; rhs[m][i][j1][k] = rhs[m][i][j1][k] - lhs[n+1][i][j1][k]*rhs[m][i][j][k]; /*-------------------------------------------------------------------- c Scale the last row immediately --------------------------------------------------------------------*/ fac2 = one/lhs[n+2][i][j1][k]; rhs[m][i][j1][k] = fac2*rhs[m][i][j1][k]; } } } /*-------------------------------------------------------------------- c BACKSUBSTITUTION --------------------------------------------------------------------*/ j = grid_points[1]-2; j1 = grid_points[1]-1; n = 0; for (m = 0; m < 3; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i][j1][k]; } } } for (m = 3; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { n = (m-3+1)*5; rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i][j1][k]; } } } /*-------------------------------------------------------------------- c The first three factors --------------------------------------------------------------------*/ n = 0; for (m = 0; m < 3; m++) { for (j = grid_points[1]-3; j >= 0; j--) { j1 = j + 1; j2 = j + 2; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i][j1][k] - lhs[n+4][i][j][k]*rhs[m][i][j2][k]; } } } } /*-------------------------------------------------------------------- c And the remaining two --------------------------------------------------------------------*/ for (m = 3; m < 5; m++) { n = (m-3+1)*5; for (j = grid_points[1]-3; j >= 0; j--) { j1 = j + 1; j2 = j1 + 1; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i][j1][k] - lhs[n+4][i][j][k]*rhs[m][i][j2][k]; } } } } } pinvr(); } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void z_solve(void) { #pragma omp parallel { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c this function performs the solution of the approximate factorization c step in the z-direction for all five matrix components c simultaneously. The Thomas algorithm is employed to solve the c systems for the z-lines. Boundary conditions are non-periodic c-------------------------------------------------------------------*/ int i, j, k, n, k1, k2, m; element_t fac1, fac2; /*-------------------------------------------------------------------- c FORWARD ELIMINATION c-------------------------------------------------------------------*/ lhsz(); n = 0; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 0; k <= grid_points[2]-3; k++) { k1 = k + 1; k2 = k + 2; fac1 = one/lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; } lhs[n+2][i][j][k1] = lhs[n+2][i][j][k1] - lhs[n+1][i][j][k1]*lhs[n+3][i][j][k]; lhs[n+3][i][j][k1] = lhs[n+3][i][j][k1] - lhs[n+1][i][j][k1]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k1] = rhs[m][i][j][k1] - lhs[n+1][i][j][k1]*rhs[m][i][j][k]; } lhs[n+1][i][j][k2] = lhs[n+1][i][j][k2] - lhs[n+0][i][j][k2]*lhs[n+3][i][j][k]; lhs[n+2][i][j][k2] = lhs[n+2][i][j][k2] - lhs[n+0][i][j][k2]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k2] = rhs[m][i][j][k2] - lhs[n+0][i][j][k2]*rhs[m][i][j][k]; } } } } /*-------------------------------------------------------------------- c The last two rows in this grid block are a bit different, c since they do not have two more rows available for the c elimination of off-diagonal entries c-------------------------------------------------------------------*/ k = grid_points[2]-2; k1 = grid_points[2]-1; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { fac1 = one/lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; } lhs[n+2][i][j][k1] = lhs[n+2][i][j][k1] - lhs[n+1][i][j][k1]*lhs[n+3][i][j][k]; lhs[n+3][i][j][k1] = lhs[n+3][i][j][k1] - lhs[n+1][i][j][k1]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k1] = rhs[m][i][j][k1] - lhs[n+1][i][j][k1]*rhs[m][i][j][k]; } /*-------------------------------------------------------------------- c scale the last row immediately c-------------------------------------------------------------------*/ fac2 = one/lhs[n+2][i][j][k1]; for (m = 0; m < 3; m++) { rhs[m][i][j][k1] = fac2*rhs[m][i][j][k1]; } } } /*-------------------------------------------------------------------- c do the u+c and the u-c factors c-------------------------------------------------------------------*/ for (m = 3; m < 5; m++) { n = (m-3+1)*5; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 0; k <= grid_points[2]-3; k++) { k1 = k + 1; k2 = k + 2; fac1 = one/lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; lhs[n+2][i][j][k1] = lhs[n+2][i][j][k1] - lhs[n+1][i][j][k1]*lhs[n+3][i][j][k]; lhs[n+3][i][j][k1] = lhs[n+3][i][j][k1] - lhs[n+1][i][j][k1]*lhs[n+4][i][j][k]; rhs[m][i][j][k1] = rhs[m][i][j][k1] - lhs[n+1][i][j][k1]*rhs[m][i][j][k]; lhs[n+1][i][j][k2] = lhs[n+1][i][j][k2] - lhs[n+0][i][j][k2]*lhs[n+3][i][j][k]; lhs[n+2][i][j][k2] = lhs[n+2][i][j][k2] - lhs[n+0][i][j][k2]*lhs[n+4][i][j][k]; rhs[m][i][j][k2] = rhs[m][i][j][k2] - lhs[n+0][i][j][k2]*rhs[m][i][j][k]; } } } /*-------------------------------------------------------------------- c And again the last two rows separately c-------------------------------------------------------------------*/ k = grid_points[2]-2; k1 = grid_points[2]-1; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { fac1 = one/lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; lhs[n+2][i][j][k1] = lhs[n+2][i][j][k1] - lhs[n+1][i][j][k1]*lhs[n+3][i][j][k]; lhs[n+3][i][j][k1] = lhs[n+3][i][j][k1] - lhs[n+1][i][j][k1]*lhs[n+4][i][j][k]; rhs[m][i][j][k1] = rhs[m][i][j][k1] - lhs[n+1][i][j][k1]*rhs[m][i][j][k]; /*-------------------------------------------------------------------- c Scale the last row immediately (some of this is overkill c if this is the last cell) c-------------------------------------------------------------------*/ fac2 = one/lhs[n+2][i][j][k1]; rhs[m][i][j][k1] = fac2*rhs[m][i][j][k1]; } } } /*-------------------------------------------------------------------- c BACKSUBSTITUTION c-------------------------------------------------------------------*/ k = grid_points[2]-2; k1 = grid_points[2]-1; n = 0; for (m = 0; m < 3; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i][j][k1]; } } } for (m = 3; m < 5; m++) { n = (m-3+1)*5; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i][j][k1]; } } } /*-------------------------------------------------------------------- c Whether or not this is the last processor, we always have c to complete the back-substitution c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c The first three factors c-------------------------------------------------------------------*/ n = 0; for (m = 0; m < 3; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = grid_points[2]-3; k >= 0; k--) { k1 = k + 1; k2 = k + 2; rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i][j][k1] - lhs[n+4][i][j][k]*rhs[m][i][j][k2]; } } } } /*-------------------------------------------------------------------- c And the remaining two c-------------------------------------------------------------------*/ for (m = 3; m < 5; m++) { n = (m-3+1)*5; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = grid_points[2]-3; k >= 0; k--) { k1 = k + 1; k2 = k + 2; rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i][j][k1] - lhs[n+4][i][j][k]*rhs[m][i][j][k2]; } } } } } tzetar(); }
sequence.c
#include "sequence.h" #include <omp.h> #include <stdlib.h> #include <string.h> #include "type.h" unsigned char* read_msa(const char* path, int* ncol, int* nrow) { FILE* f = fopen(path, "r"); char buf[SEQ_BUFFER_SIZE]; int nc; *nrow = 0; *ncol = 0; while (fgets(buf, SEQ_BUFFER_SIZE, f)) { (*nrow)++; nc = strlen(buf); *ncol = nc > *ncol ? nc : *ncol; } *ncol -= 1; unsigned char* out = (unsigned char*)malloc(sizeof(unsigned char) * (*ncol * *nrow)); rewind(f); for (int i = 0; i < *nrow; i++) { fgets(buf, SEQ_BUFFER_SIZE, f); for (int j = 0; j < *ncol; j++) { out[i * *ncol + j] = aatoi(buf[j]); } } fclose(f); return out; } unsigned char aatoi(unsigned char aa) { char id; switch (aa) { case '-': id = 0; break; case 'A': id = 1; break; case 'C': id = 2; break; case 'D': id = 3; break; case 'E': id = 4; break; case 'F': id = 5; break; case 'G': id = 6; break; case 'H': id = 7; break; case 'I': id = 8; break; case 'K': id = 9; break; case 'L': id = 10; break; case 'M': id = 11; break; case 'N': id = 12; break; case 'P': id = 13; break; case 'Q': id = 14; break; case 'R': id = 15; break; case 'S': id = 16; break; case 'T': id = 17; break; case 'V': id = 18; break; case 'W': id = 19; break; case 'Y': id = 20; break; default: id = 0; } return id; } double cal_seq_weight(double* w, unsigned char* msa, int ncol, int nrow, double seq_id) { for (int i = 0; i < nrow; i++) { // printf("%d\n", i); w[i] = 1.0; } int i, j; double sim; #pragma omp parallel for default(shared) private(j, sim) for (i = 0; i < nrow; i++) { for (j = i + 1; j < nrow; j++) { sim = cal_seq_sim(msa + i * ncol, msa + j * ncol, ncol); if (sim >= seq_id) { #pragma omp critical w[i] += 1.0; w[j] += 1.0; } } } double neff = 0.0; for (int i = 0; i < nrow; i++) { w[i] = 1.0 / w[i]; neff += w[i]; } printf(">msa ncol= %d nrow= %d neff= %.2f\n", ncol, nrow, neff); return neff; } double cal_seq_sim(unsigned char* seq1, unsigned char* seq2, int ncol) { double sum = 0.0; for (int i = 0; i < ncol; i++) { sum += seq1[i] == seq2[i]; } return sum / ncol; }
omp_parallel_copyin.c
// RUN: %libomp-compile-and-run // REQUIRES: !(abt && (clang || gcc)) #include <stdio.h> #include <stdlib.h> #include "omp_testsuite.h" static int sum1 = 789; #pragma omp threadprivate(sum1) int test_omp_parallel_copyin() { int sum, num_threads; int known_sum; sum = 0; sum1 = 7; num_threads = 0; #pragma omp parallel copyin(sum1) { /*printf("sum1=%d\n",sum1);*/ int i; #pragma omp for for (i = 1; i < 1000; i++) { sum1 = sum1 + i; } /*end of for*/ #pragma omp critical { sum = sum + sum1; num_threads++; } /*end of critical*/ } /* end of parallel*/ known_sum = (999 * 1000) / 2 + 7 * num_threads; return (known_sum == sum); } int main() { int i; int num_failed=0; for(i = 0; i < REPETITIONS; i++) { if(!test_omp_parallel_copyin()) { num_failed++; } } return num_failed; }
GB_unaryop__minv_uint16_int16.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__minv_uint16_int16 // op(A') function: GB_tran__minv_uint16_int16 // C type: uint16_t // A type: int16_t // cast: uint16_t cij = (uint16_t) aij // unaryop: cij = GB_IMINV_UNSIGNED (aij, 16) #define GB_ATYPE \ int16_t #define GB_CTYPE \ uint16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int16_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_IMINV_UNSIGNED (x, 16) ; // casting #define GB_CASTING(z, aij) \ uint16_t z = (uint16_t) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_UINT16 || GxB_NO_INT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_uint16_int16 ( uint16_t *Cx, // Cx and Ax may be aliased int16_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__minv_uint16_int16 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
threshold.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT H H RRRR EEEEE SSSSS H H OOO L DDDD % % T H H R R E SS H H O O L D D % % T HHHHH RRRR EEE SSS HHHHH O O L D D % % T H H R R E SS H H O O L D D % % T H H R R EEEEE SSSSS H H OOO LLLLL DDDD % % % % % % MagickCore Image Threshold 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/property.h" #include "MagickCore/blob.h" #include "MagickCore/cache-view.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/configure.h" #include "MagickCore/constitute.h" #include "MagickCore/decorate.h" #include "MagickCore/draw.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/effect.h" #include "MagickCore/fx.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/montage.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/quantize.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/random_.h" #include "MagickCore/random-private.h" #include "MagickCore/resize.h" #include "MagickCore/resource_.h" #include "MagickCore/segment.h" #include "MagickCore/shear.h" #include "MagickCore/signature-private.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/token.h" #include "MagickCore/transform.h" #include "MagickCore/xml-tree.h" #include "MagickCore/xml-tree-private.h" /* Define declarations. */ #define ThresholdsFilename "thresholds.xml" /* Typedef declarations. */ struct _ThresholdMap { char *map_id, *description; size_t width, height; ssize_t divisor, *levels; }; /* Static declarations. */ #if MAGICKCORE_ZERO_CONFIGURATION_SUPPORT #include "MagickCore/threshold-map.h" #else static const char *const BuiltinMap= "<?xml version=\"1.0\"?>" "<thresholds>" " <threshold map=\"threshold\" alias=\"1x1\">" " <description>Threshold 1x1 (non-dither)</description>" " <levels width=\"1\" height=\"1\" divisor=\"2\">" " 1" " </levels>" " </threshold>" " <threshold map=\"checks\" alias=\"2x1\">" " <description>Checkerboard 2x1 (dither)</description>" " <levels width=\"2\" height=\"2\" divisor=\"3\">" " 1 2" " 2 1" " </levels>" " </threshold>" "</thresholds>"; #endif /* Forward declarations. */ static ThresholdMap *GetThresholdMapFile(const char *,const char *,const char *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d a p t i v e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AdaptiveThresholdImage() selects an individual threshold for each pixel % based on the range of intensity values in its local neighborhood. This % allows for thresholding of an image whose global intensity histogram % doesn't contain distinctive peaks. % % The format of the AdaptiveThresholdImage method is: % % Image *AdaptiveThresholdImage(const Image *image,const size_t width, % const size_t height,const double bias,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width: the width of the local neighborhood. % % o height: the height of the local neighborhood. % % o bias: the mean bias. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AdaptiveThresholdImage(const Image *image, const size_t width,const size_t height,const double bias, ExceptionInfo *exception) { #define AdaptiveThresholdImageTag "AdaptiveThreshold/Image" CacheView *image_view, *threshold_view; Image *threshold_image; MagickBooleanType status; MagickOffsetType progress; MagickSizeType number_pixels; ssize_t y; /* Initialize threshold 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); threshold_image=CloneImage(image,0,0,MagickTrue,exception); if (threshold_image == (Image *) NULL) return((Image *) NULL); if ((width == 0) || (height == 0)) return(threshold_image); status=SetImageStorageClass(threshold_image,DirectClass,exception); if (status == MagickFalse) { threshold_image=DestroyImage(threshold_image); return((Image *) NULL); } /* Threshold image. */ status=MagickTrue; progress=0; number_pixels=(MagickSizeType) width*height; image_view=AcquireVirtualCacheView(image,exception); threshold_view=AcquireAuthenticCacheView(threshold_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,threshold_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double channel_bias[MaxPixelChannels], channel_sum[MaxPixelChannels]; register const Quantum *magick_restrict p, *magick_restrict pixels; register Quantum *magick_restrict q; register ssize_t i, x; ssize_t center, u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) (height/2L),image->columns+width,height,exception); q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+ GetPixelChannels(image)*(width/2); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } pixels=p; channel_bias[channel]=0.0; channel_sum[channel]=0.0; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { if (u == (ssize_t) (width-1)) channel_bias[channel]+=pixels[i]; channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image); } pixels+=GetPixelChannels(image)*image->columns; } } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double mean; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } channel_sum[channel]-=channel_bias[channel]; channel_bias[channel]=0.0; pixels=p; for (v=0; v < (ssize_t) height; v++) { channel_bias[channel]+=pixels[i]; pixels+=(width-1)*GetPixelChannels(image); channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image)*(image->columns+1); } mean=(double) (channel_sum[channel]/number_pixels+bias); SetPixelChannel(threshold_image,channel,(Quantum) ((double) p[center+i] <= mean ? 0 : QuantumRange),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(threshold_image); } if (SyncCacheViewAuthenticPixels(threshold_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,AdaptiveThresholdImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } threshold_image->type=image->type; threshold_view=DestroyCacheView(threshold_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) threshold_image=DestroyImage(threshold_image); return(threshold_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A u t o T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AutoThresholdImage() automatically performs image thresholding % dependent on which method you specify. % % The format of the AutoThresholdImage method is: % % MagickBooleanType AutoThresholdImage(Image *image, % const AutoThresholdMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image to auto-threshold. % % o method: choose from Kapur, OTSU, or Triangle. % % o exception: return any errors or warnings in this structure. % */ static double KapurThreshold(const Image *image,const double *histogram, ExceptionInfo *exception) { #define MaxIntensity 255 double *black_entropy, *cumulative_histogram, entropy, epsilon, maximum_entropy, *white_entropy; register ssize_t i, j; size_t threshold; /* Compute optimal threshold from the entopy of the histogram. */ cumulative_histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*cumulative_histogram)); black_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*black_entropy)); white_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*white_entropy)); if ((cumulative_histogram == (double *) NULL) || (black_entropy == (double *) NULL) || (white_entropy == (double *) NULL)) { if (white_entropy != (double *) NULL) white_entropy=(double *) RelinquishMagickMemory(white_entropy); if (black_entropy != (double *) NULL) black_entropy=(double *) RelinquishMagickMemory(black_entropy); if (cumulative_histogram != (double *) NULL) cumulative_histogram=(double *) RelinquishMagickMemory(cumulative_histogram); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(-1.0); } /* Entropy for black and white parts of the histogram. */ cumulative_histogram[0]=histogram[0]; for (i=1; i <= MaxIntensity; i++) cumulative_histogram[i]=cumulative_histogram[i-1]+histogram[i]; epsilon=MagickMinimumValue; for (j=0; j <= MaxIntensity; j++) { /* Black entropy. */ black_entropy[j]=0.0; if (cumulative_histogram[j] > epsilon) { entropy=0.0; for (i=0; i <= j; i++) if (histogram[i] > epsilon) entropy-=histogram[i]/cumulative_histogram[j]* log(histogram[i]/cumulative_histogram[j]); black_entropy[j]=entropy; } /* White entropy. */ white_entropy[j]=0.0; if ((1.0-cumulative_histogram[j]) > epsilon) { entropy=0.0; for (i=j+1; i <= MaxIntensity; i++) if (histogram[i] > epsilon) entropy-=histogram[i]/(1.0-cumulative_histogram[j])* log(histogram[i]/(1.0-cumulative_histogram[j])); white_entropy[j]=entropy; } } /* Find histogram bin with maximum entropy. */ maximum_entropy=black_entropy[0]+white_entropy[0]; threshold=0; for (j=1; j <= MaxIntensity; j++) if ((black_entropy[j]+white_entropy[j]) > maximum_entropy) { maximum_entropy=black_entropy[j]+white_entropy[j]; threshold=(size_t) j; } /* Free resources. */ white_entropy=(double *) RelinquishMagickMemory(white_entropy); black_entropy=(double *) RelinquishMagickMemory(black_entropy); cumulative_histogram=(double *) RelinquishMagickMemory(cumulative_histogram); return(100.0*threshold/MaxIntensity); } static double OTSUThreshold(const Image *image,const double *histogram, ExceptionInfo *exception) { double max_sigma, *myu, *omega, *probability, *sigma, threshold; register ssize_t i; /* Compute optimal threshold from maximization of inter-class variance. */ myu=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*myu)); omega=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*omega)); probability=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*probability)); sigma=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*sigma)); if ((myu == (double *) NULL) || (omega == (double *) NULL) || (probability == (double *) NULL) || (sigma == (double *) NULL)) { if (sigma != (double *) NULL) sigma=(double *) RelinquishMagickMemory(sigma); if (probability != (double *) NULL) probability=(double *) RelinquishMagickMemory(probability); if (omega != (double *) NULL) omega=(double *) RelinquishMagickMemory(omega); if (myu != (double *) NULL) myu=(double *) RelinquishMagickMemory(myu); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(-1.0); } /* Calculate probability density. */ for (i=0; i <= (ssize_t) MaxIntensity; i++) probability[i]=histogram[i]; /* Generate probability of graylevels and mean value for separation. */ omega[0]=probability[0]; myu[0]=0.0; for (i=1; i <= (ssize_t) MaxIntensity; i++) { omega[i]=omega[i-1]+probability[i]; myu[i]=myu[i-1]+i*probability[i]; } /* Sigma maximization: inter-class variance and compute optimal threshold. */ threshold=0; max_sigma=0.0; for (i=0; i < (ssize_t) MaxIntensity; i++) { sigma[i]=0.0; if ((omega[i] != 0.0) && (omega[i] != 1.0)) sigma[i]=pow(myu[MaxIntensity]*omega[i]-myu[i],2.0)/(omega[i]*(1.0- omega[i])); if (sigma[i] > max_sigma) { max_sigma=sigma[i]; threshold=(double) i; } } /* Free resources. */ myu=(double *) RelinquishMagickMemory(myu); omega=(double *) RelinquishMagickMemory(omega); probability=(double *) RelinquishMagickMemory(probability); sigma=(double *) RelinquishMagickMemory(sigma); return(100.0*threshold/MaxIntensity); } static double TriangleThreshold(const double *histogram) { double a, b, c, count, distance, inverse_ratio, max_distance, segment, x1, x2, y1, y2; register ssize_t i; ssize_t end, max, start, threshold; /* Compute optimal threshold with triangle algorithm. */ start=0; /* find start bin, first bin not zero count */ for (i=0; i <= (ssize_t) MaxIntensity; i++) if (histogram[i] > 0.0) { start=i; break; } end=0; /* find end bin, last bin not zero count */ for (i=(ssize_t) MaxIntensity; i >= 0; i--) if (histogram[i] > 0.0) { end=i; break; } max=0; /* find max bin, bin with largest count */ count=0.0; for (i=0; i <= (ssize_t) MaxIntensity; i++) if (histogram[i] > count) { max=i; count=histogram[i]; } /* Compute threshold at split point. */ x1=(double) max; y1=histogram[max]; x2=(double) end; if ((max-start) >= (end-max)) x2=(double) start; y2=0.0; a=y1-y2; b=x2-x1; c=(-1.0)*(a*x1+b*y1); inverse_ratio=1.0/sqrt(a*a+b*b+c*c); threshold=0; max_distance=0.0; if (x2 == (double) start) for (i=start; i < max; i++) { segment=inverse_ratio*(a*i+b*histogram[i]+c); distance=sqrt(segment*segment); if ((distance > max_distance) && (segment > 0.0)) { threshold=i; max_distance=distance; } } else for (i=end; i > max; i--) { segment=inverse_ratio*(a*i+b*histogram[i]+c); distance=sqrt(segment*segment); if ((distance > max_distance) && (segment < 0.0)) { threshold=i; max_distance=distance; } } return(100.0*threshold/MaxIntensity); } MagickExport MagickBooleanType AutoThresholdImage(Image *image, const AutoThresholdMethod method,ExceptionInfo *exception) { CacheView *image_view; char property[MagickPathExtent]; double gamma, *histogram, sum, threshold; MagickBooleanType status; register ssize_t i; ssize_t y; /* Form histogram. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*histogram)); if (histogram == (double *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=MagickTrue; (void) memset(histogram,0,(MaxIntensity+1UL)*sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { double intensity = GetPixelIntensity(image,p); histogram[ScaleQuantumToChar(ClampToQuantum(intensity))]++; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Normalize histogram. */ sum=0.0; for (i=0; i <= (ssize_t) MaxIntensity; i++) sum+=histogram[i]; gamma=PerceptibleReciprocal(sum); for (i=0; i <= (ssize_t) MaxIntensity; i++) histogram[i]=gamma*histogram[i]; /* Discover threshold from histogram. */ switch (method) { case KapurThresholdMethod: { threshold=KapurThreshold(image,histogram,exception); break; } case OTSUThresholdMethod: default: { threshold=OTSUThreshold(image,histogram,exception); break; } case TriangleThresholdMethod: { threshold=TriangleThreshold(histogram); break; } } histogram=(double *) RelinquishMagickMemory(histogram); if (threshold < 0.0) status=MagickFalse; if (status == MagickFalse) return(MagickFalse); /* Threshold image. */ (void) FormatLocaleString(property,MagickPathExtent,"%g%%",threshold); (void) SetImageProperty(image,"auto-threshold:threshold",property,exception); return(BilevelImage(image,QuantumRange*threshold/100.0,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B i l e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BilevelImage() changes the value of individual pixels based on the % intensity of each pixel channel. The result is a high-contrast image. % % More precisely each channel value of the image is 'thresholded' so that if % it is equal to or less than the given value it is set to zero, while any % value greater than that give is set to it maximum or QuantumRange. % % This function is what is used to implement the "-threshold" operator for % the command line API. % % If the default channel setting is given the image is thresholded using just % the gray 'intensity' of the image, rather than the individual channels. % % The format of the BilevelImage method is: % % MagickBooleanType BilevelImage(Image *image,const double threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: define the threshold values. % % o exception: return any errors or warnings in this structure. % % Aside: You can get the same results as operator using LevelImages() % with the 'threshold' value for both the black_point and the white_point. % */ MagickExport MagickBooleanType BilevelImage(Image *image,const double threshold, ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/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 (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) == MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); /* Bilevel threshold 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 Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double pixel; register ssize_t i; pixel=GetPixelIntensity(image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (image->channel_mask != DefaultChannels) pixel=(double) q[i]; q[i]=(Quantum) (pixel <= threshold ? 0 : QuantumRange); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B l a c k T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BlackThresholdImage() is like ThresholdImage() but forces all pixels below % the threshold into black while leaving all pixels at or above the threshold % unchanged. % % The format of the BlackThresholdImage method is: % % MagickBooleanType BlackThresholdImage(Image *image, % const char *threshold,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: define the threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType BlackThresholdImage(Image *image, const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; PixelInfo threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (thresholds == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); GetPixelInfo(image,&threshold); flags=ParseGeometry(thresholds,&geometry_info); threshold.red=geometry_info.rho; threshold.green=geometry_info.rho; threshold.blue=geometry_info.rho; threshold.black=geometry_info.rho; threshold.alpha=100.0; if ((flags & SigmaValue) != 0) threshold.green=geometry_info.sigma; if ((flags & XiValue) != 0) threshold.blue=geometry_info.xi; if ((flags & PsiValue) != 0) threshold.alpha=geometry_info.psi; if (threshold.colorspace == CMYKColorspace) { if ((flags & PsiValue) != 0) threshold.black=geometry_info.psi; if ((flags & ChiValue) != 0) threshold.alpha=geometry_info.chi; } if ((flags & PercentValue) != 0) { threshold.red*=(MagickRealType) (QuantumRange/100.0); threshold.green*=(MagickRealType) (QuantumRange/100.0); threshold.blue*=(MagickRealType) (QuantumRange/100.0); threshold.black*=(MagickRealType) (QuantumRange/100.0); threshold.alpha*=(MagickRealType) (QuantumRange/100.0); } /* White threshold 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 Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double pixel; register ssize_t i; pixel=GetPixelIntensity(image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (image->channel_mask != DefaultChannels) pixel=(double) q[i]; if (pixel < GetPixelInfoChannel(&threshold,channel)) q[i]=(Quantum) 0; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ThresholdImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l a m p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClampImage() set each pixel whose value is below zero to zero and any the % pixel whose value is above the quantum range to the quantum range (e.g. % 65535) otherwise the pixel value remains unchanged. % % The format of the ClampImage method is: % % MagickBooleanType ClampImage(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 ClampImage(Image *image,ExceptionInfo *exception) { #define ClampImageTag "Clamp/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 (image->storage_class == PseudoClass) { register ssize_t i; register PixelInfo *magick_restrict q; q=image->colormap; for (i=0; i < (ssize_t) image->colors; i++) { q->red=(double) ClampPixel(q->red); q->green=(double) ClampPixel(q->green); q->blue=(double) ClampPixel(q->blue); q->alpha=(double) ClampPixel(q->alpha); q++; } return(SyncImage(image,exception)); } /* Clamp 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 Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ClampPixel((MagickRealType) q[i]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ClampImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y T h r e s h o l d M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyThresholdMap() de-allocate the given ThresholdMap % % The format of the ListThresholdMaps method is: % % ThresholdMap *DestroyThresholdMap(Threshold *map) % % A description of each parameter follows. % % o map: Pointer to the Threshold map to destroy % */ MagickExport ThresholdMap *DestroyThresholdMap(ThresholdMap *map) { assert(map != (ThresholdMap *) NULL); if (map->map_id != (char *) NULL) map->map_id=DestroyString(map->map_id); if (map->description != (char *) NULL) map->description=DestroyString(map->description); if (map->levels != (ssize_t *) NULL) map->levels=(ssize_t *) RelinquishMagickMemory(map->levels); map=(ThresholdMap *) RelinquishMagickMemory(map); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t T h r e s h o l d M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetThresholdMap() loads and searches one or more threshold map files for the % map matching the given name or alias. % % The format of the GetThresholdMap method is: % % ThresholdMap *GetThresholdMap(const char *map_id, % ExceptionInfo *exception) % % A description of each parameter follows. % % o map_id: ID of the map to look for. % % o exception: return any errors or warnings in this structure. % */ MagickExport ThresholdMap *GetThresholdMap(const char *map_id, ExceptionInfo *exception) { ThresholdMap *map; map=GetThresholdMapFile(BuiltinMap,"built-in",map_id,exception); if (map != (ThresholdMap *) NULL) return(map); #if !MAGICKCORE_ZERO_CONFIGURATION_SUPPORT { const StringInfo *option; LinkedListInfo *options; options=GetConfigureOptions(ThresholdsFilename,exception); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { map=GetThresholdMapFile((const char *) GetStringInfoDatum(option), GetStringInfoPath(option),map_id,exception); if (map != (ThresholdMap *) NULL) break; option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyConfigureOptions(options); } #endif return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t T h r e s h o l d M a p F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetThresholdMapFile() look for a given threshold map name or alias in the % given XML file data, and return the allocated the map when found. % % The format of the ListThresholdMaps method is: % % ThresholdMap *GetThresholdMap(const char *xml,const char *filename, % const char *map_id,ExceptionInfo *exception) % % A description of each parameter follows. % % o xml: The threshold map list in XML format. % % o filename: The threshold map XML filename. % % o map_id: ID of the map to look for in XML list. % % o exception: return any errors or warnings in this structure. % */ static ThresholdMap *GetThresholdMapFile(const char *xml,const char *filename, const char *map_id,ExceptionInfo *exception) { char *p; const char *attribute, *content; double value; register ssize_t i; ThresholdMap *map; XMLTreeInfo *description, *levels, *threshold, *thresholds; (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading threshold map file \"%s\" ...",filename); map=(ThresholdMap *) NULL; thresholds=NewXMLTree(xml,exception); if (thresholds == (XMLTreeInfo *) NULL) return(map); for (threshold=GetXMLTreeChild(thresholds,"threshold"); threshold != (XMLTreeInfo *) NULL; threshold=GetNextXMLTreeTag(threshold)) { attribute=GetXMLTreeAttribute(threshold,"map"); if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0)) break; attribute=GetXMLTreeAttribute(threshold,"alias"); if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0)) break; } if (threshold == (XMLTreeInfo *) NULL) { thresholds=DestroyXMLTree(thresholds); return(map); } description=GetXMLTreeChild(threshold,"description"); if (description == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<description>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); return(map); } levels=GetXMLTreeChild(threshold,"levels"); if (levels == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<levels>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); return(map); } map=(ThresholdMap *) AcquireCriticalMemory(sizeof(*map)); map->map_id=(char *) NULL; map->description=(char *) NULL; map->levels=(ssize_t *) NULL; attribute=GetXMLTreeAttribute(threshold,"map"); if (attribute != (char *) NULL) map->map_id=ConstantString(attribute); content=GetXMLTreeContent(description); if (content != (char *) NULL) map->description=ConstantString(content); attribute=GetXMLTreeAttribute(levels,"width"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels width>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->width=StringToUnsignedLong(attribute); if (map->width == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels width>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } attribute=GetXMLTreeAttribute(levels,"height"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels height>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->height=StringToUnsignedLong(attribute); if (map->height == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels height>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } attribute=GetXMLTreeAttribute(levels,"divisor"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels divisor>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->divisor=(ssize_t) StringToLong(attribute); if (map->divisor < 2) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels divisor>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } content=GetXMLTreeContent(levels); if (content == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingContent", "<levels>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->levels=(ssize_t *) AcquireQuantumMemory((size_t) map->width,map->height* sizeof(*map->levels)); if (map->levels == (ssize_t *) NULL) ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap"); for (i=0; i < (ssize_t) (map->width*map->height); i++) { map->levels[i]=(ssize_t) strtol(content,&p,10); if (p == content) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> too few values, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } if ((map->levels[i] < 0) || (map->levels[i] > map->divisor)) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> %.20g out of range, map \"%s\"", (double) map->levels[i],map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } content=p; } value=(double) strtol(content,&p,10); (void) value; if (p != content) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> too many values, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } thresholds=DestroyXMLTree(thresholds); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + L i s t T h r e s h o l d M a p F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListThresholdMapFile() lists the threshold maps and their descriptions % in the given XML file data. % % The format of the ListThresholdMaps method is: % % MagickBooleanType ListThresholdMaps(FILE *file,const char*xml, % const char *filename,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to the output FILE. % % o xml: The threshold map list in XML format. % % o filename: The threshold map XML filename. % % o exception: return any errors or warnings in this structure. % */ MagickBooleanType ListThresholdMapFile(FILE *file,const char *xml, const char *filename,ExceptionInfo *exception) { const char *alias, *content, *map; XMLTreeInfo *description, *threshold, *thresholds; assert( xml != (char *) NULL ); assert( file != (FILE *) NULL ); (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading threshold map file \"%s\" ...",filename); thresholds=NewXMLTree(xml,exception); if ( thresholds == (XMLTreeInfo *) NULL ) return(MagickFalse); (void) FormatLocaleFile(file,"%-16s %-12s %s\n","Map","Alias","Description"); (void) FormatLocaleFile(file, "----------------------------------------------------\n"); threshold=GetXMLTreeChild(thresholds,"threshold"); for ( ; threshold != (XMLTreeInfo *) NULL; threshold=GetNextXMLTreeTag(threshold)) { map=GetXMLTreeAttribute(threshold,"map"); if (map == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<map>"); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } alias=GetXMLTreeAttribute(threshold,"alias"); description=GetXMLTreeChild(threshold,"description"); if (description == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<description>, map \"%s\"",map); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } content=GetXMLTreeContent(description); if (content == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingContent", "<description>, map \"%s\"", map); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } (void) FormatLocaleFile(file,"%-16s %-12s %s\n",map,alias ? alias : "", content); } thresholds=DestroyXMLTree(thresholds); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i s t T h r e s h o l d M a p s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListThresholdMaps() lists the threshold maps and their descriptions % as defined by "threshold.xml" to a file. % % The format of the ListThresholdMaps method is: % % MagickBooleanType ListThresholdMaps(FILE *file,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to the output FILE. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ListThresholdMaps(FILE *file, ExceptionInfo *exception) { const StringInfo *option; LinkedListInfo *options; MagickStatusType status; status=MagickTrue; if (file == (FILE *) NULL) file=stdout; options=GetConfigureOptions(ThresholdsFilename,exception); (void) FormatLocaleFile(file, "\n Threshold Maps for Ordered Dither Operations\n"); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { (void) FormatLocaleFile(file,"\nPath: %s\n\n",GetStringInfoPath(option)); status&=ListThresholdMapFile(file,(const char *) GetStringInfoDatum(option), GetStringInfoPath(option),exception); option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyConfigureOptions(options); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O r d e r e d D i t h e r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OrderedDitherImage() will perform a ordered dither based on a number % of pre-defined dithering threshold maps, but over multiple intensity % levels, which can be different for different channels, according to the % input argument. % % The format of the OrderedDitherImage method is: % % MagickBooleanType OrderedDitherImage(Image *image, % const char *threshold_map,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold_map: A string containing the name of the threshold dither % map to use, followed by zero or more numbers representing the number % of color levels to dither between. % % Any level number less than 2 will be equivalent to 2, and means only % binary dithering will be applied to each color channel. % % No numbers also means a 2 level (bitmap) dither will be applied to all % channels, while a single number is the number of levels applied to each % channel in sequence. More numbers will be applied in turn to each of % the color channels. % % For example: "o3x3,6" will generate a 6 level posterization of the % image with an ordered 3x3 diffused pixel dither being applied between % each level. While checker,8,8,4 will produce a 332 colormaped image % with only a single checkerboard hash pattern (50% grey) between each % color level, to basically double the number of color levels with % a bare minimim of dithering. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType OrderedDitherImage(Image *image, const char *threshold_map,ExceptionInfo *exception) { #define DitherImageTag "Dither/Image" CacheView *image_view; char token[MagickPathExtent]; const char *p; double levels[CompositePixelChannel]; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; ThresholdMap *map; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (threshold_map == (const char *) NULL) return(MagickTrue); p=(char *) threshold_map; while (((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) && (*p != '\0')) p++; threshold_map=p; while (((isspace((int) ((unsigned char) *p)) == 0) && (*p != ',')) && (*p != '\0')) { if ((p-threshold_map) >= (MagickPathExtent-1)) break; token[p-threshold_map]=(*p); p++; } token[p-threshold_map]='\0'; map=GetThresholdMap(token,exception); if (map == (ThresholdMap *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument","%s : '%s'","ordered-dither",threshold_map); return(MagickFalse); } for (i=0; i < MaxPixelChannels; i++) levels[i]=2.0; p=strchr((char *) threshold_map,','); if ((p != (char *) NULL) && (isdigit((int) ((unsigned char) *(++p))) != 0)) { (void) GetNextToken(p,&p,MagickPathExtent,token); for (i=0; (i < MaxPixelChannels); i++) levels[i]=StringToDouble(token,(char **) NULL); for (i=0; (*p != '\0') && (i < MaxPixelChannels); i++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); levels[i]=StringToDouble(token,(char **) NULL); } } for (i=0; i < MaxPixelChannels; i++) if (fabs(levels[i]) >= 1) levels[i]-=1.0; if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); 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 Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; ssize_t n; n=0; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { ssize_t level, threshold; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (fabs(levels[n]) < MagickEpsilon) { n++; continue; } threshold=(ssize_t) (QuantumScale*q[i]*(levels[n]*(map->divisor-1)+1)); level=threshold/(map->divisor-1); threshold-=level*(map->divisor-1); q[i]=ClampToQuantum((double) (level+(threshold >= map->levels[(x % map->width)+map->width*(y % map->height)]))* QuantumRange/levels[n]); n++; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,DitherImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); map=DestroyThresholdMap(map); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P e r c e p t i b l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PerceptibleImage() set each pixel whose value is less than |epsilon| to % epsilon or -epsilon (whichever is closer) otherwise the pixel value remains % unchanged. % % The format of the PerceptibleImage method is: % % MagickBooleanType PerceptibleImage(Image *image,const double epsilon, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o epsilon: the epsilon threshold (e.g. 1.0e-9). % % o exception: return any errors or warnings in this structure. % */ static inline Quantum PerceptibleThreshold(const Quantum quantum, const double epsilon) { double sign; sign=(double) quantum < 0.0 ? -1.0 : 1.0; if ((sign*quantum) >= epsilon) return(quantum); return((Quantum) (sign*epsilon)); } MagickExport MagickBooleanType PerceptibleImage(Image *image, const double epsilon,ExceptionInfo *exception) { #define PerceptibleImageTag "Perceptible/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 (image->storage_class == PseudoClass) { register ssize_t i; register PixelInfo *magick_restrict q; q=image->colormap; for (i=0; i < (ssize_t) image->colors; i++) { q->red=(double) PerceptibleThreshold(ClampToQuantum(q->red), epsilon); q->green=(double) PerceptibleThreshold(ClampToQuantum(q->green), epsilon); q->blue=(double) PerceptibleThreshold(ClampToQuantum(q->blue), epsilon); q->alpha=(double) PerceptibleThreshold(ClampToQuantum(q->alpha), epsilon); q++; } return(SyncImage(image,exception)); } /* Perceptible 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 Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=PerceptibleThreshold(q[i],epsilon); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,PerceptibleImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R a n d o m T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RandomThresholdImage() changes the value of individual pixels based on the % intensity of each pixel compared to a random threshold. The result is a % low-contrast, two color image. % % The format of the RandomThresholdImage method is: % % MagickBooleanType RandomThresholdImage(Image *image, % const char *thresholds,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o low,high: Specify the high and low thresholds. These values range from % 0 to QuantumRange. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType RandomThresholdImage(Image *image, const double min_threshold, const double max_threshold,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; PixelInfo threshold; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); GetPixelInfo(image,&threshold); /* Random threshold image. */ status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); image_view=AcquireAuthenticCacheView(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,image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register Quantum *magick_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++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double threshold; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if ((double) q[i] < min_threshold) threshold=min_threshold; else if ((double) q[i] > max_threshold) threshold=max_threshold; else threshold=(double) (QuantumRange* GetPseudoRandomValue(random_info[id])); q[i]=(double) q[i] <= threshold ? 0 : QuantumRange; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ThresholdImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R a n g e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RangeThresholdImage() applies soft and hard thresholding. % % The format of the RangeThresholdImage method is: % % MagickBooleanType RangeThresholdImage(Image *image, % const double low_black,const double low_white,const double high_white, % const double high_black,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o low_black: Define the minimum black threshold value. % % o low_white: Define the minimum white threshold value. % % o high_white: Define the maximum white threshold value. % % o high_black: Define the maximum black threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType RangeThresholdImage(Image *image, const double low_black,const double low_white,const double high_white, const double high_black,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/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 (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); /* Range threshold 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 Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double pixel; register ssize_t i; pixel=GetPixelIntensity(image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (image->channel_mask != DefaultChannels) pixel=(double) q[i]; if (pixel < low_black) q[i]=0; else if ((pixel >= low_black) && (pixel < low_white)) q[i]=ClampToQuantum(QuantumRange* PerceptibleReciprocal(low_white-low_black)*(pixel-low_black)); else if ((pixel >= low_white) && (pixel <= high_white)) q[i]=QuantumRange; else if ((pixel > high_white) && (pixel <= high_black)) q[i]=ClampToQuantum(QuantumRange*PerceptibleReciprocal( high_black-high_white)*(high_black-pixel)); else if (pixel > high_black) q[i]=0; else q[i]=0; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ThresholdImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W h i t e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WhiteThresholdImage() is like ThresholdImage() but forces all pixels above % the threshold into white while leaving all pixels at or below the threshold % unchanged. % % The format of the WhiteThresholdImage method is: % % MagickBooleanType WhiteThresholdImage(Image *image, % const char *threshold,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: Define the threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType WhiteThresholdImage(Image *image, const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; PixelInfo threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (thresholds == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); GetPixelInfo(image,&threshold); flags=ParseGeometry(thresholds,&geometry_info); threshold.red=geometry_info.rho; threshold.green=geometry_info.rho; threshold.blue=geometry_info.rho; threshold.black=geometry_info.rho; threshold.alpha=100.0; if ((flags & SigmaValue) != 0) threshold.green=geometry_info.sigma; if ((flags & XiValue) != 0) threshold.blue=geometry_info.xi; if ((flags & PsiValue) != 0) threshold.alpha=geometry_info.psi; if (threshold.colorspace == CMYKColorspace) { if ((flags & PsiValue) != 0) threshold.black=geometry_info.psi; if ((flags & ChiValue) != 0) threshold.alpha=geometry_info.chi; } if ((flags & PercentValue) != 0) { threshold.red*=(MagickRealType) (QuantumRange/100.0); threshold.green*=(MagickRealType) (QuantumRange/100.0); threshold.blue*=(MagickRealType) (QuantumRange/100.0); threshold.black*=(MagickRealType) (QuantumRange/100.0); threshold.alpha*=(MagickRealType) (QuantumRange/100.0); } /* White threshold 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 Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double pixel; register ssize_t i; pixel=GetPixelIntensity(image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (image->channel_mask != DefaultChannels) pixel=(double) q[i]; if (pixel > GetPixelInfoChannel(&threshold,channel)) q[i]=QuantumRange; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); }
nr_numint.c
/* Copyright 2014-2018 The PySCF Developers. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. * * Author: Qiming Sun <osirpt.sun@gmail.com> */ #include <stdlib.h> #include <string.h> #include <assert.h> #include "config.h" #include "gto/grid_ao_drv.h" #include "np_helper/np_helper.h" #include "vhf/fblas.h" #define BOXSIZE 56 int VXCao_empty_blocks(char *empty, unsigned char *non0table, int *shls_slice, int *ao_loc) { if (non0table == NULL || shls_slice == NULL || ao_loc == NULL) { return 0; } const int sh0 = shls_slice[0]; const int sh1 = shls_slice[1]; int bas_id; int box_id = 0; int bound = BOXSIZE; int has0 = 0; empty[box_id] = 1; for (bas_id = sh0; bas_id < sh1; bas_id++) { empty[box_id] &= !non0table[bas_id]; if (ao_loc[bas_id] == bound) { has0 |= empty[box_id]; box_id++; bound += BOXSIZE; empty[box_id] = 1; } else if (ao_loc[bas_id] > bound) { has0 |= empty[box_id]; box_id++; bound += BOXSIZE; empty[box_id] = !non0table[bas_id]; } } return has0; } static void dot_ao_dm(double *vm, double *ao, double *dm, int nao, int nocc, int ngrids, int bgrids, unsigned char *non0table, int *shls_slice, int *ao_loc) { int nbox = (nao+BOXSIZE-1) / BOXSIZE; char empty[nbox]; int has0 = VXCao_empty_blocks(empty, non0table, shls_slice, ao_loc); const char TRANS_T = 'T'; const char TRANS_N = 'N'; const double D1 = 1; double beta = 0; if (has0) { int box_id, blen, i, j; size_t b0; for (box_id = 0; box_id < nbox; box_id++) { if (!empty[box_id]) { b0 = box_id * BOXSIZE; blen = MIN(nao-b0, BOXSIZE); dgemm_(&TRANS_N, &TRANS_T, &bgrids, &nocc, &blen, &D1, ao+b0*ngrids, &ngrids, dm+b0*nocc, &nocc, &beta, vm, &ngrids); beta = 1.0; } } if (beta == 0) { // all empty for (i = 0; i < nocc; i++) { for (j = 0; j < bgrids; j++) { vm[i*ngrids+j] = 0; } } } } else { dgemm_(&TRANS_N, &TRANS_T, &bgrids, &nocc, &nao, &D1, ao, &ngrids, dm, &nocc, &beta, vm, &ngrids); } } /* vm[nocc,ngrids] = ao[i,ngrids] * dm[i,nocc] */ void VXCdot_ao_dm(double *vm, double *ao, double *dm, int nao, int nocc, int ngrids, int nbas, unsigned char *non0table, int *shls_slice, int *ao_loc) { const int nblk = (ngrids+BLKSIZE-1) / BLKSIZE; #pragma omp parallel default(none) \ shared(vm, ao, dm, nao, nocc, ngrids, nbas, \ non0table, shls_slice, ao_loc) { int ip, ib; #pragma omp for nowait schedule(static) for (ib = 0; ib < nblk; ib++) { ip = ib * BLKSIZE; dot_ao_dm(vm+ip, ao+ip, dm, nao, nocc, ngrids, MIN(ngrids-ip, BLKSIZE), non0table+ib*nbas, shls_slice, ao_loc); } } } /* vv[n,m] = ao1[n,ngrids] * ao2[m,ngrids] */ static void dot_ao_ao(double *vv, double *ao1, double *ao2, int nao, int ngrids, int bgrids, int hermi, unsigned char *non0table, int *shls_slice, int *ao_loc) { int nbox = (nao+BOXSIZE-1) / BOXSIZE; char empty[nbox]; int has0 = VXCao_empty_blocks(empty, non0table, shls_slice, ao_loc); const char TRANS_T = 'T'; const char TRANS_N = 'N'; const double D1 = 1; if (has0) { int ib, jb, leni, lenj; int j1 = nbox; size_t b0i, b0j; for (ib = 0; ib < nbox; ib++) { if (!empty[ib]) { b0i = ib * BOXSIZE; leni = MIN(nao-b0i, BOXSIZE); if (hermi) { j1 = ib + 1; } for (jb = 0; jb < j1; jb++) { if (!empty[jb]) { b0j = jb * BOXSIZE; lenj = MIN(nao-b0j, BOXSIZE); dgemm_(&TRANS_T, &TRANS_N, &lenj, &leni, &bgrids, &D1, ao2+b0j*ngrids, &ngrids, ao1+b0i*ngrids, &ngrids, &D1, vv+b0i*nao+b0j, &nao); } } } } } else { dgemm_(&TRANS_T, &TRANS_N, &nao, &nao, &bgrids, &D1, ao2, &ngrids, ao1, &ngrids, &D1, vv, &nao); } } /* vv[nao,nao] = ao1[i,nao] * ao2[i,nao] */ void VXCdot_ao_ao(double *vv, double *ao1, double *ao2, int nao, int ngrids, int nbas, int hermi, unsigned char *non0table, int *shls_slice, int *ao_loc) { const int nblk = (ngrids+BLKSIZE-1) / BLKSIZE; memset(vv, 0, sizeof(double) * nao * nao); #pragma omp parallel default(none) \ shared(vv, ao1, ao2, nao, ngrids, nbas, hermi, \ non0table, shls_slice, ao_loc) { int ip, ib; double *v_priv = calloc(nao*nao+2, sizeof(double)); #pragma omp for nowait schedule(static) for (ib = 0; ib < nblk; ib++) { ip = ib * BLKSIZE; dot_ao_ao(v_priv, ao1+ip, ao2+ip, nao, ngrids, MIN(ngrids-ip, BLKSIZE), hermi, non0table+ib*nbas, shls_slice, ao_loc); } #pragma omp critical { for (ip = 0; ip < nao*nao; ip++) { vv[ip] += v_priv[ip]; } } free(v_priv); } if (hermi != 0) { NPdsymm_triu(nao, vv, hermi); } } // 'nip,np->ip' void VXC_dscale_ao(double *aow, double *ao, double *wv, int comp, int nao, int ngrids) { #pragma omp parallel default(none) \ shared(aow, ao, wv, comp, nao, ngrids) { size_t Ngrids = ngrids; size_t ao_size = nao * Ngrids; int i, j, ic; double *pao = ao; #pragma omp for schedule(static) for (i = 0; i < nao; i++) { pao = ao + i * Ngrids; for (j = 0; j < Ngrids; j++) { aow[i*Ngrids+j] = pao[j] * wv[j]; } for (ic = 1; ic < comp; ic++) { for (j = 0; j < Ngrids; j++) { aow[i*Ngrids+j] += pao[ic*ao_size+j] * wv[ic*Ngrids+j]; } } } } } // 'ip,ip->p' void VXC_dcontract_rho(double *rho, double *bra, double *ket, int nao, int ngrids) { #pragma omp parallel default(none) \ shared(rho, bra, ket, nao, ngrids) { size_t Ngrids = ngrids; int nthread = omp_get_num_threads(); int blksize = MAX((Ngrids+nthread-1) / nthread, 1); int ib, b0, b1, i, j; #pragma omp for for (ib = 0; ib < nthread; ib++) { b0 = ib * blksize; b1 = MIN(b0 + blksize, ngrids); for (j = b0; j < b1; j++) { rho[j] = bra[j] * ket[j]; } for (i = 1; i < nao; i++) { for (j = b0; j < b1; j++) { rho[j] += bra[i*Ngrids+j] * ket[i*Ngrids+j]; } } } } }
gdal_pm_eto.c
#include<stdio.h> #include<omp.h> #include<math.h> #include "gdal.h" #include "pm_eto.h" void usage() { printf( "-----------------------------------------\n"); printf( "--Modis Processing chain--OpenMP code----\n"); printf( "-----------------------------------------\n"); printf( "./pm_eto inLst inDem inRnet\n"); printf( "\toutPm_eto\n"); printf( "-----------------------------------------\n"); printf( "\trh u\n"); return; } int main( int argc, char *argv[] ) { if( argc < 6 ) { usage(); return 1; } char *inB1 = argv[1]; //LST char *inB2 = argv[2]; //DEM char *inB3 = argv[3]; //RNET char *pm_etoF = argv[4]; double rh = atof(argv[5]); // Relative Humidity (-) double u = atof(argv[6]); // wind speed (m/s) at z height // printf("LST=%s DEM=%s RNET=%s Out=%s\n",inB1,inB2,inB3,pm_etoF); // printf("u=%f rh=%f\n",u,rh); GDALAllRegister(); GDALDatasetH hD1 = GDALOpen(inB1,GA_ReadOnly);//LST GDALDatasetH hD2 = GDALOpen(inB2,GA_ReadOnly);//DEM GDALDatasetH hD3 = GDALOpen(inB3,GA_ReadOnly);//RNET if(hD1==NULL||hD2==NULL||hD3==NULL){ printf("One or more input files "); printf("could not be loaded\n"); exit(1); } char **options = NULL; options = CSLSetNameValue( options, "TILED", "YES" ); options = CSLSetNameValue( options, "COMPRESS", "DEFLATE" ); options = CSLSetNameValue( options, "PREDICTOR", "2" ); GDALDriverH hDr2 = GDALGetDatasetDriver(hD2); GDALDatasetH hDOut = GDALCreateCopy( hDr2, pm_etoF,hD2,FALSE,options,NULL,NULL); GDALRasterBandH hBOut = GDALGetRasterBand(hDOut,1); GDALRasterBandH hB1 = GDALGetRasterBand(hD1,1);//LST GDALRasterBandH hB2 = GDALGetRasterBand(hD2,1);//DEM GDALRasterBandH hB3 = GDALGetRasterBand(hD3,1);//RNET int nX = GDALGetRasterBandXSize(hB1); int nY = GDALGetRasterBandYSize(hB1); int N=nX*nY; float *mat1 = (float *) malloc(sizeof(float)*N); float *mat2 = (float *) malloc(sizeof(float)*N); float *mat3 = (float *) malloc(sizeof(float)*N); float *matOut = (float *) malloc(sizeof(float)*N); float pmeto; int rowcol; //LST GDALRasterIO(hB1,GF_Read,0,0,nX,nY,mat1,nX,nY,GDT_Float32,0,0); //DEM GDALRasterIO(hB2,GF_Read,0,0,nX,nY,mat2,nX,nY,GDT_Float32,0,0); //RNET GDALRasterIO(hB3,GF_Read,0,0,nX,nY,mat3,nX,nY,GDT_Float32,0,0); #pragma omp parallel for default(none) \ private(rowcol, pmeto)\ shared(N, rh, u, mat1, mat2, mat3, matOut ) for(rowcol=0;rowcol<N;rowcol++){ if(mat1[rowcol]==-28768||mat1[rowcol]*0.02<250.0||mat1[rowcol]*0.02>360.0) matOut[rowcol] = -28768; else { /* t0dem = mat3[rowcol]*0.02-0.00625*mat5[rowcol]; tadem = t0dem-(a[7]*t0dem+b[7]);*/ //ETinst pmeto = EToPM( mat1[rowcol]*0.02, mat2[rowcol], u, mat3[rowcol]*0.0864, rh, 0.6); matOut[rowcol] = pmeto; } } #pragma omp barrier GDALRasterIO(hBOut,GF_Write,0,0,nX,nY,matOut,nX,nY,GDT_Float32,0,0); if(mat1 != NULL) free(mat1); if(mat2 != NULL) free(mat2); if(mat3 != NULL) free(mat3); if(matOut != NULL) free(matOut); GDALClose(hD1); GDALClose(hD2); GDALClose(hD3); GDALClose(hDOut); return(EXIT_SUCCESS); }
firstprivate-orig-no.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // use of firstprivate() void foo(int * a, int n, int g) { int i; #pragma omp parallel for firstprivate (g) for (i=0;i<n;i++) { a[i] = a[i]+g; } } int a[100]; int main() { foo(a, 100, 7); return 0; }
GB_binop__lxor_fp32.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__lxor_fp32) // A.*B function (eWiseMult): GB (_AemultB_08__lxor_fp32) // A.*B function (eWiseMult): GB (_AemultB_02__lxor_fp32) // A.*B function (eWiseMult): GB (_AemultB_04__lxor_fp32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__lxor_fp32) // A*D function (colscale): GB (_AxD__lxor_fp32) // D*A function (rowscale): GB (_DxB__lxor_fp32) // C+=B function (dense accum): GB (_Cdense_accumB__lxor_fp32) // C+=b function (dense accum): GB (_Cdense_accumb__lxor_fp32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__lxor_fp32) // C=scalar+B GB (_bind1st__lxor_fp32) // C=scalar+B' GB (_bind1st_tran__lxor_fp32) // C=A+scalar GB (_bind2nd__lxor_fp32) // C=A'+scalar GB (_bind2nd_tran__lxor_fp32) // C type: float // A type: float // A pattern? 0 // B type: float // B pattern? 0 // BinaryOp: cij = ((aij != 0) != (bij != 0)) #define GB_ATYPE \ float #define GB_BTYPE \ float #define GB_CTYPE \ float // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ float 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) \ float 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) \ float 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 != 0) != (y != 0)) ; // 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_LXOR || GxB_NO_FP32 || GxB_NO_LXOR_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 //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__lxor_fp32) ( 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__lxor_fp32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__lxor_fp32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type float float bwork = (*((float *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__lxor_fp32) ( 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 float *restrict Cx = (float *) 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__lxor_fp32) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float *restrict Cx = (float *) 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__lxor_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 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) ; float alpha_scalar ; float beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((float *) alpha_scalar_in)) ; beta_scalar = (*((float *) 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__lxor_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_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__lxor_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_04__lxor_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_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__lxor_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__lxor_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 bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float *Cx = (float *) Cx_output ; float x = (*((float *) x_input)) ; float *Bx = (float *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; float bij = GBX (Bx, p, false) ; Cx [p] = ((x != 0) != (bij != 0)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__lxor_fp32) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; float *Cx = (float *) Cx_output ; float *Ax = (float *) Ax_input ; float y = (*((float *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; float aij = GBX (Ax, p, false) ; Cx [p] = ((aij != 0) != (y != 0)) ; } 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 = GBX (Ax, pA, false) ; \ Cx [pC] = ((x != 0) != (aij != 0)) ; \ } GrB_Info GB (_bind1st_tran__lxor_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 = GBX (Ax, pA, false) ; \ Cx [pC] = ((aij != 0) != (y != 0)) ; \ } GrB_Info GB (_bind2nd_tran__lxor_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
a.32.1.c
/* { dg-do compile } */ /* { dg-require-effective-target tls } */ #include <stdlib.h> float *work; int size; float tol; void build (void); #pragma omp threadprivate(work,size,tol) void a32 (float t, int n) { tol = t; size = n; #pragma omp parallel copyin(tol,size) { build (); } } void build () { int i; work = (float *) malloc (sizeof (float) * size); for (i = 0; i < size; ++i) work[i] = tol; }
GB_unop__isfinite_bool_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__isfinite_bool_fc64 // op(A') function: GB_unop_tran__isfinite_bool_fc64 // C type: bool // A type: GxB_FC64_t // cast: GxB_FC64_t cij = (aij) // unaryop: cij = GB_cisfinite (aij) #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ bool // 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_cisfinite (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_cisfinite (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISFINITE || GxB_NO_BOOL || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__isfinite_bool_fc64 ( bool *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_cisfinite (z) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__isfinite_bool_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
task_types_serialized.c
// RUN: %libomp-compile-and-run | FileCheck %s // REQUIRES: ompt #include "callback.h" #include <omp.h> void print_task_type(int id) { #pragma omp critical { int task_type; char buffer[2048]; ompt_get_task_info(0, &task_type, NULL, NULL, NULL, NULL); format_task_type(task_type, buffer); printf("%" PRIu64 ": id=%d task_type=%s=%d\n", ompt_get_thread_data()->value, id, buffer, task_type); } }; int main() { //initial task print_task_type(0); int x; //implicit task #pragma omp parallel num_threads(1) { print_task_type(1); x++; } #pragma omp parallel num_threads(1) #pragma omp master { //explicit task #pragma omp task { print_task_type(2); x++; } //explicit task with undeferred #pragma omp task if(0) { print_task_type(3); x++; } //explicit task with untied #pragma omp task untied { print_task_type(4); x++; } //explicit task with final #pragma omp task final(1) { print_task_type(5); x++; //nested explicit task with final and undeferred #pragma omp task { print_task_type(6); x++; } } /* //TODO:not working //explicit task with mergeable #pragma omp task mergeable { print_task_type(7); x++; } */ //TODO: merged task } // Check if libomp supports the callbacks for this test. // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_task_create' // CHECK: {{^}}0: NULL_POINTER=[[NULL:.*$]] // CHECK: {{^}}[[MASTER_ID:[0-9]+]]: ompt_event_task_create: parent_task_id=0, parent_task_frame.exit=[[NULL]], parent_task_frame.reenter=[[NULL]], new_task_id={{[0-9]+}}, codeptr_ra=[[NULL]], task_type=ompt_task_initial=1, has_dependences=no // CHECK: {{^}}[[MASTER_ID]]: id=0 task_type=ompt_task_initial=1 // CHECK: {{^}}[[MASTER_ID]]: id=1 task_type=ompt_task_implicit|ompt_task_undeferred=134217730 // CHECK: {{^[0-9]+}}: ompt_event_task_create: parent_task_id={{[0-9]+}}, parent_task_frame.exit={{0x[0-f]+}}, parent_task_frame.reenter={{0x[0-f]+}}, new_task_id={{[0-9]+}}, codeptr_ra={{0x[0-f]+}}, task_type=ompt_task_explicit|ompt_task_undeferred=134217732, has_dependences=no // CHECK: {{^[0-9]+}}: id=2 task_type=ompt_task_explicit|ompt_task_undeferred=134217732 // CHECK: {{^[0-9]+}}: ompt_event_task_create: parent_task_id={{[0-9]+}}, parent_task_frame.exit={{0x[0-f]+}}, parent_task_frame.reenter={{0x[0-f]+}}, new_task_id={{[0-9]+}}, codeptr_ra={{0x[0-f]+}}, task_type=ompt_task_explicit|ompt_task_undeferred=134217732, has_dependences=no // CHECK: {{^[0-9]+}}: id=3 task_type=ompt_task_explicit|ompt_task_undeferred=134217732 // CHECK: {{^[0-9]+}}: ompt_event_task_create: parent_task_id={{[0-9]+}}, parent_task_frame.exit={{0x[0-f]+}}, parent_task_frame.reenter={{0x[0-f]+}}, new_task_id={{[0-9]+}}, codeptr_ra={{0x[0-f]+}}, task_type=ompt_task_explicit|ompt_task_undeferred|ompt_task_untied=402653188, has_dependences=no // CHECK: {{^[0-9]+}}: id=4 task_type=ompt_task_explicit|ompt_task_undeferred|ompt_task_untied=402653188 // CHECK: {{^[0-9]+}}: ompt_event_task_create: parent_task_id={{[0-9]+}}, parent_task_frame.exit={{0x[0-f]+}}, parent_task_frame.reenter={{0x[0-f]+}}, new_task_id={{[0-9]+}}, codeptr_ra={{0x[0-f]+}}, task_type=ompt_task_explicit|ompt_task_undeferred|ompt_task_final=671088644, has_dependences=no // CHECK: {{^[0-9]+}}: id=5 task_type=ompt_task_explicit|ompt_task_undeferred|ompt_task_final=671088644 // CHECK: {{^[0-9]+}}: ompt_event_task_create: parent_task_id={{[0-9]+}}, parent_task_frame.exit={{0x[0-f]+}}, parent_task_frame.reenter={{0x[0-f]+}}, new_task_id={{[0-9]+}}, codeptr_ra={{0x[0-f]+}}, task_type=ompt_task_explicit|ompt_task_undeferred|ompt_task_final=671088644, has_dependences=no // CHECK: {{^[0-9]+}}: id=6 task_type=ompt_task_explicit|ompt_task_undeferred|ompt_task_final=671088644 // ___CHECK: {{^[0-9]+}}: ompt_event_task_create: parent_task_id={{[0-9]+}}, parent_task_frame.exit={{0x[0-f]+}}, parent_task_frame.reenter={{0x[0-f]+}}, new_task_id={{[0-9]+}}, codeptr_ra={{0x[0-f]+}}, task_type=ompt_task_explicit|ompt_task_undeferred=134217732, has_dependences=no // ___CHECK: {{^[0-9]+}}: id=7 task_type=ompt_task_explicit|ompt_task_undeferred=134217732 return 0; }
acoustic-so8.c
#define _POSIX_C_SOURCE 200809L #include "stdlib.h" #include "math.h" #include "sys/time.h" #include "xmmintrin.h" #include "pmmintrin.h" #include "omp.h" struct dataobj { void *restrict data; int * size; int * npsize; int * dsize; int * hsize; int * hofs; int * oofs; } ; struct profiler { double section0; double section1; double section2; } ; void bf0(struct dataobj *restrict damp_vec, const float dt, struct dataobj *restrict u_vec, struct dataobj *restrict vp_vec, const int t0, const int t1, const int t2, const int x0_blk0_size, const int x_M, const int x_m, const int y0_blk0_size, const int y_M, const int y_m, const int z_M, const int z_m, const int nthreads); int Forward(struct dataobj *restrict damp_vec, const float dt, const float o_x, const float o_y, const float o_z, struct dataobj *restrict rec_vec, struct dataobj *restrict rec_coords_vec, struct dataobj *restrict src_vec, struct dataobj *restrict src_coords_vec, struct dataobj *restrict u_vec, struct dataobj *restrict vp_vec, const int x_M, const int x_m, const int y_M, const int y_m, const int z_M, const int z_m, const int p_rec_M, const int p_rec_m, const int p_src_M, const int p_src_m, const int time_M, const int time_m, struct profiler * timers, const int x0_blk0_size, const int y0_blk0_size, const int nthreads, const int nthreads_nonaffine) { float (*restrict damp)[damp_vec->size[1]][damp_vec->size[2]] __attribute__ ((aligned (64))) = (float (*)[damp_vec->size[1]][damp_vec->size[2]]) damp_vec->data; float (*restrict rec)[rec_vec->size[1]] __attribute__ ((aligned (64))) = (float (*)[rec_vec->size[1]]) rec_vec->data; float (*restrict rec_coords)[rec_coords_vec->size[1]] __attribute__ ((aligned (64))) = (float (*)[rec_coords_vec->size[1]]) rec_coords_vec->data; float (*restrict src)[src_vec->size[1]] __attribute__ ((aligned (64))) = (float (*)[src_vec->size[1]]) src_vec->data; float (*restrict src_coords)[src_coords_vec->size[1]] __attribute__ ((aligned (64))) = (float (*)[src_coords_vec->size[1]]) src_coords_vec->data; float (*restrict u)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]] __attribute__ ((aligned (64))) = (float (*)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]]) u_vec->data; float (*restrict vp)[vp_vec->size[1]][vp_vec->size[2]] __attribute__ ((aligned (64))) = (float (*)[vp_vec->size[1]][vp_vec->size[2]]) vp_vec->data; /* Flush denormal numbers to zero in hardware */ _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); for (int time = time_m, t0 = (time)%(3), t1 = (time + 1)%(3), t2 = (time + 2)%(3); time <= time_M; time += 1, t0 = (time)%(3), t1 = (time + 1)%(3), t2 = (time + 2)%(3)) { struct timeval start_section0, end_section0; gettimeofday(&start_section0, NULL); /* Begin section0 */ bf0(damp_vec,dt,u_vec,vp_vec,t0,t1,t2,x0_blk0_size,x_M - (x_M - x_m + 1)%(x0_blk0_size),x_m,y0_blk0_size,y_M - (y_M - y_m + 1)%(y0_blk0_size),y_m,z_M,z_m,nthreads); bf0(damp_vec,dt,u_vec,vp_vec,t0,t1,t2,x0_blk0_size,x_M - (x_M - x_m + 1)%(x0_blk0_size),x_m,(y_M - y_m + 1)%(y0_blk0_size),y_M,y_M - (y_M - y_m + 1)%(y0_blk0_size) + 1,z_M,z_m,nthreads); bf0(damp_vec,dt,u_vec,vp_vec,t0,t1,t2,(x_M - x_m + 1)%(x0_blk0_size),x_M,x_M - (x_M - x_m + 1)%(x0_blk0_size) + 1,y0_blk0_size,y_M - (y_M - y_m + 1)%(y0_blk0_size),y_m,z_M,z_m,nthreads); bf0(damp_vec,dt,u_vec,vp_vec,t0,t1,t2,(x_M - x_m + 1)%(x0_blk0_size),x_M,x_M - (x_M - x_m + 1)%(x0_blk0_size) + 1,(y_M - y_m + 1)%(y0_blk0_size),y_M,y_M - (y_M - y_m + 1)%(y0_blk0_size) + 1,z_M,z_m,nthreads); /* End section0 */ gettimeofday(&end_section0, NULL); timers->section0 += (double)(end_section0.tv_sec-start_section0.tv_sec)+(double)(end_section0.tv_usec-start_section0.tv_usec)/1000000; struct timeval start_section1, end_section1; gettimeofday(&start_section1, NULL); /* Begin section1 */ #pragma omp parallel num_threads(nthreads_nonaffine) { int chunk_size = (int)(fmax(1, (1.0F/3.0F)*(p_src_M - p_src_m + 1)/nthreads_nonaffine)); #pragma omp for collapse(1) schedule(dynamic,chunk_size) for (int p_src = p_src_m; p_src <= p_src_M; p_src += 1) { int ii_src_0 = (int)(floor(-6.66667e-2*o_x + 6.66667e-2*src_coords[p_src][0])); int ii_src_1 = (int)(floor(-6.66667e-2*o_y + 6.66667e-2*src_coords[p_src][1])); int ii_src_2 = (int)(floor(-6.66667e-2*o_z + 6.66667e-2*src_coords[p_src][2])); int ii_src_3 = (int)(floor(-6.66667e-2*o_z + 6.66667e-2*src_coords[p_src][2])) + 1; int ii_src_4 = (int)(floor(-6.66667e-2*o_y + 6.66667e-2*src_coords[p_src][1])) + 1; int ii_src_5 = (int)(floor(-6.66667e-2*o_x + 6.66667e-2*src_coords[p_src][0])) + 1; float px = (float)(-o_x - 1.5e+1F*(int)(floor(-6.66667e-2F*o_x + 6.66667e-2F*src_coords[p_src][0])) + src_coords[p_src][0]); float py = (float)(-o_y - 1.5e+1F*(int)(floor(-6.66667e-2F*o_y + 6.66667e-2F*src_coords[p_src][1])) + src_coords[p_src][1]); float pz = (float)(-o_z - 1.5e+1F*(int)(floor(-6.66667e-2F*o_z + 6.66667e-2F*src_coords[p_src][2])) + src_coords[p_src][2]); if (ii_src_0 >= x_m - 1 && ii_src_1 >= y_m - 1 && ii_src_2 >= z_m - 1 && ii_src_0 <= x_M + 1 && ii_src_1 <= y_M + 1 && ii_src_2 <= z_M + 1) { float r0 = (dt*dt)*(vp[ii_src_0 + 8][ii_src_1 + 8][ii_src_2 + 8]*vp[ii_src_0 + 8][ii_src_1 + 8][ii_src_2 + 8])*(-2.96296e-4F*px*py*pz + 4.44445e-3F*px*py + 4.44445e-3F*px*pz - 6.66667e-2F*px + 4.44445e-3F*py*pz - 6.66667e-2F*py - 6.66667e-2F*pz + 1)*src[time][p_src]; #pragma omp atomic update u[t1][ii_src_0 + 8][ii_src_1 + 8][ii_src_2 + 8] += r0; } if (ii_src_0 >= x_m - 1 && ii_src_1 >= y_m - 1 && ii_src_3 >= z_m - 1 && ii_src_0 <= x_M + 1 && ii_src_1 <= y_M + 1 && ii_src_3 <= z_M + 1) { float r1 = (dt*dt)*(vp[ii_src_0 + 8][ii_src_1 + 8][ii_src_3 + 8]*vp[ii_src_0 + 8][ii_src_1 + 8][ii_src_3 + 8])*(2.96296e-4F*px*py*pz - 4.44445e-3F*px*pz - 4.44445e-3F*py*pz + 6.66667e-2F*pz)*src[time][p_src]; #pragma omp atomic update u[t1][ii_src_0 + 8][ii_src_1 + 8][ii_src_3 + 8] += r1; } if (ii_src_0 >= x_m - 1 && ii_src_2 >= z_m - 1 && ii_src_4 >= y_m - 1 && ii_src_0 <= x_M + 1 && ii_src_2 <= z_M + 1 && ii_src_4 <= y_M + 1) { float r2 = (dt*dt)*(vp[ii_src_0 + 8][ii_src_4 + 8][ii_src_2 + 8]*vp[ii_src_0 + 8][ii_src_4 + 8][ii_src_2 + 8])*(2.96296e-4F*px*py*pz - 4.44445e-3F*px*py - 4.44445e-3F*py*pz + 6.66667e-2F*py)*src[time][p_src]; #pragma omp atomic update u[t1][ii_src_0 + 8][ii_src_4 + 8][ii_src_2 + 8] += r2; } if (ii_src_0 >= x_m - 1 && ii_src_3 >= z_m - 1 && ii_src_4 >= y_m - 1 && ii_src_0 <= x_M + 1 && ii_src_3 <= z_M + 1 && ii_src_4 <= y_M + 1) { float r3 = (dt*dt)*(vp[ii_src_0 + 8][ii_src_4 + 8][ii_src_3 + 8]*vp[ii_src_0 + 8][ii_src_4 + 8][ii_src_3 + 8])*(-2.96296e-4F*px*py*pz + 4.44445e-3F*py*pz)*src[time][p_src]; #pragma omp atomic update u[t1][ii_src_0 + 8][ii_src_4 + 8][ii_src_3 + 8] += r3; } if (ii_src_1 >= y_m - 1 && ii_src_2 >= z_m - 1 && ii_src_5 >= x_m - 1 && ii_src_1 <= y_M + 1 && ii_src_2 <= z_M + 1 && ii_src_5 <= x_M + 1) { float r4 = (dt*dt)*(vp[ii_src_5 + 8][ii_src_1 + 8][ii_src_2 + 8]*vp[ii_src_5 + 8][ii_src_1 + 8][ii_src_2 + 8])*(2.96296e-4F*px*py*pz - 4.44445e-3F*px*py - 4.44445e-3F*px*pz + 6.66667e-2F*px)*src[time][p_src]; #pragma omp atomic update u[t1][ii_src_5 + 8][ii_src_1 + 8][ii_src_2 + 8] += r4; } if (ii_src_1 >= y_m - 1 && ii_src_3 >= z_m - 1 && ii_src_5 >= x_m - 1 && ii_src_1 <= y_M + 1 && ii_src_3 <= z_M + 1 && ii_src_5 <= x_M + 1) { float r5 = (dt*dt)*(vp[ii_src_5 + 8][ii_src_1 + 8][ii_src_3 + 8]*vp[ii_src_5 + 8][ii_src_1 + 8][ii_src_3 + 8])*(-2.96296e-4F*px*py*pz + 4.44445e-3F*px*pz)*src[time][p_src]; #pragma omp atomic update u[t1][ii_src_5 + 8][ii_src_1 + 8][ii_src_3 + 8] += r5; } if (ii_src_2 >= z_m - 1 && ii_src_4 >= y_m - 1 && ii_src_5 >= x_m - 1 && ii_src_2 <= z_M + 1 && ii_src_4 <= y_M + 1 && ii_src_5 <= x_M + 1) { float r6 = (dt*dt)*(vp[ii_src_5 + 8][ii_src_4 + 8][ii_src_2 + 8]*vp[ii_src_5 + 8][ii_src_4 + 8][ii_src_2 + 8])*(-2.96296e-4F*px*py*pz + 4.44445e-3F*px*py)*src[time][p_src]; #pragma omp atomic update u[t1][ii_src_5 + 8][ii_src_4 + 8][ii_src_2 + 8] += r6; } if (ii_src_3 >= z_m - 1 && ii_src_4 >= y_m - 1 && ii_src_5 >= x_m - 1 && ii_src_3 <= z_M + 1 && ii_src_4 <= y_M + 1 && ii_src_5 <= x_M + 1) { float r7 = 2.96296e-4F*px*py*pz*(dt*dt)*(vp[ii_src_5 + 8][ii_src_4 + 8][ii_src_3 + 8]*vp[ii_src_5 + 8][ii_src_4 + 8][ii_src_3 + 8])*src[time][p_src]; #pragma omp atomic update u[t1][ii_src_5 + 8][ii_src_4 + 8][ii_src_3 + 8] += r7; } } } /* End section1 */ gettimeofday(&end_section1, NULL); timers->section1 += (double)(end_section1.tv_sec-start_section1.tv_sec)+(double)(end_section1.tv_usec-start_section1.tv_usec)/1000000; struct timeval start_section2, end_section2; gettimeofday(&start_section2, NULL); /* Begin section2 */ #pragma omp parallel num_threads(nthreads_nonaffine) { int chunk_size = (int)(fmax(1, (1.0F/3.0F)*(p_rec_M - p_rec_m + 1)/nthreads_nonaffine)); #pragma omp for collapse(1) schedule(dynamic,chunk_size) for (int p_rec = p_rec_m; p_rec <= p_rec_M; p_rec += 1) { int ii_rec_0 = (int)(floor(-6.66667e-2*o_x + 6.66667e-2*rec_coords[p_rec][0])); int ii_rec_1 = (int)(floor(-6.66667e-2*o_y + 6.66667e-2*rec_coords[p_rec][1])); int ii_rec_2 = (int)(floor(-6.66667e-2*o_z + 6.66667e-2*rec_coords[p_rec][2])); int ii_rec_3 = (int)(floor(-6.66667e-2*o_z + 6.66667e-2*rec_coords[p_rec][2])) + 1; int ii_rec_4 = (int)(floor(-6.66667e-2*o_y + 6.66667e-2*rec_coords[p_rec][1])) + 1; int ii_rec_5 = (int)(floor(-6.66667e-2*o_x + 6.66667e-2*rec_coords[p_rec][0])) + 1; float px = (float)(-o_x - 1.5e+1F*(int)(floor(-6.66667e-2F*o_x + 6.66667e-2F*rec_coords[p_rec][0])) + rec_coords[p_rec][0]); float py = (float)(-o_y - 1.5e+1F*(int)(floor(-6.66667e-2F*o_y + 6.66667e-2F*rec_coords[p_rec][1])) + rec_coords[p_rec][1]); float pz = (float)(-o_z - 1.5e+1F*(int)(floor(-6.66667e-2F*o_z + 6.66667e-2F*rec_coords[p_rec][2])) + rec_coords[p_rec][2]); float sum = 0.0F; if (ii_rec_0 >= x_m - 1 && ii_rec_1 >= y_m - 1 && ii_rec_2 >= z_m - 1 && ii_rec_0 <= x_M + 1 && ii_rec_1 <= y_M + 1 && ii_rec_2 <= z_M + 1) { sum += (-2.96296e-4F*px*py*pz + 4.44445e-3F*px*py + 4.44445e-3F*px*pz - 6.66667e-2F*px + 4.44445e-3F*py*pz - 6.66667e-2F*py - 6.66667e-2F*pz + 1)*u[t0][ii_rec_0 + 8][ii_rec_1 + 8][ii_rec_2 + 8]; } if (ii_rec_0 >= x_m - 1 && ii_rec_1 >= y_m - 1 && ii_rec_3 >= z_m - 1 && ii_rec_0 <= x_M + 1 && ii_rec_1 <= y_M + 1 && ii_rec_3 <= z_M + 1) { sum += (2.96296e-4F*px*py*pz - 4.44445e-3F*px*pz - 4.44445e-3F*py*pz + 6.66667e-2F*pz)*u[t0][ii_rec_0 + 8][ii_rec_1 + 8][ii_rec_3 + 8]; } if (ii_rec_0 >= x_m - 1 && ii_rec_2 >= z_m - 1 && ii_rec_4 >= y_m - 1 && ii_rec_0 <= x_M + 1 && ii_rec_2 <= z_M + 1 && ii_rec_4 <= y_M + 1) { sum += (2.96296e-4F*px*py*pz - 4.44445e-3F*px*py - 4.44445e-3F*py*pz + 6.66667e-2F*py)*u[t0][ii_rec_0 + 8][ii_rec_4 + 8][ii_rec_2 + 8]; } if (ii_rec_0 >= x_m - 1 && ii_rec_3 >= z_m - 1 && ii_rec_4 >= y_m - 1 && ii_rec_0 <= x_M + 1 && ii_rec_3 <= z_M + 1 && ii_rec_4 <= y_M + 1) { sum += (-2.96296e-4F*px*py*pz + 4.44445e-3F*py*pz)*u[t0][ii_rec_0 + 8][ii_rec_4 + 8][ii_rec_3 + 8]; } if (ii_rec_1 >= y_m - 1 && ii_rec_2 >= z_m - 1 && ii_rec_5 >= x_m - 1 && ii_rec_1 <= y_M + 1 && ii_rec_2 <= z_M + 1 && ii_rec_5 <= x_M + 1) { sum += (2.96296e-4F*px*py*pz - 4.44445e-3F*px*py - 4.44445e-3F*px*pz + 6.66667e-2F*px)*u[t0][ii_rec_5 + 8][ii_rec_1 + 8][ii_rec_2 + 8]; } if (ii_rec_1 >= y_m - 1 && ii_rec_3 >= z_m - 1 && ii_rec_5 >= x_m - 1 && ii_rec_1 <= y_M + 1 && ii_rec_3 <= z_M + 1 && ii_rec_5 <= x_M + 1) { sum += (-2.96296e-4F*px*py*pz + 4.44445e-3F*px*pz)*u[t0][ii_rec_5 + 8][ii_rec_1 + 8][ii_rec_3 + 8]; } if (ii_rec_2 >= z_m - 1 && ii_rec_4 >= y_m - 1 && ii_rec_5 >= x_m - 1 && ii_rec_2 <= z_M + 1 && ii_rec_4 <= y_M + 1 && ii_rec_5 <= x_M + 1) { sum += (-2.96296e-4F*px*py*pz + 4.44445e-3F*px*py)*u[t0][ii_rec_5 + 8][ii_rec_4 + 8][ii_rec_2 + 8]; } if (ii_rec_3 >= z_m - 1 && ii_rec_4 >= y_m - 1 && ii_rec_5 >= x_m - 1 && ii_rec_3 <= z_M + 1 && ii_rec_4 <= y_M + 1 && ii_rec_5 <= x_M + 1) { sum += 2.96296e-4F*px*py*pz*u[t0][ii_rec_5 + 8][ii_rec_4 + 8][ii_rec_3 + 8]; } rec[time][p_rec] = sum; } } /* End section2 */ gettimeofday(&end_section2, NULL); timers->section2 += (double)(end_section2.tv_sec-start_section2.tv_sec)+(double)(end_section2.tv_usec-start_section2.tv_usec)/1000000; } return 0; } void bf0(struct dataobj *restrict damp_vec, const float dt, struct dataobj *restrict u_vec, struct dataobj *restrict vp_vec, const int t0, const int t1, const int t2, const int x0_blk0_size, const int x_M, const int x_m, const int y0_blk0_size, const int y_M, const int y_m, const int z_M, const int z_m, const int nthreads) { float (*restrict damp)[damp_vec->size[1]][damp_vec->size[2]] __attribute__ ((aligned (64))) = (float (*)[damp_vec->size[1]][damp_vec->size[2]]) damp_vec->data; float (*restrict u)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]] __attribute__ ((aligned (64))) = (float (*)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]]) u_vec->data; float (*restrict vp)[vp_vec->size[1]][vp_vec->size[2]] __attribute__ ((aligned (64))) = (float (*)[vp_vec->size[1]][vp_vec->size[2]]) vp_vec->data; if (x0_blk0_size == 0) { return; } #pragma omp parallel num_threads(nthreads) { #pragma omp for collapse(1) schedule(dynamic,1) for (int x0_blk0 = x_m; x0_blk0 <= x_M; x0_blk0 += x0_blk0_size) { for (int y0_blk0 = y_m; y0_blk0 <= y_M; y0_blk0 += y0_blk0_size) { for (int x = x0_blk0; x <= x0_blk0 + x0_blk0_size - 1; x += 1) { for (int y = y0_blk0; y <= y0_blk0 + y0_blk0_size - 1; y += 1) { #pragma omp simd aligned(damp,u,vp:32) for (int z = z_m; z <= z_M; z += 1) { float r11 = 1.0/(vp[x + 8][y + 8][z + 8]*vp[x + 8][y + 8][z + 8]); u[t1][x + 8][y + 8][z + 8] = (r11*(2*u[t0][x + 8][y + 8][z + 8] - u[t2][x + 8][y + 8][z + 8]) + dt*damp[x + 1][y + 1][z + 1]*u[t0][x + 8][y + 8][z + 8] + (dt*dt)*(-7.93650813e-6F*(u[t0][x + 4][y + 8][z + 8] + u[t0][x + 8][y + 4][z + 8] + u[t0][x + 8][y + 8][z + 4] + u[t0][x + 8][y + 8][z + 12] + u[t0][x + 8][y + 12][z + 8] + u[t0][x + 12][y + 8][z + 8]) + 1.12874782e-4F*(u[t0][x + 5][y + 8][z + 8] + u[t0][x + 8][y + 5][z + 8] + u[t0][x + 8][y + 8][z + 5] + u[t0][x + 8][y + 8][z + 11] + u[t0][x + 8][y + 11][z + 8] + u[t0][x + 11][y + 8][z + 8]) - 8.8888891e-4F*(u[t0][x + 6][y + 8][z + 8] + u[t0][x + 8][y + 6][z + 8] + u[t0][x + 8][y + 8][z + 6] + u[t0][x + 8][y + 8][z + 10] + u[t0][x + 8][y + 10][z + 8] + u[t0][x + 10][y + 8][z + 8]) + 7.11111128e-3F*(u[t0][x + 7][y + 8][z + 8] + u[t0][x + 8][y + 7][z + 8] + u[t0][x + 8][y + 8][z + 7] + u[t0][x + 8][y + 8][z + 9] + u[t0][x + 8][y + 9][z + 8] + u[t0][x + 9][y + 8][z + 8]) - 3.79629639e-2F*u[t0][x + 8][y + 8][z + 8]))/(r11 + dt*damp[x + 1][y + 1][z + 1]); } } } } } } }
cpd.c
/** * @file cpd.c * @brief Tensor factorization with the CPD model using AO-ADMM. * @author Shaden Smith <shaden@cs.umn.edu> * @version 2.0.0 * @date 2016-05-14 */ /****************************************************************************** * INCLUDES *****************************************************************************/ #include <math.h> #include "cpd.h" #include "admm.h" #include "../csf.h" #include "../sptensor.h" #include "../mttkrp.h" #include "../timer.h" #include "../util.h" /****************************************************************************** * PRIVATE FUNCTIONS *****************************************************************************/ /****************************************************************************** * API FUNCTIONS *****************************************************************************/ splatt_error_type splatt_cpd( splatt_csf const * const tensor, splatt_idx_t rank, splatt_cpd_opts const * const cpd_options, splatt_global_opts const * const global_options, splatt_kruskal * factored) { /* allocate default options if they were not supplied */ splatt_global_opts * global_opts = (splatt_global_opts *) global_options; if(global_options == NULL) { global_opts = splatt_alloc_global_opts(); } splatt_cpd_opts * cpd_opts = (splatt_cpd_opts *) cpd_options; if(cpd_options == NULL) { cpd_opts = splatt_alloc_cpd_opts(); } splatt_omp_set_num_threads(global_opts->num_threads); /* allocate workspace */ cpd_ws * ws = cpd_alloc_ws(tensor, rank, cpd_opts, global_opts); /* perform the factorization! */ cpd_iterate(tensor, rank, ws, cpd_opts, global_opts, factored); /* clean up workspace */ cpd_free_ws(ws); /* free options if we had to allocate them */ if(global_options == NULL) { splatt_free_global_opts(global_opts); } if(cpd_options == NULL) { splatt_free_cpd_opts(cpd_opts); } return SPLATT_SUCCESS; } splatt_cpd_opts * splatt_alloc_cpd_opts(void) { splatt_cpd_opts * opts = splatt_malloc(sizeof(*opts)); /* defaults */ opts->tolerance = 1e-5; opts->max_iterations = 200; opts->inner_tolerance = 1e-2; opts->max_inner_iterations = 50; for(idx_t m=0; m < MAX_NMODES; ++m) { opts->chunk_sizes[m] = 50; opts->constraints[m] = splatt_alloc_constraint(SPLATT_CON_CLOSEDFORM); } return opts; } void splatt_free_cpd_opts( splatt_cpd_opts * opts) { /* free constraints */ for(idx_t m=0; m < MAX_NMODES; ++m) { splatt_free_constraint(opts->constraints[m]); } /* free options pointer */ splatt_free(opts); } splatt_kruskal * splatt_alloc_cpd( splatt_csf const * const csf, splatt_idx_t rank) { splatt_kruskal * cpd = splatt_malloc(sizeof(*cpd)); cpd->nmodes = csf->nmodes; cpd->rank = rank; cpd->lambda = splatt_malloc(rank * sizeof(*cpd->lambda)); for(idx_t m=0; m < csf->nmodes; ++m) { cpd->dims[m] = csf->dims[m]; cpd->factors[m] = splatt_malloc(csf->dims[m] * rank * sizeof(**cpd->factors)); /* TODO: allow custom initialization including NUMA aware */ fill_rand(cpd->factors[m], csf->dims[m] * rank); } /* initialize lambda in case it is not modified */ for(idx_t r=0; r < rank; ++r) { cpd->lambda[r] = 1.; } return cpd; } void splatt_free_cpd( splatt_kruskal * factored) { splatt_free(factored->lambda); for(idx_t m=0; m < factored->nmodes; ++m) { splatt_free(factored->factors[m]); } splatt_free(factored); } /****************************************************************************** * PUBLIC FUNCTIONS *****************************************************************************/ double cpd_iterate( splatt_csf const * const tensor, idx_t const rank, cpd_ws * const ws, splatt_cpd_opts * const cpd_opts, splatt_global_opts const * const global_opts, splatt_kruskal * factored) { idx_t const nmodes = tensor->nmodes; /* XXX: fix MTTKRP interface */ /* * The matrices used for MTTKRP. When using MPI, these may be larger than * the mats[:] matrices due to non-local indices. If the sizes are the same, * these are just aliases for mats[:]. */ matrix_t * mats[MAX_NMODES+1]; matrix_t * mttkrp_mats[MAX_NMODES+1]; for(idx_t m=0; m < tensor->nmodes; ++m) { mats[m] = mat_mkptr(factored->factors[m], tensor->dims[m], rank, 1); #ifdef SPLATT_USE_MPI /* setup local MTTKRP matrices */ #else mttkrp_mats[m] = mats[m]; #endif mat_normalize(mats[m], factored->lambda); } mats[MAX_NMODES] = ws->mttkrp_buf; mttkrp_mats[MAX_NMODES] = ws->mttkrp_buf; /* allow constraints to initialize */ cpd_init_constraints(cpd_opts, mats, nmodes); /* reset column weights */ val_t * const restrict norms = factored->lambda; for(idx_t r=0; r < rank; ++r) { norms[r] = 1.; } /* initialite aTa values */ for(idx_t m=1; m < nmodes; ++m) { mat_aTa(mats[m], ws->aTa[m]); } /* XXX TODO: CSF opts */ double * opts = splatt_default_opts(); /* MTTKRP ws */ splatt_mttkrp_ws * mttkrp_ws = splatt_mttkrp_alloc_ws(tensor, rank, opts); /* for tracking convergence */ double olderr = 1.; double err = 0.; double const ttnormsq = csf_frobsq(tensor); /* timers */ sp_timer_t itertime; sp_timer_t modetime[MAX_NMODES]; timer_start(&timers[TIMER_CPD]); val_t inner_its[MAX_NMODES]; /* foreach outer iteration */ for(idx_t it=0; it < cpd_opts->max_iterations; ++it) { timer_fstart(&itertime); /* foreach AO step */ for(idx_t m=0; m < nmodes; ++m) { timer_fstart(&modetime[m]); mttkrp_csf(tensor, mttkrp_mats, m, ws->thds, mttkrp_ws, global_opts); #ifdef SPLATT_USE_MPI /* exchange partial MTTKRP results */ #endif /* ADMM solve for constraints */ inner_its[m] = admm_(m, mats, norms, ws, cpd_opts, global_opts); #ifdef SPLATT_USE_MPI /* exchange updated factor rows */ #endif /* prepare aTa for next mode */ #ifdef SPLATT_USE_MPI /* XXX use real comm */ mat_aTa_mpi(mats[m], ws->aTa[m], MPI_COMM_WORLD); #else mat_aTa(mats[m], ws->aTa[m]); #endif timer_stop(&modetime[m]); } /* foreach mode */ /* calculate outer convergence */ double const norm = cpd_norm(ws, norms); double const inner = cpd_innerprod(nmodes-1, ws, mats, norms); double const residual = ttnormsq + norm - (2 * inner); err = residual / ttnormsq; assert(err <= olderr); timer_stop(&itertime); /* print progress */ if(global_opts->verbosity > SPLATT_VERBOSITY_NONE) { printf(" its = %4"SPLATT_PF_IDX" (%0.3"SPLATT_PF_VAL"s) " "rel-errsq = %0.5"SPLATT_PF_VAL" delta = %+0.4e\n", it+1, itertime.seconds, err, err - olderr); if(global_opts->verbosity > SPLATT_VERBOSITY_LOW) { for(idx_t m=0; m < nmodes; ++m) { printf(" mode = %1"SPLATT_PF_IDX" (%0.3fs)", m+1, modetime[m].seconds); if(inner_its[m] > 0) { printf(" [%4.1"SPLATT_PF_VAL" ADMM its per row]", inner_its[m]); } printf("\n"); } } } /* terminate if converged */ if(it > 0 && fabs(olderr - err) < cpd_opts->tolerance) { break; } olderr = err; } /* absorb into lambda if no constraints/regularizations */ if(ws->unconstrained) { cpd_post_process(mats, norms, ws, cpd_opts, global_opts); } else { cpd_finalize_constraints(cpd_opts, mats, nmodes); } splatt_free(opts); for(idx_t m=0; m < tensor->nmodes; ++m) { /* free matrix memory if not an alias */ if(mttkrp_mats[m] != mats[m]) { mat_free(mttkrp_mats[m]); } /* only free ptr */ splatt_free(mats[m]); } splatt_mttkrp_free_ws(mttkrp_ws); timer_stop(&timers[TIMER_CPD]); factored->fit = 1 - err; return err; } void cpd_post_process( matrix_t * * mats, val_t * const column_weights, cpd_ws * const ws, splatt_cpd_opts const * const cpd_opts, splatt_global_opts const * const global_opts) { idx_t const rank = mats[0]->J; val_t * tmp = splatt_malloc(rank * sizeof(*tmp)); /* normalize each matrix and adjust lambda */ for(idx_t m=0; m < ws->nmodes; ++m) { mat_normalize(mats[m], tmp); for(idx_t f=0; f < rank; ++f) { column_weights[f] *= tmp[f]; } } splatt_free(tmp); } cpd_ws * cpd_alloc_ws( splatt_csf const * const tensor, idx_t rank, splatt_cpd_opts const * const cpd_opts, splatt_global_opts const * const global_opts) { idx_t const nmodes = tensor->nmodes; cpd_ws * ws = splatt_malloc(sizeof(*ws)); ws->nmodes = nmodes; for(idx_t m=0; m < nmodes; ++m) { ws->aTa[m] = mat_alloc(rank, rank); } ws->aTa_buf = mat_alloc(rank, rank); ws->gram = mat_alloc(rank, rank); ws->nthreads = global_opts->num_threads; ws->thds = thd_init(ws->nthreads, 3, (rank * rank * sizeof(val_t)) + 64, 0, (nmodes * rank * sizeof(val_t)) + 64); /* MTTKRP space */ idx_t const maxdim = tensor->dims[argmax_elem(tensor->dims, nmodes)]; ws->mttkrp_buf = mat_alloc(maxdim, rank); /* Setup structures needed for constraints. */ ws->unconstrained = true; for(idx_t m=0; m < nmodes; ++m) { /* allocate duals if we need to perform ADMM */ if(cpd_opts->constraints[m]->solve_type != SPLATT_CON_CLOSEDFORM) { ws->duals[m] = mat_zero(tensor->dims[m], rank); } else { ws->duals[m] = NULL; } if(strcmp(cpd_opts->constraints[m]->description, "UNCONSTRAINED") != 0) { ws->unconstrained = false; } } if(ws->unconstrained) { ws->auxil = NULL; ws->mat_init = NULL; } else { ws->auxil = mat_alloc(maxdim, rank); ws->mat_init = mat_alloc(maxdim, rank); } return ws; } cpd_ws * cpd_alloc_ws_empty( idx_t const nmodes, idx_t const rank, splatt_cpd_opts const * const cpd_opts, splatt_global_opts const * const global_opts) { cpd_ws * ws = splatt_malloc(sizeof(*ws)); ws->nmodes = nmodes; for(idx_t m=0; m < nmodes; ++m) { ws->aTa[m] = mat_zero(rank, rank); } ws->aTa_buf = mat_zero(rank, rank); ws->gram = mat_zero(rank, rank); ws->nthreads = global_opts->num_threads; ws->thds = thd_init(ws->nthreads, 3, (rank * rank * sizeof(val_t)) + 64, 0, (nmodes * rank * sizeof(val_t)) + 64); /* MTTKRP space */ ws->mttkrp_buf = NULL; /* Setup structures needed for constraints. */ ws->unconstrained = true; for(idx_t m=0; m < nmodes; ++m) { ws->duals[m] = NULL; if(strcmp(cpd_opts->constraints[m]->description, "UNCONSTRAINED") != 0) { ws->unconstrained = false; } } ws->auxil = NULL; ws->mat_init = NULL; return ws; } void cpd_free_ws( cpd_ws * const ws) { mat_free(ws->mttkrp_buf); mat_free(ws->aTa_buf); mat_free(ws->gram); mat_free(ws->auxil); mat_free(ws->mat_init); for(idx_t m=0; m < ws->nmodes; ++m) { mat_free(ws->aTa[m]); mat_free(ws->duals[m]); } thd_free(ws->thds, ws->nthreads); splatt_free(ws); } val_t cpd_norm( cpd_ws const * const ws, val_t const * const restrict column_weights) { idx_t const rank = ws->aTa[0]->J; val_t * const restrict scratch = ws->aTa_buf->vals; /* initialize scratch space */ for(idx_t i=0; i < rank; ++i) { for(idx_t j=i; j < rank; ++j) { scratch[j + (i*rank)] = 1.; } } /* scratch = hada(aTa) */ for(idx_t m=0; m < ws->nmodes; ++m) { val_t const * const restrict atavals = ws->aTa[m]->vals; for(idx_t i=0; i < rank; ++i) { for(idx_t j=i; j < rank; ++j) { scratch[j + (i*rank)] *= atavals[j + (i*rank)]; } } } /* now compute weights^T * aTa[MAX_NMODES] * weights */ val_t norm = 0; for(idx_t i=0; i < rank; ++i) { norm += scratch[i+(i*rank)] * column_weights[i] * column_weights[i]; for(idx_t j=i+1; j < rank; ++j) { norm += scratch[j+(i*rank)] * column_weights[i] * column_weights[j] * 2; } } return fabs(norm); } val_t cpd_innerprod( idx_t lastmode, cpd_ws const * const ws, matrix_t * * mats, val_t const * const restrict column_weights) { idx_t const nrows = mats[lastmode]->I; idx_t const rank = mats[0]->J; val_t const * const newmat = mats[lastmode]->vals; val_t const * const mttkrp = ws->mttkrp_buf->vals; val_t myinner = 0; #pragma omp parallel reduction(+:myinner) { int const tid = splatt_omp_get_thread_num(); val_t * const restrict accumF = ws->thds[tid].scratch[0]; for(idx_t r=0; r < rank; ++r) { accumF[r] = 0.; } /* Hadamard product with newest factor and previous MTTKRP */ #pragma omp for schedule(static) for(idx_t i=0; i < nrows; ++i) { val_t const * const restrict newmat_row = newmat + (i*rank); val_t const * const restrict mttkrp_row = mttkrp + (i*rank); for(idx_t r=0; r < rank; ++r) { accumF[r] += newmat_row[r] * mttkrp_row[r]; } } /* accumulate everything into 'myinner' */ for(idx_t r=0; r < rank; ++r) { myinner += accumF[r] * column_weights[r]; } } /* end omp parallel -- reduce myinner */ /* TODO AllReduce for MPI support */ return myinner; } val_t kruskal_norm( splatt_kruskal const * const kruskal) { idx_t const rank = kruskal->rank; val_t * const scratch = (val_t *) splatt_malloc(rank * rank * sizeof(*scratch)); matrix_t * ata = mat_zero(rank, rank); /* initialize scratch space */ for(idx_t i=0; i < rank; ++i) { for(idx_t j=i; j < rank; ++j) { scratch[j + (i*rank)] = 1.; } } /* scratch = hada(aTa) */ for(idx_t m=0; m < kruskal->nmodes; ++m) { matrix_t matptr; mat_fillptr(&matptr, kruskal->factors[m], kruskal->dims[m], rank, 1); mat_aTa(&matptr, ata); val_t const * const restrict atavals = ata->vals; for(idx_t i=0; i < rank; ++i) { for(idx_t j=i; j < rank; ++j) { scratch[j + (i*rank)] *= atavals[j + (i*rank)]; } } } /* now compute weights^T * aTa[MAX_NMODES] * weights */ val_t norm = 0; val_t const * const column_weights = kruskal->lambda; for(idx_t i=0; i < rank; ++i) { norm += scratch[i+(i*rank)] * column_weights[i] * column_weights[i]; for(idx_t j=i+1; j < rank; ++j) { norm += scratch[j+(i*rank)] * column_weights[i] * column_weights[j] * 2; } } splatt_free(scratch); mat_free(ata); return fabs(norm); } double cpd_error( sptensor_t const * const tensor, splatt_kruskal const * const factored) { timer_start(&timers[TIMER_FIT]); /* find the smallest mode for MTTKRP */ idx_t const smallest_mode = argmin_elem(tensor->dims, tensor->nmodes); idx_t const nrows = tensor->dims[smallest_mode]; idx_t const rank = factored->rank; /* * MTTKRP */ matrix_t * mat_ptrs[MAX_NMODES+1]; for(idx_t m=0; m < factored->nmodes; ++m) { mat_ptrs[m] = mat_mkptr(factored->factors[m], factored->dims[m], rank, 1); } mat_ptrs[MAX_NMODES] = mat_alloc(nrows, rank); mttkrp_stream(tensor, mat_ptrs, smallest_mode); val_t const * const smallmat = factored->factors[smallest_mode]; val_t const * const mttkrp = mat_ptrs[MAX_NMODES]->vals; /* * inner product between tensor and factored */ double inner = 0; #pragma omp parallel reduction(+:inner) { int const tid = splatt_omp_get_thread_num(); val_t * const restrict accumF = splatt_malloc(rank * sizeof(*accumF)); for(idx_t r=0; r < rank; ++r) { accumF[r] = 0.; } /* Hadamard product with newest factor and previous MTTKRP */ #pragma omp for schedule(static) for(idx_t i=0; i < nrows; ++i) { val_t const * const restrict smallmat_row = smallmat + (i*rank); val_t const * const restrict mttkrp_row = mttkrp + (i*rank); for(idx_t r=0; r < rank; ++r) { accumF[r] += smallmat_row[r] * mttkrp_row[r]; } } /* accumulate everything into 'inner' */ for(idx_t r=0; r < rank; ++r) { inner += accumF[r] * factored->lambda[r]; } splatt_free(accumF); } /* end omp parallel -- reduce myinner */ double const Xnormsq = tt_normsq(tensor); double const Znormsq = kruskal_norm(factored); double const residual = sqrt(Xnormsq + Znormsq - (2 * inner)); double const err = residual / sqrt(Xnormsq); #if 0 printf("\n"); printf("Xnormsq: %e Znormsq: %e inner: %e\n", Xnormsq, Znormsq, inner); #endif /* cleanup */ mat_free(mat_ptrs[MAX_NMODES]); for(idx_t m=0; m < factored->nmodes; ++m) { /* just the ptr */ splatt_free(mat_ptrs[m]); } timer_stop(&timers[TIMER_FIT]); return err; }
pcgetrf.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/compute/pzgetrf.c, normal z -> c, Fri Sep 28 17:38:11 2018 * **/ #include "plasma_async.h" #include "plasma_context.h" #include "plasma_descriptor.h" #include "plasma_internal.h" #include "plasma_types.h" #include "plasma_workspace.h" #include <plasma_core_blas.h> #define A(m, n) (plasma_complex32_t*)plasma_tile_addr(A, m, n) /******************************************************************************/ void plasma_pcgetrf(plasma_desc_t A, int *ipiv, plasma_sequence_t *sequence, plasma_request_t *request) { // Return if failed sequence. if (sequence->status != PlasmaSuccess) return; // Read parameters from the context. plasma_context_t *plasma = plasma_context_self(); // Set tiling parameters. int ib = plasma->ib; int minmtnt = imin(A.mt, A.nt); for (int k = 0; k < minmtnt; k++) { plasma_complex32_t *a00, *a20; a00 = A(k, k); a20 = A(A.mt-1, k); // Create fake dependencies of the whole panel on its individual tiles. // These tasks are inserted to generate a correct DAG rather than // doing any useful work. for (int m = k+1; m < A.mt-1; m++) { plasma_complex32_t *amk = A(m, k); #pragma omp task depend (in:amk[0]) \ depend (inout:a00[0]) \ priority(1) { // Do some funny work here. It appears so that the compiler // might not insert the task if it is completely empty. int l = 1; l++; } } int ma00k = (A.mt-k-1)*A.mb; int na00k = plasma_tile_nmain(A, k); int lda20 = plasma_tile_mmain(A, A.mt-1); int nvak = plasma_tile_nview(A, k); int mvak = plasma_tile_mview(A, k); int ldak = plasma_tile_mmain(A, k); int num_panel_threads = imin(plasma->max_panel_threads, minmtnt-k); // panel #pragma omp task depend(inout:a00[0:ma00k*na00k]) \ depend(inout:a20[0:lda20*nvak]) \ depend(out:ipiv[k*A.mb:mvak]) \ priority(1) { volatile int *max_idx = (int*)malloc(num_panel_threads*sizeof(int)); if (max_idx == NULL) plasma_request_fail(sequence, request, PlasmaErrorOutOfMemory); volatile plasma_complex32_t *max_val = (plasma_complex32_t*)malloc(num_panel_threads*sizeof( plasma_complex32_t)); if (max_val == NULL) plasma_request_fail(sequence, request, PlasmaErrorOutOfMemory); volatile int info = 0; plasma_barrier_t barrier; plasma_barrier_init(&barrier); if (sequence->status == PlasmaSuccess) { // If nesting would not be expensive on architectures such as // KNL, this would resolve the issue with deadlocks caused by // tasks expected to run are in fact not launched. //#pragma omp parallel for shared(barrier) // schedule(dynamic,1) // num_threads(num_panel_threads) #pragma omp taskloop untied shared(barrier) \ num_tasks(num_panel_threads) \ priority(2) for (int rank = 0; rank < num_panel_threads; rank++) { { plasma_desc_t view = plasma_desc_view(A, k*A.mb, k*A.nb, A.m-k*A.mb, nvak); plasma_core_cgetrf(view, &ipiv[k*A.mb], ib, rank, num_panel_threads, max_idx, max_val, &info, &barrier); if (info != 0) plasma_request_fail(sequence, request, k*A.mb+info); } } } #pragma omp taskwait free((void*)max_idx); free((void*)max_val); for (int i = k*A.mb+1; i <= imin(A.m, k*A.mb+nvak); i++) ipiv[i-1] += k*A.mb; } // update for (int n = k+1; n < A.nt; n++) { plasma_complex32_t *a01, *a11, *a21; a01 = A(k, n); a11 = A(k+1, n); a21 = A(A.mt-1, n); int ma11k = (A.mt-k-2)*A.mb; int na11n = plasma_tile_nmain(A, n); int lda21 = plasma_tile_mmain(A, A.mt-1); int nvan = plasma_tile_nview(A, n); #pragma omp task depend(in:a00[0:ma00k*na00k]) \ depend(in:a20[0:lda20*nvak]) \ depend(in:ipiv[k*A.mb:mvak]) \ depend(inout:a01[0:ldak*nvan]) \ depend(inout:a11[0:ma11k*na11n]) \ depend(inout:a21[0:lda21*nvan]) \ priority(n == k+1) { if (sequence->status == PlasmaSuccess) { // geswp int k1 = k*A.mb+1; int k2 = imin(k*A.mb+A.mb, A.m); plasma_desc_t view = plasma_desc_view(A, 0, n*A.nb, A.m, nvan); plasma_core_cgeswp(PlasmaRowwise, view, k1, k2, ipiv, 1); // trsm plasma_core_ctrsm(PlasmaLeft, PlasmaLower, PlasmaNoTrans, PlasmaUnit, mvak, nvan, 1.0, A(k, k), ldak, A(k, n), ldak); // gemm for (int m = k+1; m < A.mt; m++) { int mvam = plasma_tile_mview(A, m); int ldam = plasma_tile_mmain(A, m); #pragma omp task priority(n == k+1) { plasma_core_cgemm( PlasmaNoTrans, PlasmaNoTrans, mvam, nvan, A.nb, -1.0, A(m, k), ldam, A(k, n), ldak, 1.0, A(m, n), ldam); } } } #pragma omp taskwait } } } // Multidependency of the whole ipiv on the individual chunks // corresponding to tiles. for (int m = 0; m < minmtnt; m++) { // insert dummy task #pragma omp task depend (in:ipiv[m*A.mb]) \ depend (inout:ipiv[0]) { int l = 1; l++; } } // pivoting to the left for (int k = 0; k < minmtnt-1; k++) { plasma_complex32_t *a10, *a20; a10 = A(k+1, k); a20 = A(A.mt-1, k); int ma10k = (A.mt-k-2)*A.mb; int na00k = plasma_tile_nmain(A, k); int lda20 = plasma_tile_mmain(A, A.mt-1); int nvak = plasma_tile_nview(A, k); #pragma omp task depend(in:ipiv[0:imin(A.m,A.n)]) \ depend(inout:a10[0:ma10k*na00k]) \ depend(inout:a20[0:lda20*nvak]) { if (sequence->status == PlasmaSuccess) { plasma_desc_t view = plasma_desc_view(A, 0, k*A.nb, A.m, A.nb); int k1 = (k+1)*A.mb+1; int k2 = imin(A.m, A.n); plasma_core_cgeswp(PlasmaRowwise, view, k1, k2, ipiv, 1); } } // Multidependency of individual tiles on the whole panel. for (int m = k+2; m < A.mt-1; m++) { plasma_complex32_t *amk = A(m, k); #pragma omp task depend (in:a10[0]) \ depend (inout:amk[0]) { // Do some funny work here. It appears so that the compiler // might not insert the task if it is completely empty. int l = 1; l++; } } } }
nestedfn-3.c
/* { dg-do run } */ #include <omp.h> extern void abort (void); int main (void) { int i = 5, l = 0; int foo (void) { return i == 6; } int bar (void) { return i - 3; } omp_set_dynamic (0); #pragma omp parallel if (foo ()) num_threads (bar ()) reduction (|:l) if (omp_get_num_threads () != 1) l = 1; i++; #pragma omp parallel if (foo ()) num_threads (bar ()) reduction (|:l) if (omp_get_num_threads () != 3) l = 1; i++; #pragma omp master if (bar () != 4) abort (); #pragma omp single { if (foo ()) abort (); i--; if (! foo ()) abort (); } if (l) abort (); i = 8; #pragma omp atomic l += bar (); if (l != 5) abort (); return 0; }
ConcatenateCoefficient.h
// -------------------------------------------------------------------------- // Binary Brain -- binary neural net framework // // Copyright (C) 2018-2019 by Ryuji Fuchikami // https://github.com/ryuz // ryuji.fuchikami@nifty.com // -------------------------------------------------------------------------- #pragma once #include "bb/Manager.h" #include "bb/Model.h" namespace bb { // 定数を連結する template <typename FT = float, typename BT = float> class ConcatenateCoefficient : public Model { protected: bool m_host_only = false; bool m_binary_mode = true; indices_t m_input_shape; indices_t m_output_shape; indices_t m_coeff_shape; index_t m_concatenate_size; std::shared_ptr<Tensor> m_param; std::shared_ptr<Tensor> m_grad; FrameBuffer m_y_buf; FrameBuffer m_dx_buf; std::mt19937_64 m_mt; public: struct create_t { index_t concatenate_size = 0; std::uint64_t seed = 1; }; protected: ConcatenateCoefficient(create_t const &create) { m_concatenate_size = create.concatenate_size; m_mt.seed(create.seed); m_param = std::shared_ptr<Tensor>(new Tensor); m_grad = std::shared_ptr<Tensor>(new Tensor); } /** * @brief コマンド処理 * @detail コマンド処理 * @param args コマンド */ void CommandProc(std::vector<std::string> args) { // HostOnlyモード設定 if (args.size() == 2 && args[0] == "host_only") { m_host_only = EvalBool(args[1]); } } public: ~ConcatenateCoefficient() {} static std::shared_ptr<ConcatenateCoefficient> Create(create_t const &create) { return std::shared_ptr<ConcatenateCoefficient>(new ConcatenateCoefficient(create)); } static std::shared_ptr<ConcatenateCoefficient> Create(index_t concatenate_size, std::uint64_t seed = 1) { create_t create; create.concatenate_size = concatenate_size; create.seed = seed; return std::shared_ptr<ConcatenateCoefficient>(new ConcatenateCoefficient(create)); } std::string GetModelName(void) const { return "ConcatenateCoefficient"; } /** * @brief 入力のshape設定 * @detail 入力のshape設定 * @param shape 新しいshape * @return なし */ indices_t SetInputShape(indices_t shape) { // 設定済みなら何もしない if ( shape == this->GetInputShape() ) { return this->GetOutputShape(); } BB_ASSERT(shape.size() > 0); // 形状設定 m_input_shape = shape; // 最後の次元にサイズを積み増しして出力形状設定 m_output_shape = m_input_shape; m_output_shape[m_output_shape.size() - 1] += m_concatenate_size; m_coeff_shape = m_input_shape; m_coeff_shape[m_output_shape.size() - 1] = m_concatenate_size; // パラメータ初期化 m_param->Resize(DataType<BT>::type, m_coeff_shape); *m_param = 0.5; m_grad->Resize(DataType<BT>::type, m_coeff_shape); *m_grad = 0; return m_output_shape; } /** * @brief 入力形状取得 * @detail 入力形状を取得する * @return 入力形状を返す */ indices_t GetInputShape(void) const { return m_input_shape; } /** * @brief 出力形状取得 * @detail 出力形状を取得する * @return 出力形状を返す */ indices_t GetOutputShape(void) const { return m_output_shape; } Variables GetParameters(void) { Variables parameters; parameters.PushBack(m_param); return parameters; } Variables GetGradients(void) { Variables gradients; gradients.PushBack(m_grad); return gradients; } void SetParameter(index_t index, BT coeff) { auto param_ptr = m_param->Lock<BT>(); param_ptr[index] = coeff; } void GetParameter(index_t index) const { auto param_ptr = m_param->LockConst<BT>(); return param_ptr[index]; } /** * @brief forward演算 * @detail forward演算を行う * @param x 入力データ * @param train 学習時にtrueを指定 * @return forward演算結果 */ inline FrameBuffer Forward(FrameBuffer x_buf, bool train = true) { BB_ASSERT(x_buf.GetType() == DataType<FT>::type); // パラメータクリップ if ( m_binary_mode ) { m_param->Clamp_inplace(0.0, 1.0); } // 戻り値のサイズ設定 m_y_buf.Resize(x_buf.GetType(), x_buf.GetFrameSize(), m_output_shape); #if 0 // #ifdef BB_WITH_CUDA if ( DataType<FT>::type == BB_TYPE_FP32 && !m_host_only && m_x_buf.IsDeviceAvailable() && m_y_buf.IsDeviceAvailable() && Manager::IsDeviceAvailable() ) { // CUDA版 auto ptr_x = x_buf.LockDeviceMemoryConst(); auto ptr_y = m_y_buf.LockDeviceMemory(true); bbcu_fp32_ConcatenateConstant_Forward( (float const *)ptr_x.GetAddr(), (float *)ptr_y.GetAddr(), (int )m_x_buf.GetNodeSize(), (int )m_x_buf.GetFrameSize(), (int )(m_x_buf.GetFrameStride() / sizeof(float)) ); return m_y_buf; } #endif { // 汎用版 index_t input_node_size = x_buf.GetNodeSize(); index_t output_node_size = m_y_buf.GetNodeSize(); index_t frame_size = m_y_buf.GetFrameSize(); auto x_ptr = x_buf.LockConst<FT>(); auto y_ptr = m_y_buf.Lock<FT>(); auto param_ptr = m_param->Lock<BT>(); #pragma omp parallel for for (index_t node = 0; node < input_node_size; ++node) { for (index_t frame = 0; frame < frame_size; ++frame) { auto x = x_ptr.Get(frame, node); y_ptr.Set(frame, node, x); } } index_t coeff_size = output_node_size - input_node_size; if ( DataType<FT>::type == BB_TYPE_BIT ) { std::uniform_real_distribution<BT> dist((BT)0, (BT)1); for (index_t i = 0; i < coeff_size; ++i) { auto coeff = param_ptr[i]; for (index_t frame = 0; frame < frame_size; ++frame) { y_ptr.Set(frame, input_node_size + i, dist(m_mt) < coeff); } } } else { #pragma omp parallel for for (index_t i = 0; i < coeff_size; ++i) { auto coeff = param_ptr[i]; for (index_t frame = 0; frame < frame_size; ++frame) { y_ptr.Set(frame, input_node_size + i, (FT)coeff); } } } return m_y_buf; } } /** * @brief backward演算 * @detail backward演算を行う * * @return backward演算結果 */ inline FrameBuffer Backward(FrameBuffer dy_buf) { if (dy_buf.Empty()) { return dy_buf; } BB_ASSERT(dy_buf.GetType() == DataType<BT>::type); // 戻り値のサイズ設定 m_dx_buf.Resize(DataType<BT>::type, dy_buf.GetFrameSize(), m_input_shape); #if 0 // #ifdef BB_WITH_CUDA if ( DataType<T>::type == BB_TYPE_FP32 && !m_host_only && m_x_buf.IsDeviceAvailable() && m_dx_buf.IsDeviceAvailable() && dy_buf.IsDeviceAvailable() && Manager::IsDeviceAvailable() ) { // GPU版 auto ptr_x = m_x_buf.LockDeviceMemoryConst(); auto ptr_dy = dy_buf.LockDeviceMemoryConst(); auto ptr_dx = m_dx_buf.LockDeviceMemory(true); bbcu_fp32_ReLU_Backward( (float const *)ptr_x.GetAddr(), (float const *)ptr_dy.GetAddr(), (float *)ptr_dx.GetAddr(), (int )dy_buf.GetNodeSize(), (int )dy_buf.GetFrameSize(), (int )(dy_buf.GetFrameStride() / sizeof(float)) ); return m_dx_buf; } #endif { //汎用版 index_t input_node_size = m_dx_buf.GetNodeSize(); index_t output_node_size = dy_buf.GetNodeSize(); index_t frame_size = dy_buf.GetFrameSize(); auto dy_ptr = dy_buf.LockConst<BT>(); auto dx_ptr = m_dx_buf.Lock<BT>(); auto grad_ptr = m_grad->Lock<BT>(); #pragma omp parallel for for (index_t node = 0; node < input_node_size; ++node) { for (index_t frame = 0; frame < frame_size; ++frame) { auto dy = dy_ptr.Get(frame, node); dx_ptr.Set(frame, node, dy); } } index_t coeff_size = output_node_size - input_node_size; #pragma omp parallel for for (index_t i = 0; i < coeff_size; ++i) { BT dy = 0; for (index_t frame = 0; frame < frame_size; ++frame) { dy += dy_ptr.Get(frame, input_node_size + i); } grad_ptr[i] += dy / (BT)frame_size; } return m_dx_buf; } } }; } // end of file
abs.c
#include <math.h> #include "../cdefs.h" #include "../types.h" #include "../misc/safeomp.h" void bib_mabs(mat_r x) { const int m = NROWS(x); const int n = NCOLS(x); #pragma omp parallel for if(m*n > OMP_MIN_SIZE) for (int j=0; j<n; j++) { SAFE_SIMD for (int i=0; i<m; i++) DATA(x)[i + n*j] = fabs(DATA(x)[i + n*j]); } }
dense.c
/* Copyright (c) 2015-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. */ #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/mmult.h" #include "utils/scale.h" #include "utils/sumstats.h" #include "utils/xpose.h" // --------------------------------------------- // Cosine // --------------------------------------------- /** * @brief * Compute the cosine similarity matrix of a matrix. This is * all pair-wise vector cosine similarities of the columns. * * @details * The implementation is dominated by a symmetric rank-k update * via the BLAS function dsyrk(). * * @param trans * Perform cosine(x) or cosine(t(x)) * @param m,n * The number of rows/columns of the input matrix x. * @param x * The input mxn matrix. * @param cos * The output nxn matrix. */ int coop_cosine_mat(const bool trans, const bool inv, const int m, const int n, const double * const restrict x, double *restrict cos) { int ncols; if (trans) { ncols = m; tcrossprod(m, n, 1.0, x, cos); } else { ncols = n; crossprod(m, n, 1.0, x, cos); } int ret = cosim_fill(ncols, cos); CHECKRET(ret); if (inv) { ret = inv_sym_chol(ncols, cos); CHECKRET(ret); } symmetrize(ncols, cos); return COOP_OK; } int coop_cosine_matmat(const bool trans, const bool inv, const int m, const int n, const double * const restrict x, const double * const restrict y, double *restrict cos) { int nrows, ncols; if (trans) { nrows = n; ncols = m; } else { nrows = m; ncols = n; } matmult(!trans, trans, 1.0, nrows, ncols, x, nrows, ncols, y, cos); int ret = cosim_fill_full(ncols, cos); CHECKRET(ret); if (inv) { ret = inv_sym_chol(ncols, cos); CHECKRET(ret); } return COOP_OK; } /** * @brief * Compute the cosine similarity between two vectors. * * @details * The implementation uses a dgemm() to compute the dot product * of x and y, and then two dsyrk() calls to compute the (square of) * the norms of x and y. * * @param n * The length of the x and y vectors. * @param x,y * The input vectors. * * @return * The cosine similarity between the two vectors. */ int coop_cosine_vecvec(const int n, const double * const restrict x, const double * const restrict y, double *cos) { double normx, normy; const double cp = ddot(n, x, y); crossprod(n, 1, 1.0, x, &normx); crossprod(n, 1, 1.0, y, &normy); *cos = cp / sqrt(normx * normy); return COOP_OK; } // --------------------------------------------- // Correlation // --------------------------------------------- /** * @brief * Compute the pearson correlation matrix. * * @details * The implementation is dominated by a symmetric rank-k update * via the BLAS function dsyrk(). * * @param m,n * The number of rows/columns of the input matrix x. * @param x * The input mxn matrix. * @param cor * The output nxn matrix. */ int coop_pcor_mat(const bool trans, const bool inv, const int m, const int n, const double * const restrict x, double *restrict cor) { double *x_cp = malloc(m*n*sizeof(*x)); CHECKMALLOC(x_cp); int nrows, ncols; if (trans) { xpose(m, n, x, x_cp); nrows = n; ncols = m; } else { memcpy(x_cp, x, m*n*sizeof(*x)); nrows = m; ncols = n; } remove_colmeans(nrows, ncols, x_cp); crossprod(nrows, ncols, 1.0, x_cp, cor); free(x_cp); int ret = cosim_fill(ncols, cor); CHECKRET(ret); if (inv) { ret = inv_sym_chol(ncols, cor); CHECKRET(ret); } symmetrize(ncols, cor); return COOP_OK; } // pcor(x, y) int coop_pcor_matmat(const bool trans, const bool inv, const int m, const int n, const double * const restrict x, const double * const restrict y, double *restrict cor) { int nrows, ncols; int ret = 0; double *x_cp = malloc(m*n * sizeof(*x)); CHECKMALLOC(x_cp); double *y_cp = malloc(m*n * sizeof(*y)); if (y_cp == NULL) { free(x_cp); return COOP_BADMALLOC; } if (trans) { xpose(m, n, x, x_cp); xpose(m, n, y, y_cp); nrows = n; ncols = m; } else { memcpy(x_cp, x, m*n*sizeof(*x)); memcpy(y_cp, y, m*n*sizeof(*y)); nrows = m; ncols = n; } scale_nostore(true, true, nrows, ncols, x_cp); scale_nostore(true, true, nrows, ncols, y_cp); const double alpha = 1. / ((double) (nrows-1)); matmult(true, false, alpha, nrows, ncols, x_cp, nrows, ncols, y_cp, cor); free(x_cp); free(y_cp); if (inv) ret = inv_sym_chol(ncols, cor); return ret; } /** * @brief * Compute the pearson correlation between two vectors. * * @details * The implementation uses a dgemm() to compute the dot product * of x and y, and then two dsyrk() calls to compute the (square of) * the norms of x and y. * * @param n * The length of the x and y vectors. * @param x,y * The input vectors. * * @return * The correlation between the two vectors. */ int coop_pcor_vecvec(const int n, const double * const restrict x, const double * const restrict y, double *restrict cor) { double normx, normy; double *x_minusmean = malloc(n*sizeof(*x)); CHECKMALLOC(x_minusmean); double *y_minusmean = malloc(n*sizeof(*y)); CHECKMALLOC(y_minusmean); const double meanx = mean(n, x); const double meany = mean(n, y); SAFE_PARALLEL_FOR_SIMD for (int i=0; i<n; i++) { x_minusmean[i] = x[i] - meanx; y_minusmean[i] = y[i] - meany; } const double cp = ddot(n, x_minusmean, y_minusmean); crossprod(n, 1, 1.0, x_minusmean, &normx); crossprod(n, 1, 1.0, y_minusmean, &normy); free(x_minusmean); free(y_minusmean); *cor = cp / sqrt(normx * normy); return COOP_OK; } // --------------------------------------------- // Covariance // --------------------------------------------- /** * @file * @brief Covariance. * * @details * Computes the variance-covariance matrix. Centering is done in-place. * * @param method * Input. The form the covariance matrix takes (pearson, kendall, * spearman). Currently only pearson works. * @param m,n * Inputs. Problem size (dims of x) * @param x * Input. The data matrix. * @param coc * Output. The covariance matrix. * * @return * The return value indicates that status of the function. Non-zero values * are errors. */ int coop_covar_mat(const bool trans, const bool inv, const int m, const int n, const double * const restrict x, double *restrict cov) { int nrows, ncols; double *x_cp = malloc(m*n*sizeof(*x)); CHECKMALLOC(x_cp); if (trans) { xpose(m, n, x, x_cp); nrows = n; ncols = m; } else { memcpy(x_cp, x, m*n*sizeof(*x)); nrows = m; ncols = n; } const double alpha = 1. / ((double) (nrows-1)); remove_colmeans(nrows, ncols, x_cp); crossprod(nrows, ncols, alpha, x_cp, cov); free(x_cp); if (inv) { int ret = inv_sym_chol(ncols, cov); CHECKRET(ret); } symmetrize(ncols, cov); return COOP_OK; } // covar(x,y) int coop_covar_matmat(const bool trans, const bool inv, const int m, const int n, const double * const restrict x, const double * const restrict y, double *restrict cov) { int ret = 0; int nrows, ncols; double *x_cp = malloc(m*n * sizeof(*x)); CHECKMALLOC(x_cp); double *y_cp = malloc(m*n * sizeof(*y)); if (y_cp == NULL) { free(x_cp); return COOP_BADMALLOC; } if (trans) { xpose(m, n, x, x_cp); xpose(m, n, y, y_cp); nrows = n; ncols = m; } else { memcpy(x_cp, x, m*n*sizeof(*x)); memcpy(y_cp, y, m*n*sizeof(*y)); nrows = m; ncols = n; } const double alpha = 1. / ((double) (nrows-1)); //TODO FIXME make tremove_colmeans and use the BLAS more efficiently... remove_colmeans(nrows, ncols, x_cp); remove_colmeans(nrows, ncols, y_cp); // matmult(!trans, trans, alpha, nrows, ncols, x_cp, nrows, ncols, y_cp, cov); matmult(true, false, alpha, nrows, ncols, x_cp, nrows, ncols, y_cp, cov); free(x_cp); free(y_cp); if (inv) ret = inv_sym_chol(ncols, cov); return ret; } /** * @brief * Compute the covariance between two vectors. * * @details * The implementation uses a dgemm() to compute the dot product * of x and y, and then two dsyrk() calls to compute the (square of) * the norms of x and y. * * @param n * The length of the x and y vectors. * @param x,y * The input vectors. * * @return * The variance of the vectors. */ int coop_covar_vecvec(const int n, const double * const restrict x, const double * const restrict y, double *restrict cov) { const double recip_n = (double) 1. / (n-1); double sum_xy = 0., sum_x = 0., sum_y = 0.; #ifdef OMP_VER_4 #pragma omp simd reduction(+: sum_xy, sum_x, sum_y) #endif for (int i=0; i<n; i++) { const double tx = x[i]; const double ty = y[i]; sum_xy += tx*ty; sum_x += tx; sum_y += ty; } *cov = (sum_xy - (sum_x*sum_y*((double) 1./n))) * recip_n; return COOP_OK; }
GB_unaryop__ainv_uint32_int8.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__ainv_uint32_int8 // op(A') function: GB_tran__ainv_uint32_int8 // C type: uint32_t // A type: int8_t // cast: uint32_t cij = (uint32_t) aij // unaryop: cij = -aij #define GB_ATYPE \ int8_t #define GB_CTYPE \ uint32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = -x ; // casting #define GB_CASTING(z, aij) \ uint32_t z = (uint32_t) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_AINV || GxB_NO_UINT32 || GxB_NO_INT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__ainv_uint32_int8 ( uint32_t *Cx, // Cx and Ax may be aliased int8_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__ainv_uint32_int8 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
act3.c
/* Owen Jauregui Borbon - A01638122 Program for calculating theapproximate area under the curve for a function using the trapezoidal rule. Parallelized using openMP. */ #include <stdio.h> #include <omp.h> int main() { // Number of threads for openMP int threads = 8; // Integration limits double left = 1; double right = 20; // Amount and size of steps for the approximation double stepAmount = 1000000; double diff = (right-left)/stepAmount; // Starting value for the approximation // using 5/x as example function double result = (5/left + 5/right)/2; // Use of openMP for parallelizing operations #pragma omp parallel shared(result) num_threads(threads) { // Parallelizing iterations #pragma omp for for(int i = 1; i < stepAmount; i++) { // Adding Y value for each step to te approximation result += 5/(left + i*diff); } } // Multiply the approximation and the step size for final result result *= diff; // Display result printf("Approximate result: %.4f \n", result); return 0; }
omp-low.c
/* * Copyright (C) 2009 Advanced Micro Devices, Inc. All Rights Reserved. */ /* Lowering pass for OpenMP directives. Converts OpenMP directives into explicit calls to the runtime library (libgomp) and data marshalling to implement data sharing and copying clauses. Contributed by Diego Novillo <dnovillo@redhat.com> Copyright (C) 2005, 2006 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 2, 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 COPYING. If not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "config.h" #include "system.h" #include "coretypes.h" #include "tm.h" #include "tree.h" #include "rtl.h" #include "tree-gimple.h" #include "tree-inline.h" #include "langhooks.h" #include "diagnostic.h" #include "tree-flow.h" #include "timevar.h" #include "flags.h" #include "function.h" #include "expr.h" #include "toplev.h" #include "tree-pass.h" #include "ggc.h" #include "except.h" /* Lowering of OpenMP parallel and workshare constructs proceeds in two phases. The first phase scans the function looking for OMP statements and then for variables that must be replaced to satisfy data sharing clauses. The second phase expands code for the constructs, as well as re-gimplifying things when variables have been replaced with complex expressions. Final code generation is done by pass_expand_omp. The flowgraph is scanned for parallel regions which are then moved to a new function, to be invoked by the thread library. */ /* Context structure. Used to store information about each parallel directive in the code. */ typedef struct omp_context { /* This field must be at the beginning, as we do "inheritance": Some callback functions for tree-inline.c (e.g., omp_copy_decl) receive a copy_body_data pointer that is up-casted to an omp_context pointer. */ copy_body_data cb; /* The tree of contexts corresponding to the encountered constructs. */ struct omp_context *outer; tree stmt; /* Map variables to fields in a structure that allows communication between sending and receiving threads. */ splay_tree field_map; tree record_type; tree sender_decl; tree receiver_decl; /* These are used just by task contexts, if task firstprivate fn is needed. srecord_type is used to communicate from the thread that encountered the task construct to task firstprivate fn, record_type is allocated by GOMP_task, initialized by task firstprivate fn and passed to the task body fn. */ splay_tree sfield_map; tree srecord_type; /* A chain of variables to add to the top-level block surrounding the construct. In the case of a parallel, this is in the child function. */ tree block_vars; /* What to do with variables with implicitly determined sharing attributes. */ enum omp_clause_default_kind default_kind; /* Nesting depth of this context. Used to beautify error messages re invalid gotos. The outermost ctx is depth 1, with depth 0 being reserved for the main body of the function. */ int depth; /* True if this parallel directive is nested within another. */ bool is_nested; } omp_context; struct omp_for_data_loop { tree v, n1, n2, step; enum tree_code cond_code; }; /* A structure describing the main elements of a parallel loop. */ struct omp_for_data { struct omp_for_data_loop loop; tree chunk_size, for_stmt; tree pre, iter_type; int collapse; bool have_nowait, have_ordered; enum omp_clause_schedule_kind sched_kind; struct omp_for_data_loop *loops; }; static splay_tree all_contexts; static int taskreg_nesting_level; struct omp_region *root_omp_region; static bitmap task_shared_vars; static void scan_omp (tree *, omp_context *); static void lower_omp (tree *, omp_context *); static tree lookup_decl_in_outer_ctx (tree, omp_context *); static tree maybe_lookup_decl_in_outer_ctx (tree, omp_context *); /* Find an OpenMP clause of type KIND within CLAUSES. */ static tree find_omp_clause (tree clauses, enum tree_code kind) { for (; clauses ; clauses = OMP_CLAUSE_CHAIN (clauses)) if (OMP_CLAUSE_CODE (clauses) == kind) return clauses; return NULL_TREE; } /* Return true if CTX is for an omp parallel. */ static inline bool is_parallel_ctx (omp_context *ctx) { return TREE_CODE (ctx->stmt) == OMP_PARALLEL; } /* Return true if CTX is for an omp task. */ static inline bool is_task_ctx (omp_context *ctx) { return TREE_CODE (ctx->stmt) == OMP_TASK; } /* Return true if CTX is for an omp parallel or omp task. */ static inline bool is_taskreg_ctx (omp_context *ctx) { return TREE_CODE (ctx->stmt) == OMP_PARALLEL || TREE_CODE (ctx->stmt) == OMP_TASK; } /* Return true if REGION is a combined parallel+workshare region. */ static inline bool is_combined_parallel (struct omp_region *region) { return region->is_combined_parallel; } /* Extract the header elements of parallel loop FOR_STMT and store them into *FD. */ static void extract_omp_for_data (tree for_stmt, struct omp_for_data *fd, struct omp_for_data_loop *loops) { tree t, *collapse_iter, *collapse_count; tree count = NULL_TREE, iter_type = long_integer_type_node; struct omp_for_data_loop *loop; int i; struct omp_for_data_loop dummy_loop; fd->for_stmt = for_stmt; fd->pre = NULL; fd->collapse = TREE_VEC_LENGTH (OMP_FOR_INIT (for_stmt)); if (fd->collapse > 1) fd->loops = loops; else fd->loops = &fd->loop; fd->have_nowait = fd->have_ordered = false; fd->sched_kind = OMP_CLAUSE_SCHEDULE_STATIC; fd->chunk_size = NULL_TREE; collapse_iter = NULL; collapse_count = NULL; for (t = OMP_FOR_CLAUSES (for_stmt); t ; t = OMP_CLAUSE_CHAIN (t)) switch (OMP_CLAUSE_CODE (t)) { case OMP_CLAUSE_NOWAIT: fd->have_nowait = true; break; case OMP_CLAUSE_ORDERED: fd->have_ordered = true; break; case OMP_CLAUSE_SCHEDULE: fd->sched_kind = OMP_CLAUSE_SCHEDULE_KIND (t); fd->chunk_size = OMP_CLAUSE_SCHEDULE_CHUNK_EXPR (t); break; case OMP_CLAUSE_COLLAPSE: if (fd->collapse > 1) { collapse_iter = &OMP_CLAUSE_COLLAPSE_ITERVAR (t); collapse_count = &OMP_CLAUSE_COLLAPSE_COUNT (t); } default: break; } /* FIXME: for now map schedule(auto) to schedule(static). There should be analysis to determine whether all iterations are approximately the same amount of work (then schedule(static) is best) or if it varries (then schedule(dynamic,N) is better). */ if (fd->sched_kind == OMP_CLAUSE_SCHEDULE_AUTO) { fd->sched_kind = OMP_CLAUSE_SCHEDULE_STATIC; gcc_assert (fd->chunk_size == NULL); } gcc_assert (fd->collapse == 1 || collapse_iter != NULL); if (fd->sched_kind == OMP_CLAUSE_SCHEDULE_RUNTIME) gcc_assert (fd->chunk_size == NULL); else if (fd->chunk_size == NULL) { /* We only need to compute a default chunk size for ordered static loops and dynamic loops. */ if (fd->sched_kind != OMP_CLAUSE_SCHEDULE_STATIC || fd->have_ordered || fd->collapse > 1) fd->chunk_size = (fd->sched_kind == OMP_CLAUSE_SCHEDULE_STATIC) ? integer_zero_node : integer_one_node; } for (i = 0; i < fd->collapse; i++) { if (fd->collapse == 1) loop = &fd->loop; else if (loops != NULL) loop = loops + i; else loop = &dummy_loop; t = TREE_VEC_ELT (OMP_FOR_INIT (for_stmt), i); gcc_assert (TREE_CODE (t) == MODIFY_EXPR); loop->v = TREE_OPERAND (t, 0); gcc_assert (DECL_P (loop->v)); gcc_assert (TREE_CODE (TREE_TYPE (loop->v)) == INTEGER_TYPE); loop->n1 = TREE_OPERAND (t, 1); t = TREE_VEC_ELT (OMP_FOR_COND (for_stmt), i); loop->cond_code = TREE_CODE (t); gcc_assert (TREE_OPERAND (t, 0) == loop->v); loop->n2 = TREE_OPERAND (t, 1); switch (loop->cond_code) { case LT_EXPR: case GT_EXPR: break; case LE_EXPR: if (POINTER_TYPE_P (TREE_TYPE (loop->n2))) loop->n2 = fold_build2 (POINTER_PLUS_EXPR, TREE_TYPE (loop->n2), loop->n2, size_one_node); else loop->n2 = fold_build2 (PLUS_EXPR, TREE_TYPE (loop->n2), loop->n2, build_int_cst (TREE_TYPE (loop->n2), 1)); loop->cond_code = LT_EXPR; break; case GE_EXPR: if (POINTER_TYPE_P (TREE_TYPE (loop->n2))) loop->n2 = fold_build2 (POINTER_PLUS_EXPR, TREE_TYPE (loop->n2), loop->n2, size_int (-1)); else loop->n2 = fold_build2 (MINUS_EXPR, TREE_TYPE (loop->n2), loop->n2, build_int_cst (TREE_TYPE (loop->n2), 1)); loop->cond_code = GT_EXPR; break; default: gcc_unreachable (); } t = TREE_VEC_ELT (OMP_FOR_INCR (fd->for_stmt), i); gcc_assert (TREE_CODE (t) == MODIFY_EXPR); gcc_assert (TREE_OPERAND (t, 0) == loop->v); t = TREE_OPERAND (t, 1); gcc_assert (TREE_OPERAND (t, 0) == loop->v); switch (TREE_CODE (t)) { case PLUS_EXPR: loop->step = TREE_OPERAND (t, 1); break; case MINUS_EXPR: loop->step = TREE_OPERAND (t, 1); loop->step = fold_build1 (NEGATE_EXPR, TREE_TYPE (loop->step), loop->step); break; default: gcc_unreachable (); } if (iter_type != long_long_unsigned_type_node) { if (POINTER_TYPE_P (TREE_TYPE (loop->v))) iter_type = long_long_unsigned_type_node; else if (TYPE_UNSIGNED (TREE_TYPE (loop->v)) && TYPE_PRECISION (TREE_TYPE (loop->v)) >= TYPE_PRECISION (iter_type)) { tree n; if (loop->cond_code == LT_EXPR) n = fold_build2 (PLUS_EXPR, TREE_TYPE (loop->v), loop->n2, loop->step); else n = loop->n1; if (TREE_CODE (n) != INTEGER_CST || tree_int_cst_lt (TYPE_MAX_VALUE (iter_type), n)) iter_type = long_long_unsigned_type_node; } else if (TYPE_PRECISION (TREE_TYPE (loop->v)) > TYPE_PRECISION (iter_type)) { tree n1, n2; if (loop->cond_code == LT_EXPR) { n1 = loop->n1; n2 = fold_build2 (PLUS_EXPR, TREE_TYPE (loop->v), loop->n2, loop->step); } else { n1 = fold_build2 (MINUS_EXPR, TREE_TYPE (loop->v), loop->n2, loop->step); n2 = loop->n1; } if (TREE_CODE (n1) != INTEGER_CST || TREE_CODE (n2) != INTEGER_CST || !tree_int_cst_lt (TYPE_MIN_VALUE (iter_type), n1) || !tree_int_cst_lt (n2, TYPE_MAX_VALUE (iter_type))) iter_type = long_long_unsigned_type_node; } } if (collapse_count && *collapse_count == NULL) { if ((i == 0 || count != NULL_TREE) && TREE_CODE (TREE_TYPE (loop->v)) == INTEGER_TYPE && TREE_CONSTANT (loop->n1) && TREE_CONSTANT (loop->n2) && TREE_CODE (loop->step) == INTEGER_CST) { tree itype = TREE_TYPE (loop->v); if (POINTER_TYPE_P (itype)) itype = lang_hooks.types.type_for_size (TYPE_PRECISION (itype), 0); t = build_int_cst (itype, (loop->cond_code == LT_EXPR ? -1 : 1)); t = fold_build2 (PLUS_EXPR, itype, fold_convert (itype, loop->step), t); t = fold_build2 (PLUS_EXPR, itype, t, fold_convert (itype, loop->n2)); t = fold_build2 (MINUS_EXPR, itype, t, fold_convert (itype, loop->n1)); if (TYPE_UNSIGNED (itype) && loop->cond_code == GT_EXPR) t = fold_build2 (TRUNC_DIV_EXPR, itype, fold_build1 (NEGATE_EXPR, itype, t), fold_build1 (NEGATE_EXPR, itype, fold_convert (itype, loop->step))); else t = fold_build2 (TRUNC_DIV_EXPR, itype, t, fold_convert (itype, loop->step)); t = fold_convert (long_long_unsigned_type_node, t); if (count != NULL_TREE) count = fold_build2 (MULT_EXPR, long_long_unsigned_type_node, count, t); else count = t; if (TREE_CODE (count) != INTEGER_CST) count = NULL_TREE; } else count = NULL_TREE; } } if (count) { if (!tree_int_cst_lt (count, TYPE_MAX_VALUE (long_integer_type_node))) iter_type = long_long_unsigned_type_node; else iter_type = long_integer_type_node; } else if (collapse_iter && *collapse_iter != NULL) iter_type = TREE_TYPE (*collapse_iter); fd->iter_type = iter_type; if (collapse_iter && *collapse_iter == NULL) *collapse_iter = create_tmp_var (iter_type, ".iter"); if (collapse_count && *collapse_count == NULL) { if (count) *collapse_count = fold_convert (iter_type, count); else *collapse_count = create_tmp_var (iter_type, ".count"); } if (fd->collapse > 1) { fd->loop.v = *collapse_iter; fd->loop.n1 = build_int_cst (TREE_TYPE (fd->loop.v), 0); fd->loop.n2 = *collapse_count; fd->loop.step = build_int_cst (TREE_TYPE (fd->loop.v), 1); fd->loop.cond_code = LT_EXPR; } } /* Given two blocks PAR_ENTRY_BB and WS_ENTRY_BB such that WS_ENTRY_BB is the immediate dominator of PAR_ENTRY_BB, return true if there are no data dependencies that would prevent expanding the parallel directive at PAR_ENTRY_BB as a combined parallel+workshare region. When expanding a combined parallel+workshare region, the call to the child function may need additional arguments in the case of OMP_FOR regions. In some cases, these arguments are computed out of variables passed in from the parent to the child via 'struct .omp_data_s'. For instance: #pragma omp parallel for schedule (guided, i * 4) for (j ...) Is lowered into: # BLOCK 2 (PAR_ENTRY_BB) .omp_data_o.i = i; #pragma omp parallel [child fn: bar.omp_fn.0 ( ..., D.1598) # BLOCK 3 (WS_ENTRY_BB) .omp_data_i = &.omp_data_o; D.1667 = .omp_data_i->i; D.1598 = D.1667 * 4; #pragma omp for schedule (guided, D.1598) When we outline the parallel region, the call to the child function 'bar.omp_fn.0' will need the value D.1598 in its argument list, but that value is computed *after* the call site. So, in principle we cannot do the transformation. To see whether the code in WS_ENTRY_BB blocks the combined parallel+workshare call, we collect all the variables used in the OMP_FOR header check whether they appear on the LHS of any statement in WS_ENTRY_BB. If so, then we cannot emit the combined call. FIXME. If we had the SSA form built at this point, we could merely hoist the code in block 3 into block 2 and be done with it. But at this point we don't have dataflow information and though we could hack something up here, it is really not worth the aggravation. */ static bool workshare_safe_to_combine_p (basic_block par_entry_bb, basic_block ws_entry_bb) { struct omp_for_data fd; tree par_stmt, ws_stmt; par_stmt = last_stmt (par_entry_bb); ws_stmt = last_stmt (ws_entry_bb); if (TREE_CODE (ws_stmt) == OMP_SECTIONS) return true; gcc_assert (TREE_CODE (ws_stmt) == OMP_FOR); extract_omp_for_data (ws_stmt, &fd, NULL); if (fd.collapse > 1 && TREE_CODE (fd.loop.n2) != INTEGER_CST) return false; if (fd.iter_type != long_integer_type_node) return false; /* FIXME. We give up too easily here. If any of these arguments are not constants, they will likely involve variables that have been mapped into fields of .omp_data_s for sharing with the child function. With appropriate data flow, it would be possible to see through this. */ if (!is_gimple_min_invariant (fd.loop.n1) || !is_gimple_min_invariant (fd.loop.n2) || !is_gimple_min_invariant (fd.loop.step) || (fd.chunk_size && !is_gimple_min_invariant (fd.chunk_size))) return false; return true; } /* Collect additional arguments needed to emit a combined parallel+workshare call. WS_STMT is the workshare directive being expanded. */ static tree get_ws_args_for (tree ws_stmt) { tree t; if (TREE_CODE (ws_stmt) == OMP_FOR) { struct omp_for_data fd; tree ws_args; extract_omp_for_data (ws_stmt, &fd, NULL); ws_args = NULL_TREE; if (fd.chunk_size) { t = fold_convert (long_integer_type_node, fd.chunk_size); ws_args = tree_cons (NULL, t, ws_args); } t = fold_convert (long_integer_type_node, fd.loop.step); ws_args = tree_cons (NULL, t, ws_args); t = fold_convert (long_integer_type_node, fd.loop.n2); ws_args = tree_cons (NULL, t, ws_args); t = fold_convert (long_integer_type_node, fd.loop.n1); ws_args = tree_cons (NULL, t, ws_args); return ws_args; } else if (TREE_CODE (ws_stmt) == OMP_SECTIONS) { basic_block bb = bb_for_stmt (ws_stmt); t = build_int_cst (unsigned_type_node, EDGE_COUNT (bb->succs)); t = tree_cons (NULL, t, NULL); return t; } gcc_unreachable (); } /* Discover whether REGION is a combined parallel+workshare region. */ static void determine_parallel_type (struct omp_region *region) { basic_block par_entry_bb, par_exit_bb; basic_block ws_entry_bb, ws_exit_bb; if (region == NULL || region->inner == NULL || region->exit == NULL || region->inner->exit == NULL) return; /* We only support parallel+for and parallel+sections. */ if (region->type != OMP_PARALLEL || (region->inner->type != OMP_FOR && region->inner->type != OMP_SECTIONS)) return; /* Check for perfect nesting PAR_ENTRY_BB -> WS_ENTRY_BB and WS_EXIT_BB -> PAR_EXIT_BB. */ par_entry_bb = region->entry; par_exit_bb = region->exit; ws_entry_bb = region->inner->entry; ws_exit_bb = region->inner->exit; if (single_succ (par_entry_bb) == ws_entry_bb && single_succ (ws_exit_bb) == par_exit_bb && workshare_safe_to_combine_p (par_entry_bb, ws_entry_bb)) { tree ws_stmt = last_stmt (region->inner->entry); if (region->inner->type == OMP_FOR) { /* If this is a combined parallel loop, we need to determine whether or not to use the combined library calls. There are two cases where we do not apply the transformation: static loops and any kind of ordered loop. In the first case, we already open code the loop so there is no need to do anything else. In the latter case, the combined parallel loop call would still need extra synchronization to implement ordered semantics, so there would not be any gain in using the combined call. */ tree clauses = OMP_FOR_CLAUSES (ws_stmt); tree c = find_omp_clause (clauses, OMP_CLAUSE_SCHEDULE); if (c == NULL || OMP_CLAUSE_SCHEDULE_KIND (c) == OMP_CLAUSE_SCHEDULE_STATIC || find_omp_clause (clauses, OMP_CLAUSE_ORDERED)) { region->is_combined_parallel = false; region->inner->is_combined_parallel = false; return; } } region->is_combined_parallel = true; region->inner->is_combined_parallel = true; region->ws_args = get_ws_args_for (ws_stmt); } } /* Return true if EXPR is variable sized. */ static inline bool is_variable_sized (tree expr) { return !TREE_CONSTANT (TYPE_SIZE_UNIT (TREE_TYPE (expr))); } /* Return true if DECL is a reference type. */ static inline bool is_reference (tree decl) { return lang_hooks.decls.omp_privatize_by_reference (decl); } /* Lookup variables in the decl or field splay trees. The "maybe" form allows for the variable form to not have been entered, otherwise we assert that the variable must have been entered. */ static inline tree lookup_decl (tree var, omp_context *ctx) { splay_tree_node n; n = splay_tree_lookup (ctx->cb.decl_map, (splay_tree_key) var); return (tree) n->value; } static inline tree maybe_lookup_decl (tree var, omp_context *ctx) { splay_tree_node n; n = splay_tree_lookup (ctx->cb.decl_map, (splay_tree_key) var); return n ? (tree) n->value : NULL_TREE; } static inline tree lookup_field (tree var, omp_context *ctx) { splay_tree_node n; n = splay_tree_lookup (ctx->field_map, (splay_tree_key) var); return (tree) n->value; } static inline tree lookup_sfield (tree var, omp_context *ctx) { splay_tree_node n; n = splay_tree_lookup (ctx->sfield_map ? ctx->sfield_map : ctx->field_map, (splay_tree_key) var); return (tree) n->value; } static inline tree maybe_lookup_field (tree var, omp_context *ctx) { splay_tree_node n; n = splay_tree_lookup (ctx->field_map, (splay_tree_key) var); return n ? (tree) n->value : NULL_TREE; } /* Return true if DECL should be copied by pointer. SHARED_CTX is the parallel context if DECL is to be shared. */ static bool use_pointer_for_field (tree decl, omp_context *shared_ctx) { if (AGGREGATE_TYPE_P (TREE_TYPE (decl))) return true; /* We can only use copy-in/copy-out semantics for shared variables when we know the value is not accessible from an outer scope. */ if (shared_ctx) { /* ??? Trivially accessible from anywhere. But why would we even be passing an address in this case? Should we simply assert this to be false, or should we have a cleanup pass that removes these from the list of mappings? */ if (TREE_STATIC (decl) || DECL_EXTERNAL (decl)) return true; /* For variables with DECL_HAS_VALUE_EXPR_P set, we cannot tell without analyzing the expression whether or not its location is accessible to anyone else. In the case of nested parallel regions it certainly may be. */ if (TREE_CODE (decl) != RESULT_DECL && DECL_HAS_VALUE_EXPR_P (decl)) return true; /* Do not use copy-in/copy-out for variables that have their address taken. */ if (TREE_ADDRESSABLE (decl)) return true; /* Disallow copy-in/out in nested parallel if decl is shared in outer parallel, otherwise each thread could store the shared variable in its own copy-in location, making the variable no longer really shared. */ if (!TREE_READONLY (decl) && shared_ctx->is_nested) { omp_context *up; for (up = shared_ctx->outer; up; up = up->outer) if (is_taskreg_ctx (up) && maybe_lookup_decl (decl, up)) break; if (up && is_taskreg_ctx (up)) { tree c; for (c = OMP_TASKREG_CLAUSES (up->stmt); c; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_SHARED && OMP_CLAUSE_DECL (c) == decl) break; if (c) return true; } } /* For tasks avoid using copy-in/out, unless they are readonly (in which case just copy-in is used). As tasks can be deferred or executed in different thread, when GOMP_task returns, the task hasn't necessarily terminated. */ if (!TREE_READONLY (decl) && is_task_ctx (shared_ctx)) { tree outer = maybe_lookup_decl_in_outer_ctx (decl, shared_ctx); if (is_gimple_reg (outer)) { /* Taking address of OUTER in lower_send_shared_vars might need regimplification of everything that uses the variable. */ if (!task_shared_vars) task_shared_vars = BITMAP_ALLOC (NULL); bitmap_set_bit (task_shared_vars, DECL_UID (outer)); TREE_ADDRESSABLE (outer) = 1; } return true; } } return false; } /* Construct a new automatic decl similar to VAR. */ static tree omp_copy_decl_2 (tree var, tree name, tree type, omp_context *ctx) { tree copy = build_decl (VAR_DECL, name, type); TREE_ADDRESSABLE (copy) = TREE_ADDRESSABLE (var); DECL_COMPLEX_GIMPLE_REG_P (copy) = DECL_COMPLEX_GIMPLE_REG_P (var); DECL_ARTIFICIAL (copy) = DECL_ARTIFICIAL (var); DECL_IGNORED_P (copy) = DECL_IGNORED_P (var); TREE_USED (copy) = 1; DECL_CONTEXT (copy) = current_function_decl; DECL_SEEN_IN_BIND_EXPR_P (copy) = 1; TREE_CHAIN (copy) = ctx->block_vars; ctx->block_vars = copy; return copy; } static tree omp_copy_decl_1 (tree var, omp_context *ctx) { return omp_copy_decl_2 (var, DECL_NAME (var), TREE_TYPE (var), ctx); } /* Build tree nodes to access the field for VAR on the receiver side. */ static tree build_receiver_ref (tree var, bool by_ref, omp_context *ctx) { tree x, field = lookup_field (var, ctx); /* If the receiver record type was remapped in the child function, remap the field into the new record type. */ x = maybe_lookup_field (field, ctx); if (x != NULL) field = x; x = build_fold_indirect_ref (ctx->receiver_decl); x = build3 (COMPONENT_REF, TREE_TYPE (field), x, field, NULL); if (by_ref) x = build_fold_indirect_ref (x); return x; } /* Build tree nodes to access VAR in the scope outer to CTX. In the case of a parallel, this is a component reference; for workshare constructs this is some variable. */ static tree build_outer_var_ref (tree var, omp_context *ctx) { tree x; if (is_global_var (maybe_lookup_decl_in_outer_ctx (var, ctx))) x = var; else if (is_variable_sized (var)) { x = TREE_OPERAND (DECL_VALUE_EXPR (var), 0); x = build_outer_var_ref (x, ctx); x = build_fold_indirect_ref (x); } else if (is_taskreg_ctx (ctx)) { bool by_ref = use_pointer_for_field (var, NULL); x = build_receiver_ref (var, by_ref, ctx); } else if (ctx->outer) x = lookup_decl (var, ctx->outer); else if (is_reference (var)) /* This can happen with orphaned constructs. If var is reference, it is possible it is shared and as such valid. */ x = var; else gcc_unreachable (); if (is_reference (var)) x = build_fold_indirect_ref (x); return x; } /* Build tree nodes to access the field for VAR on the sender side. */ static tree build_sender_ref (tree var, omp_context *ctx) { tree field = lookup_sfield (var, ctx); return build3 (COMPONENT_REF, TREE_TYPE (field), ctx->sender_decl, field, NULL); } /* Add a new field for VAR inside the structure CTX->SENDER_DECL. */ static void install_var_field (tree var, bool by_ref, int mask, omp_context *ctx) { tree field, type, sfield = NULL_TREE; gcc_assert ((mask & 1) == 0 || !splay_tree_lookup (ctx->field_map, (splay_tree_key) var)); gcc_assert ((mask & 2) == 0 || !ctx->sfield_map || !splay_tree_lookup (ctx->sfield_map, (splay_tree_key) var)); type = TREE_TYPE (var); if (by_ref) type = build_pointer_type (type); else if ((mask & 3) == 1 && is_reference (var)) type = TREE_TYPE (type); field = build_decl (FIELD_DECL, DECL_NAME (var), type); /* Remember what variable this field was created for. This does have a side effect of making dwarf2out ignore this member, so for helpful debugging we clear it later in delete_omp_context. */ DECL_ABSTRACT_ORIGIN (field) = var; if (type == TREE_TYPE (var)) { DECL_ALIGN (field) = DECL_ALIGN (var); DECL_USER_ALIGN (field) = DECL_USER_ALIGN (var); TREE_THIS_VOLATILE (field) = TREE_THIS_VOLATILE (var); } else DECL_ALIGN (field) = TYPE_ALIGN (type); if ((mask & 3) == 3) { insert_field_into_struct (ctx->record_type, field); if (ctx->srecord_type) { sfield = build_decl (FIELD_DECL, DECL_NAME (var), type); DECL_ABSTRACT_ORIGIN (sfield) = var; DECL_ALIGN (sfield) = DECL_ALIGN (field); DECL_USER_ALIGN (sfield) = DECL_USER_ALIGN (field); TREE_THIS_VOLATILE (sfield) = TREE_THIS_VOLATILE (field); insert_field_into_struct (ctx->srecord_type, sfield); } } else { if (ctx->srecord_type == NULL_TREE) { tree t; ctx->srecord_type = lang_hooks.types.make_type (RECORD_TYPE); ctx->sfield_map = splay_tree_new (splay_tree_compare_pointers, 0, 0); for (t = TYPE_FIELDS (ctx->record_type); t ; t = TREE_CHAIN (t)) { sfield = build_decl (FIELD_DECL, DECL_NAME (t), TREE_TYPE (t)); DECL_ABSTRACT_ORIGIN (sfield) = DECL_ABSTRACT_ORIGIN (t); insert_field_into_struct (ctx->srecord_type, sfield); splay_tree_insert (ctx->sfield_map, (splay_tree_key) DECL_ABSTRACT_ORIGIN (t), (splay_tree_value) sfield); } } sfield = field; insert_field_into_struct ((mask & 1) ? ctx->record_type : ctx->srecord_type, field); } if (mask & 1) splay_tree_insert (ctx->field_map, (splay_tree_key) var, (splay_tree_value) field); if ((mask & 2) && ctx->sfield_map) splay_tree_insert (ctx->sfield_map, (splay_tree_key) var, (splay_tree_value) sfield); } static tree install_var_local (tree var, omp_context *ctx) { tree new_var = omp_copy_decl_1 (var, ctx); insert_decl_map (&ctx->cb, var, new_var); return new_var; } /* Adjust the replacement for DECL in CTX for the new context. This means copying the DECL_VALUE_EXPR, and fixing up the type. */ static void fixup_remapped_decl (tree decl, omp_context *ctx, bool private_debug) { tree new_decl, size; new_decl = lookup_decl (decl, ctx); TREE_TYPE (new_decl) = remap_type (TREE_TYPE (decl), &ctx->cb); if ((!TREE_CONSTANT (DECL_SIZE (new_decl)) || private_debug) && DECL_HAS_VALUE_EXPR_P (decl)) { tree ve = DECL_VALUE_EXPR (decl); walk_tree (&ve, copy_body_r, &ctx->cb, NULL); SET_DECL_VALUE_EXPR (new_decl, ve); DECL_HAS_VALUE_EXPR_P (new_decl) = 1; } if (!TREE_CONSTANT (DECL_SIZE (new_decl))) { size = remap_decl (DECL_SIZE (decl), &ctx->cb); if (size == error_mark_node) size = TYPE_SIZE (TREE_TYPE (new_decl)); DECL_SIZE (new_decl) = size; size = remap_decl (DECL_SIZE_UNIT (decl), &ctx->cb); if (size == error_mark_node) size = TYPE_SIZE_UNIT (TREE_TYPE (new_decl)); DECL_SIZE_UNIT (new_decl) = size; } } /* The callback for remap_decl. Search all containing contexts for a mapping of the variable; this avoids having to duplicate the splay tree ahead of time. We know a mapping doesn't already exist in the given context. Create new mappings to implement default semantics. */ static tree omp_copy_decl (tree var, copy_body_data *cb) { omp_context *ctx = (omp_context *) cb; tree new_var; if (TREE_CODE (var) == LABEL_DECL) { new_var = create_artificial_label (); DECL_CONTEXT (new_var) = current_function_decl; insert_decl_map (&ctx->cb, var, new_var); return new_var; } while (!is_task_ctx (ctx)) { ctx = ctx->outer; if (ctx == NULL) return var; new_var = maybe_lookup_decl (var, ctx); if (new_var) return new_var; } if (is_global_var (var) || decl_function_context (var) != ctx->cb.src_fn) return var; return error_mark_node; } /* Return the parallel region associated with STMT. */ /* Debugging dumps for parallel regions. */ void dump_omp_region (FILE *, struct omp_region *, int); void debug_omp_region (struct omp_region *); void debug_all_omp_regions (void); /* Dump the parallel region tree rooted at REGION. */ void dump_omp_region (FILE *file, struct omp_region *region, int indent) { fprintf (file, "%*sbb %d: %s\n", indent, "", region->entry->index, tree_code_name[region->type]); if (region->inner) dump_omp_region (file, region->inner, indent + 4); if (region->cont) { fprintf (file, "%*sbb %d: OMP_CONTINUE\n", indent, "", region->cont->index); } if (region->exit) fprintf (file, "%*sbb %d: OMP_RETURN\n", indent, "", region->exit->index); else fprintf (file, "%*s[no exit marker]\n", indent, ""); if (region->next) dump_omp_region (file, region->next, indent); } void debug_omp_region (struct omp_region *region) { dump_omp_region (stderr, region, 0); } void debug_all_omp_regions (void) { dump_omp_region (stderr, root_omp_region, 0); } /* Create a new parallel region starting at STMT inside region PARENT. */ struct omp_region * new_omp_region (basic_block bb, enum tree_code type, struct omp_region *parent) { struct omp_region *region = xcalloc (1, sizeof (*region)); region->outer = parent; region->entry = bb; region->type = type; if (parent) { /* This is a nested region. Add it to the list of inner regions in PARENT. */ region->next = parent->inner; parent->inner = region; } else { /* This is a toplevel region. Add it to the list of toplevel regions in ROOT_OMP_REGION. */ region->next = root_omp_region; root_omp_region = region; } return region; } /* Release the memory associated with the region tree rooted at REGION. */ static void free_omp_region_1 (struct omp_region *region) { struct omp_region *i, *n; for (i = region->inner; i ; i = n) { n = i->next; free_omp_region_1 (i); } free (region); } /* Release the memory for the entire omp region tree. */ void free_omp_regions (void) { struct omp_region *r, *n; for (r = root_omp_region; r ; r = n) { n = r->next; free_omp_region_1 (r); } root_omp_region = NULL; } /* Create a new context, with OUTER_CTX being the surrounding context. */ static omp_context * new_omp_context (tree stmt, omp_context *outer_ctx) { omp_context *ctx = XCNEW (omp_context); splay_tree_insert (all_contexts, (splay_tree_key) stmt, (splay_tree_value) ctx); ctx->stmt = stmt; if (outer_ctx) { ctx->outer = outer_ctx; ctx->cb = outer_ctx->cb; ctx->cb.block = NULL; ctx->depth = outer_ctx->depth + 1; } else { ctx->cb.src_fn = current_function_decl; ctx->cb.dst_fn = current_function_decl; ctx->cb.src_node = cgraph_node (current_function_decl); ctx->cb.dst_node = ctx->cb.src_node; ctx->cb.src_cfun = cfun; ctx->cb.copy_decl = omp_copy_decl; ctx->cb.eh_region = -1; ctx->cb.transform_call_graph_edges = CB_CGE_MOVE; ctx->depth = 1; } ctx->cb.decl_map = splay_tree_new (splay_tree_compare_pointers, 0, 0); return ctx; } /* Destroy a omp_context data structures. Called through the splay tree value delete callback. */ static void delete_omp_context (splay_tree_value value) { omp_context *ctx = (omp_context *) value; splay_tree_delete (ctx->cb.decl_map); if (ctx->field_map) splay_tree_delete (ctx->field_map); if (ctx->sfield_map) splay_tree_delete (ctx->sfield_map); /* We hijacked DECL_ABSTRACT_ORIGIN earlier. We need to clear it before it produces corrupt debug information. */ if (ctx->record_type) { tree t; for (t = TYPE_FIELDS (ctx->record_type); t ; t = TREE_CHAIN (t)) DECL_ABSTRACT_ORIGIN (t) = NULL; } if (ctx->srecord_type) { tree t; for (t = TYPE_FIELDS (ctx->srecord_type); t ; t = TREE_CHAIN (t)) DECL_ABSTRACT_ORIGIN (t) = NULL; } XDELETE (ctx); } /* Fix up RECEIVER_DECL with a type that has been remapped to the child context. */ static void fixup_child_record_type (omp_context *ctx) { tree f, type = ctx->record_type; /* ??? It isn't sufficient to just call remap_type here, because variably_modified_type_p doesn't work the way we expect for record types. Testing each field for whether it needs remapping and creating a new record by hand works, however. */ for (f = TYPE_FIELDS (type); f ; f = TREE_CHAIN (f)) if (variably_modified_type_p (TREE_TYPE (f), ctx->cb.src_fn)) break; if (f) { tree name, new_fields = NULL; type = lang_hooks.types.make_type (RECORD_TYPE); name = DECL_NAME (TYPE_NAME (ctx->record_type)); name = build_decl (TYPE_DECL, name, type); TYPE_NAME (type) = name; for (f = TYPE_FIELDS (ctx->record_type); f ; f = TREE_CHAIN (f)) { tree new_f = copy_node (f); DECL_CONTEXT (new_f) = type; TREE_TYPE (new_f) = remap_type (TREE_TYPE (f), &ctx->cb); TREE_CHAIN (new_f) = new_fields; walk_tree (&DECL_SIZE (new_f), copy_body_r, &ctx->cb, NULL); walk_tree (&DECL_SIZE_UNIT (new_f), copy_body_r, &ctx->cb, NULL); walk_tree (&DECL_FIELD_OFFSET (new_f), copy_body_r, &ctx->cb, NULL); new_fields = new_f; /* Arrange to be able to look up the receiver field given the sender field. */ splay_tree_insert (ctx->field_map, (splay_tree_key) f, (splay_tree_value) new_f); } TYPE_FIELDS (type) = nreverse (new_fields); layout_type (type); } TREE_TYPE (ctx->receiver_decl) = build_pointer_type (type); } /* Instantiate decls as necessary in CTX to satisfy the data sharing specified by CLAUSES. */ static void scan_sharing_clauses (tree clauses, omp_context *ctx) { tree c, decl; bool scan_array_reductions = false; for (c = clauses; c; c = OMP_CLAUSE_CHAIN (c)) { bool by_ref; switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_PRIVATE: decl = OMP_CLAUSE_DECL (c); if (OMP_CLAUSE_PRIVATE_OUTER_REF (c)) goto do_private; else if (!is_variable_sized (decl)) install_var_local (decl, ctx); break; case OMP_CLAUSE_SHARED: gcc_assert (is_taskreg_ctx (ctx)); decl = OMP_CLAUSE_DECL (c); gcc_assert (!is_variable_sized (decl)); by_ref = use_pointer_for_field (decl, ctx); /* Global variables don't need to be copied, the receiver side will use them directly. */ if (is_global_var (maybe_lookup_decl_in_outer_ctx (decl, ctx))) break; if (! TREE_READONLY (decl) || TREE_ADDRESSABLE (decl) || by_ref || is_reference (decl)) { install_var_field (decl, by_ref, 3, ctx); install_var_local (decl, ctx); break; } /* We don't need to copy const scalar vars back. */ OMP_CLAUSE_SET_CODE (c, OMP_CLAUSE_FIRSTPRIVATE); goto do_private; case OMP_CLAUSE_LASTPRIVATE: /* Let the corresponding firstprivate clause create the variable. */ if (OMP_CLAUSE_LASTPRIVATE_STMT (c)) scan_array_reductions = true; if (OMP_CLAUSE_LASTPRIVATE_FIRSTPRIVATE (c)) break; /* FALLTHRU */ case OMP_CLAUSE_FIRSTPRIVATE: case OMP_CLAUSE_REDUCTION: decl = OMP_CLAUSE_DECL (c); do_private: if (is_variable_sized (decl)) { if (is_task_ctx (ctx)) install_var_field (decl, false, 1, ctx); break; } else if (is_taskreg_ctx (ctx)) { bool global = is_global_var (maybe_lookup_decl_in_outer_ctx (decl, ctx)); by_ref = use_pointer_for_field (decl, NULL); if (is_task_ctx (ctx) && (global || by_ref || is_reference (decl))) { install_var_field (decl, false, 1, ctx); if (!global) install_var_field (decl, by_ref, 2, ctx); } else if (!global) install_var_field (decl, by_ref, 3, ctx); } install_var_local (decl, ctx); break; case OMP_CLAUSE_COPYPRIVATE: if (ctx->outer) scan_omp (&OMP_CLAUSE_DECL (c), ctx->outer); /* FALLTHRU */ case OMP_CLAUSE_COPYIN: decl = OMP_CLAUSE_DECL (c); by_ref = use_pointer_for_field (decl, NULL); install_var_field (decl, by_ref, 3, ctx); break; case OMP_CLAUSE_DEFAULT: ctx->default_kind = OMP_CLAUSE_DEFAULT_KIND (c); break; case OMP_CLAUSE_IF: case OMP_CLAUSE_NUM_THREADS: case OMP_CLAUSE_SCHEDULE: if (ctx->outer) scan_omp (&OMP_CLAUSE_OPERAND (c, 0), ctx->outer); break; case OMP_CLAUSE_NOWAIT: case OMP_CLAUSE_ORDERED: case OMP_CLAUSE_COLLAPSE: case OMP_CLAUSE_UNTIED: break; default: gcc_unreachable (); } } for (c = clauses; c; c = OMP_CLAUSE_CHAIN (c)) { switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_LASTPRIVATE: /* Let the corresponding firstprivate clause create the variable. */ if (OMP_CLAUSE_LASTPRIVATE_FIRSTPRIVATE (c)) break; /* FALLTHRU */ case OMP_CLAUSE_PRIVATE: case OMP_CLAUSE_FIRSTPRIVATE: case OMP_CLAUSE_REDUCTION: decl = OMP_CLAUSE_DECL (c); if (is_variable_sized (decl)) install_var_local (decl, ctx); fixup_remapped_decl (decl, ctx, OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE && OMP_CLAUSE_PRIVATE_DEBUG (c)); if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION && OMP_CLAUSE_REDUCTION_PLACEHOLDER (c)) scan_array_reductions = true; break; case OMP_CLAUSE_SHARED: decl = OMP_CLAUSE_DECL (c); if (! is_global_var (maybe_lookup_decl_in_outer_ctx (decl, ctx))) fixup_remapped_decl (decl, ctx, false); break; case OMP_CLAUSE_COPYPRIVATE: case OMP_CLAUSE_COPYIN: case OMP_CLAUSE_DEFAULT: case OMP_CLAUSE_IF: case OMP_CLAUSE_NUM_THREADS: case OMP_CLAUSE_SCHEDULE: case OMP_CLAUSE_NOWAIT: case OMP_CLAUSE_ORDERED: case OMP_CLAUSE_COLLAPSE: case OMP_CLAUSE_UNTIED: break; default: gcc_unreachable (); } } if (scan_array_reductions) for (c = clauses; c; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION && OMP_CLAUSE_REDUCTION_PLACEHOLDER (c)) { scan_omp (&OMP_CLAUSE_REDUCTION_INIT (c), ctx); scan_omp (&OMP_CLAUSE_REDUCTION_MERGE (c), ctx); } else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE && OMP_CLAUSE_LASTPRIVATE_STMT (c)) scan_omp (&OMP_CLAUSE_LASTPRIVATE_STMT (c), ctx); } /* Create a new name for omp child function. Returns an identifier. */ static GTY(()) unsigned int tmp_ompfn_id_num; static tree create_omp_child_function_name (bool task_copy) { tree name = DECL_ASSEMBLER_NAME (current_function_decl); size_t len = IDENTIFIER_LENGTH (name); char *tmp_name, *prefix; const char *suffix; suffix = task_copy ? "_omp_cpyfn" : "_omp_fn"; prefix = alloca (len + strlen (suffix) + 1); memcpy (prefix, IDENTIFIER_POINTER (name), len); strcpy (prefix + len, suffix); #ifndef NO_DOT_IN_LABEL prefix[len] = '.'; #elif !defined NO_DOLLAR_IN_LABEL prefix[len] = '$'; #endif ASM_FORMAT_PRIVATE_NAME (tmp_name, prefix, tmp_ompfn_id_num++); return get_identifier (tmp_name); } /* Build a decl for the omp child function. It'll not contain a body yet, just the bare decl. */ static void create_omp_child_function (omp_context *ctx, bool task_copy) { tree decl, type, name, t; name = create_omp_child_function_name (task_copy); if (task_copy) type = build_function_type_list (void_type_node, ptr_type_node, ptr_type_node, NULL_TREE); else type = build_function_type_list (void_type_node, ptr_type_node, NULL_TREE); decl = build_decl (FUNCTION_DECL, name, type); decl = lang_hooks.decls.pushdecl (decl); if (!task_copy) ctx->cb.dst_fn = decl; else OMP_TASK_COPYFN (ctx->stmt) = decl; TREE_STATIC (decl) = 1; TREE_USED (decl) = 1; DECL_ARTIFICIAL (decl) = 1; DECL_IGNORED_P (decl) = 0; TREE_PUBLIC (decl) = 0; DECL_UNINLINABLE (decl) = 1; DECL_EXTERNAL (decl) = 0; DECL_CONTEXT (decl) = NULL_TREE; DECL_INITIAL (decl) = make_node (BLOCK); t = build_decl (RESULT_DECL, NULL_TREE, void_type_node); DECL_ARTIFICIAL (t) = 1; DECL_IGNORED_P (t) = 1; DECL_RESULT (decl) = t; t = build_decl (PARM_DECL, get_identifier (".omp_data_i"), ptr_type_node); DECL_ARTIFICIAL (t) = 1; DECL_ARG_TYPE (t) = ptr_type_node; DECL_CONTEXT (t) = current_function_decl; TREE_USED (t) = 1; DECL_ARGUMENTS (decl) = t; if (!task_copy) ctx->receiver_decl = t; else { t = build_decl (PARM_DECL, get_identifier (".omp_data_o"), ptr_type_node); DECL_ARTIFICIAL (t) = 1; DECL_ARG_TYPE (t) = ptr_type_node; DECL_CONTEXT (t) = current_function_decl; TREE_USED (t) = 1; TREE_CHAIN (t) = DECL_ARGUMENTS (decl); DECL_ARGUMENTS (decl) = t; } /* Allocate memory for the function structure. The call to allocate_struct_function clobbers CFUN, so we need to restore it afterward. */ allocate_struct_function (decl); DECL_SOURCE_LOCATION (decl) = EXPR_LOCATION (ctx->stmt); cfun->function_end_locus = EXPR_LOCATION (ctx->stmt); cfun = ctx->cb.src_cfun; } /* Scan an OpenMP parallel directive. */ static void scan_omp_parallel (tree *stmt_p, omp_context *outer_ctx) { omp_context *ctx; tree name; /* Ignore parallel directives with empty bodies, unless there are copyin clauses. */ if (optimize > 0 && empty_body_p (OMP_PARALLEL_BODY (*stmt_p)) && find_omp_clause (OMP_CLAUSES (*stmt_p), OMP_CLAUSE_COPYIN) == NULL) { *stmt_p = build_empty_stmt (); return; } ctx = new_omp_context (*stmt_p, outer_ctx); if (taskreg_nesting_level > 1) ctx->is_nested = true; ctx->field_map = splay_tree_new (splay_tree_compare_pointers, 0, 0); ctx->default_kind = OMP_CLAUSE_DEFAULT_SHARED; ctx->record_type = lang_hooks.types.make_type (RECORD_TYPE); name = create_tmp_var_name (".omp_data_s"); name = build_decl (TYPE_DECL, name, ctx->record_type); TYPE_NAME (ctx->record_type) = name; create_omp_child_function (ctx, false); OMP_PARALLEL_FN (*stmt_p) = ctx->cb.dst_fn; scan_sharing_clauses (OMP_PARALLEL_CLAUSES (*stmt_p), ctx); scan_omp (&OMP_PARALLEL_BODY (*stmt_p), ctx); if (TYPE_FIELDS (ctx->record_type) == NULL) ctx->record_type = ctx->receiver_decl = NULL; else { layout_type (ctx->record_type); fixup_child_record_type (ctx); } } /* Scan an OpenMP task directive. */ static void scan_omp_task (tree *stmt_p, omp_context *outer_ctx) { omp_context *ctx; tree name; /* Ignore task directives with empty bodies. */ if (optimize > 0 && empty_body_p (OMP_TASK_BODY (*stmt_p))) { *stmt_p = build_empty_stmt (); return; } ctx = new_omp_context (*stmt_p, outer_ctx); if (taskreg_nesting_level > 1) ctx->is_nested = true; ctx->field_map = splay_tree_new (splay_tree_compare_pointers, 0, 0); ctx->default_kind = OMP_CLAUSE_DEFAULT_SHARED; ctx->record_type = lang_hooks.types.make_type (RECORD_TYPE); name = create_tmp_var_name (".omp_data_s"); name = build_decl (TYPE_DECL, name, ctx->record_type); TYPE_NAME (ctx->record_type) = name; create_omp_child_function (ctx, false); OMP_TASK_FN (*stmt_p) = ctx->cb.dst_fn; scan_sharing_clauses (OMP_TASK_CLAUSES (*stmt_p), ctx); if (ctx->srecord_type) { name = create_tmp_var_name (".omp_data_a"); name = build_decl (TYPE_DECL, name, ctx->srecord_type); TYPE_NAME (ctx->srecord_type) = name; create_omp_child_function (ctx, true); } scan_omp (&OMP_TASK_BODY (*stmt_p), ctx); if (TYPE_FIELDS (ctx->record_type) == NULL) { ctx->record_type = ctx->receiver_decl = NULL; OMP_TASK_ARG_SIZE (*stmt_p) = build_int_cst (long_integer_type_node, 0); OMP_TASK_ARG_ALIGN (*stmt_p) = build_int_cst (long_integer_type_node, 1); } else { tree *p, vla_fields = NULL_TREE, *q = &vla_fields; /* Move VLA fields to the end. */ p = &TYPE_FIELDS (ctx->record_type); while (*p) if (!TYPE_SIZE_UNIT (TREE_TYPE (*p)) || ! TREE_CONSTANT (TYPE_SIZE_UNIT (TREE_TYPE (*p)))) { *q = *p; *p = TREE_CHAIN (*p); TREE_CHAIN (*q) = NULL_TREE; q = &TREE_CHAIN (*q); } else p = &TREE_CHAIN (*p); *p = vla_fields; layout_type (ctx->record_type); fixup_child_record_type (ctx); if (ctx->srecord_type) layout_type (ctx->srecord_type); OMP_TASK_ARG_SIZE (*stmt_p) = fold_convert (long_integer_type_node, TYPE_SIZE_UNIT (ctx->record_type)); OMP_TASK_ARG_ALIGN (*stmt_p) = build_int_cst (long_integer_type_node, TYPE_ALIGN_UNIT (ctx->record_type)); } } /* Scan an OpenMP loop directive. */ static void scan_omp_for (tree *stmt_p, omp_context *outer_ctx) { omp_context *ctx; tree stmt; int i; stmt = *stmt_p; ctx = new_omp_context (stmt, outer_ctx); scan_sharing_clauses (OMP_FOR_CLAUSES (stmt), ctx); scan_omp (&OMP_FOR_PRE_BODY (stmt), ctx); for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (stmt)); i++) { scan_omp (&TREE_VEC_ELT (OMP_FOR_INIT (stmt), i), ctx); scan_omp (&TREE_VEC_ELT (OMP_FOR_COND (stmt), i), ctx); scan_omp (&TREE_VEC_ELT (OMP_FOR_INCR (stmt), i), ctx); } scan_omp (&OMP_FOR_BODY (stmt), ctx); } /* Scan an OpenMP sections directive. */ static void scan_omp_sections (tree *stmt_p, omp_context *outer_ctx) { tree stmt; omp_context *ctx; stmt = *stmt_p; ctx = new_omp_context (stmt, outer_ctx); scan_sharing_clauses (OMP_SECTIONS_CLAUSES (stmt), ctx); scan_omp (&OMP_SECTIONS_BODY (stmt), ctx); } /* Scan an OpenMP single directive. */ static void scan_omp_single (tree *stmt_p, omp_context *outer_ctx) { tree stmt = *stmt_p; omp_context *ctx; tree name; ctx = new_omp_context (stmt, outer_ctx); ctx->field_map = splay_tree_new (splay_tree_compare_pointers, 0, 0); ctx->record_type = lang_hooks.types.make_type (RECORD_TYPE); name = create_tmp_var_name (".omp_copy_s"); name = build_decl (TYPE_DECL, name, ctx->record_type); TYPE_NAME (ctx->record_type) = name; scan_sharing_clauses (OMP_SINGLE_CLAUSES (stmt), ctx); scan_omp (&OMP_SINGLE_BODY (stmt), ctx); if (TYPE_FIELDS (ctx->record_type) == NULL) ctx->record_type = NULL; else layout_type (ctx->record_type); } /* Check OpenMP nesting restrictions. */ static void check_omp_nesting_restrictions (tree t, omp_context *ctx) { switch (TREE_CODE (t)) { case OMP_FOR: case OMP_SECTIONS: case OMP_SINGLE: case CALL_EXPR: for (; ctx != NULL; ctx = ctx->outer) switch (TREE_CODE (ctx->stmt)) { case OMP_FOR: case OMP_SECTIONS: case OMP_SINGLE: case OMP_ORDERED: case OMP_MASTER: case OMP_TASK: if (TREE_CODE (t) == CALL_EXPR) { warning (0, "barrier region may not be closely nested inside " "of work-sharing, critical, ordered, master or " "explicit task region"); return; } warning (0, "work-sharing region may not be closely nested inside " "of work-sharing, critical, ordered or master or explicit " "task region"); return; case OMP_PARALLEL: return; default: break; } break; case OMP_MASTER: for (; ctx != NULL; ctx = ctx->outer) switch (TREE_CODE (ctx->stmt)) { case OMP_FOR: case OMP_SECTIONS: case OMP_SINGLE: warning (0, "master region may not be closely nested inside " "of work-sharing or explicit task region"); return; case OMP_PARALLEL: return; default: break; } break; case OMP_ORDERED: for (; ctx != NULL; ctx = ctx->outer) switch (TREE_CODE (ctx->stmt)) { case OMP_CRITICAL: case OMP_TASK: warning (0, "ordered region may not be closely nested inside " "of critical or explicit task region"); return; case OMP_FOR: if (find_omp_clause (OMP_CLAUSES (ctx->stmt), OMP_CLAUSE_ORDERED) == NULL) warning (0, "ordered region must be closely nested inside " "a loop region with an ordered clause"); return; case OMP_PARALLEL: return; default: break; } break; case OMP_CRITICAL: for (; ctx != NULL; ctx = ctx->outer) if (TREE_CODE (ctx->stmt) == OMP_CRITICAL && OMP_CRITICAL_NAME (t) == OMP_CRITICAL_NAME (ctx->stmt)) { warning (0, "critical region may not be nested inside a critical " "region with the same name"); return; } break; default: break; } } /* Callback for walk_stmts used to scan for OpenMP directives at TP. */ static tree scan_omp_1 (tree *tp, int *walk_subtrees, void *data) { struct walk_stmt_info *wi = data; omp_context *ctx = wi->info; tree t = *tp; if (EXPR_HAS_LOCATION (t)) input_location = EXPR_LOCATION (t); /* Check the OpenMP nesting restrictions. */ if (ctx != NULL) { if (OMP_DIRECTIVE_P (t)) check_omp_nesting_restrictions (t, ctx); else if (TREE_CODE (t) == CALL_EXPR) { tree fndecl = get_callee_fndecl (t); if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_GOMP_BARRIER) check_omp_nesting_restrictions (t, ctx); } } *walk_subtrees = 0; switch (TREE_CODE (t)) { case OMP_PARALLEL: taskreg_nesting_level++; scan_omp_parallel (tp, ctx); taskreg_nesting_level--; break; case OMP_TASK: taskreg_nesting_level++; scan_omp_task (tp, ctx); taskreg_nesting_level--; break; case OMP_FOR: scan_omp_for (tp, ctx); break; case OMP_SECTIONS: scan_omp_sections (tp, ctx); break; case OMP_SINGLE: scan_omp_single (tp, ctx); break; case OMP_SECTION: case OMP_MASTER: case OMP_ORDERED: case OMP_CRITICAL: ctx = new_omp_context (*tp, ctx); scan_omp (&OMP_BODY (*tp), ctx); break; case BIND_EXPR: { tree var; *walk_subtrees = 1; for (var = BIND_EXPR_VARS (t); var ; var = TREE_CHAIN (var)) insert_decl_map (&ctx->cb, var, var); } break; case VAR_DECL: case PARM_DECL: case LABEL_DECL: case RESULT_DECL: if (ctx) *tp = remap_decl (t, &ctx->cb); break; default: if (ctx && TYPE_P (t)) *tp = remap_type (t, &ctx->cb); else if (!DECL_P (t)) *walk_subtrees = 1; break; } return NULL_TREE; } /* Scan all the statements starting at STMT_P. CTX contains context information about the OpenMP directives and clauses found during the scan. */ static void scan_omp (tree *stmt_p, omp_context *ctx) { location_t saved_location; struct walk_stmt_info wi; memset (&wi, 0, sizeof (wi)); wi.callback = scan_omp_1; wi.info = ctx; wi.want_bind_expr = (ctx != NULL); wi.want_locations = true; saved_location = input_location; walk_stmts (&wi, stmt_p); input_location = saved_location; } /* Re-gimplification and code generation routines. */ /* Build a call to GOMP_barrier. */ static void build_omp_barrier (tree *stmt_list) { tree t; t = built_in_decls[BUILT_IN_GOMP_BARRIER]; t = build_function_call_expr (t, NULL); gimplify_and_add (t, stmt_list); } /* If a context was created for STMT when it was scanned, return it. */ static omp_context * maybe_lookup_ctx (tree stmt) { splay_tree_node n; n = splay_tree_lookup (all_contexts, (splay_tree_key) stmt); return n ? (omp_context *) n->value : NULL; } /* Find the mapping for DECL in CTX or the immediately enclosing context that has a mapping for DECL. If CTX is a nested parallel directive, we may have to use the decl mappings created in CTX's parent context. Suppose that we have the following parallel nesting (variable UIDs showed for clarity): iD.1562 = 0; #omp parallel shared(iD.1562) -> outer parallel iD.1562 = iD.1562 + 1; #omp parallel shared (iD.1562) -> inner parallel iD.1562 = iD.1562 - 1; Each parallel structure will create a distinct .omp_data_s structure for copying iD.1562 in/out of the directive: outer parallel .omp_data_s.1.i -> iD.1562 inner parallel .omp_data_s.2.i -> iD.1562 A shared variable mapping will produce a copy-out operation before the parallel directive and a copy-in operation after it. So, in this case we would have: iD.1562 = 0; .omp_data_o.1.i = iD.1562; #omp parallel shared(iD.1562) -> outer parallel .omp_data_i.1 = &.omp_data_o.1 .omp_data_i.1->i = .omp_data_i.1->i + 1; .omp_data_o.2.i = iD.1562; -> ** #omp parallel shared(iD.1562) -> inner parallel .omp_data_i.2 = &.omp_data_o.2 .omp_data_i.2->i = .omp_data_i.2->i - 1; ** This is a problem. The symbol iD.1562 cannot be referenced inside the body of the outer parallel region. But since we are emitting this copy operation while expanding the inner parallel directive, we need to access the CTX structure of the outer parallel directive to get the correct mapping: .omp_data_o.2.i = .omp_data_i.1->i Since there may be other workshare or parallel directives enclosing the parallel directive, it may be necessary to walk up the context parent chain. This is not a problem in general because nested parallelism happens only rarely. */ static tree lookup_decl_in_outer_ctx (tree decl, omp_context *ctx) { tree t; omp_context *up; gcc_assert (ctx->is_nested); for (up = ctx->outer, t = NULL; up && t == NULL; up = up->outer) t = maybe_lookup_decl (decl, up); gcc_assert (t); return t; } /* Similar to lookup_decl_in_outer_ctx, but return DECL if not found in outer contexts. */ static tree maybe_lookup_decl_in_outer_ctx (tree decl, omp_context *ctx) { tree t = NULL; omp_context *up; if (ctx->is_nested) for (up = ctx->outer, t = NULL; up && t == NULL; up = up->outer) t = maybe_lookup_decl (decl, up); return t ? t : decl; } /* Construct the initialization value for reduction CLAUSE. */ tree omp_reduction_init (tree clause, tree type) { switch (OMP_CLAUSE_REDUCTION_CODE (clause)) { case PLUS_EXPR: case MINUS_EXPR: case BIT_IOR_EXPR: case BIT_XOR_EXPR: case TRUTH_OR_EXPR: case TRUTH_ORIF_EXPR: case TRUTH_XOR_EXPR: case NE_EXPR: return fold_convert (type, integer_zero_node); case MULT_EXPR: case TRUTH_AND_EXPR: case TRUTH_ANDIF_EXPR: case EQ_EXPR: return fold_convert (type, integer_one_node); case BIT_AND_EXPR: return fold_convert (type, integer_minus_one_node); case MAX_EXPR: if (SCALAR_FLOAT_TYPE_P (type)) { REAL_VALUE_TYPE max, min; if (HONOR_INFINITIES (TYPE_MODE (type))) { real_inf (&max); real_arithmetic (&min, NEGATE_EXPR, &max, NULL); } else real_maxval (&min, 1, TYPE_MODE (type)); return build_real (type, min); } else { gcc_assert (INTEGRAL_TYPE_P (type)); return TYPE_MIN_VALUE (type); } case MIN_EXPR: if (SCALAR_FLOAT_TYPE_P (type)) { REAL_VALUE_TYPE max; if (HONOR_INFINITIES (TYPE_MODE (type))) real_inf (&max); else real_maxval (&max, 0, TYPE_MODE (type)); return build_real (type, max); } else { gcc_assert (INTEGRAL_TYPE_P (type)); return TYPE_MAX_VALUE (type); } default: gcc_unreachable (); } } /* Generate code to implement the input clauses, FIRSTPRIVATE and COPYIN, from the receiver (aka child) side and initializers for REFERENCE_TYPE private variables. Initialization statements go in ILIST, while calls to destructors go in DLIST. */ static void lower_rec_input_clauses (tree clauses, tree *ilist, tree *dlist, omp_context *ctx) { tree_stmt_iterator diter; tree c, dtor, copyin_seq, x, args, ptr; bool copyin_by_ref = false; bool lastprivate_firstprivate = false; int pass; *dlist = alloc_stmt_list (); diter = tsi_start (*dlist); copyin_seq = NULL; /* Do all the fixed sized types in the first pass, and the variable sized types in the second pass. This makes sure that the scalar arguments to the variable sized types are processed before we use them in the variable sized operations. */ for (pass = 0; pass < 2; ++pass) { for (c = clauses; c ; c = OMP_CLAUSE_CHAIN (c)) { enum omp_clause_code c_kind = OMP_CLAUSE_CODE (c); tree var, new_var; bool by_ref; switch (c_kind) { case OMP_CLAUSE_PRIVATE: if (OMP_CLAUSE_PRIVATE_DEBUG (c)) continue; break; case OMP_CLAUSE_SHARED: if (maybe_lookup_decl (OMP_CLAUSE_DECL (c), ctx) == NULL) { gcc_assert (is_global_var (OMP_CLAUSE_DECL (c))); continue; } case OMP_CLAUSE_FIRSTPRIVATE: case OMP_CLAUSE_COPYIN: case OMP_CLAUSE_REDUCTION: break; case OMP_CLAUSE_LASTPRIVATE: if (OMP_CLAUSE_LASTPRIVATE_FIRSTPRIVATE (c)) { lastprivate_firstprivate = true; if (pass != 0) continue; } break; default: continue; } new_var = var = OMP_CLAUSE_DECL (c); if (c_kind != OMP_CLAUSE_COPYIN) new_var = lookup_decl (var, ctx); if (c_kind == OMP_CLAUSE_SHARED || c_kind == OMP_CLAUSE_COPYIN) { if (pass != 0) continue; } else if (is_variable_sized (var)) { /* For variable sized types, we need to allocate the actual storage here. Call alloca and store the result in the pointer decl that we created elsewhere. */ if (pass == 0) continue; if (c_kind != OMP_CLAUSE_FIRSTPRIVATE || !is_task_ctx (ctx)) { ptr = DECL_VALUE_EXPR (new_var); gcc_assert (TREE_CODE (ptr) == INDIRECT_REF); ptr = TREE_OPERAND (ptr, 0); gcc_assert (DECL_P (ptr)); x = TYPE_SIZE_UNIT (TREE_TYPE (new_var)); args = tree_cons (NULL, x, NULL); x = built_in_decls[BUILT_IN_ALLOCA]; x = build_function_call_expr (x, args); x = fold_convert (TREE_TYPE (ptr), x); x = build2 (MODIFY_EXPR, void_type_node, ptr, x); gimplify_and_add (x, ilist); } } else if (is_reference (var)) { /* For references that are being privatized for Fortran, allocate new backing storage for the new pointer variable. This allows us to avoid changing all the code that expects a pointer to something that expects a direct variable. Note that this doesn't apply to C++, since reference types are disallowed in data sharing clauses there, except for NRV optimized return values. */ if (pass == 0) continue; x = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (new_var))); if (c_kind == OMP_CLAUSE_FIRSTPRIVATE && is_task_ctx (ctx)) { x = build_receiver_ref (var, false, ctx); x = build_fold_addr_expr (x); } else if (TREE_CONSTANT (x)) { const char *name = NULL; if (DECL_NAME (var)) name = IDENTIFIER_POINTER (DECL_NAME (new_var)); x = create_tmp_var_raw (TREE_TYPE (TREE_TYPE (new_var)), name); gimple_add_tmp_var (x); x = build_fold_addr_expr_with_type (x, TREE_TYPE (new_var)); } else { args = tree_cons (NULL, x, NULL); x = built_in_decls[BUILT_IN_ALLOCA]; x = build_function_call_expr (x, args); x = fold_convert (TREE_TYPE (new_var), x); } x = build2 (MODIFY_EXPR, void_type_node, new_var, x); gimplify_and_add (x, ilist); new_var = build_fold_indirect_ref (new_var); } else if (c_kind == OMP_CLAUSE_REDUCTION && OMP_CLAUSE_REDUCTION_PLACEHOLDER (c)) { if (pass == 0) continue; } else if (pass != 0) continue; switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_SHARED: /* Shared global vars are just accessed directly. */ if (is_global_var (new_var)) break; /* Set up the DECL_VALUE_EXPR for shared variables now. This needs to be delayed until after fixup_child_record_type so that we get the correct type during the dereference. */ by_ref = use_pointer_for_field (var, ctx); x = build_receiver_ref (var, by_ref, ctx); SET_DECL_VALUE_EXPR (new_var, x); DECL_HAS_VALUE_EXPR_P (new_var) = 1; /* ??? If VAR is not passed by reference, and the variable hasn't been initialized yet, then we'll get a warning for the store into the omp_data_s structure. Ideally, we'd be able to notice this and not store anything at all, but we're generating code too early. Suppress the warning. */ if (!by_ref) TREE_NO_WARNING (var) = 1; break; case OMP_CLAUSE_LASTPRIVATE: if (OMP_CLAUSE_LASTPRIVATE_FIRSTPRIVATE (c)) break; /* FALLTHRU */ case OMP_CLAUSE_PRIVATE: if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_PRIVATE) x = build_outer_var_ref (var, ctx); else if (OMP_CLAUSE_PRIVATE_OUTER_REF (c)) { if (is_task_ctx (ctx)) x = build_receiver_ref (var, false, ctx); else x = build_outer_var_ref (var, ctx); } else x = NULL; x = lang_hooks.decls.omp_clause_default_ctor (c, new_var, x); if (x) gimplify_and_add (x, ilist); /* FALLTHRU */ do_dtor: x = lang_hooks.decls.omp_clause_dtor (c, new_var); if (x) { dtor = x; gimplify_stmt (&dtor); tsi_link_before (&diter, dtor, TSI_SAME_STMT); } break; case OMP_CLAUSE_FIRSTPRIVATE: if (is_task_ctx (ctx)) { if (is_reference (var) || is_variable_sized (var)) goto do_dtor; else if (is_global_var (maybe_lookup_decl_in_outer_ctx (var, ctx)) || use_pointer_for_field (var, NULL)) { x = build_receiver_ref (var, false, ctx); SET_DECL_VALUE_EXPR (new_var, x); DECL_HAS_VALUE_EXPR_P (new_var) = 1; goto do_dtor; } } x = build_outer_var_ref (var, ctx); x = lang_hooks.decls.omp_clause_copy_ctor (c, new_var, x); gimplify_and_add (x, ilist); goto do_dtor; break; case OMP_CLAUSE_COPYIN: by_ref = use_pointer_for_field (var, NULL); x = build_receiver_ref (var, by_ref, ctx); x = lang_hooks.decls.omp_clause_assign_op (c, new_var, x); append_to_statement_list (x, &copyin_seq); copyin_by_ref |= by_ref; break; case OMP_CLAUSE_REDUCTION: if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (c)) { tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (c); x = build_outer_var_ref (var, ctx); if (is_reference (var)) x = build_fold_addr_expr (x); SET_DECL_VALUE_EXPR (placeholder, x); DECL_HAS_VALUE_EXPR_P (placeholder) = 1; gimplify_and_add (OMP_CLAUSE_REDUCTION_INIT (c), ilist); OMP_CLAUSE_REDUCTION_INIT (c) = NULL; DECL_HAS_VALUE_EXPR_P (placeholder) = 0; } else { x = omp_reduction_init (c, TREE_TYPE (new_var)); gcc_assert (TREE_CODE (TREE_TYPE (new_var)) != ARRAY_TYPE); x = build2 (MODIFY_EXPR, void_type_node, new_var, x); gimplify_and_add (x, ilist); } break; default: gcc_unreachable (); } } } /* The copyin sequence is not to be executed by the main thread, since that would result in self-copies. Perhaps not visible to scalars, but it certainly is to C++ operator=. */ if (copyin_seq) { x = built_in_decls[BUILT_IN_OMP_GET_THREAD_NUM]; x = build_function_call_expr (x, NULL); x = build2 (NE_EXPR, boolean_type_node, x, build_int_cst (TREE_TYPE (x), 0)); x = build3 (COND_EXPR, void_type_node, x, copyin_seq, NULL); gimplify_and_add (x, ilist); } /* If any copyin variable is passed by reference, we must ensure the master thread doesn't modify it before it is copied over in all threads. Similarly for variables in both firstprivate and lastprivate clauses we need to ensure the lastprivate copying happens after firstprivate copying in all threads. */ if (copyin_by_ref || lastprivate_firstprivate) build_omp_barrier (ilist); } /* Generate code to implement the LASTPRIVATE clauses. This is used for both parallel and workshare constructs. PREDICATE may be NULL if it's always true. */ static void lower_lastprivate_clauses (tree clauses, tree predicate, tree *stmt_list, omp_context *ctx) { tree sub_list, x, c; bool par_clauses = false; /* Early exit if there are no lastprivate clauses. */ clauses = find_omp_clause (clauses, OMP_CLAUSE_LASTPRIVATE); if (clauses == NULL) { /* If this was a workshare clause, see if it had been combined with its parallel. In that case, look for the clauses on the parallel statement itself. */ if (is_parallel_ctx (ctx)) return; ctx = ctx->outer; if (ctx == NULL || !is_parallel_ctx (ctx)) return; clauses = find_omp_clause (OMP_PARALLEL_CLAUSES (ctx->stmt), OMP_CLAUSE_LASTPRIVATE); if (clauses == NULL) return; par_clauses = true; } sub_list = alloc_stmt_list (); for (c = clauses; c ;) { tree var, new_var; if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE) { var = OMP_CLAUSE_DECL (c); new_var = lookup_decl (var, ctx); if (OMP_CLAUSE_LASTPRIVATE_STMT (c)) gimplify_and_add (OMP_CLAUSE_LASTPRIVATE_STMT (c), &sub_list); OMP_CLAUSE_LASTPRIVATE_STMT (c) = NULL; x = build_outer_var_ref (var, ctx); if (is_reference (var)) new_var = build_fold_indirect_ref (new_var); x = lang_hooks.decls.omp_clause_assign_op (c, x, new_var); append_to_statement_list (x, &sub_list); } c = OMP_CLAUSE_CHAIN (c); if (c == NULL && !par_clauses) { /* If this was a workshare clause, see if it had been combined with its parallel. In that case, continue looking for the clauses also on the parallel statement itself. */ if (is_parallel_ctx (ctx)) break; ctx = ctx->outer; if (ctx == NULL || !is_parallel_ctx (ctx)) break; c = find_omp_clause (OMP_PARALLEL_CLAUSES (ctx->stmt), OMP_CLAUSE_LASTPRIVATE); par_clauses = true; } } if (predicate) x = build3 (COND_EXPR, void_type_node, predicate, sub_list, NULL); else x = sub_list; gimplify_and_add (x, stmt_list); } /* Generate code to implement the REDUCTION clauses. */ static void lower_reduction_clauses (tree clauses, tree *stmt_list, omp_context *ctx) { tree sub_list = NULL, x, c; int count = 0; /* First see if there is exactly one reduction clause. Use OMP_ATOMIC update in that case, otherwise use a lock. */ for (c = clauses; c && count < 2; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION) { if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (c)) { /* Never use OMP_ATOMIC for array reductions. */ count = -1; break; } count++; } if (count == 0) return; for (c = clauses; c ; c = OMP_CLAUSE_CHAIN (c)) { tree var, ref, new_var; enum tree_code code; if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_REDUCTION) continue; var = OMP_CLAUSE_DECL (c); new_var = lookup_decl (var, ctx); if (is_reference (var)) new_var = build_fold_indirect_ref (new_var); ref = build_outer_var_ref (var, ctx); code = OMP_CLAUSE_REDUCTION_CODE (c); /* reduction(-:var) sums up the partial results, so it acts identically to reduction(+:var). */ if (code == MINUS_EXPR) code = PLUS_EXPR; if (count == 1) { tree addr = build_fold_addr_expr (ref); addr = save_expr (addr); ref = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (addr)), addr); x = fold_build2 (code, TREE_TYPE (ref), ref, new_var); x = build2 (OMP_ATOMIC, void_type_node, addr, x); gimplify_and_add (x, stmt_list); return; } if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (c)) { tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (c); if (is_reference (var)) ref = build_fold_addr_expr (ref); SET_DECL_VALUE_EXPR (placeholder, ref); DECL_HAS_VALUE_EXPR_P (placeholder) = 1; gimplify_and_add (OMP_CLAUSE_REDUCTION_MERGE (c), &sub_list); OMP_CLAUSE_REDUCTION_MERGE (c) = NULL; OMP_CLAUSE_REDUCTION_PLACEHOLDER (c) = NULL; } else { x = build2 (code, TREE_TYPE (ref), ref, new_var); ref = build_outer_var_ref (var, ctx); x = build2 (MODIFY_EXPR, void_type_node, ref, x); append_to_statement_list (x, &sub_list); } } x = built_in_decls[BUILT_IN_GOMP_ATOMIC_START]; x = build_function_call_expr (x, NULL); gimplify_and_add (x, stmt_list); gimplify_and_add (sub_list, stmt_list); x = built_in_decls[BUILT_IN_GOMP_ATOMIC_END]; x = build_function_call_expr (x, NULL); gimplify_and_add (x, stmt_list); } /* Generate code to implement the COPYPRIVATE clauses. */ static void lower_copyprivate_clauses (tree clauses, tree *slist, tree *rlist, omp_context *ctx) { tree c; for (c = clauses; c ; c = OMP_CLAUSE_CHAIN (c)) { tree var, ref, x; bool by_ref; if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_COPYPRIVATE) continue; var = OMP_CLAUSE_DECL (c); by_ref = use_pointer_for_field (var, NULL); ref = build_sender_ref (var, ctx); x = (ctx->is_nested) ? lookup_decl_in_outer_ctx (var, ctx) : var; x = by_ref ? build_fold_addr_expr (x) : x; x = build2 (MODIFY_EXPR, void_type_node, ref, x); gimplify_and_add (x, slist); ref = build_receiver_ref (var, by_ref, ctx); if (is_reference (var)) { ref = build_fold_indirect_ref (ref); var = build_fold_indirect_ref (var); } x = lang_hooks.decls.omp_clause_assign_op (c, var, ref); gimplify_and_add (x, rlist); } } /* Generate code to implement the clauses, FIRSTPRIVATE, COPYIN, LASTPRIVATE, and REDUCTION from the sender (aka parent) side. */ static void lower_send_clauses (tree clauses, tree *ilist, tree *olist, omp_context *ctx) { tree c; for (c = clauses; c ; c = OMP_CLAUSE_CHAIN (c)) { tree val, ref, x, var; bool by_ref, do_in = false, do_out = false; switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_PRIVATE: if (OMP_CLAUSE_PRIVATE_OUTER_REF (c)) break; continue; case OMP_CLAUSE_FIRSTPRIVATE: case OMP_CLAUSE_COPYIN: case OMP_CLAUSE_LASTPRIVATE: case OMP_CLAUSE_REDUCTION: break; default: continue; } var = val = OMP_CLAUSE_DECL (c); if (ctx->is_nested) var = maybe_lookup_decl_in_outer_ctx (val, ctx); if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_COPYIN && is_global_var (var)) continue; if (is_variable_sized (val)) continue; by_ref = use_pointer_for_field (val, NULL); switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_PRIVATE: case OMP_CLAUSE_FIRSTPRIVATE: case OMP_CLAUSE_COPYIN: do_in = true; break; case OMP_CLAUSE_LASTPRIVATE: if (by_ref || is_reference (val)) { if (OMP_CLAUSE_LASTPRIVATE_FIRSTPRIVATE (c)) continue; do_in = true; } else { do_out = true; if (lang_hooks.decls.omp_private_outer_ref (val)) do_in = true; } break; case OMP_CLAUSE_REDUCTION: do_in = true; do_out = !(by_ref || is_reference (val)); break; default: gcc_unreachable (); } if (do_in) { ref = build_sender_ref (val, ctx); x = by_ref ? build_fold_addr_expr (var) : var; x = build2 (MODIFY_EXPR, void_type_node, ref, x); gimplify_and_add (x, ilist); if (is_task_ctx (ctx)) DECL_ABSTRACT_ORIGIN (TREE_OPERAND (ref, 1)) = NULL; } if (do_out) { ref = build_sender_ref (val, ctx); x = build2 (MODIFY_EXPR, void_type_node, var, ref); gimplify_and_add (x, olist); } } } /* Generate code to implement SHARED from the sender (aka parent) side. This is trickier, since OMP_PARALLEL_CLAUSES doesn't list things that got automatically shared. */ static void lower_send_shared_vars (tree *ilist, tree *olist, omp_context *ctx) { tree var, ovar, nvar, f, x, record_type; if (ctx->record_type == NULL) return; record_type = ctx->srecord_type ? ctx->srecord_type : ctx->record_type; for (f = TYPE_FIELDS (record_type); f ; f = TREE_CHAIN (f)) { ovar = DECL_ABSTRACT_ORIGIN (f); nvar = maybe_lookup_decl (ovar, ctx); if (!nvar || !DECL_HAS_VALUE_EXPR_P (nvar)) continue; var = ovar; /* If CTX is a nested parallel directive. Find the immediately enclosing parallel or workshare construct that contains a mapping for OVAR. */ if (ctx->is_nested) var = lookup_decl_in_outer_ctx (ovar, ctx); if (use_pointer_for_field (ovar, ctx)) { x = build_sender_ref (ovar, ctx); var = build_fold_addr_expr (var); x = build2 (MODIFY_EXPR, void_type_node, x, var); gimplify_and_add (x, ilist); } else { x = build_sender_ref (ovar, ctx); x = build2 (MODIFY_EXPR, void_type_node, x, var); gimplify_and_add (x, ilist); if (!TREE_READONLY (var)) { x = build_sender_ref (ovar, ctx); x = build2 (MODIFY_EXPR, void_type_node, var, x); gimplify_and_add (x, olist); } } } } /* Build the function calls to GOMP_parallel_start etc to actually generate the parallel operation. REGION is the parallel region being expanded. BB is the block where to insert the code. WS_ARGS will be set if this is a call to a combined parallel+workshare construct, it contains the list of additional arguments needed by the workshare construct. */ static void expand_parallel_call (struct omp_region *region, basic_block bb, tree entry_stmt, tree ws_args) { tree t, args, val, cond, c, list, clauses; block_stmt_iterator si; int start_ix; clauses = OMP_PARALLEL_CLAUSES (entry_stmt); push_gimplify_context (); /* Determine what flavor of GOMP_parallel_start we will be emitting. */ start_ix = BUILT_IN_GOMP_PARALLEL_START; if (is_combined_parallel (region)) { switch (region->inner->type) { case OMP_FOR: gcc_assert (region->inner->sched_kind != OMP_CLAUSE_SCHEDULE_AUTO); start_ix = BUILT_IN_GOMP_PARALLEL_LOOP_STATIC_START + (region->inner->sched_kind == OMP_CLAUSE_SCHEDULE_RUNTIME ? 3 : region->inner->sched_kind); break; case OMP_SECTIONS: start_ix = BUILT_IN_GOMP_PARALLEL_SECTIONS_START; break; default: gcc_unreachable (); } } /* By default, the value of NUM_THREADS is zero (selected at run time) and there is no conditional. */ cond = NULL_TREE; val = build_int_cst (unsigned_type_node, 0); c = find_omp_clause (clauses, OMP_CLAUSE_IF); if (c) cond = OMP_CLAUSE_IF_EXPR (c); c = find_omp_clause (clauses, OMP_CLAUSE_NUM_THREADS); if (c) val = OMP_CLAUSE_NUM_THREADS_EXPR (c); /* Ensure 'val' is of the correct type. */ val = fold_convert (unsigned_type_node, val); /* If we found the clause 'if (cond)', build either (cond != 0) or (cond ? val : 1u). */ if (cond) { block_stmt_iterator si; cond = gimple_boolify (cond); if (integer_zerop (val)) val = build2 (EQ_EXPR, unsigned_type_node, cond, build_int_cst (TREE_TYPE (cond), 0)); else { basic_block cond_bb, then_bb, else_bb; edge e; tree t, then_lab, else_lab, tmp; tmp = create_tmp_var (TREE_TYPE (val), NULL); e = split_block (bb, NULL); cond_bb = e->src; bb = e->dest; remove_edge (e); then_bb = create_empty_bb (cond_bb); else_bb = create_empty_bb (then_bb); then_lab = create_artificial_label (); else_lab = create_artificial_label (); t = build3 (COND_EXPR, void_type_node, cond, build_and_jump (&then_lab), build_and_jump (&else_lab)); si = bsi_start (cond_bb); bsi_insert_after (&si, t, BSI_CONTINUE_LINKING); si = bsi_start (then_bb); t = build1 (LABEL_EXPR, void_type_node, then_lab); bsi_insert_after (&si, t, BSI_CONTINUE_LINKING); t = build2 (MODIFY_EXPR, void_type_node, tmp, val); bsi_insert_after (&si, t, BSI_CONTINUE_LINKING); si = bsi_start (else_bb); t = build1 (LABEL_EXPR, void_type_node, else_lab); bsi_insert_after (&si, t, BSI_CONTINUE_LINKING); t = build2 (MODIFY_EXPR, void_type_node, tmp, build_int_cst (unsigned_type_node, 1)); bsi_insert_after (&si, t, BSI_CONTINUE_LINKING); make_edge (cond_bb, then_bb, EDGE_TRUE_VALUE); make_edge (cond_bb, else_bb, EDGE_FALSE_VALUE); make_edge (then_bb, bb, EDGE_FALLTHRU); make_edge (else_bb, bb, EDGE_FALLTHRU); val = tmp; } list = NULL_TREE; val = get_formal_tmp_var (val, &list); si = bsi_start (bb); bsi_insert_after (&si, list, BSI_CONTINUE_LINKING); } list = NULL_TREE; args = tree_cons (NULL, val, NULL); t = OMP_PARALLEL_DATA_ARG (entry_stmt); if (t == NULL) t = null_pointer_node; else t = build_fold_addr_expr (t); args = tree_cons (NULL, t, args); t = build_fold_addr_expr (OMP_PARALLEL_FN (entry_stmt)); args = tree_cons (NULL, t, args); if (ws_args) args = chainon (args, ws_args); t = built_in_decls[start_ix]; t = build_function_call_expr (t, args); gimplify_and_add (t, &list); t = OMP_PARALLEL_DATA_ARG (entry_stmt); if (t == NULL) t = null_pointer_node; else t = build_fold_addr_expr (t); args = tree_cons (NULL, t, NULL); t = build_function_call_expr (OMP_PARALLEL_FN (entry_stmt), args); gimplify_and_add (t, &list); t = built_in_decls[BUILT_IN_GOMP_PARALLEL_END]; t = build_function_call_expr (t, NULL); gimplify_and_add (t, &list); si = bsi_last (bb); bsi_insert_after (&si, list, BSI_CONTINUE_LINKING); pop_gimplify_context (NULL_TREE); } static void maybe_catch_exception (tree *stmt_p); /* Build the function call to GOMP_task to actually generate the task operation. BB is the block where to insert the code. */ static void expand_task_call (basic_block bb, tree entry_stmt) { tree t, t1, t2, t3, flags, cond, c, clauses; block_stmt_iterator si; tree args; clauses = OMP_TASK_CLAUSES (entry_stmt); c = find_omp_clause (clauses, OMP_CLAUSE_IF); if (c) cond = gimple_boolify (OMP_CLAUSE_IF_EXPR (c)); else cond = boolean_true_node; c = find_omp_clause (clauses, OMP_CLAUSE_UNTIED); flags = build_int_cst (unsigned_type_node, (c ? 1 : 0)); si = bsi_last (bb); t = OMP_TASK_DATA_ARG (entry_stmt); if (t == NULL) t2 = null_pointer_node; else t2 = build_fold_addr_expr (t); t1 = build_fold_addr_expr (OMP_TASK_FN (entry_stmt)); t = OMP_TASK_COPYFN (entry_stmt); if (t == NULL) t3 = null_pointer_node; else t3 = build_fold_addr_expr (t); args = tree_cons (NULL, flags, NULL); args = tree_cons (NULL, cond, args); args = tree_cons (NULL, OMP_TASK_ARG_ALIGN (entry_stmt), args); args = tree_cons (NULL, OMP_TASK_ARG_SIZE (entry_stmt), args); args = tree_cons (NULL, t3, NULL); args = tree_cons (NULL, t2, NULL); args = tree_cons (NULL, t1, NULL); t = build_function_call_expr (built_in_decls[BUILT_IN_GOMP_TASK], args); force_gimple_operand_bsi (&si, t, true, NULL_TREE); } /* If exceptions are enabled, wrap *STMT_P in a MUST_NOT_THROW catch handler. This prevents programs from violating the structured block semantics with throws. */ static void maybe_catch_exception (tree *stmt_p) { tree f, t; if (!flag_exceptions) return; if (lang_protect_cleanup_actions) t = lang_protect_cleanup_actions (); else { t = built_in_decls[BUILT_IN_TRAP]; t = build_function_call_expr (t, NULL); } f = build2 (EH_FILTER_EXPR, void_type_node, NULL, NULL); EH_FILTER_MUST_NOT_THROW (f) = 1; gimplify_and_add (t, &EH_FILTER_FAILURE (f)); t = build2 (TRY_CATCH_EXPR, void_type_node, *stmt_p, NULL); append_to_statement_list (f, &TREE_OPERAND (t, 1)); *stmt_p = NULL; append_to_statement_list (t, stmt_p); } /* Chain all the DECLs in LIST by their TREE_CHAIN fields. */ static tree list2chain (tree list) { tree t; for (t = list; t; t = TREE_CHAIN (t)) { tree var = TREE_VALUE (t); if (TREE_CHAIN (t)) TREE_CHAIN (var) = TREE_VALUE (TREE_CHAIN (t)); else TREE_CHAIN (var) = NULL_TREE; } return list ? TREE_VALUE (list) : NULL_TREE; } /* Remove barriers in REGION->EXIT's block. Note that this is only valid for OMP_PARALLEL regions. Since the end of a parallel region is an implicit barrier, any workshare inside the OMP_PARALLEL that left a barrier at the end of the OMP_PARALLEL region can now be removed. */ static void remove_exit_barrier (struct omp_region *region) { block_stmt_iterator si; basic_block exit_bb; edge_iterator ei; edge e; tree t; exit_bb = region->exit; /* If the parallel region doesn't return, we don't have REGION->EXIT block at all. */ if (! exit_bb) return; /* The last insn in the block will be the parallel's OMP_RETURN. The workshare's OMP_RETURN will be in a preceding block. The kinds of statements that can appear in between are extremely limited -- no memory operations at all. Here, we allow nothing at all, so the only thing we allow to precede this OMP_RETURN is a label. */ si = bsi_last (exit_bb); gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_RETURN); bsi_prev (&si); if (!bsi_end_p (si) && TREE_CODE (bsi_stmt (si)) != LABEL_EXPR) return; FOR_EACH_EDGE (e, ei, exit_bb->preds) { si = bsi_last (e->src); if (bsi_end_p (si)) continue; t = bsi_stmt (si); if (TREE_CODE (t) == OMP_RETURN) OMP_RETURN_NOWAIT (t) = 1; } } static void remove_exit_barriers (struct omp_region *region) { if (region->type == OMP_PARALLEL) remove_exit_barrier (region); if (region->inner) { region = region->inner; remove_exit_barriers (region); while (region->next) { region = region->next; remove_exit_barriers (region); } } } /* Expand the OpenMP parallel or task directive starting at REGION. */ static void expand_omp_taskreg (struct omp_region *region) { basic_block entry_bb, exit_bb, new_bb; struct function *child_cfun, *saved_cfun; tree child_fn, block, t, ws_args; block_stmt_iterator si; tree entry_stmt; edge e; bool do_cleanup_cfg = false; entry_stmt = last_stmt (region->entry); child_fn = OMP_TASKREG_FN (entry_stmt); child_cfun = DECL_STRUCT_FUNCTION (child_fn); saved_cfun = cfun; entry_bb = region->entry; exit_bb = region->exit; if (is_combined_parallel (region)) ws_args = region->ws_args; else ws_args = NULL_TREE; if (child_cfun->cfg) { /* Due to inlining, it may happen that we have already outlined the region, in which case all we need to do is make the sub-graph unreachable and emit the parallel call. */ edge entry_succ_e, exit_succ_e; block_stmt_iterator si; entry_succ_e = single_succ_edge (entry_bb); si = bsi_last (entry_bb); gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_PARALLEL || TREE_CODE (bsi_stmt (si)) == OMP_TASK); bsi_remove (&si, true); new_bb = entry_bb; remove_edge (entry_succ_e); if (exit_bb) { exit_succ_e = single_succ_edge (exit_bb); make_edge (new_bb, exit_succ_e->dest, EDGE_FALLTHRU); } do_cleanup_cfg = true; } else { /* If the parallel region needs data sent from the parent function, then the very first statement (except possible tree profile counter updates) of the parallel body is a copy assignment .OMP_DATA_I = &.OMP_DATA_O. Since &.OMP_DATA_O is passed as an argument to the child function, we need to replace it with the argument as seen by the child function. In most cases, this will end up being the identity assignment .OMP_DATA_I = .OMP_DATA_I. However, if the parallel body had a function call that has been inlined, the original PARM_DECL .OMP_DATA_I may have been converted into a different local variable. In which case, we need to keep the assignment. */ if (OMP_TASKREG_DATA_ARG (entry_stmt)) { basic_block entry_succ_bb = single_succ (entry_bb); block_stmt_iterator si; for (si = bsi_start (entry_succ_bb); ; bsi_next (&si)) { tree stmt, arg; gcc_assert (!bsi_end_p (si)); stmt = bsi_stmt (si); if (TREE_CODE (stmt) != MODIFY_EXPR) continue; arg = TREE_OPERAND (stmt, 1); STRIP_NOPS (arg); if (TREE_CODE (arg) == ADDR_EXPR && TREE_OPERAND (arg, 0) == OMP_TASKREG_DATA_ARG (entry_stmt)) { if (TREE_OPERAND (stmt, 0) == DECL_ARGUMENTS (child_fn)) bsi_remove (&si, true); else TREE_OPERAND (stmt, 1) = DECL_ARGUMENTS (child_fn); break; } } } /* Declare local variables needed in CHILD_CFUN. */ block = DECL_INITIAL (child_fn); BLOCK_VARS (block) = list2chain (child_cfun->unexpanded_var_list); DECL_SAVED_TREE (child_fn) = single_succ (entry_bb)->stmt_list; /* Reset DECL_CONTEXT on locals and function arguments. */ for (t = BLOCK_VARS (block); t; t = TREE_CHAIN (t)) DECL_CONTEXT (t) = child_fn; for (t = DECL_ARGUMENTS (child_fn); t; t = TREE_CHAIN (t)) DECL_CONTEXT (t) = child_fn; /* Split ENTRY_BB at OMP_PARALLEL or OMP_TASK, so that it can be moved to the child function. */ si = bsi_last (entry_bb); t = bsi_stmt (si); gcc_assert (t && (TREE_CODE (t) == OMP_PARALLEL || TREE_CODE (t) == OMP_TASK)); bsi_remove (&si, true); e = split_block (entry_bb, t); entry_bb = e->dest; single_succ_edge (entry_bb)->flags = EDGE_FALLTHRU; /* Move the parallel region into CHILD_CFUN. We need to reset dominance information because the expansion of the inner regions has invalidated it. */ free_dominance_info (CDI_DOMINATORS); new_bb = move_sese_region_to_fn (child_cfun, entry_bb, exit_bb); if (exit_bb) single_succ_edge (new_bb)->flags = EDGE_FALLTHRU; cgraph_add_new_function (child_fn); /* Convert OMP_RETURN into a RETURN_EXPR. */ if (exit_bb) { si = bsi_last (exit_bb); gcc_assert (!bsi_end_p (si) && TREE_CODE (bsi_stmt (si)) == OMP_RETURN); t = build1 (RETURN_EXPR, void_type_node, NULL); bsi_insert_after (&si, t, BSI_SAME_STMT); bsi_remove (&si, true); } } /* Emit a library call to launch the children threads. */ if (TREE_CODE (entry_stmt) == OMP_PARALLEL) expand_parallel_call (region, new_bb, entry_stmt, ws_args); else expand_task_call (new_bb, entry_stmt); if (do_cleanup_cfg) { /* Clean up the unreachable sub-graph we created above. */ free_dominance_info (CDI_DOMINATORS); free_dominance_info (CDI_POST_DOMINATORS); cleanup_tree_cfg (); } } /* A subroutine of expand_omp_for. Generate code for a parallel loop with any schedule. Given parameters: for (V = N1; V cond N2; V += STEP) BODY; where COND is "<" or ">", we generate pseudocode more = GOMP_loop_foo_start (N1, N2, STEP, CHUNK, &istart0, &iend0); if (more) goto L0; else goto L3; L0: V = istart0; iend = iend0; L1: BODY; V += STEP; if (V cond iend) goto L1; else goto L2; L2: if (GOMP_loop_foo_next (&istart0, &iend0)) goto L0; else goto L3; L3: If this is a combined omp parallel loop, instead of the call to GOMP_loop_foo_start, we call GOMP_loop_foo_next. For collapsed loops, given parameters: collapse(3) for (V1 = N11; V1 cond1 N12; V1 += STEP1) for (V2 = N21; V2 cond2 N22; V2 += STEP2) for (V3 = N31; V3 cond3 N32; V3 += STEP3) BODY; we generate pseudocode if (cond3 is <) adj = STEP3 - 1; else adj = STEP3 + 1; count3 = (adj + N32 - N31) / STEP3; if (cond2 is <) adj = STEP2 - 1; else adj = STEP2 + 1; count2 = (adj + N22 - N21) / STEP2; if (cond1 is <) adj = STEP1 - 1; else adj = STEP1 + 1; count1 = (adj + N12 - N11) / STEP1; count = count1 * count2 * count3; more = GOMP_loop_foo_start (0, count, 1, CHUNK, &istart0, &iend0); if (more) goto L0; else goto L3; L0: V = istart0; T = V; V3 = N31 + (T % count3) * STEP3; T = T / count3; V2 = N21 + (T % count2) * STEP2; T = T / count2; V1 = N11 + T * STEP1; iend = iend0; L1: BODY; V += 1; if (V < iend) goto L10; else goto L2; L10: V3 += STEP3; if (V3 cond3 N32) goto L1; else goto L11; L11: V3 = N31; V2 += STEP2; if (V2 cond2 N22) goto L1; else goto L12; L12: V2 = N21; V1 += STEP1; goto L1; L2: if (GOMP_loop_foo_next (&istart0, &iend0)) goto L0; else goto L3; L3: */ static void expand_omp_for_generic (struct omp_region *region, struct omp_for_data *fd, enum built_in_function start_fn, enum built_in_function next_fn) { tree l0, l1, l2 = NULL, l3 = NULL; tree type, istart0, iend0, iend; tree t, args, list; basic_block entry_bb, cont_bb, exit_bb, l0_bb, l1_bb; basic_block l2_bb = NULL, l3_bb = NULL; block_stmt_iterator si; bool in_combined_parallel = is_combined_parallel (region); type = TREE_TYPE (fd->loop.v); istart0 = create_tmp_var (long_integer_type_node, ".istart0"); iend0 = create_tmp_var (long_integer_type_node, ".iend0"); iend = create_tmp_var (type, NULL); TREE_ADDRESSABLE (istart0) = 1; TREE_ADDRESSABLE (iend0) = 1; gcc_assert ((region->cont != NULL) ^ (region->exit == NULL)); entry_bb = region->entry; l0_bb = create_empty_bb (entry_bb); l1_bb = single_succ (entry_bb); l0 = tree_block_label (l0_bb); l1 = tree_block_label (l1_bb); cont_bb = region->cont; exit_bb = region->exit; if (cont_bb) { l2_bb = create_empty_bb (cont_bb); l3_bb = single_succ (cont_bb); l2 = tree_block_label (l2_bb); l3 = tree_block_label (l3_bb); } si = bsi_last (entry_bb); gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_FOR); if (!in_combined_parallel) { /* If this is not a combined parallel loop, emit a call to GOMP_loop_foo_start in ENTRY_BB. */ list = alloc_stmt_list (); t = build_fold_addr_expr (iend0); args = tree_cons (NULL, t, NULL); t = build_fold_addr_expr (istart0); args = tree_cons (NULL, t, args); if (fd->chunk_size) { t = fold_convert (long_integer_type_node, fd->chunk_size); args = tree_cons (NULL, t, args); } t = fold_convert (long_integer_type_node, fd->loop.step); args = tree_cons (NULL, t, args); t = fold_convert (long_integer_type_node, fd->loop.n2); args = tree_cons (NULL, t, args); t = fold_convert (long_integer_type_node, fd->loop.n1); args = tree_cons (NULL, t, args); t = build_function_call_expr (built_in_decls[start_fn], args); //t = get_formal_tmp_var (t, &list); if (cont_bb) { t = build3 (COND_EXPR, void_type_node, t, build_and_jump (&l0), build_and_jump (&l3)); append_to_statement_list (t, &list); } bsi_insert_after (&si, list, BSI_SAME_STMT); } bsi_remove (&si, true); /* Iteration setup for sequential loop goes in L0_BB. */ list = alloc_stmt_list (); t = fold_convert (type, istart0); t = build2 (MODIFY_EXPR, void_type_node, fd->loop.v, t); gimplify_and_add (t, &list); t = fold_convert (type, iend0); t = build2 (MODIFY_EXPR, void_type_node, iend, t); gimplify_and_add (t, &list); si = bsi_start (l0_bb); bsi_insert_after (&si, list, BSI_CONTINUE_LINKING); /* Handle the rare case where BODY doesn't ever return. */ if (cont_bb == NULL) { remove_edge (single_succ_edge (entry_bb)); make_edge (entry_bb, l0_bb, EDGE_FALLTHRU); make_edge (l0_bb, l1_bb, EDGE_FALLTHRU); return; } /* Code to control the increment and predicate for the sequential loop goes in the first half of EXIT_BB (we split EXIT_BB so that we can inherit all the edges going out of the loop body). */ list = alloc_stmt_list (); t = build2 (PLUS_EXPR, type, fd->loop.v, fd->loop.step); t = build2 (MODIFY_EXPR, void_type_node, fd->loop.v, t); gimplify_and_add (t, &list); t = build2 (fd->loop.cond_code, boolean_type_node, fd->loop.v, iend); t = get_formal_tmp_var (t, &list); t = build3 (COND_EXPR, void_type_node, t, build_and_jump (&l1), build_and_jump (&l2)); append_to_statement_list (t, &list); si = bsi_last (cont_bb); bsi_insert_after (&si, list, BSI_SAME_STMT); gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_CONTINUE); bsi_remove (&si, true); /* Emit code to get the next parallel iteration in L2_BB. */ list = alloc_stmt_list (); t = build_fold_addr_expr (iend0); args = tree_cons (NULL, t, NULL); t = build_fold_addr_expr (istart0); args = tree_cons (NULL, t, args); t = build_function_call_expr (built_in_decls[next_fn], args); t = get_formal_tmp_var (t, &list); t = build3 (COND_EXPR, void_type_node, t, build_and_jump (&l0), build_and_jump (&l3)); append_to_statement_list (t, &list); si = bsi_start (l2_bb); bsi_insert_after (&si, list, BSI_CONTINUE_LINKING); /* Add the loop cleanup function. */ si = bsi_last (exit_bb); if (OMP_RETURN_NOWAIT (bsi_stmt (si))) t = built_in_decls[BUILT_IN_GOMP_LOOP_END_NOWAIT]; else t = built_in_decls[BUILT_IN_GOMP_LOOP_END]; t = build_function_call_expr (t, NULL); bsi_insert_after (&si, t, BSI_SAME_STMT); bsi_remove (&si, true); /* Connect the new blocks. */ remove_edge (single_succ_edge (entry_bb)); if (in_combined_parallel) make_edge (entry_bb, l2_bb, EDGE_FALLTHRU); else { make_edge (entry_bb, l0_bb, EDGE_TRUE_VALUE); make_edge (entry_bb, l3_bb, EDGE_FALSE_VALUE); } make_edge (l0_bb, l1_bb, EDGE_FALLTHRU); remove_edge (single_succ_edge (cont_bb)); make_edge (cont_bb, l1_bb, EDGE_TRUE_VALUE); make_edge (cont_bb, l2_bb, EDGE_FALSE_VALUE); make_edge (l2_bb, l0_bb, EDGE_TRUE_VALUE); make_edge (l2_bb, l3_bb, EDGE_FALSE_VALUE); } /* A subroutine of expand_omp_for. Generate code for a parallel loop with static schedule and no specified chunk size. Given parameters: for (V = N1; V cond N2; V += STEP) BODY; where COND is "<" or ">", we generate pseudocode if (cond is <) adj = STEP - 1; else adj = STEP + 1; if ((__typeof (V)) -1 > 0 && cond is >) n = -(adj + N2 - N1) / -STEP; else n = (adj + N2 - N1) / STEP; q = n / nthreads; q += (q * nthreads != n); s0 = q * threadid; e0 = min(s0 + q, n); if (s0 >= e0) goto L2; else goto L0; L0: V = s0 * STEP + N1; e = e0 * STEP + N1; L1: BODY; V += STEP; if (V cond e) goto L1; L2: */ static void expand_omp_for_static_nochunk (struct omp_region *region, struct omp_for_data *fd) { tree l0, l1, l2, n, q, s0, e0, e, t, nthreads, threadid; tree type, list; basic_block entry_bb, exit_bb, seq_start_bb, body_bb, cont_bb; basic_block fin_bb; block_stmt_iterator si; type = TREE_TYPE (fd->loop.v); entry_bb = region->entry; seq_start_bb = create_empty_bb (entry_bb); body_bb = single_succ (entry_bb); cont_bb = region->cont; fin_bb = single_succ (cont_bb); exit_bb = region->exit; l0 = tree_block_label (seq_start_bb); l1 = tree_block_label (body_bb); l2 = tree_block_label (fin_bb); /* Iteration space partitioning goes in ENTRY_BB. */ list = alloc_stmt_list (); t = built_in_decls[BUILT_IN_OMP_GET_NUM_THREADS]; t = build_function_call_expr (t, NULL); t = fold_convert (type, t); nthreads = get_formal_tmp_var (t, &list); t = built_in_decls[BUILT_IN_OMP_GET_THREAD_NUM]; t = build_function_call_expr (t, NULL); t = fold_convert (type, t); threadid = get_formal_tmp_var (t, &list); fd->loop.n1 = fold_convert (type, fd->loop.n1); if (!is_gimple_val (fd->loop.n1)) fd->loop.n1 = get_formal_tmp_var (fd->loop.n1, &list); fd->loop.n2 = fold_convert (type, fd->loop.n2); if (!is_gimple_val (fd->loop.n2)) fd->loop.n2 = get_formal_tmp_var (fd->loop.n2, &list); fd->loop.step = fold_convert (type, fd->loop.step); if (!is_gimple_val (fd->loop.step)) fd->loop.step = get_formal_tmp_var (fd->loop.step, &list); t = build_int_cst (type, (fd->loop.cond_code == LT_EXPR ? -1 : 1)); t = fold_build2 (PLUS_EXPR, type, fd->loop.step, t); t = fold_build2 (PLUS_EXPR, type, t, fd->loop.n2); t = fold_build2 (MINUS_EXPR, type, t, fd->loop.n1); t = fold_build2 (TRUNC_DIV_EXPR, type, t, fd->loop.step); t = fold_convert (type, t); if (is_gimple_val (t)) n = t; else n = get_formal_tmp_var (t, &list); t = build2 (TRUNC_DIV_EXPR, type, n, nthreads); q = get_formal_tmp_var (t, &list); t = build2 (MULT_EXPR, type, q, nthreads); t = build2 (NE_EXPR, type, t, n); t = build2 (PLUS_EXPR, type, q, t); q = get_formal_tmp_var (t, &list); t = build2 (MULT_EXPR, type, q, threadid); s0 = get_formal_tmp_var (t, &list); t = build2 (PLUS_EXPR, type, s0, q); t = build2 (MIN_EXPR, type, t, n); e0 = get_formal_tmp_var (t, &list); t = build2 (GE_EXPR, boolean_type_node, s0, e0); t = build3 (COND_EXPR, void_type_node, t, build_and_jump (&l2), build_and_jump (&l0)); append_to_statement_list (t, &list); si = bsi_last (entry_bb); gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_FOR); bsi_insert_after (&si, list, BSI_SAME_STMT); bsi_remove (&si, true); /* Setup code for sequential iteration goes in SEQ_START_BB. */ list = alloc_stmt_list (); t = fold_convert (type, s0); t = build2 (MULT_EXPR, type, t, fd->loop.step); t = build2 (PLUS_EXPR, type, t, fd->loop.n1); t = build2 (MODIFY_EXPR, void_type_node, fd->loop.v, t); gimplify_and_add (t, &list); t = fold_convert (type, e0); t = build2 (MULT_EXPR, type, t, fd->loop.step); t = build2 (PLUS_EXPR, type, t, fd->loop.n1); e = get_formal_tmp_var (t, &list); si = bsi_start (seq_start_bb); bsi_insert_after (&si, list, BSI_CONTINUE_LINKING); /* The code controlling the sequential loop replaces the OMP_CONTINUE. */ list = alloc_stmt_list (); t = build2 (PLUS_EXPR, type, fd->loop.v, fd->loop.step); t = build2 (MODIFY_EXPR, void_type_node, fd->loop.v, t); gimplify_and_add (t, &list); t = build2 (fd->loop.cond_code, boolean_type_node, fd->loop.v, e); t = get_formal_tmp_var (t, &list); t = build3 (COND_EXPR, void_type_node, t, build_and_jump (&l1), build_and_jump (&l2)); append_to_statement_list (t, &list); si = bsi_last (cont_bb); gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_CONTINUE); bsi_insert_after (&si, list, BSI_SAME_STMT); bsi_remove (&si, true); /* Replace the OMP_RETURN with a barrier, or nothing. */ si = bsi_last (exit_bb); if (!OMP_RETURN_NOWAIT (bsi_stmt (si))) { list = alloc_stmt_list (); build_omp_barrier (&list); bsi_insert_after (&si, list, BSI_SAME_STMT); } bsi_remove (&si, true); /* Connect all the blocks. */ make_edge (seq_start_bb, body_bb, EDGE_FALLTHRU); remove_edge (single_succ_edge (entry_bb)); make_edge (entry_bb, fin_bb, EDGE_TRUE_VALUE); make_edge (entry_bb, seq_start_bb, EDGE_FALSE_VALUE); make_edge (cont_bb, body_bb, EDGE_TRUE_VALUE); find_edge (cont_bb, fin_bb)->flags = EDGE_FALSE_VALUE; } /* A subroutine of expand_omp_for. Generate code for a parallel loop with static schedule and a specified chunk size. Given parameters: for (V = N1; V cond N2; V += STEP) BODY; where COND is "<" or ">", we generate pseudocode if (cond is <) adj = STEP - 1; else adj = STEP + 1; if ((__typeof (V)) -1 > 0 && cond is >) n = -(adj + N2 - N1) / -STEP; else n = (adj + N2 - N1) / STEP; trip = 0; L0: s0 = (trip * nthreads + threadid) * CHUNK; e0 = min(s0 + CHUNK, n); if (s0 < n) goto L1; else goto L4; L1: V = s0 * STEP + N1; e = e0 * STEP + N1; L2: BODY; V += STEP; if (V cond e) goto L2; else goto L3; L3: trip += 1; goto L0; L4: */ static void expand_omp_for_static_chunk (struct omp_region *region, struct omp_for_data *fd) { tree l0, l1, l2, l3, l4, n, s0, e0, e, t; tree trip, nthreads, threadid; tree type; basic_block entry_bb, exit_bb, body_bb, seq_start_bb, iter_part_bb; basic_block trip_update_bb, cont_bb, fin_bb; tree list; block_stmt_iterator si; type = TREE_TYPE (fd->loop.v); entry_bb = region->entry; iter_part_bb = create_empty_bb (entry_bb); seq_start_bb = create_empty_bb (iter_part_bb); body_bb = single_succ (entry_bb); cont_bb = region->cont; trip_update_bb = create_empty_bb (cont_bb); fin_bb = single_succ (cont_bb); exit_bb = region->exit; l0 = tree_block_label (iter_part_bb); l1 = tree_block_label (seq_start_bb); l2 = tree_block_label (body_bb); l3 = tree_block_label (trip_update_bb); l4 = tree_block_label (fin_bb); /* Trip and adjustment setup goes in ENTRY_BB. */ list = alloc_stmt_list (); t = built_in_decls[BUILT_IN_OMP_GET_NUM_THREADS]; t = build_function_call_expr (t, NULL); t = fold_convert (type, t); nthreads = get_formal_tmp_var (t, &list); t = built_in_decls[BUILT_IN_OMP_GET_THREAD_NUM]; t = build_function_call_expr (t, NULL); t = fold_convert (type, t); threadid = get_formal_tmp_var (t, &list); fd->loop.n1 = fold_convert (type, fd->loop.n1); if (!is_gimple_val (fd->loop.n1)) fd->loop.n1 = get_formal_tmp_var (fd->loop.n1, &list); fd->loop.n2 = fold_convert (type, fd->loop.n2); if (!is_gimple_val (fd->loop.n2)) fd->loop.n2 = get_formal_tmp_var (fd->loop.n2, &list); fd->loop.step = fold_convert (type, fd->loop.step); if (!is_gimple_val (fd->loop.step)) fd->loop.step = get_formal_tmp_var (fd->loop.step, &list); fd->chunk_size = fold_convert (type, fd->chunk_size); if (!is_gimple_val (fd->chunk_size)) fd->chunk_size = get_formal_tmp_var (fd->chunk_size, &list); t = build_int_cst (type, (fd->loop.cond_code == LT_EXPR ? -1 : 1)); t = fold_build2 (PLUS_EXPR, type, fd->loop.step, t); t = fold_build2 (PLUS_EXPR, type, t, fd->loop.n2); t = fold_build2 (MINUS_EXPR, type, t, fd->loop.n1); t = fold_build2 (TRUNC_DIV_EXPR, type, t, fd->loop.step); t = fold_convert (type, t); if (is_gimple_val (t)) n = t; else n = get_formal_tmp_var (t, &list); t = build_int_cst (type, 0); trip = get_initialized_tmp_var (t, &list, NULL); si = bsi_last (entry_bb); gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_FOR); bsi_insert_after (&si, list, BSI_SAME_STMT); bsi_remove (&si, true); /* Iteration space partitioning goes in ITER_PART_BB. */ list = alloc_stmt_list (); t = build2 (MULT_EXPR, type, trip, nthreads); t = build2 (PLUS_EXPR, type, t, threadid); t = build2 (MULT_EXPR, type, t, fd->chunk_size); s0 = get_formal_tmp_var (t, &list); t = build2 (PLUS_EXPR, type, s0, fd->chunk_size); t = build2 (MIN_EXPR, type, t, n); e0 = get_formal_tmp_var (t, &list); t = build2 (LT_EXPR, boolean_type_node, s0, n); t = build3 (COND_EXPR, void_type_node, t, build_and_jump (&l1), build_and_jump (&l4)); append_to_statement_list (t, &list); si = bsi_start (iter_part_bb); bsi_insert_after (&si, list, BSI_CONTINUE_LINKING); /* Setup code for sequential iteration goes in SEQ_START_BB. */ list = alloc_stmt_list (); t = fold_convert (type, s0); t = build2 (MULT_EXPR, type, t, fd->loop.step); t = build2 (PLUS_EXPR, type, t, fd->loop.n1); t = build2 (MODIFY_EXPR, void_type_node, fd->loop.v, t); gimplify_and_add (t, &list); t = fold_convert (type, e0); t = build2 (MULT_EXPR, type, t, fd->loop.step); t = build2 (PLUS_EXPR, type, t, fd->loop.n1); e = get_formal_tmp_var (t, &list); si = bsi_start (seq_start_bb); bsi_insert_after (&si, list, BSI_CONTINUE_LINKING); /* The code controlling the sequential loop goes in CONT_BB, replacing the OMP_CONTINUE. */ list = alloc_stmt_list (); t = build2 (PLUS_EXPR, type, fd->loop.v, fd->loop.step); t = build2 (MODIFY_EXPR, void_type_node, fd->loop.v, t); gimplify_and_add (t, &list); t = build2 (fd->loop.cond_code, boolean_type_node, fd->loop.v, e); t = get_formal_tmp_var (t, &list); t = build3 (COND_EXPR, void_type_node, t, build_and_jump (&l2), build_and_jump (&l3)); append_to_statement_list (t, &list); si = bsi_last (cont_bb); gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_CONTINUE); bsi_insert_after (&si, list, BSI_SAME_STMT); bsi_remove (&si, true); /* Trip update code goes into TRIP_UPDATE_BB. */ list = alloc_stmt_list (); t = build_int_cst (type, 1); t = build2 (PLUS_EXPR, type, trip, t); t = build2 (MODIFY_EXPR, void_type_node, trip, t); gimplify_and_add (t, &list); si = bsi_start (trip_update_bb); bsi_insert_after (&si, list, BSI_CONTINUE_LINKING); /* Replace the OMP_RETURN with a barrier, or nothing. */ si = bsi_last (exit_bb); if (!OMP_RETURN_NOWAIT (bsi_stmt (si))) { list = alloc_stmt_list (); build_omp_barrier (&list); bsi_insert_after (&si, list, BSI_SAME_STMT); } bsi_remove (&si, true); /* Connect the new blocks. */ remove_edge (single_succ_edge (entry_bb)); make_edge (entry_bb, iter_part_bb, EDGE_FALLTHRU); make_edge (iter_part_bb, seq_start_bb, EDGE_TRUE_VALUE); make_edge (iter_part_bb, fin_bb, EDGE_FALSE_VALUE); make_edge (seq_start_bb, body_bb, EDGE_FALLTHRU); remove_edge (single_succ_edge (cont_bb)); make_edge (cont_bb, body_bb, EDGE_TRUE_VALUE); make_edge (cont_bb, trip_update_bb, EDGE_FALSE_VALUE); make_edge (trip_update_bb, iter_part_bb, EDGE_FALLTHRU); } /* Expand the OpenMP loop defined by REGION. */ static void expand_omp_for (struct omp_region *region) { struct omp_for_data fd; struct omp_for_data_loop *loops; loops = (struct omp_for_data_loop *) alloca (TREE_VEC_LENGTH (OMP_FOR_INIT (last_stmt (region->entry))) * sizeof (struct omp_for_data_loop)); extract_omp_for_data (last_stmt (region->entry), &fd, loops); region->sched_kind = fd.sched_kind; if (fd.sched_kind == OMP_CLAUSE_SCHEDULE_STATIC && !fd.have_ordered && fd.collapse == 1 && region->cont && region->exit) { if (fd.chunk_size == NULL) expand_omp_for_static_nochunk (region, &fd); else expand_omp_for_static_chunk (region, &fd); } else { int fn_index, start_ix, next_ix; gcc_assert (fd.sched_kind != OMP_CLAUSE_SCHEDULE_AUTO); fn_index = (fd.sched_kind == OMP_CLAUSE_SCHEDULE_RUNTIME) ? 3 : fd.sched_kind; fn_index += fd.have_ordered * 4; start_ix = BUILT_IN_GOMP_LOOP_STATIC_START + fn_index; next_ix = BUILT_IN_GOMP_LOOP_STATIC_NEXT + fn_index; if (fd.iter_type == long_long_unsigned_type_node) { start_ix += BUILT_IN_GOMP_LOOP_ULL_STATIC_START - BUILT_IN_GOMP_LOOP_STATIC_START; next_ix += BUILT_IN_GOMP_LOOP_ULL_STATIC_NEXT - BUILT_IN_GOMP_LOOP_STATIC_NEXT; } expand_omp_for_generic (region, &fd, start_ix, next_ix); } pop_gimplify_context (NULL); } /* Expand code for an OpenMP sections directive. In pseudo code, we generate v = GOMP_sections_start (n); L0: switch (v) { case 0: goto L2; case 1: section 1; goto L1; case 2: ... case n: ... default: abort (); } L1: v = GOMP_sections_next (); goto L0; L2: reduction; If this is a combined parallel sections, replace the call to GOMP_sections_start with 'goto L1'. */ static void expand_omp_sections (struct omp_region *region) { tree label_vec, l0, l1, l2, t, u, v, sections_stmt; unsigned i, len; basic_block entry_bb, exit_bb, l0_bb, l1_bb, l2_bb, default_bb; block_stmt_iterator si; struct omp_region *inner; edge e; entry_bb = region->entry; l0_bb = create_empty_bb (entry_bb); l0 = tree_block_label (l0_bb); gcc_assert ((region->cont != NULL) ^ (region->exit == NULL)); l1_bb = region->cont; if (l1_bb) { l2_bb = single_succ (l1_bb); default_bb = create_empty_bb (l1_bb->prev_bb); l1 = tree_block_label (l1_bb); } else { l2_bb = create_empty_bb (l0_bb); default_bb = l2_bb; l1 = NULL; } l2 = tree_block_label (l2_bb); exit_bb = region->exit; v = create_tmp_var (unsigned_type_node, ".section"); /* We will build a switch() with enough cases for all the OMP_SECTION regions, a '0' case to handle the end of more work and a default case to abort if something goes wrong. */ len = EDGE_COUNT (entry_bb->succs); label_vec = make_tree_vec (len + 2); /* The call to GOMP_sections_start goes in ENTRY_BB, replacing the OMP_SECTIONS statement. */ si = bsi_last (entry_bb); sections_stmt = bsi_stmt (si); gcc_assert (TREE_CODE (sections_stmt) == OMP_SECTIONS); if (!is_combined_parallel (region)) { /* If we are not inside a combined parallel+sections region, call GOMP_sections_start. */ t = build_int_cst (unsigned_type_node, len); t = tree_cons (NULL, t, NULL); u = built_in_decls[BUILT_IN_GOMP_SECTIONS_START]; t = build_function_call_expr (u, t); t = build2 (MODIFY_EXPR, void_type_node, v, t); bsi_insert_after (&si, t, BSI_SAME_STMT); } bsi_remove (&si, true); /* The switch() statement replacing OMP_SECTIONS goes in L0_BB. */ si = bsi_start (l0_bb); t = build3 (SWITCH_EXPR, void_type_node, v, NULL, label_vec); bsi_insert_after (&si, t, BSI_CONTINUE_LINKING); t = build3 (CASE_LABEL_EXPR, void_type_node, build_int_cst (unsigned_type_node, 0), NULL, l2); TREE_VEC_ELT (label_vec, 0) = t; make_edge (l0_bb, l2_bb, 0); /* Convert each OMP_SECTION into a CASE_LABEL_EXPR. */ for (inner = region->inner, i = 1; inner; inner = inner->next, ++i) { basic_block s_entry_bb, s_exit_bb; s_entry_bb = inner->entry; s_exit_bb = inner->exit; t = tree_block_label (s_entry_bb); u = build_int_cst (unsigned_type_node, i); u = build3 (CASE_LABEL_EXPR, void_type_node, u, NULL, t); TREE_VEC_ELT (label_vec, i) = u; si = bsi_last (s_entry_bb); gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_SECTION); gcc_assert (i < len || OMP_SECTION_LAST (bsi_stmt (si))); bsi_remove (&si, true); e = single_pred_edge (s_entry_bb); e->flags = 0; redirect_edge_pred (e, l0_bb); single_succ_edge (s_entry_bb)->flags = EDGE_FALLTHRU; if (s_exit_bb == NULL) continue; si = bsi_last (s_exit_bb); gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_RETURN); bsi_remove (&si, true); single_succ_edge (s_exit_bb)->flags = EDGE_FALLTHRU; } /* Error handling code goes in DEFAULT_BB. */ t = tree_block_label (default_bb); u = build3 (CASE_LABEL_EXPR, void_type_node, NULL, NULL, t); TREE_VEC_ELT (label_vec, len + 1) = u; make_edge (l0_bb, default_bb, 0); si = bsi_start (default_bb); t = built_in_decls[BUILT_IN_TRAP]; t = build_function_call_expr (t, NULL); bsi_insert_after (&si, t, BSI_CONTINUE_LINKING); /* Code to get the next section goes in L1_BB. */ if (l1_bb) { si = bsi_last (l1_bb); gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_CONTINUE); t = built_in_decls[BUILT_IN_GOMP_SECTIONS_NEXT]; t = build_function_call_expr (t, NULL); t = build2 (MODIFY_EXPR, void_type_node, v, t); bsi_insert_after (&si, t, BSI_SAME_STMT); bsi_remove (&si, true); } /* Cleanup function replaces OMP_RETURN in EXIT_BB. */ if (exit_bb) { si = bsi_last (exit_bb); if (OMP_RETURN_NOWAIT (bsi_stmt (si))) t = built_in_decls[BUILT_IN_GOMP_SECTIONS_END_NOWAIT]; else t = built_in_decls[BUILT_IN_GOMP_SECTIONS_END]; t = build_function_call_expr (t, NULL); bsi_insert_after (&si, t, BSI_SAME_STMT); bsi_remove (&si, true); } /* Connect the new blocks. */ if (is_combined_parallel (region)) { /* If this was a combined parallel+sections region, we did not emit a GOMP_sections_start in the entry block, so we just need to jump to L1_BB to get the next section. */ make_edge (entry_bb, l1_bb, EDGE_FALLTHRU); } else make_edge (entry_bb, l0_bb, EDGE_FALLTHRU); if (l1_bb) { e = single_succ_edge (l1_bb); redirect_edge_succ (e, l0_bb); e->flags = EDGE_FALLTHRU; } } /* Expand code for an OpenMP single directive. We've already expanded much of the code, here we simply place the GOMP_barrier call. */ static void expand_omp_single (struct omp_region *region) { basic_block entry_bb, exit_bb; block_stmt_iterator si; bool need_barrier = false; entry_bb = region->entry; exit_bb = region->exit; si = bsi_last (entry_bb); /* The terminal barrier at the end of a GOMP_single_copy sequence cannot be removed. We need to ensure that the thread that entered the single does not exit before the data is copied out by the other threads. */ if (find_omp_clause (OMP_SINGLE_CLAUSES (bsi_stmt (si)), OMP_CLAUSE_COPYPRIVATE)) need_barrier = true; gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_SINGLE); bsi_remove (&si, true); single_succ_edge (entry_bb)->flags = EDGE_FALLTHRU; si = bsi_last (exit_bb); if (!OMP_RETURN_NOWAIT (bsi_stmt (si)) || need_barrier) { tree t = alloc_stmt_list (); build_omp_barrier (&t); bsi_insert_after (&si, t, BSI_SAME_STMT); } bsi_remove (&si, true); single_succ_edge (exit_bb)->flags = EDGE_FALLTHRU; } /* Generic expansion for OpenMP synchronization directives: master, ordered and critical. All we need to do here is remove the entry and exit markers for REGION. */ static void expand_omp_synch (struct omp_region *region) { basic_block entry_bb, exit_bb; block_stmt_iterator si; entry_bb = region->entry; exit_bb = region->exit; si = bsi_last (entry_bb); gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_SINGLE || TREE_CODE (bsi_stmt (si)) == OMP_MASTER || TREE_CODE (bsi_stmt (si)) == OMP_ORDERED || TREE_CODE (bsi_stmt (si)) == OMP_CRITICAL); bsi_remove (&si, true); single_succ_edge (entry_bb)->flags = EDGE_FALLTHRU; if (exit_bb) { si = bsi_last (exit_bb); gcc_assert (TREE_CODE (bsi_stmt (si)) == OMP_RETURN); bsi_remove (&si, true); single_succ_edge (exit_bb)->flags = EDGE_FALLTHRU; } } /* Expand the parallel region tree rooted at REGION. Expansion proceeds in depth-first order. Innermost regions are expanded first. This way, parallel regions that require a new function to be created (e.g., OMP_PARALLEL) can be expanded without having any internal dependencies in their body. */ static void expand_omp (struct omp_region *region) { while (region) { if (region->inner) expand_omp (region->inner); switch (region->type) { case OMP_PARALLEL: expand_omp_taskreg (region); break; case OMP_TASK: expand_omp_taskreg (region); break; case OMP_FOR: expand_omp_for (region); break; case OMP_SECTIONS: expand_omp_sections (region); break; case OMP_SECTION: /* Individual omp sections are handled together with their parent OMP_SECTIONS region. */ break; case OMP_SINGLE: expand_omp_single (region); break; case OMP_MASTER: case OMP_ORDERED: case OMP_CRITICAL: expand_omp_synch (region); break; default: gcc_unreachable (); } region = region->next; } } /* Helper for build_omp_regions. Scan the dominator tree starting at block BB. PARENT is the region that contains BB. */ static void build_omp_regions_1 (basic_block bb, struct omp_region *parent) { block_stmt_iterator si; tree stmt; basic_block son; si = bsi_last (bb); if (!bsi_end_p (si) && OMP_DIRECTIVE_P (bsi_stmt (si))) { struct omp_region *region; enum tree_code code; stmt = bsi_stmt (si); code = TREE_CODE (stmt); if (code == OMP_RETURN) { /* STMT is the return point out of region PARENT. Mark it as the exit point and make PARENT the immediately enclosing region. */ gcc_assert (parent); region = parent; region->exit = bb; parent = parent->outer; /* If REGION is a parallel region, determine whether it is a combined parallel+workshare region. */ if (region->type == OMP_PARALLEL) determine_parallel_type (region); } else if (code == OMP_CONTINUE) { gcc_assert (parent); parent->cont = bb; } else { /* Otherwise, this directive becomes the parent for a new region. */ region = new_omp_region (bb, code, parent); parent = region; } } for (son = first_dom_son (CDI_DOMINATORS, bb); son; son = next_dom_son (CDI_DOMINATORS, son)) build_omp_regions_1 (son, parent); } /* Scan the CFG and build a tree of OMP regions. Return the root of the OMP region tree. */ static void build_omp_regions (void) { gcc_assert (root_omp_region == NULL); calculate_dominance_info (CDI_DOMINATORS); build_omp_regions_1 (ENTRY_BLOCK_PTR, NULL); } /* Main entry point for expanding OMP-GIMPLE into runtime calls. */ static unsigned int execute_expand_omp (void) { #if 0 build_omp_regions (); if (!root_omp_region) return 0; if (dump_file) { fprintf (dump_file, "\nOMP region tree\n\n"); dump_omp_region (dump_file, root_omp_region, 0); fprintf (dump_file, "\n"); } remove_exit_barriers (root_omp_region); expand_omp (root_omp_region); free_dominance_info (CDI_DOMINATORS); free_dominance_info (CDI_POST_DOMINATORS); cleanup_tree_cfg (); free_omp_regions (); #endif return 0; } static bool gate_expand_omp (void) { return flag_openmp != 0 && errorcount == 0; } struct tree_opt_pass pass_expand_omp = { "ompexp", /* name */ gate_expand_omp, /* gate */ execute_expand_omp, /* execute */ NULL, /* sub */ NULL, /* next */ 0, /* static_pass_number */ 0, /* tv_id */ PROP_gimple_any, /* properties_required */ PROP_gimple_lomp, /* properties_provided */ 0, /* properties_destroyed */ 0, /* todo_flags_start */ TODO_dump_func, /* todo_flags_finish */ 0 /* letter */ }; /* Routines to lower OpenMP directives into OMP-GIMPLE. */ /* Lower the OpenMP sections directive in *STMT_P. */ static void lower_omp_sections (tree *stmt_p, omp_context *ctx) { tree new_stmt, stmt, body, bind, block, ilist, olist, new_body; tree t, dlist; tree_stmt_iterator tsi; unsigned i, len; stmt = *stmt_p; push_gimplify_context (); dlist = NULL; ilist = NULL; lower_rec_input_clauses (OMP_SECTIONS_CLAUSES (stmt), &ilist, &dlist, ctx); tsi = tsi_start (OMP_SECTIONS_BODY (stmt)); for (len = 0; !tsi_end_p (tsi); len++, tsi_next (&tsi)) continue; tsi = tsi_start (OMP_SECTIONS_BODY (stmt)); body = alloc_stmt_list (); for (i = 0; i < len; i++, tsi_next (&tsi)) { omp_context *sctx; tree sec_start, sec_end; sec_start = tsi_stmt (tsi); sctx = maybe_lookup_ctx (sec_start); gcc_assert (sctx); append_to_statement_list (sec_start, &body); lower_omp (&OMP_SECTION_BODY (sec_start), sctx); append_to_statement_list (OMP_SECTION_BODY (sec_start), &body); OMP_SECTION_BODY (sec_start) = NULL; if (i == len - 1) { tree l = alloc_stmt_list (); lower_lastprivate_clauses (OMP_SECTIONS_CLAUSES (stmt), NULL, &l, ctx); append_to_statement_list (l, &body); OMP_SECTION_LAST (sec_start) = 1; } sec_end = make_node (OMP_RETURN); append_to_statement_list (sec_end, &body); } block = make_node (BLOCK); bind = build3 (BIND_EXPR, void_type_node, NULL, body, block); olist = NULL_TREE; lower_reduction_clauses (OMP_SECTIONS_CLAUSES (stmt), &olist, ctx); pop_gimplify_context (NULL_TREE); record_vars_into (ctx->block_vars, ctx->cb.dst_fn); new_stmt = build3 (BIND_EXPR, void_type_node, NULL, NULL, NULL); TREE_SIDE_EFFECTS (new_stmt) = 1; new_body = alloc_stmt_list (); append_to_statement_list (ilist, &new_body); append_to_statement_list (stmt, &new_body); append_to_statement_list (bind, &new_body); t = make_node (OMP_CONTINUE); append_to_statement_list (t, &new_body); append_to_statement_list (olist, &new_body); append_to_statement_list (dlist, &new_body); maybe_catch_exception (&new_body); t = make_node (OMP_RETURN); OMP_RETURN_NOWAIT (t) = !!find_omp_clause (OMP_SECTIONS_CLAUSES (stmt), OMP_CLAUSE_NOWAIT); append_to_statement_list (t, &new_body); BIND_EXPR_BODY (new_stmt) = new_body; OMP_SECTIONS_BODY (stmt) = NULL; *stmt_p = new_stmt; } /* A subroutine of lower_omp_single. Expand the simple form of an OMP_SINGLE, without a copyprivate clause: if (GOMP_single_start ()) BODY; [ GOMP_barrier (); ] -> unless 'nowait' is present. FIXME. It may be better to delay expanding the logic of this until pass_expand_omp. The expanded logic may make the job more difficult to a synchronization analysis pass. */ static void lower_omp_single_simple (tree single_stmt, tree *pre_p) { tree t; t = built_in_decls[BUILT_IN_GOMP_SINGLE_START]; t = build_function_call_expr (t, NULL); if (TREE_TYPE (t) != boolean_type_node) t = fold_build2 (NE_EXPR, boolean_type_node, t, build_int_cst (TREE_TYPE (t), 0)); t = build3 (COND_EXPR, void_type_node, t, OMP_SINGLE_BODY (single_stmt), NULL); gimplify_and_add (t, pre_p); } /* A subroutine of lower_omp_single. Expand the simple form of an OMP_SINGLE, with a copyprivate clause: #pragma omp single copyprivate (a, b, c) Create a new structure to hold copies of 'a', 'b' and 'c' and emit: { if ((copyout_p = GOMP_single_copy_start ()) == NULL) { BODY; copyout.a = a; copyout.b = b; copyout.c = c; GOMP_single_copy_end (&copyout); } else { a = copyout_p->a; b = copyout_p->b; c = copyout_p->c; } GOMP_barrier (); } FIXME. It may be better to delay expanding the logic of this until pass_expand_omp. The expanded logic may make the job more difficult to a synchronization analysis pass. */ static void lower_omp_single_copy (tree single_stmt, tree *pre_p, omp_context *ctx) { tree ptr_type, t, args, l0, l1, l2, copyin_seq; ctx->sender_decl = create_tmp_var (ctx->record_type, ".omp_copy_o"); ptr_type = build_pointer_type (ctx->record_type); ctx->receiver_decl = create_tmp_var (ptr_type, ".omp_copy_i"); l0 = create_artificial_label (); l1 = create_artificial_label (); l2 = create_artificial_label (); t = built_in_decls[BUILT_IN_GOMP_SINGLE_COPY_START]; t = build_function_call_expr (t, NULL); t = fold_convert (ptr_type, t); t = build2 (MODIFY_EXPR, void_type_node, ctx->receiver_decl, t); gimplify_and_add (t, pre_p); t = build2 (EQ_EXPR, boolean_type_node, ctx->receiver_decl, build_int_cst (ptr_type, 0)); t = build3 (COND_EXPR, void_type_node, t, build_and_jump (&l0), build_and_jump (&l1)); gimplify_and_add (t, pre_p); t = build1 (LABEL_EXPR, void_type_node, l0); gimplify_and_add (t, pre_p); append_to_statement_list (OMP_SINGLE_BODY (single_stmt), pre_p); copyin_seq = NULL; lower_copyprivate_clauses (OMP_SINGLE_CLAUSES (single_stmt), pre_p, &copyin_seq, ctx); t = build_fold_addr_expr (ctx->sender_decl); args = tree_cons (NULL, t, NULL); t = built_in_decls[BUILT_IN_GOMP_SINGLE_COPY_END]; t = build_function_call_expr (t, args); gimplify_and_add (t, pre_p); t = build_and_jump (&l2); gimplify_and_add (t, pre_p); t = build1 (LABEL_EXPR, void_type_node, l1); gimplify_and_add (t, pre_p); append_to_statement_list (copyin_seq, pre_p); t = build1 (LABEL_EXPR, void_type_node, l2); gimplify_and_add (t, pre_p); } /* Expand code for an OpenMP single directive. */ static void lower_omp_single (tree *stmt_p, omp_context *ctx) { tree t, bind, block, single_stmt = *stmt_p, dlist; push_gimplify_context (); block = make_node (BLOCK); *stmt_p = bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, block); TREE_SIDE_EFFECTS (bind) = 1; lower_rec_input_clauses (OMP_SINGLE_CLAUSES (single_stmt), &BIND_EXPR_BODY (bind), &dlist, ctx); lower_omp (&OMP_SINGLE_BODY (single_stmt), ctx); append_to_statement_list (single_stmt, &BIND_EXPR_BODY (bind)); if (ctx->record_type) lower_omp_single_copy (single_stmt, &BIND_EXPR_BODY (bind), ctx); else lower_omp_single_simple (single_stmt, &BIND_EXPR_BODY (bind)); OMP_SINGLE_BODY (single_stmt) = NULL; append_to_statement_list (dlist, &BIND_EXPR_BODY (bind)); maybe_catch_exception (&BIND_EXPR_BODY (bind)); t = make_node (OMP_RETURN); OMP_RETURN_NOWAIT (t) = !!find_omp_clause (OMP_SINGLE_CLAUSES (single_stmt), OMP_CLAUSE_NOWAIT); append_to_statement_list (t, &BIND_EXPR_BODY (bind)); pop_gimplify_context (bind); BIND_EXPR_VARS (bind) = chainon (BIND_EXPR_VARS (bind), ctx->block_vars); BLOCK_VARS (block) = BIND_EXPR_VARS (bind); } /* Expand code for an OpenMP master directive. */ static void lower_omp_master (tree *stmt_p, omp_context *ctx) { tree bind, block, stmt = *stmt_p, lab = NULL, x; push_gimplify_context (); block = make_node (BLOCK); *stmt_p = bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, block); TREE_SIDE_EFFECTS (bind) = 1; append_to_statement_list (stmt, &BIND_EXPR_BODY (bind)); x = built_in_decls[BUILT_IN_OMP_GET_THREAD_NUM]; x = build_function_call_expr (x, NULL); x = build2 (EQ_EXPR, boolean_type_node, x, integer_zero_node); x = build3 (COND_EXPR, void_type_node, x, NULL, build_and_jump (&lab)); gimplify_and_add (x, &BIND_EXPR_BODY (bind)); lower_omp (&OMP_MASTER_BODY (stmt), ctx); maybe_catch_exception (&OMP_MASTER_BODY (stmt)); append_to_statement_list (OMP_MASTER_BODY (stmt), &BIND_EXPR_BODY (bind)); OMP_MASTER_BODY (stmt) = NULL; x = build1 (LABEL_EXPR, void_type_node, lab); gimplify_and_add (x, &BIND_EXPR_BODY (bind)); x = make_node (OMP_RETURN); OMP_RETURN_NOWAIT (x) = 1; append_to_statement_list (x, &BIND_EXPR_BODY (bind)); pop_gimplify_context (bind); BIND_EXPR_VARS (bind) = chainon (BIND_EXPR_VARS (bind), ctx->block_vars); BLOCK_VARS (block) = BIND_EXPR_VARS (bind); } /* Expand code for an OpenMP ordered directive. */ static void lower_omp_ordered (tree *stmt_p, omp_context *ctx) { tree bind, block, stmt = *stmt_p, x; push_gimplify_context (); block = make_node (BLOCK); *stmt_p = bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, block); TREE_SIDE_EFFECTS (bind) = 1; append_to_statement_list (stmt, &BIND_EXPR_BODY (bind)); x = built_in_decls[BUILT_IN_GOMP_ORDERED_START]; x = build_function_call_expr (x, NULL); gimplify_and_add (x, &BIND_EXPR_BODY (bind)); lower_omp (&OMP_ORDERED_BODY (stmt), ctx); maybe_catch_exception (&OMP_ORDERED_BODY (stmt)); append_to_statement_list (OMP_ORDERED_BODY (stmt), &BIND_EXPR_BODY (bind)); OMP_ORDERED_BODY (stmt) = NULL; x = built_in_decls[BUILT_IN_GOMP_ORDERED_END]; x = build_function_call_expr (x, NULL); gimplify_and_add (x, &BIND_EXPR_BODY (bind)); x = make_node (OMP_RETURN); OMP_RETURN_NOWAIT (x) = 1; append_to_statement_list (x, &BIND_EXPR_BODY (bind)); pop_gimplify_context (bind); BIND_EXPR_VARS (bind) = chainon (BIND_EXPR_VARS (bind), ctx->block_vars); BLOCK_VARS (block) = BIND_EXPR_VARS (bind); } /* Gimplify an OMP_CRITICAL statement. This is a relatively simple substitution of a couple of function calls. But in the NAMED case, requires that languages coordinate a symbol name. It is therefore best put here in common code. */ static GTY((param1_is (tree), param2_is (tree))) splay_tree critical_name_mutexes; static void lower_omp_critical (tree *stmt_p, omp_context *ctx) { tree bind, block, stmt = *stmt_p; tree t, lock, unlock, name; name = OMP_CRITICAL_NAME (stmt); if (name) { tree decl, args; splay_tree_node n; if (!critical_name_mutexes) critical_name_mutexes = splay_tree_new_ggc (splay_tree_compare_pointers); n = splay_tree_lookup (critical_name_mutexes, (splay_tree_key) name); if (n == NULL) { char *new_str; decl = create_tmp_var_raw (ptr_type_node, NULL); new_str = ACONCAT ((".gomp_critical_user_", IDENTIFIER_POINTER (name), NULL)); DECL_NAME (decl) = get_identifier (new_str); TREE_PUBLIC (decl) = 1; TREE_STATIC (decl) = 1; DECL_COMMON (decl) = 1; DECL_ARTIFICIAL (decl) = 1; DECL_IGNORED_P (decl) = 1; cgraph_varpool_finalize_decl (decl); splay_tree_insert (critical_name_mutexes, (splay_tree_key) name, (splay_tree_value) decl); } else decl = (tree) n->value; args = tree_cons (NULL, build_fold_addr_expr (decl), NULL); lock = built_in_decls[BUILT_IN_GOMP_CRITICAL_NAME_START]; lock = build_function_call_expr (lock, args); args = tree_cons (NULL, build_fold_addr_expr (decl), NULL); unlock = built_in_decls[BUILT_IN_GOMP_CRITICAL_NAME_END]; unlock = build_function_call_expr (unlock, args); } else { lock = built_in_decls[BUILT_IN_GOMP_CRITICAL_START]; lock = build_function_call_expr (lock, NULL); unlock = built_in_decls[BUILT_IN_GOMP_CRITICAL_END]; unlock = build_function_call_expr (unlock, NULL); } push_gimplify_context (); block = make_node (BLOCK); *stmt_p = bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, block); TREE_SIDE_EFFECTS (bind) = 1; append_to_statement_list (stmt, &BIND_EXPR_BODY (bind)); gimplify_and_add (lock, &BIND_EXPR_BODY (bind)); lower_omp (&OMP_CRITICAL_BODY (stmt), ctx); maybe_catch_exception (&OMP_CRITICAL_BODY (stmt)); append_to_statement_list (OMP_CRITICAL_BODY (stmt), &BIND_EXPR_BODY (bind)); OMP_CRITICAL_BODY (stmt) = NULL; gimplify_and_add (unlock, &BIND_EXPR_BODY (bind)); t = make_node (OMP_RETURN); OMP_RETURN_NOWAIT (t) = 1; append_to_statement_list (t, &BIND_EXPR_BODY (bind)); pop_gimplify_context (bind); BIND_EXPR_VARS (bind) = chainon (BIND_EXPR_VARS (bind), ctx->block_vars); BLOCK_VARS (block) = BIND_EXPR_VARS (bind); } /* A subroutine of lower_omp_for. Generate code to emit the predicate for a lastprivate clause. Given a loop control predicate of (V cond N2), we gate the clause on (!(V cond N2)). The lowered form is appended to *DLIST, iterator initialization is appended to *BODY_P. */ static void lower_omp_for_lastprivate (struct omp_for_data *fd, tree *body_p, tree *dlist, struct omp_context *ctx) { tree clauses, cond, stmts, vinit, t; enum tree_code cond_code; cond_code = fd->loop.cond_code; cond_code = cond_code == LT_EXPR ? GE_EXPR : LE_EXPR; /* When possible, use a strict equality expression. This can let VRP type optimizations deduce the value and remove a copy. */ if (host_integerp (fd->loop.step, 0)) { HOST_WIDE_INT step = TREE_INT_CST_LOW (fd->loop.step); if (step == 1 || step == -1) cond_code = EQ_EXPR; } cond = build2 (cond_code, boolean_type_node, fd->loop.v, fd->loop.n2); clauses = OMP_FOR_CLAUSES (fd->for_stmt); stmts = NULL; lower_lastprivate_clauses (clauses, cond, &stmts, ctx); if (stmts != NULL) { append_to_statement_list (*dlist, &stmts); *dlist = stmts; /* Optimize: v = 0; is usually cheaper than v = some_other_constant. */ vinit = fd->loop.n1; if (cond_code == EQ_EXPR && host_integerp (fd->loop.n2, 0) && ! integer_zerop (fd->loop.n2)) vinit = build_int_cst (TREE_TYPE (fd->loop.v), 0); /* Initialize the iterator variable, so that threads that don't execute any iterations don't execute the lastprivate clauses by accident. */ t = build2 (MODIFY_EXPR, void_type_node, fd->loop.v, vinit); gimplify_and_add (t, body_p); } } /* Lower code for an OpenMP loop directive. */ static void lower_omp_for (tree *stmt_p, omp_context *ctx) { tree t, stmt, ilist, dlist, new_stmt, *body_p, *rhs_p; struct omp_for_data fd; int i; stmt = *stmt_p; push_gimplify_context (); lower_omp (&OMP_FOR_PRE_BODY (stmt), ctx); lower_omp (&OMP_FOR_BODY (stmt), ctx); /* Move declaration of temporaries in the loop body before we make it go away. */ if (TREE_CODE (OMP_FOR_BODY (stmt)) == BIND_EXPR) record_vars_into (BIND_EXPR_VARS (OMP_FOR_BODY (stmt)), ctx->cb.dst_fn); new_stmt = build3 (BIND_EXPR, void_type_node, NULL, NULL, NULL); TREE_SIDE_EFFECTS (new_stmt) = 1; body_p = &BIND_EXPR_BODY (new_stmt); /* The pre-body and input clauses go before the lowered OMP_FOR. */ ilist = NULL; dlist = NULL; lower_rec_input_clauses (OMP_FOR_CLAUSES (stmt), body_p, &dlist, ctx); append_to_statement_list (OMP_FOR_PRE_BODY (stmt), body_p); /* Lower the header expressions. At this point, we can assume that the header is of the form: #pragma omp for (V = VAL1; V {<|>|<=|>=} VAL2; V = V [+-] VAL3) We just need to make sure that VAL1, VAL2 and VAL3 are lowered using the .omp_data_s mapping, if needed. */ for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (stmt)); i++) { rhs_p = &TREE_OPERAND (TREE_VEC_ELT (OMP_FOR_INIT (stmt), i), 1); if (!is_gimple_min_invariant (*rhs_p)) *rhs_p = get_formal_tmp_var (*rhs_p, body_p); rhs_p = &TREE_OPERAND (TREE_VEC_ELT (OMP_FOR_COND (stmt), i), 1); if (!is_gimple_min_invariant (*rhs_p)) *rhs_p = get_formal_tmp_var (*rhs_p, body_p); rhs_p = &TREE_OPERAND (TREE_OPERAND (TREE_VEC_ELT (OMP_FOR_INCR (stmt), i), 1), 1); if (!is_gimple_min_invariant (*rhs_p)) *rhs_p = get_formal_tmp_var (*rhs_p, body_p); if (!is_gimple_min_invariant (*rhs_p)) *rhs_p = get_formal_tmp_var (*rhs_p, body_p); } /* Once lowered, extract the bounds and clauses. */ extract_omp_for_data (stmt, &fd, NULL); lower_omp_for_lastprivate (&fd, body_p, &dlist, ctx); append_to_statement_list (stmt, body_p); append_to_statement_list (OMP_FOR_BODY (stmt), body_p); t = make_node (OMP_CONTINUE); append_to_statement_list (t, body_p); /* After the loop, add exit clauses. */ lower_reduction_clauses (OMP_FOR_CLAUSES (stmt), body_p, ctx); append_to_statement_list (dlist, body_p); maybe_catch_exception (body_p); /* Region exit marker goes at the end of the loop body. */ t = make_node (OMP_RETURN); OMP_RETURN_NOWAIT (t) = fd.have_nowait; append_to_statement_list (t, body_p); pop_gimplify_context (NULL_TREE); record_vars_into (ctx->block_vars, ctx->cb.dst_fn); OMP_FOR_BODY (stmt) = NULL_TREE; OMP_FOR_PRE_BODY (stmt) = NULL_TREE; *stmt_p = new_stmt; } struct omp_taskcopy_context { /* This field must be at the beginning, as we do "inheritance": Some callback functions for tree-inline.c (e.g., omp_copy_decl) receive a copy_body_data pointer that is up-casted to an omp_context pointer. */ copy_body_data cb; omp_context *ctx; }; static tree task_copyfn_copy_decl (tree var, copy_body_data *cb) { struct omp_taskcopy_context *tcctx = (struct omp_taskcopy_context *) cb; if (splay_tree_lookup (tcctx->ctx->sfield_map, (splay_tree_key) var)) return create_tmp_var (TREE_TYPE (var), NULL); return var; } static tree task_copyfn_remap_type (struct omp_taskcopy_context *tcctx, tree orig_type) { tree name, new_fields = NULL, type, f; type = lang_hooks.types.make_type (RECORD_TYPE); name = DECL_NAME (TYPE_NAME (orig_type)); name = build_decl (TYPE_DECL, name, type); TYPE_NAME (type) = name; for (f = TYPE_FIELDS (orig_type); f ; f = TREE_CHAIN (f)) { tree new_f = copy_node (f); DECL_CONTEXT (new_f) = type; TREE_TYPE (new_f) = remap_type (TREE_TYPE (f), &tcctx->cb); TREE_CHAIN (new_f) = new_fields; walk_tree (&DECL_SIZE (new_f), copy_body_r, &tcctx->cb, NULL); walk_tree (&DECL_SIZE_UNIT (new_f), copy_body_r, &tcctx->cb, NULL); walk_tree (&DECL_FIELD_OFFSET (new_f), copy_body_r, &tcctx->cb, NULL); new_fields = new_f; splay_tree_insert (tcctx->cb.decl_map, (splay_tree_key) f, (splay_tree_value) new_f); } TYPE_FIELDS (type) = nreverse (new_fields); layout_type (type); return type; } /* Create task copyfn. */ static void create_task_copyfn (tree task_stmt, omp_context *ctx) { struct function *child_cfun; tree child_fn, t, c, src, dst, f, sf, arg, sarg, decl; tree record_type, srecord_type, bind, list; bool record_needs_remap = false, srecord_needs_remap = false; splay_tree_node n; struct omp_taskcopy_context tcctx; child_fn = OMP_TASK_COPYFN (task_stmt); child_cfun = DECL_STRUCT_FUNCTION (child_fn); gcc_assert (child_cfun->cfg == NULL); child_cfun->x_dont_save_pending_sizes_p = 1; DECL_SAVED_TREE (child_fn) = alloc_stmt_list (); /* Reset DECL_CONTEXT on function arguments. */ for (t = DECL_ARGUMENTS (child_fn); t; t = TREE_CHAIN (t)) DECL_CONTEXT (t) = child_fn; /* Populate the function. */ push_gimplify_context (); current_function_decl = child_fn; bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, NULL); TREE_SIDE_EFFECTS (bind) = 1; list = NULL; DECL_SAVED_TREE (child_fn) = bind; DECL_SOURCE_LOCATION (child_fn) = EXPR_LOCATION (task_stmt); /* Remap src and dst argument types if needed. */ record_type = ctx->record_type; srecord_type = ctx->srecord_type; for (f = TYPE_FIELDS (record_type); f ; f = TREE_CHAIN (f)) if (variably_modified_type_p (TREE_TYPE (f), ctx->cb.src_fn)) { record_needs_remap = true; break; } for (f = TYPE_FIELDS (srecord_type); f ; f = TREE_CHAIN (f)) if (variably_modified_type_p (TREE_TYPE (f), ctx->cb.src_fn)) { srecord_needs_remap = true; break; } if (record_needs_remap || srecord_needs_remap) { memset (&tcctx, '\0', sizeof (tcctx)); tcctx.cb.src_fn = ctx->cb.src_fn; tcctx.cb.dst_fn = child_fn; tcctx.cb.src_node = cgraph_node (tcctx.cb.src_fn); tcctx.cb.dst_node = tcctx.cb.src_node; tcctx.cb.src_cfun = ctx->cb.src_cfun; tcctx.cb.copy_decl = task_copyfn_copy_decl; tcctx.cb.eh_region = -1; tcctx.cb.transform_call_graph_edges = CB_CGE_MOVE; tcctx.cb.decl_map = splay_tree_new (splay_tree_compare_pointers, 0, 0); tcctx.ctx = ctx; if (record_needs_remap) record_type = task_copyfn_remap_type (&tcctx, record_type); if (srecord_needs_remap) srecord_type = task_copyfn_remap_type (&tcctx, srecord_type); } else tcctx.cb.decl_map = NULL; push_cfun (child_cfun); arg = DECL_ARGUMENTS (child_fn); TREE_TYPE (arg) = build_pointer_type (record_type); sarg = TREE_CHAIN (arg); TREE_TYPE (sarg) = build_pointer_type (srecord_type); /* First pass: initialize temporaries used in record_type and srecord_type sizes and field offsets. */ if (tcctx.cb.decl_map) for (c = OMP_TASK_CLAUSES (task_stmt); c; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE) { tree *p; decl = OMP_CLAUSE_DECL (c); p = (tree *) splay_tree_lookup (tcctx.cb.decl_map, (splay_tree_key) decl); if (p == NULL) continue; n = splay_tree_lookup (ctx->sfield_map, (splay_tree_key) decl); sf = (tree) n->value; sf = *(tree *) splay_tree_lookup (tcctx.cb.decl_map, (splay_tree_key) sf); src = build_fold_indirect_ref (sarg); src = build3 (COMPONENT_REF, TREE_TYPE (sf), src, sf, NULL); t = build2 (MODIFY_EXPR, void_type_node, *p, src); append_to_statement_list (t, &list); } /* Second pass: copy shared var pointers and copy construct non-VLA firstprivate vars. */ for (c = OMP_TASK_CLAUSES (task_stmt); c; c = OMP_CLAUSE_CHAIN (c)) switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_SHARED: decl = OMP_CLAUSE_DECL (c); n = splay_tree_lookup (ctx->field_map, (splay_tree_key) decl); if (n == NULL) break; f = (tree) n->value; if (tcctx.cb.decl_map) f = *(tree *) splay_tree_lookup (tcctx.cb.decl_map, (splay_tree_key) f); n = splay_tree_lookup (ctx->sfield_map, (splay_tree_key) decl); sf = (tree) n->value; if (tcctx.cb.decl_map) sf = *(tree *) splay_tree_lookup (tcctx.cb.decl_map, (splay_tree_key) sf); src = build_fold_indirect_ref (sarg); src = build3 (COMPONENT_REF, TREE_TYPE (sf), src, sf, NULL); dst = build_fold_indirect_ref (arg); dst = build3 (COMPONENT_REF, TREE_TYPE (f), dst, f, NULL); t = build2 (MODIFY_EXPR, void_type_node, dst, src); append_to_statement_list (t, &list); break; case OMP_CLAUSE_FIRSTPRIVATE: decl = OMP_CLAUSE_DECL (c); if (is_variable_sized (decl)) break; n = splay_tree_lookup (ctx->field_map, (splay_tree_key) decl); if (n == NULL) break; f = (tree) n->value; if (tcctx.cb.decl_map) f = *(tree *) splay_tree_lookup (tcctx.cb.decl_map, (splay_tree_key) f); n = splay_tree_lookup (ctx->sfield_map, (splay_tree_key) decl); if (n != NULL) { sf = (tree) n->value; if (tcctx.cb.decl_map) sf = *(tree *) splay_tree_lookup (tcctx.cb.decl_map, (splay_tree_key) sf); src = build_fold_indirect_ref (sarg); src = build3 (COMPONENT_REF, TREE_TYPE (sf), src, sf, NULL); if (use_pointer_for_field (decl, NULL) || is_reference (decl)) src = build_fold_indirect_ref (src); } else src = decl; dst = build_fold_indirect_ref (arg); dst = build3 (COMPONENT_REF, TREE_TYPE (f), dst, f, NULL); t = lang_hooks.decls.omp_clause_copy_ctor (c, dst, src); append_to_statement_list (t, &list); break; case OMP_CLAUSE_PRIVATE: if (! OMP_CLAUSE_PRIVATE_OUTER_REF (c)) break; decl = OMP_CLAUSE_DECL (c); n = splay_tree_lookup (ctx->field_map, (splay_tree_key) decl); f = (tree) n->value; if (tcctx.cb.decl_map) f = *(tree *) splay_tree_lookup (tcctx.cb.decl_map, (splay_tree_key) f); n = splay_tree_lookup (ctx->sfield_map, (splay_tree_key) decl); if (n != NULL) { sf = (tree) n->value; if (tcctx.cb.decl_map) sf = *(tree *) splay_tree_lookup (tcctx.cb.decl_map, (splay_tree_key) sf); src = build_fold_indirect_ref (sarg); src = build3 (COMPONENT_REF, TREE_TYPE (sf), src, sf, NULL); if (use_pointer_for_field (decl, NULL)) src = build_fold_indirect_ref (src); } else src = decl; dst = build_fold_indirect_ref (arg); dst = build3 (COMPONENT_REF, TREE_TYPE (f), dst, f, NULL); t = build2 (MODIFY_EXPR, void_type_node, dst, src); append_to_statement_list (t, &list); break; default: break; } /* Last pass: handle VLA firstprivates. */ if (tcctx.cb.decl_map) for (c = OMP_TASK_CLAUSES (task_stmt); c; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE) { tree ind, ptr, df; decl = OMP_CLAUSE_DECL (c); if (!is_variable_sized (decl)) continue; n = splay_tree_lookup (ctx->field_map, (splay_tree_key) decl); if (n == NULL) continue; f = (tree) n->value; f = *(tree *) splay_tree_lookup (tcctx.cb.decl_map, (splay_tree_key) f); gcc_assert (DECL_HAS_VALUE_EXPR_P (decl)); ind = DECL_VALUE_EXPR (decl); gcc_assert (TREE_CODE (ind) == INDIRECT_REF); gcc_assert (DECL_P (TREE_OPERAND (ind, 0))); n = splay_tree_lookup (ctx->sfield_map, (splay_tree_key) TREE_OPERAND (ind, 0)); sf = (tree) n->value; sf = *(tree *) splay_tree_lookup (tcctx.cb.decl_map, (splay_tree_key) sf); src = build_fold_indirect_ref (sarg); src = build3 (COMPONENT_REF, TREE_TYPE (sf), src, sf, NULL); src = build_fold_indirect_ref (src); dst = build_fold_indirect_ref (arg); dst = build3 (COMPONENT_REF, TREE_TYPE (f), dst, f, NULL); t = lang_hooks.decls.omp_clause_copy_ctor (c, dst, src); append_to_statement_list (t, &list); n = splay_tree_lookup (ctx->field_map, (splay_tree_key) TREE_OPERAND (ind, 0)); df = (tree) n->value; df = *(tree *) splay_tree_lookup (tcctx.cb.decl_map, (splay_tree_key) df); ptr = build_fold_indirect_ref (arg); ptr = build3 (COMPONENT_REF, TREE_TYPE (df), ptr, df, NULL); t = build2 (MODIFY_EXPR, void_type_node, ptr, build_fold_addr_expr (dst)); append_to_statement_list (t, &list); } t = build1 (RETURN_EXPR, void_type_node, NULL); append_to_statement_list (t, &list); if (tcctx.cb.decl_map) splay_tree_delete (tcctx.cb.decl_map); pop_gimplify_context (NULL); BIND_EXPR_BODY (bind) = list; pop_cfun (); current_function_decl = ctx->cb.src_fn; } /* Lower the OpenMP parallel or task directive in *STMT_P. CTX holds context information for the directive. */ static void lower_omp_taskreg (tree *stmt_p, omp_context *ctx) { tree clauses, par_bind, par_body, new_body, bind; tree olist, ilist, par_olist, par_ilist; tree stmt, child_fn, t; stmt = *stmt_p; clauses = OMP_TASKREG_CLAUSES (stmt); par_bind = OMP_TASKREG_BODY (stmt); par_body = BIND_EXPR_BODY (par_bind); child_fn = ctx->cb.dst_fn; if (ctx->srecord_type) create_task_copyfn (stmt, ctx); push_gimplify_context (); par_olist = NULL_TREE; par_ilist = NULL_TREE; lower_rec_input_clauses (clauses, &par_ilist, &par_olist, ctx); lower_omp (&par_body, ctx); if (TREE_CODE (stmt) == OMP_PARALLEL) lower_reduction_clauses (clauses, &par_olist, ctx); /* Declare all the variables created by mapping and the variables declared in the scope of the parallel body. */ record_vars_into (ctx->block_vars, child_fn); record_vars_into (BIND_EXPR_VARS (par_bind), child_fn); if (ctx->record_type) { ctx->sender_decl = create_tmp_var (ctx->srecord_type ? ctx->srecord_type : ctx->record_type, ".omp_data_o"); OMP_TASKREG_DATA_ARG (stmt) = ctx->sender_decl; } if (ctx->srecord_type) create_task_copyfn (stmt, ctx); olist = NULL_TREE; ilist = NULL_TREE; lower_send_clauses (clauses, &ilist, &olist, ctx); lower_send_shared_vars (&ilist, &olist, ctx); /* Once all the expansions are done, sequence all the different fragments inside OMP_TASKREG_BODY. */ bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, NULL); append_to_statement_list (ilist, &BIND_EXPR_BODY (bind)); new_body = alloc_stmt_list (); if (ctx->record_type) { t = build_fold_addr_expr (ctx->sender_decl); /* fixup_child_record_type might have changed receiver_decl's type. */ t = fold_convert (TREE_TYPE (ctx->receiver_decl), t); t = build2 (MODIFY_EXPR, void_type_node, ctx->receiver_decl, t); append_to_statement_list (t, &new_body); } append_to_statement_list (par_ilist, &new_body); append_to_statement_list (par_body, &new_body); append_to_statement_list (par_olist, &new_body); maybe_catch_exception (&new_body); t = make_node (OMP_RETURN); append_to_statement_list (t, &new_body); OMP_TASKREG_BODY (stmt) = new_body; append_to_statement_list (stmt, &BIND_EXPR_BODY (bind)); append_to_statement_list (olist, &BIND_EXPR_BODY (bind)); *stmt_p = bind; pop_gimplify_context (NULL_TREE); } /* Pass *TP back through the gimplifier within the context determined by WI. This handles replacement of DECL_VALUE_EXPR, as well as adjusting the flags on ADDR_EXPR. */ static void lower_regimplify (tree *tp, struct walk_stmt_info *wi) { enum gimplify_status gs; tree pre = NULL; if (wi->is_lhs) gs = gimplify_expr (tp, &pre, NULL, is_gimple_lvalue, fb_lvalue); else if (wi->val_only) gs = gimplify_expr (tp, &pre, NULL, is_gimple_val, fb_rvalue); else gs = gimplify_expr (tp, &pre, NULL, is_gimple_formal_tmp_var, fb_rvalue); gcc_assert (gs == GS_ALL_DONE); if (pre) tsi_link_before (&wi->tsi, pre, TSI_SAME_STMT); } /* Copy EXP into a temporary. Insert the initialization statement before TSI. */ static tree init_tmp_var (tree exp, tree_stmt_iterator *tsi) { tree t, stmt; t = create_tmp_var (TREE_TYPE (exp), NULL); if (TREE_CODE (TREE_TYPE (t)) == COMPLEX_TYPE) DECL_COMPLEX_GIMPLE_REG_P (t) = 1; stmt = build2 (MODIFY_EXPR, TREE_TYPE (t), t, exp); SET_EXPR_LOCUS (stmt, EXPR_LOCUS (tsi_stmt (*tsi))); tsi_link_before (tsi, stmt, TSI_SAME_STMT); return t; } /* Similarly, but copy from the temporary and insert the statement after the iterator. */ static tree save_tmp_var (tree exp, tree_stmt_iterator *tsi) { tree t, stmt; t = create_tmp_var (TREE_TYPE (exp), NULL); if (TREE_CODE (TREE_TYPE (t)) == COMPLEX_TYPE) DECL_COMPLEX_GIMPLE_REG_P (t) = 1; stmt = build2 (MODIFY_EXPR, TREE_TYPE (t), exp, t); SET_EXPR_LOCUS (stmt, EXPR_LOCUS (tsi_stmt (*tsi))); tsi_link_after (tsi, stmt, TSI_SAME_STMT); return t; } /* Callback for walk_stmts. Lower the OpenMP directive pointed by TP. */ static tree lower_omp_1 (tree *tp, int *walk_subtrees, void *data) { struct walk_stmt_info *wi = data; omp_context *ctx = wi->info; tree t = *tp; /* If we have issued syntax errors, avoid doing any heavy lifting. Just replace the OpenMP directives with a NOP to avoid confusing RTL expansion. */ if (errorcount && OMP_DIRECTIVE_P (*tp)) { *tp = build_empty_stmt (); return NULL_TREE; } *walk_subtrees = 0; switch (TREE_CODE (*tp)) { case OMP_PARALLEL: case OMP_TASK: ctx = maybe_lookup_ctx (t); lower_omp_taskreg (tp, ctx); break; case OMP_FOR: ctx = maybe_lookup_ctx (t); gcc_assert (ctx); lower_omp_for (tp, ctx); break; case OMP_SECTIONS: ctx = maybe_lookup_ctx (t); gcc_assert (ctx); lower_omp_sections (tp, ctx); break; case OMP_SINGLE: ctx = maybe_lookup_ctx (t); gcc_assert (ctx); lower_omp_single (tp, ctx); break; case OMP_MASTER: ctx = maybe_lookup_ctx (t); gcc_assert (ctx); lower_omp_master (tp, ctx); break; case OMP_ORDERED: ctx = maybe_lookup_ctx (t); gcc_assert (ctx); lower_omp_ordered (tp, ctx); break; case OMP_CRITICAL: ctx = maybe_lookup_ctx (t); gcc_assert (ctx); lower_omp_critical (tp, ctx); break; case VAR_DECL: if (ctx && DECL_HAS_VALUE_EXPR_P (t)) { lower_regimplify (&t, wi); if (wi->val_only) { if (wi->is_lhs) t = save_tmp_var (t, &wi->tsi); else t = init_tmp_var (t, &wi->tsi); } *tp = t; } break; case ADDR_EXPR: if (ctx) lower_regimplify (tp, wi); break; case ARRAY_REF: case ARRAY_RANGE_REF: case REALPART_EXPR: case IMAGPART_EXPR: case COMPONENT_REF: case VIEW_CONVERT_EXPR: if (ctx) lower_regimplify (tp, wi); break; case INDIRECT_REF: if (ctx) { wi->is_lhs = false; wi->val_only = true; lower_regimplify (&TREE_OPERAND (t, 0), wi); } break; default: if (!TYPE_P (t) && !DECL_P (t)) *walk_subtrees = 1; break; } return NULL_TREE; } static void lower_omp (tree *stmt_p, omp_context *ctx) { struct walk_stmt_info wi; memset (&wi, 0, sizeof (wi)); wi.callback = lower_omp_1; wi.info = ctx; wi.val_only = true; wi.want_locations = true; walk_stmts (&wi, stmt_p); } /* Main entry point. */ static unsigned int execute_lower_omp (void) { all_contexts = splay_tree_new (splay_tree_compare_pointers, 0, delete_omp_context); scan_omp (&DECL_SAVED_TREE (current_function_decl), NULL); gcc_assert (taskreg_nesting_level == 0); if (all_contexts->root) { if (task_shared_vars) push_gimplify_context (); lower_omp (&DECL_SAVED_TREE (current_function_decl), NULL); if (task_shared_vars) pop_gimplify_context (NULL); } if (all_contexts) { splay_tree_delete (all_contexts); all_contexts = NULL; } BITMAP_FREE (task_shared_vars); return 0; } static bool gate_lower_omp (void) { return flag_openmp != 0; } struct tree_opt_pass pass_lower_omp = { "omplower", /* name */ gate_lower_omp, /* gate */ execute_lower_omp, /* execute */ NULL, /* sub */ NULL, /* next */ 0, /* static_pass_number */ 0, /* tv_id */ PROP_gimple_any, /* properties_required */ PROP_gimple_lomp, /* properties_provided */ 0, /* properties_destroyed */ 0, /* todo_flags_start */ TODO_dump_func, /* todo_flags_finish */ 0 /* letter */ }; /* The following is a utility to diagnose OpenMP structured block violations. It is not part of the "omplower" pass, as that's invoked too late. It should be invoked by the respective front ends after gimplification. */ static splay_tree all_labels; /* Check for mismatched contexts and generate an error if needed. Return true if an error is detected. */ static bool diagnose_sb_0 (tree *stmt_p, tree branch_ctx, tree label_ctx) { bool exit_p = true; if ((label_ctx ? TREE_VALUE (label_ctx) : NULL) == branch_ctx) return false; /* Try to avoid confusing the user by producing and error message with correct "exit" or "enter" verbiage. We prefer "exit" unless we can show that LABEL_CTX is nested within BRANCH_CTX. */ if (branch_ctx == NULL) exit_p = false; else { while (label_ctx) { if (TREE_VALUE (label_ctx) == branch_ctx) { exit_p = false; break; } label_ctx = TREE_CHAIN (label_ctx); } } if (exit_p) error ("invalid exit from OpenMP structured block"); else error ("invalid entry to OpenMP structured block"); *stmt_p = build_empty_stmt (); return true; } /* Pass 1: Create a minimal tree of OpenMP structured blocks, and record where in the tree each label is found. */ static tree diagnose_sb_1 (tree *tp, int *walk_subtrees, void *data) { struct walk_stmt_info *wi = data; tree context = (tree) wi->info; tree inner_context; tree t = *tp; int i; *walk_subtrees = 0; switch (TREE_CODE (t)) { case OMP_PARALLEL: case OMP_TASK: case OMP_SECTIONS: case OMP_SINGLE: walk_tree (&OMP_CLAUSES (t), diagnose_sb_1, wi, NULL); /* FALLTHRU */ case OMP_SECTION: case OMP_MASTER: case OMP_ORDERED: case OMP_CRITICAL: /* The minimal context here is just a tree of statements. */ inner_context = tree_cons (NULL, t, context); wi->info = inner_context; walk_stmts (wi, &OMP_BODY (t)); wi->info = context; break; case OMP_FOR: walk_tree (&OMP_FOR_CLAUSES (t), diagnose_sb_1, wi, NULL); inner_context = tree_cons (NULL, t, context); wi->info = inner_context; for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++) { walk_tree (&TREE_VEC_ELT (OMP_FOR_INIT (t), i), diagnose_sb_1, wi, NULL); walk_tree (&TREE_VEC_ELT (OMP_FOR_COND (t), i), diagnose_sb_1, wi, NULL); walk_tree (&TREE_VEC_ELT (OMP_FOR_INCR (t), i), diagnose_sb_1, wi, NULL); } walk_stmts (wi, &OMP_FOR_PRE_BODY (t)); walk_stmts (wi, &OMP_FOR_BODY (t)); wi->info = context; break; case LABEL_EXPR: splay_tree_insert (all_labels, (splay_tree_key) LABEL_EXPR_LABEL (t), (splay_tree_value) context); break; default: break; } return NULL_TREE; } /* Pass 2: Check each branch and see if its context differs from that of the destination label's context. */ static tree diagnose_sb_2 (tree *tp, int *walk_subtrees, void *data) { struct walk_stmt_info *wi = data; tree context = (tree) wi->info; splay_tree_node n; tree t = *tp; int i; *walk_subtrees = 0; switch (TREE_CODE (t)) { case OMP_PARALLEL: case OMP_TASK: case OMP_SECTIONS: case OMP_SINGLE: walk_tree (&OMP_CLAUSES (t), diagnose_sb_2, wi, NULL); /* FALLTHRU */ case OMP_SECTION: case OMP_MASTER: case OMP_ORDERED: case OMP_CRITICAL: wi->info = t; walk_stmts (wi, &OMP_BODY (t)); wi->info = context; break; case OMP_FOR: walk_tree (&OMP_FOR_CLAUSES (t), diagnose_sb_2, wi, NULL); wi->info = t; for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++) { walk_tree (&TREE_VEC_ELT (OMP_FOR_INIT (t), i), diagnose_sb_2, wi, NULL); walk_tree (&TREE_VEC_ELT (OMP_FOR_COND (t), i), diagnose_sb_2, wi, NULL); walk_tree (&TREE_VEC_ELT (OMP_FOR_INCR (t), i), diagnose_sb_2, wi, NULL); } walk_stmts (wi, &OMP_FOR_PRE_BODY (t)); walk_stmts (wi, &OMP_FOR_BODY (t)); wi->info = context; break; case GOTO_EXPR: { tree lab = GOTO_DESTINATION (t); if (TREE_CODE (lab) != LABEL_DECL) break; n = splay_tree_lookup (all_labels, (splay_tree_key) lab); diagnose_sb_0 (tp, context, n ? (tree) n->value : NULL_TREE); } break; case SWITCH_EXPR: { tree vec = SWITCH_LABELS (t); int i, len = TREE_VEC_LENGTH (vec); for (i = 0; i < len; ++i) { tree lab = CASE_LABEL (TREE_VEC_ELT (vec, i)); n = splay_tree_lookup (all_labels, (splay_tree_key) lab); if (diagnose_sb_0 (tp, context, (tree) n->value)) break; } } break; case RETURN_EXPR: diagnose_sb_0 (tp, context, NULL_TREE); break; default: break; } return NULL_TREE; } void diagnose_omp_structured_block_errors (tree fndecl) { tree save_current = current_function_decl; struct walk_stmt_info wi; current_function_decl = fndecl; all_labels = splay_tree_new (splay_tree_compare_pointers, 0, 0); memset (&wi, 0, sizeof (wi)); wi.callback = diagnose_sb_1; walk_stmts (&wi, &DECL_SAVED_TREE (fndecl)); memset (&wi, 0, sizeof (wi)); wi.callback = diagnose_sb_2; wi.want_locations = true; wi.want_return_expr = true; walk_stmts (&wi, &DECL_SAVED_TREE (fndecl)); splay_tree_delete (all_labels); all_labels = NULL; current_function_decl = save_current; } #include "gt-omp-low.h"
multiplayer.h
//Windiarta - 2006535792 void multi(int refresh) { int sizey = 24; int sizex = 40; int x, y, yi; char world[sizey][sizex]; char world2[sizey][sizex]; char player = 'A'; char playerLaser = '^'; char enemy = 'M'; char enemyShielded = 'O'; char enemyLaser = 'v'; char explosion = 'X'; int score = 0, score2 = 0; int victory = 1, victory2 = 1; int laserReady1 = 1, laserReady2 = 1; int enemyReady = 0; int j; double t1, t2; print_wait_3s(); int totalEnemies = 0; //arena #pragma omp for for (x = 0; x < sizex; x ++) { for (y = 0; y < sizey; y ++) { if ((y+1) % 2 == 0 && y < 7 && x > 4 && x < sizex - 5 && x % 2 ==0) { world[y][x] = enemy; totalEnemies ++; } else if ((y+1) % 2 == 0 && y >= 7 && y < 9 && x > 4 && x < sizex - 5 && x % 2 ==0){ world[y][x] = enemyShielded; totalEnemies = totalEnemies + 2; } else { world[y][x] = ' '; } } } world[sizey - 2][sizex / 2] = player; int i = 1; char direction = 'l'; int currentEnemies = totalEnemies; //copy world setup #pragma omp for for (j = 0; j < sizey; j++){ strcpy(world2[j], world[j]); } t1 = omp_get_wtime(); #pragma omp parallel { #pragma omp master { do{ char keyPress; i++; if(kbhit()){ keyPress = tolower(getch()); //Player movement #pragma omp task shared (world, world2, keyPress) { laserReady1++; laserReady2++; if (keyPress == 'a') { #pragma omp critical { for (x = 0; x < sizex; x = x+1) { if ( world[sizey-2][x+1] == player) { world[sizey-2][x] = player; world[sizey-2][x+1] = ' '; } } } } if (keyPress == 'd') { #pragma omp critical { for (x = sizex - 1; x > 0; x = x-1) { if ( world[sizey-2][x-1] == player) { world[sizey-2][x] = player; world[sizey-2][x-1] = ' '; } } } } if (keyPress == 'w'){ #pragma omp critical { if (laserReady1 > 2) { for (x = 0; x < sizex; x = x+1) { if ( world[sizey-2][x] == player) { world[sizey - 3][x] = playerLaser; laserReady1 = 0; } } } } } if (keyPress == 'j') { #pragma omp critical { for (x = 0; x < sizex; x = x+1) { if ( world2[sizey-2][x+1] == player) { world2[sizey-2][x] = player; world2[sizey-2][x+1] = ' '; } } } } if (keyPress == 'l') { #pragma omp critical { for (x = sizex - 1; x > 0; x = x-1) { if ( world2[sizey-2][x-1] == player) { world2[sizey-2][x] = player; world2[sizey-2][x-1] = ' '; } } } } if (keyPress == 'i') { #pragma omp critical { if (laserReady2 > 2) { for (x = 0; x < sizex; x = x+1) { if ( world2[sizey-2][x] == player) { world2[sizey - 3][x] = playerLaser; laserReady2 = 0; } } } } } } } else { keyPress = ' '; } //enemy laser spawner #pragma omp task shared (world, world2) { #pragma omp critical { //enemy laser down world 1 for (x = 0; x < sizex; x ++) { for (y = sizey-1; y >= 0; y --) { if (i%2 == 0 && world[y][x] == enemyLaser){ if(world[y+1][x] != enemy && world[y+1][x] != enemyShielded){ world[y+1][x] = enemyLaser; world[y][x] = ' '; } else if (world[y+1][x] == enemy || world[y+1][x] == enemyShielded){ world[y][x] = ' '; } } } } } #pragma omp critical { //enemy laser down world 2 for (x = 0; x < sizex; x ++) { for (y = sizey-1; y >= 0; y --) { if (i%2 == 0 && world2[y][x] == enemyLaser){ if(world2[y+1][x] != enemy && world2[y+1][x] != enemyShielded){ world2[y+1][x] = enemyLaser; world2[y][x] = ' '; } else if (world2[y+1][x] == enemy || world2[y+1][x] == enemyShielded){ world2[y][x] = ' '; } } } } } } //game management of world 1 #pragma omp task shared (world, score, victory) { int drop = 0; int enemySpeed = 1 + 10 * currentEnemies / totalEnemies; #pragma omp critical { for (x = 0; x < sizex; x ++) { for (y = 0; y < sizey; y ++) { if ((i % 5) == 0 && (world[y][x] == enemyShielded || world[y][x] == enemy) && (rand() % 15) > 13 && world[y+1][x] != playerLaser) { for (yi = y+1; yi < sizey; yi ++) { if (world[yi][x] == enemy || world[yi][x] == enemyShielded) { enemyReady = 0; break; } enemyReady = 1; } if (enemyReady) { world[y+1][x] = enemyLaser; } } if (world[y][x] == playerLaser && world[y-1][x] == enemy) { world[y][x] = ' '; world[y-1][x] = explosion; currentEnemies --; score = score + 50; } else if (world[y][x] == playerLaser && world[y-1][x] == enemyShielded) { world[y][x] = ' '; world[y-1][x] = enemy; currentEnemies --; score = score + 50; } else if (world[y][x] == playerLaser && world[y-1][x] == enemyLaser) { world[y][x] = ' '; } else if (world[y][x] == explosion) { world[y][x] = ' '; } else if ((i+1) % 2 == 0 && world[y][x] == enemyLaser && world[y+1][x] == player) { world[y+1][x] = explosion; world[y][x] = ' '; victory = 0; } else if (world[y][x] == playerLaser && world[y-1][x] != enemyLaser) { world[y-1][x] = playerLaser; world[y][x] = ' '; } } } } #pragma omp critical { //enemy movement (left/right) for (y = 0; y < sizey; y ++) { if (world[y][0] == enemy) { direction = 'r'; drop = 1; break; } if (world[y][sizex-1] == enemy){ direction = 'l'; drop = 1; break; } } } #pragma omp critical { //enemy movement (down) if (i % enemySpeed == 0) { if (direction == 'l') { for (x = 0; x < sizex - 1; x ++) { for (y = 0; y < sizey; y ++) { if (drop && (world[y-1][x+1] == enemy || world[y-1][x+1] == enemyShielded)){ world[y][x] = world[y-1][x+1]; world[y-1][x+1] = ' '; } else if (!drop && (world[y][x+1] == enemy || world[y][x+1] == enemyShielded)) { world[y][x] = world[y][x+1]; world[y][x+1] = ' '; } } } } else { for (x = sizex; x > 0; x --) { for (y = 0; y < sizey; y ++) { if (drop && (world[y-1][x-1] == enemy || world[y-1][x-1] == enemyShielded)) { world[y][x] = world[y-1][x-1]; world[y-1][x-1] = ' '; } else if (!drop && (world[y][x-1] == enemy || world[y][x-1] == enemyShielded)) { world[y][x] = world[y][x-1]; world[y][x-1] = ' '; } } } } for (x = 0; x < sizex; x ++) { if (world[sizey - 1][x] == enemy) { victory = 0; } } } } } //game management for world 2 #pragma omp task shared (world2, score2, victory2) { int drop = 0; int enemySpeed = 1 + 10 * currentEnemies / totalEnemies; #pragma omp critical { for (x = 0; x < sizex; x ++) { for (y = 0; y < sizey; y ++) { if ((i % 5) == 0 && (world2[y][x] == enemyShielded || world2[y][x] == enemy) && (rand() % 15) > 13 && world2[y+1][x] != playerLaser) { for (yi = y+1; yi < sizey; yi ++) { if (world2[yi][x] == enemy || world2[yi][x] == enemyShielded) { enemyReady = 0; break; } enemyReady = 1; } if (enemyReady) { world2[y+1][x] = enemyLaser; } } if (world2[y][x] == playerLaser && world2[y-1][x] == enemy) { world2[y][x] = ' '; world2[y-1][x] = explosion; currentEnemies --; score2 = score2 + 50; } else if (world2[y][x] == playerLaser && world2[y-1][x] == enemyShielded) { world2[y][x] = ' '; world2[y-1][x] = enemy; currentEnemies --; score2 = score2 + 50; } else if (world2[y][x] == playerLaser && world2[y-1][x] == enemyLaser) { world2[y][x] = ' '; } else if (world2[y][x] == explosion) { world2[y][x] = ' '; } else if ((i+1) % 2 == 0 && world2[y][x] == enemyLaser && world2[y+1][x] == player) { world2[y+1][x] = explosion; world2[y][x] = ' '; victory2 = 0; } else if (world2[y][x] == playerLaser && world2[y-1][x] != enemyLaser) { world2[y-1][x] = playerLaser; world2[y][x] = ' '; } } } } #pragma omp critical { //Enemy movement (left/right) for (y = 0; y < sizey; y ++) { if (world2[y][0] == enemy) { direction = 'r'; drop = 1; break; } if (world2[y][sizex-1] == enemy){ direction = 'l'; drop = 1; break; } } } #pragma omp critical { //enemy movement(down) if (i % enemySpeed == 0) { if (direction == 'l') { for (x = 0; x < sizex - 1; x ++) { for (y = 0; y < sizey; y ++) { if (drop && (world2[y-1][x+1] == enemy || world2[y-1][x+1] == enemyShielded)){ world2[y][x] = world2[y-1][x+1]; world2[y-1][x+1] = ' '; } else if (!drop && (world2[y][x+1] == enemy || world2[y][x+1] == enemyShielded)) { world2[y][x] = world2[y][x+1]; world2[y][x+1] = ' '; } } } } else { for (x = sizex; x > 0; x --) { for (y = 0; y < sizey; y ++) { if (drop && (world2[y-1][x-1] == enemy || world2[y-1][x-1] == enemyShielded)) { world2[y][x] = world2[y-1][x-1]; world2[y-1][x-1] = ' '; } else if (!drop && (world2[y][x-1] == enemy || world2[y][x-1] == enemyShielded)) { world2[y][x] = world2[y][x-1]; world2[y][x-1] = ' '; } } } } for (x = 0; x < sizex; x ++) { if (world2[sizey - 1][x] == enemy) { victory2 = 0; } } } } } //error handling #pragma omp taskwait int a = 0, b = 0; for(x = 0; x < sizex; x++){ world[sizey-1][x] = ' '; world2[sizey-1][x] = ' '; world[0][x] = ' '; world2[0][x] = ' '; if(world[sizey-2][x] == player){ a++; } if(world2[sizey-2][x] == player){ b++; } } if(a == 0) victory2 = 0; if(b == 0) victory = 0; //print area for multiplayer system("cls"); printf("\t\tSCORE: %d\t\t\t\t SCORE : %d", score, score2); printf("\n"); for (y = 0; y < sizey; y ++) { printf("|"); for (x = 0; x < sizex; x ++) { printf("%c",world[y][x]); } printf("|"); for (x = 0; x < sizex; x ++){ printf("%c",world2[y][x]); } printf("| \n"); } Sleep(refresh); } while (victory && victory2); } } //match report t2 = omp_get_wtime(); system("cls"); print_gameover(); Sleep(1000); printf("\n\n\n\n\n\n "); if(victory && !victory2)printf("Player 2 WIN"); else if (victory2 && !victory) printf("Player 1 WIN"); Sleep(1000); printf("\n\n Score Player 1 = %d", score); Sleep(1000); printf("\n\n Score Player 2 = %d", score2); Sleep(1000); printf("\n\n Time = %f", t2-t1); printf("\n\n\nPress any key to continue..."); getch(); system("cls"); }
GB_unaryop__minv_int16_fp64.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_int16_fp64 // op(A') function: GB_tran__minv_int16_fp64 // C type: int16_t // A type: double // cast: int16_t cij ; GB_CAST_SIGNED(cij,aij,16) // unaryop: cij = GB_IMINV_SIGNED (aij, 16) #define GB_ATYPE \ double #define GB_CTYPE \ int16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ double aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_IMINV_SIGNED (x, 16) ; // casting #define GB_CASTING(z, x) \ int16_t z ; GB_CAST_SIGNED(z,x,16) ; // 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_INT16 || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_int16_fp64 ( int16_t *restrict Cx, const double *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_int16_fp64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
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-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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* 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/channel.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/delegate.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",MagickPathExtent); 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(MatteColor,AllCompliance,&image->matte_color, exception); (void) QueryColorCompliance(BackgroundColor,AllCompliance, &image->background_color,exception); (void) QueryColorCompliance(BorderColor,AllCompliance,&image->border_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=MagickCoreSignature; 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, MagickPathExtent); (void) CopyMagickString(image->magick_filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick,image_info->magick,MagickPathExtent); 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->matte_color=image_info->matte_color; image->background_color=image_info->background_color; image->border_color=image_info->border_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. */ 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 == MagickCoreSignature); 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, MagickPathExtent); if (image_info != (ImageInfo *) NULL) (void) CopyMagickString(GetNextImageInList(image)->filename, image_info->filename,MagickPathExtent); 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 homogeneous_colorspace, status; MagickOffsetType n; PixelTrait alpha_trait; RectangleInfo geometry; register const Image *next; size_t depth, height, number_images, width; ssize_t x_offset, y, y_offset; /* Compute maximum area of appended area. */ assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); alpha_trait=images->alpha_trait; number_images=1; width=images->columns; height=images->rows; depth=images->depth; homogeneous_colorspace=MagickTrue; next=GetNextImageInList(images); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { if (next->depth > depth) depth=next->depth; if (next->colorspace != images->colorspace) homogeneous_colorspace=MagickFalse; if (next->alpha_trait != UndefinedPixelTrait) 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); } if (homogeneous_colorspace == MagickFalse) (void) SetImageColorspace(append_image,sRGBColorspace,exception); append_image->depth=depth; append_image->alpha_trait=alpha_trait; append_image->page=images->page; (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; MagickBooleanType proceed; SetGeometry(append_image,&geometry); GravityAdjustGeometry(next->columns,next->rows,next->gravity,&geometry); if (stack != MagickFalse) x_offset-=geometry.x; else y_offset-=geometry.y; image_view=AcquireVirtualCacheView(next,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(next,next,next->rows,1) #endif for (y=0; y < (ssize_t) next->rows; y++) { MagickBooleanType sync; PixelInfo pixel; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,next->columns,1,exception); q=QueueCacheViewAuthenticPixels(append_view,x_offset,y+y_offset, next->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } GetPixelInfo(next,&pixel); for (x=0; x < (ssize_t) next->columns; x++) { if (GetPixelWriteMask(next,p) <= (QuantumRange/2)) { SetPixelBackgoundColor(append_image,q); p+=GetPixelChannels(next); q+=GetPixelChannels(append_image); continue; } GetPixelInfoPixel(next,p,&pixel); SetPixelViaPixelInfo(append_image,&pixel,q); p+=GetPixelChannels(next); 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) next->columns; y_offset=0; } else { x_offset=0; y_offset+=(ssize_t) next->rows; } 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 == MagickCoreSignature); 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 == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pathname != NULL); property=AcquireString(pathname); (void) FormatLocaleString(property,MagickPathExtent,"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, MagickPathExtent); (void) ConcatenateMagickString(image_info->filename,pathname, MagickPathExtent); 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,MagickPathExtent, "8BIM:1999,2998:%s\nPS",pathname); (void) SetImageMask(image,WritePixelMask,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 == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if ((image->columns == 0) || (image->rows == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "NegativeOrZeroImageSize","`%s'",image->filename); return((Image *) NULL); } 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=MagickCoreSignature; 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; clone_image->image_info=CloneImageInfo(image->image_info); (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, MagickPathExtent); (void) CopyMagickString(clone_image->magick,image->magick,MagickPathExtent); (void) CopyMagickString(clone_image->filename,image->filename, MagickPathExtent); 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 (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+1, sizeof(*clone_image->colormap)); if (clone_image->colormap == (PixelInfo *) NULL) { clone_image=DestroyImage(clone_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } (void) CopyMagickMemory(clone_image->colormap,image->colormap,length* sizeof(*clone_image->colormap)); } 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->cache=ClonePixelCache(image->cache); if (SetImageExtent(clone_image,columns,rows,exception) == MagickFalse) clone_image=DestroyImage(clone_image); 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->matte_color=image_info->matte_color; clone_info->background_color=image_info->background_color; clone_info->border_color=image_info->border_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->ping=image_info->ping; clone_info->verbose=image_info->verbose; 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; clone_info->custom_stream=image_info->custom_stream; (void) CopyMagickString(clone_info->magick,image_info->magick, MagickPathExtent); (void) CopyMagickString(clone_info->unique,image_info->unique, MagickPathExtent); (void) CopyMagickString(clone_info->filename,image_info->filename, MagickPathExtent); 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); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o p y I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CopyImagePixels() copies pixels from the source image as defined by the % geometry the destination image at the specified offset. % % The format of the CopyImagePixels method is: % % MagickBooleanType CopyImagePixels(Image *image,const Image *source_image, % const RectangleInfo *geometry,const OffsetInfo *offset, % ExceptionInfo *exception); % % A description of each parameter follows: % % o image: the destination image. % % o source_image: the source image. % % o geometry: define the dimensions of the source pixel rectangle. % % o offset: define the offset in the destination image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType CopyImagePixels(Image *image, const Image *source_image,const RectangleInfo *geometry, const OffsetInfo *offset,ExceptionInfo *exception) { #define CopyImageTag "Copy/Image" CacheView *image_view, *source_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(source_image != (Image *) NULL); assert(geometry != (RectangleInfo *) NULL); assert(offset != (OffsetInfo *) NULL); if ((offset->x < 0) || (offset->y < 0) || ((ssize_t) (offset->x+geometry->width) > (ssize_t) image->columns) || ((ssize_t) (offset->y+geometry->height) > (ssize_t) image->rows)) ThrowBinaryException(OptionError,"GeometryDoesNotContainImage", image->filename); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); /* Copy image pixels. */ status=MagickTrue; progress=0; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,source_image,geometry->height,1) #endif for (y=0; y < (ssize_t) geometry->height; y++) { MagickBooleanType sync; register const Quantum *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(source_view,geometry->x,y+geometry->y, geometry->width,1,exception); q=QueueCacheViewAuthenticPixels(image_view,offset->x,y+offset->y, geometry->width,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) geometry->width; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits=GetPixelChannelTraits(source_image,channel); if ((traits == UndefinedPixelTrait) || ((traits & UpdatePixelTrait) == 0) || (source_traits == UndefinedPixelTrait)) continue; SetPixelChannel(image,channel,p[i],q); } p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_CopyImage) #endif proceed=SetImageProgress(image,CopyImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % 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 == MagickCoreSignature); 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); if (image->image_info != (ImageInfo *) NULL) image->image_info=DestroyImageInfo(image->image_info); DestroyBlob(image); if (image->semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&image->semaphore); image->signature=(~MagickCoreSignature); 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 == MagickCoreSignature); 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->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=(~MagickCoreSignature); 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 == MagickCoreSignature); 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=MagickCoreSignature; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % 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,const PixelMask type, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o type: the mask type, ReadPixelMask or WritePixelMask. % */ MagickExport Image *GetImageMask(const Image *image,const PixelMask type, 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 == MagickCoreSignature); mask_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (mask_image == (Image *) NULL) return((Image *) NULL); status=MagickTrue; mask_image->alpha_trait=UndefinedPixelTrait; (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 *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=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++) { switch (type) { case WritePixelMask: { SetPixelGray(mask_image,GetPixelWriteMask(image,p),q); break; } default: { SetPixelGray(mask_image,GetPixelReadMask(image,p),q); break; } } 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 == MagickCoreSignature); 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 == MagickCoreSignature); 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,MagickPathExtent); 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 foo; foo=(ssize_t) strtol(q,&q,10); (void) foo; } switch (*q) { case 'd': case 'o': case 'x': { q++; c=(*q); *q='\0'; (void) FormatLocaleString(filename+(p-format),(size_t) (MagickPathExtent-(p-format)),p,value); *q=c; (void) ConcatenateMagickString(filename,q,MagickPathExtent); canonical=MagickTrue; if (*(q-1) != '%') break; p++; break; } case '[': { char pattern[MagickPathExtent]; const char *option; 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 < (MagickPathExtent-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; option=(const char *) NULL; if (image != (Image *) NULL) option=GetImageProperty(image,pattern,exception); if ((option == (const char *) NULL) && (image != (Image *) NULL)) option=GetImageArtifact(image,pattern); if ((option == (const char *) NULL) && (image_info != (ImageInfo *) NULL)) option=GetImageOption(image_info,pattern); if (option == (const char *) NULL) break; q--; c=(*q); *q='\0'; (void) CopyMagickString(filename+(p-format-length),option,(size_t) (MagickPathExtent-(p-format-length))); length+=strlen(pattern)-1; *q=c; (void) ConcatenateMagickString(filename,r+1,MagickPathExtent); 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) (MagickPathExtent-(q-filename))); canonical=MagickTrue; } if (canonical == MagickFalse) (void) CopyMagickString(filename,format,MagickPathExtent); 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 == MagickCoreSignature); 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 (GetPixelWriteMask(image,p) <= (QuantumRange/2)) { 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 != MagickCoreSignature) 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[MagickPathExtent], filename[MagickPathExtent]; register const Image *p; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); (void) CopyMagickString(magick,image->magick,MagickPathExtent); (void) CopyMagickString(filename,image->filename,MagickPathExtent); 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 == MagickCoreSignature); 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 == MagickCoreSignature); 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 *magick_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++) { SetPixelViaPixelInfo(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 == MagickCoreSignature); 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 == MagickCoreSignature); 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 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 == MagickCoreSignature); 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 *magick_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 (GetPixelWriteMask(image,q) > (QuantumRange/2)) 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 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; PixelInfo background; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if ((image->background_color.alpha != OpaqueAlpha) && (image->alpha_trait == UndefinedPixelTrait)) (void) SetImageAlphaChannel(image,OnAlphaChannel,exception); ConformPixelInfo(image,&image->background_color,&background,exception); /* Set image background color. */ status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_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++) { SetPixelViaPixelInfo(image,&background,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) { return(SetPixelChannelMask(image,channel_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 == MagickCoreSignature); 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 *magick_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++) { SetPixelViaPixelInfo(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) { 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); 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)) ThrowBinaryException(ImageError,"NegativeOrZeroImageSize",image->filename); image->columns=columns; image->rows=rows; if (image->depth > (8*sizeof(MagickSizeType))) ThrowBinaryException(ImageError,"ImageDepthNotSupported",image->filename); 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 component[MagickPathExtent], magic[MagickPathExtent], *q; const MagicInfo *magic_info; const MagickInfo *magick_info; ExceptionInfo *sans_exception; Image *image; MagickBooleanType status; register const char *p; ssize_t count; /* Look for 'image.format' in filename. */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); *component='\0'; GetPathComponent(image_info->filename,SubimagePath,component); if (*component != '\0') { /* Look for scene specification (e.g. img0001.pcd[4]). */ if (IsSceneGeometry(component,MagickFalse) == MagickFalse) { if (IsGeometry(component) != MagickFalse) (void) CloneString(&image_info->extract,component); } else { size_t first, last; (void) CloneString(&image_info->scenes,component); 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; } } *component='\0'; if (*image_info->magick == '\0') GetPathComponent(image_info->filename,ExtensionPath,component); #if defined(MAGICKCORE_ZLIB_DELEGATE) if (*component != '\0') if ((LocaleCompare(component,"gz") == 0) || (LocaleCompare(component,"Z") == 0) || (LocaleCompare(component,"svgz") == 0) || (LocaleCompare(component,"wmz") == 0)) { char path[MagickPathExtent]; (void) CopyMagickString(path,image_info->filename,MagickPathExtent); path[strlen(path)-strlen(component)-1]='\0'; GetPathComponent(path,ExtensionPath,component); } #endif #if defined(MAGICKCORE_BZLIB_DELEGATE) if (*component != '\0') if (LocaleCompare(component,"bz2") == 0) { char path[MagickPathExtent]; (void) CopyMagickString(path,image_info->filename,MagickPathExtent); path[strlen(path)-strlen(component)-1]='\0'; GetPathComponent(path,ExtensionPath,component); } #endif image_info->affirm=MagickFalse; sans_exception=AcquireExceptionInfo(); if (*component != '\0') { MagickFormatType format_type; register ssize_t i; static const char *format_type_formats[] = { "AUTOTRACE", "BROWSE", "DCRAW", "EDIT", "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,component,MagickPathExtent); LocaleUpper(magic); /* Look for explicit image formats. */ format_type=UndefinedFormatType; magick_info=GetMagickInfo(magic,sans_exception); if ((magick_info != (const MagickInfo *) NULL) && (magick_info->format_type != UndefinedFormatType)) format_type=magick_info->format_type; 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++; } if (format_type == UndefinedFormatType) (void) CopyMagickString(image_info->magick,magic,MagickPathExtent); else if (format_type == ExplicitFormatType) { image_info->affirm=MagickTrue; (void) CopyMagickString(image_info->magick,magic,MagickPathExtent); } 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,MagickPathExtent); magick_info=GetMagickInfo(magic,sans_exception); GetPathComponent(image_info->filename,CanonicalPath,component); (void) CopyMagickString(image_info->filename,component,MagickPathExtent); } else { const DelegateInfo *delegate_info; /* User specified image format. */ LocaleUpper(magic); magick_info=GetMagickInfo(magic,sans_exception); delegate_info=GetDelegateInfo(magic,"*",sans_exception); if (delegate_info == (const DelegateInfo *) NULL) delegate_info=GetDelegateInfo("*",magic,sans_exception); if (((magick_info != (const MagickInfo *) NULL) || (delegate_info != (const DelegateInfo *) NULL)) && (IsMagickConflict(magic) == MagickFalse)) { image_info->affirm=MagickTrue; (void) CopyMagickString(image_info->magick,magic,MagickPathExtent); GetPathComponent(image_info->filename,CanonicalPath,component); (void) CopyMagickString(image_info->filename,component, MagickPathExtent); } } sans_exception=DestroyExceptionInfo(sans_exception); if ((magick_info == (const MagickInfo *) NULL) || (GetMagickEndianSupport(magick_info) == MagickFalse)) image_info->endian=UndefinedEndian; 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,component,exception); if ((LocaleCompare(component,image_info->filename) != 0) && (strchr(component,'%') == (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) { unsigned char *magick; size_t magick_size; /* Determine the image format from the first few bytes of the file. */ magick_size=GetMagicPatternExtent(exception); if (magick_size == 0) return(MagickFalse); image=AcquireImage(image_info,exception); (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); 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. */ *component='\0'; status=ImageToFile(image,component,exception); (void) CloseBlob(image); if (status == MagickFalse) { image=DestroyImage(image); return(MagickFalse); } SetImageInfoFile(image_info,(FILE *) NULL); (void) CopyMagickString(image->filename,component,MagickPathExtent); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImage(image); return(MagickFalse); } (void) CopyMagickString(image_info->filename,component, MagickPathExtent); image_info->temporary=MagickTrue; } magick=(unsigned char *) AcquireMagickMemory(magick_size); if (magick == (unsigned char *) NULL) { (void) CloseBlob(image); image=DestroyImage(image); return(MagickFalse); } (void) ResetMagickMemory(magick,0,magick_size); count=ReadBlob(image,magick_size,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); magick=(unsigned char *) RelinquishMagickMemory(magick); if ((magic_info != (const MagicInfo *) NULL) && (GetMagicName(magic_info) != (char *) NULL)) { /* Try to use magick_info that was determined earlier by the extension */ if ((magick_info != (const MagickInfo *) NULL) && (GetMagickUseExtension(magick_info) != MagickFalse) && (LocaleCompare(magick_info->module,GetMagicName( magic_info)) == 0)) (void) CopyMagickString(image_info->magick,magick_info->name, MagickPathExtent); else { (void) CopyMagickString(image_info->magick,GetMagicName( magic_info),MagickPathExtent); 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 == MagickCoreSignature); 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 C u s t o m S t r e a m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageInfoCustomStream() sets the image info custom stream handlers. % % The format of the SetImageInfoCustomStream method is: % % void SetImageInfoCustomStream(ImageInfo *image_info, % CustomStreamInfo *custom_stream) % % A description of each parameter follows: % % o image_info: the image info. % % o custom_stream: your custom stream methods. % */ MagickExport void SetImageInfoCustomStream(ImageInfo *image_info, CustomStreamInfo *custom_stream) { assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); image_info->custom_stream=(CustomStreamInfo *) custom_stream; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % 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 == MagickCoreSignature); 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 PixelMask type, % const Image *mask,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o type: the mask type, ReadPixelMask or WritePixelMask. % % o mask: the image mask. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageMask(Image *image,const PixelMask type, 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 == MagickCoreSignature); if (mask == (const Image *) NULL) { switch (type) { case WritePixelMask: image->write_mask=MagickFalse; break; default: image->read_mask=MagickFalse; break; } return(SyncImagePixelCache(image,exception)); } switch (type) { case WritePixelMask: image->write_mask=MagickTrue; break; default: image->read_mask=MagickTrue; break; } 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 *magick_restrict p; register Quantum *magick_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++) { MagickRealType intensity; intensity=0; if ((x < (ssize_t) mask->columns) && (y < (ssize_t) mask->rows)) intensity=GetPixelIntensity(mask,p); switch (type) { case WritePixelMask: { SetPixelWriteMask(image,ClampToQuantum(intensity),q); break; } default: { SetPixelReadMask(image,ClampToQuantum(intensity),q); break; } } 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 R e g i o n M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageRegionMask() associates a mask with the image as defined by the % specified region. % % The format of the SetImageRegionMask method is: % % MagickBooleanType SetImageRegionMask(Image *image,const PixelMask type, % const RectangleInfo *region,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o type: the mask type, ReadPixelMask or WritePixelMask. % % o geometry: the mask region. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageRegionMask(Image *image, const PixelMask type,const RectangleInfo *region,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; /* Set image mask as defined by the region. */ assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (region == (const RectangleInfo *) NULL) { switch (type) { case WritePixelMask: image->write_mask=MagickFalse; break; default: image->read_mask=MagickFalse; break; } return(SyncImagePixelCache(image,exception)); } switch (type) { case WritePixelMask: image->write_mask=MagickTrue; break; default: image->read_mask=MagickTrue; break; } if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); 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,1,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=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++) { Quantum pixel; pixel=0; if (((x >= region->x) && (x < (region->x+(ssize_t) region->width))) && ((y >= region->y) && (y < (region->y+(ssize_t) region->height)))) pixel=QuantumRange; switch (type) { case WritePixelMask: { SetPixelWriteMask(image,pixel,q); break; } default: { SetPixelReadMask(image,pixel,q); break; } } 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 == MagickCoreSignature); 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 == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); 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 != UndefinedPixelTrait) 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", "bKGD,caNv,cHRM,eXIf,gAMA,iCCP,iTXt,pHYs,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, taint; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (image->ping != MagickFalse) return(MagickTrue); if (image->storage_class != PseudoClass) return(MagickFalse); assert(image->colormap != (PixelInfo *) NULL); range_exception=MagickFalse; status=MagickTrue; taint=image->taint; 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 *magick_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); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); image->taint=taint; if ((image->ping == MagickFalse) && (range_exception != MagickFalse)) (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,"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 == MagickCoreSignature); assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); 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 == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); 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); /* 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) { 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=(FilterType) 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; } /* Pointer to allow the lookup of pre-image artifact 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 preserved when parenthesis ends. */ if (image->image_info != (ImageInfo *) NULL) image->image_info=DestroyImageInfo(image->image_info); image->image_info=CloneImageInfo(image_info); return(MagickTrue); }
GB_unop__frexpx_fp32_fp32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__frexpx_fp32_fp32) // op(A') function: GB (_unop_tran__frexpx_fp32_fp32) // C type: float // A type: float // cast: float cij = aij // unaryop: cij = GB_frexpxf (aij) #define GB_ATYPE \ float #define GB_CTYPE \ float // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_frexpxf (x) ; // casting #define GB_CAST(z, aij) \ float z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ float z = aij ; \ Cx [pC] = GB_frexpxf (z) ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_FREXPX || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__frexpx_fp32_fp32) ( float *Cx, // Cx and Ax may be aliased const float *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; // TODO: if OP is ONE and uniform-valued matrices are exploited, then // do this in O(1) time if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (float), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; float z = aij ; Cx [p] = GB_frexpxf (z) ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; float aij = Ax [p] ; float z = aij ; Cx [p] = GB_frexpxf (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__frexpx_fp32_fp32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unop__sqrt_fc32_fc32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the 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__sqrt_fc32_fc32) // op(A') function: GB (_unop_tran__sqrt_fc32_fc32) // C type: GxB_FC32_t // A type: GxB_FC32_t // cast: GxB_FC32_t cij = aij // unaryop: cij = csqrtf (aij) #define GB_ATYPE \ GxB_FC32_t #define GB_CTYPE \ GxB_FC32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = csqrtf (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC32_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC32_t z = aij ; \ Cx [pC] = csqrtf (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_SQRT || GxB_NO_FC32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__sqrt_fc32_fc32) ( GxB_FC32_t *Cx, // Cx and Ax may be aliased const GxB_FC32_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; // TODO: if OP is ONE and uniform-valued matrices are exploited, then // do this in O(1) time if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (GxB_FC32_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC32_t aij = Ax [p] ; GxB_FC32_t z = aij ; Cx [p] = csqrtf (z) ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC32_t aij = Ax [p] ; GxB_FC32_t z = aij ; Cx [p] = csqrtf (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__sqrt_fc32_fc32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
omp2-2.c
#include<math.h> #include<stdio.h> #define N 1000000 int main() { int i; double x, area = 0; //#pragma omp parallel for private(x) for (i = 0; i < N; i++) { x = (i + .5) / N; area += 4 / (1 + x*x); } printf("%.10lf\n", area/N); return 0; }
pr81006.c
/* PR c/81006 */ /* { dg-do compile } */ int a[] = {}; void foo() { #pragma omp task depend(out: a[:]) /* { dg-error "zero length array section in .depend. clause" } */ {} }
GB_unop__identity_uint16_uint64.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_uint64) // op(A') function: GB (_unop_tran__identity_uint16_uint64) // C type: uint16_t // A type: uint64_t // cast: uint16_t cij = (uint16_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint64_t #define GB_CTYPE \ uint16_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) \ uint16_t z = (uint16_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint16_t z = (uint16_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_UINT16 || GxB_NO_UINT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_uint16_uint64) ( uint16_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 ; // TODO: if OP is ONE and uniform-valued matrices are exploited, then // do this in O(1) time if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (uint64_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint64_t aij = Ax [p] ; uint16_t z = (uint16_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 ; uint64_t aij = Ax [p] ; uint16_t z = (uint16_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_uint16_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
GeneralMatrixMatrix.h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef EIGEN_GENERAL_MATRIX_MATRIX_H #define EIGEN_GENERAL_MATRIX_MATRIX_H namespace Eigen { namespace internal { template<typename _LhsScalar, typename _RhsScalar> class level3_blocking; /* Specialization for a row-major destination matrix => simple transposition of the product */ template< typename Index, typename LhsScalar, int LhsStorageOrder, bool ConjugateLhs, typename RhsScalar, int RhsStorageOrder, bool ConjugateRhs> struct general_matrix_matrix_product<Index,LhsScalar,LhsStorageOrder,ConjugateLhs,RhsScalar,RhsStorageOrder,ConjugateRhs,RowMajor> { typedef gebp_traits<RhsScalar,LhsScalar> Traits; typedef typename ScalarBinaryOpTraits<LhsScalar, RhsScalar>::ReturnType ResScalar; static EIGEN_STRONG_INLINE void run( Index rows, Index cols, Index depth, const LhsScalar* lhs, Index lhsStride, const RhsScalar* rhs, Index rhsStride, ResScalar* res, Index resStride, ResScalar alpha, level3_blocking<RhsScalar,LhsScalar>& blocking, GemmParallelInfo<Index>* info = 0) { // transpose the product such that the result is column major general_matrix_matrix_product<Index, RhsScalar, RhsStorageOrder==RowMajor ? ColMajor : RowMajor, ConjugateRhs, LhsScalar, LhsStorageOrder==RowMajor ? ColMajor : RowMajor, ConjugateLhs, ColMajor> ::run(cols,rows,depth,rhs,rhsStride,lhs,lhsStride,res,resStride,alpha,blocking,info); } }; /* Specialization for a col-major destination matrix * => Blocking algorithm following Goto's paper */ template< typename Index, typename LhsScalar, int LhsStorageOrder, bool ConjugateLhs, typename RhsScalar, int RhsStorageOrder, bool ConjugateRhs> struct general_matrix_matrix_product<Index,LhsScalar,LhsStorageOrder,ConjugateLhs,RhsScalar,RhsStorageOrder,ConjugateRhs,ColMajor> { typedef gebp_traits<LhsScalar,RhsScalar> Traits; typedef typename ScalarBinaryOpTraits<LhsScalar, RhsScalar>::ReturnType ResScalar; static void run(Index rows, Index cols, Index depth, const LhsScalar* _lhs, Index lhsStride, const RhsScalar* _rhs, Index rhsStride, ResScalar* _res, Index resStride, ResScalar alpha, level3_blocking<LhsScalar,RhsScalar>& blocking, GemmParallelInfo<Index>* info = 0) { typedef const_blas_data_mapper<LhsScalar, Index, LhsStorageOrder> LhsMapper; typedef const_blas_data_mapper<RhsScalar, Index, RhsStorageOrder> RhsMapper; typedef blas_data_mapper<typename Traits::ResScalar, Index, ColMajor> ResMapper; LhsMapper lhs(_lhs,lhsStride); RhsMapper rhs(_rhs,rhsStride); ResMapper res(_res, resStride); Index kc = blocking.kc(); // cache block size along the K direction Index mc = (std::min)(rows,blocking.mc()); // cache block size along the M direction Index nc = (std::min)(cols,blocking.nc()); // cache block size along the N direction gemm_pack_lhs<LhsScalar, Index, LhsMapper, Traits::mr, Traits::LhsProgress, LhsStorageOrder> pack_lhs; gemm_pack_rhs<RhsScalar, Index, RhsMapper, Traits::nr, RhsStorageOrder> pack_rhs; gebp_kernel<LhsScalar, RhsScalar, Index, ResMapper, Traits::mr, Traits::nr, ConjugateLhs, ConjugateRhs> gebp; #ifdef EIGEN_HAS_OPENMP if(info) { // this is the parallel version! int tid = omp_get_thread_num(); int threads = omp_get_num_threads(); LhsScalar* blockA = blocking.blockA(); eigen_internal_assert(blockA!=0); std::size_t sizeB = kc*nc; ei_declare_aligned_stack_constructed_variable(RhsScalar, blockB, sizeB, 0); // For each horizontal panel of the rhs, and corresponding vertical panel of the lhs... for(Index k=0; k<depth; k+=kc) { const Index actual_kc = (std::min)(k+kc,depth)-k; // => rows of B', and cols of the A' // In order to reduce the chance that a thread has to sleep for the other, // let's start by packing B'. pack_rhs(blockB, rhs.getSubMapper(k,0), actual_kc, nc); // Pack A_k to A' in a parallel fashion: // each thread packs the sub block A_k,i to A'_i where i is the thread id. // However, before copying to A'_i, we have to make sure that no other thread is still using it, // i.e., we test that info[tid].users equals 0. // Then, we set info[tid].users to the number of threads to mark that all other threads are going to use it. while(info[tid].users!=0) {} info[tid].users += threads; pack_lhs(blockA+info[tid].lhs_start*actual_kc, lhs.getSubMapper(info[tid].lhs_start,k), actual_kc, info[tid].lhs_length); // Notify the other threads that the part A'_i is ready to go. info[tid].sync = k; // Computes C_i += A' * B' per A'_i for(int shift=0; shift<threads; ++shift) { int i = (tid+shift)%threads; // At this point we have to make sure that A'_i has been updated by the thread i, // we use testAndSetOrdered to mimic a volatile access. // However, no need to sleep for the B' part which has been updated by the current thread! if (shift>0) { while(info[i].sync!=k) { } } gebp(res.getSubMapper(info[i].lhs_start, 0), blockA+info[i].lhs_start*actual_kc, blockB, info[i].lhs_length, actual_kc, nc, alpha); } // Then keep going as usual with the remaining B' for(Index j=nc; j<cols; j+=nc) { const Index actual_nc = (std::min)(j+nc,cols)-j; // pack B_k,j to B' pack_rhs(blockB, rhs.getSubMapper(k,j), actual_kc, actual_nc); // C_j += A' * B' gebp(res.getSubMapper(0, j), blockA, blockB, rows, actual_kc, actual_nc, alpha); } // Release all the sub blocks A'_i of A' for the current thread, // i.e., we simply decrement the number of users by 1 for(Index i=0; i<threads; ++i) #pragma omp atomic info[i].users -= 1; } } else #endif // EIGEN_HAS_OPENMP { EIGEN_UNUSED_VARIABLE(info); // this is the sequential version! std::size_t sizeA = kc*mc; std::size_t sizeB = kc*nc; ei_declare_aligned_stack_constructed_variable(LhsScalar, blockA, sizeA, blocking.blockA()); ei_declare_aligned_stack_constructed_variable(RhsScalar, blockB, sizeB, blocking.blockB()); const bool pack_rhs_once = mc!=rows && kc==depth && nc==cols; // For each horizontal panel of the rhs, and corresponding panel of the lhs... for(Index i2=0; i2<rows; i2+=mc) { const Index actual_mc = (std::min)(i2+mc,rows)-i2; for(Index k2=0; k2<depth; k2+=kc) { const Index actual_kc = (std::min)(k2+kc,depth)-k2; // OK, here we have selected one horizontal panel of rhs and one vertical panel of lhs. // => Pack lhs's panel into a sequential chunk of memory (L2/L3 caching) // Note that this panel will be read as many times as the number of blocks in the rhs's // horizontal panel which is, in practice, a very low number. pack_lhs(blockA, lhs.getSubMapper(i2,k2), actual_kc, actual_mc); // For each kc x nc block of the rhs's horizontal panel... for(Index j2=0; j2<cols; j2+=nc) { const Index actual_nc = (std::min)(j2+nc,cols)-j2; // We pack the rhs's block into a sequential chunk of memory (L2 caching) // Note that this block will be read a very high number of times, which is equal to the number of // micro horizontal panel of the large rhs's panel (e.g., rows/12 times). if((!pack_rhs_once) || i2==0) pack_rhs(blockB, rhs.getSubMapper(k2,j2), actual_kc, actual_nc); // Everything is packed, we can now call the panel * block kernel: gebp(res.getSubMapper(i2, j2), blockA, blockB, actual_mc, actual_kc, actual_nc, alpha); } } } } } }; /********************************************************************************* * Specialization of generic_product_impl for "large" GEMM, i.e., * implementation of the high level wrapper to general_matrix_matrix_product **********************************************************************************/ template<typename Scalar, typename Index, typename Gemm, typename Lhs, typename Rhs, typename Dest, typename BlockingType> struct gemm_functor { gemm_functor(const Lhs& lhs, const Rhs& rhs, Dest& dest, const Scalar& actualAlpha, BlockingType& blocking) : m_lhs(lhs), m_rhs(rhs), m_dest(dest), m_actualAlpha(actualAlpha), m_blocking(blocking) {} void initParallelSession(Index num_threads) const { m_blocking.initParallel(m_lhs.rows(), m_rhs.cols(), m_lhs.cols(), num_threads); m_blocking.allocateA(); } void operator() (Index row, Index rows, Index col=0, Index cols=-1, GemmParallelInfo<Index>* info=0) const { if(cols==-1) cols = m_rhs.cols(); Gemm::run(rows, cols, m_lhs.cols(), &m_lhs.coeffRef(row,0), m_lhs.outerStride(), &m_rhs.coeffRef(0,col), m_rhs.outerStride(), (Scalar*)&(m_dest.coeffRef(row,col)), m_dest.outerStride(), m_actualAlpha, m_blocking, info); } typedef typename Gemm::Traits Traits; protected: const Lhs& m_lhs; const Rhs& m_rhs; Dest& m_dest; Scalar m_actualAlpha; BlockingType& m_blocking; }; template<int StorageOrder, typename LhsScalar, typename RhsScalar, int MaxRows, int MaxCols, int MaxDepth, int KcFactor=1, bool FiniteAtCompileTime = MaxRows!=Dynamic && MaxCols!=Dynamic && MaxDepth != Dynamic> class gemm_blocking_space; template<typename _LhsScalar, typename _RhsScalar> class level3_blocking { typedef _LhsScalar LhsScalar; typedef _RhsScalar RhsScalar; protected: LhsScalar* m_blockA; RhsScalar* m_blockB; Index m_mc; Index m_nc; Index m_kc; public: level3_blocking() : m_blockA(0), m_blockB(0), m_mc(0), m_nc(0), m_kc(0) {} inline Index mc() const { return m_mc; } inline Index nc() const { return m_nc; } inline Index kc() const { return m_kc; } inline LhsScalar* blockA() { return m_blockA; } inline RhsScalar* blockB() { return m_blockB; } }; template<int StorageOrder, typename _LhsScalar, typename _RhsScalar, int MaxRows, int MaxCols, int MaxDepth, int KcFactor> class gemm_blocking_space<StorageOrder,_LhsScalar,_RhsScalar,MaxRows, MaxCols, MaxDepth, KcFactor, true /* == FiniteAtCompileTime */> : public level3_blocking< typename conditional<StorageOrder==RowMajor,_RhsScalar,_LhsScalar>::type, typename conditional<StorageOrder==RowMajor,_LhsScalar,_RhsScalar>::type> { enum { Transpose = StorageOrder==RowMajor, ActualRows = Transpose ? MaxCols : MaxRows, ActualCols = Transpose ? MaxRows : MaxCols }; typedef typename conditional<Transpose,_RhsScalar,_LhsScalar>::type LhsScalar; typedef typename conditional<Transpose,_LhsScalar,_RhsScalar>::type RhsScalar; typedef gebp_traits<LhsScalar,RhsScalar> Traits; enum { SizeA = ActualRows * MaxDepth, SizeB = ActualCols * MaxDepth }; #if EIGEN_MAX_STATIC_ALIGN_BYTES >= EIGEN_DEFAULT_ALIGN_BYTES EIGEN_ALIGN_MAX LhsScalar m_staticA[SizeA]; EIGEN_ALIGN_MAX RhsScalar m_staticB[SizeB]; #else EIGEN_ALIGN_MAX char m_staticA[SizeA * sizeof(LhsScalar) + EIGEN_DEFAULT_ALIGN_BYTES-1]; EIGEN_ALIGN_MAX char m_staticB[SizeB * sizeof(RhsScalar) + EIGEN_DEFAULT_ALIGN_BYTES-1]; #endif public: gemm_blocking_space(Index /*rows*/, Index /*cols*/, Index /*depth*/, Index /*num_threads*/, bool /*full_rows = false*/) { this->m_mc = ActualRows; this->m_nc = ActualCols; this->m_kc = MaxDepth; #if EIGEN_MAX_STATIC_ALIGN_BYTES >= EIGEN_DEFAULT_ALIGN_BYTES this->m_blockA = m_staticA; this->m_blockB = m_staticB; #else this->m_blockA = reinterpret_cast<LhsScalar*>((internal::UIntPtr(m_staticA) + (EIGEN_DEFAULT_ALIGN_BYTES-1)) & ~std::size_t(EIGEN_DEFAULT_ALIGN_BYTES-1)); this->m_blockB = reinterpret_cast<RhsScalar*>((internal::UIntPtr(m_staticB) + (EIGEN_DEFAULT_ALIGN_BYTES-1)) & ~std::size_t(EIGEN_DEFAULT_ALIGN_BYTES-1)); #endif } void initParallel(Index, Index, Index, Index) {} inline void allocateA() {} inline void allocateB() {} inline void allocateAll() {} }; template<int StorageOrder, typename _LhsScalar, typename _RhsScalar, int MaxRows, int MaxCols, int MaxDepth, int KcFactor> class gemm_blocking_space<StorageOrder,_LhsScalar,_RhsScalar,MaxRows, MaxCols, MaxDepth, KcFactor, false> : public level3_blocking< typename conditional<StorageOrder==RowMajor,_RhsScalar,_LhsScalar>::type, typename conditional<StorageOrder==RowMajor,_LhsScalar,_RhsScalar>::type> { enum { Transpose = StorageOrder==RowMajor }; typedef typename conditional<Transpose,_RhsScalar,_LhsScalar>::type LhsScalar; typedef typename conditional<Transpose,_LhsScalar,_RhsScalar>::type RhsScalar; typedef gebp_traits<LhsScalar,RhsScalar> Traits; Index m_sizeA; Index m_sizeB; public: gemm_blocking_space(Index rows, Index cols, Index depth, Index num_threads, bool l3_blocking) { this->m_mc = Transpose ? cols : rows; this->m_nc = Transpose ? rows : cols; this->m_kc = depth; if(l3_blocking) { computeProductBlockingSizes<LhsScalar,RhsScalar,KcFactor>(this->m_kc, this->m_mc, this->m_nc, num_threads); } else // no l3 blocking { Index n = this->m_nc; computeProductBlockingSizes<LhsScalar,RhsScalar,KcFactor>(this->m_kc, this->m_mc, n, num_threads); } m_sizeA = this->m_mc * this->m_kc; m_sizeB = this->m_kc * this->m_nc; } void initParallel(Index rows, Index cols, Index depth, Index num_threads) { this->m_mc = Transpose ? cols : rows; this->m_nc = Transpose ? rows : cols; this->m_kc = depth; eigen_internal_assert(this->m_blockA==0 && this->m_blockB==0); Index m = this->m_mc; computeProductBlockingSizes<LhsScalar,RhsScalar,KcFactor>(this->m_kc, m, this->m_nc, num_threads); m_sizeA = this->m_mc * this->m_kc; m_sizeB = this->m_kc * this->m_nc; } void allocateA() { if(this->m_blockA==0) this->m_blockA = aligned_new<LhsScalar>(m_sizeA); } void allocateB() { if(this->m_blockB==0) this->m_blockB = aligned_new<RhsScalar>(m_sizeB); } void allocateAll() { allocateA(); allocateB(); } ~gemm_blocking_space() { aligned_delete(this->m_blockA, m_sizeA); aligned_delete(this->m_blockB, m_sizeB); } }; } // end namespace internal namespace internal { template<typename Lhs, typename Rhs> struct generic_product_impl<Lhs,Rhs,DenseShape,DenseShape,GemmProduct> : generic_product_impl_base<Lhs,Rhs,generic_product_impl<Lhs,Rhs,DenseShape,DenseShape,GemmProduct> > { typedef typename Product<Lhs,Rhs>::Scalar Scalar; typedef typename Lhs::Scalar LhsScalar; typedef typename Rhs::Scalar RhsScalar; typedef internal::blas_traits<Lhs> LhsBlasTraits; typedef typename LhsBlasTraits::DirectLinearAccessType ActualLhsType; typedef typename internal::remove_all<ActualLhsType>::type ActualLhsTypeCleaned; typedef internal::blas_traits<Rhs> RhsBlasTraits; typedef typename RhsBlasTraits::DirectLinearAccessType ActualRhsType; typedef typename internal::remove_all<ActualRhsType>::type ActualRhsTypeCleaned; enum { MaxDepthAtCompileTime = EIGEN_SIZE_MIN_PREFER_FIXED(Lhs::MaxColsAtCompileTime,Rhs::MaxRowsAtCompileTime) }; typedef generic_product_impl<Lhs,Rhs,DenseShape,DenseShape,CoeffBasedProductMode> lazyproduct; template<typename Dst> static void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { if((rhs.rows()+dst.rows()+dst.cols())<20 && rhs.rows()>0) lazyproduct::evalTo(dst, lhs, rhs); else { dst.setZero(); scaleAndAddTo(dst, lhs, rhs, Scalar(1)); } } template<typename Dst> static void addTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { if((rhs.rows()+dst.rows()+dst.cols())<20 && rhs.rows()>0) lazyproduct::addTo(dst, lhs, rhs); else scaleAndAddTo(dst,lhs, rhs, Scalar(1)); } template<typename Dst> static void subTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { if((rhs.rows()+dst.rows()+dst.cols())<20 && rhs.rows()>0) lazyproduct::subTo(dst, lhs, rhs); else scaleAndAddTo(dst, lhs, rhs, Scalar(-1)); } template<typename Dest> static void scaleAndAddTo(Dest& dst, const Lhs& a_lhs, const Rhs& a_rhs, const Scalar& alpha) { eigen_assert(dst.rows()==a_lhs.rows() && dst.cols()==a_rhs.cols()); if(a_lhs.cols()==0 || a_lhs.rows()==0 || a_rhs.cols()==0) return; typename internal::add_const_on_value_type<ActualLhsType>::type lhs = LhsBlasTraits::extract(a_lhs); typename internal::add_const_on_value_type<ActualRhsType>::type rhs = RhsBlasTraits::extract(a_rhs); Scalar actualAlpha = alpha * LhsBlasTraits::extractScalarFactor(a_lhs) * RhsBlasTraits::extractScalarFactor(a_rhs); typedef internal::gemm_blocking_space<(Dest::Flags&RowMajorBit) ? RowMajor : ColMajor,LhsScalar,RhsScalar, Dest::MaxRowsAtCompileTime,Dest::MaxColsAtCompileTime,MaxDepthAtCompileTime> BlockingType; typedef internal::gemm_functor< Scalar, Index, internal::general_matrix_matrix_product< Index, LhsScalar, (ActualLhsTypeCleaned::Flags&RowMajorBit) ? RowMajor : ColMajor, bool(LhsBlasTraits::NeedToConjugate), RhsScalar, (ActualRhsTypeCleaned::Flags&RowMajorBit) ? RowMajor : ColMajor, bool(RhsBlasTraits::NeedToConjugate), (Dest::Flags&RowMajorBit) ? RowMajor : ColMajor>, ActualLhsTypeCleaned, ActualRhsTypeCleaned, Dest, BlockingType> GemmFunctor; BlockingType blocking(dst.rows(), dst.cols(), lhs.cols(), 1, true); internal::parallelize_gemm<(Dest::MaxRowsAtCompileTime>32 || Dest::MaxRowsAtCompileTime==Dynamic)> (GemmFunctor(lhs, rhs, dst, actualAlpha, blocking), a_lhs.rows(), a_rhs.cols(), a_lhs.cols(), Dest::Flags&RowMajorBit); } }; } // end namespace internal } // end namespace Eigen #endif // EIGEN_GENERAL_MATRIX_MATRIX_H
GB_unop__cos_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__cos_fc64_fc64) // op(A') function: GB (_unop_tran__cos_fc64_fc64) // C type: GxB_FC64_t // A type: GxB_FC64_t // cast: GxB_FC64_t cij = aij // unaryop: cij = ccos (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 = ccos (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] = ccos (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_COS || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__cos_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] = ccos (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] = ccos (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__cos_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