source stringlengths 3 92 | c stringlengths 26 2.25M |
|---|---|
lis_matrix_bsc.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_set
* lis_matrix_malloc
* lis_matrix_copy
* lis_matrix_convert
* lis_matrix_get_diagonal
* lis_matrix_scaling
* lis_matrix_scaling_symm
* lis_matrix_normf
* lis_matrix_transpose
************************************************/
#undef __FUNC__
#define __FUNC__ "lis_matrix_set_bsc"
LIS_INT lis_matrix_set_bsc(LIS_INT bnr, LIS_INT bnc, LIS_INT bnnz, LIS_INT *bptr, LIS_INT *bindex, LIS_SCALAR *value, LIS_MATRIX A)
{
LIS_INT err;
LIS_DEBUG_FUNC_IN;
#if 0
err = lis_matrix_check(A,LIS_MATRIX_CHECK_SET);
if( err ) return err;
#else
if(lis_matrix_is_assembled(A)) return LIS_SUCCESS;
else {
err = lis_matrix_check(A,LIS_MATRIX_CHECK_SET);
if( err ) return err;
}
#endif
A->bptr = bptr;
A->bindex = bindex;
A->value = value;
A->is_copy = LIS_FALSE;
A->status = -LIS_MATRIX_BSC;
A->is_block = LIS_TRUE;
A->bnnz = bnnz;
A->nr = (A->n-1)/bnr+1;
A->nc = (A->gn-1)/bnc+1;
if( A->n==A->np )
{
A->nc = 1 + (A->n - 1)/bnc;
A->pad = (bnc - A->n%bnc)%bnc;
}
else
{
A->nc = 2 + (A->n - 1)/bnc + (A->np - A->n - 1)/bnc;
A->pad = (bnc - A->n%bnc)%bnc + (bnc - (A->np-A->n)%bnc)%bnc;
}
A->bnr = bnr;
A->bnc = bnc;
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
#undef __FUNC__
#define __FUNC__ "lis_matrix_setDLU_bsc"
LIS_INT lis_matrix_setDLU_bsc(LIS_INT bnr, LIS_INT bnc, LIS_INT lbnnz, LIS_INT ubnnz, LIS_MATRIX_DIAG D, LIS_INT *lbptr, LIS_INT *lbindex, LIS_SCALAR *lvalue,
LIS_INT *ubptr, LIS_INT *ubindex, LIS_SCALAR *uvalue, LIS_MATRIX A)
{
LIS_INT err;
LIS_DEBUG_FUNC_IN;
#if 0
err = lis_matrix_check(A,LIS_MATRIX_CHECK_SET);
if( err ) return err;
#else
if(lis_matrix_is_assembled(A)) return LIS_SUCCESS;
else {
err = lis_matrix_check(A,LIS_MATRIX_CHECK_SET);
if( err ) return err;
}
#endif
A->L = (LIS_MATRIX_CORE)lis_calloc(sizeof(struct LIS_MATRIX_CORE_STRUCT),"lis_matrix_setDLU_bsc::A->L");
if( A->L==NULL )
{
LIS_SETERR_MEM(sizeof(struct LIS_MATRIX_CORE_STRUCT));
return LIS_OUT_OF_MEMORY;
}
A->U = (LIS_MATRIX_CORE)lis_calloc(sizeof(struct LIS_MATRIX_CORE_STRUCT),"lis_matrix_setDLU_bsc::A->U");
if( A->U==NULL )
{
LIS_SETERR_MEM(sizeof(struct LIS_MATRIX_CORE_STRUCT));
lis_matrix_DLU_destroy(A);
return LIS_OUT_OF_MEMORY;
}
A->D = D;
A->L->bnnz = lbnnz;
A->L->bptr = lbptr;
A->L->bindex = lbindex;
A->L->value = lvalue;
A->U->bnnz = ubnnz;
A->U->bptr = ubptr;
A->U->bindex = ubindex;
A->U->value = uvalue;
A->is_copy = LIS_FALSE;
A->status = -LIS_MATRIX_BSC;
A->is_splited = LIS_TRUE;
A->is_block = LIS_TRUE;
A->nr = (A->n-1)/bnr+1;
A->nc = (A->gn-1)/bnc+1;
if( A->n==A->np )
{
A->nc = 1 + (A->n - 1)/bnc;
A->pad = (bnc - A->n%bnc)%bnc;
}
else
{
A->nc = 2 + (A->n - 1)/bnc + (A->np - A->n - 1)/bnc;
A->pad = (bnc - A->n%bnc)%bnc + (bnc - (A->np-A->n)%bnc)%bnc;
}
A->bnr = bnr;
A->bnc = bnc;
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
#undef __FUNC__
#define __FUNC__ "lis_matrix_malloc_bsc"
LIS_INT lis_matrix_malloc_bsc(LIS_INT n, LIS_INT bnr, LIS_INT bnc, LIS_INT bnnz, LIS_INT **bptr, LIS_INT **bindex, LIS_SCALAR **value)
{
LIS_INT nc;
LIS_DEBUG_FUNC_IN;
nc = 1 + (n -1)/bnc;
*bptr = NULL;
*bindex = NULL;
*value = NULL;
*bptr = (LIS_INT *)lis_malloc( (nc+1)*sizeof(LIS_INT),"lis_matrix_malloc_bsc::bptr" );
if( *bptr==NULL )
{
LIS_SETERR_MEM((nc+1)*sizeof(LIS_INT));
lis_free2(3,*bptr,*bindex,*value);
return LIS_FAILS;
}
*bindex = (LIS_INT *)lis_malloc( bnnz*sizeof(LIS_INT),"lis_matrix_malloc_bsc::bindex" );
if( *bindex==NULL )
{
LIS_SETERR_MEM(bnnz*sizeof(LIS_INT));
lis_free2(3,*bptr,*bindex,*value);
return LIS_OUT_OF_MEMORY;
}
*value = (LIS_SCALAR *)lis_malloc( bnnz*bnr*bnc*sizeof(LIS_SCALAR),"lis_matrix_malloc_bsc::value" );
if( *value==NULL )
{
LIS_SETERR_MEM(bnnz*bnr*bnc*sizeof(LIS_SCALAR));
lis_free2(3,*bptr,*bindex,*value);
return LIS_OUT_OF_MEMORY;
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
#undef __FUNC__
#define __FUNC__ "lis_matrix_elements_copy_bsc"
LIS_INT lis_matrix_elements_copy_bsc(LIS_INT n, LIS_INT bnr, LIS_INT bnc, LIS_INT bnnz, LIS_INT *ptr, LIS_INT *index, LIS_SCALAR *value,
LIS_INT *o_ptr, LIS_INT *o_index, LIS_SCALAR *o_value)
{
LIS_INT i,j,k;
LIS_INT nc,bs;
LIS_DEBUG_FUNC_IN;
nc = 1 + (n - 1)/bnc;
bs = bnr*bnc;
#ifdef _OPENMP
#pragma omp parallel private(i,j,k)
#endif
{
#ifdef _OPENMP
#pragma omp for
#endif
for(i=0;i<nc+1;i++)
{
o_ptr[i] = ptr[i];
}
#ifdef _OPENMP
#pragma omp for
#endif
for(i=0;i<nc;i++)
{
for(j=ptr[i];j<ptr[i+1];j++)
{
for(k=0;k<bs;k++)
{
o_value[j*bs+k] = value[j*bs+k];
}
o_index[j] = index[j];
}
}
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
#undef __FUNC__
#define __FUNC__ "lis_matrix_copy_bsc"
LIS_INT lis_matrix_copy_bsc(LIS_MATRIX Ain, LIS_MATRIX Aout)
{
LIS_INT err;
LIS_INT np,bnnz,bnr,bnc;
LIS_INT lbnnz,ubnnz;
LIS_INT *bptr,*bindex;
LIS_INT *lbptr,*lbindex;
LIS_INT *ubptr,*ubindex;
LIS_SCALAR *value,*lvalue,*uvalue;
LIS_MATRIX_DIAG D;
LIS_DEBUG_FUNC_IN;
np = Ain->np;
bnnz = Ain->bnnz;
bnr = Ain->bnr;
bnc = Ain->bnc;
if( Ain->is_splited )
{
lbnnz = Ain->L->bnnz;
ubnnz = Ain->U->bnnz;
lbptr = NULL;
lbindex = NULL;
lvalue = NULL;
ubptr = NULL;
ubindex = NULL;
uvalue = NULL;
D = NULL;
err = lis_matrix_malloc_bsc(np,bnr,bnc,lbnnz,&lbptr,&lbindex,&lvalue);
if( err )
{
return err;
}
err = lis_matrix_malloc_bsc(np,bnr,bnc,ubnnz,&ubptr,&ubindex,&uvalue);
if( err )
{
lis_free2(6,ubptr,lbptr,ubindex,lbindex,uvalue,lvalue);
return err;
}
err = lis_matrix_diag_duplicateM(Ain,&D);
if( err )
{
lis_free2(6,ubptr,lbptr,ubindex,lbindex,uvalue,lvalue);
return err;
}
lis_matrix_diag_copy(Ain->D,D);
lis_matrix_elements_copy_bsc(np,bnr,bnc,lbnnz,Ain->L->bptr,Ain->L->bindex,Ain->L->value,lbptr,lbindex,lvalue);
lis_matrix_elements_copy_bsc(np,bnr,bnc,ubnnz,Ain->U->bptr,Ain->U->bindex,Ain->U->value,ubptr,ubindex,uvalue);
err = lis_matrix_setDLU_bsc(bnr,bnc,lbnnz,ubnnz,D,lbptr,lbindex,lvalue,ubptr,ubindex,uvalue,Aout);
if( err )
{
lis_free2(6,ubptr,lbptr,ubindex,lbindex,uvalue,lvalue);
return err;
}
}
if( !Ain->is_splited || (Ain->is_splited && Ain->is_save) )
{
bptr = NULL;
bindex = NULL;
value = NULL;
err = lis_matrix_malloc_bsc(np,bnr,bnc,bnnz,&bptr,&bindex,&value);
if( err )
{
return err;
}
lis_matrix_elements_copy_bsc(np,bnr,bnc,bnnz,Ain->bptr,Ain->bindex,Ain->value,bptr,bindex,value);
err = lis_matrix_set_bsc(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_crs2bsc"
LIS_INT lis_matrix_convert_ccs2bsc(LIS_MATRIX Ain, LIS_MATRIX Aout)
{
LIS_INT i,j,k,n,bnr,bnc;
LIS_INT ii,jj,kk,pad;
LIS_INT bnnz,bj,nr,nc,jpos,nnz,ij,kv,bi;
LIS_INT err;
LIS_INT np,nprocs,my_rank;
LIS_INT *iw,*iw2;
LIS_INT *bptr,*bindex;
LIS_SCALAR *value;
LIS_DEBUG_FUNC_IN;
bnr = Aout->conv_bnr;
bnc = Aout->conv_bnc;
n = Ain->n;
np = Ain->np;
nr = 1 + (n - 1)/bnr;
pad = (bnc - n%bnc)%bnc;
if( n==np )
{
nc = 1 + (n - 1)/bnc;
}
else
{
nc = 2 + (n - 1)/bnc + (np - n - 1)/bnc;
}
bptr = NULL;
bindex = NULL;
value = NULL;
iw = NULL;
iw2 = NULL;
bptr = (LIS_INT *)lis_malloc( (nc+1)*sizeof(LIS_INT),"lis_matrix_convert_ccs2bsc::bptr" );
if( bptr==NULL )
{
LIS_SETERR_MEM((nc+1)*sizeof(LIS_INT));
lis_free2(5,bptr,bindex,value,iw,iw2);
return LIS_OUT_OF_MEMORY;
}
#ifdef _OPENMP
nprocs = omp_get_max_threads();
#else
nprocs = 1;
#endif
iw = (LIS_INT *)lis_malloc( nprocs*nr*sizeof(LIS_INT),"lis_matrix_convert_ccs2bsc::iw" );
iw2 = (LIS_INT *)lis_malloc( nprocs*nr*sizeof(LIS_INT),"lis_matrix_convert_ccs2bsc::iw2" );
#ifdef _OPENMP
#pragma omp parallel private(i,k,ii,j,bj,kk,ij,jj,kv,jpos,my_rank)
#endif
{
#ifdef _OPENMP
my_rank = omp_get_thread_num();
#else
my_rank = 0;
#endif
memset(&iw[my_rank*nr],0,nr*sizeof(LIS_INT));
#ifdef _OPENMP
#pragma omp for
#endif
for(i=0;i<nc;i++)
{
k = 0;
kk = bnc*i;
jj = 0;
#ifdef USE_MPI
for(ii=0;ii+kk<np&&ii<bnc;ii++)
{
for(j=Ain->ptr[kk+ii];j<Ain->ptr[kk+ii+1];j++)
{
bj = Ain->index[j]/bnr;
jpos = iw[my_rank*nr + bj];
if( jpos==0 )
{
iw[my_rank*nr + bj] = 1;
iw2[my_rank*nr + jj] = bj;
jj++;
}
}
}
#else
for(ii=0;ii+kk<np&&ii<bnc;ii++)
{
for(j=Ain->ptr[kk+ii];j<Ain->ptr[kk+ii+1];j++)
{
bj = Ain->index[j]/bnr;
jpos = iw[my_rank*nr + bj];
if( jpos==0 )
{
iw[my_rank*nr + bj] = 1;
iw2[my_rank*nr + jj] = bj;
jj++;
}
}
}
#endif
for(bj=0;bj<jj;bj++)
{
k++;
ii = iw2[my_rank*nr + bj];
iw[my_rank*nr + ii]=0;
}
bptr[i+1] = k;
}
}
bptr[0] = 0;
for(i=0;i<nc;i++)
{
bptr[i+1] += bptr[i];
}
bnnz = bptr[nc];
nnz = bnnz*bnr*bnc;
bindex = (LIS_INT *)lis_malloc( bnnz*sizeof(LIS_INT),"lis_matrix_convert_ccs2bsc::bindex" );
if( bindex==NULL )
{
LIS_SETERR_MEM((nr+1)*sizeof(LIS_INT));
lis_free2(5,bptr,bindex,value,iw,iw2);
return LIS_OUT_OF_MEMORY;
}
value = (LIS_SCALAR *)lis_malloc( nnz*sizeof(LIS_SCALAR),"lis_matrix_convert_ccs2bsc::value" );
if( value==NULL )
{
LIS_SETERR_MEM(nnz*sizeof(LIS_SCALAR));
lis_free2(5,bptr,bindex,value,iw,iw2);
return LIS_OUT_OF_MEMORY;
}
/* convert bsc */
#ifdef _OPENMP
#pragma omp parallel private(bi,i,ii,k,j,bj,jpos,kv,kk,ij,jj,my_rank)
#endif
{
#ifdef _OPENMP
my_rank = omp_get_thread_num();
#else
my_rank = 0;
#endif
memset(&iw[my_rank*nr],0,nr*sizeof(LIS_INT));
#ifdef _OPENMP
#pragma omp for
#endif
for(bi=0;bi<nc;bi++)
{
i = bi*bnc;
ii = 0;
kk = bptr[bi];
while( i+ii<np && ii<=bnc-1 )
{
for( k=Ain->ptr[i+ii];k<Ain->ptr[i+ii+1];k++)
{
j = Ain->index[k];
bj = j/bnr;
j = j%bnr;
jpos = iw[my_rank*nr + bj];
if( jpos==0 )
{
kv = kk * bnr * bnc;
iw[my_rank*nr + bj] = kv+1;
bindex[kk] = bj;
for(jj=0;jj<bnr*bnc;jj++) value[kv+jj] = 0.0;
ij = j + ii*bnc;
value[kv+ij] = Ain->value[k];
kk = kk+1;
}
else
{
ij = j + ii*bnc;
value[jpos+ij-1] = Ain->value[k];
}
}
ii = ii+1;
}
for(j=bptr[bi];j<bptr[bi+1];j++)
{
iw[my_rank*nr + bindex[j]] = 0;
}
}
}
lis_free2(2,iw,iw2);
err = lis_matrix_set_bsc(bnr,bnc,bnnz,bptr,bindex,value,Aout);
if( err )
{
lis_free2(3,bptr,bindex,value);
return err;
}
Aout->pad_comm = pad;
err = lis_matrix_assemble(Aout);
if( err )
{
lis_matrix_storage_destroy(Aout);
return err;
}
#ifdef USE_MPI
Aout->commtable->pad = pad;
MPI_Barrier(Ain->comm);
#endif
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
#undef __FUNC__
#define __FUNC__ "lis_matrix_convert_bsc2crs"
LIS_INT lis_matrix_convert_bsc2crs(LIS_MATRIX Ain, LIS_MATRIX Aout)
{
LIS_INT i,j,k,l;
LIS_INT nr,nc,bnr,bnc,bs,bi,bj;
LIS_INT err;
LIS_INT n,nnz,is,nprocs,my_rank;
LIS_INT *iw,*ptr,*index;
LIS_SCALAR *value;
LIS_DEBUG_FUNC_IN;
n = Ain->n;
nr = Ain->nr;
nc = Ain->nc;
bnr = Ain->bnr;
bnc = Ain->bnc;
bs = bnr*bnc;
is = Ain->is;
#ifdef _OPENMP
nprocs = omp_get_max_threads();
#else
nprocs = 1;
#endif
iw = NULL;
ptr = NULL;
index = NULL;
value = NULL;
iw = (LIS_INT *)lis_malloc( nprocs*n*sizeof(LIS_INT),"lis_matrix_convert_bsc2crs::iw" );
if( iw==NULL )
{
LIS_SETERR_MEM(nprocs*n*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
ptr = (LIS_INT *)lis_malloc( (n+1)*sizeof(LIS_INT),"lis_matrix_convert_bsc2crs::ptr" );
if( ptr==NULL )
{
LIS_SETERR_MEM((n+1)*sizeof(LIS_INT));
lis_free2(4,ptr,index,value,iw);
return LIS_OUT_OF_MEMORY;
}
/* check nnz */
#ifdef _OPENMP
#pragma omp parallel private(i,j,bi,bj,my_rank)
#endif
{
#ifdef _OPENMP
my_rank = omp_get_thread_num();
#else
my_rank = 0;
#endif
memset(&iw[my_rank*n],0,n*sizeof(LIS_INT));
#ifdef _OPENMP
#pragma omp for
#endif
for(bj=0;bj<nc;bj++)
{
for(j=0;j<bnc;j++)
{
for(bi=Ain->bptr[bj];bi<Ain->bptr[bj+1];bi++)
{
for(i=0;i<bnr;i++)
{
if( Ain->value[bi*bs + j*bnr + i] != (LIS_SCALAR)0.0 )
{
iw[my_rank*n + Ain->bindex[bi]*bnr + i]++;
}
}
}
}
}
#ifdef _OPENMP
#pragma omp for
#endif
for(i=0;i<n;i++)
{
j = 0;
for(k=0;k<nprocs;k++)
{
j += iw[k*n + i];
}
ptr[i+1] = j;
}
}
ptr[0] = 0;
for(i=0;i<n;i++)
{
ptr[i+1] += ptr[i];
}
nnz = ptr[n];
index = (LIS_INT *)lis_malloc( nnz*sizeof(LIS_INT),"lis_matrix_convert_bsc2crs::index" );
if( index==NULL )
{
lis_free2(4,ptr,index,value,iw);
LIS_SETERR_MEM(nnz*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
value = (LIS_SCALAR *)lis_malloc( nnz*sizeof(LIS_SCALAR),"lis_matrix_convert_bsc2crs::value" );
if( value==NULL )
{
lis_free2(4,ptr,index,value,iw);
LIS_SETERR_MEM(nnz*sizeof(LIS_SCALAR));
return LIS_OUT_OF_MEMORY;
}
/* convert crs */
#ifdef _OPENMP
#pragma omp parallel private(i,j,bi,bj,k,l,my_rank)
#endif
{
#ifdef _OPENMP
my_rank = omp_get_thread_num();
#else
my_rank = 0;
#endif
#ifdef _OPENMP
#pragma omp for
#endif
for(i=0;i<n;i++)
{
k = ptr[i];
for(j=0;j<nprocs;j++)
{
l = iw[j*n + i];
iw[j*n + i] = k;
k = k + l;
}
}
#ifdef _OPENMP
#pragma omp for
#endif
for(bj=0;bj<nc;bj++)
{
for(j=0;j<bnc;j++)
{
if( bj*bnc+j==n ) break;
for(bi=Ain->bptr[bj];bi<Ain->bptr[bj+1];bi++)
{
for(i=0;i<bnr;i++)
{
if( Ain->value[bi*bs + j*bnr + i] != (LIS_SCALAR)0.0 )
{
k = iw[my_rank*n + Ain->bindex[bi]*bnr + i]++;
value[k] = Ain->value[bi*bs + j*bnr + i];
index[k] = bj*bnc + j;
}
}
}
}
}
}
err = lis_matrix_set_crs(nnz,ptr,index,value,Aout);
if( err )
{
lis_free2(4,ptr,index,value,iw);
return err;
}
Aout->pad = 0;
Aout->pad_comm = 0;
err = lis_matrix_assemble(Aout);
if( err )
{
lis_matrix_storage_destroy(Aout);
return err;
}
#ifdef USE_MPI
Aout->commtable->pad = 0;
#endif
lis_free(iw);
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
#undef __FUNC__
#define __FUNC__ "lis_matrix_get_diagonal_bsc"
LIS_INT lis_matrix_get_diagonal_bsc(LIS_MATRIX A, LIS_SCALAR d[])
{
LIS_INT i,j,k,bi,bj,bjj,nr,nc;
LIS_INT bnr,bnc,bs;
LIS_INT n;
LIS_DEBUG_FUNC_IN;
n = A->n;
nr = A->nr;
nc = A->nc;
bnr = A->bnr;
bnc = A->bnc;
bs = bnr*bnc;
if( A->is_splited )
{
#ifdef _OPENMP
#pragma omp parallel for private(i,j)
#endif
for(i=0;i<nr;i++)
{
for(j=0;j<bnr;j++)
{
d[i*bnr+j] = A->D->value[i*bs+j*bnr+j];
}
}
}
else
{
#ifdef _OPENMP
#pragma omp parallel for private(bi,bj,bjj,i,j,k)
#endif
for(bi=0;bi<nr;bi++)
{
k = 0;
i = bi*bnr;
for(bj=A->bptr[bi];bj<A->bptr[bi+1];bj++)
{
bjj = A->bindex[bj];
if( i>=bjj*bnc && i<(bjj+1)*bnc )
{
for(j=i%bnc;j<bnc&&k<bnr&&i<n;j++)
{
d[i] = A->value[bj*bs + j*bnr + k];
i++;
k++;
}
}
if( k==bnr ) break;
}
}
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
#undef __FUNC__
#define __FUNC__ "lis_matrix_scaling_bsc"
LIS_INT lis_matrix_scaling_bsc(LIS_MATRIX A, LIS_SCALAR d[])
{
LIS_INT i,j;
LIS_INT bi,bj,bs;
LIS_INT nr,nc;
LIS_INT bnr,bnc;
LIS_INT n;
LIS_DEBUG_FUNC_IN;
n = A->n;
bnr = A->bnr;
bnc = A->bnc;
nr = A->nr;
nc = A->nc;
bs = A->bnr*A->bnc;
if( A->is_splited )
{
#ifdef _OPENMP
#pragma omp parallel for private(bi,bj,i,j)
#endif
for(bi=0;bi<nr;bi++)
{
for(bj=A->L->bptr[bi];bj<A->L->bptr[bi+1];bj++)
{
for(j=0;j<bnc;j++)
{
for(i=0;i<bnr;i++)
{
A->L->value[bj*bs+j*bnr+i] *= d[bi*bnr+i];
}
}
}
for(bj=A->U->bptr[bi];bj<A->U->bptr[bi+1];bj++)
{
for(j=0;j<bnc;j++)
{
for(i=0;i<bnr;i++)
{
A->U->value[bj*bs+j*bnr+i] *= d[bi*bnr+i];
}
}
}
for(j=0;j<bnc;j++)
{
for(i=0;i<bnr;i++)
{
A->D->value[bi*bs+j*bnr+i] *= d[bi*bnr+i];
}
}
}
}
else
{
#ifdef _OPENMP
#pragma omp parallel for private(bi,bj,i,j)
#endif
for(bi=0;bi<nr;bi++)
{
for(bj=A->bptr[bi];bj<A->bptr[bi+1];bj++)
{
for(j=0;j<bnc;j++)
{
for(i=0;i<bnr;i++)
{
A->value[bj*bs+j*bnr+i] *= d[bi*bnr+i];
}
}
}
}
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
#undef __FUNC__
#define __FUNC__ "lis_matrix_scaling_symm_bsc"
LIS_INT lis_matrix_scaling_symm_bsc(LIS_MATRIX A, LIS_SCALAR d[])
{
LIS_INT i,j;
LIS_INT bi,bj,bjj,bs;
LIS_INT nr,nc;
LIS_INT bnr,bnc;
LIS_INT n;
LIS_DEBUG_FUNC_IN;
n = A->n;
bnr = A->bnr;
bnc = A->bnc;
nr = A->nr;
nc = A->nc;
bs = A->bnr*A->bnc;
if( A->is_splited )
{
#ifdef _OPENMP
#pragma omp parallel for private(bi,bj,i,j)
#endif
for(bi=0;bi<nr;bi++)
{
for(bj=A->L->bptr[bi];bj<A->L->bptr[bi+1];bj++)
{
bjj = A->L->bindex[bj];
for(j=0;j<bnc;j++)
{
for(i=0;i<bnr;i++)
{
A->L->value[bj*bs+j*bnr+i] *= d[bi*bnr+i]*d[bjj*bnc+j];
}
}
}
for(bj=A->U->bptr[bi];bj<A->U->bptr[bi+1];bj++)
{
bjj = A->U->bindex[bj];
for(j=0;j<bnc;j++)
{
for(i=0;i<bnr;i++)
{
A->U->value[bj*bs+j*bnr+i] *= d[bi*bnr+i]*d[bjj*bnc+j];
}
}
}
for(j=0;j<bnc;j++)
{
for(i=0;i<bnr;i++)
{
A->D->value[bi*bs+j*bnr+i] *= d[bi*bnr+i]*d[bi*bnr+i];
}
}
}
}
else
{
#ifdef _OPENMP
#pragma omp parallel for private(bi,bj,bjj,i,j)
#endif
for(bi=0;bi<nr;bi++)
{
for(bj=A->bptr[bi];bj<A->bptr[bi+1];bj++)
{
bjj = A->bindex[bj];
for(j=0;j<bnc;j++)
{
for(i=0;i<bnr;i++)
{
A->value[bj*bs+j*bnr+i] *= d[bi*bnr+i]*d[bjj*bnc+j];
}
}
}
}
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
#undef __FUNC__
#define __FUNC__ "lis_matrix_normf_bsc"
LIS_INT lis_matrix_normf_bsc(LIS_MATRIX A, LIS_SCALAR *nrm)
{
LIS_INT j;
LIS_INT bi,bj,bs;
LIS_INT nr,nc;
LIS_INT bnr,bnc;
LIS_INT n;
LIS_SCALAR sum;
LIS_DEBUG_FUNC_IN;
n = A->n;
bnr = A->bnr;
bnc = A->bnc;
nr = A->nr;
nc = A->nc;
bs = bnr*bnc;
sum = (LIS_SCALAR)0;
if( A->is_splited )
{
#ifdef _OPENMP
#pragma omp parallel for reduction(+:sum) private(bi,bj,j)
#endif
for(bi=0;bi<nr;bi++)
{
for(bj=A->L->bptr[bi];bj<A->L->bptr[bi+1];bj++)
{
for(j=0;j<bs;j++)
{
sum += A->L->value[bj+j]*A->L->value[bj+j];
}
}
for(bj=A->U->bptr[bi];bj<A->U->bptr[bi+1];bj++)
{
for(j=0;j<bs;j++)
{
sum += A->U->value[bj+j]*A->U->value[bj+j];
}
}
}
}
else
{
#ifdef _OPENMP
#pragma omp parallel for reduction(+:sum) private(bi,bj,j)
#endif
for(bi=0;bi<nr;bi++)
{
for(bj=A->bptr[bi];bj<A->bptr[bi+1];bj++)
{
for(j=0;j<bs;j++)
{
sum += A->value[bj+j]*A->value[bj+j];
}
}
}
}
*nrm = sqrt(sum);
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
#undef __FUNC__
#define __FUNC__ "lis_matrix_split_bsc"
LIS_INT lis_matrix_split_bsc(LIS_MATRIX A)
{
LIS_INT i,j,n,np;
LIS_INT bnr,bnc,nr,nc,bs;
LIS_INT nnzl,nnzu;
LIS_INT err;
LIS_INT *lptr,*lindex,*uptr,*uindex;
LIS_SCALAR *lvalue,*uvalue;
LIS_MATRIX_DIAG D;
#ifdef _OPENMP
LIS_INT kl,ku;
LIS_INT *liw,*uiw;
#endif
LIS_DEBUG_FUNC_IN;
n = A->n;
np = A->np;
bnr = A->bnr;
bnc = A->bnc;
nr = A->nr;
nc = A->nc;
bs = A->bnr*A->bnc;
nnzl = 0;
nnzu = 0;
D = NULL;
lptr = NULL;
lindex = NULL;
lvalue = NULL;
uptr = NULL;
uindex = NULL;
uvalue = NULL;
if( bnr!=bnc )
{
LIS_SETERR_IMP;
return LIS_ERR_NOT_IMPLEMENTED;
}
#ifdef _OPENMP
liw = (LIS_INT *)lis_malloc((nc+1)*sizeof(LIS_INT),"lis_matrix_split_bsc::liw");
if( liw==NULL )
{
LIS_SETERR_MEM((nc+1)*sizeof(LIS_INT));
return LIS_OUT_OF_MEMORY;
}
uiw = (LIS_INT *)lis_malloc((nc+1)*sizeof(LIS_INT),"lis_matrix_split_bsc::uiw");
if( uiw==NULL )
{
LIS_SETERR_MEM((nc+1)*sizeof(LIS_INT));
lis_free(liw);
return LIS_OUT_OF_MEMORY;
}
#pragma omp parallel for private(i)
for(i=0;i<nc+1;i++)
{
liw[i] = 0;
uiw[i] = 0;
}
#pragma omp parallel for private(i,j)
for(i=0;i<nc;i++)
{
for(j=A->bptr[i];j<A->bptr[i+1];j++)
{
if( A->bindex[j]<i )
{
liw[i+1]++;
}
else if( A->bindex[j]>i )
{
uiw[i+1]++;
}
}
}
for(i=0;i<nc;i++)
{
liw[i+1] += liw[i];
uiw[i+1] += uiw[i];
}
nnzl = liw[nc];
nnzu = uiw[nc];
#else
for(i=0;i<nc;i++)
{
for(j=A->bptr[i];j<A->bptr[i+1];j++)
{
if( A->bindex[j]<i )
{
nnzl++;
}
else if( A->bindex[j]>i )
{
nnzu++;
}
}
}
#endif
err = lis_matrix_LU_create(A);
if( err )
{
return err;
}
err = lis_matrix_malloc_bsc(np,bnr,bnc,nnzl,&lptr,&lindex,&lvalue);
if( err )
{
return err;
}
err = lis_matrix_malloc_bsc(np,bnr,bnc,nnzu,&uptr,&uindex,&uvalue);
if( err )
{
lis_free2(6,lptr,lindex,lvalue,uptr,uindex,uvalue);
return err;
}
err = lis_matrix_diag_duplicateM(A,&D);
if( err )
{
lis_free2(6,lptr,lindex,lvalue,uptr,uindex,uvalue);
return err;
}
#ifdef _OPENMP
#pragma omp parallel for private(i)
for(i=0;i<nc+1;i++)
{
lptr[i] = liw[i];
uptr[i] = uiw[i];
}
#pragma omp parallel for private(i,j,kl,ku)
for(i=0;i<nc;i++)
{
kl = lptr[i];
ku = uptr[i];
for(j=A->bptr[i];j<A->bptr[i+1];j++)
{
if( A->bindex[j]<i )
{
lindex[kl] = A->bindex[j];
memcpy(&lvalue[bs*kl],&A->value[bs*j],bs*sizeof(LIS_SCALAR));;
kl++;
}
else if( A->bindex[j]>i )
{
uindex[ku] = A->bindex[j];
memcpy(&uvalue[bs*ku],&A->value[bs*j],bs*sizeof(LIS_SCALAR));
ku++;
}
else
{
memcpy(&D->value[bs*i],&A->value[bs*j],bs*sizeof(LIS_SCALAR));
}
}
}
lis_free2(2,liw,uiw);
#else
nnzl = 0;
nnzu = 0;
lptr[0] = 0;
uptr[0] = 0;
for(i=0;i<nc;i++)
{
for(j=A->bptr[i];j<A->bptr[i+1];j++)
{
if( A->bindex[j]<i )
{
lindex[nnzl] = A->bindex[j];
memcpy(&lvalue[bs*nnzl],&A->value[bs*j],bs*sizeof(LIS_SCALAR));;
nnzl++;
}
else if( A->bindex[j]>i )
{
uindex[nnzu] = A->bindex[j];
memcpy(&uvalue[bs*nnzu],&A->value[bs*j],bs*sizeof(LIS_SCALAR));
nnzu++;
}
else
{
memcpy(&D->value[bs*i],&A->value[bs*j],bs*sizeof(LIS_SCALAR));
}
}
lptr[i+1] = nnzl;
uptr[i+1] = nnzu;
}
#endif
A->L->bnr = bnr;
A->L->bnc = bnc;
A->L->nr = nr;
A->L->nc = nc;
A->L->bnnz = nnzl;
A->L->bptr = lptr;
A->L->bindex = lindex;
A->L->value = lvalue;
A->U->bnr = bnr;
A->U->bnc = bnc;
A->U->nr = nr;
A->U->nc = nc;
A->U->bnnz = nnzu;
A->U->bptr = uptr;
A->U->bindex = uindex;
A->U->value = uvalue;
A->D = D;
A->is_splited = LIS_TRUE;
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
#undef __FUNC__
#define __FUNC__ "lis_matrix_merge_bsc"
LIS_INT lis_matrix_merge_bsc(LIS_MATRIX A)
{
LIS_INT i,j,n,np,nr,nc;
LIS_INT bnnz,bnr,bnc,bs;
LIS_INT err;
LIS_INT *bptr,*bindex;
LIS_SCALAR *value;
LIS_DEBUG_FUNC_IN;
n = A->n;
np = A->np;
nc = A->nc;
nr = A->nr;
bnr = A->bnr;
bnc = A->bnc;
bs = bnr*bnc;
bptr = NULL;
bindex = NULL;
value = NULL;
bnnz = A->L->bnnz + A->U->bnnz + nr;
err = lis_matrix_malloc_bsc(np,bnr,bnc,bnnz,&bptr,&bindex,&value);
if( err )
{
return err;
}
bnnz = 0;
bptr[0] = 0;
for(i=0;i<nc;i++)
{
for(j=A->L->bptr[i];j<A->L->bptr[i+1];j++)
{
bindex[bnnz] = A->L->bindex[j];
memcpy(&value[bs*bnnz],&A->L->value[bs*j],bs*sizeof(LIS_SCALAR));;
bnnz++;
}
bindex[bnnz] = i;
memcpy(&value[bs*bnnz],&A->D->value[bs*i],bs*sizeof(LIS_SCALAR));;
bnnz++;
for(j=A->U->bptr[i];j<A->U->bptr[i+1];j++)
{
bindex[bnnz] = A->U->bindex[j];
memcpy(&value[bs*bnnz],&A->U->value[bs*j],bs*sizeof(LIS_SCALAR));;
bnnz++;
}
bptr[i+1] = bnnz;
}
A->bnnz = bnnz;
A->bptr = bptr;
A->value = value;
A->bindex = bindex;
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
#undef __FUNC__
#define __FUNC__ "lis_matrix_solve_bsc"
LIS_INT lis_matrix_solve_bsc(LIS_MATRIX A, LIS_VECTOR B, LIS_VECTOR X, LIS_INT flag)
{
LIS_INT i,j,k,ii,jj,nr,bnr,bnc,bs;
LIS_SCALAR t0,t1,t2;
LIS_SCALAR *b,*x,*w;
LIS_DEBUG_FUNC_IN;
nr = A->nr;
bnr = A->bnr;
bnc = A->bnc;
bs = A->bnr*A->bnc;
b = B->value;
x = X->value;
switch(flag)
{
case LIS_MATRIX_LOWER:
switch(bnr)
{
case 1:
for(i=0;i<nr;i++)
{
t0 = b[i];
for(j=A->L->bptr[i];j<A->L->bptr[i+1];j++)
{
jj = A->L->bindex[j];
t0 -= A->L->value[j] * x[jj];
}
x[i] = A->WD->value[i] * t0;
}
break;
case 2:
for(i=0;i<nr;i++)
{
t0 = b[i*2];
t1 = b[i*2+1];
for(j=A->L->bptr[i];j<A->L->bptr[i+1];j++)
{
jj = A->L->bindex[j];
t0 -= A->L->value[j*4+0] * x[jj*2+0];
t1 -= A->L->value[j*4+1] * x[jj*2+0];
t0 -= A->L->value[j*4+2] * x[jj*2+1];
t1 -= A->L->value[j*4+3] * x[jj*2+1];
}
x[i*2+0] = A->WD->value[4*i+0] * t0 + A->WD->value[4*i+2] * t1;
x[i*2+1] = A->WD->value[4*i+1] * t0 + A->WD->value[4*i+3] * t1;
}
break;
case 3:
for(i=0;i<nr;i++)
{
t0 = b[i*3];
t1 = b[i*3+1];
t2 = b[i*3+2];
for(j=A->L->bptr[i];j<A->L->bptr[i+1];j++)
{
jj = A->L->bindex[j];
t0 -= A->L->value[j*9+0] * x[jj*3+0];
t1 -= A->L->value[j*9+1] * x[jj*3+0];
t2 -= A->L->value[j*9+2] * x[jj*3+0];
t0 -= A->L->value[j*9+3] * x[jj*3+1];
t1 -= A->L->value[j*9+4] * x[jj*3+1];
t2 -= A->L->value[j*9+5] * x[jj*3+1];
t0 -= A->L->value[j*9+6] * x[jj*3+2];
t1 -= A->L->value[j*9+7] * x[jj*3+2];
t2 -= A->L->value[j*9+8] * x[jj*3+2];
}
x[i*3+0] = A->WD->value[9*i+0] * t0 + A->WD->value[9*i+3] * t1 + A->WD->value[9*i+6] * t2;
x[i*3+1] = A->WD->value[9*i+1] * t0 + A->WD->value[9*i+4] * t1 + A->WD->value[9*i+7] * t2;
x[i*3+2] = A->WD->value[9*i+2] * t0 + A->WD->value[9*i+5] * t1 + A->WD->value[9*i+8] * t2;
}
break;
default:
w = (LIS_SCALAR *)lis_malloc(bnr*sizeof(LIS_SCALAR),"lis_matrix_solve_bsc::w");
for(i=0;i<nr;i++)
{
for(j=0;j<bnr;j++)
{
w[j] = b[i*bnr+j];
}
for(j=A->L->bptr[i];j<A->L->bptr[i+1];j++)
{
k = A->L->bindex[j] * bnc;
for(ii=0;ii<bnr;ii++)
{
t0 = w[ii];
for(jj=0;jj<bnc;jj++)
{
t0 -= A->L->value[j*bs + jj*bnr+ii] * x[k + jj];
}
w[ii] = t0;
}
}
for(ii=0;ii<bnr;ii++)
{
t0 = 0.0;
for(jj=0;jj<bnc;jj++)
{
t0 += A->WD->value[i*bs + jj*bnr+ii] * w[jj];
}
x[i*bnr+ii] = t0;
}
}
lis_free(w);
break;
}
break;
case LIS_MATRIX_UPPER:
switch(bnr)
{
case 1:
for(i=nr-1;i>=0;i--)
{
t0 = b[i];
for(j=A->U->bptr[i];j<A->U->bptr[i+1];j++)
{
jj = A->U->bindex[j];
t0 -= A->U->value[j] * x[jj];
}
x[i] = A->WD->value[i] * t0;
}
break;
case 2:
for(i=nr-1;i>=0;i--)
{
t0 = b[i*2];
t1 = b[i*2+1];
for(j=A->U->bptr[i];j<A->U->bptr[i+1];j++)
{
jj = A->U->bindex[j];
t0 -= A->U->value[j*4+0] * x[jj*2+0];
t1 -= A->U->value[j*4+1] * x[jj*2+0];
t0 -= A->U->value[j*4+2] * x[jj*2+1];
t1 -= A->U->value[j*4+3] * x[jj*2+1];
}
x[i*2+0] = A->WD->value[4*i+0] * t0 + A->WD->value[4*i+2] * t1;
x[i*2+1] = A->WD->value[4*i+1] * t0 + A->WD->value[4*i+3] * t1;
}
break;
case 3:
for(i=nr-1;i>=0;i--)
{
t0 = b[i*3];
t1 = b[i*3+1];
t2 = b[i*3+2];
for(j=A->U->bptr[i];j<A->U->bptr[i+1];j++)
{
jj = A->U->bindex[j];
t0 -= A->U->value[j*9+0] * x[jj*3+0];
t1 -= A->U->value[j*9+1] * x[jj*3+0];
t2 -= A->U->value[j*9+2] * x[jj*3+0];
t0 -= A->U->value[j*9+3] * x[jj*3+1];
t1 -= A->U->value[j*9+4] * x[jj*3+1];
t2 -= A->U->value[j*9+5] * x[jj*3+1];
t0 -= A->U->value[j*9+6] * x[jj*3+2];
t1 -= A->U->value[j*9+7] * x[jj*3+2];
t2 -= A->U->value[j*9+8] * x[jj*3+2];
}
x[i*3+0] = A->WD->value[9*i+0] * t0 + A->WD->value[9*i+3] * t1 + A->WD->value[9*i+6] * t2;
x[i*3+1] = A->WD->value[9*i+1] * t0 + A->WD->value[9*i+4] * t1 + A->WD->value[9*i+7] * t2;
x[i*3+2] = A->WD->value[9*i+2] * t0 + A->WD->value[9*i+5] * t1 + A->WD->value[9*i+8] * t2;
}
break;
default:
w = (LIS_SCALAR *)lis_malloc(bnr*sizeof(LIS_SCALAR),"lis_matrix_solve_bsc::w");
for(i=nr-1;i>=0;i--)
{
for(j=0;j<bnr;j++)
{
w[j] = b[i*bnr+j];
}
for(j=A->U->bptr[i];j<A->U->bptr[i+1];j++)
{
k = A->U->bindex[j] * bnc;
for(ii=0;ii<bnr;ii++)
{
t0 = w[ii];
for(jj=0;jj<bnc;jj++)
{
t0 -= A->U->value[j*bs + jj*bnr+ii] * x[k + jj];
}
w[ii] = t0;
}
}
for(ii=0;ii<bnr;ii++)
{
t0 = 0.0;
for(jj=0;jj<bnc;jj++)
{
t0 += A->WD->value[i*bs + jj*bnr+ii] * w[jj];
}
x[i*bnr+ii] = t0;
}
}
lis_free(w);
break;
}
break;
case LIS_MATRIX_SSOR:
switch(bnr)
{
case 1:
for(i=0;i<nr;i++)
{
t0 = b[i];
for(j=A->L->bptr[i];j<A->L->bptr[i+1];j++)
{
jj = A->L->bindex[j];
t0 -= A->L->value[j] * x[jj];
}
x[i] = A->WD->value[i] * t0;
}
for(i=nr-1;i>=0;i--)
{
t0 = 0.0;
for(j=A->U->bptr[i];j<A->U->bptr[i+1];j++)
{
jj = A->U->bindex[j];
t0 += A->U->value[j] * x[jj];
}
x[i] -= A->WD->value[i] * t0;
}
break;
case 2:
for(i=0;i<nr;i++)
{
t0 = b[i*2];
t1 = b[i*2+1];
for(j=A->L->bptr[i];j<A->L->bptr[i+1];j++)
{
jj = A->L->bindex[j];
t0 -= A->L->value[j*4+0] * x[jj*2+0];
t1 -= A->L->value[j*4+1] * x[jj*2+0];
t0 -= A->L->value[j*4+2] * x[jj*2+1];
t1 -= A->L->value[j*4+3] * x[jj*2+1];
}
x[i*2+0] = A->WD->value[4*i+0] * t0 + A->WD->value[4*i+2] * t1;
x[i*2+1] = A->WD->value[4*i+1] * t0 + A->WD->value[4*i+3] * t1;
}
for(i=nr-1;i>=0;i--)
{
t0 = 0.0;
t1 = 0.0;
for(j=A->U->bptr[i];j<A->U->bptr[i+1];j++)
{
jj = A->U->bindex[j];
t0 += A->U->value[j*4+0] * x[jj*2+0];
t1 += A->U->value[j*4+1] * x[jj*2+0];
t0 += A->U->value[j*4+2] * x[jj*2+1];
t1 += A->U->value[j*4+3] * x[jj*2+1];
}
x[i*2+0] -= A->WD->value[4*i+0] * t0 + A->WD->value[4*i+2] * t1;
x[i*2+1] -= A->WD->value[4*i+1] * t0 + A->WD->value[4*i+3] * t1;
}
break;
case 3:
for(i=0;i<nr;i++)
{
t0 = b[i*bnr];
t1 = b[i*bnr+1];
t2 = b[i*bnr+2];
for(j=A->L->bptr[i];j<A->L->bptr[i+1];j++)
{
jj = A->L->bindex[j];
t0 -= A->L->value[j*9+0] * x[jj*3+0];
t1 -= A->L->value[j*9+1] * x[jj*3+0];
t2 -= A->L->value[j*9+2] * x[jj*3+0];
t0 -= A->L->value[j*9+3] * x[jj*3+1];
t1 -= A->L->value[j*9+4] * x[jj*3+1];
t2 -= A->L->value[j*9+5] * x[jj*3+1];
t0 -= A->L->value[j*9+6] * x[jj*3+2];
t1 -= A->L->value[j*9+7] * x[jj*3+2];
t2 -= A->L->value[j*9+8] * x[jj*3+2];
}
x[i*bnr+0] = A->WD->value[9*i+0] * t0 + A->WD->value[9*i+3] * t1 + A->WD->value[9*i+6] * t2;
x[i*bnr+1] = A->WD->value[9*i+1] * t0 + A->WD->value[9*i+4] * t1 + A->WD->value[9*i+7] * t2;
x[i*bnr+2] = A->WD->value[9*i+2] * t0 + A->WD->value[9*i+5] * t1 + A->WD->value[9*i+8] * t2;
}
for(i=nr-1;i>=0;i--)
{
t0 = 0.0;
t1 = 0.0;
t2 = 0.0;
for(j=A->U->bptr[i];j<A->U->bptr[i+1];j++)
{
jj = A->U->bindex[j];
t0 += A->U->value[j*9+0] * x[jj*3+0];
t1 += A->U->value[j*9+1] * x[jj*3+0];
t2 += A->U->value[j*9+2] * x[jj*3+0];
t0 += A->U->value[j*9+3] * x[jj*3+1];
t1 += A->U->value[j*9+4] * x[jj*3+1];
t2 += A->U->value[j*9+5] * x[jj*3+1];
t0 += A->U->value[j*9+6] * x[jj*3+2];
t1 += A->U->value[j*9+7] * x[jj*3+2];
t2 += A->U->value[j*9+8] * x[jj*3+2];
}
x[i*3+0] -= A->WD->value[9*i+0] * t0 + A->WD->value[9*i+3] * t1 + A->WD->value[9*i+6] * t2;
x[i*3+1] -= A->WD->value[9*i+1] * t0 + A->WD->value[9*i+4] * t1 + A->WD->value[9*i+7] * t2;
x[i*3+2] -= A->WD->value[9*i+2] * t0 + A->WD->value[9*i+5] * t1 + A->WD->value[9*i+8] * t2;
}
break;
default:
w = (LIS_SCALAR *)lis_malloc(bnr*sizeof(LIS_SCALAR),"lis_matrix_solve_bsc::w");
for(i=0;i<nr;i++)
{
for(j=0;j<bnr;j++)
{
w[j] = b[i*bnr+j];
}
for(j=A->L->bptr[i];j<A->L->bptr[i+1];j++)
{
k = A->L->bindex[j] * bnc;
for(ii=0;ii<bnr;ii++)
{
t0 = w[ii];
for(jj=0;jj<bnc;jj++)
{
t0 -= A->L->value[j*bs + jj*bnr+ii] * x[k + jj];
}
w[ii] = t0;
}
}
for(ii=0;ii<bnr;ii++)
{
t0 = 0.0;
for(jj=0;jj<bnc;jj++)
{
t0 += A->WD->value[i*bs + jj*bnr+ii] * w[jj];
}
x[i*bnr+ii] = t0;
}
}
for(i=nr-1;i>=0;i--)
{
for(j=0;j<bnr;j++)
{
w[j] = 0.0;
}
for(j=A->U->bptr[i];j<A->U->bptr[i+1];j++)
{
k = A->U->bindex[j] * bnc;
for(ii=0;ii<bnr;ii++)
{
t0 = w[ii];
for(jj=0;jj<bnc;jj++)
{
t0 += A->U->value[j*bs + jj*bnr+ii] * x[k + jj];
}
w[ii] = t0;
}
}
for(ii=0;ii<bnr;ii++)
{
t0 = 0.0;
for(jj=0;jj<bnc;jj++)
{
t0 += A->WD->value[i*bs + jj*bnr+ii] * w[jj];
}
x[i*bnr+ii] -= t0;
}
}
lis_free(w);
break;
}
break;
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
#undef __FUNC__
#define __FUNC__ "lis_matrix_solvet_bsc"
LIS_INT lis_matrix_solvet_bsc(LIS_MATRIX A, LIS_VECTOR B, LIS_VECTOR X, LIS_INT flag)
{
LIS_INT i,j,k,ii,jj,nr,bnr,bnc,bs;
LIS_SCALAR t0,t1,t2;
LIS_SCALAR *b,*x,*w;
LIS_DEBUG_FUNC_IN;
nr = A->nr;
bnr = A->bnr;
bnc = A->bnc;
bs = A->bnr*A->bnc;
b = B->value;
x = X->value;
lis_vector_copy(B,X);
switch(flag)
{
case LIS_MATRIX_LOWER:
switch(bnr)
{
case 1:
for(i=0;i<nr;i++)
{
x[i] = x[i] * A->WD->value[i];
for(j=A->U->bptr[i];j<A->U->bptr[i+1];j++)
{
jj = A->U->bindex[j];
x[jj] -= A->U->value[j] * x[i];
}
}
break;
case 2:
for(i=0;i<nr;i++)
{
t0 = A->WD->value[4*i+0] * x[i*2] + A->WD->value[4*i+1] * x[i*2+1];
t1 = A->WD->value[4*i+2] * x[i*2] + A->WD->value[4*i+3] * x[i*2+1];
x[i*2+0] = t0;
x[i*2+1] = t1;
for(j=A->U->bptr[i];j<A->U->bptr[i+1];j++)
{
jj = A->U->bindex[j];
x[jj*2+0] -= A->U->value[j*4+0] * t0 + A->U->value[j*4+1] * t1;
x[jj*2+1] -= A->U->value[j*4+2] * t0 + A->U->value[j*4+3] * t1;
}
}
break;
case 3:
for(i=0;i<nr;i++)
{
t0 = A->WD->value[9*i+0] * x[i*3] + A->WD->value[9*i+1] * x[i*3+1] + A->WD->value[9*i+2] * x[i*3+2];
t1 = A->WD->value[9*i+3] * x[i*3] + A->WD->value[9*i+4] * x[i*3+1] + A->WD->value[9*i+5] * x[i*3+2];
t2 = A->WD->value[9*i+6] * x[i*3] + A->WD->value[9*i+7] * x[i*3+1] + A->WD->value[9*i+8] * x[i*3+2];
x[i*3] = t0;
x[i*3+1] = t1;
x[i*3+2] = t2;
for(j=A->U->bptr[i];j<A->U->bptr[i+1];j++)
{
jj = A->U->bindex[j];
x[jj*3+0] -= A->U->value[j*9+0] * t0 + A->U->value[j*9+1] * t1 + A->U->value[j*9+2] * t2;
x[jj*3+1] -= A->U->value[j*9+3] * t0 + A->U->value[j*9+4] * t1 + A->U->value[j*9+5] * t2;
x[jj*3+2] -= A->U->value[j*9+6] * t0 + A->U->value[j*9+7] * t1 + A->U->value[j*9+8] * t2;
}
}
break;
default:
w = (LIS_SCALAR *)lis_malloc(bnc*sizeof(LIS_SCALAR),"lis_matrix_solvet_bsc::w");
for(i=0;i<nr;i++)
{
for(jj=0;jj<bnc;jj++)
{
t0 = 0.0;
for(ii=0;ii<bnr;ii++)
{
t0 += A->WD->value[i*bs + jj*bnr+ii] * x[i*bnr + ii];
}
w[jj] = t0;
}
memcpy(&x[i*bnr],w,bnr*sizeof(LIS_SCALAR));
for(j=A->U->bptr[i];j<A->U->bptr[i+1];j++)
{
k = A->U->bindex[j] * bnc;
for(jj=0;jj<bnc;jj++)
{
t0 = 0.0;
for(ii=0;ii<bnr;ii++)
{
t0 += A->U->value[j*bs + jj*bnr+ii] * w[ii];
}
x[k + jj] -= t0;
}
}
}
lis_free(w);
break;
}
break;
case LIS_MATRIX_UPPER:
switch(bnr)
{
case 1:
for(i=nr-1;i>=0;i--)
{
x[i] = x[i] * A->WD->value[i];
for(j=A->L->bptr[i];j<A->L->bptr[i+1];j++)
{
jj = A->L->bindex[j];
x[jj] -= A->L->value[j] * x[i];
}
}
break;
case 2:
for(i=nr-1;i>=0;i--)
{
t0 = A->WD->value[4*i+0] * x[i*2] + A->WD->value[4*i+1] * x[i*2+1];
t1 = A->WD->value[4*i+2] * x[i*2] + A->WD->value[4*i+3] * x[i*2+1];
x[i*2+0] = t0;
x[i*2+1] = t1;
for(j=A->L->bptr[i];j<A->L->bptr[i+1];j++)
{
jj = A->L->bindex[j];
x[jj*2+0] -= A->L->value[j*4+0] * t0 + A->L->value[j*4+1] * t1;
x[jj*2+1] -= A->L->value[j*4+2] * t0 + A->L->value[j*4+3] * t1;
}
}
break;
case 3:
for(i=nr-1;i>=0;i--)
{
t0 = A->WD->value[9*i+0] * x[i*3] + A->WD->value[9*i+1] * x[i*3+1] + A->WD->value[9*i+2] * x[i*3+2];
t1 = A->WD->value[9*i+3] * x[i*3] + A->WD->value[9*i+4] * x[i*3+1] + A->WD->value[9*i+5] * x[i*3+2];
t2 = A->WD->value[9*i+6] * x[i*3] + A->WD->value[9*i+7] * x[i*3+1] + A->WD->value[9*i+8] * x[i*3+2];
x[i*3] = t0;
x[i*3+1] = t1;
x[i*3+2] = t2;
for(j=A->L->bptr[i];j<A->L->bptr[i+1];j++)
{
jj = A->L->bindex[j];
x[jj*3+0] -= A->L->value[j*9+0] * t0 + A->L->value[j*9+1] * t1 + A->L->value[j*9+2] * t2;
x[jj*3+1] -= A->L->value[j*9+3] * t0 + A->L->value[j*9+4] * t1 + A->L->value[j*9+5] * t2;
x[jj*3+2] -= A->L->value[j*9+6] * t0 + A->L->value[j*9+7] * t1 + A->L->value[j*9+8] * t2;
}
}
break;
default:
w = (LIS_SCALAR *)lis_malloc(bnr*sizeof(LIS_SCALAR),"lis_matrix_solvet_bsc::w");
for(i=nr-1;i>=0;i--)
{
for(jj=0;jj<bnc;jj++)
{
t0 = 0.0;
for(ii=0;ii<bnr;ii++)
{
t0 += A->WD->value[i*bs + jj*bnr+ii] * x[i*bnr + ii];
}
w[jj] = t0;
}
memcpy(&x[i*bnr],w,bnr*sizeof(LIS_SCALAR));
for(j=A->L->bptr[i];j<A->L->bptr[i+1];j++)
{
k = A->L->bindex[j] * bnc;
for(jj=0;jj<bnc;jj++)
{
t0 = 0.0;
for(ii=0;ii<bnr;ii++)
{
t0 += A->L->value[j*bs + jj*bnr+ii] * w[ii];
}
x[k + jj] -= t0;
}
}
}
lis_free(w);
break;
}
break;
case LIS_MATRIX_SSOR:
switch(bnr)
{
case 1:
for(i=0;i<nr;i++)
{
t0 = x[i] * A->WD->value[i];
for(j=A->U->bptr[i];j<A->U->bptr[i+1];j++)
{
jj = A->U->bindex[j];
x[jj] -= A->U->value[j] * t0;
}
}
for(i=nr-1;i>=0;i--)
{
t0 = x[i] * A->WD->value[i];
x[i] = t0;
for(j=A->L->bptr[i];j<A->L->bptr[i+1];j++)
{
jj = A->L->bindex[j];
x[jj] -= A->L->value[j] * t0;
}
}
break;
case 2:
for(i=0;i<nr;i++)
{
t0 = A->WD->value[4*i+0] * x[i*2] + A->WD->value[4*i+1] * x[i*2+1];
t1 = A->WD->value[4*i+2] * x[i*2] + A->WD->value[4*i+3] * x[i*2+1];
for(j=A->U->bptr[i];j<A->U->bptr[i+1];j++)
{
jj = A->U->bindex[j];
x[jj*2+0] -= A->U->value[j*4+0] * t0 + A->U->value[j*4+1] * t1;
x[jj*2+1] -= A->U->value[j*4+2] * t0 + A->U->value[j*4+3] * t1;
}
}
for(i=nr-1;i>=0;i--)
{
t0 = A->WD->value[4*i+0] * x[i*2] + A->WD->value[4*i+1] * x[i*2+1];
t1 = A->WD->value[4*i+2] * x[i*2] + A->WD->value[4*i+3] * x[i*2+1];
x[i*2+0] = t0;
x[i*2+1] = t1;
for(j=A->L->bptr[i];j<A->L->bptr[i+1];j++)
{
jj = A->L->bindex[j];
x[jj*2+0] -= A->L->value[j*4+0] * t0 + A->L->value[j*4+1] * t1;
x[jj*2+1] -= A->L->value[j*4+2] * t0 + A->L->value[j*4+3] * t1;
}
}
break;
case 3:
for(i=0;i<nr;i++)
{
t0 = A->WD->value[9*i+0] * x[i*3] + A->WD->value[9*i+1] * x[i*3+1] + A->WD->value[9*i+2] * x[i*3+2];
t1 = A->WD->value[9*i+3] * x[i*3] + A->WD->value[9*i+4] * x[i*3+1] + A->WD->value[9*i+5] * x[i*3+2];
t2 = A->WD->value[9*i+6] * x[i*3] + A->WD->value[9*i+7] * x[i*3+1] + A->WD->value[9*i+8] * x[i*3+2];
for(j=A->U->bptr[i];j<A->U->bptr[i+1];j++)
{
jj = A->U->bindex[j];
x[jj*3+0] -= A->U->value[j*9+0] * t0 + A->U->value[j*9+1] * t1 + A->U->value[j*9+2] * t2;
x[jj*3+1] -= A->U->value[j*9+3] * t0 + A->U->value[j*9+4] * t1 + A->U->value[j*9+5] * t2;
x[jj*3+2] -= A->U->value[j*9+6] * t0 + A->U->value[j*9+7] * t1 + A->U->value[j*9+8] * t2;
}
}
for(i=nr-1;i>=0;i--)
{
t0 = A->WD->value[9*i+0] * x[i*3] + A->WD->value[9*i+1] * x[i*3+1] + A->WD->value[9*i+2] * x[i*3+2];
t1 = A->WD->value[9*i+3] * x[i*3] + A->WD->value[9*i+4] * x[i*3+1] + A->WD->value[9*i+5] * x[i*3+2];
t2 = A->WD->value[9*i+6] * x[i*3] + A->WD->value[9*i+7] * x[i*3+1] + A->WD->value[9*i+8] * x[i*3+2];
x[i*3] = t0;
x[i*3+1] = t1;
x[i*3+2] = t2;
for(j=A->L->bptr[i];j<A->L->bptr[i+1];j++)
{
jj = A->L->bindex[j];
x[jj*3+0] -= A->L->value[j*9+0] * t0 + A->L->value[j*9+1] * t1 + A->L->value[j*9+2] * t2;
x[jj*3+1] -= A->L->value[j*9+3] * t0 + A->L->value[j*9+4] * t1 + A->L->value[j*9+5] * t2;
x[jj*3+2] -= A->L->value[j*9+6] * t0 + A->L->value[j*9+7] * t1 + A->L->value[j*9+8] * t2;
}
}
break;
default:
w = (LIS_SCALAR *)lis_malloc(bnc*sizeof(LIS_SCALAR),"lis_matrix_solvet_bsc::w");
for(i=0;i<nr;i++)
{
for(jj=0;jj<bnc;jj++)
{
t0 = 0.0;
for(ii=0;ii<bnr;ii++)
{
t0 += A->WD->value[i*bs + jj*bnr+ii] * x[i*bnr + ii];
}
w[jj] = t0;
}
for(j=A->U->bptr[i];j<A->U->bptr[i+1];j++)
{
k = A->U->bindex[j] * bnc;
for(jj=0;jj<bnc;jj++)
{
t0 = 0.0;
for(ii=0;ii<bnr;ii++)
{
t0 += A->U->value[j*bs + jj*bnr+ii] * w[ii];
}
x[k + jj] -= t0;
}
}
}
for(i=nr-1;i>=0;i--)
{
for(jj=0;jj<bnc;jj++)
{
t0 = 0.0;
for(ii=0;ii<bnr;ii++)
{
t0 += A->WD->value[i*bs + jj*bnr+ii] * x[i*bnr + ii];
}
w[jj] = t0;
}
memcpy(&x[i*bnr],w,bnr*sizeof(LIS_SCALAR));
for(j=A->L->bptr[i];j<A->L->bptr[i+1];j++)
{
k = A->L->bindex[j] * bnc;
for(jj=0;jj<bnc;jj++)
{
t0 = 0.0;
for(ii=0;ii<bnr;ii++)
{
t0 += A->L->value[j*bs + jj*bnr+ii] * w[ii];
}
x[k + jj] -= t0;
}
}
}
lis_free(w);
break;
}
break;
}
LIS_DEBUG_FUNC_OUT;
return LIS_SUCCESS;
}
|
BatchNormalization.c | #ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "generic/BatchNormalization.c"
#else
void THNN_(BatchNormalization_updateOutput)(
THNNState *state, THTensor *input, THTensor *output,
THTensor *weight, THTensor *bias,
THTensor *running_mean, THTensor *running_var,
THTensor *save_mean, THTensor *save_std,
bool train, double momentum, double eps)
{
THTensor_(resizeAs)(output, input);
long nInput = THTensor_(size)(input, 1);
long f;
ptrdiff_t n = THTensor_(nElement)(input) / nInput;
#pragma omp parallel for
for (f = 0; f < nInput; ++f) {
THTensor *in = THTensor_(newSelect)(input, 1, f);
THTensor *out = THTensor_(newSelect)(output, 1, f);
real mean, invstd;
if (train) {
// compute mean per input
accreal sum = 0;
TH_TENSOR_APPLY(real, in, sum += *in_data;);
mean = (real) sum / n;
THTensor_(set1d)(save_mean, f, (real) mean);
// compute variance per input
sum = 0;
TH_TENSOR_APPLY(real, in,
sum += (*in_data - mean) * (*in_data - mean););
if (sum == 0 && eps == 0.0) {
invstd = 0;
} else {
invstd = (real) (1 / sqrt(sum/n + eps));
}
THTensor_(set1d)(save_std, f, (real) invstd);
// update running averages
THTensor_(set1d)(running_mean, f,
(real) (momentum * mean + (1 - momentum) * THTensor_(get1d)(running_mean, f)));
accreal unbiased_var = sum / (n - 1);
THTensor_(set1d)(running_var, f,
(real) (momentum * unbiased_var + (1 - momentum) * THTensor_(get1d)(running_var, f)));
} else {
mean = THTensor_(get1d)(running_mean, f);
invstd = 1 / sqrt(THTensor_(get1d)(running_var, f) + eps);
}
// compute output
real w = weight ? THTensor_(get1d)(weight, f) : 1;
real b = bias ? THTensor_(get1d)(bias, f) : 0;
TH_TENSOR_APPLY2(real, in, real, out,
*out_data = (real) (((*in_data - mean) * invstd) * w + b););
THTensor_(free)(out);
THTensor_(free)(in);
}
}
void THNN_(BatchNormalization_backward)(
THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradInput,
THTensor *gradWeight, THTensor *gradBias, THTensor *weight,
THTensor *running_mean, THTensor *running_var,
THTensor *save_mean, THTensor *save_std,
bool train, double scale, double eps)
{
THNN_CHECK_SHAPE(input, gradOutput);
long nInput = THTensor_(size)(input, 1);
long f;
ptrdiff_t n = THTensor_(nElement)(input) / nInput;
#pragma omp parallel for
for (f = 0; f < nInput; ++f) {
THTensor *in = THTensor_(newSelect)(input, 1, f);
THTensor *gradOut = THTensor_(newSelect)(gradOutput, 1, f);
real w = weight ? THTensor_(get1d)(weight, f) : 1;
real mean, invstd;
if (train) {
mean = THTensor_(get1d)(save_mean, f);
invstd = THTensor_(get1d)(save_std, f);
} else {
mean = THTensor_(get1d)(running_mean, f);
invstd = 1 / sqrt(THTensor_(get1d)(running_var, f) + eps);
}
// sum over all gradOutput in feature plane
accreal sum = 0;
TH_TENSOR_APPLY(real, gradOut, sum += *gradOut_data;);
// dot product of the Q(X) and gradOuput
accreal dotp = 0;
TH_TENSOR_APPLY2(real, in, real, gradOut,
dotp += (*in_data - mean) * (*gradOut_data););
if (gradInput) {
THTensor_(resizeAs)(gradInput, input);
THTensor *gradIn = THTensor_(newSelect)(gradInput, 1, f);
if (train) {
// when in training mode
// Q(X) = X - E[x] ; i.e. input centered to zero mean
// Y = Q(X) / σ ; i.e. BN output before weight and bias
// dL/dX = (Q(dL/dY) - dot(Y, dL/dY) * Y) / σ * w
// projection of gradOutput on to output scaled by std
real k = (real) dotp * invstd * invstd / n;
TH_TENSOR_APPLY2(real, gradIn, real, in,
*gradIn_data = (*in_data - mean) * k;);
accreal gradMean = sum / n;
TH_TENSOR_APPLY2(real, gradIn, real, gradOut,
*gradIn_data = (*gradOut_data - gradMean - *gradIn_data) * invstd * w;);
} else {
// when in evaluation mode
// Q(X) = X - running_mean ; i.e. input centered to zero mean
// Y = Q(X) / running_std ; i.e. BN output before weight and bias
// dL/dX = w / running_std
TH_TENSOR_APPLY2(real, gradIn, real, gradOut,
*gradIn_data = *gradOut_data * invstd * w;);
}
THTensor_(free)(gradIn);
}
if (gradWeight) {
real val = THTensor_(get1d)(gradWeight, f);
THTensor_(set1d)(gradWeight, f, val + scale * dotp * invstd);
}
if (gradBias) {
real val = THTensor_(get1d)(gradBias, f);
THTensor_(set1d)(gradBias, f, val + scale * sum);
}
THTensor_(free)(gradOut);
THTensor_(free)(in);
}
}
#endif
|
ripemd_fmt_plug.c | /* ripemd cracker patch for JtR. Hacked together during April of 2013 by Dhiru
* Kholia <dhiru at openwall.com>.
*
* This software is Copyright (c) 2013 Dhiru Kholia <dhiru at openwall.com> and
* it is hereby released to the general public under the following terms:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted.
*/
#if FMT_EXTERNS_H
extern struct fmt_main fmt_ripemd_160;
extern struct fmt_main fmt_ripemd_128;
#elif FMT_REGISTERS_H
john_register_one(&fmt_ripemd_160);
john_register_one(&fmt_ripemd_128);
#else
#include <string.h>
#include "arch.h"
#include "sph_ripemd.h"
#include "misc.h"
#include "common.h"
#include "formats.h"
#include "params.h"
#include "options.h"
#if !FAST_FORMATS_OMP
#undef _OPENMP
#endif
#ifdef _OPENMP
static int omp_t = 1;
#include <omp.h>
// OMP_SCALE tuned on core i7 quad core HT
// 128 160
// 1 - 234k 234k
// 64 - 7547k 6310k
// 128 - 9849k 7987k
// 256 - 11835k 9205k
// 512 - 13288k 10027k
// 1k - 14142k 10553k
// 2k - 14607k 11980k ** this level chosen
// 4k - 14828k 10871k
// 8k - 14639k 10794k
#ifndef OMP_SCALE
#ifdef __MIC__
#define OMP_SCALE 64
#else
#define OMP_SCALE 2048
#endif // __MIC__
#endif // OMP_SCALE
#endif // _OPENMP
#include "memdbg.h"
#define FORMAT_TAG "$ripemd$"
#define TAG_LENGTH (sizeof(FORMAT_TAG)-1)
#define ALGORITHM_NAME "32/" ARCH_BITS_STR
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH -1
#define PLAINTEXT_LENGTH 125
#define BINARY_SIZE160 20
#define BINARY_SIZE128 16
#define SALT_SIZE 0
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
#define BINARY_ALIGN 4
#define SALT_ALIGN 1
static struct fmt_tests ripemd_160_tests[] = {
{"9c1185a5c5e9fc54612808977ee8f548b2258d31", ""},
{"$ripemd$9c1185a5c5e9fc54612808977ee8f548b2258d31", ""},
{"56e11fdd5479b30020fc010551536af074e1b82f", "thisisalongstring"},
{"$ripemd$56e11fdd5479b30020fc010551536af074e1b82f", "thisisalongstring"},
{"a1a94e392ce7d861a4fdcaa291e453c082807f50", "string with space"},
{"$ripemd$a1a94e392ce7d861a4fdcaa291e453c082807f50", "string with space"},
{"98f3860a474d986964df9c1fd3621e68eaf76a25", "UPPERCASE"},
{"$ripemd$98f3860a474d986964df9c1fd3621e68eaf76a25", "UPPERCASE"},
{"d3d0379126c1e5e0ba70ad6e5e53ff6aeab9f4fa", "123456789"},
{"$ripemd$d3d0379126c1e5e0ba70ad6e5e53ff6aeab9f4fa", "123456789"},
{NULL}
};
static struct fmt_tests ripemd_128_tests[] = {
{"cdf26213a150dc3ecb610f18f6b38b46", ""},
{"$ripemd$cdf26213a150dc3ecb610f18f6b38b46", ""},
{"060d8817be332f6e6a9a09a209ea453e", "thisisalongstring"},
{"$ripemd$060d8817be332f6e6a9a09a209ea453e", "thisisalongstring"},
{"ed402bdf044344c34935ac93a2d90a13", "string with space"},
{"$ripemd$ed402bdf044344c34935ac93a2d90a13", "string with space"},
{"5e71f949a0d5c69f3c1aeaf245ba527a", "UPPERCASE"},
{"$ripemd$5e71f949a0d5c69f3c1aeaf245ba527a", "UPPERCASE"},
{"1886db8acdcbfeab1e7ee3780400536f", "123456789"},
{"$ripemd$1886db8acdcbfeab1e7ee3780400536f", "123456789"},
{NULL}
};
static char (*saved_key)[PLAINTEXT_LENGTH + 1];
static ARCH_WORD_32 (*crypt_out)[BINARY_SIZE160 / sizeof(ARCH_WORD_32)];
static void init(struct fmt_main *self)
{
#ifdef _OPENMP
omp_t = omp_get_max_threads();
self->params.min_keys_per_crypt *= omp_t;
omp_t *= OMP_SCALE;
self->params.max_keys_per_crypt *= omp_t;
#endif
if (!saved_key) {
saved_key = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*saved_key));
crypt_out = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*crypt_out));
}
}
static void done(void)
{
MEM_FREE(crypt_out);
MEM_FREE(saved_key);
}
static int valid(char *ciphertext, struct fmt_main *self, int len)
{
char *p;
p = ciphertext;
if (!strncmp(p, FORMAT_TAG, TAG_LENGTH))
p += TAG_LENGTH;
if (strlen(p) != len)
return 0;
while(*p)
if(atoi16[ARCH_INDEX(*p++)]==0x7f)
return 0;
return 1;
}
static int valid160(char *ciphertext, struct fmt_main *self)
{
return valid(ciphertext, self, 40);
}
static int valid128(char *ciphertext, struct fmt_main *self)
{
return valid(ciphertext, self, 32);
}
static void *get_binary_160(char *ciphertext)
{
static union {
unsigned char c[20];
ARCH_WORD dummy;
} buf;
unsigned char *out = buf.c;
char *p;
int i;
if (!strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH))
p = strrchr(ciphertext, '$') + 1;
else
p = ciphertext;
for (i = 0; i < 20; i++) {
out[i] =
(atoi16[ARCH_INDEX(*p)] << 4) |
atoi16[ARCH_INDEX(p[1])];
p += 2;
}
return out;
}
static void *get_binary_128(char *ciphertext)
{
static union {
unsigned char c[16];
ARCH_WORD dummy;
} buf;
unsigned char *out = buf.c;
char *p;
int i;
if (!strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH))
p = strrchr(ciphertext, '$') + 1;
else
p = ciphertext;
for (i = 0; i < 16; i++) {
out[i] =
(atoi16[ARCH_INDEX(*p)] << 4) |
atoi16[ARCH_INDEX(p[1])];
p += 2;
}
return out;
}
static int get_hash_0(int index) { return crypt_out[index][0] & PH_MASK_0; }
static int get_hash_1(int index) { return crypt_out[index][0] & PH_MASK_1; }
static int get_hash_2(int index) { return crypt_out[index][0] & PH_MASK_2; }
static int get_hash_3(int index) { return crypt_out[index][0] & PH_MASK_3; }
static int get_hash_4(int index) { return crypt_out[index][0] & PH_MASK_4; }
static int get_hash_5(int index) { return crypt_out[index][0] & PH_MASK_5; }
static int get_hash_6(int index) { return crypt_out[index][0] & PH_MASK_6; }
static int crypt_160(int *pcount, struct db_salt *salt)
{
int count = *pcount;
int index = 0;
#ifdef _OPENMP
#pragma omp parallel for
for (index = 0; index < count; index++)
#endif
{
sph_ripemd160_context ctx;
sph_ripemd160_init(&ctx);
sph_ripemd160(&ctx, saved_key[index], strlen(saved_key[index]));
sph_ripemd160_close(&ctx, (unsigned char*)crypt_out[index]);
}
return count;
}
static int crypt_128(int *pcount, struct db_salt *salt)
{
int count = *pcount;
int index = 0;
#ifdef _OPENMP
#pragma omp parallel for
for (index = 0; index < count; index++)
#endif
{
sph_ripemd128_context ctx;
sph_ripemd128_init(&ctx);
sph_ripemd128(&ctx, saved_key[index], strlen(saved_key[index]));
sph_ripemd128_close(&ctx, (unsigned char*)crypt_out[index]);
}
return count;
}
static int cmp_all(void *binary, int count)
{
int index = 0;
#ifdef _OPENMP
for (; index < count; index++)
#endif
if (!memcmp(binary, crypt_out[index], ARCH_SIZE))
return 1;
return 0;
}
static int cmp_one128(void *binary, int index)
{
return !memcmp(binary, crypt_out[index], BINARY_SIZE128);
}
static int cmp_one160(void *binary, int index)
{
return !memcmp(binary, crypt_out[index], BINARY_SIZE160);
}
static int cmp_exact(char *source, int index)
{
return 1;
}
static void ripemd_set_key(char *key, int index)
{
int saved_len = strlen(key);
if (saved_len > PLAINTEXT_LENGTH)
saved_len = PLAINTEXT_LENGTH;
memcpy(saved_key[index], key, saved_len);
saved_key[index][saved_len] = 0;
}
static char *get_key(int index)
{
return saved_key[index];
}
static char *split(char *ciphertext, int index, struct fmt_main *self)
{
static char out[TAG_LENGTH + 2 * BINARY_SIZE160 + 1];
if (!strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH))
ciphertext += TAG_LENGTH;
strcpy(out, FORMAT_TAG);
strcpy(&out[TAG_LENGTH], ciphertext);
strlwr(&out[TAG_LENGTH]);
return out;
}
struct fmt_main fmt_ripemd_160 = {
{
"ripemd-160",
"RIPEMD 160",
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
BINARY_SIZE160,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
#ifdef _OPENMP
FMT_OMP | FMT_OMP_BAD |
#endif
FMT_CASE | FMT_8_BIT | FMT_SPLIT_UNIFIES_CASE,
{ NULL },
{ FORMAT_TAG },
ripemd_160_tests
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid160,
split,
get_binary_160,
fmt_default_salt,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash_0,
fmt_default_binary_hash_1,
fmt_default_binary_hash_2,
fmt_default_binary_hash_3,
fmt_default_binary_hash_4,
fmt_default_binary_hash_5,
fmt_default_binary_hash_6
},
fmt_default_salt_hash,
NULL,
fmt_default_set_salt,
ripemd_set_key,
get_key,
fmt_default_clear_keys,
crypt_160,
{
get_hash_0,
get_hash_1,
get_hash_2,
get_hash_3,
get_hash_4,
get_hash_5,
get_hash_6
},
cmp_all,
cmp_one160,
cmp_exact
}
};
struct fmt_main fmt_ripemd_128 = {
{
"ripemd-128",
"RIPEMD 128",
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
BINARY_SIZE128,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
#ifdef _OPENMP
FMT_OMP | FMT_OMP_BAD |
#endif
FMT_CASE | FMT_8_BIT | FMT_SPLIT_UNIFIES_CASE,
{ NULL },
{ FORMAT_TAG },
ripemd_128_tests
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid128,
split,
get_binary_128,
fmt_default_salt,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash_0,
fmt_default_binary_hash_1,
fmt_default_binary_hash_2,
fmt_default_binary_hash_3,
fmt_default_binary_hash_4,
fmt_default_binary_hash_5,
fmt_default_binary_hash_6
},
fmt_default_salt_hash,
NULL,
fmt_default_set_salt,
ripemd_set_key,
get_key,
fmt_default_clear_keys,
crypt_128,
{
get_hash_0,
get_hash_1,
get_hash_2,
get_hash_3,
get_hash_4,
get_hash_5,
get_hash_6
},
cmp_all,
cmp_one128,
cmp_exact
}
};
#endif /* plugin stanza */
|
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 CXXCtorInitializerMatcher = internal::Matcher<CXXCtorInitializer>;
using TemplateArgumentMatcher = internal::Matcher<TemplateArgument>;
using TemplateArgumentLocMatcher = internal::Matcher<TemplateArgumentLoc>;
/// @}
/// 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::VariadicAllOfMatcher<DecompositionDecl>
decompositionDecl;
/// 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 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 a declaration that has been implicitly added
/// by the compiler (eg. implicit default/copy constructors).
AST_MATCHER(Decl, isImplicit) {
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 P1> class MatcherT, typename P1,
typename ReturnTypesF>
internal::TraversalWrapper<
internal::PolymorphicMatcherWithParam1<MatcherT, P1, ReturnTypesF>>
traverse(TraversalKind TK, const internal::PolymorphicMatcherWithParam1<
MatcherT, P1, ReturnTypesF> &InnerMatcher) {
return internal::TraversalWrapper<
internal::PolymorphicMatcherWithParam1<MatcherT, P1, ReturnTypesF>>(
TK, InnerMatcher);
}
template <template <typename T, typename P1, typename P2> class MatcherT,
typename P1, typename P2, typename ReturnTypesF>
internal::TraversalWrapper<
internal::PolymorphicMatcherWithParam2<MatcherT, P1, P2, ReturnTypesF>>
traverse(TraversalKind TK, const internal::PolymorphicMatcherWithParam2<
MatcherT, P1, P2, ReturnTypesF> &InnerMatcher) {
return internal::TraversalWrapper<
internal::PolymorphicMatcherWithParam2<MatcherT, P1, P2, ReturnTypesF>>(
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 b, c, and d.
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 Node.getAsIntegral().toString(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 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 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 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 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::PolymorphicMatcherWithParam1<
internal::HasOverloadedOperatorNameMatcher, std::vector<std::string>,
AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>
hasOverloadedOperatorName(StringRef Name) {
return internal::PolymorphicMatcherWithParam1<
internal::HasOverloadedOperatorNameMatcher, std::vector<std::string>,
AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>(
{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::PolymorphicMatcherWithParam1<
internal::HasOverloadedOperatorNameMatcher, std::vector<std::string>,
AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>,
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>,
internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
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>,
internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
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::PolymorphicMatcherWithParam1<
internal::HasDeclarationMatcher, internal::Matcher<Decl>,
void(internal::HasDeclarationSupportedTypes)>
hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
return internal::PolymorphicMatcherWithParam1<
internal::HasDeclarationMatcher, internal::Matcher<Decl>,
void(internal::HasDeclarationSupportedTypes)>(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"))
/// \code
/// class X {};
/// void y(X &x) { x; X z; }
/// typedef int U;
/// class Y { friend class X; };
/// \endcode
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
hasType,
AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, TypedefNameDecl,
ValueDecl),
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"))
/// \code
/// class X {};
/// void y(X &x) { x; X z; }
/// class Y { friend class 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 the declarator decl's type matches
/// the inner matcher.
///
/// Given
/// \code
/// int x;
/// \endcode
/// declaratorDecl(hasTypeLoc(loc(asString("int"))))
/// matches int x
AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) {
if (!Node.getTypeSourceInfo())
// This happens for example for implicit destructors.
return false;
return Inner.matches(Node.getTypeSourceInfo()->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;
for (; ArgIndex < Node.getNumArgs(); ++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
/// hasAnyBody(functionDecl())
/// 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::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
equals(const ValueT &Value) {
return internal::PolymorphicMatcherWithParam1<
internal::ValueEqualsMatcher,
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::PolymorphicMatcherWithParam1<
internal::HasAnyOperatorNameMatcher, std::vector<std::string>,
AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
CXXRewrittenBinaryOperator,
UnaryOperator)>,
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(UsingDecl, 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);
}
/// 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(Expr, nullPointerConstant) {
return Node.isNullPointerConstant(Finder->getASTContext(),
Expr::NPC_ValueDependentIsNull);
}
/// Matches declaration of the function 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(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 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
|
simd-7.c | /* { dg-do run { target vect_simd_clones } } */
/* { dg-additional-options "-msse2" { target sse2_runtime } } */
/* { dg-additional-options "-mavx" { target avx_runtime } } */
#include <stdio.h>
#include <stdlib.h>
#define N 30
int a[N], a_ref[N], b[N];
#pragma omp declare simd inbranch
int fib( int n )
{
if (n <= 1)
return n;
else
return fib(n-1) + fib(n-2);
}
void fib_ref()
{
int i;
a_ref[0] = 0;
a_ref[1] = 1;
for (i=2; i < N; i++)
a_ref[i] = a_ref[i-2] + a_ref[i-1];
}
int main(void)
{
int i;
#pragma omp simd
for (i=0; i < N; i++)
b[i] = i;
#pragma omp simd
for (i=0; i < N; i++)
a[i] = fib(b[i]);
fib_ref ();
for (i=0; i < N; i++)
if (a[i] != a_ref[i])
abort ();
return 0;
}
|
GB_unop__cos_fc64_fc64.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__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
|
GB_binop__isgt_fp64.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__isgt_fp64)
// A.*B function (eWiseMult): GB (_AemultB_08__isgt_fp64)
// A.*B function (eWiseMult): GB (_AemultB_02__isgt_fp64)
// A.*B function (eWiseMult): GB (_AemultB_04__isgt_fp64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__isgt_fp64)
// A*D function (colscale): GB (_AxD__isgt_fp64)
// D*A function (rowscale): GB (_DxB__isgt_fp64)
// C+=B function (dense accum): GB (_Cdense_accumB__isgt_fp64)
// C+=b function (dense accum): GB (_Cdense_accumb__isgt_fp64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isgt_fp64)
// C=scalar+B GB (_bind1st__isgt_fp64)
// C=scalar+B' GB (_bind1st_tran__isgt_fp64)
// C=A+scalar GB (_bind2nd__isgt_fp64)
// C=A'+scalar GB (_bind2nd_tran__isgt_fp64)
// C type: double
// A type: double
// A pattern? 0
// B type: double
// B pattern? 0
// BinaryOp: cij = (aij > bij)
#define GB_ATYPE \
double
#define GB_BTYPE \
double
#define GB_CTYPE \
double
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
double 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) \
double 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) \
double t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = (x > y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ISGT || GxB_NO_FP64 || GxB_NO_ISGT_FP64)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__isgt_fp64)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_noaccum_template.c"
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__isgt_fp64)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__isgt_fp64)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type double
double bwork = (*((double *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__isgt_fp64)
(
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
double *restrict Cx = (double *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__isgt_fp64)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double *restrict Cx = (double *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__isgt_fp64)
(
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) ;
double alpha_scalar ;
double beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((double *) alpha_scalar_in)) ;
beta_scalar = (*((double *) beta_scalar_in )) ;
}
#include "GB_add_template.c"
GB_FREE_WORKSPACE ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__isgt_fp64)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_08_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__isgt_fp64)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__isgt_fp64)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_04_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__isgt_fp64)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__isgt_fp64)
(
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
double *Cx = (double *) Cx_output ;
double x = (*((double *) x_input)) ;
double *Bx = (double *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
double bij = GBX (Bx, p, false) ;
Cx [p] = (x > bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__isgt_fp64)
(
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 ;
double *Cx = (double *) Cx_output ;
double *Ax = (double *) Ax_input ;
double y = (*((double *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
double 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) \
{ \
double aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x > aij) ; \
}
GrB_Info GB (_bind1st_tran__isgt_fp64)
(
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 \
double
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double x = (*((const double *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
double
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
double aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij > y) ; \
}
GrB_Info GB (_bind2nd_tran__isgt_fp64)
(
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
double y = (*((const double *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_unaryop__lnot_int8_uint32.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__lnot_int8_uint32
// op(A') function: GB_tran__lnot_int8_uint32
// C type: int8_t
// A type: uint32_t
// cast: int8_t cij = (int8_t) aij
// unaryop: cij = !(aij != 0)
#define GB_ATYPE \
uint32_t
#define GB_CTYPE \
int8_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = !(x != 0) ;
// casting
#define GB_CASTING(z, x) \
int8_t z = (int8_t) x ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (x, aij) ; \
GB_OP (GB_CX (pC), x) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_LNOT || GxB_NO_INT8 || GxB_NO_UINT32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__lnot_int8_uint32
(
int8_t *restrict Cx,
const uint32_t *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__lnot_int8_uint32
(
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
|
SweepSAHBuilder.h | // Copyright 2021 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <array>
#include <stack>
#include "../../RadixSort.h"
#include "BVH.h"
namespace anari {
namespace example_device {
using Mark = uint_fast8_t;
using Key = uint32_t;
struct SweepSAHBuildTask;
struct SAHTaskWorkItem
{
size_t nodeIndex;
size_t begin;
size_t end;
size_t depth;
};
size_t workSize(const SAHTaskWorkItem &wi);
// This is a top-down, full-sweep SAH-based BVH builder, sorted by stable
// partitioning for traversal efficiency
struct SweepSAHBuilder
{
SweepSAHBuilder(BVH &bvh);
void build(const box3 &global_bbox,
const box3 *bboxes,
const vec3 *centers,
size_t primitiveCount);
private:
// normalized assumed cost of node isect
constexpr static float traversal_cost{1};
friend class SweepSAHBuildTask;
void run(SweepSAHBuildTask &task, const SAHTaskWorkItem §ion);
// Data //
size_t taskSpawnThreshold{1024};
size_t maxDepth{64};
size_t maxLeafSize{16};
RadixSort<10> sorter;
BVH &bvh;
};
struct SweepSAHBuildTask
{
SweepSAHBuildTask(SweepSAHBuilder &builder,
const box3 *bboxes,
const vec3 *centers,
const std::array<size_t *, 3> &references,
const std::array<float *, 3> &costs,
Mark *marks);
std::optional<std::pair<SAHTaskWorkItem, SAHTaskWorkItem>> build(
const SAHTaskWorkItem &item);
private:
std::pair<float, size_t> findSplit(int axis, size_t begin, size_t end) const;
// Data //
SweepSAHBuilder &builder;
const box3 *bboxes{nullptr};
const vec3 *centers{nullptr};
std::array<size_t * BVH_RESTRICT, 3> references;
std::array<float * BVH_RESTRICT, 3> costs;
Mark *marks{nullptr};
};
// Inlined definitions ////////////////////////////////////////////////////////
inline size_t workSize(const SAHTaskWorkItem &wi)
{
return wi.end - wi.begin;
}
// SweepSAHBuilder //
inline SweepSAHBuilder::SweepSAHBuilder(BVH &bvh) : bvh(bvh) {}
inline void SweepSAHBuilder::build(const box3 &global_bbox,
const box3 *bboxes,
const vec3 *centers,
size_t primitiveCount)
{
bvh.nodes = std::vector<BVH::Node>(2 * primitiveCount + 1);
bvh.primIndices = std::vector<size_t>(primitiveCount);
auto reference_data = std::vector<size_t>(primitiveCount * 3);
auto cost_data = std::vector<float>(primitiveCount * 3);
auto key_data = std::vector<Key>(primitiveCount * 2);
auto mark_data = std::vector<Mark>(primitiveCount);
std::array<float *, 3> costs = {cost_data.data(),
cost_data.data() + primitiveCount,
cost_data.data() + 2 * primitiveCount};
std::array<size_t *, 3> sorted_references;
size_t *unsorted_references = bvh.primIndices.data();
Key *sorted_keys = key_data.data();
Key *unsorted_keys = key_data.data() + primitiveCount;
bvh.node_count = 1;
bvh.nodes[0].setBounds(global_bbox);
#pragma omp parallel
{
for (int axis = 0; axis < 3; ++axis) {
#pragma omp single
{
sorted_references[axis] = unsorted_references;
unsorted_references = reference_data.data() + axis * primitiveCount;
// Make sure that one array is the final array of references used by the
// BVH
if (axis != 0 && sorted_references[axis] == bvh.primIndices.data())
std::swap(sorted_references[axis], unsorted_references);
assert(axis < 2 || sorted_references[0] == bvh.primIndices.data()
|| sorted_references[1] == bvh.primIndices.data());
}
#pragma omp for
for (size_t i = 0; i < primitiveCount; ++i) {
sorted_keys[i] = sorter.make_key(centers[i][axis]);
sorted_references[axis][i] = i;
}
sorter.sort_in_parallel(sorted_keys,
unsorted_keys,
sorted_references[axis],
unsorted_references,
primitiveCount,
sizeof(float) * CHAR_BIT);
}
#pragma omp single
{
SweepSAHBuildTask first_task(
*this, bboxes, centers, sorted_references, costs, mark_data.data());
run(first_task, {0, 0, primitiveCount, 0});
}
}
}
inline void SweepSAHBuilder::run(
SweepSAHBuildTask &task, const SAHTaskWorkItem §ion)
{
std::stack<SAHTaskWorkItem> stack;
stack.push(section);
while (!stack.empty()) {
auto work_item = stack.top();
assert(work_item.depth <= maxDepth);
stack.pop();
auto more_work = task.build(work_item);
if (more_work) {
if (workSize(more_work->first) > workSize(more_work->second))
std::swap(more_work->first, more_work->second);
stack.push(more_work->second);
auto firstItem = more_work->first;
if (workSize(firstItem) > taskSpawnThreshold) {
SweepSAHBuildTask new_task(task);
#pragma omp task firstprivate(new_task, firstItem)
{
run(new_task, firstItem);
}
} else {
stack.push(firstItem);
}
}
}
}
// SweepSAHBuildTask //
inline SweepSAHBuildTask::SweepSAHBuildTask(SweepSAHBuilder &builder,
const box3 *bboxes,
const vec3 *centers,
const std::array<size_t *, 3> &references,
const std::array<float *, 3> &costs,
Mark *marks)
: builder(builder),
bboxes(bboxes),
centers(centers),
references{references[0], references[1], references[2]},
costs{costs[0], costs[1], costs[2]},
marks(marks)
{}
inline std::optional<std::pair<SAHTaskWorkItem, SAHTaskWorkItem>>
SweepSAHBuildTask::build(const SAHTaskWorkItem &item)
{
auto &bvh = builder.bvh;
auto &node = bvh.nodes[item.nodeIndex];
auto make_leaf = [](BVH::Node &node, size_t begin, size_t end) {
node.firstItem = begin;
node.primitiveCount = end - begin;
node.is_leaf = true;
};
if (workSize(item) <= 1 || item.depth >= builder.maxDepth) {
make_leaf(node, item.begin, item.end);
return std::nullopt;
}
std::pair<float, size_t> bestSplits[3];
[[maybe_unused]] bool should_spawn_tasks =
workSize(item) > builder.taskSpawnThreshold;
// Sweep primitives to find the best cost
#pragma omp taskloop if (should_spawn_tasks) grainsize(1) default(shared)
for (int axis = 0; axis < 3; ++axis)
bestSplits[axis] = findSplit(axis, item.begin, item.end);
int bestAxis = 0;
if (bestSplits[0].first > bestSplits[1].first)
bestAxis = 1;
if (bestSplits[bestAxis].first > bestSplits[2].first)
bestAxis = 2;
auto split_index = bestSplits[bestAxis].second;
// Make sure the cost of splitting does not exceed the cost of not splitting
auto maxSplitCost =
half_area(node.getBounds()) * (workSize(item) - builder.traversal_cost);
if (bestSplits[bestAxis].first >= maxSplitCost) {
if (workSize(item) > builder.maxLeafSize) {
// Fallback strategy: median split on largest axis
bestAxis = largest_axis(node.getBounds());
split_index = (item.begin + item.end) / 2;
} else {
make_leaf(node, item.begin, item.end);
return std::nullopt;
}
}
int other_axis[2] = {(bestAxis + 1) % 3, (bestAxis + 2) % 3};
for (size_t i = item.begin; i < split_index; ++i)
marks[references[bestAxis][i]] = 1;
for (size_t i = split_index; i < item.end; ++i)
marks[references[bestAxis][i]] = 0;
auto partition_predicate = [&](size_t i) { return marks[i] != 0; };
auto left_bbox = box3();
auto right_bbox = box3();
// Partition reference arrays and compute bounding boxes
#pragma omp taskgroup
{
#pragma omp task if (should_spawn_tasks) default(shared)
{
std::stable_partition(references[other_axis[0]] + item.begin,
references[other_axis[0]] + item.end,
partition_predicate);
}
#pragma omp task if (should_spawn_tasks) default(shared)
{
std::stable_partition(references[other_axis[1]] + item.begin,
references[other_axis[1]] + item.end,
partition_predicate);
}
#pragma omp task if (should_spawn_tasks) default(shared)
{
for (size_t i = item.begin; i < split_index; ++i)
left_bbox.extend(bboxes[references[bestAxis][i]]);
}
#pragma omp task if (should_spawn_tasks) default(shared)
{
for (size_t i = split_index; i < item.end; ++i)
right_bbox.extend(bboxes[references[bestAxis][i]]);
}
}
// Allocate space for children
size_t first_child;
#pragma omp atomic capture
{
first_child = bvh.node_count;
bvh.node_count += 2;
}
auto &left = bvh.nodes[first_child + 0];
auto &right = bvh.nodes[first_child + 1];
node.firstItem = first_child;
node.primitiveCount = 0;
node.is_leaf = false;
left.setBounds(left_bbox);
right.setBounds(right_bbox);
SAHTaskWorkItem firstItem(
{first_child + 0, item.begin, split_index, item.depth + 1});
SAHTaskWorkItem second_item(
{first_child + 1, split_index, item.end, item.depth + 1});
return std::make_optional(std::make_pair(firstItem, second_item));
}
inline std::pair<float, size_t> SweepSAHBuildTask::findSplit(
int axis, size_t begin, size_t end) const
{
auto bbox = box3();
for (size_t i = end - 1; i > begin; --i) {
bbox.extend(bboxes[references[axis][i]]);
costs[axis][i] = half_area(bbox) * (end - i);
}
bbox = box3();
auto best_split =
std::pair<float, size_t>(std::numeric_limits<float>::max(), end);
for (size_t i = begin; i < end - 1; ++i) {
bbox.extend(bboxes[references[axis][i]]);
auto cost = half_area(bbox) * (i + 1 - begin) + costs[axis][i + 1];
if (cost < best_split.first)
best_split = std::make_pair(cost, i + 1);
}
return best_split;
}
} // namespace example_device
} // namespace anari
|
x86_utils.h | /* Copyright (c) 2016 Anakin Authors All Rights Reserve.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#ifndef X86_UTILS_H
#define X86_UTILS_H
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "saber/core/tensor.h"
namespace anakin {
namespace saber {
#define UNUSED(x) ((void)x)
#define MAYBE_UNUSED(x) UNUSED(x)
#ifdef _WIN32
#define __PRETTY_FUNCTION__ __FUNCSIG__
#endif
namespace utils {
/* a bunch of std:: analogues to be compliant with any msvs version
*
* Rationale: msvs c++ (and even some c) headers contain special pragma that
* injects msvs-version check into object files in order to abi-mismatches
* during the static linking. This makes sense if e.g. std:: objects are passed
* through between application and library, which is not the case for mkl-dnn
* (since there is no any c++-rt dependent stuff, ideally...). */
/* SFINAE helper -- analogue to std::enable_if */
template<bool expr, class T = void> struct enable_if {};
template<class T> struct enable_if<true, T> { typedef T type; };
/* analogue std::conditional */
template <bool, typename, typename> struct conditional {};
template <typename T, typename F> struct conditional<true, T, F>
{ typedef T type; };
template <typename T, typename F> struct conditional<false, T, F>
{ typedef F type; };
template <bool, typename, bool, typename, typename> struct conditional3 {};
template <typename T, typename FT, typename FF>
struct conditional3<true, T, false, FT, FF> { typedef T type; };
template <typename T, typename FT, typename FF>
struct conditional3<false, T, true, FT, FF> { typedef FT type; };
template <typename T, typename FT, typename FF>
struct conditional3<false, T, false, FT, FF> { typedef FF type; };
template <bool, typename U, U, U> struct conditional_v {};
template <typename U, U t, U f> struct conditional_v<true, U, t, f>
{ static constexpr U value = t; };
template <typename U, U t, U f> struct conditional_v<false, U, t, f>
{ static constexpr U value = f; };
template <typename T> struct remove_reference { typedef T type; };
template <typename T> struct remove_reference<T&> { typedef T type; };
template <typename T> struct remove_reference<T&&> { typedef T type; };
template<typename T>
inline const T& min(const T& a, const T& b) {
return a < b ? a : b;
}
template<typename T>
inline const T& max(const T& a, const T& b) {
return a > b ? a : b;
}
template <typename T>
inline T&& forward(typename utils::remove_reference<T>::type &t)
{ return static_cast<T&&>(t); }
template <typename T>
inline T&& forward(typename utils::remove_reference<T>::type &&t)
{ return static_cast<T&&>(t); }
template <typename T>
inline typename remove_reference<T>::type zero()
{ auto zero = typename remove_reference<T>::type(); return zero; }
template <typename T, typename P>
inline bool everyone_is(T val, P item) { return val == item; }
template <typename T, typename P, typename... Args>
inline bool everyone_is(T val, P item, Args... item_others) {
return val == item && everyone_is(val, item_others...);
}
template <typename T, typename P>
inline bool one_of(T val, P item) { return val == item; }
template <typename T, typename P, typename... Args>
inline bool one_of(T val, P item, Args... item_others) {
return val == item || one_of(val, item_others...);
}
template <typename... Args>
inline bool any_null(Args... ptrs) { return one_of(nullptr, ptrs...); }
inline bool implication(bool cause, bool effect) { return !cause || effect; }
template<typename T>
inline void array_copy(T *dst, const T *src, size_t size) {
for (size_t i = 0; i < size; ++i) dst[i] = src[i];
}
template<typename T>
inline bool array_cmp(const T *a1, const T *a2, size_t size) {
for (size_t i = 0; i < size; ++i) if (a1[i] != a2[i]) return false;
return true;
}
template<typename T, typename U>
inline void array_set(T *arr, const U& val, size_t size) {
for (size_t i = 0; i < size; ++i) arr[i] = static_cast<T>(val);
}
namespace product_impl {
template<size_t> struct int2type{};
template <typename T>
constexpr int product_impl(const T *arr, int2type<0>) {
return arr[0];
}
template <typename T, size_t num>
inline T product_impl(const T *arr, int2type<num>) {
return arr[0] * product_impl(arr + 1, int2type<num - 1>()); }
}
template <size_t num, typename T>
inline T array_product(const T *arr) {
return product_impl::product_impl(arr, product_impl::int2type<num-1>());
}
template<typename T, typename R = T>
inline R array_product(const T *arr, size_t size) {
R prod = 1;
for (size_t i = 0; i < size; ++i) {
prod *= arr[i];
}
return prod;
}
template <typename T, typename U>
inline typename remove_reference<T>::type div_up(const T a, const U b) {
assert(b);
return (a + b - 1) / b;
}
template <typename T, typename U>
inline typename remove_reference<T>::type rnd_up(const T a, const U b) {
return div_up(a, b) * b;
}
template <typename T, typename U>
inline typename remove_reference<T>::type rnd_dn(const T a, const U b) {
return (a / b) * b;
}
template <typename T, typename U, typename V>
inline U this_block_size(const T offset, const U max, const V block_size) {
assert(offset < max);
// TODO (Roma): can't use nstl::max() due to circular dependency... we
// need to fix this
const T block_boundary = offset + block_size;
if (block_boundary > max) {
return max - offset;
}
else {
return block_size;
}
}
template <typename T, typename U>
inline void balance211(T n, U team, U tid, T &n_start, T &n_end) {
T n_min = 1;
T &n_my = n_end;
if (team <= 1 || n == 0) {
n_start = 0;
n_my = n;
} else if(n_min == 1) {
// team = T1 + T2
// n = T1*n1 + T2*n2 (n1 - n2 = 1)
T n1 = div_up(n, (T)team);
T n2 = n1 - 1;
T T1 = n - n2 * (T)team;
n_my = (T)tid < T1 ? n1 : n2;
n_start = (T)tid <= T1 ? tid * n1 : T1 * n1 + ((T)tid - T1) * n2;
}
n_end += n_start;
}
template<typename T>
inline T nd_iterator_init(T start) { return start; }
template<typename T, typename U, typename W, typename... Args>
inline T nd_iterator_init(T start, U &x, const W &X, Args &&... tuple) {
start = nd_iterator_init(start, utils::forward<Args>(tuple)...);
x = start % X;
return start / X;
}
inline bool nd_iterator_step() { return true; }
template<typename U, typename W, typename... Args>
inline bool nd_iterator_step(U &x, const W &X, Args &&... tuple) {
if (nd_iterator_step(utils::forward<Args>(tuple)...) ) {
x = (x + 1) % X;
return x == 0;
}
return false;
}
template<typename U, typename W, typename Y>
inline bool nd_iterator_jump(U &cur, const U end, W &x, const Y &X)
{
U max_jump = end - cur;
U dim_jump = X - x;
if (dim_jump <= max_jump) {
x = 0;
cur += dim_jump;
return true;
} else {
cur += max_jump;
x += max_jump;
return false;
}
}
template<typename U, typename W, typename Y, typename... Args>
inline bool nd_iterator_jump(U &cur, const U end, W &x, const Y &X,
Args &&... tuple) {
if (nd_iterator_jump(cur, end, utils::forward<Args>(tuple)...)) {
x = (x + 1) % X;
return x == 0;
}
return false;
}
template <typename Telem, size_t Tdims>
struct array_offset_calculator {
template <typename... Targs>
array_offset_calculator(Telem *base, Targs... Fargs) : _dims{ Fargs... } {
_base_ptr = base;
}
template <typename... Targs>
inline Telem &operator()(Targs... Fargs) {
return *(_base_ptr + _offset(1, Fargs...));
}
private:
template <typename... Targs>
inline size_t _offset(size_t const dimension, size_t element) {
return element;
}
template <typename... Targs>
inline size_t _offset(size_t const dimension, size_t theta, size_t element) {
return element + (_dims[dimension] * theta);
}
template <typename... Targs>
inline size_t _offset(size_t const dimension, size_t theta, size_t element,
Targs... Fargs) {
size_t t_prime = element + (_dims[dimension] * theta);
return _offset(dimension + 1, t_prime, Fargs...);
}
Telem *_base_ptr;
const int _dims[Tdims];
};
} // namespace utils
inline void *zmalloc(size_t size, int alignment) {
void *ptr = NULL;
#ifdef _WIN32
ptr = _aligned_malloc(size, alignment);
int rc = ptr ? 0 : -1;
#else
int rc = ::posix_memalign(&ptr, alignment, size);
#endif
return (rc == 0) ? ptr : NULL;
}
inline void zfree(void *p) {
#ifdef _WIN32
_aligned_free(p);
#else
::free(p);
#endif
}
struct c_compatible {
enum { default_alignment = 4096 };
static void *operator new(size_t sz) {
return zmalloc(sz, default_alignment);
}
static void *operator new(size_t sz, void *p) {
UNUSED(sz);
return p;
}
static void *operator new[](size_t sz) {
return zmalloc(sz, default_alignment);
}
static void operator delete(void *p) {
zfree(p);
}
static void operator delete[](void *p) {
zfree(p);
}
};
inline void yield_thread() { }
// reorder weight layout from NCHW(oc, ic, kh, kw) to OIhw16i16o
inline void weight_reorder_OIhw16i16o(Tensor<X86, AK_FLOAT, NCHW> &input, Tensor<X86, AK_FLOAT, NCHW> &output) {
Shape shape = input.shape();
int oc_value = shape[0], ic_value = shape[1], kh_value = shape[2], kw_value = shape[3];
#pragma omp parallel for collapse(6) schedule(static)
for (int oc_idx = 0; oc_idx < oc_value / 16; ++oc_idx) {
for (int ic_idx = 0; ic_idx < ic_value / 16; ++ic_idx) {
for (int kh = 0; kh < kh_value; ++kh) {
for (int kw = 0; kw < kw_value; ++kw) {
for (int ic = 0; ic < 16; ++ic) {
for (int oc = 0; oc < 16; ++oc) {
int input_idx = (oc_idx * 16 + oc) * ic_value * kh_value * kw_value +
(ic_idx * 16 + ic) * kh_value * kw_value +
kh * kw_value + kw;
int output_idx = oc_idx * ic_value / 16 * kh_value * kw_value * 16 * 16 +
ic_idx * kh_value* kw_value * 16 * 16 +
kh * kw_value * 16 * 16 +
kw * 16 * 16 + ic * 16 + oc;
*(output.mutable_data() + output_idx) = *(input.data() + input_idx);
}
}
}
}
}
}
}
// reorder weight layout from NCHW(oc, ic, kh, kw) to OIhwi16o
inline void weight_reorder_OIhwi16o(Tensor<X86, AK_FLOAT, NCHW> &input, Tensor<X86, AK_FLOAT, NCHW> &output) {
Shape shape = input.shape();
#pragma omp parallel for collapse(5) schedule(static)
for (int oc_idx = 0; oc_idx < shape[0] / 16; ++oc_idx) {
for (int kh = 0; kh < shape[2]; ++kh ) {
for (int kw = 0; kw < shape[3]; ++kw) {
for (int ic = 0; ic < shape[1]; ++ic) {
for (int oc = 0; oc < 16; ++oc) {
int input_idx = (oc_idx * 16 + oc) * shape[1] * shape[2] * shape[3] +
ic * shape[2] * shape[3] +
kh * shape[3] + kw;
int output_idx = oc_idx * shape[2] * shape[3] * shape[1] * 16 +
kh * shape[3] * shape[1] * 16 +
kw * shape[1] * 16 +
ic * 16 + oc;
*(output.mutable_data() + output_idx) = *(input.data() + input_idx);
}
}
}
}
}
}
// reorder weight layout from NCHW(oc, ic, kh, kw) to OIhwi8o
inline void weight_reorder_OIhwi8o(Tensor<X86, AK_FLOAT, NCHW> &input, Tensor<X86, AK_FLOAT, NCHW> &output) {
Shape shape = input.shape();
#pragma omp parallel for collapse(5) schedule(static)
for (int oc_idx = 0; oc_idx < shape[0] / 8; ++oc_idx) {
for (int kh = 0; kh < shape[2]; ++kh) {
for (int kw = 0; kw < shape[3]; ++kw) {
for (int ic = 0; ic < shape[1]; ++ic) {
for (int oc = 0; oc < 8; ++oc) {
int input_idx = (oc_idx * 8 + oc) * shape[1] * shape[2] * shape[3] +
ic * shape[2] * shape[3] +
kh * shape[3] + kw;
int output_idx = oc_idx * shape[2] * shape[3] * shape[1] * 8 +
kh * shape[3] * shape[1] * 8 +
kw * shape[1] * 8 +
ic * 8 + oc;
*(output.mutable_data() + output_idx) = *(input.data() + input_idx);
}
}
}
}
}
}
// reorder weight layout from NCHW to Goihw16g
static void weight_reorder_Goihw16g(Tensor<X86, AK_FLOAT, NCHW> &input, Tensor<X86, AK_FLOAT, NCHW> &output){
Shape shape = input.shape();
int g_value = shape[0], oc_value = shape[1], ic_value = shape[1], kh_value = shape[2], kw_value = shape[3];
#pragma omp parallel for collapse(6) schedule(static)
for (int g_idx = 0; g_idx < g_value/16; ++g_idx) {
for (int oc_idx = 0; oc_idx < oc_value; ++oc_idx) {
for (int ic_idx = 0; ic_idx < ic_value; ++ic_idx) {
for (int kh = 0; kh < kh_value; ++kh) {
for (int kw = 0; kw < kw_value; ++kw) {
for (int g = 0; g < 16; ++g) {
int input_idx = (g_idx * 16 + g) * oc_value * ic_value * kh_value * kw_value +
oc_idx * ic_value * kh_value * kw_value +
ic_idx * kh_value * kw_value +
kh * kw_value + kw;
int output_idx = g_idx * oc_value * ic_value * kh_value * kw_value * 16 +
oc_idx * ic_value * kh_value * kw_value * 16 +
ic_idx * kh_value * kw_value * 16 +
kh * kw_value * 16 + kw * 16 + g;
*(output.mutable_data() + output_idx) = *(input.data() + input_idx);
}
}
}
}
}
}
}
inline size_t datatype_size(DataType data_type) {
switch (data_type) {
case AK_FLOAT: return sizeof(float);
case AK_INT32: return sizeof(int32_t);
case AK_INT16: return sizeof(int16_t);
case AK_INT8: return sizeof(int8_t);
case AK_UINT8: return sizeof(uint8_t);
case AK_INVALID:
default: assert(!"unknown data_type");
}
return 0;
}
} // namespace saber
} // namespace anakin
#if defined(_OPENMP)
#include <omp.h>
#else
inline int omp_get_max_threads() { return 1; }
inline int omp_get_num_threads() { return 1; }
inline int omp_get_thread_num() { return 0; }
inline int omp_in_parallel() { return 0; }
#endif
#endif // X86_UTILS_H
// vim: et ts=4 sw=4 cindent cino^=l0,\:0,N-s
|
fractional_step_strategy.h | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: Jordi Cotela
//
#ifndef KRATOS_FRACTIONAL_STEP_STRATEGY
#define KRATOS_FRACTIONAL_STEP_STRATEGY
// System includes
// External includes
// Project includes
#include "includes/define.h"
#include "includes/model_part.h"
#include "includes/cfd_variables.h"
#include "processes/process.h"
#include "solving_strategies/strategies/solving_strategy.h"
#include "utilities/variable_utils.h"
// Application includes
#include "custom_utilities/solver_settings.h"
#include "fluid_dynamics_application_variables.h"
namespace Kratos {
///@addtogroup FluidDynamicsApplication
///@{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/**
* @brief Fractional-step strategy for incompressible Navier-Stokes formulation
* This strategy implements a splitting scheme for the incompressible Navier-Stokes equations.
* It is intended to be used in combination with the FractionalStep element in the FluidDynamicsApplication.
* The fractional step index, which is stored in the ProcessInfo, takes the values
* 1 : Momentum step (calculate fractional step velocity)
* 2-3 : Unused (reserved for componentwise calculation of frac step velocity)
* 4 : Pressure step
* 5 : Computation of projections
* 6 : End of step velocity
* @tparam TSparseSpace Sparse space template type
* @tparam TDenseSpace Dense space template type
* @tparam TLinearSolver Linear solver template type
*/
template <class TSparseSpace, class TDenseSpace, class TLinearSolver>
class FractionalStepStrategy : public SolvingStrategy<TSparseSpace, TDenseSpace, TLinearSolver>
{
public:
///@name Type Definitions
///@{
/// Counted pointer of FractionalStepStrategy
KRATOS_CLASS_POINTER_DEFINITION(FractionalStepStrategy);
typedef SolvingStrategy<TSparseSpace, TDenseSpace, TLinearSolver> BaseType;
typedef typename BaseType::LocalSystemVectorType LocalSystemVectorType;
typedef typename BaseType::LocalSystemMatrixType LocalSystemMatrixType;
typedef typename SolvingStrategy<TSparseSpace, TDenseSpace, TLinearSolver>::Pointer StrategyPointerType;
typedef SolverSettings<TSparseSpace,TDenseSpace,TLinearSolver> SolverSettingsType;
///@}
///@name Life Cycle
///@{
FractionalStepStrategy(ModelPart& rModelPart,
SolverSettingsType& rSolverConfig,
bool PredictorCorrector):
BaseType(rModelPart,false),
mCalculateReactionsFlag(false),
mrPeriodicIdVar(Kratos::Variable<int>::StaticObject())
{
KRATOS_WARNING("FractionalStepStrategy") << "This constructor is deprecated. Use the one with the \'CalculateReactionsFlag\' instead." << std::endl;
InitializeStrategy(rSolverConfig,PredictorCorrector);
}
FractionalStepStrategy(ModelPart& rModelPart,
SolverSettingsType& rSolverConfig,
bool PredictorCorrector,
const Kratos::Variable<int>& PeriodicVar):
BaseType(rModelPart,false),
mCalculateReactionsFlag(false),
mrPeriodicIdVar(PeriodicVar)
{
KRATOS_WARNING("FractionalStepStrategy") << "This constructor is deprecated. Use the one with the \'CalculateReactionsFlag\' instead." << std::endl;
InitializeStrategy(rSolverConfig,PredictorCorrector);
}
FractionalStepStrategy(
ModelPart& rModelPart,
SolverSettingsType& rSolverConfig,
bool PredictorCorrector,
bool CalculateReactionsFlag)
: BaseType(rModelPart,false)
, mCalculateReactionsFlag(CalculateReactionsFlag)
, mrPeriodicIdVar(Kratos::Variable<int>::StaticObject())
{
InitializeStrategy(rSolverConfig,PredictorCorrector);
}
FractionalStepStrategy(
ModelPart& rModelPart,
SolverSettingsType& rSolverConfig,
bool PredictorCorrector,
bool CalculateReactionsFlag,
const Kratos::Variable<int>& PeriodicVar)
: BaseType(rModelPart,false)
, mCalculateReactionsFlag(CalculateReactionsFlag)
, mrPeriodicIdVar(PeriodicVar)
{
InitializeStrategy(rSolverConfig,PredictorCorrector);
}
/// Destructor.
~FractionalStepStrategy() override{}
///@}
///@name Operators
///@{
///@}
///@name Operations
///@{
void Initialize() override
{
// Set up nodes to use slip conditions if needed.
if (mUseSlipConditions) {
auto& r_model_part = BaseType::GetModelPart();
const int n_conds = r_model_part.NumberOfConditions();
#pragma omp parallel for
for (int i_cond = 0; i_cond < n_conds; ++i_cond) {
auto it_cond = r_model_part.ConditionsBegin() + i_cond;
if (it_cond->Is(SLIP)) {
auto& r_geom = it_cond->GetGeometry();
for (auto& r_node : r_geom) {
r_node.SetLock();
r_node.Set(SLIP, true);
r_node.UnSetLock();
}
}
}
}
}
int Check() override
{
KRATOS_TRY;
// Base strategy check
int ierr = BaseType::Check();
if (ierr != 0) {
return ierr;
}
// Check time order and buffer size
const auto& r_model_part = BaseType::GetModelPart();
KRATOS_ERROR_IF(mTimeOrder == 2 && r_model_part.GetBufferSize() < 3)
<< "Buffer size too small for fractional step strategy (BDF2), needed 3, got " << r_model_part.GetBufferSize() << std::endl;
KRATOS_ERROR_IF(mTimeOrder == 1 && r_model_part.GetBufferSize() < 2)
<< "Buffer size too small for fractional step strategy (Backward Euler), needed 2, got " << r_model_part.GetBufferSize() << std::endl;
// Check elements and conditions
const auto &r_current_process_info = r_model_part.GetProcessInfo();
for (const auto& r_element : r_model_part.Elements()) {
ierr = r_element.Check(r_current_process_info);
if (ierr != 0) {
break;
}
}
for (const auto& r_condition : r_model_part.Conditions()) {
ierr = r_condition.Check(r_current_process_info);
if (ierr != 0) {
break;
}
}
return ierr;
KRATOS_CATCH("");
}
void InitializeSolutionStep() override
{
// Initialize BDF2 coefficients
SetTimeCoefficients();
}
bool SolveSolutionStep() override
{
bool converged = false;
if (mPredictorCorrector) {
const unsigned int echo_level = BaseType::GetEchoLevel();
// Iterative solution for pressure
for (unsigned int it = 0; it < mMaxPressureIter; ++it) {
KRATOS_INFO_IF("FractionalStepStrategy", echo_level > 1) << "Pressure iteration " << it << std::endl;
const auto convergence_output = this->SolveStep();
converged = this->CheckPressureConvergence(std::get<1>(convergence_output));
if (converged) {
KRATOS_INFO_IF("FractionalStepStrategy", echo_level > 0) << "Predictor-corrector converged in " << it + 1 << " iterations." << std::endl;
break;
}
}
KRATOS_WARNING_IF("FractionalStepStrategy", !converged && echo_level > 0) << "Predictor-corrector iterations did not converge." << std::endl;
} else {
// Solve for fractional step velocity, then update pressure once
const auto convergence_output = this->SolveStep();
// If not doing predictor corrector iterations, norm_dp will
// typically be "large" since we are not iterating on pressure.
// It makes no sense to report that the iteration didn't converge
// based on this. Hence, what we report is the convergence of the
// fractional step velocity.
converged = std::get<0>(convergence_output);
}
// Calculate reactions
if (mCalculateReactionsFlag) {
CalculateReactions();
}
return converged;
}
void FinalizeSolutionStep() override
{
if (mReformDofSet) {
this->Clear();
}
}
//TODO: Move to private section as soon as we remove the Python exposure
/**
* @brief Calculates the reactions
* This methods calculates the reactions of the momentum equation.
* These are computed as minus the RHS and saved in the REACTION variable
*/
virtual void CalculateReactions()
{
auto &r_model_part = BaseType::GetModelPart();
auto &r_process_info = r_model_part.GetProcessInfo();
const int n_elems = r_model_part.NumberOfElements();
// Set fractional step index to the momentum equation step
const int original_step = r_process_info[FRACTIONAL_STEP];
r_process_info.SetValue(FRACTIONAL_STEP, 1);
// Allocate and initialize values for REACTION calculation
LocalSystemVectorType RHS_Contribution;
LocalSystemMatrixType LHS_Contribution;
const auto &r_const_process_info = r_process_info;
VariableUtils().SetHistoricalVariableToZero(REACTION, r_model_part.Nodes());
#pragma omp parallel for private(RHS_Contribution, LHS_Contribution)
for (int i_elem = 0; i_elem < n_elems; ++i_elem) {
// Build local system
auto it_elem = r_model_part.ElementsBegin() + i_elem;
it_elem->CalculateLocalSystem(
LHS_Contribution,
RHS_Contribution,
r_const_process_info);
// Accumulate minus the RHS as the reaction
unsigned int index = 0;
auto& r_geom = it_elem->GetGeometry();
const unsigned int n_nodes = r_geom.PointsNumber();
for (unsigned int i = 0; i < n_nodes; ++i) {
r_geom[i].SetLock();
auto& r_reaction = r_geom[i].FastGetSolutionStepValue(REACTION);
for (unsigned int d = 0; d < mDomainSize; ++d) {
r_reaction[d] -= RHS_Contribution[index++];
}
r_geom[i].UnSetLock();
}
}
// Synchronize the local REACTION values
r_model_part.GetCommunicator().AssembleCurrentData(REACTION);
// Reset original fractional step index
r_process_info.SetValue(FRACTIONAL_STEP, original_step);
}
virtual void AddIterationStep(Process::Pointer pNewStep)
{
mExtraIterationSteps.push_back(pNewStep);
}
virtual void ClearExtraIterationSteps()
{
mExtraIterationSteps.clear();
}
void Clear() override
{
mpMomentumStrategy->Clear();
mpPressureStrategy->Clear();
}
///@}
///@name Access
///@{
void SetEchoLevel(int Level) override
{
BaseType::SetEchoLevel(Level);
int StrategyLevel = Level > 0 ? Level - 1 : 0;
mpMomentumStrategy->SetEchoLevel(StrategyLevel);
mpPressureStrategy->SetEchoLevel(StrategyLevel);
}
/**
* @brief This method sets the flag mCalculateReactionsFlag
* @param CalculateReactionsFlag The flag that tells if the reactions are computed
*/
void SetCalculateReactionsFlag(bool CalculateReactionsFlag)
{
mCalculateReactionsFlag = CalculateReactionsFlag;
}
/**
* @brief This method returns the flag mCalculateReactionsFlag
* @return The flag that tells if the reactions are computed
*/
bool GetCalculateReactionsFlag()
{
return mCalculateReactionsFlag;
}
///@}
///@name Inquiry
///@{
///@}
///@name Input and output
///@{
/// Turn back information as a string.
std::string Info() const override
{
std::stringstream buffer;
buffer << "FractionalStepStrategy" ;
return buffer.str();
}
/// 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 {}
///@}
///@name Friends
///@{
///@}
protected:
///@name Protected Life Cycle
///@{
///@}
///@name Protected static Member Variables
///@{
///@}
///@name Protected member Variables
///@{
double mVelocityTolerance;
double mPressureTolerance;
double mPressureGradientRelaxationFactor;
unsigned int mMaxVelocityIter;
unsigned int mMaxPressureIter;
unsigned int mDomainSize;
unsigned int mTimeOrder;
bool mPredictorCorrector;
bool mUseSlipConditions;
bool mReformDofSet;
bool mCalculateReactionsFlag;
/// Scheme for the solution of the momentum equation
StrategyPointerType mpMomentumStrategy;
/// Scheme for the solution of the mass equation
StrategyPointerType mpPressureStrategy;
std::vector< Process::Pointer > mExtraIterationSteps;
const Kratos::Variable<int>& mrPeriodicIdVar;
///@}
///@name Protected Operators
///@{
///@}
///@name Protected Operations
///@{
/**
* @brief Set the Time Coefficients object
* Calculate the coefficients for the BDF2 time iteration.
* These are stored in the BDF_COEFFICIENTS variable of the ProcessInfo container.
*/
void SetTimeCoefficients()
{
KRATOS_TRY;
auto &r_process_info = (BaseType::GetModelPart()).GetProcessInfo();
if (mTimeOrder == 2)
{
//calculate the BDF coefficients
double Dt = r_process_info[DELTA_TIME];
double OldDt = r_process_info.GetPreviousTimeStepInfo(1)[DELTA_TIME];
double Rho = OldDt / Dt;
double TimeCoeff = 1.0 / (Dt * Rho * Rho + Dt * Rho);
Vector& BDFcoeffs = r_process_info[BDF_COEFFICIENTS];
BDFcoeffs.resize(3, false);
BDFcoeffs[0] = TimeCoeff * (Rho * Rho + 2.0 * Rho); //coefficient for step n+1 (3/2Dt if Dt is constant)
BDFcoeffs[1] = -TimeCoeff * (Rho * Rho + 2.0 * Rho + 1.0); //coefficient for step n (-4/2Dt if Dt is constant)
BDFcoeffs[2] = TimeCoeff; //coefficient for step n-1 (1/2Dt if Dt is constant)
}
else if (mTimeOrder == 1)
{
double Dt = r_process_info[DELTA_TIME];
double TimeCoeff = 1.0 / Dt;
Vector& BDFcoeffs = r_process_info[BDF_COEFFICIENTS];
BDFcoeffs.resize(2, false);
BDFcoeffs[0] = TimeCoeff; //coefficient for step n+1 (1/Dt)
BDFcoeffs[1] = -TimeCoeff; //coefficient for step n (-1/Dt)
}
KRATOS_CATCH("");
}
virtual std::tuple<bool,double> SolveStep()
{
ModelPart& rModelPart = BaseType::GetModelPart();
const int n_nodes = rModelPart.NumberOfNodes();
// 1. Fractional step momentum iteration
rModelPart.GetProcessInfo().SetValue(FRACTIONAL_STEP,1);
bool Converged = false;
for(unsigned int it = 0; it < mMaxVelocityIter; ++it)
{
KRATOS_INFO_IF("FractionalStepStrategy", BaseType::GetEchoLevel() > 1) << "Momentum iteration " << it << std::endl;
// build momentum system and solve for fractional step velocity increment
rModelPart.GetProcessInfo().SetValue(FRACTIONAL_STEP,1);
double NormDv = mpMomentumStrategy->Solve();
// // Compute projections (for stabilization)
// rModelPart.GetProcessInfo().SetValue(FRACTIONAL_STEP,4);
// this->ComputeSplitOssProjections(rModelPart);
// // Additional steps // Moved to end of step
// for (std::vector<Process::Pointer>::iterator iExtraSteps = mExtraIterationSteps.begin();
// iExtraSteps != mExtraIterationSteps.end(); ++iExtraSteps)
// (*iExtraSteps)->Execute();
// Check convergence
Converged = this->CheckFractionalStepConvergence(NormDv);
if (Converged)
{
KRATOS_INFO_IF("FractionalStepStrategy", BaseType::GetEchoLevel() > 0) << "Fractional velocity converged in " << it + 1 << " iterations." << std::endl;
break;
}
}
KRATOS_INFO_IF("FractionalStepStrategy", !Converged && BaseType::GetEchoLevel() > 0) << "Fractional velocity iterations did not converge." << std::endl;
// Compute projections (for stabilization)
rModelPart.GetProcessInfo().SetValue(FRACTIONAL_STEP,4);
this->ComputeSplitOssProjections(rModelPart);
// 2. Pressure solution (store pressure variation in PRESSURE_OLD_IT)
rModelPart.GetProcessInfo().SetValue(FRACTIONAL_STEP,5);
#pragma omp parallel for
for (int i_node = 0; i_node < n_nodes; ++i_node) {
auto it_node = rModelPart.NodesBegin() + i_node;
const double old_press = it_node->FastGetSolutionStepValue(PRESSURE);
it_node->FastGetSolutionStepValue(PRESSURE_OLD_IT) = -mPressureGradientRelaxationFactor * old_press;
}
KRATOS_INFO_IF("FractionalStepStrategy", BaseType::GetEchoLevel() > 0) << "Calculating Pressure." << std::endl;
double NormDp = mpPressureStrategy->Solve();
#pragma omp parallel for
for (int i_node = 0; i_node < n_nodes; ++i_node) {
auto it_node = rModelPart.NodesBegin() + i_node;
it_node->FastGetSolutionStepValue(PRESSURE_OLD_IT) += it_node->FastGetSolutionStepValue(PRESSURE);
}
// 3. Compute end-of-step velocity
KRATOS_INFO_IF("FractionalStepStrategy", BaseType::GetEchoLevel() > 0) << "Updating Velocity." << std::endl;
rModelPart.GetProcessInfo().SetValue(FRACTIONAL_STEP,6);
this->CalculateEndOfStepVelocity();
/*
mpPressureStrategy->Clear();
double NormDu = mpPressureStrategy->Solve();
mpPressureStrategy->Clear();
*/
// Additional steps
for (std::vector<Process::Pointer>::iterator iExtraSteps = mExtraIterationSteps.begin();
iExtraSteps != mExtraIterationSteps.end(); ++iExtraSteps)
(*iExtraSteps)->Execute();
// Set the output tuple as the fractional velocity convergence and pressure norm
return std::make_tuple(Converged, NormDp);
}
bool CheckFractionalStepConvergence(const double NormDv)
{
ModelPart& rModelPart = BaseType::GetModelPart();
const int n_nodes = rModelPart.NumberOfNodes();
double NormV = 0.00;
#pragma omp parallel for reduction(+:NormV)
for (int i_node = 0; i_node < n_nodes; ++i_node) {
const auto it_node = rModelPart.NodesBegin() + i_node;
const auto &r_vel = it_node->FastGetSolutionStepValue(VELOCITY);
for (unsigned int d = 0; d < 3; ++d) {
NormV += r_vel[d] * r_vel[d];
}
}
NormV = BaseType::GetModelPart().GetCommunicator().GetDataCommunicator().SumAll(NormV);
NormV = sqrt(NormV);
const double zero_tol = 1.0e-12;
const double Ratio = (NormV < zero_tol) ? NormDv : NormDv / NormV;
KRATOS_INFO_IF("FractionalStepStrategy", BaseType::GetEchoLevel() > 0) << "CONVERGENCE CHECK:" << std::endl;
KRATOS_INFO_IF("FractionalStepStrategy", BaseType::GetEchoLevel() > 0)
<< std::scientific << std::setprecision(8) << "FRAC VEL.: ratio = " << Ratio <<"; exp.ratio = " << mVelocityTolerance << " abs = " << NormDv << std::endl;
if (Ratio < mVelocityTolerance)
return true;
else
return false;
}
bool CheckPressureConvergence(const double NormDp)
{
ModelPart& rModelPart = BaseType::GetModelPart();
const int n_nodes = rModelPart.NumberOfNodes();
double NormP = 0.00;
#pragma omp parallel for reduction(+:NormP)
for (int i_node = 0; i_node < n_nodes; ++i_node) {
const auto it_node = rModelPart.NodesBegin() + i_node;
const double Pr = it_node->FastGetSolutionStepValue(PRESSURE);
NormP += Pr * Pr;
}
NormP = BaseType::GetModelPart().GetCommunicator().GetDataCommunicator().SumAll(NormP);
NormP = sqrt(NormP);
const double zero_tol = 1.0e-12;
const double Ratio = (NormP < zero_tol) ? NormDp : NormDp / NormP;
KRATOS_INFO_IF("FractionalStepStrategy", BaseType::GetEchoLevel() > 0) << "Pressure relative error: " << Ratio << std::endl;
if (Ratio < mPressureTolerance)
{
return true;
}
else
return false;
}
virtual void ComputeSplitOssProjections(ModelPart& rModelPart)
{
array_1d<double,3> Out = ZeroVector(3);
const int n_nodes = rModelPart.NumberOfNodes();
const int n_elems = rModelPart.NumberOfElements();
#pragma omp parallel for
for (int i_node = 0; i_node < n_nodes; ++i_node) {
auto it_node = rModelPart.NodesBegin() + i_node;
it_node->FastGetSolutionStepValue(CONV_PROJ) = CONV_PROJ.Zero();
it_node->FastGetSolutionStepValue(PRESS_PROJ) = PRESS_PROJ.Zero();
it_node->FastGetSolutionStepValue(DIVPROJ) = 0.0;
it_node->FastGetSolutionStepValue(NODAL_AREA) = 0.0;
}
#pragma omp parallel for
for (int i_elem = 0; i_elem < n_elems; ++i_elem) {
const auto it_elem = rModelPart.ElementsBegin() + i_elem;
it_elem->Calculate(CONV_PROJ, Out, rModelPart.GetProcessInfo());
}
rModelPart.GetCommunicator().AssembleCurrentData(CONV_PROJ);
rModelPart.GetCommunicator().AssembleCurrentData(PRESS_PROJ);
rModelPart.GetCommunicator().AssembleCurrentData(DIVPROJ);
rModelPart.GetCommunicator().AssembleCurrentData(NODAL_AREA);
// If there are periodic conditions, add contributions from both sides to the periodic nodes
this->PeriodicConditionProjectionCorrection(rModelPart);
#pragma omp parallel for
for (int i_node = 0; i_node < n_nodes; ++i_node) {
auto it_node = rModelPart.NodesBegin() + i_node;
const double NodalArea = it_node->FastGetSolutionStepValue(NODAL_AREA);
it_node->FastGetSolutionStepValue(CONV_PROJ) /= NodalArea;
it_node->FastGetSolutionStepValue(PRESS_PROJ) /= NodalArea;
it_node->FastGetSolutionStepValue(DIVPROJ) /= NodalArea;
}
}
virtual void CalculateEndOfStepVelocity()
{
ModelPart& rModelPart = BaseType::GetModelPart();
const int n_nodes = rModelPart.NumberOfNodes();
const int n_elems = rModelPart.NumberOfElements();
array_1d<double,3> Out = ZeroVector(3);
VariableUtils().SetHistoricalVariableToZero(FRACT_VEL, rModelPart.Nodes());
#pragma omp parallel for
for (int i_elem = 0; i_elem < n_elems; ++i_elem) {
const auto it_elem = rModelPart.ElementsBegin() + i_elem;
it_elem->Calculate(VELOCITY, Out, rModelPart.GetProcessInfo());
}
rModelPart.GetCommunicator().AssembleCurrentData(FRACT_VEL);
this->PeriodicConditionVelocityCorrection(rModelPart);
// Force the end of step velocity to verify slip conditions in the model
if (mUseSlipConditions)
this->EnforceSlipCondition(SLIP);
if (mDomainSize > 2)
{
#pragma omp parallel for
for (int i_node = 0; i_node < n_nodes; ++i_node) {
auto it_node = rModelPart.NodesBegin() + i_node;
const double NodalArea = it_node->FastGetSolutionStepValue(NODAL_AREA);
if ( ! it_node->IsFixed(VELOCITY_X) )
it_node->FastGetSolutionStepValue(VELOCITY_X) += it_node->FastGetSolutionStepValue(FRACT_VEL_X) / NodalArea;
if ( ! it_node->IsFixed(VELOCITY_Y) )
it_node->FastGetSolutionStepValue(VELOCITY_Y) += it_node->FastGetSolutionStepValue(FRACT_VEL_Y) / NodalArea;
if ( ! it_node->IsFixed(VELOCITY_Z) )
it_node->FastGetSolutionStepValue(VELOCITY_Z) += it_node->FastGetSolutionStepValue(FRACT_VEL_Z) / NodalArea;
}
}
else
{
#pragma omp parallel for
for (int i_node = 0; i_node < n_nodes; ++i_node) {
auto it_node = rModelPart.NodesBegin() + i_node;
const double NodalArea = it_node->FastGetSolutionStepValue(NODAL_AREA);
if ( ! it_node->IsFixed(VELOCITY_X) )
it_node->FastGetSolutionStepValue(VELOCITY_X) += it_node->FastGetSolutionStepValue(FRACT_VEL_X) / NodalArea;
if ( ! it_node->IsFixed(VELOCITY_Y) )
it_node->FastGetSolutionStepValue(VELOCITY_Y) += it_node->FastGetSolutionStepValue(FRACT_VEL_Y) / NodalArea;
}
}
}
/**
* @brief Substract wall-normal component of velocity update to ensure that the final velocity satisfies slip conditions.
* @param rSlipWallFlag If Node.Is(rSlipWallFlag) == true, the node is in the wall.
*/
void EnforceSlipCondition(const Kratos::Flags& rSlipWallFlag)
{
ModelPart& rModelPart = BaseType::GetModelPart();
const int num_nodes_in_model_part = rModelPart.NumberOfNodes();
#pragma omp parallel for
for (int i = 0; i < num_nodes_in_model_part; i++)
{
ModelPart::NodeIterator itNode = rModelPart.NodesBegin() + i;
const Node<3>& r_const_node = *itNode;
if ( r_const_node.Is(rSlipWallFlag) )
{
const array_1d<double,3>& rNormal = itNode->FastGetSolutionStepValue(NORMAL);
array_1d<double,3>& rDeltaVelocity = itNode->FastGetSolutionStepValue(FRACT_VEL);
double Proj = rNormal[0] * rDeltaVelocity[0];
double Norm = rNormal[0] * rNormal[0];
for (unsigned int d = 1; d < mDomainSize; ++d)
{
Proj += rNormal[d] * rDeltaVelocity[d];
Norm += rNormal[d] * rNormal[d];
}
Proj /= Norm;
rDeltaVelocity -= Proj * rNormal;
}
}
}
/** On periodic boundaries, the nodal area and the values to project need to take into account contributions from elements on
* both sides of the boundary. This is done using the conditions and the non-historical nodal data containers as follows:\n
* 1- The partition that owns the PeriodicCondition adds the values on both nodes to their non-historical containers.\n
* 2- The non-historical containers are added across processes, transmiting the right value from the condition owner to all partitions.\n
* 3- The value on all periodic nodes is replaced by the one received in step 2.
*/
void PeriodicConditionProjectionCorrection(ModelPart& rModelPart)
{
Communicator& r_comm = rModelPart.GetCommunicator();
if (mrPeriodicIdVar.Key() != Kratos::Variable<int>::StaticObject().Key())
{
int GlobalNodesNum = r_comm.LocalMesh().Nodes().size();
GlobalNodesNum = r_comm.GetDataCommunicator().SumAll(GlobalNodesNum);
for (typename ModelPart::ConditionIterator itCond = rModelPart.ConditionsBegin(); itCond != rModelPart.ConditionsEnd(); itCond++ )
{
ModelPart::ConditionType::GeometryType& rGeom = itCond->GetGeometry();
if (rGeom.PointsNumber() == 2)
{
Node<3>& rNode0 = rGeom[0];
int Node0Pair = rNode0.FastGetSolutionStepValue(mrPeriodicIdVar);
Node<3>& rNode1 = rGeom[1];
int Node1Pair = rNode1.FastGetSolutionStepValue(mrPeriodicIdVar);
// If the nodes are marked as a periodic pair (this is to avoid acting on two-noded conditions that are not PeriodicCondition)
if ( ( static_cast<int>(rNode0.Id()) == Node1Pair ) && (static_cast<int>(rNode1.Id()) == Node0Pair ) )
{
double NodalArea = rNode0.FastGetSolutionStepValue(NODAL_AREA) + rNode1.FastGetSolutionStepValue(NODAL_AREA);
array_1d<double,3> ConvProj = rNode0.FastGetSolutionStepValue(CONV_PROJ) + rNode1.FastGetSolutionStepValue(CONV_PROJ);
array_1d<double,3> PressProj = rNode0.FastGetSolutionStepValue(PRESS_PROJ) + rNode1.FastGetSolutionStepValue(PRESS_PROJ);
double DivProj = rNode0.FastGetSolutionStepValue(DIVPROJ) + rNode1.FastGetSolutionStepValue(DIVPROJ);
rNode0.GetValue(NODAL_AREA) = NodalArea;
rNode0.GetValue(CONV_PROJ) = ConvProj;
rNode0.GetValue(PRESS_PROJ) = PressProj;
rNode0.GetValue(DIVPROJ) = DivProj;
rNode1.GetValue(NODAL_AREA) = NodalArea;
rNode1.GetValue(CONV_PROJ) = ConvProj;
rNode1.GetValue(PRESS_PROJ) = PressProj;
rNode1.GetValue(DIVPROJ) = DivProj;
}
}
else if (rGeom.PointsNumber() == 4 && rGeom[0].FastGetSolutionStepValue(mrPeriodicIdVar) > GlobalNodesNum)
{
double NodalArea = rGeom[0].FastGetSolutionStepValue(NODAL_AREA);
array_1d<double,3> ConvProj = rGeom[0].FastGetSolutionStepValue(CONV_PROJ);
array_1d<double,3> PressProj = rGeom[0].FastGetSolutionStepValue(PRESS_PROJ);
double DivProj = rGeom[0].FastGetSolutionStepValue(DIVPROJ);
for (unsigned int i = 1; i < 4; i++)
{
NodalArea += rGeom[i].FastGetSolutionStepValue(NODAL_AREA);
ConvProj += rGeom[i].FastGetSolutionStepValue(CONV_PROJ);
PressProj += rGeom[i].FastGetSolutionStepValue(PRESS_PROJ);
DivProj += rGeom[i].FastGetSolutionStepValue(DIVPROJ);
}
for (unsigned int i = 0; i < 4; i++)
{
rGeom[i].GetValue(NODAL_AREA) = NodalArea;
rGeom[i].GetValue(CONV_PROJ) = ConvProj;
rGeom[i].GetValue(PRESS_PROJ) = PressProj;
rGeom[i].GetValue(DIVPROJ) = DivProj;
}
}
}
rModelPart.GetCommunicator().AssembleNonHistoricalData(NODAL_AREA);
rModelPart.GetCommunicator().AssembleNonHistoricalData(CONV_PROJ);
rModelPart.GetCommunicator().AssembleNonHistoricalData(PRESS_PROJ);
rModelPart.GetCommunicator().AssembleNonHistoricalData(DIVPROJ);
for (typename ModelPart::NodeIterator itNode = rModelPart.NodesBegin(); itNode != rModelPart.NodesEnd(); itNode++)
{
if (itNode->GetValue(NODAL_AREA) != 0.0)
{
itNode->FastGetSolutionStepValue(NODAL_AREA) = itNode->GetValue(NODAL_AREA);
itNode->FastGetSolutionStepValue(CONV_PROJ) = itNode->GetValue(CONV_PROJ);
itNode->FastGetSolutionStepValue(PRESS_PROJ) = itNode->GetValue(PRESS_PROJ);
itNode->FastGetSolutionStepValue(DIVPROJ) = itNode->GetValue(DIVPROJ);
// reset for next iteration
itNode->GetValue(NODAL_AREA) = 0.0;
itNode->GetValue(CONV_PROJ) = CONV_PROJ.Zero();
itNode->GetValue(PRESS_PROJ) = PRESS_PROJ.Zero();
itNode->GetValue(DIVPROJ) = 0.0;
}
}
}
}
void PeriodicConditionVelocityCorrection(ModelPart& rModelPart)
{
Communicator& r_comm = rModelPart.GetCommunicator();
if (mrPeriodicIdVar.Key() != Kratos::Variable<int>::StaticObject().Key())
{
int GlobalNodesNum = r_comm.LocalMesh().Nodes().size();
GlobalNodesNum = r_comm.GetDataCommunicator().SumAll(GlobalNodesNum);
for (typename ModelPart::ConditionIterator itCond = rModelPart.ConditionsBegin(); itCond != rModelPart.ConditionsEnd(); itCond++ )
{
ModelPart::ConditionType::GeometryType& rGeom = itCond->GetGeometry();
if (rGeom.PointsNumber() == 2)
{
Node<3>& rNode0 = rGeom[0];
int Node0Pair = rNode0.FastGetSolutionStepValue(mrPeriodicIdVar);
Node<3>& rNode1 = rGeom[1];
int Node1Pair = rNode1.FastGetSolutionStepValue(mrPeriodicIdVar);
// If the nodes are marked as a periodic pair (this is to avoid acting on two-noded conditions that are not PeriodicCondition)
if ( ( static_cast<int>(rNode0.Id()) == Node1Pair ) && (static_cast<int>(rNode1.Id()) == Node0Pair ) )
{
array_1d<double,3> DeltaVel = rNode0.FastGetSolutionStepValue(FRACT_VEL) + rNode1.FastGetSolutionStepValue(FRACT_VEL);
rNode0.GetValue(FRACT_VEL) = DeltaVel;
rNode1.GetValue(FRACT_VEL) = DeltaVel;
}
}
else if (rGeom.PointsNumber() == 4 && rGeom[0].FastGetSolutionStepValue(mrPeriodicIdVar) > GlobalNodesNum)
{
array_1d<double,3> DeltaVel = rGeom[0].FastGetSolutionStepValue(FRACT_VEL);
for (unsigned int i = 1; i < 4; i++)
{
DeltaVel += rGeom[i].FastGetSolutionStepValue(FRACT_VEL);
}
for (unsigned int i = 0; i < 4; i++)
{
rGeom[i].GetValue(FRACT_VEL) = DeltaVel;
}
}
}
rModelPart.GetCommunicator().AssembleNonHistoricalData(FRACT_VEL);
for (typename ModelPart::NodeIterator itNode = rModelPart.NodesBegin(); itNode != rModelPart.NodesEnd(); itNode++)
{
array_1d<double,3>& rDeltaVel = itNode->GetValue(FRACT_VEL);
if ( rDeltaVel[0]*rDeltaVel[0] + rDeltaVel[1]*rDeltaVel[1] + rDeltaVel[2]*rDeltaVel[2] != 0.0)
{
itNode->FastGetSolutionStepValue(FRACT_VEL) = itNode->GetValue(FRACT_VEL);
rDeltaVel = ZeroVector(3);
}
}
}
}
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
///@}
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
void InitializeStrategy(
SolverSettingsType& rSolverConfig,
bool PredictorCorrector)
{
KRATOS_TRY;
mTimeOrder = rSolverConfig.GetTimeOrder();
// Check that input parameters are reasonable and sufficient.
this->Check();
mDomainSize = rSolverConfig.GetDomainSize();
mPredictorCorrector = PredictorCorrector;
mUseSlipConditions = rSolverConfig.UseSlipConditions();
mReformDofSet = rSolverConfig.GetReformDofSet();
auto& r_process_info = BaseType::GetModelPart().GetProcessInfo();
if (r_process_info.Has(FS_PRESSURE_GRADIENT_RELAXATION_FACTOR)) {
mPressureGradientRelaxationFactor = r_process_info[FS_PRESSURE_GRADIENT_RELAXATION_FACTOR];
KRATOS_INFO("FractionalStepStrategy") << "Using fractional step strategy with "
"pressure gradient relaxation = "
<< mPressureGradientRelaxationFactor << ".\n";
} else {
mPressureGradientRelaxationFactor = 1.0;
r_process_info.SetValue(FS_PRESSURE_GRADIENT_RELAXATION_FACTOR, mPressureGradientRelaxationFactor);
}
BaseType::SetEchoLevel(rSolverConfig.GetEchoLevel());
// Initialize strategies for each step
bool HaveVelStrategy = rSolverConfig.FindStrategy(SolverSettingsType::Velocity,mpMomentumStrategy);
if (HaveVelStrategy)
{
rSolverConfig.FindTolerance(SolverSettingsType::Velocity,mVelocityTolerance);
rSolverConfig.FindMaxIter(SolverSettingsType::Velocity,mMaxVelocityIter);
}
else
{
KRATOS_ERROR << "FractionalStepStrategy error: No Velocity strategy defined in FractionalStepSettings" << std::endl;
}
bool HavePressStrategy = rSolverConfig.FindStrategy(SolverSettingsType::Pressure,mpPressureStrategy);
if (HavePressStrategy)
{
rSolverConfig.FindTolerance(SolverSettingsType::Pressure,mPressureTolerance);
rSolverConfig.FindMaxIter(SolverSettingsType::Pressure,mMaxPressureIter);
}
else
{
KRATOS_ERROR << "FractionalStepStrategy error: No Pressure strategy defined in FractionalStepSettings" << std::endl;
}
Process::Pointer pTurbulenceProcess;
bool HaveTurbulence = rSolverConfig.GetTurbulenceModel(pTurbulenceProcess);
if (HaveTurbulence)
mExtraIterationSteps.push_back(pTurbulenceProcess);
// Check input parameters
this->Check();
KRATOS_CATCH("");
}
///@}
///@name Private Access
///@{
///@}
///@name Private Inquiry
///@{
///@}
///@name Un accessible methods
///@{
/// Assignment operator.
FractionalStepStrategy& operator=(FractionalStepStrategy const& rOther){}
/// Copy constructor.
FractionalStepStrategy(FractionalStepStrategy const& rOther){}
///@}
}; /// Class FStepStrategy
///@}
///@name Type Definitions
///@{
///@}
///@} // addtogroup
} // namespace Kratos.
#endif // KRATOS_FRACTIONAL_STEP_STRATEGY
|
ContractionCleanup.h | /*
open source routing machine
Copyright (C) Dennis Luxen, others 2010
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU AFFERO General Public License as published by
the Free Software Foundation; either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
or see http://www.gnu.org/licenses/agpl.txt.
*/
#ifndef CONTRACTIONCLEANUP_H_INCLUDED
#define CONTRACTIONCLEANUP_H_INCLUDED
#ifdef _GLIBCXX_PARALLEL
#include <parallel/algorithm>
#else
#include <algorithm>
#endif
#ifdef _WIN32
#include <time.h>
#else
#include <sys/time.h>
#endif
#include "Contractor.h"
#ifdef _OPENMP
#include <omp.h>
#endif
class ContractionCleanup {
private:
struct _HeapData {
NodeID parent;
_HeapData( NodeID p ) {
parent = p;
}
};
#ifdef _MANYCORES
typedef BinaryHeap< NodeID, NodeID, int, _HeapData, DenseStorage<NodeID, NodeID> > _Heap;
#else
typedef BinaryHeap< NodeID, NodeID, int, _HeapData > _Heap;
#endif
struct _ThreadData {
_Heap* _heapForward;
_Heap* _heapBackward;
_ThreadData( NodeID nodes ) {
_heapBackward = new _Heap(nodes);
_heapForward = new _Heap(nodes);
}
~_ThreadData()
{
delete _heapBackward;
delete _heapForward;
}
};
union _MiddleName {
NodeID nameID;
NodeID middle;
};
public:
struct Edge {
NodeID source;
NodeID target;
struct EdgeData {
int distance;
bool shortcut;
bool forward;
bool backward;
short type;
_MiddleName middleName;
} data;
//sorts by source and other attributes
static bool CompareBySource( const Edge& left, const Edge& right ) {
if ( left.source != right.source )
return left.source < right.source;
int l = ( left.data.forward ? -1 : 0 ) + ( left.data.backward ? -1 : 0 );
int r = ( right.data.forward ? -1 : 0 ) + ( right.data.backward ? -1 : 0 );
if ( l != r )
return l < r;
if ( left.target != right.target )
return left.target < right.target;
return left.data.distance < right.data.distance;
}
bool operator== ( const Edge& right ) const {
return ( source == right.source && target == right.target && data.distance == right.data.distance && data.shortcut == right.data.shortcut && data.forward == right.data.forward && data.backward == right.data.backward && data.middleName.middle == right.data.middleName.middle );
}
};
ContractionCleanup( int numNodes, const std::vector< Edge >& edges ) {
_graph = edges;
_numNodes = numNodes;
}
~ContractionCleanup() {
}
void Run() {
RemoveUselessShortcuts();
}
template< class EdgeT >
void GetData( std::vector< EdgeT >& edges ) {
for ( int edge = 0, endEdges = ( int ) _graph.size(); edge != endEdges; ++edge ) {
EdgeT newEdge;
newEdge.source = _graph[edge].source;
newEdge.target = _graph[edge].target;
newEdge.data.distance = _graph[edge].data.distance;
newEdge.data.shortcut = _graph[edge].data.shortcut;
newEdge.data.middleName = _graph[edge].data.middleName;
newEdge.data.forward = _graph[edge].data.forward;
newEdge.data.backward = _graph[edge].data.backward;
newEdge.data.type = _graph[edge].data.type;
edges.push_back( newEdge );
}
#ifdef _GLIBCXX_PARALLEL
__gnu_parallel::sort( edges.begin(), edges.end() );
#else
sort( edges.begin(), edges.end() );
#endif
}
private:
class AllowForwardEdge {
public:
bool operator()( const Edge& data ) const {
return data.data.forward;
}
};
class AllowBackwardEdge {
public:
bool operator()( const Edge& data ) const {
return data.data.backward;
}
};
double _Timestamp() {
#ifdef _WIN32
// not currently used
time_t t = time(NULL);
return (double)t;
#else
struct timeval tp;
gettimeofday(&tp, NULL);
return double(tp.tv_sec) + tp.tv_usec / 1000000.;
#endif
}
void BuildOutgoingGraph() {
//sort edges by source
#ifdef _GLIBCXX_PARALLEL
__gnu_parallel::sort( _graph.begin(), _graph.end(), Edge::CompareBySource );
#else
sort( _graph.begin(), _graph.end(), Edge::CompareBySource );
#endif
try {
_firstEdge.resize( _numNodes + 1 );
} catch(...) {
cerr << "Not enough RAM on machine" << endl;
}
_firstEdge[0] = 0;
for ( NodeID i = 0, node = 0; i < ( NodeID ) _graph.size(); i++ ) {
while ( _graph[i].source != node )
_firstEdge[++node] = i;
if ( i == ( NodeID ) _graph.size() - 1 )
while ( node < _numNodes )
_firstEdge[++node] = ( int ) _graph.size();
}
}
void RemoveUselessShortcuts() {
int maxThreads = omp_get_max_threads();
std::vector < _ThreadData* > threadData;
for ( int threadNum = 0; threadNum < maxThreads; ++threadNum ) {
threadData.push_back( new _ThreadData( _numNodes ) );
}
//cout << "Scanning for useless shortcuts" << endl;
BuildOutgoingGraph();
#pragma omp parallel for
for ( int i = 0; i < (int)_graph.size(); i++ ) {
for ( unsigned edge = _firstEdge[_graph[i].source]; edge < _firstEdge[_graph[i].source + 1]; ++edge ) {
if ( edge == (unsigned)i )
continue;
if ( _graph[edge].target != _graph[i].target )
continue;
if ( _graph[edge].data.distance < _graph[i].data.distance )
continue;
_graph[edge].data.forward &= !_graph[i].data.forward;
_graph[edge].data.backward &= !_graph[i].data.backward;
}
if ( !_graph[i].data.forward && !_graph[i].data.backward )
continue;
//only remove shortcuts
if ( !_graph[i].data.shortcut )
continue;
if ( _graph[i].data.forward ) {
int result = _ComputeDistance( _graph[i].source, _graph[i].target, threadData[omp_get_thread_num()] );
if ( result < _graph[i].data.distance ) {
_graph[i].data.forward = false;
}
}
if ( _graph[i].data.backward ) {
int result = _ComputeDistance( _graph[i].target, _graph[i].source, threadData[omp_get_thread_num()] );
if ( result < _graph[i].data.distance ) {
_graph[i].data.backward = false;
}
}
}
//cout << "Removing edges" << endl;
int usefull = 0;
for ( int i = 0; i < ( int ) _graph.size(); i++ ) {
if ( !_graph[i].data.forward && !_graph[i].data.backward && _graph[i].data.shortcut )
continue;
_graph[usefull] = _graph[i];
usefull++;
}
//cout << "Removed " << _graph.size() - usefull << " useless shortcuts" << endl;
_graph.resize( usefull );
for ( int threadNum = 0; threadNum < maxThreads; ++threadNum ) {
delete threadData[threadNum];
}
}
template< class EdgeAllowed, class StallEdgeAllowed > void _ComputeStep( _Heap* heapForward, _Heap* heapBackward, const EdgeAllowed& edgeAllowed, const StallEdgeAllowed& stallEdgeAllowed, NodeID* middle, int* targetDistance ) {
const NodeID node = heapForward->DeleteMin();
const int distance = heapForward->GetKey( node );
if ( heapBackward->WasInserted( node ) ) {
const int newDistance = heapBackward->GetKey( node ) + distance;
if ( newDistance < *targetDistance ) {
*middle = node;
*targetDistance = newDistance;
}
}
if ( distance > *targetDistance ) {
heapForward->DeleteAll();
return;
}
for ( int edge = _firstEdge[node], endEdges = _firstEdge[node + 1]; edge != endEdges; ++edge ) {
const NodeID to = _graph[edge].target;
const int edgeWeight = _graph[edge].data.distance;
assert( edgeWeight > 0 );
const int toDistance = distance + edgeWeight;
if ( edgeAllowed( _graph[edge] ) ) {
//New Node discovered -> Add to Heap + Node Info Storage
if ( !heapForward->WasInserted( to ) )
heapForward->Insert( to, toDistance, node );
//Found a shorter Path -> Update distance
else if ( toDistance < heapForward->GetKey( to ) ) {
heapForward->DecreaseKey( to, toDistance );
//new parent
heapForward->GetData( to ) = node;
}
}
}
}
int _ComputeDistance( NodeID source, NodeID target, _ThreadData * data, std::vector< NodeID >* path = NULL ) {
data->_heapForward->Clear();
data->_heapBackward->Clear();
//insert source into heap
data->_heapForward->Insert( source, 0, source );
data->_heapBackward->Insert( target, 0, target );
int targetDistance = std::numeric_limits< int >::max();
NodeID middle = 0;
AllowForwardEdge forward;
AllowBackwardEdge backward;
while ( data->_heapForward->Size() + data->_heapBackward->Size() > 0 ) {
if ( data->_heapForward->Size() > 0 ) {
_ComputeStep( data->_heapForward, data->_heapBackward, forward, backward, &middle, &targetDistance );
}
if ( data->_heapBackward->Size() > 0 ) {
_ComputeStep( data->_heapBackward, data->_heapForward, backward, forward, &middle, &targetDistance );
}
}
if ( targetDistance == std::numeric_limits< int >::max() )
return std::numeric_limits< unsigned >::max();
return targetDistance;
}
NodeID _numNodes;
std::vector< Edge > _graph;
std::vector< unsigned > _firstEdge;
};
#endif // CONTRACTIONCLEANUP_H_INCLUDED
|
broadcast_reduce-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.
*/
/*!
* Copyright (c) 2015-2017 by Contributors
* \file broadcast_reduce-inl.h
* \brief CPU-specific Function definition of broadcast and reduce operators
*/
#ifndef MXNET_OPERATOR_TENSOR_BROADCAST_REDUCE_INL_H_
#define MXNET_OPERATOR_TENSOR_BROADCAST_REDUCE_INL_H_
#include <mxnet/operator_util.h>
#include <algorithm>
#include <vector>
#include <string>
#include <utility>
#include "../mshadow_op.h"
#include "../operator_common.h"
namespace mxnet {
namespace op {
namespace broadcast {
using namespace mshadow;
const int MAX_DIM = 5;
template<int ndim>
MSHADOW_XINLINE Shape<ndim> calc_stride(const Shape<ndim>& shape) {
Shape<ndim> stride;
index_t cumprod = 1;
#pragma unroll
for (int i = ndim - 1; i >= 0; --i) {
stride[i] = (shape[i] > 1) ? cumprod : 0;
cumprod *= shape[i];
}
return stride;
}
template<int ndim>
MSHADOW_XINLINE void unravel_dot(const index_t idx, const Shape<ndim>& shape,
const Shape<ndim>& stridej, const Shape<ndim>& stridek, index_t* j, index_t* k) {
*j = 0;
*k = 0;
#pragma unroll
for (index_t i = ndim-1, idx_t = idx; i >=0; --i) {
const auto tmp = idx_t / shape[i];
const auto coord = idx_t - tmp*shape[i];
*j += coord*stridej[i];
*k += coord*stridek[i];
idx_t = tmp;
}
}
template<int ndim>
MSHADOW_XINLINE Shape<ndim> unravel(const index_t idx, const Shape<ndim>& shape) {
Shape<ndim> ret;
#pragma unroll
for (index_t i = ndim-1, j = idx; i >=0; --i) {
auto tmp = j / shape[i];
ret[i] = j - tmp*shape[i];
j = tmp;
}
return ret;
}
template<int ndim>
MSHADOW_XINLINE index_t ravel(const Shape<ndim>& coord, const Shape<ndim>& shape) {
index_t ret = 0;
#pragma unroll
for (index_t i = 0; i < ndim; ++i) {
ret = ret * shape[i] + (shape[i] > 1) * coord[i];
}
return ret;
}
template<int ndim>
MSHADOW_XINLINE int diff(const Shape<ndim>& small, const Shape<ndim>& big, Shape<ndim>* dims,
Shape<ndim>* stride) {
int mdim = 0;
#pragma unroll
for (int i = 0; i < ndim; ++i) {
mdim += small[i] != big[i];
(*dims)[i] = (*stride)[i] = 1;
}
index_t s = 1;
#pragma unroll
for (int i = ndim - 1, j = mdim; i >= 0; --i) {
if (small[i] != big[i]) {
--j;
(*stride)[j] = s;
(*dims)[j] = big[i];
}
s *= big[i];
}
return mdim;
}
template<int ndim>
MSHADOW_XINLINE index_t unravel_dot(const index_t idx, const Shape<ndim>& shape,
const Shape<ndim>& stride) {
index_t ret = 0;
#pragma unroll
for (index_t i = ndim-1, j = idx; i >=0; --i) {
auto tmp = j / shape[i];
ret += (j - tmp*shape[i])*stride[i];
j = tmp;
}
return ret;
}
template<int ndim>
MSHADOW_XINLINE index_t dot(const Shape<ndim>& coord, const Shape<ndim>& stride) {
index_t ret = 0;
#pragma unroll
for (int i = 0; i < ndim; ++i)
ret += coord[i] * stride[i];
return ret;
}
template<typename DType>
MSHADOW_XINLINE void assign(DType* dst, const bool addto, const DType src) {
if (addto) {
*dst += src;
} else {
*dst = src;
}
}
template<int ndim, typename DType, typename OP>
MSHADOW_XINLINE void binary_broadcast_assign(const index_t idx, const bool addto,
const DType* __restrict lhs,
const DType* __restrict rhs, DType* out,
const Shape<ndim>& lshape, const Shape<ndim>& rshape,
const Shape<ndim>& oshape) {
const Shape<ndim> coord = unravel(idx, oshape);
const index_t j = ravel(coord, lshape);
const index_t k = ravel(coord, rshape);
assign(&out[idx], addto, OP::Map(lhs[j], rhs[k]));
}
template<typename Reducer, int ndim, typename AType, typename DType, typename OType, typename OP>
MSHADOW_XINLINE void seq_reduce_assign(const index_t idx, const size_t M, const bool addto,
const DType* __restrict big, OType *small,
const Shape<ndim>& bshape, const Shape<ndim>& sshape,
const Shape<ndim>& rshape, const Shape<ndim>& rstride) {
Shape<ndim> coord = unravel(idx, sshape);
index_t j = ravel(coord, bshape);
AType val, residual;
Reducer::SetInitValue(val, residual);
for (size_t k = 0; k < M; ++k) {
coord = unravel(k, rshape);
Reducer::Reduce(val, AType(OP::Map(big[j + dot(coord, rstride)])), residual);
}
Reducer::Finalize(val, residual);
assign(&small[idx], addto, OType(val));
}
#ifdef __CUDACC__
#include "broadcast_reduce-inl.cuh"
#else
template<int ndim, typename DType, typename OP>
void binary_broadcast_compute(const size_t N, const bool addto, const DType *lhs,
const DType *rhs, DType *out, const Shape<ndim> lshape,
const Shape<ndim> rshape, const Shape<ndim> oshape) {
for (size_t idx = 0; idx < N; ++idx) {
binary_broadcast_assign<ndim, DType, OP>(idx, addto, lhs, rhs, out, lshape, rshape, oshape);
}
}
template<int ndim, typename DType, typename OP>
void BinaryBroadcastComputeImpl(Stream<cpu> *s, const OpReqType req,
const TBlob& lhs, const TBlob& rhs, const TBlob& out) {
if (req == kNullOp) return;
size_t N = out.shape_.Size();
binary_broadcast_compute<ndim, DType, OP>(N, req == kAddTo, lhs.dptr<DType>(), rhs.dptr<DType>(),
out.dptr<DType>(), lhs.shape_.get<ndim>(), rhs.shape_.get<ndim>(),
out.shape_.get<ndim>());
}
template<typename Reducer, int ndim, typename AType, typename DType, typename OType, typename OP>
void seq_reduce_compute(const size_t N, const size_t M, const bool addto,
const DType *big, OType *small, const Shape<ndim> bshape,
const Shape<ndim> sshape, const Shape<ndim> rshape,
const Shape<ndim> rstride) {
#pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount())
for (index_t idx = 0; idx < static_cast<index_t>(N); ++idx) {
seq_reduce_assign<Reducer, ndim, AType, DType, OType, OP>(idx, M, addto, big, small,
bshape, sshape, rshape, rstride);
}
}
template <typename Reducer, int ndim, typename DType, typename OP>
void seq_reduce_compute_extra_mem(const size_t N, const size_t M, const bool addto,
const DType* big, DType* small,
const Shape<ndim> bshape,
const Shape<ndim> sshape,
const Shape<ndim> rshape,
const Shape<ndim> rstride,
const index_t* ws_dptr) {
#pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount())
for (index_t idx = 0; idx < static_cast<index_t>(N); ++idx) {
Shape<ndim> coord = unravel(idx, sshape);
index_t j = ravel(coord, bshape);
DType val, residual;
Reducer::SetInitValue(val, residual);
for (size_t k = 0; k < M; ++k) {
Reducer::Reduce(val, OP::Map(big[j + ws_dptr[k]]), residual);
}
assign(&small[idx], addto, val);
}
}
template <typename Reducer, int ndim, typename DType, typename OP, bool safe_acc = false>
void Reduce(Stream<cpu>* s, const TBlob& small, const OpReqType req,
const Tensor<cpu, 1, char>& workspace, const TBlob& big) {
if (req == kNullOp) return;
Shape<ndim> rshape, rstride;
diff(small.shape_.get<ndim>(), big.shape_.get<ndim>(), &rshape, &rstride);
size_t N = small.shape_.Size(), M = rshape.Size();
if (!safe_acc) {
seq_reduce_compute<Reducer, ndim, DType, DType, DType, OP>(
N, M, req == kAddTo, big.dptr<DType>(), small.dptr<DType>(),
big.shape_.get<ndim>(), small.shape_.get<ndim>(), rshape, rstride);
} else {
// TODO(haojin2): Use real-only type swtich for windows temporarily due to CI issues.
#ifndef _WIN32
MXNET_ACC_TYPE_SWITCH(mshadow::DataType<DType>::kFlag, DataType, AType, {
typedef typename std::conditional<safe_acc, AType, DataType>::type AccType;
MSHADOW_TYPE_SWITCH(small.type_flag_, OType, {
typedef typename std::conditional<safe_acc, OType, DataType>::type OutType;
seq_reduce_compute<Reducer, ndim, AccType, DataType, OutType, OP>(
N, M, req == kAddTo, big.dptr<DataType>(), small.dptr<OutType>(),
big.shape_.get<ndim>(), small.shape_.get<ndim>(), rshape, rstride);
});
});
#else
MXNET_REAL_ACC_TYPE_SWITCH(mshadow::DataType<DType>::kFlag, DataType, AType, {
typedef typename std::conditional<safe_acc, AType, DataType>::type AccType;
MSHADOW_TYPE_SWITCH(small.type_flag_, OType, {
typedef typename std::conditional<safe_acc, OType, DataType>::type OutType;
seq_reduce_compute<Reducer, ndim, AccType, DataType, OutType, OP>(
N, M, req == kAddTo, big.dptr<DataType>(), small.dptr<OutType>(),
big.shape_.get<ndim>(), small.shape_.get<ndim>(), rshape, rstride);
});
});
#endif
}
}
template <typename Reducer, int ndim, typename DType, typename OP>
void ReduceWithExtraMem(Stream<cpu>* s, const TBlob& small, const OpReqType req,
const Tensor<cpu, 1, char>& workspace, const TBlob& big) {
using namespace mxnet_op;
if (req == kNullOp) return;
Shape<ndim> rshape, rstride;
diff(small.shape_.get<ndim>(), big.shape_.get<ndim>(), &rshape, &rstride);
index_t* ws_dptr = reinterpret_cast<index_t*>(workspace.dptr_);
size_t N = small.shape_.Size(), M = rshape.Size();
#pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount())
for (index_t k = 0; k < static_cast<index_t>(M); k++) {
Shape<ndim> coord = unravel(k, rshape);
ws_dptr[k] = dot(coord, rstride);
}
seq_reduce_compute_extra_mem<Reducer, ndim, DType, OP>(
N, M, req == kAddTo, big.dptr<DType>(), small.dptr<DType>(), big.shape_.get<ndim>(),
small.shape_.get<ndim>(), rshape, rstride, ws_dptr);
}
template<int ndim, typename DType>
size_t ReduceWorkspaceSize(Stream<cpu> *s, const mxnet::TShape& small, const OpReqType req,
const mxnet::TShape& big) {
return 0;
}
template<int ndim, typename DType>
size_t ReduceWorkspaceSize(Stream<cpu> *s, const mxnet::TShape& small, const OpReqType req,
const mxnet::TShape& big, const mxnet::TShape& lhs,
const mxnet::TShape& rhs) {
return 0;
}
template<typename Reducer, int ndim, typename DType, typename OP1, typename OP2>
MSHADOW_XINLINE void seq_reduce_assign(const index_t idx, const size_t M, const bool addto,
const DType* __restrict big, const DType* __restrict lhs,
const DType* __restrict rhs, DType *small,
const Shape<ndim>& big_shape, const Shape<ndim>& lhs_shape0,
const Shape<ndim>& rhs_shape0,
const Shape<ndim>& small_shape, const Shape<ndim>& rshape,
const Shape<ndim>& lhs_shape, const Shape<ndim>& rhs_shape,
const Shape<ndim>& rstride, const Shape<ndim>& lhs_stride,
const Shape<ndim>& rhs_stride) {
Shape<ndim> coord = unravel(idx, small_shape);
const index_t idx_big0 = ravel(coord, big_shape);
const index_t idx_lhs0 = ravel(coord, lhs_shape0);
const index_t idx_rhs0 = ravel(coord, rhs_shape0);
DType val, residual;
Reducer::SetInitValue(val, residual);
for (size_t k = 0; k < M; ++k) {
Shape<ndim> coord_big = unravel(k, rshape);
index_t idx_big = idx_big0 + dot(coord_big, rstride);
Shape<ndim> coord_lhs = unravel(k, lhs_shape);
index_t idx_lhs = idx_lhs0 + dot(coord_lhs, lhs_stride);
Shape<ndim> coord_rhs = unravel(k, rhs_shape);
index_t idx_rhs = idx_rhs0 + dot(coord_rhs, rhs_stride);
Reducer::Reduce(val, OP1::Map(big[idx_big], OP2::Map(lhs[idx_lhs], rhs[idx_rhs])), residual);
}
Reducer::Finalize(val, residual);
assign(&small[idx], addto, val);
}
template<typename Reducer, int ndim, typename DType, typename OP1, typename OP2>
void seq_reduce_compute(const size_t N, const size_t M, const bool addto,
const DType *big, const DType *lhs, const DType *rhs, DType *small,
const Shape<ndim> big_shape, const Shape<ndim> small_shape,
const Shape<ndim> rshape, const Shape<ndim> rstride,
const Shape<ndim> lhs_shape, const Shape<ndim> lhs_stride,
const Shape<ndim> rhs_shape, const Shape<ndim> rhs_stride,
const Shape<ndim>& lhs_shape0, const Shape<ndim>& rhs_shape0) {
#pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount())
for (index_t idx = 0; idx < static_cast<index_t>(N); ++idx) {
seq_reduce_assign<Reducer, ndim, DType, OP1, OP2>(idx, M, addto, big, lhs, rhs, small,
big_shape, lhs_shape0, rhs_shape0, small_shape, rshape, lhs_shape, rhs_shape, rstride,
lhs_stride, rhs_stride);
}
}
template<typename Reducer, int ndim, typename DType, typename OP1, typename OP2>
void Reduce(Stream<cpu> *s, const TBlob& small, const OpReqType req,
const Tensor<cpu, 1, char>& workspace, const TBlob& big, const TBlob& lhs,
const TBlob& rhs) {
if (req == kNullOp) return;
Shape<ndim> rshape, rstride;
diff(small.shape_.get<ndim>(), big.shape_.get<ndim>(), &rshape, &rstride);
size_t N = small.shape_.Size();
size_t M = rshape.Size();
Shape<ndim> lhs_shape, lhs_stride;
diff(small.shape_.get<ndim>(), lhs.shape_.get<ndim>(), &lhs_shape, &lhs_stride);
Shape<ndim> rhs_shape, rhs_stride;
diff(small.shape_.get<ndim>(), rhs.shape_.get<ndim>(), &rhs_shape, &rhs_stride);
seq_reduce_compute<Reducer, ndim, DType, OP1, OP2>(
N, M, req == kAddTo,
big.dptr<DType>(), lhs.dptr<DType>(), rhs.dptr<DType>(), small.dptr<DType>(),
big.shape_.get<ndim>(), small.shape_.get<ndim>(),
rshape, rstride,
lhs_shape, lhs_stride,
rhs_shape, rhs_stride,
lhs.shape_.get<ndim>(), rhs.shape_.get<ndim>());
}
#endif
} // namespace broadcast
} // namespace op
} // namespace mxnet
#endif // MXNET_OPERATOR_TENSOR_BROADCAST_REDUCE_INL_H_
|
statistic.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% SSSSS TTTTT AAA TTTTT IIIII SSSSS TTTTT IIIII CCCC %
% SS T A A T I SS T I C %
% SSS T AAAAA T I SSS T I C %
% SS T A A T I SS T I C %
% SSSSS T A A T IIIII SSSSS T IIIII CCCC %
% %
% %
% MagickCore Image Statistical Methods %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright @ 1999 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/accelerate-private.h"
#include "MagickCore/animate.h"
#include "MagickCore/artifact.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-private.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/client.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/compress.h"
#include "MagickCore/constitute.h"
#include "MagickCore/display.h"
#include "MagickCore/draw.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/gem.h"
#include "MagickCore/gem-private.h"
#include "MagickCore/geometry.h"
#include "MagickCore/list.h"
#include "MagickCore/image-private.h"
#include "MagickCore/magic.h"
#include "MagickCore/magick.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/quantum-private.h"
#include "MagickCore/random_.h"
#include "MagickCore/random-private.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/thread-private.h"
#include "MagickCore/timer.h"
#include "MagickCore/utility.h"
#include "MagickCore/version.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% E v a l u a t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% EvaluateImage() applies a value to the image with an arithmetic, relational,
% or logical operator to an image. Use these operations to lighten or darken
% an image, to increase or decrease contrast in an image, or to produce the
% "negative" of an image.
%
% The format of the EvaluateImage method is:
%
% MagickBooleanType EvaluateImage(Image *image,
% const MagickEvaluateOperator op,const double value,
% ExceptionInfo *exception)
% MagickBooleanType EvaluateImages(Image *images,
% const MagickEvaluateOperator op,const double value,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o op: A channel op.
%
% o value: A value value.
%
% o exception: return any errors or warnings in this structure.
%
*/
typedef struct _PixelChannels
{
double
channel[MaxPixelChannels];
} PixelChannels;
static PixelChannels **DestroyPixelThreadSet(const Image *images,
PixelChannels **pixels)
{
ssize_t
i;
size_t
rows;
assert(pixels != (PixelChannels **) NULL);
rows=MagickMax(GetImageListLength(images),(size_t)
GetMagickResourceLimit(ThreadResource));
for (i=0; i < (ssize_t) rows; i++)
if (pixels[i] != (PixelChannels *) NULL)
pixels[i]=(PixelChannels *) RelinquishMagickMemory(pixels[i]);
pixels=(PixelChannels **) RelinquishMagickMemory(pixels);
return(pixels);
}
static PixelChannels **AcquirePixelThreadSet(const Image *images)
{
const Image
*next;
PixelChannels
**pixels;
ssize_t
i;
size_t
columns,
number_images,
rows;
number_images=GetImageListLength(images);
rows=MagickMax(number_images,(size_t) GetMagickResourceLimit(ThreadResource));
pixels=(PixelChannels **) AcquireQuantumMemory(rows,sizeof(*pixels));
if (pixels == (PixelChannels **) NULL)
return((PixelChannels **) NULL);
(void) memset(pixels,0,rows*sizeof(*pixels));
columns=MagickMax(number_images,MaxPixelChannels);
for (next=images; next != (Image *) NULL; next=next->next)
columns=MagickMax(next->columns,columns);
for (i=0; i < (ssize_t) rows; i++)
{
ssize_t
j;
pixels[i]=(PixelChannels *) AcquireQuantumMemory(columns,sizeof(**pixels));
if (pixels[i] == (PixelChannels *) NULL)
return(DestroyPixelThreadSet(images,pixels));
for (j=0; j < (ssize_t) columns; j++)
{
ssize_t
k;
for (k=0; k < MaxPixelChannels; k++)
pixels[i][j].channel[k]=0.0;
}
}
return(pixels);
}
static inline double EvaluateMax(const double x,const double y)
{
if (x > y)
return(x);
return(y);
}
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int IntensityCompare(const void *x,const void *y)
{
const PixelChannels
*color_1,
*color_2;
double
distance;
ssize_t
i;
color_1=(const PixelChannels *) x;
color_2=(const PixelChannels *) y;
distance=0.0;
for (i=0; i < MaxPixelChannels; i++)
distance+=color_1->channel[i]-(double) color_2->channel[i];
return(distance < 0.0 ? -1 : distance > 0.0 ? 1 : 0);
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static double ApplyEvaluateOperator(RandomInfo *random_info,const Quantum pixel,
const MagickEvaluateOperator op,const double value)
{
double
result;
ssize_t
i;
result=0.0;
switch (op)
{
case UndefinedEvaluateOperator:
break;
case AbsEvaluateOperator:
{
result=(double) fabs((double) (pixel+value));
break;
}
case AddEvaluateOperator:
{
result=(double) (pixel+value);
break;
}
case AddModulusEvaluateOperator:
{
/*
This returns a 'floored modulus' of the addition which is a positive
result. It differs from % or fmod() that returns a 'truncated modulus'
result, where floor() is replaced by trunc() and could return a
negative result (which is clipped).
*/
result=pixel+value;
result-=(QuantumRange+1.0)*floor((double) result/(QuantumRange+1.0));
break;
}
case AndEvaluateOperator:
{
result=(double) ((ssize_t) pixel & (ssize_t) (value+0.5));
break;
}
case CosineEvaluateOperator:
{
result=(double) (QuantumRange*(0.5*cos((double) (2.0*MagickPI*
QuantumScale*pixel*value))+0.5));
break;
}
case DivideEvaluateOperator:
{
result=pixel/(value == 0.0 ? 1.0 : value);
break;
}
case ExponentialEvaluateOperator:
{
result=(double) (QuantumRange*exp((double) (value*QuantumScale*pixel)));
break;
}
case GaussianNoiseEvaluateOperator:
{
result=(double) GenerateDifferentialNoise(random_info,pixel,GaussianNoise,
value);
break;
}
case ImpulseNoiseEvaluateOperator:
{
result=(double) GenerateDifferentialNoise(random_info,pixel,ImpulseNoise,
value);
break;
}
case InverseLogEvaluateOperator:
{
result=(QuantumRange*pow((value+1.0),QuantumScale*pixel)-1.0)*
PerceptibleReciprocal(value);
break;
}
case LaplacianNoiseEvaluateOperator:
{
result=(double) GenerateDifferentialNoise(random_info,pixel,
LaplacianNoise,value);
break;
}
case LeftShiftEvaluateOperator:
{
result=(double) pixel;
for (i=0; i < (ssize_t) value; i++)
result*=2.0;
break;
}
case LogEvaluateOperator:
{
if ((QuantumScale*pixel) >= MagickEpsilon)
result=(double) (QuantumRange*log((double) (QuantumScale*value*pixel+
1.0))/log((double) (value+1.0)));
break;
}
case MaxEvaluateOperator:
{
result=(double) EvaluateMax((double) pixel,value);
break;
}
case MeanEvaluateOperator:
{
result=(double) (pixel+value);
break;
}
case MedianEvaluateOperator:
{
result=(double) (pixel+value);
break;
}
case MinEvaluateOperator:
{
result=(double) MagickMin((double) pixel,value);
break;
}
case MultiplicativeNoiseEvaluateOperator:
{
result=(double) GenerateDifferentialNoise(random_info,pixel,
MultiplicativeGaussianNoise,value);
break;
}
case MultiplyEvaluateOperator:
{
result=(double) (value*pixel);
break;
}
case OrEvaluateOperator:
{
result=(double) ((ssize_t) pixel | (ssize_t) (value+0.5));
break;
}
case PoissonNoiseEvaluateOperator:
{
result=(double) GenerateDifferentialNoise(random_info,pixel,PoissonNoise,
value);
break;
}
case PowEvaluateOperator:
{
if (pixel < 0)
result=(double) -(QuantumRange*pow((double) -(QuantumScale*pixel),
(double) value));
else
result=(double) (QuantumRange*pow((double) (QuantumScale*pixel),
(double) value));
break;
}
case RightShiftEvaluateOperator:
{
result=(double) pixel;
for (i=0; i < (ssize_t) value; i++)
result/=2.0;
break;
}
case RootMeanSquareEvaluateOperator:
{
result=((double) pixel*pixel+value);
break;
}
case SetEvaluateOperator:
{
result=value;
break;
}
case SineEvaluateOperator:
{
result=(double) (QuantumRange*(0.5*sin((double) (2.0*MagickPI*
QuantumScale*pixel*value))+0.5));
break;
}
case SubtractEvaluateOperator:
{
result=(double) (pixel-value);
break;
}
case SumEvaluateOperator:
{
result=(double) (pixel+value);
break;
}
case ThresholdEvaluateOperator:
{
result=(double) (((double) pixel <= value) ? 0 : QuantumRange);
break;
}
case ThresholdBlackEvaluateOperator:
{
result=(double) (((double) pixel <= value) ? 0 : pixel);
break;
}
case ThresholdWhiteEvaluateOperator:
{
result=(double) (((double) pixel > value) ? QuantumRange : pixel);
break;
}
case UniformNoiseEvaluateOperator:
{
result=(double) GenerateDifferentialNoise(random_info,pixel,UniformNoise,
value);
break;
}
case XorEvaluateOperator:
{
result=(double) ((ssize_t) pixel ^ (ssize_t) (value+0.5));
break;
}
}
return(result);
}
static Image *AcquireImageCanvas(const Image *images,ExceptionInfo *exception)
{
const Image
*p,
*q;
size_t
columns,
rows;
q=images;
columns=images->columns;
rows=images->rows;
for (p=images; p != (Image *) NULL; p=p->next)
{
if (p->number_channels > q->number_channels)
q=p;
if (p->columns > columns)
columns=p->columns;
if (p->rows > rows)
rows=p->rows;
}
return(CloneImage(q,columns,rows,MagickTrue,exception));
}
MagickExport Image *EvaluateImages(const Image *images,
const MagickEvaluateOperator op,ExceptionInfo *exception)
{
#define EvaluateImageTag "Evaluate/Image"
CacheView
*evaluate_view,
**image_view;
const Image
*view;
Image
*image;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelChannels
**magick_restrict evaluate_pixels;
RandomInfo
**magick_restrict random_info;
size_t
number_images;
ssize_t
n,
y;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
unsigned long
key;
#endif
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=AcquireImageCanvas(images,exception);
if (image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
{
image=DestroyImage(image);
return((Image *) NULL);
}
number_images=GetImageListLength(images);
evaluate_pixels=AcquirePixelThreadSet(images);
if (evaluate_pixels == (PixelChannels **) NULL)
{
image=DestroyImage(image);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
return((Image *) NULL);
}
image_view=(CacheView **) AcquireQuantumMemory(number_images,
sizeof(*image_view));
if (image_view == (CacheView **) NULL)
{
image=DestroyImage(image);
evaluate_pixels=DestroyPixelThreadSet(images,evaluate_pixels);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
return(image);
}
view=images;
for (n=0; n < (ssize_t) number_images; n++)
{
image_view[n]=AcquireVirtualCacheView(view,exception);
view=GetNextImageInList(view);
}
/*
Evaluate image pixels.
*/
status=MagickTrue;
progress=0;
random_info=AcquireRandomInfoThreadSet();
evaluate_view=AcquireAuthenticCacheView(image,exception);
if (op == MedianEvaluateOperator)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,images,image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
const Quantum
**p;
PixelChannels
*evaluate_pixel;
Quantum
*magick_restrict q;
ssize_t
x;
ssize_t
j;
if (status == MagickFalse)
continue;
p=(const Quantum **) AcquireQuantumMemory(number_images,sizeof(*p));
if (p == (const Quantum **) NULL)
{
status=MagickFalse;
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
images->filename);
continue;
}
for (j=0; j < (ssize_t) number_images; j++)
{
p[j]=GetCacheViewVirtualPixels(image_view[j],0,y,image->columns,1,
exception);
if (p[j] == (const Quantum *) NULL)
break;
}
q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1,
exception);
if ((j < (ssize_t) number_images) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
evaluate_pixel=evaluate_pixels[id];
for (x=0; x < (ssize_t) image->columns; x++)
{
const Image
*next;
ssize_t
i;
next=images;
for (j=0; j < (ssize_t) number_images; j++)
{
for (i=0; i < MaxPixelChannels; i++)
evaluate_pixel[j].channel[i]=0.0;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(next,channel);
PixelTrait evaluate_traits = GetPixelChannelTraits(image,channel);
if ((traits == UndefinedPixelTrait) ||
(evaluate_traits == UndefinedPixelTrait) ||
((traits & UpdatePixelTrait) == 0))
continue;
evaluate_pixel[j].channel[i]=ApplyEvaluateOperator(
random_info[id],GetPixelChannel(next,channel,p[j]),op,
evaluate_pixel[j].channel[i]);
}
p[j]+=GetPixelChannels(next);
next=GetNextImageInList(next);
}
qsort((void *) evaluate_pixel,number_images,sizeof(*evaluate_pixel),
IntensityCompare);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits == UndefinedPixelTrait) ||
((traits & UpdatePixelTrait) == 0))
continue;
q[i]=ClampToQuantum(evaluate_pixel[number_images/2].channel[i]);
}
q+=GetPixelChannels(image);
}
p=(const Quantum **) RelinquishMagickMemory((void *) p);
if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse)
status=MagickFalse;
if (images->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(images,EvaluateImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
}
else
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,images,image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const Image
*next;
const int
id = GetOpenMPThreadId();
const Quantum
**p;
PixelChannels
*evaluate_pixel;
Quantum
*magick_restrict q;
ssize_t
i,
x;
ssize_t
j;
if (status == MagickFalse)
continue;
p=(const Quantum **) AcquireQuantumMemory(number_images,sizeof(*p));
if (p == (const Quantum **) NULL)
{
status=MagickFalse;
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
images->filename);
continue;
}
for (j=0; j < (ssize_t) number_images; j++)
{
p[j]=GetCacheViewVirtualPixels(image_view[j],0,y,image->columns,1,
exception);
if (p[j] == (const Quantum *) NULL)
break;
}
q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1,
exception);
if ((j < (ssize_t) number_images) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
evaluate_pixel=evaluate_pixels[id];
for (j=0; j < (ssize_t) image->columns; j++)
for (i=0; i < MaxPixelChannels; i++)
evaluate_pixel[j].channel[i]=0.0;
next=images;
for (j=0; j < (ssize_t) number_images; j++)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i < (ssize_t) GetPixelChannels(next); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(next,channel);
PixelTrait evaluate_traits = GetPixelChannelTraits(image,channel);
if ((traits == UndefinedPixelTrait) ||
(evaluate_traits == UndefinedPixelTrait))
continue;
if ((traits & UpdatePixelTrait) == 0)
continue;
evaluate_pixel[x].channel[i]=ApplyEvaluateOperator(
random_info[id],GetPixelChannel(next,channel,p[j]),j == 0 ?
AddEvaluateOperator : op,evaluate_pixel[x].channel[i]);
}
p[j]+=GetPixelChannels(next);
}
next=GetNextImageInList(next);
}
for (x=0; x < (ssize_t) image->columns; x++)
{
switch (op)
{
case MeanEvaluateOperator:
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
evaluate_pixel[x].channel[i]/=(double) number_images;
break;
}
case MultiplyEvaluateOperator:
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
for (j=0; j < (ssize_t) (number_images-1); j++)
evaluate_pixel[x].channel[i]*=QuantumScale;
}
break;
}
case RootMeanSquareEvaluateOperator:
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
evaluate_pixel[x].channel[i]=sqrt(evaluate_pixel[x].channel[i]/
number_images);
break;
}
default:
break;
}
}
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits == UndefinedPixelTrait) ||
((traits & UpdatePixelTrait) == 0))
continue;
q[i]=ClampToQuantum(evaluate_pixel[x].channel[i]);
}
q+=GetPixelChannels(image);
}
p=(const Quantum **) RelinquishMagickMemory((void *) p);
if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse)
status=MagickFalse;
if (images->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(images,EvaluateImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
}
for (n=0; n < (ssize_t) number_images; n++)
image_view[n]=DestroyCacheView(image_view[n]);
image_view=(CacheView **) RelinquishMagickMemory(image_view);
evaluate_view=DestroyCacheView(evaluate_view);
evaluate_pixels=DestroyPixelThreadSet(images,evaluate_pixels);
random_info=DestroyRandomInfoThreadSet(random_info);
if (status == MagickFalse)
image=DestroyImage(image);
return(image);
}
MagickExport MagickBooleanType EvaluateImage(Image *image,
const MagickEvaluateOperator op,const double value,ExceptionInfo *exception)
{
CacheView
*image_view;
const char
*artifact;
MagickBooleanType
clamp,
status;
MagickOffsetType
progress;
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);
status=MagickTrue;
progress=0;
clamp=MagickFalse;
artifact=GetImageArtifact(image,"evaluate:clamp");
if (artifact != (const char *) NULL)
clamp=IsStringTrue(artifact);
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();
Quantum
*magick_restrict q;
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++)
{
double
result;
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;
if ((traits & CopyPixelTrait) != 0)
continue;
if ((traits & UpdatePixelTrait) == 0)
continue;
result=ApplyEvaluateOperator(random_info[id],q[i],op,value);
if (op == MeanEvaluateOperator)
result/=2.0;
q[i]=clamp != MagickFalse ? ClampPixel(result) : ClampToQuantum(result);
}
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,EvaluateImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
random_info=DestroyRandomInfoThreadSet(random_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F u n c t i o n I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FunctionImage() applies a value to the image with an arithmetic, relational,
% or logical operator to an image. Use these operations to lighten or darken
% an image, to increase or decrease contrast in an image, or to produce the
% "negative" of an image.
%
% The format of the FunctionImage method is:
%
% MagickBooleanType FunctionImage(Image *image,
% const MagickFunction function,const ssize_t number_parameters,
% const double *parameters,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o function: A channel function.
%
% o parameters: one or more parameters.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Quantum ApplyFunction(Quantum pixel,const MagickFunction function,
const size_t number_parameters,const double *parameters,
ExceptionInfo *exception)
{
double
result;
ssize_t
i;
(void) exception;
result=0.0;
switch (function)
{
case PolynomialFunction:
{
/*
Polynomial: polynomial constants, highest to lowest order (e.g. c0*x^3+
c1*x^2+c2*x+c3).
*/
result=0.0;
for (i=0; i < (ssize_t) number_parameters; i++)
result=result*QuantumScale*pixel+parameters[i];
result*=QuantumRange;
break;
}
case SinusoidFunction:
{
double
amplitude,
bias,
frequency,
phase;
/*
Sinusoid: frequency, phase, amplitude, bias.
*/
frequency=(number_parameters >= 1) ? parameters[0] : 1.0;
phase=(number_parameters >= 2) ? parameters[1] : 0.0;
amplitude=(number_parameters >= 3) ? parameters[2] : 0.5;
bias=(number_parameters >= 4) ? parameters[3] : 0.5;
result=(double) (QuantumRange*(amplitude*sin((double) (2.0*
MagickPI*(frequency*QuantumScale*pixel+phase/360.0)))+bias));
break;
}
case ArcsinFunction:
{
double
bias,
center,
range,
width;
/*
Arcsin (peged at range limits for invalid results): width, center,
range, and bias.
*/
width=(number_parameters >= 1) ? parameters[0] : 1.0;
center=(number_parameters >= 2) ? parameters[1] : 0.5;
range=(number_parameters >= 3) ? parameters[2] : 1.0;
bias=(number_parameters >= 4) ? parameters[3] : 0.5;
result=2.0*PerceptibleReciprocal(width)*(QuantumScale*pixel-center);
if (result <= -1.0)
result=bias-range/2.0;
else
if (result >= 1.0)
result=bias+range/2.0;
else
result=(double) (range/MagickPI*asin((double) result)+bias);
result*=QuantumRange;
break;
}
case ArctanFunction:
{
double
center,
bias,
range,
slope;
/*
Arctan: slope, center, range, and bias.
*/
slope=(number_parameters >= 1) ? parameters[0] : 1.0;
center=(number_parameters >= 2) ? parameters[1] : 0.5;
range=(number_parameters >= 3) ? parameters[2] : 1.0;
bias=(number_parameters >= 4) ? parameters[3] : 0.5;
result=(double) (MagickPI*slope*(QuantumScale*pixel-center));
result=(double) (QuantumRange*(range/MagickPI*atan((double)
result)+bias));
break;
}
case UndefinedFunction:
break;
}
return(ClampToQuantum(result));
}
MagickExport MagickBooleanType FunctionImage(Image *image,
const MagickFunction function,const size_t number_parameters,
const double *parameters,ExceptionInfo *exception)
{
#define FunctionImageTag "Function/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);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
#if defined(MAGICKCORE_OPENCL_SUPPORT)
if (AccelerateFunctionImage(image,function,number_parameters,parameters,
exception) != MagickFalse)
return(MagickTrue);
#endif
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++)
{
Quantum
*magick_restrict q;
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++)
{
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;
if ((traits & UpdatePixelTrait) == 0)
continue;
q[i]=ApplyFunction(q[i],function,number_parameters,parameters,
exception);
}
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,FunctionImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e E n t r o p y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageEntropy() returns the entropy of one or more image channels.
%
% The format of the GetImageEntropy method is:
%
% MagickBooleanType GetImageEntropy(const Image *image,double *entropy,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o entropy: the average entropy of the selected channels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetImageEntropy(const Image *image,
double *entropy,ExceptionInfo *exception)
{
ChannelStatistics
*channel_statistics;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
channel_statistics=GetImageStatistics(image,exception);
if (channel_statistics == (ChannelStatistics *) NULL)
return(MagickFalse);
*entropy=channel_statistics[CompositePixelChannel].entropy;
channel_statistics=(ChannelStatistics *) RelinquishMagickMemory(
channel_statistics);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e E x t r e m a %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageExtrema() returns the extrema of one or more image channels.
%
% The format of the GetImageExtrema method is:
%
% MagickBooleanType GetImageExtrema(const Image *image,size_t *minima,
% size_t *maxima,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o minima: the minimum value in the channel.
%
% o maxima: the maximum value in the channel.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetImageExtrema(const Image *image,
size_t *minima,size_t *maxima,ExceptionInfo *exception)
{
double
max,
min;
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=GetImageRange(image,&min,&max,exception);
*minima=(size_t) ceil(min-0.5);
*maxima=(size_t) floor(max+0.5);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e K u r t o s i s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageKurtosis() returns the kurtosis and skewness of one or more image
% channels.
%
% The format of the GetImageKurtosis method is:
%
% MagickBooleanType GetImageKurtosis(const Image *image,double *kurtosis,
% double *skewness,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o kurtosis: the kurtosis of the channel.
%
% o skewness: the skewness of the channel.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetImageKurtosis(const Image *image,
double *kurtosis,double *skewness,ExceptionInfo *exception)
{
ChannelStatistics
*channel_statistics;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
channel_statistics=GetImageStatistics(image,exception);
if (channel_statistics == (ChannelStatistics *) NULL)
return(MagickFalse);
*kurtosis=channel_statistics[CompositePixelChannel].kurtosis;
*skewness=channel_statistics[CompositePixelChannel].skewness;
channel_statistics=(ChannelStatistics *) RelinquishMagickMemory(
channel_statistics);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e M e a n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageMean() returns the mean and standard deviation of one or more image
% channels.
%
% The format of the GetImageMean method is:
%
% MagickBooleanType GetImageMean(const Image *image,double *mean,
% double *standard_deviation,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o mean: the average value in the channel.
%
% o standard_deviation: the standard deviation of the channel.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetImageMean(const Image *image,double *mean,
double *standard_deviation,ExceptionInfo *exception)
{
ChannelStatistics
*channel_statistics;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
channel_statistics=GetImageStatistics(image,exception);
if (channel_statistics == (ChannelStatistics *) NULL)
return(MagickFalse);
*mean=channel_statistics[CompositePixelChannel].mean;
*standard_deviation=
channel_statistics[CompositePixelChannel].standard_deviation;
channel_statistics=(ChannelStatistics *) RelinquishMagickMemory(
channel_statistics);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e M e d i a n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageMedian() returns the median pixel of one or more image channels.
%
% The format of the GetImageMedian method is:
%
% MagickBooleanType GetImageMedian(const Image *image,double *median,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o median: the average value in the channel.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetImageMedian(const Image *image,double *median,
ExceptionInfo *exception)
{
ChannelStatistics
*channel_statistics;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
channel_statistics=GetImageStatistics(image,exception);
if (channel_statistics == (ChannelStatistics *) NULL)
return(MagickFalse);
*median=channel_statistics[CompositePixelChannel].median;
channel_statistics=(ChannelStatistics *) RelinquishMagickMemory(
channel_statistics);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e M o m e n t s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageMoments() returns the normalized moments of one or more image
% channels.
%
% The format of the GetImageMoments method is:
%
% ChannelMoments *GetImageMoments(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 ChannelMoments *GetImageMoments(const Image *image,
ExceptionInfo *exception)
{
#define MaxNumberImageMoments 8
CacheView
*image_view;
ChannelMoments
*channel_moments;
double
channels,
M00[MaxPixelChannels+1],
M01[MaxPixelChannels+1],
M02[MaxPixelChannels+1],
M03[MaxPixelChannels+1],
M10[MaxPixelChannels+1],
M11[MaxPixelChannels+1],
M12[MaxPixelChannels+1],
M20[MaxPixelChannels+1],
M21[MaxPixelChannels+1],
M22[MaxPixelChannels+1],
M30[MaxPixelChannels+1];
PointInfo
centroid[MaxPixelChannels+1];
ssize_t
c,
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
channel_moments=(ChannelMoments *) AcquireQuantumMemory(MaxPixelChannels+1,
sizeof(*channel_moments));
if (channel_moments == (ChannelMoments *) NULL)
return(channel_moments);
(void) memset(channel_moments,0,(MaxPixelChannels+1)*
sizeof(*channel_moments));
(void) memset(centroid,0,sizeof(centroid));
(void) memset(M00,0,sizeof(M00));
(void) memset(M01,0,sizeof(M01));
(void) memset(M02,0,sizeof(M02));
(void) memset(M03,0,sizeof(M03));
(void) memset(M10,0,sizeof(M10));
(void) memset(M11,0,sizeof(M11));
(void) memset(M12,0,sizeof(M12));
(void) memset(M20,0,sizeof(M20));
(void) memset(M21,0,sizeof(M21));
(void) memset(M22,0,sizeof(M22));
(void) memset(M30,0,sizeof(M30));
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
const Quantum
*magick_restrict p;
ssize_t
x;
/*
Compute center of mass (centroid).
*/
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++)
{
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;
if ((traits & UpdatePixelTrait) == 0)
continue;
M00[channel]+=QuantumScale*p[i];
M00[MaxPixelChannels]+=QuantumScale*p[i];
M10[channel]+=x*QuantumScale*p[i];
M10[MaxPixelChannels]+=x*QuantumScale*p[i];
M01[channel]+=y*QuantumScale*p[i];
M01[MaxPixelChannels]+=y*QuantumScale*p[i];
}
p+=GetPixelChannels(image);
}
}
for (c=0; c <= MaxPixelChannels; c++)
{
/*
Compute center of mass (centroid).
*/
centroid[c].x=M10[c]*PerceptibleReciprocal(M00[c]);
centroid[c].y=M01[c]*PerceptibleReciprocal(M00[c]);
}
for (y=0; y < (ssize_t) image->rows; y++)
{
const Quantum
*magick_restrict p;
ssize_t
x;
/*
Compute the image moments.
*/
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++)
{
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;
if ((traits & UpdatePixelTrait) == 0)
continue;
M11[channel]+=(x-centroid[channel].x)*(y-centroid[channel].y)*
QuantumScale*p[i];
M11[MaxPixelChannels]+=(x-centroid[channel].x)*(y-centroid[channel].y)*
QuantumScale*p[i];
M20[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)*
QuantumScale*p[i];
M20[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)*
QuantumScale*p[i];
M02[channel]+=(y-centroid[channel].y)*(y-centroid[channel].y)*
QuantumScale*p[i];
M02[MaxPixelChannels]+=(y-centroid[channel].y)*(y-centroid[channel].y)*
QuantumScale*p[i];
M21[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)*
(y-centroid[channel].y)*QuantumScale*p[i];
M21[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)*
(y-centroid[channel].y)*QuantumScale*p[i];
M12[channel]+=(x-centroid[channel].x)*(y-centroid[channel].y)*
(y-centroid[channel].y)*QuantumScale*p[i];
M12[MaxPixelChannels]+=(x-centroid[channel].x)*(y-centroid[channel].y)*
(y-centroid[channel].y)*QuantumScale*p[i];
M22[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)*
(y-centroid[channel].y)*(y-centroid[channel].y)*QuantumScale*p[i];
M22[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)*
(y-centroid[channel].y)*(y-centroid[channel].y)*QuantumScale*p[i];
M30[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)*
(x-centroid[channel].x)*QuantumScale*p[i];
M30[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)*
(x-centroid[channel].x)*QuantumScale*p[i];
M03[channel]+=(y-centroid[channel].y)*(y-centroid[channel].y)*
(y-centroid[channel].y)*QuantumScale*p[i];
M03[MaxPixelChannels]+=(y-centroid[channel].y)*(y-centroid[channel].y)*
(y-centroid[channel].y)*QuantumScale*p[i];
}
p+=GetPixelChannels(image);
}
}
channels=(double) GetImageChannels(image);
M00[MaxPixelChannels]/=channels;
M01[MaxPixelChannels]/=channels;
M02[MaxPixelChannels]/=channels;
M03[MaxPixelChannels]/=channels;
M10[MaxPixelChannels]/=channels;
M11[MaxPixelChannels]/=channels;
M12[MaxPixelChannels]/=channels;
M20[MaxPixelChannels]/=channels;
M21[MaxPixelChannels]/=channels;
M22[MaxPixelChannels]/=channels;
M30[MaxPixelChannels]/=channels;
for (c=0; c <= MaxPixelChannels; c++)
{
/*
Compute elliptical angle, major and minor axes, eccentricity, & intensity.
*/
channel_moments[c].centroid=centroid[c];
channel_moments[c].ellipse_axis.x=sqrt((2.0*PerceptibleReciprocal(M00[c]))*
((M20[c]+M02[c])+sqrt(4.0*M11[c]*M11[c]+(M20[c]-M02[c])*(M20[c]-M02[c]))));
channel_moments[c].ellipse_axis.y=sqrt((2.0*PerceptibleReciprocal(M00[c]))*
((M20[c]+M02[c])-sqrt(4.0*M11[c]*M11[c]+(M20[c]-M02[c])*(M20[c]-M02[c]))));
channel_moments[c].ellipse_angle=RadiansToDegrees(1.0/2.0*atan(2.0*
M11[c]*PerceptibleReciprocal(M20[c]-M02[c])));
if (fabs(M11[c]) < 0.0)
{
if ((fabs(M20[c]-M02[c]) >= 0.0) &&
((M20[c]-M02[c]) < 0.0))
channel_moments[c].ellipse_angle+=90.0;
}
else
if (M11[c] < 0.0)
{
if (fabs(M20[c]-M02[c]) >= 0.0)
{
if ((M20[c]-M02[c]) < 0.0)
channel_moments[c].ellipse_angle+=90.0;
else
channel_moments[c].ellipse_angle+=180.0;
}
}
else
if ((fabs(M20[c]-M02[c]) >= 0.0) && ((M20[c]-M02[c]) < 0.0))
channel_moments[c].ellipse_angle+=90.0;
channel_moments[c].ellipse_eccentricity=sqrt(1.0-(
channel_moments[c].ellipse_axis.y*
channel_moments[c].ellipse_axis.y*PerceptibleReciprocal(
channel_moments[c].ellipse_axis.x*
channel_moments[c].ellipse_axis.x)));
channel_moments[c].ellipse_intensity=M00[c]*
PerceptibleReciprocal(MagickPI*channel_moments[c].ellipse_axis.x*
channel_moments[c].ellipse_axis.y+MagickEpsilon);
}
for (c=0; c <= MaxPixelChannels; c++)
{
/*
Normalize image moments.
*/
M10[c]=0.0;
M01[c]=0.0;
M11[c]*=PerceptibleReciprocal(pow(M00[c],1.0+(1.0+1.0)/2.0));
M20[c]*=PerceptibleReciprocal(pow(M00[c],1.0+(2.0+0.0)/2.0));
M02[c]*=PerceptibleReciprocal(pow(M00[c],1.0+(0.0+2.0)/2.0));
M21[c]*=PerceptibleReciprocal(pow(M00[c],1.0+(2.0+1.0)/2.0));
M12[c]*=PerceptibleReciprocal(pow(M00[c],1.0+(1.0+2.0)/2.0));
M22[c]*=PerceptibleReciprocal(pow(M00[c],1.0+(2.0+2.0)/2.0));
M30[c]*=PerceptibleReciprocal(pow(M00[c],1.0+(3.0+0.0)/2.0));
M03[c]*=PerceptibleReciprocal(pow(M00[c],1.0+(0.0+3.0)/2.0));
M00[c]=1.0;
}
image_view=DestroyCacheView(image_view);
for (c=0; c <= MaxPixelChannels; c++)
{
/*
Compute Hu invariant moments.
*/
channel_moments[c].invariant[0]=M20[c]+M02[c];
channel_moments[c].invariant[1]=(M20[c]-M02[c])*(M20[c]-M02[c])+4.0*M11[c]*
M11[c];
channel_moments[c].invariant[2]=(M30[c]-3.0*M12[c])*(M30[c]-3.0*M12[c])+
(3.0*M21[c]-M03[c])*(3.0*M21[c]-M03[c]);
channel_moments[c].invariant[3]=(M30[c]+M12[c])*(M30[c]+M12[c])+
(M21[c]+M03[c])*(M21[c]+M03[c]);
channel_moments[c].invariant[4]=(M30[c]-3.0*M12[c])*(M30[c]+M12[c])*
((M30[c]+M12[c])*(M30[c]+M12[c])-3.0*(M21[c]+M03[c])*(M21[c]+M03[c]))+
(3.0*M21[c]-M03[c])*(M21[c]+M03[c])*(3.0*(M30[c]+M12[c])*(M30[c]+M12[c])-
(M21[c]+M03[c])*(M21[c]+M03[c]));
channel_moments[c].invariant[5]=(M20[c]-M02[c])*((M30[c]+M12[c])*
(M30[c]+M12[c])-(M21[c]+M03[c])*(M21[c]+M03[c]))+4.0*M11[c]*
(M30[c]+M12[c])*(M21[c]+M03[c]);
channel_moments[c].invariant[6]=(3.0*M21[c]-M03[c])*(M30[c]+M12[c])*
((M30[c]+M12[c])*(M30[c]+M12[c])-3.0*(M21[c]+M03[c])*(M21[c]+M03[c]))-
(M30[c]-3*M12[c])*(M21[c]+M03[c])*(3.0*(M30[c]+M12[c])*(M30[c]+M12[c])-
(M21[c]+M03[c])*(M21[c]+M03[c]));
channel_moments[c].invariant[7]=M11[c]*((M30[c]+M12[c])*(M30[c]+M12[c])-
(M03[c]+M21[c])*(M03[c]+M21[c]))-(M20[c]-M02[c])*(M30[c]+M12[c])*
(M03[c]+M21[c]);
}
if (y < (ssize_t) image->rows)
channel_moments=(ChannelMoments *) RelinquishMagickMemory(channel_moments);
return(channel_moments);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e C h a n n e l P e r c e p t u a l H a s h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImagePerceptualHash() returns the perceptual hash of one or more
% image channels.
%
% The format of the GetImagePerceptualHash method is:
%
% ChannelPerceptualHash *GetImagePerceptualHash(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.
%
*/
static inline double MagickLog10(const double x)
{
#define Log10Epsilon (1.0e-11)
if (fabs(x) < Log10Epsilon)
return(log10(Log10Epsilon));
return(log10(fabs(x)));
}
MagickExport ChannelPerceptualHash *GetImagePerceptualHash(const Image *image,
ExceptionInfo *exception)
{
ChannelPerceptualHash
*perceptual_hash;
char
*colorspaces,
*p,
*q;
const char
*artifact;
MagickBooleanType
status;
ssize_t
i;
perceptual_hash=(ChannelPerceptualHash *) AcquireQuantumMemory(
MaxPixelChannels+1UL,sizeof(*perceptual_hash));
if (perceptual_hash == (ChannelPerceptualHash *) NULL)
return((ChannelPerceptualHash *) NULL);
artifact=GetImageArtifact(image,"phash:colorspaces");
if (artifact != NULL)
colorspaces=AcquireString(artifact);
else
colorspaces=AcquireString("sRGB,HCLp");
perceptual_hash[0].number_colorspaces=0;
perceptual_hash[0].number_channels=0;
q=colorspaces;
for (i=0; (p=StringToken(",",&q)) != (char *) NULL; i++)
{
ChannelMoments
*moments;
Image
*hash_image;
size_t
j;
ssize_t
channel,
colorspace;
if (i >= MaximumNumberOfPerceptualColorspaces)
break;
colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse,p);
if (colorspace < 0)
break;
perceptual_hash[0].colorspace[i]=(ColorspaceType) colorspace;
hash_image=BlurImage(image,0.0,1.0,exception);
if (hash_image == (Image *) NULL)
break;
hash_image->depth=8;
status=TransformImageColorspace(hash_image,(ColorspaceType) colorspace,
exception);
if (status == MagickFalse)
break;
moments=GetImageMoments(hash_image,exception);
perceptual_hash[0].number_colorspaces++;
perceptual_hash[0].number_channels+=GetImageChannels(hash_image);
hash_image=DestroyImage(hash_image);
if (moments == (ChannelMoments *) NULL)
break;
for (channel=0; channel <= MaxPixelChannels; channel++)
for (j=0; j < MaximumNumberOfImageMoments; j++)
perceptual_hash[channel].phash[i][j]=
(-MagickLog10(moments[channel].invariant[j]));
moments=(ChannelMoments *) RelinquishMagickMemory(moments);
}
colorspaces=DestroyString(colorspaces);
return(perceptual_hash);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e R a n g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageRange() returns the range of one or more image channels.
%
% The format of the GetImageRange method is:
%
% MagickBooleanType GetImageRange(const Image *image,double *minima,
% double *maxima,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o minima: the minimum value in the channel.
%
% o maxima: the maximum value in the channel.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetImageRange(const Image *image,double *minima,
double *maxima,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
initialize,
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;
initialize=MagickTrue;
*maxima=0.0;
*minima=0.0;
image_view=AcquireVirtualCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status,initialize) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
double
row_maxima = 0.0,
row_minima = 0.0;
MagickBooleanType
row_initialize;
const Quantum
*magick_restrict p;
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;
}
row_initialize=MagickTrue;
for (x=0; x < (ssize_t) image->columns; x++)
{
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;
if ((traits & UpdatePixelTrait) == 0)
continue;
if (row_initialize != MagickFalse)
{
row_minima=(double) p[i];
row_maxima=(double) p[i];
row_initialize=MagickFalse;
}
else
{
if ((double) p[i] < row_minima)
row_minima=(double) p[i];
if ((double) p[i] > row_maxima)
row_maxima=(double) p[i];
}
}
p+=GetPixelChannels(image);
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_GetImageRange)
#endif
{
if (initialize != MagickFalse)
{
*minima=row_minima;
*maxima=row_maxima;
initialize=MagickFalse;
}
else
{
if (row_minima < *minima)
*minima=row_minima;
if (row_maxima > *maxima)
*maxima=row_maxima;
}
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e S t a t i s t i c s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageStatistics() returns statistics for each channel in the image. The
% statistics include the channel depth, its minima, maxima, mean, standard
% deviation, kurtosis and skewness. You can access the red channel mean, for
% example, like this:
%
% channel_statistics=GetImageStatistics(image,exception);
% red_mean=channel_statistics[RedPixelChannel].mean;
%
% Use MagickRelinquishMemory() to free the statistics buffer.
%
% The format of the GetImageStatistics method is:
%
% ChannelStatistics *GetImageStatistics(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.
%
*/
static ssize_t GetMedianPixel(Quantum *pixels,const size_t n)
{
#define SwapPixels(alpha,beta) \
{ \
Quantum gamma=(alpha); \
(alpha)=(beta);(beta)=gamma; \
}
ssize_t
low = 0,
high = (ssize_t) n-1,
median = (low+high)/2;
for ( ; ; )
{
ssize_t
l = low+1,
h = high,
mid = (low+high)/2;
if (high <= low)
return(median);
if (high == (low+1))
{
if (pixels[low] > pixels[high])
SwapPixels(pixels[low],pixels[high]);
return(median);
}
if (pixels[mid] > pixels[high])
SwapPixels(pixels[mid],pixels[high]);
if (pixels[low] > pixels[high])
SwapPixels(pixels[low], pixels[high]);
if (pixels[mid] > pixels[low])
SwapPixels(pixels[mid],pixels[low]);
SwapPixels(pixels[mid],pixels[low+1]);
for ( ; ; )
{
do l++; while (pixels[low] > pixels[l]);
do h--; while (pixels[h] > pixels[low]);
if (h < l)
break;
SwapPixels(pixels[l],pixels[h]);
}
SwapPixels(pixels[low],pixels[h]);
if (h <= median)
low=l;
if (h >= median)
high=h-1;
}
}
MagickExport ChannelStatistics *GetImageStatistics(const Image *image,
ExceptionInfo *exception)
{
ChannelStatistics
*channel_statistics;
double
area,
channels,
*histogram,
standard_deviation;
MagickStatusType
status;
MemoryInfo
*median_info;
Quantum
*median;
QuantumAny
range;
size_t
depth;
ssize_t
i,
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)*
sizeof(*histogram));
channel_statistics=(ChannelStatistics *) AcquireQuantumMemory(
MaxPixelChannels+1,sizeof(*channel_statistics));
if ((channel_statistics == (ChannelStatistics *) NULL) ||
(histogram == (double *) NULL))
{
if (histogram != (double *) NULL)
histogram=(double *) RelinquishMagickMemory(histogram);
if (channel_statistics != (ChannelStatistics *) NULL)
channel_statistics=(ChannelStatistics *) RelinquishMagickMemory(
channel_statistics);
return(channel_statistics);
}
(void) memset(channel_statistics,0,(MaxPixelChannels+1)*
sizeof(*channel_statistics));
for (i=0; i <= (ssize_t) MaxPixelChannels; i++)
{
channel_statistics[i].depth=1;
channel_statistics[i].maxima=(-MagickMaximumValue);
channel_statistics[i].minima=MagickMaximumValue;
}
(void) memset(histogram,0,(MaxMap+1)*GetPixelChannels(image)*
sizeof(*histogram));
for (y=0; y < (ssize_t) image->rows; y++)
{
const Quantum
*magick_restrict p;
ssize_t
x;
/*
Compute pixel statistics.
*/
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelReadMask(image,p) <= (QuantumRange/2))
{
p+=GetPixelChannels(image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
if ((traits & UpdatePixelTrait) == 0)
continue;
if (channel_statistics[channel].depth != MAGICKCORE_QUANTUM_DEPTH)
{
depth=channel_statistics[channel].depth;
range=GetQuantumRange(depth);
status=p[i] != ScaleAnyToQuantum(ScaleQuantumToAny(p[i],range),
range) ? MagickTrue : MagickFalse;
if (status != MagickFalse)
{
channel_statistics[channel].depth++;
if (channel_statistics[channel].depth >
channel_statistics[CompositePixelChannel].depth)
channel_statistics[CompositePixelChannel].depth=
channel_statistics[channel].depth;
i--;
continue;
}
}
if ((double) p[i] < channel_statistics[channel].minima)
channel_statistics[channel].minima=(double) p[i];
if ((double) p[i] > channel_statistics[channel].maxima)
channel_statistics[channel].maxima=(double) p[i];
channel_statistics[channel].sum+=p[i];
channel_statistics[channel].sum_squared+=(double) p[i]*p[i];
channel_statistics[channel].sum_cubed+=(double) p[i]*p[i]*p[i];
channel_statistics[channel].sum_fourth_power+=(double) p[i]*p[i]*p[i]*
p[i];
channel_statistics[channel].area++;
if ((double) p[i] < channel_statistics[CompositePixelChannel].minima)
channel_statistics[CompositePixelChannel].minima=(double) p[i];
if ((double) p[i] > channel_statistics[CompositePixelChannel].maxima)
channel_statistics[CompositePixelChannel].maxima=(double) p[i];
histogram[GetPixelChannels(image)*ScaleQuantumToMap(
ClampToQuantum((double) p[i]))+i]++;
channel_statistics[CompositePixelChannel].sum+=(double) p[i];
channel_statistics[CompositePixelChannel].sum_squared+=(double)
p[i]*p[i];
channel_statistics[CompositePixelChannel].sum_cubed+=(double)
p[i]*p[i]*p[i];
channel_statistics[CompositePixelChannel].sum_fourth_power+=(double)
p[i]*p[i]*p[i]*p[i];
channel_statistics[CompositePixelChannel].area++;
}
p+=GetPixelChannels(image);
}
}
for (i=0; i <= (ssize_t) MaxPixelChannels; i++)
{
/*
Normalize pixel statistics.
*/
area=PerceptibleReciprocal(channel_statistics[i].area);
channel_statistics[i].sum*=area;
channel_statistics[i].sum_squared*=area;
channel_statistics[i].sum_cubed*=area;
channel_statistics[i].sum_fourth_power*=area;
channel_statistics[i].mean=channel_statistics[i].sum;
channel_statistics[i].variance=channel_statistics[i].sum_squared;
standard_deviation=sqrt(channel_statistics[i].variance-
(channel_statistics[i].mean*channel_statistics[i].mean));
standard_deviation=sqrt(PerceptibleReciprocal(channel_statistics[i].area-
1.0)*channel_statistics[i].area*standard_deviation*standard_deviation);
channel_statistics[i].standard_deviation=standard_deviation;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
number_bins;
ssize_t
j;
/*
Compute pixel entropy.
*/
PixelChannel channel = GetPixelChannelChannel(image,i);
number_bins=0.0;
for (j=0; j <= (ssize_t) MaxMap; j++)
if (histogram[GetPixelChannels(image)*j+i] > 0.0)
number_bins++;
area=PerceptibleReciprocal(channel_statistics[channel].area);
for (j=0; j <= (ssize_t) MaxMap; j++)
{
double
count;
count=area*histogram[GetPixelChannels(image)*j+i];
channel_statistics[channel].entropy+=-count*MagickLog10(count)*
PerceptibleReciprocal(MagickLog10(number_bins));
channel_statistics[CompositePixelChannel].entropy+=-count*
MagickLog10(count)*PerceptibleReciprocal(MagickLog10(number_bins))/
GetPixelChannels(image);
}
}
histogram=(double *) RelinquishMagickMemory(histogram);
for (i=0; i <= (ssize_t) MaxPixelChannels; i++)
{
/*
Compute kurtosis & skewness statistics.
*/
standard_deviation=PerceptibleReciprocal(
channel_statistics[i].standard_deviation);
channel_statistics[i].skewness=(channel_statistics[i].sum_cubed-3.0*
channel_statistics[i].mean*channel_statistics[i].sum_squared+2.0*
channel_statistics[i].mean*channel_statistics[i].mean*
channel_statistics[i].mean)*(standard_deviation*standard_deviation*
standard_deviation);
channel_statistics[i].kurtosis=(channel_statistics[i].sum_fourth_power-4.0*
channel_statistics[i].mean*channel_statistics[i].sum_cubed+6.0*
channel_statistics[i].mean*channel_statistics[i].mean*
channel_statistics[i].sum_squared-3.0*channel_statistics[i].mean*
channel_statistics[i].mean*1.0*channel_statistics[i].mean*
channel_statistics[i].mean)*(standard_deviation*standard_deviation*
standard_deviation*standard_deviation)-3.0;
}
median_info=AcquireVirtualMemory(image->columns,image->rows*sizeof(*median));
if (median_info == (MemoryInfo *) NULL)
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
else
{
median=(Quantum *) GetVirtualMemoryBlob(median_info);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
size_t
n = 0;
/*
Compute median statistics for each channel.
*/
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
if ((traits & UpdatePixelTrait) == 0)
continue;
for (y=0; y < (ssize_t) image->rows; y++)
{
const Quantum
*magick_restrict p;
ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelReadMask(image,p) <= (QuantumRange/2))
{
p+=GetPixelChannels(image);
continue;
}
median[n++]=p[i];
}
p+=GetPixelChannels(image);
}
channel_statistics[channel].median=(double) median[
GetMedianPixel(median,n)];
}
median_info=RelinquishVirtualMemory(median_info);
}
channel_statistics[CompositePixelChannel].mean=0.0;
channel_statistics[CompositePixelChannel].median=0.0;
channel_statistics[CompositePixelChannel].standard_deviation=0.0;
channel_statistics[CompositePixelChannel].entropy=0.0;
for (i=0; i < (ssize_t) MaxPixelChannels; i++)
{
channel_statistics[CompositePixelChannel].mean+=
channel_statistics[i].mean;
channel_statistics[CompositePixelChannel].median+=
channel_statistics[i].median;
channel_statistics[CompositePixelChannel].standard_deviation+=
channel_statistics[i].standard_deviation;
channel_statistics[CompositePixelChannel].entropy+=
channel_statistics[i].entropy;
}
channels=(double) GetImageChannels(image);
channel_statistics[CompositePixelChannel].mean/=channels;
channel_statistics[CompositePixelChannel].median/=channels;
channel_statistics[CompositePixelChannel].standard_deviation/=channels;
channel_statistics[CompositePixelChannel].entropy/=channels;
if (y < (ssize_t) image->rows)
channel_statistics=(ChannelStatistics *) RelinquishMagickMemory(
channel_statistics);
return(channel_statistics);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P o l y n o m i a l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PolynomialImage() returns a new image where each pixel is the sum of the
% pixels in the image sequence after applying its corresponding terms
% (coefficient and degree pairs).
%
% The format of the PolynomialImage method is:
%
% Image *PolynomialImage(const Image *images,const size_t number_terms,
% const double *terms,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o images: the image sequence.
%
% o number_terms: the number of terms in the list. The actual list length
% is 2 x number_terms + 1 (the constant).
%
% o terms: the list of polynomial coefficients and degree pairs and a
% constant.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *PolynomialImage(const Image *images,
const size_t number_terms,const double *terms,ExceptionInfo *exception)
{
#define PolynomialImageTag "Polynomial/Image"
CacheView
*polynomial_view;
Image
*image;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelChannels
**magick_restrict polynomial_pixels;
size_t
number_images;
ssize_t
y;
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImageCanvas(images,exception);
if (image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
{
image=DestroyImage(image);
return((Image *) NULL);
}
number_images=GetImageListLength(images);
polynomial_pixels=AcquirePixelThreadSet(images);
if (polynomial_pixels == (PixelChannels **) NULL)
{
image=DestroyImage(image);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
return((Image *) NULL);
}
/*
Polynomial image pixels.
*/
status=MagickTrue;
progress=0;
polynomial_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++)
{
CacheView
*image_view;
const Image
*next;
const int
id = GetOpenMPThreadId();
PixelChannels
*polynomial_pixel;
Quantum
*magick_restrict q;
ssize_t
i,
j,
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(polynomial_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
polynomial_pixel=polynomial_pixels[id];
for (j=0; j < (ssize_t) image->columns; j++)
for (i=0; i < MaxPixelChannels; i++)
polynomial_pixel[j].channel[i]=0.0;
next=images;
for (j=0; j < (ssize_t) number_images; j++)
{
const Quantum
*p;
if (j >= (ssize_t) number_terms)
continue;
image_view=AcquireVirtualCacheView(next,exception);
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
{
image_view=DestroyCacheView(image_view);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i < (ssize_t) GetPixelChannels(next); i++)
{
MagickRealType
coefficient,
degree;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(next,channel);
PixelTrait polynomial_traits=GetPixelChannelTraits(image,channel);
if ((traits == UndefinedPixelTrait) ||
(polynomial_traits == UndefinedPixelTrait))
continue;
if ((traits & UpdatePixelTrait) == 0)
continue;
coefficient=(MagickRealType) terms[2*j];
degree=(MagickRealType) terms[(j << 1)+1];
polynomial_pixel[x].channel[i]+=coefficient*
pow(QuantumScale*GetPixelChannel(image,channel,p),degree);
}
p+=GetPixelChannels(next);
}
image_view=DestroyCacheView(image_view);
next=GetNextImageInList(next);
}
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
if ((traits & UpdatePixelTrait) == 0)
continue;
q[i]=ClampToQuantum(QuantumRange*polynomial_pixel[x].channel[i]);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(polynomial_view,exception) == MagickFalse)
status=MagickFalse;
if (images->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(images,PolynomialImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
polynomial_view=DestroyCacheView(polynomial_view);
polynomial_pixels=DestroyPixelThreadSet(images,polynomial_pixels);
if (status == MagickFalse)
image=DestroyImage(image);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S t a t i s t i c I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% StatisticImage() makes each pixel the min / max / median / mode / etc. of
% the neighborhood of the specified width and height.
%
% The format of the StatisticImage method is:
%
% Image *StatisticImage(const Image *image,const StatisticType type,
% const size_t width,const size_t height,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o type: the statistic type (median, mode, etc.).
%
% o width: the width of the pixel neighborhood.
%
% o height: the height of the pixel neighborhood.
%
% o exception: return any errors or warnings in this structure.
%
*/
typedef struct _SkipNode
{
size_t
next[9],
count,
signature;
} SkipNode;
typedef struct _SkipList
{
ssize_t
level;
SkipNode
*nodes;
} SkipList;
typedef struct _PixelList
{
size_t
length,
seed;
SkipList
skip_list;
size_t
signature;
} PixelList;
static PixelList *DestroyPixelList(PixelList *pixel_list)
{
if (pixel_list == (PixelList *) NULL)
return((PixelList *) NULL);
if (pixel_list->skip_list.nodes != (SkipNode *) NULL)
pixel_list->skip_list.nodes=(SkipNode *) RelinquishAlignedMemory(
pixel_list->skip_list.nodes);
pixel_list=(PixelList *) RelinquishMagickMemory(pixel_list);
return(pixel_list);
}
static PixelList **DestroyPixelListThreadSet(PixelList **pixel_list)
{
ssize_t
i;
assert(pixel_list != (PixelList **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (pixel_list[i] != (PixelList *) NULL)
pixel_list[i]=DestroyPixelList(pixel_list[i]);
pixel_list=(PixelList **) RelinquishMagickMemory(pixel_list);
return(pixel_list);
}
static PixelList *AcquirePixelList(const size_t width,const size_t height)
{
PixelList
*pixel_list;
pixel_list=(PixelList *) AcquireMagickMemory(sizeof(*pixel_list));
if (pixel_list == (PixelList *) NULL)
return(pixel_list);
(void) memset((void *) pixel_list,0,sizeof(*pixel_list));
pixel_list->length=width*height;
pixel_list->skip_list.nodes=(SkipNode *) AcquireAlignedMemory(65537UL,
sizeof(*pixel_list->skip_list.nodes));
if (pixel_list->skip_list.nodes == (SkipNode *) NULL)
return(DestroyPixelList(pixel_list));
(void) memset(pixel_list->skip_list.nodes,0,65537UL*
sizeof(*pixel_list->skip_list.nodes));
pixel_list->signature=MagickCoreSignature;
return(pixel_list);
}
static PixelList **AcquirePixelListThreadSet(const size_t width,
const size_t height)
{
PixelList
**pixel_list;
ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
pixel_list=(PixelList **) AcquireQuantumMemory(number_threads,
sizeof(*pixel_list));
if (pixel_list == (PixelList **) NULL)
return((PixelList **) NULL);
(void) memset(pixel_list,0,number_threads*sizeof(*pixel_list));
for (i=0; i < (ssize_t) number_threads; i++)
{
pixel_list[i]=AcquirePixelList(width,height);
if (pixel_list[i] == (PixelList *) NULL)
return(DestroyPixelListThreadSet(pixel_list));
}
return(pixel_list);
}
static void AddNodePixelList(PixelList *pixel_list,const size_t color)
{
SkipList
*p;
ssize_t
level;
size_t
search,
update[9];
/*
Initialize the node.
*/
p=(&pixel_list->skip_list);
p->nodes[color].signature=pixel_list->signature;
p->nodes[color].count=1;
/*
Determine where it belongs in the list.
*/
search=65536UL;
for (level=p->level; level >= 0; level--)
{
while (p->nodes[search].next[level] < color)
search=p->nodes[search].next[level];
update[level]=search;
}
/*
Generate a pseudo-random level for this node.
*/
for (level=0; ; level++)
{
pixel_list->seed=(pixel_list->seed*42893621L)+1L;
if ((pixel_list->seed & 0x300) != 0x300)
break;
}
if (level > 8)
level=8;
if (level > (p->level+2))
level=p->level+2;
/*
If we're raising the list's level, link back to the root node.
*/
while (level > p->level)
{
p->level++;
update[p->level]=65536UL;
}
/*
Link the node into the skip-list.
*/
do
{
p->nodes[color].next[level]=p->nodes[update[level]].next[level];
p->nodes[update[level]].next[level]=color;
} while (level-- > 0);
}
static inline void GetMedianPixelList(PixelList *pixel_list,Quantum *pixel)
{
SkipList
*p;
size_t
color;
ssize_t
count;
/*
Find the median value for each of the color.
*/
p=(&pixel_list->skip_list);
color=65536L;
count=0;
do
{
color=p->nodes[color].next[0];
count+=p->nodes[color].count;
} while (count <= (ssize_t) (pixel_list->length >> 1));
*pixel=ScaleShortToQuantum((unsigned short) color);
}
static inline void GetModePixelList(PixelList *pixel_list,Quantum *pixel)
{
SkipList
*p;
size_t
color,
max_count,
mode;
ssize_t
count;
/*
Make each pixel the 'predominant color' of the specified neighborhood.
*/
p=(&pixel_list->skip_list);
color=65536L;
mode=color;
max_count=p->nodes[mode].count;
count=0;
do
{
color=p->nodes[color].next[0];
if (p->nodes[color].count > max_count)
{
mode=color;
max_count=p->nodes[mode].count;
}
count+=p->nodes[color].count;
} while (count < (ssize_t) pixel_list->length);
*pixel=ScaleShortToQuantum((unsigned short) mode);
}
static inline void GetNonpeakPixelList(PixelList *pixel_list,Quantum *pixel)
{
SkipList
*p;
size_t
color,
next,
previous;
ssize_t
count;
/*
Finds the non peak value for each of the colors.
*/
p=(&pixel_list->skip_list);
color=65536L;
next=p->nodes[color].next[0];
count=0;
do
{
previous=color;
color=next;
next=p->nodes[color].next[0];
count+=p->nodes[color].count;
} while (count <= (ssize_t) (pixel_list->length >> 1));
if ((previous == 65536UL) && (next != 65536UL))
color=next;
else
if ((previous != 65536UL) && (next == 65536UL))
color=previous;
*pixel=ScaleShortToQuantum((unsigned short) color);
}
static inline void InsertPixelList(const Quantum pixel,PixelList *pixel_list)
{
size_t
signature;
unsigned short
index;
index=ScaleQuantumToShort(pixel);
signature=pixel_list->skip_list.nodes[index].signature;
if (signature == pixel_list->signature)
{
pixel_list->skip_list.nodes[index].count++;
return;
}
AddNodePixelList(pixel_list,index);
}
static void ResetPixelList(PixelList *pixel_list)
{
int
level;
SkipNode
*root;
SkipList
*p;
/*
Reset the skip-list.
*/
p=(&pixel_list->skip_list);
root=p->nodes+65536UL;
p->level=0;
for (level=0; level < 9; level++)
root->next[level]=65536UL;
pixel_list->seed=pixel_list->signature++;
}
MagickExport Image *StatisticImage(const Image *image,const StatisticType type,
const size_t width,const size_t height,ExceptionInfo *exception)
{
#define StatisticImageTag "Statistic/Image"
CacheView
*image_view,
*statistic_view;
Image
*statistic_image;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelList
**magick_restrict pixel_list;
ssize_t
center,
y;
/*
Initialize statistics 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);
statistic_image=CloneImage(image,0,0,MagickTrue,
exception);
if (statistic_image == (Image *) NULL)
return((Image *) NULL);
status=SetImageStorageClass(statistic_image,DirectClass,exception);
if (status == MagickFalse)
{
statistic_image=DestroyImage(statistic_image);
return((Image *) NULL);
}
pixel_list=AcquirePixelListThreadSet(MagickMax(width,1),MagickMax(height,1));
if (pixel_list == (PixelList **) NULL)
{
statistic_image=DestroyImage(statistic_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Make each pixel the min / max / median / mode / etc. of the neighborhood.
*/
center=(ssize_t) GetPixelChannels(image)*(image->columns+MagickMax(width,1))*
(MagickMax(height,1)/2L)+GetPixelChannels(image)*(MagickMax(width,1)/2L);
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
statistic_view=AcquireAuthenticCacheView(statistic_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,statistic_image,statistic_image->rows,1)
#endif
for (y=0; y < (ssize_t) statistic_image->rows; y++)
{
const int
id = GetOpenMPThreadId();
const Quantum
*magick_restrict p;
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) MagickMax(width,1)/2L),y-
(ssize_t) (MagickMax(height,1)/2L),image->columns+MagickMax(width,1),
MagickMax(height,1),exception);
q=QueueCacheViewAuthenticPixels(statistic_view,0,y,statistic_image->columns, 1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) statistic_image->columns; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
area,
maximum,
minimum,
sum,
sum_squared;
Quantum
pixel;
const Quantum
*magick_restrict pixels;
ssize_t
u;
ssize_t
v;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait statistic_traits=GetPixelChannelTraits(statistic_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(statistic_traits == UndefinedPixelTrait))
continue;
if (((statistic_traits & CopyPixelTrait) != 0) ||
(GetPixelWriteMask(image,p) <= (QuantumRange/2)))
{
SetPixelChannel(statistic_image,channel,p[center+i],q);
continue;
}
if ((statistic_traits & UpdatePixelTrait) == 0)
continue;
pixels=p;
area=0.0;
minimum=pixels[i];
maximum=pixels[i];
sum=0.0;
sum_squared=0.0;
ResetPixelList(pixel_list[id]);
for (v=0; v < (ssize_t) MagickMax(height,1); v++)
{
for (u=0; u < (ssize_t) MagickMax(width,1); u++)
{
if ((type == MedianStatistic) || (type == ModeStatistic) ||
(type == NonpeakStatistic))
{
InsertPixelList(pixels[i],pixel_list[id]);
pixels+=GetPixelChannels(image);
continue;
}
area++;
if (pixels[i] < minimum)
minimum=(double) pixels[i];
if (pixels[i] > maximum)
maximum=(double) pixels[i];
sum+=(double) pixels[i];
sum_squared+=(double) pixels[i]*pixels[i];
pixels+=GetPixelChannels(image);
}
pixels+=GetPixelChannels(image)*image->columns;
}
switch (type)
{
case ContrastStatistic:
{
pixel=ClampToQuantum(MagickAbsoluteValue((maximum-minimum)*
PerceptibleReciprocal(maximum+minimum)));
break;
}
case GradientStatistic:
{
pixel=ClampToQuantum(MagickAbsoluteValue(maximum-minimum));
break;
}
case MaximumStatistic:
{
pixel=ClampToQuantum(maximum);
break;
}
case MeanStatistic:
default:
{
pixel=ClampToQuantum(sum/area);
break;
}
case MedianStatistic:
{
GetMedianPixelList(pixel_list[id],&pixel);
break;
}
case MinimumStatistic:
{
pixel=ClampToQuantum(minimum);
break;
}
case ModeStatistic:
{
GetModePixelList(pixel_list[id],&pixel);
break;
}
case NonpeakStatistic:
{
GetNonpeakPixelList(pixel_list[id],&pixel);
break;
}
case RootMeanSquareStatistic:
{
pixel=ClampToQuantum(sqrt(sum_squared/area));
break;
}
case StandardDeviationStatistic:
{
pixel=ClampToQuantum(sqrt(sum_squared/area-(sum/area*sum/area)));
break;
}
}
SetPixelChannel(statistic_image,channel,pixel,q);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(statistic_image);
}
if (SyncCacheViewAuthenticPixels(statistic_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,StatisticImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
statistic_view=DestroyCacheView(statistic_view);
image_view=DestroyCacheView(image_view);
pixel_list=DestroyPixelListThreadSet(pixel_list);
if (status == MagickFalse)
statistic_image=DestroyImage(statistic_image);
return(statistic_image);
}
|
tools.h | int log2i(int x){
int r = 0;
x >>= 1;
while(x){
r++;
x >>= 1;
}
return r;
}
int pow2i(int x){
return (1 << x);
}
void printarray(int *a,int n, const char* msg){
if (n<=32) {
printf("%s: ",msg);
for (int i = 0; i <n; ++i){
printf("%4i ",a[i]);
}
printf("\n");
}
}
void initarray(int *a, int n, const int c){
#pragma omp parallel for
for (int i = 0; i < n; ++i){
a[i] = c*(i+1);
}
}
void validate(int *s, int *sgold, int n){
for (int i = 0; i < n; ++i){
if(s[i] != sgold[i]){
printf("failed\n");
printf("Error s[%i](%i) != sgold[%i](%i)\n", i, s[i], i, sgold[i]);
exit(EXIT_FAILURE);
}
}
}
|
for-1.c | void bar (int);
int a[256];
void
foo (void)
{
int i;
#pragma omp for
for (i = 0; i != 64; i++)
bar (i);
#pragma omp for
for (i = 128; i != 64; i--)
bar (i);
#pragma omp for
for (i = 0; i != 64; i = i + 1)
bar (i);
#pragma omp for
for (i = 128; i != 64; i = i - 1)
bar (i);
#pragma omp for
for (i = 0; i != 64; i = 1 + i)
bar (i);
#pragma omp for
for (i = 128; i != 64; i = -1 + i)
bar (i);
#pragma omp for
for (i = 0; i != 64; i += 1)
bar (i);
#pragma omp for
for (i = 128; i != 64; i -= 1)
bar (i);
#pragma omp single
{
#pragma omp simd
for (i = 0; i != 64; i++)
a[i] = a[i] + 1;
#pragma omp simd
for (i = 128; i != 64; i--)
a[i] = a[i] + 1;
#pragma omp simd
for (i = 0; i != 64; i = i + 1)
a[i] = a[i] + 1;
#pragma omp simd
for (i = 128; i != 64; i = i - 1)
a[i] = a[i] + 1;
#pragma omp simd
for (i = 0; i != 64; i = 1 + i)
a[i] = a[i] + 1;
#pragma omp simd
for (i = 128; i != 64; i = -1 + i)
a[i] = a[i] + 1;
#pragma omp simd
for (i = 0; i != 64; i += 1)
a[i] = a[i] + 1;
#pragma omp simd
for (i = 128; i != 64; i -= 1)
a[i] = a[i] + 1;
}
}
|
main.c | #include <stdio.h>
#include <omp.h>
int main(int argc, char **argv) {
// Fork a team of threads giving them their own copies of variables
// Argumentos para omp parallel:
// private(A) -> leva ao escopo da Thread uma cópia da variável A sem o valor
// firstprivate(B) -> leva ao escopo da Thread uma cópia da variável B incluindo valor
/*
int tid;
int x;
int y = 10;
int z;
#pragma omp parallel private(tid, x, z) firstprivate(y)
{
// Obtain thread number
tid = omp_get_thread_num();
printf("Hello from thread #%2d: x = %d; y = %d\n", tid, x, y);
#pragma omp master
printf("Oi, sou o mestre, o thread #%2d\n", tid);
}
*/
// Fork a team of threads
int n = 10000, i;
double a[10000], b[10000], sum;
#pragma omp parallel for num_threads(8)
for (i = 0; i < n; i++) {
a[i] = b[i] = i * 1.0;
}
sum = 0.0;
// Aqui tem concorrência no sum
// #pragma omp parallel for num_threads(8)
// for (i = 0; i < n; i++) {
// sum = sum + (a[i] + b[i]);
// }
// Usar o reduction faz: variável privada pra cada um, realiza as operações da thread
// e depois unifica com a operação definida dentro dos parênteses
#pragma omp parallel for reduction(+: sum) num_threads(8)
for (i = 0; i < n; i++) {
sum = sum + (a[i] * b[i]);
}
printf("sum = %.0f\n", sum);
return 0;
}
|
bml_norm_ellpack_typed.c | #include "../../macros.h"
#include "../../typed.h"
#include "../bml_norm.h"
#include "../bml_parallel.h"
#include "../bml_types.h"
#include "bml_norm_ellpack.h"
#include "bml_types_ellpack.h"
#include <complex.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#ifdef _OPENMP
#include <omp.h>
#endif
/** Calculate the sum of squares of the elements of a matrix.
*
* \ingroup norm_group
*
* \param A The matrix A
* \return The sum of squares of A
*/
double TYPED_FUNC(
bml_sum_squares_ellpack) (
bml_matrix_ellpack_t * A)
{
int N = A->N;
int M = A->M;
int *A_nnz = (int *) A->nnz;
int *A_localRowMin = A->domain->localRowMin;
int *A_localRowMax = A->domain->localRowMax;
REAL_T sum = 0.0;
REAL_T *A_value = (REAL_T *) A->value;
int myRank = bml_getMyRank();
int rowMin = A_localRowMin[myRank];
int rowMax = A_localRowMax[myRank];
#ifdef USE_OMP_OFFLOAD
//#pragma omp target map(tofrom:sum)
#pragma omp target update from(A_nnz[:N], A_value[:N*M])
#endif
#pragma omp parallel for \
shared(N, M, A_value, A_nnz) \
shared(rowMin, rowMax) \
reduction(+:sum)
for (int i = rowMin; i < rowMax; i++)
{
for (int j = 0; j < A_nnz[i]; j++)
{
REAL_T xval = A_value[ROWMAJOR(i, j, N, M)];
sum += xval * xval;
}
}
return (double) REAL_PART(sum);
}
/** Calculate the sum of squares of all the core elements of a submatrix.
*
* \ingroup norm_group
*
* \param A The matrix
* \param core_pos Core rows of submatrix
* \param core_size Number of core rows
* \return The sum of squares of A
*/
double TYPED_FUNC(
bml_sum_squares_submatrix_ellpack) (
bml_matrix_ellpack_t * A,
int core_size)
{
int N = A->N;
int M = A->M;
int *A_index = (int *) A->index;
int *A_nnz = (int *) A->nnz;
REAL_T sum = 0.0;
REAL_T *A_value = (REAL_T *) A->value;
#ifdef USE_OMP_OFFLOAD
//#pragma omp target map(tofrom:sum)
#pragma omp target update from(A_nnz[:N], A_index[:N*M], A_value[:N*M])
#endif
#pragma omp parallel for \
reduction(+:sum)
for (int i = 0; i < core_size; i++)
{
for (int j = 0; j < A_nnz[i]; j++)
{
if (A_index[ROWMAJOR(i, j, N, M)] < core_size)
{
REAL_T value = A_value[ROWMAJOR(i, j, N, M)];
sum += value * value;
}
}
}
return (double) REAL_PART(sum);
}
/** Calculate the sum of the elements of \alpha A(i,j) * B(i,j).
*
* \ingroup norm_group
*
* \param A The matrix A
* \param B The matrix B
* \param alpha Multiplier for A
* \pram threshold Threshold
* \return The sum of squares of \alpha A(i,j) * B(i,j)
*/
double TYPED_FUNC(
bml_sum_AB_ellpack) (
bml_matrix_ellpack_t * A,
bml_matrix_ellpack_t * B,
double alpha,
double threshold)
{
int A_N = A->N;
int A_M = A->M;
int B_N = B->N;
int B_M = B->M;
int *A_index = (int *) A->index;
int *A_nnz = (int *) A->nnz;
int *B_index = (int *) B->index;
int *B_nnz = (int *) B->nnz;
int *A_localRowMin = A->domain->localRowMin;
int *A_localRowMax = A->domain->localRowMax;
REAL_T sum = 0.0;
REAL_T *A_value = (REAL_T *) A->value;
REAL_T *B_value = (REAL_T *) B->value;
REAL_T alpha_ = (REAL_T) alpha;
int myRank = bml_getMyRank();
int rowMin = A_localRowMin[myRank];
int rowMax = A_localRowMax[myRank];
#if !(defined(__IBMC__) || defined(__ibmxl__))
REAL_T y[A_N];
int ix[A_N], jjb[A_N];
memset(y, 0.0, A_N * sizeof(REAL_T));
memset(ix, 0, A_N * sizeof(int));
memset(jjb, 0, A_N * sizeof(int));
#endif
#ifdef USE_OMP_OFFLOAD
//#pragma omp target map(tofrom:sum)
#pragma omp target update from(A_nnz[:A_N], A_index[:A_N*A_M], A_value[:A_N*A_M])
#pragma omp target update from(B_nnz[:B_N], B_index[:B_N*B_M], B_value[:B_N*B_M])
#endif
#if defined(__IBMC__) || defined(__ibmxl__)
#pragma omp parallel for \
shared(alpha_) \
shared(A_N, A_M, A_index, A_nnz, A_value) \
shared(A_localRowMin, A_localRowMax, myRank) \
shared(B_N, B_M, B_index, B_nnz, B_value) \
reduction(+:sum)
#else
#pragma omp parallel for \
shared(alpha_) \
shared(A_N, A_M, A_index, A_nnz, A_value) \
shared(A_localRowMin, A_localRowMax, myRank) \
shared(B_N, B_M, B_index, B_nnz, B_value) \
firstprivate(ix, jjb, y) \
reduction(+:sum)
#endif
//for (int i = 0; i < A_N; i++)
for (int i = rowMin; i < rowMax; i++)
{
#if defined(__IBMC__) || defined(__ibmxl__)
REAL_T y[A_N];
int ix[A_N], jjb[A_N];
memset(ix, 0, A_N * sizeof(int));
#endif
int l = 0;
for (int jp = 0; jp < A_nnz[i]; jp++)
{
int k = A_index[ROWMAJOR(i, jp, A_N, A_M)];
if (ix[k] == 0)
{
y[k] = 0.0;
ix[k] = i + 1;
jjb[l] = k;
l++;
}
y[k] += alpha_ * A_value[ROWMAJOR(i, jp, A_N, A_M)];
}
for (int jp = 0; jp < B_nnz[i]; jp++)
{
int k = B_index[ROWMAJOR(i, jp, B_N, B_M)];
if (ix[k] == 0)
{
y[k] = 0.0;
ix[k] = i + 1;
jjb[l] = k;
l++;
}
y[k] *= B_value[ROWMAJOR(i, jp, B_N, B_M)];
}
for (int jp = 0; jp < l; jp++)
{
if (ABS(y[jjb[jp]]) > threshold)
sum += y[jjb[jp]]; //* y[jjb[jp]];
ix[jjb[jp]] = 0;
y[jjb[jp]] = 0.0;
jjb[jp] = 0;
}
}
return (double) REAL_PART(sum);
}
/** Calculate the sum of squares of the elements of \alpha A + \beta B.
*
* \ingroup norm_group
*
* \param A The matrix A
* \param B The matrix B
* \param alpha Multiplier for A
* \param beta Multiplier for B
* \pram threshold Threshold
* \return The sum of squares of \alpha A + \beta B
*/
double TYPED_FUNC(
bml_sum_squares2_ellpack) (
bml_matrix_ellpack_t * A,
bml_matrix_ellpack_t * B,
double alpha,
double beta,
double threshold)
{
int A_N = A->N;
int A_M = A->M;
int B_N = B->N;
int B_M = B->M;
int *A_index = (int *) A->index;
int *A_nnz = (int *) A->nnz;
int *B_index = (int *) B->index;
int *B_nnz = (int *) B->nnz;
int *A_localRowMin = A->domain->localRowMin;
int *A_localRowMax = A->domain->localRowMax;
REAL_T sum = 0.0;
REAL_T *A_value = (REAL_T *) A->value;
REAL_T *B_value = (REAL_T *) B->value;
REAL_T alpha_ = (REAL_T) alpha;
REAL_T beta_ = (REAL_T) beta;
int myRank = bml_getMyRank();
int rowMin = A_localRowMin[myRank];
int rowMax = A_localRowMax[myRank];
#if !(defined(__IBMC__) || defined(__ibmxl__))
REAL_T y[A_N];
int ix[A_N], jjb[A_N];
memset(y, 0.0, A_N * sizeof(REAL_T));
memset(ix, 0, A_N * sizeof(int));
memset(jjb, 0, A_N * sizeof(int));
#endif
#ifdef USE_OMP_OFFLOAD
//#pragma omp target map(tofrom:sum)
#pragma omp target update from(A_nnz[:A_N], A_index[:A_N*A_M], A_value[:A_N*A_M])
#pragma omp target update from(B_nnz[:B_N], B_index[:B_N*B_M], B_value[:B_N*B_M])
#endif
#if defined(__IBMC__) || defined(__ibmxl__)
#pragma omp parallel for \
shared(alpha_, beta_) \
shared(A_N, A_M, A_index, A_nnz, A_value) \
shared(A_localRowMin, A_localRowMax, myRank) \
shared(B_N, B_M, B_index, B_nnz, B_value) \
reduction(+:sum)
#else
#pragma omp parallel for \
shared(alpha_, beta_) \
shared(A_N, A_M, A_index, A_nnz, A_value) \
shared(A_localRowMin, A_localRowMax, myRank) \
shared(B_N, B_M, B_index, B_nnz, B_value) \
firstprivate(ix, jjb, y) \
reduction(+:sum)
#endif
//for (int i = 0; i < A_N; i++)
for (int i = rowMin; i < rowMax; i++)
{
#if defined(__IBMC__) || defined(__ibmxl__)
REAL_T y[A_N];
int ix[A_N], jjb[A_N];
memset(ix, 0, A_N * sizeof(int));
#endif
int l = 0;
for (int jp = 0; jp < A_nnz[i]; jp++)
{
int k = A_index[ROWMAJOR(i, jp, A_N, A_M)];
if (ix[k] == 0)
{
y[k] = 0.0;
ix[k] = i + 1;
jjb[l] = k;
l++;
}
y[k] += alpha_ * A_value[ROWMAJOR(i, jp, A_N, A_M)];
}
for (int jp = 0; jp < B_nnz[i]; jp++)
{
int k = B_index[ROWMAJOR(i, jp, B_N, B_M)];
if (ix[k] == 0)
{
y[k] = 0.0;
ix[k] = i + 1;
jjb[l] = k;
l++;
}
y[k] += beta_ * B_value[ROWMAJOR(i, jp, B_N, B_M)];
}
for (int jp = 0; jp < l; jp++)
{
if (ABS(y[jjb[jp]]) > threshold)
sum += y[jjb[jp]] * y[jjb[jp]];
ix[jjb[jp]] = 0;
y[jjb[jp]] = 0.0;
jjb[jp] = 0;
}
}
return (double) REAL_PART(sum);
}
/** Calculate the Frobenius norm of matrix A.
*
* \ingroup norm_group
*
* \param A The matrix A
* \return The Frobenius norm of A
*/
double TYPED_FUNC(
bml_fnorm_ellpack) (
bml_matrix_ellpack_t * A)
{
double fnorm = TYPED_FUNC(bml_sum_squares_ellpack) (A);
#ifdef DO_MPI
if (bml_getNRanks() > 1 && A->distribution_mode == distributed)
{
bml_sumRealReduce(&fnorm);
}
#endif
fnorm = sqrt(fnorm);
return (double) REAL_PART(fnorm);
}
/** Calculate the Frobenius norm of 2 matrices.
*
* \ingroup norm_group
*
* \param A The matrix A
* \param B The matrix B
* \return The Frobenius norm of A-B
*/
double TYPED_FUNC(
bml_fnorm2_ellpack) (
bml_matrix_ellpack_t * A,
bml_matrix_ellpack_t * B)
{
int N = A->N;
int M = A->M;
double fnorm = 0.0;
REAL_T rvalue;
int *A_nnz = (int *) A->nnz;
int *A_index = (int *) A->index;
int *A_localRowMin = A->domain->localRowMin;
int *A_localRowMax = A->domain->localRowMax;
REAL_T *A_value = (REAL_T *) A->value;
int *B_nnz = (int *) B->nnz;
int *B_index = (int *) B->index;
REAL_T *B_value = (REAL_T *) B->value;
REAL_T temp;
int myRank = bml_getMyRank();
int rowMin = A_localRowMin[myRank];
int rowMax = A_localRowMax[myRank];
#ifdef USE_OMP_OFFLOAD
//#pragma omp target map(tofrom:fnorm)
#pragma omp target update from(A_nnz[:N], A_index[:N*M], A_value[:N*M])
#endif
#pragma omp parallel for \
private(rvalue, temp) \
shared(N, M, A_nnz, A_index, A_value) \
shared(A_localRowMin, A_localRowMax, myRank) \
shared(B_nnz, B_index, B_value) \
reduction(+:fnorm)
//for (int i = 0; i < N; i++)
for (int i = rowMin; i < rowMax; i++)
{
for (int j = 0; j < A_nnz[i]; j++)
{
for (int k = 0; k < B_nnz[i]; k++)
{
if (A_index[ROWMAJOR(i, j, N, M)] ==
B_index[ROWMAJOR(i, k, N, M)])
{
rvalue = B_value[ROWMAJOR(i, k, N, M)];
break;
}
rvalue = 0.0;
}
temp = A_value[ROWMAJOR(i, j, N, M)] - rvalue;
fnorm += temp * temp;
}
for (int j = 0; j < B_nnz[i]; j++)
{
for (int k = 0; k < A_nnz[i]; k++)
{
if (A_index[ROWMAJOR(i, k, N, M)] ==
B_index[ROWMAJOR(i, j, N, M)])
{
rvalue = A_value[ROWMAJOR(i, k, N, M)];
break;
}
rvalue = 0.0;
}
if (rvalue == 0.0)
{
temp = B_value[ROWMAJOR(i, j, N, M)];
fnorm += temp * temp;
}
}
}
#ifdef DO_MPI
if (bml_getNRanks() > 1 && A->distribution_mode == distributed)
{
bml_sumRealReduce(&fnorm);
}
#endif
fnorm = sqrt(fnorm);
return (double) REAL_PART(fnorm);
}
|
RotationInvariantEncoding.c | #ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "generic/RotationInvariantEncoding.c"
#else
static int orn_(RIE_AlignFeature)(lua_State *L)
{
THTensor *feature = luaT_checkudata(L, 2, torch_Tensor);
THTensor *mainDirection = luaT_checkudata(L, 3, torch_Tensor);
THTensor *aligned = luaT_checkudata(L, 4, torch_Tensor);
const uint16 nBatch = lua_tonumber(L, 5);
const uint16 nFeature = lua_tonumber(L, 6);
const uint8 nOrientation = lua_tonumber(L, 7);
uint16 i;
uint16 j;
uint8 l;
real *feature_data = THTensor_(data)(feature);
real *mainDirection_data = THTensor_(data)(mainDirection);
real *aligned_data = THTensor_(data)(aligned);
#pragma omp parallel for private(i)
for (i = 0; i < nBatch; i++) {
for (j = 0; j < nFeature; j++) {
real *direction = mainDirection_data + i * nFeature + j;
real maxVal = -THInf;
for (l = 0; l < nOrientation; l++) {
real val = *(feature_data + i * (nFeature * nOrientation)
+ j * (nOrientation)
+ l);
if (val > maxVal) {
maxVal = val;
*direction = l;
}
}
for (l = 0; l < nOrientation; l++) {
real src = *(feature_data + i * (nFeature * nOrientation)
+ j * (nOrientation)
+ l);
uint8 alignedIndex = (l - (uint8)*direction + nOrientation) % nOrientation;
real *target = aligned_data + i * (nFeature * nOrientation)
+ j * (nOrientation)
+ alignedIndex;
*target = src;
}
}
}
return 0;
}
// backward de/dx
/* self,
self.gradInput,
self.mainDirection,
gradOutput,
self.nBatch,
self.nFeature,
self.nOrientation
*/
static int orn_(RIE_UnAlignFeature)(lua_State *L)
{
THTensor *feature = luaT_checkudata(L, 2, torch_Tensor);
THTensor *mainDirection = luaT_checkudata(L, 3, torch_Tensor);
THTensor *aligned = luaT_checkudata(L, 4, torch_Tensor);
const uint16 nBatch = lua_tonumber(L, 5);
const uint16 nFeature = lua_tonumber(L, 6);
const uint8 nOrientation = lua_tonumber(L, 7);
uint16 i;
uint16 j;
uint8 l;
real *feature_data = THTensor_(data)(feature);
real *mainDirection_data = THTensor_(data)(mainDirection);
real *aligned_data = THTensor_(data)(aligned);
#pragma omp parallel for private(i)
for (i = 0; i < nBatch; i++) {
for (j = 0; j < nFeature; j++) {
uint8 direction = (uint8)*(mainDirection_data + i * nFeature + j);
for (l = 0; l < nOrientation; l++) {
real src = *(aligned_data + i * (nFeature * nOrientation)
+ j * (nOrientation)
+ l);
uint8 alignedIndex = (l + direction) % nOrientation;
real *target = feature_data + i * (nFeature * nOrientation)
+ j * (nOrientation)
+ alignedIndex;
*target = src;
}
}
}
return 0;
}
static const struct luaL_Reg orn_(RIE__) [] = {
{"RIE_AlignFeature", orn_(RIE_AlignFeature)},
{"RIE_UnAlignFeature", orn_(RIE_UnAlignFeature)},
{NULL, NULL}
};
static void orn_(RIE_init)(lua_State *L)
{
luaT_pushmetatable(L, torch_Tensor);
luaT_registeratname(L, orn_(RIE__), "orn");
lua_pop(L,1);
}
#endif
|
ten_tusscher_2004_epi_S2_7.c | //Original Ten Tusscher
#include <assert.h>
#include <stdlib.h>
#include "ten_tusscher_2004_epi_S2_7.h"
GET_CELL_MODEL_DATA(init_cell_model_data) {
assert(cell_model);
if(get_initial_v)
cell_model->initial_v = INITIAL_V;
if(get_neq)
cell_model->number_of_ode_equations = NEQ;
}
//TODO: this should be called only once for the whole mesh, like in the GPU code
SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu) {
// Default initial conditions
/*
sv[0] = INITIAL_V; // V; millivolt
sv[1] = 0.f; //M
sv[2] = 0.75; //H
sv[3] = 0.75f; //J
sv[4] = 0.f; //Xr1
sv[5] = 1.f; //Xr2
sv[6] = 0.f; //Xs
sv[7] = 1.f; //S
sv[8] = 0.f; //R
sv[9] = 0.f; //D
sv[10] = 1.f; //F
sv[11] = 1.f; //FCa
sv[12] = 1.f; //G
sv[13] = 0.0002; //Cai
sv[14] = 0.2f; //CaSR
sv[15] = 11.6f; //Nai
sv[16] = 138.3f; //Ki
*/
// Elnaz's steady-state initial conditions
real sv_sst[]={-86.5108357840011,0.00130598320935367,0.778297936322614,0.778168249814233,0.000176184942496385,0.484492639570884,0.00295234515201219,0.999998328994369,1.95207361603797e-08,1.90559907730747e-05,0.999779205501714,1.00683281960406,0.999990079738075,5.13012060586906e-05,1.20488538387603,8.59982990627790,140.667607494303};
for (uint32_t i = 0; i < NEQ; i++)
sv[i] = sv_sst[i];
}
SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu) {
uint32_t sv_id;
int i;
#pragma omp parallel for private(sv_id)
for (i = 0; i < num_cells_to_solve; i++) {
if(cells_to_solve)
sv_id = cells_to_solve[i];
else
sv_id = i;
for (int j = 0; j < num_steps; ++j) {
solve_model_ode_cpu(dt, sv + (sv_id * NEQ), stim_currents[i]);
}
}
}
void solve_model_ode_cpu(real dt, real *sv, real stim_current) {
assert(sv);
real rY[NEQ], rDY[NEQ];
for(int i = 0; i < NEQ; i++)
rY[i] = sv[i];
RHS_cpu(rY, rDY, stim_current, dt);
for(int i = 0; i < NEQ; i++)
sv[i] = rDY[i];
}
void RHS_cpu(const real *sv, real *rDY_, real stim_current, real dt) {
// State variables
real svolt = sv[0];
real sm = sv[1];
real sh = sv[2];
real sj = sv[3];
real sxr1 = sv[4];
real sxr2 = sv[5];
real sxs = sv[6];
real ss = sv[7];
real sr = sv[8];
real sd = sv[9];
real sf = sv[10];
real sfca = sv[11];
real sg = sv[12];
real Cai = sv[13];
real CaSR = sv[14];
real Nai = sv[15];
real Ki = sv[16];
//External concentrations
real Ko=5.4;
real Cao=2.0;
real Nao=140.0;
//Intracellular volumes
real Vc=0.016404;
real Vsr=0.001094;
//Calcium dynamics
real Bufc=0.15f;
real Kbufc=0.001f;
real Bufsr=10.f;
real Kbufsr=0.3f;
real taufca=2.f;
real taug=2.f;
real Vmaxup=0.000425f;
real Kup=0.00025f;
//Constants
const real R = 8314.472f;
const real F = 96485.3415f;
const real T =310.0f;
real RTONF =(R*T)/F;
//Cellular capacitance
real CAPACITANCE=0.185;
//Parameters for currents
//Parameters for IKr
real Gkr=0.096;
//Parameters for Iks
real pKNa=0.03;
///#ifdef EPI
real Gks=0.245;
///#endif
///#ifdef ENDO
/// real Gks=0.245;
///#endif
///#ifdef MCELL
/// real Gks=0.062;
///#endif
//Parameters for Ik1
real GK1=5.405;
//Parameters for Ito
//#ifdef EPI
real Gto=0.294;
//#endif
// #ifdef ENDO
// real Gto=0.073;
//#endif
//#ifdef MCELL
// real Gto=0.294;
///#endif
//Parameters for INa
real GNa=14.838;
//Parameters for IbNa
real GbNa=0.00029;
//Parameters for INaK
real KmK=1.0;
real KmNa=40.0;
real knak=1.362;
//Parameters for ICaL
real GCaL=0.000175;
//Parameters for IbCa
real GbCa=0.000592;
//Parameters for INaCa
real knaca=1000;
real KmNai=87.5;
real KmCa=1.38;
real ksat=0.1;
real n=0.35;
//Parameters for IpCa
real GpCa=0.825;
real KpCa=0.0005;
//Parameters for IpK;
real GpK=0.0146;
real parameters []={13.5180163805163,0.000327758478537637,0.000171474998724435,0.000691830399658185,0.287392821646320,0.166300577201109,0.184041710714562,3.74850836746364,0.0218547235879219,3.15306872250787,1099.99995030167,0.000576388720425406,0.124097096559342,0.0199999709711304,0.00444385627683816,2.41454672727958e-05};
GNa=parameters[0];
GbNa=parameters[1];
GCaL=parameters[2];
GbCa=parameters[3];
Gto=parameters[4];
Gkr=parameters[5];
Gks=parameters[6];
GK1=parameters[7];
GpK=parameters[8];
knak=parameters[9];
knaca=parameters[10];
Vmaxup=parameters[11];
GpCa=parameters[12];
real arel=parameters[13];
real crel=parameters[14];
real Vleak=parameters[15];
real IKr;
real IKs;
real IK1;
real Ito;
real INa;
real IbNa;
real ICaL;
real IbCa;
real INaCa;
real IpCa;
real IpK;
real INaK;
real Irel;
real Ileak;
real dNai;
real dKi;
real dCai;
real dCaSR;
real A;
// real BufferFactorc;
// real BufferFactorsr;
real SERCA;
real Caisquare;
real CaSRsquare;
real CaCurrent;
real CaSRCurrent;
real fcaold;
real gold;
real Ek;
real Ena;
real Eks;
real Eca;
real CaCSQN;
real bjsr;
real cjsr;
real CaBuf;
real bc;
real cc;
real Ak1;
real Bk1;
real rec_iK1;
real rec_ipK;
real rec_iNaK;
real AM;
real BM;
real AH_1;
real BH_1;
real AH_2;
real BH_2;
real AJ_1;
real BJ_1;
real AJ_2;
real BJ_2;
real M_INF;
real H_INF;
real J_INF;
real TAU_M;
real TAU_H;
real TAU_J;
real axr1;
real bxr1;
real axr2;
real bxr2;
real Xr1_INF;
real Xr2_INF;
real TAU_Xr1;
real TAU_Xr2;
real Axs;
real Bxs;
real Xs_INF;
real TAU_Xs;
real R_INF;
real TAU_R;
real S_INF;
real TAU_S;
real Ad;
real Bd;
real Cd;
real TAU_D;
real D_INF;
real TAU_F;
real F_INF;
real FCa_INF;
real G_INF;
real inverseVcF2=1/(2*Vc*F);
real inverseVcF=1./(Vc*F);
real Kupsquare=Kup*Kup;
// real BufcKbufc=Bufc*Kbufc;
// real Kbufcsquare=Kbufc*Kbufc;
// real Kbufc2=2*Kbufc;
// real BufsrKbufsr=Bufsr*Kbufsr;
// const real Kbufsrsquare=Kbufsr*Kbufsr;
// const real Kbufsr2=2*Kbufsr;
const real exptaufca=exp(-dt/taufca);
const real exptaug=exp(-dt/taug);
real sItot;
//Needed to compute currents
Ek=RTONF*(log((Ko/Ki)));
Ena=RTONF*(log((Nao/Nai)));
Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai)));
Eca=0.5*RTONF*(log((Cao/Cai)));
Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200)));
Bk1=(3.*exp(0.0002*(svolt-Ek+100))+
exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek)));
rec_iK1=Ak1/(Ak1+Bk1);
rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T))));
rec_ipK=1./(1.+exp((25-svolt)/5.98));
//Compute currents
INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena);
ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))*
(exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.);
Ito=Gto*sr*ss*(svolt-Ek);
IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek);
IKs=Gks*sxs*sxs*(svolt-Eks);
IK1=GK1*rec_iK1*(svolt-Ek);
INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))*
(1./(1+ksat*exp((n-1)*svolt*F/(R*T))))*
(exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao-
exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5);
INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK;
IpCa=GpCa*Cai/(KpCa+Cai);
IpK=GpK*rec_ipK*(svolt-Ek);
IbNa=GbNa*(svolt-Ena);
IbCa=GbCa*(svolt-Eca);
//Determine total current
(sItot) = IKr +
IKs +
IK1 +
Ito +
INa +
IbNa +
ICaL +
IbCa +
INaK +
INaCa +
IpCa +
IpK +
stim_current;
//update concentrations
Caisquare=Cai*Cai;
CaSRsquare=CaSR*CaSR;
CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE;
///A=0.016464f*CaSRsquare/(0.0625f+CaSRsquare)+0.008232f;
A=arel*CaSRsquare/(0.0625f+CaSRsquare)+crel;
Irel=A*sd*sg;
///Ileak=0.00008f*(CaSR-Cai);
Ileak=Vleak*(CaSR-Cai);
SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare));
CaSRCurrent=SERCA-Irel-Ileak;
CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr);
dCaSR=dt*(Vc/Vsr)*CaSRCurrent;
bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr;
cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR);
CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.;
CaBuf=Bufc*Cai/(Cai+Kbufc);
dCai=dt*(CaCurrent-CaSRCurrent);
bc=Bufc-CaBuf-dCai-Cai+Kbufc;
cc=Kbufc*(CaBuf+dCai+Cai);
Cai=(sqrt(bc*bc+4*cc)-bc)/2;
dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE;
Nai+=dt*dNai;
dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE;
Ki+=dt*dKi;
//compute steady state values and time constants
AM=1./(1.+exp((-60.-svolt)/5.));
BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.));
TAU_M=AM*BM;
M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03)));
if (svolt>=-40.)
{
AH_1=0.;
BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1))));
TAU_H= 1.0/(AH_1+BH_1);
}
else
{
AH_2=(0.057*exp(-(svolt+80.)/6.8));
BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt));
TAU_H=1.0/(AH_2+BH_2);
}
H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43)));
if(svolt>=-40.)
{
AJ_1=0.;
BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.))));
TAU_J= 1.0/(AJ_1+BJ_1);
}
else
{
AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)*
exp(-0.04391*svolt))*(svolt+37.78)/
(1.+exp(0.311*(svolt+79.23))));
BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14))));
TAU_J= 1.0/(AJ_2+BJ_2);
}
J_INF=H_INF;
Xr1_INF=1./(1.+exp((-26.-svolt)/7.));
axr1=450./(1.+exp((-45.-svolt)/10.));
bxr1=6./(1.+exp((svolt-(-30.))/11.5));
TAU_Xr1=axr1*bxr1;
Xr2_INF=1./(1.+exp((svolt-(-88.))/24.));
axr2=3./(1.+exp((-60.-svolt)/20.));
bxr2=1.12/(1.+exp((svolt-60.)/20.));
TAU_Xr2=axr2*bxr2;
Xs_INF=1./(1.+exp((-5.-svolt)/14.));
Axs=1100./(sqrt(1.+exp((-10.-svolt)/6)));
Bxs=1./(1.+exp((svolt-60.)/20.));
TAU_Xs=Axs*Bxs;
#ifdef EPI
R_INF=1./(1.+exp((20-svolt)/6.));
S_INF=1./(1.+exp((svolt+20)/5.));
TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8;
TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.;
#endif
#ifdef ENDO
R_INF=1./(1.+exp((20-svolt)/6.));
S_INF=1./(1.+exp((svolt+28)/5.));
TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8;
TAU_S=1000.*exp(-(svolt+67)*(svolt+67)/1000.)+8.;
#endif
#ifdef MCELL
R_INF=1./(1.+exp((20-svolt)/6.));
S_INF=1./(1.+exp((svolt+20)/5.));
TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8;
TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.;
#endif
D_INF=1./(1.+exp((-5-svolt)/7.5));
Ad=1.4/(1.+exp((-35-svolt)/13))+0.25;
Bd=1.4/(1.+exp((svolt+5)/5));
Cd=1./(1.+exp((50-svolt)/20));
TAU_D=Ad*Bd+Cd;
F_INF=1./(1.+exp((svolt+20)/7));
TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10));
FCa_INF=(1./(1.+pow((Cai/0.000325),8))+
0.1/(1.+exp((Cai-0.0005)/0.0001))+
0.20/(1.+exp((Cai-0.00075)/0.0008))+
0.23 )/1.46;
if(Cai<0.00035)
G_INF=1./(1.+pow((Cai/0.00035),6));
else
G_INF=1./(1.+pow((Cai/0.00035),16));
//Update gates
rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M);
rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H);
rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J);
rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1);
rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2);
rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs);
rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S);
rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R);
rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D);
rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F);
fcaold= sfca;
sfca = FCa_INF-(FCa_INF-sfca)*exptaufca;
if(sfca>fcaold && (svolt)>-37.0)
sfca = fcaold;
gold = sg;
sg = G_INF-(G_INF-sg)*exptaug;
if(sg>gold && (svolt)>-37.0)
sg=gold;
//update voltage
rDY_[0] = svolt + dt*(-sItot);
rDY_[11] = sfca;
rDY_[12] = sg;
rDY_[13] = Cai;
rDY_[14] = CaSR;
rDY_[15] = Nai;
rDY_[16] = Ki;
}
|
tile.c |
/******************************************************************************
* INCLUDES
*****************************************************************************/
#include "tile.h"
#include "sort.h"
#include "timer.h"
#include "io.h"
#include "util.h"
#include "ccp/ccp.h"
/******************************************************************************
* PRIVATE FUNCTIONS
*****************************************************************************/
/**
* @brief Build a pointer structure (i.e. CSR rowptr) into the slabs of tt.
*
* @param inds Indices of just the slice ids.
* @param nnz The number of nonzeros (and thus slice ids).
* @param nslabs The number of slabs to construct.
*
* @return An array of length (nslabs+1) that points into inds and marks the
* start/end of each slab.
*/
static idx_t * p_mkslabptr(
idx_t const * const inds,
idx_t const nnz,
idx_t const nslabs)
{
idx_t * slabs = (idx_t *) calloc(nslabs+1, sizeof(idx_t));
/* make an offset ptr before prefix sum */
for(idx_t n=0; n < nnz; ++n) {
idx_t const slabid = inds[n] / TILE_SIZES[0];
slabs[1 + slabid] += 1;
}
for(idx_t s=1; s <= nslabs; ++s) {
slabs[s] += slabs[s-1];
}
return slabs;
}
/**
* @brief Construct a set of unique values (and counts) found within inds.
*
* @param inds The array of indices to tally.
* @param start The first index to tally.
* @param end The last index to tally.
* @param seen An array for marking the counts of each index that is found.
* NOTE: must at least as large as the largest index.
* @param uniques A sorted array of the unique indices found.
*
* @return The number of unique indices found in ind[start:end].
*/
static idx_t p_fill_uniques(
idx_t const * const inds,
idx_t const start,
idx_t const end,
idx_t * const seen,
idx_t * const uniques)
{
idx_t nuniques = 0;
for(idx_t n=start; n < end; ++n) {
idx_t const jj = inds[n];
/* mark ids and counts of all unique entries */
seen[jj] += 1;
if(seen[jj] == 1) {
uniques[nuniques++] = jj;
}
}
quicksort(uniques, nuniques);
return nuniques;
}
/**
* @brief Use the uniques/seen arrays to rearrange the nonzeros in a given into
* a tiled order. Slabs are already ordered after sorting, so this
* function will be used to first tile into 'tubes' and then finally into
* proper tiles.
*
* @param start The first nonzero in the working set.
* @param end The last nonzero in the working set.
* @param src The tensor to rearrange.
* @param dest A tensor to write the rearrange slab into.
* @param mode The mode to tile with.
* @param seen An array used to count the number of times each index appears in
* the mode.
* @param uniques An array used to mark the unique indices. Indexes into seen.
* @param nuniques The number of unique indices in the mode (between start/end).
* @param tsize The dimension of the tiles to construct.
*/
static void p_tile_uniques(
idx_t const start,
idx_t const end,
sptensor_t * const src,
sptensor_t * const dest,
idx_t const mode,
idx_t * const seen,
idx_t * const uniques,
idx_t const nuniques,
idx_t const tsize)
{
idx_t const ntubes = (nuniques / tsize) + (nuniques % tsize != 0);
idx_t * tmkr = (idx_t *) calloc(ntubes+1, sizeof(idx_t));
/* make a marker array so we can quickly move nnz into dest */
tmkr[0] = start;
for(idx_t n=0; n < nuniques; ++n) {
tmkr[1+(n / tsize)] += seen[uniques[n]];
}
for(idx_t t=1; t <= ntubes; ++t) {
tmkr[t] += tmkr[t-1];
}
/* reuse seen[] to map ind to unique id */
for(idx_t n=0; n < nuniques; ++n) {
seen[uniques[n]] = n;
}
/* place nnz */
idx_t const * const ind = src->ind[mode];
for(idx_t n=start; n < end; ++n) {
idx_t const index = tmkr[seen[ind[n]] / tsize];
for(idx_t m=0; m < src->nmodes; ++m) {
dest->ind[m][index] = src->ind[m][n];
}
dest->vals[index] = src->vals[n];
tmkr[seen[ind[n]] / tsize] += 1;
}
free(tmkr);
}
/**
* @brief Empty a set of unique indices and their counts. Scales with the number
* of uniques, not the size of the arrays!
*
* @param seen The count for each unique index.
* @param uniques The index of each unique value. Used to index into seen.
* @param nuniques The number of uniques to clear.
*/
static void p_clear_uniques(
idx_t * const seen,
idx_t * const uniques,
idx_t const nuniques)
{
for(idx_t n=0; n < nuniques; ++n) {
seen[uniques[n]] = 0;
uniques[n] = 0;
}
}
/**
* @brief Rearrange nonzeros into a tiled slab.
*
* @param start The first nonzero in the slab.
* @param end The last nonzero in the slab.
* @param tt The tensor to rearrange.
* @param tt_buf A tensor to use for double-buffering when rearranging.
* @param dim_perm The mode permutation to tile with.
* @param seen An array *for each mode* used to count the number of times each
* index appears in the slab.
* @param uniques An array *for each mode* used to mark the unique indices. Used
* to index into seen.
* @param nuniques An idx_t for each mode to count the unique indices in the
* slab.
*/
static void p_pack_slab(
idx_t const start,
idx_t const end,
sptensor_t * const tt,
sptensor_t * const tt_buf,
idx_t const * const dim_perm,
idx_t * const * const seen,
idx_t * const * const uniques,
idx_t * const nuniques)
{
idx_t const fibmode = dim_perm[1];
idx_t const idxmode = dim_perm[2];
/* get unique fibers */
nuniques[fibmode] = p_fill_uniques(tt->ind[fibmode], start, end,
seen[fibmode], uniques[fibmode]);
p_tile_uniques(start, end, tt, tt_buf, fibmode, seen[fibmode],
uniques[fibmode], nuniques[fibmode], TILE_SIZES[1]);
/* get unique idxs */
nuniques[idxmode] = p_fill_uniques(tt_buf->ind[idxmode], start, end,
seen[idxmode], uniques[idxmode]);
p_tile_uniques(start, end, tt_buf, tt, idxmode, seen[idxmode],
uniques[idxmode], nuniques[idxmode], TILE_SIZES[2]);
/* Clear out uniques for next slab. Complexity is #uniques, not dimension
* of tensor... */
p_clear_uniques(seen[fibmode], uniques[fibmode], nuniques[fibmode]);
p_clear_uniques(seen[idxmode], uniques[idxmode], nuniques[idxmode]);
}
/******************************************************************************
* PUBLIC FUNCTIONS
*****************************************************************************/
void tt_tile(
sptensor_t * const tt,
idx_t * dim_perm)
{
timer_start(&timers[TIMER_TILE]);
idx_t const nslices = tt->dims[dim_perm[0]];
idx_t const nslabs = (nslices / TILE_SIZES[0]) +
(nslices % TILE_SIZES[0] != 0);
tt_sort(tt, dim_perm[0], dim_perm);
sptensor_t * tt_buf = tt_alloc(tt->nnz, tt->nmodes);
for(idx_t m=0; m < tt->nmodes; ++m) {
tt_buf->dims[m] = tt->dims[m];
}
/* fill in slabs */
idx_t * slabptr = p_mkslabptr(tt->ind[dim_perm[0]], tt->nnz, nslabs);
/* seen and uniques are used to mark unique idxs in each slab */
idx_t * seen[MAX_NMODES];
idx_t * uniques[MAX_NMODES];
idx_t nuniques[MAX_NMODES];
for(idx_t m=1; m < tt->nmodes; ++m) {
seen[dim_perm[m]] = (idx_t *) calloc(tt->dims[dim_perm[m]], sizeof(idx_t));
uniques[dim_perm[m]] = (idx_t *) calloc(tt->dims[dim_perm[m]], sizeof(idx_t));
}
/* tile each slab of nonzeros */
for(idx_t s=0; s < nslabs; ++s) {
idx_t const start = slabptr[s];
idx_t const end = slabptr[s+1];
p_pack_slab(start, end, tt, tt_buf, dim_perm, seen, uniques, nuniques);
}
for(idx_t m=1; m < tt->nmodes; ++m) {
free(seen[dim_perm[m]]);
free(uniques[dim_perm[m]]);
}
tt_free(tt_buf);
free(slabptr);
timer_stop(&timers[TIMER_TILE]);
}
idx_t * tt_densetile(
sptensor_t * const tt,
idx_t const * const tile_dims)
{
idx_t const nmodes = tt->nmodes;
idx_t ntiles = 1;
for(idx_t m=0; m < nmodes; ++m) {
ntiles *= tile_dims[m];
}
/* the actual number of indices to place in each tile */
idx_t tsizes[MAX_NMODES];
for(idx_t m=0; m < nmodes; ++m) {
tsizes[m] = SS_MAX(tt->dims[m] / tile_dims[m], 1);
}
idx_t * tcounts = calloc(ntiles+2, sizeof(*tcounts));
#pragma omp parallel
{
/* count tile sizes (in nnz) */
idx_t coord[MAX_NMODES];
#pragma omp for schedule(static)
for(idx_t x=0; x < tt->nnz; ++x) {
for(idx_t m=0; m < nmodes; ++m) {
/* capping at dims-1 fixes overflow when dims don't divide evenly */
coord[m] = SS_MIN(tt->ind[m][x] / tsizes[m], tile_dims[m]-1);
}
/* offset by 1 to make prefix sum easy */
idx_t const id = get_tile_id(tile_dims, nmodes, coord);
assert(id < ntiles);
#pragma omp atomic
++tcounts[2+id];
}
} /* omp parallel */
/* prefix sum */
for(idx_t t=3; t <= ntiles+1; ++t) {
tcounts[t] += tcounts[t-1];
}
sptensor_t * newtt = tt_alloc(tt->nnz, tt->nmodes);
/* copy old tensor into new tiled one */
idx_t coord[MAX_NMODES];
for(idx_t x=0; x < tt->nnz; ++x) {
for(idx_t m=0; m < nmodes; ++m) {
coord[m] = SS_MIN(tt->ind[m][x] / tsizes[m], tile_dims[m]-1);
}
/* offset by 1 to make prefix sum easy */
idx_t const id = get_tile_id(tile_dims, nmodes, coord);
assert(id < ntiles);
idx_t newidx = tcounts[id+1]++;
newtt->vals[newidx] = tt->vals[x];
for(idx_t m=0; m < nmodes; ++m) {
newtt->ind[m][newidx] = tt->ind[m][x];
}
}
/* copy data into old struct */
par_memcpy(tt->vals, newtt->vals, tt->nnz * sizeof(val_t));
for(idx_t m=0; m < nmodes; ++m) {
par_memcpy(tt->ind[m], newtt->ind[m], tt->nnz * sizeof(idx_t));
}
tt_free(newtt);
return tcounts;
}
idx_t * tt_ccptile(
sptensor_t * const tt,
idx_t const * const tile_dims)
{
idx_t const nmodes = tt->nmodes;
idx_t * hist[MAX_NMODES];
idx_t * parts[MAX_NMODES];
idx_t ntiles = 1;
for(idx_t m=0; m < nmodes; ++m) {
ntiles *= tile_dims[m];
hist[m] = calloc(tt->dims[m], sizeof(**hist));
parts[m] = splatt_malloc((tile_dims[m]+1) * sizeof(**parts));
}
idx_t * tcounts = calloc(ntiles+2, sizeof(*tcounts));
#pragma omp parallel
{
/* compute a histogram for each mode */
for(idx_t m=0; m < nmodes; ++m) {
idx_t const * const inds = tt->ind[m];
idx_t * const hgram = hist[m];
#pragma omp for schedule(static) nowait
for(idx_t x=0; x < tt->nnz; ++x) {
#pragma omp atomic
++hgram[inds[x]];
}
}
#pragma omp barrier
/* now use CCP to partition each mode into tiles */
#pragma omp for schedule(static, 1)
for(idx_t m=0; m < nmodes; ++m) {
partition_1d(hist[m], tt->dims[m], parts[m], tile_dims[m]);
}
/* now go back over and count nnz per m-D tile */
idx_t coord[MAX_NMODES];
#pragma omp for schedule(dynamic, 32)
for(idx_t x=0; x < tt->nnz; ++x) {
/* map nnz to tile coords */
for(idx_t m=0; m < nmodes; ++m) {
/* TODO: Binary search. But, tile_dims[m] is usually going to be pretty
* small, so this is low priority? */
for(idx_t p=0; p < tile_dims[m]; ++p) {
if(parts[m][p+1] > tt->ind[m][x]) {
coord[m] = p;
break;
}
}
}
/* offset by 1 to make prefix sum easy */
idx_t const id = get_tile_id(tile_dims, nmodes, coord);
assert(id < ntiles);
#pragma omp atomic
++tcounts[2+id];
} /* foreach nnz */
} /* omp parallel */
/* prefix sum */
for(idx_t t=3; t <= ntiles+1; ++t) {
tcounts[t] += tcounts[t-1];
}
sptensor_t * newtt = tt_alloc(tt->nnz, tt->nmodes);
/* copy old tensor into new tiled one */
idx_t coord[MAX_NMODES];
for(idx_t x=0; x < tt->nnz; ++x) {
/* map nnz to linear tile ID, just like before */
for(idx_t m=0; m < nmodes; ++m) {
for(idx_t p=0; p < tile_dims[m]; ++p) {
if(parts[m][p+1] > tt->ind[m][x]) {
coord[m] = p;
break;
}
}
}
/* offset by 1 to make prefix sum easy */
idx_t const id = get_tile_id(tile_dims, nmodes, coord);
assert(id < ntiles);
idx_t newidx = tcounts[id+1]++;
newtt->vals[newidx] = tt->vals[x];
for(idx_t m=0; m < nmodes; ++m) {
newtt->ind[m][newidx] = tt->ind[m][x];
}
} /* foreach nnz */
/* copy data into old struct */
par_memcpy(tt->vals, newtt->vals, tt->nnz * sizeof(val_t));
for(idx_t m=0; m < nmodes; ++m) {
par_memcpy(tt->ind[m], newtt->ind[m], tt->nnz * sizeof(idx_t));
}
tt_free(newtt);
for(idx_t m=0; m < nmodes; ++m) {
free(hist[m]);
splatt_free(parts[m]);
}
return tcounts;
}
idx_t get_tile_id(
idx_t const * const tile_dims,
idx_t const nmodes,
idx_t const * const tile_coord)
{
idx_t id = 0;
idx_t mult = 1;
for(idx_t m=nmodes; m-- != 0;) {
id += tile_coord[m] * mult;
mult *= tile_dims[m];
}
/* bounds check */
if(id >= mult) {
id = TILE_ERR;
}
return id;
}
void fill_tile_coords(
idx_t const * const tile_dims,
idx_t const nmodes,
idx_t const tile_id,
idx_t * const tile_coord)
{
/* Check for invalid id first */
idx_t maxid = 1;
for(idx_t m=0; m < nmodes; ++m) {
maxid *= tile_dims[m];
}
if(tile_id >= maxid) {
for(idx_t m=0; m < nmodes; ++m) {
tile_coord[m] = tile_dims[m];
}
return;
}
/* test passed, convert! */
idx_t id = tile_id;
for(idx_t m = nmodes; m-- != 0; ) {
tile_coord[m] = id % tile_dims[m];
id /= tile_dims[m];
}
}
idx_t get_next_tileid(
idx_t const previd,
idx_t const * const tile_dims,
idx_t const nmodes,
idx_t const iter_mode,
idx_t const mode_idx)
{
idx_t maxid = 1;
idx_t coords[MAX_NMODES];
for(idx_t m=0; m < nmodes; ++m) {
coords[m] = 0;
maxid *= tile_dims[m];
}
if(previd == TILE_BEGIN) {
coords[iter_mode] = mode_idx;
return get_tile_id(tile_dims, nmodes, coords);
}
/* check for out of bounds */
if(previd >= maxid) {
return TILE_ERR;
}
/* convert previd to coords */
fill_tile_coords(tile_dims, nmodes, previd, coords);
/* overflowing this mode means TILE_END */
idx_t const overmode = (iter_mode == 0) ? 1 : 0;
/* increment least significant mode (unless we're iterating over it) and
* propagate overflows */
idx_t pmode = (iter_mode == nmodes-1) ? nmodes-2 : nmodes-1;
++coords[pmode];
while(coords[pmode] == tile_dims[pmode]) {
if(pmode == overmode) {
return TILE_END;
}
/* overflow this one too and move on */
coords[pmode] = 0;
--pmode;
/* we don't alter the mode we are iterating over */
if(pmode == iter_mode) {
/* XXX: checking for overmode should catch this */
assert(pmode > 0);
/* if we aren't at the end just skip over it */
--pmode;
}
/* we're now at a valid mode, carry over previous overflow */
++coords[pmode];
}
return get_tile_id(tile_dims, nmodes, coords);
}
|
colorspace.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% CCCC OOO L OOO RRRR SSSSS PPPP AAA CCCC EEEEE %
% C O O L O O R R SS P P A A C E %
% C O O L O O RRRR SSS PPPP AAAAA C EEE %
% C O O L O O R R SS P A A C E %
% CCCC OOO LLLLL OOO R R SSSSS P A A CCCC EEEEE %
% %
% %
% MagickCore Image Colorspace Methods %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/attribute.h"
#include "magick/cache.h"
#include "magick/cache-private.h"
#include "magick/cache-view.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/enhance.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/gem.h"
#include "magick/gem-private.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel-private.h"
#include "magick/property.h"
#include "magick/quantize.h"
#include "magick/quantum.h"
#include "magick/resource_.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/utility.h"
/*
Typedef declarations.
*/
typedef struct _TransformPacket
{
MagickRealType
x,
y,
z;
} TransformPacket;
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e C o l o r s p a c e T y p e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageColorspaceType() returns the potential colorspace of image:
% sRGBColorspaceType, RGBColorspaceType, GRAYColorspaceType, etc.
%
% To ensure the image type matches its potential, use SetImageColorspaceType():
%
% (void) SetImageColorspaceType(image,GetImageColorspaceType(image),
% exception);
%
% The format of the GetImageColorspaceType method is:
%
% ColorspaceType GetImageColorspaceType(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 ColorspaceType GetImageColorspaceType(const Image *image,
ExceptionInfo *exception)
{
ColorspaceType
colorspace;
ImageType
type;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
colorspace=image->colorspace;
type=IdentifyImageType(image,exception);
if ((type == BilevelType) || (type == GrayscaleType) ||
(type == GrayscaleMatteType))
colorspace=GRAYColorspace;
return(colorspace);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R G B T r a n s f o r m I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RGBTransformImage() converts the reference image from sRGB to an alternate
% colorspace. The transformation matrices are not the standard ones: the
% weights are rescaled to normalized the range of the transformed values to
% be [0..QuantumRange].
%
% The format of the RGBTransformImage method is:
%
% MagickBooleanType RGBTransformImage(Image *image,
% const ColorspaceType colorspace)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o colorspace: the colorspace to transform the image to.
%
*/
static inline void ConvertRGBToCMY(const Quantum red,const Quantum green,
const Quantum blue,double *cyan,double *magenta,double *yellow)
{
*cyan=QuantumScale*(QuantumRange-red);
*magenta=QuantumScale*(QuantumRange-green);
*yellow=QuantumScale*(QuantumRange-blue);
}
static void ConvertRGBToLab(const Quantum red,const Quantum green,
const Quantum blue,double *L,double *a,double *b)
{
double
X,
Y,
Z;
ConvertRGBToXYZ(red,green,blue,&X,&Y,&Z);
ConvertXYZToLab(X,Y,Z,L,a,b);
}
static inline void ConvertXYZToLMS(const double x,const double y,
const double z,double *L,double *M,double *S)
{
*L=0.7328*x+0.4296*y-0.1624*z;
*M=(-0.7036*x+1.6975*y+0.0061*z);
*S=0.0030*x+0.0136*y+0.9834*z;
}
static void ConvertRGBToLMS(const Quantum red,const Quantum green,
const Quantum blue,double *L,double *M,double *S)
{
double
X,
Y,
Z;
ConvertRGBToXYZ(red,green,blue,&X,&Y,&Z);
ConvertXYZToLMS(X,Y,Z,L,M,S);
}
static void ConvertRGBToLuv(const Quantum red,const Quantum green,
const Quantum blue,double *L,double *u,double *v)
{
double
X,
Y,
Z;
ConvertRGBToXYZ(red,green,blue,&X,&Y,&Z);
ConvertXYZToLuv(X,Y,Z,L,u,v);
}
static void ConvertRGBToxyY(const Quantum red,const Quantum green,
const Quantum blue,double *low_x,double *low_y,double *cap_Y)
{
double
gamma,
X,
Y,
Z;
ConvertRGBToXYZ(red,green,blue,&X,&Y,&Z);
gamma=PerceptibleReciprocal(X+Y+Z);
*low_x=gamma*X;
*low_y=gamma*Y;
*cap_Y=Y;
}
static void ConvertRGBToYPbPr(const Quantum red,const Quantum green,
const Quantum blue,double *Y,double *Pb,double *Pr)
{
*Y=QuantumScale*(0.298839*red+0.586811*green+0.114350*blue);
*Pb=QuantumScale*((-0.1687367)*red-0.331264*green+0.5*blue)+0.5;
*Pr=QuantumScale*(0.5*red-0.418688*green-0.081312*blue)+0.5;
}
static void ConvertRGBToYCbCr(const Quantum red,const Quantum green,
const Quantum blue,double *Y,double *Cb,double *Cr)
{
ConvertRGBToYPbPr(red,green,blue,Y,Cb,Cr);
}
static void ConvertRGBToYUV(const Quantum red,const Quantum green,
const Quantum blue,double *Y,double *U,double *V)
{
*Y=QuantumScale*(0.298839*red+0.586811*green+0.114350*blue);
*U=QuantumScale*((-0.147)*red-0.289*green+0.436*blue)+0.5;
*V=QuantumScale*(0.615*red-0.515*green-0.100*blue)+0.5;
}
static void ConvertRGBToYDbDr(const Quantum red,const Quantum green,
const Quantum blue,double *Y,double *Db,double *Dr)
{
*Y=QuantumScale*(0.298839*red+0.586811*green+0.114350*blue);
*Db=QuantumScale*(-0.450*red-0.883*green+1.333*blue)+0.5;
*Dr=QuantumScale*(-1.333*red+1.116*green+0.217*blue)+0.5;
}
static void ConvertRGBToYIQ(const Quantum red,const Quantum green,
const Quantum blue,double *Y,double *I,double *Q)
{
*Y=QuantumScale*(0.298839*red+0.586811*green+0.114350*blue);
*I=QuantumScale*(0.595716*red-0.274453*green-0.321263*blue)+0.5;
*Q=QuantumScale*(0.211456*red-0.522591*green+0.311135*blue)+0.5;
}
MagickExport MagickBooleanType RGBTransformImage(Image *image,
const ColorspaceType colorspace)
{
#define RGBTransformImageTag "RGBTransform/Image"
CacheView
*image_view;
ExceptionInfo
*exception;
MagickBooleanType
status;
MagickOffsetType
progress;
PrimaryInfo
primary_info;
register ssize_t
i;
ssize_t
y;
TransformPacket
*x_map,
*y_map,
*z_map;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(colorspace != sRGBColorspace);
assert(colorspace != TransparentColorspace);
assert(colorspace != UndefinedColorspace);
status=MagickTrue;
progress=0;
exception=(&image->exception);
switch (colorspace)
{
case CMYKColorspace:
{
MagickPixelPacket
zero;
/*
Convert RGB to CMYK colorspace.
*/
if (image->storage_class == PseudoClass)
{
if (SyncImage(image) == MagickFalse)
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
}
if (SetImageColorspace(image,colorspace) == MagickFalse)
return(MagickFalse);
GetMagickPixelPacket(image,&zero);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
MagickPixelPacket
pixel;
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
pixel=zero;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetMagickPixelPacket(image,q,indexes+x,&pixel);
pixel.red=(MagickRealType) pixel.red;
pixel.green=(MagickRealType) pixel.green;
pixel.blue=(MagickRealType) pixel.blue;
ConvertRGBToCMYK(&pixel);
SetPixelPacket(image,&pixel,q,indexes+x);
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
image->type=image->matte == MagickFalse ? ColorSeparationType :
ColorSeparationMatteType;
if (SetImageColorspace(image,colorspace) == MagickFalse)
return(MagickFalse);
return(status);
}
case LinearGRAYColorspace:
case GRAYColorspace:
{
/*
Transform image from sRGB to GRAY.
*/
if (image->storage_class == PseudoClass)
{
if (SyncImage(image) == MagickFalse)
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
}
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelGray(q,ClampToQuantum(GetPixelIntensity(image,q)));
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (SetImageColorspace(image,colorspace) == MagickFalse)
return(MagickFalse);
image->type=GrayscaleType;
return(status);
}
case CMYColorspace:
case HCLColorspace:
case HCLpColorspace:
case HSBColorspace:
case HSIColorspace:
case HSLColorspace:
case HSVColorspace:
case HWBColorspace:
case LabColorspace:
case LCHColorspace:
case LCHabColorspace:
case LCHuvColorspace:
case LMSColorspace:
case LuvColorspace:
case xyYColorspace:
case XYZColorspace:
case YCbCrColorspace:
case YDbDrColorspace:
case YIQColorspace:
case YPbPrColorspace:
case YUVColorspace:
{
/*
Transform image from sRGB to HSI.
*/
if (image->storage_class == PseudoClass)
{
if (SyncImage(image) == MagickFalse)
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
}
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
X,
Y,
Z;
Quantum
blue,
green,
red;
red=ClampToQuantum((MagickRealType) GetPixelRed(q));
green=ClampToQuantum((MagickRealType) GetPixelGreen(q));
blue=ClampToQuantum((MagickRealType) GetPixelBlue(q));
switch (colorspace)
{
case CMYColorspace:
{
ConvertRGBToCMY(red,green,blue,&X,&Y,&Z);
break;
}
case HCLColorspace:
{
ConvertRGBToHCL(red,green,blue,&X,&Y,&Z);
break;
}
case HCLpColorspace:
{
ConvertRGBToHCLp(red,green,blue,&X,&Y,&Z);
break;
}
case HSBColorspace:
{
ConvertRGBToHSB(red,green,blue,&X,&Y,&Z);
break;
}
case HSIColorspace:
{
ConvertRGBToHSI(red,green,blue,&X,&Y,&Z);
break;
}
case HSLColorspace:
{
ConvertRGBToHSL(red,green,blue,&X,&Y,&Z);
break;
}
case HSVColorspace:
{
ConvertRGBToHSV(red,green,blue,&X,&Y,&Z);
break;
}
case HWBColorspace:
{
ConvertRGBToHWB(red,green,blue,&X,&Y,&Z);
break;
}
case LabColorspace:
{
ConvertRGBToLab(red,green,blue,&X,&Y,&Z);
break;
}
case LCHColorspace:
case LCHabColorspace:
{
ConvertRGBToLCHab(red,green,blue,&X,&Y,&Z);
break;
}
case LCHuvColorspace:
{
ConvertRGBToLCHuv(red,green,blue,&X,&Y,&Z);
break;
}
case LMSColorspace:
{
ConvertRGBToLMS(red,green,blue,&X,&Y,&Z);
break;
}
case LuvColorspace:
{
ConvertRGBToLuv(red,green,blue,&X,&Y,&Z);
break;
}
case xyYColorspace:
{
ConvertRGBToxyY(red,green,blue,&X,&Y,&Z);
break;
}
case XYZColorspace:
{
ConvertRGBToXYZ(red,green,blue,&X,&Y,&Z);
break;
}
case YCbCrColorspace:
{
ConvertRGBToYCbCr(red,green,blue,&X,&Y,&Z);
break;
}
case YDbDrColorspace:
{
ConvertRGBToYDbDr(red,green,blue,&X,&Y,&Z);
break;
}
case YIQColorspace:
{
ConvertRGBToYIQ(red,green,blue,&X,&Y,&Z);
break;
}
case YPbPrColorspace:
{
ConvertRGBToYPbPr(red,green,blue,&X,&Y,&Z);
break;
}
case YUVColorspace:
{
ConvertRGBToYUV(red,green,blue,&X,&Y,&Z);
break;
}
default:
{
X=QuantumScale*red;
Y=QuantumScale*green;
Z=QuantumScale*blue;
break;
}
}
SetPixelRed(q,ClampToQuantum((MagickRealType) QuantumRange*X));
SetPixelGreen(q,ClampToQuantum((MagickRealType) QuantumRange*Y));
SetPixelBlue(q,ClampToQuantum((MagickRealType) QuantumRange*Z));
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (SetImageColorspace(image,colorspace) == MagickFalse)
return(MagickFalse);
return(status);
}
case LogColorspace:
{
#define DisplayGamma (1.0/1.7)
#define FilmGamma 0.6
#define ReferenceBlack 95.0
#define ReferenceWhite 685.0
const char
*value;
double
black,
density,
film_gamma,
gamma,
reference_black,
reference_white;
Quantum
*logmap;
/*
Transform RGB to Log colorspace.
*/
density=DisplayGamma;
gamma=DisplayGamma;
value=GetImageProperty(image,"gamma");
if (value != (const char *) NULL)
gamma=PerceptibleReciprocal(StringToDouble(value,(char **) NULL));
film_gamma=FilmGamma;
value=GetImageProperty(image,"film-gamma");
if (value != (const char *) NULL)
film_gamma=StringToDouble(value,(char **) NULL);
reference_black=ReferenceBlack;
value=GetImageProperty(image,"reference-black");
if (value != (const char *) NULL)
reference_black=StringToDouble(value,(char **) NULL);
reference_white=ReferenceWhite;
value=GetImageProperty(image,"reference-white");
if (value != (const char *) NULL)
reference_white=StringToDouble(value,(char **) NULL);
logmap=(Quantum *) AcquireQuantumMemory((size_t) MaxMap+1UL,
sizeof(*logmap));
if (logmap == (Quantum *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
black=pow(10.0,(reference_black-reference_white)*(gamma/density)*0.002/
film_gamma);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static)
#endif
for (i=0; i <= (ssize_t) MaxMap; i++)
logmap[i]=ScaleMapToQuantum((MagickRealType) (MaxMap*(reference_white+
log10(black+(1.0*i/MaxMap)*(1.0-black))/((gamma/density)*0.002/
film_gamma))/1024.0));
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=(ssize_t) image->columns; x != 0; x--)
{
Quantum
blue,
green,
red;
red=ClampToQuantum(DecodePixelGamma((MagickRealType)
GetPixelRed(q)));
green=ClampToQuantum(DecodePixelGamma((MagickRealType)
GetPixelGreen(q)));
blue=ClampToQuantum(DecodePixelGamma((MagickRealType)
GetPixelBlue(q)));
SetPixelRed(q,logmap[ScaleQuantumToMap(red)]);
SetPixelGreen(q,logmap[ScaleQuantumToMap(green)]);
SetPixelBlue(q,logmap[ScaleQuantumToMap(blue)]);
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
logmap=(Quantum *) RelinquishMagickMemory(logmap);
if (SetImageColorspace(image,colorspace) == MagickFalse)
return(MagickFalse);
return(status);
}
case RGBColorspace:
case scRGBColorspace:
{
/*
Transform image from sRGB to linear RGB.
*/
if (image->storage_class == PseudoClass)
{
if (SyncImage(image) == MagickFalse)
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
}
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
Quantum
blue,
green,
red;
red=ClampToQuantum(DecodePixelGamma((MagickRealType)
GetPixelRed(q)));
green=ClampToQuantum(DecodePixelGamma((MagickRealType)
GetPixelGreen(q)));
blue=ClampToQuantum(DecodePixelGamma((MagickRealType)
GetPixelBlue(q)));
SetPixelRed(q,red);
SetPixelGreen(q,green);
SetPixelBlue(q,blue);
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (SetImageColorspace(image,colorspace) == MagickFalse)
return(MagickFalse);
return(status);
}
default:
break;
}
/*
Allocate the tables.
*/
x_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL,
sizeof(*x_map));
y_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL,
sizeof(*y_map));
z_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL,
sizeof(*z_map));
if ((x_map == (TransformPacket *) NULL) ||
(y_map == (TransformPacket *) NULL) ||
(z_map == (TransformPacket *) NULL))
{
if (x_map != (TransformPacket *) NULL)
x_map=(TransformPacket *) RelinquishMagickMemory(x_map);
if (y_map != (TransformPacket *) NULL)
y_map=(TransformPacket *) RelinquishMagickMemory(y_map);
if (z_map != (TransformPacket *) NULL)
z_map=(TransformPacket *) RelinquishMagickMemory(z_map);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) memset(&primary_info,0,sizeof(primary_info));
switch (colorspace)
{
case OHTAColorspace:
{
/*
Initialize OHTA tables:
I1 = 0.33333*R+0.33334*G+0.33333*B
I2 = 0.50000*R+0.00000*G-0.50000*B
I3 =-0.25000*R+0.50000*G-0.25000*B
I and Q, normally -0.5 through 0.5, are normalized to the range 0
through QuantumRange.
*/
primary_info.y=(double) (MaxMap+1.0)/2.0;
primary_info.z=(double) (MaxMap+1.0)/2.0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static)
#endif
for (i=0; i <= (ssize_t) MaxMap; i++)
{
x_map[i].x=(MagickRealType) (0.33333*(double) i);
y_map[i].x=(MagickRealType) (0.33334*(double) i);
z_map[i].x=(MagickRealType) (0.33333*(double) i);
x_map[i].y=(MagickRealType) (0.50000*(double) i);
y_map[i].y=(MagickRealType) (0.00000*(double) i);
z_map[i].y=(MagickRealType) (-0.50000*(double) i);
x_map[i].z=(MagickRealType) (-0.25000*(double) i);
y_map[i].z=(MagickRealType) (0.50000*(double) i);
z_map[i].z=(MagickRealType) (-0.25000*(double) i);
}
break;
}
case Rec601LumaColorspace:
{
/*
Initialize Rec601 luma tables:
G = 0.298839*R+0.586811*G+0.114350*B
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static)
#endif
for (i=0; i <= (ssize_t) MaxMap; i++)
{
x_map[i].x=(MagickRealType) (0.298839*(double) i);
y_map[i].x=(MagickRealType) (0.586811*(double) i);
z_map[i].x=(MagickRealType) (0.114350*(double) i);
x_map[i].y=(MagickRealType) (0.298839*(double) i);
y_map[i].y=(MagickRealType) (0.586811*(double) i);
z_map[i].y=(MagickRealType) (0.114350*(double) i);
x_map[i].z=(MagickRealType) (0.298839*(double) i);
y_map[i].z=(MagickRealType) (0.586811*(double) i);
z_map[i].z=(MagickRealType) (0.114350*(double) i);
}
break;
}
case Rec601YCbCrColorspace:
{
/*
Initialize YCbCr tables (ITU-R BT.601):
Y = 0.2988390*R+0.5868110*G+0.1143500*B
Cb= -0.1687367*R-0.3312640*G+0.5000000*B
Cr= 0.5000000*R-0.4186880*G-0.0813120*B
Cb and Cr, normally -0.5 through 0.5, are normalized to the range 0
through QuantumRange.
*/
primary_info.y=(double) (MaxMap+1.0)/2.0;
primary_info.z=(double) (MaxMap+1.0)/2.0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static)
#endif
for (i=0; i <= (ssize_t) MaxMap; i++)
{
x_map[i].x=(MagickRealType) (0.298839*(double) i);
y_map[i].x=(MagickRealType) (0.586811*(double) i);
z_map[i].x=(MagickRealType) (0.114350*(double) i);
x_map[i].y=(MagickRealType) (-0.1687367*(double) i);
y_map[i].y=(MagickRealType) (-0.331264*(double) i);
z_map[i].y=(MagickRealType) (0.500000*(double) i);
x_map[i].z=(MagickRealType) (0.500000*(double) i);
y_map[i].z=(MagickRealType) (-0.418688*(double) i);
z_map[i].z=(MagickRealType) (-0.081312*(double) i);
}
break;
}
case Rec709LumaColorspace:
{
/*
Initialize Rec709 luma tables:
G = 0.212656*R+0.715158*G+0.072186*B
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static)
#endif
for (i=0; i <= (ssize_t) MaxMap; i++)
{
x_map[i].x=(MagickRealType) (0.212656*(double) i);
y_map[i].x=(MagickRealType) (0.715158*(double) i);
z_map[i].x=(MagickRealType) (0.072186*(double) i);
x_map[i].y=(MagickRealType) (0.212656*(double) i);
y_map[i].y=(MagickRealType) (0.715158*(double) i);
z_map[i].y=(MagickRealType) (0.072186*(double) i);
x_map[i].z=(MagickRealType) (0.212656*(double) i);
y_map[i].z=(MagickRealType) (0.715158*(double) i);
z_map[i].z=(MagickRealType) (0.072186*(double) i);
}
break;
}
case Rec709YCbCrColorspace:
{
/*
Initialize YCbCr tables (ITU-R BT.709):
Y = 0.212656*R+0.715158*G+0.072186*B
Cb= -0.114572*R-0.385428*G+0.500000*B
Cr= 0.500000*R-0.454153*G-0.045847*B
Cb and Cr, normally -0.5 through 0.5, are normalized to the range 0
through QuantumRange.
*/
primary_info.y=(double) (MaxMap+1.0)/2.0;
primary_info.z=(double) (MaxMap+1.0)/2.0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static)
#endif
for (i=0; i <= (ssize_t) MaxMap; i++)
{
x_map[i].x=(MagickRealType) (0.212656*(double) i);
y_map[i].x=(MagickRealType) (0.715158*(double) i);
z_map[i].x=(MagickRealType) (0.072186*(double) i);
x_map[i].y=(MagickRealType) (-0.114572*(double) i);
y_map[i].y=(MagickRealType) (-0.385428*(double) i);
z_map[i].y=(MagickRealType) (0.500000*(double) i);
x_map[i].z=(MagickRealType) (0.500000*(double) i);
y_map[i].z=(MagickRealType) (-0.454153*(double) i);
z_map[i].z=(MagickRealType) (-0.045847*(double) i);
}
break;
}
case YCCColorspace:
{
/*
Initialize YCC tables:
Y = 0.298839*R+0.586811*G+0.114350*B
C1= -0.298839*R-0.586811*G+0.88600*B
C2= 0.70100*R-0.586811*G-0.114350*B
YCC is scaled by 1.3584. C1 zero is 156 and C2 is at 137.
*/
primary_info.y=(double) ScaleQuantumToMap(ScaleCharToQuantum(156));
primary_info.z=(double) ScaleQuantumToMap(ScaleCharToQuantum(137));
for (i=0; i <= (ssize_t) (0.018*MaxMap); i++)
{
x_map[i].x=0.005382*i;
y_map[i].x=0.010566*i;
z_map[i].x=0.002052*i;
x_map[i].y=(-0.003296)*i;
y_map[i].y=(-0.006471)*i;
z_map[i].y=0.009768*i;
x_map[i].z=0.009410*i;
y_map[i].z=(-0.007880)*i;
z_map[i].z=(-0.001530)*i;
}
for ( ; i <= (ssize_t) MaxMap; i++)
{
x_map[i].x=0.298839*(1.099*i-0.099);
y_map[i].x=0.586811*(1.099*i-0.099);
z_map[i].x=0.114350*(1.099*i-0.099);
x_map[i].y=(-0.298839)*(1.099*i-0.099);
y_map[i].y=(-0.586811)*(1.099*i-0.099);
z_map[i].y=0.88600*(1.099*i-0.099);
x_map[i].z=0.70100*(1.099*i-0.099);
y_map[i].z=(-0.586811)*(1.099*i-0.099);
z_map[i].z=(-0.114350)*(1.099*i-0.099);
}
break;
}
default:
{
/*
Linear conversion tables.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static)
#endif
for (i=0; i <= (ssize_t) MaxMap; i++)
{
x_map[i].x=(MagickRealType) (1.0*(double) i);
y_map[i].x=(MagickRealType) 0.0;
z_map[i].x=(MagickRealType) 0.0;
x_map[i].y=(MagickRealType) 0.0;
y_map[i].y=(MagickRealType) (1.0*(double) i);
z_map[i].y=(MagickRealType) 0.0;
x_map[i].z=(MagickRealType) 0.0;
y_map[i].z=(MagickRealType) 0.0;
z_map[i].z=(MagickRealType) (1.0*(double) i);
}
break;
}
}
/*
Convert from sRGB.
*/
switch (image->storage_class)
{
case DirectClass:
default:
{
/*
Convert DirectClass image.
*/
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
MagickPixelPacket
pixel;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
register size_t
blue,
green,
red;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
red=ScaleQuantumToMap(ClampToQuantum((MagickRealType)
GetPixelRed(q)));
green=ScaleQuantumToMap(ClampToQuantum((MagickRealType)
GetPixelGreen(q)));
blue=ScaleQuantumToMap(ClampToQuantum((MagickRealType)
GetPixelBlue(q)));
pixel.red=(x_map[red].x+y_map[green].x+z_map[blue].x)+
(MagickRealType) primary_info.x;
pixel.green=(x_map[red].y+y_map[green].y+z_map[blue].y)+
(MagickRealType) primary_info.y;
pixel.blue=(x_map[red].z+y_map[green].z+z_map[blue].z)+
(MagickRealType) primary_info.z;
SetPixelRed(q,ScaleMapToQuantum(pixel.red));
SetPixelGreen(q,ScaleMapToQuantum(pixel.green));
SetPixelBlue(q,ScaleMapToQuantum(pixel.blue));
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,RGBTransformImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
break;
}
case PseudoClass:
{
register size_t
blue,
green,
red;
/*
Convert PseudoClass image.
*/
for (i=0; i < (ssize_t) image->colors; i++)
{
MagickPixelPacket
pixel;
red=ScaleQuantumToMap(ClampToQuantum((MagickRealType)
image->colormap[i].red));
green=ScaleQuantumToMap(ClampToQuantum((MagickRealType)
image->colormap[i].green));
blue=ScaleQuantumToMap(ClampToQuantum((MagickRealType)
image->colormap[i].blue));
pixel.red=x_map[red].x+y_map[green].x+z_map[blue].x+primary_info.x;
pixel.green=x_map[red].y+y_map[green].y+z_map[blue].y+primary_info.y;
pixel.blue=x_map[red].z+y_map[green].z+z_map[blue].z+primary_info.z;
image->colormap[i].red=ScaleMapToQuantum(pixel.red);
image->colormap[i].green=ScaleMapToQuantum(pixel.green);
image->colormap[i].blue=ScaleMapToQuantum(pixel.blue);
}
(void) SyncImage(image);
break;
}
}
/*
Relinquish resources.
*/
z_map=(TransformPacket *) RelinquishMagickMemory(z_map);
y_map=(TransformPacket *) RelinquishMagickMemory(y_map);
x_map=(TransformPacket *) RelinquishMagickMemory(x_map);
if (SetImageColorspace(image,colorspace) == MagickFalse)
return(MagickFalse);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e C o l o r s p a c e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageColorspace() sets the colorspace member of the Image structure.
%
% The format of the SetImageColorspace method is:
%
% MagickBooleanType SetImageColorspace(Image *image,
% const ColorspaceType colorspace)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o colorspace: the colorspace.
%
*/
MagickExport MagickBooleanType SetImageColorspace(Image *image,
const ColorspaceType colorspace)
{
ImageType
type;
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->colorspace == colorspace)
return(MagickTrue);
image->colorspace=colorspace;
image->rendering_intent=UndefinedIntent;
image->gamma=1.000/2.200;
(void) memset(&image->chromaticity,0,sizeof(image->chromaticity));
type=image->type;
if (IsGrayColorspace(colorspace) != MagickFalse)
{
if (colorspace == LinearGRAYColorspace)
image->gamma=1.0;
type=GrayscaleType;
}
else
if ((IsRGBColorspace(colorspace) != MagickFalse) ||
(colorspace == XYZColorspace) || (colorspace == xyYColorspace))
image->gamma=1.0;
else
{
image->rendering_intent=PerceptualIntent;
image->chromaticity.red_primary.x=0.6400;
image->chromaticity.red_primary.y=0.3300;
image->chromaticity.red_primary.z=0.0300;
image->chromaticity.green_primary.x=0.3000;
image->chromaticity.green_primary.y=0.6000;
image->chromaticity.green_primary.z=0.1000;
image->chromaticity.blue_primary.x=0.1500;
image->chromaticity.blue_primary.y=0.0600;
image->chromaticity.blue_primary.z=0.7900;
image->chromaticity.white_point.x=0.3127;
image->chromaticity.white_point.y=0.3290;
image->chromaticity.white_point.z=0.3583;
}
status=SyncImagePixelCache(image,&image->exception);
image->type=type;
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e G r a y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageGray() returns MagickTrue if all the pixels in the image have the
% same red, green, and blue intensities and changes the type of the image to
% bi-level or grayscale.
%
% The format of the SetImageGray method is:
%
% MagickBooleanType SetImageGray(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 SetImageGray(Image *image,
ExceptionInfo *exception)
{
const char
*value;
CacheView
*image_view;
ImageType
type;
register const PixelPacket
*p;
register ssize_t
x;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if ((image->type == BilevelType) || (image->type == GrayscaleType) ||
(image->type == GrayscaleMatteType))
return(MagickTrue);
if ((IsGrayColorspace(image->colorspace) == MagickFalse) &&
(IssRGBCompatibleColorspace(image->colorspace) == MagickFalse))
return(MagickFalse);
value=GetImageProperty(image,"colorspace:auto-grayscale");
if (IsStringNotFalse(value) == MagickFalse)
return(MagickFalse);
type=BilevelType;
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsGrayPixel(p) == MagickFalse)
{
type=UndefinedType;
break;
}
if ((type == BilevelType) && (IsMonochromePixel(p) == MagickFalse))
type=GrayscaleType;
p++;
}
if (type == UndefinedType)
break;
}
image_view=DestroyCacheView(image_view);
if (type == UndefinedType)
return(MagickFalse);
image->colorspace=GRAYColorspace;
if (SyncImagePixelCache((Image *) image,exception) == MagickFalse)
return(MagickFalse);
image->type=type;
if ((type == GrayscaleType) && (image->matte != MagickFalse))
image->type=GrayscaleMatteType;
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e M o n o c h r o m e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageMonochrome() returns MagickTrue if all the pixels in the image have
% the same red, green, and blue intensities and the intensity is either
% 0 or QuantumRange and changes the type of the image to bi-level.
%
% The format of the SetImageMonochrome method is:
%
% MagickBooleanType SetImageMonochrome(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 SetImageMonochrome(Image *image,
ExceptionInfo *exception)
{
const char
*value;
CacheView
*image_view;
ImageType
type;
register ssize_t
x;
register const PixelPacket
*p;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->type == BilevelType)
return(MagickTrue);
if ((IsGrayColorspace(image->colorspace) == MagickFalse) &&
(IssRGBCompatibleColorspace(image->colorspace) == MagickFalse))
return(MagickFalse);
value=GetImageProperty(image,"colorspace:auto-grayscale");
if (IsStringNotFalse(value) == MagickFalse)
return(MagickFalse);
type=BilevelType;
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsMonochromePixel(p) == MagickFalse)
{
type=UndefinedType;
break;
}
p++;
}
if (type == UndefinedType)
break;
}
image_view=DestroyCacheView(image_view);
if (type == UndefinedType)
return(MagickFalse);
image->colorspace=GRAYColorspace;
if (SyncImagePixelCache((Image *) image,exception) == MagickFalse)
return(MagickFalse);
image->type=type;
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r a n s f o r m I m a g e C o l o r s p a c e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransformImageColorspace() transforms an image colorspace.
%
% The format of the TransformImageColorspace method is:
%
% MagickBooleanType TransformImageColorspace(Image *image,
% const ColorspaceType colorspace)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o colorspace: the colorspace.
%
*/
MagickExport MagickBooleanType TransformImageColorspace(Image *image,
const ColorspaceType colorspace)
{
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->colorspace == colorspace)
return(MagickTrue);
(void) DeleteImageProfile(image,"icc");
(void) DeleteImageProfile(image,"icm");
if (colorspace == LinearGRAYColorspace)
return(GrayscaleImage(image,Rec709LuminancePixelIntensityMethod));
if (colorspace == GRAYColorspace)
return(GrayscaleImage(image,Rec709LumaPixelIntensityMethod));
if (colorspace == UndefinedColorspace)
return(SetImageColorspace(image,colorspace));
/*
Convert the reference image from an alternate colorspace to sRGB.
*/
if (IssRGBColorspace(colorspace) != MagickFalse)
return(TransformRGBImage(image,image->colorspace));
status=MagickTrue;
if (IssRGBColorspace(image->colorspace) == MagickFalse)
status=TransformRGBImage(image,image->colorspace);
if (status == MagickFalse)
return(status);
/*
Convert the reference image from sRGB to an alternate colorspace.
*/
if (RGBTransformImage(image,colorspace) == MagickFalse)
status=MagickFalse;
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ T r a n s f o r m R G B I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransformRGBImage() converts the reference image from an alternate
% colorspace to sRGB. The transformation matrices are not the standard ones:
% the weights are rescaled to normalize the range of the transformed values to
% be [0..QuantumRange].
%
% The format of the TransformRGBImage method is:
%
% MagickBooleanType TransformRGBImage(Image *image,
% const ColorspaceType colorspace)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o colorspace: the colorspace to transform the image to.
%
*/
static inline void ConvertCMYToRGB(const double cyan,const double magenta,
const double yellow,Quantum *red,Quantum *green,Quantum *blue)
{
*red=ClampToQuantum(QuantumRange*(1.0-cyan));
*green=ClampToQuantum(QuantumRange*(1.0-magenta));
*blue=ClampToQuantum(QuantumRange*(1.0-yellow));
}
static inline void ConvertLMSToXYZ(const double L,const double M,const double S,
double *X,double *Y,double *Z)
{
*X=1.096123820835514*L-0.278869000218287*M+0.182745179382773*S;
*Y=0.454369041975359*L+0.473533154307412*M+0.072097803717229*S;
*Z=(-0.009627608738429)*L-0.005698031216113*M+1.015325639954543*S;
}
static inline void ConvertLMSToRGB(const double L,const double M,
const double S,Quantum *red,Quantum *green,Quantum *blue)
{
double
X,
Y,
Z;
ConvertLMSToXYZ(L,M,S,&X,&Y,&Z);
ConvertXYZToRGB(X,Y,Z,red,green,blue);
}
static inline void ConvertLuvToRGB(const double L,const double u,
const double v,Quantum *red,Quantum *green,Quantum *blue)
{
double
X,
Y,
Z;
ConvertLuvToXYZ(100.0*L,354.0*u-134.0,262.0*v-140.0,&X,&Y,&Z);
ConvertXYZToRGB(X,Y,Z,red,green,blue);
}
static inline ssize_t RoundToYCC(const MagickRealType value)
{
if (value <= 0.0)
return(0);
if (value >= 1388.0)
return(1388);
return((ssize_t) (value+0.5));
}
static inline void ConvertLabToRGB(const double L,const double a,
const double b,Quantum *red,Quantum *green,Quantum *blue)
{
double
X,
Y,
Z;
ConvertLabToXYZ(100.0*L,255.0*(a-0.5),255.0*(b-0.5),&X,&Y,&Z);
ConvertXYZToRGB(X,Y,Z,red,green,blue);
}
static inline void ConvertxyYToRGB(const double low_x,const double low_y,
const double cap_Y,Quantum *red,Quantum *green,Quantum *blue)
{
double
gamma,
X,
Y,
Z;
gamma=PerceptibleReciprocal(low_y);
X=gamma*cap_Y*low_x;
Y=cap_Y;
Z=gamma*cap_Y*(1.0-low_x-low_y);
ConvertXYZToRGB(X,Y,Z,red,green,blue);
}
static void ConvertYPbPrToRGB(const double Y,const double Pb,const double Pr,
Quantum *red,Quantum *green,Quantum *blue)
{
*red=ClampToQuantum(QuantumRange*(0.99999999999914679361*Y-
1.2188941887145875e-06*(Pb-0.5)+1.4019995886561440468*(Pr-0.5)));
*green=ClampToQuantum(QuantumRange*(0.99999975910502514331*Y-
0.34413567816504303521*(Pb-0.5)-0.71413649331646789076*(Pr-0.5)));
*blue=ClampToQuantum(QuantumRange*(1.00000124040004623180*Y+
1.77200006607230409200*(Pb-0.5)+2.1453384174593273e-06*(Pr-0.5)));
}
static void ConvertYCbCrToRGB(const double Y,const double Cb,
const double Cr,Quantum *red,Quantum *green,Quantum *blue)
{
ConvertYPbPrToRGB(Y,Cb,Cr,red,green,blue);
}
static void ConvertYDbDrToRGB(const double Y,const double Db,const double Dr,
Quantum *red,Quantum *green,Quantum *blue)
{
*red=ClampToQuantum(QuantumRange*(Y+9.2303716147657e-05*(Db-0.5)-
0.52591263066186533*(Dr-0.5)));
*green=ClampToQuantum(QuantumRange*(Y-0.12913289889050927*(Db-0.5)+
0.26789932820759876*(Dr-0.5)));
*blue=ClampToQuantum(QuantumRange*(Y+0.66467905997895482*(Db-0.5)-
7.9202543533108e-05*(Dr-0.5)));
}
static void ConvertYIQToRGB(const double Y,const double I,const double Q,
Quantum *red,Quantum *green,Quantum *blue)
{
*red=ClampToQuantum(QuantumRange*(Y+0.9562957197589482261*(I-0.5)+
0.6210244164652610754*(Q-0.5)));
*green=ClampToQuantum(QuantumRange*(Y-0.2721220993185104464*(I-0.5)-
0.6473805968256950427*(Q-0.5)));
*blue=ClampToQuantum(QuantumRange*(Y-1.1069890167364901945*(I-0.5)+
1.7046149983646481374*(Q-0.5)));
}
static void ConvertYUVToRGB(const double Y,const double U,const double V,
Quantum *red,Quantum *green,Quantum *blue)
{
*red=ClampToQuantum(QuantumRange*(Y-3.945707070708279e-05*(U-0.5)+
1.1398279671717170825*(V-0.5)));
*green=ClampToQuantum(QuantumRange*(Y-0.3946101641414141437*(U-0.5)-
0.5805003156565656797*(V-0.5)));
*blue=ClampToQuantum(QuantumRange*(Y+2.0319996843434342537*(U-0.5)-
4.813762626262513e-04*(V-0.5)));
}
MagickExport MagickBooleanType TransformRGBImage(Image *image,
const ColorspaceType colorspace)
{
#define TransformRGBImageTag "Transform/Image"
static const float
YCCMap[1389] =
{
0.000000, 0.000720f, 0.001441f, 0.002161f, 0.002882f, 0.003602f,
0.004323f, 0.005043f, 0.005764f, 0.006484f, 0.007205f, 0.007925f,
0.008646f, 0.009366f, 0.010086f, 0.010807f, 0.011527f, 0.012248f,
0.012968f, 0.013689f, 0.014409f, 0.015130f, 0.015850f, 0.016571f,
0.017291f, 0.018012f, 0.018732f, 0.019452f, 0.020173f, 0.020893f,
0.021614f, 0.022334f, 0.023055f, 0.023775f, 0.024496f, 0.025216f,
0.025937f, 0.026657f, 0.027378f, 0.028098f, 0.028818f, 0.029539f,
0.030259f, 0.030980f, 0.031700f, 0.032421f, 0.033141f, 0.033862f,
0.034582f, 0.035303f, 0.036023f, 0.036744f, 0.037464f, 0.038184f,
0.038905f, 0.039625f, 0.040346f, 0.041066f, 0.041787f, 0.042507f,
0.043228f, 0.043948f, 0.044669f, 0.045389f, 0.046110f, 0.046830f,
0.047550f, 0.048271f, 0.048991f, 0.049712f, 0.050432f, 0.051153f,
0.051873f, 0.052594f, 0.053314f, 0.054035f, 0.054755f, 0.055476f,
0.056196f, 0.056916f, 0.057637f, 0.058357f, 0.059078f, 0.059798f,
0.060519f, 0.061239f, 0.061960f, 0.062680f, 0.063401f, 0.064121f,
0.064842f, 0.065562f, 0.066282f, 0.067003f, 0.067723f, 0.068444f,
0.069164f, 0.069885f, 0.070605f, 0.071326f, 0.072046f, 0.072767f,
0.073487f, 0.074207f, 0.074928f, 0.075648f, 0.076369f, 0.077089f,
0.077810f, 0.078530f, 0.079251f, 0.079971f, 0.080692f, 0.081412f,
0.082133f, 0.082853f, 0.083573f, 0.084294f, 0.085014f, 0.085735f,
0.086455f, 0.087176f, 0.087896f, 0.088617f, 0.089337f, 0.090058f,
0.090778f, 0.091499f, 0.092219f, 0.092939f, 0.093660f, 0.094380f,
0.095101f, 0.095821f, 0.096542f, 0.097262f, 0.097983f, 0.098703f,
0.099424f, 0.100144f, 0.100865f, 0.101585f, 0.102305f, 0.103026f,
0.103746f, 0.104467f, 0.105187f, 0.105908f, 0.106628f, 0.107349f,
0.108069f, 0.108790f, 0.109510f, 0.110231f, 0.110951f, 0.111671f,
0.112392f, 0.113112f, 0.113833f, 0.114553f, 0.115274f, 0.115994f,
0.116715f, 0.117435f, 0.118156f, 0.118876f, 0.119597f, 0.120317f,
0.121037f, 0.121758f, 0.122478f, 0.123199f, 0.123919f, 0.124640f,
0.125360f, 0.126081f, 0.126801f, 0.127522f, 0.128242f, 0.128963f,
0.129683f, 0.130403f, 0.131124f, 0.131844f, 0.132565f, 0.133285f,
0.134006f, 0.134726f, 0.135447f, 0.136167f, 0.136888f, 0.137608f,
0.138329f, 0.139049f, 0.139769f, 0.140490f, 0.141210f, 0.141931f,
0.142651f, 0.143372f, 0.144092f, 0.144813f, 0.145533f, 0.146254f,
0.146974f, 0.147695f, 0.148415f, 0.149135f, 0.149856f, 0.150576f,
0.151297f, 0.152017f, 0.152738f, 0.153458f, 0.154179f, 0.154899f,
0.155620f, 0.156340f, 0.157061f, 0.157781f, 0.158501f, 0.159222f,
0.159942f, 0.160663f, 0.161383f, 0.162104f, 0.162824f, 0.163545f,
0.164265f, 0.164986f, 0.165706f, 0.166427f, 0.167147f, 0.167867f,
0.168588f, 0.169308f, 0.170029f, 0.170749f, 0.171470f, 0.172190f,
0.172911f, 0.173631f, 0.174352f, 0.175072f, 0.175793f, 0.176513f,
0.177233f, 0.177954f, 0.178674f, 0.179395f, 0.180115f, 0.180836f,
0.181556f, 0.182277f, 0.182997f, 0.183718f, 0.184438f, 0.185159f,
0.185879f, 0.186599f, 0.187320f, 0.188040f, 0.188761f, 0.189481f,
0.190202f, 0.190922f, 0.191643f, 0.192363f, 0.193084f, 0.193804f,
0.194524f, 0.195245f, 0.195965f, 0.196686f, 0.197406f, 0.198127f,
0.198847f, 0.199568f, 0.200288f, 0.201009f, 0.201729f, 0.202450f,
0.203170f, 0.203890f, 0.204611f, 0.205331f, 0.206052f, 0.206772f,
0.207493f, 0.208213f, 0.208934f, 0.209654f, 0.210375f, 0.211095f,
0.211816f, 0.212536f, 0.213256f, 0.213977f, 0.214697f, 0.215418f,
0.216138f, 0.216859f, 0.217579f, 0.218300f, 0.219020f, 0.219741f,
0.220461f, 0.221182f, 0.221902f, 0.222622f, 0.223343f, 0.224063f,
0.224784f, 0.225504f, 0.226225f, 0.226945f, 0.227666f, 0.228386f,
0.229107f, 0.229827f, 0.230548f, 0.231268f, 0.231988f, 0.232709f,
0.233429f, 0.234150f, 0.234870f, 0.235591f, 0.236311f, 0.237032f,
0.237752f, 0.238473f, 0.239193f, 0.239914f, 0.240634f, 0.241354f,
0.242075f, 0.242795f, 0.243516f, 0.244236f, 0.244957f, 0.245677f,
0.246398f, 0.247118f, 0.247839f, 0.248559f, 0.249280f, 0.250000f,
0.250720f, 0.251441f, 0.252161f, 0.252882f, 0.253602f, 0.254323f,
0.255043f, 0.255764f, 0.256484f, 0.257205f, 0.257925f, 0.258646f,
0.259366f, 0.260086f, 0.260807f, 0.261527f, 0.262248f, 0.262968f,
0.263689f, 0.264409f, 0.265130f, 0.265850f, 0.266571f, 0.267291f,
0.268012f, 0.268732f, 0.269452f, 0.270173f, 0.270893f, 0.271614f,
0.272334f, 0.273055f, 0.273775f, 0.274496f, 0.275216f, 0.275937f,
0.276657f, 0.277378f, 0.278098f, 0.278818f, 0.279539f, 0.280259f,
0.280980f, 0.281700f, 0.282421f, 0.283141f, 0.283862f, 0.284582f,
0.285303f, 0.286023f, 0.286744f, 0.287464f, 0.288184f, 0.288905f,
0.289625f, 0.290346f, 0.291066f, 0.291787f, 0.292507f, 0.293228f,
0.293948f, 0.294669f, 0.295389f, 0.296109f, 0.296830f, 0.297550f,
0.298271f, 0.298991f, 0.299712f, 0.300432f, 0.301153f, 0.301873f,
0.302594f, 0.303314f, 0.304035f, 0.304755f, 0.305476f, 0.306196f,
0.306916f, 0.307637f, 0.308357f, 0.309078f, 0.309798f, 0.310519f,
0.311239f, 0.311960f, 0.312680f, 0.313401f, 0.314121f, 0.314842f,
0.315562f, 0.316282f, 0.317003f, 0.317723f, 0.318444f, 0.319164f,
0.319885f, 0.320605f, 0.321326f, 0.322046f, 0.322767f, 0.323487f,
0.324207f, 0.324928f, 0.325648f, 0.326369f, 0.327089f, 0.327810f,
0.328530f, 0.329251f, 0.329971f, 0.330692f, 0.331412f, 0.332133f,
0.332853f, 0.333573f, 0.334294f, 0.335014f, 0.335735f, 0.336455f,
0.337176f, 0.337896f, 0.338617f, 0.339337f, 0.340058f, 0.340778f,
0.341499f, 0.342219f, 0.342939f, 0.343660f, 0.344380f, 0.345101f,
0.345821f, 0.346542f, 0.347262f, 0.347983f, 0.348703f, 0.349424f,
0.350144f, 0.350865f, 0.351585f, 0.352305f, 0.353026f, 0.353746f,
0.354467f, 0.355187f, 0.355908f, 0.356628f, 0.357349f, 0.358069f,
0.358790f, 0.359510f, 0.360231f, 0.360951f, 0.361671f, 0.362392f,
0.363112f, 0.363833f, 0.364553f, 0.365274f, 0.365994f, 0.366715f,
0.367435f, 0.368156f, 0.368876f, 0.369597f, 0.370317f, 0.371037f,
0.371758f, 0.372478f, 0.373199f, 0.373919f, 0.374640f, 0.375360f,
0.376081f, 0.376801f, 0.377522f, 0.378242f, 0.378963f, 0.379683f,
0.380403f, 0.381124f, 0.381844f, 0.382565f, 0.383285f, 0.384006f,
0.384726f, 0.385447f, 0.386167f, 0.386888f, 0.387608f, 0.388329f,
0.389049f, 0.389769f, 0.390490f, 0.391210f, 0.391931f, 0.392651f,
0.393372f, 0.394092f, 0.394813f, 0.395533f, 0.396254f, 0.396974f,
0.397695f, 0.398415f, 0.399135f, 0.399856f, 0.400576f, 0.401297f,
0.402017f, 0.402738f, 0.403458f, 0.404179f, 0.404899f, 0.405620f,
0.406340f, 0.407061f, 0.407781f, 0.408501f, 0.409222f, 0.409942f,
0.410663f, 0.411383f, 0.412104f, 0.412824f, 0.413545f, 0.414265f,
0.414986f, 0.415706f, 0.416427f, 0.417147f, 0.417867f, 0.418588f,
0.419308f, 0.420029f, 0.420749f, 0.421470f, 0.422190f, 0.422911f,
0.423631f, 0.424352f, 0.425072f, 0.425793f, 0.426513f, 0.427233f,
0.427954f, 0.428674f, 0.429395f, 0.430115f, 0.430836f, 0.431556f,
0.432277f, 0.432997f, 0.433718f, 0.434438f, 0.435158f, 0.435879f,
0.436599f, 0.437320f, 0.438040f, 0.438761f, 0.439481f, 0.440202f,
0.440922f, 0.441643f, 0.442363f, 0.443084f, 0.443804f, 0.444524f,
0.445245f, 0.445965f, 0.446686f, 0.447406f, 0.448127f, 0.448847f,
0.449568f, 0.450288f, 0.451009f, 0.451729f, 0.452450f, 0.453170f,
0.453891f, 0.454611f, 0.455331f, 0.456052f, 0.456772f, 0.457493f,
0.458213f, 0.458934f, 0.459654f, 0.460375f, 0.461095f, 0.461816f,
0.462536f, 0.463256f, 0.463977f, 0.464697f, 0.465418f, 0.466138f,
0.466859f, 0.467579f, 0.468300f, 0.469020f, 0.469741f, 0.470461f,
0.471182f, 0.471902f, 0.472622f, 0.473343f, 0.474063f, 0.474784f,
0.475504f, 0.476225f, 0.476945f, 0.477666f, 0.478386f, 0.479107f,
0.479827f, 0.480548f, 0.481268f, 0.481988f, 0.482709f, 0.483429f,
0.484150f, 0.484870f, 0.485591f, 0.486311f, 0.487032f, 0.487752f,
0.488473f, 0.489193f, 0.489914f, 0.490634f, 0.491354f, 0.492075f,
0.492795f, 0.493516f, 0.494236f, 0.494957f, 0.495677f, 0.496398f,
0.497118f, 0.497839f, 0.498559f, 0.499280f, 0.500000f, 0.500720f,
0.501441f, 0.502161f, 0.502882f, 0.503602f, 0.504323f, 0.505043f,
0.505764f, 0.506484f, 0.507205f, 0.507925f, 0.508646f, 0.509366f,
0.510086f, 0.510807f, 0.511527f, 0.512248f, 0.512968f, 0.513689f,
0.514409f, 0.515130f, 0.515850f, 0.516571f, 0.517291f, 0.518012f,
0.518732f, 0.519452f, 0.520173f, 0.520893f, 0.521614f, 0.522334f,
0.523055f, 0.523775f, 0.524496f, 0.525216f, 0.525937f, 0.526657f,
0.527378f, 0.528098f, 0.528818f, 0.529539f, 0.530259f, 0.530980f,
0.531700f, 0.532421f, 0.533141f, 0.533862f, 0.534582f, 0.535303f,
0.536023f, 0.536744f, 0.537464f, 0.538184f, 0.538905f, 0.539625f,
0.540346f, 0.541066f, 0.541787f, 0.542507f, 0.543228f, 0.543948f,
0.544669f, 0.545389f, 0.546109f, 0.546830f, 0.547550f, 0.548271f,
0.548991f, 0.549712f, 0.550432f, 0.551153f, 0.551873f, 0.552594f,
0.553314f, 0.554035f, 0.554755f, 0.555476f, 0.556196f, 0.556916f,
0.557637f, 0.558357f, 0.559078f, 0.559798f, 0.560519f, 0.561239f,
0.561960f, 0.562680f, 0.563401f, 0.564121f, 0.564842f, 0.565562f,
0.566282f, 0.567003f, 0.567723f, 0.568444f, 0.569164f, 0.569885f,
0.570605f, 0.571326f, 0.572046f, 0.572767f, 0.573487f, 0.574207f,
0.574928f, 0.575648f, 0.576369f, 0.577089f, 0.577810f, 0.578530f,
0.579251f, 0.579971f, 0.580692f, 0.581412f, 0.582133f, 0.582853f,
0.583573f, 0.584294f, 0.585014f, 0.585735f, 0.586455f, 0.587176f,
0.587896f, 0.588617f, 0.589337f, 0.590058f, 0.590778f, 0.591499f,
0.592219f, 0.592939f, 0.593660f, 0.594380f, 0.595101f, 0.595821f,
0.596542f, 0.597262f, 0.597983f, 0.598703f, 0.599424f, 0.600144f,
0.600865f, 0.601585f, 0.602305f, 0.603026f, 0.603746f, 0.604467f,
0.605187f, 0.605908f, 0.606628f, 0.607349f, 0.608069f, 0.608790f,
0.609510f, 0.610231f, 0.610951f, 0.611671f, 0.612392f, 0.613112f,
0.613833f, 0.614553f, 0.615274f, 0.615994f, 0.616715f, 0.617435f,
0.618156f, 0.618876f, 0.619597f, 0.620317f, 0.621037f, 0.621758f,
0.622478f, 0.623199f, 0.623919f, 0.624640f, 0.625360f, 0.626081f,
0.626801f, 0.627522f, 0.628242f, 0.628963f, 0.629683f, 0.630403f,
0.631124f, 0.631844f, 0.632565f, 0.633285f, 0.634006f, 0.634726f,
0.635447f, 0.636167f, 0.636888f, 0.637608f, 0.638329f, 0.639049f,
0.639769f, 0.640490f, 0.641210f, 0.641931f, 0.642651f, 0.643372f,
0.644092f, 0.644813f, 0.645533f, 0.646254f, 0.646974f, 0.647695f,
0.648415f, 0.649135f, 0.649856f, 0.650576f, 0.651297f, 0.652017f,
0.652738f, 0.653458f, 0.654179f, 0.654899f, 0.655620f, 0.656340f,
0.657061f, 0.657781f, 0.658501f, 0.659222f, 0.659942f, 0.660663f,
0.661383f, 0.662104f, 0.662824f, 0.663545f, 0.664265f, 0.664986f,
0.665706f, 0.666427f, 0.667147f, 0.667867f, 0.668588f, 0.669308f,
0.670029f, 0.670749f, 0.671470f, 0.672190f, 0.672911f, 0.673631f,
0.674352f, 0.675072f, 0.675793f, 0.676513f, 0.677233f, 0.677954f,
0.678674f, 0.679395f, 0.680115f, 0.680836f, 0.681556f, 0.682277f,
0.682997f, 0.683718f, 0.684438f, 0.685158f, 0.685879f, 0.686599f,
0.687320f, 0.688040f, 0.688761f, 0.689481f, 0.690202f, 0.690922f,
0.691643f, 0.692363f, 0.693084f, 0.693804f, 0.694524f, 0.695245f,
0.695965f, 0.696686f, 0.697406f, 0.698127f, 0.698847f, 0.699568f,
0.700288f, 0.701009f, 0.701729f, 0.702450f, 0.703170f, 0.703891f,
0.704611f, 0.705331f, 0.706052f, 0.706772f, 0.707493f, 0.708213f,
0.708934f, 0.709654f, 0.710375f, 0.711095f, 0.711816f, 0.712536f,
0.713256f, 0.713977f, 0.714697f, 0.715418f, 0.716138f, 0.716859f,
0.717579f, 0.718300f, 0.719020f, 0.719741f, 0.720461f, 0.721182f,
0.721902f, 0.722622f, 0.723343f, 0.724063f, 0.724784f, 0.725504f,
0.726225f, 0.726945f, 0.727666f, 0.728386f, 0.729107f, 0.729827f,
0.730548f, 0.731268f, 0.731988f, 0.732709f, 0.733429f, 0.734150f,
0.734870f, 0.735591f, 0.736311f, 0.737032f, 0.737752f, 0.738473f,
0.739193f, 0.739914f, 0.740634f, 0.741354f, 0.742075f, 0.742795f,
0.743516f, 0.744236f, 0.744957f, 0.745677f, 0.746398f, 0.747118f,
0.747839f, 0.748559f, 0.749280f, 0.750000f, 0.750720f, 0.751441f,
0.752161f, 0.752882f, 0.753602f, 0.754323f, 0.755043f, 0.755764f,
0.756484f, 0.757205f, 0.757925f, 0.758646f, 0.759366f, 0.760086f,
0.760807f, 0.761527f, 0.762248f, 0.762968f, 0.763689f, 0.764409f,
0.765130f, 0.765850f, 0.766571f, 0.767291f, 0.768012f, 0.768732f,
0.769452f, 0.770173f, 0.770893f, 0.771614f, 0.772334f, 0.773055f,
0.773775f, 0.774496f, 0.775216f, 0.775937f, 0.776657f, 0.777378f,
0.778098f, 0.778818f, 0.779539f, 0.780259f, 0.780980f, 0.781700f,
0.782421f, 0.783141f, 0.783862f, 0.784582f, 0.785303f, 0.786023f,
0.786744f, 0.787464f, 0.788184f, 0.788905f, 0.789625f, 0.790346f,
0.791066f, 0.791787f, 0.792507f, 0.793228f, 0.793948f, 0.794669f,
0.795389f, 0.796109f, 0.796830f, 0.797550f, 0.798271f, 0.798991f,
0.799712f, 0.800432f, 0.801153f, 0.801873f, 0.802594f, 0.803314f,
0.804035f, 0.804755f, 0.805476f, 0.806196f, 0.806916f, 0.807637f,
0.808357f, 0.809078f, 0.809798f, 0.810519f, 0.811239f, 0.811960f,
0.812680f, 0.813401f, 0.814121f, 0.814842f, 0.815562f, 0.816282f,
0.817003f, 0.817723f, 0.818444f, 0.819164f, 0.819885f, 0.820605f,
0.821326f, 0.822046f, 0.822767f, 0.823487f, 0.824207f, 0.824928f,
0.825648f, 0.826369f, 0.827089f, 0.827810f, 0.828530f, 0.829251f,
0.829971f, 0.830692f, 0.831412f, 0.832133f, 0.832853f, 0.833573f,
0.834294f, 0.835014f, 0.835735f, 0.836455f, 0.837176f, 0.837896f,
0.838617f, 0.839337f, 0.840058f, 0.840778f, 0.841499f, 0.842219f,
0.842939f, 0.843660f, 0.844380f, 0.845101f, 0.845821f, 0.846542f,
0.847262f, 0.847983f, 0.848703f, 0.849424f, 0.850144f, 0.850865f,
0.851585f, 0.852305f, 0.853026f, 0.853746f, 0.854467f, 0.855187f,
0.855908f, 0.856628f, 0.857349f, 0.858069f, 0.858790f, 0.859510f,
0.860231f, 0.860951f, 0.861671f, 0.862392f, 0.863112f, 0.863833f,
0.864553f, 0.865274f, 0.865994f, 0.866715f, 0.867435f, 0.868156f,
0.868876f, 0.869597f, 0.870317f, 0.871037f, 0.871758f, 0.872478f,
0.873199f, 0.873919f, 0.874640f, 0.875360f, 0.876081f, 0.876801f,
0.877522f, 0.878242f, 0.878963f, 0.879683f, 0.880403f, 0.881124f,
0.881844f, 0.882565f, 0.883285f, 0.884006f, 0.884726f, 0.885447f,
0.886167f, 0.886888f, 0.887608f, 0.888329f, 0.889049f, 0.889769f,
0.890490f, 0.891210f, 0.891931f, 0.892651f, 0.893372f, 0.894092f,
0.894813f, 0.895533f, 0.896254f, 0.896974f, 0.897695f, 0.898415f,
0.899135f, 0.899856f, 0.900576f, 0.901297f, 0.902017f, 0.902738f,
0.903458f, 0.904179f, 0.904899f, 0.905620f, 0.906340f, 0.907061f,
0.907781f, 0.908501f, 0.909222f, 0.909942f, 0.910663f, 0.911383f,
0.912104f, 0.912824f, 0.913545f, 0.914265f, 0.914986f, 0.915706f,
0.916427f, 0.917147f, 0.917867f, 0.918588f, 0.919308f, 0.920029f,
0.920749f, 0.921470f, 0.922190f, 0.922911f, 0.923631f, 0.924352f,
0.925072f, 0.925793f, 0.926513f, 0.927233f, 0.927954f, 0.928674f,
0.929395f, 0.930115f, 0.930836f, 0.931556f, 0.932277f, 0.932997f,
0.933718f, 0.934438f, 0.935158f, 0.935879f, 0.936599f, 0.937320f,
0.938040f, 0.938761f, 0.939481f, 0.940202f, 0.940922f, 0.941643f,
0.942363f, 0.943084f, 0.943804f, 0.944524f, 0.945245f, 0.945965f,
0.946686f, 0.947406f, 0.948127f, 0.948847f, 0.949568f, 0.950288f,
0.951009f, 0.951729f, 0.952450f, 0.953170f, 0.953891f, 0.954611f,
0.955331f, 0.956052f, 0.956772f, 0.957493f, 0.958213f, 0.958934f,
0.959654f, 0.960375f, 0.961095f, 0.961816f, 0.962536f, 0.963256f,
0.963977f, 0.964697f, 0.965418f, 0.966138f, 0.966859f, 0.967579f,
0.968300f, 0.969020f, 0.969741f, 0.970461f, 0.971182f, 0.971902f,
0.972622f, 0.973343f, 0.974063f, 0.974784f, 0.975504f, 0.976225f,
0.976945f, 0.977666f, 0.978386f, 0.979107f, 0.979827f, 0.980548f,
0.981268f, 0.981988f, 0.982709f, 0.983429f, 0.984150f, 0.984870f,
0.985591f, 0.986311f, 0.987032f, 0.987752f, 0.988473f, 0.989193f,
0.989914f, 0.990634f, 0.991354f, 0.992075f, 0.992795f, 0.993516f,
0.994236f, 0.994957f, 0.995677f, 0.996398f, 0.997118f, 0.997839f,
0.998559f, 0.999280f, 1.000000
};
CacheView
*image_view;
ExceptionInfo
*exception;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
TransformPacket
*y_map,
*x_map,
*z_map;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=MagickTrue;
progress=0;
exception=(&image->exception);
switch (colorspace)
{
case CMYKColorspace:
{
MagickPixelPacket
zero;
/*
Transform image from CMYK to sRGB.
*/
if (image->storage_class == PseudoClass)
{
if (SyncImage(image) == MagickFalse)
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
}
GetMagickPixelPacket(image,&zero);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
MagickPixelPacket
pixel;
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
pixel=zero;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetMagickPixelPacket(image,q,indexes+x,&pixel);
ConvertCMYKToRGB(&pixel);
SetPixelPacket(image,&pixel,q,indexes+x);
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (SetImageColorspace(image,sRGBColorspace) == MagickFalse)
return(MagickFalse);
return(status);
}
case GRAYColorspace:
case Rec601LumaColorspace:
case Rec709LumaColorspace:
{
/*
Transform linear RGB to sRGB colorspace.
*/
if (image->storage_class == PseudoClass)
{
if (SyncImage(image) == MagickFalse)
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
}
if (SetImageColorspace(image,sRGBColorspace) == MagickFalse)
return(MagickFalse);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=(ssize_t) image->columns; x != 0; x--)
{
MagickRealType
gray;
gray=(MagickRealType) GetPixelGray(q);
if ((image->intensity == Rec601LuminancePixelIntensityMethod) ||
(image->intensity == Rec709LuminancePixelIntensityMethod))
gray=EncodePixelGamma(gray);
SetPixelRed(q,ClampToQuantum(gray));
SetPixelGreen(q,ClampToQuantum(gray));
SetPixelBlue(q,ClampToQuantum(gray));
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (SetImageColorspace(image,sRGBColorspace) == MagickFalse)
return(MagickFalse);
return(status);
}
case CMYColorspace:
case HCLColorspace:
case HCLpColorspace:
case HSBColorspace:
case HSIColorspace:
case HSLColorspace:
case HSVColorspace:
case HWBColorspace:
case LabColorspace:
case LCHColorspace:
case LCHabColorspace:
case LCHuvColorspace:
case LMSColorspace:
case LuvColorspace:
case xyYColorspace:
case XYZColorspace:
case YCbCrColorspace:
case YDbDrColorspace:
case YIQColorspace:
case YPbPrColorspace:
case YUVColorspace:
{
/*
Transform image from source colorspace to sRGB.
*/
if (image->storage_class == PseudoClass)
{
if (SyncImage(image) == MagickFalse)
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
}
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
X,
Y,
Z;
Quantum
blue,
green,
red;
X=QuantumScale*GetPixelRed(q);
Y=QuantumScale*GetPixelGreen(q);
Z=QuantumScale*GetPixelBlue(q);
switch (colorspace)
{
case CMYColorspace:
{
ConvertCMYToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case HCLColorspace:
{
ConvertHCLToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case HCLpColorspace:
{
ConvertHCLpToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case HSBColorspace:
{
ConvertHSBToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case HSIColorspace:
{
ConvertHSIToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case HSLColorspace:
{
ConvertHSLToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case HSVColorspace:
{
ConvertHSVToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case HWBColorspace:
{
ConvertHWBToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case LabColorspace:
{
ConvertLabToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case LCHColorspace:
case LCHabColorspace:
{
ConvertLCHabToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case LCHuvColorspace:
{
ConvertLCHuvToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case LMSColorspace:
{
ConvertLMSToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case LuvColorspace:
{
ConvertLuvToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case xyYColorspace:
{
ConvertxyYToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case XYZColorspace:
{
ConvertXYZToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case YCbCrColorspace:
{
ConvertYCbCrToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case YDbDrColorspace:
{
ConvertYDbDrToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case YIQColorspace:
{
ConvertYIQToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case YPbPrColorspace:
{
ConvertYPbPrToRGB(X,Y,Z,&red,&green,&blue);
break;
}
case YUVColorspace:
{
ConvertYUVToRGB(X,Y,Z,&red,&green,&blue);
break;
}
default:
{
red=ClampToQuantum(QuantumRange*X);
green=ClampToQuantum(QuantumRange*Y);
blue=ClampToQuantum(QuantumRange*Z);
break;
}
}
SetPixelRed(q,ClampToQuantum((MagickRealType) red));
SetPixelGreen(q,ClampToQuantum((MagickRealType) green));
SetPixelBlue(q,ClampToQuantum((MagickRealType) blue));
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (SetImageColorspace(image,sRGBColorspace) == MagickFalse)
return(MagickFalse);
return(status);
}
case LogColorspace:
{
const char
*value;
double
black,
density,
film_gamma,
gamma,
reference_black,
reference_white;
Quantum
*logmap;
/*
Transform Log to sRGB colorspace.
*/
density=DisplayGamma;
gamma=DisplayGamma;
value=GetImageProperty(image,"gamma");
if (value != (const char *) NULL)
gamma=PerceptibleReciprocal(StringToDouble(value,(char **) NULL));
film_gamma=FilmGamma;
value=GetImageProperty(image,"film-gamma");
if (value != (const char *) NULL)
film_gamma=StringToDouble(value,(char **) NULL);
reference_black=ReferenceBlack;
value=GetImageProperty(image,"reference-black");
if (value != (const char *) NULL)
reference_black=StringToDouble(value,(char **) NULL);
reference_white=ReferenceWhite;
value=GetImageProperty(image,"reference-white");
if (value != (const char *) NULL)
reference_white=StringToDouble(value,(char **) NULL);
logmap=(Quantum *) AcquireQuantumMemory((size_t) MaxMap+1UL,
sizeof(*logmap));
if (logmap == (Quantum *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
black=pow(10.0,(reference_black-reference_white)*(gamma/density)*0.002/
film_gamma);
for (i=0; i <= (ssize_t) (reference_black*MaxMap/1024.0); i++)
logmap[i]=(Quantum) 0;
for ( ; i < (ssize_t) (reference_white*MaxMap/1024.0); i++)
logmap[i]=ClampToQuantum((MagickRealType) QuantumRange/(1.0-black)*
(pow(10.0,(1024.0*i/MaxMap-reference_white)*(gamma/density)*0.002/
film_gamma)-black));
for ( ; i <= (ssize_t) MaxMap; i++)
logmap[i]=QuantumRange;
if (image->storage_class == PseudoClass)
{
if (SyncImage(image) == MagickFalse)
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
}
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=(ssize_t) image->columns; x != 0; x--)
{
Quantum
blue,
green,
red;
red=ClampToQuantum(EncodePixelGamma((MagickRealType)
logmap[ScaleQuantumToMap(GetPixelRed(q))]));
green=ClampToQuantum(EncodePixelGamma((MagickRealType)
logmap[ScaleQuantumToMap(GetPixelGreen(q))]));
blue=ClampToQuantum(EncodePixelGamma((MagickRealType)
logmap[ScaleQuantumToMap(GetPixelBlue(q))]));
SetPixelRed(q,red);
SetPixelGreen(q,green);
SetPixelBlue(q,blue);
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
logmap=(Quantum *) RelinquishMagickMemory(logmap);
if (SetImageColorspace(image,sRGBColorspace) == MagickFalse)
return(MagickFalse);
return(status);
}
case RGBColorspace:
case scRGBColorspace:
{
/*
Transform linear RGB to sRGB colorspace.
*/
if (image->storage_class == PseudoClass)
{
if (SyncImage(image) == MagickFalse)
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
}
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=(ssize_t) image->columns; x != 0; x--)
{
Quantum
blue,
green,
red;
red=ClampToQuantum(EncodePixelGamma((MagickRealType) GetPixelRed(q)));
green=ClampToQuantum(EncodePixelGamma((MagickRealType)
GetPixelGreen(q)));
blue=ClampToQuantum(EncodePixelGamma((MagickRealType)
GetPixelBlue(q)));
SetPixelRed(q,red);
SetPixelGreen(q,green);
SetPixelBlue(q,blue);
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (SetImageColorspace(image,sRGBColorspace) == MagickFalse)
return(MagickFalse);
return(status);
}
default:
break;
}
/*
Allocate the tables.
*/
x_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL,
sizeof(*x_map));
y_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL,
sizeof(*y_map));
z_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL,
sizeof(*z_map));
if ((x_map == (TransformPacket *) NULL) ||
(y_map == (TransformPacket *) NULL) ||
(z_map == (TransformPacket *) NULL))
{
if (z_map != (TransformPacket *) NULL)
z_map=(TransformPacket *) RelinquishMagickMemory(z_map);
if (y_map != (TransformPacket *) NULL)
y_map=(TransformPacket *) RelinquishMagickMemory(y_map);
if (x_map != (TransformPacket *) NULL)
x_map=(TransformPacket *) RelinquishMagickMemory(x_map);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
switch (colorspace)
{
case OHTAColorspace:
{
/*
Initialize OHTA tables:
R = I1+1.00000*I2-0.66668*I3
G = I1+0.00000*I2+1.33333*I3
B = I1-1.00000*I2-0.66668*I3
I and Q, normally -0.5 through 0.5, must be normalized to the range 0
through QuantumRange.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static)
#endif
for (i=0; i <= (ssize_t) MaxMap; i++)
{
x_map[i].x=(1.0*(double) i);
y_map[i].x=(0.5*1.00000*(2.0*(double) i-MaxMap));
z_map[i].x=(-0.5*0.66668*(2.0*(double) i-MaxMap));
x_map[i].y=(1.0*(double) i);
y_map[i].y=(0.5*0.00000*(2.0*(double) i-MaxMap));
z_map[i].y=(0.5*1.33333*(2.0*(double) i-MaxMap));
x_map[i].z=(1.0*(double) i);
y_map[i].z=(-0.5*1.00000*(2.0*(double) i-MaxMap));
z_map[i].z=(-0.5*0.66668*(2.0*(double) i-MaxMap));
}
break;
}
case Rec601YCbCrColorspace:
{
/*
Initialize YCbCr tables:
R = Y +1.402000*Cr
G = Y-0.344136*Cb-0.714136*Cr
B = Y+1.772000*Cb
Cb and Cr, normally -0.5 through 0.5, must be normalized to the range 0
through QuantumRange.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static)
#endif
for (i=0; i <= (ssize_t) MaxMap; i++)
{
x_map[i].x=0.99999999999914679361*(double) i;
y_map[i].x=0.5*(-1.2188941887145875e-06)*(2.00*(double) i-MaxMap);
z_map[i].x=0.5*1.4019995886561440468*(2.00*(double) i-MaxMap);
x_map[i].y=0.99999975910502514331*(double) i;
y_map[i].y=0.5*(-0.34413567816504303521)*(2.00*(double) i-MaxMap);
z_map[i].y=0.5*(-0.71413649331646789076)*(2.00*(double) i-MaxMap);
x_map[i].z=1.00000124040004623180*(double) i;
y_map[i].z=0.5*1.77200006607230409200*(2.00*(double) i-MaxMap);
z_map[i].z=0.5*2.1453384174593273e-06*(2.00*(double) i-MaxMap);
}
break;
}
case Rec709YCbCrColorspace:
{
/*
Initialize YCbCr tables:
R = Y +1.574800*Cr
G = Y-0.187324*Cb-0.468124*Cr
B = Y+1.855600*Cb
Cb and Cr, normally -0.5 through 0.5, must be normalized to the range 0
through QuantumRange.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static)
#endif
for (i=0; i <= (ssize_t) MaxMap; i++)
{
x_map[i].x=(MagickRealType) (1.0*(double) i);
y_map[i].x=(MagickRealType) (0.5*0.000000*(2.0*(double) i-MaxMap));
z_map[i].x=(MagickRealType) (0.5*1.574800*(2.0*(double) i-MaxMap));
x_map[i].y=(MagickRealType) (1.0*(double) i);
y_map[i].y=(MagickRealType) (0.5*(-0.187324)*(2.0*(double) i-MaxMap));
z_map[i].y=(MagickRealType) (0.5*(-0.468124)*(2.0*(double) i-MaxMap));
x_map[i].z=(MagickRealType) (1.0*(double) i);
y_map[i].z=(MagickRealType) (0.5*1.855600*(2.0*(double) i-MaxMap));
z_map[i].z=(MagickRealType) (0.5*0.000000*(2.0*(double) i-MaxMap));
}
break;
}
case YCCColorspace:
{
/*
Initialize YCC tables:
R = Y +1.340762*C2
G = Y-0.317038*C1-0.682243*C2
B = Y+1.632639*C1
YCC is scaled by 1.3584. C1 zero is 156 and C2 is at 137.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static)
#endif
for (i=0; i <= (ssize_t) MaxMap; i++)
{
x_map[i].x=(MagickRealType) (1.3584000*(double) i);
y_map[i].x=(MagickRealType) (0.0000000);
z_map[i].x=(MagickRealType) (1.8215000*((double) i-(MagickRealType)
ScaleQuantumToMap(ScaleCharToQuantum(137))));
x_map[i].y=(MagickRealType) (1.3584000*(double) i);
y_map[i].y=(MagickRealType) ((-0.4302726)*((double) i-(MagickRealType)
ScaleQuantumToMap(ScaleCharToQuantum(156))));
z_map[i].y=(MagickRealType) ((-0.9271435)*((double) i-(MagickRealType)
ScaleQuantumToMap(ScaleCharToQuantum(137))));
x_map[i].z=(MagickRealType) (1.3584000*(double) i);
y_map[i].z=(MagickRealType) (2.2179000*((double) i-(MagickRealType)
ScaleQuantumToMap(ScaleCharToQuantum(156))));
z_map[i].z=(MagickRealType) (0.0000000);
}
break;
}
default:
{
/*
Linear conversion tables.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static)
#endif
for (i=0; i <= (ssize_t) MaxMap; i++)
{
x_map[i].x=(MagickRealType) (1.0*(double) i);
y_map[i].x=(MagickRealType) 0.0;
z_map[i].x=(MagickRealType) 0.0;
x_map[i].y=(MagickRealType) 0.0;
y_map[i].y=(MagickRealType) (1.0*(double) i);
z_map[i].y=(MagickRealType) 0.0;
x_map[i].z=(MagickRealType) 0.0;
y_map[i].z=(MagickRealType) 0.0;
z_map[i].z=(MagickRealType) (1.0*(double) i);
}
break;
}
}
/*
Convert to sRGB.
*/
switch (image->storage_class)
{
case DirectClass:
default:
{
/*
Convert DirectClass image.
*/
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
MagickPixelPacket
pixel;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register size_t
blue,
green,
red;
red=ScaleQuantumToMap(GetPixelRed(q));
green=ScaleQuantumToMap(GetPixelGreen(q));
blue=ScaleQuantumToMap(GetPixelBlue(q));
pixel.red=x_map[red].x+y_map[green].x+z_map[blue].x;
pixel.green=x_map[red].y+y_map[green].y+z_map[blue].y;
pixel.blue=x_map[red].z+y_map[green].z+z_map[blue].z;
if (colorspace == YCCColorspace)
{
pixel.red=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.red/
(double) MaxMap)];
pixel.green=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.green/
(double) MaxMap)];
pixel.blue=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.blue/
(double) MaxMap)];
}
else
{
pixel.red=(MagickRealType) ScaleMapToQuantum(pixel.red);
pixel.green=(MagickRealType) ScaleMapToQuantum(pixel.green);
pixel.blue=(MagickRealType) ScaleMapToQuantum(pixel.blue);
}
SetPixelRed(q,ClampToQuantum(pixel.red));
SetPixelGreen(q,ClampToQuantum(pixel.green));
SetPixelBlue(q,ClampToQuantum(pixel.blue));
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,TransformRGBImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
break;
}
case PseudoClass:
{
/*
Convert PseudoClass image.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->colors,1)
#endif
for (i=0; i < (ssize_t) image->colors; i++)
{
MagickPixelPacket
pixel;
register size_t
blue,
green,
red;
red=ScaleQuantumToMap(image->colormap[i].red);
green=ScaleQuantumToMap(image->colormap[i].green);
blue=ScaleQuantumToMap(image->colormap[i].blue);
pixel.red=x_map[red].x+y_map[green].x+z_map[blue].x;
pixel.green=x_map[red].y+y_map[green].y+z_map[blue].y;
pixel.blue=x_map[red].z+y_map[green].z+z_map[blue].z;
if (colorspace == YCCColorspace)
{
pixel.red=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.red/
(double) MaxMap)];
pixel.green=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.green/
(double) MaxMap)];
pixel.blue=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.blue/
(double) MaxMap)];
}
else
{
pixel.red=(MagickRealType) ScaleMapToQuantum(pixel.red);
pixel.green=(MagickRealType) ScaleMapToQuantum(pixel.green);
pixel.blue=(MagickRealType) ScaleMapToQuantum(pixel.blue);
}
image->colormap[i].red=ClampToQuantum(pixel.red);
image->colormap[i].green=ClampToQuantum(pixel.green);
image->colormap[i].blue=ClampToQuantum(pixel.blue);
}
(void) SyncImage(image);
break;
}
}
/*
Relinquish resources.
*/
z_map=(TransformPacket *) RelinquishMagickMemory(z_map);
y_map=(TransformPacket *) RelinquishMagickMemory(y_map);
x_map=(TransformPacket *) RelinquishMagickMemory(x_map);
if (SetImageColorspace(image,sRGBColorspace) == MagickFalse)
return(MagickFalse);
return(MagickTrue);
}
|
explicit_strategy.h | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors:
//
#if !defined(EXPLICIT_STRATEGY)
#define EXPLICIT_STRATEGY
/* System includes */
#include <string>
#include <iostream>
#include <algorithm>
/////////#define _OPENMP
/* External includes */
#ifdef _OPENMP
#include <omp.h>
#endif
/* Project includes */
#include "includes/define.h"
#include "includes/model_part.h"
#include "includes/element.h"
#include "solving_strategies/strategies/solving_strategy.h"
#include "solving_strategies/schemes/scheme.h"
#include "includes/variables.h"
#include "containers/array_1d.h"
namespace Kratos
{
template<
class TSparseSpace,
class TDenseSpace,
class TLinearSolver>
class ExplicitStrategy : public SolvingStrategy<TSparseSpace,TDenseSpace,TLinearSolver>
{
public:
KRATOS_CLASS_POINTER_DEFINITION(ExplicitStrategy);
typedef SolvingStrategy<TSparseSpace,TDenseSpace,TLinearSolver> BaseType;
typedef typename BaseType::TDataType TDataType;
typedef TSparseSpace SparseSpaceType;
typedef typename BaseType::TBuilderAndSolverType TBuilderAndSolverType;
typedef typename BaseType::TSchemeType TSchemeType;
typedef typename BaseType::DofsArrayType DofsArrayType;
typedef typename Element::DofsVectorType DofsVectorType;
typedef typename BaseType::TSystemMatrixType TSystemMatrixType;
typedef typename BaseType::TSystemVectorType TSystemVectorType;
typedef typename BaseType::LocalSystemVectorType LocalSystemVectorType;
typedef typename BaseType::LocalSystemMatrixType LocalSystemMatrixType;
typedef ModelPart::NodesContainerType NodesArrayType;
typedef ModelPart::ElementsContainerType ElementsArrayType;
typedef ModelPart::ConditionsContainerType ConditionsArrayType;
typedef ModelPart::ConditionsContainerType::ContainerType ConditionsContainerType;
typedef ConditionsContainerType::iterator ConditionsContainerIterator;
typedef typename BaseType::TSystemMatrixPointerType TSystemMatrixPointerType;
typedef typename BaseType::TSystemVectorPointerType TSystemVectorPointerType;
typedef ModelPart::PropertiesType PropertiesType;
//typedef Element::Pointer ParticlePointer;
//typedef typename std::vector<ParticlePointer> ParticlePointerVector;
//typedef typename std::vector<ParticlePointer>::iterator ParticlePointerIterator;
//typedef GlobalPointersVector<Element > ParticleWeakVector;
//typedef GlobalPointersVector<Element >::iterator ParticleWeakIterator;
ExplicitStrategy(
ModelPart& model_part,
const int dimension,
const bool move_mesh_flag
)
: SolvingStrategy<TSparseSpace,TDenseSpace,TLinearSolver>(model_part, move_mesh_flag)
{
std::cout<< "*************************************"<< std::endl;
std::cout <<"* EXPLICIT CALCULATIONS STRATEGY *"<< std::endl;
std::cout<< "*************************************"<< std::endl;
}
~ExplicitStrategy () override {}
//***************************************************************************
//***************************************************************************
void AssembleLoop()
{
KRATOS_TRY
ModelPart& r_model_part = BaseType::GetModelPart();
ProcessInfo& CurrentProcessInfo = r_model_part.GetProcessInfo();
ElementsArrayType& pElements = r_model_part.Elements();
typename ElementsArrayType::iterator it_begin = pElements.ptr_begin() ;
typename ElementsArrayType::iterator it_end = pElements.ptr_end();
for (ElementsArrayType::iterator it = it_begin; it != it_end; ++it)
{
// Element::GeometryType& geom = it->GetGeometry();
//for (unsigned int i = 0; i < geom.size(); i++)
// geom(i)->SetLock();
it->AddExplicitContribution(CurrentProcessInfo);
//for (unsigned int i = 0; i < geom.size(); i++)
// geom(i)->UnSetLock();
}
KRATOS_CATCH("")
}
//***************************************************************************
//***************************************************************************
void NormalizeVariable(const Variable<array_1d<double, 3 > >& rRHSVariable, const Variable<double >& rNormalizationVariable)
{
KRATOS_TRY
ModelPart& r_model_part = BaseType::GetModelPart();
NodesArrayType& pNodes = r_model_part.Nodes();
//const double delta_t = CurrentProcessInfo.GetValue(DELTA_TIME); //included in factor
#ifdef _OPENMP
int number_of_threads = omp_get_max_threads();
#else
int number_of_threads = 1;
#endif
DenseVector<unsigned int> node_partition;
CreatePartition(number_of_threads, pNodes.size(), node_partition);
#pragma omp parallel for
for(int k=0; k<number_of_threads; k++)
{
typename NodesArrayType::iterator i_begin=pNodes.ptr_begin()+node_partition[k];
typename NodesArrayType::iterator i_end=pNodes.ptr_begin()+node_partition[k+1];
for(ModelPart::NodeIterator i=i_begin; i!= i_end; ++i)
{
array_1d<double,3>& node_rhs_variable = (i)->FastGetSolutionStepValue(rRHSVariable);
double& normalization_variable = (i)->FastGetSolutionStepValue(rNormalizationVariable);
node_rhs_variable /= normalization_variable;
}
}
KRATOS_CATCH("")
}
void ExplicitUpdateLoop(const Variable<array_1d<double, 3 > >& rUpdateVariable, const Variable<array_1d<double, 3 > >& rRHSVariable, const double& factor)
{
KRATOS_TRY
ModelPart& r_model_part = BaseType::GetModelPart();
NodesArrayType& pNodes = r_model_part.Nodes();
//const double delta_t = CurrentProcessInfo.GetValue(DELTA_TIME); //included in factor
#ifdef _OPENMP
int number_of_threads = omp_get_max_threads();
#else
int number_of_threads = 1;
#endif
DenseVector<unsigned int> node_partition;
CreatePartition(number_of_threads, pNodes.size(), node_partition);
#pragma omp parallel for
for(int k=0; k<number_of_threads; k++)
{
typename NodesArrayType::iterator i_begin=pNodes.ptr_begin()+node_partition[k];
typename NodesArrayType::iterator i_end=pNodes.ptr_begin()+node_partition[k+1];
for(ModelPart::NodeIterator i=i_begin; i!= i_end; ++i)
{
array_1d<double,3>& node_update_variable = (i)->FastGetSolutionStepValue(rUpdateVariable);
array_1d<double,3>& node_rhs_variable = (i)->FastGetSolutionStepValue(rRHSVariable);
noalias(node_update_variable) += factor* node_rhs_variable ;
}
}
KRATOS_CATCH("")
}
inline void CreatePartition(unsigned int number_of_threads, const int number_of_rows, DenseVector<unsigned int>& partitions)
{
partitions.resize(number_of_threads+1);
int partition_size = number_of_rows / number_of_threads;
partitions[0] = 0;
partitions[number_of_threads] = number_of_rows;
for(unsigned int i = 1; i<number_of_threads; i++)
partitions[i] = partitions[i-1] + partition_size ;
}
//********************************************
//********************************************
void InitializeSolutionStep() override
{
KRATOS_TRY
ModelPart& r_model_part = BaseType::GetModelPart();
ProcessInfo& CurrentProcessInfo = r_model_part.GetProcessInfo();
ElementsArrayType& pElements = r_model_part.Elements();
typename ElementsArrayType::iterator it_begin = pElements.ptr_begin() ;
typename ElementsArrayType::iterator it_end = pElements.ptr_end();
for (ElementsArrayType::iterator it = it_begin; it != it_end; ++it)
{
it->InitializeSolutionStep(CurrentProcessInfo);
}
KRATOS_CATCH("")
}
void FinalizeSolutionStep() override
{
KRATOS_TRY
ModelPart& r_model_part = BaseType::GetModelPart();
ProcessInfo& CurrentProcessInfo = r_model_part.GetProcessInfo();
ElementsArrayType& pElements = r_model_part.Elements();
typename ElementsArrayType::iterator it_begin = pElements.ptr_begin() ;
typename ElementsArrayType::iterator it_end = pElements.ptr_end();
for (ElementsArrayType::iterator it = it_begin; it != it_end; ++it)
{
it->FinalizeSolutionStep(CurrentProcessInfo);
}
KRATOS_CATCH("")
}
/// Turn back information as a string.
std::string Info() const override
{
return "ExplicitStrategy";
}
/// 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();
}
};
} /* namespace Kratos.*/
#endif /* EXPLICT_STRATEGY */
|
conv_op.h | /* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#pragma once
#include <algorithm>
#include <string>
#include <unordered_map>
#include <vector>
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
#include "./math/im2col.h"
#include "./math/vol2col.h"
#include "./math/math_function.h"
#include "mpc_op.h"
namespace paddle {
namespace operators {
using Tensor = framework::Tensor;
constexpr int kConvMKLDNNFP32 = 1;
constexpr int kConvMKLDNNINT8 = 2;
constexpr int MaxKeyLength = 256;
// Base convolution operator definations for other conv
// like operators to reuse the implementation.
inline int ConvOutputSize(int input_size, int filter_size, int dilation,
int padding, int stride) {
const int dkernel = dilation * (filter_size - 1) + 1;
int output_size = (input_size + 2 * padding - dkernel) / stride + 1;
PADDLE_ENFORCE_GT(
output_size, 0,
platform::errors::InvalidArgument(
"The output's size is expected to be greater than 0. "
"But recieved: output's size is %d. The output's size is computed by "
"((input_size + 2 * padding - (dilation * (filter_size - 1) + 1)) / "
"stride + 1), where input_size is %d, padding is %d, "
"filter_size is %d, dilation is %d, stride is %d.",
output_size, input_size, padding, filter_size, dilation, stride));
return output_size;
}
inline int ConvOutputSize(int input_size, int filter_size, int dilation,
int padding_1, int padding_2, int stride) {
const int dkernel = dilation * (filter_size - 1) + 1;
int output_size = (input_size + padding_1 + padding_2 - dkernel) / stride + 1;
PADDLE_ENFORCE_GT(
output_size, 0,
platform::errors::InvalidArgument(
"The output's size is expected to be greater than 0. "
"But recieved: output's size is %d. The output's size is computed by "
"((input_size + padding_1 + padding_2 - (dilation * (filter_size - "
"1) + 1)) / stride + 1), where input_size is %d, padding is "
"(%d, %d), filter_size is %d, dilation is %d, stride is %d.",
output_size, input_size, padding_1, padding_2, filter_size, dilation,
stride));
return output_size;
}
template <typename T = int>
inline void UpdatePaddingAndDilation(std::vector<T>* paddings,
std::vector<T>* dilation,
const std::string& padding_algorithm,
const framework::DDim data_dims,
const std::vector<T>& strides,
const std::vector<T>& ksize) {
// set padding size == data_dims.size() * 2
auto data_shape = framework::vectorize<T>(data_dims);
if (static_cast<int>(paddings->size()) == data_dims.size()) {
for (int i = 0; i < data_dims.size(); ++i) {
T copy_pad = *(paddings->begin() + 2 * i);
paddings->insert(paddings->begin() + 2 * i + 1, copy_pad);
}
} else {
PADDLE_ENFORCE_EQ(
data_dims.size() * 2, paddings->size(),
platform::errors::InvalidArgument(
"Attribute padding's size should be the same or twice as the "
"input's dimension. "
"But recieved: padding's size is %d, padding is [%s]; input's "
"dimension is %d, input's shape is [%s].",
paddings->size(), framework::make_ddim(*paddings), data_dims.size(),
data_dims));
}
// when padding_algorithm is "VALID" or "SAME"
if (padding_algorithm == "SAME") {
for (int i = 0; i < data_dims.size(); ++i) {
T out_size = (data_dims[i] + strides[i] - 1) / strides[i];
T pad_sum =
std::max((out_size - 1) * strides[i] + ksize[i] - data_shape[i],
static_cast<T>(0));
T pad_0 = pad_sum / 2;
T pad_1 = pad_sum - pad_0;
*(paddings->begin() + i * 2) = pad_0;
*(paddings->begin() + i * 2 + 1) = pad_1;
// dilation
*(dilation->begin() + i) = 1;
}
} else if (padding_algorithm == "VALID") {
for (auto it = paddings->begin(); it != paddings->end(); it++) {
*it = 0;
}
}
}
inline bool IsExpand(const std::vector<int64_t>& filter_dim,
const std::vector<int>& strides,
const std::vector<int>& paddings,
const std::vector<int>& dilations) {
bool filter_1 = true, strides_1 = true, padding_0 = true, dilation_1 = true;
for (size_t j = 0; j < strides.size(); ++j) {
// extra 1 for share dim
filter_1 = filter_1 && (static_cast<int>(filter_dim[j + 2 + 1]) == 1);
strides_1 = strides_1 && (strides[j] == 1);
padding_0 = padding_0 && (paddings[j] == 0);
dilation_1 = dilation_1 && (dilations[j] == 1);
}
if (paddings.size() != strides.size()) {
for (size_t j = 0; j < paddings.size(); ++j) {
padding_0 = padding_0 && (paddings[j] == 0);
}
}
return !(filter_1 && strides_1 && padding_0 && dilation_1);
}
template <typename DeviceContext, typename T>
inline void ResizeToChannelFirst(const framework::ExecutionContext& context,
const Tensor* input,
Tensor* transformed_input,
bool is_output = false) {
// extra 1 for leading share dim S
int dim = input->dims().size() - 2 - 1;
if (dim == 3) {
// input
transformed_input->Resize(input->dims());
auto in_dims_vec = framework::vectorize(input->dims());
if (is_output) {
// same as paddle, resize output of conv op
// SNDHWC -> SNCDHW
// all for simulate paddle conv op (plaintext)'s behavior
in_dims_vec[0] = input->dims()[0];
in_dims_vec[1] = input->dims()[1];
in_dims_vec[2] = input->dims()[5];
in_dims_vec[3] = input->dims()[2];
in_dims_vec[4] = input->dims()[3];
in_dims_vec[5] = input->dims()[4];
} else {
// SNDHWC -> NCSDHW
in_dims_vec[0] = input->dims()[1];
in_dims_vec[1] = input->dims()[5];
in_dims_vec[2] = input->dims()[0];
in_dims_vec[3] = input->dims()[2];
in_dims_vec[4] = input->dims()[3];
in_dims_vec[5] = input->dims()[4];
}
transformed_input->Resize(framework::make_ddim(in_dims_vec));
transformed_input->mutable_data<T>(context.GetPlace());
} else if (dim == 2) {
// input
transformed_input->Resize(input->dims());
auto in_dims_vec = framework::vectorize(input->dims());
if (is_output) {
in_dims_vec[0] = input->dims()[0];
in_dims_vec[1] = input->dims()[1];
in_dims_vec[2] = input->dims()[4];
in_dims_vec[3] = input->dims()[2];
in_dims_vec[4] = input->dims()[3];
} else {
// SNHWC -> NCSHW
in_dims_vec[0] = input->dims()[1];
in_dims_vec[1] = input->dims()[4];
in_dims_vec[2] = input->dims()[0];
in_dims_vec[3] = input->dims()[2];
in_dims_vec[4] = input->dims()[3];
}
transformed_input->Resize(framework::make_ddim(in_dims_vec));
transformed_input->mutable_data<T>(context.GetPlace());
}
}
template <typename DeviceContext, typename T>
inline void ResizeToChannelLast(const framework::ExecutionContext& context,
const Tensor* input,
Tensor* transformed_input) {
// extra 1 for leading share dim S
int dim = input->dims().size() - 2 - 1;
if (dim == 3) {
// input
transformed_input->Resize(input->dims());
// NCSDHW -> SNDHWC
auto in_dims_vec = framework::vectorize(input->dims());
in_dims_vec[0] = input->dims()[2];
in_dims_vec[1] = input->dims()[0];
in_dims_vec[2] = input->dims()[3];
in_dims_vec[3] = input->dims()[4];
in_dims_vec[4] = input->dims()[5];
in_dims_vec[5] = input->dims()[1];
transformed_input->Resize(framework::make_ddim(in_dims_vec));
transformed_input->mutable_data<T>(context.GetPlace());
} else if (dim == 2) {
// input
transformed_input->Resize(input->dims());
// NCSHW -> SNHWC
auto in_dims_vec = framework::vectorize(input->dims());
in_dims_vec[0] = input->dims()[2];
in_dims_vec[1] = input->dims()[0];
in_dims_vec[2] = input->dims()[3];
in_dims_vec[3] = input->dims()[4];
in_dims_vec[4] = input->dims()[1];
transformed_input->Resize(framework::make_ddim(in_dims_vec));
transformed_input->mutable_data<T>(context.GetPlace());
}
}
template <typename DeviceContext, typename T>
inline void ResizeToShareLast(const framework::ExecutionContext& context,
const Tensor* input,
Tensor* transformed_input) {
transformed_input->Resize(input->dims());
// SNC.. -> NCS..
auto in_dims_vec = framework::vectorize(input->dims());
in_dims_vec[0] = input->dims()[1];
in_dims_vec[1] = input->dims()[2];
in_dims_vec[2] = input->dims()[0];
transformed_input->Resize(framework::make_ddim(in_dims_vec));
transformed_input->mutable_data<T>(context.GetPlace());
}
template <typename DeviceContext, typename T>
inline void ResizeToShareFirst(const framework::ExecutionContext& context,
const Tensor* input,
Tensor* transformed_input) {
transformed_input->Resize(input->dims());
// NCS.. -> SNC..
auto in_dims_vec = framework::vectorize(input->dims());
in_dims_vec[0] = input->dims()[2];
in_dims_vec[1] = input->dims()[0];
in_dims_vec[2] = input->dims()[1];
transformed_input->Resize(framework::make_ddim(in_dims_vec));
transformed_input->mutable_data<T>(context.GetPlace());
}
template <typename DeviceContext, typename T>
inline void TransToChannelFirst(const framework::ExecutionContext& context,
const Tensor* input,
Tensor* transformed_input,
bool is_output = false) {
// extra 1 for leading share dim
// swap share and batch_size
int dim = input->dims().size() - 2 - 1;
if (dim == 3) {
auto& dev_ctx = context.template device_context<DeviceContext>();
std::vector<int> axis;
if (is_output) {
axis = std::vector<int>{0, 1, 5, 2, 3, 4};
} else {
axis = std::vector<int>{1, 5, 0, 2, 3, 4};
}
math::Transpose<DeviceContext, T, 6> trans6;
trans6(dev_ctx, *input, transformed_input, axis);
} else if (dim == 2) {
auto& dev_ctx = context.template device_context<DeviceContext>();
std::vector<int> axis{1, 4, 0, 2, 3};
if (is_output) {
axis = std::vector<int>{0, 1, 4, 2, 3};
} else {
axis = std::vector<int>{1, 4, 0, 2, 3};
}
math::Transpose<DeviceContext, T, 5> trans5;
trans5(dev_ctx, *input, transformed_input, axis);
}
}
template <typename DeviceContext, typename T>
inline void TransToChannelLast(const framework::ExecutionContext& context,
const Tensor* input, Tensor* transformed_input) {
// extra 1 for leading share dim
// swap share and batch_size
int dim = input->dims().size() - 2 - 1;
if (dim == 3) {
auto& dev_ctx = context.template device_context<DeviceContext>();
std::vector<int> axis{0, 1, 3, 4, 5, 2};
math::Transpose<DeviceContext, T, 6> trans6;
trans6(dev_ctx, *input, transformed_input, axis);
} else if (dim == 2) {
auto& dev_ctx = context.template device_context<DeviceContext>();
std::vector<int> axis{0, 1, 3, 4, 2};
math::Transpose<DeviceContext, T, 5> trans5;
trans5(dev_ctx, *input, transformed_input, axis);
}
}
template <typename DeviceContext, typename T>
inline void TransToShareFirst(const framework::ExecutionContext& context,
const Tensor* input, Tensor* transformed_input) {
int dim = input->dims().size();
PADDLE_ENFORCE_GT(
dim, 3,
platform::errors::InvalidArgument(
"The input's dim is expected to be greater than 4."));
std::vector<int> axis(dim);
for (size_t i = 3; i < dim; ++i) {
axis[i] = i;
}
// share
axis[0] = 2;
// N
axis[1] = 0;
// C
axis[2] = 1;
auto& dev_ctx = context.template device_context<DeviceContext>();
switch(dim) {
case 4:
math::Transpose<DeviceContext, T, 4> trans4;
trans4(dev_ctx, *input, transformed_input, axis);
break;
case 5:
math::Transpose<DeviceContext, T, 5> trans5;
trans5(dev_ctx, *input, transformed_input, axis);
break;
case 6:
math::Transpose<DeviceContext, T, 6> trans6;
trans6(dev_ctx, *input, transformed_input, axis);
break;
default:
PADDLE_ENFORCE_LT(
dim, 7, platform::errors::InvalidArgument(
"The input's dim greater than 6 not supported yet. "));
}
}
template <typename DeviceContext, typename T>
inline void TransToShareLast(const framework::ExecutionContext& context,
const Tensor* input, Tensor* transformed_input) {
int dim = input->dims().size();
PADDLE_ENFORCE_GT(
dim, 4,
platform::errors::InvalidArgument(
"The input's dim is expected to be greater than 4."));
std::vector<int> axis(dim);
for (size_t i = 3; i < dim; ++i) {
axis[i] = i;
}
// SNC -> NCS
axis[0] = 1;
axis[1] = 2;
axis[2] = 0;
auto& dev_ctx = context.template device_context<DeviceContext>();
switch(dim) {
case 5:
math::Transpose<DeviceContext, T, 5> trans5;
trans5(dev_ctx, *input, transformed_input, axis);
break;
case 6:
math::Transpose<DeviceContext, T, 6> trans6;
trans6(dev_ctx, *input, transformed_input, axis);
break;
default:
PADDLE_ENFORCE_LT(
dim, 7, platform::errors::InvalidArgument(
"The input's dim greater than 6 not supported yet. "));
}
}
template <typename DeviceContext, typename T>
inline void TransToBatchFirst(const framework::ExecutionContext& context,
const Tensor* input, Tensor* transformed_input) {
int dim = input->dims().size();
PADDLE_ENFORCE_GT(
dim, 4,
platform::errors::InvalidArgument(
"The input's dim is expected to be greater than 4."));
std::vector<int> axis(dim);
for (size_t i = 3; i < dim; ++i) {
axis[i] = i;
}
// N
axis[0] = 1;
// C
axis[1] = 2;
// share
axis[2] = 0;
auto& dev_ctx = context.template device_context<DeviceContext>();
switch(dim) {
case 5:
math::Transpose<DeviceContext, T, 5> trans5;
trans5(dev_ctx, *input, transformed_input, axis);
break;
case 6:
math::Transpose<DeviceContext, T, 6> trans6;
trans6(dev_ctx, *input, transformed_input, axis);
break;
default:
PADDLE_ENFORCE_LT(
dim, 7, platform::errors::InvalidArgument(
"The input's dim greater than 6 not supported yet. "));
}
}
template <typename DeviceContext, typename T>
inline void ResizeToSwapedLeadingDims(const framework::ExecutionContext& context,
const Tensor* input,
Tensor* transformed_input) {
transformed_input->Resize(input->dims());
// NS.. -> SN..
// or CS.. -> SC..
auto in_dims_vec = framework::vectorize(input->dims());
in_dims_vec[0] = input->dims()[1];
in_dims_vec[1] = input->dims()[0];
transformed_input->Resize(framework::make_ddim(in_dims_vec));
transformed_input->mutable_data<T>(context.GetPlace());
}
template <typename DeviceContext, typename T>
void TransToSwapedLeadingDims(const framework::ExecutionContext& context,
const Tensor* input,
Tensor* output){
output->Resize(input->dims());
auto in_dims_vec = framework::vectorize(input->dims());
in_dims_vec[0] = input->dims()[1];
in_dims_vec[1] = input->dims()[0];
output->Resize(framework::make_ddim(in_dims_vec));
output->mutable_data<T>(context.GetPlace());
const int dim = input->dims().size();
std::vector<int> axis(dim);
for (size_t i = 0; i < dim; ++i) {
axis[i] = i;
}
axis[0] = 1;
axis[1] = 0;
auto& dev_ctx = context.template device_context<DeviceContext>();
switch(dim) {
case 3:
math::Transpose<DeviceContext, T, 3> trans3;
trans3(dev_ctx, *input, output, axis);
break;
case 4:
math::Transpose<DeviceContext, T, 4> trans4;
trans4(dev_ctx, *input, output, axis);
break;
case 5:
math::Transpose<DeviceContext, T, 5> trans5;
trans5(dev_ctx, *input, output, axis);
break;
case 6:
math::Transpose<DeviceContext, T, 6> trans6;
trans6(dev_ctx, *input, output, axis);
break;
default:
PADDLE_ENFORCE_GT(
dim, 2, platform::errors::InvalidArgument(
"The input's dim less than 3 not supported yet. "));
PADDLE_ENFORCE_LT(
dim, 7, platform::errors::InvalidArgument(
"The input's dim greater than 6 not supported yet. "));
}
return;
}
template <typename DeviceContext, typename T, typename Func>
void SharesToCols(const framework::ExecutionContext& context,
const Tensor* input,
const std::vector<int>& dilations,
const std::vector<int>& strides,
const std::vector<int>& paddings,
Tensor* col, Func data2col) {
// // input: CSHW or CSDHW, S for share dim
framework::DDim in_plain_dim =
framework::slice_ddim(input->dims(), 1, input->dims().size());
framework::DDim col_plain_dim =
framework::slice_ddim(col->dims(), 1, col->dims().size());
auto& dev_ctx = context.template device_context<DeviceContext>();
const int share_size = input->dims()[0];
for (size_t i = 0; i < share_size; ++i) {
Tensor share = input->Slice(i, i + 1).Resize(in_plain_dim);
Tensor col_share = col->Slice(i, i + 1).Resize(col_plain_dim);
data2col(dev_ctx, share, dilations, strides, paddings, &col_share);
}
}
template <typename DeviceContext, typename T>
Tensor SwapedLeadingDims(const framework::ExecutionContext& context,
const Tensor* input) {
Tensor output(input->type());
ResizeToSwapedLeadingDims<DeviceContext, T>(context, input,
&output);
TransToSwapedLeadingDims<DeviceContext, T>(context, input,
&output);
return output;
}
template <typename DeviceContext, typename T>
Tensor TransposeMpcMat(const framework::ExecutionContext& context,
const Tensor* input) {
Tensor output(input->type());
auto in_dims_vec = framework::vectorize(input->dims());
PADDLE_ENFORCE_EQ(
in_dims_vec.size(), 3, platform::errors::InvalidArgument(
"The input's dim should be 3. "));
in_dims_vec[0] = input->dims()[0];
in_dims_vec[1] = input->dims()[2];
in_dims_vec[2] = input->dims()[1];
output.Resize(framework::make_ddim(in_dims_vec));
output.mutable_data<T>(context.GetPlace());
std::vector<int> axis(3);
axis[0] = 0;
axis[1] = 2;
axis[2] = 1;
auto& dev_ctx = context.template device_context<DeviceContext>();
math::Transpose<DeviceContext, T, 3> trans3;
trans3(dev_ctx, *input, &output, axis);
return output;
}
// Define Op classes in .h file so that other conv
// operator implementations can reuse the code.
class Conv2DOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() final;
protected:
virtual void Apply() {}
};
class ConvOpInferVarType : public framework::PassInDtypeAndVarTypeToOutput {
protected:
std::unordered_map<std::string, std::string>& GetInputOutputWithSameType()
const override {
static std::unordered_map<std::string, std::string> m{
{"Input", /*->*/ "Output"}};
return m;
}
};
template <typename DeviceContext, typename T>
struct CopyData {
void operator()(T* dst, const T* src, size_t numel);
};
class ConvOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
std::vector<int64_t> output_shape = ComputeOutputShape(ctx);
OP_INOUT_CHECK(ctx->HasOutput("Output"), "Output", "Output", "Conv");
ctx->SetOutputDim("Output", framework::make_ddim(output_shape));
ctx->ShareLoD("Input", "Output");
}
protected:
std::vector<int64_t> ComputeOutputShape(
framework::InferShapeContext* ctx) const;
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override;
framework::OpKernelType GetKernelTypeForVar(
const std::string& var_name, const Tensor& tensor,
const framework::OpKernelType& expected_kernel_type) const override;
};
class ConvOpGrad : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override;
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override;
framework::OpKernelType GetKernelTypeForVar(
const std::string& var_name, const Tensor& tensor,
const framework::OpKernelType& expected_kernel_type) const override;
};
// TODO: add conv double grad
template <typename DeviceContext, typename T>
class GemmConvKernel : public MpcOpKernel<T> {
public:
void ComputeImpl(const framework::ExecutionContext& context) const override {
const Tensor* input = context.Input<Tensor>("Input");
// The filter will be reshaped in the calculations,
// so here use an assignment operation,
// that avoids modifying the variable in the Scope.
Tensor filter = *context.Input<Tensor>("Filter");
Tensor* output = context.Output<Tensor>("Output");
output->mutable_data<T>(context.GetPlace());
const int groups = context.Attr<int>("groups");
const std::vector<int> strides = context.Attr<std::vector<int>>("strides");
std::vector<int> paddings = context.Attr<std::vector<int>>("paddings");
std::vector<int> dilations = context.Attr<std::vector<int>>("dilations");
const std::string padding_algorithm =
context.Attr<std::string>("padding_algorithm");
const std::string data_format = context.Attr<std::string>("data_format");
const bool channel_last = (data_format == "NHWC" || data_format == "NDHWC");
Tensor transformed_input(input->type());
Tensor transformed_output(output->type());
if (channel_last) {
ResizeToChannelFirst<DeviceContext, T>(context, input,
&transformed_input);
TransToChannelFirst<DeviceContext, T>(context, input, &transformed_input);
ResizeToChannelFirst<DeviceContext, T>(context, output,
&transformed_output, true);
} else {
ResizeToShareLast<DeviceContext, T>(context, input,
&transformed_input);
TransToShareLast<DeviceContext, T>(context, input, &transformed_input);
transformed_output = *output;
}
// update padding and dilation
auto trans_in_dims = transformed_input.dims();
auto filter_dims = filter.dims();
// extra 1 for share dim
framework::DDim in_data_dims =
framework::slice_ddim(trans_in_dims, 2 + 1, trans_in_dims.size());
framework::DDim filter_data_dims =
framework::slice_ddim(filter_dims, 2 + 1, filter_dims.size());
std::vector<int> ksize = framework::vectorize<int>(filter_data_dims);
UpdatePaddingAndDilation(&paddings, &dilations, padding_algorithm,
in_data_dims, strides, ksize);
auto& dev_ctx = context.template device_context<DeviceContext>();
const int batch_size = static_cast<int>(transformed_input.dims()[0]);
// filter_shape_vec:
// {k_share, k_o, k_i, k_h, k_w} or {k_share, k_o, k_i, k_d, k_h, k_w}
std::vector<int64_t> filter_shape_vec(framework::vectorize(filter.dims()));
// output_shape_vec:
// {o_n, o_c, o_share, o_h, o_w} or {o_n, o_c, o_share, o_d, o_h, o_w}
std::vector<int64_t> output_shape_vec(
framework::vectorize(transformed_output.dims()));
// use col_shape in the im2col calculation
// col_shape_vec:
// {i_s, i_c/g, k_h, k_w, o_h, o_w} or {i_s, i_c/g, k_d, k_h, k_w,
// o_d, o_h, o_w}
size_t data_dim = filter_shape_vec.size() - 2 - 1;
std::vector<int64_t> col_shape_vec(2 + 2 * data_dim);
col_shape_vec[0] = trans_in_dims[2];
col_shape_vec[1] = trans_in_dims[1] / groups;
std::vector<int64_t> col_matrix_shape_vec(3);
col_matrix_shape_vec[0] = col_shape_vec[0];
col_matrix_shape_vec[1] = col_shape_vec[1];
col_matrix_shape_vec[2] = 1;
// use col_matrix_shape in the gemm calculation
// size:
// (i_c/g * k_h * k_w, o_h * o_w) or (i_c/g * k_d * k_h * k_w, o_d * o_h *
// o_w)
for (size_t j = 0; j < data_dim; ++j) {
col_shape_vec[j + 2] = filter_shape_vec[j + 3];
col_shape_vec[j + 2 + data_dim] = output_shape_vec[j + 3];
col_matrix_shape_vec[1] *= filter_shape_vec[j + 3];
col_matrix_shape_vec[2] *= output_shape_vec[j + 3];
}
framework::DDim col_shape(framework::make_ddim(col_shape_vec));
framework::DDim col_matrix_shape(framework::make_ddim(col_matrix_shape_vec));
bool is_expand = IsExpand(filter_shape_vec, strides, paddings, dilations);
Tensor col;
// col_matrix shares the same piece of data with col,
// but will be reshaped into a two-dimensional matrix shape
// to call the matrix multiplication interface.
Tensor col_matrix;
if (is_expand) {
col = context.AllocateTmpTensor<T, DeviceContext>(col_shape, dev_ctx);
col_matrix.ShareDataWith(col);
col_matrix.Resize(col_matrix_shape);
}
// with share dim
framework::DDim in_matrix_shape = framework::slice_ddim(
transformed_input.dims(), 1, transformed_input.dims().size());
// SOIHW or SOIDHW
framework::DDim filter_matrix_shape = {filter.dims()[0], filter.dims()[1],
filter.numel() / (filter.dims()[0] * filter.dims()[1]) };
filter.Resize(filter_matrix_shape);
int in_step = static_cast<int>(transformed_input.dims()[1]) / groups;
int out_step = static_cast<int>(transformed_output.dims()[2]) / groups;
// S, N*groups, C/groups, H*W or D*H*W
framework::DDim output_matrix_shape = {
transformed_output.dims()[0],
batch_size * groups,
out_step,
transformed_output.numel() /
(transformed_output.dims()[0]
* transformed_output.dims()[1]
* transformed_output.dims()[2])};
// convolution operator: im2col(or vol2col) + gemm
math::Vol2ColFunctor<DeviceContext, T> vol2col;
math::Im2ColFunctor<math::ColFormat::kCFO, DeviceContext, T> im2col;
Tensor batched_col;
Tensor batched_filter;
batched_col.mutable_data<T>(framework::make_ddim({batch_size * groups,
col_matrix_shape[0],
col_matrix_shape[1],
col_matrix_shape[2]}),
context.GetPlace(), 0);
batched_filter.mutable_data<T>(framework::make_ddim({batch_size,
filter_matrix_shape[0],
groups,
out_step,
filter_matrix_shape[2],
}),
context.GetPlace(), 0);
auto original_out_dims = transformed_output.dims();
transformed_output.Resize(output_matrix_shape);
transformed_output.mutable_data<T>(context.GetPlace());
auto copy_functor = CopyData<DeviceContext, T>();
for (int i = 0; i < batch_size; i++) {
Tensor in_batch =
transformed_input.Slice(i, i + 1).Resize(in_matrix_shape);
Tensor filter_slice = batched_filter.Slice(i, i + 1);
copy_functor(filter_slice.data<T>(),
filter.data<T>(), filter.numel());
for (int g = 0; g < groups; g++) {
Tensor in_slice = in_batch.Slice(g * in_step, (g + 1) * in_step);
Tensor in_slice_ = SwapedLeadingDims<DeviceContext, T>(context, &in_slice);
if (!is_expand) {
col.ShareDataWith(in_slice_);
col_matrix.ShareDataWith(col);
col_matrix.Resize(col_matrix_shape);
} else if (data_dim == 2U) {
SharesToCols<DeviceContext, T>(context, &in_slice_, dilations, strides,
std::vector<int>{paddings[0], paddings[2], paddings[1],
paddings[3]}, &col, im2col);
} else if (data_dim == 3U) {
SharesToCols<DeviceContext, T>(context, &in_slice_, dilations, strides, paddings, &col, vol2col);
}
size_t col_matrix_size = col_matrix.numel();
size_t col_group_size = col_matrix_size * groups;
copy_functor(batched_col.template data<T>()
+ i * col_group_size + g * col_matrix_size,
col_matrix.template data<T>(),
col_matrix_size);
}
}
Tensor batched_col_ = SwapedLeadingDims<DeviceContext, T>(context, &batched_col);
Tensor batched_fil_ = SwapedLeadingDims<DeviceContext, T>(context, &batched_filter);
batched_fil_.Resize(framework::make_ddim({filter_matrix_shape[0],
batch_size * groups,
out_step,
filter_matrix_shape[2],
}));
// TransToShareFirst<DeviceContext, T>(context, &batched_filter, &batched_fil_);
mpc::MpcInstance::mpc_instance()->mpc_protocol()->mpc_operators()->matmul(
&batched_fil_, &batched_col_, &transformed_output);
transformed_output.Resize(original_out_dims);
if (channel_last) {
TransToChannelLast<DeviceContext, T>(context, &transformed_output,
output);
}
}
};
template <typename DeviceContext, typename T>
class GemmConvGradKernel : public MpcOpKernel<T> {
public:
void ComputeImpl(const framework::ExecutionContext& context) const override {
const Tensor* input = context.Input<Tensor>("Input");
const Tensor* output_grad =
context.Input<Tensor>(framework::GradVarName("Output"));
Tensor* input_grad =
context.Output<Tensor>(framework::GradVarName("Input"));
Tensor* filter_grad =
context.Output<Tensor>(framework::GradVarName("Filter"));
// The filter and filter_grad will be reshaped in the calculations,
// so here use an assignment operation,
// that avoids modifying the variable in the Scope.
Tensor filter = *context.Input<Tensor>("Filter");
if (!input_grad && !filter_grad) return;
int groups = context.Attr<int>("groups");
const std::vector<int> strides = context.Attr<std::vector<int>>("strides");
std::vector<int> paddings = context.Attr<std::vector<int>>("paddings");
std::vector<int> dilations = context.Attr<std::vector<int>>("dilations");
const std::string padding_algorithm =
context.Attr<std::string>("padding_algorithm");
const std::string data_format = context.Attr<std::string>("data_format");
const bool channel_last = (data_format == "NHWC" || data_format == "NDHWC");
Tensor transformed_input(input->type());
Tensor transformed_output_grad(output_grad->type());
if (channel_last) {
ResizeToChannelFirst<DeviceContext, T>(context, input,
&transformed_input);
TransToChannelFirst<DeviceContext, T>(context, input, &transformed_input);
ResizeToChannelFirst<DeviceContext, T>(context, output_grad,
&transformed_output_grad, true);
TransToChannelFirst<DeviceContext, T>(context, output_grad,
&transformed_output_grad, true);
} else {
ResizeToShareLast<DeviceContext, T>(context, input,
&transformed_input);
TransToShareLast<DeviceContext, T>(context, input, &transformed_input);
transformed_output_grad = *output_grad;
}
// update padding and dilation
auto in_dims = transformed_input.dims();
auto filter_dims = filter.dims();
// extra 1 for share dim
framework::DDim in_data_dims =
framework::slice_ddim(in_dims, 2 + 1, in_dims.size());
framework::DDim filter_data_dims =
framework::slice_ddim(filter_dims, 2 + 1, filter_dims.size());
std::vector<int> ksize = framework::vectorize<int>(filter_data_dims);
UpdatePaddingAndDilation(&paddings, &dilations, padding_algorithm,
in_data_dims, strides, ksize);
const int batch_size = static_cast<int>(transformed_input.dims()[0]);
auto& dev_ctx = context.template device_context<DeviceContext>();
// filter_shape_vec: {k_share, k_o, k_i, k_h, k_w} or {k_share, k_o, k_i, k_d, k_h, k_w}
std::vector<int64_t> filter_shape_vec(framework::vectorize(filter.dims()));
// output_shape_vec: {o_n, o_c, o_share, o_h, o_w} or {o_n, o_c, o_share, o_d, o_h, o_w}
std::vector<int64_t> output_shape_vec(
framework::vectorize(transformed_output_grad.dims()));
// use col_shape in the im2col calculation
// col_shape_vec: {i_c/g, k_h, k_w, o_h, o_w} or {i_c/g, k_d, k_h, k_w, o_d,
// o_h, o_w}
size_t data_dim = filter_shape_vec.size() - 2 - 1;
std::vector<int64_t> col_shape_vec(2 + 2 * data_dim);
col_shape_vec[0] = in_dims[2];
col_shape_vec[1] = in_dims[1] / groups;
std::vector<int64_t> col_matrix_shape_vec(3);
col_matrix_shape_vec[0] = col_shape_vec[0];
col_matrix_shape_vec[1] = col_shape_vec[1];
col_matrix_shape_vec[2] = 1;
// use col_matrix_shape in the gemm calculation
// size:
// (i_c/g * k_h * k_w, o_h * o_w) or (i_c/g * k_d * k_h * k_w, o_d * o_h *
// o_w)
for (size_t j = 0; j < data_dim; ++j) {
col_shape_vec[j + 2] = filter_shape_vec[j + 3];
col_shape_vec[j + 2 + data_dim] = output_shape_vec[j + 3];
col_matrix_shape_vec[1] *= filter_shape_vec[j + 3];
col_matrix_shape_vec[2] *= output_shape_vec[j + 3];
}
framework::DDim col_shape(framework::make_ddim(col_shape_vec));
framework::DDim col_matrix_shape(framework::make_ddim(col_matrix_shape_vec));
// with share dim
framework::DDim input_shape = framework::slice_ddim(
transformed_input.dims(), 1, transformed_input.dims().size());
// SOIHW or SOIDHW
framework::DDim filter_matrix_shape = {filter.dims()[0], filter.dims()[1],
filter.numel() / (filter.dims()[0] * filter.dims()[1]) };
filter.Resize(filter_matrix_shape);
// convolution backward input operator: gemm + col2im(or col2vol)
// convolution backward weight operator: im2col(or vol2col) + gemm
int in_step = static_cast<int>(transformed_input.dims()[1]) / groups;
int out_step = static_cast<int>(transformed_output_grad.dims()[2]) / groups;
bool is_expand = IsExpand(filter_shape_vec, strides, paddings, dilations);
Tensor col;
// col_matrix shares the same piece of data with col,
// but will be reshaped into a two-dimensional matrix shape
// to call the matrix multiplication interface.
Tensor col_matrix;
if (is_expand) {
col = context.AllocateTmpTensor<T, DeviceContext>(col_shape, dev_ctx);
col_matrix.ShareDataWith(col);
col_matrix.Resize(col_matrix_shape);
}
math::SetConstant<DeviceContext, T> set_zero;
Tensor batched_filter;
batched_filter.mutable_data<T>(framework::make_ddim({batch_size,
filter_matrix_shape[0],
groups,
out_step,
filter_matrix_shape[2],
}),
context.GetPlace(), 0);
auto copy_functor = CopyData<DeviceContext, T>();
// #pragma omp for
for (int i = 0; i < batch_size; i++) {
Tensor filter_slice = batched_filter.Slice(i, i + 1);
copy_functor(filter_slice.data<T>(),
filter.data<T>(), filter.numel());
}
Tensor batched_fil_ = SwapedLeadingDims<DeviceContext, T>(context, &batched_filter);
batched_fil_.Resize(framework::make_ddim({filter_matrix_shape[0],
batch_size * groups,
out_step,
filter_matrix_shape[2],
}));
transformed_output_grad.Resize(framework::make_ddim({
transformed_output_grad.dims()[0],
batch_size * groups,
out_step,
transformed_output_grad.numel() / (
transformed_output_grad.dims()[0] *
transformed_output_grad.dims()[1] *
transformed_output_grad.dims()[2])
}));
if (input_grad) {
input_grad->mutable_data<T>(context.GetPlace());
Tensor transformed_input_grad(input_grad->type());
if (channel_last) {
ResizeToChannelFirst<DeviceContext, T>(context, input_grad,
&transformed_input_grad);
} else {
ResizeToShareLast<DeviceContext, T>(context, input_grad,
&transformed_input_grad);
}
// if is_expand is false, the operation of set_zero is unnecessary,
// because math::matmul will reset input_grad.
if (is_expand) {
set_zero(dev_ctx, &transformed_input_grad, static_cast<T>(0));
}
Tensor batched_gemm(input_grad->type());
batched_gemm.Resize(framework::make_ddim({col_matrix_shape[0],
batch_size * groups,
col_matrix_shape[1],
col_matrix_shape[2],
}));
batched_gemm.mutable_data<T>(context.GetPlace());
mpc::MpcInstance::mpc_instance()->mpc_protocol()->mpc_operators()->matmul(
&batched_fil_, &transformed_output_grad, &batched_gemm, true, false);
batched_gemm = SwapedLeadingDims<DeviceContext, T>(
context, &batched_gemm);
batched_gemm.Resize(framework::make_ddim({batch_size,
groups,
col_matrix_shape[0],
col_matrix_shape[1],
col_matrix_shape[2],
}));
math::Col2VolFunctor<DeviceContext, T> col2vol;
math::Col2ImFunctor<math::ColFormat::kCFO, DeviceContext, T> col2im;
for (int i = 0; i < batch_size; i++) {
Tensor in_grad_batch =
transformed_input_grad.Slice(i, i + 1).Resize(input_shape);
Tensor gemm_group =
batched_gemm.Slice(i, i + 1).Resize(framework::make_ddim(
{groups, col_matrix_shape[0],
col_matrix_shape[1], col_matrix_shape[2], }));
for (int g = 0; g < groups; g++) {
Tensor in_grad_slice =
in_grad_batch.Slice(g * in_step, (g + 1) * in_step);
Tensor gemm =
gemm_group.Slice(g, g + 1).Resize(framework::make_ddim(
{ col_matrix_shape[0], col_matrix_shape[1], col_matrix_shape[2], }));
Tensor im_ =
SwapedLeadingDims<DeviceContext, T>(context, &in_grad_slice);
if (!is_expand) {
gemm.Resize(im_.dims());
} else {
gemm.Resize(col.dims());
}
if (is_expand && data_dim == 2U) {
SharesToCols<DeviceContext, T>(context, &gemm, dilations, strides,
std::vector<int>{paddings[0], paddings[2], paddings[1],
paddings[3]},
&im_, col2im);
} else if (is_expand && data_dim == 3U) {
SharesToCols<DeviceContext, T>(context, &gemm, dilations, strides, paddings, &im_, col2vol);
}
TransToSwapedLeadingDims<DeviceContext, T>(context, is_expand ? &im_ : &gemm, &in_grad_slice);
}
}
if (channel_last) {
TransToChannelLast<DeviceContext, T>(context, &transformed_input_grad,
input_grad);
} else {
TransToShareFirst<DeviceContext, T>(context, &transformed_input_grad,
input_grad);
}
}
if (filter_grad) {
filter_grad->mutable_data<T>(context.GetPlace());
auto filter_grad_dims = filter_grad->dims();
Tensor filter_grad_;
filter_grad_.mutable_data<T>(framework::make_ddim({filter_matrix_shape[0],
batch_size * groups,
out_step,
filter_matrix_shape[2]
}), context.GetPlace(), 0);
math::Im2ColFunctor<math::ColFormat::kCFO, DeviceContext, T> im2col;
math::Vol2ColFunctor<DeviceContext, T> vol2col;
Tensor batched_col;
batched_col.mutable_data<T>(framework::make_ddim({batch_size * groups,
col_matrix_shape[0],
col_matrix_shape[1],
col_matrix_shape[2]}),
context.GetPlace(), 0);
for (int i = 0; i < batch_size; i++) {
Tensor in_batch = transformed_input.Slice(i, i + 1).Resize(input_shape);
for (int g = 0; g < groups; g++) {
Tensor in_slice = in_batch.Slice(g * in_step, (g + 1) * in_step);
Tensor in_slice_ = SwapedLeadingDims<DeviceContext, T>(context, &in_slice);
if (!is_expand) {
col.ShareDataWith(in_slice_);
col_matrix.ShareDataWith(col);
col_matrix.Resize(col_matrix_shape);
} else if (data_dim == 2U) {
SharesToCols<DeviceContext, T>(context, &in_slice_, dilations, strides,
std::vector<int>{paddings[0], paddings[2], paddings[1],
paddings[3]}, &col, im2col);
} else if (data_dim == 3U) {
SharesToCols<DeviceContext, T>(context, &in_slice_, dilations, strides, paddings, &col, vol2col);
}
size_t col_matrix_size = col_matrix.numel();
size_t col_group_size = col_matrix_size * groups;
copy_functor(batched_col.template data<T>()
+ i * col_group_size + g * col_matrix_size,
col_matrix.template data<T>(),
col_matrix_size);
}
}
Tensor batched_col_ = SwapedLeadingDims<DeviceContext, T>(context, &batched_col);
// gemm
mpc::MpcInstance::mpc_instance()->mpc_protocol()->mpc_operators()->matmul(
&transformed_output_grad, &batched_col_, &filter_grad_, 0, 1);
filter_grad_.Resize(framework::make_ddim({filter_matrix_shape[0],
batch_size,
groups,
out_step,
filter_matrix_shape[2]
}));
using EigenTensor5 = paddle::framework::EigenTensor<T, 5>;
using EigenTensor4 = paddle::framework::EigenTensor<T, 4>;
filter_grad->Resize(framework::make_ddim({filter_matrix_shape[0],
groups,
out_step,
filter_matrix_shape[2]
}));
auto eigen_filter_grad_ = EigenTensor5::From(filter_grad_);
auto eigen_filter_grad = EigenTensor4::From(*filter_grad);
eigen_filter_grad.device(*dev_ctx.eigen_device()) =
eigen_filter_grad_.sum(Eigen::array<int,1>({1}));
filter_grad->Resize(filter_grad_dims);
}
}
};
} // namespace operators
} // namespace paddle
|
pr3.c | //Write an OpenMP program to multiply two matrices A & B and find the resultant matrix C
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#define NRA 62
#define NCA 15
#define NCB 7
int main (int argc, char *argv[])
{
int tid, nthreads, i, j, k, chunk;
double a[NRA][NCA],b[NCA][NCB],c[NRA][NCB]; /* matrix A to be multiplied*/ /* matrix B to be multiplied */ /* result matrix C */
/* number of rows in matrix A */
/* number of columns in matrix A */
/* number of columns in matrix B */
chunk = 10;
/*** Spawn a parallel region explicitly scoping all variables ***/
#pragma omp parallel shared(a,b,c,nthreads,chunk) private(tid,i,j,k)
{
tid = omp_get_thread_num();
if (tid == 0)
{
nthreads = omp_get_num_threads();
printf("Starting matrix multiple example with %d threads\n",nthreads);
printf("Initializing matrices...\n");
}
/*** Initialize matrices ***/
#pragma omp for schedule (static, chunk)
for (i=0; i<NRA; i++)
for (j=0; j<NCA; j++)
a[i][j]= i+j;
#pragma omp for schedule (static, chunk)
for (i=0; i<NCA; i++)
for (j=0; j<NCB; j++)
b[i][j]= i*j;
#pragma omp for schedule (static, chunk)
for (i=0; i<NRA; i++)
for (j=0; j<NCB; j++)
c[i][j]= 0;
/*** Do matrix multiply sharing iterations on outer loop ***/
/*** Display who does which iterations for demonstration purposes ***/
printf("Thread %d starting matrix multiply...\n",tid);
#pragma omp for schedule (static, chunk)
for (i=0; i<NRA; i++)
{
printf("Thread=%d did row=%d\n",tid,i);
for(j=0; j<NCB; j++)
for (k=0; k<NCA; k++)
c[i][j] += a[i][k] * b[k][j];
}
} // End of parallel region
/*** Print results ***/
/* set loop iteration chunk size */
printf("******************************************************\n");
printf("Result Matrix:\n");
for (i=0; i<NRA; i++)
{
for (j=0; j<NCB; j++)
printf("%6.2f ", c[i][j]);
printf("\n");
}
printf("******************************************************\n");
printf ("Done.\n");
}
|
YAKL_reductions.h |
#pragma once
template <class T, int myMem> class ParallelMin;
template <class T, int myMem> class ParallelMax;
template <class T, int myMem> class ParallelSum;
#ifdef YAKL_ARCH_HIP
template <class T> class ParallelMin<T,memDevice> {
void *tmp; // Temporary storage
size_t nTmp; // Size of temporary storage
int nItems; // Number of items in the array that will be reduced
T *rsltP; // Device pointer for reduction result
public:
ParallelMin() { tmp = NULL; }
ParallelMin(int const nItems) { tmp = NULL; setup(nItems); }
~ParallelMin() { finalize(); }
void setup(int const nItems) {
finalize();
rsltP = (T *) yaklAllocDevice(sizeof(T),""); // Allocate device pointer for result
// Get the amount of temporary storage needed (call with NULL storage pointer)
hipcub::DeviceReduce::Min(tmp, nTmp, rsltP , rsltP , nItems );
tmp = yaklAllocDevice(nTmp,""); // Allocate temporary storage
this->nItems = nItems;
}
void finalize() {
if (tmp != NULL) {
yaklFreeDevice(rsltP,"");
yaklFreeDevice(tmp,"");
}
tmp = NULL;
}
T operator() (T *data) {
T rslt;
hipcub::DeviceReduce::Min(tmp, nTmp, data , rsltP , nItems , 0 ); // Compute the reduction
hipMemcpyAsync(&rslt,rsltP,sizeof(T),hipMemcpyDeviceToHost,0); // Copy result to host
check_last_error();
fence();
return rslt;
}
void deviceReduce(T *data, T *devP) {
hipcub::DeviceReduce::Min(tmp, nTmp, data , devP , nItems , 0 ); // Compute the reduction
#if defined(YAKL_AUTO_FENCE) || defined(YAKL_DEBUG)
fence();
#endif
}
};
template <class T> class ParallelMax<T,memDevice> {
void *tmp; // Temporary storage
size_t nTmp; // Size of temporary storage
int nItems; // Number of items in the array that will be reduced
T *rsltP; // Device pointer for reduction result
public:
ParallelMax() { tmp = NULL; }
ParallelMax(int const nItems) { tmp = NULL; setup(nItems); }
~ParallelMax() { finalize(); }
void setup(int const nItems) {
finalize();
rsltP = (T *) yaklAllocDevice(sizeof(T),""); // Allocate device pointer for result
// Get the amount of temporary storage needed (call with NULL storage pointer)
hipcub::DeviceReduce::Max(tmp, nTmp, rsltP , rsltP , nItems );
tmp = yaklAllocDevice(nTmp,""); // Allocate temporary storage
this->nItems = nItems;
}
void finalize() {
if (tmp != NULL) {
yaklFreeDevice(rsltP,"");
yaklFreeDevice(tmp,"");
}
tmp = NULL;
}
T operator() (T *data) {
T rslt;
hipcub::DeviceReduce::Max(tmp, nTmp, data , rsltP , nItems , 0 ); // Compute the reduction
hipMemcpyAsync(&rslt,rsltP,sizeof(T),hipMemcpyDeviceToHost,0); // Copy result to host
check_last_error();
fence();
return rslt;
}
void deviceReduce(T *data, T *devP) {
hipcub::DeviceReduce::Max(tmp, nTmp, data , devP , nItems , 0 ); // Compute the reduction
#if defined(YAKL_AUTO_FENCE) || defined(YAKL_DEBUG)
fence();
#endif
}
};
template <class T> class ParallelSum<T,memDevice> {
void *tmp; // Temporary storage
size_t nTmp; // Size of temporary storage
int nItems; // Number of items in the array that will be reduced
T *rsltP; // Device pointer for reduction result
public:
ParallelSum() { tmp = NULL; }
ParallelSum(int const nItems) { tmp = NULL; setup(nItems); }
~ParallelSum() { finalize(); }
void setup(int const nItems) {
finalize();
rsltP = (T *) yaklAllocDevice(sizeof(T),""); // Allocate device pointer for result
// Get the amount of temporary storage needed (call with NULL storage pointer)
hipcub::DeviceReduce::Sum(tmp, nTmp, rsltP , rsltP , nItems );
tmp = yaklAllocDevice(nTmp,""); // Allocate temporary storage
this->nItems = nItems;
}
void finalize() {
if (tmp != NULL) {
yaklFreeDevice(rsltP,"");
yaklFreeDevice(tmp,"");
}
tmp = NULL;
}
T operator() (T *data) {
T rslt;
hipcub::DeviceReduce::Sum(tmp, nTmp, data , rsltP , nItems , 0 ); // Compute the reduction
hipMemcpyAsync(&rslt,rsltP,sizeof(T),hipMemcpyDeviceToHost,0); // Copy result to host
check_last_error();
fence();
return rslt;
}
void deviceReduce(T *data, T *devP) {
hipcub::DeviceReduce::Sum(tmp, nTmp, data , devP , nItems , 0 ); // Compute the reduction
#if defined(YAKL_AUTO_FENCE) || defined(YAKL_DEBUG)
fence();
#endif
}
};
#elif defined(YAKL_ARCH_CUDA)
template <class T> class ParallelMin<T,memDevice> {
void *tmp; // Temporary storage
size_t nTmp; // Size of temporary storage
int nItems; // Number of items in the array that will be reduced
T *rsltP; // Device pointer for reduction result
public:
ParallelMin() { tmp = NULL; }
ParallelMin(int const nItems) { tmp = NULL; setup(nItems); }
~ParallelMin() { finalize(); }
void setup(int const nItems) {
finalize();
rsltP = (T *) yaklAllocDevice(sizeof(T),""); // Allocate device pointer for result
// Get the amount of temporary storage needed (call with NULL storage pointer)
cub::DeviceReduce::Min(tmp, nTmp, rsltP , rsltP , nItems );
tmp = yaklAllocDevice(nTmp,""); // Allocate temporary storage
this->nItems = nItems;
}
void finalize() {
if (tmp != NULL) {
yaklFreeDevice(rsltP,"");
yaklFreeDevice(tmp,"");
}
tmp = NULL;
}
T operator() (T *data) {
T rslt;
cub::DeviceReduce::Min(tmp, nTmp, data , rsltP , nItems , 0 ); // Compute the reduction
cudaMemcpyAsync(&rslt,rsltP,sizeof(T),cudaMemcpyDeviceToHost,0); // Copy result to host
check_last_error();
fence();
return rslt;
}
void deviceReduce(T *data, T *devP) {
cub::DeviceReduce::Min(tmp, nTmp, data , devP , nItems , 0 ); // Compute the reduction
#if defined(YAKL_AUTO_FENCE) || defined(YAKL_DEBUG)
fence();
#endif
}
};
template <class T> class ParallelMax<T,memDevice> {
void *tmp; // Temporary storage
size_t nTmp; // Size of temporary storage
int nItems; // Number of items in the array that will be reduced
T *rsltP; // Device pointer for reduction result
public:
ParallelMax() { tmp = NULL; }
ParallelMax(int const nItems) { tmp = NULL; setup(nItems); }
~ParallelMax() { finalize(); }
void setup(int const nItems) {
finalize();
rsltP = (T *) yaklAllocDevice(sizeof(T),""); // Allocate device pointer for result
// Get the amount of temporary storage needed (call with NULL storage pointer)
cub::DeviceReduce::Max(tmp, nTmp, rsltP , rsltP , nItems );
tmp = yaklAllocDevice(nTmp,""); // Allocate temporary storage
this->nItems = nItems;
}
void finalize() {
if (tmp != NULL) {
yaklFreeDevice(rsltP,"");
yaklFreeDevice(tmp,"");
}
tmp = NULL;
}
T operator() (T *data) {
T rslt;
cub::DeviceReduce::Max(tmp, nTmp, data , rsltP , nItems , 0 ); // Compute the reduction
cudaMemcpyAsync(&rslt,rsltP,sizeof(T),cudaMemcpyDeviceToHost,0); // Copy result to host
check_last_error();
fence();
return rslt;
}
void deviceReduce(T *data, T *devP) {
cub::DeviceReduce::Max(tmp, nTmp, data , devP , nItems , 0 ); // Compute the reduction
#if defined(YAKL_AUTO_FENCE) || defined(YAKL_DEBUG)
fence();
#endif
}
};
template <class T> class ParallelSum<T,memDevice> {
void *tmp; // Temporary storage
size_t nTmp; // Size of temporary storage
int nItems; // Number of items in the array that will be reduced
T *rsltP; // Device pointer for reduction result
public:
ParallelSum() { tmp = NULL; }
ParallelSum(int const nItems) { tmp = NULL; setup(nItems); }
~ParallelSum() { finalize(); }
void setup(int const nItems) {
finalize();
rsltP = (T *) yaklAllocDevice(sizeof(T),""); // Allocate device pointer for result
// Get the amount of temporary storage needed (call with NULL storage pointer)
cub::DeviceReduce::Sum(tmp, nTmp, rsltP , rsltP , nItems );
tmp = yaklAllocDevice(nTmp,""); // Allocate temporary storage
this->nItems = nItems;
}
void finalize() {
if (tmp != NULL) {
yaklFreeDevice(rsltP,"");
yaklFreeDevice(tmp,"");
}
tmp = NULL;
}
T operator() (T *data) {
T rslt;
cub::DeviceReduce::Sum(tmp, nTmp, data , rsltP , nItems , 0 ); // Compute the reduction
cudaMemcpyAsync(&rslt,rsltP,sizeof(T),cudaMemcpyDeviceToHost,0); // Copy result to host
check_last_error();
fence();
return rslt;
}
void deviceReduce(T *data, T *devP) {
cub::DeviceReduce::Sum(tmp, nTmp, data , devP , nItems , 0 ); // Compute the reduction
#if defined(YAKL_AUTO_FENCE) || defined(YAKL_DEBUG)
fence();
#endif
}
};
#elif defined(YAKL_ARCH_SYCL)
template <class T> class ParallelMin<T,memDevice> {
int nItems; // Number of items in the array that will be reduced
T *rsltP; // Device pointer for reduction result
public:
ParallelMin() { }
ParallelMin(int const nItems) { setup(nItems); }
~ParallelMin() { finalize(); }
void setup(int const nItems) {
finalize();
rsltP = (T *) yaklAllocDevice(sizeof(T),""); // Allocate device pointer for result
this->nItems = nItems;
}
void finalize() {
yaklFreeDevice(rsltP,"");
}
T operator() (T *data) {
T rslt;
sycl_default_stream.memcpy(&rslt,rsltP,sizeof(T)); // Copy result to host
return rslt;
}
void deviceReduce(T *data, T *devP) {
sycl_default_stream.submit([&](sycl::handler& cgh) {
auto minReduction = sycl::ONEAPI::reduction(devP, sycl::ONEAPI::minimum<>());
cgh.parallel_for(sycl::nd_range<1>{nItems, 32},
minReduction,
[=](sycl::nd_item<1> idx, auto& min) {
min.combine(data[idx.get_global_id()]);
});
}).wait();
}
};
template <class T> class ParallelMax<T,memDevice> {
int nItems; // Number of items in the array that will be reduced
T *rsltP; // Device pointer for reduction result
public:
ParallelMax() { }
ParallelMax(int const nItems) { setup(nItems); }
~ParallelMax() { finalize(); }
void setup(int const nItems) {
finalize();
rsltP = (T *) yaklAllocDevice(sizeof(T),""); // Allocate device pointer for result
this->nItems = nItems;
}
void finalize() {
yaklFreeDevice(rsltP,"");
}
T operator() (T *data) {
T rslt;
sycl_default_stream.memcpy(&rslt,rsltP,sizeof(T)); // Copy result to host
return rslt;
}
void deviceReduce(T *data, T *devP) {
sycl_default_stream.submit([&](sycl::handler& cgh) {
auto maxReduction = sycl::ONEAPI::reduction(devP, sycl::ONEAPI::maximum<>());
cgh.parallel_for(sycl::nd_range<1>{nItems, 32},
maxReduction,
[=](sycl::nd_item<1> idx, auto& max) {
max.combine(data[idx.get_global_id()]);
});
}).wait();
}
};
template <class T> class ParallelSum<T,memDevice> {
int nItems; // Number of items in the array that will be reduced
T *rsltP; // Device pointer for reduction result
public:
ParallelSum() { }
ParallelSum(int const nItems) { setup(nItems); }
~ParallelSum() { finalize(); }
void setup(int const nItems) {
finalize();
rsltP = (T *) yaklAllocDevice(sizeof(T),""); // Allocate device pointer for result
this->nItems = nItems;
}
void finalize() {
yaklFreeDevice(rsltP,"");
}
T operator() (T *data) {
T rslt;
sycl_default_stream.memcpy(&rslt,rsltP,sizeof(T)); // Copy result to host
return rslt;
}
void deviceReduce(T *data, T *devP) {
sycl_default_stream.submit([&](sycl::handler& cgh) {
auto sumReduction = sycl::ONEAPI::reduction(devP, sycl::ONEAPI::plus<>());
cgh.parallel_for(sycl::nd_range<1>{nItems, 32},
sumReduction,
[=](sycl::nd_item<1> idx, auto& sum) {
sum.combine(idx.get_global_id());
});
}).wait();
}
};
#elif defined(YAKL_ARCH_OPENMP45)
template <class T> class ParallelSum<T,memDevice> {
int nItems;
public:
ParallelSum() {}
ParallelSum(int const nItems) {
this->nItems = nItems;
}
~ParallelSum() { }
T operator() (T *data) {
T rslt = 0;
#pragma omp target teams distribute parallel for simd reduction(+:rslt) is_device_ptr(data)
for(int i=0; i<nItems; i++) {
rslt += data[i];
}
return rslt;
}
void deviceReduce(T *data, T *devP) {
T rslt = 0;
#pragma omp target teams distribute parallel for simd reduction(+:rslt) is_device_ptr(data)
for (int i=0; i<nItems; i++) {
rslt += data[i];
}
omp_target_memcpy(devP,&rslt,sizeof(T),0,0,omp_get_default_device(),omp_get_initial_device());
#pragma omp taskwait
check_last_error();
}
};
template <class T> class ParallelMin<T,memDevice> {
int nItems;
public:
ParallelMin() {}
ParallelMin(int const nItems) {
this->nItems = nItems;
}
~ParallelMin() { }
T operator() (T *data) {
T rslt = std::numeric_limits<T>::max();
#pragma omp target teams distribute parallel for simd reduction(min:rslt) is_device_ptr(data)
for(int i=0; i<nItems; i++) {
rslt = data[i] < rslt ? data[i] : rslt;
}
return rslt;
}
void deviceReduce(T *data, T *devP) {
T rslt = std::numeric_limits<T>::max();
#pragma omp target teams distribute parallel for simd reduction(min:rslt) is_device_ptr(data)
for (int i=0; i<nItems; i++) {
rslt = data[i] < rslt ? data[i] : rslt;
}
omp_target_memcpy(devP,&rslt,sizeof(T),0,0,omp_get_default_device(),omp_get_initial_device());
#pragma omp taskwait
check_last_error();
}
};
template <class T> class ParallelMax<T,memDevice> {
int nItems;
public:
ParallelMax() {}
ParallelMax(int const nItems) {
this->nItems = nItems;
}
~ParallelMax() { }
T operator() (T *data) {
T rslt = std::numeric_limits<T>::lowest();
#pragma omp target teams distribute parallel for simd reduction(max:rslt) is_device_ptr(data)
for(int i=0; i<nItems; i++) {
rslt = data[i] > rslt ? data[i] : rslt;
}
return rslt;
}
void deviceReduce(T *data, T *devP) {
T rslt = std::numeric_limits<T>::lowest();
#pragma omp target teams distribute parallel for simd reduction(max:rslt) is_device_ptr(data)
for (int i=0; i<nItems; i++) {
rslt = data[i] > rslt ? data[i] : rslt;
}
omp_target_memcpy(devP,&rslt,sizeof(T),0,0,omp_get_default_device(),omp_get_initial_device());
#pragma omp taskwait
check_last_error();
}
};
#elif defined(YAKL_ARCH_OPENMP)
template <class T> class ParallelSum<T,memDevice> {
int nItems;
public:
ParallelSum() {}
ParallelSum(int const nItems) {
this->nItems = nItems;
}
~ParallelSum() { }
T operator() (T *data) {
T rslt = 0;
#pragma omp parallel for reduction(+:rslt)
for(int i=0; i<nItems; i++) {
rslt += data[i];
}
return rslt;
}
void deviceReduce(T *data, T *devP) {
T rslt = 0;
#pragma omp parallel for reduction(+:rslt)
for (int i=0; i<nItems; i++) {
rslt += data[i];
}
*devP = rslt;
}
};
template <class T> class ParallelMin<T,memDevice> {
int nItems;
public:
ParallelMin() {}
ParallelMin(int const nItems) {
this->nItems = nItems;
}
~ParallelMin() { }
T operator() (T *data) {
T rslt = std::numeric_limits<T>::max();
#pragma omp parallel for reduction(min:rslt)
for(int i=0; i<nItems; i++) {
rslt = data[i] < rslt ? data[i] : rslt;
}
return rslt;
}
void deviceReduce(T *data, T *devP) {
T rslt = std::numeric_limits<T>::max();
#pragma omp parallel for reduction(min:rslt)
for (int i=0; i<nItems; i++) {
rslt = data[i] < rslt ? data[i] : rslt;
}
*devP = rslt;
}
};
template <class T> class ParallelMax<T,memDevice> {
int nItems;
public:
ParallelMax() {}
ParallelMax(int const nItems) {
this->nItems = nItems;
}
~ParallelMax() { }
T operator() (T *data) {
T rslt = std::numeric_limits<T>::lowest();
#pragma omp parallel for reduction(max:rslt)
for(int i=0; i<nItems; i++) {
rslt = data[i] > rslt ? data[i] : rslt;
}
return rslt;
}
void deviceReduce(T *data, T *devP) {
T rslt = std::numeric_limits<T>::lowest();
#pragma omp parallel for reduction(max:rslt)
for (int i=0; i<nItems; i++) {
rslt = data[i] > rslt ? data[i] : rslt;
}
*devP = rslt;
}
};
#else
template <class T> class ParallelMin<T,memDevice> {
int nItems; // Number of items in the array that will be reduced
public:
ParallelMin() {}
ParallelMin(int const nItems) {
this->nItems = nItems;
}
~ParallelMin() {
}
void setup(int nItems) { this->nItems = nItems; }
T operator() (T *data) {
T rslt = data[0];
for (int i=1; i<nItems; i++) {
rslt = data[i] < rslt ? data[i] : rslt;
}
return rslt;
}
void deviceReduce(T *data, T *rslt) {
*(rslt) = data[0];
for (int i=1; i<nItems; i++) {
*(rslt) = data[i] < *(rslt) ? data[i] : rslt;
}
}
};
template <class T> class ParallelMax<T,memDevice> {
int nItems; // Number of items in the array that will be reduced
public:
ParallelMax() {}
ParallelMax(int const nItems) {
this->nItems = nItems;
}
~ParallelMax() {
}
void setup(int nItems) { this->nItems = nItems; }
T operator() (T *data) {
T rslt = data[0];
for (int i=1; i<nItems; i++) {
rslt = data[i] > rslt ? data[i] : rslt;
}
return rslt;
}
void deviceReduce(T *data, T *rslt) {
*(rslt) = data[0];
for (int i=1; i<nItems; i++) {
*(rslt) = data[i] > *(rslt) ? data[i] : rslt;
}
}
};
template <class T> class ParallelSum<T,memDevice> {
int nItems; // Number of items in the array that will be reduced
public:
ParallelSum() {}
ParallelSum(int const nItems) {
this->nItems = nItems;
}
~ParallelSum() {
}
void setup(int nItems) { this->nItems = nItems; }
T operator() (T *data) {
T rslt = data[0];
for (int i=1; i<nItems; i++) {
rslt += data[i];
}
return rslt;
}
void deviceReduce(T *data, T *rslt) {
*(rslt) = data[0];
for (int i=1; i<nItems; i++) {
*(rslt) += data[i];
}
}
};
#endif
template <class T> class ParallelMin<T,memHost> {
int nItems; // Number of items in the array that will be reduced
public:
ParallelMin() {}
ParallelMin(int const nItems) {
this->nItems = nItems;
}
~ParallelMin() {
}
void setup(int nItems) { this->nItems = nItems; }
T operator() (T *data) {
T rslt = data[0];
for (int i=1; i<nItems; i++) {
rslt = data[i] < rslt ? data[i] : rslt;
}
return rslt;
}
void deviceReduce(T *data, T *rslt) {
*(rslt) = data[0];
for (int i=1; i<nItems; i++) {
*(rslt) = data[i] < *(rslt) ? data[i] : rslt;
}
}
};
template <class T> class ParallelMax<T,memHost> {
int nItems; // Number of items in the array that will be reduced
public:
ParallelMax() {}
ParallelMax(int const nItems) {
this->nItems = nItems;
}
~ParallelMax() {
}
void setup(int nItems) { this->nItems = nItems; }
T operator() (T *data) {
T rslt = data[0];
for (int i=1; i<nItems; i++) {
rslt = data[i] > rslt ? data[i] : rslt;
}
return rslt;
}
void deviceReduce(T *data, T *rslt) {
*(rslt) = data[0];
for (int i=1; i<nItems; i++) {
*(rslt) = data[i] > *(rslt) ? data[i] : rslt;
}
}
};
template <class T> class ParallelSum<T,memHost> {
int nItems; // Number of items in the array that will be reduced
public:
ParallelSum() {}
ParallelSum(int const nItems) {
this->nItems = nItems;
}
~ParallelSum() {
}
void setup(int nItems) { this->nItems = nItems; }
T operator() (T *data) {
T rslt = data[0];
for (int i=1; i<nItems; i++) {
rslt += data[i];
}
return rslt;
}
void deviceReduce(T *data, T *rslt) {
*(rslt) = data[0];
for (int i=1; i<nItems; i++) {
*(rslt) += data[i];
}
}
};
|
ft.c | //-------------------------------------------------------------------------//
// //
// This benchmark is an OpenMP C version of the NPB FT code. This OpenMP //
// C version is developed by the Center for Manycore Programming at Seoul //
// National University and derived from the OpenMP Fortran versions in //
// "NPB3.3-OMP" developed by NAS. //
// //
// Permission to use, copy, distribute and modify this software for any //
// purpose with or without fee is hereby granted. This software is //
// provided "as is" without express or implied warranty. //
// //
// Information on NPB 3.3, including the technical report, the original //
// specifications, source code, results and information on how to submit //
// new results, is available at: //
// //
// http://www.nas.nasa.gov/Software/NPB/ //
// //
// Send comments or suggestions for this OpenMP C version to //
// cmp@aces.snu.ac.kr //
// //
// Center for Manycore Programming //
// School of Computer Science and Engineering //
// Seoul National University //
// Seoul 151-744, Korea //
// //
// E-mail: cmp@aces.snu.ac.kr //
// //
//-------------------------------------------------------------------------//
//-------------------------------------------------------------------------//
// Authors: Sangmin Seo, Jungwon Kim, Jun Lee, Jeongho Nah, Gangwon Jo, //
// and Jaejin Lee //
//-------------------------------------------------------------------------//
//---------------------------------------------------------------------
// FT benchmark
//---------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#include "global.h"
#include "randdp.h"
#include "timers.h"
#include "print_results.h"
#include "../my_include/my_include.h"
//---------------------------------------------------------------------------
static dcomplex ty1[MAXDIM][FFTBLOCKPAD_DEFAULT];
static dcomplex ty2[MAXDIM][FFTBLOCKPAD_DEFAULT];
#pragma omp threadprivate(ty1,ty2)
//---------------------------------------------------------------------
// u0, u1, u2 are the main arrays in the problem.
// Depending on the decomposition, these arrays will have different
// dimensions. To accomodate all possibilities, we allocate them as
// one-dimensional arrays and pass them to subroutines for different
// views
// - u0 contains the initial (transformed) initial condition
// - u1 and u2 are working arrays
// - twiddle contains exponents for the time evolution operator.
//---------------------------------------------------------------------
//---------------------------------------------------------------------
// Large arrays are in common so that they are allocated on the
// heap rather than the stack. This common block is not
// referenced directly anywhere else. Padding is to avoid accidental
// cache problems, since all array sizes are powers of two.
//---------------------------------------------------------------------
/* common /bigarrays/ */
dcomplex u0[NTOTALP];
dcomplex pad1[3];
dcomplex u1[NTOTALP];
dcomplex pad2[3];
//dcomplex u2[NTOTALP];
double twiddle[NTOTALP];
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
static void init_ui(void *ou0, void *ou1, void *ot, int d1, int d2, int d3);
static void evolve(void *ou0, void *ou1, void *ot, int d1, int d2, int d3);
static void compute_initial_conditions(void *ou0, int d1, int d2, int d3);
static double ipow46(double a, int exponent);
static void setup();
static void compute_indexmap(void *ot, int d1, int d2, int d3);
static void print_timers();
static void fft(int dir, dcomplex x1[NTOTALP], dcomplex x2[NTOTALP]);
static void cffts1(int is, int d1, int d2, int d3, void *ox, void *oxout);
static void cffts2(int is, int d1, int d2, int d3, void *ox, void *oxout);
static void cffts3(int is, int d1, int d2, int d3, void *ox, void *oxout);
static void fft_init(int n);
static void cfftz(int is, int m, int n,
dcomplex x[n][fftblockpad], dcomplex y[n][fftblockpad]);
static void fftz2(int is, int l, int m, int n, int ny, int ny1,
dcomplex u[n], dcomplex x[n][ny1], dcomplex y[n][ny1]);
static int ilog2(int n);
static void checksum(int i, void *ou1, int d1, int d2, int d3);
static void verify(int d1, int d2, int d3, int nt,
logical *verified, char *Class);
//---------------------------------------------------------------------------
int main(int argc, char *argv[])
{
int i;
int iter;
double total_time, mflops;
logical verified;
char Class;
//---------------------------------------------------------------------
// Run the entire problem once to make sure all data is touched.
// This reduces variable startup costs, which is important for such a
// short benchmark. The other NPB 2 implementations are similar.
//---------------------------------------------------------------------
for (i = 1; i <= T_max; i++) {
timer_clear(i);
}
setup();
init_ui(u0, u1, twiddle, dims[0], dims[1], dims[2]);
compute_indexmap(twiddle, dims[0], dims[1], dims[2]);
compute_initial_conditions(u1, dims[0], dims[1], dims[2]);
fft_init(dims[0]);
fft(1, u1, u0);
//---------------------------------------------------------------------
// Start over from the beginning. Note that all operations must
// be timed, in contrast to other benchmarks.
//---------------------------------------------------------------------
for (i = 1; i <= T_max; i++) {
timer_clear(i);
}
timer_start(T_total);
if (timers_enabled) timer_start(T_setup);
compute_indexmap(twiddle, dims[0], dims[1], dims[2]);
compute_initial_conditions(u1, dims[0], dims[1], dims[2]);
fft_init(dims[0]);
if (timers_enabled) timer_stop(T_setup);
if (timers_enabled) timer_start(T_fft);
fft(1, u1, u0);
if (timers_enabled) timer_stop(T_fft);
//EasyCrash: crash test
//flush_whole_cache();
//start_crash();
for (iter = 1; iter <= niter; iter++) {
if (timers_enabled) timer_start(T_evolve);
evolve(u0, u1, twiddle, dims[0], dims[1], dims[2]);
if (timers_enabled) timer_stop(T_evolve);
if (timers_enabled) timer_start(T_fft);
//fft(-1, u1, u2);
fft(-1, u1, u1);
if (timers_enabled) timer_stop(T_fft);
if (timers_enabled) timer_start(T_checksum);
//checksum(iter, u2, dims[0], dims[1], dims[2]);
checksum(iter, u1, dims[0], dims[1], dims[2]);
if (timers_enabled) timer_stop(T_checksum);
///*
//EasyCrash:
// EC(&ty1, sizeof(ty1));
// EC(&ty2, sizeof(ty2));
EC(&u0, NTOTALP*sizeof(double));
// EC(&u1, NTOTALP);
clflush(&iter);
mfence();
//*/
/*
//checkpoint:
checkpoint(&ty1, MAXDIM*FFTBLOCKPAD_DEFAULT*sizeof(double));
checkpoint(&ty2, MAXDIM*FFTBLOCKPAD_DEFAULT*sizeof(double));
checkpoint(&u0, NTOTALP*sizeof(double));
checkpoint(&u1, NTOTALP*sizeof(double));
clflush(&iter);
mfence();
*/
}
end_crash();
verify(NX, NY, NZ, niter, &verified, &Class);
timer_stop(T_total);
total_time = timer_read(T_total);
if (total_time != 0.0) {
mflops = 1.0e-6 * (double)NTOTAL *
(14.8157 + 7.19641 * log((double)NTOTAL)
+ (5.23518 + 7.21113 * log((double)NTOTAL)) * niter)
/ total_time;
} else {
mflops = 0.0;
}
print_results("FT", Class, NX, NY, NZ, niter,
total_time, mflops, " floating point", verified,
NPBVERSION, COMPILETIME, CS1, CS2, CS3, CS4, CS5, CS6, CS7);
if (timers_enabled) print_timers();
return 0;
}
//---------------------------------------------------------------------
// touch all the big data
//---------------------------------------------------------------------
static void init_ui(void *ou0, void *ou1, void *ot, int d1, int d2, int d3)
{
dcomplex (*u0)[d2][d1+1] = (dcomplex (*)[d2][d1+1])ou0;
dcomplex (*u1)[d2][d1+1] = (dcomplex (*)[d2][d1+1])ou1;
double (*twiddle)[d2][d1+1] = (double (*)[d2][d1+1])ot;
int i, j, k;
#pragma omp parallel for default(shared) private(i,j,k)
for (k = 0; k < d3; k++) {
for (j = 0; j < d2; j++) {
for (i = 0; i < d1; i++) {
u0[k][j][i] = dcmplx(0.0, 0.0);
u1[k][j][i] = dcmplx(0.0, 0.0);
twiddle[k][j][i] = 0.0;
}
}
}
}
//---------------------------------------------------------------------
// evolve u0 -> u1 (t time steps) in fourier space
//---------------------------------------------------------------------
static void evolve(void *ou0, void *ou1, void *ot, int d1, int d2, int d3)
{
dcomplex (*u0)[d2][d1+1] = (dcomplex (*)[d2][d1+1])ou0;
dcomplex (*u1)[d2][d1+1] = (dcomplex (*)[d2][d1+1])ou1;
double (*twiddle)[d2][d1+1] = (double (*)[d2][d1+1])ot;
int i, j, k;
#pragma omp parallel for default(shared) private(i,j,k)
for (k = 0; k < d3; k++) {
for (j = 0; j < d2; j++) {
for (i = 0; i < d1; i++) {
u0[k][j][i] = dcmplx_mul2(u0[k][j][i], twiddle[k][j][i]);
u1[k][j][i] = u0[k][j][i];
}
}
}
}
//---------------------------------------------------------------------
// Fill in array u0 with initial conditions from
// random number generator
//---------------------------------------------------------------------
static void compute_initial_conditions(void *ou0, int d1, int d2, int d3)
{
dcomplex (*u0)[d2][d1+1] = (dcomplex (*)[d2][d1+1])ou0;
int k, j;
double x0, start, an, dummy, starts[NZ];
start = SEED;
//---------------------------------------------------------------------
// Jump to the starting element for our first plane.
//---------------------------------------------------------------------
an = ipow46(A, 0);
dummy = randlc(&start, an);
an = ipow46(A, 2*NX*NY);
starts[0] = start;
for (k = 1; k < dims[2]; k++) {
dummy = randlc(&start, an);
starts[k] = start;
}
//---------------------------------------------------------------------
// Go through by z planes filling in one square at a time.
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(k,j,x0)
for (k = 0; k < dims[2]; k++) {
x0 = starts[k];
for (j = 0; j < dims[1]; j++) {
vranlc(2*NX, &x0, A, (double *)&u0[k][j][0]);
}
}
}
//---------------------------------------------------------------------
// compute a^exponent mod 2^46
//---------------------------------------------------------------------
static double ipow46(double a, int exponent)
{
double result, dummy, q, r;
int n, n2;
//---------------------------------------------------------------------
// Use
// a^n = a^(n/2)*a^(n/2) if n even else
// a^n = a*a^(n-1) if n odd
//---------------------------------------------------------------------
result = 1;
if (exponent == 0) return result;
q = a;
r = 1;
n = exponent;
while (n > 1) {
n2 = n / 2;
if (n2 * 2 == n) {
dummy = randlc(&q, q);
n = n2;
} else {
dummy = randlc(&r, q);
n = n-1;
}
}
dummy = randlc(&r, q);
result = r;
return result;
}
static void setup()
{
FILE *fp;
debug = false;
if ((fp = fopen("timer.flag", "r")) != NULL) {
timers_enabled = true;
fclose(fp);
} else {
timers_enabled = false;
}
niter = NITER_DEFAULT;
printf("\n\n NAS Parallel Benchmarks (NPB3.3-OMP-C) - FT Benchmark\n\n");
printf(" Size : %4dx%4dx%4d\n", NX, NY, NZ);
printf(" Iterations :%7d\n", niter);
printf(" Number of available threads :%7d\n", omp_get_max_threads());
printf("\n");
dims[0] = NX;
dims[1] = NY;
dims[2] = NZ;
//---------------------------------------------------------------------
// Set up info for blocking of ffts and transposes. This improves
// performance on cache-based systems. Blocking involves
// working on a chunk of the problem at a time, taking chunks
// along the first, second, or third dimension.
//
// - In cffts1 blocking is on 2nd dimension (with fft on 1st dim)
// - In cffts2/3 blocking is on 1st dimension (with fft on 2nd and 3rd dims)
// Since 1st dim is always in processor, we'll assume it's long enough
// (default blocking factor is 16 so min size for 1st dim is 16)
// The only case we have to worry about is cffts1 in a 2d decomposition.
// so the blocking factor should not be larger than the 2nd dimension.
//---------------------------------------------------------------------
fftblock = FFTBLOCK_DEFAULT;
fftblockpad = FFTBLOCKPAD_DEFAULT;
if (fftblock != FFTBLOCK_DEFAULT) fftblockpad = fftblock+3;
}
//---------------------------------------------------------------------
// compute function from local (i,j,k) to ibar^2+jbar^2+kbar^2
// for time evolution exponent.
//---------------------------------------------------------------------
static void compute_indexmap(void *ot, int d1, int d2, int d3)
{
double (*twiddle)[d2][d1+1] = (double (*)[d2][d1+1])ot;
int i, j, k, kk, kk2, jj, kj2, ii;
double ap;
//---------------------------------------------------------------------
// basically we want to convert the fortran indices
// 1 2 3 4 5 6 7 8
// to
// 0 1 2 3 -4 -3 -2 -1
// The following magic formula does the trick:
// mod(i-1+n/2, n) - n/2
//---------------------------------------------------------------------
ap = -4.0 * ALPHA * PI * PI;
#pragma omp parallel for default(shared) private(i,j,k,kk,kk2,jj,kj2,ii)
for (k = 0; k < dims[2]; k++) {
kk = ((k + NZ/2) % NZ) - NZ/2;
kk2 = kk*kk;
for (j = 0; j < dims[1]; j++) {
jj = ((j + NY/2) % NY) - NY/2;
kj2 = jj*jj + kk2;
for (i = 0; i < dims[0]; i++) {
ii = ((i + NX/2) % NX) - NX/2;
twiddle[k][j][i] = exp(ap * (double)(ii*ii+kj2));
}
}
}
}
static void print_timers()
{
int i;
double t, t_m;
char *tstrings[T_max+1];
tstrings[1] = " total ";
tstrings[2] = " setup ";
tstrings[3] = " fft ";
tstrings[4] = " evolve ";
tstrings[5] = " checksum ";
tstrings[6] = " fftx ";
tstrings[7] = " ffty ";
tstrings[8] = " fftz ";
t_m = timer_read(T_total);
if (t_m <= 0.0) t_m = 1.00;
for (i = 1; i <= T_max; i++) {
t = timer_read(i);
printf(" timer %2d(%16s) :%9.4f (%6.2f%%)\n",
i, tstrings[i], t, t*100.0/t_m);
}
}
//---------------------------------------------------------------------
// note: args x1, x2 must be different arrays
// note: args for cfftsx are (direction, layout, xin, xout, scratch)
// xin/xout may be the same and it can be somewhat faster
// if they are
//---------------------------------------------------------------------
static void fft(int dir, dcomplex x1[NTOTALP], dcomplex x2[NTOTALP])
{
if (dir == 1) {
cffts1(1, dims[0], dims[1], dims[2], x1, x1);
cffts2(1, dims[0], dims[1], dims[2], x1, x1);
cffts3(1, dims[0], dims[1], dims[2], x1, x2);
} else {
cffts3(-1, dims[0], dims[1], dims[2], x1, x1);
cffts2(-1, dims[0], dims[1], dims[2], x1, x1);
cffts1(-1, dims[0], dims[1], dims[2], x1, x2);
}
}
static void cffts1(int is, int d1, int d2, int d3, void *ox, void *oxout)
{
dcomplex (*x)[d2][d1+1] = (dcomplex (*)[d2][d1+1])ox;
dcomplex (*xout)[d2][d1+1] = (dcomplex (*)[d2][d1+1])oxout;
int logd1;
int i, j, k, jj;
logd1 = ilog2(d1);
if (timers_enabled) timer_start(T_fftx);
#pragma omp parallel for default(shared) private(i,j,k,jj)
for (k = 0; k < d3; k++) {
for (jj = 0; jj <= d2 - fftblock; jj += fftblock) {
for (j = 0; j < fftblock; j++) {
for (i = 0; i < d1; i++) {
ty1[i][j] = x[k][j+jj][i];
}
}
cfftz(is, logd1, d1, ty1, ty2);
for (j = 0; j < fftblock; j++) {
for (i = 0; i < d1; i++) {
xout[k][j+jj][i] = ty1[i][j];
}
}
}
}
if (timers_enabled) timer_stop(T_fftx);
}
static void cffts2(int is, int d1, int d2, int d3, void *ox, void *oxout)
{
dcomplex (*x)[d2][d1+1] = (dcomplex (*)[d2][d1+1])ox;
dcomplex (*xout)[d2][d1+1] = (dcomplex (*)[d2][d1+1])oxout;
int logd2;
int i, j, k, ii;
logd2 = ilog2(d2);
if (timers_enabled) timer_start(T_ffty);
#pragma omp parallel for default(shared) private(i,j,k,ii)
for (k = 0; k < d3; k++) {
for (ii = 0; ii <= d1 - fftblock; ii += fftblock) {
for (j = 0; j < d2; j++) {
for (i = 0; i < fftblock; i++) {
ty1[j][i] = x[k][j][i+ii];
}
}
cfftz(is, logd2, d2, ty1, ty2);
for (j = 0; j < d2; j++) {
for (i = 0; i < fftblock; i++) {
xout[k][j][i+ii] = ty1[j][i];
}
}
}
}
if (timers_enabled) timer_stop(T_ffty);
}
static void cffts3(int is, int d1, int d2, int d3, void *ox, void *oxout)
{
dcomplex (*x)[d2][d1+1] = (dcomplex (*)[d2][d1+1])ox;
dcomplex (*xout)[d2][d1+1] = (dcomplex (*)[d2][d1+1])oxout;
int logd3;
int i, j, k, ii;
logd3 = ilog2(d3);
if (timers_enabled) timer_start(T_fftz);
#pragma omp parallel for default(shared) private(i,j,k,ii)
for (j = 0; j < d2; j++) {
for (ii = 0; ii <= d1 - fftblock; ii += fftblock) {
for (k = 0; k < d3; k++) {
for (i = 0; i < fftblock; i++) {
ty1[k][i] = x[k][j][i+ii];
}
}
cfftz(is, logd3, d3, ty1, ty2);
for (k = 0; k < d3; k++) {
for (i = 0; i < fftblock; i++) {
xout[k][j][i+ii] = ty1[k][i];
}
}
}
}
if (timers_enabled) timer_stop(T_fftz);
}
//---------------------------------------------------------------------
// compute the roots-of-unity array that will be used for subsequent FFTs.
//---------------------------------------------------------------------
static void fft_init(int n)
{
int m, nu, ku, i, j, ln;
double t, ti;
//---------------------------------------------------------------------
// Initialize the U array with sines and cosines in a manner that permits
// stride one access at each FFT iteration.
//---------------------------------------------------------------------
nu = n;
m = ilog2(n);
u[0] = dcmplx(m, 0.0);
ku = 2;
ln = 1;
for (j = 1; j <= m; j++) {
t = PI / ln;
for (i = 0; i <= ln - 1; i++) {
ti = i * t;
u[i+ku-1] = dcmplx(cos(ti), sin(ti));
}
ku = ku + ln;
ln = 2 * ln;
}
}
//---------------------------------------------------------------------
// Computes NY N-point complex-to-complex FFTs of X using an algorithm due
// to Swarztrauber. X is both the input and the output array, while Y is a
// scratch array. It is assumed that N = 2^M. Before calling CFFTZ to
// perform FFTs, the array U must be initialized by calling CFFTZ with IS
// set to 0 and M set to MX, where MX is the maximum value of M for any
// subsequent call.
//---------------------------------------------------------------------
static void cfftz(int is, int m, int n,
dcomplex x[n][fftblockpad], dcomplex y[n][fftblockpad])
{
int i, j, l, mx;
//---------------------------------------------------------------------
// Check if input parameters are invalid.
//---------------------------------------------------------------------
mx = (int)(u[0].real);
if ((is != 1 && is != -1) || m < 1 || m > mx) {
printf("CFFTZ: Either U has not been initialized, or else\n"
"one of the input parameters is invalid%5d%5d%5d\n", is, m, mx);
exit(EXIT_FAILURE);
}
//---------------------------------------------------------------------
// Perform one variant of the Stockham FFT.
//---------------------------------------------------------------------
for (l = 1; l <= m; l += 2) {
fftz2(is, l, m, n, fftblock, fftblockpad, u, x, y);
if (l == m) {
//-----------------------------------------------------------------
// Copy Y to X.
//-----------------------------------------------------------------
for (j = 0; j < n; j++) {
for (i = 0; i < fftblock; i++) {
x[j][i] = y[j][i];
}
}
return;
}
fftz2(is, l + 1, m, n, fftblock, fftblockpad, u, y, x);
}
}
//---------------------------------------------------------------------
// Performs the L-th iteration of the second variant of the Stockham FFT.
//---------------------------------------------------------------------
static void fftz2(int is, int l, int m, int n, int ny, int ny1,
dcomplex u[n], dcomplex x[n][ny1], dcomplex y[n][ny1])
{
int k, n1, li, lj, lk, ku, i, j, i11, i12, i21, i22;
dcomplex u1, x11, x21;
//---------------------------------------------------------------------
// Set initial parameters.
//---------------------------------------------------------------------
n1 = n / 2;
lk = 1 << (l - 1);
li = 1 << (m - l);
lj = 2 * lk;
ku = li;
for (i = 0; i <= li - 1; i++) {
i11 = i * lk;
i12 = i11 + n1;
i21 = i * lj;
i22 = i21 + lk;
if (is >= 1) {
u1 = u[ku+i];
} else {
u1 = dconjg(u[ku+i]);
}
//---------------------------------------------------------------------
// This loop is vectorizable.
//---------------------------------------------------------------------
for (k = 0; k <= lk - 1; k++) {
for (j = 0; j < ny; j++) {
x11 = x[i11+k][j];
x21 = x[i12+k][j];
y[i21+k][j] = dcmplx_add(x11, x21);
y[i22+k][j] = dcmplx_mul(u1, dcmplx_sub(x11, x21));
}
}
}
}
static int ilog2(int n)
{
int nn, lg;
if (n == 1) return 0;
lg = 1;
nn = 2;
while (nn < n) {
nn = nn*2;
lg = lg+1;
}
return lg;
}
static void checksum(int i, void *ou1, int d1, int d2, int d3)
{
dcomplex (*u1)[d2][d1+1] = (dcomplex (*)[d2][d1+1])ou1;
int j, q, r, s;
dcomplex chk = dcmplx(0.0, 0.0);
#pragma omp parallel default(shared) private(i,q,r,s)
{
dcomplex my_chk = dcmplx(0.0, 0.0);
#pragma omp for nowait
for (j = 1; j <= 1024; j++) {
q = j % NX;
r = 3*j % NY;
s = 5*j % NZ;
my_chk = dcmplx_add(my_chk, u1[s][r][q]);
}
#pragma omp critical
{
chk = dcmplx_add(chk, my_chk);
}
}
chk = dcmplx_div2(chk, (double)(NTOTAL));
printf(" T =%5d Checksum =%22.12E%22.12E\n", i, chk.real, chk.imag);
sums[i] = chk;
}
static void verify(int d1, int d2, int d3, int nt,
logical *verified, char *Class)
{
int i;
double err, epsilon;
//---------------------------------------------------------------------
// Reference checksums
//---------------------------------------------------------------------
dcomplex csum_ref[25+1];
*Class = 'U';
epsilon = 1.0e-12;
*verified = false;
if (d1 == 64 && d2 == 64 && d3 == 64 && nt == 6) {
//---------------------------------------------------------------------
// Sample size reference checksums
//---------------------------------------------------------------------
*Class = 'S';
csum_ref[1] = dcmplx(5.546087004964E+02, 4.845363331978E+02);
csum_ref[2] = dcmplx(5.546385409189E+02, 4.865304269511E+02);
csum_ref[3] = dcmplx(5.546148406171E+02, 4.883910722336E+02);
csum_ref[4] = dcmplx(5.545423607415E+02, 4.901273169046E+02);
csum_ref[5] = dcmplx(5.544255039624E+02, 4.917475857993E+02);
csum_ref[6] = dcmplx(5.542683411902E+02, 4.932597244941E+02);
} else if (d1 == 128 && d2 == 128 && d3 == 32 && nt == 6) {
//---------------------------------------------------------------------
// Class W size reference checksums
//---------------------------------------------------------------------
*Class = 'W';
csum_ref[1] = dcmplx(5.673612178944E+02, 5.293246849175E+02);
csum_ref[2] = dcmplx(5.631436885271E+02, 5.282149986629E+02);
csum_ref[3] = dcmplx(5.594024089970E+02, 5.270996558037E+02);
csum_ref[4] = dcmplx(5.560698047020E+02, 5.260027904925E+02);
csum_ref[5] = dcmplx(5.530898991250E+02, 5.249400845633E+02);
csum_ref[6] = dcmplx(5.504159734538E+02, 5.239212247086E+02);
} else if (d1 == 256 && d2 == 256 && d3 == 128 && nt == 6) {
//---------------------------------------------------------------------
// Class A size reference checksums
//---------------------------------------------------------------------
*Class = 'A';
csum_ref[1] = dcmplx(5.046735008193E+02, 5.114047905510E+02);
csum_ref[2] = dcmplx(5.059412319734E+02, 5.098809666433E+02);
csum_ref[3] = dcmplx(5.069376896287E+02, 5.098144042213E+02);
csum_ref[4] = dcmplx(5.077892868474E+02, 5.101336130759E+02);
csum_ref[5] = dcmplx(5.085233095391E+02, 5.104914655194E+02);
csum_ref[6] = dcmplx(5.091487099959E+02, 5.107917842803E+02);
} else if (d1 == 512 && d2 == 256 && d3 == 256 && nt == 20) {
//---------------------------------------------------------------------
// Class B size reference checksums
//---------------------------------------------------------------------
*Class = 'B';
csum_ref[1] = dcmplx(5.177643571579E+02, 5.077803458597E+02);
csum_ref[2] = dcmplx(5.154521291263E+02, 5.088249431599E+02);
csum_ref[3] = dcmplx(5.146409228649E+02, 5.096208912659E+02);
csum_ref[4] = dcmplx(5.142378756213E+02, 5.101023387619E+02);
csum_ref[5] = dcmplx(5.139626667737E+02, 5.103976610617E+02);
csum_ref[6] = dcmplx(5.137423460082E+02, 5.105948019802E+02);
csum_ref[7] = dcmplx(5.135547056878E+02, 5.107404165783E+02);
csum_ref[8] = dcmplx(5.133910925466E+02, 5.108576573661E+02);
csum_ref[9] = dcmplx(5.132470705390E+02, 5.109577278523E+02);
csum_ref[10] = dcmplx(5.131197729984E+02, 5.110460304483E+02);
csum_ref[11] = dcmplx(5.130070319283E+02, 5.111252433800E+02);
csum_ref[12] = dcmplx(5.129070537032E+02, 5.111968077718E+02);
csum_ref[13] = dcmplx(5.128182883502E+02, 5.112616233064E+02);
csum_ref[14] = dcmplx(5.127393733383E+02, 5.113203605551E+02);
csum_ref[15] = dcmplx(5.126691062020E+02, 5.113735928093E+02);
csum_ref[16] = dcmplx(5.126064276004E+02, 5.114218460548E+02);
csum_ref[17] = dcmplx(5.125504076570E+02, 5.114656139760E+02);
csum_ref[18] = dcmplx(5.125002331720E+02, 5.115053595966E+02);
csum_ref[19] = dcmplx(5.124551951846E+02, 5.115415130407E+02);
csum_ref[20] = dcmplx(5.124146770029E+02, 5.115744692211E+02);
} else if (d1 == 512 && d2 == 512 && d3 == 512 && nt == 20) {
//---------------------------------------------------------------------
// Class C size reference checksums
//---------------------------------------------------------------------
*Class = 'C';
csum_ref[1] = dcmplx(5.195078707457E+02, 5.149019699238E+02);
csum_ref[2] = dcmplx(5.155422171134E+02, 5.127578201997E+02);
csum_ref[3] = dcmplx(5.144678022222E+02, 5.122251847514E+02);
csum_ref[4] = dcmplx(5.140150594328E+02, 5.121090289018E+02);
csum_ref[5] = dcmplx(5.137550426810E+02, 5.121143685824E+02);
csum_ref[6] = dcmplx(5.135811056728E+02, 5.121496764568E+02);
csum_ref[7] = dcmplx(5.134569343165E+02, 5.121870921893E+02);
csum_ref[8] = dcmplx(5.133651975661E+02, 5.122193250322E+02);
csum_ref[9] = dcmplx(5.132955192805E+02, 5.122454735794E+02);
csum_ref[10] = dcmplx(5.132410471738E+02, 5.122663649603E+02);
csum_ref[11] = dcmplx(5.131971141679E+02, 5.122830879827E+02);
csum_ref[12] = dcmplx(5.131605205716E+02, 5.122965869718E+02);
csum_ref[13] = dcmplx(5.131290734194E+02, 5.123075927445E+02);
csum_ref[14] = dcmplx(5.131012720314E+02, 5.123166486553E+02);
csum_ref[15] = dcmplx(5.130760908195E+02, 5.123241541685E+02);
csum_ref[16] = dcmplx(5.130528295923E+02, 5.123304037599E+02);
csum_ref[17] = dcmplx(5.130310107773E+02, 5.123356167976E+02);
csum_ref[18] = dcmplx(5.130103090133E+02, 5.123399592211E+02);
csum_ref[19] = dcmplx(5.129905029333E+02, 5.123435588985E+02);
csum_ref[20] = dcmplx(5.129714421109E+02, 5.123465164008E+02);
} else if (d1 == 2048 && d2 == 1024 && d3 == 1024 && nt == 25) {
//---------------------------------------------------------------------
// Class D size reference checksums
//---------------------------------------------------------------------
*Class = 'D';
csum_ref[1] = dcmplx(5.122230065252E+02, 5.118534037109E+02);
csum_ref[2] = dcmplx(5.120463975765E+02, 5.117061181082E+02);
csum_ref[3] = dcmplx(5.119865766760E+02, 5.117096364601E+02);
csum_ref[4] = dcmplx(5.119518799488E+02, 5.117373863950E+02);
csum_ref[5] = dcmplx(5.119269088223E+02, 5.117680347632E+02);
csum_ref[6] = dcmplx(5.119082416858E+02, 5.117967875532E+02);
csum_ref[7] = dcmplx(5.118943814638E+02, 5.118225281841E+02);
csum_ref[8] = dcmplx(5.118842385057E+02, 5.118451629348E+02);
csum_ref[9] = dcmplx(5.118769435632E+02, 5.118649119387E+02);
csum_ref[10] = dcmplx(5.118718203448E+02, 5.118820803844E+02);
csum_ref[11] = dcmplx(5.118683569061E+02, 5.118969781011E+02);
csum_ref[12] = dcmplx(5.118661708593E+02, 5.119098918835E+02);
csum_ref[13] = dcmplx(5.118649768950E+02, 5.119210777066E+02);
csum_ref[14] = dcmplx(5.118645605626E+02, 5.119307604484E+02);
csum_ref[15] = dcmplx(5.118647586618E+02, 5.119391362671E+02);
csum_ref[16] = dcmplx(5.118654451572E+02, 5.119463757241E+02);
csum_ref[17] = dcmplx(5.118665212451E+02, 5.119526269238E+02);
csum_ref[18] = dcmplx(5.118679083821E+02, 5.119580184108E+02);
csum_ref[19] = dcmplx(5.118695433664E+02, 5.119626617538E+02);
csum_ref[20] = dcmplx(5.118713748264E+02, 5.119666538138E+02);
csum_ref[21] = dcmplx(5.118733606701E+02, 5.119700787219E+02);
csum_ref[22] = dcmplx(5.118754661974E+02, 5.119730095953E+02);
csum_ref[23] = dcmplx(5.118776626738E+02, 5.119755100241E+02);
csum_ref[24] = dcmplx(5.118799262314E+02, 5.119776353561E+02);
csum_ref[25] = dcmplx(5.118822370068E+02, 5.119794338060E+02);
} else if (d1 == 4096 && d2 == 2048 && d3 == 2048 && nt == 25) {
//---------------------------------------------------------------------
// Class E size reference checksums
//---------------------------------------------------------------------
*Class = 'E';
csum_ref[1] = dcmplx(5.121601045346E+02, 5.117395998266E+02);
csum_ref[2] = dcmplx(5.120905403678E+02, 5.118614716182E+02);
csum_ref[3] = dcmplx(5.120623229306E+02, 5.119074203747E+02);
csum_ref[4] = dcmplx(5.120438418997E+02, 5.119345900733E+02);
csum_ref[5] = dcmplx(5.120311521872E+02, 5.119551325550E+02);
csum_ref[6] = dcmplx(5.120226088809E+02, 5.119720179919E+02);
csum_ref[7] = dcmplx(5.120169296534E+02, 5.119861371665E+02);
csum_ref[8] = dcmplx(5.120131225172E+02, 5.119979364402E+02);
csum_ref[9] = dcmplx(5.120104767108E+02, 5.120077674092E+02);
csum_ref[10] = dcmplx(5.120085127969E+02, 5.120159443121E+02);
csum_ref[11] = dcmplx(5.120069224127E+02, 5.120227453670E+02);
csum_ref[12] = dcmplx(5.120055158164E+02, 5.120284096041E+02);
csum_ref[13] = dcmplx(5.120041820159E+02, 5.120331373793E+02);
csum_ref[14] = dcmplx(5.120028605402E+02, 5.120370938679E+02);
csum_ref[15] = dcmplx(5.120015223011E+02, 5.120404138831E+02);
csum_ref[16] = dcmplx(5.120001570022E+02, 5.120432068837E+02);
csum_ref[17] = dcmplx(5.119987650555E+02, 5.120455615860E+02);
csum_ref[18] = dcmplx(5.119973525091E+02, 5.120475499442E+02);
csum_ref[19] = dcmplx(5.119959279472E+02, 5.120492304629E+02);
csum_ref[20] = dcmplx(5.119945006558E+02, 5.120506508902E+02);
csum_ref[21] = dcmplx(5.119930795911E+02, 5.120518503782E+02);
csum_ref[22] = dcmplx(5.119916728462E+02, 5.120528612016E+02);
csum_ref[23] = dcmplx(5.119902874185E+02, 5.120537101195E+02);
csum_ref[24] = dcmplx(5.119889291565E+02, 5.120544194514E+02);
csum_ref[25] = dcmplx(5.119876028049E+02, 5.120550079284E+02);
}
if (*Class != 'U') {
*verified = true;
for (i = 1; i <= nt; i++) {
err = dcmplx_abs(dcmplx_div(dcmplx_sub(sums[i], csum_ref[i]),
csum_ref[i]));
if (!(err <= epsilon)) {
*verified = false;
break;
}
}
}
if (*Class != 'U') {
if (*verified) {
printf(" Result verification successful\n");
} else {
printf(" Result verification failed\n");
}
}
printf(" class = %c\n", *Class);
}
|
atomic-16.c | // { dg-do run }
extern void abort (void);
int x = 6, cnt;
int
foo (void)
{
return cnt++;
}
int
main ()
{
int v, *p;
p = &x;
#pragma omp atomic update
p[foo (), 0] = 16 + 6 - p[foo (), 0];
#pragma omp atomic read
v = x;
if (cnt != 2 || v != 16)
abort ();
#pragma omp atomic capture
v = p[foo () + foo (), 0] = p[foo () + foo (), 0] + 3;
if (cnt != 6 || v != 19)
abort ();
#pragma omp atomic capture
v = p[foo (), 0] = 12 * 1 / 2 + (foo (), 0) + p[foo (), 0];
if (cnt != 9 || v != 25)
abort ();
#pragma omp atomic capture
{
v = p[foo () & 0]; p[foo () & 0] = (foo (), 1) * 9 - p[foo () & 0];
}
if (cnt != 13 || v != 25)
abort ();
#pragma omp atomic read
v = x;
if (v != -16)
abort ();
#pragma omp atomic capture
{
p[0 & foo ()] = 16 - 2 + 3 + p[0 & foo ()]; v = p[0 & foo ()];
}
if (cnt != 16 || v != 1)
abort ();
#pragma omp atomic capture
{
v = p[foo (), 0]; p[foo (), 0] = (foo (), 7) ? 13 : foo () + 6;
}
if (cnt != 19 || v != 1)
abort ();
#pragma omp atomic read
v = x;
if (v != 13)
abort ();
return 0;
}
|
3d7pt.c | /*
* Order-1, 3D 7 point stencil
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+2;
Ny = atoi(argv[2])+2;
Nz = atoi(argv[3])+2;
}
if (argc > 4)
Nt = atoi(argv[4]);
double ****A = (double ****) malloc(sizeof(double***)*2);
A[0] = (double ***) malloc(sizeof(double**)*Nz);
A[1] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[0][i] = (double**) malloc(sizeof(double*)*Ny);
A[1][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[0][i][j] = (double*) malloc(sizeof(double)*Nx);
A[1][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 8;
tile_size[1] = 8;
tile_size[2] = 8;
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
#pragma scop
for (t = 0; t < Nt-1; t++) {
for (i = 1; i < Nz-1; i++) {
for (j = 1; j < Ny-1; j++) {
for (k = 1; k < Nx-1; k++) {
A[(t+1)%2][i][j][k] = alpha * (A[t%2][i][j][k])
+ beta * (A[t%2][i - 1][j][k] + A[t%2][i][j - 1][k] + A[t%2][i][j][k - 1] +
A[t%2][i + 1][j][k] + A[t%2][i][j + 1][k] + A[t%2][i][j][k + 1]);
}
}
}
}
#pragma endscop
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = min(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(1, "constant")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays (Causing performance degradation
/* for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
}
free(A[0][i]);
free(A[1][i]);
}
free(A[0]);
free(A[1]);
*/
return 0;
}
|
omp_for_schedule_auto_nothreadprivate.c | // RUN: %libomp-compile-and-run
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "omp_testsuite.h"
int test_omp_for_auto()
{
int j;
int sum;
int sum0;
int known_sum;
int threadsnum;
sum = 0;
sum0 = 12345;
// array which keeps track of which threads participated in the for loop
// e.g., given 4 threads, [ 0 | 1 | 1 | 0 ] implies
// threads 0 and 3 did not, threads 1 and 2 did
int max_threads = omp_get_max_threads();
int* active_threads = (int*)malloc(sizeof(int)*max_threads);
for(j = 0; j < max_threads; j++)
active_threads[j] = 0;
#pragma omp parallel
{
int i;
int sum1 = 0;
#pragma omp for firstprivate(sum0) schedule(auto)
for (i = 1; i <= LOOPCOUNT; i++) {
active_threads[omp_get_thread_num()] = 1;
sum0 = sum0 + i;
sum1 = sum0;
}
#pragma omp critical
{
sum = sum + sum1;
}
}
// count the threads that participated (sum is stored in threadsnum)
threadsnum=0;
for(j = 0; j < max_threads; j++) {
if(active_threads[j])
threadsnum++;
}
free(active_threads);
known_sum = 12345 * threadsnum + (LOOPCOUNT * (LOOPCOUNT + 1)) / 2;
return (known_sum == sum);
}
int main()
{
int i;
int num_failed=0;
for(i = 0; i < REPETITIONS; i++) {
if(!test_omp_for_auto()) {
num_failed++;
}
}
return num_failed;
}
|
binarytrees2.c | // The Computer Language Benchmarks Game
// https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
//
// Contributed by Jeremy Zerfas
// Based on the C++ program from Jon Harrop, Alex Mizrahi, and Bruno Coutinho.
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <apr_pools.h>
// intptr_t should be the native integer type on most sane systems.
typedef intptr_t intnative_t;
typedef struct tree_node{
struct tree_node * left_Node, * right_Node;
} tree_node;
// Create a binary tree of depth tree_Depth in memory_Pool and return a pointer
// to the created binary tree.
static tree_node * create_Tree(const intnative_t tree_Depth,
apr_pool_t * const memory_Pool){
tree_node * const root_Node=apr_pcalloc(memory_Pool, sizeof(tree_node));
// If tree_Depth is one or more then recursively call create_Tree() in order
// to create the left and right subtrees.
if(tree_Depth>0){
root_Node->left_Node=create_Tree(tree_Depth-1, memory_Pool);
root_Node->right_Node=create_Tree(tree_Depth-1, memory_Pool);
}
return root_Node;
}
// Compute and return the checksum for the binary tree that has root_Node as the
// root node.
static intnative_t compute_Tree_Checksum(const tree_node * const root_Node){
// If there are subtrees then recursively call compute_Tree_Checksum() on
// them and return 1 plus the checksum of those subtrees.
if(root_Node->left_Node && root_Node->right_Node)
return compute_Tree_Checksum(root_Node->left_Node)+
compute_Tree_Checksum(root_Node->right_Node)+1;
// If the function gets here then this is a single node tree so just return
// 1 as the checksum.
return 1;
}
int main(int argc, char *argv[]){
// Set minimum_Tree_Depth to 4 and maximum_Tree_Depth to the maximum of what
// was specified as the argument to the program and minimum_Tree_Depth+2.
const intnative_t minimum_Tree_Depth=4,
maximum_Tree_Depth=atoi(argv[1])<minimum_Tree_Depth+2 ?
minimum_Tree_Depth+2 : atoi(argv[1]);
apr_initialize();
// Create a memory_Pool which will be used for storing both the stretch_Tree
// and the long_Lived_Tree.
apr_pool_t * memory_Pool;
apr_pool_create_unmanaged(&memory_Pool);
// Create a stretch_Tree of depth maximum_Tree_Depth+1, compute its
// checksum, and print its statistics. This work could be done in parallel
// along with all the other tree processing but APR memory pools aren't
// quite as streamlined as other memory pool implementations so it uses less
// resources to do this work by itself and then clear the memory_Pool so
// that most of the memory that was already allocated for the stretch_Tree
// can be reused for the upcoming long_Lived_Tree work rather than having
// APR allocate more memory for memory pools. Unfortunately since the
// long_Lived_Tree is about half the size of the stretch_Tree, this ends up
// wasting about half the memory that was being used by the stretch_Tree.
// APR subpools could be used to use that otherwise wasted memory for the
// processing of other trees that will be done later but it appears subpools
// only work with managed pools (even though APR's documentation for the
// apr_pool_create_unmanaged_ex() function seems to suggest that it possibly
// should work for unmanaged pools too) which are noticeably slower than
// unmanaged memory pools.
tree_node * stretch_Tree=create_Tree(maximum_Tree_Depth+1, memory_Pool);
printf("stretch tree of depth %jd\t check: %jd\n",
(intmax_t)maximum_Tree_Depth+1,
(intmax_t)compute_Tree_Checksum(stretch_Tree));
apr_pool_clear(memory_Pool);
// The long_Lived_Tree will be created in just a little bit simultaneously
// (assuming OpenMP was enabled and the program is running on a multi-
// processor system) while the rest of the trees are also being processed.
// long_Lived_Tree will store the reference to it which will remain valid
// until near the end of the program.
tree_node * long_Lived_Tree;
// These will be used to store checksums for the various trees so the
// statistics for the various trees can be output in the correct order
// later.
intnative_t long_Lived_Tree_Checksum,
tree_Checksums[(maximum_Tree_Depth-minimum_Tree_Depth+2)/2];
#pragma omp parallel
{
// Have one thread create the long_Lived_Tree of depth
// maximum_Tree_Depth in the memory_Pool which was already previously
// used for the stretch_Tree, compute the long_Lived_Tree_Checksum, and
// then just leave the long_Lived_Tree alone for a while while the rest
// of the binary trees finish processing (which should have
// simultaneously been started to be processed by any other available
// threads).
#pragma omp single nowait
{
long_Lived_Tree=create_Tree(maximum_Tree_Depth, memory_Pool);
long_Lived_Tree_Checksum=compute_Tree_Checksum(long_Lived_Tree);
}
// Create a thread_Memory_Pool for this thread to use.
apr_pool_t * thread_Memory_Pool;
apr_pool_create_unmanaged(&thread_Memory_Pool);
#pragma omp for nowait
for(intnative_t tree_Depth=minimum_Tree_Depth;
tree_Depth<=maximum_Tree_Depth; tree_Depth+=2){
// Create a bunch of binary trees of depth tree_Depth, compute their
// checksums, and add the checksums to the total_Trees_Checksum.
intnative_t total_Trees_Checksum=0;
for(intnative_t iterations=
1<<(maximum_Tree_Depth-tree_Depth+minimum_Tree_Depth);
iterations-->0;){
apr_pool_clear(thread_Memory_Pool);
total_Trees_Checksum+=compute_Tree_Checksum(
create_Tree(tree_Depth, thread_Memory_Pool));
}
// Record the total_Trees_Checksum for the trees of depth
// tree_Depth.
tree_Checksums[(tree_Depth-minimum_Tree_Depth)/2]=
total_Trees_Checksum;
}
apr_pool_destroy(thread_Memory_Pool);
}
// Print the statistics for all of the various tree depths.
for(intnative_t tree_Depth=minimum_Tree_Depth;
tree_Depth<=maximum_Tree_Depth; tree_Depth+=2)
printf("%jd\t trees of depth %jd\t check: %jd\n",
(intmax_t)1<<(maximum_Tree_Depth-tree_Depth+minimum_Tree_Depth),
(intmax_t)tree_Depth,
(intmax_t)tree_Checksums[(tree_Depth-minimum_Tree_Depth)/2]);
// Print the statistics for the long_Lived_Tree that was processed earlier
// and then delete the memory_Pool that still is storing it up to this
// point. Note that although the long_Lived_Tree variable isn't used here,
// it still is in scope and valid to use until the call to
// apr_pool_destroy(memory_Pool) is made.
printf("long lived tree of depth %jd\t check: %jd\n",
(intmax_t)maximum_Tree_Depth,
(intmax_t)long_Lived_Tree_Checksum);
apr_pool_destroy(memory_Pool);
apr_terminate();
return 0;
}
|
3d25pt_var.c | /*
* Order-1, 3D 25 point stencil with axis-symmetric ariable coefficients
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, m, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+8;
Ny = atoi(argv[2])+8;
Nz = atoi(argv[3])+8;
}
if (argc > 4)
Nt = atoi(argv[4]);
// allocate the arrays
double ****A = (double ****) malloc(sizeof(double***)*2);
for(m=0; m<2;m++){
A[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
double ****coef = (double ****) malloc(sizeof(double***)*13);
for(m=0; m<13;m++){
coef[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
coef[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
coef[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 24;
tile_size[1] = 24;
tile_size[2] = 32;
tile_size[3] = 32;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
for (m=0; m<13; m++) {
for (i=1; i<Nz; i++) {
for (j=1; j<Ny; j++) {
for (k=1; k<Nx; k++) {
coef[m][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
#pragma scop
for (t = 0; t < Nt; t++) {
for (i = 4; i < Nz-4; i++) {
for (j = 4; j < Ny-4; j++) {
for (k = 4; k < Nx-4; k++) {
A[(t+1)%2][i][j][k] =
coef[0][i][j][k] * A[(t)%2][i ][j ][k ] +
coef[1][i][j][k] * (A[(t)%2][i-1][j ][k ] + A[(t)%2][i+1][j ][k ]) +
coef[2][i][j][k] * (A[(t)%2][i ][j-1][k ] + A[(t)%2][i ][j+1][k ]) +
coef[3][i][j][k] * (A[(t)%2][i ][j ][k-1] + A[(t)%2][i ][j ][k+1]) +
coef[4][i][j][k] * (A[(t)%2][i-2][j ][k ] + A[(t)%2][i+2][j ][k ]) +
coef[5][i][j][k] * (A[(t)%2][i ][j-2][k ] + A[(t)%2][i ][j+2][k ]) +
coef[6][i][j][k] * (A[(t)%2][i ][j ][k-2] + A[(t)%2][i ][j ][k+2]) +
coef[7][i][j][k] * (A[(t)%2][i-3][j ][k ] + A[(t)%2][i+3][j ][k ]) +
coef[8][i][j][k] * (A[(t)%2][i ][j-3][k ] + A[(t)%2][i ][j+3][k ]) +
coef[9][i][j][k] * (A[(t)%2][i ][j ][k-3] + A[(t)%2][i ][j ][k+3]) +
coef[10][i][j][k]* (A[(t)%2][i-4][j ][k ] + A[(t)%2][i+4][j ][k ]) +
coef[11][i][j][k]* (A[(t)%2][i ][j-4][k ] + A[(t)%2][i ][j+4][k ]) +
coef[12][i][j][k]* (A[(t)%2][i ][j ][k-4] + A[(t)%2][i ][j ][k+4]) ;
}
}
}
}
#pragma endscop
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = min(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(4, "variable axis-symmetric")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
}
free(A[0][i]);
free(A[1][i]);
}
free(A[0]);
free(A[1]);
for(m=0; m<13;m++){
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(coef[m][i][j]);
}
free(coef[m][i]);
}
free(coef[m]);
}
return 0;
}
|
par_rap.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)
******************************************************************************/
#include "_hypre_parcsr_ls.h"
#include "_hypre_utilities.h"
/*--------------------------------------------------------------------------
* hypre_BoomerAMGBuildCoarseOperator
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoomerAMGBuildCoarseOperator( hypre_ParCSRMatrix *RT,
hypre_ParCSRMatrix *A,
hypre_ParCSRMatrix *P,
hypre_ParCSRMatrix **RAP_ptr )
{
hypre_BoomerAMGBuildCoarseOperatorKT( RT, A, P, 0, RAP_ptr);
return hypre_error_flag;
}
HYPRE_Int
hypre_BoomerAMGBuildCoarseOperatorKT( hypre_ParCSRMatrix *RT,
hypre_ParCSRMatrix *A,
hypre_ParCSRMatrix *P,
HYPRE_Int keepTranspose,
hypre_ParCSRMatrix **RAP_ptr )
{
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_RAP] -= hypre_MPI_Wtime();
#endif
MPI_Comm comm = hypre_ParCSRMatrixComm(A);
hypre_CSRMatrix *RT_diag = hypre_ParCSRMatrixDiag(RT);
hypre_CSRMatrix *RT_offd = hypre_ParCSRMatrixOffd(RT);
HYPRE_Int num_cols_diag_RT = hypre_CSRMatrixNumCols(RT_diag);
HYPRE_Int num_cols_offd_RT = hypre_CSRMatrixNumCols(RT_offd);
HYPRE_Int num_rows_offd_RT = hypre_CSRMatrixNumRows(RT_offd);
hypre_ParCSRCommPkg *comm_pkg_RT = hypre_ParCSRMatrixCommPkg(RT);
HYPRE_Int num_recvs_RT = 0;
HYPRE_Int num_sends_RT = 0;
HYPRE_Int *send_map_starts_RT;
HYPRE_Int *send_map_elmts_RT;
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag);
HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag);
HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd);
HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd);
HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd);
HYPRE_Int num_cols_diag_A = hypre_CSRMatrixNumCols(A_diag);
HYPRE_Int num_cols_offd_A = hypre_CSRMatrixNumCols(A_offd);
hypre_CSRMatrix *P_diag = hypre_ParCSRMatrixDiag(P);
HYPRE_Real *P_diag_data = hypre_CSRMatrixData(P_diag);
HYPRE_Int *P_diag_i = hypre_CSRMatrixI(P_diag);
HYPRE_Int *P_diag_j = hypre_CSRMatrixJ(P_diag);
hypre_CSRMatrix *P_offd = hypre_ParCSRMatrixOffd(P);
HYPRE_BigInt *col_map_offd_P = hypre_ParCSRMatrixColMapOffd(P);
HYPRE_Real *P_offd_data = hypre_CSRMatrixData(P_offd);
HYPRE_Int *P_offd_i = hypre_CSRMatrixI(P_offd);
HYPRE_Int *P_offd_j = hypre_CSRMatrixJ(P_offd);
HYPRE_BigInt first_col_diag_P = hypre_ParCSRMatrixFirstColDiag(P);
HYPRE_BigInt last_col_diag_P;
HYPRE_Int num_cols_diag_P = hypre_CSRMatrixNumCols(P_diag);
HYPRE_Int num_cols_offd_P = hypre_CSRMatrixNumCols(P_offd);
HYPRE_BigInt *coarse_partitioning = hypre_ParCSRMatrixColStarts(P);
HYPRE_BigInt *RT_partitioning = hypre_ParCSRMatrixColStarts(RT);
hypre_ParCSRMatrix *RAP;
HYPRE_BigInt *col_map_offd_RAP = NULL;
HYPRE_BigInt *new_col_map_offd_RAP = NULL;
hypre_CSRMatrix *RAP_int = NULL;
HYPRE_Real *RAP_int_data;
HYPRE_Int *RAP_int_i;
HYPRE_BigInt *RAP_int_j;
hypre_CSRMatrix *RAP_ext;
HYPRE_Real *RAP_ext_data = NULL;
HYPRE_Int *RAP_ext_i = NULL;
HYPRE_BigInt *RAP_ext_j = NULL;
hypre_CSRMatrix *RAP_diag;
HYPRE_Real *RAP_diag_data;
HYPRE_Int *RAP_diag_i;
HYPRE_Int *RAP_diag_j;
hypre_CSRMatrix *RAP_offd;
HYPRE_Real *RAP_offd_data = NULL;
HYPRE_Int *RAP_offd_i = NULL;
HYPRE_Int *RAP_offd_j = NULL;
HYPRE_Int RAP_size;
HYPRE_Int RAP_ext_size;
HYPRE_Int RAP_diag_size;
HYPRE_Int RAP_offd_size;
HYPRE_Int P_ext_diag_size;
HYPRE_Int P_ext_offd_size;
HYPRE_BigInt first_col_diag_RAP;
HYPRE_BigInt last_col_diag_RAP;
HYPRE_Int num_cols_offd_RAP = 0;
hypre_CSRMatrix *R_diag;
HYPRE_Real *R_diag_data;
HYPRE_Int *R_diag_i;
HYPRE_Int *R_diag_j;
hypre_CSRMatrix *R_offd;
HYPRE_Real *R_offd_data;
HYPRE_Int *R_offd_i;
HYPRE_Int *R_offd_j;
HYPRE_Real *RA_diag_data_array = NULL;
HYPRE_Int *RA_diag_j_array = NULL;
HYPRE_Real *RA_offd_data_array = NULL;
HYPRE_Int *RA_offd_j_array = NULL;
hypre_CSRMatrix *Ps_ext;
HYPRE_Real *Ps_ext_data;
HYPRE_Int *Ps_ext_i;
HYPRE_BigInt *Ps_ext_j;
HYPRE_Real *P_ext_diag_data = NULL;
HYPRE_Int *P_ext_diag_i = NULL;
HYPRE_Int *P_ext_diag_j = NULL;
HYPRE_Real *P_ext_offd_data = NULL;
HYPRE_Int *P_ext_offd_i = NULL;
HYPRE_Int *P_ext_offd_j = NULL;
HYPRE_BigInt *P_big_offd_j = NULL;
HYPRE_BigInt *col_map_offd_Pext;
HYPRE_Int *map_P_to_Pext = NULL;
HYPRE_Int *map_P_to_RAP = NULL;
HYPRE_Int *map_Pext_to_RAP = NULL;
HYPRE_Int *P_marker;
HYPRE_Int **P_mark_array;
HYPRE_Int **A_mark_array;
HYPRE_Int *A_marker;
HYPRE_BigInt *temp;
HYPRE_BigInt n_coarse, n_coarse_RT;
HYPRE_Int square = 1;
HYPRE_Int num_cols_offd_Pext = 0;
HYPRE_Int ic, i, j, k;
HYPRE_Int i1, i2, i3, ii, ns, ne, size, rest;
HYPRE_Int cnt = 0; /*value; */
HYPRE_Int jj1, jj2, jj3, jcol;
HYPRE_Int *jj_count, *jj_cnt_diag, *jj_cnt_offd;
HYPRE_Int jj_counter, jj_count_diag, jj_count_offd;
HYPRE_Int jj_row_begining, jj_row_begin_diag, jj_row_begin_offd;
HYPRE_Int start_indexing = 0; /* start indexing for RAP_data at 0 */
HYPRE_Int num_nz_cols_A;
HYPRE_Int num_procs;
HYPRE_Int num_threads;
HYPRE_Real r_entry;
HYPRE_Real r_a_product;
HYPRE_Real r_a_p_product;
HYPRE_Real zero = 0.0;
HYPRE_Int *prefix_sum_workspace;
/*-----------------------------------------------------------------------
* Copy ParCSRMatrix RT into CSRMatrix R so that we have row-wise access
* to restriction .
*-----------------------------------------------------------------------*/
hypre_MPI_Comm_size(comm, &num_procs);
num_threads = hypre_NumThreads();
if (comm_pkg_RT)
{
num_recvs_RT = hypre_ParCSRCommPkgNumRecvs(comm_pkg_RT);
num_sends_RT = hypre_ParCSRCommPkgNumSends(comm_pkg_RT);
send_map_starts_RT = hypre_ParCSRCommPkgSendMapStarts(comm_pkg_RT);
send_map_elmts_RT = hypre_ParCSRCommPkgSendMapElmts(comm_pkg_RT);
}
else if (num_procs > 1)
{
hypre_MatvecCommPkgCreate(RT);
comm_pkg_RT = hypre_ParCSRMatrixCommPkg(RT);
num_recvs_RT = hypre_ParCSRCommPkgNumRecvs(comm_pkg_RT);
num_sends_RT = hypre_ParCSRCommPkgNumSends(comm_pkg_RT);
send_map_starts_RT = hypre_ParCSRCommPkgSendMapStarts(comm_pkg_RT);
send_map_elmts_RT = hypre_ParCSRCommPkgSendMapElmts(comm_pkg_RT);
}
hypre_CSRMatrixTranspose(RT_diag, &R_diag, 1);
if (num_cols_offd_RT)
{
hypre_CSRMatrixTranspose(RT_offd, &R_offd, 1);
R_offd_data = hypre_CSRMatrixData(R_offd);
R_offd_i = hypre_CSRMatrixI(R_offd);
R_offd_j = hypre_CSRMatrixJ(R_offd);
}
/*-----------------------------------------------------------------------
* Access the CSR vectors for R. Also get sizes of fine and
* coarse grids.
*-----------------------------------------------------------------------*/
R_diag_data = hypre_CSRMatrixData(R_diag);
R_diag_i = hypre_CSRMatrixI(R_diag);
R_diag_j = hypre_CSRMatrixJ(R_diag);
n_coarse = hypre_ParCSRMatrixGlobalNumCols(P);
num_nz_cols_A = num_cols_diag_A + num_cols_offd_A;
n_coarse_RT = hypre_ParCSRMatrixGlobalNumCols(RT);
if (n_coarse != n_coarse_RT || num_cols_diag_RT != num_cols_diag_P)
{
square = 0;
}
/*-----------------------------------------------------------------------
* Generate Ps_ext, i.e. portion of P that is stored on neighbor procs
* and needed locally for triple matrix product
*-----------------------------------------------------------------------*/
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
hypre_UnorderedIntMap send_map_elmts_RT_inverse_map;
HYPRE_Int *send_map_elmts_starts_RT_aggregated = NULL;
HYPRE_Int *send_map_elmts_RT_aggregated = NULL;
HYPRE_Int send_map_elmts_RT_inverse_map_initialized =
num_sends_RT > 0 && send_map_starts_RT[num_sends_RT] - send_map_starts_RT[0] > 0;
if (send_map_elmts_RT_inverse_map_initialized)
{
hypre_UnorderedIntSet send_map_elmts_set;
hypre_UnorderedIntSetCreate(&send_map_elmts_set,
2 * (send_map_starts_RT[num_sends_RT] - send_map_starts_RT[0]), 16 * hypre_NumThreads());
#pragma omp parallel for HYPRE_SMP_SCHEDULE
for (i = send_map_starts_RT[0]; i < send_map_starts_RT[num_sends_RT]; i++)
{
HYPRE_Int key = send_map_elmts_RT[i];
hypre_UnorderedIntSetPut(&send_map_elmts_set, key);
}
HYPRE_Int send_map_elmts_unique_size;
HYPRE_Int *send_map_elmts_unique = hypre_UnorderedIntSetCopyToArray(&send_map_elmts_set,
&send_map_elmts_unique_size);
hypre_UnorderedIntSetDestroy(&send_map_elmts_set);
hypre_UnorderedIntMapCreate(&send_map_elmts_RT_inverse_map, 2 * send_map_elmts_unique_size,
16 * hypre_NumThreads());
#pragma omp parallel for HYPRE_SMP_SCHEDULE
for (i = 0; i < send_map_elmts_unique_size; i++)
{
hypre_UnorderedIntMapPutIfAbsent(&send_map_elmts_RT_inverse_map, send_map_elmts_unique[i], i);
}
hypre_TFree(send_map_elmts_unique, HYPRE_MEMORY_HOST);
send_map_elmts_starts_RT_aggregated = hypre_TAlloc(HYPRE_Int, send_map_elmts_unique_size + 1,
HYPRE_MEMORY_HOST);
send_map_elmts_RT_aggregated = hypre_TAlloc(HYPRE_Int, send_map_starts_RT[num_sends_RT],
HYPRE_MEMORY_HOST);
#pragma omp parallel for HYPRE_SMP_SCHEDULE
for (i = 0; i < send_map_elmts_unique_size; i++)
{
send_map_elmts_starts_RT_aggregated[i] = 0;
}
#pragma omp parallel for HYPRE_SMP_SCHEDULE
for (i = send_map_starts_RT[0]; i < send_map_starts_RT[num_sends_RT]; i++)
{
HYPRE_Int idx = hypre_UnorderedIntMapGet(&send_map_elmts_RT_inverse_map, send_map_elmts_RT[i]);
#pragma omp atomic
send_map_elmts_starts_RT_aggregated[idx]++;
}
for (i = 0; i < send_map_elmts_unique_size - 1; i++)
{
send_map_elmts_starts_RT_aggregated[i + 1] += send_map_elmts_starts_RT_aggregated[i];
}
send_map_elmts_starts_RT_aggregated[send_map_elmts_unique_size] = send_map_starts_RT[num_sends_RT];
#pragma omp parallel for HYPRE_SMP_SCHEDULE
for (i = send_map_starts_RT[num_sends_RT] - 1; i >= send_map_starts_RT[0]; i--)
{
HYPRE_Int idx = hypre_UnorderedIntMapGet(&send_map_elmts_RT_inverse_map, send_map_elmts_RT[i]);
HYPRE_Int offset = hypre_fetch_and_add(send_map_elmts_starts_RT_aggregated + idx, -1) - 1;
send_map_elmts_RT_aggregated[offset] = i;
}
}
#endif /* HYPRE_CONCURRENT_HOPSCOTCH */
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX] -= hypre_MPI_Wtime();
hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX_RAP] -= hypre_MPI_Wtime();
#endif
if (num_procs > 1)
{
Ps_ext = hypre_ParCSRMatrixExtractBExt(P, A, 1);
Ps_ext_data = hypre_CSRMatrixData(Ps_ext);
Ps_ext_i = hypre_CSRMatrixI(Ps_ext);
Ps_ext_j = hypre_CSRMatrixBigJ(Ps_ext);
}
P_ext_diag_i = hypre_TAlloc(HYPRE_Int, num_cols_offd_A + 1, HYPRE_MEMORY_HOST);
P_ext_offd_i = hypre_TAlloc(HYPRE_Int, num_cols_offd_A + 1, HYPRE_MEMORY_HOST);
P_ext_diag_i[0] = 0;
P_ext_offd_i[0] = 0;
P_ext_diag_size = 0;
P_ext_offd_size = 0;
last_col_diag_P = first_col_diag_P + (HYPRE_BigInt) num_cols_diag_P - 1;
/*HYPRE_Int prefix_sum_workspace[2*(num_threads + 1)];*/
prefix_sum_workspace = hypre_TAlloc(HYPRE_Int, 2 * (num_threads + 1), HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel private(i,j)
#endif /* This threading causes problem, maybe the prefix_sum in combination with BigInt? */
{
HYPRE_Int i_begin, i_end;
hypre_GetSimpleThreadPartition(&i_begin, &i_end, num_cols_offd_A);
HYPRE_Int P_ext_diag_size_private = 0;
HYPRE_Int P_ext_offd_size_private = 0;
for (i = i_begin; i < i_end; i++)
{
for (j = Ps_ext_i[i]; j < Ps_ext_i[i + 1]; j++)
if (Ps_ext_j[j] < first_col_diag_P || Ps_ext_j[j] > last_col_diag_P)
{
P_ext_offd_size_private++;
}
else
{
P_ext_diag_size_private++;
}
}
hypre_prefix_sum_pair(&P_ext_diag_size_private, &P_ext_diag_size, &P_ext_offd_size_private,
&P_ext_offd_size, prefix_sum_workspace);
#ifdef HYPRE_USING_OPENMP
#pragma omp master
#endif
{
if (P_ext_diag_size)
{
P_ext_diag_j = hypre_CTAlloc(HYPRE_Int, P_ext_diag_size, HYPRE_MEMORY_HOST);
P_ext_diag_data = hypre_CTAlloc(HYPRE_Real, P_ext_diag_size, HYPRE_MEMORY_HOST);
}
if (P_ext_offd_size)
{
P_ext_offd_j = hypre_CTAlloc(HYPRE_Int, P_ext_offd_size, HYPRE_MEMORY_HOST);
P_big_offd_j = hypre_CTAlloc(HYPRE_BigInt, P_ext_offd_size, HYPRE_MEMORY_HOST);
P_ext_offd_data = hypre_CTAlloc(HYPRE_Real, P_ext_offd_size, HYPRE_MEMORY_HOST);
//temp = hypre_CTAlloc(HYPRE_BigInt, P_ext_offd_size+num_cols_offd_P, HYPRE_MEMORY_HOST);
}
}
#ifdef HYPRE_USING_OPENMP
#pragma omp barrier
#endif
for (i = i_begin; i < i_end; i++)
{
for (j = Ps_ext_i[i]; j < Ps_ext_i[i + 1]; j++)
{
HYPRE_BigInt value = Ps_ext_j[j];
if (value < first_col_diag_P || value > last_col_diag_P)
{
//Ps_ext_j[P_ext_offd_size_private] = value;
//temp[P_ext_offd_size_private] = value;
P_big_offd_j[P_ext_offd_size_private] = value;
P_ext_offd_data[P_ext_offd_size_private++] = Ps_ext_data[j];
}
else
{
P_ext_diag_j[P_ext_diag_size_private] = (HYPRE_Int)(Ps_ext_j[j] - first_col_diag_P);
P_ext_diag_data[P_ext_diag_size_private++] = Ps_ext_data[j];
}
}
P_ext_diag_i[i + 1] = P_ext_diag_size_private;
P_ext_offd_i[i + 1] = P_ext_offd_size_private;
}
} /* omp parallel */
hypre_TFree(prefix_sum_workspace, HYPRE_MEMORY_HOST);
if (num_procs > 1)
{
hypre_CSRMatrixDestroy(Ps_ext);
Ps_ext = NULL;
}
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
if (P_ext_offd_size || num_cols_offd_P)
{
hypre_UnorderedBigIntSet found_set;
hypre_UnorderedBigIntSetCreate(&found_set, P_ext_offd_size + num_cols_offd_P,
16 * hypre_NumThreads());
#pragma omp parallel private(i)
{
#pragma omp for HYPRE_SMP_SCHEDULE
for (i = 0; i < P_ext_offd_size; i++)
{
//hypre_UnorderedBigIntSetPut(&found_set, Ps_ext_j[i]);
hypre_UnorderedBigIntSetPut(&found_set, P_big_offd_j[i]);
}
#pragma omp for HYPRE_SMP_SCHEDULE
for (i = 0; i < num_cols_offd_P; i++)
{
hypre_UnorderedBigIntSetPut(&found_set, col_map_offd_P[i]);
}
} /* omp parallel */
/* Warning on getting temp right !!!!! */
temp = hypre_UnorderedBigIntSetCopyToArray(&found_set, &num_cols_offd_Pext);
hypre_UnorderedBigIntSetDestroy(&found_set);
hypre_UnorderedBigIntMap col_map_offd_Pext_inverse;
hypre_big_sort_and_create_inverse_map(temp, num_cols_offd_Pext, &col_map_offd_Pext,
&col_map_offd_Pext_inverse);
#pragma omp parallel for HYPRE_SMP_SCHEDULE
for (i = 0 ; i < P_ext_offd_size; i++)
//Ps_ext_j[i] = hypre_UnorderedBigIntMapGet(&col_map_offd_Pext_inverse, Ps_ext_j[i]);
{
P_ext_offd_j[i] = hypre_UnorderedBigIntMapGet(&col_map_offd_Pext_inverse, P_big_offd_j[i]);
}
if (num_cols_offd_Pext) { hypre_UnorderedBigIntMapDestroy(&col_map_offd_Pext_inverse); }
}
#else /* !HYPRE_CONCURRENT_HOPSCOTCH */
if (P_ext_offd_size || num_cols_offd_P)
{
temp = hypre_CTAlloc(HYPRE_BigInt, P_ext_offd_size + num_cols_offd_P, HYPRE_MEMORY_HOST);
for (i = 0; i < P_ext_offd_size; i++)
//Ps_ext_j[i] = temp[i];
//temp[i] = Ps_ext_j[i];
{
temp[i] = P_big_offd_j[i];
}
cnt = P_ext_offd_size;
for (i = 0; i < num_cols_offd_P; i++)
{
temp[cnt++] = col_map_offd_P[i];
}
}
if (cnt)
{
hypre_BigQsort0(temp, 0, cnt - 1);
num_cols_offd_Pext = 1;
HYPRE_BigInt value = temp[0];
for (i = 1; i < cnt; i++)
{
if (temp[i] > value)
{
value = temp[i];
temp[num_cols_offd_Pext++] = value;
}
}
}
if (num_cols_offd_Pext)
{
col_map_offd_Pext = hypre_CTAlloc(HYPRE_BigInt, num_cols_offd_Pext, HYPRE_MEMORY_HOST);
}
for (i = 0; i < num_cols_offd_Pext; i++)
{
col_map_offd_Pext[i] = temp[i];
}
if (P_ext_offd_size || num_cols_offd_P)
{
hypre_TFree(temp, HYPRE_MEMORY_HOST);
}
/*if (P_ext_offd_size)
P_ext_offd_j = hypre_CTAlloc(HYPRE_Int, P_ext_offd_size, HYPRE_MEMORY_HOST);*/
for (i = 0 ; i < P_ext_offd_size; i++)
P_ext_offd_j[i] = hypre_BigBinarySearch(col_map_offd_Pext,
//Ps_ext_j[i],
P_big_offd_j[i],
num_cols_offd_Pext);
#endif /* !HYPRE_CONCURRENT_HOPSCOTCH */
if (P_ext_offd_size)
{
hypre_TFree(P_big_offd_j, HYPRE_MEMORY_HOST);
}
/*if (num_procs > 1)
{
hypre_CSRMatrixDestroy(Ps_ext);
Ps_ext = NULL;
}*/
if (num_cols_offd_P)
{
map_P_to_Pext = hypre_CTAlloc(HYPRE_Int, num_cols_offd_P, HYPRE_MEMORY_HOST);
cnt = 0;
for (i = 0; i < num_cols_offd_Pext; i++)
if (col_map_offd_Pext[i] == col_map_offd_P[cnt])
{
map_P_to_Pext[cnt++] = i;
if (cnt == num_cols_offd_P) { break; }
}
}
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX] += hypre_MPI_Wtime();
hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX_RAP] += hypre_MPI_Wtime();
#endif
/*-----------------------------------------------------------------------
* First Pass: Determine size of RAP_int and set up RAP_int_i if there
* are more than one processor and nonzero elements in R_offd
*-----------------------------------------------------------------------*/
P_mark_array = hypre_CTAlloc(HYPRE_Int *, num_threads, HYPRE_MEMORY_HOST);
A_mark_array = hypre_CTAlloc(HYPRE_Int *, num_threads, HYPRE_MEMORY_HOST);
if (num_cols_offd_RT)
{
jj_count = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,ii,ic,i1,i2,i3,jj1,jj2,jj3,ns,ne,size,rest,jj_counter,jj_row_begining,A_marker,P_marker) HYPRE_SMP_SCHEDULE
#endif
for (ii = 0; ii < num_threads; ii++)
{
size = num_cols_offd_RT / num_threads;
rest = num_cols_offd_RT - size * num_threads;
if (ii < rest)
{
ns = ii * size + ii;
ne = (ii + 1) * size + ii + 1;
}
else
{
ns = ii * size + rest;
ne = (ii + 1) * size + rest;
}
/*-----------------------------------------------------------------------
* Allocate marker arrays.
*-----------------------------------------------------------------------*/
if (num_cols_offd_Pext || num_cols_diag_P)
{
P_mark_array[ii] = hypre_CTAlloc(HYPRE_Int, num_cols_diag_P + num_cols_offd_Pext,
HYPRE_MEMORY_HOST);
P_marker = P_mark_array[ii];
}
A_mark_array[ii] = hypre_CTAlloc(HYPRE_Int, num_nz_cols_A, HYPRE_MEMORY_HOST);
A_marker = A_mark_array[ii];
/*-----------------------------------------------------------------------
* Initialize some stuff.
*-----------------------------------------------------------------------*/
jj_counter = start_indexing;
for (ic = 0; ic < num_cols_diag_P + num_cols_offd_Pext; ic++)
{
P_marker[ic] = -1;
}
for (i = 0; i < num_nz_cols_A; i++)
{
A_marker[i] = -1;
}
/*-----------------------------------------------------------------------
* Loop over exterior c-points
*-----------------------------------------------------------------------*/
for (ic = ns; ic < ne; ic++)
{
jj_row_begining = jj_counter;
/*--------------------------------------------------------------------
* Loop over entries in row ic of R_offd.
*--------------------------------------------------------------------*/
for (jj1 = R_offd_i[ic]; jj1 < R_offd_i[ic + 1]; jj1++)
{
i1 = R_offd_j[jj1];
/*-----------------------------------------------------------------
* Loop over entries in row i1 of A_offd.
*-----------------------------------------------------------------*/
for (jj2 = A_offd_i[i1]; jj2 < A_offd_i[i1 + 1]; jj2++)
{
i2 = A_offd_j[jj2];
/*--------------------------------------------------------------
* Check A_marker to see if point i2 has been previously
* visited. New entries in RAP only occur from unmarked points.
*--------------------------------------------------------------*/
if (A_marker[i2] != ic)
{
/*-----------------------------------------------------------
* Mark i2 as visited.
*-----------------------------------------------------------*/
A_marker[i2] = ic;
/*-----------------------------------------------------------
* Loop over entries in row i2 of P_ext.
*-----------------------------------------------------------*/
for (jj3 = P_ext_diag_i[i2]; jj3 < P_ext_diag_i[i2 + 1]; jj3++)
{
i3 = P_ext_diag_j[jj3];
/*--------------------------------------------------------
* Check P_marker to see that RAP_{ic,i3} has not already
* been accounted for. If it has not, mark it and increment
* counter.
*--------------------------------------------------------*/
if (P_marker[i3] < jj_row_begining)
{
P_marker[i3] = jj_counter;
jj_counter++;
}
}
for (jj3 = P_ext_offd_i[i2]; jj3 < P_ext_offd_i[i2 + 1]; jj3++)
{
i3 = P_ext_offd_j[jj3] + num_cols_diag_P;
/*--------------------------------------------------------
* Check P_marker to see that RAP_{ic,i3} has not already
* been accounted for. If it has not, mark it and increment
* counter.
*--------------------------------------------------------*/
if (P_marker[i3] < jj_row_begining)
{
P_marker[i3] = jj_counter;
jj_counter++;
}
}
}
}
/*-----------------------------------------------------------------
* Loop over entries in row i1 of A_diag.
*-----------------------------------------------------------------*/
for (jj2 = A_diag_i[i1]; jj2 < A_diag_i[i1 + 1]; jj2++)
{
i2 = A_diag_j[jj2];
/*--------------------------------------------------------------
* Check A_marker to see if point i2 has been previously
* visited. New entries in RAP only occur from unmarked points.
*--------------------------------------------------------------*/
if (A_marker[i2 + num_cols_offd_A] != ic)
{
/*-----------------------------------------------------------
* Mark i2 as visited.
*-----------------------------------------------------------*/
A_marker[i2 + num_cols_offd_A] = ic;
/*-----------------------------------------------------------
* Loop over entries in row i2 of P_diag.
*-----------------------------------------------------------*/
for (jj3 = P_diag_i[i2]; jj3 < P_diag_i[i2 + 1]; jj3++)
{
i3 = P_diag_j[jj3];
/*--------------------------------------------------------
* Check P_marker to see that RAP_{ic,i3} has not already
* been accounted for. If it has not, mark it and increment
* counter.
*--------------------------------------------------------*/
if (P_marker[i3] < jj_row_begining)
{
P_marker[i3] = jj_counter;
jj_counter++;
}
}
/*-----------------------------------------------------------
* Loop over entries in row i2 of P_offd.
*-----------------------------------------------------------*/
for (jj3 = P_offd_i[i2]; jj3 < P_offd_i[i2 + 1]; jj3++)
{
i3 = map_P_to_Pext[P_offd_j[jj3]] + num_cols_diag_P;
/*--------------------------------------------------------
* Check P_marker to see that RAP_{ic,i3} has not already
* been accounted for. If it has not, mark it and increment
* counter.
*--------------------------------------------------------*/
if (P_marker[i3] < jj_row_begining)
{
P_marker[i3] = jj_counter;
jj_counter++;
}
}
}
}
}
}
jj_count[ii] = jj_counter;
}
/*-----------------------------------------------------------------------
* Allocate RAP_int_data and RAP_int_j arrays.
*-----------------------------------------------------------------------*/
for (i = 0; i < num_threads - 1; i++)
{
jj_count[i + 1] += jj_count[i];
}
RAP_size = jj_count[num_threads - 1];
RAP_int_i = hypre_CTAlloc(HYPRE_Int, num_cols_offd_RT + 1, HYPRE_MEMORY_HOST);
RAP_int_data = hypre_CTAlloc(HYPRE_Real, RAP_size, HYPRE_MEMORY_HOST);
RAP_int_j = hypre_CTAlloc(HYPRE_BigInt, RAP_size, HYPRE_MEMORY_HOST);
RAP_int_i[num_cols_offd_RT] = RAP_size;
/*-----------------------------------------------------------------------
* Second Pass: Fill in RAP_int_data and RAP_int_j.
*-----------------------------------------------------------------------*/
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,ii,ic,i1,i2,i3,jj1,jj2,jj3,ns,ne,size,rest,jj_counter,jj_row_begining,A_marker,P_marker,r_entry,r_a_product,r_a_p_product) HYPRE_SMP_SCHEDULE
#endif
for (ii = 0; ii < num_threads; ii++)
{
size = num_cols_offd_RT / num_threads;
rest = num_cols_offd_RT - size * num_threads;
if (ii < rest)
{
ns = ii * size + ii;
ne = (ii + 1) * size + ii + 1;
}
else
{
ns = ii * size + rest;
ne = (ii + 1) * size + rest;
}
/*-----------------------------------------------------------------------
* Initialize some stuff.
*-----------------------------------------------------------------------*/
if (num_cols_offd_Pext || num_cols_diag_P)
{
P_marker = P_mark_array[ii];
}
A_marker = A_mark_array[ii];
jj_counter = start_indexing;
if (ii > 0) { jj_counter = jj_count[ii - 1]; }
for (ic = 0; ic < num_cols_diag_P + num_cols_offd_Pext; ic++)
{
P_marker[ic] = -1;
}
for (i = 0; i < num_nz_cols_A; i++)
{
A_marker[i] = -1;
}
/*-----------------------------------------------------------------------
* Loop over exterior c-points.
*-----------------------------------------------------------------------*/
for (ic = ns; ic < ne; ic++)
{
jj_row_begining = jj_counter;
RAP_int_i[ic] = jj_counter;
/*--------------------------------------------------------------------
* Loop over entries in row ic of R_offd.
*--------------------------------------------------------------------*/
for (jj1 = R_offd_i[ic]; jj1 < R_offd_i[ic + 1]; jj1++)
{
i1 = R_offd_j[jj1];
r_entry = R_offd_data[jj1];
/*-----------------------------------------------------------------
* Loop over entries in row i1 of A_offd.
*-----------------------------------------------------------------*/
for (jj2 = A_offd_i[i1]; jj2 < A_offd_i[i1 + 1]; jj2++)
{
i2 = A_offd_j[jj2];
r_a_product = r_entry * A_offd_data[jj2];
/*--------------------------------------------------------------
* Check A_marker to see if point i2 has been previously
* visited. New entries in RAP only occur from unmarked points.
*--------------------------------------------------------------*/
if (A_marker[i2] != ic)
{
/*-----------------------------------------------------------
* Mark i2 as visited.
*-----------------------------------------------------------*/
A_marker[i2] = ic;
/*-----------------------------------------------------------
* Loop over entries in row i2 of P_ext.
*-----------------------------------------------------------*/
for (jj3 = P_ext_diag_i[i2]; jj3 < P_ext_diag_i[i2 + 1]; jj3++)
{
i3 = P_ext_diag_j[jj3];
r_a_p_product = r_a_product * P_ext_diag_data[jj3];
/*--------------------------------------------------------
* Check P_marker to see that RAP_{ic,i3} has not already
* been accounted for. If it has not, create a new entry.
* If it has, add new contribution.
*--------------------------------------------------------*/
if (P_marker[i3] < jj_row_begining)
{
P_marker[i3] = jj_counter;
RAP_int_data[jj_counter] = r_a_p_product;
RAP_int_j[jj_counter] = (HYPRE_BigInt)i3 + first_col_diag_P;
jj_counter++;
}
else
{
RAP_int_data[P_marker[i3]] += r_a_p_product;
}
}
for (jj3 = P_ext_offd_i[i2]; jj3 < P_ext_offd_i[i2 + 1]; jj3++)
{
i3 = P_ext_offd_j[jj3] + num_cols_diag_P;
r_a_p_product = r_a_product * P_ext_offd_data[jj3];
/*--------------------------------------------------------
* Check P_marker to see that RAP_{ic,i3} has not already
* been accounted for. If it has not, create a new entry.
* If it has, add new contribution.
*--------------------------------------------------------*/
if (P_marker[i3] < jj_row_begining)
{
P_marker[i3] = jj_counter;
RAP_int_data[jj_counter] = r_a_p_product;
RAP_int_j[jj_counter]
= col_map_offd_Pext[i3 - num_cols_diag_P];
jj_counter++;
}
else
{
RAP_int_data[P_marker[i3]] += r_a_p_product;
}
}
}
/*--------------------------------------------------------------
* If i2 is previously visited ( A_marker[12]=ic ) it yields
* no new entries in RAP and can just add new contributions.
*--------------------------------------------------------------*/
else
{
for (jj3 = P_ext_diag_i[i2]; jj3 < P_ext_diag_i[i2 + 1]; jj3++)
{
i3 = P_ext_diag_j[jj3];
r_a_p_product = r_a_product * P_ext_diag_data[jj3];
RAP_int_data[P_marker[i3]] += r_a_p_product;
}
for (jj3 = P_ext_offd_i[i2]; jj3 < P_ext_offd_i[i2 + 1]; jj3++)
{
i3 = P_ext_offd_j[jj3] + num_cols_diag_P;
r_a_p_product = r_a_product * P_ext_offd_data[jj3];
RAP_int_data[P_marker[i3]] += r_a_p_product;
}
}
}
/*-----------------------------------------------------------------
* Loop over entries in row i1 of A_diag.
*-----------------------------------------------------------------*/
for (jj2 = A_diag_i[i1]; jj2 < A_diag_i[i1 + 1]; jj2++)
{
i2 = A_diag_j[jj2];
r_a_product = r_entry * A_diag_data[jj2];
/*--------------------------------------------------------------
* Check A_marker to see if point i2 has been previously
* visited. New entries in RAP only occur from unmarked points.
*--------------------------------------------------------------*/
if (A_marker[i2 + num_cols_offd_A] != ic)
{
/*-----------------------------------------------------------
* Mark i2 as visited.
*-----------------------------------------------------------*/
A_marker[i2 + num_cols_offd_A] = ic;
/*-----------------------------------------------------------
* Loop over entries in row i2 of P_diag.
*-----------------------------------------------------------*/
for (jj3 = P_diag_i[i2]; jj3 < P_diag_i[i2 + 1]; jj3++)
{
i3 = P_diag_j[jj3];
r_a_p_product = r_a_product * P_diag_data[jj3];
/*--------------------------------------------------------
* Check P_marker to see that RAP_{ic,i3} has not already
* been accounted for. If it has not, create a new entry.
* If it has, add new contribution.
*--------------------------------------------------------*/
if (P_marker[i3] < jj_row_begining)
{
P_marker[i3] = jj_counter;
RAP_int_data[jj_counter] = r_a_p_product;
RAP_int_j[jj_counter] = (HYPRE_BigInt)i3 + first_col_diag_P;
jj_counter++;
}
else
{
RAP_int_data[P_marker[i3]] += r_a_p_product;
}
}
for (jj3 = P_offd_i[i2]; jj3 < P_offd_i[i2 + 1]; jj3++)
{
i3 = map_P_to_Pext[P_offd_j[jj3]] + num_cols_diag_P;
r_a_p_product = r_a_product * P_offd_data[jj3];
/*--------------------------------------------------------
* Check P_marker to see that RAP_{ic,i3} has not already
* been accounted for. If it has not, create a new entry.
* If it has, add new contribution.
*--------------------------------------------------------*/
if (P_marker[i3] < jj_row_begining)
{
P_marker[i3] = jj_counter;
RAP_int_data[jj_counter] = r_a_p_product;
RAP_int_j[jj_counter] =
col_map_offd_Pext[i3 - num_cols_diag_P];
jj_counter++;
}
else
{
RAP_int_data[P_marker[i3]] += r_a_p_product;
}
}
}
/*--------------------------------------------------------------
* If i2 is previously visited ( A_marker[12]=ic ) it yields
* no new entries in RAP and can just add new contributions.
*--------------------------------------------------------------*/
else
{
for (jj3 = P_diag_i[i2]; jj3 < P_diag_i[i2 + 1]; jj3++)
{
i3 = P_diag_j[jj3];
r_a_p_product = r_a_product * P_diag_data[jj3];
RAP_int_data[P_marker[i3]] += r_a_p_product;
}
for (jj3 = P_offd_i[i2]; jj3 < P_offd_i[i2 + 1]; jj3++)
{
i3 = map_P_to_Pext[P_offd_j[jj3]] + num_cols_diag_P;
r_a_p_product = r_a_product * P_offd_data[jj3];
RAP_int_data[P_marker[i3]] += r_a_p_product;
}
}
}
}
}
if (num_cols_offd_Pext || num_cols_diag_P)
{
hypre_TFree(P_mark_array[ii], HYPRE_MEMORY_HOST);
}
hypre_TFree(A_mark_array[ii], HYPRE_MEMORY_HOST);
}
RAP_int = hypre_CSRMatrixCreate(num_cols_offd_RT, num_rows_offd_RT, RAP_size);
hypre_CSRMatrixMemoryLocation(RAP_int) = HYPRE_MEMORY_HOST;
hypre_CSRMatrixI(RAP_int) = RAP_int_i;
hypre_CSRMatrixBigJ(RAP_int) = RAP_int_j;
hypre_CSRMatrixData(RAP_int) = RAP_int_data;
hypre_TFree(jj_count, HYPRE_MEMORY_HOST);
}
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX] -= hypre_MPI_Wtime();
hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX_RAP] -= hypre_MPI_Wtime();
#endif
RAP_ext_size = 0;
if (num_sends_RT || num_recvs_RT)
{
void *request;
hypre_ExchangeExternalRowsInit(RAP_int, comm_pkg_RT, &request);
RAP_ext = hypre_ExchangeExternalRowsWait(request);
RAP_ext_i = hypre_CSRMatrixI(RAP_ext);
RAP_ext_j = hypre_CSRMatrixBigJ(RAP_ext);
RAP_ext_data = hypre_CSRMatrixData(RAP_ext);
RAP_ext_size = RAP_ext_i[hypre_CSRMatrixNumRows(RAP_ext)];
}
if (num_cols_offd_RT)
{
hypre_CSRMatrixDestroy(RAP_int);
RAP_int = NULL;
}
RAP_diag_i = hypre_TAlloc(HYPRE_Int, num_cols_diag_RT + 1, HYPRE_MEMORY_DEVICE);
RAP_offd_i = hypre_TAlloc(HYPRE_Int, num_cols_diag_RT + 1, HYPRE_MEMORY_DEVICE);
first_col_diag_RAP = first_col_diag_P;
last_col_diag_RAP = first_col_diag_P + num_cols_diag_P - 1;
/*-----------------------------------------------------------------------
* check for new nonzero columns in RAP_offd generated through RAP_ext
*-----------------------------------------------------------------------*/
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
hypre_UnorderedBigIntMap col_map_offd_RAP_inverse;
if (RAP_ext_size || num_cols_offd_Pext)
{
hypre_UnorderedBigIntSet found_set;
hypre_UnorderedBigIntSetCreate(&found_set, 2 * (RAP_ext_size + num_cols_offd_Pext),
16 * hypre_NumThreads());
cnt = 0;
#pragma omp parallel private(i)
{
#pragma omp for HYPRE_SMP_SCHEDULE
for (i = 0; i < RAP_ext_size; i++)
{
if (RAP_ext_j[i] < first_col_diag_RAP
|| RAP_ext_j[i] > last_col_diag_RAP)
{
hypre_UnorderedBigIntSetPut(&found_set, RAP_ext_j[i]);
}
}
#pragma omp for HYPRE_SMP_SCHEDULE
for (i = 0; i < num_cols_offd_Pext; i++)
{
hypre_UnorderedBigIntSetPut(&found_set, col_map_offd_Pext[i]);
}
} /* omp parallel */
temp = hypre_UnorderedBigIntSetCopyToArray(&found_set, &num_cols_offd_RAP);
hypre_UnorderedBigIntSetDestroy(&found_set);
hypre_big_sort_and_create_inverse_map(temp, num_cols_offd_RAP, &col_map_offd_RAP,
&col_map_offd_RAP_inverse);
}
#else /* !HYPRE_CONCURRENT_HOPSCOTCH */
if (RAP_ext_size || num_cols_offd_Pext)
{
temp = hypre_CTAlloc(HYPRE_BigInt, RAP_ext_size + num_cols_offd_Pext, HYPRE_MEMORY_HOST);
cnt = 0;
for (i = 0; i < RAP_ext_size; i++)
if (RAP_ext_j[i] < first_col_diag_RAP
|| RAP_ext_j[i] > last_col_diag_RAP)
{
temp[cnt++] = RAP_ext_j[i];
}
for (i = 0; i < num_cols_offd_Pext; i++)
{
temp[cnt++] = col_map_offd_Pext[i];
}
if (cnt)
{
hypre_BigQsort0(temp, 0, cnt - 1);
HYPRE_BigInt value = temp[0];
num_cols_offd_RAP = 1;
for (i = 1; i < cnt; i++)
{
if (temp[i] > value)
{
value = temp[i];
temp[num_cols_offd_RAP++] = value;
}
}
}
/* now evaluate col_map_offd_RAP */
if (num_cols_offd_RAP)
{
col_map_offd_RAP = hypre_CTAlloc(HYPRE_BigInt, num_cols_offd_RAP, HYPRE_MEMORY_HOST);
}
for (i = 0 ; i < num_cols_offd_RAP; i++)
{
col_map_offd_RAP[i] = temp[i];
}
hypre_TFree(temp, HYPRE_MEMORY_HOST);
}
#endif /* !HYPRE_CONCURRENT_HOPSCOTCH */
if (num_cols_offd_P)
{
map_P_to_RAP = hypre_TAlloc(HYPRE_Int, num_cols_offd_P, HYPRE_MEMORY_HOST);
cnt = 0;
for (i = 0; i < num_cols_offd_RAP; i++)
if (col_map_offd_RAP[i] == col_map_offd_P[cnt])
{
map_P_to_RAP[cnt++] = i;
if (cnt == num_cols_offd_P) { break; }
}
}
if (num_cols_offd_Pext)
{
map_Pext_to_RAP = hypre_TAlloc(HYPRE_Int, num_cols_offd_Pext, HYPRE_MEMORY_HOST);
cnt = 0;
for (i = 0; i < num_cols_offd_RAP; i++)
if (col_map_offd_RAP[i] == col_map_offd_Pext[cnt])
{
map_Pext_to_RAP[cnt++] = i;
if (cnt == num_cols_offd_Pext) { break; }
}
}
/*-----------------------------------------------------------------------
* Convert RAP_ext column indices
*-----------------------------------------------------------------------*/
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < RAP_ext_size; i++)
if (RAP_ext_j[i] < first_col_diag_RAP
|| RAP_ext_j[i] > last_col_diag_RAP)
RAP_ext_j[i] = (HYPRE_BigInt)num_cols_diag_P
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
+ (HYPRE_BigInt)hypre_UnorderedBigIntMapGet(&col_map_offd_RAP_inverse, RAP_ext_j[i]);
#else
+(HYPRE_BigInt)hypre_BigBinarySearch(col_map_offd_RAP, RAP_ext_j[i], num_cols_offd_RAP);
#endif
else
{
RAP_ext_j[i] -= first_col_diag_RAP;
}
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
if (num_cols_offd_RAP)
{
hypre_UnorderedBigIntMapDestroy(&col_map_offd_RAP_inverse);
}
#endif
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX] += hypre_MPI_Wtime();
hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX_RAP] += hypre_MPI_Wtime();
#endif
/* need to allocate new P_marker etc. and make further changes */
/*-----------------------------------------------------------------------
* Initialize some stuff.
*-----------------------------------------------------------------------*/
jj_cnt_diag = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);
jj_cnt_offd = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,j,k,jcol,ii,ic,i1,i2,i3,jj1,jj2,jj3,ns,ne,size,rest,jj_count_diag,jj_count_offd,jj_row_begin_diag,jj_row_begin_offd,A_marker,P_marker) HYPRE_SMP_SCHEDULE
#endif
for (ii = 0; ii < num_threads; ii++)
{
size = num_cols_diag_RT / num_threads;
rest = num_cols_diag_RT - size * num_threads;
if (ii < rest)
{
ns = ii * size + ii;
ne = (ii + 1) * size + ii + 1;
}
else
{
ns = ii * size + rest;
ne = (ii + 1) * size + rest;
}
P_mark_array[ii] = hypre_CTAlloc(HYPRE_Int, num_cols_diag_P + num_cols_offd_RAP,
HYPRE_MEMORY_HOST);
A_mark_array[ii] = hypre_CTAlloc(HYPRE_Int, num_nz_cols_A, HYPRE_MEMORY_HOST);
P_marker = P_mark_array[ii];
A_marker = A_mark_array[ii];
jj_count_diag = start_indexing;
jj_count_offd = start_indexing;
for (ic = 0; ic < num_cols_diag_P + num_cols_offd_RAP; ic++)
{
P_marker[ic] = -1;
}
for (i = 0; i < num_nz_cols_A; i++)
{
A_marker[i] = -1;
}
/*-----------------------------------------------------------------------
* Loop over interior c-points.
*-----------------------------------------------------------------------*/
for (ic = ns; ic < ne; ic++)
{
/*--------------------------------------------------------------------
* Set marker for diagonal entry, RAP_{ic,ic}. and for all points
* being added to row ic of RAP_diag and RAP_offd through RAP_ext
*--------------------------------------------------------------------*/
jj_row_begin_diag = jj_count_diag;
jj_row_begin_offd = jj_count_offd;
if (square)
{
P_marker[ic] = jj_count_diag++;
}
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
if (send_map_elmts_RT_inverse_map_initialized)
{
HYPRE_Int i = hypre_UnorderedIntMapGet(&send_map_elmts_RT_inverse_map, ic);
if (i != -1)
{
for (j = send_map_elmts_starts_RT_aggregated[i]; j < send_map_elmts_starts_RT_aggregated[i + 1];
j++)
{
HYPRE_Int jj = send_map_elmts_RT_aggregated[j];
for (k = RAP_ext_i[jj]; k < RAP_ext_i[jj + 1]; k++)
{
jcol = (HYPRE_Int)RAP_ext_j[k];
if (jcol < num_cols_diag_P)
{
if (P_marker[jcol] < jj_row_begin_diag)
{
P_marker[jcol] = jj_count_diag;
jj_count_diag++;
}
}
else
{
if (P_marker[jcol] < jj_row_begin_offd)
{
P_marker[jcol] = jj_count_offd;
jj_count_offd++;
}
}
}
}
} // if (set)
}
#else /* !HYPRE_CONCURRENT_HOPSCOTCH */
for (i = 0; i < num_sends_RT; i++)
for (j = send_map_starts_RT[i]; j < send_map_starts_RT[i + 1]; j++)
if (send_map_elmts_RT[j] == ic)
{
for (k = RAP_ext_i[j]; k < RAP_ext_i[j + 1]; k++)
{
jcol = (HYPRE_Int) RAP_ext_j[k];
if (jcol < num_cols_diag_P)
{
if (P_marker[jcol] < jj_row_begin_diag)
{
P_marker[jcol] = jj_count_diag;
jj_count_diag++;
}
}
else
{
if (P_marker[jcol] < jj_row_begin_offd)
{
P_marker[jcol] = jj_count_offd;
jj_count_offd++;
}
}
}
break;
}
#endif /* !HYPRE_CONCURRENT_HOPSCOTCH */
/*--------------------------------------------------------------------
* Loop over entries in row ic of R_diag.
*--------------------------------------------------------------------*/
for (jj1 = R_diag_i[ic]; jj1 < R_diag_i[ic + 1]; jj1++)
{
i1 = R_diag_j[jj1];
/*-----------------------------------------------------------------
* Loop over entries in row i1 of A_offd.
*-----------------------------------------------------------------*/
if (num_cols_offd_A)
{
for (jj2 = A_offd_i[i1]; jj2 < A_offd_i[i1 + 1]; jj2++)
{
i2 = A_offd_j[jj2];
/*--------------------------------------------------------------
* Check A_marker to see if point i2 has been previously
* visited. New entries in RAP only occur from unmarked points.
*--------------------------------------------------------------*/
if (A_marker[i2] != ic)
{
/*-----------------------------------------------------------
* Mark i2 as visited.
*-----------------------------------------------------------*/
A_marker[i2] = ic;
/*-----------------------------------------------------------
* Loop over entries in row i2 of P_ext.
*-----------------------------------------------------------*/
for (jj3 = P_ext_diag_i[i2]; jj3 < P_ext_diag_i[i2 + 1]; jj3++)
{
i3 = P_ext_diag_j[jj3];
/*--------------------------------------------------------
* Check P_marker to see that RAP_{ic,i3} has not already
* been accounted for. If it has not, mark it and increment
* counter.
*--------------------------------------------------------*/
if (P_marker[i3] < jj_row_begin_diag)
{
P_marker[i3] = jj_count_diag;
jj_count_diag++;
}
}
for (jj3 = P_ext_offd_i[i2]; jj3 < P_ext_offd_i[i2 + 1]; jj3++)
{
i3 = map_Pext_to_RAP[P_ext_offd_j[jj3]] + num_cols_diag_P;
/*--------------------------------------------------------
* Check P_marker to see that RAP_{ic,i3} has not already
* been accounted for. If it has not, mark it and increment
* counter.
*--------------------------------------------------------*/
if (P_marker[i3] < jj_row_begin_offd)
{
P_marker[i3] = jj_count_offd;
jj_count_offd++;
}
}
}
}
}
/*-----------------------------------------------------------------
* Loop over entries in row i1 of A_diag.
*-----------------------------------------------------------------*/
for (jj2 = A_diag_i[i1]; jj2 < A_diag_i[i1 + 1]; jj2++)
{
i2 = A_diag_j[jj2];
/*--------------------------------------------------------------
* Check A_marker to see if point i2 has been previously
* visited. New entries in RAP only occur from unmarked points.
*--------------------------------------------------------------*/
if (A_marker[i2 + num_cols_offd_A] != ic)
{
/*-----------------------------------------------------------
* Mark i2 as visited.
*-----------------------------------------------------------*/
A_marker[i2 + num_cols_offd_A] = ic;
/*-----------------------------------------------------------
* Loop over entries in row i2 of P_diag.
*-----------------------------------------------------------*/
for (jj3 = P_diag_i[i2]; jj3 < P_diag_i[i2 + 1]; jj3++)
{
i3 = P_diag_j[jj3];
/*--------------------------------------------------------
* Check P_marker to see that RAP_{ic,i3} has not already
* been accounted for. If it has not, mark it and increment
* counter.
*--------------------------------------------------------*/
if (P_marker[i3] < jj_row_begin_diag)
{
P_marker[i3] = jj_count_diag;
jj_count_diag++;
}
}
/*-----------------------------------------------------------
* Loop over entries in row i2 of P_offd.
*-----------------------------------------------------------*/
if (num_cols_offd_P)
{
for (jj3 = P_offd_i[i2]; jj3 < P_offd_i[i2 + 1]; jj3++)
{
i3 = map_P_to_RAP[P_offd_j[jj3]] + num_cols_diag_P;
/*--------------------------------------------------------
* Check P_marker to see that RAP_{ic,i3} has not already
* been accounted for. If it has not, mark it and increment
* counter.
*--------------------------------------------------------*/
if (P_marker[i3] < jj_row_begin_offd)
{
P_marker[i3] = jj_count_offd;
jj_count_offd++;
}
}
}
}
}
}
/*--------------------------------------------------------------------
* Set RAP_diag_i and RAP_offd_i for this row.
*--------------------------------------------------------------------*/
/*
RAP_diag_i[ic] = jj_row_begin_diag;
RAP_offd_i[ic] = jj_row_begin_offd;
*/
}
jj_cnt_diag[ii] = jj_count_diag;
jj_cnt_offd[ii] = jj_count_offd;
}
for (i = 0; i < num_threads - 1; i++)
{
jj_cnt_diag[i + 1] += jj_cnt_diag[i];
jj_cnt_offd[i + 1] += jj_cnt_offd[i];
}
jj_count_diag = jj_cnt_diag[num_threads - 1];
jj_count_offd = jj_cnt_offd[num_threads - 1];
RAP_diag_i[num_cols_diag_RT] = jj_count_diag;
RAP_offd_i[num_cols_diag_RT] = jj_count_offd;
/*-----------------------------------------------------------------------
* Allocate RAP_diag_data and RAP_diag_j arrays.
* Allocate RAP_offd_data and RAP_offd_j arrays.
*-----------------------------------------------------------------------*/
RAP_diag_size = jj_count_diag;
if (RAP_diag_size)
{
RAP_diag_data = hypre_CTAlloc(HYPRE_Real, RAP_diag_size, HYPRE_MEMORY_DEVICE);
RAP_diag_j = hypre_CTAlloc(HYPRE_Int, RAP_diag_size, HYPRE_MEMORY_DEVICE);
}
RAP_offd_size = jj_count_offd;
if (RAP_offd_size)
{
RAP_offd_data = hypre_CTAlloc(HYPRE_Real, RAP_offd_size, HYPRE_MEMORY_DEVICE);
RAP_offd_j = hypre_CTAlloc(HYPRE_Int, RAP_offd_size, HYPRE_MEMORY_DEVICE);
}
if (RAP_offd_size == 0 && num_cols_offd_RAP != 0)
{
num_cols_offd_RAP = 0;
hypre_TFree(col_map_offd_RAP, HYPRE_MEMORY_HOST);
}
RA_diag_data_array = hypre_TAlloc(HYPRE_Real, num_cols_diag_A * num_threads, HYPRE_MEMORY_HOST);
RA_diag_j_array = hypre_TAlloc(HYPRE_Int, num_cols_diag_A * num_threads, HYPRE_MEMORY_HOST);
if (num_cols_offd_A)
{
RA_offd_data_array = hypre_TAlloc(HYPRE_Real, num_cols_offd_A * num_threads, HYPRE_MEMORY_HOST);
RA_offd_j_array = hypre_TAlloc(HYPRE_Int, num_cols_offd_A * num_threads, HYPRE_MEMORY_HOST);
}
/*-----------------------------------------------------------------------
* Second Pass: Fill in RAP_diag_data and RAP_diag_j.
* Second Pass: Fill in RAP_offd_data and RAP_offd_j.
*-----------------------------------------------------------------------*/
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,j,k,jcol,ii,ic,i1,i2,i3,jj1,jj2,jj3,ns,ne,size,rest,jj_count_diag,jj_count_offd,jj_row_begin_diag,jj_row_begin_offd,A_marker,P_marker,r_entry,r_a_product,r_a_p_product) HYPRE_SMP_SCHEDULE
#endif
for (ii = 0; ii < num_threads; ii++)
{
size = num_cols_diag_RT / num_threads;
rest = num_cols_diag_RT - size * num_threads;
if (ii < rest)
{
ns = ii * size + ii;
ne = (ii + 1) * size + ii + 1;
}
else
{
ns = ii * size + rest;
ne = (ii + 1) * size + rest;
}
/*-----------------------------------------------------------------------
* Initialize some stuff.
*-----------------------------------------------------------------------*/
P_marker = P_mark_array[ii];
A_marker = A_mark_array[ii];
for (ic = 0; ic < num_cols_diag_P + num_cols_offd_RAP; ic++)
{
P_marker[ic] = -1;
}
for (i = 0; i < num_nz_cols_A ; i++)
{
A_marker[i] = -1;
}
jj_count_diag = start_indexing;
jj_count_offd = start_indexing;
if (ii > 0)
{
jj_count_diag = jj_cnt_diag[ii - 1];
jj_count_offd = jj_cnt_offd[ii - 1];
}
// temporal matrix RA = R*A
// only need to store one row per thread because R*A and (R*A)*P are fused
// into one loop.
hypre_CSRMatrix RA_diag, RA_offd;
RA_diag.data = RA_diag_data_array + num_cols_diag_A * ii;
RA_diag.j = RA_diag_j_array + num_cols_diag_A * ii;
RA_diag.num_nonzeros = 0;
RA_offd.num_nonzeros = 0;
if (num_cols_offd_A)
{
RA_offd.data = RA_offd_data_array + num_cols_offd_A * ii;
RA_offd.j = RA_offd_j_array + num_cols_offd_A * ii;
}
/*-----------------------------------------------------------------------
* Loop over interior c-points.
*-----------------------------------------------------------------------*/
for (ic = ns; ic < ne; ic++)
{
/*--------------------------------------------------------------------
* Create diagonal entry, RAP_{ic,ic} and add entries of RAP_ext
*--------------------------------------------------------------------*/
jj_row_begin_diag = jj_count_diag;
jj_row_begin_offd = jj_count_offd;
RAP_diag_i[ic] = jj_row_begin_diag;
RAP_offd_i[ic] = jj_row_begin_offd;
HYPRE_Int ra_row_begin_diag = RA_diag.num_nonzeros;
HYPRE_Int ra_row_begin_offd = RA_offd.num_nonzeros;
if (square)
{
P_marker[ic] = jj_count_diag;
RAP_diag_data[jj_count_diag] = zero;
RAP_diag_j[jj_count_diag] = ic;
jj_count_diag++;
}
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
if (send_map_elmts_RT_inverse_map_initialized)
{
HYPRE_Int i = hypre_UnorderedIntMapGet(&send_map_elmts_RT_inverse_map, ic);
if (i != -1)
{
for (j = send_map_elmts_starts_RT_aggregated[i]; j < send_map_elmts_starts_RT_aggregated[i + 1];
j++)
{
HYPRE_Int jj = send_map_elmts_RT_aggregated[j];
for (k = RAP_ext_i[jj]; k < RAP_ext_i[jj + 1]; k++)
{
jcol = (HYPRE_Int)RAP_ext_j[k];
if (jcol < num_cols_diag_P)
{
if (P_marker[jcol] < jj_row_begin_diag)
{
P_marker[jcol] = jj_count_diag;
RAP_diag_data[jj_count_diag]
= RAP_ext_data[k];
RAP_diag_j[jj_count_diag] = jcol;
jj_count_diag++;
}
else
RAP_diag_data[P_marker[jcol]]
+= RAP_ext_data[k];
}
else
{
if (P_marker[jcol] < jj_row_begin_offd)
{
P_marker[jcol] = jj_count_offd;
RAP_offd_data[jj_count_offd]
= RAP_ext_data[k];
RAP_offd_j[jj_count_offd]
= jcol - num_cols_diag_P;
jj_count_offd++;
}
else
RAP_offd_data[P_marker[jcol]]
+= RAP_ext_data[k];
}
}
}
} // if (set)
}
#else /* !HYPRE_CONCURRENT_HOPSCOTCH */
for (i = 0; i < num_sends_RT; i++)
for (j = send_map_starts_RT[i]; j < send_map_starts_RT[i + 1]; j++)
if (send_map_elmts_RT[j] == ic)
{
for (k = RAP_ext_i[j]; k < RAP_ext_i[j + 1]; k++)
{
jcol = (HYPRE_Int)RAP_ext_j[k];
if (jcol < num_cols_diag_P)
{
if (P_marker[jcol] < jj_row_begin_diag)
{
P_marker[jcol] = jj_count_diag;
RAP_diag_data[jj_count_diag]
= RAP_ext_data[k];
RAP_diag_j[jj_count_diag] = jcol;
jj_count_diag++;
}
else
RAP_diag_data[P_marker[jcol]]
+= RAP_ext_data[k];
}
else
{
if (P_marker[jcol] < jj_row_begin_offd)
{
P_marker[jcol] = jj_count_offd;
RAP_offd_data[jj_count_offd]
= RAP_ext_data[k];
RAP_offd_j[jj_count_offd]
= jcol - num_cols_diag_P;
jj_count_offd++;
}
else
RAP_offd_data[P_marker[jcol]]
+= RAP_ext_data[k];
}
}
break;
}
#endif /* !HYPRE_CONCURRENT_HOPSCOTCH */
/*--------------------------------------------------------------------
* Loop over entries in row ic of R_diag and compute row ic of RA.
*--------------------------------------------------------------------*/
for (jj1 = R_diag_i[ic]; jj1 < R_diag_i[ic + 1]; jj1++)
{
i1 = R_diag_j[jj1];
r_entry = R_diag_data[jj1];
/*-----------------------------------------------------------------
* Loop over entries in row i1 of A_offd.
*-----------------------------------------------------------------*/
if (num_cols_offd_A)
{
for (jj2 = A_offd_i[i1]; jj2 < A_offd_i[i1 + 1]; jj2++)
{
i2 = A_offd_j[jj2];
HYPRE_Real a_entry = A_offd_data[jj2];
HYPRE_Int marker = A_marker[i2];
/*--------------------------------------------------------------
* Check A_marker to see if point i2 has been previously
* visited. New entries in RAP only occur from unmarked points.
*--------------------------------------------------------------*/
if (marker < ra_row_begin_offd)
{
/*-----------------------------------------------------------
* Mark i2 as visited.
*-----------------------------------------------------------*/
A_marker[i2] = RA_offd.num_nonzeros;
RA_offd.data[RA_offd.num_nonzeros - ra_row_begin_offd] = r_entry * a_entry;
RA_offd.j[RA_offd.num_nonzeros - ra_row_begin_offd] = i2;
RA_offd.num_nonzeros++;
}
/*--------------------------------------------------------------
* If i2 is previously visited ( A_marker[12]=ic ) it yields
* no new entries in RA and can just add new contributions.
*--------------------------------------------------------------*/
else
{
RA_offd.data[marker - ra_row_begin_offd] += r_entry * a_entry;
// JSP: compiler will more likely to generate FMA instructions
// when we don't eliminate common subexpressions of
// r_entry * A_offd_data[jj2] manually.
}
} // loop over entries in row i1 of A_offd
} // num_cols_offd_A
/*-----------------------------------------------------------------
* Loop over entries in row i1 of A_diag.
*-----------------------------------------------------------------*/
for (jj2 = A_diag_i[i1]; jj2 < A_diag_i[i1 + 1]; jj2++)
{
i2 = A_diag_j[jj2];
HYPRE_Real a_entry = A_diag_data[jj2];
HYPRE_Int marker = A_marker[i2 + num_cols_offd_A];
/*--------------------------------------------------------------
* Check A_marker to see if point i2 has been previously
* visited. New entries in RAP only occur from unmarked points.
*--------------------------------------------------------------*/
if (marker < ra_row_begin_diag)
{
/*-----------------------------------------------------------
* Mark i2 as visited.
*-----------------------------------------------------------*/
A_marker[i2 + num_cols_offd_A] = RA_diag.num_nonzeros;
RA_diag.data[RA_diag.num_nonzeros - ra_row_begin_diag] = r_entry * a_entry;
RA_diag.j[RA_diag.num_nonzeros - ra_row_begin_diag] = i2;
RA_diag.num_nonzeros++;
}
/*--------------------------------------------------------------
* If i2 is previously visited ( A_marker[12]=ic ) it yields
* no new entries in RA and can just add new contributions.
*--------------------------------------------------------------*/
else
{
RA_diag.data[marker - ra_row_begin_diag] += r_entry * a_entry;
}
} // loop over entries in row i1 of A_diag
} // loop over entries in row ic of R_diag
/*--------------------------------------------------------------------
* Loop over entries in row ic of RA_offd.
*--------------------------------------------------------------------*/
for (jj1 = ra_row_begin_offd; jj1 < RA_offd.num_nonzeros; jj1++)
{
i1 = RA_offd.j[jj1 - ra_row_begin_offd];
r_a_product = RA_offd.data[jj1 - ra_row_begin_offd];
/*-----------------------------------------------------------
* Loop over entries in row i1 of P_ext.
*-----------------------------------------------------------*/
for (jj2 = P_ext_diag_i[i1]; jj2 < P_ext_diag_i[i1 + 1]; jj2++)
{
i2 = P_ext_diag_j[jj2];
HYPRE_Real p_entry = P_ext_diag_data[jj2];
HYPRE_Int marker = P_marker[i2];
/*--------------------------------------------------------
* Check P_marker to see that RAP_{ic,i2} has not already
* been accounted for. If it has not, create a new entry.
* If it has, add new contribution.
*--------------------------------------------------------*/
if (marker < jj_row_begin_diag)
{
P_marker[i2] = jj_count_diag;
RAP_diag_data[jj_count_diag] = r_a_product * p_entry;
RAP_diag_j[jj_count_diag] = i2;
jj_count_diag++;
}
else
{
RAP_diag_data[marker] += r_a_product * p_entry;
}
}
for (jj2 = P_ext_offd_i[i1]; jj2 < P_ext_offd_i[i1 + 1]; jj2++)
{
i2 = map_Pext_to_RAP[P_ext_offd_j[jj2]] + num_cols_diag_P;
HYPRE_Real p_entry = P_ext_offd_data[jj2];
HYPRE_Int marker = P_marker[i2];
/*--------------------------------------------------------
* Check P_marker to see that RAP_{ic,i2} has not already
* been accounted for. If it has not, create a new entry.
* If it has, add new contribution.
*--------------------------------------------------------*/
if (marker < jj_row_begin_offd)
{
P_marker[i2] = jj_count_offd;
RAP_offd_data[jj_count_offd] = r_a_product * p_entry;
RAP_offd_j[jj_count_offd] = i2 - num_cols_diag_P;
jj_count_offd++;
}
else
{
RAP_offd_data[marker] += r_a_product * p_entry;
}
}
} // loop over entries in row ic of RA_offd
/*--------------------------------------------------------------------
* Loop over entries in row ic of RA_diag.
*--------------------------------------------------------------------*/
for (jj1 = ra_row_begin_diag; jj1 < RA_diag.num_nonzeros; jj1++)
{
HYPRE_Int i1 = RA_diag.j[jj1 - ra_row_begin_diag];
HYPRE_Real r_a_product = RA_diag.data[jj1 - ra_row_begin_diag];
/*-----------------------------------------------------------------
* Loop over entries in row i1 of P_diag.
*-----------------------------------------------------------------*/
for (jj2 = P_diag_i[i1]; jj2 < P_diag_i[i1 + 1]; jj2++)
{
i2 = P_diag_j[jj2];
HYPRE_Real p_entry = P_diag_data[jj2];
HYPRE_Int marker = P_marker[i2];
/*--------------------------------------------------------
* Check P_marker to see that RAP_{ic,i2} has not already
* been accounted for. If it has not, create a new entry.
* If it has, add new contribution.
*--------------------------------------------------------*/
if (marker < jj_row_begin_diag)
{
P_marker[i2] = jj_count_diag;
RAP_diag_data[jj_count_diag] = r_a_product * p_entry;
RAP_diag_j[jj_count_diag] = i2;
jj_count_diag++;
}
else
{
RAP_diag_data[marker] += r_a_product * p_entry;
}
}
if (num_cols_offd_P)
{
for (jj2 = P_offd_i[i1]; jj2 < P_offd_i[i1 + 1]; jj2++)
{
i2 = map_P_to_RAP[P_offd_j[jj2]] + num_cols_diag_P;
HYPRE_Real p_entry = P_offd_data[jj2];
HYPRE_Int marker = P_marker[i2];
/*--------------------------------------------------------
* Check P_marker to see that RAP_{ic,i2} has not already
* been accounted for. If it has not, create a new entry.
* If it has, add new contribution.
*--------------------------------------------------------*/
if (marker < jj_row_begin_offd)
{
P_marker[i2] = jj_count_offd;
RAP_offd_data[jj_count_offd] = r_a_product * p_entry;
RAP_offd_j[jj_count_offd] = i2 - num_cols_diag_P;
jj_count_offd++;
}
else
{
RAP_offd_data[marker] += r_a_product * p_entry;
}
}
} // num_cols_offd_P
} // loop over entries in row ic of RA_diag.
} // Loop over interior c-points.
hypre_TFree(P_mark_array[ii], HYPRE_MEMORY_HOST);
hypre_TFree(A_mark_array[ii], HYPRE_MEMORY_HOST);
} // omp parallel for
/* check if really all off-diagonal entries occurring in col_map_offd_RAP
are represented and eliminate if necessary */
P_marker = hypre_CTAlloc(HYPRE_Int, num_cols_offd_RAP, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_cols_offd_RAP; i++)
{
P_marker[i] = -1;
}
jj_count_offd = 0;
#ifdef HYPRE_USING_ATOMIC
#pragma omp parallel for private(i3) reduction(+:jj_count_offd) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < RAP_offd_size; i++)
{
i3 = RAP_offd_j[i];
#ifdef HYPRE_USING_ATOMIC
if (hypre_compare_and_swap(P_marker + i3, -1, 0) == -1)
{
jj_count_offd++;
}
#else
if (P_marker[i3])
{
P_marker[i3] = 0;
jj_count_offd++;
}
#endif
}
if (jj_count_offd < num_cols_offd_RAP)
{
new_col_map_offd_RAP = hypre_CTAlloc(HYPRE_BigInt, jj_count_offd, HYPRE_MEMORY_HOST);
jj_counter = 0;
for (i = 0; i < num_cols_offd_RAP; i++)
if (!P_marker[i])
{
P_marker[i] = jj_counter;
new_col_map_offd_RAP[jj_counter++] = col_map_offd_RAP[i];
}
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i3) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < RAP_offd_size; i++)
{
i3 = RAP_offd_j[i];
RAP_offd_j[i] = P_marker[i3];
}
num_cols_offd_RAP = jj_count_offd;
hypre_TFree(col_map_offd_RAP, HYPRE_MEMORY_HOST);
col_map_offd_RAP = new_col_map_offd_RAP;
}
hypre_TFree(P_marker, HYPRE_MEMORY_HOST);
RAP = hypre_ParCSRMatrixCreate(comm, n_coarse_RT, n_coarse,
RT_partitioning, coarse_partitioning,
num_cols_offd_RAP, RAP_diag_size,
RAP_offd_size);
RAP_diag = hypre_ParCSRMatrixDiag(RAP);
hypre_CSRMatrixI(RAP_diag) = RAP_diag_i;
if (RAP_diag_size)
{
hypre_CSRMatrixData(RAP_diag) = RAP_diag_data;
hypre_CSRMatrixJ(RAP_diag) = RAP_diag_j;
}
RAP_offd = hypre_ParCSRMatrixOffd(RAP);
hypre_CSRMatrixI(RAP_offd) = RAP_offd_i;
if (num_cols_offd_RAP)
{
hypre_CSRMatrixData(RAP_offd) = RAP_offd_data;
hypre_CSRMatrixJ(RAP_offd) = RAP_offd_j;
hypre_ParCSRMatrixColMapOffd(RAP) = col_map_offd_RAP;
}
if (num_procs > 1)
{
/* hypre_GenerateRAPCommPkg(RAP, A); */
hypre_MatvecCommPkgCreate(RAP);
}
*RAP_ptr = RAP;
/*-----------------------------------------------------------------------
* Free R, P_ext and marker arrays.
*-----------------------------------------------------------------------*/
if (keepTranspose)
{
hypre_ParCSRMatrixDiagT(RT) = R_diag;
}
else
{
hypre_CSRMatrixDestroy(R_diag);
}
R_diag = NULL;
if (num_cols_offd_RT)
{
if (keepTranspose)
{
hypre_ParCSRMatrixOffdT(RT) = R_offd;
}
else
{
hypre_CSRMatrixDestroy(R_offd);
}
R_offd = NULL;
}
if (num_sends_RT || num_recvs_RT)
{
hypre_CSRMatrixDestroy(RAP_ext);
RAP_ext = NULL;
}
hypre_TFree(P_mark_array, HYPRE_MEMORY_HOST);
hypre_TFree(A_mark_array, HYPRE_MEMORY_HOST);
hypre_TFree(P_ext_diag_i, HYPRE_MEMORY_HOST);
hypre_TFree(P_ext_offd_i, HYPRE_MEMORY_HOST);
hypre_TFree(jj_cnt_diag, HYPRE_MEMORY_HOST);
hypre_TFree(jj_cnt_offd, HYPRE_MEMORY_HOST);
if (num_cols_offd_P)
{
hypre_TFree(map_P_to_Pext, HYPRE_MEMORY_HOST);
hypre_TFree(map_P_to_RAP, HYPRE_MEMORY_HOST);
}
if (num_cols_offd_Pext)
{
hypre_TFree(col_map_offd_Pext, HYPRE_MEMORY_HOST);
hypre_TFree(map_Pext_to_RAP, HYPRE_MEMORY_HOST);
}
if (P_ext_diag_size)
{
hypre_TFree(P_ext_diag_data, HYPRE_MEMORY_HOST);
hypre_TFree(P_ext_diag_j, HYPRE_MEMORY_HOST);
}
if (P_ext_offd_size)
{
hypre_TFree(P_ext_offd_data, HYPRE_MEMORY_HOST);
hypre_TFree(P_ext_offd_j, HYPRE_MEMORY_HOST);
}
hypre_TFree(RA_diag_data_array, HYPRE_MEMORY_HOST);
hypre_TFree(RA_diag_j_array, HYPRE_MEMORY_HOST);
if (num_cols_offd_A)
{
hypre_TFree(RA_offd_data_array, HYPRE_MEMORY_HOST);
hypre_TFree(RA_offd_j_array, HYPRE_MEMORY_HOST);
}
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
if (send_map_elmts_RT_inverse_map_initialized)
{
hypre_UnorderedIntMapDestroy(&send_map_elmts_RT_inverse_map);
}
hypre_TFree(send_map_elmts_starts_RT_aggregated, HYPRE_MEMORY_HOST);
hypre_TFree(send_map_elmts_RT_aggregated, HYPRE_MEMORY_HOST);
#endif
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_RAP] += hypre_MPI_Wtime();
#endif
return (0);
}
|
eddy_diff_sfdiag_impl.h |
#ifndef __EDDY_DIFF_SFDIAG_IMPL_H__
#define __EDDY_DIFF_SFDIAG_IMPL_H__
#ifndef EDDY_DIFF_SFDIAG_IMPL_VERSION_MAJOR
#define EDDY_DIFF_SFDIAG_IMPL_VERSION_MAJOR 1
#endif
#ifndef EDDY_DIFF_SFDIAG_IMPL_VERSION_MINOR
#define EDDY_DIFF_SFDIAG_IMPL_VERSION_MINOR 0
#endif
#ifndef EDDY_DIFF_SFDIAG_IMPL_PATCH_VERSION
#define EDDY_DIFF_SFDIAG_IMPL_PATCH_VERSION 0
#endif
#ifndef EDDY_DIFF_SFDIAG_IMPL_CREATE_DATE
#define EDDY_DIFF_SFDIAG_IMPL_CREATE_DATE "Date: 25-10-2016 , Time: 18:09 PM GMT+2"
#endif
#ifndef EDDY_DIFF_SFDIAG_IMPL_BUILD_DATE
#define EDDY_DIFF_SFDIAG_IMPL_BUILD_DATE ""
#endif
#ifndef EDDY_DIFF_SFDIAG_IMPL_AUTHOR
#define EDDY_DIFF_SFDIAG_IMPL_AUTHOR "Name: Bernard Gingold , e-mail: beniekg@gmail.com"
#endif
#include "module_cam_bl_eddy_diff_F90_iface.h"
#include "PhysLib_Config.h"
#include "std_headers.h"
namespace phys_lib_wrappers {
namespace module_eddy_diff {
/*
* Wrapping structure called 'Wrap_Sfdiag' its main
* purpose is to present herself as high level wrapper interface
* to underlying Fortran 90 'SFDIAG' subroutine.
* Notification:
* 'EDDY_DIFF_mp_SFDIAG' subroutine is module
* internal (private) and should not be called
* directly by C++ code side.
*/
template<typename R64 = double,
typename I32 = int > struct Wrap_Sfdiag {
/*******************************
Constructors and Destructor.
********************************/
/*
@Purpose:
Default Constructor - explicitly default.
*/
Wrap_Sfdiag() = default;
/*
@Purpose:
1st 'main' Constructor which purpose
is to allocate and initialize scalar
and array members. Array members are
zero-filled. Caller must later initialize
input arrays to correct physical state.
*/
Wrap_Sfdiag(_In_ const I32 pcols,
_In_ const I32 pver,
_In_ const I32 ncol,
_In_ const I32 qsat)
:
m_pcols{ pcols },
m_pver{ pver },
m_ncol{ ncol },
m_qsat{ qsat },
m_qt{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) },
m_ql{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) },
m_sl{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) },
m_pi{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * (m_pver + 1) * sizeof(R64)), align32B)) },
m_pm{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) },
m_zi{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * (m_pver + 1) * sizeof(R64)), align32B)) },
m_cld{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) },
m_sfi{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * (m_pver + 1) * sizeof(R64)), align32B)) },
m_sfuh{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) },
m_sflh{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) },
m_slslope{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) },
m_qtslope{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) } {
// Check for memory allocation errors (malloc failure).
for (int i{ 0 }; i != this->m_nArrays; ++i) {
if ((&this->m_qt)[i] == NULL) {
std::cerr << "[" << __DATE__ << ":" << __TIME__ << "]" << "FATAL ERROR: Memory allocation failure in 1st Ctor Wrap_Sfdiag!!\n";
std::cerr << "at " << __FILE__ << ":" << __LINE__ << "(" << std::hex << "0x" << __FUNCTIONW__ << ")" << "\n";
std::cerr << "***** ERROR-DETAILS ***** \n";
std::cerr << "Failure detected at index: " << i << " heap address: " << std::hex << "0x" << (&this->m_qt)[i] << "\n";
std::cerr << "Cannot recover, hence on first failure occurrence --> calling exit(-1)!!\n";
std::exit(-1);
}
}
// Zero-initialize arrays.
#if defined (USE_ICL_OPENMP) && \
OPENMP_CURR_VER >= 40
#pragma omp parallel for if((m_pcols * m_pver) >= (1 << 20))
for (int i{ 0 }; i != this->m_pcols; ++i) {
#if defined (USE_AUTO_VECTORIZATION)
#pragma ivdep
#pragma simd
#pragma unroll(UNROLL_4X)
#endif
for(int j{ 0 }; j != this->m_pver; ++j) {
this->m_qt[i + m_pcols * j] = 0.0;
this->m_ql[i + m_pcols * j] = 0.0;
this->m_sl[i + m_pcols * j] = 0.0;
this->m_pi[i + m_pcols * j] = 0.0;
this->m_pm[i + m_pcols * j] = 0.0;
this->m_zi[i + m_pcols * j] = 0.0;
this->m_cld[i + m_pcols * j] = 0.0;
this->m_sfi[i + m_pcols * j] = 0.0;
this->m_sfuh[i + m_pcols * j] = 0.0;
this->m_sflh[i + m_pcols * j] = 0.0;
this->m_slslope[i + m_pcols * j] = 0.0;
this->m_qtslope[i + m_pcols * j] = 0.0;
}
}
// Copy top element == 0.0 to arrays 2D
// where m_pver == m_pver + 1.
const int top = this->m_pcols * (this->m_pver + 1);
this->m_pi[top] = 0.0;
this->m_zi[top] = 0.0;
this->m_sfi[top] = 0.0;
#else
// Use loop blocking.
// Warning: You must not #undef 'USE_LOOP_BLOCKING' macro!!
#if defined (USE_LOOP_BLOCKING)
for (int i{ 0 }; i < m_pcols; i += DEFAULT_BLOCK_SIZE) {
for (int j{ 0 }; j < m_pver; j += DEFAULT_BLOCK_SIZE) {
for (int ii = i; ii < DEFAULT_BLOCK_SIZE; ++ii) {
#if defined (USE_AUTO_VECTORIZATION)
#pragma ivdep
#pragma simd
#endif
for (int jj = j; jj < DEFAULT_BLOCK_SIZE; ++jj) {
this->m_qt[ii + m_pcols * jj] = 0.0;
this->m_ql[ii + m_pcols * jj] = 0.0;
this->m_sl[ii + m_pcols * jj] = 0.0;
this->m_pi[ii + m_pcols * jj] = 0.0;
this->m_pm[ii + m_pcols * jj] = 0.0;
this->m_zi[ii + m_pcols * jj] = 0.0;
this->m_cld[ii + m_pcols * jj] = 0.0;
this->m_sfi[ii + m_pcols * jj] = 0.0;
this->m_sfuh[ii + m_pcols * jj] = 0.0;
this->m_sflh[ii + m_pcols * jj] = 0.0;
this->m_slslope[ii + m_pcols * jj] = 0.0;
this->m_qtslope[ii + m_pcols * jj] = 0.0;
}
}
}
}
#endif
// Copy top element == 0.0 to arrays 2D
// where m_pver == m_pver + 1.
const int top = this->m_pcols * (this->m_pver + 1);
this->m_pi[top] = 0.0;
this->m_zi[top] = 0.0;
this->m_sfi[top] = 0.0;
#endif
}
/*
@Purpose:
2nd 'main' Constructor which purpose
is to allocate and initialize scalar
and array members. Array output members are
zero-filled. Caller must pass initialized
input arrays to correct physical state.
*/
Wrap_Sfdiag(_In_ const I32 pcols,
_In_ const I32 pver,
_In_ const I32 ncol,
_In_ const I32 qsat,
_In_ R64* __restrict const qt,
_In_ R64* __restrict const ql,
_In_ R64* __restrict const sl,
_In_ R64* __restrict const pi,
_In_ R64* __restrict const pm,
_In_ R64* __restrict const zi,
_In_ R64* __restrict const cld,
_In_ R64* __restrict const slslope,
_In_ R64* __restrict const qtslope)
:
m_pcols{ pcols },
m_pver{ pver },
m_ncol{ ncol },
m_qsat{ qsat },
m_qt{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) },
m_ql{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) },
m_sl{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) },
m_pi{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * (m_pver + 1) * sizeof(R64)), align32B)) },
m_pm{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) },
m_zi{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * (m_pver + 1) * sizeof(R64)), align32B)) },
m_cld{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) },
m_sfi{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * (m_pver + 1) * sizeof(R64)), align32B)) },
m_sfuh{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) },
m_sflh{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) },
m_slslope{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) },
m_qtslope{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) } {
// Check for memory allocation errors (malloc failures).
for (int i{ 0 }; i != this->m_nArrays; ++i) {
if ((&this->m_qt)[i] == NULL) {
std::cerr << "[" << __DATE__ << ":" << __TIME__ << "]" << "FATAL ERROR: Memory allocation failure in 2nd Ctor Wrap_Sfdiag!!\n";
std::cerr << "at " << __FILE__ << ":" << __LINE__ << "(" << std::hex << "0x" << __FUNCTIONW__ << ")" << "\n";
std::cerr << "***** ERROR-DETAILS ***** \n";
std::cerr << "Failure detected at index: " << i << " heap address: " << std::hex << "0x" << (&this->m_qt)[i] << "\n";
std::cerr << "Cannot recover, hence on first failure occurrence --> calling exit(-1)!!\n";
std::exit(-1);
}
}
// Check input arrays for existance of NULL pointers.
if (qt == NULL ||
ql == NULL ||
sl == NULL ||
pi == NULL ||
pm == NULL ||
zi == NULL ||
cld == NULL ||
slslope == NULL ||
qtslope == NULL) {
std::cerr << "[" << __DATE__ << ":" << __TIME__ << "]" << "FATAL ERROR: Memory allocation failure in 2nd Ctor Wrap_Sfdiag!!\n";
std::cerr << "at " << __FILE__ << ":" << __LINE__ << "(" << std::hex << "0x" << __FUNCTIONW__ << ")" << "\n";
std::cerr << "***** ERROR-DETAILS ***** \n";
std::cerr << "One or more caller's arrays contains invalid pointer!!\n";
std::cerr << "Cannot recover, hence on first failure occurrence --> calling exit(-1)!!\n";
std::exit(-1);
}
// Copy input arrays and zero-initialize output arrays.
#if defined (USE_ICL_OPENMP) && \
OPENMP_CURR_VER >= 40
#pragma omp parallel for if((m_pcols * m_pver) >= (1 << 20))
for (int i{ 0 }; i != this->m_m_pcols; ++i) {
#if defined (USE_AUTO_VECTORIZATION)
#pragma ivdep
#pragma simd
#pragma unroll(UNROLL_4X)
#endif
for (int j { 0 }; j != this->m_pver; ++j) {
this->m_qt[i + m_pcols * j] = qt[i + m_pcols * j];
this->m_ql[i + m_pcols * j] = ql[i + m_pcols * j];
this->m_sl[i + m_pcols * j] = sl[i + m_pcols * j];
this->m_pi[i + m_pcols * j] = pi[i + m_pcols * j];
this->m_pm[i + m_pcols * j] = pm[i + m_pcols * j];
this->m_zi[i + m_pcols * j] = zi[i + m_pcols * j];
this->m_cld[i + m_pcols * j] = cld[i + m_pcols * j];
this->m_sfi[i + m_pcols * j] = 0.0;
this->m_sfuh[i + m_pcols * j] = 0.0;
this->m_sflh[i + m_pcols * j] = 0.0;
this->m_slslope[i + m_pcols * j] = slslope[i + m_pcols * j];
this->m_qtslope[i + m_pcols * j] = qtslope[i + m_pcols * j];
}
}
// Copy top element from caller's input arrays to arrays 2D
// where m_pver == m_pver + 1.
const int top = this->m_pcols * (this->m_pver + 1);
this->m_pi[top] = pi[top];
this->m_zi[top] = zi[top];
this->m_sfi[top] = 0.0;
#else
// Use loop blocking.
// Warning: You must not #undef 'USE_LOOP_BLOCKING' macro!!
#if defined (USE_LOOP_BLOCKING)
for (int i{ 0 }; i < m_pcols; i += DEFAULT_BLOCK_SIZE) {
for (int j{ 0 }; j < m_pver; j += DEFAULT_BLOCK_SIZE) {
for (int ii = i; ii < DEFAULT_BLOCK_SIZE; ++ii) {
#if defined (USE_AUTO_VECTORIZATION)
#pragma ivdep
#pragma simd
#endif
for (int jj = j; jj < DEFAULT_BLOCK_SIZE; ++jj) {
this->m_qt[ii + m_pcols * jj] = qt[ii + m_pcols * jj];
this->m_ql[ii + m_pcols * jj] = ql[ii + m_pcols * jj];
this->m_sl[ii + m_pcols * jj] = sl[ii + m_pcols * jj];
this->m_pi[ii + m_pcols * jj] = pi[ii + m_pcols * jj];
this->m_pm[ii + m_pcols * jj] = pm[ii + m_pcols * jj];
this->m_zi[ii + m_pcols * jj] = zi[ii + m_pcols * jj];
this->m_cld[ii + m_pcols * jj] = cld[ii + m_pcols * jj];
this->m_sfi[ii + m_pcols * jj] = 0.0;
this->m_sfuh[ii + m_pcols * jj] = 0.0;
this->m_sflh[ii + m_pcols * jj] = 0.0;
this->m_slslope[ii + m_pcols * jj] = slslope[ii + m_pcols * jj];
this->m_qtslope[ii + m_pcols * jj] = qtslope[ii + m_pcols * jj];
}
}
}
}
#endif
// Copy top element from caller's input arrays to arrays 2D
// where m_pver == m_pver + 1.
const int top = this->m_pcols * (this->m_pver + 1);
this->m_pi[top] = pi[top];
this->m_zi[top] = zi[top];
this->m_sfi[top] = 0.0;
#endif
}
/*
@Purpose:
Copy Constructor implements deep copy semantics.
*/
Wrap_Sfdiag(_In_ const Wrap_Sfdiag &x)
:
m_pcols{ x.m_pcols },
m_pver{ x.m_pver },
m_ncol{ x.m_ncol },
m_qsat{ x.m_qsat },
m_qt{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) },
m_ql{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) },
m_sl{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) },
m_pi{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * (m_pver + 1) * sizeof(R64)), align32B)) },
m_pm{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) },
m_zi{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * (m_pver + 1) * sizeof(R64)), align32B)) },
m_cld{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) },
m_sfi{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * (m_pver + 1) * sizeof(R64)), align32B)) },
m_sfuh{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) },
m_sflh{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) },
m_slslope{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) },
m_qtslope{ reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)), align32B)) } {
// Check for memory allocation error (malloc failures)
for (int i{ 0 }; i != this->m_nArrays; ++i) {
if ((&this->m_qt)[i] == NULL) {
std::cerr << "[" << __DATE__ << ":" << __TIME__ << "]" << "FATAL ERROR: Memory allocation failure in Copy-Ctor Wrap_Sfdiag!!\n";
std::cerr << "at " << __FILE__ << ":" << __LINE__ << "(" << std::hex << "0x" << __FUNCTIONW__ << ")" << "\n";
std::cerr << "***** ERROR-DETAILS ***** \n";
std::cerr << "Failure detected at index: " << i << " heap address: " << std::hex << "0x" << (&this->m_qt)[i] << "\n";
std::cerr << "Cannot recover, hence on first failure occurrence --> calling exit(-1)!!\n";
std::exit(-1);
}
}
#if defined (USE_ICL_OPENMP) && \
OPENMP_CURR_VER >= 40
#pragma omp parallel for if((m_pcols * m_pver) >= (1 << 20))
for (int i{ 0 }; i != this->m_pcols; ++i) {
#if defined (USE_AUTO_VECTORIZATION)
#pragma ivdep
#pragma simd
#pragma unroll(UNROLL_4X)
#endif
for (int j { 0 }; j != this->m_pver; ++j) {
this->m_qt[i + m_pcols * j] = x.m_qt[i + x.m_pcols * j];
this->m_ql[i + m_pcols * j] = x.m_ql[i + x.m_pcols * j];
this->m_sl[i + m_pcols * j] = x.m_sl[i + x.m_pcols * j];
this->m_pi[i + m_pcols * j] = x.m_pi[i + x.m_pcols * j];
this->m_pm[i + m_pcols * j] = x.m_pm[i + x.m_pcols * j];
this->m_zi[i + m_pcols * j] = x.m_zi[i + x.m_pcols * j];
this->m_cld[i + m_pcols * j] = x.m_cld[i + x.m_pcols * j];
this->m_sfi[i + m_pcols * j] = x.m_sfi[i + x.m_pcols * j];
this->m_sfuh[i + m_pcols * j] = x.m_sfuh[i + x.m_pcols * j];
this->m_sflh[i + m_pcols * j] = x.m_sflh[i + x.m_pcols * j];
this->m_slslope[i + m_pcols * j] = x.m_slslope[i + x.m_pcols * j];
this->m_qtslope[i + m_pcols * j] = x.m_qtslope[i + x.m_pcols * j];
}
}
// Copy top element from caller's input arrays to arrays 2D
// where m_pver == m_pver + 1.
const int top = this->m_pcols * (this->m_pver + 1);
this->m_pi[top] = x.m_pi[top];
this->m_zi[top] = x.m_zi[top];
this->m_sfi[top] = x.m_sfi[top];
#else
// Use loop blocking.
// Warning: You must not #undef 'USE_LOOP_BLOCKING' macro!!
#if defined (USE_LOOP_BLOCKING)
for (int i{ 0 }; i < m_pcols; i += DEFAULT_BLOCK_SIZE) {
for (int j{ 0 }; j < m_pver; j += DEFAULT_BLOCK_SIZE) {
for (int ii = i; ii < DEFAULT_BLOCK_SIZE; ++ii) {
#if defined (USE_AUTO_VECTORIZATION)
#pragma ivdep
#pragma simd
#endif
for (int jj = j; jj < DEFAULT_BLOCK_SIZE; ++jj) {
this->m_qt[ii + m_pcols * jj] = x.m_qt[ii + x.m_pcols * jj];
this->m_ql[ii + m_pcols * jj] = x.m_ql[ii + x.m_pcols * jj];
this->m_sl[ii + m_pcols * jj] = x.m_sl[ii + x.m_pcols * jj];
this->m_pi[ii + m_pcols * jj] = x.m_pi[ii + x.m_pcols * jj];
this->m_pm[ii + m_pcols * jj] = x.m_pm[ii + x.m_pcols * jj];
this->m_zi[ii + m_pcols * jj] = x.m_zi[ii + x.m_pcols * jj];
this->m_cld[ii + m_pcols * jj] = x.m_cld[ii + x.m_pcols * jj];
this->m_sfi[ii + m_pcols * jj] = x.m_sfi[ii + x.m_pcols * jj];
this->m_sfuh[ii + m_pcols * jj] = x.m_sfuh[ii + x.m_pcols * jj];
this->m_sflh[ii + m_pcols * jj] = x.m_sflh[ii + x.m_pcols * jj];
this->m_slslope[ii + m_pcols * jj] = x.m_slslope[ii + x.m_pcols * jj];
this->m_qtslope[ii + m_pcols * jj] = x.m_qtslope[ii + x.m_pcols * jj];
}
}
}
}
#endif
// Copy top element from caller's input arrays to arrays 2D
// where m_pver == m_pver + 1.
const int top = this->m_pcols * (this->m_pver + 1);
this->m_pi[top] = x.m_pi[top];
this->m_zi[top] = x.m_zi[top];
this->m_sfi[top] = x.m_sfi[top];
#endif
}
/*
@Purpose:
Move Constructor implements shallow copy semantics.
*/
Wrap_Sfdiag(_In_ Wrap_Sfdiag &&x)
:
m_pcols{ x.m_pcols },
m_pver{ x.m_pver },
m_ncol{ x.m_ncol },
m_qsat{ x.m_qsat } {
// Assign *this pointers to x's pointers.
for (int i{ 0 }; i != this->m_nArrays; ++i) {
(&this->m_qt)[i] = (&x.m_qt)[i];
}
// Nullify x's pointers.
for (int i{ 0 }; i != this->m_nArrays; ++i) {
(&x.m_qt)[i] = NULL;
}
x.m_pcols = 0;
x.m_pver = 0;
}
/*
@Purpose:
Class Destructor.
*/
~Wrap_Sfdiag() {
for (int i{ 0 }; i != this->m_nArrays; ++i) {
if ((&this->m_qt)[i]) {
_mm_free((&this->m_qt)[i]);
}
}
for (int i{ 0 }; i != this->m_nArrays; ++i) {
(&this->m_qt)[i] = NULL;
}
this->m_pcols = 0;
this->m_pver = 0;
}
/*
@Purpose:
Copy-assign Operator implements deep copy semantics.
*/
Wrap_Sfdiag & operator=(_In_ const Wrap_Sfdiag &x) {
if (this == &x) return (*this);
this->m_pcols = x.m_pcols;
this->m_pver = x.m_pver;
this->m_ncol = x.m_ncol;
this->m_qsat = x.m_qsat;
constexpr int ntPtrs2D{9};
R64 *tPtrs2D[ntPtrs2D] = {};
for (int i{ 0 }; i != ntPtrs2D; ++i) {
tPtrs2D[i] = reinterpret_cast<R64*>(_mm_malloc((m_pcols * m_pver * sizeof(R64)),align32B));
}
for (int i{ 0 }; i != ntPtrs2D; ++i) {
if (tPtrs2D[i] == NULL) {
std::cerr << "[" << __DATE__ << ":" << __TIME__ << "]" << "FATAL ERROR: Memory allocation failure in Copy Operator Wrap_Sfdiag!!\n";
std::cerr << "at " << __FILE__ << ":" << __LINE__ << "(" << std::hex << "0x" << __FUNCTIONW__ << ")" << "\n";
std::cerr << "***** ERROR-DETAILS ***** \n";
std::cerr << "Checking allocation of temporary arrays 2D\.n";
std::cerr << "Failure detected at index: " << i << " heap address: " << std::hex << "0x" << tPtrs2D[i] << "\n";
std::cerr << "Cannot recover, hence on first failure occurrence --> calling exit(-1)!!\n";
std::exit(-1);
}
}
constexpr int ntPtrs2Dp1{3};
R64 *tPtrs2Dp1[ntPtrs2Dp1] = {};
for (int i{ 0 }; i != ntPtrs2Dp1; ++i) {
tPtrs2Dp1[i] = reinterpret_cast<R64*>(_mm_malloc((m_pcols * (m_pver + 1) * sizeof(R64)), align32B));
}
for (int i{ 0 }; i != ntPtrs2Dp1; ++i) {
if (tPtrs2Dp1[i] == NULL) {
std::cerr << "[" << __DATE__ << ":" << __TIME__ << "]" << "FATAL ERROR: Memory allocation failure in Copy Operator Wrap_Sfdiag!!\n";
std::cerr << "at " << __FILE__ << ":" << __LINE__ << "(" << std::hex << "0x" << __FUNCTIONW__ << ")" << "\n";
std::cerr << "***** ERROR-DETAILS ***** \n";
std::cerr << "Checking allocation of temporary arrays 2D\.n";
std::cerr << "Failure detected at index: " << i << " heap address: " << std::hex << "0x" << tPtrs2Dp1[i] << "\n";
std::cerr << "Cannot recover, hence on first failure occurrence --> calling exit(-1)!!\n";
std::exit(-1);
}
}
// Begin arrays 2D - large copy loop. First arrays 2D.
// OpenMP will be in use if total size >= (1 << 20).
#if defined (USE_ICL_OPENMP) && \
OPENMP_CURR_VER >= 40
#pragma omp parallel for if((m_pcols * m_pver) >= (1 << 20))
for (int i{ 0 }; i != this->m_pcols; ++i) {
#if defined (USE_AUTO_VECTORIZATION)
#pragma ivdep
#pragma simd
#pragma unroll(UNROLL_4X)
#endif
for (int j{ 0 }; j != this->m_pver; ++j) {
tPtrs2D[0][i + m_pcols * j] = x.m_qt[i + x.m_pcols * j];
tPtrs2D[1][i + m_pcols * j] = x.m_ql[i + x.m_pcols * j];
tPtrs2D[2][i + m_pcols * j] = x.m_sl[i + x.m_pcols * j];
tPtrs2Dp1[0][i + m_pcols * j] = x.m_pi[i + x.m_pcols * j];
tPtrs2D[3][i + m_pcols * j] = x.m_pm[i + x.m_pcols * j];
tPtrs2Dp1[1][i + m_pcols * j] = x.m_zi[i + x.m_pcols * j];
tPtrs2D[4][i + m_pcols * j] = x.m_cld[i + x.m_pcols * j];
tPtrs2Dp1[2][i + m_pcols * j] = x.m_sfi[i + x.m_pcols * j];
tPtrs2D[5][i + m_pcols * j] = x.m_sfuh[i + x.m_pcols * j];
tPtrs2D[6][i + m_pcols * j] = x.m_sflh[i + x.m_pcols * j];
tPtrs2D[7][i + m_pcols * j] = x.m_slslope[i + x.m_pcols * j];
tPtrs2D[8][i + m_pcols * j] = x.m_qtslope[i + x.m_pcols * j];
}
}
const int top = this->m_pcols * (this->m_pver + 1);
tPtrs2Dp1[0][top] = x.m_pi[top];
tPtrs2Dp1[1][top] = x.m_zi[top];
tPtrs2Dp1[2][top] = x.m_sfi[top];
// Deallocate current state.
for (int i{ 0 }; i != this->m_nArrays; ++i) {
_mm_free((&this->m_qt)[i]);
}
// Copy temporary pointers to *this.
this->m_qt = tPtrs2D[0];
this->m_ql = tPtrs2D[1];
this->m_sl = tPtrs2D[2];
this->m_pi = tPtrs2Dp1[0];
this->m_pm = tPtrs2D[3];
this->m_zi = tPtrs2Dp1[1];
this->m_cld = tPtrs2D[4];
this->m_sfi = tPtrs2Dp1[2];
this->m_sfuh = tPtrs2D[5];
this->m_sflh = tPtrs2D[6];
this->m_slslope = tPtrs2D[7];
this->m_qtslope = tPtrs2D[8];
return (*this);
#else
// Use loop blocking.
// Warning: You must not #undef 'USE_LOOP_BLOCKING' macro!!
#if defined (USE_LOOP_BLOCKING)
for (int i{ 0 }; i != this->m_pcols; i += DEFAULT_BLOCK_SIZE) {
for (int j{ 0 }; j != this->m_pver; j += DEFAULT_BLOCK_SIZE) {
for (int ii = i; ii < DEFAULT_BLOCK_SIZE; ++ii) {
#if defined (USE_AUTO_VECTORIZATION)
#pragma ivdep
#pragma simd
#endif
for (int jj = j; jj < DEFAULT_BLOCK_SIZE; ++jj) {
tPtrs2D[0][ii + m_pcols * jj] = x.m_qt[ii + x.m_pcols * jj];
tPtrs2D[1][ii + m_pcols * jj] = x.m_ql[ii + x.m_pcols * jj];
tPtrs2D[2][ii + m_pcols * jj] = x.m_sl[ii + x.m_pcols * jj];
tPtrs2Dp1[0][ii + m_pcols * jj] = x.m_pi[ii + x.m_pcols * jj];
tPtrs2D[3][ii + m_pcols * jj] = x.m_pm[ii + x.m_pcols * jj];
tPtrs2Dp1[1][ii + m_pcols * jj] = x.m_zi[ii + x.m_pcols * jj];
tPtrs2D[4][ii + m_pcols * jj] = x.m_cld[ii + x.m_pcols * jj];
tPtrs2Dp1[2][ii + m_pcols * jj] = x.m_sfi[ii + x.m_pcols * jj];
tPtrs2D[5][ii + m_pcols * jj] = x.m_sfuh[ii + x.m_pcols * jj];
tPtrs2D[6][ii + m_pcols * jj] = x.m_sflh[ii + x.m_pcols * jj];
tPtrs2D[7][ii + m_pcols * jj] = x.m_slslope[ii + x.m_pcols * jj];
tPtrs2D[8][ii + m_pcols * jj] = x.m_qtslope[ii + x.m_pcols * jj];
}
}
}
}
#endif
const int top = this->m_pcols * (this->m_pver + 1);
tPtrs2Dp1[0][top] = x.m_pi[top];
tPtrs2Dp1[1][top] = x.m_zi[top];
tPtrs2Dp1[2][top] = x.m_sfi[top];
// Deallocate current state.
for (int i{ 0 }; i != this->m_nArrays; ++i) {
_mm_free((&this->m_qt)[i]);
}
// Copy temporary pointers to *this.
this->m_qt = tPtrs2D[0];
this->m_ql = tPtrs2D[1];
this->m_sl = tPtrs2D[2];
this->m_pi = tPtrs2Dp1[0];
this->m_pm = tPtrs2D[3];
this->m_zi = tPtrs2Dp1[1];
this->m_cld = tPtrs2D[4];
this->m_sfi = tPtrs2Dp1[2];
this->m_sfuh = tPtrs2D[5];
this->m_sflh = tPtrs2D[6];
this->m_slslope = tPtrs2D[7];
this->m_qtslope = tPtrs2D[8];
return (*this);
#endif
}
/*
@Purpose:
Move Operator implements shallow copy semantics.
*/
Wrap_Sfdiag & operator=(_In_ Wrap_Sfdiag &&x) {
if (this == &x) return (*this);
this->m_pcols = x.m_pcols;
this->m_pver = x.m_pver;
this->m_ncol = x.m_ncol;
this->m_qsat = x.m_qsat;
// Deallocate current state.
for (int i{ 0 }; i != this->m_nArrays; ++i) {
if ((&this->m_qt)[i]) {
_mm_free((&this->m_qt)[i]);
}
}
//Reassign x's pointers.
for (int i{ 0 }; i != this->m_nArrays; ++i) {
(&this->m_qt)[i] = (&x.m_qt)[i];
}
// Nullify x's pointers.
for (int i{ 0 }; i != this->m_nArrays; ++i) {
(&x.m_qt)[i] = NULL;
}
x.m_pcols = 0;
x.m_pver = 0;
return (*this);
}
/*
@Purpose:
Calls Fortran 90 'SFDIAG' subroutine.
Warning:
'SFDIAG' probably will not
be accessible from outside eddy_diff module.
*/
void Call_SFDIAG() {
EDDY_DIFF_mp_SFDIAG(&this->m_cld, &this->m_pver, &this->m_ncol, &this->m_qt[0],
&this->m_ql[0], &this->m_sl[0], &this->m_pi[0], &this->m_pm[0], &this->m_zi[0],
&this->m_cld[0], &this->m_sfi[0], &this->m_sfuh[0], &this->m_sflh[0],
&this->m_slslope[0], &this->m_qtslope[0], &this->m_qsat[0]);
}
/*
@Purpose:
Member variables:
*/
I32 m_pcols;
I32 m_pver;
I32 m_ncol;
I32 m_qsat;
_Field_size_(m_pcols * m_pver) R64* __restrict m_qt;
_Field_size_(m_pcols * m_pver) R64* __restrict m_ql;
_Field_size_(m_pcols * m_pver) R64* __restrict m_sl;
_Field_size_(m_pcols * m_pver + 1) R64* __restrict m_pi;
_Field_size_(m_pcols * m_pver) R64* __restrict m_pm;
_Field_size_(m_pcols * m_pver + 1) R64* __restrict m_zi;
_Field_size_(m_pcols * m_pver) R64* __restrict m_cld;
_Field_size_(m_pcols * m_pver + 1) R64* __restrict m_sfi;
_Field_size_(m_pcols * m_pver) R64* __restrict m_sfuh;
_Field_size_(m_pcols * m_pver) R64* __restrict m_sflh;
_Field_size_(m_pcols * m_pver) R64* __restrict m_slslope;
_Field_size_(m_pcols * m_pver) R64* __restrict m_qtslope;
static const int m_nArrays = 12;
static const int m_nArrays2D = 9;
static const int m_nArrays2Dp1 = 3;
};
}
}
#endif /*__EDDY_DIFF_SFDIAG_IMPL_H__*/ |
decl2.c | /* Process declarations and variables for C++ compiler.
Copyright (C) 1988-2018 Free Software Foundation, Inc.
Hacked by Michael Tiemann (tiemann@cygnus.com)
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
GCC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
/* Process declarations and symbol lookup for C++ front end.
Also constructs types; the standard scalar types at initialization,
and structure, union, array and enum types when they are declared. */
/* ??? not all decl nodes are given the most useful possible
line numbers. For example, the CONST_DECLs for enum values. */
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "memmodel.h"
#include "target.h"
#include "cp-tree.h"
#include "c-family/c-common.h"
#include "timevar.h"
#include "stringpool.h"
#include "cgraph.h"
#include "varasm.h"
#include "attribs.h"
#include "stor-layout.h"
#include "calls.h"
#include "decl.h"
#include "toplev.h"
#include "c-family/c-objc.h"
#include "c-family/c-pragma.h"
#include "dumpfile.h"
#include "intl.h"
#include "c-family/c-ada-spec.h"
#include "asan.h"
/* Id for dumping the raw trees. */
int raw_dump_id;
extern cpp_reader *parse_in;
/* This structure contains information about the initializations
and/or destructions required for a particular priority level. */
typedef struct priority_info_s {
/* Nonzero if there have been any initializations at this priority
throughout the translation unit. */
int initializations_p;
/* Nonzero if there have been any destructions at this priority
throughout the translation unit. */
int destructions_p;
} *priority_info;
static void mark_vtable_entries (tree);
static bool maybe_emit_vtables (tree);
static tree start_objects (int, int);
static void finish_objects (int, int, tree);
static tree start_static_storage_duration_function (unsigned);
static void finish_static_storage_duration_function (tree);
static priority_info get_priority_info (int);
static void do_static_initialization_or_destruction (tree, bool);
static void one_static_initialization_or_destruction (tree, tree, bool);
static void generate_ctor_or_dtor_function (bool, int, location_t *);
static int generate_ctor_and_dtor_functions_for_priority (splay_tree_node,
void *);
static tree prune_vars_needing_no_initialization (tree *);
static void write_out_vars (tree);
static void import_export_class (tree);
static tree get_guard_bits (tree);
static void determine_visibility_from_class (tree, tree);
static bool determine_hidden_inline (tree);
static void maybe_instantiate_decl (tree);
/* A list of static class variables. This is needed, because a
static class variable can be declared inside the class without
an initializer, and then initialized, statically, outside the class. */
static GTY(()) vec<tree, va_gc> *pending_statics;
/* A list of functions which were declared inline, but which we
may need to emit outline anyway. */
static GTY(()) vec<tree, va_gc> *deferred_fns;
/* A list of decls that use types with no linkage, which we need to make
sure are defined. */
static GTY(()) vec<tree, va_gc> *no_linkage_decls;
/* A vector of alternating decls and identifiers, where the latter
is to be an alias for the former if the former is defined. */
static GTY(()) vec<tree, va_gc> *mangling_aliases;
/* hash traits for declarations. Hashes single decls via
DECL_ASSEMBLER_NAME_RAW. */
struct mangled_decl_hash : ggc_remove <tree>
{
typedef tree value_type; /* A DECL. */
typedef tree compare_type; /* An identifier. */
static hashval_t hash (const value_type decl)
{
return IDENTIFIER_HASH_VALUE (DECL_ASSEMBLER_NAME_RAW (decl));
}
static bool equal (const value_type existing, compare_type candidate)
{
tree name = DECL_ASSEMBLER_NAME_RAW (existing);
return candidate == name;
}
static inline void mark_empty (value_type &p) {p = NULL_TREE;}
static inline bool is_empty (value_type p) {return !p;}
static bool is_deleted (value_type e)
{
return e == reinterpret_cast <value_type> (1);
}
static void mark_deleted (value_type &e)
{
e = reinterpret_cast <value_type> (1);
}
};
/* A hash table of decls keyed by mangled name. Used to figure out if
we need compatibility aliases. */
static GTY(()) hash_table<mangled_decl_hash> *mangled_decls;
/* Nonzero if we're done parsing and into end-of-file activities. */
int at_eof;
/* True if note_mangling_alias should enqueue mangling aliases for
later generation, rather than emitting them right away. */
bool defer_mangling_aliases = true;
/* Return a member function type (a METHOD_TYPE), given FNTYPE (a
FUNCTION_TYPE), CTYPE (class type), and QUALS (the cv-qualifiers
that apply to the function). */
tree
build_memfn_type (tree fntype, tree ctype, cp_cv_quals quals,
cp_ref_qualifier rqual)
{
tree raises;
tree attrs;
int type_quals;
bool late_return_type_p;
if (fntype == error_mark_node || ctype == error_mark_node)
return error_mark_node;
gcc_assert (TREE_CODE (fntype) == FUNCTION_TYPE
|| TREE_CODE (fntype) == METHOD_TYPE);
type_quals = quals & ~TYPE_QUAL_RESTRICT;
ctype = cp_build_qualified_type (ctype, type_quals);
raises = TYPE_RAISES_EXCEPTIONS (fntype);
attrs = TYPE_ATTRIBUTES (fntype);
late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (fntype);
fntype = build_method_type_directly (ctype, TREE_TYPE (fntype),
(TREE_CODE (fntype) == METHOD_TYPE
? TREE_CHAIN (TYPE_ARG_TYPES (fntype))
: TYPE_ARG_TYPES (fntype)));
if (attrs)
fntype = cp_build_type_attribute_variant (fntype, attrs);
if (rqual)
fntype = build_ref_qualified_type (fntype, rqual);
if (raises)
fntype = build_exception_variant (fntype, raises);
if (late_return_type_p)
TYPE_HAS_LATE_RETURN_TYPE (fntype) = 1;
return fntype;
}
/* Return a variant of FNTYPE, a FUNCTION_TYPE or METHOD_TYPE, with its
return type changed to NEW_RET. */
tree
change_return_type (tree new_ret, tree fntype)
{
tree newtype;
tree args = TYPE_ARG_TYPES (fntype);
tree raises = TYPE_RAISES_EXCEPTIONS (fntype);
tree attrs = TYPE_ATTRIBUTES (fntype);
bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (fntype);
if (new_ret == error_mark_node)
return fntype;
if (same_type_p (new_ret, TREE_TYPE (fntype)))
return fntype;
if (TREE_CODE (fntype) == FUNCTION_TYPE)
{
newtype = build_function_type (new_ret, args);
newtype = apply_memfn_quals (newtype,
type_memfn_quals (fntype),
type_memfn_rqual (fntype));
}
else
newtype = build_method_type_directly
(class_of_this_parm (fntype), new_ret, TREE_CHAIN (args));
if (FUNCTION_REF_QUALIFIED (fntype))
newtype = build_ref_qualified_type (newtype, type_memfn_rqual (fntype));
if (raises)
newtype = build_exception_variant (newtype, raises);
if (attrs)
newtype = cp_build_type_attribute_variant (newtype, attrs);
if (late_return_type_p)
TYPE_HAS_LATE_RETURN_TYPE (newtype) = 1;
return newtype;
}
/* Build a PARM_DECL of FN with NAME and TYPE, and set DECL_ARG_TYPE
appropriately. */
tree
cp_build_parm_decl (tree fn, tree name, tree type)
{
tree parm = build_decl (input_location,
PARM_DECL, name, type);
DECL_CONTEXT (parm) = fn;
/* DECL_ARG_TYPE is only used by the back end and the back end never
sees templates. */
if (!processing_template_decl)
DECL_ARG_TYPE (parm) = type_passed_as (type);
return parm;
}
/* Returns a PARM_DECL of FN for a parameter of the indicated TYPE, with the
indicated NAME. */
tree
build_artificial_parm (tree fn, tree name, tree type)
{
tree parm = cp_build_parm_decl (fn, name, type);
DECL_ARTIFICIAL (parm) = 1;
/* All our artificial parms are implicitly `const'; they cannot be
assigned to. */
TREE_READONLY (parm) = 1;
return parm;
}
/* Constructors for types with virtual baseclasses need an "in-charge" flag
saying whether this constructor is responsible for initialization of
virtual baseclasses or not. All destructors also need this "in-charge"
flag, which additionally determines whether or not the destructor should
free the memory for the object.
This function adds the "in-charge" flag to member function FN if
appropriate. It is called from grokclassfn and tsubst.
FN must be either a constructor or destructor.
The in-charge flag follows the 'this' parameter, and is followed by the
VTT parm (if any), then the user-written parms. */
void
maybe_retrofit_in_chrg (tree fn)
{
tree basetype, arg_types, parms, parm, fntype;
/* If we've already add the in-charge parameter don't do it again. */
if (DECL_HAS_IN_CHARGE_PARM_P (fn))
return;
/* When processing templates we can't know, in general, whether or
not we're going to have virtual baseclasses. */
if (processing_template_decl)
return;
/* We don't need an in-charge parameter for constructors that don't
have virtual bases. */
if (DECL_CONSTRUCTOR_P (fn)
&& !CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fn)))
return;
arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
basetype = TREE_TYPE (TREE_VALUE (arg_types));
arg_types = TREE_CHAIN (arg_types);
parms = DECL_CHAIN (DECL_ARGUMENTS (fn));
/* If this is a subobject constructor or destructor, our caller will
pass us a pointer to our VTT. */
if (CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fn)))
{
parm = build_artificial_parm (fn, vtt_parm_identifier, vtt_parm_type);
/* First add it to DECL_ARGUMENTS between 'this' and the real args... */
DECL_CHAIN (parm) = parms;
parms = parm;
/* ...and then to TYPE_ARG_TYPES. */
arg_types = hash_tree_chain (vtt_parm_type, arg_types);
DECL_HAS_VTT_PARM_P (fn) = 1;
}
/* Then add the in-charge parm (before the VTT parm). */
parm = build_artificial_parm (fn, in_charge_identifier, integer_type_node);
DECL_CHAIN (parm) = parms;
parms = parm;
arg_types = hash_tree_chain (integer_type_node, arg_types);
/* Insert our new parameter(s) into the list. */
DECL_CHAIN (DECL_ARGUMENTS (fn)) = parms;
/* And rebuild the function type. */
fntype = build_method_type_directly (basetype, TREE_TYPE (TREE_TYPE (fn)),
arg_types);
if (TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn)))
fntype = build_exception_variant (fntype,
TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn)));
if (TYPE_ATTRIBUTES (TREE_TYPE (fn)))
fntype = (cp_build_type_attribute_variant
(fntype, TYPE_ATTRIBUTES (TREE_TYPE (fn))));
TREE_TYPE (fn) = fntype;
/* Now we've got the in-charge parameter. */
DECL_HAS_IN_CHARGE_PARM_P (fn) = 1;
}
/* Classes overload their constituent function names automatically.
When a function name is declared in a record structure,
its name is changed to it overloaded name. Since names for
constructors and destructors can conflict, we place a leading
'$' for destructors.
CNAME is the name of the class we are grokking for.
FUNCTION is a FUNCTION_DECL. It was created by `grokdeclarator'.
FLAGS contains bits saying what's special about today's
arguments. DTOR_FLAG == DESTRUCTOR.
If FUNCTION is a destructor, then we must add the `auto-delete' field
as a second parameter. There is some hair associated with the fact
that we must "declare" this variable in the manner consistent with the
way the rest of the arguments were declared.
QUALS are the qualifiers for the this pointer. */
void
grokclassfn (tree ctype, tree function, enum overload_flags flags)
{
tree fn_name = DECL_NAME (function);
/* Even within an `extern "C"' block, members get C++ linkage. See
[dcl.link] for details. */
SET_DECL_LANGUAGE (function, lang_cplusplus);
if (fn_name == NULL_TREE)
{
error ("name missing for member function");
fn_name = get_identifier ("<anonymous>");
DECL_NAME (function) = fn_name;
}
DECL_CONTEXT (function) = ctype;
if (flags == DTOR_FLAG)
DECL_CXX_DESTRUCTOR_P (function) = 1;
if (flags == DTOR_FLAG || DECL_CONSTRUCTOR_P (function))
maybe_retrofit_in_chrg (function);
}
/* Create an ARRAY_REF, checking for the user doing things backwards
along the way. DECLTYPE_P is for N3276, as in the parser. */
tree
grok_array_decl (location_t loc, tree array_expr, tree index_exp,
bool decltype_p)
{
tree type;
tree expr;
tree orig_array_expr = array_expr;
tree orig_index_exp = index_exp;
tree overload = NULL_TREE;
if (error_operand_p (array_expr) || error_operand_p (index_exp))
return error_mark_node;
if (processing_template_decl)
{
if (type_dependent_expression_p (array_expr)
|| type_dependent_expression_p (index_exp))
return build_min_nt_loc (loc, ARRAY_REF, array_expr, index_exp,
NULL_TREE, NULL_TREE);
array_expr = build_non_dependent_expr (array_expr);
index_exp = build_non_dependent_expr (index_exp);
}
type = TREE_TYPE (array_expr);
gcc_assert (type);
type = non_reference (type);
/* If they have an `operator[]', use that. */
if (MAYBE_CLASS_TYPE_P (type) || MAYBE_CLASS_TYPE_P (TREE_TYPE (index_exp)))
{
tsubst_flags_t complain = tf_warning_or_error;
if (decltype_p)
complain |= tf_decltype;
expr = build_new_op (loc, ARRAY_REF, LOOKUP_NORMAL, array_expr,
index_exp, NULL_TREE, &overload, complain);
}
else
{
tree p1, p2, i1, i2;
/* Otherwise, create an ARRAY_REF for a pointer or array type.
It is a little-known fact that, if `a' is an array and `i' is
an int, you can write `i[a]', which means the same thing as
`a[i]'. */
if (TREE_CODE (type) == ARRAY_TYPE || VECTOR_TYPE_P (type))
p1 = array_expr;
else
p1 = build_expr_type_conversion (WANT_POINTER, array_expr, false);
if (TREE_CODE (TREE_TYPE (index_exp)) == ARRAY_TYPE)
p2 = index_exp;
else
p2 = build_expr_type_conversion (WANT_POINTER, index_exp, false);
i1 = build_expr_type_conversion (WANT_INT | WANT_ENUM, array_expr,
false);
i2 = build_expr_type_conversion (WANT_INT | WANT_ENUM, index_exp,
false);
if ((p1 && i2) && (i1 && p2))
error ("ambiguous conversion for array subscript");
if (p1 && i2)
array_expr = p1, index_exp = i2;
else if (i1 && p2)
array_expr = p2, index_exp = i1;
else
{
error ("invalid types %<%T[%T]%> for array subscript",
type, TREE_TYPE (index_exp));
return error_mark_node;
}
if (array_expr == error_mark_node || index_exp == error_mark_node)
error ("ambiguous conversion for array subscript");
if (TREE_CODE (TREE_TYPE (array_expr)) == POINTER_TYPE)
array_expr = mark_rvalue_use (array_expr);
else
array_expr = mark_lvalue_use_nonread (array_expr);
index_exp = mark_rvalue_use (index_exp);
expr = build_array_ref (input_location, array_expr, index_exp);
}
if (processing_template_decl && expr != error_mark_node)
{
if (overload != NULL_TREE)
return (build_min_non_dep_op_overload
(ARRAY_REF, expr, overload, orig_array_expr, orig_index_exp));
return build_min_non_dep (ARRAY_REF, expr, orig_array_expr, orig_index_exp,
NULL_TREE, NULL_TREE);
}
return expr;
}
/* Given the cast expression EXP, checking out its validity. Either return
an error_mark_node if there was an unavoidable error, return a cast to
void for trying to delete a pointer w/ the value 0, or return the
call to delete. If DOING_VEC is true, we handle things differently
for doing an array delete.
Implements ARM $5.3.4. This is called from the parser. */
tree
delete_sanity (tree exp, tree size, bool doing_vec, int use_global_delete,
tsubst_flags_t complain)
{
tree t, type;
if (exp == error_mark_node)
return exp;
if (processing_template_decl)
{
t = build_min (DELETE_EXPR, void_type_node, exp, size);
DELETE_EXPR_USE_GLOBAL (t) = use_global_delete;
DELETE_EXPR_USE_VEC (t) = doing_vec;
TREE_SIDE_EFFECTS (t) = 1;
return t;
}
/* An array can't have been allocated by new, so complain. */
if (TREE_CODE (TREE_TYPE (exp)) == ARRAY_TYPE)
warning (0, "deleting array %q#E", exp);
t = build_expr_type_conversion (WANT_POINTER, exp, true);
if (t == NULL_TREE || t == error_mark_node)
{
error ("type %q#T argument given to %<delete%>, expected pointer",
TREE_TYPE (exp));
return error_mark_node;
}
type = TREE_TYPE (t);
/* As of Valley Forge, you can delete a pointer to const. */
/* You can't delete functions. */
if (TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE)
{
error ("cannot delete a function. Only pointer-to-objects are "
"valid arguments to %<delete%>");
return error_mark_node;
}
/* Deleting ptr to void is undefined behavior [expr.delete/3]. */
if (VOID_TYPE_P (TREE_TYPE (type)))
{
warning (OPT_Wdelete_incomplete, "deleting %qT is undefined", type);
doing_vec = 0;
}
/* Deleting a pointer with the value zero is valid and has no effect. */
if (integer_zerop (t))
return build1 (NOP_EXPR, void_type_node, t);
if (doing_vec)
return build_vec_delete (t, /*maxindex=*/NULL_TREE,
sfk_deleting_destructor,
use_global_delete, complain);
else
return build_delete (type, t, sfk_deleting_destructor,
LOOKUP_NORMAL, use_global_delete,
complain);
}
/* Report an error if the indicated template declaration is not the
sort of thing that should be a member template. */
void
check_member_template (tree tmpl)
{
tree decl;
gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
decl = DECL_TEMPLATE_RESULT (tmpl);
if (TREE_CODE (decl) == FUNCTION_DECL
|| DECL_ALIAS_TEMPLATE_P (tmpl)
|| (TREE_CODE (decl) == TYPE_DECL
&& MAYBE_CLASS_TYPE_P (TREE_TYPE (decl))))
{
/* The parser rejects template declarations in local classes
(with the exception of generic lambdas). */
gcc_assert (!current_function_decl || LAMBDA_FUNCTION_P (decl));
/* The parser rejects any use of virtual in a function template. */
gcc_assert (!(TREE_CODE (decl) == FUNCTION_DECL
&& DECL_VIRTUAL_P (decl)));
/* The debug-information generating code doesn't know what to do
with member templates. */
DECL_IGNORED_P (tmpl) = 1;
}
else if (variable_template_p (tmpl))
/* OK */;
else
error ("template declaration of %q#D", decl);
}
/* Sanity check: report error if this function FUNCTION is not
really a member of the class (CTYPE) it is supposed to belong to.
TEMPLATE_PARMS is used to specify the template parameters of a member
template passed as FUNCTION_DECL. If the member template is passed as a
TEMPLATE_DECL, it can be NULL since the parameters can be extracted
from the declaration. If the function is not a function template, it
must be NULL.
It returns the original declaration for the function, NULL_TREE if
no declaration was found, error_mark_node if an error was emitted. */
tree
check_classfn (tree ctype, tree function, tree template_parms)
{
if (DECL_USE_TEMPLATE (function)
&& !(TREE_CODE (function) == TEMPLATE_DECL
&& DECL_TEMPLATE_SPECIALIZATION (function))
&& DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (function)))
/* Since this is a specialization of a member template,
we're not going to find the declaration in the class.
For example, in:
struct S { template <typename T> void f(T); };
template <> void S::f(int);
we're not going to find `S::f(int)', but there's no
reason we should, either. We let our callers know we didn't
find the method, but we don't complain. */
return NULL_TREE;
/* Basic sanity check: for a template function, the template parameters
either were not passed, or they are the same of DECL_TEMPLATE_PARMS. */
if (TREE_CODE (function) == TEMPLATE_DECL)
{
if (template_parms
&& !comp_template_parms (template_parms,
DECL_TEMPLATE_PARMS (function)))
{
error ("template parameter lists provided don%'t match the "
"template parameters of %qD", function);
return error_mark_node;
}
template_parms = DECL_TEMPLATE_PARMS (function);
}
/* OK, is this a definition of a member template? */
bool is_template = (template_parms != NULL_TREE);
/* [temp.mem]
A destructor shall not be a member template. */
if (DECL_DESTRUCTOR_P (function) && is_template)
{
error ("destructor %qD declared as member template", function);
return error_mark_node;
}
/* We must enter the scope here, because conversion operators are
named by target type, and type equivalence relies on typenames
resolving within the scope of CTYPE. */
tree pushed_scope = push_scope (ctype);
tree matched = NULL_TREE;
tree fns = get_class_binding (ctype, DECL_NAME (function));
for (ovl_iterator iter (fns); !matched && iter; ++iter)
{
tree fndecl = *iter;
/* A member template definition only matches a member template
declaration. */
if (is_template != (TREE_CODE (fndecl) == TEMPLATE_DECL))
continue;
if (!DECL_DECLARES_FUNCTION_P (fndecl))
continue;
tree p1 = TYPE_ARG_TYPES (TREE_TYPE (function));
tree p2 = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
/* We cannot simply call decls_match because this doesn't work
for static member functions that are pretending to be
methods, and because the name may have been changed by
asm("new_name"). */
/* Get rid of the this parameter on functions that become
static. */
if (DECL_STATIC_FUNCTION_P (fndecl)
&& TREE_CODE (TREE_TYPE (function)) == METHOD_TYPE)
p1 = TREE_CHAIN (p1);
/* ref-qualifier or absence of same must match. */
if (type_memfn_rqual (TREE_TYPE (function))
!= type_memfn_rqual (TREE_TYPE (fndecl)))
continue;
// Include constraints in the match.
tree c1 = get_constraints (function);
tree c2 = get_constraints (fndecl);
/* While finding a match, same types and params are not enough
if the function is versioned. Also check version ("target")
attributes. */
if (same_type_p (TREE_TYPE (TREE_TYPE (function)),
TREE_TYPE (TREE_TYPE (fndecl)))
&& compparms (p1, p2)
&& !targetm.target_option.function_versions (function, fndecl)
&& (!is_template
|| comp_template_parms (template_parms,
DECL_TEMPLATE_PARMS (fndecl)))
&& equivalent_constraints (c1, c2)
&& (DECL_TEMPLATE_SPECIALIZATION (function)
== DECL_TEMPLATE_SPECIALIZATION (fndecl))
&& (!DECL_TEMPLATE_SPECIALIZATION (function)
|| (DECL_TI_TEMPLATE (function) == DECL_TI_TEMPLATE (fndecl))))
matched = fndecl;
}
if (!matched)
{
if (!COMPLETE_TYPE_P (ctype))
cxx_incomplete_type_error (function, ctype);
else
{
if (DECL_CONV_FN_P (function))
fns = get_class_binding (ctype, conv_op_identifier);
error_at (DECL_SOURCE_LOCATION (function),
"no declaration matches %q#D", function);
if (fns)
print_candidates (fns);
else if (DECL_CONV_FN_P (function))
inform (DECL_SOURCE_LOCATION (function),
"no conversion operators declared");
else
inform (DECL_SOURCE_LOCATION (function),
"no functions named %qD", function);
inform (DECL_SOURCE_LOCATION (TYPE_NAME (ctype)),
"%#qT defined here", ctype);
}
matched = error_mark_node;
}
if (pushed_scope)
pop_scope (pushed_scope);
return matched;
}
/* DECL is a function with vague linkage. Remember it so that at the
end of the translation unit we can decide whether or not to emit
it. */
void
note_vague_linkage_fn (tree decl)
{
if (processing_template_decl)
return;
DECL_DEFER_OUTPUT (decl) = 1;
vec_safe_push (deferred_fns, decl);
}
/* As above, but for variable template instantiations. */
void
note_variable_template_instantiation (tree decl)
{
vec_safe_push (pending_statics, decl);
}
/* We have just processed the DECL, which is a static data member.
The other parameters are as for cp_finish_decl. */
void
finish_static_data_member_decl (tree decl,
tree init, bool init_const_expr_p,
tree asmspec_tree,
int flags)
{
DECL_CONTEXT (decl) = current_class_type;
/* We cannot call pushdecl here, because that would fill in the
TREE_CHAIN of our decl. Instead, we modify cp_finish_decl to do
the right thing, namely, to put this decl out straight away. */
if (! processing_template_decl)
vec_safe_push (pending_statics, decl);
if (LOCAL_CLASS_P (current_class_type)
/* We already complained about the template definition. */
&& !DECL_TEMPLATE_INSTANTIATION (decl))
permerror (input_location, "local class %q#T shall not have static data member %q#D",
current_class_type, decl);
else
for (tree t = current_class_type; TYPE_P (t);
t = CP_TYPE_CONTEXT (t))
if (TYPE_UNNAMED_P (t))
{
if (permerror (DECL_SOURCE_LOCATION (decl),
"static data member %qD in unnamed class", decl))
inform (DECL_SOURCE_LOCATION (TYPE_NAME (t)),
"unnamed class defined here");
break;
}
DECL_IN_AGGR_P (decl) = 1;
if (TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE
&& TYPE_DOMAIN (TREE_TYPE (decl)) == NULL_TREE)
SET_VAR_HAD_UNKNOWN_BOUND (decl);
if (init)
{
/* Similarly to start_decl_1, we want to complete the type in order
to do the right thing in cp_apply_type_quals_to_decl, possibly
clear TYPE_QUAL_CONST (c++/65579). */
tree type = TREE_TYPE (decl) = complete_type (TREE_TYPE (decl));
cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
}
cp_finish_decl (decl, init, init_const_expr_p, asmspec_tree, flags);
}
/* DECLARATOR and DECLSPECS correspond to a class member. The other
parameters are as for cp_finish_decl. Return the DECL for the
class member declared. */
tree
grokfield (const cp_declarator *declarator,
cp_decl_specifier_seq *declspecs,
tree init, bool init_const_expr_p,
tree asmspec_tree,
tree attrlist)
{
tree value;
const char *asmspec = 0;
int flags;
tree name;
if (init
&& TREE_CODE (init) == TREE_LIST
&& TREE_VALUE (init) == error_mark_node
&& TREE_CHAIN (init) == NULL_TREE)
init = NULL_TREE;
value = grokdeclarator (declarator, declspecs, FIELD, init != 0, &attrlist);
if (! value || value == error_mark_node)
/* friend or constructor went bad. */
return error_mark_node;
if (TREE_TYPE (value) == error_mark_node)
return value;
if (TREE_CODE (value) == TYPE_DECL && init)
{
error ("typedef %qD is initialized (use decltype instead)", value);
init = NULL_TREE;
}
/* Pass friendly classes back. */
if (value == void_type_node)
return value;
name = DECL_NAME (value);
if (name != NULL_TREE)
{
if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
{
error ("explicit template argument list not allowed");
return error_mark_node;
}
if (IDENTIFIER_POINTER (name)[0] == '_'
&& id_equal (name, "_vptr"))
error ("member %qD conflicts with virtual function table field name",
value);
}
/* Stash away type declarations. */
if (TREE_CODE (value) == TYPE_DECL)
{
DECL_NONLOCAL (value) = 1;
DECL_CONTEXT (value) = current_class_type;
if (attrlist)
{
int attrflags = 0;
/* If this is a typedef that names the class for linkage purposes
(7.1.3p8), apply any attributes directly to the type. */
if (OVERLOAD_TYPE_P (TREE_TYPE (value))
&& value == TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (value))))
attrflags = ATTR_FLAG_TYPE_IN_PLACE;
cplus_decl_attributes (&value, attrlist, attrflags);
}
if (decl_spec_seq_has_spec_p (declspecs, ds_typedef)
&& TREE_TYPE (value) != error_mark_node
&& TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (value))) != value)
set_underlying_type (value);
/* It's important that push_template_decl below follows
set_underlying_type above so that the created template
carries the properly set type of VALUE. */
if (processing_template_decl)
value = push_template_decl (value);
record_locally_defined_typedef (value);
return value;
}
int friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
if (!friendp && DECL_IN_AGGR_P (value))
{
error ("%qD is already defined in %qT", value, DECL_CONTEXT (value));
return void_type_node;
}
if (asmspec_tree && asmspec_tree != error_mark_node)
asmspec = TREE_STRING_POINTER (asmspec_tree);
if (init)
{
if (TREE_CODE (value) == FUNCTION_DECL)
{
if (init == ridpointers[(int)RID_DELETE])
{
if (friendp && decl_defined_p (value))
{
error ("redefinition of %q#D", value);
inform (DECL_SOURCE_LOCATION (value),
"%q#D previously defined here", value);
}
else
{
DECL_DELETED_FN (value) = 1;
DECL_DECLARED_INLINE_P (value) = 1;
DECL_INITIAL (value) = error_mark_node;
}
}
else if (init == ridpointers[(int)RID_DEFAULT])
{
if (defaultable_fn_check (value))
{
DECL_DEFAULTED_FN (value) = 1;
DECL_INITIALIZED_IN_CLASS_P (value) = 1;
DECL_DECLARED_INLINE_P (value) = 1;
}
}
else if (TREE_CODE (init) == DEFAULT_ARG)
error ("invalid initializer for member function %qD", value);
else if (TREE_CODE (TREE_TYPE (value)) == METHOD_TYPE)
{
if (integer_zerop (init))
DECL_PURE_VIRTUAL_P (value) = 1;
else if (error_operand_p (init))
; /* An error has already been reported. */
else
error ("invalid initializer for member function %qD",
value);
}
else
{
gcc_assert (TREE_CODE (TREE_TYPE (value)) == FUNCTION_TYPE);
if (friendp)
error ("initializer specified for friend function %qD",
value);
else
error ("initializer specified for static member function %qD",
value);
}
}
else if (TREE_CODE (value) == FIELD_DECL)
/* C++11 NSDMI, keep going. */;
else if (!VAR_P (value))
gcc_unreachable ();
}
/* Pass friend decls back. */
if ((TREE_CODE (value) == FUNCTION_DECL
|| TREE_CODE (value) == TEMPLATE_DECL)
&& DECL_CONTEXT (value) != current_class_type)
return value;
/* Need to set this before push_template_decl. */
if (VAR_P (value))
DECL_CONTEXT (value) = current_class_type;
if (processing_template_decl && VAR_OR_FUNCTION_DECL_P (value))
{
value = push_template_decl (value);
if (error_operand_p (value))
return error_mark_node;
}
if (attrlist)
cplus_decl_attributes (&value, attrlist, 0);
if (init && DIRECT_LIST_INIT_P (init))
flags = LOOKUP_NORMAL;
else
flags = LOOKUP_IMPLICIT;
switch (TREE_CODE (value))
{
case VAR_DECL:
finish_static_data_member_decl (value, init, init_const_expr_p,
asmspec_tree, flags);
return value;
case FIELD_DECL:
if (asmspec)
error ("%<asm%> specifiers are not permitted on non-static data members");
if (DECL_INITIAL (value) == error_mark_node)
init = error_mark_node;
cp_finish_decl (value, init, /*init_const_expr_p=*/false,
NULL_TREE, flags);
DECL_IN_AGGR_P (value) = 1;
return value;
case FUNCTION_DECL:
if (asmspec)
set_user_assembler_name (value, asmspec);
cp_finish_decl (value,
/*init=*/NULL_TREE,
/*init_const_expr_p=*/false,
asmspec_tree, flags);
/* Pass friends back this way. */
if (DECL_FRIEND_P (value))
return void_type_node;
DECL_IN_AGGR_P (value) = 1;
return value;
default:
gcc_unreachable ();
}
return NULL_TREE;
}
/* Like `grokfield', but for bitfields.
WIDTH is the width of the bitfield, a constant expression.
The other parameters are as for grokfield. */
tree
grokbitfield (const cp_declarator *declarator,
cp_decl_specifier_seq *declspecs, tree width, tree init,
tree attrlist)
{
tree value = grokdeclarator (declarator, declspecs, BITFIELD,
init != NULL_TREE, &attrlist);
if (value == error_mark_node)
return NULL_TREE; /* friends went bad. */
if (TREE_TYPE (value) == error_mark_node)
return value;
/* Pass friendly classes back. */
if (VOID_TYPE_P (value))
return void_type_node;
if (!INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (value))
&& (POINTER_TYPE_P (value)
|| !dependent_type_p (TREE_TYPE (value))))
{
error ("bit-field %qD with non-integral type", value);
return error_mark_node;
}
if (TREE_CODE (value) == TYPE_DECL)
{
error ("cannot declare %qD to be a bit-field type", value);
return NULL_TREE;
}
/* Usually, finish_struct_1 catches bitfields with invalid types.
But, in the case of bitfields with function type, we confuse
ourselves into thinking they are member functions, so we must
check here. */
if (TREE_CODE (value) == FUNCTION_DECL)
{
error ("cannot declare bit-field %qD with function type",
DECL_NAME (value));
return NULL_TREE;
}
if (width && TYPE_WARN_IF_NOT_ALIGN (TREE_TYPE (value)))
{
error ("cannot declare bit-field %qD with %<warn_if_not_aligned%> type",
DECL_NAME (value));
return NULL_TREE;
}
if (DECL_IN_AGGR_P (value))
{
error ("%qD is already defined in the class %qT", value,
DECL_CONTEXT (value));
return void_type_node;
}
if (TREE_STATIC (value))
{
error ("static member %qD cannot be a bit-field", value);
return NULL_TREE;
}
int flags = LOOKUP_IMPLICIT;
if (init && DIRECT_LIST_INIT_P (init))
flags = LOOKUP_NORMAL;
cp_finish_decl (value, init, false, NULL_TREE, flags);
if (width != error_mark_node)
{
/* The width must be an integer type. */
if (!type_dependent_expression_p (width)
&& !INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (width)))
error ("width of bit-field %qD has non-integral type %qT", value,
TREE_TYPE (width));
else
{
/* Temporarily stash the width in DECL_BIT_FIELD_REPRESENTATIVE.
check_bitfield_decl picks it from there later and sets DECL_SIZE
accordingly. */
DECL_BIT_FIELD_REPRESENTATIVE (value) = width;
SET_DECL_C_BIT_FIELD (value);
}
}
DECL_IN_AGGR_P (value) = 1;
if (attrlist)
cplus_decl_attributes (&value, attrlist, /*flags=*/0);
return value;
}
/* Returns true iff ATTR is an attribute which needs to be applied at
instantiation time rather than template definition time. */
static bool
is_late_template_attribute (tree attr, tree decl)
{
tree name = get_attribute_name (attr);
tree args = TREE_VALUE (attr);
const struct attribute_spec *spec = lookup_attribute_spec (name);
tree arg;
if (!spec)
/* Unknown attribute. */
return false;
/* Attribute weak handling wants to write out assembly right away. */
if (is_attribute_p ("weak", name))
return true;
/* Attributes used and unused are applied directly to typedefs for the
benefit of maybe_warn_unused_local_typedefs. */
if (TREE_CODE (decl) == TYPE_DECL
&& (is_attribute_p ("unused", name)
|| is_attribute_p ("used", name)))
return false;
/* Attribute tls_model wants to modify the symtab. */
if (is_attribute_p ("tls_model", name))
return true;
/* #pragma omp declare simd attribute needs to be always deferred. */
if (flag_openmp
&& is_attribute_p ("omp declare simd", name))
return true;
/* An attribute pack is clearly dependent. */
if (args && PACK_EXPANSION_P (args))
return true;
/* If any of the arguments are dependent expressions, we can't evaluate
the attribute until instantiation time. */
for (arg = args; arg; arg = TREE_CHAIN (arg))
{
tree t = TREE_VALUE (arg);
/* If the first attribute argument is an identifier, only consider
second and following arguments. Attributes like mode, format,
cleanup and several target specific attributes aren't late
just because they have an IDENTIFIER_NODE as first argument. */
if (arg == args && attribute_takes_identifier_p (name)
&& identifier_p (t))
continue;
if (value_dependent_expression_p (t)
|| type_dependent_expression_p (t))
return true;
}
if (TREE_CODE (decl) == TYPE_DECL
|| TYPE_P (decl)
|| spec->type_required)
{
tree type = TYPE_P (decl) ? decl : TREE_TYPE (decl);
/* We can't apply any attributes to a completely unknown type until
instantiation time. */
enum tree_code code = TREE_CODE (type);
if (code == TEMPLATE_TYPE_PARM
|| code == BOUND_TEMPLATE_TEMPLATE_PARM
|| code == TYPENAME_TYPE)
return true;
/* Also defer most attributes on dependent types. This is not
necessary in all cases, but is the better default. */
else if (dependent_type_p (type)
/* But some attributes specifically apply to templates. */
&& !is_attribute_p ("abi_tag", name)
&& !is_attribute_p ("deprecated", name)
&& !is_attribute_p ("visibility", name))
return true;
else
return false;
}
else
return false;
}
/* ATTR_P is a list of attributes. Remove any attributes which need to be
applied at instantiation time and return them. If IS_DEPENDENT is true,
the declaration itself is dependent, so all attributes should be applied
at instantiation time. */
static tree
splice_template_attributes (tree *attr_p, tree decl)
{
tree *p = attr_p;
tree late_attrs = NULL_TREE;
tree *q = &late_attrs;
if (!p)
return NULL_TREE;
for (; *p; )
{
if (is_late_template_attribute (*p, decl))
{
ATTR_IS_DEPENDENT (*p) = 1;
*q = *p;
*p = TREE_CHAIN (*p);
q = &TREE_CHAIN (*q);
*q = NULL_TREE;
}
else
p = &TREE_CHAIN (*p);
}
return late_attrs;
}
/* Remove any late attributes from the list in ATTR_P and attach them to
DECL_P. */
static void
save_template_attributes (tree *attr_p, tree *decl_p, int flags)
{
tree *q;
if (attr_p && *attr_p == error_mark_node)
return;
tree late_attrs = splice_template_attributes (attr_p, *decl_p);
if (!late_attrs)
return;
if (DECL_P (*decl_p))
q = &DECL_ATTRIBUTES (*decl_p);
else
q = &TYPE_ATTRIBUTES (*decl_p);
tree old_attrs = *q;
/* Merge the late attributes at the beginning with the attribute
list. */
late_attrs = merge_attributes (late_attrs, *q);
if (*q != late_attrs
&& !DECL_P (*decl_p)
&& !(flags & ATTR_FLAG_TYPE_IN_PLACE))
{
if (!dependent_type_p (*decl_p))
*decl_p = cp_build_type_attribute_variant (*decl_p, late_attrs);
else
{
*decl_p = build_variant_type_copy (*decl_p);
TYPE_ATTRIBUTES (*decl_p) = late_attrs;
}
}
else
*q = late_attrs;
if (!DECL_P (*decl_p) && *decl_p == TYPE_MAIN_VARIANT (*decl_p))
{
/* We've added new attributes directly to the main variant, so
now we need to update all of the other variants to include
these new attributes. */
tree variant;
for (variant = TYPE_NEXT_VARIANT (*decl_p); variant;
variant = TYPE_NEXT_VARIANT (variant))
{
gcc_assert (TYPE_ATTRIBUTES (variant) == old_attrs);
TYPE_ATTRIBUTES (variant) = TYPE_ATTRIBUTES (*decl_p);
}
}
}
/* True if ATTRS contains any dependent attributes that affect type
identity. */
bool
any_dependent_type_attributes_p (tree attrs)
{
for (tree a = attrs; a; a = TREE_CHAIN (a))
if (ATTR_IS_DEPENDENT (a))
{
const attribute_spec *as = lookup_attribute_spec (TREE_PURPOSE (a));
if (as && as->affects_type_identity)
return true;
}
return false;
}
/* Return true iff ATTRS are acceptable attributes to be applied in-place
to a typedef which gives a previously unnamed class or enum a name for
linkage purposes. */
bool
attributes_naming_typedef_ok (tree attrs)
{
for (; attrs; attrs = TREE_CHAIN (attrs))
{
tree name = get_attribute_name (attrs);
if (is_attribute_p ("vector_size", name))
return false;
}
return true;
}
/* Like reconstruct_complex_type, but handle also template trees. */
tree
cp_reconstruct_complex_type (tree type, tree bottom)
{
tree inner, outer;
bool late_return_type_p = false;
if (TYPE_PTR_P (type))
{
inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
outer = build_pointer_type_for_mode (inner, TYPE_MODE (type),
TYPE_REF_CAN_ALIAS_ALL (type));
}
else if (TREE_CODE (type) == REFERENCE_TYPE)
{
inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
outer = build_reference_type_for_mode (inner, TYPE_MODE (type),
TYPE_REF_CAN_ALIAS_ALL (type));
}
else if (TREE_CODE (type) == ARRAY_TYPE)
{
inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
outer = build_cplus_array_type (inner, TYPE_DOMAIN (type));
/* Don't call cp_build_qualified_type on ARRAY_TYPEs, the
element type qualification will be handled by the recursive
cp_reconstruct_complex_type call and cp_build_qualified_type
for ARRAY_TYPEs changes the element type. */
return outer;
}
else if (TREE_CODE (type) == FUNCTION_TYPE)
{
late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (type);
inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
outer = build_function_type (inner, TYPE_ARG_TYPES (type));
outer = apply_memfn_quals (outer,
type_memfn_quals (type),
type_memfn_rqual (type));
}
else if (TREE_CODE (type) == METHOD_TYPE)
{
late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (type);
inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
/* The build_method_type_directly() routine prepends 'this' to argument list,
so we must compensate by getting rid of it. */
outer
= build_method_type_directly
(class_of_this_parm (type), inner,
TREE_CHAIN (TYPE_ARG_TYPES (type)));
}
else if (TREE_CODE (type) == OFFSET_TYPE)
{
inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
outer = build_offset_type (TYPE_OFFSET_BASETYPE (type), inner);
}
else
return bottom;
if (TYPE_ATTRIBUTES (type))
outer = cp_build_type_attribute_variant (outer, TYPE_ATTRIBUTES (type));
outer = cp_build_qualified_type (outer, cp_type_quals (type));
if (late_return_type_p)
TYPE_HAS_LATE_RETURN_TYPE (outer) = 1;
return outer;
}
/* Replaces any constexpr expression that may be into the attributes
arguments with their reduced value. */
static void
cp_check_const_attributes (tree attributes)
{
if (attributes == error_mark_node)
return;
tree attr;
for (attr = attributes; attr; attr = TREE_CHAIN (attr))
{
tree arg;
for (arg = TREE_VALUE (attr); arg; arg = TREE_CHAIN (arg))
{
tree expr = TREE_VALUE (arg);
if (EXPR_P (expr))
TREE_VALUE (arg) = fold_non_dependent_expr (expr);
}
}
}
/* Return true if TYPE is an OpenMP mappable type. */
bool
cp_omp_mappable_type (tree type)
{
/* Mappable type has to be complete. */
if (type == error_mark_node || !COMPLETE_TYPE_P (type))
return false;
/* Arrays have mappable type if the elements have mappable type. */
while (TREE_CODE (type) == ARRAY_TYPE)
type = TREE_TYPE (type);
/* A mappable type cannot contain virtual members. */
if (CLASS_TYPE_P (type) && CLASSTYPE_VTABLES (type))
return false;
/* All data members must be non-static. */
if (CLASS_TYPE_P (type))
{
tree field;
for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
if (VAR_P (field))
return false;
/* All fields must have mappable types. */
else if (TREE_CODE (field) == FIELD_DECL
&& !cp_omp_mappable_type (TREE_TYPE (field)))
return false;
}
return true;
}
/* Return the last pushed declaration for the symbol DECL or NULL
when no such declaration exists. */
static tree
find_last_decl (tree decl)
{
tree last_decl = NULL_TREE;
if (tree name = DECL_P (decl) ? DECL_NAME (decl) : NULL_TREE)
{
/* Look up the declaration in its scope. */
tree pushed_scope = NULL_TREE;
if (tree ctype = DECL_CONTEXT (decl))
pushed_scope = push_scope (ctype);
last_decl = lookup_name (name);
if (pushed_scope)
pop_scope (pushed_scope);
/* The declaration may be a member conversion operator
or a bunch of overfloads (handle the latter below). */
if (last_decl && BASELINK_P (last_decl))
last_decl = BASELINK_FUNCTIONS (last_decl);
}
if (!last_decl)
return NULL_TREE;
if (DECL_P (last_decl) || TREE_CODE (last_decl) == OVERLOAD)
{
/* A set of overloads of the same function. */
for (lkp_iterator iter (last_decl); iter; ++iter)
{
if (TREE_CODE (*iter) == OVERLOAD)
continue;
if (decls_match (decl, *iter, /*record_decls=*/false))
return *iter;
}
return NULL_TREE;
}
return NULL_TREE;
}
/* Like decl_attributes, but handle C++ complexity. */
void
cplus_decl_attributes (tree *decl, tree attributes, int flags)
{
if (*decl == NULL_TREE || *decl == void_type_node
|| *decl == error_mark_node)
return;
/* Add implicit "omp declare target" attribute if requested. */
if (scope_chain->omp_declare_target_attribute
&& ((VAR_P (*decl)
&& (TREE_STATIC (*decl) || DECL_EXTERNAL (*decl)))
|| TREE_CODE (*decl) == FUNCTION_DECL))
{
if (VAR_P (*decl)
&& DECL_CLASS_SCOPE_P (*decl))
error ("%q+D static data member inside of declare target directive",
*decl);
else if (!processing_template_decl
&& VAR_P (*decl)
&& !cp_omp_mappable_type (TREE_TYPE (*decl)))
error ("%q+D in declare target directive does not have mappable type",
*decl);
else
attributes = tree_cons (get_identifier ("omp declare target"),
NULL_TREE, attributes);
}
if (processing_template_decl)
{
if (check_for_bare_parameter_packs (attributes))
return;
save_template_attributes (&attributes, decl, flags);
}
cp_check_const_attributes (attributes);
if (TREE_CODE (*decl) == TEMPLATE_DECL)
decl = &DECL_TEMPLATE_RESULT (*decl);
if (TREE_TYPE (*decl) && TYPE_PTRMEMFUNC_P (TREE_TYPE (*decl)))
{
attributes
= decl_attributes (decl, attributes, flags | ATTR_FLAG_FUNCTION_NEXT);
decl_attributes (&TYPE_PTRMEMFUNC_FN_TYPE_RAW (TREE_TYPE (*decl)),
attributes, flags);
}
else
{
tree last_decl = find_last_decl (*decl);
decl_attributes (decl, attributes, flags, last_decl);
}
if (TREE_CODE (*decl) == TYPE_DECL)
SET_IDENTIFIER_TYPE_VALUE (DECL_NAME (*decl), TREE_TYPE (*decl));
/* Propagate deprecation out to the template. */
if (TREE_DEPRECATED (*decl))
if (tree ti = get_template_info (*decl))
{
tree tmpl = TI_TEMPLATE (ti);
tree pattern = (TYPE_P (*decl) ? TREE_TYPE (tmpl)
: DECL_TEMPLATE_RESULT (tmpl));
if (*decl == pattern)
TREE_DEPRECATED (tmpl) = true;
}
}
/* Walks through the namespace- or function-scope anonymous union
OBJECT, with the indicated TYPE, building appropriate VAR_DECLs.
Returns one of the fields for use in the mangled name. */
static tree
build_anon_union_vars (tree type, tree object)
{
tree main_decl = NULL_TREE;
tree field;
/* Rather than write the code to handle the non-union case,
just give an error. */
if (TREE_CODE (type) != UNION_TYPE)
{
error ("anonymous struct not inside named type");
return error_mark_node;
}
for (field = TYPE_FIELDS (type);
field != NULL_TREE;
field = DECL_CHAIN (field))
{
tree decl;
tree ref;
if (DECL_ARTIFICIAL (field))
continue;
if (TREE_CODE (field) != FIELD_DECL)
{
permerror (DECL_SOURCE_LOCATION (field),
"%q#D invalid; an anonymous union can only "
"have non-static data members", field);
continue;
}
if (TREE_PRIVATE (field))
permerror (DECL_SOURCE_LOCATION (field),
"private member %q#D in anonymous union", field);
else if (TREE_PROTECTED (field))
permerror (DECL_SOURCE_LOCATION (field),
"protected member %q#D in anonymous union", field);
if (processing_template_decl)
ref = build_min_nt_loc (UNKNOWN_LOCATION, COMPONENT_REF, object,
DECL_NAME (field), NULL_TREE);
else
ref = build_class_member_access_expr (object, field, NULL_TREE,
false, tf_warning_or_error);
if (DECL_NAME (field))
{
tree base;
decl = build_decl (input_location,
VAR_DECL, DECL_NAME (field), TREE_TYPE (field));
DECL_ANON_UNION_VAR_P (decl) = 1;
DECL_ARTIFICIAL (decl) = 1;
base = get_base_address (object);
TREE_PUBLIC (decl) = TREE_PUBLIC (base);
TREE_STATIC (decl) = TREE_STATIC (base);
DECL_EXTERNAL (decl) = DECL_EXTERNAL (base);
SET_DECL_VALUE_EXPR (decl, ref);
DECL_HAS_VALUE_EXPR_P (decl) = 1;
decl = pushdecl (decl);
}
else if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
decl = build_anon_union_vars (TREE_TYPE (field), ref);
else
decl = 0;
if (main_decl == NULL_TREE)
main_decl = decl;
}
return main_decl;
}
/* Finish off the processing of a UNION_TYPE structure. If the union is an
anonymous union, then all members must be laid out together. PUBLIC_P
is nonzero if this union is not declared static. */
void
finish_anon_union (tree anon_union_decl)
{
tree type;
tree main_decl;
bool public_p;
if (anon_union_decl == error_mark_node)
return;
type = TREE_TYPE (anon_union_decl);
public_p = TREE_PUBLIC (anon_union_decl);
/* The VAR_DECL's context is the same as the TYPE's context. */
DECL_CONTEXT (anon_union_decl) = DECL_CONTEXT (TYPE_NAME (type));
if (TYPE_FIELDS (type) == NULL_TREE)
return;
if (public_p)
{
error ("namespace-scope anonymous aggregates must be static");
return;
}
main_decl = build_anon_union_vars (type, anon_union_decl);
if (main_decl == error_mark_node)
return;
if (main_decl == NULL_TREE)
{
pedwarn (input_location, 0, "anonymous union with no members");
return;
}
if (!processing_template_decl)
{
/* Use main_decl to set the mangled name. */
DECL_NAME (anon_union_decl) = DECL_NAME (main_decl);
maybe_commonize_var (anon_union_decl);
if (TREE_STATIC (anon_union_decl) || DECL_EXTERNAL (anon_union_decl))
mangle_decl (anon_union_decl);
DECL_NAME (anon_union_decl) = NULL_TREE;
}
pushdecl (anon_union_decl);
cp_finish_decl (anon_union_decl, NULL_TREE, false, NULL_TREE, 0);
}
/* Auxiliary functions to make type signatures for
`operator new' and `operator delete' correspond to
what compiler will be expecting. */
tree
coerce_new_type (tree type)
{
int e = 0;
tree args = TYPE_ARG_TYPES (type);
gcc_assert (TREE_CODE (type) == FUNCTION_TYPE);
if (!same_type_p (TREE_TYPE (type), ptr_type_node))
{
e = 1;
error ("%<operator new%> must return type %qT", ptr_type_node);
}
if (args && args != void_list_node)
{
if (TREE_PURPOSE (args))
{
/* [basic.stc.dynamic.allocation]
The first parameter shall not have an associated default
argument. */
error ("the first parameter of %<operator new%> cannot "
"have a default argument");
/* Throw away the default argument. */
TREE_PURPOSE (args) = NULL_TREE;
}
if (!same_type_p (TREE_VALUE (args), size_type_node))
{
e = 2;
args = TREE_CHAIN (args);
}
}
else
e = 2;
if (e == 2)
permerror (input_location, "%<operator new%> takes type %<size_t%> (%qT) "
"as first parameter", size_type_node);
switch (e)
{
case 2:
args = tree_cons (NULL_TREE, size_type_node, args);
/* Fall through. */
case 1:
type = build_exception_variant
(build_function_type (ptr_type_node, args),
TYPE_RAISES_EXCEPTIONS (type));
/* Fall through. */
default:;
}
return type;
}
tree
coerce_delete_type (tree type)
{
int e = 0;
tree args = TYPE_ARG_TYPES (type);
gcc_assert (TREE_CODE (type) == FUNCTION_TYPE);
if (!same_type_p (TREE_TYPE (type), void_type_node))
{
e = 1;
error ("%<operator delete%> must return type %qT", void_type_node);
}
if (!args || args == void_list_node
|| !same_type_p (TREE_VALUE (args), ptr_type_node))
{
e = 2;
if (args && args != void_list_node)
args = TREE_CHAIN (args);
error ("%<operator delete%> takes type %qT as first parameter",
ptr_type_node);
}
switch (e)
{
case 2:
args = tree_cons (NULL_TREE, ptr_type_node, args);
/* Fall through. */
case 1:
type = build_exception_variant
(build_function_type (void_type_node, args),
TYPE_RAISES_EXCEPTIONS (type));
/* Fall through. */
default:;
}
return type;
}
/* DECL is a VAR_DECL for a vtable: walk through the entries in the vtable
and mark them as needed. */
static void
mark_vtable_entries (tree decl)
{
tree fnaddr;
unsigned HOST_WIDE_INT idx;
/* It's OK for the vtable to refer to deprecated virtual functions. */
warning_sentinel w(warn_deprecated_decl);
FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (DECL_INITIAL (decl)),
idx, fnaddr)
{
tree fn;
STRIP_NOPS (fnaddr);
if (TREE_CODE (fnaddr) != ADDR_EXPR
&& TREE_CODE (fnaddr) != FDESC_EXPR)
/* This entry is an offset: a virtual base class offset, a
virtual call offset, an RTTI offset, etc. */
continue;
fn = TREE_OPERAND (fnaddr, 0);
TREE_ADDRESSABLE (fn) = 1;
/* When we don't have vcall offsets, we output thunks whenever
we output the vtables that contain them. With vcall offsets,
we know all the thunks we'll need when we emit a virtual
function, so we emit the thunks there instead. */
if (DECL_THUNK_P (fn))
use_thunk (fn, /*emit_p=*/0);
/* Set the location, as marking the function could cause
instantiation. We do not need to preserve the incoming
location, as we're called from c_parse_final_cleanups, which
takes care of that. */
input_location = DECL_SOURCE_LOCATION (fn);
mark_used (fn);
}
}
/* Set DECL up to have the closest approximation of "initialized common"
linkage available. */
void
comdat_linkage (tree decl)
{
if (flag_weak)
make_decl_one_only (decl, cxx_comdat_group (decl));
else if (TREE_CODE (decl) == FUNCTION_DECL
|| (VAR_P (decl) && DECL_ARTIFICIAL (decl)))
/* We can just emit function and compiler-generated variables
statically; having multiple copies is (for the most part) only
a waste of space.
There are two correctness issues, however: the address of a
template instantiation with external linkage should be the
same, independent of what translation unit asks for the
address, and this will not hold when we emit multiple copies of
the function. However, there's little else we can do.
Also, by default, the typeinfo implementation assumes that
there will be only one copy of the string used as the name for
each type. Therefore, if weak symbols are unavailable, the
run-time library should perform a more conservative check; it
should perform a string comparison, rather than an address
comparison. */
TREE_PUBLIC (decl) = 0;
else
{
/* Static data member template instantiations, however, cannot
have multiple copies. */
if (DECL_INITIAL (decl) == 0
|| DECL_INITIAL (decl) == error_mark_node)
DECL_COMMON (decl) = 1;
else if (EMPTY_CONSTRUCTOR_P (DECL_INITIAL (decl)))
{
DECL_COMMON (decl) = 1;
DECL_INITIAL (decl) = error_mark_node;
}
else if (!DECL_EXPLICIT_INSTANTIATION (decl))
{
/* We can't do anything useful; leave vars for explicit
instantiation. */
DECL_EXTERNAL (decl) = 1;
DECL_NOT_REALLY_EXTERN (decl) = 0;
}
}
if (TREE_PUBLIC (decl))
DECL_COMDAT (decl) = 1;
}
/* For win32 we also want to put explicit instantiations in
linkonce sections, so that they will be merged with implicit
instantiations; otherwise we get duplicate symbol errors.
For Darwin we do not want explicit instantiations to be
linkonce. */
void
maybe_make_one_only (tree decl)
{
/* We used to say that this was not necessary on targets that support weak
symbols, because the implicit instantiations will defer to the explicit
one. However, that's not actually the case in SVR4; a strong definition
after a weak one is an error. Also, not making explicit
instantiations one_only means that we can end up with two copies of
some template instantiations. */
if (! flag_weak)
return;
/* We can't set DECL_COMDAT on functions, or cp_finish_file will think
we can get away with not emitting them if they aren't used. We need
to for variables so that cp_finish_decl will update their linkage,
because their DECL_INITIAL may not have been set properly yet. */
if (!TARGET_WEAK_NOT_IN_ARCHIVE_TOC
|| (! DECL_EXPLICIT_INSTANTIATION (decl)
&& ! DECL_TEMPLATE_SPECIALIZATION (decl)))
{
make_decl_one_only (decl, cxx_comdat_group (decl));
if (VAR_P (decl))
{
varpool_node *node = varpool_node::get_create (decl);
DECL_COMDAT (decl) = 1;
/* Mark it needed so we don't forget to emit it. */
node->forced_by_abi = true;
TREE_USED (decl) = 1;
}
}
}
/* Returns true iff DECL, a FUNCTION_DECL or VAR_DECL, has vague linkage.
This predicate will give the right answer during parsing of the
function, which other tests may not. */
bool
vague_linkage_p (tree decl)
{
if (!TREE_PUBLIC (decl))
{
/* maybe_thunk_body clears TREE_PUBLIC on the maybe-in-charge 'tor
variants, check one of the "clones" for the real linkage. */
if ((DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P (decl)
|| DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl))
&& DECL_CHAIN (decl)
&& DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)))
return vague_linkage_p (DECL_CHAIN (decl));
gcc_checking_assert (!DECL_COMDAT (decl));
return false;
}
/* Unfortunately, import_export_decl has not always been called
before the function is processed, so we cannot simply check
DECL_COMDAT. */
if (DECL_COMDAT (decl)
|| (TREE_CODE (decl) == FUNCTION_DECL
&& DECL_DECLARED_INLINE_P (decl))
|| (DECL_LANG_SPECIFIC (decl)
&& DECL_TEMPLATE_INSTANTIATION (decl))
|| (VAR_P (decl) && DECL_INLINE_VAR_P (decl)))
return true;
else if (DECL_FUNCTION_SCOPE_P (decl))
/* A local static in an inline effectively has vague linkage. */
return (TREE_STATIC (decl)
&& vague_linkage_p (DECL_CONTEXT (decl)));
else
return false;
}
/* Determine whether or not we want to specifically import or export CTYPE,
using various heuristics. */
static void
import_export_class (tree ctype)
{
/* -1 for imported, 1 for exported. */
int import_export = 0;
/* It only makes sense to call this function at EOF. The reason is
that this function looks at whether or not the first non-inline
non-abstract virtual member function has been defined in this
translation unit. But, we can't possibly know that until we've
seen the entire translation unit. */
gcc_assert (at_eof);
if (CLASSTYPE_INTERFACE_KNOWN (ctype))
return;
/* If MULTIPLE_SYMBOL_SPACES is set and we saw a #pragma interface,
we will have CLASSTYPE_INTERFACE_ONLY set but not
CLASSTYPE_INTERFACE_KNOWN. In that case, we don't want to use this
heuristic because someone will supply a #pragma implementation
elsewhere, and deducing it here would produce a conflict. */
if (CLASSTYPE_INTERFACE_ONLY (ctype))
return;
if (lookup_attribute ("dllimport", TYPE_ATTRIBUTES (ctype)))
import_export = -1;
else if (lookup_attribute ("dllexport", TYPE_ATTRIBUTES (ctype)))
import_export = 1;
else if (CLASSTYPE_IMPLICIT_INSTANTIATION (ctype)
&& !flag_implicit_templates)
/* For a template class, without -fimplicit-templates, check the
repository. If the virtual table is assigned to this
translation unit, then export the class; otherwise, import
it. */
import_export = repo_export_class_p (ctype) ? 1 : -1;
else if (TYPE_POLYMORPHIC_P (ctype))
{
/* The ABI specifies that the virtual table and associated
information are emitted with the key method, if any. */
tree method = CLASSTYPE_KEY_METHOD (ctype);
/* If weak symbol support is not available, then we must be
careful not to emit the vtable when the key function is
inline. An inline function can be defined in multiple
translation units. If we were to emit the vtable in each
translation unit containing a definition, we would get
multiple definition errors at link-time. */
if (method && (flag_weak || ! DECL_DECLARED_INLINE_P (method)))
import_export = (DECL_REALLY_EXTERN (method) ? -1 : 1);
}
/* When MULTIPLE_SYMBOL_SPACES is set, we cannot count on seeing
a definition anywhere else. */
if (MULTIPLE_SYMBOL_SPACES && import_export == -1)
import_export = 0;
/* Allow back ends the chance to overrule the decision. */
if (targetm.cxx.import_export_class)
import_export = targetm.cxx.import_export_class (ctype, import_export);
if (import_export)
{
SET_CLASSTYPE_INTERFACE_KNOWN (ctype);
CLASSTYPE_INTERFACE_ONLY (ctype) = (import_export < 0);
}
}
/* Return true if VAR has already been provided to the back end; in that
case VAR should not be modified further by the front end. */
static bool
var_finalized_p (tree var)
{
return varpool_node::get_create (var)->definition;
}
/* DECL is a VAR_DECL or FUNCTION_DECL which, for whatever reason,
must be emitted in this translation unit. Mark it as such. */
void
mark_needed (tree decl)
{
TREE_USED (decl) = 1;
if (TREE_CODE (decl) == FUNCTION_DECL)
{
/* Extern inline functions don't become needed when referenced.
If we know a method will be emitted in other TU and no new
functions can be marked reachable, just use the external
definition. */
struct cgraph_node *node = cgraph_node::get_create (decl);
node->forced_by_abi = true;
/* #pragma interface and -frepo code can call mark_needed for
maybe-in-charge 'tors; mark the clones as well. */
tree clone;
FOR_EACH_CLONE (clone, decl)
mark_needed (clone);
}
else if (VAR_P (decl))
{
varpool_node *node = varpool_node::get_create (decl);
/* C++ frontend use mark_decl_references to force COMDAT variables
to be output that might appear dead otherwise. */
node->forced_by_abi = true;
}
}
/* DECL is either a FUNCTION_DECL or a VAR_DECL. This function
returns true if a definition of this entity should be provided in
this object file. Callers use this function to determine whether
or not to let the back end know that a definition of DECL is
available in this translation unit. */
bool
decl_needed_p (tree decl)
{
gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
/* This function should only be called at the end of the translation
unit. We cannot be sure of whether or not something will be
COMDAT until that point. */
gcc_assert (at_eof);
/* All entities with external linkage that are not COMDAT/EXTERN should be
emitted; they may be referred to from other object files. */
if (TREE_PUBLIC (decl) && !DECL_COMDAT (decl) && !DECL_REALLY_EXTERN (decl))
return true;
/* Functions marked "dllexport" must be emitted so that they are
visible to other DLLs. */
if (flag_keep_inline_dllexport
&& lookup_attribute ("dllexport", DECL_ATTRIBUTES (decl)))
return true;
/* When not optimizing, do not bother to produce definitions for extern
symbols. */
if (DECL_REALLY_EXTERN (decl)
&& ((TREE_CODE (decl) != FUNCTION_DECL
&& !optimize)
|| (TREE_CODE (decl) == FUNCTION_DECL
&& !opt_for_fn (decl, optimize)))
&& !lookup_attribute ("always_inline", decl))
return false;
/* If this entity was used, let the back end see it; it will decide
whether or not to emit it into the object file. */
if (TREE_USED (decl))
return true;
/* Virtual functions might be needed for devirtualization. */
if (flag_devirtualize
&& TREE_CODE (decl) == FUNCTION_DECL
&& DECL_VIRTUAL_P (decl))
return true;
/* Otherwise, DECL does not need to be emitted -- yet. A subsequent
reference to DECL might cause it to be emitted later. */
return false;
}
/* If necessary, write out the vtables for the dynamic class CTYPE.
Returns true if any vtables were emitted. */
static bool
maybe_emit_vtables (tree ctype)
{
tree vtbl;
tree primary_vtbl;
int needed = 0;
varpool_node *current = NULL, *last = NULL;
/* If the vtables for this class have already been emitted there is
nothing more to do. */
primary_vtbl = CLASSTYPE_VTABLES (ctype);
if (var_finalized_p (primary_vtbl))
return false;
/* Ignore dummy vtables made by get_vtable_decl. */
if (TREE_TYPE (primary_vtbl) == void_type_node)
return false;
/* On some targets, we cannot determine the key method until the end
of the translation unit -- which is when this function is
called. */
if (!targetm.cxx.key_method_may_be_inline ())
determine_key_method (ctype);
/* See if any of the vtables are needed. */
for (vtbl = CLASSTYPE_VTABLES (ctype); vtbl; vtbl = DECL_CHAIN (vtbl))
{
import_export_decl (vtbl);
if (DECL_NOT_REALLY_EXTERN (vtbl) && decl_needed_p (vtbl))
needed = 1;
}
if (!needed)
{
/* If the references to this class' vtables are optimized away,
still emit the appropriate debugging information. See
dfs_debug_mark. */
if (DECL_COMDAT (primary_vtbl)
&& CLASSTYPE_DEBUG_REQUESTED (ctype))
note_debug_info_needed (ctype);
return false;
}
/* The ABI requires that we emit all of the vtables if we emit any
of them. */
for (vtbl = CLASSTYPE_VTABLES (ctype); vtbl; vtbl = DECL_CHAIN (vtbl))
{
/* Mark entities references from the virtual table as used. */
mark_vtable_entries (vtbl);
if (TREE_TYPE (DECL_INITIAL (vtbl)) == 0)
{
vec<tree, va_gc> *cleanups = NULL;
tree expr = store_init_value (vtbl, DECL_INITIAL (vtbl), &cleanups,
LOOKUP_NORMAL);
/* It had better be all done at compile-time. */
gcc_assert (!expr && !cleanups);
}
/* Write it out. */
DECL_EXTERNAL (vtbl) = 0;
rest_of_decl_compilation (vtbl, 1, 1);
/* Because we're only doing syntax-checking, we'll never end up
actually marking the variable as written. */
if (flag_syntax_only)
TREE_ASM_WRITTEN (vtbl) = 1;
else if (DECL_ONE_ONLY (vtbl))
{
current = varpool_node::get_create (vtbl);
if (last)
current->add_to_same_comdat_group (last);
last = current;
}
}
/* Since we're writing out the vtable here, also write the debug
info. */
note_debug_info_needed (ctype);
return true;
}
/* A special return value from type_visibility meaning internal
linkage. */
enum { VISIBILITY_ANON = VISIBILITY_INTERNAL+1 };
/* walk_tree helper function for type_visibility. */
static tree
min_vis_r (tree *tp, int *walk_subtrees, void *data)
{
int *vis_p = (int *)data;
if (! TYPE_P (*tp))
{
*walk_subtrees = 0;
}
else if (OVERLOAD_TYPE_P (*tp)
&& !TREE_PUBLIC (TYPE_MAIN_DECL (*tp)))
{
*vis_p = VISIBILITY_ANON;
return *tp;
}
else if (CLASS_TYPE_P (*tp)
&& CLASSTYPE_VISIBILITY (*tp) > *vis_p)
*vis_p = CLASSTYPE_VISIBILITY (*tp);
return NULL;
}
/* Returns the visibility of TYPE, which is the minimum visibility of its
component types. */
static int
type_visibility (tree type)
{
int vis = VISIBILITY_DEFAULT;
cp_walk_tree_without_duplicates (&type, min_vis_r, &vis);
return vis;
}
/* Limit the visibility of DECL to VISIBILITY, if not explicitly
specified (or if VISIBILITY is static). If TMPL is true, this
constraint is for a template argument, and takes precedence
over explicitly-specified visibility on the template. */
static void
constrain_visibility (tree decl, int visibility, bool tmpl)
{
if (visibility == VISIBILITY_ANON)
{
/* extern "C" declarations aren't affected by the anonymous
namespace. */
if (!DECL_EXTERN_C_P (decl))
{
TREE_PUBLIC (decl) = 0;
DECL_WEAK (decl) = 0;
DECL_COMMON (decl) = 0;
DECL_COMDAT (decl) = false;
if (VAR_OR_FUNCTION_DECL_P (decl))
{
struct symtab_node *snode = symtab_node::get (decl);
if (snode)
snode->set_comdat_group (NULL);
}
DECL_INTERFACE_KNOWN (decl) = 1;
if (DECL_LANG_SPECIFIC (decl))
DECL_NOT_REALLY_EXTERN (decl) = 1;
}
}
else if (visibility > DECL_VISIBILITY (decl)
&& (tmpl || !DECL_VISIBILITY_SPECIFIED (decl)))
{
DECL_VISIBILITY (decl) = (enum symbol_visibility) visibility;
/* This visibility was not specified. */
DECL_VISIBILITY_SPECIFIED (decl) = false;
}
}
/* Constrain the visibility of DECL based on the visibility of its template
arguments. */
static void
constrain_visibility_for_template (tree decl, tree targs)
{
/* If this is a template instantiation, check the innermost
template args for visibility constraints. The outer template
args are covered by the class check. */
tree args = INNERMOST_TEMPLATE_ARGS (targs);
int i;
for (i = TREE_VEC_LENGTH (args); i > 0; --i)
{
int vis = 0;
tree arg = TREE_VEC_ELT (args, i-1);
if (TYPE_P (arg))
vis = type_visibility (arg);
else
{
if (REFERENCE_REF_P (arg))
arg = TREE_OPERAND (arg, 0);
if (TREE_TYPE (arg))
STRIP_NOPS (arg);
if (TREE_CODE (arg) == ADDR_EXPR)
arg = TREE_OPERAND (arg, 0);
if (VAR_OR_FUNCTION_DECL_P (arg))
{
if (! TREE_PUBLIC (arg))
vis = VISIBILITY_ANON;
else
vis = DECL_VISIBILITY (arg);
}
}
if (vis)
constrain_visibility (decl, vis, true);
}
}
/* Like c_determine_visibility, but with additional C++-specific
behavior.
Function-scope entities can rely on the function's visibility because
it is set in start_preparsed_function.
Class-scope entities cannot rely on the class's visibility until the end
of the enclosing class definition.
Note that because namespaces have multiple independent definitions,
namespace visibility is handled elsewhere using the #pragma visibility
machinery rather than by decorating the namespace declaration.
The goal is for constraints from the type to give a diagnostic, and
other constraints to be applied silently. */
void
determine_visibility (tree decl)
{
/* Remember that all decls get VISIBILITY_DEFAULT when built. */
/* Only relevant for names with external linkage. */
if (!TREE_PUBLIC (decl))
return;
/* Cloned constructors and destructors get the same visibility as
the underlying function. That should be set up in
maybe_clone_body. */
gcc_assert (!DECL_CLONED_FUNCTION_P (decl));
bool orig_visibility_specified = DECL_VISIBILITY_SPECIFIED (decl);
enum symbol_visibility orig_visibility = DECL_VISIBILITY (decl);
/* The decl may be a template instantiation, which could influence
visibilty. */
tree template_decl = NULL_TREE;
if (TREE_CODE (decl) == TYPE_DECL)
{
if (CLASS_TYPE_P (TREE_TYPE (decl)))
{
if (CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)))
template_decl = decl;
}
else if (TYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
template_decl = decl;
}
else if (DECL_LANG_SPECIFIC (decl) && DECL_USE_TEMPLATE (decl))
template_decl = decl;
/* If DECL is a member of a class, visibility specifiers on the
class can influence the visibility of the DECL. */
tree class_type = NULL_TREE;
if (DECL_CLASS_SCOPE_P (decl))
class_type = DECL_CONTEXT (decl);
else
{
/* Not a class member. */
/* Virtual tables have DECL_CONTEXT set to their associated class,
so they are automatically handled above. */
gcc_assert (!VAR_P (decl)
|| !DECL_VTABLE_OR_VTT_P (decl));
if (DECL_FUNCTION_SCOPE_P (decl) && ! DECL_VISIBILITY_SPECIFIED (decl))
{
/* Local statics and classes get the visibility of their
containing function by default, except that
-fvisibility-inlines-hidden doesn't affect them. */
tree fn = DECL_CONTEXT (decl);
if (DECL_VISIBILITY_SPECIFIED (fn))
{
DECL_VISIBILITY (decl) = DECL_VISIBILITY (fn);
DECL_VISIBILITY_SPECIFIED (decl) =
DECL_VISIBILITY_SPECIFIED (fn);
}
else
{
if (DECL_CLASS_SCOPE_P (fn))
determine_visibility_from_class (decl, DECL_CONTEXT (fn));
else if (determine_hidden_inline (fn))
{
DECL_VISIBILITY (decl) = default_visibility;
DECL_VISIBILITY_SPECIFIED (decl) =
visibility_options.inpragma;
}
else
{
DECL_VISIBILITY (decl) = DECL_VISIBILITY (fn);
DECL_VISIBILITY_SPECIFIED (decl) =
DECL_VISIBILITY_SPECIFIED (fn);
}
}
/* Local classes in templates have CLASSTYPE_USE_TEMPLATE set,
but have no TEMPLATE_INFO. Their containing template
function does, and the local class could be constrained
by that. */
if (DECL_LANG_SPECIFIC (fn) && DECL_USE_TEMPLATE (fn))
template_decl = fn;
else if (template_decl)
{
/* FN must be a regenerated lambda function, since they don't
have template arguments. Find a containing non-lambda
template instantiation. */
tree ctx = fn;
while (ctx && !get_template_info (ctx))
ctx = get_containing_scope (ctx);
template_decl = ctx;
}
}
else if (VAR_P (decl) && DECL_TINFO_P (decl)
&& flag_visibility_ms_compat)
{
/* Under -fvisibility-ms-compat, types are visible by default,
even though their contents aren't. */
tree underlying_type = TREE_TYPE (DECL_NAME (decl));
int underlying_vis = type_visibility (underlying_type);
if (underlying_vis == VISIBILITY_ANON
|| (CLASS_TYPE_P (underlying_type)
&& CLASSTYPE_VISIBILITY_SPECIFIED (underlying_type)))
constrain_visibility (decl, underlying_vis, false);
else
DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
}
else if (VAR_P (decl) && DECL_TINFO_P (decl))
{
/* tinfo visibility is based on the type it's for. */
constrain_visibility
(decl, type_visibility (TREE_TYPE (DECL_NAME (decl))), false);
/* Give the target a chance to override the visibility associated
with DECL. */
if (TREE_PUBLIC (decl)
&& !DECL_REALLY_EXTERN (decl)
&& CLASS_TYPE_P (TREE_TYPE (DECL_NAME (decl)))
&& !CLASSTYPE_VISIBILITY_SPECIFIED (TREE_TYPE (DECL_NAME (decl))))
targetm.cxx.determine_class_data_visibility (decl);
}
else if (template_decl)
/* Template instantiations and specializations get visibility based
on their template unless they override it with an attribute. */;
else if (! DECL_VISIBILITY_SPECIFIED (decl))
{
if (determine_hidden_inline (decl))
DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
else
{
/* Set default visibility to whatever the user supplied with
#pragma GCC visibility or a namespace visibility attribute. */
DECL_VISIBILITY (decl) = default_visibility;
DECL_VISIBILITY_SPECIFIED (decl) = visibility_options.inpragma;
}
}
}
if (template_decl)
{
/* If the specialization doesn't specify visibility, use the
visibility from the template. */
tree tinfo = get_template_info (template_decl);
tree args = TI_ARGS (tinfo);
tree attribs = (TREE_CODE (decl) == TYPE_DECL
? TYPE_ATTRIBUTES (TREE_TYPE (decl))
: DECL_ATTRIBUTES (decl));
if (args != error_mark_node)
{
tree pattern = DECL_TEMPLATE_RESULT (TI_TEMPLATE (tinfo));
if (!DECL_VISIBILITY_SPECIFIED (decl))
{
if (!DECL_VISIBILITY_SPECIFIED (pattern)
&& determine_hidden_inline (decl))
DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
else
{
DECL_VISIBILITY (decl) = DECL_VISIBILITY (pattern);
DECL_VISIBILITY_SPECIFIED (decl)
= DECL_VISIBILITY_SPECIFIED (pattern);
}
}
if (args
/* Template argument visibility outweighs #pragma or namespace
visibility, but not an explicit attribute. */
&& !lookup_attribute ("visibility", attribs))
{
int depth = TMPL_ARGS_DEPTH (args);
if (DECL_VISIBILITY_SPECIFIED (decl))
{
/* A class template member with explicit visibility
overrides the class visibility, so we need to apply
all the levels of template args directly. */
int i;
for (i = 1; i <= depth; ++i)
{
tree lev = TMPL_ARGS_LEVEL (args, i);
constrain_visibility_for_template (decl, lev);
}
}
else if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
/* Limit visibility based on its template arguments. */
constrain_visibility_for_template (decl, args);
}
}
}
if (class_type)
determine_visibility_from_class (decl, class_type);
if (decl_anon_ns_mem_p (decl))
/* Names in an anonymous namespace get internal linkage.
This might change once we implement export. */
constrain_visibility (decl, VISIBILITY_ANON, false);
else if (TREE_CODE (decl) != TYPE_DECL)
{
/* Propagate anonymity from type to decl. */
int tvis = type_visibility (TREE_TYPE (decl));
if (tvis == VISIBILITY_ANON
|| ! DECL_VISIBILITY_SPECIFIED (decl))
constrain_visibility (decl, tvis, false);
}
else if (no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/true))
/* DR 757: A type without linkage shall not be used as the type of a
variable or function with linkage, unless
o the variable or function has extern "C" linkage (7.5 [dcl.link]), or
o the variable or function is not used (3.2 [basic.def.odr]) or is
defined in the same translation unit.
Since non-extern "C" decls need to be defined in the same
translation unit, we can make the type internal. */
constrain_visibility (decl, VISIBILITY_ANON, false);
/* If visibility changed and DECL already has DECL_RTL, ensure
symbol flags are updated. */
if ((DECL_VISIBILITY (decl) != orig_visibility
|| DECL_VISIBILITY_SPECIFIED (decl) != orig_visibility_specified)
&& ((VAR_P (decl) && TREE_STATIC (decl))
|| TREE_CODE (decl) == FUNCTION_DECL)
&& DECL_RTL_SET_P (decl))
make_decl_rtl (decl);
}
/* By default, static data members and function members receive
the visibility of their containing class. */
static void
determine_visibility_from_class (tree decl, tree class_type)
{
if (DECL_VISIBILITY_SPECIFIED (decl))
return;
if (determine_hidden_inline (decl))
DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
else
{
/* Default to the class visibility. */
DECL_VISIBILITY (decl) = CLASSTYPE_VISIBILITY (class_type);
DECL_VISIBILITY_SPECIFIED (decl)
= CLASSTYPE_VISIBILITY_SPECIFIED (class_type);
}
/* Give the target a chance to override the visibility associated
with DECL. */
if (VAR_P (decl)
&& (DECL_TINFO_P (decl)
|| (DECL_VTABLE_OR_VTT_P (decl)
/* Construction virtual tables are not exported because
they cannot be referred to from other object files;
their name is not standardized by the ABI. */
&& !DECL_CONSTRUCTION_VTABLE_P (decl)))
&& TREE_PUBLIC (decl)
&& !DECL_REALLY_EXTERN (decl)
&& !CLASSTYPE_VISIBILITY_SPECIFIED (class_type))
targetm.cxx.determine_class_data_visibility (decl);
}
/* Returns true iff DECL is an inline that should get hidden visibility
because of -fvisibility-inlines-hidden. */
static bool
determine_hidden_inline (tree decl)
{
return (visibility_options.inlines_hidden
/* Don't do this for inline templates; specializations might not be
inline, and we don't want them to inherit the hidden
visibility. We'll set it here for all inline instantiations. */
&& !processing_template_decl
&& TREE_CODE (decl) == FUNCTION_DECL
&& DECL_DECLARED_INLINE_P (decl)
&& (! DECL_LANG_SPECIFIC (decl)
|| ! DECL_EXPLICIT_INSTANTIATION (decl)));
}
/* Constrain the visibility of a class TYPE based on the visibility of its
field types. Warn if any fields require lesser visibility. */
void
constrain_class_visibility (tree type)
{
tree binfo;
tree t;
int i;
int vis = type_visibility (type);
if (vis == VISIBILITY_ANON
|| DECL_IN_SYSTEM_HEADER (TYPE_MAIN_DECL (type)))
return;
/* Don't warn about visibility if the class has explicit visibility. */
if (CLASSTYPE_VISIBILITY_SPECIFIED (type))
vis = VISIBILITY_INTERNAL;
for (t = TYPE_FIELDS (type); t; t = DECL_CHAIN (t))
if (TREE_CODE (t) == FIELD_DECL && TREE_TYPE (t) != error_mark_node
&& !DECL_ARTIFICIAL (t))
{
tree ftype = strip_pointer_or_array_types (TREE_TYPE (t));
int subvis = type_visibility (ftype);
if (subvis == VISIBILITY_ANON)
{
if (!in_main_input_context())
{
tree nlt = no_linkage_check (ftype, /*relaxed_p=*/false);
if (nlt)
{
if (same_type_p (TREE_TYPE (t), nlt))
warning (OPT_Wsubobject_linkage, "\
%qT has a field %qD whose type has no linkage",
type, t);
else
warning (OPT_Wsubobject_linkage, "\
%qT has a field %qD whose type depends on the type %qT which has no linkage",
type, t, nlt);
}
else
warning (OPT_Wsubobject_linkage, "\
%qT has a field %qD whose type uses the anonymous namespace",
type, t);
}
}
else if (MAYBE_CLASS_TYPE_P (ftype)
&& vis < VISIBILITY_HIDDEN
&& subvis >= VISIBILITY_HIDDEN)
warning (OPT_Wattributes, "\
%qT declared with greater visibility than the type of its field %qD",
type, t);
}
binfo = TYPE_BINFO (type);
for (i = 0; BINFO_BASE_ITERATE (binfo, i, t); ++i)
{
int subvis = type_visibility (TREE_TYPE (t));
if (subvis == VISIBILITY_ANON)
{
if (!in_main_input_context())
{
tree nlt = no_linkage_check (TREE_TYPE (t), /*relaxed_p=*/false);
if (nlt)
{
if (same_type_p (TREE_TYPE (t), nlt))
warning (OPT_Wsubobject_linkage, "\
%qT has a base %qT whose type has no linkage",
type, TREE_TYPE (t));
else
warning (OPT_Wsubobject_linkage, "\
%qT has a base %qT whose type depends on the type %qT which has no linkage",
type, TREE_TYPE (t), nlt);
}
else
warning (OPT_Wsubobject_linkage, "\
%qT has a base %qT whose type uses the anonymous namespace",
type, TREE_TYPE (t));
}
}
else if (vis < VISIBILITY_HIDDEN
&& subvis >= VISIBILITY_HIDDEN)
warning (OPT_Wattributes, "\
%qT declared with greater visibility than its base %qT",
type, TREE_TYPE (t));
}
}
/* Functions for adjusting the visibility of a tagged type and its nested
types and declarations when it gets a name for linkage purposes from a
typedef. */
static void bt_reset_linkage_1 (binding_entry, void *);
static void bt_reset_linkage_2 (binding_entry, void *);
/* First reset the visibility of all the types. */
static void
reset_type_linkage_1 (tree type)
{
set_linkage_according_to_type (type, TYPE_MAIN_DECL (type));
if (CLASS_TYPE_P (type))
binding_table_foreach (CLASSTYPE_NESTED_UTDS (type),
bt_reset_linkage_1, NULL);
}
static void
bt_reset_linkage_1 (binding_entry b, void */*data*/)
{
reset_type_linkage_1 (b->type);
}
/* Then reset the visibility of any static data members or member
functions that use those types. */
static void
reset_decl_linkage (tree decl)
{
if (TREE_PUBLIC (decl))
return;
if (DECL_CLONED_FUNCTION_P (decl))
return;
TREE_PUBLIC (decl) = true;
DECL_INTERFACE_KNOWN (decl) = false;
determine_visibility (decl);
tentative_decl_linkage (decl);
}
static void
reset_type_linkage_2 (tree type)
{
if (CLASS_TYPE_P (type))
{
if (tree vt = CLASSTYPE_VTABLES (type))
{
tree name = mangle_vtbl_for_type (type);
DECL_NAME (vt) = name;
SET_DECL_ASSEMBLER_NAME (vt, name);
reset_decl_linkage (vt);
}
if (tree ti = CLASSTYPE_TYPEINFO_VAR (type))
{
tree name = mangle_typeinfo_for_type (type);
DECL_NAME (ti) = name;
SET_DECL_ASSEMBLER_NAME (ti, name);
TREE_TYPE (name) = type;
reset_decl_linkage (ti);
}
for (tree m = TYPE_FIELDS (type); m; m = DECL_CHAIN (m))
{
tree mem = STRIP_TEMPLATE (m);
if (TREE_CODE (mem) == VAR_DECL || TREE_CODE (mem) == FUNCTION_DECL)
reset_decl_linkage (mem);
}
binding_table_foreach (CLASSTYPE_NESTED_UTDS (type),
bt_reset_linkage_2, NULL);
}
}
static void
bt_reset_linkage_2 (binding_entry b, void */*data*/)
{
reset_type_linkage_2 (b->type);
}
void
reset_type_linkage (tree type)
{
reset_type_linkage_1 (type);
reset_type_linkage_2 (type);
}
/* Set up our initial idea of what the linkage of DECL should be. */
void
tentative_decl_linkage (tree decl)
{
if (DECL_INTERFACE_KNOWN (decl))
/* We've already made a decision as to how this function will
be handled. */;
else if (vague_linkage_p (decl))
{
if (TREE_CODE (decl) == FUNCTION_DECL
&& decl_defined_p (decl))
{
DECL_EXTERNAL (decl) = 1;
DECL_NOT_REALLY_EXTERN (decl) = 1;
note_vague_linkage_fn (decl);
/* A non-template inline function with external linkage will
always be COMDAT. As we must eventually determine the
linkage of all functions, and as that causes writes to
the data mapped in from the PCH file, it's advantageous
to mark the functions at this point. */
if (DECL_DECLARED_INLINE_P (decl)
&& (!DECL_IMPLICIT_INSTANTIATION (decl)
|| DECL_DEFAULTED_FN (decl)))
{
/* This function must have external linkage, as
otherwise DECL_INTERFACE_KNOWN would have been
set. */
gcc_assert (TREE_PUBLIC (decl));
comdat_linkage (decl);
DECL_INTERFACE_KNOWN (decl) = 1;
}
}
else if (VAR_P (decl))
maybe_commonize_var (decl);
}
}
/* DECL is a FUNCTION_DECL or VAR_DECL. If the object file linkage
for DECL has not already been determined, do so now by setting
DECL_EXTERNAL, DECL_COMDAT and other related flags. Until this
function is called entities with vague linkage whose definitions
are available must have TREE_PUBLIC set.
If this function decides to place DECL in COMDAT, it will set
appropriate flags -- but will not clear DECL_EXTERNAL. It is up to
the caller to decide whether or not to clear DECL_EXTERNAL. Some
callers defer that decision until it is clear that DECL is actually
required. */
void
import_export_decl (tree decl)
{
int emit_p;
bool comdat_p;
bool import_p;
tree class_type = NULL_TREE;
if (DECL_INTERFACE_KNOWN (decl))
return;
/* We cannot determine what linkage to give to an entity with vague
linkage until the end of the file. For example, a virtual table
for a class will be defined if and only if the key method is
defined in this translation unit. As a further example, consider
that when compiling a translation unit that uses PCH file with
"-frepo" it would be incorrect to make decisions about what
entities to emit when building the PCH; those decisions must be
delayed until the repository information has been processed. */
gcc_assert (at_eof);
/* Object file linkage for explicit instantiations is handled in
mark_decl_instantiated. For static variables in functions with
vague linkage, maybe_commonize_var is used.
Therefore, the only declarations that should be provided to this
function are those with external linkage that are:
* implicit instantiations of function templates
* inline function
* implicit instantiations of static data members of class
templates
* virtual tables
* typeinfo objects
Furthermore, all entities that reach this point must have a
definition available in this translation unit.
The following assertions check these conditions. */
gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
/* Any code that creates entities with TREE_PUBLIC cleared should
also set DECL_INTERFACE_KNOWN. */
gcc_assert (TREE_PUBLIC (decl));
if (TREE_CODE (decl) == FUNCTION_DECL)
gcc_assert (DECL_IMPLICIT_INSTANTIATION (decl)
|| DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
|| DECL_DECLARED_INLINE_P (decl));
else
gcc_assert (DECL_IMPLICIT_INSTANTIATION (decl)
|| DECL_VTABLE_OR_VTT_P (decl)
|| DECL_TINFO_P (decl));
/* Check that a definition of DECL is available in this translation
unit. */
gcc_assert (!DECL_REALLY_EXTERN (decl));
/* Assume that DECL will not have COMDAT linkage. */
comdat_p = false;
/* Assume that DECL will not be imported into this translation
unit. */
import_p = false;
/* See if the repository tells us whether or not to emit DECL in
this translation unit. */
emit_p = repo_emit_p (decl);
if (emit_p == 0)
import_p = true;
else if (emit_p == 1)
{
/* The repository indicates that this entity should be defined
here. Make sure the back end honors that request. */
mark_needed (decl);
/* Output the definition as an ordinary strong definition. */
DECL_EXTERNAL (decl) = 0;
DECL_INTERFACE_KNOWN (decl) = 1;
return;
}
if (import_p)
/* We have already decided what to do with this DECL; there is no
need to check anything further. */
;
else if (VAR_P (decl) && DECL_VTABLE_OR_VTT_P (decl))
{
class_type = DECL_CONTEXT (decl);
import_export_class (class_type);
if (CLASSTYPE_INTERFACE_KNOWN (class_type)
&& CLASSTYPE_INTERFACE_ONLY (class_type))
import_p = true;
else if ((!flag_weak || TARGET_WEAK_NOT_IN_ARCHIVE_TOC)
&& !CLASSTYPE_USE_TEMPLATE (class_type)
&& CLASSTYPE_KEY_METHOD (class_type)
&& !DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (class_type)))
/* The ABI requires that all virtual tables be emitted with
COMDAT linkage. However, on systems where COMDAT symbols
don't show up in the table of contents for a static
archive, or on systems without weak symbols (where we
approximate COMDAT linkage by using internal linkage), the
linker will report errors about undefined symbols because
it will not see the virtual table definition. Therefore,
in the case that we know that the virtual table will be
emitted in only one translation unit, we make the virtual
table an ordinary definition with external linkage. */
DECL_EXTERNAL (decl) = 0;
else if (CLASSTYPE_INTERFACE_KNOWN (class_type))
{
/* CLASS_TYPE is being exported from this translation unit,
so DECL should be defined here. */
if (!flag_weak && CLASSTYPE_EXPLICIT_INSTANTIATION (class_type))
/* If a class is declared in a header with the "extern
template" extension, then it will not be instantiated,
even in translation units that would normally require
it. Often such classes are explicitly instantiated in
one translation unit. Therefore, the explicit
instantiation must be made visible to other translation
units. */
DECL_EXTERNAL (decl) = 0;
else
{
/* The generic C++ ABI says that class data is always
COMDAT, even if there is a key function. Some
variants (e.g., the ARM EABI) says that class data
only has COMDAT linkage if the class data might be
emitted in more than one translation unit. When the
key method can be inline and is inline, we still have
to arrange for comdat even though
class_data_always_comdat is false. */
if (!CLASSTYPE_KEY_METHOD (class_type)
|| DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (class_type))
|| targetm.cxx.class_data_always_comdat ())
{
/* The ABI requires COMDAT linkage. Normally, we
only emit COMDAT things when they are needed;
make sure that we realize that this entity is
indeed needed. */
comdat_p = true;
mark_needed (decl);
}
}
}
else if (!flag_implicit_templates
&& CLASSTYPE_IMPLICIT_INSTANTIATION (class_type))
import_p = true;
else
comdat_p = true;
}
else if (VAR_P (decl) && DECL_TINFO_P (decl))
{
tree type = TREE_TYPE (DECL_NAME (decl));
if (CLASS_TYPE_P (type))
{
class_type = type;
import_export_class (type);
if (CLASSTYPE_INTERFACE_KNOWN (type)
&& TYPE_POLYMORPHIC_P (type)
&& CLASSTYPE_INTERFACE_ONLY (type)
/* If -fno-rtti was specified, then we cannot be sure
that RTTI information will be emitted with the
virtual table of the class, so we must emit it
wherever it is used. */
&& flag_rtti)
import_p = true;
else
{
if (CLASSTYPE_INTERFACE_KNOWN (type)
&& !CLASSTYPE_INTERFACE_ONLY (type))
{
comdat_p = (targetm.cxx.class_data_always_comdat ()
|| (CLASSTYPE_KEY_METHOD (type)
&& DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (type))));
mark_needed (decl);
if (!flag_weak)
{
comdat_p = false;
DECL_EXTERNAL (decl) = 0;
}
}
else
comdat_p = true;
}
}
else
comdat_p = true;
}
else if (DECL_TEMPLOID_INSTANTIATION (decl))
{
/* DECL is an implicit instantiation of a function or static
data member. */
if ((flag_implicit_templates
&& !flag_use_repository)
|| (flag_implicit_inline_templates
&& TREE_CODE (decl) == FUNCTION_DECL
&& DECL_DECLARED_INLINE_P (decl)))
comdat_p = true;
else
/* If we are not implicitly generating templates, then mark
this entity as undefined in this translation unit. */
import_p = true;
}
else if (DECL_FUNCTION_MEMBER_P (decl))
{
if (!DECL_DECLARED_INLINE_P (decl))
{
tree ctype = DECL_CONTEXT (decl);
import_export_class (ctype);
if (CLASSTYPE_INTERFACE_KNOWN (ctype))
{
DECL_NOT_REALLY_EXTERN (decl)
= ! (CLASSTYPE_INTERFACE_ONLY (ctype)
|| (DECL_DECLARED_INLINE_P (decl)
&& ! flag_implement_inlines
&& !DECL_VINDEX (decl)));
if (!DECL_NOT_REALLY_EXTERN (decl))
DECL_EXTERNAL (decl) = 1;
/* Always make artificials weak. */
if (DECL_ARTIFICIAL (decl) && flag_weak)
comdat_p = true;
else
maybe_make_one_only (decl);
}
}
else
comdat_p = true;
}
else
comdat_p = true;
if (import_p)
{
/* If we are importing DECL into this translation unit, mark is
an undefined here. */
DECL_EXTERNAL (decl) = 1;
DECL_NOT_REALLY_EXTERN (decl) = 0;
}
else if (comdat_p)
{
/* If we decided to put DECL in COMDAT, mark it accordingly at
this point. */
comdat_linkage (decl);
}
DECL_INTERFACE_KNOWN (decl) = 1;
}
/* Return an expression that performs the destruction of DECL, which
must be a VAR_DECL whose type has a non-trivial destructor, or is
an array whose (innermost) elements have a non-trivial destructor. */
tree
build_cleanup (tree decl)
{
tree clean = cxx_maybe_build_cleanup (decl, tf_warning_or_error);
gcc_assert (clean != NULL_TREE);
return clean;
}
/* Returns the initialization guard variable for the variable DECL,
which has static storage duration. */
tree
get_guard (tree decl)
{
tree sname;
tree guard;
sname = mangle_guard_variable (decl);
guard = get_global_binding (sname);
if (! guard)
{
tree guard_type;
/* We use a type that is big enough to contain a mutex as well
as an integer counter. */
guard_type = targetm.cxx.guard_type ();
guard = build_decl (DECL_SOURCE_LOCATION (decl),
VAR_DECL, sname, guard_type);
/* The guard should have the same linkage as what it guards. */
TREE_PUBLIC (guard) = TREE_PUBLIC (decl);
TREE_STATIC (guard) = TREE_STATIC (decl);
DECL_COMMON (guard) = DECL_COMMON (decl);
DECL_COMDAT (guard) = DECL_COMDAT (decl);
CP_DECL_THREAD_LOCAL_P (guard) = CP_DECL_THREAD_LOCAL_P (decl);
set_decl_tls_model (guard, DECL_TLS_MODEL (decl));
if (DECL_ONE_ONLY (decl))
make_decl_one_only (guard, cxx_comdat_group (guard));
if (TREE_PUBLIC (decl))
DECL_WEAK (guard) = DECL_WEAK (decl);
DECL_VISIBILITY (guard) = DECL_VISIBILITY (decl);
DECL_VISIBILITY_SPECIFIED (guard) = DECL_VISIBILITY_SPECIFIED (decl);
DECL_ARTIFICIAL (guard) = 1;
DECL_IGNORED_P (guard) = 1;
TREE_USED (guard) = 1;
pushdecl_top_level_and_finish (guard, NULL_TREE);
}
return guard;
}
/* Return an atomic load of src with the appropriate memory model. */
static tree
build_atomic_load_byte (tree src, HOST_WIDE_INT model)
{
tree ptr_type = build_pointer_type (char_type_node);
tree mem_model = build_int_cst (integer_type_node, model);
tree t, addr, val;
unsigned int size;
int fncode;
size = tree_to_uhwi (TYPE_SIZE_UNIT (char_type_node));
fncode = BUILT_IN_ATOMIC_LOAD_N + exact_log2 (size) + 1;
t = builtin_decl_implicit ((enum built_in_function) fncode);
addr = build1 (ADDR_EXPR, ptr_type, src);
val = build_call_expr (t, 2, addr, mem_model);
return val;
}
/* Return those bits of the GUARD variable that should be set when the
guarded entity is actually initialized. */
static tree
get_guard_bits (tree guard)
{
if (!targetm.cxx.guard_mask_bit ())
{
/* We only set the first byte of the guard, in order to leave room
for a mutex in the high-order bits. */
guard = build1 (ADDR_EXPR,
build_pointer_type (TREE_TYPE (guard)),
guard);
guard = build1 (NOP_EXPR,
build_pointer_type (char_type_node),
guard);
guard = build1 (INDIRECT_REF, char_type_node, guard);
}
return guard;
}
/* Return an expression which determines whether or not the GUARD
variable has already been initialized. */
tree
get_guard_cond (tree guard, bool thread_safe)
{
tree guard_value;
if (!thread_safe)
guard = get_guard_bits (guard);
else
guard = build_atomic_load_byte (guard, MEMMODEL_ACQUIRE);
/* Mask off all but the low bit. */
if (targetm.cxx.guard_mask_bit ())
{
guard_value = integer_one_node;
if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard)))
guard_value = fold_convert (TREE_TYPE (guard), guard_value);
guard = cp_build_binary_op (input_location,
BIT_AND_EXPR, guard, guard_value,
tf_warning_or_error);
}
guard_value = integer_zero_node;
if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard)))
guard_value = fold_convert (TREE_TYPE (guard), guard_value);
return cp_build_binary_op (input_location,
EQ_EXPR, guard, guard_value,
tf_warning_or_error);
}
/* Return an expression which sets the GUARD variable, indicating that
the variable being guarded has been initialized. */
tree
set_guard (tree guard)
{
tree guard_init;
/* Set the GUARD to one. */
guard = get_guard_bits (guard);
guard_init = integer_one_node;
if (!same_type_p (TREE_TYPE (guard_init), TREE_TYPE (guard)))
guard_init = fold_convert (TREE_TYPE (guard), guard_init);
return cp_build_modify_expr (input_location, guard, NOP_EXPR, guard_init,
tf_warning_or_error);
}
/* Returns true iff we can tell that VAR does not have a dynamic
initializer. */
static bool
var_defined_without_dynamic_init (tree var)
{
/* If it's defined in another TU, we can't tell. */
if (DECL_EXTERNAL (var))
return false;
/* If it has a non-trivial destructor, registering the destructor
counts as dynamic initialization. */
if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (var)))
return false;
/* If it's in this TU, its initializer has been processed, unless
it's a case of self-initialization, then DECL_INITIALIZED_P is
false while the initializer is handled by finish_id_expression. */
if (!DECL_INITIALIZED_P (var))
return false;
/* If it has no initializer or a constant one, it's not dynamic. */
return (!DECL_NONTRIVIALLY_INITIALIZED_P (var)
|| DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (var));
}
/* Returns true iff VAR is a variable that needs uses to be
wrapped for possible dynamic initialization. */
static bool
var_needs_tls_wrapper (tree var)
{
return (!error_operand_p (var)
&& CP_DECL_THREAD_LOCAL_P (var)
&& !DECL_GNU_TLS_P (var)
&& !DECL_FUNCTION_SCOPE_P (var)
&& !var_defined_without_dynamic_init (var));
}
/* Get the FUNCTION_DECL for the shared TLS init function for this
translation unit. */
static tree
get_local_tls_init_fn (void)
{
tree sname = get_identifier ("__tls_init");
tree fn = get_global_binding (sname);
if (!fn)
{
fn = build_lang_decl (FUNCTION_DECL, sname,
build_function_type (void_type_node,
void_list_node));
SET_DECL_LANGUAGE (fn, lang_c);
TREE_PUBLIC (fn) = false;
DECL_ARTIFICIAL (fn) = true;
mark_used (fn);
set_global_binding (fn);
}
return fn;
}
/* Get a FUNCTION_DECL for the init function for the thread_local
variable VAR. The init function will be an alias to the function
that initializes all the non-local TLS variables in the translation
unit. The init function is only used by the wrapper function. */
static tree
get_tls_init_fn (tree var)
{
/* Only C++11 TLS vars need this init fn. */
if (!var_needs_tls_wrapper (var))
return NULL_TREE;
/* If -fno-extern-tls-init, assume that we don't need to call
a tls init function for a variable defined in another TU. */
if (!flag_extern_tls_init && DECL_EXTERNAL (var))
return NULL_TREE;
/* If the variable is internal, or if we can't generate aliases,
call the local init function directly. */
if (!TREE_PUBLIC (var) || !TARGET_SUPPORTS_ALIASES)
return get_local_tls_init_fn ();
tree sname = mangle_tls_init_fn (var);
tree fn = get_global_binding (sname);
if (!fn)
{
fn = build_lang_decl (FUNCTION_DECL, sname,
build_function_type (void_type_node,
void_list_node));
SET_DECL_LANGUAGE (fn, lang_c);
TREE_PUBLIC (fn) = TREE_PUBLIC (var);
DECL_ARTIFICIAL (fn) = true;
DECL_COMDAT (fn) = DECL_COMDAT (var);
DECL_EXTERNAL (fn) = DECL_EXTERNAL (var);
if (DECL_ONE_ONLY (var))
make_decl_one_only (fn, cxx_comdat_group (fn));
if (TREE_PUBLIC (var))
{
tree obtype = strip_array_types (non_reference (TREE_TYPE (var)));
/* If the variable is defined somewhere else and might have static
initialization, make the init function a weak reference. */
if ((!TYPE_NEEDS_CONSTRUCTING (obtype)
|| TYPE_HAS_CONSTEXPR_CTOR (obtype)
|| TYPE_HAS_TRIVIAL_DFLT (obtype))
&& TYPE_HAS_TRIVIAL_DESTRUCTOR (obtype)
&& DECL_EXTERNAL (var))
declare_weak (fn);
else
DECL_WEAK (fn) = DECL_WEAK (var);
}
DECL_VISIBILITY (fn) = DECL_VISIBILITY (var);
DECL_VISIBILITY_SPECIFIED (fn) = DECL_VISIBILITY_SPECIFIED (var);
DECL_DLLIMPORT_P (fn) = DECL_DLLIMPORT_P (var);
DECL_IGNORED_P (fn) = 1;
mark_used (fn);
DECL_BEFRIENDING_CLASSES (fn) = var;
set_global_binding (fn);
}
return fn;
}
/* Get a FUNCTION_DECL for the init wrapper function for the thread_local
variable VAR. The wrapper function calls the init function (if any) for
VAR and then returns a reference to VAR. The wrapper function is used
in place of VAR everywhere VAR is mentioned. */
tree
get_tls_wrapper_fn (tree var)
{
/* Only C++11 TLS vars need this wrapper fn. */
if (!var_needs_tls_wrapper (var))
return NULL_TREE;
tree sname = mangle_tls_wrapper_fn (var);
tree fn = get_global_binding (sname);
if (!fn)
{
/* A named rvalue reference is an lvalue, so the wrapper should
always return an lvalue reference. */
tree type = non_reference (TREE_TYPE (var));
type = build_reference_type (type);
tree fntype = build_function_type (type, void_list_node);
fn = build_lang_decl (FUNCTION_DECL, sname, fntype);
SET_DECL_LANGUAGE (fn, lang_c);
TREE_PUBLIC (fn) = TREE_PUBLIC (var);
DECL_ARTIFICIAL (fn) = true;
DECL_IGNORED_P (fn) = 1;
/* The wrapper is inline and emitted everywhere var is used. */
DECL_DECLARED_INLINE_P (fn) = true;
if (TREE_PUBLIC (var))
{
comdat_linkage (fn);
#ifdef HAVE_GAS_HIDDEN
/* Make the wrapper bind locally; there's no reason to share
the wrapper between multiple shared objects. */
DECL_VISIBILITY (fn) = VISIBILITY_INTERNAL;
DECL_VISIBILITY_SPECIFIED (fn) = true;
#endif
}
if (!TREE_PUBLIC (fn))
DECL_INTERFACE_KNOWN (fn) = true;
mark_used (fn);
note_vague_linkage_fn (fn);
#if 0
/* We want CSE to commonize calls to the wrapper, but marking it as
pure is unsafe since it has side-effects. I guess we need a new
ECF flag even weaker than ECF_PURE. FIXME! */
DECL_PURE_P (fn) = true;
#endif
DECL_BEFRIENDING_CLASSES (fn) = var;
set_global_binding (fn);
}
return fn;
}
/* At EOF, generate the definition for the TLS wrapper function FN:
T& var_wrapper() {
if (init_fn) init_fn();
return var;
} */
static void
generate_tls_wrapper (tree fn)
{
tree var = DECL_BEFRIENDING_CLASSES (fn);
start_preparsed_function (fn, NULL_TREE, SF_DEFAULT | SF_PRE_PARSED);
tree body = begin_function_body ();
/* Only call the init fn if there might be one. */
if (tree init_fn = get_tls_init_fn (var))
{
tree if_stmt = NULL_TREE;
/* If init_fn is a weakref, make sure it exists before calling. */
if (lookup_attribute ("weak", DECL_ATTRIBUTES (init_fn)))
{
if_stmt = begin_if_stmt ();
tree addr = cp_build_addr_expr (init_fn, tf_warning_or_error);
tree cond = cp_build_binary_op (DECL_SOURCE_LOCATION (var),
NE_EXPR, addr, nullptr_node,
tf_warning_or_error);
finish_if_stmt_cond (cond, if_stmt);
}
finish_expr_stmt (build_cxx_call
(init_fn, 0, NULL, tf_warning_or_error));
if (if_stmt)
{
finish_then_clause (if_stmt);
finish_if_stmt (if_stmt);
}
}
else
/* If there's no initialization, the wrapper is a constant function. */
TREE_READONLY (fn) = true;
finish_return_stmt (convert_from_reference (var));
finish_function_body (body);
expand_or_defer_fn (finish_function (/*inline_p=*/false));
}
/* Start the process of running a particular set of global constructors
or destructors. Subroutine of do_[cd]tors. Also called from
vtv_start_verification_constructor_init_function. */
static tree
start_objects (int method_type, int initp)
{
tree body;
tree fndecl;
char type[14];
/* Make ctor or dtor function. METHOD_TYPE may be 'I' or 'D'. */
if (initp != DEFAULT_INIT_PRIORITY)
{
char joiner;
#ifdef JOINER
joiner = JOINER;
#else
joiner = '_';
#endif
sprintf (type, "sub_%c%c%.5u", method_type, joiner, initp);
}
else
sprintf (type, "sub_%c", method_type);
fndecl = build_lang_decl (FUNCTION_DECL,
get_file_function_name (type),
build_function_type_list (void_type_node,
NULL_TREE));
start_preparsed_function (fndecl, /*attrs=*/NULL_TREE, SF_PRE_PARSED);
TREE_PUBLIC (current_function_decl) = 0;
/* Mark as artificial because it's not explicitly in the user's
source code. */
DECL_ARTIFICIAL (current_function_decl) = 1;
/* Mark this declaration as used to avoid spurious warnings. */
TREE_USED (current_function_decl) = 1;
/* Mark this function as a global constructor or destructor. */
if (method_type == 'I')
DECL_GLOBAL_CTOR_P (current_function_decl) = 1;
else
DECL_GLOBAL_DTOR_P (current_function_decl) = 1;
body = begin_compound_stmt (BCS_FN_BODY);
return body;
}
/* Finish the process of running a particular set of global constructors
or destructors. Subroutine of do_[cd]tors. */
static void
finish_objects (int method_type, int initp, tree body)
{
tree fn;
/* Finish up. */
finish_compound_stmt (body);
fn = finish_function (/*inline_p=*/false);
if (method_type == 'I')
{
DECL_STATIC_CONSTRUCTOR (fn) = 1;
decl_init_priority_insert (fn, initp);
}
else
{
DECL_STATIC_DESTRUCTOR (fn) = 1;
decl_fini_priority_insert (fn, initp);
}
expand_or_defer_fn (fn);
}
/* The names of the parameters to the function created to handle
initializations and destructions for objects with static storage
duration. */
#define INITIALIZE_P_IDENTIFIER "__initialize_p"
#define PRIORITY_IDENTIFIER "__priority"
/* The name of the function we create to handle initializations and
destructions for objects with static storage duration. */
#define SSDF_IDENTIFIER "__static_initialization_and_destruction"
/* The declaration for the __INITIALIZE_P argument. */
static GTY(()) tree initialize_p_decl;
/* The declaration for the __PRIORITY argument. */
static GTY(()) tree priority_decl;
/* The declaration for the static storage duration function. */
static GTY(()) tree ssdf_decl;
/* All the static storage duration functions created in this
translation unit. */
static GTY(()) vec<tree, va_gc> *ssdf_decls;
/* A map from priority levels to information about that priority
level. There may be many such levels, so efficient lookup is
important. */
static splay_tree priority_info_map;
/* Begins the generation of the function that will handle all
initialization and destruction of objects with static storage
duration. The function generated takes two parameters of type
`int': __INITIALIZE_P and __PRIORITY. If __INITIALIZE_P is
nonzero, it performs initializations. Otherwise, it performs
destructions. It only performs those initializations or
destructions with the indicated __PRIORITY. The generated function
returns no value.
It is assumed that this function will only be called once per
translation unit. */
static tree
start_static_storage_duration_function (unsigned count)
{
tree type;
tree body;
char id[sizeof (SSDF_IDENTIFIER) + 1 /* '\0' */ + 32];
/* Create the identifier for this function. It will be of the form
SSDF_IDENTIFIER_<number>. */
sprintf (id, "%s_%u", SSDF_IDENTIFIER, count);
type = build_function_type_list (void_type_node,
integer_type_node, integer_type_node,
NULL_TREE);
/* Create the FUNCTION_DECL itself. */
ssdf_decl = build_lang_decl (FUNCTION_DECL,
get_identifier (id),
type);
TREE_PUBLIC (ssdf_decl) = 0;
DECL_ARTIFICIAL (ssdf_decl) = 1;
/* Put this function in the list of functions to be called from the
static constructors and destructors. */
if (!ssdf_decls)
{
vec_alloc (ssdf_decls, 32);
/* Take this opportunity to initialize the map from priority
numbers to information about that priority level. */
priority_info_map = splay_tree_new (splay_tree_compare_ints,
/*delete_key_fn=*/0,
/*delete_value_fn=*/
(splay_tree_delete_value_fn)
(void (*) (void)) free);
/* We always need to generate functions for the
DEFAULT_INIT_PRIORITY so enter it now. That way when we walk
priorities later, we'll be sure to find the
DEFAULT_INIT_PRIORITY. */
get_priority_info (DEFAULT_INIT_PRIORITY);
}
vec_safe_push (ssdf_decls, ssdf_decl);
/* Create the argument list. */
initialize_p_decl = cp_build_parm_decl
(ssdf_decl, get_identifier (INITIALIZE_P_IDENTIFIER), integer_type_node);
TREE_USED (initialize_p_decl) = 1;
priority_decl = cp_build_parm_decl
(ssdf_decl, get_identifier (PRIORITY_IDENTIFIER), integer_type_node);
TREE_USED (priority_decl) = 1;
DECL_CHAIN (initialize_p_decl) = priority_decl;
DECL_ARGUMENTS (ssdf_decl) = initialize_p_decl;
/* Put the function in the global scope. */
pushdecl (ssdf_decl);
/* Start the function itself. This is equivalent to declaring the
function as:
static void __ssdf (int __initialize_p, init __priority_p);
It is static because we only need to call this function from the
various constructor and destructor functions for this module. */
start_preparsed_function (ssdf_decl,
/*attrs=*/NULL_TREE,
SF_PRE_PARSED);
/* Set up the scope of the outermost block in the function. */
body = begin_compound_stmt (BCS_FN_BODY);
return body;
}
/* Finish the generation of the function which performs initialization
and destruction of objects with static storage duration. After
this point, no more such objects can be created. */
static void
finish_static_storage_duration_function (tree body)
{
/* Close out the function. */
finish_compound_stmt (body);
expand_or_defer_fn (finish_function (/*inline_p=*/false));
}
/* Return the information about the indicated PRIORITY level. If no
code to handle this level has yet been generated, generate the
appropriate prologue. */
static priority_info
get_priority_info (int priority)
{
priority_info pi;
splay_tree_node n;
n = splay_tree_lookup (priority_info_map,
(splay_tree_key) priority);
if (!n)
{
/* Create a new priority information structure, and insert it
into the map. */
pi = XNEW (struct priority_info_s);
pi->initializations_p = 0;
pi->destructions_p = 0;
splay_tree_insert (priority_info_map,
(splay_tree_key) priority,
(splay_tree_value) pi);
}
else
pi = (priority_info) n->value;
return pi;
}
/* The effective initialization priority of a DECL. */
#define DECL_EFFECTIVE_INIT_PRIORITY(decl) \
((!DECL_HAS_INIT_PRIORITY_P (decl) || DECL_INIT_PRIORITY (decl) == 0) \
? DEFAULT_INIT_PRIORITY : DECL_INIT_PRIORITY (decl))
/* Whether a DECL needs a guard to protect it against multiple
initialization. */
#define NEEDS_GUARD_P(decl) (TREE_PUBLIC (decl) && (DECL_COMMON (decl) \
|| DECL_ONE_ONLY (decl) \
|| DECL_WEAK (decl)))
/* Called from one_static_initialization_or_destruction(),
via walk_tree.
Walks the initializer list of a global variable and looks for
temporary variables (DECL_NAME() == NULL and DECL_ARTIFICIAL != 0)
and that have their DECL_CONTEXT() == NULL.
For each such temporary variable, set their DECL_CONTEXT() to
the current function. This is necessary because otherwise
some optimizers (enabled by -O2 -fprofile-arcs) might crash
when trying to refer to a temporary variable that does not have
it's DECL_CONTECT() properly set. */
static tree
fix_temporary_vars_context_r (tree *node,
int * /*unused*/,
void * /*unused1*/)
{
gcc_assert (current_function_decl);
if (TREE_CODE (*node) == BIND_EXPR)
{
tree var;
for (var = BIND_EXPR_VARS (*node); var; var = DECL_CHAIN (var))
if (VAR_P (var)
&& !DECL_NAME (var)
&& DECL_ARTIFICIAL (var)
&& !DECL_CONTEXT (var))
DECL_CONTEXT (var) = current_function_decl;
}
return NULL_TREE;
}
/* Set up to handle the initialization or destruction of DECL. If
INITP is nonzero, we are initializing the variable. Otherwise, we
are destroying it. */
static void
one_static_initialization_or_destruction (tree decl, tree init, bool initp)
{
tree guard_if_stmt = NULL_TREE;
tree guard;
/* If we are supposed to destruct and there's a trivial destructor,
nothing has to be done. */
if (!initp
&& TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl)))
return;
/* Trick the compiler into thinking we are at the file and line
where DECL was declared so that error-messages make sense, and so
that the debugger will show somewhat sensible file and line
information. */
input_location = DECL_SOURCE_LOCATION (decl);
/* Make sure temporary variables in the initialiser all have
their DECL_CONTEXT() set to a value different from NULL_TREE.
This can happen when global variables initializers are built.
In that case, the DECL_CONTEXT() of the global variables _AND_ of all
the temporary variables that might have been generated in the
accompanying initializers is NULL_TREE, meaning the variables have been
declared in the global namespace.
What we want to do here is to fix that and make sure the DECL_CONTEXT()
of the temporaries are set to the current function decl. */
cp_walk_tree_without_duplicates (&init,
fix_temporary_vars_context_r,
NULL);
/* Because of:
[class.access.spec]
Access control for implicit calls to the constructors,
the conversion functions, or the destructor called to
create and destroy a static data member is performed as
if these calls appeared in the scope of the member's
class.
we pretend we are in a static member function of the class of
which the DECL is a member. */
if (member_p (decl))
{
DECL_CONTEXT (current_function_decl) = DECL_CONTEXT (decl);
DECL_STATIC_FUNCTION_P (current_function_decl) = 1;
}
/* Assume we don't need a guard. */
guard = NULL_TREE;
/* We need a guard if this is an object with external linkage that
might be initialized in more than one place. (For example, a
static data member of a template, when the data member requires
construction.) */
if (NEEDS_GUARD_P (decl))
{
tree guard_cond;
guard = get_guard (decl);
/* When using __cxa_atexit, we just check the GUARD as we would
for a local static. */
if (flag_use_cxa_atexit)
{
/* When using __cxa_atexit, we never try to destroy
anything from a static destructor. */
gcc_assert (initp);
guard_cond = get_guard_cond (guard, false);
}
/* If we don't have __cxa_atexit, then we will be running
destructors from .fini sections, or their equivalents. So,
we need to know how many times we've tried to initialize this
object. We do initializations only if the GUARD is zero,
i.e., if we are the first to initialize the variable. We do
destructions only if the GUARD is one, i.e., if we are the
last to destroy the variable. */
else if (initp)
guard_cond
= cp_build_binary_op (input_location,
EQ_EXPR,
cp_build_unary_op (PREINCREMENT_EXPR,
guard,
/*noconvert=*/true,
tf_warning_or_error),
integer_one_node,
tf_warning_or_error);
else
guard_cond
= cp_build_binary_op (input_location,
EQ_EXPR,
cp_build_unary_op (PREDECREMENT_EXPR,
guard,
/*noconvert=*/true,
tf_warning_or_error),
integer_zero_node,
tf_warning_or_error);
guard_if_stmt = begin_if_stmt ();
finish_if_stmt_cond (guard_cond, guard_if_stmt);
}
/* If we're using __cxa_atexit, we have not already set the GUARD,
so we must do so now. */
if (guard && initp && flag_use_cxa_atexit)
finish_expr_stmt (set_guard (guard));
/* Perform the initialization or destruction. */
if (initp)
{
if (init)
{
finish_expr_stmt (init);
if (sanitize_flags_p (SANITIZE_ADDRESS, decl))
{
varpool_node *vnode = varpool_node::get (decl);
if (vnode)
vnode->dynamically_initialized = 1;
}
}
/* If we're using __cxa_atexit, register a function that calls the
destructor for the object. */
if (flag_use_cxa_atexit)
finish_expr_stmt (register_dtor_fn (decl));
}
else
finish_expr_stmt (build_cleanup (decl));
/* Finish the guard if-stmt, if necessary. */
if (guard)
{
finish_then_clause (guard_if_stmt);
finish_if_stmt (guard_if_stmt);
}
/* Now that we're done with DECL we don't need to pretend to be a
member of its class any longer. */
DECL_CONTEXT (current_function_decl) = NULL_TREE;
DECL_STATIC_FUNCTION_P (current_function_decl) = 0;
}
/* Generate code to do the initialization or destruction of the decls in VARS,
a TREE_LIST of VAR_DECL with static storage duration.
Whether initialization or destruction is performed is specified by INITP. */
static void
do_static_initialization_or_destruction (tree vars, bool initp)
{
tree node, init_if_stmt, cond;
/* Build the outer if-stmt to check for initialization or destruction. */
init_if_stmt = begin_if_stmt ();
cond = initp ? integer_one_node : integer_zero_node;
cond = cp_build_binary_op (input_location,
EQ_EXPR,
initialize_p_decl,
cond,
tf_warning_or_error);
finish_if_stmt_cond (cond, init_if_stmt);
/* To make sure dynamic construction doesn't access globals from other
compilation units where they might not be yet constructed, for
-fsanitize=address insert __asan_before_dynamic_init call that
prevents access to either all global variables that need construction
in other compilation units, or at least those that haven't been
initialized yet. Variables that need dynamic construction in
the current compilation unit are kept accessible. */
if (initp && (flag_sanitize & SANITIZE_ADDRESS))
finish_expr_stmt (asan_dynamic_init_call (/*after_p=*/false));
node = vars;
do {
tree decl = TREE_VALUE (node);
tree priority_if_stmt;
int priority;
priority_info pi;
/* If we don't need a destructor, there's nothing to do. Avoid
creating a possibly empty if-stmt. */
if (!initp && TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl)))
{
node = TREE_CHAIN (node);
continue;
}
/* Remember that we had an initialization or finalization at this
priority. */
priority = DECL_EFFECTIVE_INIT_PRIORITY (decl);
pi = get_priority_info (priority);
if (initp)
pi->initializations_p = 1;
else
pi->destructions_p = 1;
/* Conditionalize this initialization on being in the right priority
and being initializing/finalizing appropriately. */
priority_if_stmt = begin_if_stmt ();
cond = cp_build_binary_op (input_location,
EQ_EXPR,
priority_decl,
build_int_cst (NULL_TREE, priority),
tf_warning_or_error);
finish_if_stmt_cond (cond, priority_if_stmt);
/* Process initializers with same priority. */
for (; node
&& DECL_EFFECTIVE_INIT_PRIORITY (TREE_VALUE (node)) == priority;
node = TREE_CHAIN (node))
/* Do one initialization or destruction. */
one_static_initialization_or_destruction (TREE_VALUE (node),
TREE_PURPOSE (node), initp);
/* Finish up the priority if-stmt body. */
finish_then_clause (priority_if_stmt);
finish_if_stmt (priority_if_stmt);
} while (node);
/* Revert what __asan_before_dynamic_init did by calling
__asan_after_dynamic_init. */
if (initp && (flag_sanitize & SANITIZE_ADDRESS))
finish_expr_stmt (asan_dynamic_init_call (/*after_p=*/true));
/* Finish up the init/destruct if-stmt body. */
finish_then_clause (init_if_stmt);
finish_if_stmt (init_if_stmt);
}
/* VARS is a list of variables with static storage duration which may
need initialization and/or finalization. Remove those variables
that don't really need to be initialized or finalized, and return
the resulting list. The order in which the variables appear in
VARS is in reverse order of the order in which they should actually
be initialized. The list we return is in the unreversed order;
i.e., the first variable should be initialized first. */
static tree
prune_vars_needing_no_initialization (tree *vars)
{
tree *var = vars;
tree result = NULL_TREE;
while (*var)
{
tree t = *var;
tree decl = TREE_VALUE (t);
tree init = TREE_PURPOSE (t);
/* Deal gracefully with error. */
if (error_operand_p (decl))
{
var = &TREE_CHAIN (t);
continue;
}
/* The only things that can be initialized are variables. */
gcc_assert (VAR_P (decl));
/* If this object is not defined, we don't need to do anything
here. */
if (DECL_EXTERNAL (decl))
{
var = &TREE_CHAIN (t);
continue;
}
/* Also, if the initializer already contains errors, we can bail
out now. */
if (init && TREE_CODE (init) == TREE_LIST
&& value_member (error_mark_node, init))
{
var = &TREE_CHAIN (t);
continue;
}
/* This variable is going to need initialization and/or
finalization, so we add it to the list. */
*var = TREE_CHAIN (t);
TREE_CHAIN (t) = result;
result = t;
}
return result;
}
/* Make sure we have told the back end about all the variables in
VARS. */
static void
write_out_vars (tree vars)
{
tree v;
for (v = vars; v; v = TREE_CHAIN (v))
{
tree var = TREE_VALUE (v);
if (!var_finalized_p (var))
{
import_export_decl (var);
rest_of_decl_compilation (var, 1, 1);
}
}
}
/* Generate a static constructor (if CONSTRUCTOR_P) or destructor
(otherwise) that will initialize all global objects with static
storage duration having the indicated PRIORITY. */
static void
generate_ctor_or_dtor_function (bool constructor_p, int priority,
location_t *locus)
{
char function_key;
tree fndecl;
tree body;
size_t i;
input_location = *locus;
/* ??? */
/* Was: locus->line++; */
/* We use `I' to indicate initialization and `D' to indicate
destruction. */
function_key = constructor_p ? 'I' : 'D';
/* We emit the function lazily, to avoid generating empty
global constructors and destructors. */
body = NULL_TREE;
/* For Objective-C++, we may need to initialize metadata found in this module.
This must be done _before_ any other static initializations. */
if (c_dialect_objc () && (priority == DEFAULT_INIT_PRIORITY)
&& constructor_p && objc_static_init_needed_p ())
{
body = start_objects (function_key, priority);
objc_generate_static_init_call (NULL_TREE);
}
/* Call the static storage duration function with appropriate
arguments. */
FOR_EACH_VEC_SAFE_ELT (ssdf_decls, i, fndecl)
{
/* Calls to pure or const functions will expand to nothing. */
if (! (flags_from_decl_or_type (fndecl) & (ECF_CONST | ECF_PURE)))
{
tree call;
if (! body)
body = start_objects (function_key, priority);
call = cp_build_function_call_nary (fndecl, tf_warning_or_error,
build_int_cst (NULL_TREE,
constructor_p),
build_int_cst (NULL_TREE,
priority),
NULL_TREE);
finish_expr_stmt (call);
}
}
/* Close out the function. */
if (body)
finish_objects (function_key, priority, body);
}
/* Generate constructor and destructor functions for the priority
indicated by N. */
static int
generate_ctor_and_dtor_functions_for_priority (splay_tree_node n, void * data)
{
location_t *locus = (location_t *) data;
int priority = (int) n->key;
priority_info pi = (priority_info) n->value;
/* Generate the functions themselves, but only if they are really
needed. */
if (pi->initializations_p)
generate_ctor_or_dtor_function (/*constructor_p=*/true, priority, locus);
if (pi->destructions_p)
generate_ctor_or_dtor_function (/*constructor_p=*/false, priority, locus);
/* Keep iterating. */
return 0;
}
/* Return C++ property of T, based on given operation OP. */
static int
cpp_check (tree t, cpp_operation op)
{
switch (op)
{
case HAS_DEPENDENT_TEMPLATE_ARGS:
{
tree ti = CLASSTYPE_TEMPLATE_INFO (t);
if (!ti)
return 0;
++processing_template_decl;
const bool dep = any_dependent_template_arguments_p (TI_ARGS (ti));
--processing_template_decl;
return dep;
}
case IS_ABSTRACT:
return DECL_PURE_VIRTUAL_P (t);
case IS_CONSTRUCTOR:
return DECL_CONSTRUCTOR_P (t);
case IS_DESTRUCTOR:
return DECL_DESTRUCTOR_P (t);
case IS_COPY_CONSTRUCTOR:
return DECL_COPY_CONSTRUCTOR_P (t);
case IS_MOVE_CONSTRUCTOR:
return DECL_MOVE_CONSTRUCTOR_P (t);
case IS_TEMPLATE:
return TREE_CODE (t) == TEMPLATE_DECL;
case IS_TRIVIAL:
return trivial_type_p (t);
default:
return 0;
}
}
/* Collect source file references recursively, starting from NAMESPC. */
static void
collect_source_refs (tree namespc)
{
/* Iterate over names in this name space. */
for (tree t = NAMESPACE_LEVEL (namespc)->names; t; t = TREE_CHAIN (t))
if (DECL_IS_BUILTIN (t))
;
else if (TREE_CODE (t) == NAMESPACE_DECL && !DECL_NAMESPACE_ALIAS (t))
collect_source_refs (t);
else
collect_source_ref (DECL_SOURCE_FILE (t));
}
/* Collect decls relevant to SOURCE_FILE from all namespaces recursively,
starting from NAMESPC. */
static void
collect_ada_namespace (tree namespc, const char *source_file)
{
tree decl = NAMESPACE_LEVEL (namespc)->names;
/* Collect decls from this namespace. This will skip
NAMESPACE_DECLs (both aliases and regular, it cannot tell). */
collect_ada_nodes (decl, source_file);
/* Now scan for namespace children, and dump them. */
for (; decl; decl = TREE_CHAIN (decl))
if (TREE_CODE (decl) == NAMESPACE_DECL && !DECL_NAMESPACE_ALIAS (decl))
collect_ada_namespace (decl, source_file);
}
/* Returns true iff there is a definition available for variable or
function DECL. */
bool
decl_defined_p (tree decl)
{
if (TREE_CODE (decl) == FUNCTION_DECL)
return (DECL_INITIAL (decl) != NULL_TREE
/* A pending instantiation of a friend temploid is defined. */
|| (DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
&& DECL_INITIAL (DECL_TEMPLATE_RESULT
(DECL_TI_TEMPLATE (decl)))));
else
{
gcc_assert (VAR_P (decl));
return !DECL_EXTERNAL (decl);
}
}
/* Nonzero for a VAR_DECL whose value can be used in a constant expression.
[expr.const]
An integral constant-expression can only involve ... const
variables of integral or enumeration types initialized with
constant expressions ...
C++0x also allows constexpr variables and temporaries initialized
with constant expressions. We handle the former here, but the latter
are just folded away in cxx_eval_constant_expression.
The standard does not require that the expression be non-volatile.
G++ implements the proposed correction in DR 457. */
bool
decl_constant_var_p (tree decl)
{
if (!decl_maybe_constant_var_p (decl))
return false;
/* We don't know if a template static data member is initialized with
a constant expression until we instantiate its initializer. Even
in the case of a constexpr variable, we can't treat it as a
constant until its initializer is complete in case it's used in
its own initializer. */
maybe_instantiate_decl (decl);
return DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl);
}
/* Returns true if DECL could be a symbolic constant variable, depending on
its initializer. */
bool
decl_maybe_constant_var_p (tree decl)
{
tree type = TREE_TYPE (decl);
if (!VAR_P (decl))
return false;
if (DECL_DECLARED_CONSTEXPR_P (decl))
return true;
if (DECL_HAS_VALUE_EXPR_P (decl))
/* A proxy isn't constant. */
return false;
if (TREE_CODE (type) == REFERENCE_TYPE)
/* References can be constant. */;
else if (CP_TYPE_CONST_NON_VOLATILE_P (type)
&& INTEGRAL_OR_ENUMERATION_TYPE_P (type))
/* And const integers. */;
else
return false;
if (DECL_INITIAL (decl)
&& !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
/* We know the initializer, and it isn't constant. */
return false;
else
return true;
}
/* Complain that DECL uses a type with no linkage. In C++98 mode this is
called from grokfndecl and grokvardecl; in all modes it is called from
cp_write_global_declarations. */
void
no_linkage_error (tree decl)
{
if (cxx_dialect >= cxx11 && decl_defined_p (decl))
/* In C++11 it's ok if the decl is defined. */
return;
tree t = no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false);
if (t == NULL_TREE)
/* The type that got us on no_linkage_decls must have gotten a name for
linkage purposes. */;
else if (CLASS_TYPE_P (t) && TYPE_BEING_DEFINED (t))
/* The type might end up having a typedef name for linkage purposes. */
vec_safe_push (no_linkage_decls, decl);
else if (TYPE_UNNAMED_P (t))
{
bool d = false;
if (cxx_dialect >= cxx11)
d = permerror (DECL_SOURCE_LOCATION (decl), "%q#D, declared using "
"unnamed type, is used but never defined", decl);
else if (DECL_EXTERN_C_P (decl))
/* Allow this; it's pretty common in C. */;
else if (VAR_P (decl))
/* DRs 132, 319 and 389 seem to indicate types with
no linkage can only be used to declare extern "C"
entities. Since it's not always an error in the
ISO C++ 90 Standard, we only issue a warning. */
d = warning_at (DECL_SOURCE_LOCATION (decl), 0, "unnamed type "
"with no linkage used to declare variable %q#D with "
"linkage", decl);
else
d = permerror (DECL_SOURCE_LOCATION (decl), "unnamed type with no "
"linkage used to declare function %q#D with linkage",
decl);
if (d && is_typedef_decl (TYPE_NAME (t)))
inform (DECL_SOURCE_LOCATION (TYPE_NAME (t)), "%q#D does not refer "
"to the unqualified type, so it is not used for linkage",
TYPE_NAME (t));
}
else if (cxx_dialect >= cxx11)
{
if (VAR_P (decl) || !DECL_PURE_VIRTUAL_P (decl))
permerror (DECL_SOURCE_LOCATION (decl),
"%q#D, declared using local type "
"%qT, is used but never defined", decl, t);
}
else if (VAR_P (decl))
warning_at (DECL_SOURCE_LOCATION (decl), 0, "type %qT with no linkage "
"used to declare variable %q#D with linkage", t, decl);
else
permerror (DECL_SOURCE_LOCATION (decl), "type %qT with no linkage used "
"to declare function %q#D with linkage", t, decl);
}
/* Collect declarations from all namespaces relevant to SOURCE_FILE. */
static void
collect_all_refs (const char *source_file)
{
collect_ada_namespace (global_namespace, source_file);
}
/* Clear DECL_EXTERNAL for NODE. */
static bool
clear_decl_external (struct cgraph_node *node, void * /*data*/)
{
DECL_EXTERNAL (node->decl) = 0;
return false;
}
/* Build up the function to run dynamic initializers for thread_local
variables in this translation unit and alias the init functions for the
individual variables to it. */
static void
handle_tls_init (void)
{
tree vars = prune_vars_needing_no_initialization (&tls_aggregates);
if (vars == NULL_TREE)
return;
location_t loc = DECL_SOURCE_LOCATION (TREE_VALUE (vars));
write_out_vars (vars);
tree guard = build_decl (loc, VAR_DECL, get_identifier ("__tls_guard"),
boolean_type_node);
TREE_PUBLIC (guard) = false;
TREE_STATIC (guard) = true;
DECL_ARTIFICIAL (guard) = true;
DECL_IGNORED_P (guard) = true;
TREE_USED (guard) = true;
CP_DECL_THREAD_LOCAL_P (guard) = true;
set_decl_tls_model (guard, decl_default_tls_model (guard));
pushdecl_top_level_and_finish (guard, NULL_TREE);
tree fn = get_local_tls_init_fn ();
start_preparsed_function (fn, NULL_TREE, SF_PRE_PARSED);
tree body = begin_function_body ();
tree if_stmt = begin_if_stmt ();
tree cond = cp_build_unary_op (TRUTH_NOT_EXPR, guard, false,
tf_warning_or_error);
finish_if_stmt_cond (cond, if_stmt);
finish_expr_stmt (cp_build_modify_expr (loc, guard, NOP_EXPR,
boolean_true_node,
tf_warning_or_error));
for (; vars; vars = TREE_CHAIN (vars))
{
tree var = TREE_VALUE (vars);
tree init = TREE_PURPOSE (vars);
one_static_initialization_or_destruction (var, init, true);
/* Output init aliases even with -fno-extern-tls-init. */
if (TARGET_SUPPORTS_ALIASES && TREE_PUBLIC (var))
{
tree single_init_fn = get_tls_init_fn (var);
if (single_init_fn == NULL_TREE)
continue;
cgraph_node *alias
= cgraph_node::get_create (fn)->create_same_body_alias
(single_init_fn, fn);
gcc_assert (alias != NULL);
}
}
finish_then_clause (if_stmt);
finish_if_stmt (if_stmt);
finish_function_body (body);
expand_or_defer_fn (finish_function (/*inline_p=*/false));
}
/* We're at the end of compilation, so generate any mangling aliases that
we've been saving up, if DECL is going to be output and ID2 isn't
already taken by another declaration. */
static void
generate_mangling_alias (tree decl, tree id2)
{
struct cgraph_node *n = NULL;
if (TREE_CODE (decl) == FUNCTION_DECL)
{
n = cgraph_node::get (decl);
if (!n)
/* Don't create an alias to an unreferenced function. */
return;
}
tree *slot
= mangled_decls->find_slot_with_hash (id2, IDENTIFIER_HASH_VALUE (id2),
INSERT);
/* If there's a declaration already using this mangled name,
don't create a compatibility alias that conflicts. */
if (*slot)
return;
tree alias = make_alias_for (decl, id2);
*slot = alias;
DECL_IGNORED_P (alias) = 1;
TREE_PUBLIC (alias) = TREE_PUBLIC (decl);
DECL_VISIBILITY (alias) = DECL_VISIBILITY (decl);
if (vague_linkage_p (decl))
DECL_WEAK (alias) = 1;
if (n)
n->create_same_body_alias (alias, decl);
else
varpool_node::create_extra_name_alias (alias, decl);
}
/* Note that we might want to emit an alias with the symbol ID2 for DECL at
the end of translation, for compatibility across bugs in the mangling
implementation. */
void
note_mangling_alias (tree decl, tree id2)
{
if (TARGET_SUPPORTS_ALIASES)
{
if (!defer_mangling_aliases)
generate_mangling_alias (decl, id2);
else
{
vec_safe_push (mangling_aliases, decl);
vec_safe_push (mangling_aliases, id2);
}
}
}
/* Emit all mangling aliases that were deferred up to this point. */
void
generate_mangling_aliases ()
{
while (!vec_safe_is_empty (mangling_aliases))
{
tree id2 = mangling_aliases->pop();
tree decl = mangling_aliases->pop();
generate_mangling_alias (decl, id2);
}
defer_mangling_aliases = false;
}
/* Record a mangling of DECL, whose DECL_ASSEMBLER_NAME has just been
set. NEED_WARNING is true if we must warn about collisions. We do
this to spot changes in mangling that may require compatibility
aliases. */
void
record_mangling (tree decl, bool need_warning)
{
if (!mangled_decls)
mangled_decls = hash_table<mangled_decl_hash>::create_ggc (499);
gcc_checking_assert (DECL_ASSEMBLER_NAME_SET_P (decl));
tree id = DECL_ASSEMBLER_NAME_RAW (decl);
tree *slot
= mangled_decls->find_slot_with_hash (id, IDENTIFIER_HASH_VALUE (id),
INSERT);
/* If this is already an alias, remove the alias, because the real
decl takes precedence. */
if (*slot && DECL_ARTIFICIAL (*slot) && DECL_IGNORED_P (*slot))
if (symtab_node *n = symtab_node::get (*slot))
if (n->cpp_implicit_alias)
{
n->remove ();
*slot = NULL_TREE;
}
if (!*slot)
*slot = decl;
else if (need_warning)
{
error_at (DECL_SOURCE_LOCATION (decl),
"mangling of %q#D as %qE conflicts with a previous mangle",
decl, id);
inform (DECL_SOURCE_LOCATION (*slot),
"previous mangling %q#D", *slot);
inform (DECL_SOURCE_LOCATION (decl),
"a later -fabi-version= (or =0)"
" avoids this error with a change in mangling");
*slot = decl;
}
}
/* The mangled name of DECL is being forcibly changed to NAME. Remove
any existing knowledge of DECL's mangled name meaning DECL. */
void
overwrite_mangling (tree decl, tree name)
{
if (tree id = DECL_ASSEMBLER_NAME_RAW (decl))
if ((TREE_CODE (decl) == VAR_DECL
|| TREE_CODE (decl) == FUNCTION_DECL)
&& mangled_decls)
if (tree *slot
= mangled_decls->find_slot_with_hash (id, IDENTIFIER_HASH_VALUE (id),
NO_INSERT))
if (*slot == decl)
{
mangled_decls->clear_slot (slot);
/* If this is an alias, remove it from the symbol table. */
if (DECL_ARTIFICIAL (decl) && DECL_IGNORED_P (decl))
if (symtab_node *n = symtab_node::get (decl))
if (n->cpp_implicit_alias)
n->remove ();
}
DECL_ASSEMBLER_NAME_RAW (decl) = name;
}
/* The entire file is now complete. If requested, dump everything
to a file. */
static void
dump_tu (void)
{
dump_flags_t flags;
if (FILE *stream = dump_begin (raw_dump_id, &flags))
{
dump_node (global_namespace, flags & ~TDF_SLIM, stream);
dump_end (raw_dump_id, stream);
}
}
static location_t locus_at_end_of_parsing;
/* Check the deallocation functions for CODE to see if we want to warn that
only one was defined. */
static void
maybe_warn_sized_delete (enum tree_code code)
{
tree sized = NULL_TREE;
tree unsized = NULL_TREE;
for (ovl_iterator iter (get_global_binding (ovl_op_identifier (false, code)));
iter; ++iter)
{
tree fn = *iter;
/* We're only interested in usual deallocation functions. */
if (!usual_deallocation_fn_p (fn))
continue;
if (FUNCTION_ARG_CHAIN (fn) == void_list_node)
unsized = fn;
else
sized = fn;
}
if (DECL_INITIAL (unsized) && !DECL_INITIAL (sized))
warning_at (DECL_SOURCE_LOCATION (unsized), OPT_Wsized_deallocation,
"the program should also define %qD", sized);
else if (!DECL_INITIAL (unsized) && DECL_INITIAL (sized))
warning_at (DECL_SOURCE_LOCATION (sized), OPT_Wsized_deallocation,
"the program should also define %qD", unsized);
}
/* Check the global deallocation functions to see if we want to warn about
defining unsized without sized (or vice versa). */
static void
maybe_warn_sized_delete ()
{
if (!flag_sized_deallocation || !warn_sized_deallocation)
return;
maybe_warn_sized_delete (DELETE_EXPR);
maybe_warn_sized_delete (VEC_DELETE_EXPR);
}
/* Earlier we left PTRMEM_CST in variable initializers alone so that we could
look them up when evaluating non-type template parameters. Now we need to
lower them to something the back end can understand. */
static void
lower_var_init ()
{
varpool_node *node;
FOR_EACH_VARIABLE (node)
{
tree d = node->decl;
if (tree init = DECL_INITIAL (d))
DECL_INITIAL (d) = cplus_expand_constant (init);
}
}
/* This routine is called at the end of compilation.
Its job is to create all the code needed to initialize and
destroy the global aggregates. We do the destruction
first, since that way we only need to reverse the decls once. */
void
c_parse_final_cleanups (void)
{
tree vars;
bool reconsider;
size_t i;
unsigned ssdf_count = 0;
int retries = 0;
tree decl;
locus_at_end_of_parsing = input_location;
at_eof = 1;
/* Bad parse errors. Just forget about it. */
if (! global_bindings_p () || current_class_type
|| !vec_safe_is_empty (decl_namespace_list))
return;
/* This is the point to write out a PCH if we're doing that.
In that case we do not want to do anything else. */
if (pch_file)
{
/* Mangle all symbols at PCH creation time. */
symtab_node *node;
FOR_EACH_SYMBOL (node)
if (! is_a <varpool_node *> (node)
|| ! DECL_HARD_REGISTER (node->decl))
DECL_ASSEMBLER_NAME (node->decl);
c_common_write_pch ();
dump_tu ();
/* Ensure even the callers don't try to finalize the CU. */
flag_syntax_only = 1;
return;
}
timevar_stop (TV_PHASE_PARSING);
timevar_start (TV_PHASE_DEFERRED);
symtab->process_same_body_aliases ();
/* Handle -fdump-ada-spec[-slim] */
if (flag_dump_ada_spec || flag_dump_ada_spec_slim)
{
if (flag_dump_ada_spec_slim)
collect_source_ref (main_input_filename);
else
collect_source_refs (global_namespace);
dump_ada_specs (collect_all_refs, cpp_check);
}
/* FIXME - huh? was input_line -= 1;*/
/* We now have to write out all the stuff we put off writing out.
These include:
o Template specializations that we have not yet instantiated,
but which are needed.
o Initialization and destruction for non-local objects with
static storage duration. (Local objects with static storage
duration are initialized when their scope is first entered,
and are cleaned up via atexit.)
o Virtual function tables.
All of these may cause others to be needed. For example,
instantiating one function may cause another to be needed, and
generating the initializer for an object may cause templates to be
instantiated, etc., etc. */
emit_support_tinfos ();
do
{
tree t;
tree decl;
reconsider = false;
/* If there are templates that we've put off instantiating, do
them now. */
instantiate_pending_templates (retries);
ggc_collect ();
/* Write out virtual tables as required. Writing out the
virtual table for a template class may cause the
instantiation of members of that class. If we write out
vtables then we remove the class from our list so we don't
have to look at it again. */
for (i = keyed_classes->length ();
keyed_classes->iterate (--i, &t);)
if (maybe_emit_vtables (t))
{
reconsider = true;
keyed_classes->unordered_remove (i);
}
/* The input_location may have been changed during marking of
vtable entries. */
input_location = locus_at_end_of_parsing;
/* Write out needed type info variables. We have to be careful
looping through unemitted decls, because emit_tinfo_decl may
cause other variables to be needed. New elements will be
appended, and we remove from the vector those that actually
get emitted. */
for (i = unemitted_tinfo_decls->length ();
unemitted_tinfo_decls->iterate (--i, &t);)
if (emit_tinfo_decl (t))
{
reconsider = true;
unemitted_tinfo_decls->unordered_remove (i);
}
/* The list of objects with static storage duration is built up
in reverse order. We clear STATIC_AGGREGATES so that any new
aggregates added during the initialization of these will be
initialized in the correct order when we next come around the
loop. */
vars = prune_vars_needing_no_initialization (&static_aggregates);
if (vars)
{
/* We need to start a new initialization function each time
through the loop. That's because we need to know which
vtables have been referenced, and TREE_SYMBOL_REFERENCED
isn't computed until a function is finished, and written
out. That's a deficiency in the back end. When this is
fixed, these initialization functions could all become
inline, with resulting performance improvements. */
tree ssdf_body;
/* Set the line and file, so that it is obviously not from
the source file. */
input_location = locus_at_end_of_parsing;
ssdf_body = start_static_storage_duration_function (ssdf_count);
/* Make sure the back end knows about all the variables. */
write_out_vars (vars);
/* First generate code to do all the initializations. */
if (vars)
do_static_initialization_or_destruction (vars, /*initp=*/true);
/* Then, generate code to do all the destructions. Do these
in reverse order so that the most recently constructed
variable is the first destroyed. If we're using
__cxa_atexit, then we don't need to do this; functions
were registered at initialization time to destroy the
local statics. */
if (!flag_use_cxa_atexit && vars)
{
vars = nreverse (vars);
do_static_initialization_or_destruction (vars, /*initp=*/false);
}
else
vars = NULL_TREE;
/* Finish up the static storage duration function for this
round. */
input_location = locus_at_end_of_parsing;
finish_static_storage_duration_function (ssdf_body);
/* All those initializations and finalizations might cause
us to need more inline functions, more template
instantiations, etc. */
reconsider = true;
ssdf_count++;
/* ??? was: locus_at_end_of_parsing.line++; */
}
/* Now do the same for thread_local variables. */
handle_tls_init ();
/* Go through the set of inline functions whose bodies have not
been emitted yet. If out-of-line copies of these functions
are required, emit them. */
FOR_EACH_VEC_SAFE_ELT (deferred_fns, i, decl)
{
/* Does it need synthesizing? */
if (DECL_DEFAULTED_FN (decl) && ! DECL_INITIAL (decl)
&& (! DECL_REALLY_EXTERN (decl) || possibly_inlined_p (decl)))
{
/* Even though we're already at the top-level, we push
there again. That way, when we pop back a few lines
hence, all of our state is restored. Otherwise,
finish_function doesn't clean things up, and we end
up with CURRENT_FUNCTION_DECL set. */
push_to_top_level ();
/* The decl's location will mark where it was first
needed. Save that so synthesize method can indicate
where it was needed from, in case of error */
input_location = DECL_SOURCE_LOCATION (decl);
synthesize_method (decl);
pop_from_top_level ();
reconsider = true;
}
if (!DECL_INITIAL (decl) && decl_tls_wrapper_p (decl))
generate_tls_wrapper (decl);
if (!DECL_SAVED_TREE (decl))
continue;
cgraph_node *node = cgraph_node::get_create (decl);
/* We lie to the back end, pretending that some functions
are not defined when they really are. This keeps these
functions from being put out unnecessarily. But, we must
stop lying when the functions are referenced, or if they
are not comdat since they need to be put out now. If
DECL_INTERFACE_KNOWN, then we have already set
DECL_EXTERNAL appropriately, so there's no need to check
again, and we do not want to clear DECL_EXTERNAL if a
previous call to import_export_decl set it.
This is done in a separate for cycle, because if some
deferred function is contained in another deferred
function later in deferred_fns varray,
rest_of_compilation would skip this function and we
really cannot expand the same function twice. */
import_export_decl (decl);
if (DECL_NOT_REALLY_EXTERN (decl)
&& DECL_INITIAL (decl)
&& decl_needed_p (decl))
{
if (node->cpp_implicit_alias)
node = node->get_alias_target ();
node->call_for_symbol_thunks_and_aliases (clear_decl_external,
NULL, true);
/* If we mark !DECL_EXTERNAL one of the symbols in some comdat
group, we need to mark all symbols in the same comdat group
that way. */
if (node->same_comdat_group)
for (cgraph_node *next
= dyn_cast<cgraph_node *> (node->same_comdat_group);
next != node;
next = dyn_cast<cgraph_node *> (next->same_comdat_group))
next->call_for_symbol_thunks_and_aliases (clear_decl_external,
NULL, true);
}
/* If we're going to need to write this function out, and
there's already a body for it, create RTL for it now.
(There might be no body if this is a method we haven't
gotten around to synthesizing yet.) */
if (!DECL_EXTERNAL (decl)
&& decl_needed_p (decl)
&& !TREE_ASM_WRITTEN (decl)
&& !node->definition)
{
/* We will output the function; no longer consider it in this
loop. */
DECL_DEFER_OUTPUT (decl) = 0;
/* Generate RTL for this function now that we know we
need it. */
expand_or_defer_fn (decl);
/* If we're compiling -fsyntax-only pretend that this
function has been written out so that we don't try to
expand it again. */
if (flag_syntax_only)
TREE_ASM_WRITTEN (decl) = 1;
reconsider = true;
}
}
if (wrapup_namespace_globals ())
reconsider = true;
/* Static data members are just like namespace-scope globals. */
FOR_EACH_VEC_SAFE_ELT (pending_statics, i, decl)
{
if (var_finalized_p (decl) || DECL_REALLY_EXTERN (decl)
/* Don't write it out if we haven't seen a definition. */
|| (DECL_IN_AGGR_P (decl) && !DECL_INLINE_VAR_P (decl)))
continue;
import_export_decl (decl);
/* If this static data member is needed, provide it to the
back end. */
if (DECL_NOT_REALLY_EXTERN (decl) && decl_needed_p (decl))
DECL_EXTERNAL (decl) = 0;
}
if (vec_safe_length (pending_statics) != 0
&& wrapup_global_declarations (pending_statics->address (),
pending_statics->length ()))
reconsider = true;
retries++;
}
while (reconsider);
lower_var_init ();
generate_mangling_aliases ();
/* All used inline functions must have a definition at this point. */
FOR_EACH_VEC_SAFE_ELT (deferred_fns, i, decl)
{
if (/* Check online inline functions that were actually used. */
DECL_ODR_USED (decl) && DECL_DECLARED_INLINE_P (decl)
/* If the definition actually was available here, then the
fact that the function was not defined merely represents
that for some reason (use of a template repository,
#pragma interface, etc.) we decided not to emit the
definition here. */
&& !DECL_INITIAL (decl)
/* Don't complain if the template was defined. */
&& !(DECL_TEMPLATE_INSTANTIATION (decl)
&& DECL_INITIAL (DECL_TEMPLATE_RESULT
(template_for_substitution (decl)))))
{
warning_at (DECL_SOURCE_LOCATION (decl), 0,
"inline function %qD used but never defined", decl);
/* Avoid a duplicate warning from check_global_declaration. */
TREE_NO_WARNING (decl) = 1;
}
}
/* So must decls that use a type with no linkage. */
FOR_EACH_VEC_SAFE_ELT (no_linkage_decls, i, decl)
no_linkage_error (decl);
maybe_warn_sized_delete ();
/* Then, do the Objective-C stuff. This is where all the
Objective-C module stuff gets generated (symtab,
class/protocol/selector lists etc). This must be done after C++
templates, destructors etc. so that selectors used in C++
templates are properly allocated. */
if (c_dialect_objc ())
objc_write_global_declarations ();
/* We give C linkage to static constructors and destructors. */
push_lang_context (lang_name_c);
/* Generate initialization and destruction functions for all
priorities for which they are required. */
if (priority_info_map)
splay_tree_foreach (priority_info_map,
generate_ctor_and_dtor_functions_for_priority,
/*data=*/&locus_at_end_of_parsing);
else if (c_dialect_objc () && objc_static_init_needed_p ())
/* If this is obj-c++ and we need a static init, call
generate_ctor_or_dtor_function. */
generate_ctor_or_dtor_function (/*constructor_p=*/true,
DEFAULT_INIT_PRIORITY,
&locus_at_end_of_parsing);
/* We're done with the splay-tree now. */
if (priority_info_map)
splay_tree_delete (priority_info_map);
/* Generate any missing aliases. */
maybe_apply_pending_pragma_weaks ();
/* We're done with static constructors, so we can go back to "C++"
linkage now. */
pop_lang_context ();
if (flag_vtable_verify)
{
vtv_recover_class_info ();
vtv_compute_class_hierarchy_transitive_closure ();
vtv_build_vtable_verify_fndecl ();
}
perform_deferred_noexcept_checks ();
finish_repo ();
fini_constexpr ();
/* The entire file is now complete. If requested, dump everything
to a file. */
dump_tu ();
if (flag_detailed_statistics)
{
dump_tree_statistics ();
dump_time_statistics ();
}
timevar_stop (TV_PHASE_DEFERRED);
timevar_start (TV_PHASE_PARSING);
/* Indicate that we're done with front end processing. */
at_eof = 2;
}
/* Perform any post compilation-proper cleanups for the C++ front-end.
This should really go away. No front-end should need to do
anything past the compilation process. */
void
cxx_post_compilation_parsing_cleanups (void)
{
timevar_start (TV_PHASE_LATE_PARSING_CLEANUPS);
if (flag_vtable_verify)
{
/* Generate the special constructor initialization function that
calls __VLTRegisterPairs, and give it a very high
initialization priority. This must be done after
finalize_compilation_unit so that we have accurate
information about which vtable will actually be emitted. */
vtv_generate_init_routine ();
}
input_location = locus_at_end_of_parsing;
if (flag_checking)
validate_conversion_obstack ();
timevar_stop (TV_PHASE_LATE_PARSING_CLEANUPS);
}
/* FN is an OFFSET_REF, DOTSTAR_EXPR or MEMBER_REF indicating the
function to call in parse-tree form; it has not yet been
semantically analyzed. ARGS are the arguments to the function.
They have already been semantically analyzed. This may change
ARGS. */
tree
build_offset_ref_call_from_tree (tree fn, vec<tree, va_gc> **args,
tsubst_flags_t complain)
{
tree orig_fn;
vec<tree, va_gc> *orig_args = NULL;
tree expr;
tree object;
orig_fn = fn;
object = TREE_OPERAND (fn, 0);
if (processing_template_decl)
{
gcc_assert (TREE_CODE (fn) == DOTSTAR_EXPR
|| TREE_CODE (fn) == MEMBER_REF);
if (type_dependent_expression_p (fn)
|| any_type_dependent_arguments_p (*args))
return build_min_nt_call_vec (fn, *args);
orig_args = make_tree_vector_copy (*args);
/* Transform the arguments and add the implicit "this"
parameter. That must be done before the FN is transformed
because we depend on the form of FN. */
make_args_non_dependent (*args);
object = build_non_dependent_expr (object);
if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE)
{
if (TREE_CODE (fn) == DOTSTAR_EXPR)
object = cp_build_addr_expr (object, complain);
vec_safe_insert (*args, 0, object);
}
/* Now that the arguments are done, transform FN. */
fn = build_non_dependent_expr (fn);
}
/* A qualified name corresponding to a bound pointer-to-member is
represented as an OFFSET_REF:
struct B { void g(); };
void (B::*p)();
void B::g() { (this->*p)(); } */
if (TREE_CODE (fn) == OFFSET_REF)
{
tree object_addr = cp_build_addr_expr (object, complain);
fn = TREE_OPERAND (fn, 1);
fn = get_member_function_from_ptrfunc (&object_addr, fn,
complain);
vec_safe_insert (*args, 0, object_addr);
}
if (CLASS_TYPE_P (TREE_TYPE (fn)))
expr = build_op_call (fn, args, complain);
else
expr = cp_build_function_call_vec (fn, args, complain);
if (processing_template_decl && expr != error_mark_node)
expr = build_min_non_dep_call_vec (expr, orig_fn, orig_args);
if (orig_args != NULL)
release_tree_vector (orig_args);
return expr;
}
void
check_default_args (tree x)
{
tree arg = TYPE_ARG_TYPES (TREE_TYPE (x));
bool saw_def = false;
int i = 0 - (TREE_CODE (TREE_TYPE (x)) == METHOD_TYPE);
for (; arg && arg != void_list_node; arg = TREE_CHAIN (arg), ++i)
{
if (TREE_PURPOSE (arg))
saw_def = true;
else if (saw_def && !PACK_EXPANSION_P (TREE_VALUE (arg)))
{
error ("default argument missing for parameter %P of %q+#D", i, x);
TREE_PURPOSE (arg) = error_mark_node;
}
}
}
/* Return true if function DECL can be inlined. This is used to force
instantiation of methods that might be interesting for inlining. */
bool
possibly_inlined_p (tree decl)
{
gcc_assert (TREE_CODE (decl) == FUNCTION_DECL);
if (DECL_UNINLINABLE (decl))
return false;
if (!optimize)
return DECL_DECLARED_INLINE_P (decl);
/* When optimizing, we might inline everything when flatten
attribute or heuristics inlining for size or autoinlining
is used. */
return true;
}
/* Normally, we can wait until instantiation-time to synthesize DECL.
However, if DECL is a static data member initialized with a constant
or a constexpr function, we need it right now because a reference to
such a data member or a call to such function is not value-dependent.
For a function that uses auto in the return type, we need to instantiate
it to find out its type. For OpenMP user defined reductions, we need
them instantiated for reduction clauses which inline them by hand
directly. */
static void
maybe_instantiate_decl (tree decl)
{
if (DECL_LANG_SPECIFIC (decl)
&& DECL_TEMPLATE_INFO (decl)
&& (decl_maybe_constant_var_p (decl)
|| (TREE_CODE (decl) == FUNCTION_DECL
&& DECL_OMP_DECLARE_REDUCTION_P (decl))
|| undeduced_auto_decl (decl))
&& !DECL_DECLARED_CONCEPT_P (decl)
&& !uses_template_parms (DECL_TI_ARGS (decl)))
{
/* Instantiating a function will result in garbage collection. We
must treat this situation as if we were within the body of a
function so as to avoid collecting live data only referenced from
the stack (such as overload resolution candidates). */
++function_depth;
instantiate_decl (decl, /*defer_ok=*/false,
/*expl_inst_class_mem_p=*/false);
--function_depth;
}
}
/* Mark DECL (either a _DECL or a BASELINK) as "used" in the program.
If DECL is a specialization or implicitly declared class member,
generate the actual definition. Return false if something goes
wrong, true otherwise. */
bool
mark_used (tree decl, tsubst_flags_t complain)
{
/* If we're just testing conversions or resolving overloads, we
don't want any permanent effects like forcing functions to be
output or instantiating templates. */
if ((complain & tf_conv))
return true;
/* If DECL is a BASELINK for a single function, then treat it just
like the DECL for the function. Otherwise, if the BASELINK is
for an overloaded function, we don't know which function was
actually used until after overload resolution. */
if (BASELINK_P (decl))
{
decl = BASELINK_FUNCTIONS (decl);
if (really_overloaded_fn (decl))
return true;
decl = OVL_FIRST (decl);
}
/* Set TREE_USED for the benefit of -Wunused. */
TREE_USED (decl) = 1;
/* And for structured bindings also the underlying decl. */
if (DECL_DECOMPOSITION_P (decl) && DECL_DECOMP_BASE (decl))
TREE_USED (DECL_DECOMP_BASE (decl)) = 1;
if (TREE_CODE (decl) == TEMPLATE_DECL)
return true;
if (DECL_CLONED_FUNCTION_P (decl))
TREE_USED (DECL_CLONED_FUNCTION (decl)) = 1;
/* Mark enumeration types as used. */
if (TREE_CODE (decl) == CONST_DECL)
used_types_insert (DECL_CONTEXT (decl));
if (TREE_CODE (decl) == FUNCTION_DECL
&& !maybe_instantiate_noexcept (decl, complain))
return false;
if (TREE_CODE (decl) == FUNCTION_DECL
&& DECL_DELETED_FN (decl))
{
if (DECL_ARTIFICIAL (decl)
&& DECL_CONV_FN_P (decl)
&& LAMBDA_TYPE_P (DECL_CONTEXT (decl)))
/* We mark a lambda conversion op as deleted if we can't
generate it properly; see maybe_add_lambda_conv_op. */
sorry ("converting lambda that uses %<...%> to function pointer");
else if (complain & tf_error)
{
error ("use of deleted function %qD", decl);
if (!maybe_explain_implicit_delete (decl))
inform (DECL_SOURCE_LOCATION (decl), "declared here");
}
return false;
}
if (TREE_DEPRECATED (decl) && (complain & tf_warning)
&& deprecated_state != DEPRECATED_SUPPRESS)
warn_deprecated_use (decl, NULL_TREE);
/* We can only check DECL_ODR_USED on variables or functions with
DECL_LANG_SPECIFIC set, and these are also the only decls that we
might need special handling for. */
if (!VAR_OR_FUNCTION_DECL_P (decl)
|| DECL_LANG_SPECIFIC (decl) == NULL
|| DECL_THUNK_P (decl))
{
if (!processing_template_decl
&& !require_deduced_type (decl, complain))
return false;
return true;
}
/* We only want to do this processing once. We don't need to keep trying
to instantiate inline templates, because unit-at-a-time will make sure
we get them compiled before functions that want to inline them. */
if (DECL_ODR_USED (decl))
return true;
/* Normally, we can wait until instantiation-time to synthesize DECL.
However, if DECL is a static data member initialized with a constant
or a constexpr function, we need it right now because a reference to
such a data member or a call to such function is not value-dependent.
For a function that uses auto in the return type, we need to instantiate
it to find out its type. For OpenMP user defined reductions, we need
them instantiated for reduction clauses which inline them by hand
directly. */
maybe_instantiate_decl (decl);
if (processing_template_decl || in_template_function ())
return true;
/* Check this too in case we're within instantiate_non_dependent_expr. */
if (DECL_TEMPLATE_INFO (decl)
&& uses_template_parms (DECL_TI_ARGS (decl)))
return true;
if (!require_deduced_type (decl, complain))
return false;
if (builtin_pack_fn_p (decl))
{
error ("use of built-in parameter pack %qD outside of a template",
DECL_NAME (decl));
return false;
}
/* If we don't need a value, then we don't need to synthesize DECL. */
if (cp_unevaluated_operand || in_discarded_stmt)
return true;
DECL_ODR_USED (decl) = 1;
if (DECL_CLONED_FUNCTION_P (decl))
DECL_ODR_USED (DECL_CLONED_FUNCTION (decl)) = 1;
/* DR 757: A type without linkage shall not be used as the type of a
variable or function with linkage, unless
o the variable or function has extern "C" linkage (7.5 [dcl.link]), or
o the variable or function is not used (3.2 [basic.def.odr]) or is
defined in the same translation unit. */
if (cxx_dialect > cxx98
&& decl_linkage (decl) != lk_none
&& !DECL_EXTERN_C_P (decl)
&& !DECL_ARTIFICIAL (decl)
&& !decl_defined_p (decl)
&& no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false))
{
if (is_local_extern (decl))
/* There's no way to define a local extern, and adding it to
the vector interferes with GC, so give an error now. */
no_linkage_error (decl);
else
vec_safe_push (no_linkage_decls, decl);
}
if (TREE_CODE (decl) == FUNCTION_DECL && DECL_DECLARED_INLINE_P (decl)
&& !DECL_INITIAL (decl) && !DECL_ARTIFICIAL (decl))
/* Remember it, so we can check it was defined. */
note_vague_linkage_fn (decl);
/* Is it a synthesized method that needs to be synthesized? */
if (TREE_CODE (decl) == FUNCTION_DECL
&& DECL_NONSTATIC_MEMBER_FUNCTION_P (decl)
&& DECL_DEFAULTED_FN (decl)
/* A function defaulted outside the class is synthesized either by
cp_finish_decl or instantiate_decl. */
&& !DECL_DEFAULTED_OUTSIDE_CLASS_P (decl)
&& ! DECL_INITIAL (decl))
{
/* Defer virtual destructors so that thunks get the right
linkage. */
if (DECL_VIRTUAL_P (decl) && !at_eof)
{
note_vague_linkage_fn (decl);
return true;
}
/* Remember the current location for a function we will end up
synthesizing. Then we can inform the user where it was
required in the case of error. */
DECL_SOURCE_LOCATION (decl) = input_location;
/* Synthesizing an implicitly defined member function will result in
garbage collection. We must treat this situation as if we were
within the body of a function so as to avoid collecting live data
on the stack (such as overload resolution candidates).
We could just let cp_write_global_declarations handle synthesizing
this function by adding it to deferred_fns, but doing
it at the use site produces better error messages. */
++function_depth;
synthesize_method (decl);
--function_depth;
/* If this is a synthesized method we don't need to
do the instantiation test below. */
}
else if (VAR_OR_FUNCTION_DECL_P (decl)
&& DECL_TEMPLATE_INFO (decl)
&& !DECL_DECLARED_CONCEPT_P (decl)
&& (!DECL_EXPLICIT_INSTANTIATION (decl)
|| always_instantiate_p (decl)))
/* If this is a function or variable that is an instance of some
template, we now know that we will need to actually do the
instantiation. We check that DECL is not an explicit
instantiation because that is not checked in instantiate_decl.
We put off instantiating functions in order to improve compile
times. Maintaining a stack of active functions is expensive,
and the inliner knows to instantiate any functions it might
need. Therefore, we always try to defer instantiation. */
{
++function_depth;
instantiate_decl (decl, /*defer_ok=*/true,
/*expl_inst_class_mem_p=*/false);
--function_depth;
}
return true;
}
bool
mark_used (tree decl)
{
return mark_used (decl, tf_warning_or_error);
}
tree
vtv_start_verification_constructor_init_function (void)
{
return start_objects ('I', MAX_RESERVED_INIT_PRIORITY - 1);
}
tree
vtv_finish_verification_constructor_init_function (tree function_body)
{
tree fn;
finish_compound_stmt (function_body);
fn = finish_function (/*inline_p=*/false);
DECL_STATIC_CONSTRUCTOR (fn) = 1;
decl_init_priority_insert (fn, MAX_RESERVED_INIT_PRIORITY - 1);
return fn;
}
#include "gt-cp-decl2.h"
|
agent_uid_map.h | // -----------------------------------------------------------------------------
//
// Copyright (C) 2021 CERN & University of Surrey for the benefit of the
// BioDynaMo collaboration. 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.
//
// See the LICENSE file distributed with this work for details.
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership.
//
// -----------------------------------------------------------------------------
#ifndef CORE_CONTAINER_AGENT_UID_MAP_H_
#define CORE_CONTAINER_AGENT_UID_MAP_H_
#include <limits>
#include <vector>
#include "core/agent/agent_uid.h"
namespace bdm {
/// AgentUidMap is an associative container that exploits the properties of
/// AgentUid to store data in contigous arrays. Inserting elements and reading
/// elements at the same time is thread-safe as long as the keys are different.
/// These operations with distinct keys are lock-free and atomic free, and thus
/// offer high-performance.
template <typename TValue>
class AgentUidMap {
struct Iterator {
AgentUidMap* map_;
uint64_t idx_;
};
public:
AgentUidMap() {}
AgentUidMap(const AgentUidMap& other)
: data_(other.data_), agent_uid_reused_(other.agent_uid_reused_) {}
explicit AgentUidMap(uint64_t initial_size) {
data_.resize(initial_size);
agent_uid_reused_.resize(initial_size, AgentUid::kReusedMax);
}
void resize(uint64_t new_size) { // NOLINT
data_.resize(new_size);
agent_uid_reused_.resize(new_size, AgentUid::kReusedMax);
}
void clear() { // NOLINT
for (auto& el : agent_uid_reused_) {
el = AgentUid::kReusedMax;
}
}
void ParallelClear() {
#pragma omp parallel for
for (uint64_t i = 0; i < data_.size(); ++i) {
agent_uid_reused_[i] = AgentUid::kReusedMax;
}
}
uint64_t size() const { // NOLINT
return data_.size();
}
void Remove(const AgentUid& key) {
if (key.GetIndex() >= data_.size()) {
return;
}
agent_uid_reused_[key.GetIndex()] = AgentUid::kReusedMax;
}
bool Contains(const AgentUid& uid) const {
auto idx = uid.GetIndex();
if (idx >= data_.size()) {
return false;
}
return uid.GetReused() == agent_uid_reused_[idx];
}
void Insert(const AgentUid& uid, const TValue& value) {
auto idx = uid.GetIndex();
data_[idx] = value;
agent_uid_reused_[idx] = uid.GetReused();
}
const TValue& operator[](const AgentUid& key) const {
return data_[key.GetIndex()];
}
typename AgentUid::Reused_t GetReused(uint64_t index) const {
return agent_uid_reused_[index];
}
private:
std::vector<TValue> data_;
std::vector<typename AgentUid::Reused_t> agent_uid_reused_;
};
} // namespace bdm
#endif // CORE_CONTAINER_AGENT_UID_MAP_H_
|
ex6.c | #include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include "timer.h"
int main(int argc, char **argv)
{
const long N = 10000;
const long M = 1000000;
double tempo, fim, inicio;
int i, j, cont, T;
T = atoi(argv[1]);
GET_TIME(inicio);
#pragma omp parallel for num_threads(T) private(i,j,cont)
for (i = 0; i < N; i++)
for(j = 0; j < M; j++)
cont = cont + 1;
GET_TIME(fim);
tempo = fim - inicio;
printf("Tempo: %.8lf\n", tempo);
return 0;
}
|
npdot.c | /* Copyright 2014-2018 The PySCF Developers. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*
* Author: Qiming Sun <osirpt.sun@gmail.com>
*/
#include <stdlib.h>
#include <string.h>
#include <complex.h>
//#include <omp.h>
#include "config.h"
#include "vhf/fblas.h"
#define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
#define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
/*
* numpy.dot may call unoptimized blas
*/
void NPdgemm(const char trans_a, const char trans_b,
const int m, const int n, const int k,
const int lda, const int ldb, const int ldc,
const int offseta, const int offsetb, const int offsetc,
double *a, double *b, double *c,
const double alpha, const double beta)
{
const size_t dimc = ldc;
int i, j;
if (m == 0 || n == 0) {
return;
} else if (k == 0) {
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
c[i*dimc+j] = 0;
} }
return;
}
a += offseta;
b += offsetb;
c += offsetc;
if ((k/m) > 3 && (k/n) > 3) { // parallelize k
if (beta == 0) {
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
c[i*dimc+j] = 0;
}
}
} else {
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
c[i*dimc+j] *= beta;
}
}
}
#pragma omp parallel default(none) shared(a, b, c) \
private(i, j)
{
int nthread = omp_get_num_threads();
int nblk = MAX((k+nthread-1) / nthread, 1);
double D0 = 0;
double *cpriv = malloc(sizeof(double) * (m*n+2));
int di;
size_t ij;
size_t astride = nblk;
size_t bstride = nblk;
if (trans_a == 'N') {
astride *= lda;
}
if (trans_b != 'N') {
bstride *= ldb;
}
#pragma omp for
for (i = 0; i < nthread; i++) {
di = MIN(nblk, k-i*nblk);
if (di > 0) {
dgemm_(&trans_a, &trans_b, &m, &n, &di,
&alpha, a+astride*i, &lda,
b+bstride*i, &ldb,
&D0, cpriv, &m);
}
}
#pragma omp critical
if (di > 0) {
for (ij = 0, i = 0; i < n; i++) {
for (j = 0; j < m; j++, ij++) {
c[i*dimc+j] += cpriv[ij];
}
}
}
free(cpriv);
}
} else if (m > n+4) { // parallelize m
#pragma omp parallel default(none) shared(a, b, c)
{
int nthread = omp_get_num_threads();
int nblk = MAX((m+nthread-1) / nthread, 1);
nthread = (m+nblk-1) / nblk;
int di;
size_t bstride = nblk;
if (trans_a != 'N') {
bstride *= lda;
}
#pragma omp for
for (i = 0; i < nthread; i++) {
di = MIN(nblk, m-i*nblk);
if (di > 0) {
dgemm_(&trans_a, &trans_b, &di, &n, &k,
&alpha, a+bstride*i, &lda, b, &ldb,
&beta, c+i*nblk, &ldc);
}
}
}
} else { // parallelize n
#pragma omp parallel default(none) shared(a, b, c)
{
int nthread = omp_get_num_threads();
int nblk = MAX((n+nthread-1) / nthread, 1);
nthread = (n+nblk-1) / nblk;
int di;
size_t bstride = nblk;
size_t cstride = dimc * nblk;
if (trans_b == 'N') {
bstride *= ldb;
}
#pragma omp for
for (i = 0; i < nthread; i++) {
di = MIN(nblk, n-i*nblk);
if (di > 0) {
dgemm_(&trans_a, &trans_b, &m, &di, &k,
&alpha, a, &lda, b+bstride*i, &ldb,
&beta, c+cstride*i, &ldc);
}
}
}
}
}
void NPzgemm(const char trans_a, const char trans_b,
const int m, const int n, const int k,
const int lda, const int ldb, const int ldc,
const int offseta, const int offsetb, const int offsetc,
double complex *a, double complex *b, double complex *c,
const double complex *alpha, const double complex *beta)
{
const size_t dimc = ldc;
int i, j;
if (m == 0 || n == 0) {
return;
} else if (k == 0) {
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
c[i*dimc+j] = 0;
} }
return;
}
a += offseta;
b += offsetb;
c += offsetc;
if ((k/m) > 3 && (k/n) > 3) { // parallelize k
if (creal(*beta) == 0 && cimag(*beta) == 0) {
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
c[i*dimc+j] = 0;
}
}
} else {
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
c[i*dimc+j] *= beta[0];
}
}
}
#pragma omp parallel default(none) shared(a, b, c, alpha) \
private(i, j)
{
int nthread = omp_get_num_threads();
int nblk = MAX((k+nthread-1) / nthread, 1);
double complex Z0 = 0;
double complex *cpriv = malloc(sizeof(double complex) * (m*n+2));
int di;
size_t ij;
size_t astride = nblk;
size_t bstride = nblk;
if (trans_a == 'N') {
astride *= lda;
}
if (trans_b != 'N') {
bstride *= ldb;
}
#pragma omp for
for (i = 0; i < nthread; i++) {
di = MIN(nblk, k-i*nblk);
if (di > 0) {
zgemm_(&trans_a, &trans_b, &m, &n, &di,
alpha, a+astride*i, &lda,
b+bstride*i, &ldb,
&Z0, cpriv, &m);
}
}
#pragma omp critical
if (di > 0) {
for (ij = 0, i = 0; i < n; i++) {
for (j = 0; j < m; j++, ij++) {
c[i*dimc+j] += cpriv[ij];
}
}
}
free(cpriv);
}
} else if (m > n+4) { // parallelize m
#pragma omp parallel default(none) shared(a, b, c, alpha, beta)
{
int nthread = omp_get_num_threads();
int nblk = MAX((m+nthread-1) / nthread, 1);
nthread = (m+nblk-1) / nblk;
int di;
size_t bstride = nblk;
if (trans_a != 'N') {
bstride *= lda;
}
#pragma omp for
for (i = 0; i < nthread; i++) {
di = MIN(nblk, m-i*nblk);
if (di > 0) {
zgemm_(&trans_a, &trans_b, &di, &n, &k,
alpha, a+bstride*i, &lda, b, &ldb,
beta, c+i*nblk, &ldc);
}
}
}
} else { // parallelize n
#pragma omp parallel default(none) shared(a, b, c, alpha, beta)
{
int nthread = omp_get_num_threads();
int nblk = MAX((n+nthread-1) / nthread, 1);
nthread = (n+nblk-1) / nblk;
int di;
size_t bstride = nblk;
size_t cstride = dimc * nblk;
if (trans_b == 'N') {
bstride *= ldb;
}
#pragma omp for
for (i = 0; i < nthread; i++) {
di = MIN(nblk, n-i*nblk);
if (di > 0) {
zgemm_(&trans_a, &trans_b, &m, &di, &k,
alpha, a, &lda, b+bstride*i, &ldb,
beta, c+cstride*i, &ldc);
}
}
}
}
}
|
divided.c | #include <math.h>
#include <omp.h>
#include <stdio.h>
#include <stdlib.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))
#define S1(i, j, k) reach[i][j] = reach[i][j] || (reach[i][k] && reach[k][j])
void printMatrix(int **, int, int);
int **allocateMatrix(int);
void computeTC0(int **matrix, int n) {
int **reach = allocateMatrix(n + 1);
int i, j, k;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
reach[i][j] = matrix[i][j];
double start = omp_get_wtime();
register int lbp = 0;
register int ubp = floord(n + 1, 2) - 1;
for (int c0 = 0; c0 < ubp; c0 += 1)
for (int c1 = 0; c1 <= min(c0 + 1, n / 2 - 1); c1 += 1)
for (int c2 = 0; c2 <= min(c0 - c1 + 1, n / 2 - 1); c2 += 1)
for (int c4 = max(2 * c0 + 1, 2 * c1 + 2 * c2); c4 <= 2 * c0 + 2;
c4 += 1)
for (int c5 = 2 * c1 + 1; c5 <= min(2 * c1 + 2, -2 * c2 + c4 + 1);
c5 += 1)
for (int c6 = 2 * c2 + 1; c6 <= min(2 * c2 + 2, c4 - c5 + 2);
c6 += 1)
reach[c5][c6] = reach[c5][c6] || (reach[c5][c4 - c5 - c6 + 2] &&
reach[c4 - c5 - c6 + 2][c6]);
for (int c0 = ubp; c0 < 2 * n - 2; c0 += 1)
for (int c1 = 0; c1 < n / 2; c1 += 1)
for (int c2 = max(0, -2 * n + c0 - c1 + (n + 1) / 2);
c2 <= min(c0 - c1 + 1, n / 2 - 1); c2 += 1) {
if (3 * n + 2 * c1 == 2 * c0 + 2 && 2 * c2 + 2 == n)
for (int c5 = -3 * n + 2 * c0 + 3; c5 <= -3 * n + 2 * c0 + 4; c5 += 1)
reach[c5][n - 1] =
reach[c5][n - 1] || (reach[c5][-3 * n + 2 * c0 - c5 + 4] &&
reach[-3 * n + 2 * c0 - c5 + 4][n - 1]);
for (int c4 = max(2 * c0 + 1, 2 * c1 + 2 * c2);
c4 <= min(2 * c0 + 2, n + 2 * c1 + 2 * c2 - 1); c4 += 1)
for (int c5 = 2 * c1 + 1;
c5 <= min(min(n - 1, 2 * c1 + 2), -2 * c2 + c4 + 1); c5 += 1)
for (int c6 = 2 * c2 + 1;
c6 <= min(min(n - 1, 2 * c2 + 2), c4 - c5 + 2); c6 += 1)
reach[c5][c6] = reach[c5][c6] || (reach[c5][c4 - c5 - c6 + 2] &&
reach[c4 - c5 - c6 + 2][c6]);
if (2 * n + c2 >= c0 + c1 + 3) {
for (int c4 = max(2 * c0 + 1, n + 2 * c1 + 2 * c2);
c4 <= min(min(min(4 * n - 5, 2 * c0 + 2), 3 * n + 2 * c1 - 2),
n + c0 + c1 + c2 + 1);
c4 += 1) {
if (n + c0 + c1 + c2 >= c4) {
for (int c5 = 2 * c1 + 1; c5 <= min(n - 1, 2 * c1 + 2); c5 += 1)
for (int c6 = 2 * c2 + 1; c6 <= min(n - 1, 2 * c2 + 2);
c6 += 1) {
if (n + c5 + c6 >= c4 + 3) {
reach[c5][c6] =
reach[c5][c6] || (reach[c5][c4 - c5 - c6 + 2] &&
reach[c4 - c5 - c6 + 2][c6]);
} else
reach[c5][c6] =
reach[c5][c6] || (reach[c5][-n + c4 - c5 - c6 + 2] &&
reach[-n + c4 - c5 - c6 + 2][c6]);
}
} else
for (int c5 = 2 * c1 + 1; c5 <= min(n - 1, 2 * c1 + 2); c5 += 1)
for (int c6 = 2 * c2 + 1; c6 <= min(n - 1, 2 * c2 + 2);
c6 += 1) {
if (n + c5 + c6 >= c0 + c1 + c2 + 4) {
reach[c5][c6] = reach[c5][c6] ||
(reach[c5][c0 + c1 + c2 - c5 - c6 + 3] &&
reach[c0 + c1 + c2 - c5 - c6 + 3][c6]);
} else
reach[c5][c6] =
reach[c5][c6] ||
(reach[c5][-n + c0 + c1 + c2 - c5 - c6 + 3] &&
reach[-n + c0 + c1 + c2 - c5 - c6 + 3][c6]);
}
}
if (c0 + 3 == 2 * n && 2 * c1 + 2 == n && 2 * c2 + 2 == n)
reach[n - 1][n - 1] =
reach[n - 1][n - 1] || (reach[n - 1][0] && reach[0][n - 1]);
} else if (2 * c1 + 2 == n && 3 * n + 2 * c2 == 2 * c0 + 2)
for (int c6 = -3 * n + 2 * c0 + 3; c6 <= -3 * n + 2 * c0 + 4; c6 += 1)
reach[n - 1][c6] =
reach[n - 1][c6] || (reach[n - 1][-3 * n + 2 * c0 - c6 + 4] &&
reach[-3 * n + 2 * c0 - c6 + 4][c6]);
for (int c4 = max(2 * c0 + 1, 2 * n + 2 * c1 + 2 * c2 + 2);
c4 <= min(2 * c0 + 2, 3 * n + 2 * c1 + 2 * c2 + 1); c4 += 1)
for (int c5 = max(2 * c1 + 1, -3 * n - 2 * c2 + c4 + 1);
c5 <= min(n - 1, 2 * c1 + 2); c5 += 1)
for (int c6 = max(2 * c2 + 1, -3 * n + c4 - c5 + 3);
c6 <= min(n - 1, 2 * c2 + 2); c6 += 1)
reach[c5][c6] =
reach[c5][c6] || (reach[c5][-2 * n + c4 - c5 - c6 + 2] &&
reach[-2 * n + c4 - c5 - c6 + 2][c6]);
}
for (int c0 = 2 * n - 2; c0 < 2 * n + floord(n, 2) - 2; c0 += 1)
for (int c1 = -2 * n + c0 + 2; c1 < n / 2; c1 += 1)
for (int c2 = max(-2 * n + c0 + 2, -2 * n + c0 - c1 + (n + 1) / 2);
c2 < n / 2; c2 += 1)
for (int c4 = 2 * c0 + 1;
c4 <= min(min(5 * n - 5, 2 * c0 + 2), 3 * n + 2 * c1 + 2 * c2 + 1);
c4 += 1)
for (int c5 = max(max(2 * c1 + 1, -3 * n - 2 * c2 + c4 + 1),
-4 * n + c4 + 4);
c5 <= min(n - 1, 2 * c1 + 2); c5 += 1)
for (int c6 = max(2 * c2 + 1, -3 * n + c4 - c5 + 3);
c6 <= min(n - 1, 2 * c2 + 2); c6 += 1)
reach[c5][c6] =
reach[c5][c6] || (reach[c5][-2 * n + c4 - c5 - c6 + 2] &&
reach[-2 * n + c4 - c5 - c6 + 2][c6]);
printf("Sequential: %lf\n", omp_get_wtime() - start);
printMatrix(reach, n, 0);
}
void computeTC1(int **matrix, int n) {
int **reach = allocateMatrix(n + 1);
int i, j, k;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
reach[i][j] = matrix[i][j];
double start = omp_get_wtime();
register int lbp = 0;
register int ubp = floord(n + 1, 2) - 1;
//#pragma omp parallel for private(c1, c2, c3, c4, c5, c6)
for (int c0 = 0; c0 < ubp; c0 += 1)
for (int c1 = 0; c1 <= min(c0 + 1, n / 2 - 1); c1 += 1)
for (int c2 = 0; c2 <= min(c0 - c1 + 1, n / 2 - 1); c2 += 1)
for (int c4 = max(2 * c0 + 1, 2 * c1 + 2 * c2); c4 <= 2 * c0 + 2;
c4 += 1)
#pragma omp parallel for private(c5, c6)
for (int c5 = 2 * c1 + 1; c5 <= min(2 * c1 + 2, -2 * c2 + c4 + 1);
c5 += 1)
for (int c6 = 2 * c2 + 1; c6 <= min(2 * c2 + 2, c4 - c5 + 2);
c6 += 1)
reach[c5][c6] = reach[c5][c6] || (reach[c5][c4 - c5 - c6 + 2] &&
reach[c4 - c5 - c6 + 2][c6]);
//#pragma omp parallel for private(c1, c2, c3, c4, c5, c6)
for (int c0 = ubp; c0 < 2 * n - 2; c0 += 1)
for (int c1 = 0; c1 < n / 2; c1 += 1)
for (int c2 = max(0, -2 * n + c0 - c1 + (n + 1) / 2);
c2 <= min(c0 - c1 + 1, n / 2 - 1); c2 += 1) {
if (3 * n + 2 * c1 == 2 * c0 + 2 && 2 * c2 + 2 == n)
for (int c5 = -3 * n + 2 * c0 + 3; c5 <= -3 * n + 2 * c0 + 4; c5 += 1)
reach[c5][n - 1] =
reach[c5][n - 1] || (reach[c5][-3 * n + 2 * c0 - c5 + 4] &&
reach[-3 * n + 2 * c0 - c5 + 4][n - 1]);
for (int c4 = max(2 * c0 + 1, 2 * c1 + 2 * c2);
c4 <= min(2 * c0 + 2, n + 2 * c1 + 2 * c2 - 1); c4 += 1)
#pragma omp parallel for private(c5, c6)
for (int c5 = 2 * c1 + 1;
c5 <= min(min(n - 1, 2 * c1 + 2), -2 * c2 + c4 + 1); c5 += 1)
for (int c6 = 2 * c2 + 1;
c6 <= min(min(n - 1, 2 * c2 + 2), c4 - c5 + 2); c6 += 1)
reach[c5][c6] = reach[c5][c6] || (reach[c5][c4 - c5 - c6 + 2] &&
reach[c4 - c5 - c6 + 2][c6]);
if (2 * n + c2 >= c0 + c1 + 3) {
for (int c4 = max(2 * c0 + 1, n + 2 * c1 + 2 * c2);
c4 <= min(min(min(4 * n - 5, 2 * c0 + 2), 3 * n + 2 * c1 - 2),
n + c0 + c1 + c2 + 1);
c4 += 1) {
if (n + c0 + c1 + c2 >= c4) {
#pragma omp parallel for private(c5, c6)
for (int c5 = 2 * c1 + 1; c5 <= min(n - 1, 2 * c1 + 2); c5 += 1)
for (int c6 = 2 * c2 + 1; c6 <= min(n - 1, 2 * c2 + 2);
c6 += 1) {
if (n + c5 + c6 >= c4 + 3) {
reach[c5][c6] =
reach[c5][c6] || (reach[c5][c4 - c5 - c6 + 2] &&
reach[c4 - c5 - c6 + 2][c6]);
} else
reach[c5][c6] =
reach[c5][c6] || (reach[c5][-n + c4 - c5 - c6 + 2] &&
reach[-n + c4 - c5 - c6 + 2][c6]);
}
} else
#pragma omp parallel for private(c5, c6)
for (int c5 = 2 * c1 + 1; c5 <= min(n - 1, 2 * c1 + 2); c5 += 1)
for (int c6 = 2 * c2 + 1; c6 <= min(n - 1, 2 * c2 + 2);
c6 += 1) {
if (n + c5 + c6 >= c0 + c1 + c2 + 4) {
reach[c5][c6] = reach[c5][c6] ||
(reach[c5][c0 + c1 + c2 - c5 - c6 + 3] &&
reach[c0 + c1 + c2 - c5 - c6 + 3][c6]);
} else
reach[c5][c6] =
reach[c5][c6] ||
(reach[c5][-n + c0 + c1 + c2 - c5 - c6 + 3] &&
reach[-n + c0 + c1 + c2 - c5 - c6 + 3][c6]);
}
}
if (c0 + 3 == 2 * n && 2 * c1 + 2 == n && 2 * c2 + 2 == n)
reach[n - 1][n - 1] =
reach[n - 1][n - 1] || (reach[n - 1][0] && reach[0][n - 1]);
} else if (2 * c1 + 2 == n && 3 * n + 2 * c2 == 2 * c0 + 2)
for (int c6 = -3 * n + 2 * c0 + 3; c6 <= -3 * n + 2 * c0 + 4; c6 += 1)
reach[n - 1][c6] =
reach[n - 1][c6] || (reach[n - 1][-3 * n + 2 * c0 - c6 + 4] &&
reach[-3 * n + 2 * c0 - c6 + 4][c6]);
for (int c4 = max(2 * c0 + 1, 2 * n + 2 * c1 + 2 * c2 + 2);
c4 <= min(2 * c0 + 2, 3 * n + 2 * c1 + 2 * c2 + 1); c4 += 1)
#pragma omp parallel for private(c5, c6)
for (int c5 = max(2 * c1 + 1, -3 * n - 2 * c2 + c4 + 1);
c5 <= min(n - 1, 2 * c1 + 2); c5 += 1)
for (int c6 = max(2 * c2 + 1, -3 * n + c4 - c5 + 3);
c6 <= min(n - 1, 2 * c2 + 2); c6 += 1)
reach[c5][c6] =
reach[c5][c6] || (reach[c5][-2 * n + c4 - c5 - c6 + 2] &&
reach[-2 * n + c4 - c5 - c6 + 2][c6]);
}
//#pragma omp parallel for private(c1, c2, c3, c4, c5, c6)
for (int c0 = 2 * n - 2; c0 < 2 * n + floord(n, 2) - 2; c0 += 1)
for (int c1 = -2 * n + c0 + 2; c1 < n / 2; c1 += 1)
for (int c2 = max(-2 * n + c0 + 2, -2 * n + c0 - c1 + (n + 1) / 2);
c2 < n / 2; c2 += 1)
for (int c4 = 2 * c0 + 1;
c4 <= min(min(5 * n - 5, 2 * c0 + 2), 3 * n + 2 * c1 + 2 * c2 + 1);
c4 += 1)
#pragma omp parallel for private(c5, c6)
for (int c5 = max(max(2 * c1 + 1, -3 * n - 2 * c2 + c4 + 1),
-4 * n + c4 + 4);
c5 <= min(n - 1, 2 * c1 + 2); c5 += 1)
for (int c6 = max(2 * c2 + 1, -3 * n + c4 - c5 + 3);
c6 <= min(n - 1, 2 * c2 + 2); c6 += 1)
reach[c5][c6] =
reach[c5][c6] || (reach[c5][-2 * n + c4 - c5 - c6 + 2] &&
reach[-2 * n + c4 - c5 - c6 + 2][c6]);
printf("Parallel: %lf\n", omp_get_wtime() - start);
printMatrix(reach, n, 1);
}
#define TILESIZE 32
void computeTC2(int **matrix, int n) {
int **reach = allocateMatrix(n + 1);
int i, j, k;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
reach[i][j] = matrix[i][j];
double start = omp_get_wtime();
register int lbp = 0;
register int ubp = floord(n + 1, 32) - 1;
if (n >= 16 && n <= 31) {
for (int c4 = 1; c4 <= 32; c4 += 1)
for (int c5 = 1; c5 <= min(n, c4); c5 += 1)
for (int c6 = 1; c6 <= min(n, c4 - c5 + 1); c6 += 1) {
if (c4 + 1 >= n + c5 + c6) {
reach[c5][c6] =
reach[c5][c6] || (reach[c5][-n + c4 - c5 - c6 + 2] &&
reach[-n + c4 - c5 - c6 + 2][c6]);
} else
reach[c5][c6] = reach[c5][c6] || (reach[c5][c4 - c5 - c6 + 2] &&
reach[c4 - c5 - c6 + 2][c6]);
}
} else {
if (n >= 32)
for (int c0 = 0; c0 < n / 16 + n / 32; c0 += 1)
for (int c1 = 0; c1 <= min(c0, (n - 1) / 32); c1 += 1) {
for (int c2 = 0; c2 <= min(c0 - c1, n / 32 - 1); c2 += 1)
for (int c4 = 32 * c0 + 1; c4 <= 32 * c0 + 32; c4 += 1)
for (int c5 = 32 * c1 + 1;
c5 <= min(min(n, 32 * c1 + 32), -32 * c2 + c4); c5 += 1)
for (int c6 = 32 * c2 + 1; c6 <= min(32 * c2 + 32, c4 - c5 + 1);
c6 += 1) {
if (n + c5 + c6 >= c4 + 2) {
reach[c5][c6] =
reach[c5][c6] || (reach[c5][c4 - c5 - c6 + 2] &&
reach[c4 - c5 - c6 + 2][c6]);
} else if (c4 + 1 >= 2 * n + c5 + c6) {
reach[c5][c6] = reach[c5][c6] ||
(reach[c5][-2 * n + c4 - c5 - c6 + 2] &&
reach[-2 * n + c4 - c5 - c6 + 2][c6]);
} else
reach[c5][c6] =
reach[c5][c6] || (reach[c5][-n + c4 - c5 - c6 + 2] &&
reach[-n + c4 - c5 - c6 + 2][c6]);
}
if (32 * c0 + 31 >= n + 32 * c1 && n % 32 >= 1) {
for (int c4 = 32 * c0 + 1;
c4 <= min(32 * c0 + 32, -((n - 1) % 32) + 2 * n + 32 * c1 - 1);
c4 += 1)
for (int c5 = 32 * c1 + 1;
c5 <= min(min(n, 32 * c1 + 32), ((n - 1) % 32) - n + c4 + 1);
c5 += 1)
for (int c6 = -((n - 1) % 32) + n; c6 <= min(n, c4 - c5 + 1);
c6 += 1)
reach[c5][c6] =
reach[c5][c6] || (reach[c5][c4 - c5 - c6 + 2] &&
reach[c4 - c5 - c6 + 2][c6]);
for (int c4 = max(32 * c0 + 1, -((n - 1) % 32) + 2 * n + 32 * c1);
c4 <= 32 * c0 + 32; c4 += 1) {
for (int c5 = 32 * c1 + 1;
c5 <= min(32 * c1 + 32, ((n - 1) % 32) - 2 * n + c4 + 1);
c5 += 1)
for (int c6 = -((n - 1) % 32) + n; c6 <= n; c6 += 1) {
if (n + c5 + c6 >= c4 + 2) {
reach[c5][c6] =
reach[c5][c6] || (reach[c5][c4 - c5 - c6 + 2] &&
reach[c4 - c5 - c6 + 2][c6]);
} else
reach[c5][c6] =
reach[c5][c6] || (reach[c5][-n + c4 - c5 - c6 + 2] &&
reach[-n + c4 - c5 - c6 + 2][c6]);
}
for (int c5 = ((n - 1) % 32) - 2 * n + c4 + 2;
c5 <= min(n, 32 * c1 + 32); c5 += 1)
for (int c6 = -((n - 1) % 32) + n; c6 <= n; c6 += 1)
reach[c5][c6] =
reach[c5][c6] || (reach[c5][c4 - c5 - c6 + 2] &&
reach[c4 - c5 - c6 + 2][c6]);
}
}
}
if (n % 32 == 0)
for (int c0 = 3 * n / 32; c0 < 5 * n / 32; c0 += 1)
for (int c1 = max(0, (-n / 8) + c0); c1 < n / 32; c1 += 1)
for (int c2 = max(0, (-3 * n / 32) + c0 - c1 - 1); c2 < n / 32;
c2 += 1) {
for (int c4 = 32 * c0 + 1;
c4 <= min(32 * c0 + 32, 2 * n + 32 * c1 + 32 * c2 + 62);
c4 += 1) {
for (int c5 = 32 * c1 + 1; c5 < -2 * n - 32 * c2 + c4 - 30;
c5 += 1)
for (int c6 = max(32 * c2 + 1, -3 * n + c4 - c5 + 2);
c6 <= 32 * c2 + 32; c6 += 1)
reach[c5][c6] =
reach[c5][c6] || (reach[c5][-2 * n + c4 - c5 - c6 + 2] &&
reach[-2 * n + c4 - c5 - c6 + 2][c6]);
for (int c5 = max(32 * c1 + 1, -2 * n - 32 * c2 + c4 - 30);
c5 <= 32 * c1 + 32; c5 += 1) {
for (int c6 = 32 * c2 + 1; c6 <= -2 * n + c4 - c5 + 1; c6 += 1)
reach[c5][c6] =
reach[c5][c6] || (reach[c5][-2 * n + c4 - c5 - c6 + 2] &&
reach[-2 * n + c4 - c5 - c6 + 2][c6]);
for (int c6 = max(32 * c2 + 1, -2 * n + c4 - c5 + 2);
c6 <= 32 * c2 + 32; c6 += 1)
reach[c5][c6] =
reach[c5][c6] || (reach[c5][-n + c4 - c5 - c6 + 2] &&
reach[-n + c4 - c5 - c6 + 2][c6]);
}
}
for (int c4 = max(32 * c0 + 1, 2 * n + 32 * c1 + 32 * c2 + 63);
c4 <= min(32 * c0 + 32, 3 * n + 32 * c1 + 32 * c2 + 62);
c4 += 1)
for (int c5 = max(32 * c1 + 1, -3 * n - 32 * c2 + c4 - 30);
c5 <= 32 * c1 + 32; c5 += 1)
for (int c6 = max(32 * c2 + 1, -3 * n + c4 - c5 + 2);
c6 <= 32 * c2 + 32; c6 += 1)
reach[c5][c6] =
reach[c5][c6] || (reach[c5][-2 * n + c4 - c5 - c6 + 2] &&
reach[-2 * n + c4 - c5 - c6 + 2][c6]);
}
}
if (n >= 2 && n % 32 >= 1)
for (int c0 = n / 16 + n / 32; c0 <= (5 * n - 3) / 32; c0 += 1) {
if (n >= 8 * c0 + 1 && 32 * c0 + 33 >= 5 * n) {
for (int c4 = 32 * c0 + 1; c4 < 5 * n - 1; c4 += 1)
for (int c5 = max(1, -4 * n + c4 + 2); c5 <= min(n, c4); c5 += 1)
for (int c6 = max(1, -3 * n + c4 - c5 + 2);
c6 <= min(n, c4 - c5 + 1); c6 += 1) {
if (n + c5 + c6 >= c4 + 2) {
reach[c5][c6] = reach[c5][c6] || (reach[c5][c4 - c5 - c6 + 2] &&
reach[c4 - c5 - c6 + 2][c6]);
} else if (c4 + 1 >= 2 * n + c5 + c6) {
reach[c5][c6] =
reach[c5][c6] || (reach[c5][-2 * n + c4 - c5 - c6 + 2] &&
reach[-2 * n + c4 - c5 - c6 + 2][c6]);
} else
reach[c5][c6] =
reach[c5][c6] || (reach[c5][-n + c4 - c5 - c6 + 2] &&
reach[-n + c4 - c5 - c6 + 2][c6]);
}
} else if (8 * c0 >= n) {
for (int c1 = c0 - (n + 7) / 8; c1 <= (n - 1) / 32; c1 += 1) {
for (int c2 = max(c0 - (n + 7) / 8, c0 - c1 - (3 * n + 29) / 32 - 1);
c2 < n / 32; c2 += 1)
for (int c4 = 32 * c0 + 1;
c4 <= min(min(32 * c0 + 32, 4 * n + 32 * c2 + 30),
3 * n + 32 * c1 + 32 * c2 + 62);
c4 += 1)
for (int c5 = max(32 * c1 + 1, -3 * n - 32 * c2 + c4 - 30);
c5 <= min(n, 32 * c1 + 32); c5 += 1)
for (int c6 = max(32 * c2 + 1, -3 * n + c4 - c5 + 2);
c6 <= 32 * c2 + 32; c6 += 1)
reach[c5][c6] =
reach[c5][c6] || (reach[c5][-2 * n + c4 - c5 - c6 + 2] &&
reach[-2 * n + c4 - c5 - c6 + 2][c6]);
for (int c4 = 32 * c0 + 1;
c4 <= min(min(5 * n - 2, 32 * c0 + 32), 4 * n + 32 * c1 + 30);
c4 += 1)
for (int c5 = max(32 * c1 + 1, -4 * n + c4 + 2);
c5 <= min(n, 32 * c1 + 32); c5 += 1)
for (int c6 = max(-3 * n + c4 - c5 + 2, -((n - 1) % 32) + n);
c6 <= n; c6 += 1)
reach[c5][c6] =
reach[c5][c6] || (reach[c5][-2 * n + c4 - c5 - c6 + 2] &&
reach[-2 * n + c4 - c5 - c6 + 2][c6]);
}
} else
for (int c1 = 0; c1 <= floord(n - 1, 32); c1 += 1) {
for (int c2 = max(0, c0 - c1 - (3 * n + 29) / 32 - 1); c2 < n / 32;
c2 += 1)
for (int c4 = 32 * c0 + 1;
c4 <= min(32 * c0 + 32, 3 * n + 32 * c1 + 32 * c2 + 62);
c4 += 1)
for (int c5 = max(32 * c1 + 1, -3 * n - 32 * c2 + c4 - 30);
c5 <= min(n, 32 * c1 + 32); c5 += 1) {
for (int c6 = max(32 * c2 + 1, -3 * n + c4 - c5 + 2);
c6 <= min(32 * c2 + 32, -n + c4 - c5 + 1); c6 += 1) {
if (2 * n + c5 + c6 >= c4 + 2) {
reach[c5][c6] =
reach[c5][c6] || (reach[c5][-n + c4 - c5 - c6 + 2] &&
reach[-n + c4 - c5 - c6 + 2][c6]);
} else if (c0 % 2 == 0) {
reach[c5][c6] = reach[c5][c6] ||
(reach[c5][-2 * n + c4 - c5 - c6 + 2] &&
reach[-2 * n + c4 - c5 - c6 + 2][c6]);
} else if (c6 >= 33) {
reach[c5][c6] = reach[c5][c6] ||
(reach[c5][-2 * n + c4 - c5 - c6 + 2] &&
reach[-2 * n + c4 - c5 - c6 + 2][c6]);
} else if (n >= 64 && c4 >= 2 * n + 16 * c0 + 17) {
reach[c5][c6] = reach[c5][c6] ||
(reach[c5][-2 * n + c4 - c5 - c6 + 2] &&
reach[-2 * n + c4 - c5 - c6 + 2][c6]);
} else if (n <= 63 && c4 >= 2 * n + 16 * c0 + 17) {
reach[c5][c6] = reach[c5][c6] ||
(reach[c5][-2 * n + c4 - c5 - c6 + 2] &&
reach[-2 * n + c4 - c5 - c6 + 2][c6]);
} else
reach[c5][c6] = reach[c5][c6] ||
(reach[c5][-2 * n + c4 - c5 - c6 + 2] &&
reach[-2 * n + c4 - c5 - c6 + 2][c6]);
}
for (int c6 = -n + c4 - c5 + 2; c6 <= 32 * c2 + 32; c6 += 1)
reach[c5][c6] =
reach[c5][c6] || (reach[c5][c4 - c5 - c6 + 2] &&
reach[c4 - c5 - c6 + 2][c6]);
}
if (3 * c1 == c0)
for (int c4 = 32 * c0 + 1; c4 <= (64 * c0 / 3) + n; c4 += 1)
for (int c5 = (32 * c0 / 3) + 1;
c5 <= min(n, (-32 * c0 / 3) + c4); c5 += 1)
for (int c6 = (32 * c0 / 3) + 1; c6 <= min(n, c4 - c5 + 1);
c6 += 1)
reach[c5][c6] =
reach[c5][c6] || (reach[c5][c4 - c5 - c6 + 2] &&
reach[c4 - c5 - c6 + 2][c6]);
for (int c4 = max(32 * c0 + 1, -((n - 1) % 32) + 2 * n + 32 * c1);
c4 <= min(min(4 * n - 2, 32 * c0 + 32), 3 * n + 32 * c1 + 30);
c4 += 1) {
for (int c5 = 32 * c1 + 1; c5 <= -3 * n + c4 + 1; c5 += 1) {
if (n >= 32) {
for (int c6 = -((n - 1) % 32) + n; c6 <= n; c6 += 1)
reach[c5][c6] =
reach[c5][c6] || (reach[c5][-2 * n + c4 - c5 - c6 + 2] &&
reach[-2 * n + c4 - c5 - c6 + 2][c6]);
} else if (n >= 16 && 2 * n + 32 >= c4) {
for (int c6 = -3 * n + c4 - c5 + 2; c6 <= n; c6 += 1)
reach[c5][c6] =
reach[c5][c6] || (reach[c5][-2 * n + c4 - c5 - c6 + 2] &&
reach[-2 * n + c4 - c5 - c6 + 2][c6]);
} else if (c4 >= 3 * n + 1 &&
16 * ((-2 * n + c4 - 1) / 32) + 15 >= n) {
for (int c6 = -3 * n + c4 - c5 + 2; c6 <= n; c6 += 1)
reach[c5][c6] =
reach[c5][c6] || (reach[c5][-2 * n + c4 - c5 - c6 + 2] &&
reach[-2 * n + c4 - c5 - c6 + 2][c6]);
} else
for (int c6 = 1; c6 <= n; c6 += 1)
reach[1][c6] = reach[1][c6] || (reach[1][n - c6 + 1] &&
reach[n - c6 + 1][c6]);
}
for (int c5 = max(32 * c1 + 1, -3 * n + c4 + 2);
c5 <=
min(min(n, 32 * c1 + 32), ((n - 1) % 32) - 2 * n + c4 + 1);
c5 += 1)
for (int c6 = -((n - 1) % 32) + n; c6 <= n; c6 += 1) {
if (n + c5 + c6 >= c4 + 2) {
reach[c5][c6] =
reach[c5][c6] || (reach[c5][c4 - c5 - c6 + 2] &&
reach[c4 - c5 - c6 + 2][c6]);
} else if (c4 + 1 >= 2 * n + c5 + c6) {
reach[c5][c6] =
reach[c5][c6] || (reach[c5][-2 * n + c4 - c5 - c6 + 2] &&
reach[-2 * n + c4 - c5 - c6 + 2][c6]);
} else
reach[c5][c6] =
reach[c5][c6] || (reach[c5][-n + c4 - c5 - c6 + 2] &&
reach[-n + c4 - c5 - c6 + 2][c6]);
}
for (int c5 = ((n - 1) % 32) - 2 * n + c4 + 2;
c5 <= min(n, 32 * c1 + 32); c5 += 1) {
if (c4 + 32 >= ((2 * n + c4 - 1) % 32) + 3 * n) {
for (int c6 = -((n - 1) % 32) + n; c6 <= min(n, c4 - c5 + 1);
c6 += 1)
reach[c5][c6] =
reach[c5][c6] || (reach[c5][c4 - c5 - c6 + 2] &&
reach[c4 - c5 - c6 + 2][c6]);
} else if (n >= 32) {
for (int c6 = -((n - 1) % 32) + n; c6 <= n; c6 += 1)
reach[c5][c6] =
reach[c5][c6] || (reach[c5][c4 - c5 - c6 + 2] &&
reach[c4 - c5 - c6 + 2][c6]);
} else if (2 * n >= c4 + 2) {
for (int c6 = 1; c6 <= c4 - c5 + 1; c6 += 1)
reach[c5][c6] =
reach[c5][c6] || (reach[c5][c4 - c5 - c6 + 2] &&
reach[c4 - c5 - c6 + 2][c6]);
} else
for (int c6 = 1; c6 <= n; c6 += 1)
reach[n][c6] = reach[n][c6] || (reach[n][n - c6 + 1] &&
reach[n - c6 + 1][c6]);
}
}
for (int c4 = max(32 * c0 + 1, 3 * n + 32 * c1 + 31);
c4 <= min(4 * n - 2, 32 * c0 + 32); c4 += 1)
for (int c5 = 32 * c1 + 1; c5 <= 32 * c1 + 32; c5 += 1)
for (int c6 = max(-3 * n + c4 - c5 + 2, -((n - 1) % 32) + n);
c6 <= n; c6 += 1)
reach[c5][c6] =
reach[c5][c6] || (reach[c5][-2 * n + c4 - c5 - c6 + 2] &&
reach[-2 * n + c4 - c5 - c6 + 2][c6]);
for (int c4 = 4 * n - 1; c4 <= 32 * c0 + 32; c4 += 1)
for (int c5 = max(32 * c1 + 1, -4 * n + c4 + 2);
c5 <= min(n, 32 * c1 + 32); c5 += 1)
for (int c6 = max(-3 * n + c4 - c5 + 2, -((n - 1) % 32) + n);
c6 <= n; c6 += 1)
reach[c5][c6] =
reach[c5][c6] || (reach[c5][-2 * n + c4 - c5 - c6 + 2] &&
reach[-2 * n + c4 - c5 - c6 + 2][c6]);
}
}
printf("Parallel2: %lf\n", omp_get_wtime() - start);
printMatrix(reach, n, 2);
}
void computeTC3(int **matrix, int n) {
int **reach = allocateMatrix(n + 1);
int i, j, k;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
reach[i][j] = matrix[i][j];
double start = omp_get_wtime();
for (k = 0; k < n; k++) {
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
reach[i][j] = reach[i][j] || (reach[i][k] && reach[k][j]);
}
}
}
printf("Seq Normal: %lf\n", omp_get_wtime() - start);
printMatrix(reach, n, 2);
}
void printMatrix(int **matrix, int N, int fileno) {
/*
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
printf ("%d ", matrix[i][j]);
printf("\n");
}
*/
char filename[10];
sprintf(filename, "result%d", fileno);
FILE *f = fopen(filename, "wt");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
fprintf(f, "%d ", matrix[i][j]);
fprintf(f, "\n");
}
fclose(f);
}
int **allocateMatrix(int N) {
int **t = (int **)malloc(sizeof(int *) * N);
for (int i = 0; i < N; i++) {
t[i] = (int *)malloc(sizeof(int) * N);
}
return t;
}
int main(void) {
const int N = 400;
int **graph = allocateMatrix(N);
int g[4][4] = {{1, 1, 0, 1}, {0, 1, 1, 0}, {0, 0, 1, 1}, {0, 0, 0, 1}};
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
graph[i][j] = g[i][j];
for (int i = 0; i < N; i++)
graph[i][i] = 1;
printMatrix(graph, 6, 9);
computeTC0(graph, N);
computeTC1(graph, N);
computeTC2(graph, N);
computeTC3(graph, N);
return 0;
}
|
openmp_wrapper.h | /*!
* Copyright (c) 2017 Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*/
#ifndef LIGHTGBM_OPENMP_WRAPPER_H_
#define LIGHTGBM_OPENMP_WRAPPER_H_
#ifdef _OPENMP
#include <LightGBM/utils/log.h>
#include <omp.h>
#include <exception>
#include <memory>
#include <mutex>
#include <stdexcept>
#include <vector>
inline int OMP_NUM_THREADS() {
int ret = 1;
#pragma omp parallel
#pragma omp master
{ ret = omp_get_num_threads(); }
return ret;
}
class ThreadExceptionHelper {
public:
ThreadExceptionHelper() {
ex_ptr_ = nullptr;
}
~ThreadExceptionHelper() {
ReThrow();
}
void ReThrow() {
if (ex_ptr_ != nullptr) {
std::rethrow_exception(ex_ptr_);
}
}
void CaptureException() {
// only catch first exception.
if (ex_ptr_ != nullptr) { return; }
std::unique_lock<std::mutex> guard(lock_);
if (ex_ptr_ != nullptr) { return; }
ex_ptr_ = std::current_exception();
}
private:
std::exception_ptr ex_ptr_;
std::mutex lock_;
};
#define OMP_INIT_EX() ThreadExceptionHelper omp_except_helper
#define OMP_LOOP_EX_BEGIN() try {
#define OMP_LOOP_EX_END() \
} \
catch (std::exception & ex) { \
Log::Warning(ex.what()); \
omp_except_helper.CaptureException(); \
} \
catch (...) { \
omp_except_helper.CaptureException(); \
}
#define OMP_THROW_EX() omp_except_helper.ReThrow()
#else
#ifdef _MSC_VER
#pragma warning(disable : 4068) // disable unknown pragma warning
#endif
#ifdef __cplusplus
extern "C" {
#endif
/** Fall here if no OPENMP support, so just
simulate a single thread running.
All #pragma omp should be ignored by the compiler **/
inline void omp_set_num_threads(int) {}
inline int omp_get_num_threads() {return 1;}
inline int omp_get_thread_num() {return 0;}
inline int OMP_NUM_THREADS() { return 1; }
#ifdef __cplusplus
}; // extern "C"
#endif
#define OMP_INIT_EX()
#define OMP_LOOP_EX_BEGIN()
#define OMP_LOOP_EX_END()
#define OMP_THROW_EX()
#endif
#endif /* LIGHTGBM_OPENMP_WRAPPER_H_ */
|
omp_target_offload.c | // RUN: %libomp-compile-and-run
#include <string.h>
#include <stdlib.h>
enum kmp_target_offload_kind {
tgt_disabled = 0,
tgt_default = 1,
tgt_mandatory = 2
};
extern int __kmpc_get_target_offload();
const char *disabled_examples[] = {
// Allowed inputs
"disabled", "DISABLED", "Disabled", "dIsAbLeD", "DiSaBlEd"};
const char *default_examples[] = {
// Allowed inputs
"default", "DEFAULT", "Default", "deFAulT", "DEfaULt",
// These should be changed to default (failed match)
"mandatry", "defaults", "disable", "enabled", "mandatorynot"};
const char *mandatory_examples[] = {
// Allowed inputs
"mandatory", "MANDATORY", "Mandatory", "manDatoRy", "MANdATOry"};
// Return target-offload-var ICV
int get_target_offload_icv() {
#pragma omp parallel
{}
return __kmpc_get_target_offload();
}
int main() {
int i;
const char *omp_target_offload = "OMP_TARGET_OFFLOAD=";
char buf[80];
for (i = 0; i < sizeof(disabled_examples) / sizeof(char *); ++i) {
strcpy(buf, omp_target_offload);
strcat(buf, disabled_examples[i]);
kmp_set_defaults(buf);
if (tgt_disabled != get_target_offload_icv())
return EXIT_FAILURE;
}
for (i = 0; i < sizeof(default_examples) / sizeof(char *); ++i) {
strcpy(buf, omp_target_offload);
strcat(buf, default_examples[i]);
kmp_set_defaults(buf);
if (tgt_default != get_target_offload_icv())
return EXIT_FAILURE;
}
for (i = 0; i < sizeof(mandatory_examples) / sizeof(char *); ++i) {
strcpy(buf, omp_target_offload);
strcat(buf, mandatory_examples[i]);
kmp_set_defaults(buf);
if (tgt_mandatory != get_target_offload_icv())
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
merge_sort.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)
******************************************************************************/
#include "_hypre_utilities.h"
#include "../seq_mv/HYPRE_seq_mv.h"
//#define DBG_MERGE_SORT
#ifdef DBG_MERGE_SORT
#include <algorithm>
#include <unordered_map>
#endif
#define SWAP(T, a, b) do { T tmp = a; a = b; b = tmp; } while (0)
/*--------------------------------------------------------------------------
* hypre_MergeOrderedArrays: merge two ordered arrays
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_MergeOrderedArrays( HYPRE_Int size1, HYPRE_Int *array1,
HYPRE_Int size2, HYPRE_Int *array2,
HYPRE_Int *size3_ptr, HYPRE_Int **array3_ptr )
{
HYPRE_Int *array3;
HYPRE_Int i, j, k;
array3 = hypre_CTAlloc(HYPRE_Int, (size1 + size2), HYPRE_MEMORY_HOST);
i = j = k = 0;
while (i < size1 && j < size2)
{
if (array1[i] > array2[j])
{
array3[k++] = array2[j++];
}
else if (array1[i] < array2[j])
{
array3[k++] = array1[i++];
}
else
{
array3[k++] = array1[i++];
j++;
}
}
while (i < size1)
{
array3[k++] = array1[i++];
}
while (j < size2)
{
array3[k++] = array2[j++];
}
/* Set pointers */
*size3_ptr = k;
*array3_ptr = hypre_TReAlloc(array3, HYPRE_Int, k, HYPRE_MEMORY_HOST);
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_union2
*
* Union of two sorted (in ascending order) array arr1 and arr2 into arr3
*
* Assumptions:
* 1) no duplicate entries in arr1 and arr2. But an entry is
* allowed to appear in both arr1 and arr2
* 2) arr3 should have enough space on entry
* 3) map1 and map2 map arr1 and arr2 to arr3
*--------------------------------------------------------------------------*/
void hypre_union2( HYPRE_Int n1, HYPRE_BigInt *arr1,
HYPRE_Int n2, HYPRE_BigInt *arr2,
HYPRE_Int *n3, HYPRE_BigInt *arr3,
HYPRE_Int *map1, HYPRE_Int *map2 )
{
HYPRE_Int i = 0, j = 0, k = 0;
while (i < n1 && j < n2)
{
if (arr1[i] < arr2[j])
{
if (map1) { map1[i] = k; }
arr3[k++] = arr1[i++];
}
else if (arr1[i] > arr2[j])
{
if (map2) { map2[j] = k; }
arr3[k++] = arr2[j++];
}
else /* == */
{
if (map1) { map1[i] = k; }
if (map2) { map2[j] = k; }
arr3[k++] = arr1[i++];
j++;
}
}
while (i < n1)
{
if (map1) { map1[i] = k; }
arr3[k++] = arr1[i++];
}
while (j < n2)
{
if (map2) { map2[j] = k; }
arr3[k++] = arr2[j++];
}
*n3 = k;
}
/*--------------------------------------------------------------------------
* hypre_merge
*--------------------------------------------------------------------------*/
static void hypre_merge( HYPRE_Int *first1, HYPRE_Int *last1,
HYPRE_Int *first2, HYPRE_Int *last2,
HYPRE_Int *out )
{
for ( ; first1 != last1; ++out)
{
if (first2 == last2)
{
for ( ; first1 != last1; ++first1, ++out)
{
*out = *first1;
}
return;
}
if (*first2 < *first1)
{
*out = *first2;
++first2;
}
else
{
*out = *first1;
++first1;
}
}
for ( ; first2 != last2; ++first2, ++out)
{
*out = *first2;
}
}
/*--------------------------------------------------------------------------
* hypre_big_merge
*--------------------------------------------------------------------------*/
static void hypre_big_merge( HYPRE_BigInt *first1, HYPRE_BigInt *last1,
HYPRE_BigInt *first2, HYPRE_BigInt *last2,
HYPRE_BigInt *out )
{
for ( ; first1 != last1; ++out)
{
if (first2 == last2)
{
for ( ; first1 != last1; ++first1, ++out)
{
*out = *first1;
}
return;
}
if (*first2 < *first1)
{
*out = *first2;
++first2;
}
else
{
*out = *first1;
++first1;
}
}
for ( ; first2 != last2; ++first2, ++out)
{
*out = *first2;
}
}
/*--------------------------------------------------------------------------
* kth_element_
*--------------------------------------------------------------------------*/
static void kth_element_( HYPRE_Int *out1, HYPRE_Int *out2,
HYPRE_Int *a1, HYPRE_Int *a2,
HYPRE_Int left, HYPRE_Int right,
HYPRE_Int n1, HYPRE_Int n2, HYPRE_Int k)
{
while (1)
{
HYPRE_Int i = (left + right)/2; // right < k -> i < k
HYPRE_Int j = k - i - 1;
#ifdef DBG_MERGE_SORT
hypre_assert(left <= right && right <= k);
hypre_assert(i < k); // i == k implies left == right == k that can never happen
hypre_assert(j >= 0 && j < n2);
#endif
if ((j == -1 || a1[i] >= a2[j]) && (j == n2 - 1 || a1[i] <= a2[j + 1]))
{
*out1 = i; *out2 = j + 1;
return;
}
else if (j >= 0 && a2[j] >= a1[i] && (i == n1 - 1 || a2[j] <= a1[i + 1]))
{
*out1 = i + 1; *out2 = j;
return;
}
else if (a1[i] > a2[j] && j != n2 - 1 && a1[i] > a2[j+1])
{
// search in left half of a1
right = i - 1;
}
else
{
// search in right half of a1
left = i + 1;
}
}
}
/**
* Partition the input so that
* a1[0:*out1) and a2[0:*out2) contain the smallest k elements
*/
/*--------------------------------------------------------------------------
* kth_element
*
* Partition the input so that
* a1[0:*out1) and a2[0:*out2) contain the smallest k elements
*--------------------------------------------------------------------------*/
static void kth_element( HYPRE_Int *out1, HYPRE_Int *out2,
HYPRE_Int *a1, HYPRE_Int *a2,
HYPRE_Int n1, HYPRE_Int n2, HYPRE_Int k)
{
// either of the inputs is empty
if (n1 == 0)
{
*out1 = 0; *out2 = k;
return;
}
if (n2 == 0)
{
*out1 = k; *out2 = 0;
return;
}
if (k >= n1 + n2)
{
*out1 = n1; *out2 = n2;
return;
}
// one is greater than the other
if (k < n1 && a1[k] <= a2[0])
{
*out1 = k; *out2 = 0;
return;
}
if (k - n1 >= 0 && a2[k - n1] >= a1[n1 - 1])
{
*out1 = n1; *out2 = k - n1;
return;
}
if (k < n2 && a2[k] <= a1[0])
{
*out1 = 0; *out2 = k;
return;
}
if (k - n2 >= 0 && a1[k - n2] >= a2[n2 - 1])
{
*out1 = k - n2; *out2 = n2;
return;
}
// now k > 0
// faster to do binary search on the shorter sequence
if (n1 > n2)
{
SWAP(HYPRE_Int, n1, n2);
SWAP(HYPRE_Int *, a1, a2);
SWAP(HYPRE_Int *, out1, out2);
}
if (k < (n1 + n2)/2)
{
kth_element_(out1, out2, a1, a2, 0, hypre_min(n1 - 1, k), n1, n2, k);
}
else
{
// when k is big, faster to find (n1 + n2 - k)th biggest element
HYPRE_Int offset1 = hypre_max(k - n2, 0), offset2 = hypre_max(k - n1, 0);
HYPRE_Int new_k = k - offset1 - offset2;
HYPRE_Int new_n1 = hypre_min(n1 - offset1, new_k + 1);
HYPRE_Int new_n2 = hypre_min(n2 - offset2, new_k + 1);
kth_element_(out1, out2, a1 + offset1, a2 + offset2, 0, new_n1 - 1, new_n1, new_n2, new_k);
*out1 += offset1;
*out2 += offset2;
}
#ifdef DBG_MERGE_SORT
hypre_assert(*out1 + *out2 == k);
#endif
}
/*--------------------------------------------------------------------------
* big_kth_element_
*--------------------------------------------------------------------------*/
static void big_kth_element_( HYPRE_Int *out1, HYPRE_Int *out2,
HYPRE_BigInt *a1, HYPRE_BigInt *a2,
HYPRE_Int left, HYPRE_Int right,
HYPRE_Int n1, HYPRE_Int n2, HYPRE_Int k)
{
while (1)
{
HYPRE_Int i = (left + right)/2; // right < k -> i < k
HYPRE_Int j = k - i - 1;
#ifdef DBG_MERGE_SORT
hypre_assert(left <= right && right <= k);
hypre_assert(i < k); // i == k implies left == right == k that can never happen
hypre_assert(j >= 0 && j < n2);
#endif
if ((j == -1 || a1[i] >= a2[j]) && (j == n2 - 1 || a1[i] <= a2[j + 1]))
{
*out1 = i; *out2 = j + 1;
return;
}
else if (j >= 0 && a2[j] >= a1[i] && (i == n1 - 1 || a2[j] <= a1[i + 1]))
{
*out1 = i + 1; *out2 = j;
return;
}
else if (a1[i] > a2[j] && j != n2 - 1 && a1[i] > a2[j+1])
{
// search in left half of a1
right = i - 1;
}
else
{
// search in right half of a1
left = i + 1;
}
}
}
/*--------------------------------------------------------------------------
* big_kth_element
*
* Partition the input so that
* a1[0:*out1) and a2[0:*out2) contain the smallest k elements
*--------------------------------------------------------------------------*/
static void big_kth_element( HYPRE_Int *out1, HYPRE_Int *out2,
HYPRE_BigInt *a1, HYPRE_BigInt *a2,
HYPRE_Int n1, HYPRE_Int n2, HYPRE_Int k)
{
// either of the inputs is empty
if (n1 == 0)
{
*out1 = 0; *out2 = k;
return;
}
if (n2 == 0)
{
*out1 = k; *out2 = 0;
return;
}
if (k >= n1 + n2)
{
*out1 = n1; *out2 = n2;
return;
}
// one is greater than the other
if (k < n1 && a1[k] <= a2[0])
{
*out1 = k; *out2 = 0;
return;
}
if (k - n1 >= 0 && a2[k - n1] >= a1[n1 - 1])
{
*out1 = n1; *out2 = k - n1;
return;
}
if (k < n2 && a2[k] <= a1[0])
{
*out1 = 0; *out2 = k;
return;
}
if (k - n2 >= 0 && a1[k - n2] >= a2[n2 - 1])
{
*out1 = k - n2; *out2 = n2;
return;
}
// now k > 0
// faster to do binary search on the shorter sequence
if (n1 > n2)
{
SWAP(HYPRE_Int, n1, n2);
SWAP(HYPRE_BigInt *, a1, a2);
SWAP(HYPRE_Int *, out1, out2);
}
if (k < (n1 + n2)/2)
{
big_kth_element_(out1, out2, a1, a2, 0, hypre_min(n1 - 1, k), n1, n2, k);
}
else
{
// when k is big, faster to find (n1 + n2 - k)th biggest element
HYPRE_Int offset1 = hypre_max(k - n2, 0), offset2 = hypre_max(k - n1, 0);
HYPRE_Int new_k = k - offset1 - offset2;
HYPRE_Int new_n1 = hypre_min(n1 - offset1, new_k + 1);
HYPRE_Int new_n2 = hypre_min(n2 - offset2, new_k + 1);
big_kth_element_(out1, out2, a1 + (HYPRE_BigInt)offset1, a2 + (HYPRE_BigInt)offset2, 0, new_n1 - 1, new_n1, new_n2, new_k);
*out1 += offset1;
*out2 += offset2;
}
#ifdef DBG_MERGE_SORT
hypre_assert(*out1 + *out2 == k);
#endif
}
/*--------------------------------------------------------------------------
* hypre_parallel_merge
*
* @param num_threads number of threads that participate in this merge
* @param my_thread_num thread id (zer0-based) among the threads that
* participate in this merge
*--------------------------------------------------------------------------*/
static void hypre_parallel_merge( HYPRE_Int *first1, HYPRE_Int *last1,
HYPRE_Int *first2, HYPRE_Int *last2,
HYPRE_Int *out, HYPRE_Int num_threads,
HYPRE_Int my_thread_num )
{
HYPRE_Int n1 = last1 - first1;
HYPRE_Int n2 = last2 - first2;
HYPRE_Int n = n1 + n2;
HYPRE_Int n_per_thread = (n + num_threads - 1)/num_threads;
HYPRE_Int begin_rank = hypre_min(n_per_thread*my_thread_num, n);
HYPRE_Int end_rank = hypre_min(begin_rank + n_per_thread, n);
#ifdef DBG_MERGE_SORT
hypre_assert(std::is_sorted(first1, last1));
hypre_assert(std::is_sorted(first2, last2));
#endif
HYPRE_Int begin1, begin2, end1, end2;
kth_element(&begin1, &begin2, first1, first2, n1, n2, begin_rank);
kth_element(&end1, &end2, first1, first2, n1, n2, end_rank);
while (begin1 > end1 && begin1 > 0 && begin2 < n2 && first1[begin1 - 1] == first2[begin2])
{
#ifdef DBG_MERGE_SORT
printf("%s:%d\n", __FILE__, __LINE__);
#endif
begin1--; begin2++;
}
while (begin2 > end2 && end1 > 0 && end2 < n2 && first1[end1 - 1] == first2[end2])
{
#ifdef DBG_MERGE_SORT
printf("%s:%d\n", __FILE__, __LINE__);
#endif
end1--; end2++;
}
#ifdef DBG_MERGE_SORT
hypre_assert(begin1 <= end1);
hypre_assert(begin2 <= end2);
#endif
hypre_merge(
first1 + begin1, first1 + end1,
first2 + begin2, first2 + end2,
out + begin1 + begin2);
#ifdef DBG_MERGE_SORT
hypre_assert(std::is_sorted(out + begin1 + begin2, out + end1 + end2));
#endif
}
/*--------------------------------------------------------------------------
* hypre_big_parallel_merge
*
* @param num_threads number of threads that participate in this merge
* @param my_thread_num thread id (zero-based) among the threads that
* participate in this merge
*--------------------------------------------------------------------------*/
static void hypre_big_parallel_merge(
HYPRE_BigInt *first1, HYPRE_BigInt *last1, HYPRE_BigInt *first2, HYPRE_BigInt *last2,
HYPRE_BigInt *out,
HYPRE_Int num_threads, HYPRE_Int my_thread_num)
{
HYPRE_Int n1 = (HYPRE_Int)(last1 - first1);
HYPRE_Int n2 = (HYPRE_Int)(last2 - first2);
HYPRE_Int n = n1 + n2;
HYPRE_Int n_per_thread = (n + num_threads - 1)/num_threads;
HYPRE_Int begin_rank = hypre_min(n_per_thread*my_thread_num, n);
HYPRE_Int end_rank = hypre_min(begin_rank + n_per_thread, n);
#ifdef DBG_MERGE_SORT
hypre_assert(std::is_sorted(first1, last1));
hypre_assert(std::is_sorted(first2, last2));
#endif
HYPRE_Int begin1, begin2, end1, end2;
big_kth_element(&begin1, &begin2, first1, first2, n1, n2, begin_rank);
big_kth_element(&end1, &end2, first1, first2, n1, n2, end_rank);
while (begin1 > end1 && begin1 > 0 && begin2 < n2 && first1[begin1 - 1] == first2[begin2])
{
#ifdef DBG_MERGE_SORT
printf("%s:%d\n", __FILE__, __LINE__);
#endif
begin1--; begin2++;
}
while (begin2 > end2 && end1 > 0 && end2 < n2 && first1[end1 - 1] == first2[end2])
{
#ifdef DBG_MERGE_SORT
printf("%s:%d\n", __FILE__, __LINE__);
#endif
end1--; end2++;
}
#ifdef DBG_MERGE_SORT
hypre_assert(begin1 <= end1);
hypre_assert(begin2 <= end2);
#endif
hypre_big_merge(
first1 + (HYPRE_BigInt)begin1, first1 + (HYPRE_BigInt)end1,
first2 + (HYPRE_BigInt)begin2, first2 + (HYPRE_BigInt)end2,
out + (HYPRE_BigInt)(begin1 + begin2));
#ifdef DBG_MERGE_SORT
hypre_assert(std::is_sorted(out + begin1 + begin2, out + end1 + end2));
#endif
}
/*--------------------------------------------------------------------------
* hypre_merge_sort
*--------------------------------------------------------------------------*/
void hypre_merge_sort( HYPRE_Int *in, HYPRE_Int *temp, HYPRE_Int len, HYPRE_Int **out )
{
if (0 == len) return;
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_MERGE] -= hypre_MPI_Wtime();
#endif
#ifdef DBG_MERGE_SORT
HYPRE_Int *dbg_buf = new HYPRE_Int[len];
std::copy(in, in + len, dbg_buf);
std::sort(dbg_buf, dbg_buf + len);
#endif
// HYPRE_Int thread_private_len[hypre_NumThreads()];
// HYPRE_Int out_len = 0;
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel
#endif
{
HYPRE_Int num_threads = hypre_NumActiveThreads();
HYPRE_Int my_thread_num = hypre_GetThreadNum();
// thread-private sort
HYPRE_Int i_per_thread = (len + num_threads - 1)/num_threads;
HYPRE_Int i_begin = hypre_min(i_per_thread*my_thread_num, len);
HYPRE_Int i_end = hypre_min(i_begin + i_per_thread, len);
hypre_qsort0(in, i_begin, i_end - 1);
// merge sorted sequences
HYPRE_Int in_group_size;
HYPRE_Int *in_buf = in;
HYPRE_Int *out_buf = temp;
for (in_group_size = 1; in_group_size < num_threads; in_group_size *= 2)
{
#ifdef HYPRE_USING_OPENMP
#pragma omp barrier
#endif
// merge 2 in-groups into 1 out-group
HYPRE_Int out_group_size = in_group_size*2;
HYPRE_Int group_leader = my_thread_num/out_group_size*out_group_size;
// HYPRE_Int group_sub_leader = hypre_min(group_leader + in_group_size, num_threads - 1);
HYPRE_Int id_in_group = my_thread_num%out_group_size;
HYPRE_Int num_threads_in_group =
hypre_min(group_leader + out_group_size, num_threads) - group_leader;
HYPRE_Int in_group1_begin = hypre_min(i_per_thread*group_leader, len);
HYPRE_Int in_group1_end = hypre_min(in_group1_begin + i_per_thread*in_group_size, len);
HYPRE_Int in_group2_begin = hypre_min(in_group1_begin + i_per_thread*in_group_size, len);
HYPRE_Int in_group2_end = hypre_min(in_group2_begin + i_per_thread*in_group_size, len);
hypre_parallel_merge(
in_buf + in_group1_begin, in_buf + in_group1_end,
in_buf + in_group2_begin, in_buf + in_group2_end,
out_buf + in_group1_begin,
num_threads_in_group,
id_in_group);
HYPRE_Int *temp = in_buf;
in_buf = out_buf;
out_buf = temp;
}
*out = in_buf;
} /* omp parallel */
#ifdef DBG_MERGE_SORT
hypre_assert(std::equal(*out, *out + len, dbg_buf));
delete[] dbg_buf;
#endif
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_MERGE] += hypre_MPI_Wtime();
#endif
}
/*--------------------------------------------------------------------------
* hypre_sort_and_create_inverse_map
*
* Sort array "in" with length len and put result in array "out"
* "in" will be deallocated unless in == *out
* inverse_map is an inverse hash table s.t.
* inverse_map[i] = j iff (*out)[j] = i
*--------------------------------------------------------------------------*/
void hypre_sort_and_create_inverse_map(HYPRE_Int *in, HYPRE_Int len, HYPRE_Int **out,
hypre_UnorderedIntMap *inverse_map)
{
if (len == 0)
{
return;
}
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_MERGE] -= hypre_MPI_Wtime();
#endif
HYPRE_Int *temp = hypre_TAlloc(HYPRE_Int, len, HYPRE_MEMORY_HOST);
hypre_merge_sort(in, temp, len, out);
hypre_UnorderedIntMapCreate(inverse_map, 2*len, 16*hypre_NumThreads());
HYPRE_Int i;
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
#pragma omp parallel for HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < len; i++)
{
HYPRE_Int old = hypre_UnorderedIntMapPutIfAbsent(inverse_map, (*out)[i], i);
hypre_assert(old == HYPRE_HOPSCOTCH_HASH_EMPTY);
#ifdef DBG_MERGE_SORT
if (hypre_UnorderedIntMapGet(inverse_map, (*out)[i]) != i)
{
fprintf(stderr, "%d %d\n", i, (*out)[i]);
hypre_assert(false);
}
#endif
}
#ifdef DBG_MERGE_SORT
std::unordered_map<HYPRE_Int, HYPRE_Int> inverse_map2(len);
for (HYPRE_Int i = 0; i < len; ++i) {
inverse_map2[(*out)[i]] = i;
if (hypre_UnorderedIntMapGet(inverse_map, (*out)[i]) != i)
{
fprintf(stderr, "%d %d\n", i, (*out)[i]);
hypre_assert(false);
}
}
hypre_assert(hypre_UnorderedIntMapSize(inverse_map) == len);
#endif
if (*out == in)
{
hypre_TFree(temp, HYPRE_MEMORY_HOST);
}
else
{
hypre_TFree(in, HYPRE_MEMORY_HOST);
}
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_MERGE] += hypre_MPI_Wtime();
#endif
}
/*--------------------------------------------------------------------------
* hypre_big_merge_sort
*--------------------------------------------------------------------------*/
void hypre_big_merge_sort(HYPRE_BigInt *in, HYPRE_BigInt *temp, HYPRE_Int len,
HYPRE_BigInt **out)
{
if (0 == len) return;
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_MERGE] -= hypre_MPI_Wtime();
#endif
#ifdef DBG_MERGE_SORT
HYPRE_Int *dbg_buf = new HYPRE_Int[len];
std::copy(in, in + len, dbg_buf);
std::sort(dbg_buf, dbg_buf + len);
#endif
// HYPRE_Int thread_private_len[hypre_NumThreads()];
// HYPRE_Int out_len = 0;
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel
#endif
{
HYPRE_Int num_threads = hypre_NumActiveThreads();
HYPRE_Int my_thread_num = hypre_GetThreadNum();
// thread-private sort
HYPRE_Int i_per_thread = (len + num_threads - 1)/num_threads;
HYPRE_Int i_begin = hypre_min(i_per_thread*my_thread_num, len);
HYPRE_Int i_end = hypre_min(i_begin + i_per_thread, len);
hypre_BigQsort0(in, i_begin, i_end - 1);
// merge sorted sequences
HYPRE_Int in_group_size;
HYPRE_BigInt *in_buf = in;
HYPRE_BigInt *out_buf = temp;
for (in_group_size = 1; in_group_size < num_threads; in_group_size *= 2)
{
#ifdef HYPRE_USING_OPENMP
#pragma omp barrier
#endif
// merge 2 in-groups into 1 out-group
HYPRE_Int out_group_size = in_group_size*2;
HYPRE_Int group_leader = my_thread_num/out_group_size*out_group_size;
// HYPRE_Int group_sub_leader = hypre_min(group_leader + in_group_size, num_threads - 1);
HYPRE_Int id_in_group = my_thread_num%out_group_size;
HYPRE_Int num_threads_in_group =
hypre_min(group_leader + out_group_size, num_threads) - group_leader;
HYPRE_Int in_group1_begin = hypre_min(i_per_thread*group_leader, len);
HYPRE_Int in_group1_end = hypre_min(in_group1_begin + i_per_thread*in_group_size, len);
HYPRE_Int in_group2_begin = hypre_min(in_group1_begin + i_per_thread*in_group_size, len);
HYPRE_Int in_group2_end = hypre_min(in_group2_begin + i_per_thread*in_group_size, len);
hypre_big_parallel_merge(
in_buf + (HYPRE_BigInt)in_group1_begin, in_buf + (HYPRE_BigInt)in_group1_end,
in_buf + (HYPRE_BigInt)in_group2_begin, in_buf + (HYPRE_BigInt)in_group2_end,
out_buf + (HYPRE_BigInt)in_group1_begin,
num_threads_in_group,
id_in_group);
HYPRE_BigInt *temp = in_buf;
in_buf = out_buf;
out_buf = temp;
}
*out = in_buf;
} /* omp parallel */
#ifdef DBG_MERGE_SORT
hypre_assert(std::equal(*out, *out + len, dbg_buf));
delete[] dbg_buf;
#endif
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_MERGE] += hypre_MPI_Wtime();
#endif
}
/*--------------------------------------------------------------------------
* hypre_big_sort_and_create_inverse_map
*--------------------------------------------------------------------------*/
void hypre_big_sort_and_create_inverse_map(HYPRE_BigInt *in, HYPRE_Int len, HYPRE_BigInt **out,
hypre_UnorderedBigIntMap *inverse_map)
{
if (len == 0)
{
return;
}
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_MERGE] -= hypre_MPI_Wtime();
#endif
HYPRE_BigInt *temp = hypre_TAlloc(HYPRE_BigInt, len, HYPRE_MEMORY_HOST);
hypre_big_merge_sort(in, temp, len, out);
hypre_UnorderedBigIntMapCreate(inverse_map, 2*len, 16*hypre_NumThreads());
HYPRE_Int i;
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
#pragma omp parallel for HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < len; i++)
{
HYPRE_Int old = hypre_UnorderedBigIntMapPutIfAbsent(inverse_map, (*out)[i], i);
hypre_assert(old == HYPRE_HOPSCOTCH_HASH_EMPTY);
#ifdef DBG_MERGE_SORT
if (hypre_UnorderedBigIntMapGet(inverse_map, (*out)[i]) != i)
{
fprintf(stderr, "%d %d\n", i, (*out)[i]);
hypre_assert(false);
}
#endif
}
#ifdef DBG_MERGE_SORT
std::unordered_map<HYPRE_Int, HYPRE_Int> inverse_map2(len);
for (HYPRE_Int i = 0; i < len; ++i) {
inverse_map2[(*out)[i]] = i;
if (hypre_UnorderedBigIntMapGet(inverse_map, (*out)[i]) != i)
{
fprintf(stderr, "%d %d\n", i, (*out)[i]);
hypre_assert(false);
}
}
hypre_assert(hypre_UnorderedBigIntMapSize(inverse_map) == len);
#endif
if (*out == in)
{
hypre_TFree(temp, HYPRE_MEMORY_HOST);
}
else
{
hypre_TFree(in, HYPRE_MEMORY_HOST);
}
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_MERGE] += hypre_MPI_Wtime();
#endif
}
/* vim: set tabstop=8 softtabstop=3 sw=3 expandtab: */
|
region_layer.c | #include "region_layer.h"
#include "activations.h"
#include "blas.h"
#include "box.h"
#include "dark_cuda.h"
#include "utils.h"
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#define DOABS 1
region_layer make_region_layer(int batch, int w, int h, int n, int classes, int coords, int max_boxes)
{
region_layer l = { (LAYER_TYPE)0 };
l.type = REGION;
l.n = n;
l.batch = batch;
l.h = h;
l.w = w;
l.classes = classes;
l.coords = coords;
l.cost = (float*)xcalloc(1, sizeof(float));
l.biases = (float*)xcalloc(n * 2, sizeof(float));
l.bias_updates = (float*)xcalloc(n * 2, sizeof(float));
l.outputs = h*w*n*(classes + coords + 1);
l.inputs = l.outputs;
l.max_boxes = max_boxes;
l.truths = max_boxes*(5);
l.delta = (float*)xcalloc(batch * l.outputs, sizeof(float));
l.output = (float*)xcalloc(batch * l.outputs, sizeof(float));
int i;
for(i = 0; i < n*2; ++i){
l.biases[i] = .5;
}
l.forward = forward_region_layer;
l.backward = backward_region_layer;
#ifdef GPU
l.forward_gpu = forward_region_layer_gpu;
l.backward_gpu = backward_region_layer_gpu;
l.output_gpu = cuda_make_array(l.output, batch*l.outputs);
l.delta_gpu = cuda_make_array(l.delta, batch*l.outputs);
#endif
fprintf(stderr, "detection\n");
srand(time(0));
return l;
}
void resize_region_layer(layer *l, int w, int h)
{
#ifdef GPU
int old_w = l->w;
int old_h = l->h;
#endif
l->w = w;
l->h = h;
l->outputs = h*w*l->n*(l->classes + l->coords + 1);
l->inputs = l->outputs;
l->output = (float*)xrealloc(l->output, l->batch * l->outputs * sizeof(float));
l->delta = (float*)xrealloc(l->delta, l->batch * l->outputs * sizeof(float));
#ifdef GPU
if (old_w < w || old_h < h) {
cuda_free(l->delta_gpu);
cuda_free(l->output_gpu);
l->delta_gpu = cuda_make_array(l->delta, l->batch*l->outputs);
l->output_gpu = cuda_make_array(l->output, l->batch*l->outputs);
}
#endif
}
box get_region_box(float *x, float *biases, int n, int index, int i, int j, int w, int h)
{
box b;
b.x = (i + logistic_activate(x[index + 0])) / w;
b.y = (j + logistic_activate(x[index + 1])) / h;
b.w = exp(x[index + 2]) * biases[2*n];
b.h = exp(x[index + 3]) * biases[2*n+1];
if(DOABS){
b.w = exp(x[index + 2]) * biases[2*n] / w;
b.h = exp(x[index + 3]) * biases[2*n+1] / h;
}
return b;
}
float delta_region_box(box truth, float *x, float *biases, int n, int index, int i, int j, int w, int h, float *delta, float scale)
{
box pred = get_region_box(x, biases, n, index, i, j, w, h);
float iou = box_iou(pred, truth);
float tx = (truth.x*w - i);
float ty = (truth.y*h - j);
float tw = log(truth.w / biases[2*n]);
float th = log(truth.h / biases[2*n + 1]);
if(DOABS){
tw = log(truth.w*w / biases[2*n]);
th = log(truth.h*h / biases[2*n + 1]);
}
delta[index + 0] = scale * (tx - logistic_activate(x[index + 0])) * logistic_gradient(logistic_activate(x[index + 0]));
delta[index + 1] = scale * (ty - logistic_activate(x[index + 1])) * logistic_gradient(logistic_activate(x[index + 1]));
delta[index + 2] = scale * (tw - x[index + 2]);
delta[index + 3] = scale * (th - x[index + 3]);
return iou;
}
void delta_region_class(float *output, float *delta, int index, int class_id, int classes, tree *hier, float scale, float *avg_cat, int focal_loss)
{
int i, n;
if(hier){
float pred = 1;
while(class_id >= 0){
pred *= output[index + class_id];
int g = hier->group[class_id];
int offset = hier->group_offset[g];
for(i = 0; i < hier->group_size[g]; ++i){
delta[index + offset + i] = scale * (0 - output[index + offset + i]);
}
delta[index + class_id] = scale * (1 - output[index + class_id]);
class_id = hier->parent[class_id];
}
*avg_cat += pred;
} else {
// Focal loss
if (focal_loss) {
// Focal Loss
float alpha = 0.5; // 0.25 or 0.5
//float gamma = 2; // hardcoded in many places of the grad-formula
int ti = index + class_id;
float pt = output[ti] + 0.000000000000001F;
// http://fooplot.com/#W3sidHlwZSI6MCwiZXEiOiItKDEteCkqKDIqeCpsb2coeCkreC0xKSIsImNvbG9yIjoiIzAwMDAwMCJ9LHsidHlwZSI6MTAwMH1d
float grad = -(1 - pt) * (2 * pt*logf(pt) + pt - 1); // http://blog.csdn.net/linmingan/article/details/77885832
//float grad = (1 - pt) * (2 * pt*logf(pt) + pt - 1); // https://github.com/unsky/focal-loss
for (n = 0; n < classes; ++n) {
delta[index + n] = scale * (((n == class_id) ? 1 : 0) - output[index + n]);
delta[index + n] *= alpha*grad;
if (n == class_id) *avg_cat += output[index + n];
}
}
else {
// default
for (n = 0; n < classes; ++n) {
delta[index + n] = scale * (((n == class_id) ? 1 : 0) - output[index + n]);
if (n == class_id) *avg_cat += output[index + n];
}
}
}
}
float logit(float x)
{
return log(x/(1.-x));
}
float tisnan(float x)
{
return (x != x);
}
static int entry_index(layer l, int batch, int location, int entry)
{
int n = location / (l.w*l.h);
int loc = location % (l.w*l.h);
return batch*l.outputs + n*l.w*l.h*(l.coords + l.classes + 1) + entry*l.w*l.h + loc;
}
void softmax_tree(float *input, int batch, int inputs, float temp, tree *hierarchy, float *output);
void forward_region_layer(const region_layer l, network_state state)
{
int i,j,b,t,n;
int size = l.coords + l.classes + 1;
memcpy(l.output, state.input, l.outputs*l.batch*sizeof(float));
#ifndef GPU
flatten(l.output, l.w*l.h, size*l.n, l.batch, 1);
#endif
for (b = 0; b < l.batch; ++b){
for(i = 0; i < l.h*l.w*l.n; ++i){
int index = size*i + b*l.outputs;
l.output[index + 4] = logistic_activate(l.output[index + 4]);
}
}
#ifndef GPU
if (l.softmax_tree){
for (b = 0; b < l.batch; ++b){
for(i = 0; i < l.h*l.w*l.n; ++i){
int index = size*i + b*l.outputs;
softmax_tree(l.output + index + 5, 1, 0, 1, l.softmax_tree, l.output + index + 5);
}
}
} else if (l.softmax){
for (b = 0; b < l.batch; ++b){
for(i = 0; i < l.h*l.w*l.n; ++i){
int index = size*i + b*l.outputs;
softmax(l.output + index + 5, l.classes, 1, l.output + index + 5, 1);
}
}
}
#endif
if(!state.train) return;
memset(l.delta, 0, l.outputs * l.batch * sizeof(float));
float avg_iou = 0;
float recall = 0;
float avg_cat = 0;
float avg_obj = 0;
float avg_anyobj = 0;
int count = 0;
int class_count = 0;
*(l.cost) = 0;
for (b = 0; b < l.batch; ++b) {
if(l.softmax_tree){
int onlyclass_id = 0;
for(t = 0; t < l.max_boxes; ++t){
box truth = float_to_box(state.truth + t*5 + b*l.truths);
if(!truth.x) break; // continue;
int class_id = state.truth[t*5 + b*l.truths + 4];
float maxp = 0;
int maxi = 0;
if(truth.x > 100000 && truth.y > 100000){
for(n = 0; n < l.n*l.w*l.h; ++n){
int index = size*n + b*l.outputs + 5;
float scale = l.output[index-1];
float p = scale*get_hierarchy_probability(l.output + index, l.softmax_tree, class_id);
if(p > maxp){
maxp = p;
maxi = n;
}
}
int index = size*maxi + b*l.outputs + 5;
delta_region_class(l.output, l.delta, index, class_id, l.classes, l.softmax_tree, l.class_scale, &avg_cat, l.focal_loss);
++class_count;
onlyclass_id = 1;
break;
}
}
if(onlyclass_id) continue;
}
for (j = 0; j < l.h; ++j) {
for (i = 0; i < l.w; ++i) {
for (n = 0; n < l.n; ++n) {
int index = size*(j*l.w*l.n + i*l.n + n) + b*l.outputs;
box pred = get_region_box(l.output, l.biases, n, index, i, j, l.w, l.h);
float best_iou = 0;
int best_class_id = -1;
for(t = 0; t < l.max_boxes; ++t){
box truth = float_to_box(state.truth + t*5 + b*l.truths);
int class_id = state.truth[t * 5 + b*l.truths + 4];
if (class_id >= l.classes) continue; // if label contains class_id more than number of classes in the cfg-file
if(!truth.x) break; // continue;
float iou = box_iou(pred, truth);
if (iou > best_iou) {
best_class_id = state.truth[t*5 + b*l.truths + 4];
best_iou = iou;
}
}
avg_anyobj += l.output[index + 4];
l.delta[index + 4] = l.noobject_scale * ((0 - l.output[index + 4]) * logistic_gradient(l.output[index + 4]));
if(l.classfix == -1) l.delta[index + 4] = l.noobject_scale * ((best_iou - l.output[index + 4]) * logistic_gradient(l.output[index + 4]));
else{
if (best_iou > l.thresh) {
l.delta[index + 4] = 0;
if(l.classfix > 0){
delta_region_class(l.output, l.delta, index + 5, best_class_id, l.classes, l.softmax_tree, l.class_scale*(l.classfix == 2 ? l.output[index + 4] : 1), &avg_cat, l.focal_loss);
++class_count;
}
}
}
if(*(state.net.seen) < 12800){
box truth = {0};
truth.x = (i + .5)/l.w;
truth.y = (j + .5)/l.h;
truth.w = l.biases[2*n];
truth.h = l.biases[2*n+1];
if(DOABS){
truth.w = l.biases[2*n]/l.w;
truth.h = l.biases[2*n+1]/l.h;
}
delta_region_box(truth, l.output, l.biases, n, index, i, j, l.w, l.h, l.delta, .01);
}
}
}
}
for(t = 0; t < l.max_boxes; ++t){
box truth = float_to_box(state.truth + t*5 + b*l.truths);
int class_id = state.truth[t * 5 + b*l.truths + 4];
if (class_id >= l.classes) {
printf(" Warning: in txt-labels class_id=%d >= classes=%d in cfg-file. In txt-labels class_id should be [from 0 to %d] \n", class_id, l.classes, l.classes-1);
getchar();
continue; // if label contains class_id more than number of classes in the cfg-file
}
if(!truth.x) break; // continue;
float best_iou = 0;
int best_index = 0;
int best_n = 0;
i = (truth.x * l.w);
j = (truth.y * l.h);
//printf("%d %f %d %f\n", i, truth.x*l.w, j, truth.y*l.h);
box truth_shift = truth;
truth_shift.x = 0;
truth_shift.y = 0;
//printf("index %d %d\n",i, j);
for(n = 0; n < l.n; ++n){
int index = size*(j*l.w*l.n + i*l.n + n) + b*l.outputs;
box pred = get_region_box(l.output, l.biases, n, index, i, j, l.w, l.h);
if(l.bias_match){
pred.w = l.biases[2*n];
pred.h = l.biases[2*n+1];
if(DOABS){
pred.w = l.biases[2*n]/l.w;
pred.h = l.biases[2*n+1]/l.h;
}
}
//printf("pred: (%f, %f) %f x %f\n", pred.x, pred.y, pred.w, pred.h);
pred.x = 0;
pred.y = 0;
float iou = box_iou(pred, truth_shift);
if (iou > best_iou){
best_index = index;
best_iou = iou;
best_n = n;
}
}
//printf("%d %f (%f, %f) %f x %f\n", best_n, best_iou, truth.x, truth.y, truth.w, truth.h);
float iou = delta_region_box(truth, l.output, l.biases, best_n, best_index, i, j, l.w, l.h, l.delta, l.coord_scale);
if(iou > .5) recall += 1;
avg_iou += iou;
//l.delta[best_index + 4] = iou - l.output[best_index + 4];
avg_obj += l.output[best_index + 4];
l.delta[best_index + 4] = l.object_scale * (1 - l.output[best_index + 4]) * logistic_gradient(l.output[best_index + 4]);
if (l.rescore) {
l.delta[best_index + 4] = l.object_scale * (iou - l.output[best_index + 4]) * logistic_gradient(l.output[best_index + 4]);
}
if (l.map) class_id = l.map[class_id];
delta_region_class(l.output, l.delta, best_index + 5, class_id, l.classes, l.softmax_tree, l.class_scale, &avg_cat, l.focal_loss);
++count;
++class_count;
}
}
//printf("\n");
#ifndef GPU
flatten(l.delta, l.w*l.h, size*l.n, l.batch, 0);
#endif
*(l.cost) = pow(mag_array(l.delta, l.outputs * l.batch), 2);
printf("Region Avg IOU: %f, Class: %f, Obj: %f, No Obj: %f, Avg Recall: %f, count: %d\n", avg_iou/count, avg_cat/class_count, avg_obj/count, avg_anyobj/(l.w*l.h*l.n*l.batch), recall/count, count);
}
void backward_region_layer(const region_layer l, network_state state)
{
axpy_cpu(l.batch*l.inputs, 1, l.delta, 1, state.delta, 1);
}
void get_region_boxes(layer l, int w, int h, float thresh, float **probs, box *boxes, int only_objectness, int *map)
{
int i;
float *const predictions = l.output;
#pragma omp parallel for
for (i = 0; i < l.w*l.h; ++i){
int j, n;
int row = i / l.w;
int col = i % l.w;
for(n = 0; n < l.n; ++n){
int index = i*l.n + n;
int p_index = index * (l.classes + 5) + 4;
float scale = predictions[p_index];
if(l.classfix == -1 && scale < .5) scale = 0;
int box_index = index * (l.classes + 5);
boxes[index] = get_region_box(predictions, l.biases, n, box_index, col, row, l.w, l.h);
boxes[index].x *= w;
boxes[index].y *= h;
boxes[index].w *= w;
boxes[index].h *= h;
int class_index = index * (l.classes + 5) + 5;
if(l.softmax_tree){
hierarchy_predictions(predictions + class_index, l.classes, l.softmax_tree, 0);
int found = 0;
if(map){
for(j = 0; j < 200; ++j){
float prob = scale*predictions[class_index+map[j]];
probs[index][j] = (prob > thresh) ? prob : 0;
}
} else {
for(j = l.classes - 1; j >= 0; --j){
if(!found && predictions[class_index + j] > .5){
found = 1;
} else {
predictions[class_index + j] = 0;
}
float prob = predictions[class_index+j];
probs[index][j] = (scale > thresh) ? prob : 0;
}
}
} else {
for(j = 0; j < l.classes; ++j){
float prob = scale*predictions[class_index+j];
probs[index][j] = (prob > thresh) ? prob : 0;
}
}
if(only_objectness){
probs[index][0] = scale;
}
}
}
}
#ifdef GPU
void forward_region_layer_gpu(const region_layer l, network_state state)
{
/*
if(!state.train){
copy_ongpu(l.batch*l.inputs, state.input, 1, l.output_gpu, 1);
return;
}
*/
flatten_ongpu(state.input, l.h*l.w, l.n*(l.coords + l.classes + 1), l.batch, 1, l.output_gpu);
if(l.softmax_tree){
int i;
int count = 5;
for (i = 0; i < l.softmax_tree->groups; ++i) {
int group_size = l.softmax_tree->group_size[i];
softmax_gpu(l.output_gpu+count, group_size, l.classes + 5, l.w*l.h*l.n*l.batch, 1, l.output_gpu + count);
count += group_size;
}
}else if (l.softmax){
softmax_gpu(l.output_gpu+5, l.classes, l.classes + 5, l.w*l.h*l.n*l.batch, 1, l.output_gpu + 5);
}
float* in_cpu = (float*)xcalloc(l.batch * l.inputs, sizeof(float));
float *truth_cpu = 0;
if(state.truth){
int num_truth = l.batch*l.truths;
truth_cpu = (float*)xcalloc(num_truth, sizeof(float));
cuda_pull_array(state.truth, truth_cpu, num_truth);
}
cuda_pull_array(l.output_gpu, in_cpu, l.batch*l.inputs);
//cudaStreamSynchronize(get_cuda_stream());
network_state cpu_state = state;
cpu_state.train = state.train;
cpu_state.truth = truth_cpu;
cpu_state.input = in_cpu;
forward_region_layer(l, cpu_state);
//cuda_push_array(l.output_gpu, l.output, l.batch*l.outputs);
free(cpu_state.input);
if(!state.train) return;
cuda_push_array(l.delta_gpu, l.delta, l.batch*l.outputs);
//cudaStreamSynchronize(get_cuda_stream());
if(cpu_state.truth) free(cpu_state.truth);
}
void backward_region_layer_gpu(region_layer l, network_state state)
{
flatten_ongpu(l.delta_gpu, l.h*l.w, l.n*(l.coords + l.classes + 1), l.batch, 0, state.delta);
}
#endif
void correct_region_boxes(detection *dets, int n, int w, int h, int netw, int neth, int relative)
{
int i;
int new_w = 0;
int new_h = 0;
if (((float)netw / w) < ((float)neth / h)) {
new_w = netw;
new_h = (h * netw) / w;
}
else {
new_h = neth;
new_w = (w * neth) / h;
}
for (i = 0; i < n; ++i) {
box b = dets[i].bbox;
b.x = (b.x - (netw - new_w) / 2. / netw) / ((float)new_w / netw);
b.y = (b.y - (neth - new_h) / 2. / neth) / ((float)new_h / neth);
b.w *= (float)netw / new_w;
b.h *= (float)neth / new_h;
if (!relative) {
b.x *= w;
b.w *= w;
b.y *= h;
b.h *= h;
}
dets[i].bbox = b;
}
}
void get_region_detections(layer l, int w, int h, int netw, int neth, float thresh, int *map, float tree_thresh, int relative, detection *dets)
{
int i, j, n, z;
float *predictions = l.output;
if (l.batch == 2) {
float *flip = l.output + l.outputs;
for (j = 0; j < l.h; ++j) {
for (i = 0; i < l.w / 2; ++i) {
for (n = 0; n < l.n; ++n) {
for (z = 0; z < l.classes + l.coords + 1; ++z) {
int i1 = z*l.w*l.h*l.n + n*l.w*l.h + j*l.w + i;
int i2 = z*l.w*l.h*l.n + n*l.w*l.h + j*l.w + (l.w - i - 1);
float swap = flip[i1];
flip[i1] = flip[i2];
flip[i2] = swap;
if (z == 0) {
flip[i1] = -flip[i1];
flip[i2] = -flip[i2];
}
}
}
}
}
for (i = 0; i < l.outputs; ++i) {
l.output[i] = (l.output[i] + flip[i]) / 2.;
}
}
for (i = 0; i < l.w*l.h; ++i) {
int row = i / l.w;
int col = i % l.w;
for (n = 0; n < l.n; ++n) {
int index = n*l.w*l.h + i;
for (j = 0; j < l.classes; ++j) {
dets[index].prob[j] = 0;
}
int obj_index = entry_index(l, 0, n*l.w*l.h + i, l.coords);
int box_index = entry_index(l, 0, n*l.w*l.h + i, 0);
int mask_index = entry_index(l, 0, n*l.w*l.h + i, 4);
float scale = l.background ? 1 : predictions[obj_index];
dets[index].bbox = get_region_box(predictions, l.biases, n, box_index, col, row, l.w, l.h);// , l.w*l.h);
dets[index].objectness = scale > thresh ? scale : 0;
if (dets[index].mask) {
for (j = 0; j < l.coords - 4; ++j) {
dets[index].mask[j] = l.output[mask_index + j*l.w*l.h];
}
}
int class_index = entry_index(l, 0, n*l.w*l.h + i, l.coords + !l.background);
if (l.softmax_tree) {
hierarchy_predictions(predictions + class_index, l.classes, l.softmax_tree, 0);// , l.w*l.h);
if (map) {
for (j = 0; j < 200; ++j) {
int class_index = entry_index(l, 0, n*l.w*l.h + i, l.coords + 1 + map[j]);
float prob = scale*predictions[class_index];
dets[index].prob[j] = (prob > thresh) ? prob : 0;
}
}
else {
int j = hierarchy_top_prediction(predictions + class_index, l.softmax_tree, tree_thresh, l.w*l.h);
dets[index].prob[j] = (scale > thresh) ? scale : 0;
}
}
else {
if (dets[index].objectness) {
for (j = 0; j < l.classes; ++j) {
int class_index = entry_index(l, 0, n*l.w*l.h + i, l.coords + 1 + j);
float prob = scale*predictions[class_index];
dets[index].prob[j] = (prob > thresh) ? prob : 0;
}
}
}
}
}
correct_region_boxes(dets, l.w*l.h*l.n, w, h, netw, neth, relative);
}
void zero_objectness(layer l)
{
int i, n;
for (i = 0; i < l.w*l.h; ++i) {
for (n = 0; n < l.n; ++n) {
int obj_index = entry_index(l, 0, n*l.w*l.h + i, l.coords);
l.output[obj_index] = 0;
}
}
}
|
conv1x1s1_sgemm_pack4_neon_sgemm.h | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
#include "option.h"
#include "mat.h"
namespace ncnn{
static void conv1x1s1_sgemm_pack4_neon_sgemm(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt,
int inch, int outw, int outh, int outch)
{
const int size = outw * outh;
Mat tmp = bottom_blob;
const float* bias = _bias;
int nn_outch = 0;
int remain_outch_start = 0;
#if __ARM_NEON && __aarch64__
nn_outch = outch >> 1;
remain_outch_start = nn_outch << 1;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp=0; pp<nn_outch; pp++)
{
int p = pp * 2;
float* outptr0 = top_blob.channel(p);
float* outptr1 = top_blob.channel(p+1);
const float zeros[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
const float* biasptr = bias ? bias + p * 4 : zeros;
int i=0;
for (; i+11<size; i+=12)
{
const float* tmpptr = tmp.channel(i/12);
const float* kptr01 = (const float*)kernel.channel(pp);
int nn = inch;// inch always > 0
asm volatile(
"ld1 {v0.4s, v1.4s}, [%10] \n"
"mov v8.16b, v0.16b \n"
"mov v9.16b, v0.16b \n"
"mov v10.16b, v0.16b \n"
"mov v11.16b, v0.16b \n"
"mov v12.16b, v0.16b \n"
"mov v13.16b, v0.16b \n"
"mov v14.16b, v0.16b \n"
"mov v15.16b, v0.16b \n"
"mov v16.16b, v0.16b \n"
"mov v17.16b, v0.16b \n"
"mov v18.16b, v0.16b \n"
"mov v19.16b, v0.16b \n"
"mov v20.16b, v1.16b \n"
"mov v21.16b, v1.16b \n"
"mov v22.16b, v1.16b \n"
"mov v23.16b, v1.16b \n"
"mov v24.16b, v1.16b \n"
"mov v25.16b, v1.16b \n"
"mov v26.16b, v1.16b \n"
"mov v27.16b, v1.16b \n"
"mov v28.16b, v1.16b \n"
"mov v29.16b, v1.16b \n"
"mov v30.16b, v1.16b \n"
"mov v31.16b, v1.16b \n"
"0: \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n"
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%4], #64 \n"// w0011_01
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v9.4s, v4.4s, v0.s[1] \n"
"fmla v10.4s, v4.4s, v0.s[2] \n"
"fmla v11.4s, v4.4s, v0.s[3] \n"
"fmla v12.4s, v4.4s, v1.s[0] \n"
"fmla v13.4s, v4.4s, v1.s[1] \n"
"fmla v14.4s, v4.4s, v1.s[2] \n"
"fmla v15.4s, v4.4s, v1.s[3] \n"
"fmla v16.4s, v4.4s, v2.s[0] \n"
"fmla v17.4s, v4.4s, v2.s[1] \n"
"fmla v18.4s, v4.4s, v2.s[2] \n"
"fmla v19.4s, v4.4s, v2.s[3] \n"
"fmla v20.4s, v5.4s, v0.s[0] \n"
"fmla v21.4s, v5.4s, v0.s[1] \n"
"fmla v22.4s, v5.4s, v0.s[2] \n"
"fmla v23.4s, v5.4s, v0.s[3] \n"
"fmla v24.4s, v5.4s, v1.s[0] \n"
"fmla v25.4s, v5.4s, v1.s[1] \n"
"fmla v26.4s, v5.4s, v1.s[2] \n"
"fmla v27.4s, v5.4s, v1.s[3] \n"
"fmla v28.4s, v5.4s, v2.s[0] \n"
"fmla v29.4s, v5.4s, v2.s[1] \n"
"fmla v30.4s, v5.4s, v2.s[2] \n"
"fmla v31.4s, v5.4s, v2.s[3] \n"
"fmla v8.4s, v6.4s, v3.s[0] \n"
"fmla v9.4s, v6.4s, v3.s[1] \n"
"fmla v10.4s, v6.4s, v3.s[2] \n"
"fmla v11.4s, v6.4s, v3.s[3] \n"
"fmla v20.4s, v7.4s, v3.s[0] \n"
"fmla v21.4s, v7.4s, v3.s[1] \n"
"fmla v22.4s, v7.4s, v3.s[2] \n"
"fmla v23.4s, v7.4s, v3.s[3] \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n"
"fmla v12.4s, v6.4s, v0.s[0] \n"
"fmla v13.4s, v6.4s, v0.s[1] \n"
"fmla v14.4s, v6.4s, v0.s[2] \n"
"fmla v15.4s, v6.4s, v0.s[3] \n"
"fmla v16.4s, v6.4s, v1.s[0] \n"
"fmla v17.4s, v6.4s, v1.s[1] \n"
"fmla v18.4s, v6.4s, v1.s[2] \n"
"fmla v19.4s, v6.4s, v1.s[3] \n"
"fmla v24.4s, v7.4s, v0.s[0] \n"
"fmla v25.4s, v7.4s, v0.s[1] \n"
"fmla v26.4s, v7.4s, v0.s[2] \n"
"fmla v27.4s, v7.4s, v0.s[3] \n"
"fmla v28.4s, v7.4s, v1.s[0] \n"
"fmla v29.4s, v7.4s, v1.s[1] \n"
"fmla v30.4s, v7.4s, v1.s[2] \n"
"fmla v31.4s, v7.4s, v1.s[3] \n"
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%4], #64 \n"// w2233_01
"fmla v8.4s, v4.4s, v2.s[0] \n"
"fmla v9.4s, v4.4s, v2.s[1] \n"
"fmla v10.4s, v4.4s, v2.s[2] \n"
"fmla v11.4s, v4.4s, v2.s[3] \n"
"fmla v12.4s, v4.4s, v3.s[0] \n"
"fmla v13.4s, v4.4s, v3.s[1] \n"
"fmla v14.4s, v4.4s, v3.s[2] \n"
"fmla v15.4s, v4.4s, v3.s[3] \n"
"fmla v20.4s, v5.4s, v2.s[0] \n"
"fmla v21.4s, v5.4s, v2.s[1] \n"
"fmla v22.4s, v5.4s, v2.s[2] \n"
"fmla v23.4s, v5.4s, v2.s[3] \n"
"fmla v24.4s, v5.4s, v3.s[0] \n"
"fmla v25.4s, v5.4s, v3.s[1] \n"
"fmla v26.4s, v5.4s, v3.s[2] \n"
"fmla v27.4s, v5.4s, v3.s[3] \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n"
"fmla v16.4s, v4.4s, v0.s[0] \n"
"fmla v17.4s, v4.4s, v0.s[1] \n"
"fmla v18.4s, v4.4s, v0.s[2] \n"
"fmla v19.4s, v4.4s, v0.s[3] \n"
"fmla v28.4s, v5.4s, v0.s[0] \n"
"fmla v29.4s, v5.4s, v0.s[1] \n"
"fmla v30.4s, v5.4s, v0.s[2] \n"
"fmla v31.4s, v5.4s, v0.s[3] \n"
"fmla v8.4s, v6.4s, v1.s[0] \n"
"fmla v9.4s, v6.4s, v1.s[1] \n"
"fmla v10.4s, v6.4s, v1.s[2] \n"
"fmla v11.4s, v6.4s, v1.s[3] \n"
"fmla v12.4s, v6.4s, v2.s[0] \n"
"fmla v13.4s, v6.4s, v2.s[1] \n"
"fmla v14.4s, v6.4s, v2.s[2] \n"
"fmla v15.4s, v6.4s, v2.s[3] \n"
"fmla v16.4s, v6.4s, v3.s[0] \n"
"fmla v17.4s, v6.4s, v3.s[1] \n"
"fmla v18.4s, v6.4s, v3.s[2] \n"
"fmla v19.4s, v6.4s, v3.s[3] \n"
"subs %w0, %w0, #1 \n"
"fmla v20.4s, v7.4s, v1.s[0] \n"
"fmla v21.4s, v7.4s, v1.s[1] \n"
"fmla v22.4s, v7.4s, v1.s[2] \n"
"fmla v23.4s, v7.4s, v1.s[3] \n"
"fmla v24.4s, v7.4s, v2.s[0] \n"
"fmla v25.4s, v7.4s, v2.s[1] \n"
"fmla v26.4s, v7.4s, v2.s[2] \n"
"fmla v27.4s, v7.4s, v2.s[3] \n"
"fmla v28.4s, v7.4s, v3.s[0] \n"
"fmla v29.4s, v7.4s, v3.s[1] \n"
"fmla v30.4s, v7.4s, v3.s[2] \n"
"fmla v31.4s, v7.4s, v3.s[3] \n"
"bne 0b \n"
"st1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%1], #64 \n"
"st1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%2], #64 \n"
"st1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%1], #64 \n"
"st1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%2], #64 \n"
"st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n"
"st1 {v28.4s, v29.4s, v30.4s, v31.4s}, [%2], #64 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(tmpptr), // %3
"=r"(kptr01) // %4
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(tmpptr),
"4"(kptr01),
"r"(biasptr) // %10
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"
);
}
for (; i+7<size; i+=8)
{
float* tmpptr = tmp.channel(i/12+(i%12)/8);
const float* kptr01 = (const float*)kernel.channel(pp);
int nn = inch;// inch always > 0
asm volatile(
"ld1 {v0.4s, v1.4s}, [%10] \n"
"mov v16.16b, v0.16b \n"
"mov v17.16b, v0.16b \n"
"mov v18.16b, v0.16b \n"
"mov v19.16b, v0.16b \n"
"mov v20.16b, v0.16b \n"
"mov v21.16b, v0.16b \n"
"mov v22.16b, v0.16b \n"
"mov v23.16b, v0.16b \n"
"mov v24.16b, v1.16b \n"
"mov v25.16b, v1.16b \n"
"mov v26.16b, v1.16b \n"
"mov v27.16b, v1.16b \n"
"mov v28.16b, v1.16b \n"
"mov v29.16b, v1.16b \n"
"mov v30.16b, v1.16b \n"
"mov v31.16b, v1.16b \n"
"0: \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n"// r0 r1 r2 r3
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%4], #64 \n"// w0011_01
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v8.4s, v1.s[0] \n"
"fmla v18.4s, v8.4s, v2.s[0] \n"
"fmla v19.4s, v8.4s, v3.s[0] \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%3], #64 \n"// r4 r5 r6 r7
"fmla v20.4s, v8.4s, v4.s[0] \n"
"fmla v21.4s, v8.4s, v5.s[0] \n"
"fmla v22.4s, v8.4s, v6.s[0] \n"
"fmla v23.4s, v8.4s, v7.s[0] \n"
"fmla v24.4s, v9.4s, v0.s[0] \n"
"fmla v25.4s, v9.4s, v1.s[0] \n"
"fmla v26.4s, v9.4s, v2.s[0] \n"
"fmla v27.4s, v9.4s, v3.s[0] \n"
"fmla v28.4s, v9.4s, v4.s[0] \n"
"fmla v29.4s, v9.4s, v5.s[0] \n"
"fmla v30.4s, v9.4s, v6.s[0] \n"
"fmla v31.4s, v9.4s, v7.s[0] \n"
"fmla v16.4s, v10.4s, v0.s[1] \n"
"fmla v17.4s, v10.4s, v1.s[1] \n"
"fmla v18.4s, v10.4s, v2.s[1] \n"
"fmla v19.4s, v10.4s, v3.s[1] \n"
"fmla v20.4s, v10.4s, v4.s[1] \n"
"fmla v21.4s, v10.4s, v5.s[1] \n"
"fmla v22.4s, v10.4s, v6.s[1] \n"
"fmla v23.4s, v10.4s, v7.s[1] \n"
"fmla v24.4s, v11.4s, v0.s[1] \n"
"fmla v25.4s, v11.4s, v1.s[1] \n"
"fmla v26.4s, v11.4s, v2.s[1] \n"
"fmla v27.4s, v11.4s, v3.s[1] \n"
"fmla v28.4s, v11.4s, v4.s[1] \n"
"fmla v29.4s, v11.4s, v5.s[1] \n"
"fmla v30.4s, v11.4s, v6.s[1] \n"
"fmla v31.4s, v11.4s, v7.s[1] \n"
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%4], #64 \n"// w2233_01
"fmla v16.4s, v12.4s, v0.s[2] \n"
"fmla v17.4s, v12.4s, v1.s[2] \n"
"fmla v18.4s, v12.4s, v2.s[2] \n"
"fmla v19.4s, v12.4s, v3.s[2] \n"
"fmla v20.4s, v12.4s, v4.s[2] \n"
"fmla v21.4s, v12.4s, v5.s[2] \n"
"fmla v22.4s, v12.4s, v6.s[2] \n"
"fmla v23.4s, v12.4s, v7.s[2] \n"
"fmla v24.4s, v13.4s, v0.s[2] \n"
"fmla v25.4s, v13.4s, v1.s[2] \n"
"fmla v26.4s, v13.4s, v2.s[2] \n"
"fmla v27.4s, v13.4s, v3.s[2] \n"
"fmla v28.4s, v13.4s, v4.s[2] \n"
"fmla v29.4s, v13.4s, v5.s[2] \n"
"fmla v30.4s, v13.4s, v6.s[2] \n"
"fmla v31.4s, v13.4s, v7.s[2] \n"
"fmla v16.4s, v14.4s, v0.s[3] \n"
"fmla v17.4s, v14.4s, v1.s[3] \n"
"fmla v18.4s, v14.4s, v2.s[3] \n"
"fmla v19.4s, v14.4s, v3.s[3] \n"
"fmla v20.4s, v14.4s, v4.s[3] \n"
"fmla v21.4s, v14.4s, v5.s[3] \n"
"fmla v22.4s, v14.4s, v6.s[3] \n"
"fmla v23.4s, v14.4s, v7.s[3] \n"
"subs %w0, %w0, #1 \n"
"fmla v24.4s, v15.4s, v0.s[3] \n"
"fmla v25.4s, v15.4s, v1.s[3] \n"
"fmla v26.4s, v15.4s, v2.s[3] \n"
"fmla v27.4s, v15.4s, v3.s[3] \n"
"fmla v28.4s, v15.4s, v4.s[3] \n"
"fmla v29.4s, v15.4s, v5.s[3] \n"
"fmla v30.4s, v15.4s, v6.s[3] \n"
"fmla v31.4s, v15.4s, v7.s[3] \n"
"bne 0b \n"
"st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n"
"st1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%2], #64 \n"
"st1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%1], #64 \n"
"st1 {v28.4s, v29.4s, v30.4s, v31.4s}, [%2], #64 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(tmpptr), // %3
"=r"(kptr01) // %4
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(tmpptr),
"4"(kptr01),
"r"(biasptr) // %10
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"
);
}
for (; i+3<size; i+=4)
{
float* tmpptr = tmp.channel(i/12 + (i%12)/8 + (i%12%8)/4);
const float* kptr01 = (const float*)kernel.channel(pp);
int nn = inch;// inch always > 0
asm volatile(
"ld1 {v0.4s, v1.4s}, [%10] \n"
"mov v16.16b, v0.16b \n"
"mov v17.16b, v0.16b \n"
"mov v18.16b, v0.16b \n"
"mov v19.16b, v0.16b \n"
"mov v20.16b, v1.16b \n"
"mov v21.16b, v1.16b \n"
"mov v22.16b, v1.16b \n"
"mov v23.16b, v1.16b \n"
"0: \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n"// r0 r1 r2 r3
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%4], #64 \n"// w0011_01
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v8.4s, v1.s[0] \n"
"fmla v18.4s, v8.4s, v2.s[0] \n"
"fmla v19.4s, v8.4s, v3.s[0] \n"
"fmla v20.4s, v9.4s, v0.s[0] \n"
"fmla v21.4s, v9.4s, v1.s[0] \n"
"fmla v22.4s, v9.4s, v2.s[0] \n"
"fmla v23.4s, v9.4s, v3.s[0] \n"
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%4], #64 \n"// w2233_01
"fmla v16.4s, v10.4s, v0.s[1] \n"
"fmla v17.4s, v10.4s, v1.s[1] \n"
"fmla v18.4s, v10.4s, v2.s[1] \n"
"fmla v19.4s, v10.4s, v3.s[1] \n"
"fmla v20.4s, v11.4s, v0.s[1] \n"
"fmla v21.4s, v11.4s, v1.s[1] \n"
"fmla v22.4s, v11.4s, v2.s[1] \n"
"fmla v23.4s, v11.4s, v3.s[1] \n"
"fmla v16.4s, v12.4s, v0.s[2] \n"
"fmla v17.4s, v12.4s, v1.s[2] \n"
"fmla v18.4s, v12.4s, v2.s[2] \n"
"fmla v19.4s, v12.4s, v3.s[2] \n"
"fmla v20.4s, v13.4s, v0.s[2] \n"
"fmla v21.4s, v13.4s, v1.s[2] \n"
"fmla v22.4s, v13.4s, v2.s[2] \n"
"fmla v23.4s, v13.4s, v3.s[2] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.4s, v14.4s, v0.s[3] \n"
"fmla v17.4s, v14.4s, v1.s[3] \n"
"fmla v18.4s, v14.4s, v2.s[3] \n"
"fmla v19.4s, v14.4s, v3.s[3] \n"
"fmla v20.4s, v15.4s, v0.s[3] \n"
"fmla v21.4s, v15.4s, v1.s[3] \n"
"fmla v22.4s, v15.4s, v2.s[3] \n"
"fmla v23.4s, v15.4s, v3.s[3] \n"
"bne 0b \n"
"st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n"
"st1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%2], #64 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(tmpptr), // %3
"=r"(kptr01) // %4
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(tmpptr),
"4"(kptr01),
"r"(biasptr) // %10
: "cc", "memory", "v0", "v1", "v2", "v3", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23"
);
}
for (; i+1<size; i+=2)
{
float* tmpptr = tmp.channel(i/12 + (i%12)/8 + (i%12%8)/4 + (i%12%4)/2);
const float* kptr01 = (const float*)kernel.channel(pp);
int nn = inch;// inch always > 0
asm volatile(
"ld1 {v0.4s, v1.4s}, [%10] \n"
"mov v16.16b, v0.16b \n"
"mov v17.16b, v0.16b \n"
"mov v18.16b, v1.16b \n"
"mov v19.16b, v1.16b \n"
"0: \n"
"prfm pldl1keep, [%3, #256] \n"
"ld1 {v0.4s, v1.4s}, [%3], #32 \n"// r0 r1
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%4], #64 \n"// w0011_01
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v8.4s, v1.s[0] \n"
"fmla v18.4s, v9.4s, v0.s[0] \n"
"fmla v19.4s, v9.4s, v1.s[0] \n"
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%4], #64 \n"// w2233_01
"fmla v16.4s, v10.4s, v0.s[1] \n"
"fmla v17.4s, v10.4s, v1.s[1] \n"
"fmla v18.4s, v11.4s, v0.s[1] \n"
"fmla v19.4s, v11.4s, v1.s[1] \n"
"fmla v16.4s, v12.4s, v0.s[2] \n"
"fmla v17.4s, v12.4s, v1.s[2] \n"
"fmla v18.4s, v13.4s, v0.s[2] \n"
"fmla v19.4s, v13.4s, v1.s[2] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.4s, v14.4s, v0.s[3] \n"
"fmla v17.4s, v14.4s, v1.s[3] \n"
"fmla v18.4s, v15.4s, v0.s[3] \n"
"fmla v19.4s, v15.4s, v1.s[3] \n"
"bne 0b \n"
"st1 {v16.4s, v17.4s}, [%1], #32 \n"
"st1 {v18.4s, v19.4s}, [%2], #32 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(tmpptr), // %3
"=r"(kptr01) // %4
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(tmpptr),
"4"(kptr01),
"r"(biasptr) // %10
: "cc", "memory", "v0", "v1", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19"
);
}
for (; i<size; i++)
{
float* tmpptr = tmp.channel(i/12 + (i%12)/8 + (i%12%8)/4 + (i%12%4)/2 + i%12%2);
const float* kptr01 = (const float*)kernel.channel(pp);
int nn = inch;// inch always > 0
asm volatile(
"ld1 {v16.4s, v17.4s}, [%10] \n"
"0: \n"
"prfm pldl1keep, [%3, #128] \n"
"ld1 {v0.4s}, [%3], #16 \n"// r0
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%4], #64 \n"// w0011_01
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v9.4s, v0.s[0] \n"
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%4], #64 \n"// w2233_01
"fmla v16.4s, v10.4s, v0.s[1] \n"
"fmla v17.4s, v11.4s, v0.s[1] \n"
"fmla v16.4s, v12.4s, v0.s[2] \n"
"fmla v17.4s, v13.4s, v0.s[2] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.4s, v14.4s, v0.s[3] \n"
"fmla v17.4s, v15.4s, v0.s[3] \n"
"bne 0b \n"
"st1 {v16.4s}, [%1], #16 \n"
"st1 {v17.4s}, [%2], #16 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(tmpptr), // %3
"=r"(kptr01) // %4
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(tmpptr),
"4"(kptr01),
"r"(biasptr) // %10
: "cc", "memory", "v0", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17"
);
}
}
#endif // __ARM_NEON && __aarch64__
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=remain_outch_start; p<outch; p++)
{
float* outptr0 = top_blob.channel(p);
const float zeros[4] = {0.f, 0.f, 0.f, 0.f};
const float* biasptr = bias ? bias + p * 4 : zeros;
int i=0;
#if __aarch64__
for (; i+11<size; i+=12)
{
float* tmpptr = tmp.channel(i/12);
const float* kptr0 = (const float*)kernel.channel(p/2+p%2);
int nn = inch;// inch always > 0
asm volatile(
"ld1 {v0.4s}, [%8] \n"
"mov v8.16b, v0.16b \n"
"mov v9.16b, v0.16b \n"
"mov v10.16b, v0.16b \n"
"mov v11.16b, v0.16b \n"
"mov v12.16b, v0.16b \n"
"mov v13.16b, v0.16b \n"
"mov v14.16b, v0.16b \n"
"mov v15.16b, v0.16b \n"
"mov v16.16b, v0.16b \n"
"mov v17.16b, v0.16b \n"
"mov v18.16b, v0.16b \n"
"mov v19.16b, v0.16b \n"
"0: \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%2], #64 \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%3], #64 \n"// w0123_0
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v9.4s, v4.4s, v0.s[1] \n"
"fmla v10.4s, v4.4s, v0.s[2] \n"
"fmla v11.4s, v4.4s, v0.s[3] \n"
"fmla v12.4s, v4.4s, v1.s[0] \n"
"fmla v13.4s, v4.4s, v1.s[1] \n"
"fmla v14.4s, v4.4s, v1.s[2] \n"
"fmla v15.4s, v4.4s, v1.s[3] \n"
"fmla v16.4s, v4.4s, v2.s[0] \n"
"fmla v17.4s, v4.4s, v2.s[1] \n"
"fmla v18.4s, v4.4s, v2.s[2] \n"
"fmla v19.4s, v4.4s, v2.s[3] \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%2], #64 \n"
"fmla v8.4s, v5.4s, v3.s[0] \n"
"fmla v9.4s, v5.4s, v3.s[1] \n"
"fmla v10.4s, v5.4s, v3.s[2] \n"
"fmla v11.4s, v5.4s, v3.s[3] \n"
"fmla v12.4s, v5.4s, v20.s[0] \n"
"fmla v13.4s, v5.4s, v20.s[1] \n"
"fmla v14.4s, v5.4s, v20.s[2] \n"
"fmla v15.4s, v5.4s, v20.s[3] \n"
"fmla v16.4s, v5.4s, v21.s[0] \n"
"fmla v17.4s, v5.4s, v21.s[1] \n"
"fmla v18.4s, v5.4s, v21.s[2] \n"
"fmla v19.4s, v5.4s, v21.s[3] \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%2], #64 \n"
"fmla v8.4s, v6.4s, v22.s[0] \n"
"fmla v9.4s, v6.4s, v22.s[1] \n"
"fmla v10.4s, v6.4s, v22.s[2] \n"
"fmla v11.4s, v6.4s, v22.s[3] \n"
"fmla v12.4s, v6.4s, v23.s[0] \n"
"fmla v13.4s, v6.4s, v23.s[1] \n"
"fmla v14.4s, v6.4s, v23.s[2] \n"
"fmla v15.4s, v6.4s, v23.s[3] \n"
"fmla v16.4s, v6.4s, v24.s[0] \n"
"fmla v17.4s, v6.4s, v24.s[1] \n"
"fmla v18.4s, v6.4s, v24.s[2] \n"
"fmla v19.4s, v6.4s, v24.s[3] \n"
"subs %w0, %w0, #1 \n"
"fmla v8.4s, v7.4s, v25.s[0] \n"
"fmla v9.4s, v7.4s, v25.s[1] \n"
"fmla v10.4s, v7.4s, v25.s[2] \n"
"fmla v11.4s, v7.4s, v25.s[3] \n"
"fmla v12.4s, v7.4s, v26.s[0] \n"
"fmla v13.4s, v7.4s, v26.s[1] \n"
"fmla v14.4s, v7.4s, v26.s[2] \n"
"fmla v15.4s, v7.4s, v26.s[3] \n"
"fmla v16.4s, v7.4s, v27.s[0] \n"
"fmla v17.4s, v7.4s, v27.s[1] \n"
"fmla v18.4s, v7.4s, v27.s[2] \n"
"fmla v19.4s, v7.4s, v27.s[3] \n"
"bne 0b \n"
"st1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%1], #64 \n"
"st1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%1], #64 \n"
"st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27"
);
}
#endif
for (; i+7<size; i+=8)
{
#if __aarch64__
float* tmpptr = tmp.channel(i/12+(i%12)/8);
const float* kptr0 = (const float*)kernel.channel(p/2+p%2);
#else
float* tmpptr = tmp.channel(i/8);
const float* kptr0 = (const float*)kernel.channel(p);
#endif
int nn = inch;// inch always > 0
#if __aarch64__
asm volatile(
"ld1 {v0.4s}, [%8] \n"
"mov v16.16b, v0.16b \n"
"mov v17.16b, v0.16b \n"
"mov v18.16b, v0.16b \n"
"mov v19.16b, v0.16b \n"
"mov v20.16b, v0.16b \n"
"mov v21.16b, v0.16b \n"
"mov v22.16b, v0.16b \n"
"mov v23.16b, v0.16b \n"
"0: \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%2], #64 \n"// r0 r1 r2 r3
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%3], #64 \n"// w0123
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v8.4s, v1.s[0] \n"
"fmla v18.4s, v8.4s, v2.s[0] \n"
"fmla v19.4s, v8.4s, v3.s[0] \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%2], #64 \n"// r4 r5 r6 r7
"fmla v20.4s, v8.4s, v4.s[0] \n"
"fmla v21.4s, v8.4s, v5.s[0] \n"
"fmla v22.4s, v8.4s, v6.s[0] \n"
"fmla v23.4s, v8.4s, v7.s[0] \n"
"fmla v16.4s, v9.4s, v0.s[1] \n"
"fmla v17.4s, v9.4s, v1.s[1] \n"
"fmla v18.4s, v9.4s, v2.s[1] \n"
"fmla v19.4s, v9.4s, v3.s[1] \n"
"fmla v20.4s, v9.4s, v4.s[1] \n"
"fmla v21.4s, v9.4s, v5.s[1] \n"
"fmla v22.4s, v9.4s, v6.s[1] \n"
"fmla v23.4s, v9.4s, v7.s[1] \n"
"fmla v16.4s, v10.4s, v0.s[2] \n"
"fmla v17.4s, v10.4s, v1.s[2] \n"
"fmla v18.4s, v10.4s, v2.s[2] \n"
"fmla v19.4s, v10.4s, v3.s[2] \n"
"fmla v20.4s, v10.4s, v4.s[2] \n"
"fmla v21.4s, v10.4s, v5.s[2] \n"
"fmla v22.4s, v10.4s, v6.s[2] \n"
"fmla v23.4s, v10.4s, v7.s[2] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.4s, v11.4s, v0.s[3] \n"
"fmla v17.4s, v11.4s, v1.s[3] \n"
"fmla v18.4s, v11.4s, v2.s[3] \n"
"fmla v19.4s, v11.4s, v3.s[3] \n"
"fmla v20.4s, v11.4s, v4.s[3] \n"
"fmla v21.4s, v11.4s, v5.s[3] \n"
"fmla v22.4s, v11.4s, v6.s[3] \n"
"fmla v23.4s, v11.4s, v7.s[3] \n"
"bne 0b \n"
"st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n"
"st1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%1], #64 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23"
);
#else
asm volatile(
"vld1.f32 {d0-d1}, [%8] \n"
"vmov q8, q0 \n"
"vmov q9, q0 \n"
"vmov q10, q0 \n"
"vmov q11, q0 \n"
"vmov q12, q0 \n"
"vmov q13, q0 \n"
"vmov q14, q0 \n"
"vmov q15, q0 \n"
"0: \n"
"pld [%2, #512] \n"
"vldm %2!, {d0-d7} \n"
"pld [%3, #512] \n"
"vldm %3!, {d8-d15} \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q9, q4, d0[1] \n"
"vmla.f32 q10, q4, d1[0] \n"
"vmla.f32 q11, q4, d1[1] \n"
"vmla.f32 q12, q4, d2[0] \n"
"vmla.f32 q13, q4, d2[1] \n"
"vmla.f32 q14, q4, d3[0] \n"
"vmla.f32 q15, q4, d3[1] \n"
"vmla.f32 q8, q5, d4[0] \n"
"vmla.f32 q9, q5, d4[1] \n"
"vmla.f32 q10, q5, d5[0] \n"
"vmla.f32 q11, q5, d5[1] \n"
"vmla.f32 q12, q5, d6[0] \n"
"vmla.f32 q13, q5, d6[1] \n"
"vmla.f32 q14, q5, d7[0] \n"
"vmla.f32 q15, q5, d7[1] \n"
"pld [%2, #512] \n"
"vldm %2!, {d0-d7} \n"
"vmla.f32 q8, q6, d0[0] \n"
"vmla.f32 q9, q6, d0[1] \n"
"vmla.f32 q10, q6, d1[0] \n"
"vmla.f32 q11, q6, d1[1] \n"
"vmla.f32 q12, q6, d2[0] \n"
"vmla.f32 q13, q6, d2[1] \n"
"vmla.f32 q14, q6, d3[0] \n"
"vmla.f32 q15, q6, d3[1] \n"
"subs %0, %0, #1 \n"
"vmla.f32 q8, q7, d4[0] \n"
"vmla.f32 q9, q7, d4[1] \n"
"vmla.f32 q10, q7, d5[0] \n"
"vmla.f32 q11, q7, d5[1] \n"
"vmla.f32 q12, q7, d6[0] \n"
"vmla.f32 q13, q7, d6[1] \n"
"vmla.f32 q14, q7, d7[0] \n"
"vmla.f32 q15, q7, d7[1] \n"
"bne 0b \n"
"vstm %1!, {d16-d23} \n"
"vstm %1!, {d24-d31} \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
#endif
}
for (; i+3<size; i+=4)
{
#if __aarch64__
float* tmpptr = tmp.channel(i/12 + (i%12)/8 + (i%12%8)/4);
const float* kptr0 = (const float*)kernel.channel(p/2+p%2);
#else
float* tmpptr = tmp.channel(i/8 + (i%8)/4);
const float* kptr0 = (const float*)kernel.channel(p);
#endif
int nn = inch;// inch always > 0
#if __aarch64__
asm volatile(
"ld1 {v0.4s}, [%8] \n"
"mov v16.16b, v0.16b \n"
"mov v17.16b, v0.16b \n"
"mov v18.16b, v0.16b \n"
"mov v19.16b, v0.16b \n"
"0: \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%2], #64 \n"// r0 r1 r2 r3
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%3], #64 \n"// w0123
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v8.4s, v1.s[0] \n"
"fmla v18.4s, v8.4s, v2.s[0] \n"
"fmla v19.4s, v8.4s, v3.s[0] \n"
"fmla v16.4s, v9.4s, v0.s[1] \n"
"fmla v17.4s, v9.4s, v1.s[1] \n"
"fmla v18.4s, v9.4s, v2.s[1] \n"
"fmla v19.4s, v9.4s, v3.s[1] \n"
"fmla v16.4s, v10.4s, v0.s[2] \n"
"fmla v17.4s, v10.4s, v1.s[2] \n"
"fmla v18.4s, v10.4s, v2.s[2] \n"
"fmla v19.4s, v10.4s, v3.s[2] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.4s, v11.4s, v0.s[3] \n"
"fmla v17.4s, v11.4s, v1.s[3] \n"
"fmla v18.4s, v11.4s, v2.s[3] \n"
"fmla v19.4s, v11.4s, v3.s[3] \n"
"bne 0b \n"
"st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "v0", "v1", "v2", "v3", "v8", "v9", "v10", "v11", "v16", "v17", "v18", "v19"
);
#else
asm volatile(
"vld1.f32 {d0-d1}, [%8] \n"
"vmov q8, q0 \n"
"vmov q9, q0 \n"
"vmov q10, q0 \n"
"vmov q11, q0 \n"
"0: \n"
"pld [%2, #512] \n"
"vldm %2!, {d0-d7} \n"
"pld [%3, #512] \n"
"vldm %3!, {d8-d15} \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q9, q4, d2[0] \n"
"vmla.f32 q10, q4, d4[0] \n"
"vmla.f32 q11, q4, d6[0] \n"
"vmla.f32 q8, q5, d0[1] \n"
"vmla.f32 q9, q5, d2[1] \n"
"vmla.f32 q10, q5, d4[1] \n"
"vmla.f32 q11, q5, d6[1] \n"
"vmla.f32 q8, q6, d1[0] \n"
"vmla.f32 q9, q6, d3[0] \n"
"vmla.f32 q10, q6, d5[0] \n"
"vmla.f32 q11, q6, d7[0] \n"
"subs %0, %0, #1 \n"
"vmla.f32 q8, q7, d1[1] \n"
"vmla.f32 q9, q7, d3[1] \n"
"vmla.f32 q10, q7, d5[1] \n"
"vmla.f32 q11, q7, d7[1] \n"
"bne 0b \n"
"vstm %1!, {d16-d23} \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11"
);
#endif
}
for (; i+1<size; i+=2)
{
#if __aarch64__
float* tmpptr = tmp.channel(i/12 + (i%12)/8 + (i%12%8)/4 + (i%12%4)/2);
const float* kptr0 = (const float*)kernel.channel(p/2+p%2);
#else
float* tmpptr = tmp.channel(i/8 + (i%8)/4 + (i%4)/2);
const float* kptr0 = (const float*)kernel.channel(p);
#endif
int nn = inch;// inch always > 0
#if __aarch64__
asm volatile(
"ld1 {v0.4s}, [%8] \n"
"mov v16.16b, v0.16b \n"
"mov v17.16b, v0.16b \n"
"0: \n"
"prfm pldl1keep, [%2, #256] \n"
"ld1 {v0.4s, v1.4s}, [%2], #32 \n"// r0 r1
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%3], #64 \n"// w0123
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v8.4s, v1.s[0] \n"
"fmla v16.4s, v9.4s, v0.s[1] \n"
"fmla v17.4s, v9.4s, v1.s[1] \n"
"fmla v16.4s, v10.4s, v0.s[2] \n"
"fmla v17.4s, v10.4s, v1.s[2] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.4s, v11.4s, v0.s[3] \n"
"fmla v17.4s, v11.4s, v1.s[3] \n"
"bne 0b \n"
"st1 {v16.4s, v17.4s}, [%1], #32 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "v0", "v1", "v8", "v9", "v10", "v11", "v16", "v17"
);
#else
asm volatile(
"vld1.f32 {d0-d1}, [%8] \n"
"vmov q8, q0 \n"
"vmov q9, q0 \n"
"0: \n"
"pld [%2, #256] \n"
"vld1.f32 {d0-d3}, [%2 :128]! \n"
"pld [%3, #512] \n"
"vldm %3!, {d8-d15} \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q9, q4, d2[0] \n"
"vmla.f32 q8, q5, d0[1] \n"
"vmla.f32 q9, q5, d2[1] \n"
"vmla.f32 q8, q6, d1[0] \n"
"vmla.f32 q9, q6, d3[0] \n"
"subs %0, %0, #1 \n"
"vmla.f32 q8, q7, d1[1] \n"
"vmla.f32 q9, q7, d3[1] \n"
"bne 0b \n"
"vst1.f32 {d16-d19}, [%1 :128]! \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "q0", "q1", "q4", "q5", "q6", "q7", "q8", "q9"
);
#endif
}
for (; i<size; i++)
{
#if __aarch64__
float* tmpptr = tmp.channel(i/12 + (i%12)/8 + (i%12%8)/4 + (i%12%4)/2 + i%12%2);
const float* kptr0 = (const float*)kernel.channel(p/2+p%2);
#else
float* tmpptr = tmp.channel(i/8 + (i%8)/4 + (i%4)/2 + i%2);
const float* kptr0 = (const float*)kernel.channel(p);
#endif
int nn = inch;// inch always > 0
#if __aarch64__
asm volatile(
"ld1 {v16.4s}, [%8] \n"
"0: \n"
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v0.4s}, [%2], #16 \n"// r0
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%3], #64 \n"// w0123
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v16.4s, v9.4s, v0.s[1] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.4s, v10.4s, v0.s[2] \n"
"fmla v16.4s, v11.4s, v0.s[3] \n"
"bne 0b \n"
"st1 {v16.4s}, [%1], #16 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "v0", "v8", "v9", "v10", "v11", "v16"
);
#else
asm volatile(
"vld1.f32 {d16-d17}, [%8] \n"
"0: \n"
"pld [%2, #128] \n"
"vld1.f32 {d0-d1}, [%2 :128]! \n"
"pld [%3, #512] \n"
"vldm %3!, {d8-d15} \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q8, q5, d0[1] \n"
"subs %0, %0, #1 \n"
"vmla.f32 q8, q6, d1[0] \n"
"vmla.f32 q8, q7, d1[1] \n"
"bne 0b \n"
"vst1.f32 {d16-d17}, [%1 :128]! \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "q0", "q4", "q5", "q6", "q7", "q8"
);
#endif
}
}
// // NOTE sgemm
// for (; p<outch; p++)
// {
// Mat out0 = top_blob.channel(p);
//
// const float bias0 = bias ? bias[p] : 0.f;
//
// float* outptr0 = out0;
//
// for (int i=0; i<size; i++)
// {
// float sum = bias0;
//
// const float* kptr = _kernel.channel(p);
//
// for (int q=0; q<inch; q++)
// {
// const float* img0 = bottom_blob.channel(q);
//
// sum += img0[i] * kptr[0];
// kptr ++;
// }
//
// outptr0[i] = sum;
// }
// }
}
}
|
valid.yolo11.src.h | #pragma once
#include "ukr.h"
#include "omp.h"
#include "transpose.h"
#include "gen_ukr_A6B2gemm_1_28272_17_17_1024_1_1.h"
#include "gen_ukr_A1B2gemm_1_28272_17_17_1024_1_1.h"
void testrun(float* A ,float*B, float*C, float*oriB ){
int tid = omp_get_thread_num();
int Nx = 17;
int Ny = 17;
int Nh = 1;
long long Astrides[6] = {0,1,2,3,4,5};
int b1 = 0;
for (int fpck = (tid%1)*16; fpck < uNf; fpck+=1*16){
for(int cwh = (tid/1)*8; cwh < uNc*uNw*uNh/8*8; cwh+=8*1){
transpose8x8_avx(oriB+ (fpck+0)*uNc*uNw*uNh + cwh, B + fpck*uNc*uNw*uNh + cwh* 16 + 0, uNc*uNw*uNh, 16);
transpose8x8_avx(oriB+ (fpck+8)*uNc*uNw*uNh + cwh, B + fpck*uNc*uNw*uNh + cwh* 16 + 8, uNc*uNw*uNh, 16);
}
}
#pragma omp barrier// begin push button generated block
for(int xy5=0;xy5<289+0;xy5+=289)
{
for(int f5=0;f5<28272+0;f5+=28272)
{
for(int c5=0;c5<1024+0;c5+=1024)
{
for(int c4=c5;c4<min(1024, 1024+c5);c4+=1024)
{
for(int f4=f5;f4<min(28272, 28272+f5);f4+=3072)
{
for(int xy4=xy5;xy4<min(289, 289+xy5);xy4+=289)
{
for(int c3=c4;c3<min(1024, 1024+c4);c3+=Tc1)
{
for(int xy3=xy4;xy3<min(289, 289+xy4);xy3+=Txy3)
{
for(int f3=f4;f3<min(28272, 3072+f4);f3+=Tf2)
{
for(int xy2=xy3;xy2<min(289, Txy3+xy3);xy2+=6)
{
for(int f2=f3;f2<min(28272, Tf2+f3);f2+=16)
{
for(int c2=c3;c2<min(1024, Tc1+c3);c2+=Tc1)
{
for(int c1=c2;c1<min(1024, Tc1+c2);c1+=Tc1)
{
for(int xy1=xy2;xy1<min(289, 6+xy2);xy1+=6)
{
for(int f1=f2;f1<min(28272, 16+f2);f1+=16)
{
int ctile=min(Tc1, 1024-c1);
int x1=xy1/17;
int y1=xy1%17/1;
int c1_1=c1/1;
int c1_2=c1%1/1;
int kf1_1=f1/16;
int kf1_2=f1%16/1;
int of1_1=f1/1;
int of1_2=f1%1/1;
int offsetA=0+b1*295936+c1_1*289+1*x1*17+1*y1*1+c1_2*1;
int offsetB=0+kf1_1*16384+c1*16+0*16+0*16+kf1_2*1;
int offsetC=0+b1*8170608+of1_1*289+x1*17+y1*1+of1_2*1;
if(17-y1>=6){
cnn_ukr_float_scatter_6x2v_cxycgemm(A+offsetA, B+offsetB, C+offsetC, ctile, Astrides);
}
else if(17*17-xy1>=6){
for(int sti=17-y1;sti<6;sti+=1)
{
Astrides[sti]+=0;
}
cnn_ukr_float_scatter_6x2v_cxycgemm(A+offsetA, B+offsetB, C+offsetC, ctile, Astrides);
for(int sti=17-y1;sti<6;sti+=1)
{
Astrides[sti]-=0;
}
}
else{
cnn_ukr_float_scatter_1x2v_cxycgemm(A+offsetA, B+offsetB, C+offsetC, ctile, Astrides);
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
// end push button generated block
} |
accelerate_kernel_c.c | /*Crown Copyright 2012 AWE.
*
* This file is part of CloverLeaf.
*
* CloverLeaf is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* CloverLeaf 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
* CloverLeaf. If not, see http://www.gnu.org/licenses/. */
/**
* @brief C acceleration kernel
* @author Wayne Gaudin
* @details The pressure and viscosity gradients are used to update the
* velocity field.
*/
#include <stdio.h>
#include <stdlib.h>
#include "ftocmacros.h"
#include <math.h>
void accelerate_kernel_c_(int *xmin,int *xmax,int *ymin,int *ymax,
double *dbyt,
double *xarea,
double *yarea,
double *volume,
double *density0,
double *pressure,
double *viscosity,
double *xvel0,
double *yvel0,
double *xvel1,
double *yvel1)
{
int x_min=*xmin;
int x_max=*xmax;
int y_min=*ymin;
int y_max=*ymax;
double dt=*dbyt;
int j,k,err;
double nodal_mass;
double stepby_mass_s;
#pragma omp parallel
{
#pragma omp for private(nodal_mass,j, stepby_mass_s)
for (k=y_min;k<=y_max+1;k++) {
#pragma ivdep
for (j=x_min;j<=x_max+1;j++) {
nodal_mass=(density0[FTNREF2D(j-1,k-1,x_max+4,x_min-2,y_min-2)]*volume[FTNREF2D(j-1,k-1,x_max+4,x_min-2,y_min-2)]
+density0[FTNREF2D(j ,k-1,x_max+4,x_min-2,y_min-2)]*volume[FTNREF2D(j ,k-1,x_max+4,x_min-2,y_min-2)]
+density0[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)]*volume[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)]
+density0[FTNREF2D(j-1,k ,x_max+4,x_min-2,y_min-2)]*volume[FTNREF2D(j-1,k ,x_max+4,x_min-2,y_min-2)])
*0.25;
stepby_mass_s=0.5*dt/nodal_mass;
xvel1[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]=xvel0[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]
-stepby_mass_s
*(xarea[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]
*(pressure[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)]-pressure[FTNREF2D(j-1,k ,x_max+4,x_min-2,y_min-2)])
+xarea[FTNREF2D(j ,k-1,x_max+5,x_min-2,y_min-2)]
*(pressure[FTNREF2D(j ,k-1,x_max+4,x_min-2,y_min-2)]-pressure[FTNREF2D(j-1,k-1,x_max+4,x_min-2,y_min-2)]));
yvel1[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]=yvel0[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]
-stepby_mass_s
*(yarea[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)]
*(pressure[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)]-pressure[FTNREF2D(j ,k-1,x_max+4,x_min-2,y_min-2)])
+yarea[FTNREF2D(j-1,k ,x_max+4,x_min-2,y_min-2)]
*(pressure[FTNREF2D(j-1,k ,x_max+4,x_min-2,y_min-2)]-pressure[FTNREF2D(j-1,k-1,x_max+4,x_min-2,y_min-2)]));
xvel1[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]=xvel1[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]
-stepby_mass_s
*(xarea[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]
*(viscosity[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)]-viscosity[FTNREF2D(j-1,k ,x_max+4,x_min-2,y_min-2)])
+xarea[FTNREF2D(j ,k-1,x_max+5,x_min-2,y_min-2)]
*(viscosity[FTNREF2D(j ,k-1,x_max+4,x_min-2,y_min-2)]-viscosity[FTNREF2D(j-1,k-1,x_max+4,x_min-2,y_min-2)]));
yvel1[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]=yvel1[FTNREF2D(j ,k ,x_max+5,x_min-2,y_min-2)]
-stepby_mass_s
*(yarea[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)]
*(viscosity[FTNREF2D(j ,k ,x_max+4,x_min-2,y_min-2)]-viscosity[FTNREF2D(j ,k-1,x_max+4,x_min-2,y_min-2)])
+yarea[FTNREF2D(j-1,k ,x_max+4,x_min-2,y_min-2)]
*(viscosity[FTNREF2D(j-1,k ,x_max+4,x_min-2,y_min-2)]-viscosity[FTNREF2D(j-1,k-1,x_max+4,x_min-2,y_min-2)]));
}
}
}
}
|
DiracMatrix.h | //////////////////////////////////////////////////////////////////////////////////////
// This file is distributed under the University of Illinois/NCSA Open Source License.
// See LICENSE file in top directory for details.
//
// Copyright (c) 2019 QMCPACK developers.
//
// File developed by: Ye Luo, yeluo@anl.gov, Argonne National Laboratory
//
// File created by: Jeongnim Kim, jeongnim.kim@intel.com, Intel Corp.
//////////////////////////////////////////////////////////////////////////////////////
#ifndef QMCPLUSPLUS_DIRAC_MATRIX_H
#define QMCPLUSPLUS_DIRAC_MATRIX_H
#include "CPU/Blasf.h"
#include "CPU/BlasThreadingEnv.h"
#include "OhmmsPETE/OhmmsMatrix.h"
#include "type_traits/scalar_traits.h"
#include "Message/OpenMP.h"
#include "CPU/SIMD/simd.hpp"
namespace qmcplusplus
{
inline int Xgetrf(int n, int m, float* restrict a, int lda, int* restrict piv)
{
int status;
sgetrf(n, m, a, lda, piv, status);
return status;
}
inline int Xgetri(int n, float* restrict a, int lda, int* restrict piv, float* restrict work, int& lwork)
{
int status;
sgetri(n, a, lda, piv, work, lwork, status);
return status;
}
inline int Xgetrf(int n, int m, std::complex<float>* restrict a, int lda, int* restrict piv)
{
int status;
cgetrf(n, m, a, lda, piv, status);
return status;
}
/** inversion of a float matrix after lu factorization*/
inline int Xgetri(int n,
std::complex<float>* restrict a,
int lda,
int* restrict piv,
std::complex<float>* restrict work,
int& lwork)
{
int status;
cgetri(n, a, lda, piv, work, lwork, status);
return status;
}
inline int Xgetrf(int n, int m, double* restrict a, int lda, int* restrict piv)
{
int status;
dgetrf(n, m, a, lda, piv, status);
return status;
}
inline int Xgetri(int n, double* restrict a, int lda, int* restrict piv, double* restrict work, int& lwork)
{
int status;
dgetri(n, a, lda, piv, work, lwork, status);
return status;
}
inline int Xgetrf(int n, int m, std::complex<double>* restrict a, int lda, int* restrict piv)
{
int status;
zgetrf(n, m, a, lda, piv, status);
return status;
}
/** inversion of a std::complex<double> matrix after lu factorization*/
inline int Xgetri(int n,
std::complex<double>* restrict a,
int lda,
int* restrict piv,
std::complex<double>* restrict work,
int& lwork)
{
int status;
zgetri(n, a, lda, piv, work, lwork, status);
return status;
}
template<typename TIN, typename TOUT>
inline void TansposeSquare(const TIN* restrict in, TOUT* restrict out, size_t n, size_t lda)
{
#pragma omp simd
for (size_t i = 0; i < n; ++i)
for (size_t j = 0; j < n; ++j)
out[i * lda + j] = in[i + j * lda];
}
template<typename T, typename T_FP>
inline void computeLogDet(const T* restrict diag, int n, const int* restrict pivot, std::complex<T_FP>& logdet)
{
logdet = std::complex<T_FP>();
for (size_t i = 0; i < n; i++)
logdet += std::log(std::complex<T_FP>((pivot[i] == i + 1) ? diag[i] : -diag[i]));
}
/** helper class to compute matrix inversion and the log value of determinant
* @tparam T_FP the datatype used in the actual computation of matrix inversion
*/
template<typename T_FP>
class DiracMatrix
{
typedef typename scalar_traits<T_FP>::real_type real_type_fp;
aligned_vector<T_FP> m_work;
aligned_vector<int> m_pivot;
int Lwork;
/// scratch space used for mixed precision
Matrix<T_FP> psiM_fp;
/// LU diagonal elements
aligned_vector<T_FP> LU_diag;
/// reset internal work space
inline void reset(T_FP* invMat_ptr, const int lda)
{
m_pivot.resize(lda);
Lwork = -1;
T_FP tmp;
real_type_fp lw;
Xgetri(lda, invMat_ptr, lda, m_pivot.data(), &tmp, Lwork);
convert(tmp, lw);
Lwork = static_cast<int>(lw);
m_work.resize(Lwork);
LU_diag.resize(lda);
}
/** compute the inverse of invMat (in place) and the log value of determinant
* @tparam TREAL real type
* @param n invMat is n x n matrix
* @param lda the first dimension of invMat
* @param LogDet log determinant value of invMat before inversion
*/
template<typename TREAL>
inline void computeInvertAndLog(T_FP* invMat, const int n, const int lda, std::complex<TREAL>& LogDet)
{
BlasThreadingEnv knob(getNextLevelNumThreads());
if (Lwork < lda)
reset(invMat, lda);
int status = Xgetrf(n, n, invMat, lda, m_pivot.data());
if (status != 0)
{
std::ostringstream msg;
msg << "Xgetrf failed with error " << status << std::endl;
throw std::runtime_error(msg.str());
}
for (int i = 0; i < n; i++)
LU_diag[i] = invMat[i * lda + i];
computeLogDet(LU_diag.data(), n, m_pivot.data(), LogDet);
status = Xgetri(n, invMat, lda, m_pivot.data(), m_work.data(), Lwork);
if (status != 0)
{
std::ostringstream msg;
msg << "Xgetri failed with error " << status << std::endl;
throw std::runtime_error(msg.str());
}
}
public:
DiracMatrix() : Lwork(0) {}
/** compute the inverse of the transpose of matrix A and its determinant value in log
* when T_FP and TMAT are the same
* @tparam TMAT matrix value type
* @tparam TREAL real type
*/
template<typename TMAT, typename TREAL>
inline std::enable_if_t<std::is_same<T_FP, TMAT>::value> invert_transpose(const Matrix<TMAT>& amat,
Matrix<TMAT>& invMat,
std::complex<TREAL>& LogDet)
{
const int n = invMat.rows();
const int lda = invMat.cols();
simd::transpose(amat.data(), n, amat.cols(), invMat.data(), n, lda);
computeInvertAndLog(invMat.data(), n, lda, LogDet);
}
/** compute the inverse of the transpose of matrix A and its determinant value in log
* when T_FP and TMAT are not the same and need scratch space psiM_fp
* @tparam TMAT matrix value type
* @tparam TREAL real type
*/
template<typename TMAT, typename TREAL>
inline std::enable_if_t<!std::is_same<T_FP, TMAT>::value> invert_transpose(const Matrix<TMAT>& amat,
Matrix<TMAT>& invMat,
std::complex<TREAL>& LogDet)
{
const int n = invMat.rows();
const int lda = invMat.cols();
psiM_fp.resize(n, lda);
simd::transpose(amat.data(), n, amat.cols(), psiM_fp.data(), n, lda);
computeInvertAndLog(psiM_fp.data(), n, lda, LogDet);
invMat = psiM_fp;
}
};
} // namespace qmcplusplus
#endif // QMCPLUSPLUS_DIRAC_MATRIX_H
|
nonneg.c |
/******************************************************************************
* INCLUDES
*****************************************************************************/
#include "../admm.h"
/******************************************************************************
* PUBLIC FUNCTIONS
*****************************************************************************/
/**
* @brief The proximal update for a non-negative factorization. This routine
* projects 'primal' onto the non-negative orthant. Simply, it zeroes
* out negative entries.
*
* @param[out] primal The row-major matrix to update.
* @param nrows The number of rows in primal.
* @param ncols The number of columns in primal.
* @param offset Not used.
* @param data Not used.
* @param rho Not used.
* @param should_parallelize If true, parallelize.
*/
void splatt_nonneg_prox(
val_t * primal,
idx_t const nrows,
idx_t const ncols,
idx_t const offset,
void * data,
val_t const rho,
bool const should_parallelize)
{
#pragma omp parallel for if(should_parallelize)
for(idx_t i=0; i < nrows; ++i) {
for(idx_t j=0; j < ncols; ++j) {
idx_t const index = j + (i*ncols);
primal[index] = (primal[index] > 0.) ? primal[index] : 0.;
}
}
}
/******************************************************************************
* API FUNCTIONS
*****************************************************************************/
splatt_error_type splatt_register_nonneg(
splatt_cpd_opts * opts,
splatt_idx_t const * const modes_included,
splatt_idx_t const num_modes)
{
for(idx_t m = 0; m < num_modes; ++m) {
idx_t const mode = modes_included[m];
splatt_cpd_constraint * ntf_con = splatt_alloc_constraint(SPLATT_CON_ADMM);
/* only fill the details that are used */
ntf_con->prox_func = splatt_nonneg_prox;
/* set hints to assist optimizations */
ntf_con->hints.row_separable = true;
ntf_con->hints.sparsity_inducing = true;
sprintf(ntf_con->description, "NON-NEGATIVE");
/* add to the CPD factorization */
splatt_register_constraint(opts, mode, ntf_con);
/* memory will be freed by splatt_free_constraint() */
}
return SPLATT_SUCCESS;
}
|
GB_unop__frexpx_fp64_fp64.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCUDA_DEV
#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_fp64_fp64)
// op(A') function: GB (_unop_tran__frexpx_fp64_fp64)
// C type: double
// A type: double
// cast: double cij = aij
// unaryop: cij = GB_frexpx (aij)
#define GB_ATYPE \
double
#define GB_CTYPE \
double
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
double aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = GB_frexpx (x) ;
// casting
#define GB_CAST(z, aij) \
double z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
double aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
double z = aij ; \
Cx [pC] = GB_frexpx (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_FREXPX || GxB_NO_FP64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__frexpx_fp64_fp64)
(
double *Cx, // Cx and Ax may be aliased
const double *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++)
{
double aij = Ax [p] ;
double z = aij ;
Cx [p] = GB_frexpx (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 ;
double aij = Ax [p] ;
double z = aij ;
Cx [p] = GB_frexpx (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__frexpx_fp64_fp64)
(
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
|
utilityNestedDisectionMetis.h | // ***********************************************************************
//
// Grappolo: A C++ library for graph clustering
// Mahantesh Halappanavar (hala@pnnl.gov)
// Pacific Northwest National Laboratory
//
// ***********************************************************************
//
// Copyright (2014) Battelle Memorial Institute
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// ************************************************************************
#ifndef _graph_NestDisect_
#define _graph_NestDisect_
/*
int METIS NodeND(idx t *nvtxs, idx t *xadj, idx t *adjncy, idx t *vwgt, idx t *options,
idx t *perm, idx t *iperm)
Description
This function computes fill reducing orderings of sparse matrices using the multilevel nested dissection algorithm.
Parameters
nvtxs: The number of vertices in the graph.
xadj, adjncy: The adjacency structure of the graph as described in Section 5.5.
vwgt (NULL): An array of size nvtxs specifying the weights of the vertices. If the graph is weighted, the nested dissection ordering computes vertex separators that minimize the sum of the weights of the vertices
on the separators. A NULL can be passed to indicate a graph with equal weight vertices (or unweighted).
options (NULL)
This is the array of options as described in Section 5.4. The following options are valid:
METIS_OPTION_CTYPE, METIS_OPTION_RTYPE, METIS_OPTION_NO2HOP,
METIS_OPTION_NSEPS, METIS_OPTION_NITER, METIS_OPTION_UFACTOR,
METIS_OPTION_COMPRESS, METIS_OPTION_CCORDER, METIS_OPTION_SEED,
METIS_OPTION_PFACTOR, METIS_OPTION_NUMBERING, METIS_OPTION_DBGLVL
perm, iperm: These are vectors, each of size nvtxs. Upon successful completion, they store the fill-reducing permutation and inverse-permutation. Let A be the original matrix and A0 be the permuted matrix. The
arrays perm and iperm are defined as follows.
Row (column) i of A0 is the perm[i] row (column) of A, and row (column) i of A is the iperm[i] row (column) of A0. The numbering of this vector starts from either 0 or 1, depending on the value of options[METIS OPTION NUMBERING].
Returns:
METIS OK Indicates that the function returned normally.
METIS ERROR INPUT Indicates an input error.
METIS ERROR MEMORY Indicates that it could not allocate the required memory.
METIS ERROR Indicates some other type of error.
*/
extern "C" {
#include "metis.h"
}
using namespace std;
/*
#ifdef __cplusplus
extern "C" {
#endif
//Nested dissection
int METIS_NodeND(idx t *nvtxs, idx t *xadj, idx t *adjncy, idx t *vwgt, idx t *options,
idx t *perm, idx t *iperm);
#ifdef __cplusplus
}
#endif
*/
//METIS Graph Partitioner:
void MetisNDReorder( graph *G, long *old2NewMap ) {
printf("Within MetisNDReorder(): \n");
//Get the iterators for the graph:
long NV = G->numVertices;
long NE = G->numEdges;
long *vtxPtr = G->edgeListPtrs;
edge *vtxInd = G->edgeList;
printf("|V|= %ld, |E|= %ld \n", NV, NE);
int status=0;
idx_t nvtxs = (idx_t) NV;
idx_t *xadj = (idx_t *) malloc ((NV+1) * sizeof(idx_t));
assert(xadj != 0);
#pragma omp parallel for
for(long i=0; i<=NV; i++) {
xadj[i] = (idx_t) vtxPtr[i];
}
idx_t *adjncy = (idx_t *) malloc (2*NE * sizeof(idx_t));
assert(adjncy != 0);
#pragma omp parallel for
for(long i=0; i<2*NE; i++) {
adjncy[i] = (idx_t) vtxInd[i].tail;
}
idx_t *adjwgt = (idx_t *) malloc (2*NE * sizeof(idx_t));
assert(adjwgt != 0);
#pragma omp parallel for
for(long i=0; i<2*NE; i++) {
adjwgt[i] = (idx_t) vtxInd[i].weight;
}
idx_t *perm = (idx_t *) malloc (NV * sizeof(idx_t)); assert(perm != 0);
idx_t *iperm = (idx_t *) malloc (NV * sizeof(idx_t)); assert(iperm != 0);
real_t ubvec = 1.03;
idx_t options[METIS_NOPTIONS];
METIS_SetDefaultOptions(options);
options[METIS_OPTION_CTYPE] = METIS_CTYPE_SHEM; //Sorted heavy-edge matching
options[METIS_OPTION_IPTYPE] = METIS_IPTYPE_NODE; //Grows a bisection using a greedy strategy.
options[METIS_OPTION_RTYPE] = METIS_RTYPE_SEP1SIDED; //FM-based cut refinement.
options[METIS_OPTION_DBGLVL] = 1; //#different separators at each level of nested dissection.
options[METIS_OPTION_UFACTOR] = 200; //Maximum allowed load imbalance among partitions
options[METIS_OPTION_NO2HOP] = 0; //The 2–hop matching (0=perform; 1=Do not)
options[METIS_OPTION_COMPRESS] = 1; //Combine vertices with identical adjacency lists (0=do not)
options[METIS_OPTION_CCORDER] = 0; //Connected components identified and ordered separately (1=Yes)
options[METIS_OPTION_SEED] = 786; //Specifies the seed for the random number generator.
options[METIS_OPTION_NITER] = 10; //#iterations for the refinement algorithms
options[METIS_OPTION_NSEPS] = 1; //#different separators
options[METIS_OPTION_PFACTOR] = 10; //Min degree of the vertices that will be ordered last
options[METIS_OPTION_NUMBERING]= 0; //C-style numbering, starting from 0
/* int returnVal = METIS_PartGraphKway(&nvtxs, &ncon, xadj, adjncy, NULL, NULL, adjwgt,
&nparts, NULL, NULL, options, &objval, part); */
status = METIS_NodeND(&nvtxs, xadj, adjncy, NULL, options, perm, iperm);
if(status == METIS_OK)
printf("Nested dissection returned correctly. Will store the permutations in vectors perm and iperm.\n");
else {
if(status == METIS_ERROR_MEMORY)
printf("Metis could not allocate memory.\n");
else if(status == METIS_ERROR_INPUT)
printf("Metis had issues with input.\n");
else
printf("Some other Metis error: %ld\n", status);
}
#pragma omp parallel for
for(long i=0; i<=NV; i++) {
old2NewMap[i] = (long) perm[i]; //Do explicit typecasts
}
//Cleaup:
free(xadj); free(adjncy); free(adjwgt);
free(perm); free(iperm);
printf("Returning back from Metis\n");
}
#endif
|
DRB020-privatemissing-var-yes.c | /*
Copyright (c) 2017, Lawrence Livermore National Security, LLC.
Produced at the Lawrence Livermore National Laboratory
Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund,
Markus Schordan, and Ian Karlin
(email: 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.
*/
/*
tmp should be put as private to avoid race condition
Data race pair: tmp@65 vs. tmp@66
*/
#include <stdlib.h>
int main(int argc, char* argv[])
{
int i;
int tmp;
int len=100;
if (argc>1)
len = atoi(argv[1]);
int a[len];
#pragma omp parallel for private(i )
for (i=0;i<len;i++)
a[i]=i;
#pragma omp parallel for private(tmp )
for (i=0;i<len;i++)
{
tmp =a[i]+i;
a[i] = tmp;
}
for (i=0;i<len;i++)
printf("%d\n", a[i]);
return 0;
}
|
DRB050-functionparameter-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.
*/
#include <stdio.h>
#include <stdlib.h>
/*
Arrays passed as function parameters
*/
#include <omp.h>
void foo1(double o1[],double c[],int len)
{
int i;
#pragma omp parallel for private (i) firstprivate (len)
for (i = 0; i <= len - 1; i += 1) {
double volnew_o8 = 0.5 * c[i];
o1[i] = volnew_o8;
}
}
int main()
{
double o1[101];
double c[101];
int i;
int len = 100;
#pragma omp parallel for private (i)
for (i = 0; i <= len - 1; i += 1) {
c[i] = i + 1.01;
o1[i] = i + 1.01;
}
foo1(&o1[1],&o1[0],100);
for (i = 0; i <= len - 1; i += 1) {
printf("%lf\n",o1[i]);
}
return 0;
}
|
xpose.c | #include "../bib.h"
#include "../types.h"
#include "../cdefs.h"
#include "safeomp.h"
#define BLOCKSIZE 8 // TODO check cache line explicitly
int bib_xpose(cmat_r x, mat_r tx)
{
CHECKIFSAME(x, tx);
const len_t m = x->nrows;
const len_t n = x->ncols;
const double *const x_data = x->data;
double *const tx_data = tx->data;
if (m != tx->ncols || n != tx->nrows)
return LIBBIB_INDIMMISMATCH;
#pragma omp parallel for default(none) schedule(dynamic, 1) if(n>OMP_MIN_SIZE)
for (len_t j=0; j<n; j+=BLOCKSIZE)
{
for (len_t i=0; i<m; i+=BLOCKSIZE)
{
for (len_t col=j; col<j+BLOCKSIZE && col<n; ++col)
{
for (len_t row=i; row<i+BLOCKSIZE && row<m; ++row)
tx_data[col + n*row] = x_data[row + m*col];
}
}
}
return LIBBIB_OK;
}
int bib_xpose_a(cmat_r x, dmatrix_t **restrict tx)
{
CHECKIFSAME(x, *tx);
*tx = newmat(NCOLS(x), NROWS(x));
if (DATA(*tx) == NULL)
return LIBBIB_BADMALLOC;
return bib_xpose(x, *tx);
}
|
displacement_lagrangemultiplier_contact_criteria.h | // KRATOS ___| | | |
// \___ \ __| __| | | __| __| | | __| _` | |
// | | | | | ( | | | | ( | |
// _____/ \__|_| \__,_|\___|\__|\__,_|_| \__,_|_| MECHANICS
//
// License: BSD License
// license: StructuralMechanicsApplication/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 (and it subclasses)
typedef ConvergenceCriteria< TSparseSpace, TDenseSpace > BaseType;
typedef typename BaseType::TDataType TDataType;
typedef typename BaseType::DofsArrayType DofsArrayType;
typedef typename BaseType::TSystemMatrixType TSystemMatrixType;
typedef typename BaseType::TSystemVectorType TSystemVectorType;
/// The sparse space used
typedef TSparseSpace SparseSpaceType;
/// The r_table stream definition TODO: Replace by logger
typedef TableStreamUtility::Pointer TablePrinterPointerType;
/// The index type definition
typedef std::size_t IndexType;
/// The key type definition
typedef std::size_t KeyType;
/// The epsilon tolerance definition
static constexpr double Tolerance = std::numeric_limits<double>::epsilon();
///@}
///@name Life Cycle
///@{
/**
* @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 TDataType DispRatioTolerance,
const TDataType DispAbsTolerance,
const TDataType RotRatioTolerance,
const TDataType RotAbsTolerance,
const TDataType LMRatioTolerance,
const TDataType 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;
}
/**
* @brief Default constructor (parameters)
* @param ThisParameters The configuration parameters
*/
explicit DisplacementLagrangeMultiplierContactCriteria( Parameters ThisParameters = Parameters(R"({})"))
: BaseType()
{
// Validate and assign defaults
ThisParameters = this->ValidateAndAssignParameters(ThisParameters, this->GetDefaultParameters());
this->AssignSettings(ThisParameters);
}
// 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
///@{
/**
* @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
TDataType 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;
TDataType 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 TDataType disp_ratio = std::sqrt(disp_increase_norm/disp_solution_norm);
const TDataType rot_ratio = std::sqrt(rot_increase_norm/rot_solution_norm);
const TDataType lm_ratio = lm_solution_norm > Tolerance ? std::sqrt(lm_increase_norm/lm_solution_norm) : 0.0;
const TDataType disp_abs = std::sqrt(disp_increase_norm)/static_cast<TDataType>(disp_dof_num);
const TDataType rot_abs = std::sqrt(rot_increase_norm)/static_cast<TDataType>(rot_dof_num);
const TDataType lm_abs = std::sqrt(lm_increase_norm)/static_cast<TDataType>(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 Operations
///@{
///@}
///@name Acces
///@{
///@}
///@name Inquiry
///@{
///@}
///@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
TDataType mDispRatioTolerance; /// The ratio threshold for the norm of the displacement
TDataType mDispAbsTolerance; /// The absolute value threshold for the norm of the displacement
TDataType mRotRatioTolerance; /// The ratio threshold for the norm of the rotation
TDataType mRotAbsTolerance; /// The absolute value threshold for the norm of the rotation
TDataType mLMRatioTolerance; /// The ratio threshold for the norm of the LM
TDataType 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 */
|
Example_single.1.c | /*
* @@name: single.1c
* @@type: C
* @@compilable: yes
* @@linkable: no
* @@expect: success
*/
#include <stdio.h>
void work1() {}
void work2() {}
void single_example()
{
#pragma omp parallel
{
#pragma omp single
printf("Beginning work1.\n");
work1();
#pragma omp single
printf("Finishing work1.\n");
#pragma omp single nowait
printf("Finished work1 and beginning work2.\n");
work2();
}
}
|
GB_cumsum.c | //------------------------------------------------------------------------------
// GB_cumsum: cumlative sum of an array
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// Compute the cumulative sum of an array count[0:n], of size n+1
// in pseudo-MATLAB notation:
// k = sum (count [0:n-1] != 0) ;
// count = cumsum ([0 count[0:n-1]]) ;
// That is, count [j] on input is overwritten with the value of
// sum (count [0..j-1]). count [n] is implicitly zero on input.
// On output, count [n] is the total sum.
#include "GB.h"
GB_PUBLIC // accessed by the MATLAB tests in GraphBLAS/Test only
void GB_cumsum // cumulative sum of an array
(
int64_t *GB_RESTRICT count, // size n+1, input/output
const int64_t n,
int64_t *GB_RESTRICT kresult, // return k, if needed by the caller
int nthreads
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
ASSERT (count != NULL) ;
ASSERT (n >= 0) ;
//--------------------------------------------------------------------------
// determine # of threads to use
//--------------------------------------------------------------------------
#if !defined ( _OPENMP )
nthreads = 1 ;
#endif
if (nthreads > 1)
{
nthreads = GB_IMIN (nthreads, n / 1024) ;
nthreads = GB_IMAX (nthreads, 1) ;
}
//--------------------------------------------------------------------------
// count = cumsum ([0 count[0:n-1]]) ;
//--------------------------------------------------------------------------
if (kresult == NULL)
{
if (nthreads <= 2)
{
//------------------------------------------------------------------
// cumsum with one thread
//------------------------------------------------------------------
int64_t s = 0 ;
for (int64_t i = 0 ; i < n ; i++)
{
int64_t c = count [i] ;
count [i] = s ;
s += c ;
}
count [n] = s ;
}
else
{
//------------------------------------------------------------------
// cumsum with multiple threads
//------------------------------------------------------------------
// allocate workspace
int64_t *ws = GB_MALLOC (nthreads, int64_t) ;
if (ws == NULL)
{
// out of memory; use a single thread instead
GB_cumsum (count, n, NULL, 1) ;
return ;
}
int tid ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (tid = 0 ; tid < nthreads ; tid++)
{
// each task sums up its own part
int64_t istart, iend ;
GB_PARTITION (istart, iend, n, tid, nthreads) ;
int64_t s = 0 ;
for (int64_t i = istart ; i < iend ; i++)
{
s += count [i] ;
}
ws [tid] = s ;
}
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (tid = 0 ; tid < nthreads ; tid++)
{
// each tasks computes the cumsum of its own part
int64_t istart, iend ;
GB_PARTITION (istart, iend, n, tid, nthreads) ;
int64_t s = 0 ;
for (int i = 0 ; i < tid ; i++)
{
s += ws [i] ;
}
for (int64_t i = istart ; i < iend ; i++)
{
int64_t c = count [i] ;
count [i] = s ;
s += c ;
}
if (iend == n)
{
count [n] = s ;
}
}
// free workspace
GB_FREE (ws) ;
}
}
else
{
if (nthreads <= 2)
{
//------------------------------------------------------------------
// cumsum with one thread, also compute k
//------------------------------------------------------------------
int64_t k = 0 ;
int64_t s = 0 ;
for (int64_t i = 0 ; i < n ; i++)
{
int64_t c = count [i] ;
if (c != 0) k++ ;
count [i] = s ;
s += c ;
}
count [n] = s ;
(*kresult) = k ;
}
else
{
//------------------------------------------------------------------
// cumsum with multiple threads, also compute k
//------------------------------------------------------------------
int64_t *ws = GB_MALLOC (2*nthreads, int64_t) ;
if (ws == NULL)
{
// out of memory; use a single thread instead
GB_cumsum (count, n, kresult, 1) ;
return ;
}
int64_t *wk = ws + nthreads ;
int tid ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (tid = 0 ; tid < nthreads ; tid++)
{
// each task sums up its own part
int64_t istart, iend ;
GB_PARTITION (istart, iend, n, tid, nthreads) ;
int64_t k = 0 ;
int64_t s = 0 ;
for (int64_t i = istart ; i < iend ; i++)
{
int64_t c = count [i] ;
if (c != 0) k++ ;
s += c ;
}
ws [tid] = s ;
wk [tid] = k ;
}
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (tid = 0 ; tid < nthreads ; tid++)
{
// each task computes the cumsum of its own part
int64_t istart, iend ;
GB_PARTITION (istart, iend, n, tid, nthreads) ;
int64_t s = 0 ;
for (int i = 0 ; i < tid ; i++)
{
s += ws [i] ;
}
for (int64_t i = istart ; i < iend ; i++)
{
int64_t c = count [i] ;
count [i] = s ;
s += c ;
}
if (iend == n)
{
count [n] = s ;
}
}
int64_t k = 0 ;
for (int tid = 0 ; tid < nthreads ; tid++)
{
k += wk [tid] ;
}
(*kresult) = k ;
// free workspace
GB_FREE (ws) ;
}
}
}
|
scheduled-clause.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=200,chunk,a[n],suma=0;
int dyn_var_value, nthreads_var_value, thread_limit_var;
omp_sched_t kind;
int modifier = 0;
int primera = 1;
if(argc < 3) {
fprintf(stderr,"\nFalta iteraciones o chunk \n");
exit(-1);
}
n = atoi(argv[1]); if (n>200) n=200; chunk = atoi(argv[2]);
for (i=0; i<n; i++) a[i] = i;
printf(" Fuera del parallel: \n");
printf(" dyn-var-> %d ;nthreads-var->%d; thread-limit-var->%d; run-sched-var-kind->%d; run-sched-var-modifier->%d; \n",
omp_get_dynamic(),omp_get_max_threads(),omp_get_thread_limit(), kind, modifier);
#pragma omp parallel for firstprivate(suma) \
lastprivate(suma) schedule(static,chunk)
for (i=0; i<n; i++)
{
#pragma omp critical
if(primera == 1){
primera = 0;
omp_get_schedule(&kind, &modifier);
printf(" Fuera del parallel: \n");
printf(" dyn-var-> %d ;nthreads-var->%d; thread-limit-var->%d; run-sched-var-kind->%d; run-sched-var-modifier->%d; \n",
omp_get_dynamic(),omp_get_max_threads(),omp_get_thread_limit(), kind, modifier);
}
#pragma omp atomic
suma = suma + a[i];
#pragma omp critical
printf(" thread %d suma a[%d]=%d suma=%d \n",
omp_get_thread_num(),i,a[i],suma);
}
printf("Fuera de 'parallel for' suma=%d\n",suma);
return(0);
}
|
top_k_op.h | /* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#pragma once
#include <algorithm>
#include <iostream>
#include <utility>
#include <vector>
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
namespace paddle {
namespace operators {
using Tensor = framework::Tensor;
template <typename T, int MajorType = Eigen::RowMajor,
typename IndexType = Eigen::DenseIndex>
using EigenMatrix = framework::EigenMatrix<T, MajorType, IndexType>;
template <typename DeviceContext, typename T>
class TopkKernel : public framework::OpKernel<T> {
public:
void Compute(const framework::ExecutionContext& ctx) const override {
// Get the top k elements of each row of input tensor
// FIXME: only deal with matrix(2d tensor).
auto* input = ctx.Input<Tensor>("X");
auto* output = ctx.Output<Tensor>("Out");
auto* indices = ctx.Output<Tensor>("Indices");
// k is determined by Attr
const size_t k = static_cast<int>(ctx.Attr<int>("k"));
T* output_data = output->mutable_data<T>(ctx.GetPlace());
int64_t* indices_data = indices->mutable_data<int64_t>(ctx.GetPlace());
auto eg_input = EigenMatrix<T>::From(*input);
// reshape input to a flattern matrix(like flat_inner_dims)
framework::DDim inputdims = input->dims();
const size_t row = framework::product(
framework::slice_ddim(inputdims, 0, inputdims.size() - 1));
const size_t col = inputdims[inputdims.size() - 1];
Eigen::DSizes<int, 2> flat2dims(row, col);
// NOTE: eigen shape doesn't affect paddle tensor.
eg_input.reshape(flat2dims);
#ifdef PADDLE_WITH_MKLML
#pragma omp parallel for
#endif
for (size_t i = 0; i < row; i++) {
std::vector<std::pair<T, size_t>> vec;
for (size_t j = 0; j < col; j++) {
vec.push_back(std::pair<T, size_t>(eg_input(i, j), j));
}
std::partial_sort(
vec.begin(), vec.begin() + k, vec.end(),
[](const std::pair<T, size_t>& l, const std::pair<T, size_t>& r) {
return l.first > r.first;
});
for (size_t j = 0; j < k; j++) {
output_data[i * k + j] = vec[j].first;
indices_data[i * k + j] = int64_t(vec[j].second);
}
}
}
};
} // namespace operators
} // namespace paddle
|
ops.h | /*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
#pragma once
#ifndef OPS_H_
#define OPS_H_
#include <op_boilerplate.h>
#include <array/DataTypeUtils.h>
#include <helpers/shape.h>
#include <vector>
#include <Environment.h>
#include <loops/summarystatsreduce.h>
#include <loops/ReduceType.h>
#define MIN_V 1e-12
#define MAX_FLOAT 1e37
#define MIN_FLOAT 1e-37
#define MAX_INT 2147483647
#define MIN_CUTFOFF -3.79297773665f
#define FLOAT_MIN_NORMAL 1.17549435e-38
#define EPS 1e-5
#define AFFINITY close
#define DOUBLE_PI_T T(2.0 * 3.14159265358979323846)
#define DOUBLE_PI_X X(2.0 * 3.14159265358979323846)
#define no_op_exec_special_any static const bool requiresSpecial = false; static void execSpecial(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, X *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {}
#define no_op_exec_special_bool static const bool requiresSpecial = false; static void execSpecial(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, X *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {}
#define no_op_exec_special_same static const bool requiresSpecial = false; static void execSpecial(X *dx, Nd4jLong *xShapeBuffer, X *result, Nd4jLong *resultShapeBuffer, X *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {}
#define no_op_exec_special static const bool requiresSpecial = false; static void execSpecial(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, Z *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {}
#define no_op_exec_special_accumulation static const bool requiresSpecialAccumulation = false; static void execSpecial(X *x, Nd4jLong *xShapeInfo, Z *extraParams, Z *result, Nd4jLong *resultShapeInfoBuffer, int *dimension, int dimensionLength, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffset){}
#define no_op_exec_special_accumulation_long static const bool requiresSpecialAccumulation = false; static void execSpecial(X *x, Nd4jLong *xShapeInfo, X *extraParams, Z *result, Nd4jLong *resultShapeInfoBuffer, int *dimension, int dimensionLength, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffset){}
#define no_op_exec_special_accumulation_same static const bool requiresSpecialAccumulation = false; static void execSpecial(X *x, Nd4jLong *xShapeInfo, X *extraParams, X *result, Nd4jLong *resultShapeInfoBuffer, int *dimension, int dimensionLength, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffset){}
#ifdef __CUDACC__
#include <helpers/sharedmem.h>
#define no_op_exec_special_any_cuda static __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, X *extraParams, int *allocationPointer, Z *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {}
#define no_op_exec_special_bool_cuda static __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, X *extraParams, int *allocationPointer, Z *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {}
#define no_op_exec_special_same_cuda static __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeBuffer, X *result, Nd4jLong *resultShapeBuffer, X *extraParams, int *allocationPointer, X *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {}
#define no_op_exec_special_cuda static __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeBuffer,Z *result, Nd4jLong *resultShapeBuffer,Z *extraParams, int *allocationPointer, Z *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {}
#define no_op_exec_special_accumulation_same_cuda static inline __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeInfo, X *extraParams, X *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, X *reductionBuffer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets) {}
#define no_op_exec_special_accumulation_long_cuda static inline __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeInfo, X *extraParams, Z *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, Z *reductionBuffer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets) {}
#define no_op_exec_special_accumulation_cuda static inline __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeInfo, Z *extraParams, Z *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, Z *reductionBuffer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets) {}
#else
// hacky fix for isnan/being being out of scope
//#ifdef IOS
//#define isinf(x) 0 // this isn't right. But std::isinf fails
//#define isnan(x) 0
//#else
//#define isnan std::isnan
//#define isinf std::isinf
//#endif
#define no_op_exec_special_cuda
#define no_op_exec_special_accumulation_cuda
#define no_op_exec_special_accumulation_same_cuda
#define no_op_exec_special_accumulation_long_cuda
#define no_op_exec_special_any_cuda
#define no_op_exec_special_bool_cuda
#define no_op_exec_special_same_cuda
#define no_op_exec_special_accumulation_same_cuda
#endif
#define SELU_ALPHA 1.6732632423543772848170429916717
#define SELU_LAMBDA 1.0507009873554804934193349852946
#ifdef _OPENMP
#pragma omp declare reduction(maxTF : float,double,float16,bfloat16 : \
omp_out = nd4j::math::nd4j_max(omp_in, omp_out) )\
initializer (omp_priv=-MAX_FLOAT)
#pragma omp declare reduction(minTF : float,double,float16,bfloat16 : \
omp_out = nd4j::math::nd4j_min(omp_in, omp_out) )\
initializer (omp_priv=MAX_FLOAT)
#pragma omp declare reduction(maxT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \
omp_out = nd4j::math::nd4j_max(omp_in, omp_out) )\
initializer (omp_priv=0)
#pragma omp declare reduction(minT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \
omp_out = nd4j::math::nd4j_min(omp_in, omp_out) )\
initializer (omp_priv=0)
#pragma omp declare reduction(amaxT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \
omp_out = nd4j::math::nd4j_max(nd4j::math::nd4j_abs(omp_in), nd4j::math::nd4j_abs(omp_out)) )
#pragma omp declare reduction(aminT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \
omp_out = nd4j::math::nd4j_min(nd4j::math::nd4j_abs(omp_in), nd4j::math::nd4j_abs(omp_out)) )
#pragma omp declare reduction(asumT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \
omp_out = nd4j::math::nd4j_abs(omp_in) + nd4j::math::nd4j_abs(omp_out))\
initializer (omp_priv=0)
#pragma omp declare reduction(sumT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \
omp_out = omp_in + omp_out)\
initializer (omp_priv=0)
#pragma omp declare reduction(prodT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \
omp_out = omp_in * omp_out)\
initializer (omp_priv=1)
#endif
namespace functions {
namespace indexreduce {
template <typename T>
struct IndexValue {
T value;
Nd4jLong index;
_CUDA_HD IndexValue() = default;
_CUDA_HD IndexValue(const T val, const Nd4jLong ind): index(ind), value(val) {}
};
}
namespace summarystats {
template <typename T>
class SummaryStatsData;
}
}
namespace simdOps {
template <typename X, typename Y, typename Z>
class Add {
public:
op_def static Z op(X d1, Y d2) {
return static_cast<Z>(d1 + d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return static_cast<Z>(d1 + d2);
}
op_def static Z op(X d1) {
return static_cast<Z>(d1);
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return static_cast<Z>(d1 + params[0]);
}
op_def static X startingValue() {
return static_cast<X>(0.f);
}
};
template <typename X, typename Y>
class NewAdd {
public:
op_def static X op(X d1, Y d2, X *params) {
return d1 + d2;
}
};
template <typename X, typename Y, typename Z>
class Subtract {
public:
op_def static Z op(X d1, Y d2) {
return static_cast<Z>(d1 - d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return static_cast<Z>(d1 - d2);
}
op_def static Z op(X d1) {
return static_cast<Z>(d1);
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return static_cast<Z>(d1 - params[0]);
}
};
template <typename X, typename Y, typename Z>
class SquaredSubtract {
public:
op_def static Z op(X d1, Y d2) {
auto d = static_cast<Z>(d1 - d2);
return d * d;
}
op_def static Z op(X d1, Y d2, Z *params) {
auto d = static_cast<Z>(d1 - d2);
return d * d;
}
op_def static Z op(X d1) {
return d1;
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
auto d = static_cast<Z>(d1 - params[0]);
return d * d;
}
};
template <typename X, typename Y, typename Z>
class SquaredReverseSubtract {
public:
op_def static Z op(X d1, Y d2) {
auto d = static_cast<Z>(d2 - d1);
return d * d;
}
op_def static Z op(X d1, Y d2, Z *params) {
auto d = static_cast<Z>(d2 - d1);
return d * d;
}
op_def static Z op(X d1) {
return d1;
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
auto d = static_cast<Z>(params[0] - d1);
return d * d;
}
};
template <typename X, typename Y, typename Z>
class ReverseSubtract {
public:
op_def static Z op(X d1, Y d2) {
return static_cast<Z>(d2 - d1);
}
op_def static Z op(X d1, Y d2, Z *params) {
return static_cast<Z>(d2 - d1);
}
op_def static Z op(X d1) {
return d1;
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return static_cast<Z>(params[0] - d1);
}
};
template <typename X, typename Y, typename Z>
class LogPoissonLossFull {
public:
op_def static Z op(X z, Y c) {
auto zz = static_cast<Z>(z);
auto zc = static_cast<Z>(c);
return (nd4j::math::nd4j_exp<Y, Z>(c) - zz * zc + (zz * nd4j::math::nd4j_log<X, Z>(z) - zz + static_cast<Z>(0.5f) * nd4j::math::nd4j_log<Z, Z>(static_cast<Z>(DOUBLE_PI_X) * zz)));
}
op_def static Z op(X z, Y c, Z *params) {
auto zz = static_cast<Z>(z);
auto zc = static_cast<Z>(c);
return (nd4j::math::nd4j_exp<Y, Z>(c) - zz * zc + (zz * nd4j::math::nd4j_log<X, Z>(z) - zz + static_cast<Z>(0.5f) * nd4j::math::nd4j_log<Z, Z>(static_cast<Z>(DOUBLE_PI_X) * zz)));
}
op_def static Z op(X z) {
auto zz = static_cast<Z>(z);
return (zz * nd4j::math::nd4j_log<Y, Z>(z) - zz + static_cast<Z>(0.5f) * nd4j::math::nd4j_log<Z, Z>(static_cast<Z>(DOUBLE_PI_X) * zz));
}
// op for MetaOps
op_def static X op(X z, Y *params) {
return (nd4j::math::nd4j_exp<X, X>(params[0]) - z * params[0] + (z * nd4j::math::nd4j_log<X, Z>(z) - z + static_cast<X>(0.5f) * nd4j::math::nd4j_log<X, Z>(DOUBLE_PI_X * z)));
}
};
template <typename X, typename Y, typename Z>
class LogPoissonLoss {
public:
op_def static Z op(X z, Y c) {
auto zz = static_cast<Z>(z);
auto zc = static_cast<Z>(c);
return (nd4j::math::nd4j_exp<Y, Z>(c) - zz * zc);
}
op_def static Z op(X z, Y c, Z *params) {
auto zz = static_cast<Z>(z);
auto zc = static_cast<Z>(c);
return (nd4j::math::nd4j_exp<Y, Z>(c) - zz * zc);
}
op_def static Z op(X z) {
return static_cast<Z>(z);
}
// op for MetaOps
op_def static Z op(X z, Y *params) {
return (nd4j::math::nd4j_exp<Y, Z>(params[0]) - static_cast<Z>(z) * static_cast<Z>(params[0]));
}
};
template <typename X, typename Y, typename Z>
class Multiply {
public:
op_def static Z op(X d1, Y d2) {
return static_cast<Z>(d1 * d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return static_cast<Z>(d1 * d2);
}
op_def static Z op(X d1) {
return static_cast<Z>(d1);
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return static_cast<Z>(d1 * params[0]);
}
op_def static X startingValue() {
return static_cast<X>(1.f);
}
};
template <typename X, typename Y, typename Z>
class Divide {
public:
op_def static Z op(X d1, Y d2) {
return static_cast<Z>(d1 / d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return static_cast<Z>(d1 / d2);
}
op_def static Z op(X d1) {
return static_cast<Z>(d1);
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return static_cast<Z>(d1 / params[0]);
}
op_def static X startingValue() {
return static_cast<X>(1);
}
};
template <typename X, typename Y, typename Z>
class SafeDivide {
public:
op_def static Z op(X d1, Y d2) {
if(d2 == static_cast<Y>(0))
return static_cast<Z>(0);
return static_cast<Z>(d1 / d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
if(d2 == static_cast<Y>(0))
return static_cast<Z>(0);
return static_cast<Z>(d1 / d2);
}
op_def static Z op(X d1) {
return static_cast<Z>(d1);
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
if(params[0] == static_cast<Y>(0))
return static_cast<Z>(0);
return static_cast<Z>(d1 / params[0]);
}
};
template <typename X, typename Y, typename Z>
class FloorDiv {
public:
op_def static Z op(X d1, Y d2) {
return nd4j::math::nd4j_floor<Z,Z>(static_cast<Z>(d1 / d2));
}
op_def static Z op(X d1, Y d2, Z *params) {
return nd4j::math::nd4j_floor<Z,Z>(static_cast<Z>(d1 / d2));
}
op_def static Z op(X d1) {
return nd4j::math::nd4j_floor<Z,Z>(static_cast<Z>(d1));
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return nd4j::math::nd4j_floor<Z,Z>(static_cast<Z>(d1 / params[0]));
}
};
template <typename X, typename Y, typename Z>
class TruncateDiv {
public:
op_def static Z op(X d1, Y d2) {
auto i1 = static_cast<int>(d1);
auto i2 = static_cast<int>(d2);
return static_cast<Z>(i1 / i2);
}
op_def static Z op(X d1, Y d2, Z *params) {
auto i1 = static_cast<int>(d1);
auto i2 = static_cast<int>(d2);
return static_cast<Z>(i1 / i2);
}
op_def static Z op(X d1) {
return d1;
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
auto i1 = static_cast<int>(d1);
auto i2 = static_cast<int>(params[0]);
return static_cast<Z>(i1 / i2);
}
};
template <typename X, typename Y, typename Z>
class TruncateMod {
public:
op_def static Z op(X d1, Y d2) {
auto i1 = static_cast<int>(d1);
auto i2 = static_cast<int>(d2);
return static_cast<Z>(i1 % i2);
}
op_def static Z op(X d1, Y d2, Z *params) {
auto i1 = static_cast<int>(d1);
auto i2 = static_cast<int>(d2);
return static_cast<Z>(i1 % i2);
}
op_def static Z op(X d1) {
return static_cast<Z>(d1);
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
auto i1 = static_cast<int>(d1);
auto i2 = static_cast<int>(params[0]);
return static_cast<Z>(i1 % i2);
}
};
template<typename X, typename Y, typename Z>
class Remainder {
public:
op_def static Z op(X d1, Y d2) {
return nd4j::math::nd4j_remainder<X, Y, Z>(d1, d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return nd4j::math::nd4j_remainder<X, Y, Z>(d1, d2);
}
op_def static Z op(X d1) {
return d1;
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return nd4j::math::nd4j_remainder<X, Y, Z>(d1, params[0]);
}
};
template <typename X, typename Y, typename Z>
class FMod {
public:
op_def static Z op(X d1, Y d2) {
return nd4j::math::nd4j_fmod<X, Y, Z>(d1, d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return nd4j::math::nd4j_fmod<X, Y, Z>(d1, d2);
}
op_def static Z op(X d1) {
return d1;
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return nd4j::math::nd4j_fmod<X, Y, Z>(d1, params[0]);
}
};
template <typename X, typename Y, typename Z>
class FloorMod {
public:
op_def static Z op(X d1, Y d2) {
auto m = nd4j::math::nd4j_fmod<X, Y, Z>(d1, d2);
return (d1 < static_cast<X>(0)) == (d2 < static_cast<Y>(0)) ? m : nd4j::math::nd4j_fmod<Z, Y, Z>(m + static_cast<Z>(d2), d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
auto m = nd4j::math::nd4j_fmod<X, Y, Z>(d1, d2);
return (d1 < static_cast<X>(0.0f)) == (d2 < static_cast<Y>(0)) ? m : nd4j::math::nd4j_fmod<Z, Y, Z>(m + static_cast<Z>(d2), d2);
}
op_def static Z op(X d1) {
return d1;
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return op(d1, params[0]);
}
};
template <typename X, typename Y, typename Z>
class ReverseDivide {
public:
op_def static Z op(X d1, Y d2) {
return static_cast<Z>(d2 / d1);
}
op_def static Z op(X d1, Y d2, Z *params) {
return static_cast<Z>(d2 / d1);
}
op_def static Z op(X d1) {
return static_cast<Z>(d1);
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return static_cast<Z>(params[0] / d1);
}
};
template <typename X, typename Y, typename Z>
class CopyPws {
public:
op_def static Z op(X d1, Y d2) {
return static_cast<Z>(d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return static_cast<Z>(d2);
}
op_def static Z op(X d1) {
return static_cast<Z>(d1);
}
op_def static Z op(X d1, Y *params) {
return static_cast<Z>(d1);
}
};
template <typename X>
class Copy {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return d1;
}
};
template <typename X, typename Y, typename Z>
class Copy2 {
public:
op_def static Z op(X d1, Y d2) {
return static_cast<Z>(d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return static_cast<Z>(d2);
}
op_def static Z op(X d1) {
return static_cast<Z>(d1);
}
op_def static Z op(X d1, Y *params) {
return static_cast<Z>(d1);
}
};
template <typename X, typename Y, typename Z>
class Axpy {
public:
op_def static Z op(X d1, Y d2) {
return static_cast<Z>(d2 + d1);
}
op_def static Z op(X d1, Y d2, Z *params) {
auto alpha = params[0];
return alpha * static_cast<Z>(d1) + static_cast<Z>(d2);
}
op_def static Z op(X d1) {
return static_cast<Z>(d1);
}
};
template <typename X, typename Z>
class Assign {
public:
no_op_exec_special_any
no_op_exec_special_any_cuda
op_def static Z op(X d1, X *params) {
return static_cast<Z>(d1);
}
};
template <typename X, typename Z>
class And {
public:
no_op_exec_special_bool
no_op_exec_special_bool_cuda
op_def static Z op(X d1, X d2) {
return d2 + d1;
}
op_def static Z op(X d1, X d2, X *params) {
if (params != nullptr) {
auto comp = params[0];
return d1 != comp && d2 != comp ? static_cast<Z>(1) : static_cast<Z>(0);
} else {
auto b1 = static_cast<bool>(d1);
auto b2 = static_cast<bool>(d2);
return (b1 && b2) ? static_cast<Z>(1) : static_cast<Z>(0);
}
}
op_def static Z op(X d1) {
return d1;
}
// op for MetaOps
op_def static Z op(X d1, X *params) {
return static_cast<Z>(119);
}
};
template <typename X, typename Z>
class Or {
public:
no_op_exec_special_bool
no_op_exec_special_bool_cuda
op_def static Z op(X d1, X d2) {
return d2 + d1;
}
op_def static Z op(X d1, X d2, X *params) {
if (params != nullptr) {
auto comp = params[0];
return d1 != comp || d2 != comp ? static_cast<Z>(1) : static_cast<Z>(0);
} else {
auto b1 = static_cast<bool>(d1);
auto b2 = static_cast<bool>(d2);
return b1 || b2 ? static_cast<Z>(1) : static_cast<Z>(0);
}
}
op_def static Z op(X d1) {
return d1;
}
// op for MetaOps
op_def static Z op(X d1, X *params) {
return static_cast<Z>(119);
}
};
template <typename X, typename Z>
class Xor {
public:
no_op_exec_special_bool
no_op_exec_special_bool_cuda
op_def static Z op(X d1, X d2) {
return d2 + d1;
}
op_def static Z op(X d1, X d2, X *params) {
if (params != nullptr) {
auto comp = params[0];
return ((d1 == comp && d2 != comp) || (d1 != comp && d2 == comp)) ? static_cast<Z>(1) : static_cast<Z>(0);
} else {
auto b1 = static_cast<bool>(d1);
auto b2 = static_cast<bool>(d2);
return (!b1 && b2 )||(b1 && !b2) ? static_cast<Z>(1) : static_cast<Z>(0);
}
}
op_def static Z op(X d1) {
return d1;
}
};
template <typename X, typename Z>
class Not {
public:
no_op_exec_special_bool
no_op_exec_special_bool_cuda
op_def static Z op(X d1, X d2) {
return static_cast<Z>(0);
}
op_def static Z op(X d1, X d2, X *params) {
return d1 != d2 ? static_cast<Z>(1) : static_cast<Z>(0);
}
// this transform op should run only on boolean input
op_def static Z op(X d1, X *params) {
auto b1 = static_cast<bool>(d1);
return !b1;
}
};
template <typename X, typename Y, typename Z>
class LogicalNot {
public:
op_def static Z op(X d1, Y d2) {
return !((int) d1 && (int) d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return static_cast<X>(!(static_cast<int>(d1) && static_cast<int>(d2)));
}
op_def static Z op(X d1) {
return d1;
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return static_cast<X>(119);
}
};
template <typename X, typename Y, typename Z>
class LogicalXor {
public:
op_def static Z op(X d1, Y d2) {
auto i1 = static_cast<int>(d1);
auto i2 = static_cast<int>(d2);
return (i1 | i2) &~ (i1 & i2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return op(d1, d2);
}
op_def static Z op(X d1) {
return d1;
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return static_cast<Z>(119);
}
};
template <typename X, typename Y, typename Z>
class LogicalAnd {
public:
op_def static Z op(X d1, Y d2) {
return static_cast<int>(d1) & static_cast<int>(d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return op(d1, d2);
}
op_def static Z op(Y d1) {
return d1;
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return static_cast<Z>(119);
}
};
template <typename X, typename Y, typename Z>
class LogicalOr {
public:
op_def static Z op(X d1, Y d2) {
return static_cast<int>(d1) | static_cast<int>(d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return op(d1, d2);
}
op_def static Z op(X d1) {
return d1;
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return static_cast<X>(119);
}
};
template <typename X, typename Y, typename Z>
class Mod {
public:
/*
// just a optional note, feel free to remove later
op_def static half op(half d1, half d2, half *params) {
return __float2half(simdOps::Mod<float>::op(__half2float(d1), __half2float(d2), nullptr));
}
*/
op_def static Z op(X d1, Y d2) {
return static_cast<int>(d1) % static_cast<int>(d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return op(d1, d2);
}
// op for MetaOp
op_def static Z op(X d1, Y *params) {
return op(d1, params[0]);
}
};
template <typename X, typename Y, typename Z>
class ReverseMod {
public:
op_def static Z op(X d1, Y d2) {
return static_cast<int>(d2) % static_cast<int>(d1);
}
op_def static Z op(X d1, Y d2, Z *params) {
return op(d1, d2);
}
// op for MetaOp
op_def static Z op(X d1, Y *params) {
return op(d1, params[0]);
}
};
/**
* Whether 2 elements in an array
* are epsilion equal
*/
template <typename X, typename Z>
class Epsilon {
public:
op_def static Z op(X d1, X d2) {
X diff = d1 - d2;
X absDiff = nd4j::math::nd4j_abs<X>(diff);
if (absDiff <= static_cast<X>(MIN_V))
return static_cast<Z>(1);
return static_cast<Z>(0);
}
op_def static Z op(X d1, X d2, X *params) {
return op(d1, d2);
}
op_def static Z op(X d1, X *params) {
return d1;
}
};
template <typename X, typename Z>
class EqualTo {
public:
op_def static Z op(X d1, X d2) {
return d1 == d2;
}
op_def static Z op(X d1, X d2, X *params) {
return op(d1, d2);
}
op_def static Z op(X d1, X *params) {
return d1;
}
};
template <typename X, typename Z>
class NotEqualTo {
public:
op_def static Z op(X d1, X d2) {
return d1 != d2;
}
op_def static Z op(X d1, X d2, X *params) {
return op(d1, d2);
}
op_def static Z op(X d1, X *params) {
return d1;
}
};
template <typename X, typename Z>
class GreaterThanOrEqual {
public:
op_def static Z op(X d1, X d2) {
return d1 >= d2;
}
op_def static Z op(X d1, X d2, X *params) {
return op(d1, d2);
}
// FIXME: this signature clashes with MetaOp stuff
op_def static Z op(X d1, X *params) {
return d1;
}
};
template <typename X, typename Z>
class GreaterThan {
public:
op_def static Z op(X d1, X d2) {
return d1 > d2;
}
op_def static Z op(X d1, X d2, X *params) {
return op(d1, d2);
}
// FIXME: this signature clashes with MetaOp stuff
op_def static Z op(X d1, X *params) {
return d1;
}
};
template <typename X, typename Z>
class LessThan {
public:
op_def static Z op(X d1, X d2) {
return d1 < d2;
}
op_def static Z op(X d1, X d2, X *params) {
return op(d1, d2);
}
op_def static Z op(X d1, X *params) {
return d1;
}
};
template <typename X, typename Z>
class LessThanOrEqual {
public:
op_def static Z op(X d1, X d2) {
return d1 <= d2;
}
op_def static Z op(X d1, X d2, X *params) {
return op(d1, d2);
}
op_def static Z op(X d1, X *params) {
return d1;
}
};
template <typename X>
class Abs {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_abs<X>(d1);
}
};
template <typename X>
class Ceiling {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_ceil<X,X>(d1);
}
};
template <typename X>
class Cosine {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_cos<X,X>(d1);
}
};
template <typename X>
class Exp {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_exp<X, X>(d1);
}
};
template <typename X>
class HardTanhDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return ((d1 >= static_cast<X>(-1.f) && d1 <= static_cast<X>(1.f)) ? static_cast<X>(1.f) : static_cast<X>(0.f));
}
};
template <typename X>
class HardTanh {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
if (d1 < static_cast<X>(-1))
return static_cast<X>(-1);
else if (d1 > static_cast<X>(1))
return static_cast<X>(1);
else
return d1;
}
};
template <typename X>
class Floor {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_floor<X,X>(d1);
}
};
template <typename X>
class Log {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_log<X, X>(d1);
}
};
template <typename X>
class Log1p {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_log<X, X>(1 + d1);
}
};
template <typename X, typename Y, typename Z>
class LogX {
public:
op_def static Z op(X d1, Y d2, Z *params) {
return nd4j::math::nd4j_log<X, Z>(d1) / nd4j::math::nd4j_log<Y, Z>(d2) ;
}
};
template <typename X>
class StabilizeFP16 {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
if (d1 <= static_cast<X>(0))
return static_cast<X>(nd4j::DataTypeUtils::min<float16>());
else return d1;
}
};
template <typename X>
class StabilizeX {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
if (d1 <= static_cast<X>(0))
return nd4j::DataTypeUtils::min<X>();
else return d1;
}
};
template <typename X>
class SpecialDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return d1 * (static_cast<X>(1.f) - d1);
}
};
template <typename X>
class Neg {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return -d1;
}
};
template <typename X>
class Erf {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_erf<X,X>(d1);
}
};
template <typename X>
class Erfc {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_erfc<X,X>(d1);
}
};
template <typename X>
class Reciprocal {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
// op_def static T op(T d1) {
// return (T(1.0f) / d1);
// }
// op for MetaOps
op_def static X op(X d1, X *params) {
return (static_cast<X>(1) / d1);
}
};
template <typename X, typename Z>
class Sqr {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, Z *params) {
return nd4j::math::nd4j_pow<X, X, Z>(d1, static_cast<X>(2));
}
op_def static Z op(X d1) {
return nd4j::math::nd4j_pow<X, X, Z>(d1, static_cast<X>(2));
}
};
template <typename X, typename Y, typename Z>
class RelativeError {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, Y d2) {
return nd4j::math::nd4j_re<X>(d1, d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return op(d1, d2);
}
op_def static Z op(X d1) {
return static_cast<Z>(0);
}
};
template <typename X, typename Y, typename Z>
class BinaryRelativeError {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, Y d2, Z *params) {
X threshold = params[0];
return nd4j::math::nd4j_re<X>(d1, d2) > threshold ? static_cast<Z>(1) : static_cast<Z>(0);
}
op_def static Z op(X d1) {
return static_cast<Z>(0);
}
};
template <typename X, typename Y, typename Z>
class BinaryMinimumAbsoluteRelativeError {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, X *params) {
X d2 = params[0];
X thresholdRelative = params[1];
X thresholdAbsolute = params[2];
return nd4j::math::nd4j_re<X>(d1, d2) > thresholdRelative ? (nd4j::math::nd4j_abs<X>(d1 - static_cast<X>(d2)) < thresholdAbsolute ? static_cast<Z>(0) : static_cast<Z>(1)) : static_cast<Z>(0);
}
op_def static Z op(X d1, Y d2, Z *params) {
X thresholdRelative = params[0];
X thresholdAbsolute = params[1];
return nd4j::math::nd4j_re<X>(d1, d2) > thresholdRelative ? (nd4j::math::nd4j_abs<X>(d1 - static_cast<X>(d2)) < thresholdAbsolute ? static_cast<Z>(0) : static_cast<Z>(1)) : static_cast<Z>(0);
}
op_def static Z op(X d1) {
return static_cast<Z>(0);
}
};
template <typename X, typename Y, typename Z>
class ReversePow {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, Z *params) {
return nd4j::math::nd4j_pow<X, X, Z>(params[0], d1);
}
op_def static Z op(X d1, Y d2) {
return nd4j::math::nd4j_pow<X, Y, Z>(d2, d1);
}
op_def static Z op(X d1, Y d2, Z *params) {
return nd4j::math::nd4j_pow<X, Y, Z>(d2, d1);
}
op_def static Z op(X d1) {
return d1;
}
};
template <typename X, typename Y, typename Z>
class Pow {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, Z *params) {
return nd4j::math::nd4j_pow<X, X, Z>(d1, params[0]);
}
op_def static Z op(X d1, Y d2) {
return nd4j::math::nd4j_pow<X, Y, Z>(d1, d2);
}
op_def static Z op(X d1, Y d2, Z *params) {
return nd4j::math::nd4j_pow<X, Y, Z>(d1, d2);
}
op_def static Z op(X d1) {
return d1;
}
};
template <typename X, typename Y, typename Z>
class PowDerivative {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, Z *params) {
return params[0] * nd4j::math::nd4j_pow<X, Z, Z>(d1, static_cast<Z>(params[0]) - static_cast<Z>(1.f));
}
op_def static Z op(X d1, Y d2) {
return static_cast<Z>(d2) * nd4j::math::nd4j_pow<X, Z, Z>(d1, static_cast<Z>(d2) - static_cast<Z>(1.f));
}
op_def static Z op(X d1, Y d2, Z *params) {
return static_cast<Z>(d2) * nd4j::math::nd4j_pow<X, Z, Z>(d1, static_cast<Z>(d2) - static_cast<Z>(1.f));
}
op_def static Z op(X d1) {
return d1;
}
};
template <typename X>
class Round {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_round<X,X>(d1);
}
};
template <typename X, typename Z>
class IsNan {
public:
no_op_exec_special_bool
no_op_exec_special_bool_cuda
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static Z op(X d1, X *params) {
return nd4j::math::nd4j_isnan(d1) ? static_cast<X>(1) : static_cast<X>(0);
}
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z update(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) {
return reduction;
}
};
template <typename X>
class Expm1 {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_exp<X, X>(d1) - static_cast<X>(1);
}
};
template <typename X, typename Z>
class IsPositive {
public:
no_op_exec_special_bool
no_op_exec_special_bool_cuda
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static Z op(X d1, X *params) {
return d1 > (X)0.f;
}
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z update(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) {
return reduction;
}
};
template <typename X, typename Z>
class IsInf {
public:
no_op_exec_special_bool
no_op_exec_special_bool_cuda
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static Z op(X d1, X *params) {
return nd4j::math::nd4j_isinf<X>(d1) ? static_cast<Z>(1) : static_cast<Z>(0);
}
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z update(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) {
return reduction;
}
};
template <typename X, typename Z>
class IsInfOrNan{
public:
no_op_exec_special_bool
no_op_exec_special_bool_cuda
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static Z op(X d1, X *params) {
return nd4j::math::nd4j_isfin<X>(d1) ? static_cast<Z>(0) : static_cast<Z>(1);
}
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z update(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) {
return reduction;
}
};
template <typename X, typename Z>
class IsFinite {
public:
no_op_exec_special_bool
no_op_exec_special_bool_cuda
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
op_def static Z op(X d1, X *params) {
return nd4j::math::nd4j_isfin<X>(d1) ? static_cast<Z>(1) : static_cast<Z>(0);
}
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z update(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) {
return reduction;
}
};
template <typename X>
class ClipByValue {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
if (d1 > params[1])
return params[1];
if (d1 < params[0])
return params[0];
return d1;
}
};
template <typename X, typename Y, typename Z>
class LstmClip {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, Y d2, Z *params) {
X _v = (X) d2;
if (d1 > _v)
return _v;
else if (d1 < -_v)
return -_v;
else return d1;
}
};
template <typename X>
class Swish {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return d1 * nd4j::math::nd4j_sigmoid<X,X>(d1);
}
};
template <typename X>
class GELU {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return d1 * nd4j::math::nd4j_sigmoid<X,X>(static_cast<X>(1.702f) * d1);
}
};
template <typename X>
class PreciseGELU {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
auto sp = nd4j::math::nd4j_sqrt<X, X>(static_cast<X>(2) / static_cast<X>(M_PI));
auto xp = d1 + nd4j::math::nd4j_pow<X, X, X>(static_cast<X>(0.044715) * d1, static_cast<X>(3));
return (d1 / static_cast<X>(2)) * (static_cast<X>(1) + nd4j::math::nd4j_tanh<X, X>(sp * xp));
}
};
template <typename X>
class GELUDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
auto x17 = static_cast<X>(1.702f) * d1;
auto ep = nd4j::math::nd4j_pow<X,X,X>(static_cast<X>(M_E), x17);
// (E^(1.702 x) (1. + E^(1.702 x) + 1.702 x))/(1. + E^(1.702 x))^2
return (ep * (static_cast<X>(1.f) + ep + x17)) / nd4j::math::nd4j_pow<X, int, X>((static_cast<X>(1.f) + ep), 2);
}
};
template <typename X>
class PreciseGELUDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
auto x79 = static_cast<X>(0.797885) * d1;
auto x03 = nd4j::math::nd4j_pow<X, int, X>(static_cast<X>(0.0356774) * d1, 3);
auto x39 = static_cast<X>(0.398942) * d1;
auto x05 = nd4j::math::nd4j_pow<X, int, X>(static_cast<X>(0.0535161) * d1, 3);
auto scz = nd4j::math::nd4j_sech<X, X>(x79 + x03);
// 0.5 + (0.398942 x + 0.0535161 x^3) Sech[0.797885 x + 0.0356774 x^3]^2 + 0.5 Tanh[0.797885 x + 0.0356774 x^3]
return static_cast<X>(0.5) + (x39 + x05) * (scz * scz) + static_cast<X>(0.5) * nd4j::math::nd4j_tanh<X, X>(x79 + x03);
}
};
template <typename X>
class SwishDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
X ex = nd4j::math::nd4j_pow<X, X, X>(static_cast<X>(M_E), d1);
return (ex * (d1 + ex + static_cast<X>(1.f))) / nd4j::math::nd4j_pow<X, X, X>((ex + static_cast<X>(1.f)) , static_cast<X>(2.f));
}
};
template <typename X>
class LogSigmoid {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_log<X, X>(nd4j::math::nd4j_sigmoid<X, X>(d1));
}
};
template <typename X>
class LogSigmoidDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
X ex = nd4j::math::nd4j_pow<X, X, X>(M_E, d1);
return static_cast<X>(1.f) / (ex + static_cast<X>(1.f));
}
};
template <typename X>
class Sigmoid {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_sigmoid<X, X>(d1);
}
};
template <typename X>
class SigmoidDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_sigmoidderivative<X, X>(d1);
}
};
template <typename X>
class HardSigmoid {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_min<X>(static_cast<X>(1), nd4j::math::nd4j_max<X>(static_cast<X>(0), (static_cast<X>(0.2f)) * d1 + static_cast<X>(0.5f)));
}
};
template <typename X>
class HardSigmoidDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return d1 < static_cast<X>(-2.5f) || d1 > static_cast<X>(2.5f) ? static_cast<X>(0.f) : static_cast<X>(0.2f);
}
};
/**
* Scale to be between a min and max
*/
template <typename X>
class SetRange {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
auto min = params[0];
auto max = params[1];
if (static_cast<X>(d1) >= min && static_cast<X>(d1) <= max)
return d1;
if (min == static_cast<X>(0) && max == static_cast<X>(1)) {
auto val = static_cast<X>(1) / (static_cast<X>(1) + nd4j::math::nd4j_exp<X, X>(-d1));
return (nd4j::math::nd4j_floor<X,X>(val * (max - min)) + min);
}
return (nd4j::math::nd4j_floor<X,X>(d1 * (max - min)) + min);
}
};
template <typename X>
class Sin {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_sin<X,X>(d1);
}
};
template <typename X>
class Square {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return d1 * d1;
}
};
template <typename X, typename Z>
class Sqrt {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, Z *params) {
return nd4j::math::nd4j_sqrt<X, Z>(d1);
}
};
template <typename X, typename Z>
class RSqrt {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, Z *params) {
return static_cast<Z>(1) / nd4j::math::nd4j_sqrt<X, Z>(d1);
}
};
template <typename X>
class Rint {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_rint<X,X>(d1);
}
};
template <typename X>
class SoftPlus {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::softplus<X, X>(d1);
}
};
template <typename X>
class Sign {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return (d1 > static_cast<X>(0)) - (d1 < static_cast<X>(0));
}
};
template <typename X>
class TimesOneMinus {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return d1 * (static_cast<X>(1) - d1);
}
};
template <typename X>
class RationalTanh {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
// keep 2/3 as runtime variable, to match precision
auto dis = (static_cast<X>(2) / static_cast<X>(3)) * d1;
auto tanh = nd4j::math::nd4j_sgn<X,X>(dis) * (static_cast<X>(1) - (static_cast<X>(1) / (static_cast<X>(1) + static_cast<X>(nd4j::math::nd4j_abs<X>(dis)) + nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(2)) + static_cast<X>(1.41645f) * nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(4)) )));
return static_cast<X>(1.7159f) * tanh;
}
};
template <typename X>
class RationalTanhDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
auto dis = (static_cast<X>(2.f) / static_cast<X>(3.f)) * d1;
auto a = static_cast<X>(1.f) + nd4j::math::nd4j_abs<X>(dis) + nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(2.f)) + static_cast<X>(1.41645f) * nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(4));
auto tDeriv = (static_cast<X>(1.f) + nd4j::math::nd4j_sign<X,X>(dis) * (static_cast<X>(2.f) * dis + static_cast<X>(4.f) * static_cast<X>(1.41645f) * nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(3)))) / (a * a);
return static_cast<X>(1.7159f) * (static_cast<X>(2.f) / static_cast<X>(3.f)) * tDeriv;
}
};
template <typename X>
class Tanh {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_tanh<X, X>(d1);
}
};
template <typename X>
class RectifiedTanh {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_max<X>(static_cast<X>(0), nd4j::math::nd4j_tanh<X,X>(d1));
}
};
template <typename X>
class RectifiedTanhDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return d1 > static_cast<X>(0.f) ? nd4j::math::nd4j_tanhderivative<X,X>(d1) : static_cast<X>(0.f);
}
};
template <typename X>
class ATanh {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_atanh<X,X>(d1);
}
};
template <typename X>
class TanhDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_tanhderivative<X,X>(d1);
}
};
template <typename X>
class Cube {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return d1 * d1 * d1;
}
};
template <typename X>
class CubeDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return static_cast<X>(3) * d1 * d1;
}
};
template <typename X>
class ACos {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_acos<X, X>(d1);
}
};
template <typename X>
class ASinh {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_asinh<X, X>(d1);
}
};
template <typename X>
class ASinhDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return static_cast<X>(1.f) / (nd4j::math::nd4j_sqrt<X, X>(nd4j::math::nd4j_pow<X, X, X>(d1, static_cast<X>(2.f)) + static_cast<X>(1.f)));
}
};
template <typename X>
class ACosh {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_acosh<X, X>(d1);
}
};
template <typename X>
class ACoshDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return static_cast<X>(1.f) / (nd4j::math::nd4j_sqrt<X, X>(d1 - static_cast<X>(1.f)) * nd4j::math::nd4j_sqrt<X, X>(d1 + static_cast<X>(1.f)));
}
};
template <typename X>
class Ones {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return static_cast<X>(1.0f);
}
};
template <typename X>
class SoftSign {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_softsign<X, X>(d1);
}
};
template <typename X>
class SoftSignDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_softsignderivative<X,X>(d1);
}
};
template <typename X, typename Z>
class MatchConditionBool {
public:
no_op_exec_special_bool
no_op_exec_special_bool_cuda
// this op return 1.0 if condition met, 0.0 otherwise
op_def static Z op(X d1, X *extraParams) {
X compare = extraParams[0];
X eps = extraParams[1];
auto mode = static_cast<int>(extraParams[2]);
//nd4j_printf("value: %f; comp: %f; eps: %f; mode: %i;\n", d1, compare, eps, mode);
switch (mode) {
case 0: // equals
return nd4j::math::nd4j_abs<X>(d1 - compare) <= eps ? true : false;
case 1: // not equals
return nd4j::math::nd4j_abs<X>(d1 - compare) > eps ? true : false;
case 2: // less_than
return d1 < compare ? true : false;
case 3: // greater_than
return d1 > compare ? true : false;
case 4: // less_or_equals_than
return d1 <= compare ? true : false;
case 5: // greater_or_equals_than
return d1 >= compare ? true : false;
case 6: // abs_less_than
return nd4j::math::nd4j_abs<X>(d1) < compare ? true : false;
case 7: // abs_greater_than
return nd4j::math::nd4j_abs<X>(d1) > compare ? true : false;
case 8: // is inf
return nd4j::math::nd4j_isinf(d1) ? true : false;
case 9: // is nan
return nd4j::math::nd4j_isnan(d1) ? true : false;
case 10:
return (d1 == compare) ? true : false;
case 11:
return (d1 != compare) ? true : false;
case 12: // abs_greater_or_equals_than
return nd4j::math::nd4j_abs<X>(d1) >= compare ? true : false;
case 13: // abs_less_or_equals_than
return nd4j::math::nd4j_abs<X>(d1) <= compare ? true : false;
case 14:
// isFinite
return !(nd4j::math::nd4j_isinf(d1) || nd4j::math::nd4j_isnan(d1));
case 15:
// isInfinite
return nd4j::math::nd4j_isinf(d1) || nd4j::math::nd4j_isnan(d1);
default:
printf("Undefined match condition: [%i]\n", mode);
}
return d1;
}
};
template <typename X, typename Z>
class MatchCondition {
public:
no_op_exec_special
no_op_exec_special_cuda
no_op_exec_special_accumulation_long
no_op_exec_special_accumulation_cuda
op_def static Z startingValue(const X *input) {
return static_cast<Z>(0);
}
op_def static Z merge(Z old, Z opOutput, X *extraParams) {
return old + opOutput;
}
op_def static Z update(Z old, Z opOutput, X *extraParams) {
return old + opOutput;
}
// this op return 1.0 if condition met, 0.0 otherwise
op_def static Z op(X d1, X *extraParams) {
X compare = extraParams[0];
X eps = extraParams[1];
auto mode = static_cast<int>(extraParams[2]);
//printf("value: %f; comp: %f; eps: %f; mode: %i;\n", (float) d1, (float) compare, (float) eps, mode);
switch (mode) {
case 0: // equals
return nd4j::math::nd4j_abs<X>(d1 - compare) <= eps ? 1 : 0;
case 1: // not equals
return nd4j::math::nd4j_abs<X>(d1 - compare) > eps ? 1 : 0;
case 2: // less_than
return d1 < compare ? 1 : 0;
case 3: // greater_than
return d1 > compare ? 1 : 0;
case 4: // less_or_equals_than
return d1 <= compare ? 1 : 0;
case 5: // greater_or_equals_than
return d1 >= compare ? 1 : 0;
case 6: // abs_less_than
return nd4j::math::nd4j_abs<X>(d1) < compare ? 1 : 0;
case 7: // abs_greater_than
return nd4j::math::nd4j_abs<X>(d1) > compare ? 1 : 0;
case 8: // is inf
return nd4j::math::nd4j_isinf(d1) ? 1 : 0;
case 9: // is nan
return nd4j::math::nd4j_isnan(d1) ? 1 : 0;
case 10:
return (d1 == compare) ? 1 : 0;
case 11:
return (d1 != compare) ? 1 : 0;
case 12: // abs_greater_or_equals_than
return nd4j::math::nd4j_abs<X>(d1) >= compare ? 1 : 0;
case 13: // abs_less_or_equals_than
return nd4j::math::nd4j_abs<X>(d1) <= compare ? 1 : 0;
case 14:
// isFinite
return !(nd4j::math::nd4j_isinf(d1) || nd4j::math::nd4j_isnan(d1)) ? 1 : 0;
case 15:
// isInfinite
return nd4j::math::nd4j_isinf(d1) || nd4j::math::nd4j_isnan(d1) ? 1 : 0;
default:
printf("Undefined match condition: [%i]\n", mode);
}
return d1;
}
op_def static Z postProcess(Z reduction, Nd4jLong n, X *extraParams) {
return reduction;
}
};
template <typename X>
class ELU {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_elu<X,X>(d1);
}
};
template <typename X>
class ELUDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_eluderivative<X,X>(d1);
}
};
template <typename X, typename Y, typename Z>
class RELU {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static Z op(X d1, Y d2, Z *params) {
auto xt = static_cast<Z>(d1);
auto xf = static_cast<Z>(d2);
return xt < xf ? xf : xt;
}
};
template <typename X, typename Y, typename Z>
class SXELogitsSmoother {
public:
op_def static Z op(X d1, Y d2, Z *params) {
return d1 * ((X)1.f - (X) d2) + (X)(0.5f) * (X) d2;
}
};
template <typename X, typename Y, typename Z>
class RELU6 {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static Z op(X d1, Y d2, Z *params) {
auto relu = simdOps::RELU<X,Y,Z>::op(d1, d2, params);
return relu < static_cast<Z>(6) ? relu : static_cast<Z>(6);
}
};
template <typename X, typename Y, typename Z>
class LeakyRELU {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, Y d2, Z *params) {
auto val = static_cast<Z>(d1);
auto alpha = static_cast<Z>(d2);
return val < 0.0f ? alpha * val : val;
}
};
template <typename X>
class SELU {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return d1 > static_cast<X>(0.0f) ? static_cast<X>(SELU_LAMBDA) * static_cast<X>(d1) : static_cast<X>(SELU_LAMBDA) * (static_cast<X>(SELU_ALPHA) * nd4j::math::nd4j_exp<X, X>(d1) - static_cast<X>(SELU_ALPHA));
}
};
template <typename X>
class SELUDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return d1 > static_cast<X>(0.f) ? static_cast<X>(SELU_LAMBDA) : static_cast<X>(SELU_ALPHA) * static_cast<X>(SELU_LAMBDA) * nd4j::math::nd4j_exp<X, X>(d1);
}
};
template <typename X, typename Y, typename Z>
class LeakyRELUDerivative {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, Y d2, Z *params) {
if (d1 >= static_cast<X>(0))
return static_cast<Z>(1);
else
return static_cast<Z>(d2);
}
};
template <typename X>
class ASin {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_asin<X,X>(d1);
}
};
template <typename X>
class Sinh {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_sinh<X,X>(d1);
}
};
template <typename X>
class SinhDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_cosh<X, X>(d1);
}
};
template <typename X>
class Cosh {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_cosh<X,X>(d1);
}
};
template <typename X>
class Tan {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_tan<X,X>(d1);
}
};
template <typename X>
class TanDerivative {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return static_cast<X>(1.f) / nd4j::math::nd4j_pow<X, X, X>(nd4j::math::nd4j_cos<X, X>(d1), static_cast<X>(2.0f));
}
};
template <typename X>
class ATan {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return nd4j::math::nd4j_atan<X, X>(d1);
}
};
template <typename X, typename Y, typename Z>
class Atan2 {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, Y d2) {
return nd4j::math::nd4j_atan2<X, Z>(d2, d1);
}
op_def static Z op(X d1, Y d2, Z *params) {
return op(d1, d2);
}
// op for MetaOps
op_def static Z op(X d1, Y *params) {
return op(d1, params[0]);
}
};
template <typename X>
class Identity {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return d1;
}
};
template <typename X>
class Stabilize {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
X k = params[0];
if (d1 * k > static_cast<X>(- MIN_CUTFOFF))
return static_cast<X>(- MIN_CUTFOFF) / k;
else if (d1 * k < static_cast<X>(MIN_CUTFOFF))
return static_cast<X>(MIN_CUTFOFF) / k;
return d1;
}
};
template <typename X, typename Y, typename Z>
class Step {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static Z op(X d1, Y d2, Z *params) {
return (d1 > static_cast<X>(d2) ? static_cast<Z>(1) : static_cast<Z>(0));
}
};
template <typename X>
class OneMinus {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
op_def static X op(X d1, X *params) {
return static_cast<X>(1) - d1;
}
};
template <typename X>
class Sum {
public:
no_op_exec_special_accumulation_same
no_op_exec_special_accumulation_same_cuda
op_def static X startingValue(const X *input) {
return static_cast<X>(0.0f);
}
op_def static X merge(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static X update(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static X op(X d1, X *extraParams) {
return d1;
}
op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) {
return reduction;
}
};
template <typename X>
class ReduceSameBenchmarkOp {
public:
no_op_exec_special_accumulation_same
no_op_exec_special_accumulation_same_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0.0f);
}
op_def static X merge(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static X update(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static X op(X d1, X *extraParams) {
auto f1 = static_cast<float>(d1);
return static_cast<X>(nd4j::math::nd4j_pow<float,float,float>(f1, 3)
+ nd4j::math::nd4j_log<float,float>(f1) * nd4j::math::nd4j_sin<float,float>(f1)
/ nd4j::math::nd4j_tanh<float,float>(static_cast<float>(M_E) * static_cast<float>(M_PI) * f1)
* nd4j::math::nd4j_sqrt<float,float>(static_cast<float>(M_PI) / f1)
- nd4j::math::nd4j_atan<float,float>(static_cast<float>(M_E) / f1));
}
op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) {
return reduction;
}
};
template <typename X, typename Z>
class ShannonEntropy {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z update(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z op(X d1, Z *extraParams) {
auto p = d1 * d1;
return static_cast<Z>(p) * nd4j::math::nd4j_log<X, Z>(p);
}
op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) {
return -reduction;
}
};
template <typename X, typename Z>
class LogEntropy {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z update(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z op(X d1, Z *extraParams) {
return static_cast<Z>(d1) * nd4j::math::nd4j_log<X, Z>(d1);
}
op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) {
//entropy is -sum(p(x) * log(p(x))); log entropy is log of this
return nd4j::math::nd4j_log<Z, Z>(-reduction);
}
};
template <typename X, typename Z>
class Entropy {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z update(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z op(X d1, Z *extraParams) {
return static_cast<Z>(d1) * nd4j::math::nd4j_log<X, Z>(d1);
}
op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) {
return static_cast<Z>(-reduction); //entropy is -sum(p(x) * log(p(x)))
}
};
template <typename X>
class ASum {
public:
no_op_exec_special_accumulation_same
no_op_exec_special_accumulation_same_cuda
const static functions::ReduceType reduceType = functions::ReduceType::ASUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static X merge(X old, X opOutput, X *extraParams) {
return nd4j::math::nd4j_abs<X>(opOutput) + nd4j::math::nd4j_abs<X>(old);
}
op_def static X update(X old, X opOutput, X *extraParams) {
return nd4j::math::nd4j_abs<X>(opOutput) + nd4j::math::nd4j_abs<X>(old);
}
op_def static X op(X d1, X *extraParams) {
return nd4j::math::nd4j_abs<X>(d1);
}
op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) {
return nd4j::math::nd4j_abs<X>(reduction);
}
};
template <typename X, typename Z>
class CountNonZero {
public:
no_op_exec_special_accumulation_long
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::ASUM;
op_def static Z startingValue(const X *input) {
return static_cast<Z>(0);
}
op_def static Z merge(Z old, Z opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z update(Z old, Z opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z op(X d1, X *extraParams) {
return d1 == static_cast<X>(0.0f) ? static_cast<Z>(0.0f) : static_cast<Z>(1.0f);
}
op_def static Z postProcess(Z reduction, Nd4jLong n, X *extraParams) {
return reduction;
}
};
template <typename X, typename Z>
class CountZero {
public:
no_op_exec_special_accumulation_long
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static Z startingValue(const X *input) {
return static_cast<Z>(0.0f);
}
op_def static Z merge(Z old, Z opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z update(Z old, Z opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z op(X d1, X *extraParams) {
return d1 == static_cast<X>(0) ? static_cast<X>(1) : static_cast<X>(0);
}
op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) {
return static_cast<Z>(reduction);
}
};
template <typename X>
class Prod {
public:
no_op_exec_special_accumulation_same
no_op_exec_special_accumulation_same_cuda
const static functions::ReduceType reduceType = functions::ReduceType::PRODUCT;
op_def static X startingValue(const X *input) {
return static_cast<X>(1);
}
op_def static X merge(X old, X opOutput, X *extraParams) {
return opOutput * old;
}
op_def static X update(X old, X opOutput, X *extraParams) {
return opOutput * old;
}
op_def static X op(X d1, X *extraParams) {
return d1;
}
op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) {
return reduction;
}
};
template <typename X, typename Z>
class Any {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0.0f);
}
op_def static Z merge(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z update(X old, X opOutput, X *extraParams) {
return opOutput + old;
}
op_def static Z op(X d1, X *extraParams) {
return d1;
}
op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) {
return reduction > static_cast<X>(0) ? static_cast<Z>(1) : static_cast<Z>(0) ;
}
};
template <typename X, typename Z>
class All {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::PRODUCT;
op_def static X startingValue(const X *input) {
return static_cast<X>(1);
}
op_def static Z merge(X old, X opOutput, X *extraParams) {
return opOutput * old;
}
op_def static Z update(X old, X opOutput, X *extraParams) {
return opOutput * old;
}
op_def static Z op(X d1, X *extraParams) {
return d1;
}
op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) {
return reduction > static_cast<X>(0) ? static_cast<Z>(1) : static_cast<Z>(0);
}
};
template <typename X, typename Z>
class Mean {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z update(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z op(X d1, Z *extraParams) {
return d1;
}
op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) {
return reduction / (Z) n;
}
};
template <typename X, typename Z>
class ReduceFloatBenchmarkOp {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z update(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z op(X d1, Z *extraParams) {
auto f1 = static_cast<float>(d1);
return static_cast<Z>(nd4j::math::nd4j_pow<float,float,float>(f1, 3)
+ nd4j::math::nd4j_log<float,float>(f1) * nd4j::math::nd4j_sin<float,float>(f1)
/ nd4j::math::nd4j_tanh<float,float>(static_cast<float>(M_E) * static_cast<float>(M_PI) * f1)
* nd4j::math::nd4j_sqrt<float,float>(static_cast<float>(M_PI) / f1)
- nd4j::math::nd4j_atan<float,float>(static_cast<float>(M_E) / f1));
}
op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) {
return (Z) reduction / (Z) n;
}
};
template <typename X, typename Z>
class AMean {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(Z old, Z opOutput, Z *extraParams) {
return nd4j::math::nd4j_abs<X>(opOutput) + nd4j::math::nd4j_abs<X>(old);
}
op_def static Z update(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z op(X d1, Z *extraParams) {
return nd4j::math::nd4j_abs<X>(d1);
}
op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) {
return nd4j::math::nd4j_abs<Z>(reduction) / static_cast<Z>(n);
}
};
template <typename X>
class Max {
public:
no_op_exec_special_accumulation_same
no_op_exec_special_accumulation_same_cuda
const static functions::ReduceType reduceType = functions::ReduceType::MAX;
op_def static X startingValue(const X *input) {
return input[0];
}
op_def static X merge(X old, X opOutput, X *extraParams) {
return nd4j::math::nd4j_max<X>(old, opOutput);
}
op_def static X update(X old, X opOutput, X *extraParams) {
return nd4j::math::nd4j_max<X>(opOutput, old);
}
op_def static X op(X d1, X d2, X *params) {
return nd4j::math::nd4j_max<X>(d1, d2);
}
op_def static X op(X d1, X d2) {
return nd4j::math::nd4j_max<X>(d1, d2);
}
// FIXME: this signature overlaps with MetaOp
op_def static X op(X d1, X *extraParams) {
return d1;
}
op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) {
return reduction;
}
};
template <typename X, typename Y, typename Z>
class AMaxPairwise {
public:
op_def static Z op(X d1, Y d2, Z *params) {
return op(d1, d2);
}
op_def static Z op(X d1, Y d2) {
auto z1 = static_cast<Z>(d1);
auto z2 = static_cast<Z>(d2);
if (nd4j::math::nd4j_abs<Z>(z1) > nd4j::math::nd4j_abs<Z>(z2))
return z1;
else
return z2;
}
};
template <typename X, typename Y, typename Z>
class AMinPairwise {
public:
op_def static Z op(X d1, Y d2, Z *params) {
return op(d1, d2);
}
op_def static Z op(X d1, Y d2) {
auto z1 = static_cast<Z>(d1);
auto z2 = static_cast<Z>(d2);
if (nd4j::math::nd4j_abs<Z>(z1) < nd4j::math::nd4j_abs<Z>(z2))
return z1;
else
return z2;
}
};
template <typename X, typename Y, typename Z>
class MaxPairwise {
public:
op_def static Z op(X d1, Y d2, Z *params) {
return nd4j::math::nd4j_max<Z>(static_cast<Z>(d1), static_cast<Z>(d2));
}
op_def static Z op(X d1, Y d2) {
return nd4j::math::nd4j_max<Z>(static_cast<Z>(d1), static_cast<Z>(d2));
}
};
template <typename X, typename Y, typename Z>
class MinPairwise {
public:
op_def static Z op(X d1, Y d2, Z *params) {
return nd4j::math::nd4j_min<Z>(static_cast<Z>(d1), static_cast<Z>(d2));
}
op_def static Z op(X d1, Y d2) {
return nd4j::math::nd4j_min<Z>(static_cast<Z>(d1), static_cast<Z>(d2));
}
};
template <typename X>
class AMax {
public:
no_op_exec_special_accumulation_same
no_op_exec_special_accumulation_same_cuda
const static functions::ReduceType reduceType = functions::ReduceType::AMAX;
op_def static X startingValue(const X *input) {
return input[0];
}
op_def static X merge(X old, X opOutput, X *extraParams) {
return nd4j::math::nd4j_max<X>(nd4j::math::nd4j_abs<X>(old), nd4j::math::nd4j_abs<X>(opOutput));
}
op_def static X update(X old, X opOutput, X *extraParams) {
return nd4j::math::nd4j_max<X>(nd4j::math::nd4j_abs<X>(opOutput), nd4j::math::nd4j_abs<X>(old));
}
op_def static X op(X d1, X d2, X *params) {
return nd4j::math::nd4j_max<X>(nd4j::math::nd4j_abs<X>(d1), nd4j::math::nd4j_abs<X>(d2));
}
op_def static X op(X d1, X d2) {
return nd4j::math::nd4j_abs<X>(d1) > nd4j::math::nd4j_abs<X>(d2) ? d1 : d2;
}
// FIXME: this signature overlaps with MetaOp
op_def static X op(X d1, X *extraParams) {
return nd4j::math::nd4j_abs<X>(d1);
}
op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) {
return nd4j::math::nd4j_abs<X>(reduction);
}
};
template <typename X>
class AMin {
public:
no_op_exec_special_accumulation_same
no_op_exec_special_accumulation_same_cuda
const static functions::ReduceType reduceType = functions::ReduceType::AMIN;
op_def static X startingValue(const X *input) {
return input[0];
}
op_def static X merge(X old, X opOutput, X *extraParams) {
return nd4j::math::nd4j_min<X>(nd4j::math::nd4j_abs<X>(old), nd4j::math::nd4j_abs<X>(opOutput));
}
op_def static X update(X old, X opOutput, X *extraParams) {
return nd4j::math::nd4j_min<X>(nd4j::math::nd4j_abs<X>(opOutput), nd4j::math::nd4j_abs<X>(old));
}
op_def static X op(X d1, X d2, X *params) {
return nd4j::math::nd4j_min<X>(nd4j::math::nd4j_abs<X>(d1), nd4j::math::nd4j_abs<X>(d2));
}
op_def static X op(X d1, X d2) {
return nd4j::math::nd4j_min<X>(nd4j::math::nd4j_abs<X>(d1), nd4j::math::nd4j_abs<X>(d2));
}
// FIXME: this signature overlaps with MetaOp
op_def static X op(X d1, X *extraParams) {
return nd4j::math::nd4j_abs<X>(d1);
}
op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) {
return nd4j::math::nd4j_abs<X>(reduction);
}
};
template <typename X>
class Min {
public:
no_op_exec_special_accumulation_same
no_op_exec_special_accumulation_same_cuda
const static functions::ReduceType reduceType = functions::ReduceType::MIN;
op_def static X startingValue(const X *input) {
return input[0];
}
op_def static X merge(X old, X opOutput, X *extraParams) {
return nd4j::math::nd4j_min<X>(old, opOutput);
}
op_def static X update(X old, X opOutput, X *extraParams) {
return nd4j::math::nd4j_min<X>(opOutput, old);
}
op_def static X op(X d1, X d2, X *params) {
return nd4j::math::nd4j_min<X>(d1, d2);
}
op_def static X op(X d1, X d2) {
return nd4j::math::nd4j_min<X>(d1, d2);
}
// FIXME: this signature overlaps with MetaOp
op_def static X op(X d1, X *extraParams) {
return d1;
}
op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) {
return reduction;
}
};
template <typename X, typename Z>
class Norm1 {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z update(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z op(X d1, Z *extraParams) {
return static_cast<Z>(nd4j::math::nd4j_abs<X>(d1));
}
op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) {
return reduction;
}
};
template <typename X, typename Z>
class Norm2 {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z update(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) {
return nd4j::math::nd4j_sqrt<Z, Z>(reduction);
}
op_def static Z op(X d1, Z *extraParams) {
return static_cast<Z>(d1 * d1);
}
};
template <typename X, typename Z>
class SquaredNorm {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z update(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z op(X d1, Z *extraParams) {
return static_cast<Z>(d1 * d1);
}
op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) {
return reduction;
}
};
template <typename X, typename Z>
class NormFrobenius {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z update(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z op(X d1, Z *extraParams) {
X v = nd4j::math::nd4j_abs<X>(d1);
return static_cast<Z>(v * v);
}
op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) {
return nd4j::math::nd4j_sqrt<Z, Z>(reduction);
}
};
template <typename X, typename Z>
class NormP {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z update(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z op(X d1, Z *extraParams) {
return nd4j::math::nd4j_pow<X, Z, Z>(nd4j::math::nd4j_abs<X>(d1), extraParams[0]);
}
op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) {
return nd4j::math::nd4j_pow<Z, Z, Z>(reduction, static_cast<Z>(1.0f) / extraParams[0]);
}
};
template <typename X, typename Z>
class NormMax {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0);
}
op_def static Z merge(Z old, Z opOutput, Z *extraParams) {
return opOutput + old;
}
op_def static Z update(Z old, Z opOutput, Z *extraParams) {
return nd4j::math::nd4j_max<Z>(nd4j::math::nd4j_abs<Z>(old),
nd4j::math::nd4j_abs<Z>(opOutput));
}
op_def static Z op(X d1, Z *extraParams) {
return static_cast<Z>(d1);
}
op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) {
return nd4j::math::nd4j_max<Z>(nd4j::math::nd4j_abs<Z>(reduction), nd4j::math::nd4j_abs<Z>(reduction));
}
};
template <typename X, typename Z>
class Variance {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0.0f);
}
op_def static Z merge(X old, X opOutput, Z *extraParams) {
return old + opOutput;
}
op_def static Z update(X old, X opOutput, Z *extraParams) {
return old + opOutput;
}
op_def static X op(X d1, Z *extraParams) {
X mean = static_cast<X>(extraParams[0]);
X ret = d1 - mean;
return ret * ret;
}
op_def static Z postProcess(X reduction, Nd4jLong n, Z *extraParams) {
// T bias = extraParams[1];
// return (reduction - (nd4j::math::nd4j_pow<T>(bias, static_cast<T>(2.0f)) / static_cast<T>(n))) / (n - 1)
return static_cast<Z>(reduction) / static_cast<Z>(n - 1);
}
};
/**
* Standard deviation of a buffer
*/
template <typename X, typename Z>
class StandardDeviation {
public:
no_op_exec_special_accumulation
no_op_exec_special_accumulation_cuda
const static functions::ReduceType reduceType = functions::ReduceType::SUM;
op_def static X startingValue(const X *input) {
return static_cast<X>(0.0f);
}
op_def static Z merge(X old, X opOutput, Z *extraParams) {
return old + opOutput;
}
op_def static Z update(X old, X opOutput, Z *extraParams) {
return old + opOutput;
}
op_def static Z op(X d1, Z *extraParams) {
X mean = extraParams[0];
X ret = d1 - mean;
return ret * ret;
}
op_def static Z postProcess(X reduction, Nd4jLong n, Z *extraParams) {
Z ret = Variance<X,Z>::postProcess(reduction, n, extraParams);
Z sqrtRet = nd4j::math::nd4j_sqrt<X, Z>(ret);
return sqrtRet;
}
};
template <typename X, typename Y>
class CosineSimilarity {
public:
static const int extraParamsLen = 2;
op_def static X *generateExtraParams() {
//T *extraParams = new T[2];
return nullptr;
}
op_def static void finalizeExtraParams(X *extraParams) {
//delete[] extraParams;
}
op_def static Y startingValue(const X *input) {
return static_cast<Y>(0.0f);
}
op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParams) {
return reduction / (nd4j::math::nd4j_sqrt<Y, Y>(extraParams[0]) * nd4j::math::nd4j_sqrt<Y, Y>(extraParams[1]));
}
op_def static Y op(X d1, X d2, Y *extraParams) {
extraParams[0] += static_cast<Y>(d1 * d1);
extraParams[1] += static_cast<Y>(d2 * d2);
return static_cast<Y>(d1 * d2);
}
op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) {
extraParamsTotal[0] += extraParamsLocal[0];
extraParamsTotal[1] += extraParamsLocal[1];
}
#ifdef __CUDACC__
static _CUDA_D inline Y opAtomic(X d1, X d2, Y *extraParams) {
nd4j::math::atomics::nd4j_atomicAdd(&extraParams[0],static_cast<Y>(d1 * d1));
nd4j::math::atomics::nd4j_atomicAdd(&extraParams[1],static_cast<Y>(d2 * d2));
return static_cast<Y>(d1 * d2);
}
#endif
op_def static Y update(Y old, Y opOutput, Y *extraParams) {
return old + opOutput;
}
op_def static Y merge(Y old, Y opOutput, Y *extraParams) {
return update(old, opOutput, extraParams);
}
};
template <typename X, typename Y>
class JaccardDistance {
public:
static const int extraParamsLen = 2;
op_def static X *generateExtraParams() {
//T *extraParams = new T[2];
return nullptr;
}
op_def static void finalizeExtraParams(X *extraParams) {
//delete[] extraParams;
}
op_def static Y startingValue(const X *input) {
return static_cast<X>(0.0f);
}
op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParams) {
// num / denom
return (static_cast<Y>(1.0f)) - (extraParams[0] / extraParams[1]);
}
op_def static Y num(X d1, X d2) {
return nd4j::math::nd4j_min<X>(d1, d2);
}
op_def static Y denom(X d1, X d2) {
return nd4j::math::nd4j_max<X>(d1, d2);
}
op_def static Y op(X d1, X d2, Y *extraParams) {
extraParams[0] += static_cast<Y>(num(d1, d2));
extraParams[1] += static_cast<Y>(denom(d1, d2));
return static_cast<Y>(0.0f);
}
op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) {
extraParamsTotal[0] += extraParamsLocal[0];
extraParamsTotal[1] += extraParamsLocal[1];
}
#ifdef __CUDACC__
__device__
static inline Y opAtomic(X d1, X d2, Y *extraParams) {
nd4j::math::atomics::nd4j_atomicAdd(&extraParams[0],num(d1, d2));
nd4j::math::atomics::nd4j_atomicAdd(&extraParams[1], denom(d1, d2));
return static_cast<Y>(0.0f);
}
#endif
op_def static Y update(Y old, Y opOutput, Y *extraParams) {
return old + opOutput;
}
op_def static Y merge(Y old, Y opOutput, Y *extraParams) {
return update(old, opOutput, extraParams);
}
};
template <typename X, typename Y>
class SimpleHammingDistance {
public:
static const int extraParamsLen = 0;
op_def static X *generateExtraParams() {
//T *extraParams = new T[2];
return nullptr;
}
op_def static void finalizeExtraParams(X *extraParams) {
//delete[] extraParams;
}
op_def static Y startingValue(const X *input) {
return static_cast<Y>(0.0f);
}
op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParams) {
return static_cast<Y>(reduction / n);
}
op_def static Y op(X d1, X d2, Y *extraParams) {
return (d1 == d2) ? static_cast<Y>(0.0f) : static_cast<Y>(1.0f);
}
op_def static void aggregateExtraParams(X *extraParamsTotal, X *extraParamsLocal) {
}
#ifdef __CUDACC__
__device__
static inline Y opAtomic(X d1, X d2, Y *extraParams) {
return op(d1, d2, extraParams);
}
#endif
op_def static Y update(Y old, Y opOutput, Y *extraParams) {
return old + opOutput;
}
op_def static Y merge(Y old, Y opOutput, Y *extraParams) {
return update(old, opOutput, extraParams);
}
};
template <typename X, typename Y>
class CosineDistance {
public:
static const int extraParamsLen = 2;
op_def static X *generateExtraParams() {
//T *extraParams = new T[2];
return nullptr;
}
op_def static void finalizeExtraParams(X *extraParams) {
//delete[] extraParams;
}
op_def static Y startingValue(const X *input) {
return static_cast<Y>(0.0f);
}
op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParams) {
return (static_cast<Y>(1.0f)) - (reduction / (nd4j::math::nd4j_sqrt<Y, Y>(extraParams[0]) * nd4j::math::nd4j_sqrt<Y, Y>(extraParams[1])));
}
op_def static Y op(X d1, X d2, Y *extraParams) {
extraParams[0] += static_cast<Y>(nd4j::math::nd4j_abs<X>(d1) * nd4j::math::nd4j_abs<X>(d1));
extraParams[1] += static_cast<Y>(nd4j::math::nd4j_abs<X>(d2) * nd4j::math::nd4j_abs<X>(d2));
return (d1 * d2);
}
op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) {
extraParamsTotal[0] += extraParamsLocal[0];
extraParamsTotal[1] += extraParamsLocal[1];
}
#ifdef __CUDACC__
static _CUDA_D inline Y opAtomic(X d1, X d2, Y *extraParams) {
nd4j::math::atomics::nd4j_atomicAdd(&extraParams[0], nd4j::math::nd4j_abs<Y>(d1) * nd4j::math::nd4j_abs<Y>(d1));
nd4j::math::atomics::nd4j_atomicAdd(&extraParams[1], nd4j::math::nd4j_abs<Y>(d2) * nd4j::math::nd4j_abs<Y>(d2));
return (d1 * d2);
}
#endif
op_def static Y update(Y old, Y opOutput, Y *extraParams) {
return old + opOutput;
}
op_def static Y merge(Y old, Y opOutput, Y *extraParams) {
return update(old, opOutput, extraParams);
}
};
/**
* Dot product between 2 arrays
*/
template <typename X, typename Y>
class Dot {
public:
static const int extraParamsLen = 0;
op_def static X * generateExtraParams() {
return nullptr;
}
op_def static void finalizeExtraParams(X *extraParamsRef) {
//no-op
//delete[] * extraParamsRef;
}
op_def static Y startingValue(const X *input) {
return static_cast<Y>(0.0f);
}
op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParamsRef) {
return reduction;
}
op_def static Y op(X d1, X d2, Y *extraParamsRef) {
return static_cast<Y>(d1 * d2);
}
#ifdef __CUDACC__
__device__
static inline Y opAtomic(X d1, X d2, Y *extraParamsRef) {
return op(d1, d2, extraParamsRef);
}
#endif
op_def static Y update(Y old, Y opOutput, Y *extraParamsRef) {
return opOutput + old;
}
op_def static Y merge(Y old, Y opOutput, Y *extraParamsRef) {
return update(old, opOutput, extraParamsRef);
}
op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) {}
};
/**
* Op to check equality within arrays
*/
template <typename X, typename Z>
class EqualsWithEps {
public:
static const int extraParamsLen = 0;
op_def static X * generateExtraParams() {
return nullptr;
}
op_def static void finalizeExtraParams(X *extraParamsRef) {
//no-op
}
op_def static Z startingValue(const X *input) {
return static_cast<Z>(0.0f);
}
op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParamsRef) {
return reduction;
}
op_def static Z op(X d1, X d2, Z *extraParamsRef) {
double eps = nd4j::math::nd4j_abs<double>(extraParamsRef[2]);
return static_cast<Z>(!nd4j::math::nd4j_eq<X>(d1, d2, eps));
}
#ifdef __CUDACC__
__device__
static inline Z opAtomic(X d1, X d2, Z *extraParamsRef) {
return op(d1, d2, extraParamsRef);
}
#endif
op_def static Z update(Z old, Z opOutput, Z *extraParamsRef) {
return opOutput + old;
}
op_def static Z merge(X old, Z opOutput, Z *extraParamsRef) {
return update(old, opOutput, extraParamsRef);
}
op_def static void aggregateExtraParams(Z *extraParamsTotal, Z *extraParamsLocal) {}
};
template <typename X, typename Y>
class EuclideanDistance {
public:
static const int extraParamsLen = 0;
op_def static X * generateExtraParams() {
return nullptr;
}
op_def static void finalizeExtraParams(X *extraParamsRef) {
//no-op
}
op_def static Y startingValue(const X *input) {
return static_cast<Y>(0.0f);
}
op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParamsRef) {
return nd4j::math::nd4j_sqrt<Y, Y>(reduction);
}
op_def static Y op(X d1, X d2, Y *extraParamsRef) {
X ret = d1 - d2;
return static_cast<Y>(ret * ret);
}
#ifdef __CUDACC__
__device__
static inline Y opAtomic(X d1, X d2, Y *extraParamsRef) {
return op(d1, d2, extraParamsRef);
}
#endif
op_def static Y update(Y old, Y opOutput, Y *extraParamsRef) {
return opOutput + old;
}
op_def static Y merge(Y old, Y opOutput, Y *extraParamsRef) {
return update(old, opOutput, extraParamsRef);
}
op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) {}
};
template <typename X, typename Y>
class ManhattanDistance {
public:
static const int extraParamsLen = 0;
op_def static X * generateExtraParams() {
return nullptr;
}
op_def static void finalizeExtraParams(X *extraParamsRef) {
//no-op
}
op_def static Y startingValue(const X *input) {
return static_cast<Y>(0.0f);
}
op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParamsRef) {
return reduction;
}
op_def static Y op(X d1, X d2, Y *extraParamsRef) {
return nd4j::math::nd4j_abs<X>(d1 - d2);
}
op_def static Y update(Y old, Y opOutput, Y *extraParamsRef) {
return old + opOutput;
}
op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) {
}
#ifdef __CUDACC__
__device__
static inline Y opAtomic(X d1, X d2, Y *extraParamsRef) {
return op(d1, d2, extraParamsRef);
}
#endif
#ifndef __clang__
#pragma omp declare simd uniform(extraParamsRef)
#endif
op_def static Y merge(X old, X opOutput, X *extraParamsRef) {
return update(old, opOutput, extraParamsRef);
}
};
template <typename X>
class IndexAbsoluteMax {
public:
static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> val, X *extraParams) {
return nd4j::math::nd4j_abs<X>(val);
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) {
opOutput.value = nd4j::math::nd4j_abs<X>(opOutput.value);
old.value = nd4j::math::nd4j_abs<X>(old.value);
if (opOutput.value > old.value)
return opOutput;
#ifdef __CUDACC__
// workaround for cuda race condition at merge phase
else if (opOutput.value == old.value && opOutput.index < old.index)
return opOutput;
#elif defined(__GNUC__)
#endif
return old;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge(
functions::indexreduce::IndexValue<X> f1,
functions::indexreduce::IndexValue<X> f2, X *extraParams) {
if (nd4j::math::nd4j_abs<X>(f1.value) > nd4j::math::nd4j_abs<X>(f2.value))
return f2;
return f1;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess(
functions::indexreduce::IndexValue<X> reduction, int n, int xOffset,
X *dx, int incx, X *extraParams, X *result) {
return reduction;
}
static _CUDA_HD inline X startingValue(const X *input) {
return 0;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) {
functions::indexreduce::IndexValue<X> local;
local.value = startingValue(input);
local.index = 0;
return local;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1,
functions::indexreduce::IndexValue<X> d2, X *extraParams) {
return d1;
}
};
template <typename X>
class FirstIndex {
public:
static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> val, X *extraParams) {
return val;
}
static _CUDA_HD functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) {
#ifdef __CUDACC__
if (opOutput.index < 0)
return old;
#endif
auto res = simdOps::MatchCondition<X,X>::op(opOutput.value, extraParams);
//printf("res: %f; oldIdx: %i; newIdx: %i\n", res, old.index, opOutput.index);
if (res == static_cast<X>(0))
return old;
if (old.index < 0)
return opOutput;
if (old.index > opOutput.index)
return opOutput;
return old;
}
static _CUDA_HD inline X startingValue(const X *input) {
return -nd4j::DataTypeUtils::max<X>();
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) {
functions::indexreduce::IndexValue<X> local;
local.value = startingValue(input);
local.index = -1;
return local;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1,
functions::indexreduce::IndexValue<X> d2, X *extraParams) {
return d1;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge(
functions::indexreduce::IndexValue<X> f1,
functions::indexreduce::IndexValue<X> f2, X *extraParams) {
if (f1.index > f2.index)
return f2;
return f1;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess(
functions::indexreduce::IndexValue<X> reduction, int n, int xOffset,
X *dx, int incx, X *extraParams, X *result) {
return reduction;
}
};
template <typename X>
class LastIndex {
public:
static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> val, X *extraParams) {
return val;
}
static _CUDA_HD functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) {
#ifdef __CUDACC__
if (opOutput.index < 0)
return old;
#endif
auto res = simdOps::MatchCondition<X,X>::op(opOutput.value, extraParams);
if (res == static_cast<X>(0))
return old;
if (old.index < 0)
return opOutput;
if (old.index < opOutput.index)
return opOutput;
return old;
}
static _CUDA_HD inline X startingValue(const X *input) {
return -nd4j::DataTypeUtils::max<X>();
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) {
functions::indexreduce::IndexValue<X> local;
local.value = startingValue(input);
local.index = -1;
return local;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1,
functions::indexreduce::IndexValue<X> d2, X *extraParams) {
return d1;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge(
functions::indexreduce::IndexValue<X> f1,
functions::indexreduce::IndexValue<X> f2, X *extraParams) {
if (f1.index < f2.index)
return f2;
return f1;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess(
functions::indexreduce::IndexValue<X> reduction, int n, int xOffset,
X *dx, int incx, X *extraParams, X *result) {
return reduction;
}
};
template <typename X>
class IndexMax {
public:
static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> val, X *extraParams) {
return val;
}
static _CUDA_HD functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) {
if (opOutput.value > old.value) {
return opOutput;
}
#ifdef __CUDACC__
// workaround for cuda race condition at merge phase
else if (opOutput.value == old.value && opOutput.index < old.index)
return opOutput;
#elif defined(__GNUC__)
#endif
return old;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge(
functions::indexreduce::IndexValue<X> f1,
functions::indexreduce::IndexValue<X> f2, X *extraParams) {
if (f1.value > f2.value)
return f2;
return f1;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess(
functions::indexreduce::IndexValue<X> reduction, int n, int xOffset,
X *dx, int incx, X *extraParams, X *result) {
return reduction;
}
static _CUDA_HD inline X startingValue(const X *input) {
return -nd4j::DataTypeUtils::max<X>();
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) {
functions::indexreduce::IndexValue<X> local;
local.value = startingValue(input);
local.index = 0;
return local;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1,
functions::indexreduce::IndexValue<X> d2, X *extraParams) {
return d1;
}
};
template <typename X>
class IndexAbsoluteMin {
public:
static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(
functions::indexreduce::IndexValue<X> val, X *extraParams) {
return val;
}
static _CUDA_HD inline X startingValue(const X *input) {
return nd4j::DataTypeUtils::max<X>();
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) {
functions::indexreduce::IndexValue<X> local;
local.value = startingValue(input);
local.index = 0;
return local;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) {
opOutput.value = nd4j::math::nd4j_abs<X>(opOutput.value);
old.value = nd4j::math::nd4j_abs<X>(old.value);
if (opOutput.value < old.value)
return opOutput;
#ifdef __CUDACC__
// workaround for cuda race condition at merge phase
else if (opOutput.value == old.value && opOutput.index < old.index)
return opOutput;
#elif defined(__GNUC__)
#endif
return old;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge(
functions::indexreduce::IndexValue<X> f1,
functions::indexreduce::IndexValue<X> f2, X *extraParams) {
if (nd4j::math::nd4j_abs<X>(f1.value) < nd4j::math::nd4j_abs<X>(f2.value))
return f2;
return f1;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess(
functions::indexreduce::IndexValue<X> reduction, int n, int xOffset,
X *dx, int incx, X *extraParams, X *result) {
return reduction;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1,
functions::indexreduce::IndexValue<X> d2, X *extraParams) {
return d1;
}
};
template <typename X>
class IndexMin {
public:
static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(
functions::indexreduce::IndexValue<X> val, X *extraParams) {
return val;
}
static _CUDA_HD inline X startingValue(const X *input) {
return nd4j::DataTypeUtils::max<X>();
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) {
functions::indexreduce::IndexValue<X> local;
local.value = startingValue(input);
local.index = 0;
return local;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) {
if (opOutput.value < old.value)
return opOutput;
#ifdef __CUDACC__
// workaround for cuda race condition at merge phase
else if (opOutput.value == old.value && opOutput.index < old.index)
return opOutput;
#elif defined(__GNUC__)
#endif
return old;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge(
functions::indexreduce::IndexValue<X> f1,
functions::indexreduce::IndexValue<X> f2, X *extraParams) {
if (f1.value < f2.value)
return f2;
return f1;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess(
functions::indexreduce::IndexValue<X> reduction, int n, int xOffset,
X *dx, int incx, X *extraParams, X *result) {
return reduction;
}
static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1,
functions::indexreduce::IndexValue<X> d2, X *extraParams) {
return d1;
}
};
template <typename X, typename Z>
class SummaryStatsVariance {
public:
static _CUDA_HD inline Z getValue(const bool biasCorrected, functions::summarystats::SummaryStatsData<X> val) {
if (biasCorrected) {
Z ret = static_cast<Z>(val.varianceBiasCorrected());
if (ret < static_cast<Z>(0.0f))
return static_cast<Z>(val.variance());
return ret;
}
return static_cast<Z>(val.variance());
}
static _CUDA_HD inline functions::summarystats::SummaryStatsData<X> op(functions::summarystats::SummaryStatsData<X> d1, Z *extraParams) {
return d1;
}
};
template <typename X, typename Z>
class SummaryStatsStandardDeviation {
public:
static _CUDA_HD inline Z getValue(const bool biasCorrected, functions::summarystats::SummaryStatsData<X> val) {
if (biasCorrected) {
auto ret = static_cast<Z>(val.varianceBiasCorrected());
if (ret < static_cast<Z>(0.0f))
return nd4j::math::nd4j_sqrt<double, Z>(val.variance());
else
return nd4j::math::nd4j_sqrt<double, Z>(ret);
}
return nd4j::math::nd4j_sqrt<double, Z>(val.variance());
}
static _CUDA_HD inline functions::summarystats::SummaryStatsData<X> op(functions::summarystats::SummaryStatsData<X> d1, Z *extraParams) {
return d1;
}
};
template <typename X>
class DropOut {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
inline _CUDA_D static X op(X d1, X *params) {
X prob = params[0];
#ifdef __CUDACC__
X length = params[1];
X tid = gridDim.x * blockDim.x + threadIdx.x;
X rnd = nd4j::math::nd4j_abs<X>(nd4j::math::nd4j_cos<X>(static_cast<X>(clock64()) * static_cast<X>(tid) + static_cast<X>(length) * static_cast<X>(tid)));
#else
X rnd = static_cast<X>(rand() / RAND_MAX);
#endif
return rnd >= prob ? static_cast<X>(0.0f) : d1;
}
};
template <typename X, typename Y, typename Z>
class DropOutInverted {
public:
no_op_exec_special
no_op_exec_special_cuda
#ifdef __CUDACC__
__device__
#endif
inline static Z op(X d1, Y d2, Z *params) {
Y prob = d2;
#ifdef __CUDACC__
X length = params[1];
X tid = gridDim.x * blockDim.x + threadIdx.x;
X rnd = nd4j::math::nd4j_abs<X>(nd4j::math::nd4j_cos<X>(static_cast<X>(clock64()) * static_cast<X>(tid) + static_cast<X>(length) * static_cast<X>(tid)));
#else
X rnd = static_cast<X>(rand() / RAND_MAX);
#endif
return rnd >= static_cast<X>(prob) ? static_cast<Z>(0.0f) : reinterpret_cast<Z>(d1 / static_cast<X>(prob));
}
};
template <typename X, typename Y, typename Z>
class ReplaceNans {
public:
no_op_exec_special
no_op_exec_special_cuda
op_def static Z op(X d1, Y d2, Z *params) {
return nd4j::math::nd4j_isnan(d1) ? static_cast<Z>(d2) : static_cast<Z>(d1) ;
}
};
// this op is used for conditional pairwise transforms only
template <typename X, typename Y, typename Z>
class CompareAndReplace{
public:
// op definition for PairWise Transform
op_def static Z op(X d1, Y d2, Z *params) {
auto zd1 = static_cast<Z>(d1);
auto zd2 = static_cast<Z>(d2);
auto compare = params[0];
auto eps = params[2];
int mode = (int) params[3];
if (mode == 0) // equals
if (nd4j::math::nd4j_abs<Z>(zd1 - compare) <= eps)
return zd2;
else
return zd1;
else if (mode == 1) // not equals eps
if (nd4j::math::nd4j_abs<Z>(zd1 - compare) > eps)
return zd2;
else
return zd1;
else if (mode == 2) // less_than eps
if (zd1 < compare)
return zd2;
else
return zd1;
else if (mode ==3) // greater_than
if (zd1 > compare)
return zd2;
else
return zd1;
else if (mode == 4) // less_or_equals_than
if (zd1 <= compare)
return zd2;
else
return zd1;
else if (mode == 5) // greater_or_equals_than
if (zd1 >= compare)
return zd2;
else
return zd1;
else if (mode == 6) // abs_less_than
if (nd4j::math::nd4j_abs<Z>(zd1) < compare)
return zd2;
else
return zd1;
else if (mode == 7) // abs_greater_than
if (nd4j::math::nd4j_abs<Z>(zd1) > compare)
return zd2;
else
return zd1;
else if (mode == 8) // is inf
if (nd4j::math::nd4j_isinf(zd1))
return zd2;
else
return zd1;
else if (mode == 9) // is nan
if (nd4j::math::nd4j_isnan(zd1))
return zd2;
else
return zd1;
else if (mode == 10)
if (zd1 == compare)
return zd2;
else
return zd1;
else if (mode == 11)
if (zd1 != compare)
return zd2;
else
return zd1;
else if (mode == 12) // abs_greater_or_equals_than
if (nd4j::math::nd4j_abs<Z>(zd1) >= compare)
return zd2;
else
return zd1;
else if (mode == 13) // abs_less_or_equals_than
if (nd4j::math::nd4j_abs<Z>(zd1) <= compare)
return zd2;
else
return zd1;
else
printf("Undefined boolean operation: [%i]\n", mode);
return zd1;
}
};
template <typename X, typename Y, typename Z>
class CompareAndSet {
public:
// op definition for PairWise Transform
op_def static Z op(X dX, Y dY, Z *params) {
auto d1 = static_cast<Z>(dX);
auto d2 = static_cast<Z>(dY);
auto compare = params[0];
auto eps = params[2];
auto mode = static_cast<int>(params[3]);
if (mode == 0) // equals
if (nd4j::math::nd4j_abs<Z>(d2 - compare) <= eps)
return d2;
else
return d1;
else if (mode == 1) // not equals
if (nd4j::math::nd4j_abs<Z>(d2 - compare) > eps)
return d2;
else
return d1;
else if (mode == 2) // less_than
if (d2 < compare)
return d2;
else
return d1;
else if (mode ==3) // greater_than
if (d2 > compare)
return d2;
else
return d1;
else if (mode == 4) // less_or_equals_than
if (d2 <= compare)
return d2;
else
return d1;
else if (mode == 5) // greater_or_equals_than
if (d2 >= compare)
return d2;
else
return d1;
else if (mode == 6) // abs_less_than
if (nd4j::math::nd4j_abs<Z>(d2) < compare)
return d2;
else
return d1;
else if (mode == 7) // abs_greater_than
if (nd4j::math::nd4j_abs<Z>(d2) > compare)
return d2;
else
return d1;
else if (mode == 8) // is inf
if (nd4j::math::nd4j_isinf(d2))
return d2;
else
return d1;
else if (mode == 9) // is nan
if (nd4j::math::nd4j_isnan(d2))
return d2;
else
return d1;
else if (mode == 10)
if (d2 == compare)
return d2;
else
return d1;
else if (mode == 11)
if (d2 != compare)
return d2;
else
return d1;
else if (mode == 12) // abs_greater_or_equals_than
if (nd4j::math::nd4j_abs<Z>(d1) >= compare)
return d2;
else
return d1;
else if (mode == 13) // abs_less_or_equals_than
if (nd4j::math::nd4j_abs<Z>(d1) <= compare)
return d2;
else
return d1;
else
printf("Undefined boolean operation: [%i]\n", mode);
return d1;
}
};
template <typename X>
class CompareAndSetTransform {
public:
no_op_exec_special_same
no_op_exec_special_same_cuda
// op definition for Transform
op_def static X op(X d1, X *params) {
auto compare = params[0];
auto set = params[1];
auto eps = params[2];
// with mode == 0 we do set if d1 equals to compare, and with mode == 1 - we go otherwise
int mode = (int) params[3];
if (mode == 0) // equals
if (nd4j::math::nd4j_abs<X>(d1 - compare) <= eps)
return set;
else
return d1;
//return nd4j::math::nd4j_abs<T>(d1 - compare) <= eps ? set : d1;
else if (mode == 1) // not equals
if (nd4j::math::nd4j_abs<X>(d1 - compare) > eps)
return set;
else
return d1;
//return nd4j::math::nd4j_abs<T>(d1 - compare) > eps ? set : d1;
else if (mode == 2) // less_than
if (d1 < compare)
return set;
else
return d1;
else if (mode ==3) // greater_than
if (d1 > compare)
return set;
else
return d1;
else if (mode == 4) // less_or_equals_than
if (d1 <= compare)
return set;
else
return d1;
else if (mode == 5) // greater_or_equals_than
if (d1 >= compare)
return set;
else
return d1;
else if (mode == 6) // abs_less_than
if (nd4j::math::nd4j_abs<X>(d1) < compare)
return set;
else
return d1;
else if (mode == 7) // abs_greater_than
if (nd4j::math::nd4j_abs<X>(d1) > compare)
return set;
else
return d1;
else if (mode == 8) // is inf
if (nd4j::math::nd4j_isinf(d1))
return set;
else
return d1;
else if (mode == 9) // is nan
if (nd4j::math::nd4j_isnan(d1))
return set;
else
return d1;
else if (mode == 10)
if (d1 == compare)
return set;
else
return d1;
else if (mode == 11)
if (d1 != compare)
return set;
else
return d1;
else if (mode == 12) // abs_greater_or_equals_than
if (nd4j::math::nd4j_abs<X>(d1) >= compare)
return set;
else
return d1;
else if (mode == 13) // abs_less_or_equals_than
if (nd4j::math::nd4j_abs<X>(d1) <= compare)
return set;
else
return d1;
else
printf("Undefined boolean operation: [%i]\n", mode);
return d1;
}
};
}
#endif
|
sum_prod3.c | #include "q_incs.h"
#include "sum_prod3.h"
extern uint64_t num_ops;
static inline void
_vvmul(
float * restrict X,
double * restrict Y,
uint32_t n,
double * restrict Z
)
{
#pragma omp simd
for ( uint32_t i = 0; i < n; i++ ) {
Z[i] = X[i] * Y[i];
}
// num_ops += n;
}
static inline void
_sum(
double * restrict X,
uint32_t n,
double *ptr_y
)
{
double sum = 0;
#pragma omp simd reduction(+:sum)
for ( uint32_t i = 0; i < n; i++ ) {
sum += X[i];
}
// num_ops += n;
*ptr_y = sum;
}
int
sum_prod3(
float **X, /* M vectors of length N */
uint64_t M,
uint64_t N,
double *w, /* vector of length N */
double **A /* M vectors of length M */
)
{
int status = 0;
double *temp1 = NULL, *temp2 = NULL;
int block_size = 65536;
temp1 = malloc(block_size * sizeof(double));
return_if_malloc_failed(temp1);
temp2 = malloc(block_size * sizeof(double));
return_if_malloc_failed(temp2);
uint32_t nT = sysconf(_SC_NPROCESSORS_ONLN);
// nT = 4; // TODO FIX HARD CODING
#pragma omp parallel for schedule(static) num_threads(nT)
for ( uint64_t i = 0; i < M; i++ ) {
memset(A[i], '\0', M*sizeof(double));
// num_ops += M;
}
unsigned int nB = N / block_size;
if ( ( nB * block_size ) != N ) { nB++; }
for ( unsigned int b = 0; b < nB; b++ ) {
unsigned int lb = b * block_size;
unsigned int ub = lb + block_size;
if ( ub > N ) { ub = N; }
#pragma omp parallel for schedule(static, 1) num_threads(nT)
for ( uint64_t i = 0; i < M; i++ ) {
float *Xi = X[i];
double *Ai = A[i];
_vvmul(Xi+lb, w+lb, ub-lb, temp1);
double sum = 0;
for ( uint64_t j = i; j < M; j++ ) {
_vvmul(X[j]+lb, temp1, ub-lb, temp2);
_sum(temp2, ub-lb, &sum);
Ai[j] += sum;
}
}
}
BYE:
free_if_non_null(temp1);
free_if_non_null(temp2);
return status;
}
|
GB_unop__minv_fp64_fp64.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__minv_fp64_fp64)
// op(A') function: GB (_unop_tran__minv_fp64_fp64)
// C type: double
// A type: double
// cast: double cij = aij
// unaryop: cij = 1./aij
#define GB_ATYPE \
double
#define GB_CTYPE \
double
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
double aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = 1./x ;
// casting
#define GB_CAST(z, aij) \
double z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
double aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
double z = aij ; \
Cx [pC] = 1./z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_MINV || GxB_NO_FP64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__minv_fp64_fp64)
(
double *Cx, // Cx and Ax may be aliased
const double *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++)
{
double aij = Ax [p] ;
double z = aij ;
Cx [p] = 1./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 ;
double aij = Ax [p] ;
double z = aij ;
Cx [p] = 1./z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__minv_fp64_fp64)
(
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
|
main.ref.c | #include <sys/time.h>
#include <time.h>
#include <stdio.h>
static unsigned long long current_time_ns() {
#ifdef __MACH__
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
unsigned long long s = 1000000000ULL * (unsigned long long)mts.tv_sec;
return (unsigned long long)mts.tv_nsec + s;
#else
struct timespec t ={0,0};
clock_gettime(CLOCK_MONOTONIC, &t);
unsigned long long s = 1000000000ULL * (unsigned long long)t.tv_sec;
return (((unsigned long long)t.tv_nsec)) + s;
#endif
}
//===============================================================================================================================================================================================================
//===============================================================================================================================================================================================================
// DEFINE / INCLUDE
//===============================================================================================================================================================================================================
//===============================================================================================================================================================================================================
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#include <avilib.h>
#include <avimod.h>
#include <omp.h>
#include "define.h"
//===============================================================================================================================================================================================================200
// WRITE DATA FUNCTION
//===============================================================================================================================================================================================================200
void write_data( char* filename,
int frameNo,
int frames_processed,
int endoPoints,
int* input_a,
int* input_b,
int epiPoints,
int* input_2a,
int* input_2b){
//================================================================================80
// VARIABLES
//================================================================================80
FILE* fid;
int i,j;
char c;
//================================================================================80
// OPEN FILE FOR READING
//================================================================================80
fid = fopen(filename, "w+");
if( fid == NULL ){
printf( "The file was not opened for writing\n" );
return;
}
//================================================================================80
// WRITE VALUES TO THE FILE
//================================================================================80
fprintf(fid, "Total AVI Frames: %d\n", frameNo);
fprintf(fid, "Frames Processed: %d\n", frames_processed);
fprintf(fid, "endoPoints: %d\n", endoPoints);
fprintf(fid, "epiPoints: %d", epiPoints);
for(j=0; j<frames_processed;j++)
{
fprintf(fid, "\n---Frame %d---",j);
fprintf(fid, "\n--endo--\n",j);
for(i=0; i<endoPoints; i++){
fprintf(fid, "%d\t", input_a[j+i*frameNo]);
}
fprintf(fid, "\n");
for(i=0; i<endoPoints; i++){
// if(input_b[j*size+i] > 2000) input_b[j*size+i]=0;
fprintf(fid, "%d\t", input_b[j+i*frameNo]);
}
fprintf(fid, "\n--epi--\n",j);
for(i=0; i<epiPoints; i++){
//if(input_2a[j*size_2+i] > 2000) input_2a[j*size_2+i]=0;
fprintf(fid, "%d\t", input_2a[j+i*frameNo]);
}
fprintf(fid, "\n");
for(i=0; i<epiPoints; i++){
//if(input_2b[j*size_2+i] > 2000) input_2b[j*size_2+i]=0;
fprintf(fid, "%d\t", input_2b[j+i*frameNo]);
}
}
// ================================================================================80
// CLOSE FILE
// ================================================================================80
fclose(fid);
}
//===============================================================================================================================================================================================================
//===============================================================================================================================================================================================================
// MAIN FUNCTION
//===============================================================================================================================================================================================================
//===============================================================================================================================================================================================================
int main(int argc, char *argv []){
//======================================================================================================================================================
// VARIABLES
//======================================================================================================================================================
// counters
int i;
int frames_processed;
// parameters
public_struct public_s;
private_struct private_s[ALL_POINTS];
//======================================================================================================================================================
// FRAMES
//======================================================================================================================================================
if(argc!=4){
printf("ERROR: usage: heartwall <inputfile> <num of frames> <num of threads>\n");
exit(1);
}
char* video_file_name;
video_file_name = argv[1];
avi_t* d_frames = (avi_t*)AVI_open_input_file(video_file_name, 1); // added casting
if (d_frames == NULL) {
AVI_print_error((char *) "Error with AVI_open_input_file");
return -1;
}
public_s.d_frames = d_frames;
public_s.frames = AVI_video_frames(public_s.d_frames);
public_s.frame_rows = AVI_video_height(public_s.d_frames);
public_s.frame_cols = AVI_video_width(public_s.d_frames);
public_s.frame_elem = public_s.frame_rows * public_s.frame_cols;
public_s.frame_mem = sizeof(fp) * public_s.frame_elem;
//======================================================================================================================================================
// CHECK INPUT ARGUMENTS
//======================================================================================================================================================
frames_processed = atoi(argv[2]);
if(frames_processed<0 || frames_processed>public_s.frames){
printf("ERROR: %d is an incorrect number of frames specified, select in the range of 0-%d\n", frames_processed, public_s.frames);
return 0;
}
int omp_num_threads;
omp_num_threads = atoi(argv[3]);
if (omp_num_threads <=0){
printf ("num of threads must be a positive integer");
return 0;
}
printf("num of threads: %d\n", omp_num_threads);
//======================================================================================================================================================
// INPUTS
//======================================================================================================================================================
//====================================================================================================
// ENDO POINTS
//====================================================================================================
public_s.endoPoints = ENDO_POINTS;
public_s.d_endo_mem = sizeof(int) * public_s.endoPoints;
public_s.d_endoRow = (int *)malloc(public_s.d_endo_mem);
public_s.d_endoRow[ 0] = 369;
public_s.d_endoRow[ 1] = 400;
public_s.d_endoRow[ 2] = 429;
public_s.d_endoRow[ 3] = 452;
public_s.d_endoRow[ 4] = 476;
public_s.d_endoRow[ 5] = 486;
public_s.d_endoRow[ 6] = 479;
public_s.d_endoRow[ 7] = 458;
public_s.d_endoRow[ 8] = 433;
public_s.d_endoRow[ 9] = 404;
public_s.d_endoRow[10] = 374;
public_s.d_endoRow[11] = 346;
public_s.d_endoRow[12] = 318;
public_s.d_endoRow[13] = 294;
public_s.d_endoRow[14] = 277;
public_s.d_endoRow[15] = 269;
public_s.d_endoRow[16] = 275;
public_s.d_endoRow[17] = 287;
public_s.d_endoRow[18] = 311;
public_s.d_endoRow[19] = 339;
public_s.d_endoCol = (int *)malloc(public_s.d_endo_mem);
public_s.d_endoCol[ 0] = 408;
public_s.d_endoCol[ 1] = 406;
public_s.d_endoCol[ 2] = 397;
public_s.d_endoCol[ 3] = 383;
public_s.d_endoCol[ 4] = 354;
public_s.d_endoCol[ 5] = 322;
public_s.d_endoCol[ 6] = 294;
public_s.d_endoCol[ 7] = 270;
public_s.d_endoCol[ 8] = 250;
public_s.d_endoCol[ 9] = 237;
public_s.d_endoCol[10] = 235;
public_s.d_endoCol[11] = 241;
public_s.d_endoCol[12] = 254;
public_s.d_endoCol[13] = 273;
public_s.d_endoCol[14] = 300;
public_s.d_endoCol[15] = 328;
public_s.d_endoCol[16] = 356;
public_s.d_endoCol[17] = 383;
public_s.d_endoCol[18] = 401;
public_s.d_endoCol[19] = 411;
public_s.d_tEndoRowLoc = (int *)malloc(public_s.d_endo_mem * public_s.frames);
public_s.d_tEndoColLoc = (int *)malloc(public_s.d_endo_mem * public_s.frames);
//====================================================================================================
// EPI POINTS
//====================================================================================================
public_s.epiPoints = EPI_POINTS;
public_s.d_epi_mem = sizeof(int) * public_s.epiPoints;
public_s.d_epiRow = (int *)malloc(public_s.d_epi_mem);
public_s.d_epiRow[ 0] = 390;
public_s.d_epiRow[ 1] = 419;
public_s.d_epiRow[ 2] = 448;
public_s.d_epiRow[ 3] = 474;
public_s.d_epiRow[ 4] = 501;
public_s.d_epiRow[ 5] = 519;
public_s.d_epiRow[ 6] = 535;
public_s.d_epiRow[ 7] = 542;
public_s.d_epiRow[ 8] = 543;
public_s.d_epiRow[ 9] = 538;
public_s.d_epiRow[10] = 528;
public_s.d_epiRow[11] = 511;
public_s.d_epiRow[12] = 491;
public_s.d_epiRow[13] = 466;
public_s.d_epiRow[14] = 438;
public_s.d_epiRow[15] = 406;
public_s.d_epiRow[16] = 376;
public_s.d_epiRow[17] = 347;
public_s.d_epiRow[18] = 318;
public_s.d_epiRow[19] = 291;
public_s.d_epiRow[20] = 275;
public_s.d_epiRow[21] = 259;
public_s.d_epiRow[22] = 256;
public_s.d_epiRow[23] = 252;
public_s.d_epiRow[24] = 252;
public_s.d_epiRow[25] = 257;
public_s.d_epiRow[26] = 266;
public_s.d_epiRow[27] = 283;
public_s.d_epiRow[28] = 305;
public_s.d_epiRow[29] = 331;
public_s.d_epiRow[30] = 360;
public_s.d_epiCol = (int *)malloc(public_s.d_epi_mem);
public_s.d_epiCol[ 0] = 457;
public_s.d_epiCol[ 1] = 454;
public_s.d_epiCol[ 2] = 446;
public_s.d_epiCol[ 3] = 431;
public_s.d_epiCol[ 4] = 411;
public_s.d_epiCol[ 5] = 388;
public_s.d_epiCol[ 6] = 361;
public_s.d_epiCol[ 7] = 331;
public_s.d_epiCol[ 8] = 301;
public_s.d_epiCol[ 9] = 273;
public_s.d_epiCol[10] = 243;
public_s.d_epiCol[11] = 218;
public_s.d_epiCol[12] = 196;
public_s.d_epiCol[13] = 178;
public_s.d_epiCol[14] = 166;
public_s.d_epiCol[15] = 157;
public_s.d_epiCol[16] = 155;
public_s.d_epiCol[17] = 165;
public_s.d_epiCol[18] = 177;
public_s.d_epiCol[19] = 197;
public_s.d_epiCol[20] = 218;
public_s.d_epiCol[21] = 248;
public_s.d_epiCol[22] = 276;
public_s.d_epiCol[23] = 304;
public_s.d_epiCol[24] = 333;
public_s.d_epiCol[25] = 361;
public_s.d_epiCol[26] = 391;
public_s.d_epiCol[27] = 415;
public_s.d_epiCol[28] = 434;
public_s.d_epiCol[29] = 448;
public_s.d_epiCol[30] = 455;
public_s.d_tEpiRowLoc = (int *)malloc(public_s.d_epi_mem * public_s.frames);
public_s.d_tEpiColLoc = (int *)malloc(public_s.d_epi_mem * public_s.frames);
//====================================================================================================
// ALL POINTS
//====================================================================================================
public_s.allPoints = ALL_POINTS;
//======================================================================================================================================================
// CONSTANTS
//======================================================================================================================================================
public_s.tSize = 25;
public_s.sSize = 40;
public_s.maxMove = 10;
public_s.alpha = 0.87;
//======================================================================================================================================================
// SUMS
//======================================================================================================================================================
for(i=0; i<public_s.allPoints; i++){
private_s[i].in_partial_sum = (fp *)malloc(sizeof(fp) * 2*public_s.tSize+1);
private_s[i].in_sqr_partial_sum = (fp *)malloc(sizeof(fp) * 2*public_s.tSize+1);
private_s[i].par_max_val = (fp *)malloc(sizeof(fp) * (2*public_s.tSize+2*public_s.sSize+1));
private_s[i].par_max_coo = (int *)malloc(sizeof(int) * (2*public_s.tSize+2*public_s.sSize+1));
}
//======================================================================================================================================================
// INPUT 2 (SAMPLE AROUND POINT)
//======================================================================================================================================================
public_s.in2_rows = 2 * public_s.sSize + 1;
public_s.in2_cols = 2 * public_s.sSize + 1;
public_s.in2_elem = public_s.in2_rows * public_s.in2_cols;
public_s.in2_mem = sizeof(fp) * public_s.in2_elem;
for(i=0; i<public_s.allPoints; i++){
private_s[i].d_in2 = (fp *)malloc(public_s.in2_mem);
private_s[i].d_in2_sqr = (fp *)malloc(public_s.in2_mem);
}
//======================================================================================================================================================
// INPUT (POINT TEMPLATE)
//======================================================================================================================================================
public_s.in_mod_rows = public_s.tSize+1+public_s.tSize;
public_s.in_mod_cols = public_s.in_mod_rows;
public_s.in_mod_elem = public_s.in_mod_rows * public_s.in_mod_cols;
public_s.in_mod_mem = sizeof(fp) * public_s.in_mod_elem;
for(i=0; i<public_s.allPoints; i++){
private_s[i].d_in_mod = (fp *)malloc(public_s.in_mod_mem);
private_s[i].d_in_sqr = (fp *)malloc(public_s.in_mod_mem);
}
//======================================================================================================================================================
// ARRAY OF TEMPLATES FOR ALL POINTS
//======================================================================================================================================================
public_s.d_endoT = (fp *)malloc(public_s.in_mod_mem * public_s.endoPoints);
public_s.d_epiT = (fp *)malloc(public_s.in_mod_mem * public_s.epiPoints);
//======================================================================================================================================================
// SETUP private_s POINTERS TO ROWS, COLS AND TEMPLATE
//======================================================================================================================================================
for(i=0; i<public_s.endoPoints; i++){
private_s[i].point_no = i;
private_s[i].in_pointer = private_s[i].point_no * public_s.in_mod_elem;
private_s[i].d_Row = public_s.d_endoRow; // original row coordinates
private_s[i].d_Col = public_s.d_endoCol; // original col coordinates
private_s[i].d_tRowLoc = public_s.d_tEndoRowLoc; // updated row coordinates
private_s[i].d_tColLoc = public_s.d_tEndoColLoc; // updated row coordinates
private_s[i].d_T = public_s.d_endoT; // templates
}
for(i=public_s.endoPoints; i<public_s.allPoints; i++){
private_s[i].point_no = i-public_s.endoPoints;
private_s[i].in_pointer = private_s[i].point_no * public_s.in_mod_elem;
private_s[i].d_Row = public_s.d_epiRow;
private_s[i].d_Col = public_s.d_epiCol;
private_s[i].d_tRowLoc = public_s.d_tEpiRowLoc;
private_s[i].d_tColLoc = public_s.d_tEpiColLoc;
private_s[i].d_T = public_s.d_epiT;
}
//======================================================================================================================================================
// CONVOLUTION
//======================================================================================================================================================
public_s.ioffset = 0;
public_s.joffset = 0;
public_s.conv_rows = public_s.in_mod_rows + public_s.in2_rows - 1; // number of rows in I
public_s.conv_cols = public_s.in_mod_cols + public_s.in2_cols - 1; // number of columns in I
public_s.conv_elem = public_s.conv_rows * public_s.conv_cols; // number of elements
public_s.conv_mem = sizeof(fp) * public_s.conv_elem;
for(i=0; i<public_s.allPoints; i++){
private_s[i].d_conv = (fp *)malloc(public_s.conv_mem);
}
//======================================================================================================================================================
// CUMULATIVE SUM
//======================================================================================================================================================
//====================================================================================================
// PAD ARRAY
//====================================================================================================
//====================================================================================================
// VERTICAL CUMULATIVE SUM
//====================================================================================================
public_s.in2_pad_add_rows = public_s.in_mod_rows;
public_s.in2_pad_add_cols = public_s.in_mod_cols;
public_s.in2_pad_rows = public_s.in2_rows + 2*public_s.in2_pad_add_rows;
public_s.in2_pad_cols = public_s.in2_cols + 2*public_s.in2_pad_add_cols;
public_s.in2_pad_elem = public_s.in2_pad_rows * public_s.in2_pad_cols;
public_s.in2_pad_mem = sizeof(fp) * public_s.in2_pad_elem;
for(i=0; i<public_s.allPoints; i++){
private_s[i].d_in2_pad = (fp *)malloc(public_s.in2_pad_mem);
}
//====================================================================================================
// SELECTION, SELECTION 2, SUBTRACTION
//====================================================================================================
//====================================================================================================
// HORIZONTAL CUMULATIVE SUM
//====================================================================================================
public_s.in2_pad_cumv_sel_rowlow = 1 + public_s.in_mod_rows; // (1 to n+1)
public_s.in2_pad_cumv_sel_rowhig = public_s.in2_pad_rows - 1;
public_s.in2_pad_cumv_sel_collow = 1;
public_s.in2_pad_cumv_sel_colhig = public_s.in2_pad_cols;
public_s.in2_pad_cumv_sel2_rowlow = 1;
public_s.in2_pad_cumv_sel2_rowhig = public_s.in2_pad_rows - public_s.in_mod_rows - 1;
public_s.in2_pad_cumv_sel2_collow = 1;
public_s.in2_pad_cumv_sel2_colhig = public_s.in2_pad_cols;
public_s.in2_sub_rows = public_s.in2_pad_cumv_sel_rowhig - public_s.in2_pad_cumv_sel_rowlow + 1;
public_s.in2_sub_cols = public_s.in2_pad_cumv_sel_colhig - public_s.in2_pad_cumv_sel_collow + 1;
public_s.in2_sub_elem = public_s.in2_sub_rows * public_s.in2_sub_cols;
public_s.in2_sub_mem = sizeof(fp) * public_s.in2_sub_elem;
for(i=0; i<public_s.allPoints; i++){
private_s[i].d_in2_sub = (fp *)malloc(public_s.in2_sub_mem);
}
//====================================================================================================
// SELECTION, SELECTION 2, SUBTRACTION, SQUARE, NUMERATOR
//====================================================================================================
public_s.in2_sub_cumh_sel_rowlow = 1;
public_s.in2_sub_cumh_sel_rowhig = public_s.in2_sub_rows;
public_s.in2_sub_cumh_sel_collow = 1 + public_s.in_mod_cols;
public_s.in2_sub_cumh_sel_colhig = public_s.in2_sub_cols - 1;
public_s.in2_sub_cumh_sel2_rowlow = 1;
public_s.in2_sub_cumh_sel2_rowhig = public_s.in2_sub_rows;
public_s.in2_sub_cumh_sel2_collow = 1;
public_s.in2_sub_cumh_sel2_colhig = public_s.in2_sub_cols - public_s.in_mod_cols - 1;
public_s.in2_sub2_sqr_rows = public_s.in2_sub_cumh_sel_rowhig - public_s.in2_sub_cumh_sel_rowlow + 1;
public_s.in2_sub2_sqr_cols = public_s.in2_sub_cumh_sel_colhig - public_s.in2_sub_cumh_sel_collow + 1;
public_s.in2_sub2_sqr_elem = public_s.in2_sub2_sqr_rows * public_s.in2_sub2_sqr_cols;
public_s.in2_sub2_sqr_mem = sizeof(fp) * public_s.in2_sub2_sqr_elem;
for(i=0; i<public_s.allPoints; i++){
private_s[i].d_in2_sub2_sqr = (fp *)malloc(public_s.in2_sub2_sqr_mem);
}
//======================================================================================================================================================
// CUMULATIVE SUM 2
//======================================================================================================================================================
//====================================================================================================
// PAD ARRAY
//====================================================================================================
//====================================================================================================
// VERTICAL CUMULATIVE SUM
//====================================================================================================
//====================================================================================================
// SELECTION, SELECTION 2, SUBTRACTION
//====================================================================================================
//====================================================================================================
// HORIZONTAL CUMULATIVE SUM
//====================================================================================================
//====================================================================================================
// SELECTION, SELECTION 2, SUBTRACTION, DIFFERENTIAL LOCAL SUM, DENOMINATOR A, DENOMINATOR, CORRELATION
//====================================================================================================
//======================================================================================================================================================
// TEMPLATE MASK CREATE
//======================================================================================================================================================
public_s.tMask_rows = public_s.in_mod_rows + (public_s.sSize+1+public_s.sSize) - 1;
public_s.tMask_cols = public_s.tMask_rows;
public_s.tMask_elem = public_s.tMask_rows * public_s.tMask_cols;
public_s.tMask_mem = sizeof(fp) * public_s.tMask_elem;
for(i=0; i<public_s.allPoints; i++){
private_s[i].d_tMask = (fp *)malloc(public_s.tMask_mem);
}
//======================================================================================================================================================
// POINT MASK INITIALIZE
//======================================================================================================================================================
public_s.mask_rows = public_s.maxMove;
public_s.mask_cols = public_s.mask_rows;
public_s.mask_elem = public_s.mask_rows * public_s.mask_cols;
public_s.mask_mem = sizeof(fp) * public_s.mask_elem;
//======================================================================================================================================================
// MASK CONVOLUTION
//======================================================================================================================================================
public_s.mask_conv_rows = public_s.tMask_rows; // number of rows in I
public_s.mask_conv_cols = public_s.tMask_cols; // number of columns in I
public_s.mask_conv_elem = public_s.mask_conv_rows * public_s.mask_conv_cols; // number of elements
public_s.mask_conv_mem = sizeof(fp) * public_s.mask_conv_elem;
public_s.mask_conv_ioffset = (public_s.mask_rows-1)/2;
if((public_s.mask_rows-1) % 2 > 0.5){
public_s.mask_conv_ioffset = public_s.mask_conv_ioffset + 1;
}
public_s.mask_conv_joffset = (public_s.mask_cols-1)/2;
if((public_s.mask_cols-1) % 2 > 0.5){
public_s.mask_conv_joffset = public_s.mask_conv_joffset + 1;
}
for(i=0; i<public_s.allPoints; i++){
private_s[i].d_mask_conv = (fp *)malloc(public_s.mask_conv_mem);
}
//======================================================================================================================================================
// PRINT FRAME PROGRESS START
//======================================================================================================================================================
printf("frame progress: ");
fflush(NULL);
//======================================================================================================================================================
// KERNEL
//======================================================================================================================================================
for(public_s.frame_no=0; public_s.frame_no<frames_processed; public_s.frame_no++){
//====================================================================================================
// GETTING FRAME
//====================================================================================================
// Extract a cropped version of the first frame from the video file
public_s.d_frame = get_frame(public_s.d_frames, // pointer to video file
public_s.frame_no, // number of frame that needs to be returned
0, // cropped?
0, // scaled?
1); // converted
//====================================================================================================
// PROCESSING
//====================================================================================================
{ const unsigned long long parallel_for_start = current_time_ns();
#pragma omp parallel for
for(i=0; i<public_s.allPoints; i++){
kernel( public_s,
private_s[i]);
} ;
const unsigned long long parallel_for_end = current_time_ns();
printf("pragma546_omp_parallel %llu ns\n", parallel_for_end - parallel_for_start); }
//====================================================================================================
// FREE MEMORY FOR FRAME
//====================================================================================================
// free frame after each loop iteration, since AVI library allocates memory for every frame fetched
// free(public_s.d_frame);
//====================================================================================================
// PRINT FRAME PROGRESS
//====================================================================================================
printf("%d ", public_s.frame_no);
fflush(NULL);
} ;
//======================================================================================================================================================
// PRINT FRAME PROGRESS END
//======================================================================================================================================================
printf("\n");
fflush(NULL);
//======================================================================================================================================================
// DEALLOCATION
//======================================================================================================================================================
//==================================================50
// DUMP DATA TO FILE
//==================================================50
#ifdef OUTPUT
write_data( "result.txt",
public_s.frames,
frames_processed,
public_s.endoPoints,
public_s.d_tEndoRowLoc,
public_s.d_tEndoColLoc,
public_s.epiPoints,
public_s.d_tEpiRowLoc,
public_s.d_tEpiColLoc);
#endif
//====================================================================================================
// COMMON
//====================================================================================================
free(public_s.d_endoRow);
free(public_s.d_endoCol);
free(public_s.d_tEndoRowLoc);
free(public_s.d_tEndoColLoc);
free(public_s.d_endoT);
free(public_s.d_epiRow);
free(public_s.d_epiCol);
free(public_s.d_tEpiRowLoc);
free(public_s.d_tEpiColLoc);
free(public_s.d_epiT);
//====================================================================================================
// POINTERS
//====================================================================================================
for(i=0; i<public_s.allPoints; i++){
free(private_s[i].in_partial_sum);
free(private_s[i].in_sqr_partial_sum);
free(private_s[i].par_max_val);
free(private_s[i].par_max_coo);
free(private_s[i].d_in2);
free(private_s[i].d_in2_sqr);
free(private_s[i].d_in_mod);
free(private_s[i].d_in_sqr);
free(private_s[i].d_conv);
free(private_s[i].d_in2_pad);
free(private_s[i].d_in2_sub);
free(private_s[i].d_in2_sub2_sqr);
free(private_s[i].d_tMask);
free(private_s[i].d_mask_conv);
}
return 0;
}
//========================================================================================================================================================================================================
//========================================================================================================================================================================================================
// END OF FILE
//========================================================================================================================================================================================================
//========================================================================================================================================================================================================
|
helloomp1.c | #include <omp.h>
#include <stdio.h>
#include <stdlib.h>
int main () {
int num_thds, tid;
#pragma omp parallel
{
num_thds = omp_get_num_threads();
tid = omp_get_thread_num();
printf("Hello World from thread number %d out of %d threads\n ",tid,num_thds);
// if (tid == 0)
// {
// nthreads = omp_get_num_threads();
// printf("Number of threads = %d\n", nthreads);
// }
}
}
|
target-25.c | #include <stdlib.h>
#include <unistd.h>
int
main ()
{
int x = 0, y = 0, z = 0, s = 11, t = 12, u = 13, w = 7, err;
#pragma omp parallel
#pragma omp single
{
#pragma omp task depend(in: x)
{
usleep (5000);
x = 1;
}
#pragma omp task depend(in: x)
{
usleep (6000);
y = 2;
}
#pragma omp task depend(out: z)
{
usleep (7000);
z = 3;
}
#pragma omp target map(tofrom: x) map(from: err) map (to: y, z) depend(inout: x, z)
err = (x != 1 || y != 2 || z != 3);
if (err)
abort ();
#pragma omp task depend(in: x)
{
usleep (5000);
x = 4;
}
#pragma omp task depend(in: x)
{
usleep (4000);
y = 5;
}
#pragma omp task depend(in: z)
{
usleep (3000);
z = 6;
}
#pragma omp target enter data nowait map (to: w)
#pragma omp target enter data depend (inout: x, z) map (to: x, y, z)
#pragma omp target map (alloc: x, y, z) map(from: err)
{
err = (x != 4 || y != 5 || z != 6);
x = 7;
y = 8;
z = 9;
}
if (err)
abort ();
#pragma omp taskwait
#pragma omp target map (alloc: w) map(from: err)
{
err = w != 7;
w = 17;
}
if (err)
abort ();
#pragma omp task depend(in: x)
{
usleep (2000);
s = 14;
}
#pragma omp task depend(in: x)
{
usleep (3000);
t = 15;
}
#pragma omp task depend(in: z)
{
usleep (4000);
u = 16;
}
#pragma omp target exit data depend (inout: x, z) map (from: x, y, z, w)
if (x != 7 || y != 8 || z != 9 || s != 14 || t != 15 || u != 16 || w != 17)
abort ();
}
return 0;
}
|
opencl_blockchain_fmt_plug.c | /* blockchain "My Wallet" cracker patch for JtR. Hacked together during June of
* 2013 by Dhiru Kholia <dhiru at openwall.com>.
*
* See https://blockchain.info/wallet/wallet-format
* This software is Copyright (c) 2012 Lukas Odzioba <ukasz at openwall.net>
* and Copyright (c) 2013 Dhiru Kholia <dhiru at openwall.com>, and it is
* hereby released to the general public under the following terms:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted.
*
* improved dection, added iteration count and handle v2 hashes, Feb, 2015, JimF.
*/
#ifdef HAVE_OPENCL
#if FMT_EXTERNS_H
extern struct fmt_main fmt_opencl_blockchain;
#elif FMT_REGISTERS_H
john_register_one(&fmt_opencl_blockchain);
#else
#include <string.h>
#include "aes.h"
#ifdef _OPENMP
#include <omp.h>
#endif
#include "arch.h"
#include "formats.h"
#include "common.h"
#include "stdint.h"
#include "jumbo.h"
#include "common-opencl.h"
#include "options.h"
#define FORMAT_LABEL "blockchain-opencl"
#define FORMAT_NAME "blockchain My Wallet"
#define FORMAT_TAG "$blockchain$"
#define TAG_LENGTH 12
#define ALGORITHM_NAME "PBKDF2-SHA1 OpenCL AES"
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH -1
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
#define BINARY_SIZE 0
#define PLAINTEXT_LENGTH 64
#define SALT_SIZE sizeof(struct custom_salt)
#define BINARY_ALIGN MEM_ALIGN_WORD
#define SALT_ALIGN 4
#define BIG_ENOUGH (8192 * 32)
// increase me (in multiples of 16) to increase the decrypted and search area
#define SAFETY_FACTOR 160
typedef struct {
uint32_t length;
uint8_t v[PLAINTEXT_LENGTH];
} blockchain_password;
typedef struct {
uint32_t v[32/4];
} blockchain_hash;
typedef struct {
uint32_t iterations;
uint32_t outlen;
uint32_t skip_bytes;
uint8_t length;
uint8_t salt[64];
} blockchain_salt;
static int *cracked;
static int any_cracked;
static struct fmt_tests blockchain_tests[] = {
{"$blockchain$400$53741f25a90ef521c90bb2fd73673e64089ff2cca6ba3cbf6f34e0f80f960b2f60b9ac48df009dc30c288dcf1ade5f16c70a3536403fc11a68f242ba5ad3fcceae3ca5ecd23905997474260aa1357fc322b1434ffa026ba6ad33707c9ad5260e7230b87d8888a45ddc27513adb30af8755ec0737963ae6bb281318c48f224e9c748f6697f75f63f718bebb3401d6d5f02cf62b1701c205762c2f43119b68771ed10ddab79b5f74f56d611f61f77b8b65b5b5669756017429633118b8e5b8b638667e44154de4cc76468c4200eeebda2711a65333a7e3c423c8241e219cdca5ac47c0d4479444241fa27da20dba1a1d81e778a037d40d33ddea7c39e6d02461d97185f66a73deedff39bc53af0e9b04a3d7bf43648303c9f652d99630cd0789819376d68443c85f0eeb7af7c83eecddf25ea912f7721e3fb73ccaedf860f0f033ffc990ed73db441220d0cbe6e029676fef264dc2dc497f39bedf4041ba355d086134744d5a36e09515d230cd499eb20e0c574fb1bd9d994ce26f53f21d06dd58db4f8e0efbcaee7038df793bbb3daa96", "strongpassword"},
{"$blockchain$384$ece598c58b22a3b245a02039ce36bdf589a86b6344e802b4a3ac9b727cc0b6977e9509bc1ac4d1b7b9cbf9089ecdc89706f0a469325f7ee218b2212b6cd3e32677be20eee91e267fe13ebded02946d4ae1163ef22b3dca327d7390091247ac770288a0c7be181b21a48a8f945d9913cdfdc4cfd739ee3a41ced11cacde22e3233250e36f8b8fb4d81de5298a84374af75b88afda3438eed232e52aa0eb29e0d475456c86ae9d1aaadca14bc25f273c93fd4d7fd8316ed5306733bca77e8214277edd3155342abe0710985dc20b4f80e6620e386aa7658f92df25c7c932f0eb1beca25253662bd558647a3ba741f89450bfdba59a0c016477450fbcecd62226626e06ed2e3f5a4180e32d534c7769bcd1160aad840cfd3b7b13a90d34fedb3408fe74379a9e8a840fe3bfee8e0ee01f77ee389613fa750c3d2771b83eeb4e16598f76c15c311c325bd5d54543571aa20934060e332f451e58d67ad0f4635c0c021fa76821a68d64f1a5fb6fd70365eef4442cedcc91eb8696d52d078807edd89d", "qwertyuiop1"},
/* here is a v2 hash. NOTE, it uses 5000 pbkdf2 for the hash */
{"$blockchain$v2$5000$544$9a4d5157d4969636b2fe0738f77a376feda2fb979738c5cf0e712f5d4a2f001608824a865d25041bc85e0ad35985999fcfae7d218eb109a703781f57e7b5a03c29ffdfb756ec8ee38ed8941b056922cdd174c8e89feb40e1a0e1766792845f57992ae9d7667eff41a5e5580f3f289b050d76cc0f049cbd30c675efc3a553c0f19f30cb9589c7c3773dd095de92a991963789408351f543c1dc307751e5f781c278da77270035e3743df01ab4e41155b6437d9c7e64388a28f8331aca4822e6b89cdd5f45061b99768218d853a3575bbd029564826bcb188d55444273cda588d4e593fc5d29696713d747cfc8302a3e9c9dbb1bb3754c2e00f28b69d8faeb2e45c04085359c6a9b6bfecfd0a6a8f27ad647b6bfd498f2224a8c0442f7fe730656263ac2869923b296ad9955dbad515b4f88ad33619bdacc33ae7f14c65fce029e0f9e4a9c414716d9a23e4361aa264493bb6fc9a7fda82599b0232174b9fc92a1c717ca2cc6deb8bd6aaf3706b95fdfdc582316cb3d271178dafe3a6704a918e07be057bef676bb144840c7f26676f183f2744fc2fe22c9c3feb7461b4383981c00b6fff403fef578f6e5464dc2d0bcb7b8d0dc2e7add502b34c8fe9f9b638eebe7ede25e351b17ea8b8c1f5213b69780c0ba7ef3d5734c0635e9d2ee49524914f047d45536180be25e7610db809db694ceeb16a3bfd8abd5ab0cda4415203408387698fe707568566f7f567164707091a806ac2d11b9b9dd0c3c991ff037f457", "Openwall1234#"},
/* this is the 'raw' hash to the line above. We do not handle this yet, but probably should. It is also mime, and not base-16 */
//{"{\"pbkdf2_iterations\":5000,\"version\":2,\"payload\":\"mk1RV9SWljay/gc493o3b+2i+5eXOMXPDnEvXUovABYIgkqGXSUEG8heCtNZhZmfz659IY6xCacDeB9X57WgPCn/37dW7I7jjtiUGwVpIs3RdMjon+tA4aDhdmeShF9XmSrp12Z+/0Gl5VgPPyibBQ12zA8EnL0wxnXvw6VTwPGfMMuVicfDdz3Qld6SqZGWN4lAg1H1Q8HcMHdR5feBwnjadycANeN0PfAatOQRVbZDfZx+ZDiKKPgzGspIIua4nN1fRQYbmXaCGNhTo1dbvQKVZIJryxiNVURCc82liNTlk/xdKWlnE9dHz8gwKj6cnbsbs3VMLgDyi2nY+usuRcBAhTWcaptr/s/QpqjyetZHtr/UmPIiSowEQvf+cwZWJjrChpkjspatmVXbrVFbT4itM2Gb2swzrn8Uxl/OAp4PnkqcQUcW2aI+Q2GqJkSTu2/Jp/2oJZmwIyF0ufySoccXyizG3ri9aq83Brlf39xYIxbLPScReNr+OmcEqRjge+BXvvZ2uxRIQMfyZnbxg/J0T8L+IsnD/rdGG0ODmBwAtv/0A/71ePblRk3C0Ly3uNDcLnrdUCs0yP6fm2OO6+ft4l41Gxfqi4wfUhO2l4DAun7z1XNMBjXp0u5JUkkU8EfUVTYYC+JedhDbgJ22lM7rFqO/2KvVqwzaRBUgNAg4dpj+cHVoVm9/VnFkcHCRqAasLRG5ud0MPJkf8Df0Vw==\"}", "Openwall1234#"},
{NULL}
};
static struct custom_salt {
unsigned char data[BIG_ENOUGH];
int length;
int iter;
} *cur_salt;
static cl_int cl_error;
static blockchain_password *inbuffer;
static blockchain_hash *outbuffer;
static blockchain_salt currentsalt;
static cl_mem mem_in, mem_out, mem_setting;
static struct fmt_main *self;
size_t insize, outsize, settingsize, cracked_size;
#define STEP 0
#define SEED 256
// This file contains auto-tuning routine(s). Has to be included after formats definitions.
#include "opencl-autotune.h"
#include "memdbg.h"
static const char * warn[] = {
"xfer: ", ", crypt: ", ", xfer: "
};
/* ------- Helper functions ------- */
static size_t get_task_max_work_group_size()
{
return autotune_get_task_max_work_group_size(FALSE, 0, crypt_kernel);
}
static void create_clobj(size_t gws, struct fmt_main *self)
{
insize = sizeof(blockchain_password) * gws;
outsize = sizeof(blockchain_hash) * gws;
settingsize = sizeof(blockchain_salt);
cracked_size = sizeof(*cracked) * gws;
inbuffer = mem_calloc(1, insize);
outbuffer = mem_alloc(outsize);
cracked = mem_calloc(1, cracked_size);
/// Allocate memory
mem_in =
clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, insize, NULL,
&cl_error);
HANDLE_CLERROR(cl_error, "Error allocating mem in");
mem_setting =
clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, settingsize,
NULL, &cl_error);
HANDLE_CLERROR(cl_error, "Error allocating mem setting");
mem_out =
clCreateBuffer(context[gpu_id], CL_MEM_WRITE_ONLY, outsize, NULL,
&cl_error);
HANDLE_CLERROR(cl_error, "Error allocating mem out");
HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 0, sizeof(mem_in),
&mem_in), "Error while setting mem_in kernel argument");
HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 1, sizeof(mem_out),
&mem_out), "Error while setting mem_out kernel argument");
HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 2, sizeof(mem_setting),
&mem_setting), "Error while setting mem_salt kernel argument");
}
static void release_clobj(void)
{
if (cracked) {
HANDLE_CLERROR(clReleaseMemObject(mem_in), "Release mem in");
HANDLE_CLERROR(clReleaseMemObject(mem_setting), "Release mem setting");
HANDLE_CLERROR(clReleaseMemObject(mem_out), "Release mem out");
MEM_FREE(inbuffer);
MEM_FREE(outbuffer);
MEM_FREE(cracked);
}
}
static void done(void)
{
if (autotuned) {
release_clobj();
HANDLE_CLERROR(clReleaseKernel(crypt_kernel), "Release kernel");
HANDLE_CLERROR(clReleaseProgram(program[gpu_id]), "Release Program");
autotuned--;
}
}
static void init(struct fmt_main *_self)
{
self = _self;
opencl_prepare_dev(gpu_id);
}
static void reset(struct db_main *db)
{
if (!autotuned) {
char build_opts[64];
snprintf(build_opts, sizeof(build_opts),
"-DKEYLEN=%d -DSALTLEN=%d -DOUTLEN=%d",
PLAINTEXT_LENGTH,
(int)sizeof(currentsalt.salt),
(int)sizeof(outbuffer->v));
opencl_init("$JOHN/kernels/pbkdf2_hmac_sha1_unsplit_kernel.cl",
gpu_id, build_opts);
crypt_kernel = clCreateKernel(program[gpu_id], "derive_key", &cl_error);
HANDLE_CLERROR(cl_error, "Error creating kernel");
// Initialize openCL tuning (library) for this format.
opencl_init_auto_setup(SEED, 0, NULL, warn, 1, self,
create_clobj, release_clobj,
sizeof(blockchain_password), 0, db);
// Auto tune execution from shared/included code.
autotune_run(self, 1, 0, 1000);
}
}
static int valid(char *ciphertext, struct fmt_main *self)
{
char *ctcopy, *keeptr, *p;
int len, extra;
if (strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH) != 0)
return 0;
ctcopy = strdup(ciphertext);
keeptr = ctcopy;
ctcopy += TAG_LENGTH;
if ((p = strtokm(ctcopy, "$")) == NULL)
goto err;
if (!strcmp(p, "v2")) {
if ((p = strtokm(NULL, "$")) == NULL)
goto err;
if (!isdec(p))
goto err;
if ((p = strtokm(NULL, "$")) == NULL)
goto err;
}
if (!isdec(p))
goto err;
len = atoi(p);
if(len > BIG_ENOUGH || !len)
goto err;
if ((p = strtokm(NULL, "$")) == NULL)
goto err;
if (hexlenl(p, &extra) != len * 2 || extra)
goto err;
MEM_FREE(keeptr);
return 1;
err:
MEM_FREE(keeptr);
return 0;
}
static void *get_salt(char *ciphertext)
{
char *ctcopy = strdup(ciphertext);
char *keeptr = ctcopy;
int i;
char *p;
static union {
struct custom_salt _cs;
ARCH_WORD_32 dummy;
} un;
struct custom_salt *cs = &(un._cs);
memset(&un, 0, sizeof(un));
ctcopy += TAG_LENGTH;
p = strtokm(ctcopy, "$");
if (!strcmp(p, "v2")) {
p = strtokm(NULL, "$");
cs->iter = atoi(p);
p = strtokm(NULL, "$");
} else
cs->iter = 10;
cs->length = atoi(p);
p = strtokm(NULL, "$");
for (i = 0; i < cs->length; i++)
cs->data[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16
+ atoi16[ARCH_INDEX(p[i * 2 + 1])];
MEM_FREE(keeptr);
return (void *)cs;
}
static void set_salt(void *salt)
{
cur_salt = (struct custom_salt *)salt;
memcpy((char*)currentsalt.salt, cur_salt->data, 16);
currentsalt.length = 16;
currentsalt.iterations = cur_salt->iter;
currentsalt.outlen = 32;
currentsalt.skip_bytes = 0;
HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_setting,
CL_FALSE, 0, settingsize, ¤tsalt, 0, NULL, NULL),
"Copy salt to gpu");
}
#undef set_key
static void set_key(char *key, int index)
{
uint8_t length = strlen(key);
if (length > PLAINTEXT_LENGTH)
length = PLAINTEXT_LENGTH;
inbuffer[index].length = length;
memcpy(inbuffer[index].v, key, length);
}
static char *get_key(int index)
{
static char ret[PLAINTEXT_LENGTH + 1];
uint8_t length = inbuffer[index].length;
memcpy(ret, inbuffer[index].v, length);
ret[length] = '\0';
return ret;
}
static int blockchain_decrypt(unsigned char *derived_key, unsigned char *data)
{
unsigned char out[SAFETY_FACTOR];
AES_KEY akey;
unsigned char iv[16];
memcpy(iv, cur_salt->data, 16);
if(AES_set_decrypt_key(derived_key, 256, &akey) < 0) {
fprintf(stderr, "AES_set_decrypt_key failed in crypt!\n");
}
AES_cbc_encrypt(data + 16, out, 16, &akey, iv, AES_DECRYPT);
/* various tests */
if (out[0] != '{') // fast test
return -1;
// "guid" will be found in the first block
if (memmem(out, 16, "\"guid\"", 6)) {
memcpy(iv, cur_salt->data, 16); //IV has to be reset.
AES_cbc_encrypt(data + 16, out, SAFETY_FACTOR, &akey, iv, AES_DECRYPT);
if (memmem(out, SAFETY_FACTOR, "\"sharedKey\"", 11) &&
memmem(out, SAFETY_FACTOR, "\"options\"", 9))
// Note, we 'could' check that the guid and sharedKey values are
// 'valid' GUID's, but there really is no point. We already have
// 2^216 confidence in the simple text strings being found.
return 0;
}
return -1;
}
static int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
int index;
size_t *lws = local_work_size ? &local_work_size : NULL;
global_work_size = GET_MULTIPLE_OR_BIGGER(count, local_work_size);
if (any_cracked) {
memset(cracked, 0, cracked_size);
any_cracked = 0;
}
/// Copy data to gpu
BENCH_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_in, CL_FALSE, 0,
insize, inbuffer, 0, NULL, multi_profilingEvent[0]),
"Copy data to gpu");
/// Run kernel
BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], crypt_kernel, 1,
NULL, &global_work_size, lws, 0, NULL,
multi_profilingEvent[1]), "Run kernel");
/// Read the result back
BENCH_CLERROR(clEnqueueReadBuffer(queue[gpu_id], mem_out, CL_TRUE, 0,
outsize, outbuffer, 0, NULL, multi_profilingEvent[2]), "Copy result back");
if (ocl_autotune_running)
return count;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (index = 0; index < count; index++)
if (!blockchain_decrypt((unsigned char*)outbuffer[index].v, cur_salt->data))
{
cracked[index] = 1;
#ifdef _OPENMP
#pragma omp atomic
#endif
any_cracked |= 1;
}
return count;
}
static int cmp_all(void *binary, int count)
{
return any_cracked;
}
static int cmp_one(void *binary, int index)
{
return cracked[index];
}
static int cmp_exact(char *source, int index)
{
return 1;
}
struct fmt_main fmt_opencl_blockchain = {
{
FORMAT_LABEL,
FORMAT_NAME,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_CASE | FMT_8_BIT | FMT_OMP,
{ NULL },
{ FORMAT_TAG },
blockchain_tests
}, {
init,
done,
reset,
fmt_default_prepare,
valid,
fmt_default_split,
fmt_default_binary,
get_salt,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash
},
fmt_default_salt_hash,
NULL,
set_salt,
set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
fmt_default_get_hash
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
#endif /* HAVE_OPENCL */
|
residualbased_elimination_builder_and_solver_with_constraints.h | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: Vicente Mataix Ferrandiz
//
//
#if !defined(KRATOS_RESIDUAL_BASED_ELIMINATION_BUILDER_AND_SOLVER_WITH_CONSTRAINTS)
#define KRATOS_RESIDUAL_BASED_ELIMINATION_BUILDER_AND_SOLVER_WITH_CONSTRAINTS
/* System includes */
#include <unordered_set>
#include <unordered_map>
/* External includes */
/* Project includes */
#include "solving_strategies/builder_and_solvers/residualbased_elimination_builder_and_solver.h"
#include "utilities/sparse_matrix_multiplication_utility.h"
#include "utilities/constraint_utilities.h"
#include "input_output/logger.h"
namespace Kratos
{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/**
* @class ResidualBasedEliminationBuilderAndSolverWithConstraints
* @ingroup KratosCore
* @brief Current class provides an implementation for standard builder and solving operations.
* @details The RHS is constituted by the unbalanced loads (residual)
* Degrees of freedom are reordered putting the restrained degrees of freedom at
* the end of the system ordered in reverse order with respect to the DofSet.
* Imposition of the dirichlet conditions is naturally dealt with as the residual already contains
* this information.
* Calculation of the reactions involves a cost very similiar to the calculation of the total residual
* The system is build in the following manner. A T matrix is assembled and constant vector g is assembled too. The T matrix contains the relations of all the dofs of the system, even the nodes with no master/slave relation. Then the size is n_total x n_red
* The relation u = T u_red
* Then:
* A_red = T^t A T
* b_red = T^t (b - A g)
* @todo There is a more efficient way to asemble the system, but more costly, which is the following. In this case T will be only a relation matrix between master and slave dofs. Then n_slave x n_master: us = T um + g
* Separating into independent dofs, master ans slave dofs:
* u = uu
* um
* us
* A = Auu Aum Aus
* Amu Amm Ams
* Asu Asm Ass
* b = bu
* bm
* bs
* Finally:
* A_red = Auu Aum + Aus T
* Amu + T^t Asu Amm + T^t Ams^t + Ams T + T^t Ass T
* b_red = bu - Aus g
* bm - Ams g
*
* This system requires extra care and is more complicated and requires to compute the blocks properly
* @author Vicente Mataix Ferrandiz
*/
template <class TSparseSpace,
class TDenseSpace,
class TLinearSolver
>
class ResidualBasedEliminationBuilderAndSolverWithConstraints
: public ResidualBasedEliminationBuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver>
{
public:
///@name Type Definitions
///@{
/// Pointer definition of ResidualBasedEliminationBuilderAndSolverWithConstraints
KRATOS_CLASS_POINTER_DEFINITION(ResidualBasedEliminationBuilderAndSolverWithConstraints);
/// Definition of the base class
typedef ResidualBasedEliminationBuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver> BaseType;
// The size_t types
typedef std::size_t SizeType;
typedef std::size_t IndexType;
/// Definition of the classes from the base class
typedef typename BaseType::TSchemeType TSchemeType;
typedef typename BaseType::TDataType TDataType;
typedef typename BaseType::DofsArrayType DofsArrayType;
typedef typename BaseType::TSystemMatrixType TSystemMatrixType;
typedef typename BaseType::TSystemVectorType TSystemVectorType;
typedef typename BaseType::LocalSystemVectorType LocalSystemVectorType;
typedef typename BaseType::LocalSystemMatrixType LocalSystemMatrixType;
typedef typename BaseType::TSystemMatrixPointerType TSystemMatrixPointerType;
typedef typename BaseType::TSystemVectorPointerType TSystemVectorPointerType;
typedef typename BaseType::NodeType NodeType;
typedef typename BaseType::NodesArrayType NodesArrayType;
typedef typename BaseType::ElementsArrayType ElementsArrayType;
typedef typename BaseType::ConditionsArrayType ConditionsArrayType;
/// Additional definitions
typedef PointerVectorSet<Element, IndexedObject> ElementsContainerType;
typedef Element::EquationIdVectorType EquationIdVectorType;
typedef Element::DofsVectorType DofsVectorType;
typedef boost::numeric::ublas::compressed_matrix<double> CompressedMatrixType;
/// DoF types definition
typedef typename NodeType::DofType DofType;
typedef typename DofType::Pointer DofPointerType;
/// Set definition
typedef std::unordered_set<IndexType> IndexSetType;
/// Map definition
typedef std::unordered_map<IndexType, IndexType> IndexMapType;
/// MPC definitions
typedef MasterSlaveConstraint MasterSlaveConstraintType;
typedef typename MasterSlaveConstraint::Pointer MasterSlaveConstraintPointerType;
typedef std::vector<IndexType> VectorIndexType;
typedef Vector VectorType;
///@}
///@name Enum's
///@{
///@}
///@name Life Cycle
///@{
/**
* @brief Default constructor. (with parameters)
*/
explicit ResidualBasedEliminationBuilderAndSolverWithConstraints(
typename TLinearSolver::Pointer pNewLinearSystemSolver,
Parameters ThisParameters
) : BaseType(pNewLinearSystemSolver)
{
// Validate default parameters
Parameters default_parameters = Parameters(R"(
{
"name" : "ResidualBasedEliminationBuilderAndSolverWithConstraints",
"check_constraint_relation" : true,
"reset_relation_matrix_each_iteration" : true
})" );
ThisParameters.ValidateAndAssignDefaults(default_parameters);
mCheckConstraintRelation = ThisParameters["check_constraint_relation"].GetBool();
mResetRelationMatrixEachIteration = ThisParameters["reset_relation_matrix_each_iteration"].GetBool();
}
/**
* @brief Default constructor
*/
explicit ResidualBasedEliminationBuilderAndSolverWithConstraints(
typename TLinearSolver::Pointer pNewLinearSystemSolver,
const bool CheckConstraintRelation = true,
const bool ResetRelationMatrixEachIteration = false
)
: BaseType(pNewLinearSystemSolver),
mCheckConstraintRelation(CheckConstraintRelation),
mResetRelationMatrixEachIteration(ResetRelationMatrixEachIteration)
{
}
/** Destructor.
*/
~ResidualBasedEliminationBuilderAndSolverWithConstraints() override
{
}
///@}
///@name Operators
///@{
///@}
///@name Operations
///@{
void SetUpSystem(ModelPart& rModelPart) override
{
if(rModelPart.MasterSlaveConstraints().size() > 0)
SetUpSystemWithConstraints(rModelPart);
else
BaseType::SetUpSystem(rModelPart);
}
/**
* @brief Function to perform the build of the RHS. The vector could be sized as the total number
* of dofs or as the number of unrestrained ones
* @param pScheme The integration scheme considered
* @param rModelPart The model part of the problem to solve
* @param rA The LHS matrix
* @param rb The RHS vector
*/
void Build(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemMatrixType& rA,
TSystemVectorType& rb
) override
{
if(rModelPart.MasterSlaveConstraints().size() > 0)
BuildWithConstraints(pScheme, rModelPart, rA, rb);
else
BaseType::Build(pScheme, rModelPart, rA, rb);
}
/**
* @brief Function to perform the building and solving phase at the same time.
* @details It is ideally the fastest and safer function to use when it is possible to solve
* just after building
* @param pScheme The integration scheme considered
* @param rModelPart The model part of the problem to solve
* @param A The LHS matrix
* @param Dx The Unknowns vector
* @param b The RHS vector
*/
void BuildAndSolve(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemMatrixType& A,
TSystemVectorType& Dx,
TSystemVectorType& b) override
{
if(rModelPart.MasterSlaveConstraints().size() > 0)
BuildAndSolveWithConstraints(pScheme, rModelPart, A, Dx, b);
else
BaseType::BuildAndSolve(pScheme, rModelPart, A, Dx, b);
}
/**
* @brief Function to perform the build of the RHS.
* @details The vector could be sized as the total number of dofs or as the number of unrestrained ones
* @param pScheme The integration scheme considered
* @param rModelPart The model part of the problem to solve
*/
void BuildRHS(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemVectorType& b) override
{
KRATOS_TRY
if(rModelPart.MasterSlaveConstraints().size() > 0)
BuildRHSWithConstraints(pScheme, rModelPart, b);
else
BaseType::BuildRHS(pScheme, rModelPart, b);
KRATOS_CATCH("")
}
/**
* @brief Builds the list of the DofSets involved in the problem by "asking" to each element
* and condition its Dofs.
* @details The list of dofs is stores insde the BuilderAndSolver as it is closely connected to the
* way the matrix and RHS are built
* @param pScheme The integration scheme considered
* @param rModelPart The model part of the problem to solve
*/
void SetUpDofSet(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart
) override
{
if(rModelPart.MasterSlaveConstraints().size() > 0)
SetUpDofSetWithConstraints(pScheme, rModelPart);
else
BaseType::SetUpDofSet(pScheme, rModelPart);
}
/**
* @brief It applies certain operations at the system of equations at the begining of the solution step
* @param rModelPart The model part to compute
* @param rA The LHS matrix of the system of equations
* @param rDx The vector of unkowns
* @param rb The RHS vector of the system of equations
*/
void InitializeSolutionStep(
ModelPart& rModelPart,
TSystemMatrixType& rA,
TSystemVectorType& rDx,
TSystemVectorType& rb
) override
{
KRATOS_TRY
BaseType::InitializeSolutionStep(rModelPart, rA, rDx, rb);
// Getting process info
const ProcessInfo& r_process_info = rModelPart.GetProcessInfo();
// Computing constraints
const int n_constraints = static_cast<int>(rModelPart.MasterSlaveConstraints().size());
auto constraints_begin = rModelPart.MasterSlaveConstraintsBegin();
#pragma omp parallel for schedule(guided, 512) firstprivate(n_constraints, constraints_begin)
for (int k = 0; k < n_constraints; ++k) {
auto it = constraints_begin + k;
it->InitializeSolutionStep(r_process_info); // Here each constraint constructs and stores its T and C matrices. Also its equation slave_ids.
}
KRATOS_CATCH("ResidualBasedEliminationBuilderAndSolverWithConstraints failed to initialize solution step.")
}
/**
* @brief It applies certain operations at the system of equations at the end of the solution step
* @param rModelPart The model part to compute
* @param rA The LHS matrix of the system of equations
* @param rDx The vector of unkowns
* @param rb The RHS vector of the system of equations
*/
void FinalizeSolutionStep(
ModelPart& rModelPart,
TSystemMatrixType& rA,
TSystemVectorType& rDx,
TSystemVectorType& rb
) override
{
KRATOS_TRY
BaseType::FinalizeSolutionStep(rModelPart, rA, rDx, rb);
// Getting process info
const ProcessInfo& r_process_info = rModelPart.GetProcessInfo();
// Computing constraints
const int n_constraints = static_cast<int>(rModelPart.MasterSlaveConstraints().size());
const auto constraints_begin = rModelPart.MasterSlaveConstraintsBegin();
#pragma omp parallel for schedule(guided, 512) firstprivate(n_constraints, constraints_begin)
for (int k = 0; k < n_constraints; ++k) {
auto it = constraints_begin + k;
it->FinalizeSolutionStep(r_process_info);
}
KRATOS_CATCH("ResidualBasedEliminationBuilderAndSolverWithConstraints failed to finalize solution step.")
}
///@}
///@name Access
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Input and output
///@{
/// Turn back information as a string.
std::string Info() const override
{
return "ResidualBasedEliminationBuilderAndSolverWithConstraints";
}
/// 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
///@{
TSystemMatrixPointerType mpTMatrix = NULL; /// This is matrix containing the global relation for the constraints
TSystemMatrixPointerType mpOldAMatrix = NULL; /// This is matrix containing the old LHS structure
TSystemVectorPointerType mpConstantVector = NULL; /// This is vector containing the rigid movement of the constraint
TSystemVectorPointerType mpDeltaConstantVector = NULL; /// This is vector contains the effective constant displacement
DofsArrayType mDoFMasterFixedSet; /// The set containing the fixed master DoF of the system
DofsArrayType mDoFSlaveSet; /// The set containing the slave DoF of the system
SizeType mDoFToSolveSystemSize = 0; /// Number of degrees of freedom of the problem to actually be solved
IndexMapType mReactionEquationIdMap; /// In order to know the corresponding EquaionId for each component of the reaction vector
bool mCheckConstraintRelation = false; /// If we do a constraint check relation
bool mResetRelationMatrixEachIteration = false; /// If we reset the relation matrix at each iteration
bool mComputeConstantContribution = false; /// If we compute the constant contribution of the MPC
bool mCleared = true; /// If the system has been reseted
///@}
///@name Protected Operators
///@{
///@}
///@name Protected Operations
///@{
/**
* @brief This method assembles the global relation matrix (T matrix used to impose the MPC)
* @param rT The global relation matrix
* @param rTransformationMatrix The local transformation contribution
* @param rSlaveEquationId The equation id of the slave dofs
* @param rMasterEquationId The equation id of the master dofs
*/
void AssembleRelationMatrix(
TSystemMatrixType& rT,
const LocalSystemMatrixType& rTransformationMatrix,
const EquationIdVectorType& rSlaveEquationId,
const EquationIdVectorType& rMasterEquationId
)
{
const SizeType local_size_1 = rTransformationMatrix.size1();
for (IndexType i_local = 0; i_local < local_size_1; ++i_local) {
IndexType i_global = rSlaveEquationId[i_local];
if (i_global < BaseType::mEquationSystemSize) {
BaseType::AssembleRowContributionFreeDofs(rT, rTransformationMatrix, i_global, i_local, rMasterEquationId);
}
}
}
/**
* @brief This method construcs the relationship between the DoF
* @param pScheme The integration scheme
* @param rA The LHS of the system
* @param rModelPart The model part which defines the problem
*/
void ConstructMatrixStructure(
typename TSchemeType::Pointer pScheme,
TSystemMatrixType& rA,
ModelPart& rModelPart
) override
{
if(rModelPart.MasterSlaveConstraints().size() > 0)
ConstructMatrixStructureWithConstraints(pScheme, rA, rModelPart);
else
BaseType::ConstructMatrixStructure(pScheme, rA, rModelPart);
}
/**
* @brief The same methods as the base class but with constraints
* @param pScheme The pointer to the integration scheme
* @param rModelPart The model part to compute
* @param rA The LHS matrix of the system of equations
* @param rDx The vector of unkowns
* @param rb The RHS vector of the system of equations
*/
void BuildAndSolveWithConstraints(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemMatrixType& rA,
TSystemVectorType& rDx,
TSystemVectorType& rb
)
{
KRATOS_TRY
Timer::Start("Build");
// We apply the master/slave relationship before build
ApplyMasterSlaveRelation(pScheme, rModelPart, rA, rDx, rb);
// We compute the effective constant vector
TSystemVectorType dummy_Dx(mDoFToSolveSystemSize);
TSparseSpace::SetToZero(dummy_Dx);
ComputeEffectiveConstant(pScheme, rModelPart, dummy_Dx);
// We do the build (after that we resize the solution vector to avoid problems)
BuildWithConstraints(pScheme, rModelPart, rA, rb);
Timer::Stop("Build");
// Now we apply the BC
rDx.resize(mDoFToSolveSystemSize, false);
ApplyDirichletConditions(pScheme, rModelPart, rA, rDx, rb);
KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", (this->GetEchoLevel() == 3)) <<
"Before the solution of the system" << "\nSystem Matrix = " << rA << "\nUnknowns vector = " << rDx << "\nRHS vector = " << rb << std::endl;
// We solve the system of equations
const double start_solve = OpenMPUtils::GetCurrentTime();
Timer::Start("Solve");
SystemSolveWithPhysics(rA, rDx, rb, rModelPart);
Timer::Stop("Solve");
const double stop_solve = OpenMPUtils::GetCurrentTime();
// We compute the effective constant vector
ComputeEffectiveConstant(pScheme, rModelPart, rDx);
// We reconstruct the Unknowns vector and the residual
const double start_reconstruct_slaves = OpenMPUtils::GetCurrentTime();
ReconstructSlaveSolutionAfterSolve(pScheme, rModelPart, rA, rDx, rb);
const double stop_reconstruct_slaves = OpenMPUtils::GetCurrentTime();
KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", (this->GetEchoLevel() >= 1 && rModelPart.GetCommunicator().MyPID() == 0)) << "Reconstruct slaves time: " << stop_reconstruct_slaves - start_reconstruct_slaves << std::endl;
// Some verbosity
KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", (this->GetEchoLevel() >= 1 && rModelPart.GetCommunicator().MyPID() == 0)) << "System solve time: " << stop_solve - start_solve << std::endl;
KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", (this->GetEchoLevel() == 3)) <<
"After the solution of the system" << "\nSystem Matrix = " << rA << "\nUnknowns vector = " << rDx << "\nRHS vector = " << rb << std::endl;
KRATOS_CATCH("")
}
/**
* @brief The same methods as the base class but with constraints
* @param pScheme The pointer to the integration scheme
* @param rModelPart The model part to compute
* @param rb The RHS vector of the system of equations
*/
void BuildRHSWithConstraints(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemVectorType& rb
)
{
Timer::Start("Build RHS");
// Resetting to zero the vector of reactions
if(BaseType::mCalculateReactionsFlag) {
TSparseSpace::SetToZero(*(BaseType::mpReactionsVector));
}
// Builing without BC
BuildRHSNoDirichlet(pScheme,rModelPart,rb);
Timer::Stop("Build RHS");
ApplyDirichletConditionsRHS(pScheme, rModelPart, rb);
// We get the global T matrix
const TSystemMatrixType& rTMatrix = *mpTMatrix;
// Reconstruct the RHS
TSystemVectorType rb_copy = rb;
rb.resize(BaseType::mEquationSystemSize, false);
TSparseSpace::Mult(rTMatrix, rb_copy, rb);
// Adding contribution to reactions
TSystemVectorType& r_reactions_vector = *BaseType::mpReactionsVector;
if (BaseType::mCalculateReactionsFlag) {
for (auto& r_dof : BaseType::mDofSet) {
const bool is_master_fixed = mDoFMasterFixedSet.find(r_dof) == mDoFMasterFixedSet.end() ? false : true;
const bool is_slave = mDoFSlaveSet.find(r_dof) == mDoFSlaveSet.end() ? false : true;
if (is_master_fixed || is_slave) { // Fixed or MPC dof
const IndexType equation_id = r_dof.EquationId();
r_reactions_vector[mReactionEquationIdMap[equation_id]] += rb[equation_id];
}
}
}
// Some verbosity
KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", (this->GetEchoLevel() == 3)) <<
"After the solution of the system" << "\nRHS vector = " << rb << std::endl;
}
/**
* @brief Builds the list of the DofSets involved in the problem by "asking" to each element and condition its Dofs.
* @details Equivalent to the ResidualBasedEliminationBuilderAndSolver but with constraints. The list of dofs is stores insde the BuilderAndSolver as it is closely connected to the way the matrix and RHS are built
* @param pScheme The integration scheme considered
* @param rModelPart The model part of the problem to solve
*/
void SetUpDofSetWithConstraints(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart
)
{
KRATOS_TRY;
KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", ( this->GetEchoLevel() > 1 && rModelPart.GetCommunicator().MyPID() == 0)) << "Setting up the dofs" << std::endl;
DofsVectorType dof_list, second_dof_list; // NOTE: The second dof list is only used on constraints to include master/slave relations
typedef std::unordered_set < DofPointerType, DofPointerHasher> set_type;
// Declaring temporal variables
DofsArrayType dof_temp_all, dof_temp_solvable, dof_temp_slave;
// We assign an empty dof array to our dof sets
BaseType::mDofSet = DofsArrayType(); /// This corresponds with all the DoF of the system
mDoFSlaveSet = DofsArrayType(); /// This corresponds with the slave (the ones not solved after compacting the system using MPC)
/**
* Here we declare three sets.
* - The global set: Contains all the DoF of the system
* - The slave set: The DoF that are not going to be solved, due to MPC formulation
*/
set_type dof_global_set, dof_global_slave_set;
#pragma omp parallel firstprivate(dof_list, second_dof_list)
{
ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo();
// We cleate the temporal set and we reserve some space on them
set_type dofs_tmp_set, dof_temp_slave_set;
dofs_tmp_set.reserve(20000);
dof_temp_slave_set.reserve(200);
// Gets the array of elements from the modeler
ElementsArrayType& r_elements_array = rModelPart.Elements();
const int number_of_elements = static_cast<int>(r_elements_array.size());
#pragma omp for schedule(guided, 512) nowait
for (int i = 0; i < number_of_elements; ++i) {
auto it_elem = r_elements_array.begin() + i;
// Gets list of Dof involved on every element
pScheme->GetElementalDofList(*(it_elem.base()), dof_list, r_current_process_info);
dofs_tmp_set.insert(dof_list.begin(), dof_list.end());
}
// Gets the array of conditions from the modeler
ConditionsArrayType& r_conditions_array = rModelPart.Conditions();
const int number_of_conditions = static_cast<int>(r_conditions_array.size());
#pragma omp for schedule(guided, 512) nowait
for (int i = 0; i < number_of_conditions; ++i) {
auto it_cond = r_conditions_array.begin() + i;
// Gets list of Dof involved on every element
pScheme->GetConditionDofList(*(it_cond.base()), dof_list, r_current_process_info);
dofs_tmp_set.insert(dof_list.begin(), dof_list.end());
}
// Gets the array of constraints from the modeler
auto& r_constraints_array = rModelPart.MasterSlaveConstraints();
const int number_of_constraints = static_cast<int>(r_constraints_array.size());
#pragma omp for schedule(guided, 512) nowait
for (int i = 0; i < number_of_constraints; ++i) {
auto it_const = r_constraints_array.begin() + i;
// Gets list of Dof involved on every element
it_const->GetDofList(dof_list, second_dof_list, r_current_process_info);
dofs_tmp_set.insert(dof_list.begin(), dof_list.end());
dofs_tmp_set.insert(second_dof_list.begin(), second_dof_list.end());
dof_temp_slave_set.insert(dof_list.begin(), dof_list.end());
}
// We merge all the sets in one thread
#pragma omp critical
{
dof_global_set.insert(dofs_tmp_set.begin(), dofs_tmp_set.end());
dof_global_slave_set.insert(dof_temp_slave_set.begin(), dof_temp_slave_set.end());
}
}
KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", ( this->GetEchoLevel() > 2)) << "Initializing ordered array filling\n" << std::endl;
/// We transfer the temporal sets to our DoF set
dof_temp_all.reserve(dof_global_set.size());
for (auto p_dof : dof_global_set) {
dof_temp_all.push_back( p_dof );
}
dof_temp_all.Sort();
BaseType::mDofSet = dof_temp_all;
dof_temp_slave.reserve(dof_global_slave_set.size());
for (auto p_dof : dof_global_slave_set) {
dof_temp_slave.push_back( p_dof );
}
dof_temp_slave.Sort();
mDoFSlaveSet = dof_temp_slave;
// Throws an exception if there are no Degrees Of Freedom involved in the analysis
KRATOS_ERROR_IF(BaseType::mDofSet.size() == 0) << "No degrees of freedom!" << std::endl;
KRATOS_WARNING_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", mDoFSlaveSet.size() == 0) << "No slave degrees of freedom to solve!" << std::endl;
KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", ( this->GetEchoLevel() > 2)) << "Number of degrees of freedom:" << BaseType::mDofSet.size() << std::endl;
BaseType::mDofSetIsInitialized = true;
KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", ( this->GetEchoLevel() > 2 && rModelPart.GetCommunicator().MyPID() == 0)) << "Finished setting up the dofs" << std::endl;
#ifdef USE_LOCKS_IN_ASSEMBLY
KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", ( this->GetEchoLevel() > 2)) << "Initializing lock array" << std::endl;
if (BaseType::mLockArray.size() != 0) {
for (int i = 0; i < static_cast<int>(BaseType::mLockArray.size()); ++i) {
omp_destroy_lock(&BaseType::mLockArray[i]);
}
}
BaseType::mLockArray.resize(BaseType::mDofSet.size());
for (int i = 0; i < static_cast<int>(BaseType::mLockArray.size()); ++i) {
omp_init_lock(&BaseType::mLockArray[i]);
}
KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", ( this->GetEchoLevel() > 2)) << "End of setup dof set\n" << std::endl;
#endif
// If reactions are to be calculated, we check if all the dofs have reactions defined
// This is tobe done only in debug mode
#ifdef KRATOS_DEBUG
if(BaseType::GetCalculateReactionsFlag()) {
for(auto dof_iterator = BaseType::mDofSet.begin(); dof_iterator != BaseType::mDofSet.end(); ++dof_iterator) {
KRATOS_ERROR_IF_NOT(dof_iterator->HasReaction()) << "Reaction variable not set for the following : " << std::endl
<< "Node : " << dof_iterator->Id()<< std::endl
<< "Dof : " << (*dof_iterator) << std::endl << "Not possible to calculate reactions." << std::endl;
}
}
#endif
KRATOS_CATCH("");
}
/**
* @brief This is a call to the linear system solver (taking into account some physical particularities of the problem)
* @param rA The LHS matrix
* @param rDx The Unknowns vector
* @param rb The RHS vector
* @param rModelPart The model part of the problem to solve
*/
void SystemSolveWithPhysics(
TSystemMatrixType& rA,
TSystemVectorType& rDx,
TSystemVectorType& rb,
ModelPart& rModelPart
)
{
KRATOS_TRY
double norm_b = 0.0;
if (TSparseSpace::Size(rb) > 0)
norm_b = TSparseSpace::TwoNorm(rb);
if (norm_b > 0.0) {
// Create the auxiliar dof set
DofsArrayType aux_dof_set;
aux_dof_set.reserve(mDoFToSolveSystemSize);
for (auto& r_dof : BaseType::mDofSet) {
if (r_dof.EquationId() < BaseType::mEquationSystemSize) {
auto it = mDoFSlaveSet.find(r_dof);
if (it == mDoFSlaveSet.end())
aux_dof_set.push_back( &r_dof );
}
}
aux_dof_set.Sort();
KRATOS_ERROR_IF_NOT(aux_dof_set.size() == mDoFToSolveSystemSize) << "Inconsistency (I) in system size: " << mDoFToSolveSystemSize << " vs " << aux_dof_set.size() << "\n Size dof set " << BaseType::mDofSet.size() << " vs Size slave dof set " << mDoFSlaveSet.size() << std::endl;
KRATOS_ERROR_IF_NOT(aux_dof_set.size() == rA.size1()) << "Inconsistency (II) in system size: " << rA.size1() << " vs " << aux_dof_set.size() << "\n Size dof set " << BaseType::mDofSet.size() << " vs Size slave dof set " << mDoFSlaveSet.size() << std::endl;
// Provide physical data as needed
if(BaseType::mpLinearSystemSolver->AdditionalPhysicalDataIsNeeded())
BaseType::mpLinearSystemSolver->ProvideAdditionalData(rA, rDx, rb, aux_dof_set, rModelPart);
// Do solve
BaseType::mpLinearSystemSolver->Solve(rA, rDx, rb);
} else {
TSparseSpace::SetToZero(rDx);
KRATOS_WARNING_IF("ResidualBasedEliminationBuilderAndSolver", rModelPart.GetCommunicator().MyPID() == 0) << "ATTENTION! setting the RHS to zero!" << std::endl;
}
// Prints informations about the current time
KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolver", this->GetEchoLevel() > 1 && rModelPart.GetCommunicator().MyPID() == 0) << *(BaseType::mpLinearSystemSolver) << std::endl;
KRATOS_CATCH("")
}
/**
* @brief This function is exactly same as the ConstructMatrixStructure() function in base class except that the function
* @details Has the call to ApplyConstraints function call once the element and conditions compute their equation ids
* @todo Move this method to a common class with block builder and solver with constraints
*/
virtual void ConstructMatrixStructureWithConstraints(
typename TSchemeType::Pointer pScheme,
TSystemMatrixType& rA,
ModelPart& rModelPart
)
{
// Filling with zero the matrix (creating the structure)
Timer::Start("MatrixStructure");
// The total number of dof of the system
const SizeType equation_size = BaseType::mEquationSystemSize;
// This vector contains the indexes sets for all rows
std::vector<IndexSetType> indices(equation_size);
// We reserve some indexes on each row
#pragma omp parallel for firstprivate(equation_size)
for (int index = 0; index < static_cast<int>(equation_size); ++index)
indices[index].reserve(40);
/// Definition of the eqautio id vector type
EquationIdVectorType ids(3, 0);
EquationIdVectorType second_ids(3, 0); // NOTE: Used only on the constraints to take into account the master dofs
#pragma omp parallel firstprivate(ids, second_ids)
{
// The process info
ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo();
// We repeat the same declaration for each thead
std::vector<IndexSetType> temp_indexes(equation_size);
#pragma omp for
for (int index = 0; index < static_cast<int>(equation_size); ++index)
temp_indexes[index].reserve(30);
// Getting the size of the array of elements from the model
const int number_of_elements = static_cast<int>(rModelPart.Elements().size());
// Element initial iterator
const auto el_begin = rModelPart.ElementsBegin();
// We iterate over the elements
#pragma omp for schedule(guided, 512) nowait
for (int i_elem = 0; i_elem<number_of_elements; ++i_elem) {
auto it_elem = el_begin + i_elem;
pScheme->EquationId( *(it_elem.base()), ids, r_current_process_info);
for (auto& id_i : ids) {
if (id_i < BaseType::mEquationSystemSize) {
auto& row_indices = temp_indexes[id_i];
for (auto& id_j : ids) {
if (id_j < BaseType::mEquationSystemSize) {
row_indices.insert(id_j);
}
}
}
}
}
// Getting the size of the array of the conditions
const int number_of_conditions = static_cast<int>(rModelPart.Conditions().size());
// Condition initial iterator
const auto cond_begin = rModelPart.ConditionsBegin();
// We iterate over the conditions
#pragma omp for schedule(guided, 512) nowait
for (int i_cond = 0; i_cond<number_of_conditions; ++i_cond) {
auto it_cond = cond_begin + i_cond;
pScheme->Condition_EquationId( *(it_cond.base()), ids, r_current_process_info);
for (auto& id_i : ids) {
if (id_i < BaseType::mEquationSystemSize) {
auto& row_indices = temp_indexes[id_i];
for (auto& id_j : ids) {
if (id_j < BaseType::mEquationSystemSize) {
row_indices.insert(id_j);
}
}
}
}
}
// Getting the size of the array of the constraints
const int number_of_constraints = static_cast<int>(rModelPart.MasterSlaveConstraints().size());
// Constraint initial iterator
const auto const_begin = rModelPart.MasterSlaveConstraints().begin();
// We iterate over the constraints
#pragma omp for schedule(guided, 512) nowait
for (int i_const = 0; i_const < number_of_constraints; ++i_const) {
auto it_const = const_begin + i_const;
// Detect if the constraint is active or not. If the user did not make any choice the constraint
// It is active by default
bool constraint_is_active = true;
if( it_const->IsDefined(ACTIVE) ) {
constraint_is_active = it_const->Is(ACTIVE);
}
if(constraint_is_active) {
it_const->EquationIdVector(ids, second_ids, r_current_process_info);
// Slave DoFs
for (auto& id_i : ids) {
if (id_i < BaseType::mEquationSystemSize) {
auto& row_indices = temp_indexes[id_i];
for (auto& id_j : ids) {
if (id_j < BaseType::mEquationSystemSize) {
row_indices.insert(id_j);
}
}
}
}
// Master DoFs
for (auto& id_i : second_ids) {
if (id_i < BaseType::mEquationSystemSize) {
auto& row_indices = temp_indexes[id_i];
for (auto& id_j : second_ids) {
if (id_j < BaseType::mEquationSystemSize) {
row_indices.insert(id_j);
}
}
}
}
}
}
// Merging all the temporal indexes
#pragma omp critical
{
for (int i = 0; i < static_cast<int>(temp_indexes.size()); ++i) {
indices[i].insert(temp_indexes[i].begin(), temp_indexes[i].end());
}
}
}
// Count the row sizes
SizeType nnz = 0;
for (IndexType i = 0; i < indices.size(); ++i)
nnz += indices[i].size();
rA = CompressedMatrixType(indices.size(), indices.size(), nnz);
double *Avalues = rA.value_data().begin();
IndexType *Arow_indices = rA.index1_data().begin();
IndexType *Acol_indices = rA.index2_data().begin();
// Filling the index1 vector - DO NOT MAKE PARALLEL THE FOLLOWING LOOP!
Arow_indices[0] = 0;
for (int i = 0; i < static_cast<int>(rA.size1()); i++)
Arow_indices[i + 1] = Arow_indices[i] + indices[i].size();
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(rA.size1()); ++i) {
const IndexType row_begin = Arow_indices[i];
const IndexType row_end = Arow_indices[i + 1];
IndexType k = row_begin;
for (auto it = indices[i].begin(); it != indices[i].end(); ++it) {
Acol_indices[k] = *it;
Avalues[k] = 0.0;
k++;
}
indices[i].clear(); //deallocating the memory
std::sort(&Acol_indices[row_begin], &Acol_indices[row_end]);
}
rA.set_filled(indices.size() + 1, nnz);
Timer::Stop("MatrixStructure");
}
/**
* @brief This function is exactly same as the ConstructMatrixStructure() function in base class except that the function has the call to ApplyConstraints function call once the element and conditions compute their equation slave_ids
* @param pScheme The pointer to the integration scheme
* @param rT The global relation matrix
* @param rModelPart The model part to compute
*/
virtual void ConstructRelationMatrixStructure(
typename TSchemeType::Pointer pScheme,
TSystemMatrixType& rT,
ModelPart& rModelPart
)
{
// Filling with zero the matrix (creating the structure)
Timer::Start("RelationMatrixStructure");
IndexMapType solvable_dof_reorder;
std::unordered_map<IndexType, IndexSetType> master_indices;
// Filling with "ones"
typedef std::pair<IndexType, IndexType> IndexIndexPairType;
typedef std::pair<IndexType, IndexSetType> IndexIndexSetPairType;
IndexType counter = 0;
for (auto& dof : BaseType::mDofSet) {
if (dof.EquationId() < BaseType::mEquationSystemSize) {
const IndexType equation_id = dof.EquationId();
auto it = mDoFSlaveSet.find(dof);
if (it == mDoFSlaveSet.end()) {
solvable_dof_reorder.insert(IndexIndexPairType(equation_id, counter));
master_indices.insert(IndexIndexSetPairType(equation_id, IndexSetType({counter})));
++counter;
} else {
master_indices.insert(IndexIndexSetPairType(equation_id, IndexSetType({})));
}
}
}
// The process info
ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo();
/// Definition of the eqautio id vector type
EquationIdVectorType ids(3, 0);
EquationIdVectorType second_ids(3, 0); // NOTE: Used only on the constraints to take into account the master dofs
const int number_of_constraints = static_cast<int>(rModelPart.MasterSlaveConstraints().size());
const auto it_const_begin = rModelPart.MasterSlaveConstraints().begin();
// TODO: OMP
for (int i_const = 0; i_const < number_of_constraints; ++i_const) {
auto it_const = it_const_begin + i_const;
// Detect if the constraint is active or not. If the user did not make any choice the constraint
// It is active by default
bool constraint_is_active = true;
if( it_const->IsDefined(ACTIVE) ) {
constraint_is_active = it_const->Is(ACTIVE);
}
if(constraint_is_active) {
it_const->EquationIdVector(ids, second_ids, r_current_process_info);
for (auto& slave_id : ids) {
if (slave_id < BaseType::mEquationSystemSize) {
auto it_slave = solvable_dof_reorder.find(slave_id);
if (it_slave == solvable_dof_reorder.end()) {
for (auto& master_id : second_ids) {
if (master_id < BaseType::mEquationSystemSize) {
auto& master_row_indices = master_indices[slave_id];
master_row_indices.insert(solvable_dof_reorder[master_id]);
}
}
}
}
}
}
}
KRATOS_DEBUG_ERROR_IF_NOT(BaseType::mEquationSystemSize == master_indices.size()) << "Inconsistency in the dofs size: " << BaseType::mEquationSystemSize << "\t vs \t" << master_indices.size() << std::endl;
// Count the row sizes
SizeType nnz = 0;
for (IndexType i = 0; i < BaseType::mEquationSystemSize; ++i) {
nnz += master_indices[i].size();
}
rT = CompressedMatrixType(BaseType::mEquationSystemSize, mDoFToSolveSystemSize, nnz);
double *Tvalues = rT.value_data().begin();
IndexType *Trow_indices = rT.index1_data().begin();
IndexType *Tcol_indices = rT.index2_data().begin();
// Filling the index1 vector - DO NOT MAKE PARALLEL THE FOLLOWING LOOP!
Trow_indices[0] = 0;
for (IndexType i = 0; i < BaseType::mEquationSystemSize; ++i)
Trow_indices[i + 1] = Trow_indices[i] + master_indices[i].size();
KRATOS_DEBUG_ERROR_IF_NOT(Trow_indices[BaseType::mEquationSystemSize] == nnz) << "Nonzero values does not coincide with the row index definition: " << Trow_indices[BaseType::mEquationSystemSize] << " vs " << nnz << std::endl;
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(rT.size1()); ++i) {
const IndexType row_begin = Trow_indices[i];
const IndexType row_end = Trow_indices[i + 1];
IndexType k = row_begin;
for (auto it = master_indices[i].begin(); it != master_indices[i].end(); ++it) {
Tcol_indices[k] = *it;
Tvalues[k] = 0.0;
k++;
}
master_indices[i].clear(); //deallocating the memory
std::sort(&Tcol_indices[row_begin], &Tcol_indices[row_end]);
}
rT.set_filled(BaseType::mEquationSystemSize + 1, nnz);
// Setting ones
for (auto& solv_dof : solvable_dof_reorder) {
rT(solv_dof.first, solv_dof.second) = 1.0;
}
Timer::Stop("RelationMatrixStructure");
}
/**
* @brief This function is exactly same as the Build() function in base class except that the function
* @details It has the call to ApplyConstraints function call once the LHS or RHS are computed by elements and conditions
* @param pScheme The integration scheme considered
* @param rModelPart The model part of the problem to solve
* @param rA The LHS matrix
* @param rb The RHS vector
* @param UseBaseBuild If the abse Build function will be used
*/
void BuildWithConstraints(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemMatrixType& rA,
TSystemVectorType& rb,
const bool UseBaseBuild = true
)
{
KRATOS_TRY
// We build the original system
if (UseBaseBuild)
BaseType::Build(pScheme, rModelPart, rA, rb);
else
BuildWithoutConstraints(pScheme, rModelPart, rA, rb);
// Assemble the constraints
const double start_build = OpenMPUtils::GetCurrentTime();
// We get the global T matrix
const TSystemMatrixType& rTMatrix = *mpTMatrix;
// We compute only once (or if cleared)
if (mCleared) {
mCleared = false;
ComputeConstraintContribution(pScheme, rModelPart, true, mComputeConstantContribution);
} else if (mResetRelationMatrixEachIteration) {
ResetConstraintSystem();
ComputeConstraintContribution(pScheme, rModelPart, mResetRelationMatrixEachIteration, mComputeConstantContribution);
}
// We compute the transposed matrix of the global relation matrix
TSystemMatrixType T_transpose_matrix(mDoFToSolveSystemSize, BaseType::mEquationSystemSize);
SparseMatrixMultiplicationUtility::TransposeMatrix<TSystemMatrixType, TSystemMatrixType>(T_transpose_matrix, rTMatrix, 1.0);
// The proper way to include the constants is in the RHS as T^t(f - A * g)
TSystemVectorType rb_copy = rb;
if (mComputeConstantContribution) {
// We get the g constant vector
TSystemVectorType& rDeltaConstantVector = *mpDeltaConstantVector;
TSystemVectorType aux_constant_vector(rDeltaConstantVector);
TSparseSpace::Mult(rA, rDeltaConstantVector, aux_constant_vector);
TSparseSpace::UnaliasedAdd(rb_copy, -1.0, aux_constant_vector);
}
// The auxiliar matrix to store the intermediate matrix multiplication
TSystemMatrixType auxiliar_A_matrix(mDoFToSolveSystemSize, BaseType::mEquationSystemSize);
SparseMatrixMultiplicationUtility::MatrixMultiplication(T_transpose_matrix, rA, auxiliar_A_matrix);
// We do a backup of the matrix before apply the constraints
if (mpOldAMatrix == NULL) { // If the pointer is not initialized initialize it to an empty matrix
TSystemMatrixPointerType pNewOldAMatrix = TSystemMatrixPointerType(new TSystemMatrixType(0, 0));
mpOldAMatrix.swap(pNewOldAMatrix);
}
(*mpOldAMatrix).swap(rA);
// We resize of system of equations
rA.resize(mDoFToSolveSystemSize, mDoFToSolveSystemSize, false);
rb.resize(mDoFToSolveSystemSize, false);
// Final multiplication
SparseMatrixMultiplicationUtility::MatrixMultiplication(auxiliar_A_matrix, rTMatrix, rA);
TSparseSpace::Mult(T_transpose_matrix, rb_copy, rb);
// Cleaning up memory
auxiliar_A_matrix.resize(0, 0, false);
T_transpose_matrix.resize(0, 0, false);
const double stop_build = OpenMPUtils::GetCurrentTime();
KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", (this->GetEchoLevel() >= 1 && rModelPart.GetCommunicator().MyPID() == 0)) << "Constraint relation build time and multiplication: " << stop_build - start_build << std::endl;
KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", (this->GetEchoLevel() > 2 && rModelPart.GetCommunicator().MyPID() == 0)) << "Finished parallel building with constraints" << std::endl;
KRATOS_CATCH("")
}
/**
* @brief Function to perform the build of the RHS.
* @details The vector could be sized as the total number of dofs or as the number of unrestrained ones
* @param pScheme The integration scheme considered
* @param rModelPart The model part of the problem to solve
* @param rb The RHS of the system
*/
void BuildRHSNoDirichlet(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemVectorType& rb
)
{
KRATOS_TRY
// Assemble the constraints
const double start_build = OpenMPUtils::GetCurrentTime();
// We get the global T matrix
const TSystemMatrixType& rTMatrix = *mpTMatrix;
// We compute only once (or if cleared)
if (mCleared) {
mCleared = false;
ComputeConstraintContribution(pScheme, rModelPart, true, mComputeConstantContribution);
} else if (mResetRelationMatrixEachIteration) {
ResetConstraintSystem();
ComputeConstraintContribution(pScheme, rModelPart, mResetRelationMatrixEachIteration, mComputeConstantContribution);
}
// We compute the transposed matrix of the global relation matrix
TSystemMatrixType T_transpose_matrix(mDoFToSolveSystemSize, BaseType::mEquationSystemSize);
SparseMatrixMultiplicationUtility::TransposeMatrix<TSystemMatrixType, TSystemMatrixType>(T_transpose_matrix, rTMatrix, 1.0);
// We build the original system
TSystemMatrixType A; // Dummy auxiliar matrix we ned to build anyway because are needed to impose the rigid displacements
if (mComputeConstantContribution) {
A.resize(BaseType::mEquationSystemSize, BaseType::mEquationSystemSize, false);
ConstructMatrixStructure(pScheme, A, rModelPart);
BuildWithoutConstraints(pScheme, rModelPart, A, rb);
} else {
BuildRHSNoDirichletWithoutConstraints(pScheme, rModelPart, rb);
}
// The proper way to include the constants is in the RHS as T^t(f - A * g)
TSystemVectorType rb_copy = rb;
if (mComputeConstantContribution) {
// We get the g constant vector
TSystemVectorType& rDeltaConstantVector = *mpDeltaConstantVector;
TSystemVectorType aux_constant_vector(rDeltaConstantVector);
TSparseSpace::Mult(A, rDeltaConstantVector, aux_constant_vector);
TSparseSpace::UnaliasedAdd(rb_copy, -1.0, aux_constant_vector);
}
rb.resize(mDoFToSolveSystemSize, false);
// Final multiplication
TSparseSpace::Mult(T_transpose_matrix, rb_copy, rb);
const double stop_build = OpenMPUtils::GetCurrentTime();
KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", (this->GetEchoLevel() >= 1 && rModelPart.GetCommunicator().MyPID() == 0)) << "Constraint relation build time and multiplication: " << stop_build - start_build << std::endl;
KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", (this->GetEchoLevel() > 2 && rModelPart.GetCommunicator().MyPID() == 0)) << "Finished parallel building with constraints" << std::endl;
KRATOS_CATCH("")
}
/**
* @brief This method resize and initializes the system of euqations
* @details Additionally what is done in the base class the constraints are initialized
* @param pA The pointer to the LHS matrix
* @param pDx The pointer to the vector of Unknowns
* @param pb The pointer to the RHS vector
* @param rModelPart The model part to be computed
*/
void ResizeAndInitializeVectors(
typename TSchemeType::Pointer pScheme,
TSystemMatrixPointerType& pA,
TSystemVectorPointerType& pDx,
TSystemVectorPointerType& pb,
ModelPart& rModelPart
) override
{
// We resize the basic system
BaseType::ResizeAndInitializeVectors(pScheme, pA, pDx, pb, rModelPart);
// If needed resize the vector for the calculation of reactions
if (BaseType::mCalculateReactionsFlag) {
const SizeType reactions_vector_size = BaseType::mDofSet.size() - mDoFToSolveSystemSize + mDoFMasterFixedSet.size();
TSystemVectorType& rReactionsVector = *(BaseType::mpReactionsVector);
if (rReactionsVector.size() != reactions_vector_size)
rReactionsVector.resize(reactions_vector_size, false);
}
// Now we resize the relation matrix used on the MPC solution
if(rModelPart.MasterSlaveConstraints().size() > 0) {
if (mpTMatrix == NULL) { // If the pointer is not initialized initialize it to an empty matrix
TSystemMatrixPointerType pNewT = TSystemMatrixPointerType(new TSystemMatrixType(0, 0));
mpTMatrix.swap(pNewT);
}
// The rigid movement
if (mpConstantVector == NULL) { // If the pointer is not initialized initialize it to an empty vector
TSystemVectorPointerType pNewConstantVector = TSystemVectorPointerType(new TSystemVectorType(0));
mpConstantVector.swap(pNewConstantVector);
}
// The effective rigid movement
if (mpDeltaConstantVector == NULL) { // If the pointer is not initialized initialize it to an empty vector
TSystemVectorPointerType pNewConstantVector = TSystemVectorPointerType(new TSystemVectorType(0));
mpDeltaConstantVector.swap(pNewConstantVector);
}
// System matrices/vectors
TSystemMatrixType& rTMatrix = *mpTMatrix;
TSystemVectorType& rConstantVector = *mpConstantVector;
TSystemVectorType& rDeltaConstantVector = *mpDeltaConstantVector;
// Resizing the system matrix
if (rTMatrix.size1() == 0 || BaseType::GetReshapeMatrixFlag() || mCleared) { // If the matrix is not initialized
rTMatrix.resize(BaseType::mEquationSystemSize, mDoFToSolveSystemSize, false);
ConstructRelationMatrixStructure(pScheme, rTMatrix, rModelPart);
} else {
if (rTMatrix.size1() != BaseType::mEquationSystemSize || rTMatrix.size2() != mDoFToSolveSystemSize) {
KRATOS_ERROR <<"The equation system size has changed during the simulation. This is not permited."<<std::endl;
rTMatrix.resize(BaseType::mEquationSystemSize, mDoFToSolveSystemSize, false);
ConstructRelationMatrixStructure(pScheme, rTMatrix, rModelPart);
}
}
// Resizing the system vector
// The rigid movement
if (rConstantVector.size() != BaseType::mEquationSystemSize || BaseType::GetReshapeMatrixFlag() || mCleared) {
rConstantVector.resize(BaseType::mEquationSystemSize, false);
mComputeConstantContribution = ComputeConstraintContribution(pScheme, rModelPart);
} else {
if (rConstantVector.size() != BaseType::mEquationSystemSize) {
KRATOS_ERROR <<"The equation system size has changed during the simulation. This is not permited."<<std::endl;
rConstantVector.resize(BaseType::mEquationSystemSize, false);
mComputeConstantContribution = ComputeConstraintContribution(pScheme, rModelPart);
}
}
// The effective rigid movement
if (mComputeConstantContribution) {
if (rDeltaConstantVector.size() != BaseType::mEquationSystemSize || BaseType::GetReshapeMatrixFlag() || mCleared) {
rDeltaConstantVector.resize(BaseType::mEquationSystemSize, false);
} else {
if (rDeltaConstantVector.size() != BaseType::mEquationSystemSize) {
KRATOS_ERROR <<"The equation system size has changed during the simulation. This is not permited."<<std::endl;
rDeltaConstantVector.resize(BaseType::mEquationSystemSize, false);
}
}
}
}
}
/**
* @brief It computes the reactions of the system
* @param pScheme The pointer to the integration scheme
* @param rModelPart The model part to compute
* @param rA The LHS matrix of the system of equations
* @param rDx The vector of unkowns
* @param rb The RHS vector of the system of equations
*/
void CalculateReactions(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemMatrixType& rA,
TSystemVectorType& rDx,
TSystemVectorType& rb
) override
{
KRATOS_TRY
// Refresh RHS to have the correct reactions
BuildRHS(pScheme, rModelPart, rb);
// Adding contribution to reactions
TSystemVectorType& r_reactions_vector = *BaseType::mpReactionsVector;
// Updating variables
for (auto& r_dof : BaseType::mDofSet) {
if ((r_dof.IsFixed()) || mDoFSlaveSet.find(r_dof) != mDoFSlaveSet.end()) {
r_dof.GetSolutionStepReactionValue() = -r_reactions_vector[mReactionEquationIdMap[r_dof.EquationId()]];
}
}
KRATOS_CATCH("ResidualBasedEliminationBuilderAndSolverWithConstraints::CalculateReactions failed ..");
}
/**
* @brief Applies the dirichlet conditions. This operation may be very heavy or completely unexpensive depending on the implementation choosen and on how the System Matrix is built.
* @details In the base ResidualBasedEliminationBuilderAndSolver does nothing, due to the fact that the BC are automatically managed with the elimination. But in the constrints approach the slave DoF depending on fixed DoFs must be reconstructed
* @param pScheme The integration scheme considered
* @param rModelPart The model part of the problem to solve
* @param rA The LHS matrix
* @param rDx The Unknowns vector
* @param rb The RHS vector
*/
void ApplyDirichletConditions(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemMatrixType& rA,
TSystemVectorType& rDx,
TSystemVectorType& rb
) override
{
KRATOS_TRY;
if (mDoFMasterFixedSet.size() > 0) {
// We apply the same method as in the block builder and solver but instead of fixing the fixed Dofs, we just fix the master fixed Dofs
std::vector<double> scaling_factors (mDoFToSolveSystemSize, 0.0);
// NOTE: Dofs are assumed to be numbered consecutively
const auto it_dof_begin = BaseType::mDofSet.begin();
IndexType counter = 0;
for (IndexType i = 0; i < BaseType::mDofSet.size(); ++i) {
auto it_dof = it_dof_begin + i;
const IndexType equation_id = it_dof->EquationId();
if (equation_id < BaseType::mEquationSystemSize ) {
auto it_first_check = mDoFSlaveSet.find(*it_dof);
if (it_first_check == mDoFSlaveSet.end()) {
auto it_second_check = mDoFSlaveSet.find(*it_dof);
if (it_second_check == mDoFSlaveSet.end()) {
if(mDoFMasterFixedSet.find(*it_dof) == mDoFMasterFixedSet.end()) {
scaling_factors[counter] = 1.0;
}
}
counter += 1;
}
}
}
double* Avalues = rA.value_data().begin();
IndexType* Arow_indices = rA.index1_data().begin();
IndexType* Acol_indices = rA.index2_data().begin();
// Detect if there is a line of all zeros and set the diagonal to a 1 if this happens
#pragma omp parallel for
for(int k = 0; k < static_cast<int>(mDoFToSolveSystemSize); ++k) {
const IndexType col_begin = Arow_indices[k];
const IndexType col_end = Arow_indices[k+1];
bool empty = true;
for (IndexType j = col_begin; j < col_end; ++j) {
if(Avalues[j] != 0.0) {
empty = false;
break;
}
}
if(empty) {
rA(k,k) = 1.0;
rb[k] = 0.0;
}
}
#pragma omp parallel for
for (int k = 0; k < static_cast<int>(mDoFToSolveSystemSize); ++k) {
const IndexType col_begin = Arow_indices[k];
const IndexType col_end = Arow_indices[k+1];
const double k_factor = scaling_factors[k];
if (k_factor == 0) {
// Zero out the whole row, except the diagonal
for (IndexType j = col_begin; j < col_end; ++j)
if (static_cast<int>(Acol_indices[j]) != k )
Avalues[j] = 0.0;
// Zero out the RHS
rb[k] = 0.0;
} else {
// Zero out the column which is associated with the zero'ed row
for (IndexType j = col_begin; j < col_end; ++j) {
if(scaling_factors[ Acol_indices[j] ] == 0 ) {
Avalues[j] = 0.0;
}
}
}
}
}
KRATOS_CATCH("");
}
/**
* @brief This function is intended to be called at the end of the solution step to clean up memory storage not needed
*/
void Clear() override
{
BaseType::Clear();
// Reseting auxiliar set of dofs
mDoFMasterFixedSet = DofsArrayType();
mDoFSlaveSet = DofsArrayType();
// Clearing the relation map
mReactionEquationIdMap.clear();
// Clear constraint system
if (mpTMatrix != nullptr)
TSparseSpace::Clear(mpTMatrix);
if (mpConstantVector != nullptr)
TSparseSpace::Clear(mpConstantVector);
if (mpDeltaConstantVector != nullptr)
TSparseSpace::Clear(mpDeltaConstantVector);
// Set the flag
mCleared = true;
KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", this->GetEchoLevel() > 1) << "Clear Function called" << std::endl;
}
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
///@}
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
/**
* @brief This method computes the equivalent coounter part of the SetUpSystem when using constraints
* @param rModelPart The model part of the problem to solve
*/
void SetUpSystemWithConstraints(ModelPart& rModelPart)
{
KRATOS_TRY
// First we set up the system of equations without constraints
// Set equation id for degrees of freedom the free degrees of freedom are positioned at the beginning of the system, while the fixed one are at the end (in opposite order).
//
// That means that if the EquationId is greater than "mEquationSystemSize" the pointed degree of freedom is restrained
// This is almost the same SetUpSystem from ResidualBasedEliminationBuilderAndSolver, but we don't discard from the system the fixed dofs that are part of a constraint at the same time
/// First we detect the master fixed DoFs ///
// The current process info
ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo();
// Vector containing the localization in the system of the different terms
DofsVectorType slave_dof_list, master_dof_list;
// Declaring temporal variables
DofsArrayType dof_temp_fixed_master;
typedef std::unordered_set < DofPointerType, DofPointerHasher> set_type;
set_type dof_global_fixed_master_set;
// Iterate over constraints
const int number_of_constraints = static_cast<int>(rModelPart.MasterSlaveConstraints().size());
const auto it_const_begin = rModelPart.MasterSlaveConstraints().begin();
#pragma omp parallel firstprivate(slave_dof_list, master_dof_list)
{
// We cleate the temporal set and we reserve some space on them
set_type dof_temp_fixed_master_set;
dof_temp_fixed_master_set.reserve(2000);
#pragma omp for schedule(guided, 512) nowait
for (int i_const = 0; i_const < number_of_constraints; ++i_const) {
auto it_const = it_const_begin + i_const;
// Detect if the constraint is active or not. If the user did not make any choice the constraint
// It is active by default
bool constraint_is_active = true;
if (it_const->IsDefined(ACTIVE))
constraint_is_active = it_const->Is(ACTIVE);
if (constraint_is_active) {
it_const->GetDofList(slave_dof_list, master_dof_list, r_current_process_info);
// Filling the set of dofs master and fixed at the same time
for (auto& master_dof : master_dof_list) {
if (master_dof->IsFixed()) {
dof_temp_fixed_master_set.insert(master_dof);
}
}
}
}
// We merge all the sets in one thread
#pragma omp critical
{
dof_global_fixed_master_set.insert(dof_temp_fixed_master_set.begin(), dof_temp_fixed_master_set.end());
}
}
dof_temp_fixed_master.reserve(dof_global_fixed_master_set.size());
for (auto p_dof : dof_global_fixed_master_set) {
dof_temp_fixed_master.push_back( p_dof );
}
dof_temp_fixed_master.Sort();
mDoFMasterFixedSet = dof_temp_fixed_master;
/// Now we compute as expected ///
int free_id = 0;
int fix_id = BaseType::mDofSet.size();
for (auto& dof : BaseType::mDofSet) {
if (dof.IsFixed()) {
auto it = mDoFMasterFixedSet.find(dof);
if (it == mDoFMasterFixedSet.end()) {
dof.SetEquationId(--fix_id);
} else {
dof.SetEquationId(free_id++);
}
} else {
dof.SetEquationId(free_id++);
}
}
BaseType::mEquationSystemSize = fix_id;
// Add the computation of the global ids of the solvable dofs
IndexType counter = 0;
for (auto& dof : BaseType::mDofSet) {
if (dof.EquationId() < BaseType::mEquationSystemSize) {
auto it = mDoFSlaveSet.find(dof);
if (it == mDoFSlaveSet.end()) {
++counter;
}
}
}
// The total system of equations to be solved
mDoFToSolveSystemSize = counter;
// Finally we build the relation between the EquationID and the component of the reaction
counter = 0;
for (auto& r_dof : BaseType::mDofSet) {
const bool is_master_fixed = mDoFMasterFixedSet.find(r_dof) == mDoFMasterFixedSet.end() ? false : true;
const bool is_slave = mDoFSlaveSet.find(r_dof) == mDoFSlaveSet.end() ? false : true;
if (is_master_fixed || is_slave) { // Fixed or MPC dof
mReactionEquationIdMap.insert({r_dof.EquationId(), counter});
++counter;
}
}
KRATOS_CATCH("ResidualBasedEliminationBuilderAndSolverWithConstraints::SetUpSystemWithConstraints failed ..");
}
/**
* @brief This method initializes the DoF using the master/slave relationship
* @param pScheme The pointer to the integration scheme
* @param rModelPart The model part to compute
* @param rA The LHS matrix of the system of equations
* @param rDx The vector of unkowns
* @param rb The RHS vector of the system of equations
*/
void ApplyMasterSlaveRelation(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemMatrixType& rA,
TSystemVectorType& rDx,
TSystemVectorType& rb
)
{
KRATOS_TRY
// First we reset the slave dofs
ConstraintUtilities::ResetSlaveDofs(rModelPart);
// Now we apply the constraints
ConstraintUtilities::ApplyConstraints(rModelPart);
KRATOS_CATCH("");
}
/**
* @brief This method checks that the master/slave relation is properly set
* @param pScheme The pointer to the integration scheme
* @param rModelPart The model part to compute
* @param rDx The vector of unkowns
* @param rDxSolved The vector of unkowns actually solved
*/
bool CheckMasterSlaveRelation(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemVectorType& rDx,
TSystemVectorType& rDxSolved
)
{
KRATOS_TRY
// Auxiliar values
const auto it_dof_begin = BaseType::mDofSet.begin();
TSystemVectorType current_solution(mDoFToSolveSystemSize);
TSystemVectorType updated_solution(BaseType::mEquationSystemSize);
TSystemVectorType residual_solution(BaseType::mEquationSystemSize);
// Get current values
IndexType counter = 0;
for (IndexType i = 0; i < BaseType::mDofSet.size(); ++i) {
auto it_dof = it_dof_begin + i;
const IndexType equation_id = it_dof->EquationId();
if (equation_id < BaseType::mEquationSystemSize ) {
auto it = mDoFSlaveSet.find(*it_dof);
if (it == mDoFSlaveSet.end()) {
current_solution[counter] = it_dof->GetSolutionStepValue() + rDxSolved[counter];
counter += 1;
}
}
}
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(BaseType::mDofSet.size()); ++i) {
auto it_dof = it_dof_begin + i;
const IndexType equation_id = it_dof->EquationId();
if (equation_id < BaseType::mEquationSystemSize ) {
residual_solution[equation_id] = it_dof->GetSolutionStepValue() + rDx[equation_id];
}
}
// Apply master slave constraints
const TSystemMatrixType& rTMatrix = *mpTMatrix;
TSparseSpace::Mult(rTMatrix, current_solution, updated_solution);
if (mComputeConstantContribution) {
ComputeConstraintContribution(pScheme, rModelPart, false, true);
const TSystemVectorType& rConstantVector = *mpConstantVector;
TSparseSpace::UnaliasedAdd(updated_solution, 1.0, rConstantVector);
}
TSparseSpace::UnaliasedAdd(residual_solution, -1.0, updated_solution);
// Check database
for(int k = 0; k < static_cast<int>(BaseType::mEquationSystemSize); ++k) {
if (std::abs(residual_solution[k]) > std::numeric_limits<double>::epsilon()) return false;
}
return true;
KRATOS_CATCH("");
}
/**
* @brief This method reconstructs the slave solution after Solving.
* @param pScheme The pointer to the integration scheme
* @param rModelPart Reference to the ModelPart containing the problem.
* @param rA System matrix
* @param rDx Vector of results (variations on nodal variables)
* @param rb RHS vector (residual)
*/
void ReconstructSlaveSolutionAfterSolve(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemMatrixType& rA,
TSystemVectorType& rDx,
TSystemVectorType& rb
)
{
KRATOS_TRY
// We get the global T matrix and the constant vector
const TSystemMatrixType& rTMatrix = *mpTMatrix;
// We reconstruct the complete vector of Unknowns
TSystemVectorType Dx_copy = rDx;
rDx.resize(BaseType::mEquationSystemSize);
TSparseSpace::Mult(rTMatrix, Dx_copy, rDx);
// Add the constant vector
if (mComputeConstantContribution) {
const TSystemVectorType& rDeltaConstantVector = *mpDeltaConstantVector;
TSparseSpace::UnaliasedAdd(rDx, 1.0, rDeltaConstantVector);
}
// We check the solution
if (mCheckConstraintRelation) {
KRATOS_ERROR_IF_NOT(CheckMasterSlaveRelation(pScheme, rModelPart, rDx, Dx_copy)) << "The relation between master/slave dofs is not respected" << std::endl;
}
// Simply restore old LHS
(rA).swap(*mpOldAMatrix);
mpOldAMatrix = NULL;
// Reconstruct the RHS
TSystemVectorType rb_copy = rb;
rb.resize(BaseType::mEquationSystemSize, false);
TSparseSpace::Mult(rTMatrix, rb_copy, rb);
KRATOS_CATCH("ResidualBasedEliminationBuilderAndSolverWithConstraints::ReconstructSlaveSolutionAfterSolve failed ..");
}
/**
* @brief Function to perform the build the system without constraints
* @param pScheme The integration scheme considered
* @param rModelPart The model part of the problem to solve
* @param rA The LHS matrix
* @param rb The RHS vector
*/
void BuildWithoutConstraints(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemMatrixType& rA,
TSystemVectorType& rb
)
{
// The current process info
ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo();
// Getting the array of elements
ElementsArrayType& r_elements_array = rModelPart.Elements();
// Getting the array of the conditions
ConditionsArrayType& r_conditons_array = rModelPart.Conditions();
// Contributions to the system
LocalSystemMatrixType lhs_contribution = LocalSystemMatrixType(0, 0);
LocalSystemVectorType rhs_contribution = LocalSystemVectorType(0);
// Vector containing the localization in the system of the different terms
Element::EquationIdVectorType equation_id;
// Assemble all elements and conditions
#pragma omp parallel firstprivate( lhs_contribution, rhs_contribution, equation_id)
{
// Elements
const auto it_elem_begin = r_elements_array.begin();
const int nelements = static_cast<int>(r_elements_array.size());
#pragma omp for schedule(guided, 512) nowait
for (int i = 0; i<nelements; ++i) {
auto it_elem = it_elem_begin + i;
// Detect if the element is active or not. If the user did not make any choice the element is active by default
bool element_is_active = true;
if (it_elem->IsDefined(ACTIVE))
element_is_active = it_elem->Is(ACTIVE);
if (element_is_active) {
// Calculate elemental contribution
pScheme->CalculateSystemContributions(*(it_elem.base()), lhs_contribution, rhs_contribution, equation_id, r_current_process_info);
// Assemble the elemental contribution
AssembleWithoutConstraints(rA, rb, lhs_contribution, rhs_contribution, equation_id);
// Clean local elemental memory
pScheme->CleanMemory(*(it_elem.base()));
}
}
// Conditions
const auto it_cond_begin = r_conditons_array.begin();
const int nconditions = static_cast<int>(r_conditons_array.size());
#pragma omp for schedule(guided, 512)
for (int i = 0; i<nconditions; ++i) {
auto it_cond = it_cond_begin + i;
// Detect if the element is active or not. If the user did not make any choice the element is active by default
bool condition_is_active = true;
if (it_cond->IsDefined(ACTIVE))
condition_is_active = it_cond->Is(ACTIVE);
if (condition_is_active) {
// Calculate elemental contribution
pScheme->Condition_CalculateSystemContributions(*(it_cond.base()), lhs_contribution, rhs_contribution, equation_id, r_current_process_info);
// Assemble the elemental contribution
AssembleWithoutConstraints(rA, rb, lhs_contribution, rhs_contribution, equation_id);
// Clean local elemental memory
pScheme->CleanMemory(*(it_cond.base()));
}
}
}
}
/**
* @brief Function to perform the build of the RHS without constraints
* @details The vector could be sized as the total number of dofs or as the number of unrestrained ones
* @param pScheme The integration scheme considered
* @param rModelPart The model part of the problem to solve
* @param rb The RHS of the system
*/
void BuildRHSNoDirichletWithoutConstraints(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemVectorType& rb
)
{
// The current process info
ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo();
// Getting the array of elements
ElementsArrayType& r_elements_array = rModelPart.Elements();
// Getting the array of the conditions
ConditionsArrayType& r_conditons_array = rModelPart.Conditions();
// Contributions to the system
LocalSystemVectorType rhs_contribution = LocalSystemVectorType(0);
// Vector containing the localization in the system of the different terms
Element::EquationIdVectorType equation_id;
// Assemble all elements and conditions
#pragma omp parallel firstprivate( rhs_contribution, equation_id)
{
// Elements
const auto it_elem_begin = r_elements_array.begin();
const int nelements = static_cast<int>(r_elements_array.size());
#pragma omp for schedule(guided, 512) nowait
for (int i = 0; i<nelements; ++i) {
auto it_elem = it_elem_begin + i;
// Detect if the element is active or not. If the user did not make any choice the element is active by default
bool element_is_active = true;
if (it_elem->IsDefined(ACTIVE))
element_is_active = it_elem->Is(ACTIVE);
if (element_is_active) {
// Calculate elemental Right Hand Side Contribution
pScheme->Calculate_RHS_Contribution(*(it_elem.base()), rhs_contribution, equation_id, r_current_process_info);
// Assemble the elemental contribution
AssembleRHSWithoutConstraints(rb, rhs_contribution, equation_id);
}
}
// Conditions
const auto it_cond_begin = r_conditons_array.begin();
const int nconditions = static_cast<int>(r_conditons_array.size());
#pragma omp for schedule(guided, 512)
for (int i = 0; i<nconditions; ++i) {
auto it_cond = it_cond_begin + i;
// Detect if the element is active or not. If the user did not make any choice the element is active by default
bool condition_is_active = true;
if (it_cond->IsDefined(ACTIVE))
condition_is_active = it_cond->Is(ACTIVE);
if (condition_is_active) {
// Calculate elemental contribution
pScheme->Condition_Calculate_RHS_Contribution(*(it_cond.base()), rhs_contribution, equation_id, r_current_process_info);
// Assemble the elemental contribution
AssembleRHSWithoutConstraints(rb, rhs_contribution, equation_id);
}
}
}
}
/**
* @brief This function does the assembling of the LHS and RHS
* @note The main difference respect the block builder and solver is the fact that the fixed DoFs are not considered on the assembling
*/
void AssembleWithoutConstraints(
TSystemMatrixType& rA,
TSystemVectorType& rb,
const LocalSystemMatrixType& rLHSContribution,
const LocalSystemVectorType& rRHSContribution,
const Element::EquationIdVectorType& rEquationId
)
{
const SizeType local_size = rLHSContribution.size1();
// Assemble RHS
AssembleRHSWithoutConstraints(rb, rRHSContribution, rEquationId);
// Assemble LHS
for (IndexType i_local = 0; i_local < local_size; ++i_local) {
const IndexType i_global = rEquationId[i_local];
if (i_global < BaseType::mEquationSystemSize) {
BaseType::AssembleRowContributionFreeDofs(rA, rLHSContribution, i_global, i_local, rEquationId);
}
}
}
/**
* @brief Assembling local contribution of nodes and elements in the RHS
* @param rb The RHS vector
*/
void AssembleRHSWithoutConstraints(
TSystemVectorType& rb,
const LocalSystemVectorType& rRHSContribution,
const Element::EquationIdVectorType& rEquationId
)
{
const SizeType local_size = rRHSContribution.size();
if (!BaseType::mCalculateReactionsFlag) {
for (IndexType i_local = 0; i_local < local_size; ++i_local) {
const IndexType i_global = rEquationId[i_local];
if (i_global < BaseType::mEquationSystemSize) { // free dof
// ASSEMBLING THE SYSTEM VECTOR
double& r_b_value = rb[i_global];
const double rhs_value = rRHSContribution[i_local];
#pragma omp atomic
r_b_value += rhs_value;
}
}
} else {
TSystemVectorType& r_reactions_vector = *BaseType::mpReactionsVector;
for (IndexType i_local = 0; i_local < local_size; ++i_local) {
const IndexType i_global = rEquationId[i_local];
auto it_dof = BaseType::mDofSet.begin() + i_global;
const bool is_master_fixed = mDoFMasterFixedSet.find(*it_dof) == mDoFMasterFixedSet.end() ? false : true;
const bool is_slave = mDoFSlaveSet.find(*it_dof) == mDoFSlaveSet.end() ? false : true;
if (is_master_fixed || is_slave) { // Fixed or MPC dof
double& r_b_value = r_reactions_vector[mReactionEquationIdMap[i_global]];
const double rhs_value = rRHSContribution[i_local];
#pragma omp atomic
r_b_value += rhs_value;
} else if (it_dof->IsFree()) { // Free dof not in the MPC
// ASSEMBLING THE SYSTEM VECTOR
double& r_b_value = rb[i_global];
const double& rhs_value = rRHSContribution[i_local];
#pragma omp atomic
r_b_value += rhs_value;
}
}
}
}
/**
* @brief This method set to zero the relation matrix
*/
void ResetConstraintSystem()
{
TSystemMatrixType& rTMatrix = *mpTMatrix;
double *Tvalues = rTMatrix.value_data().begin();
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(rTMatrix.nnz()); ++i) {
Tvalues[i] = 0.0;
}
IndexMapType solvable_dof_reorder;
// Filling with "ones"
typedef std::pair<IndexType, IndexType> IndexIndexPairType;
IndexType counter = 0;
for (auto& dof : BaseType::mDofSet) {
if (dof.EquationId() < BaseType::mEquationSystemSize) {
const IndexType equation_id = dof.EquationId();
auto it = mDoFSlaveSet.find(dof);
if (it == mDoFSlaveSet.end()) {
solvable_dof_reorder.insert(IndexIndexPairType(equation_id, counter));
++counter;
}
}
}
// Setting ones
for (auto& solv_dof : solvable_dof_reorder) {
rTMatrix(solv_dof.first, solv_dof.second) = 1.0;
}
if (mComputeConstantContribution) {
TSystemVectorType& rConstantVector = *mpConstantVector;
TSparseSpace::SetToZero(rConstantVector);
}
}
/**
* @brief This method applies the BC, only in the RHS
* @param pScheme The pointer to the integration scheme
* @param rModelPart The model part to compute
* @param rb The RHS vector of the system of equations
*/
void ApplyDirichletConditionsRHS(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemVectorType& rb
)
{
KRATOS_TRY;
if (mDoFMasterFixedSet.size() > 0) {
// NOTE: dofs are assumed to be numbered consecutively
const auto it_dof_begin = BaseType::mDofSet.begin();
#pragma omp parallel for
for(int k = 0; k < static_cast<int>(mDoFToSolveSystemSize); ++k) {
auto it_dof = it_dof_begin + k;
if (k < static_cast<int>(BaseType::mEquationSystemSize)) {
auto it = mDoFSlaveSet.find(*it_dof);
if (it == mDoFSlaveSet.end()) {
if(mDoFMasterFixedSet.find(*it_dof) != mDoFMasterFixedSet.end()) {
rb[k] = 0.0;
}
}
}
}
}
KRATOS_CATCH("");
}
/**
* @brief This method computes the absolute constant contribution of the MPC
* @param pScheme The integration scheme considered
* @param rModelPart The model part of the problem to solve
* @param ComputeTranslationMatrix If the translation matrix will be assembled
* @param ComputeConstantVector If the constant vector will be assembled
* @return If there are constant constraints
*/
bool ComputeConstraintContribution(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
const bool ComputeTranslationMatrix = false,
const bool ComputeConstantVector = false
)
{
KRATOS_TRY;
// We build the global T matrix and the g constant vector
TSystemMatrixType& rTMatrix = *mpTMatrix;
TSystemVectorType& rConstantVector = *mpConstantVector;
// Filling constant vector
if (ComputeConstantVector) {
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(BaseType::mEquationSystemSize); ++i) {
rConstantVector[i] = 0.0;
}
}
// Auxiliar set to reorder master DoFs
IndexMapType solvable_dof_reorder;
// Filling with "ones"
typedef std::pair<IndexType, IndexType> IndexIndexPairType;
IndexType counter = 0;
for (auto& dof : BaseType::mDofSet) {
if (dof.EquationId() < BaseType::mEquationSystemSize) {
const IndexType equation_id = dof.EquationId();
auto it = mDoFSlaveSet.find(dof);
if (it == mDoFSlaveSet.end()) {
solvable_dof_reorder.insert(IndexIndexPairType(equation_id, counter));
++counter;
}
}
}
// The current process info
ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo();
// Initialize the constant vector
double aux_constant_value = 0.0;
// Contributions to the system
LocalSystemMatrixType transformation_matrix = LocalSystemMatrixType(0, 0);
LocalSystemVectorType constant_vector = LocalSystemVectorType(0);
// Vector containing the localization in the system of the different terms
EquationIdVectorType slave_equation_id, master_equation_id;
const int number_of_constraints = static_cast<int>(rModelPart.MasterSlaveConstraints().size());
std::unordered_set<IndexType> auxiliar_constant_equations_ids;
#pragma omp parallel firstprivate(transformation_matrix, constant_vector, slave_equation_id, master_equation_id)
{
std::unordered_set<IndexType> auxiliar_temp_constant_equations_ids;
auxiliar_temp_constant_equations_ids.reserve(2000);
#pragma omp for schedule(guided, 512)
for (int i_const = 0; i_const < number_of_constraints; ++i_const) {
auto it_const = rModelPart.MasterSlaveConstraints().begin() + i_const;
// Detect if the constraint is active or not. If the user did not make any choice the constraint
// It is active by default
bool constraint_is_active = true;
if (it_const->IsDefined(ACTIVE))
constraint_is_active = it_const->Is(ACTIVE);
if (constraint_is_active) {
it_const->CalculateLocalSystem(transformation_matrix, constant_vector, r_current_process_info);
it_const->EquationIdVector(slave_equation_id, master_equation_id, r_current_process_info);
// Reassign reordered dofs to the master side
for (auto& id : master_equation_id) {
id = solvable_dof_reorder[id];
}
if (ComputeConstantVector) {
for (IndexType i = 0; i < slave_equation_id.size(); ++i) {
const IndexType i_global = slave_equation_id[i];
if (i_global < BaseType::mEquationSystemSize) {
const double constant_value = constant_vector[i];
if (std::abs(constant_value) > 0.0) {
auxiliar_temp_constant_equations_ids.insert(i_global);
double& r_value = rConstantVector[i_global];
#pragma omp atomic
r_value += constant_value;
}
}
}
} else {
for (IndexType i = 0; i < slave_equation_id.size(); ++i) {
const IndexType i_global = slave_equation_id[i];
if (i_global < BaseType::mEquationSystemSize) {
const double constant_value = constant_vector[i];
#pragma omp atomic
aux_constant_value += std::abs(constant_value);
}
}
}
if (ComputeTranslationMatrix) {
// Assemble the constraint contribution
AssembleRelationMatrix(rTMatrix, transformation_matrix, slave_equation_id, master_equation_id);
}
}
}
// We merge all the sets in one thread
#pragma omp critical
{
auxiliar_constant_equations_ids.insert(auxiliar_temp_constant_equations_ids.begin(), auxiliar_temp_constant_equations_ids.end());
}
}
return aux_constant_value > std::numeric_limits<double>::epsilon() ? true : false;
KRATOS_CATCH("");
}
/**
* @brief This method computes the efective constant
* @param pScheme The pointer to the integration scheme
* @param rModelPart The model part to compute
* @param rDxSolved The vector of unkowns actually solved
*/
void ComputeEffectiveConstant(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemVectorType& rDxSolved
)
{
if (mComputeConstantContribution) {
// We get
const TSystemMatrixType& rTMatrix = *mpTMatrix;
TSystemVectorType& rConstantVector = *mpConstantVector;
TSystemVectorType& rDeltaConstantVector = *mpDeltaConstantVector;
TSparseSpace::Copy(rConstantVector, rDeltaConstantVector);
// We reconstruct the complete vector of Unknowns
TSystemVectorType Dx(BaseType::mEquationSystemSize);
TSparseSpace::Mult(rTMatrix, rDxSolved, Dx);
// Compute the effective constant vector
// Auxiliar initial dof iterator
const auto it_dof_begin = BaseType::mDofSet.begin();
TSystemVectorType u(BaseType::mEquationSystemSize);
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(BaseType::mDofSet.size()); ++i) {
auto it_dof = it_dof_begin + i;
const IndexType equation_id = it_dof->EquationId();
if (equation_id < BaseType::mEquationSystemSize ) {
u[equation_id] = it_dof->GetSolutionStepValue() + Dx[equation_id];
}
}
TSystemVectorType u_bar(mDoFToSolveSystemSize);
IndexType counter = 0;
for (IndexType i = 0; i < BaseType::mDofSet.size(); ++i) {
auto it_dof = it_dof_begin + i;
const IndexType equation_id = it_dof->EquationId();
if (equation_id < BaseType::mEquationSystemSize ) {
auto it = mDoFSlaveSet.find(*it_dof);
if (it == mDoFSlaveSet.end()) {
u_bar[counter] = it_dof->GetSolutionStepValue() + rDxSolved[counter];
counter += 1;
}
}
}
TSystemVectorType u_bar_complete(BaseType::mEquationSystemSize);
TSparseSpace::Mult(rTMatrix, u_bar, u_bar_complete);
TSparseSpace::UnaliasedAdd(rDeltaConstantVector, 1.0, u_bar_complete);
TSparseSpace::UnaliasedAdd(rDeltaConstantVector, -1.0, u);
}
}
///@}
///@name Private Access
///@{
///@}
///@name Private Inquiry
///@{
///@}
///@name Un accessible methods
///@{
///@}
}; /* Class ResidualBasedEliminationBuilderAndSolverWithConstraints */
///@}
///@name Type Definitions
///@{
///@}
} /* namespace Kratos.*/
#endif /* KRATOS_RESIDUAL_BASED_BLOCK_BUILDER_AND_SOLVER defined */
|
convolution_pack8to4_int8.h | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
static void convolution_pack8to4_int8_sse(const Mat& bottom_blob, Mat& top_blob, const Mat& weight_data_int8, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, const Option& opt)
{
int w = bottom_blob.w;
int channels = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const int maxk = kernel_w * kernel_h;
// kernel offsets
std::vector<int> _space_ofs(maxk);
int* space_ofs = &_space_ofs[0];
{
int p1 = 0;
int p2 = 0;
int gap = w * dilation_h - kernel_w * dilation_w;
for (int i = 0; i < kernel_h; i++)
{
for (int j = 0; j < kernel_w; j++)
{
space_ofs[p1] = p2;
p1++;
p2 += dilation_w;
}
p2 += gap;
}
}
// num_output
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
int* outptr = top_blob.channel(p);
for (int i = 0; i < outh; i++)
{
for (int j = 0; j < outw; j++)
{
__m128i _sum0 = _mm_setzero_si128();
__m128i _sum1 = _mm_setzero_si128();
__m128i _sum2 = _mm_setzero_si128();
__m128i _sum3 = _mm_setzero_si128();
const signed char* kptr = weight_data_int8.channel(p);
// channels
for (int q = 0; q < channels; q++)
{
const Mat m = bottom_blob.channel(q);
const signed char* sptr = m.row<signed char>(i * stride_h) + j * stride_w * 8;
for (int k = 0; k < maxk; k++)
{
// TODO use _mm_cvtepi8_epi16 on sse4.1
__m128i _val = _mm_loadl_epi64((const __m128i*)(sptr + space_ofs[k] * 8));
_val = _mm_unpacklo_epi8(_val, _mm_cmpgt_epi8(_mm_setzero_si128(), _val));
// TODO use _mm_cvtepi8_epi16 on sse4.1
__m128i _w01 = _mm_loadu_si128((const __m128i*)kptr);
__m128i _w23 = _mm_loadu_si128((const __m128i*)(kptr + 16));
__m128i _extw01 = _mm_cmpgt_epi8(_mm_setzero_si128(), _w01);
__m128i _extw23 = _mm_cmpgt_epi8(_mm_setzero_si128(), _w23);
__m128i _w0 = _mm_unpacklo_epi8(_w01, _extw01);
__m128i _w1 = _mm_unpackhi_epi8(_w01, _extw01);
__m128i _w2 = _mm_unpacklo_epi8(_w23, _extw23);
__m128i _w3 = _mm_unpackhi_epi8(_w23, _extw23);
__m128i _sl0 = _mm_mullo_epi16(_val, _w0);
__m128i _sh0 = _mm_mulhi_epi16(_val, _w0);
__m128i _sl1 = _mm_mullo_epi16(_val, _w1);
__m128i _sh1 = _mm_mulhi_epi16(_val, _w1);
__m128i _sl2 = _mm_mullo_epi16(_val, _w2);
__m128i _sh2 = _mm_mulhi_epi16(_val, _w2);
__m128i _sl3 = _mm_mullo_epi16(_val, _w3);
__m128i _sh3 = _mm_mulhi_epi16(_val, _w3);
_sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl0, _sh0));
_sum1 = _mm_add_epi32(_sum1, _mm_unpacklo_epi16(_sl1, _sh1));
_sum2 = _mm_add_epi32(_sum2, _mm_unpacklo_epi16(_sl2, _sh2));
_sum3 = _mm_add_epi32(_sum3, _mm_unpacklo_epi16(_sl3, _sh3));
_sum0 = _mm_add_epi32(_sum0, _mm_unpackhi_epi16(_sl0, _sh0));
_sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl1, _sh1));
_sum2 = _mm_add_epi32(_sum2, _mm_unpackhi_epi16(_sl2, _sh2));
_sum3 = _mm_add_epi32(_sum3, _mm_unpackhi_epi16(_sl3, _sh3));
kptr += 32;
}
}
// transpose 4x4
{
__m128i _tmp0, _tmp1, _tmp2, _tmp3;
_tmp0 = _mm_unpacklo_epi32(_sum0, _sum1);
_tmp1 = _mm_unpacklo_epi32(_sum2, _sum3);
_tmp2 = _mm_unpackhi_epi32(_sum0, _sum1);
_tmp3 = _mm_unpackhi_epi32(_sum2, _sum3);
_sum0 = _mm_unpacklo_epi64(_tmp0, _tmp1);
_sum1 = _mm_unpackhi_epi64(_tmp0, _tmp1);
_sum2 = _mm_unpacklo_epi64(_tmp2, _tmp3);
_sum3 = _mm_unpackhi_epi64(_tmp2, _tmp3);
}
_sum0 = _mm_add_epi32(_sum0, _sum1);
_sum2 = _mm_add_epi32(_sum2, _sum3);
_sum0 = _mm_add_epi32(_sum0, _sum2);
_mm_storeu_si128((__m128i*)(outptr + j * 4), _sum0);
}
outptr += outw * 4;
}
}
}
|
GB_binop__lxor_bool.c | //------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__lxor_bool)
// A.*B function (eWiseMult): GB (_AemultB_01__lxor_bool)
// A.*B function (eWiseMult): GB (_AemultB_02__lxor_bool)
// A.*B function (eWiseMult): GB (_AemultB_03__lxor_bool)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__lxor_bool)
// A*D function (colscale): GB (_AxD__lxor_bool)
// D*A function (rowscale): GB (_DxB__lxor_bool)
// C+=B function (dense accum): GB (_Cdense_accumB__lxor_bool)
// C+=b function (dense accum): GB (_Cdense_accumb__lxor_bool)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__lxor_bool)
// C=scalar+B GB (_bind1st__lxor_bool)
// C=scalar+B' GB (_bind1st_tran__lxor_bool)
// C=A+scalar GB (_bind2nd__lxor_bool)
// C=A'+scalar GB (_bind2nd_tran__lxor_bool)
// C type: bool
// A type: bool
// B,b type: bool
// BinaryOp: cij = (aij != bij)
#define GB_ATYPE \
bool
#define GB_BTYPE \
bool
#define GB_CTYPE \
bool
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
bool aij = GBX (Ax, pA, A_iso)
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
bool bij = GBX (Bx, pB, B_iso)
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
bool t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = (x != y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_LXOR || GxB_NO_BOOL || GxB_NO_LXOR_BOOL)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_ewise3_noaccum__lxor_bool)
(
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__lxor_bool)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__lxor_bool)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type bool
bool bwork = (*((bool *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__lxor_bool)
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool *restrict Cx = (bool *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__lxor_bool)
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool *restrict Cx = (bool *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__lxor_bool)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
#include "GB_add_template.c"
GB_FREE_WORK ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C = A.*B or C<M> = A.*B
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_01__lxor_bool)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_01_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__lxor_bool)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_03__lxor_bool)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_03_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__lxor_bool)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__lxor_bool)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool *Cx = (bool *) Cx_output ;
bool x = (*((bool *) x_input)) ;
bool *Bx = (bool *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
bool bij = GBX (Bx, p, false) ;
Cx [p] = (x != bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__lxor_bool)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
bool *Cx = (bool *) Cx_output ;
bool *Ax = (bool *) Ax_input ;
bool y = (*((bool *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
bool aij = GBX (Ax, p, false) ;
Cx [p] = (aij != y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
bool aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x != aij) ; \
}
GrB_Info GB (_bind1st_tran__lxor_bool)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
bool
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool x = (*((const bool *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
bool
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
bool aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij != y) ; \
}
GrB_Info GB (_bind2nd_tran__lxor_bool)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool y = (*((const bool *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
whirlpool_fmt_plug.c | /* whirlpool cracker patch for JtR. Hacked together during April of 2013 by Dhiru
* Kholia <dhiru at openwall.com>.
*
* This software is Copyright (c) 2013 Dhiru Kholia <dhiru at openwall.com> and
* it is hereby released to the general public under the following terms:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted.
*/
#if FMT_EXTERNS_H
extern struct fmt_main fmt_whirlpool_0;
extern struct fmt_main fmt_whirlpool_1;
extern struct fmt_main fmt_whirlpool;
#elif FMT_REGISTERS_H
john_register_one(&fmt_whirlpool_0);
john_register_one(&fmt_whirlpool_1);
john_register_one(&fmt_whirlpool);
#else
#include <string.h>
#include "arch.h"
#include "openssl_local_overrides.h"
#include "sph_whirlpool.h"
#include "misc.h"
#include "common.h"
#include "formats.h"
#include "params.h"
#include "options.h"
#include <openssl/opensslv.h>
#if (AC_BUILT && HAVE_WHIRLPOOL) || \
(!AC_BUILT && OPENSSL_VERSION_NUMBER >= 0x10000000 && !HAVE_NO_SSL_WHIRLPOOL)
#include <openssl/whrlpool.h>
#endif
#ifdef _OPENMP
static int omp_t = 1;
#include <omp.h>
#ifndef OMP_SCALE
#define OMP_SCALE 256
#endif
#endif
#include "memdbg.h"
#define FORMAT_LABEL "Whirpool"
#define FORMAT_NAME ""
#define FORMAT_TAG "$whirlpool$"
#define TAG_LENGTH 11
#define ALGORITHM_NAME "32/" ARCH_BITS_STR
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH -1
#define PLAINTEXT_LENGTH 125
#define CIPHERTEXT_LENGTH 128
#define BINARY_SIZE 64
#define SALT_SIZE 0
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
#define BINARY_ALIGN 4
#define SALT_ALIGN 1
static struct fmt_tests whirlpool_0_tests[] = {
{"B3E1AB6EAF640A34F784593F2074416ACCD3B8E62C620175FCA0997B1BA2347339AA0D79E754C308209EA36811DFA40C1C32F1A2B9004725D987D3635165D3C8", ""},
// repeat hash in exactly the same form that is used in john.pot
{FORMAT_TAG "B3E1AB6EAF640A34F784593F2074416ACCD3B8E62C620175FCA0997B1BA2347339AA0D79E754C308209EA36811DFA40C1C32F1A2B9004725D987D3635165D3C8", ""},
{NULL}
};
static struct fmt_tests whirlpool_1_tests[] = {
{"470F0409ABAA446E49667D4EBE12A14387CEDBD10DD17B8243CAD550A089DC0FEEA7AA40F6C2AAAB71C6EBD076E43C7CFCA0AD32567897DCB5969861049A0F5A", ""},
// repeat hash in exactly the same form that is used in john.pot
{FORMAT_TAG "470F0409ABAA446E49667D4EBE12A14387CEDBD10DD17B8243CAD550A089DC0FEEA7AA40F6C2AAAB71C6EBD076E43C7CFCA0AD32567897DCB5969861049A0F5A", ""},
{NULL}
};
static struct fmt_tests whirlpool_tests[] = {
{"19FA61D75522A4669B44E39C1D2E1726C530232130D407F89AFEE0964997F7A73E83BE698B288FEBCF88E3E03C4F0757EA8964E59B63D93708B138CC42A66EB3", ""},
// repeat hash in exactly the same form that is used in john.pot
{FORMAT_TAG "19FA61D75522A4669B44E39C1D2E1726C530232130D407F89AFEE0964997F7A73E83BE698B288FEBCF88E3E03C4F0757EA8964E59B63D93708B138CC42A66EB3", ""},
{NULL}
};
static char (*saved_key)[PLAINTEXT_LENGTH + 1];
static uint32_t (*crypt_out)[BINARY_SIZE / sizeof(uint32_t)];
static void init(struct fmt_main *self)
{
#ifdef _OPENMP
omp_t = omp_get_max_threads();
self->params.min_keys_per_crypt *= omp_t;
omp_t *= OMP_SCALE;
self->params.max_keys_per_crypt *= omp_t;
#endif
saved_key = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*saved_key));
crypt_out = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*crypt_out));
}
static void done(void)
{
MEM_FREE(crypt_out);
MEM_FREE(saved_key);
}
static int valid(char *ciphertext, struct fmt_main *self)
{
char *p;
int extra;
p = ciphertext;
if (!strncmp(p, FORMAT_TAG, TAG_LENGTH))
p += TAG_LENGTH;
if (hexlen(p, &extra) != CIPHERTEXT_LENGTH || extra)
return 0;
return 1;
}
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))
ciphertext += TAG_LENGTH;
memcpy(out, FORMAT_TAG, TAG_LENGTH);
memcpy(out + TAG_LENGTH, ciphertext, CIPHERTEXT_LENGTH + 1);
strupr(out + TAG_LENGTH);
return out;
}
static void *get_binary(char *ciphertext)
{
static union {
unsigned char c[BINARY_SIZE];
ARCH_WORD dummy;
} buf;
unsigned char *out = buf.c;
char *p;
int i;
p = ciphertext + TAG_LENGTH;
for (i = 0; i < BINARY_SIZE; i++) {
out[i] =
(atoi16[ARCH_INDEX(*p)] << 4) |
atoi16[ARCH_INDEX(p[1])];
p += 2;
}
return out;
}
#define COMMON_GET_HASH_VAR crypt_out
#include "common-get-hash.h"
static int crypt_0(int *pcount, struct db_salt *salt)
{
int count = *pcount;
int index = 0;
#ifdef _OPENMP
#pragma omp parallel for
for (index = 0; index < count; index++)
#endif
{
sph_whirlpool0_context ctx;
sph_whirlpool0_init(&ctx);
sph_whirlpool0(&ctx, saved_key[index], strlen(saved_key[index]));
sph_whirlpool0_close(&ctx, (unsigned char*)crypt_out[index]);
}
return count;
}
static int crypt_1(int *pcount, struct db_salt *salt)
{
int count = *pcount;
int index = 0;
#ifdef _OPENMP
#pragma omp parallel for
for (index = 0; index < count; index++)
#endif
{
sph_whirlpool1_context ctx;
sph_whirlpool1_init(&ctx);
sph_whirlpool1(&ctx, saved_key[index], strlen(saved_key[index]));
sph_whirlpool1_close(&ctx, (unsigned char*)crypt_out[index]);
}
return count;
}
static int crypt_2(int *pcount, struct db_salt *salt)
{
int count = *pcount;
int index = 0;
#ifdef _OPENMP
#pragma omp parallel for
for (index = 0; index < count; index++)
#endif
{
#if (AC_BUILT && HAVE_WHIRLPOOL) || \
(!AC_BUILT && OPENSSL_VERSION_NUMBER >= 0x10000000 && !HAVE_NO_SSL_WHIRLPOOL)
WHIRLPOOL_CTX ctx;
WHIRLPOOL_Init(&ctx);
WHIRLPOOL_Update(&ctx, saved_key[index], strlen(saved_key[index]));
WHIRLPOOL_Final((unsigned char*)crypt_out[index], &ctx);
#else
sph_whirlpool_context ctx;
sph_whirlpool_init(&ctx);
sph_whirlpool(&ctx, saved_key[index], strlen(saved_key[index]));
sph_whirlpool_close(&ctx, (unsigned char*)crypt_out[index]);
#endif
}
return count;
}
static int cmp_all(void *binary, int count)
{
int index = 0;
#ifdef _OPENMP
for (; index < count; index++)
#endif
if (!memcmp(binary, crypt_out[index], ARCH_SIZE))
return 1;
return 0;
}
static int cmp_one(void *binary, int index)
{
return !memcmp(binary, crypt_out[index], BINARY_SIZE);
}
static int cmp_exact(char *source, int index)
{
return 1;
}
static void whirlpool_set_key(char *key, int index)
{
strnzcpy(saved_key[index], key, sizeof(*saved_key));
}
static char *get_key(int index)
{
return saved_key[index];
}
struct fmt_main fmt_whirlpool_0 = {
{
"whirlpool0",
"",
"WHIRLPOOL-0 " ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_OMP_BAD |
FMT_SPLIT_UNIFIES_CASE,
{ NULL },
{ FORMAT_TAG },
whirlpool_0_tests
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid,
split,
get_binary,
fmt_default_salt,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash_0,
fmt_default_binary_hash_1,
fmt_default_binary_hash_2,
fmt_default_binary_hash_3,
fmt_default_binary_hash_4,
fmt_default_binary_hash_5,
fmt_default_binary_hash_6
},
fmt_default_salt_hash,
NULL,
fmt_default_set_salt,
whirlpool_set_key,
get_key,
fmt_default_clear_keys,
crypt_0,
{
#define COMMON_GET_HASH_LINK
#include "common-get-hash.h"
},
cmp_all,
cmp_one,
cmp_exact
}
};
struct fmt_main fmt_whirlpool_1 = {
{
"whirlpool1",
"",
"WHIRLPOOL-1 " ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_OMP_BAD |
FMT_SPLIT_UNIFIES_CASE,
{ NULL },
{ FORMAT_TAG },
whirlpool_1_tests
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid,
split,
get_binary,
fmt_default_salt,
{ NULL
},
fmt_default_source,
{
fmt_default_binary_hash_0,
fmt_default_binary_hash_1,
fmt_default_binary_hash_2,
fmt_default_binary_hash_3,
fmt_default_binary_hash_4,
fmt_default_binary_hash_5,
fmt_default_binary_hash_6
},
fmt_default_salt_hash,
NULL,
fmt_default_set_salt,
whirlpool_set_key,
get_key,
fmt_default_clear_keys,
crypt_1,
{
#define COMMON_GET_HASH_LINK
#include "common-get-hash.h"
},
cmp_all,
cmp_one,
cmp_exact
}
};
struct fmt_main fmt_whirlpool = {
{
"whirlpool",
"",
"WHIRLPOOL " ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_OMP_BAD |
FMT_SPLIT_UNIFIES_CASE,
{ NULL },
{ FORMAT_TAG },
whirlpool_tests
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid,
split,
get_binary,
fmt_default_salt,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash_0,
fmt_default_binary_hash_1,
fmt_default_binary_hash_2,
fmt_default_binary_hash_3,
fmt_default_binary_hash_4,
fmt_default_binary_hash_5,
fmt_default_binary_hash_6
},
fmt_default_salt_hash,
NULL,
fmt_default_set_salt,
whirlpool_set_key,
get_key,
fmt_default_clear_keys,
crypt_2,
{
#define COMMON_GET_HASH_LINK
#include "common-get-hash.h"
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
|
kvstore_dist_server.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 mxnet_node.h
* \brief implement mxnet nodes
*/
#ifndef MXNET_KVSTORE_KVSTORE_DIST_SERVER_H_
#define MXNET_KVSTORE_KVSTORE_DIST_SERVER_H_
#include <queue>
#include <string>
#include <mutex>
#include <condition_variable>
#include <memory>
#include <functional>
#include <future>
#include <vector>
#include "ps/ps.h"
#include "mxnet/kvstore.h"
#include "../operator/tensor/elemwise_binary_op-inl.h"
#include "../operator/tensor/init_op.h"
namespace mxnet {
namespace kvstore {
static const int kRowSparsePushPull = 1;
static const int kDefaultPushPull = 0;
static const int kStopServer = -1;
static const int kSyncMode = -2;
/**
* \brief executor runs a function using the thread called \ref Start
*/
class Executor {
public:
/**
* \brief start the executor
*/
void Start() {
std::unique_lock<std::mutex> lk(mu_);
while (true) {
cond_.wait(lk, [this]{return !queue_.empty();});
Block blk = std::move(queue_.front());
queue_.pop();
lk.unlock();
if (blk.f) {
blk.f(); blk.p->set_value();
} else {
blk.p->set_value(); break;
}
lk.lock();
}
}
/**
* \brief function
*/
typedef std::function<void()> Func;
/**
* \brief let the thread called \ref Start to exec a function. threadsafe
*/
void Exec(const Func& func) {
Block blk(func);
auto fut = blk.p->get_future();
{
std::lock_guard<std::mutex> lk(mu_);
queue_.push(std::move(blk));
cond_.notify_one();
}
fut.wait();
}
/**
* \brief stop the thread, threadsafe
*/
void Stop() {
Exec(Func());
}
private:
struct Block {
explicit Block(const Func& func) : f(func), p(std::make_shared<std::promise<void>>()) { }
Func f;
std::shared_ptr<std::promise<void>> p;
};
std::queue<Block> queue_;
std::mutex mu_;
std::condition_variable cond_;
};
class KVStoreDistServer {
public:
KVStoreDistServer() {
using namespace std::placeholders;
ps_server_ = new ps::KVServer<float>(0);
static_cast<ps::SimpleApp*>(ps_server_)->set_request_handle(
std::bind(&KVStoreDistServer::CommandHandle, this, _1, _2));
ps_server_->set_request_handle(
std::bind(&KVStoreDistServer::DataHandleEx, this, _1, _2, _3));
sync_mode_ = false;
log_verbose_ = dmlc::GetEnv("MXNET_KVSTORE_DIST_ROW_SPARSE_VERBOSE", false);
}
~KVStoreDistServer() {
delete ps_server_;
}
void set_controller(const KVStore::Controller& controller) {
CHECK(controller);
controller_ = controller;
}
void set_updater(const KVStore::Updater& updater) {
CHECK(updater);
updater_ = updater;
}
/**
* \brief blocked until received the command \a kSyncMode
*/
void Run() {
exec_.Start();
}
private:
struct MergeBuf {
std::vector<ps::KVMeta> request;
NDArray array;
};
void CommandHandle(const ps::SimpleData& recved, ps::SimpleApp* app) {
if (recved.head == kStopServer) {
exec_.Stop();
} else if (recved.head == kSyncMode) {
sync_mode_ = true;
} else {
// let the main thread to execute ctrl, which is necessary for python
exec_.Exec([this, recved]() {
CHECK(controller_);
controller_(recved.head, recved.body);
});
}
app->Response(recved);
}
void DataHandleEx(const ps::KVMeta& req_meta,
const ps::KVPairs<real_t>& req_data,
ps::KVServer<real_t>* server) {
if (req_meta.cmd == kRowSparsePushPull) {
DataHandleRowSparse(req_meta, req_data, server);
} else {
DataHandleDefault(req_meta, req_data, server);
}
return;
}
inline void ApplyUpdates(const int key, MergeBuf *merged, NDArray *stored,
ps::KVServer<real_t>* server) {
if (merged->request.size() == (size_t) ps::NumWorkers()) {
// let the main thread to execute updater_, which is necessary for python
if (updater_) {
exec_.Exec([this, key, merged, stored](){
CHECK(updater_);
updater_(key, merged->array, stored);
});
} else {
// if no updater, just copy
CopyFromTo(merged->array, stored);
}
if (log_verbose_) {
LOG(INFO) << "sync response to " << merged->request.size() << " workers";
}
for (const auto& req : merged->request) {
server->Response(req);
}
merged->request.clear();
stored->WaitToRead();
} else {
merged->array.WaitToRead();
}
}
void DecodeRowIds(const ps::SArray<ps::Key> &keys, int64_t *indices,
const int64_t master_key, const int64_t num_rows) {
indices[0] = 0;
for (int64_t i = 1; i <= num_rows; i++) {
int key = DecodeKey(keys[i]);
auto row_id = key - master_key;
indices[i - 1] = row_id;
}
}
void DataHandleRowSparse(const ps::KVMeta& req_meta,
const ps::KVPairs<real_t>& req_data,
ps::KVServer<real_t>* server) {
int master_key = DecodeKey(req_data.keys[0]);
auto num_rows = req_data.keys.size() - 1;
auto& stored = store_[master_key];
if (req_meta.push) {
CHECK_GT(req_data.lens.size(), 0) << "req_data.lens cannot be empty";
CHECK_EQ(req_data.lens[0], 0);
real_t* data = req_data.vals.data();
if (stored.is_none()) {
if (log_verbose_) LOG(INFO) << "initial push: " << master_key;
// initialization
CHECK_GT(num_rows, 0) << "init with empty data is not supported";
auto unit_len = req_data.lens[1];
CHECK_GT(unit_len, 0);
size_t ds[] = {num_rows, (size_t) unit_len};
TShape dshape(ds, ds + 2);
CHECK_EQ(req_data.vals.size(), num_rows * unit_len);
TBlob recv_blob(data, dshape, cpu::kDevMask); // NOLINT(*)
NDArray recved = NDArray(recv_blob, 0);
stored = NDArray(kRowSparseStorage, dshape, Context());
Engine::Get()->PushAsync(
[recved, stored](RunContext ctx, Engine::CallbackOnComplete on_complete) {
NDArray rsp = stored;
stored.CheckAndAlloc({mshadow::Shape1(recved.shape()[0])});
mshadow::Stream<cpu> *s = ctx.get_stream<cpu>();
op::PopulateFullIdxRspImpl(s, &rsp);
mshadow::Copy(rsp.data().FlatTo1D<cpu, float>(),
recved.data().FlatTo1D<cpu, float>(), s);
on_complete();
}, recved.ctx(), {recved.var()}, {stored.var()},
FnProperty::kNormal, 0, PROFILER_MESSAGE_FUNCNAME);
stored.WaitToRead();
server->Response(req_meta);
return;
}
// synced push
if (sync_mode_) {
if (log_verbose_) LOG(INFO) << "sync push: " << master_key << " " << req_data.keys;
auto& merged = merge_buf_[master_key];
if (merged.array.is_none()) {
merged.array = NDArray(kRowSparseStorage, stored.shape(), Context());
}
if (num_rows == 0) {
// reset to zeros
if (merged.request.size() == 0) {
merged.array = NDArray(kRowSparseStorage, stored.shape(), Context());
} else {
// nothing to aggregate
}
merged.request.push_back(req_meta);
ApplyUpdates(master_key, &merged, &stored, server);
return;
}
auto unit_len = req_data.lens[1];
CHECK_GT(unit_len, 0);
// indices
std::vector<int64_t> indices(num_rows);
DecodeRowIds(req_data.keys, indices.data(), master_key, num_rows);
// data
TBlob idx_blob(indices.data(), mshadow::Shape1(num_rows), cpu::kDevMask);
size_t ds[] = {(size_t) num_rows, (size_t) unit_len};
TShape dshape(ds, ds + 2);
TBlob recv_blob(data, dshape, cpu::kDevMask); // NOLINT(*)
// row_sparse NDArray
NDArray recved(kRowSparseStorage, stored.shape(), recv_blob, {idx_blob}, 0);
if (merged.request.size() == 0) {
CopyFromTo(recved, &merged.array, 0);
} else {
NDArray out(kRowSparseStorage, stored.shape(), Context());
std::vector<Engine::VarHandle> const_vars;
const_vars.push_back(recved.var());
const_vars.push_back(merged.array.var());
// accumulate row_sparse gradients
// TODO(haibin) override + operator for row_sparse NDArray
// instead of calling BinaryComputeRspRsp directly
using namespace mshadow;
Engine::Get()->PushAsync(
[recved, merged, out](RunContext ctx, Engine::CallbackOnComplete on_complete) {
op::ElemwiseBinaryOp::ComputeEx<cpu, mshadow::op::plus>(
{}, {}, {recved, merged.array}, {kWriteTo}, {out});
on_complete();
}, recved.ctx(), const_vars, {out.var()},
FnProperty::kNormal, 0, PROFILER_MESSAGE_FUNCNAME);
CopyFromTo(out, &merged.array, 0);
}
merged.request.push_back(req_meta);
ApplyUpdates(master_key, &merged, &stored, server);
} else {
// async push
if (log_verbose_) LOG(INFO) << "async push: " << master_key;
if (num_rows == 0) {
server->Response(req_meta);
return;
}
auto unit_len = req_data.lens[1];
CHECK_GT(unit_len, 0);
// indices
std::vector<int64_t> indices(num_rows);
DecodeRowIds(req_data.keys, indices.data(), master_key, num_rows);
TBlob idx_blob(indices.data(), mshadow::Shape1(num_rows), cpu::kDevMask);
size_t ds[] = {(size_t) num_rows, (size_t) unit_len};
TShape dshape(ds, ds + 2);
TBlob recv_blob(data, dshape, cpu::kDevMask); // NOLINT(*)
NDArray recved(kRowSparseStorage, stored.shape(), recv_blob, {idx_blob}, 0);
exec_.Exec([this, master_key, &recved, &stored](){
CHECK(updater_);
updater_(master_key, recved, &stored);
});
server->Response(req_meta);
stored.WaitToRead();
}
} else {
// pull
if (log_verbose_) LOG(INFO) << "pull: " << master_key;
ps::KVPairs<real_t> response;
if (num_rows == 0) {
std::vector<int> lens(req_data.keys.size(), 0);
response.keys = req_data.keys;
response.lens.CopyFrom(lens.begin(), lens.end());
server->Response(req_meta, response);
return;
}
CHECK(!stored.is_none()) << "init " << master_key << " first";
auto shape = stored.shape();
auto unit_len = shape.ProdShape(1, shape.ndim());
const float* data = stored.data().dptr<float>();
auto len = unit_len * num_rows;
// concat values
response.vals.resize(len);
#pragma omp parallel for
for (size_t i = 1; i <= num_rows; i++) {
int key = DecodeKey(req_data.keys[i]);
int64_t row_id = key - master_key;
const auto src = data + row_id * unit_len;
auto begin = (i - 1) * unit_len;
auto end = i * unit_len;
response.vals.segment(begin, end).CopyFrom(src, unit_len);
}
// setup response
response.keys = req_data.keys;
std::vector<int> lens(req_data.keys.size(), unit_len);
lens[0] = 0;
response.lens.CopyFrom(lens.begin(), lens.end());
server->Response(req_meta, response);
}
}
void DataHandleDefault(const ps::KVMeta& req_meta,
const ps::KVPairs<real_t> &req_data,
ps::KVServer<real_t>* server) {
CHECK_EQ(req_meta.cmd, kDefaultPushPull);
// do some check
CHECK_EQ(req_data.keys.size(), (size_t)1);
if (req_meta.push) {
CHECK_EQ(req_data.lens.size(), (size_t)1);
CHECK_EQ(req_data.vals.size(), (size_t)req_data.lens[0]);
}
int key = DecodeKey(req_data.keys[0]);
auto& stored = store_[key];
// there used several WaitToRead, this is because \a recved's memory
// could be deallocated when this function returns. so we need to make sure
// the operators with \a NDArray are actually finished
if (req_meta.push) {
size_t ds[] = {(size_t)req_data.lens[0]};
TShape dshape(ds, ds + 1);
TBlob recv_blob((real_t*)req_data.vals.data(), // NOLINT(*)
dshape, cpu::kDevMask);
NDArray recved = NDArray(recv_blob, 0);
if (stored.is_none()) {
// initialization
stored = NDArray(dshape, Context());
CopyFromTo(recved, &stored, 0);
server->Response(req_meta);
stored.WaitToRead();
} else if (sync_mode_) {
// synced push
auto& merged = merge_buf_[key];
if (merged.array.is_none()) {
merged.array = NDArray(dshape, Context());
}
if (merged.request.size() == 0) {
CopyFromTo(recved, &merged.array, 0);
} else {
merged.array += recved;
}
merged.request.push_back(req_meta);
ApplyUpdates(key, &merged, &stored, server);
} else {
// async push
exec_.Exec([this, key, &recved, &stored](){
CHECK(updater_);
updater_(key, recved, &stored);
});
server->Response(req_meta);
stored.WaitToRead();
}
} else {
// pull
ps::KVPairs<real_t> response;
CHECK(!stored.is_none()) << "init " << key << " first";
auto len = stored.shape().Size();
response.keys = req_data.keys;
response.lens = {len};
// TODO(mli) try to remove this CopyFrom
response.vals.CopyFrom(static_cast<const float*>(stored.data().dptr_), len);
server->Response(req_meta, response);
}
}
int DecodeKey(ps::Key key) {
auto kr = ps::Postoffice::Get()->GetServerKeyRanges()[ps::MyRank()];
return key - kr.begin();
}
/**
* \brief user defined
*/
bool sync_mode_;
KVStore::Controller controller_;
KVStore::Updater updater_;
std::unordered_map<int, NDArray> store_;
std::unordered_map<int, MergeBuf> merge_buf_;
Executor exec_;
ps::KVServer<float>* ps_server_;
// whether to LOG verbose information
bool log_verbose_;
};
} // namespace kvstore
} // namespace mxnet
#endif // MXNET_KVSTORE_KVSTORE_DIST_SERVER_H_
|
RCCE.h | //
// Copyright 2010 Intel Corporation
//
// 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.
//
// [2010-10-25] added support for non-blocking send/recv operations
// - RCCE_isend(), ..._test(), ..._wait(), ..._push()
// - RCCE_irecv(), ..._test(), ..._wait(), ..._push()
// by Carsten Clauss, Chair for Operating Systems,
// RWTH Aachen University
//
// [2012-09-10] added support for "tagged" flags
// - RCCE_send_tagged(), RCCE_recv_tagged(), RCCE_recv_probe_tagged()
// by Carsten Clauss, Chair for Operating Systems,
// RWTH Aachen University
//
// [2015-10-18] port (i)RCCE to "HermitCore"
// by Stefan Lankes, Institute for Automation of Complex Power Systems
// RWTH Aachen University
#ifndef RCCE_H
#define RCCE_H
#include <stdlib.h>
#include <stdio.h>
#ifdef __hermit__
#define SCC
#define COPPERRIDGE
#define USE_REMOTE_PUT_LOCAL_GET
#define USE_PROBE_FLAGS
#undef SHMADD
#endif
#define _RCCE "1.0.13 release"
// #define USE_BYTE_FLAGS
// #define USE_FLAG_EXPERIMENTAL
// little trick to allow the application to be called "RCCE_APP" under
// OpenMP, and "main" otherwise
#define ABS(x) ((x > 0)?x:-x)
#if !defined(_OPENMP) || defined(__hermit__)
#define RCCE_APP main
#endif
// modify next line for Intel BareMetal, which supports stdout, but not stdferr
#define STDERR stdout
#ifdef __hermit__
#define LOG2_LINE_SIZE 6
#else
#define LOG2_LINE_SIZE 5
#endif
#define RCCE_LINE_SIZE (1<<LOG2_LINE_SIZE)
// RCCE_BUFF_SIZE_MAX is space per UE, which is half of the space per tile
#ifdef __hermit__
#define RCCE_BUFF_SIZE_MAX (64*1024)
#else
#define RCCE_BUFF_SIZE_MAX (1<<13)
#endif
#ifdef SHMADD
//64MB
//#define RCCE_SHM_SIZE_MAX 0x4000000
// 128MB
//#define RCCE_SHM_SIZE_MAX 0x8000000
// 256MB
//#define RCCE_SHM_SIZE_MAX 0x10000000
// 512MB
#define RCCE_SHM_SIZE_MAX 0x20000000
// 960MB
//#define RCCE_SHM_SIZE_MAX 0x3C000000
#else
#ifndef SCC_COUPLED_SYSTEMS
// 64MB
#define RCCE_SHM_SIZE_MAX (1<<26)
#else
// In Coupled Mode only 4MB
#define RCCE_SHM_SIZE_MAX (1<<22)
#endif
#endif
#ifdef __hermit__
#define RCCE_MAX_BOARDS 1
#define RCCE_MAXNP_PER_BOARD 8
#else
#define RCCE_MAX_BOARDS 2 /* allow up to 2 SCC boards for now */
#define RCCE_MAXNP_PER_BOARD 48
#endif
#define RCCE_MAXNP (RCCE_MAX_BOARDS * RCCE_MAXNP_PER_BOARD)
#define RCCE_SUCCESS 0
#define RCCE_PENDING -1
#define RCCE_RESERVED -2
#define RCCE_REJECTED -3
#define RCCE_ERROR_BASE 1234321
#define RCCE_ERROR_TARGET (RCCE_ERROR_BASE + 1)
#define RCCE_ERROR_SOURCE (RCCE_ERROR_BASE + 2)
#define RCCE_ERROR_ID (RCCE_ERROR_BASE + 3)
#define RCCE_ERROR_MESSAGE_LENGTH (RCCE_ERROR_BASE + 4)
#define RCCE_ERROR_FLAG_UNDEFINED (RCCE_ERROR_BASE + 5)
#define RCCE_ERROR_NUM_UES (RCCE_ERROR_BASE + 6)
#define RCCE_ERROR_DATA_OVERLAP (RCCE_ERROR_BASE + 7)
#define RCCE_ERROR_ALIGNMENT (RCCE_ERROR_BASE + 8)
#define RCCE_ERROR_DEBUG_FLAG (RCCE_ERROR_BASE + 9)
#define RCCE_ERROR_FLAG_NOT_IN_COMM_BUFFER (RCCE_ERROR_BASE + 10)
#define RCCE_ERROR_FLAG_STATUS_UNDEFINED (RCCE_ERROR_BASE + 11)
#define RCCE_ERROR_FLAG_NOT_ALLOCATED (RCCE_ERROR_BASE + 12)
#define RCCE_ERROR_VAL_UNDEFINED (RCCE_ERROR_BASE + 13)
#define RCCE_ERROR_INVALID_ERROR_CODE (RCCE_ERROR_BASE + 14)
#define RCCE_ERROR_RPC_NOT_ALLOCATED (RCCE_ERROR_BASE + 15)
#define RCCE_ERROR_RPC_INTERNAL (RCCE_ERROR_BASE + 16)
#define RCCE_ERROR_MULTIPLE_RPC_REQUESTS (RCCE_ERROR_BASE + 17)
#define RCCE_ERROR_FDIVIDER (RCCE_ERROR_BASE + 18)
#define RCCE_ERROR_FREQUENCY_EXCEEDED (RCCE_ERROR_BASE + 19)
#define RCCE_ERROR_NO_ACTIVE_RPC_REQUEST (RCCE_ERROR_BASE + 20)
#define RCCE_ERROR_STALE_RPC_REQUEST (RCCE_ERROR_BASE + 21)
#define RCCE_ERROR_COMM_UNDEFINED (RCCE_ERROR_BASE + 22)
#define RCCE_ERROR_ILLEGAL_OP (RCCE_ERROR_BASE + 23)
#define RCCE_ERROR_ILLEGAL_TYPE (RCCE_ERROR_BASE + 24)
#define RCCE_ERROR_MALLOC (RCCE_ERROR_BASE + 25)
#define RCCE_ERROR_COMM_INITIALIZED (RCCE_ERROR_BASE + 26)
#define RCCE_ERROR_CORE_NOT_IN_HOSTFILE (RCCE_ERROR_BASE + 27)
#define RCCE_ERROR_NO_MULTICAST_SUPPORT (RCCE_ERROR_BASE + 28)
#define RCCE_MAX_ERROR_STRING 45
#define RCCE_DEBUG_ALL 111111
#define RCCE_DEBUG_SYNCH 111444
#define RCCE_DEBUG_COMM 111555
#define RCCE_DEBUG_RPC 111666
#define RCCE_DEBUG_DEBUG 111888
#define RCCE_FLAG_SET 1
#define RCCE_FLAG_UNSET 0
#define RCCE_NUM_OPS 4
#define RCCE_OP_BASE 23232323
#define RCCE_SUM (RCCE_OP_BASE)
#define RCCE_MIN (RCCE_OP_BASE+1)
#define RCCE_MAX (RCCE_OP_BASE+2)
#define RCCE_PROD (RCCE_OP_BASE+3)
#define RCCE_TYPE_BASE 63636363
#define RCCE_INT (RCCE_TYPE_BASE)
#define RCCE_LONG (RCCE_TYPE_BASE+1)
#define RCCE_FLOAT (RCCE_TYPE_BASE+2)
#define RCCE_DOUBLE (RCCE_TYPE_BASE+3)
// MPB pointer type
typedef volatile unsigned char* t_vcharp;
#if (defined(SINGLEBITFLAGS) || defined(USE_BYTE_FLAGS)) && !defined(USE_FLAG_EXPERIMENTAL)
typedef struct {
int location; /* location of bit within line (0-255) */
t_vcharp flag_addr; /* address of byte containing flag inside cache line */
t_vcharp line_address; /* start of cache line containing flag */
} RCCE_FLAG;
#else
#ifdef USE_FLAG_EXPERIMENTAL
typedef volatile unsigned char *RCCE_FLAG;
#else
typedef volatile ssize_t *RCCE_FLAG;
#endif
#endif
#ifdef USE_FLAG_EXPERIMENTAL
typedef unsigned char RCCE_FLAG_STATUS;
#else
typedef ssize_t RCCE_FLAG_STATUS;
#endif
typedef struct {
int size;
int my_rank;
int initialized;
int member[RCCE_MAXNP];
#ifdef USE_FAT_BARRIER
RCCE_FLAG gather[RCCE_MAXNP];
#else
RCCE_FLAG gather;
#endif
RCCE_FLAG release;
volatile int cycle;
volatile int count;
int step;
int label;
} RCCE_COMM;
typedef struct _RCCE_SEND_REQUEST {
char *privbuf; // source buffer in local private memory (send buffer)
t_vcharp combuf; // intermediate buffer in MPB
size_t chunk; // size of MPB available for this message (bytes)
RCCE_FLAG *ready; // flag indicating whether receiver is ready
RCCE_FLAG *sent; // flag indicating whether message has been sent by source
size_t size; // size of message (bytes)
int dest; // UE that will receive the message
int copy; // set to 0 for synchronization only (no copying/sending)
void* tag; // additional tag?
int len; // length of additional tag
RCCE_FLAG *probe; // flag for probing for incoming messages
size_t wsize; // offset within send buffer when putting in "chunk" bytes
size_t remainder; // bytes remaining to be sent
size_t nbytes; // number of bytes to be sent in single RCCE_put call
char *bufptr; // running pointer inside privbuf for current location
int label; // jump/goto label for the reentrance of the respective poll function
int finished; // flag that indicates whether the request has already been finished
struct _RCCE_SEND_REQUEST *next;
} RCCE_SEND_REQUEST;
typedef struct _RCCE_RECV_REQUEST {
char *privbuf; // source buffer in local private memory (send buffer)
t_vcharp combuf; // intermediate buffer in MPB
size_t chunk; // size of MPB available for this message (bytes)
RCCE_FLAG *ready; // flag indicating whether receiver is ready
RCCE_FLAG *sent; // flag indicating whether message has been sent by source
size_t size; // size of message (bytes)
int source; // UE that will send the message
int copy; // set to 0 for cancel function
void* tag; // additional tag?
int len; // length of additional tag
RCCE_FLAG *probe; // flag for probing for incoming messages
size_t wsize; // offset within send buffer when putting in "chunk" bytes
size_t remainder; // bytes remaining to be sent
size_t nbytes; // number of bytes to be sent in single RCCE_put call
char *bufptr; // running pointer inside privbuf for current location
int label; // jump/goto label for the reentrance of the respective poll function
int finished; // flag that indicates whether the request has already been finished
struct _RCCE_RECV_REQUEST *next;
} RCCE_RECV_REQUEST;
typedef struct tree_s {
int parent; // UE of parent
int num_children;
int child[RCCE_MAXNP]; // UEs of children
} tree_t;
#ifdef RC_POWER_MANAGEMENT
typedef struct{
int release;
int old_voltage_level;
int new_voltage_level;
int old_frequency_divider;
int new_frequency_divider;
long long start_cycle;
} RCCE_REQUEST;
int RCCE_power_domain(void);
int RCCE_iset_power(int, RCCE_REQUEST *, int *, int *);
int RCCE_wait_power(RCCE_REQUEST *);
int RCCE_set_frequency_divider(int, int *);
int RCCE_power_domain_master(void);
int RCCE_power_domain_size(void);
#endif
int RCCE_init(int *, char***);
int RCCE_finalize(void);
double RCCE_wtime(void);
int RCCE_ue(void);
int RCCE_num_ues(void);
#ifdef SCC_COUPLED_SYSTEMS
int RCCE_dev(void);
int RCCE_dev_ue(void);
int RCCE_num_dev(void);
int RCCE_num_ues_dev(int);
int RCCE_ue_to_dev(int);
#endif
#ifdef GORY
t_vcharp RCCE_malloc(size_t);
t_vcharp RCCE_malloc_request(size_t, size_t *);
t_vcharp RCCE_palloc(size_t,int);
void RCCE_free(t_vcharp);
int RCCE_put(t_vcharp, t_vcharp, int, int);
int RCCE_get(t_vcharp, t_vcharp, int, int);
int RCCE_wait_until(RCCE_FLAG, RCCE_FLAG_STATUS);
int RCCE_test_flag(RCCE_FLAG, RCCE_FLAG_STATUS, int *);
int RCCE_flag_alloc(RCCE_FLAG *);
int RCCE_flag_free(RCCE_FLAG *);
int RCCE_flag_write(RCCE_FLAG *, RCCE_FLAG_STATUS, int);
int RCCE_flag_read(RCCE_FLAG, RCCE_FLAG_STATUS *, int);
int RCCE_flag_write_tagged(RCCE_FLAG *, RCCE_FLAG_STATUS, int, char*, int);
int RCCE_flag_read_tagged(RCCE_FLAG, RCCE_FLAG_STATUS *, int, char*, int);
int RCCE_send(char *, t_vcharp, size_t, RCCE_FLAG *, RCCE_FLAG *, size_t, int);
int RCCE_recv(char *, t_vcharp, size_t, RCCE_FLAG *, RCCE_FLAG *, size_t, int, RCCE_FLAG *);
int RCCE_recv_test(char *, t_vcharp, size_t, RCCE_FLAG *, RCCE_FLAG *, size_t, int, int *, RCCE_FLAG *);
#ifdef USE_FLAG_EXPERIMENTAL
int RCCE_put_flag(t_vcharp, t_vcharp, int, int);
int RCCE_get_flag(t_vcharp, t_vcharp, int, int);
#endif
#else
// standard non-gory functions:
t_vcharp RCCE_malloc(size_t);
int RCCE_flag_write(RCCE_FLAG *, RCCE_FLAG_STATUS, int);
int RCCE_flag_read(RCCE_FLAG, RCCE_FLAG_STATUS *, int);
int RCCE_send(char *, size_t, int);
int RCCE_recv(char *, size_t, int);
int RCCE_recv_test(char *, size_t, int, int *);
int RCCE_send_pipe(char *, size_t, int);
int RCCE_recv_pipe(char *, size_t, int);
int RCCE_send_mcast(char *, size_t);
int RCCE_recv_mcast(char *, size_t, int);
int RCCE_send_tagged(char *, size_t, int, void *, int);
int RCCE_recv_tagged(char *, size_t, int, void *, int);
int RCCE_recv_probe_tagged(int, int *, t_vcharp *, void *, int);
int RCCE_allreduce(char *, char *, int, int, int, RCCE_COMM);
int RCCE_reduce(char *, char *, int, int, int, int, RCCE_COMM);
int RCCE_bcast(char *, size_t, int, RCCE_COMM);
int RCCE_recv_probe(int, int *, t_vcharp *);
int RCCE_recv_cancel(size_t, int);
int RCCE_isend(char *, size_t, int, RCCE_SEND_REQUEST *);
int RCCE_isend_test(RCCE_SEND_REQUEST *, int *);
int RCCE_isend_wait(RCCE_SEND_REQUEST *);
int RCCE_isend_push(int);
int RCCE_irecv(char *, size_t, int, RCCE_RECV_REQUEST *);
int RCCE_irecv_test(RCCE_RECV_REQUEST *, int *);
int RCCE_irecv_wait(RCCE_RECV_REQUEST *);
int RCCE_irecv_push(int);
#endif
t_vcharp RCCE_shmalloc(size_t);
void RCCE_shfree(t_vcharp);
void RCCE_shflush(void);
t_vcharp RCCE_shrealloc(t_vcharp, size_t);
// LfBS-customized functions:
void* RCCE_memcpy_get(void *, const void *, size_t);
void* RCCE_memcpy_put(void *, const void *, size_t);
#define RCCE_memcpy(a,b,c) RCCE_memcpy_put(a,b,c)
int RCCE_comm_split(int (*)(int, void *), void *, RCCE_COMM *);
int RCCE_comm_free(RCCE_COMM *);
int RCCE_comm_size(RCCE_COMM, int *);
int RCCE_comm_rank(RCCE_COMM, int *);
void RCCE_fence(void);
int RCCE_barrier(RCCE_COMM *);
int RCCE_tree_init(RCCE_COMM *, tree_t *, int);
int RCCE_tree_barrier(RCCE_COMM *, tree_t *);
int RCCE_tournament_barrier(RCCE_COMM *);
int RCCE_tournament_fixed_barrier(RCCE_COMM *);
int RCCE_dissemination_barrier(RCCE_COMM *);
int RCCE_TNS_barrier(RCCE_COMM *);
int RCCE_AIR_barrier(RCCE_COMM *);
int RCCE_AIR_barrier2(RCCE_COMM *);
int RCCE_nb_barrier(RCCE_COMM *);
int RCCE_nb_TNS_barrier(RCCE_COMM *);
int RCCE_nb_AIR_barrier(RCCE_COMM *);
int RCCE_error_string(int, char *, int *);
int RCCE_debug_set(int);
int RCCE_debug_unset(int);
extern RCCE_COMM RCCE_COMM_WORLD;
#ifdef RC_POWER_MANAGEMENT
extern RCCE_COMM RCCE_P_COMM;
#define RCCE_POWER_DEFAULT -99999
#endif
#if defined(_OPENMP) && !defined(__hermit__)
#pragma omp threadprivate (RCCE_COMM_WORLD)
#ifdef RC_POWER_MANAGEMENT
#pragma omp threadprivate (RCCE_P_COMM)
#endif
#endif
#endif
|
rnn_helpers.h | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
#ifdef _WIN32
#pragma warning(disable : 4267)
#endif
#include <algorithm>
#include <functional>
#include <future>
#include <string>
#include <vector>
#include "gsl/gsl"
#include "core/common/common.h"
#include "core/common/logging/logging.h"
#include "core/framework/allocator.h"
#include "core/util/math.h"
#include "core/util/math_cpuonly.h"
#include "core/platform/threadpool.h"
namespace onnxruntime {
class Tensor;
class OpKernelContext;
namespace rnn {
namespace detail {
enum Direction {
kForward = 0,
kReverse = 1,
kBidirectional = 2
};
inline Direction MakeDirection(const std::string& direction) {
if (direction == "forward") {
return kForward;
}
if (direction == "reverse") {
return kReverse;
}
if (direction == "bidirectional") {
return kBidirectional;
}
ORT_THROW("Invalid 'direction' argument of '", direction,
"'. Must be one of 'forward', 'reverse', or 'bidirectional'.");
}
/** Allocate a unique_ptr using allocator_, and return a span to the allocated memory so usage is safe
@param allocator IAllocator to use for the allocation.
@param size Allocation size. Number of elements of type TAlloc, or total size if TAlloc is 'void'.
@param unique_ptr unique_ptr that will control the lifetime of the allocated memory.
@param fill If true, fill the allocated memory with fill_value.
@param fill_value Value to use if 'fill' is true.
@returns A span to provide bounds checked access to the allocated memory.
*/
template <typename TAlloc>
gsl::span<TAlloc> Allocate(std::shared_ptr<IAllocator> allocator,
size_t size,
IAllocatorUniquePtr<TAlloc>& unique_ptr,
bool fill = false, TAlloc fill_value = TAlloc{}) {
unique_ptr = IAllocator::MakeUniquePtr<TAlloc>(allocator, size);
auto span = gsl::make_span(unique_ptr.get(), size);
if (fill) {
// Do't use span.begin() it will cause performance issue and stop compiler to optimize the code
std::fill_n(unique_ptr.get(), size, fill_value);
}
return span;
}
// validate the common inputs to RNN, LSTM and GRU operators
Status ValidateCommonRnnInputs(const Tensor& X,
const Tensor& W,
const Tensor& R,
const Tensor* B,
int WRB_dim_1_multipler, // multiplier used with hidden_size for W, R and B inputs
const Tensor* sequence_lens,
const Tensor* initial_h,
int64_t num_directions,
int64_t hidden_size);
/// Copy an input array repeatedly to an output array
/// @param input_begin Beginning of input
/// @param input_end End of input
/// @param output Output iterator
/// @param repetitions Number of times to repeat copy. Assumes output is sufficiently sized.
/// @returns Position of output iterator after copy is completed
template <typename TInIter, typename TOutIter>
TOutIter RepeatVectorToConstructArray(TInIter input_begin,
TInIter input_end,
TOutIter output,
int64_t repetitions) {
for (int64_t i = 0; i < repetitions; i++) {
output = std::copy(input_begin, input_end, output);
}
return output;
}
// reverse an LSTM or GRU sequence which has shape [seq_length, batch_size, hidden_size]
// and output to shape [seq_length, num_directions, batch_size, hidden_size]
template <typename T>
void ReverseSequence(gsl::span<const T> inputs,
gsl::span<T> inputs_reverse,
gsl::span<const int> sequence_lengths,
const int max_sequence_length,
const int batch_size,
const int input_size,
const int num_directions,
concurrency::ThreadPool*) {
for (int i = 0; i < batch_size; i++) {
int seq_len = sequence_lengths[i];
#ifdef _OPENMP
// Parallel execute the loop.
#pragma omp parallel for
#endif
for (int j = 0; j < seq_len; j++) {
gsl::span<const T> src = inputs.subspan(j * batch_size * input_size + i * input_size, input_size);
gsl::span<T> dest = inputs_reverse.subspan(num_directions * (seq_len - j - 1) * batch_size * input_size + i * input_size, input_size);
// Use gsl::copy instead of std::copy() to allow compiler to optimize the code
gsl::copy(src, dest);
}
#ifdef _OPENMP
// Parallel execute the loop.
#pragma omp parallel for
#endif
for (int j = seq_len; j < max_sequence_length; j++) {
gsl::span<const T> src = inputs.subspan(j * batch_size * input_size + i * input_size, input_size);
gsl::span<T> dest = inputs_reverse.subspan(num_directions * j * batch_size * input_size + i * input_size, input_size);
// Use gsl::copy instead of std::copy() to allow compiler to optimize the code
gsl::copy(src, dest);
}
}
}
// A has size M x K, B has size N x K (transposed), and C has size M x N
// We check that A, B and C are large enough before calling the lower level GEMM implementation
template <typename TSpanAIter, typename TSpanBIter, typename TSpanCIter>
void ComputeGemm(const int M,
const int N,
const int K,
const float alpha,
TSpanAIter A,
TSpanAIter A_end,
const int lda,
TSpanBIter B,
TSpanBIter B_end,
const int ldb,
const float beta,
TSpanCIter C,
TSpanCIter C_end,
const int ldc, concurrency::ThreadPool* tp) {
// validate all the inputs
// need to use the lda/ldb/ldc strides which should be >= the columns for the span
ORT_ENFORCE(lda >= K && ldb >= K && ldc >= N);
ORT_ENFORCE(A + (M * lda - (lda - K)) <= A_end);
ORT_ENFORCE(B + (N * ldb - (ldb - K)) <= B_end);
ORT_ENFORCE(C + (M * ldc - (ldc - N)) <= C_end);
::onnxruntime::math::GemmEx<float>(
CblasNoTrans, CblasTrans,
M, N, K, alpha,
&*A, lda,
&*B, ldb, beta,
&*C, ldc, tp);
}
// helper to convert a span to a raw pointer
// after validating the memory covered by the span supports the size required
template <typename T>
const T* SafeRawConstPointer(typename gsl::span<T>::const_iterator cur,
typename gsl::span<T>::const_iterator end,
size_t size) {
ORT_ENFORCE(cur + size <= end);
return &*cur;
}
// helper to convert a span to a raw pointer
// after validating the memory covered by the span supports the size required
template <typename T>
const T* SafeRawConstPointer(gsl::span<T> span, size_t offset, size_t size) {
ORT_ENFORCE(offset + size <= size_t(span.size()));
return span.data();
}
// helper to convert a span to a raw pointer
// after validating the memory covered by the span supports the size required
template <typename T>
T* SafeRawPointer(typename gsl::span<T>::iterator cur,
typename gsl::span<T>::iterator end,
size_t size) {
ORT_ENFORCE(cur + size <= end);
return &*cur;
}
// helper to convert a span to a raw pointer
// after validating the memory covered by the span supports the size required
template <typename T>
T* SafeRawPointer(typename gsl::span<T> span, size_t offset, size_t size) {
ORT_ENFORCE(offset + size <= size_t(span.size()));
return span.data() + offset;
}
void DumpMatrixImpl(const std::string& name, const float* src, int row, int col,
int offset = 0, int col_width = -1);
// Helper class to wrap the processing of the activation funcs and any alpha/beta values.
// The alpha/beta values are consumed in the order of the activation funcs. once they run out
// defaults will be used as needed.
// The Entries property contains the normalized function names and the alpha/beta value to use.
class ActivationFuncs {
public:
struct Entry {
const std::string name;
const float alpha;
const float beta;
};
ActivationFuncs() = default;
ActivationFuncs(const std::vector<std::string>& funcs,
const std::vector<float>& alphas,
const std::vector<float>& betas);
const std::vector<Entry>& Entries() const {
return entries_;
}
private:
std::vector<Entry> entries_;
};
namespace deepcpu {
using AddBiasIntoFuncPtr = void (*)(const float*, float*, const int);
using ClipWithBiasFuncPtr = void (*)(float, const float*, float*, const int);
using ActivationFuncPtr = void (*)(float*, int, float, float);
using ActivationFuncBPtr = void (*)(const float*, float*, int, float, float);
using LstmMergeGatesFuncPtr = void (*)(const float*, float*, const float*, float*, int, float, float);
using GruResetGateFuncPtr = void (*)(const float*, float*, float*, int, float, float);
using GruOutputGateFuncPtr = void (*)(float*, const float*, const float*, float*, int, float, float);
ActivationFuncPtr ActivationFuncByName(const std::string& func);
LstmMergeGatesFuncPtr LstmMergeGatesFuncByName(const std::string& func);
GruResetGateFuncPtr GruResetGateFuncByName(const std::string& func);
GruOutputGateFuncPtr GruOutputGateFuncByName(const std::string& func);
void add_bias_into_ignore(const float* ignored, const float* pd, int c);
void add_bias_into(const float* ps, float* pd, int c);
void clip(float b, float* pd, int c);
void clip_add_bias(float b, const float* pb, float* pd, int c);
void clip_ignore_bias(float b, const float* pb, float* pd, int c);
void sigmoid_m(const float* ps1, float* ps1_c, const float* ps2, float* pd, int c, float alpha, float beta);
void tanh_m(const float* ps1, float* ps1_c, const float* ps2, float* pd, int c, float alpha, float beta);
void relu_m(const float* ps1, const float* ps1_c, const float* ps2, float* pd, int c, float alpha, float beta);
void sigmoid_exact_m(const float* ps1, const float* ps1_c, const float* ps2, float* pd, int c, float alpha, float beta);
void tanh_exact_m(const float* ps1, const float* ps1_c, const float* ps2, float* pd, int c, float alpha, float beta);
void sigmoid(float* pd, int c, float alpha, float beta);
void tanh(float* pd, int c, float alpha, float beta);
void relu(float* pd, int c, float alpha, float beta);
void sigmoid_exact(float* pd, int c, float alpha, float beta);
void tanh_exact(float* pd, int c, float alpha, float beta);
void merge_lstm_gates_to_memory(const float* pprev, const float* pi, const float* pf, const float* pg, float* pcurr,
int c);
void gru_reset_gate_tanh(const float* ps1, float* ps2, float* pd, int c, float alpha, float beta);
void gru_reset_gate_sigmoid(const float* ps1, float* ps2, float* pd, int c, float alpha, float beta);
void gru_reset_gate_relu(const float* ps1, const float* ps2, float* pd, int c, float alpha, float beta);
void gru_output_gate_tanh(float* ph, const float* pz, const float* ps, float* po, int c, float alpha, float beta);
void gru_output_gate_sigmoid(float* ph, const float* pz, const float* ps, float* po, int c, float alpha, float beta);
void gru_output_gate_relu(const float* ph, const float* pz, const float* ps, float* po, int c, float alpha, float beta);
inline void elementwise_product(const float* op1, const float* op2, float* dest, int size) {
for (int i = 0; i < size; i++)
dest[i] += op1[i] * op2[i];
}
inline void elementwise_sum1(const float* src, float* dest, int size) {
for (int i = 0; i < size; i++)
dest[i] += src[i];
}
inline void elementwise_sum2(const float* src1, const float* src2, float* dest, int size) {
for (int i = 0; i < size; i++)
dest[i] += src1[i] + src2[i];
}
} // namespace deepcpu
} // namespace detail
} // namespace rnn
} // namespace onnxruntime
|
memutils.c | /*
Copyright (c) 2012 by Marcin Krotkiewski, University of Oslo
See ../License.txt for License Agreement.
*/
#include "memutils.h"
#include <stdlib.h>
#include "mtypes.h"
#ifdef USE_NUMA
#include <numa.h>
#include <numaif.h>
#endif
static size_t total_mem = 0;
static size_t total_thread_mem = 0;
#ifndef APPLE
#ifdef USE_OPENMP
#pragma omp threadprivate(total_thread_mem)
#endif /* USE_OPENMP */
#endif /* APPLE */
void inc_memory_usage(size_t size)
{
#ifdef USE_OPENMP
#pragma omp atomic
#endif /* USE_OPENMP */
total_mem += size;
total_thread_mem += size;
}
void dec_memory_usage(size_t size)
{
#ifdef USE_OPENMP
#pragma omp atomic
#endif /* USE_OPENMP */
total_mem -= size;
total_thread_mem -= size;
}
size_t get_total_memory_usage(void)
{
return total_mem;
}
size_t get_thread_memory_usage(void)
{
return total_thread_mem;
}
void *_mmalloc(void* (*func)(size_t), const char *varname, size_t size)
{
void *ptr=NULL;
{
if(size!=0){
#ifdef USE_TCMALLOC
if(func==tc_malloc)
ptr=func(size);
else
#endif
#if defined(USE_OPENMP)
#pragma omp critical(memory_allocation)
#endif
ptr=func(size);
if(!ptr){
const char *se = strerror(errno);
#ifdef USE_OPENMP
#pragma omp single
#endif
{
EMESSAGE("could not allocate memory (%"PRI_SIZET" bytes, variable %s)", (size_t)size, varname);
EMESSAGE("system error %d: %s", errno, se);
USERERROR("Out of memory", MUTILS_OUT_OF_MEMORY);
exit(1); /* not executed in MATLAB*/
}
}
#ifdef DEBUG
register_pointer(ptr, varname, size);
inc_memory_usage(size);
if(DEBUG_MEMORY<=get_debug_mode()) {
MESSAGE("memory allocated (Mbytes) %s: %"PRI_SIZET" (%"PRI_SIZET")",
varname, (size_t)size, (size_t)(get_total_memory_usage()/1024/1024));
fflush(stdout);
}
#endif
} else ptr=NULL;
}
return ptr;
}
void *_mcalloc(void* (*func)(size_t, size_t), const char *varname, size_t size)
{
void *ptr;
{
if(size!=0){
#ifdef USE_TCMALLOC
if(func==tc_calloc)
ptr=func(1,size);
else
#endif
#if defined(USE_OPENMP)
#pragma omp critical(memory_allocation)
#endif
ptr=func(1, size);
if(!ptr){
const char *se = strerror(errno);
#ifdef USE_OPENMP
#pragma omp single
#endif
{
EMESSAGE("could not allocate memory (%"PRI_SIZET" bytes, variable %s)", (size_t)size, varname);
EMESSAGE("system error %d: %s", errno, se);
USERERROR("Out of memory", MUTILS_OUT_OF_MEMORY);
exit(1); /* not executed in MATLAB*/
}
}
#ifdef DEBUG
register_pointer(ptr, varname, size);
inc_memory_usage(size);
if(DEBUG_MEMORY<=get_debug_mode()) {
MESSAGE("memory allocated (Mbytes) %s: %"PRI_SIZET" (%"PRI_SIZET")",
varname, (size_t)size, (size_t)(get_total_memory_usage()/1024/1024));
fflush(stdout);
}
#endif
} else ptr=NULL;
}
return ptr;
}
void *_mrealloc(void* (*func)(void *, size_t), void *var, const char *varname, size_t size, size_t inc)
{
void *ptr;
{
if(inc!=0){
#ifdef USE_TCMALLOC
if(func==tc_realloc)
ptr=func(var,size);
else
#endif
#if defined(USE_OPENMP)
#pragma omp critical(memory_allocation)
#endif
ptr=func(var, size);
if(size && !ptr){
const char *se = strerror(errno);
#ifdef USE_OPENMP
#pragma omp single
#endif
{
EMESSAGE("could not reallocate memory (%"PRI_SIZET" bytes, variable %s)", (size_t)size, varname);
EMESSAGE("system error %d: %s", errno, se);
USERERROR("Out of memory", MUTILS_OUT_OF_MEMORY);
exit(1); /* not executed in MATLAB*/
}
}
#ifdef DEBUG
release_pointer(var, varname, size-inc);
register_pointer(ptr, varname, size);
if(inc>0) inc_memory_usage(inc);
else dec_memory_usage(inc);
if(DEBUG_MEMORY<=get_debug_mode()) {
MESSAGE("memory allocated (Mbytes) %s: %"PRI_SIZET" (%"PRI_SIZET")",
varname, (size_t)size, (size_t)(get_total_memory_usage()/1024/1024));
fflush(stdout);
}
#endif
} else ptr=var;
}
return ptr;
}
void _mfree(void (*func)(void *), void *var, const char *varname, size_t size)
{
{
#ifdef DEBUG
if(var){
dec_memory_usage(size);
release_pointer(var, varname, size);
if(DEBUG_MEMORY<=get_debug_mode()) {
MESSAGE("memory allocated (Mbytes) %s: %"PRI_SIZET" (%"PRI_SIZET")",
varname, (size_t)size, (size_t)(get_total_memory_usage()/1024/1024));
fflush(stdout);
}
}
#endif
#if defined(USE_OPENMP)
#pragma omp critical(memory_allocation)
#endif
func(var);
}
}
static void **ptr_list = NULL;
static char **var_list = NULL;
static size_t *size_list = NULL;
static unsigned list_size = 0;
static unsigned list_elems = 0;
void register_pointer(void *ptr, const char *varname, size_t size)
{
#ifdef USE_OPENMP
#pragma omp critical(memory_debug_pointers)
#endif
{
#ifdef USE_OPENMP
#pragma omp flush
#endif
if(ptr!=NULL){
if(list_size==list_elems){
ptr_list = realloc(ptr_list, sizeof(void*)*(list_size+64));
var_list = realloc(var_list, sizeof(char*)*(list_size+64));
size_list = realloc(size_list, sizeof(size_t*)*(list_size+64));
list_size += 64;
}
ptr_list[list_elems] = ptr;
var_list[list_elems] = strdup(varname);
size_list[list_elems] = size;
list_elems++;
}
}
}
void release_pointer(void *ptr, const char *varname, size_t size)
{
#ifdef USE_OPENMP
#pragma omp critical(memory_debug_pointers)
#endif
{
unsigned i, j;
unsigned removed = 0;
#ifdef USE_OPENMP
#pragma omp flush
#endif
if(list_size==0){
USERWARNING("No more pointers to free. Double free of '%s' possible.", MUTILS_DOUBLEFREE, varname);
} else if(ptr!=NULL){
i=0;
while(i<list_elems){
if(ptr_list[i]==ptr){
if(size_list[i] != size){
DMESSAGE("WARNING: wrong size of the released pointer '%s' 0x%lx : %"PRI_ULONG" != %"PRI_ULONG, DEBUG_BASIC,
varname, (unsigned long)ptr, (unsigned long)size_list[i], (unsigned long)size);
}
j=i;
while(j<list_elems-1){
ptr_list[j] = ptr_list[j+1];
var_list[j] = var_list[j+1];
size_list[j] = size_list[j+1];
j++;
}
list_elems--;
removed = 1;
break;
}
i++;
}
if(!removed){
MESSAGE("Released pointer '%s' 0x%lx is not known, i.e. not allocated by mutils.",
varname, (unsigned long)ptr);
}
}
}
}
void print_allocated_pointers()
{
#ifdef USE_OPENMP
#pragma omp critical(memory_debug_pointers)
#endif
{
unsigned i;
#ifdef USE_OPENMP
#pragma omp flush
#endif
if(list_elems==0){
DMESSAGE("All allocated pointers have been freed.", DEBUG_BASIC);
DMESSAGE("If you see non-zero global memory usage, "
"it means that wrong size has been given when freeing some pointers.", DEBUG_BASIC);
}
for(i=0; i<list_elems; i++){
DMESSAGE("'%s' 0x%lx", DEBUG_BASIC, var_list[i], (unsigned long)ptr_list[i]);
}
}
}
#ifndef WINDOWS
void *_mmalign(const char *varname, size_t align, size_t size)
{
void *ptr;
if(size!=0){
int retval = posix_memalign(&ptr, align, size);
if(retval){
const char *se = strerror(retval);
#ifdef USE_OPENMP
#pragma omp single
#endif
{
EMESSAGE("could not allocate memory (%"PRI_SIZET" bytes, variable %s)", (size_t)size, varname);
EMESSAGE("system error %d: %s", errno, se);
USERERROR("Out of memory", MUTILS_OUT_OF_MEMORY);
exit(1); /* not executed in MATLAB*/
}
}
/* use huge pages if available and needed */
if(align>=HUGEPAGESIZE)
madvise((void*)ptr, size, ADVISE_LARGE);
#ifdef DEBUG
register_pointer(ptr, varname, size);
inc_memory_usage(size);
if(DEBUG_MEMORY<=get_debug_mode()) {
MESSAGE("memory allocated (Mbytes) %s: %"PRI_SIZET" (%"PRI_SIZET")",
varname, (size_t)size, (size_t)(get_total_memory_usage()/1024/1024));
fflush(stdout);
}
#endif
} else ptr=NULL;
return ptr;
}
#include "tictoc.h"
void *_memmap(const char *varname, size_t size)
{
void *ptr;
if(size!=0){
ptr = mmap(NULL, size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_POPULATE, -1, 0);
if(size && !ptr){
const char *se = strerror(errno);
#ifdef USE_OPENMP
#pragma omp single
#endif
{
EMESSAGE("could not mmap memory (%"PRI_SIZET" bytes, variable %s)", (size_t)size, varname);
EMESSAGE("system error %d: %s", errno, se);
USERERROR("Out of memory", MUTILS_OUT_OF_MEMORY);
exit(1); /* not executed in MATLAB*/
}
}
#ifdef DEBUG
register_pointer(ptr, varname, size);
inc_memory_usage(size);
if(DEBUG_MEMORY<=get_debug_mode()) {
MESSAGE("memory allocated using mmap (Mbytes) %s: %"PRI_SIZET" (%"PRI_SIZET")",
varname, (size_t)size, (size_t)(get_total_memory_usage()/1024/1024));
fflush(stdout);
}
#endif
} else ptr=NULL;
return ptr;
}
void _memunmap(void *var, const char *varname, size_t size)
{
#ifdef DEBUG
if(var){
dec_memory_usage(size);
release_pointer(var, varname, size);
if(DEBUG_MEMORY<=get_debug_mode()) {
MESSAGE("memory allocated (Mbytes) %s: %"PRI_SIZET" (%"PRI_SIZET")",
varname, (size_t)size, (size_t)(get_total_memory_usage()/1024/1024));
fflush(stdout);
}
}
#endif
#if defined(USE_OPENMP)
#pragma omp critical
#endif
munmap(var, size);
}
#endif /* WINDOWS */
/* memutils.c ends here */
|
lastpass_sniffed_fmt_plug.c | /* LastPass sniffed session cracker patch for JtR. Hacked together during
* November of 2012 by Dhiru Kholia <dhiru at openwall.com>.
*
* Burp Suite is awesome. Open-source it!
*
* This software is Copyright (c) 2012 Dhiru Kholia <dhiru at openwall.com>,
* and it is hereby released to the general public under the following terms:
* Redistribution and use in source and binary forms, with or without
* modification, are permitted.
*
* Jan, 2015, JimF. Fixed salt-dupe problem. Now salt ONLY depends upon
* unencrypted user name, so we have real salt-dupe removal.
*/
#if FMT_EXTERNS_H
extern struct fmt_main fmt_sniffed_lastpass;
#elif FMT_REGISTERS_H
john_register_one(&fmt_sniffed_lastpass);
#else
#include <string.h>
#include <errno.h>
#include "arch.h"
#include "johnswap.h"
#include "misc.h"
#include "common.h"
#include "formats.h"
#include "params.h"
#include "options.h"
#include "base64_convert.h"
#include "aes.h"
#include "pbkdf2_hmac_sha256.h"
#ifdef _OPENMP
#include <omp.h>
#ifndef OMP_SCALE
#define OMP_SCALE 64
#endif
#endif
#include "memdbg.h"
#define FORMAT_LABEL "LastPass"
#define FORMAT_NAME "sniffed sessions"
#define FORMAT_TAG "$lastpass$"
#define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1)
#ifdef SIMD_COEF_32
#define ALGORITHM_NAME "PBKDF2-SHA256 AES " SHA256_ALGORITHM_NAME
#else
#define ALGORITHM_NAME "PBKDF2-SHA256 AES 32/" ARCH_BITS_STR
#endif
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH 0
#define PLAINTEXT_LENGTH 55
#define BINARY_SIZE 16
#define SALT_SIZE sizeof(struct custom_salt)
#define BINARY_ALIGN 4
#define SALT_ALIGN sizeof(int)
#ifdef SIMD_COEF_32
#define MIN_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA256
#define MAX_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA256
#else
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
#endif
/* sentms=1352643586902&xml=2&username=hackme%40mailinator.com&method=cr&hash=4c11d8717015d92db74c42bc1a2570abea3fa18ab17e58a51ce885ee217ccc3f&version=2.0.15&encrypted_username=i%2BhJCwPOj5eQN4tvHcMguoejx4VEmiqzOXOdWIsZKlk%3D&uuid=aHnPh8%40NdhSTWZ%40GJ2fEZe%24cF%40kdzdYh&lang=en-US&iterations=500&sessonly=0&otp=&sesameotp=&multifactorresponse=&lostpwotphash=07a286341be484fc3b96c176e611b10f4d74f230c516f944a008f960f4ec8870&requesthash=i%2BhJCwPOj5eQN4tvHcMguoejx4VEmiqzOXOdWIsZKlk%3D&requestsrc=cr&encuser=i%2BhJCwPOj5eQN4tvHcMguoejx4VEmiqzOXOdWIsZKlk%3D&hasplugin=2.0.15
* decodeURIComponent("hackme%40mailinator.com")
* decodeURIComponent("i%2BhJCwPOj5eQN4tvHcMguoejx4VEmiqzOXOdWIsZKlk%3D") */
/* C:\Users\Administrator\AppData\Local\Google\Chrome\User Data\Default\Extensions\hdokiejnpimakedhajhdlcegeplioahd\2.0.15_0
* lpfulllib.js and server.js are main files involved */
static struct fmt_tests lastpass_tests[] = {
{"$lastpass$hackme@mailinator.com$500$i+hJCwPOj5eQN4tvHcMguoejx4VEmiqzOXOdWIsZKlk=", "openwall"},
{"$lastpass$pass_gen@generated.com$500$vgC0g8BxOi4MerkKfZYFFSAJi8riD7k0ROLpBEA3VJk=", "password"},
// get one with salt under 16 bytes.
{"$lastpass$1@short.com$500$2W/GA8d2N+Z4HGvRYs2R7w==", "password"},
{NULL}
};
static char (*saved_key)[PLAINTEXT_LENGTH + 1];
static uint32_t (*crypt_key)[4];
static struct custom_salt {
unsigned int iterations;
unsigned int length;
char username[129];
} *cur_salt;
static void init(struct fmt_main *self)
{
#if defined (_OPENMP)
int omp_t = omp_get_max_threads();
self->params.min_keys_per_crypt *= omp_t;
omp_t *= OMP_SCALE;
self->params.max_keys_per_crypt *= omp_t;
#endif
saved_key = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*saved_key));
crypt_key = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*crypt_key));
}
static void done(void)
{
MEM_FREE(crypt_key);
MEM_FREE(saved_key);
}
static int valid(char *ciphertext, struct fmt_main *self)
{
char *ctcopy, *keeptr, *p;
if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN) != 0)
return 0;
ctcopy = strdup(ciphertext);
keeptr = ctcopy;
ctcopy += FORMAT_TAG_LEN;
if ((p = strtokm(ctcopy, "$")) == NULL) /* username */
goto err;
if (strlen(p) > 128)
goto err;
if ((p = strtokm(NULL, "$")) == NULL) /* iterations */
goto err;
if (!isdec(p))
goto err;
if ((p = strtokm(NULL, "$")) == NULL) /* data */
goto err;
if (strlen(p) > 50) /* not exact! */
goto err;
MEM_FREE(keeptr);
return 1;
err:
MEM_FREE(keeptr);
return 0;
}
static void *get_salt(char *ciphertext)
{
char *ctcopy = strdup(ciphertext);
char *keeptr = ctcopy;
int i;
char *p;
static struct custom_salt cs;
memset(&cs, 0, sizeof(cs));
ctcopy += FORMAT_TAG_LEN; /* skip over "$lastpass$" */
p = strtokm(ctcopy, "$");
i = strlen(p);
if (i > 16)
i = 16;
cs.length = i; /* truncated length */
strncpy(cs.username, p, 128);
p = strtokm(NULL, "$");
cs.iterations = atoi(p);
MEM_FREE(keeptr);
return (void *)&cs;
}
static void *get_binary(char *ciphertext)
{
static unsigned int out[4];
char Tmp[48];
char *p;
ciphertext += FORMAT_TAG_LEN;
p = strchr(ciphertext, '$')+1;
p = strchr(p, '$')+1;
base64_convert(p, e_b64_mime, strlen(p), Tmp, e_b64_raw, sizeof(Tmp), 0, 0);
memcpy(out, Tmp, 16);
return out;
}
static void set_salt(void *salt)
{
cur_salt = (struct custom_salt *)salt;
}
static int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
int index = 0;
#ifdef _OPENMP
#pragma omp parallel for
for (index = 0; index < count; index += MAX_KEYS_PER_CRYPT)
#endif
{
uint32_t key[MAX_KEYS_PER_CRYPT][8];
unsigned i;
#ifdef SIMD_COEF_32
int lens[MAX_KEYS_PER_CRYPT];
unsigned char *pin[MAX_KEYS_PER_CRYPT];
union {
uint32_t *pout[MAX_KEYS_PER_CRYPT];
unsigned char *poutc;
} x;
for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) {
lens[i] = strlen(saved_key[i+index]);
pin[i] = (unsigned char*)saved_key[i+index];
x.pout[i] = key[i];
}
pbkdf2_sha256_sse((const unsigned char **)pin, lens, (unsigned char*)cur_salt->username, strlen(cur_salt->username), cur_salt->iterations, &(x.poutc), 32, 0);
#else
pbkdf2_sha256((unsigned char*)saved_key[index], strlen(saved_key[index]), (unsigned char*)cur_salt->username, strlen(cur_salt->username), cur_salt->iterations, (unsigned char*)(&key[0]),32,0);
#endif
for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) {
unsigned char *Key = (unsigned char*)key[i];
AES_KEY akey;
unsigned char iv[16];
unsigned char out[32];
if (AES_set_encrypt_key(Key, 256, &akey) < 0) {
fprintf(stderr, "AES_set_encrypt_key failed in crypt!\n");
}
memset(iv, 0, sizeof(iv));
AES_cbc_encrypt((const unsigned char*)cur_salt->username, out, 32, &akey, iv, AES_ENCRYPT);
memcpy(crypt_key[index+i], out, 16);
}
}
return count;
}
static int get_hash_0(int index) { return crypt_key[index][0] & PH_MASK_0; }
static int get_hash_1(int index) { return crypt_key[index][0] & PH_MASK_1; }
static int get_hash_2(int index) { return crypt_key[index][0] & PH_MASK_2; }
static int get_hash_3(int index) { return crypt_key[index][0] & PH_MASK_3; }
static int get_hash_4(int index) { return crypt_key[index][0] & PH_MASK_4; }
static int get_hash_5(int index) { return crypt_key[index][0] & PH_MASK_5; }
static int get_hash_6(int index) { return crypt_key[index][0] & PH_MASK_6; }
static int cmp_all(void *binary, int count) {
int index;
for (index = 0; index < count; index++)
if ( ((uint32_t*)binary)[0] == crypt_key[index][0] )
return 1;
return 0;
}
static int cmp_one(void *binary, int index)
{
return !memcmp(binary, crypt_key[index], BINARY_SIZE);
}
static int cmp_exact(char *source, int index)
{
return 1;
}
static void lastpass_set_key(char *key, int index)
{
int saved_len = strlen(key);
if (saved_len > PLAINTEXT_LENGTH)
saved_len = PLAINTEXT_LENGTH;
memcpy(saved_key[index], key, saved_len);
saved_key[index][saved_len] = 0;
}
static char *get_key(int index)
{
return saved_key[index];
}
static unsigned int iteration_count(void *salt)
{
struct custom_salt *my_salt;
my_salt = salt;
return (unsigned int) my_salt->iterations;
}
struct fmt_main fmt_sniffed_lastpass = {
{
FORMAT_LABEL,
FORMAT_NAME,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_CASE | FMT_8_BIT | FMT_OMP,
{
"iteration count",
},
{ FORMAT_TAG },
lastpass_tests
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid,
fmt_default_split,
get_binary,
get_salt,
{
iteration_count,
},
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,
NULL,
set_salt,
lastpass_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 */
|
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 wait 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 wait 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
|
over-relaxation.c | /*
* Copyright (c) 2020 Maxime Schmitt <maxime.schmitt@manchester.ac.uk>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <assert.h>
#include <stdint.h>
#include <tgmath.h>
#include "over-relaxation.h"
#define max(a, b) ((a) > (b) ? (a) : (b))
#define min(a, b) ((a) < (b) ? (a) : (b))
void solve_over_relaxation(size_t sizeX, size_t sizeY,
double t[restrict sizeX][sizeY],
double tNext[restrict sizeX][sizeY],
double relaxation_factor, double stop_criteria,
double dx, double dy, double *restrict error_end,
size_t *num_iterations) {
assert(sizeX >= 3 && sizeY >= 3);
double factorX = relaxation_factor * 0.5 * dy * dy / ((dx * dx) + (dy * dy));
double factorY = relaxation_factor * 0.5 * dx * dx / ((dx * dx) + (dy * dy));
const size_t iteration_stop =
*num_iterations != 0 ? *num_iterations : SIZE_MAX;
stop_criteria =
*num_iterations != 0 ? -HUGE_VAL : stop_criteria * stop_criteria;
*num_iterations = 0;
double max_error;
do {
max_error = 0.;
for (size_t i = 1; i < sizeX - 1; ++i) {
for (size_t j = 1; j < sizeY - 1; ++j) {
tNext[i][j] = (t[i - 1][j] + t[i + 1][j]) * factorX +
(t[i][j - 1] + t[i][j + 1]) * factorY +
(1. - relaxation_factor) * tNext[i][j];
double error = t[i][j] - tNext[i][j];
error *= error;
max_error = max(error, max_error);
}
}
(*num_iterations)++;
if (!finite(max_error))
break;
void *tmp = tNext;
tNext = t;
t = tmp;
} while (max_error > stop_criteria && *num_iterations != iteration_stop);
*error_end = sqrt(max_error);
}
void solve_over_relaxation_vectorized(size_t sizeX, size_t sizeY,
double t[restrict sizeX][sizeY],
double tNext[restrict sizeX][sizeY],
double relaxation_factor,
double stop_criteria, double dx,
double dy, double *restrict error_end,
size_t *num_iterations) {
assert(sizeX >= 3 && sizeY >= 3);
double factorX = relaxation_factor * 0.5 * dy * dy / ((dx * dx) + (dy * dy));
double factorY = relaxation_factor * 0.5 * dx * dx / ((dx * dx) + (dy * dy));
const size_t iteration_stop =
*num_iterations != 0 ? *num_iterations : SIZE_MAX;
stop_criteria =
*num_iterations != 0 ? -HUGE_VAL : stop_criteria * stop_criteria;
*num_iterations = 0;
double max_error;
do {
max_error = 0.;
for (size_t i = 1; i < sizeX - 1; ++i) {
#pragma omp simd reduction(max : max_error)
for (size_t j = 1; j < sizeY - 1; ++j) {
tNext[i][j] = (t[i - 1][j] + t[i + 1][j]) * factorX +
(t[i][j - 1] + t[i][j + 1]) * factorY +
(1. - relaxation_factor) * tNext[i][j];
double error = t[i][j] - tNext[i][j];
error *= error;
max_error = max(error, max_error);
}
}
(*num_iterations)++;
if (!finite(max_error))
break;
void *tmp = tNext;
tNext = t;
t = tmp;
} while (max_error > stop_criteria && *num_iterations != iteration_stop);
*error_end = sqrt(max_error);
}
void solve_over_relaxation_parallel(size_t sizeX, size_t sizeY,
double t[restrict sizeX][sizeY],
double tNext[restrict sizeX][sizeY],
double relaxation_factor,
double stop_criteria, double dx, double dy,
double *restrict error_end,
size_t *num_iterations) {
assert(sizeX >= 3 && sizeY >= 3);
double factorX = relaxation_factor * 0.5 * dy * dy / ((dx * dx) + (dy * dy));
double factorY = relaxation_factor * 0.5 * dx * dx / ((dx * dx) + (dy * dy));
const size_t iteration_stop =
*num_iterations != 0 ? *num_iterations : SIZE_MAX;
stop_criteria =
*num_iterations != 0 ? -HUGE_VAL : stop_criteria * stop_criteria;
*num_iterations = 0;
double max_error;
#pragma omp parallel default(none) \
shared(sizeX, sizeY, max_error, stop_criteria, num_iterations, factorX, \
factorY, relaxation_factor, iteration_stop) firstprivate(t, tNext)
{
size_t local_num_iteration = 0;
do {
#pragma omp barrier
#pragma omp single
max_error = 0.;
#pragma omp for reduction(max : max_error)
for (size_t i = 1; i < sizeX - 1; ++i) {
#pragma omp simd reduction(max : max_error)
for (size_t j = 1; j < sizeY - 1; ++j) {
tNext[i][j] = (t[i - 1][j] + t[i + 1][j]) * factorX +
(t[i][j - 1] + t[i][j + 1]) * factorY +
(1. - relaxation_factor) * tNext[i][j];
double error = t[i][j] - tNext[i][j];
error *= error;
max_error = max(error, max_error);
}
}
#pragma omp master
(*num_iterations)++;
local_num_iteration++;
if (!finite(max_error))
break;
void *tmp = tNext;
tNext = t;
t = tmp;
} while (max_error > stop_criteria &&
local_num_iteration != iteration_stop);
}
*error_end = sqrt(max_error);
}
void solve_over_relaxation_parallel_tiled(size_t sizeX, size_t sizeY,
double t[restrict sizeX][sizeY],
double tNext[restrict sizeX][sizeY],
double relaxation_factor,
double stop_criteria, double dx,
double dy, double *restrict error_end,
size_t *num_iterations) {
assert(sizeX >= 3 && sizeY >= 3);
double factorX = relaxation_factor * 0.5 * dy * dy / ((dx * dx) + (dy * dy));
double factorY = relaxation_factor * 0.5 * dx * dx / ((dx * dx) + (dy * dy));
const size_t iteration_stop =
*num_iterations != 0 ? *num_iterations : SIZE_MAX;
stop_criteria =
*num_iterations != 0 ? -HUGE_VAL : stop_criteria * stop_criteria;
*num_iterations = 0;
double max_error;
#pragma omp parallel default(none) \
shared(sizeX, sizeY, max_error, stop_criteria, num_iterations, factorX, \
factorY, relaxation_factor, iteration_stop) firstprivate(t, tNext)
{
size_t local_num_iteration = 0;
do {
#pragma omp barrier
#pragma omp single
max_error = 0.;
#pragma omp for reduction(max : max_error)
for (size_t t1 = 0; t1 <= (sizeX - 2) / 32; t1++) {
for (size_t t2 = 0; t2 <= (sizeY - 2) / 32; t2++) {
for (size_t t3 = max(1, 32 * t1); t3 <= min(sizeX - 2, 32 * t1 + 31);
t3++) {
size_t lbv = max(1, 32 * t2);
size_t ubv = min(sizeY - 2, 32 * t2 + 31);
#pragma omp simd reduction(max : max_error)
for (size_t t4 = lbv; t4 <= ubv; t4++) {
tNext[t3][t4] = (t[t3 - 1][t4] + t[t3 + 1][t4]) * factorX +
(t[t3][t4 - 1] + t[t3][t4 + 1]) * factorY +
(1. - relaxation_factor) * tNext[t3][t4];
double error = t[t3][t4] - tNext[t3][t4];
error *= error;
max_error = max(error, max_error);
}
}
}
}
#pragma omp master
(*num_iterations)++;
local_num_iteration++;
if (!finite(max_error))
break;
void *tmp = tNext;
tNext = t;
t = tmp;
} while (max_error > stop_criteria &&
local_num_iteration != iteration_stop);
}
*error_end = sqrt(max_error);
}
|
sobel-omp.c | #include <unistd.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <string.h>
#include <omp.h>
#include "lib/neryimg.h"
#include "lib/utils.h"
int main(int argc, char **argv){
unsigned int tid, i, j;
// Checks number of arguments.
if (argc != 3) fail("usage: ./sobel-omp <input ppm> <output ppm>");
// Reads source image file.
FILE* originalImageFile = fopen(argv[1], "rb");
if (!originalImageFile) fail("Could not read original image file");
// Loads source image.
ppm_image originalImage = getPpmShared(originalImageFile);
if (!originalImage) fail("Could not alloc PPM for the original image");
// Adds margin to image.
originalImage = addMargins(originalImage);
to_greyscale(originalImage);
// Allocates resulting image.
ppm_image result = allocSharedImage(originalImage->width, originalImage->height);
fill_img(result, 1, 0, 0); // Fills it with black pixels.
// for statement is splitted between processes by OMP.
#pragma omp parallel for private(tid, i, j) shared(result, originalImage)
for (i = 1; i < result->width -2; i++) {
for (j = 1; j < result->height; j++) {
transformPixelSobel(originalImage, i, j, result);
}
}
saveImage(result, argv[2]);
return 0;
}
|
Parser.h | //===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines the Parser interface.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_PARSE_PARSER_H
#define LLVM_CLANG_PARSE_PARSER_H
#include "clang/AST/OpenMPClause.h"
#include "clang/AST/Availability.h"
#include "clang/Basic/BitmaskEnum.h"
#include "clang/Basic/OpenMPKinds.h"
#include "clang/Basic/OperatorPrecedence.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Lex/CodeCompletionHandler.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/Sema.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/SaveAndRestore.h"
#include <memory>
#include <stack>
namespace clang {
class PragmaHandler;
class Scope;
class BalancedDelimiterTracker;
class CorrectionCandidateCallback;
class DeclGroupRef;
class DiagnosticBuilder;
struct LoopHint;
class Parser;
class ParsingDeclRAIIObject;
class ParsingDeclSpec;
class ParsingDeclarator;
class ParsingFieldDeclarator;
class ColonProtectionRAIIObject;
class InMessageExpressionRAIIObject;
class PoisonSEHIdentifiersRAIIObject;
class OMPClause;
class ObjCTypeParamList;
class ObjCTypeParameter;
/// Parser - This implements a parser for the C family of languages. After
/// parsing units of the grammar, productions are invoked to handle whatever has
/// been read.
///
class Parser : public CodeCompletionHandler {
friend class ColonProtectionRAIIObject;
friend class ParsingOpenMPDirectiveRAII;
friend class InMessageExpressionRAIIObject;
friend class PoisonSEHIdentifiersRAIIObject;
friend class ObjCDeclContextSwitch;
friend class ParenBraceBracketBalancer;
friend class BalancedDelimiterTracker;
Preprocessor &PP;
/// Tok - The current token we are peeking ahead. All parsing methods assume
/// that this is valid.
Token Tok;
// PrevTokLocation - The location of the token we previously
// consumed. This token is used for diagnostics where we expected to
// see a token following another token (e.g., the ';' at the end of
// a statement).
SourceLocation PrevTokLocation;
/// Tracks an expected type for the current token when parsing an expression.
/// Used by code completion for ranking.
PreferredTypeBuilder PreferredType;
unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0;
unsigned short MisplacedModuleBeginCount = 0;
/// Actions - These are the callbacks we invoke as we parse various constructs
/// in the file.
Sema &Actions;
DiagnosticsEngine &Diags;
/// ScopeCache - Cache scopes to reduce malloc traffic.
enum { ScopeCacheSize = 16 };
unsigned NumCachedScopes;
Scope *ScopeCache[ScopeCacheSize];
/// Identifiers used for SEH handling in Borland. These are only
/// allowed in particular circumstances
// __except block
IdentifierInfo *Ident__exception_code,
*Ident___exception_code,
*Ident_GetExceptionCode;
// __except filter expression
IdentifierInfo *Ident__exception_info,
*Ident___exception_info,
*Ident_GetExceptionInfo;
// __finally
IdentifierInfo *Ident__abnormal_termination,
*Ident___abnormal_termination,
*Ident_AbnormalTermination;
/// Contextual keywords for Microsoft extensions.
IdentifierInfo *Ident__except;
mutable IdentifierInfo *Ident_sealed;
/// Ident_super - IdentifierInfo for "super", to support fast
/// comparison.
IdentifierInfo *Ident_super;
/// Ident_vector, Ident_bool - cached IdentifierInfos for "vector" and
/// "bool" fast comparison. Only present if AltiVec or ZVector are enabled.
IdentifierInfo *Ident_vector;
IdentifierInfo *Ident_bool;
/// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison.
/// Only present if AltiVec enabled.
IdentifierInfo *Ident_pixel;
/// Objective-C contextual keywords.
IdentifierInfo *Ident_instancetype;
/// Identifier for "introduced".
IdentifierInfo *Ident_introduced;
/// Identifier for "deprecated".
IdentifierInfo *Ident_deprecated;
/// Identifier for "obsoleted".
IdentifierInfo *Ident_obsoleted;
/// Identifier for "unavailable".
IdentifierInfo *Ident_unavailable;
/// Identifier for "message".
IdentifierInfo *Ident_message;
/// Identifier for "strict".
IdentifierInfo *Ident_strict;
/// Identifier for "replacement".
IdentifierInfo *Ident_replacement;
/// Identifiers used by the 'external_source_symbol' attribute.
IdentifierInfo *Ident_language, *Ident_defined_in,
*Ident_generated_declaration;
/// C++11 contextual keywords.
mutable IdentifierInfo *Ident_final;
mutable IdentifierInfo *Ident_GNU_final;
mutable IdentifierInfo *Ident_override;
// C++2a contextual keywords.
mutable IdentifierInfo *Ident_import;
mutable IdentifierInfo *Ident_module;
// C++ type trait keywords that can be reverted to identifiers and still be
// used as type traits.
llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits;
std::unique_ptr<PragmaHandler> AlignHandler;
std::unique_ptr<PragmaHandler> GCCVisibilityHandler;
std::unique_ptr<PragmaHandler> OptionsHandler;
std::unique_ptr<PragmaHandler> PackHandler;
std::unique_ptr<PragmaHandler> MSStructHandler;
std::unique_ptr<PragmaHandler> UnusedHandler;
std::unique_ptr<PragmaHandler> WeakHandler;
std::unique_ptr<PragmaHandler> RedefineExtnameHandler;
std::unique_ptr<PragmaHandler> FPContractHandler;
std::unique_ptr<PragmaHandler> OpenCLExtensionHandler;
std::unique_ptr<PragmaHandler> OpenMPHandler;
std::unique_ptr<PragmaHandler> PCSectionHandler;
std::unique_ptr<PragmaHandler> MSCommentHandler;
std::unique_ptr<PragmaHandler> MSDetectMismatchHandler;
std::unique_ptr<PragmaHandler> MSPointersToMembers;
std::unique_ptr<PragmaHandler> MSVtorDisp;
std::unique_ptr<PragmaHandler> MSInitSeg;
std::unique_ptr<PragmaHandler> MSDataSeg;
std::unique_ptr<PragmaHandler> MSBSSSeg;
std::unique_ptr<PragmaHandler> MSConstSeg;
std::unique_ptr<PragmaHandler> MSCodeSeg;
std::unique_ptr<PragmaHandler> MSSection;
std::unique_ptr<PragmaHandler> MSRuntimeChecks;
std::unique_ptr<PragmaHandler> MSIntrinsic;
std::unique_ptr<PragmaHandler> MSOptimize;
std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler;
std::unique_ptr<PragmaHandler> OptimizeHandler;
std::unique_ptr<PragmaHandler> LoopHintHandler;
std::unique_ptr<PragmaHandler> UnrollHintHandler;
std::unique_ptr<PragmaHandler> NoUnrollHintHandler;
std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler;
std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler;
std::unique_ptr<PragmaHandler> FPHandler;
std::unique_ptr<PragmaHandler> STDCFENVHandler;
std::unique_ptr<PragmaHandler> STDCCXLIMITHandler;
std::unique_ptr<PragmaHandler> STDCUnknownHandler;
std::unique_ptr<PragmaHandler> AttributePragmaHandler;
std::unique_ptr<PragmaHandler> MaxTokensHerePragmaHandler;
std::unique_ptr<PragmaHandler> MaxTokensTotalPragmaHandler;
std::unique_ptr<CommentHandler> CommentSemaHandler;
/// Whether the '>' token acts as an operator or not. This will be
/// true except when we are parsing an expression within a C++
/// template argument list, where the '>' closes the template
/// argument list.
bool GreaterThanIsOperator;
/// ColonIsSacred - When this is false, we aggressively try to recover from
/// code like "foo : bar" as if it were a typo for "foo :: bar". This is not
/// safe in case statements and a few other things. This is managed by the
/// ColonProtectionRAIIObject RAII object.
bool ColonIsSacred;
/// Parsing OpenMP directive mode.
bool OpenMPDirectiveParsing = false;
/// When true, we are directly inside an Objective-C message
/// send expression.
///
/// This is managed by the \c InMessageExpressionRAIIObject class, and
/// should not be set directly.
bool InMessageExpression;
/// Gets set to true after calling ProduceSignatureHelp, it is for a
/// workaround to make sure ProduceSignatureHelp is only called at the deepest
/// function call.
bool CalledSignatureHelp = false;
/// The "depth" of the template parameters currently being parsed.
unsigned TemplateParameterDepth;
/// RAII class that manages the template parameter depth.
class TemplateParameterDepthRAII {
unsigned &Depth;
unsigned AddedLevels;
public:
explicit TemplateParameterDepthRAII(unsigned &Depth)
: Depth(Depth), AddedLevels(0) {}
~TemplateParameterDepthRAII() {
Depth -= AddedLevels;
}
void operator++() {
++Depth;
++AddedLevels;
}
void addDepth(unsigned D) {
Depth += D;
AddedLevels += D;
}
void setAddedDepth(unsigned D) {
Depth = Depth - AddedLevels + D;
AddedLevels = D;
}
unsigned getDepth() const { return Depth; }
unsigned getOriginalDepth() const { return Depth - AddedLevels; }
};
/// Factory object for creating ParsedAttr objects.
AttributeFactory AttrFactory;
/// Gathers and cleans up TemplateIdAnnotations when parsing of a
/// top-level declaration is finished.
SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
/// Identifiers which have been declared within a tentative parse.
SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
/// Tracker for '<' tokens that might have been intended to be treated as an
/// angle bracket instead of a less-than comparison.
///
/// This happens when the user intends to form a template-id, but typoes the
/// template-name or forgets a 'template' keyword for a dependent template
/// name.
///
/// We track these locations from the point where we see a '<' with a
/// name-like expression on its left until we see a '>' or '>>' that might
/// match it.
struct AngleBracketTracker {
/// Flags used to rank candidate template names when there is more than one
/// '<' in a scope.
enum Priority : unsigned short {
/// A non-dependent name that is a potential typo for a template name.
PotentialTypo = 0x0,
/// A dependent name that might instantiate to a template-name.
DependentName = 0x2,
/// A space appears before the '<' token.
SpaceBeforeLess = 0x0,
/// No space before the '<' token
NoSpaceBeforeLess = 0x1,
LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue*/ DependentName)
};
struct Loc {
Expr *TemplateName;
SourceLocation LessLoc;
AngleBracketTracker::Priority Priority;
unsigned short ParenCount, BracketCount, BraceCount;
bool isActive(Parser &P) const {
return P.ParenCount == ParenCount && P.BracketCount == BracketCount &&
P.BraceCount == BraceCount;
}
bool isActiveOrNested(Parser &P) const {
return isActive(P) || P.ParenCount > ParenCount ||
P.BracketCount > BracketCount || P.BraceCount > BraceCount;
}
};
SmallVector<Loc, 8> Locs;
/// Add an expression that might have been intended to be a template name.
/// In the case of ambiguity, we arbitrarily select the innermost such
/// expression, for example in 'foo < bar < baz', 'bar' is the current
/// candidate. No attempt is made to track that 'foo' is also a candidate
/// for the case where we see a second suspicious '>' token.
void add(Parser &P, Expr *TemplateName, SourceLocation LessLoc,
Priority Prio) {
if (!Locs.empty() && Locs.back().isActive(P)) {
if (Locs.back().Priority <= Prio) {
Locs.back().TemplateName = TemplateName;
Locs.back().LessLoc = LessLoc;
Locs.back().Priority = Prio;
}
} else {
Locs.push_back({TemplateName, LessLoc, Prio,
P.ParenCount, P.BracketCount, P.BraceCount});
}
}
/// Mark the current potential missing template location as having been
/// handled (this happens if we pass a "corresponding" '>' or '>>' token
/// or leave a bracket scope).
void clear(Parser &P) {
while (!Locs.empty() && Locs.back().isActiveOrNested(P))
Locs.pop_back();
}
/// Get the current enclosing expression that might hve been intended to be
/// a template name.
Loc *getCurrent(Parser &P) {
if (!Locs.empty() && Locs.back().isActive(P))
return &Locs.back();
return nullptr;
}
};
AngleBracketTracker AngleBrackets;
IdentifierInfo *getSEHExceptKeyword();
/// True if we are within an Objective-C container while parsing C-like decls.
///
/// This is necessary because Sema thinks we have left the container
/// to parse the C-like decls, meaning Actions.getObjCDeclContext() will
/// be NULL.
bool ParsingInObjCContainer;
/// Whether to skip parsing of function bodies.
///
/// This option can be used, for example, to speed up searches for
/// declarations/definitions when indexing.
bool SkipFunctionBodies;
/// The location of the expression statement that is being parsed right now.
/// Used to determine if an expression that is being parsed is a statement or
/// just a regular sub-expression.
SourceLocation ExprStatementTokLoc;
/// Flags describing a context in which we're parsing a statement.
enum class ParsedStmtContext {
/// This context permits declarations in language modes where declarations
/// are not statements.
AllowDeclarationsInC = 0x1,
/// This context permits standalone OpenMP directives.
AllowStandaloneOpenMPDirectives = 0x2,
/// This context is at the top level of a GNU statement expression.
InStmtExpr = 0x4,
/// The context of a regular substatement.
SubStmt = 0,
/// The context of a compound-statement.
Compound = AllowDeclarationsInC | AllowStandaloneOpenMPDirectives,
LLVM_MARK_AS_BITMASK_ENUM(InStmtExpr)
};
/// Act on an expression statement that might be the last statement in a
/// GNU statement expression. Checks whether we are actually at the end of
/// a statement expression and builds a suitable expression statement.
StmtResult handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx);
public:
Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
~Parser() override;
const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
Preprocessor &getPreprocessor() const { return PP; }
Sema &getActions() const { return Actions; }
AttributeFactory &getAttrFactory() { return AttrFactory; }
const Token &getCurToken() const { return Tok; }
Scope *getCurScope() const { return Actions.getCurScope(); }
void incrementMSManglingNumber() const {
return Actions.incrementMSManglingNumber();
}
Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); }
// Type forwarding. All of these are statically 'void*', but they may all be
// different actual classes based on the actions in place.
typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
typedef OpaquePtr<TemplateName> TemplateTy;
typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists;
typedef Sema::FullExprArg FullExprArg;
// Parsing methods.
/// Initialize - Warm up the parser.
///
void Initialize();
/// Parse the first top-level declaration in a translation unit.
bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result);
/// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
/// the EOF was encountered.
bool ParseTopLevelDecl(DeclGroupPtrTy &Result, bool IsFirstDecl = false);
bool ParseTopLevelDecl() {
DeclGroupPtrTy Result;
return ParseTopLevelDecl(Result);
}
/// ConsumeToken - Consume the current 'peek token' and lex the next one.
/// This does not work with special tokens: string literals, code completion,
/// annotation tokens and balanced tokens must be handled using the specific
/// consume methods.
/// Returns the location of the consumed token.
SourceLocation ConsumeToken() {
assert(!isTokenSpecial() &&
"Should consume special tokens with Consume*Token");
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
bool TryConsumeToken(tok::TokenKind Expected) {
if (Tok.isNot(Expected))
return false;
assert(!isTokenSpecial() &&
"Should consume special tokens with Consume*Token");
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return true;
}
bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) {
if (!TryConsumeToken(Expected))
return false;
Loc = PrevTokLocation;
return true;
}
/// ConsumeAnyToken - Dispatch to the right Consume* method based on the
/// current token type. This should only be used in cases where the type of
/// the token really isn't known, e.g. in error recovery.
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) {
if (isTokenParen())
return ConsumeParen();
if (isTokenBracket())
return ConsumeBracket();
if (isTokenBrace())
return ConsumeBrace();
if (isTokenStringLiteral())
return ConsumeStringToken();
if (Tok.is(tok::code_completion))
return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken()
: handleUnexpectedCodeCompletionToken();
if (Tok.isAnnotation())
return ConsumeAnnotationToken();
return ConsumeToken();
}
SourceLocation getEndOfPreviousToken() {
return PP.getLocForEndOfToken(PrevTokLocation);
}
/// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds
/// to the given nullability kind.
IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) {
return Actions.getNullabilityKeyword(nullability);
}
private:
//===--------------------------------------------------------------------===//
// Low-Level token peeking and consumption methods.
//
/// isTokenParen - Return true if the cur token is '(' or ')'.
bool isTokenParen() const {
return Tok.isOneOf(tok::l_paren, tok::r_paren);
}
/// isTokenBracket - Return true if the cur token is '[' or ']'.
bool isTokenBracket() const {
return Tok.isOneOf(tok::l_square, tok::r_square);
}
/// isTokenBrace - Return true if the cur token is '{' or '}'.
bool isTokenBrace() const {
return Tok.isOneOf(tok::l_brace, tok::r_brace);
}
/// isTokenStringLiteral - True if this token is a string-literal.
bool isTokenStringLiteral() const {
return tok::isStringLiteral(Tok.getKind());
}
/// isTokenSpecial - True if this token requires special consumption methods.
bool isTokenSpecial() const {
return isTokenStringLiteral() || isTokenParen() || isTokenBracket() ||
isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation();
}
/// Returns true if the current token is '=' or is a type of '='.
/// For typos, give a fixit to '='
bool isTokenEqualOrEqualTypo();
/// Return the current token to the token stream and make the given
/// token the current token.
void UnconsumeToken(Token &Consumed) {
Token Next = Tok;
PP.EnterToken(Consumed, /*IsReinject*/true);
PP.Lex(Tok);
PP.EnterToken(Next, /*IsReinject*/true);
}
SourceLocation ConsumeAnnotationToken() {
assert(Tok.isAnnotation() && "wrong consume method");
SourceLocation Loc = Tok.getLocation();
PrevTokLocation = Tok.getAnnotationEndLoc();
PP.Lex(Tok);
return Loc;
}
/// ConsumeParen - This consume method keeps the paren count up-to-date.
///
SourceLocation ConsumeParen() {
assert(isTokenParen() && "wrong consume method");
if (Tok.getKind() == tok::l_paren)
++ParenCount;
else if (ParenCount) {
AngleBrackets.clear(*this);
--ParenCount; // Don't let unbalanced )'s drive the count negative.
}
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
/// ConsumeBracket - This consume method keeps the bracket count up-to-date.
///
SourceLocation ConsumeBracket() {
assert(isTokenBracket() && "wrong consume method");
if (Tok.getKind() == tok::l_square)
++BracketCount;
else if (BracketCount) {
AngleBrackets.clear(*this);
--BracketCount; // Don't let unbalanced ]'s drive the count negative.
}
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
/// ConsumeBrace - This consume method keeps the brace count up-to-date.
///
SourceLocation ConsumeBrace() {
assert(isTokenBrace() && "wrong consume method");
if (Tok.getKind() == tok::l_brace)
++BraceCount;
else if (BraceCount) {
AngleBrackets.clear(*this);
--BraceCount; // Don't let unbalanced }'s drive the count negative.
}
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
/// ConsumeStringToken - Consume the current 'peek token', lexing a new one
/// and returning the token kind. This method is specific to strings, as it
/// handles string literal concatenation, as per C99 5.1.1.2, translation
/// phase #6.
SourceLocation ConsumeStringToken() {
assert(isTokenStringLiteral() &&
"Should only consume string literals with this method");
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
/// Consume the current code-completion token.
///
/// This routine can be called to consume the code-completion token and
/// continue processing in special cases where \c cutOffParsing() isn't
/// desired, such as token caching or completion with lookahead.
SourceLocation ConsumeCodeCompletionToken() {
assert(Tok.is(tok::code_completion));
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
///\ brief When we are consuming a code-completion token without having
/// matched specific position in the grammar, provide code-completion results
/// based on context.
///
/// \returns the source location of the code-completion token.
SourceLocation handleUnexpectedCodeCompletionToken();
/// Abruptly cut off parsing; mainly used when we have reached the
/// code-completion point.
void cutOffParsing() {
if (PP.isCodeCompletionEnabled())
PP.setCodeCompletionReached();
// Cut off parsing by acting as if we reached the end-of-file.
Tok.setKind(tok::eof);
}
/// Determine if we're at the end of the file or at a transition
/// between modules.
bool isEofOrEom() {
tok::TokenKind Kind = Tok.getKind();
return Kind == tok::eof || Kind == tok::annot_module_begin ||
Kind == tok::annot_module_end || Kind == tok::annot_module_include;
}
/// Checks if the \p Level is valid for use in a fold expression.
bool isFoldOperator(prec::Level Level) const;
/// Checks if the \p Kind is a valid operator for fold expressions.
bool isFoldOperator(tok::TokenKind Kind) const;
/// Initialize all pragma handlers.
void initializePragmaHandlers();
/// Destroy and reset all pragma handlers.
void resetPragmaHandlers();
/// Handle the annotation token produced for #pragma unused(...)
void HandlePragmaUnused();
/// Handle the annotation token produced for
/// #pragma GCC visibility...
void HandlePragmaVisibility();
/// Handle the annotation token produced for
/// #pragma pack...
void HandlePragmaPack();
/// Handle the annotation token produced for
/// #pragma ms_struct...
void HandlePragmaMSStruct();
/// Handle the annotation token produced for
/// #pragma comment...
void HandlePragmaMSComment();
void HandlePragmaMSPointersToMembers();
void HandlePragmaMSVtorDisp();
void HandlePragmaMSPragma();
bool HandlePragmaMSSection(StringRef PragmaName,
SourceLocation PragmaLocation);
bool HandlePragmaMSSegment(StringRef PragmaName,
SourceLocation PragmaLocation);
bool HandlePragmaMSInitSeg(StringRef PragmaName,
SourceLocation PragmaLocation);
/// Handle the annotation token produced for
/// #pragma align...
void HandlePragmaAlign();
/// Handle the annotation token produced for
/// #pragma clang __debug dump...
void HandlePragmaDump();
/// Handle the annotation token produced for
/// #pragma weak id...
void HandlePragmaWeak();
/// Handle the annotation token produced for
/// #pragma weak id = id...
void HandlePragmaWeakAlias();
/// Handle the annotation token produced for
/// #pragma redefine_extname...
void HandlePragmaRedefineExtname();
/// Handle the annotation token produced for
/// #pragma STDC FP_CONTRACT...
void HandlePragmaFPContract();
/// Handle the annotation token produced for
/// #pragma STDC FENV_ACCESS...
void HandlePragmaFEnvAccess();
/// \brief Handle the annotation token produced for
/// #pragma clang fp ...
void HandlePragmaFP();
/// Handle the annotation token produced for
/// #pragma OPENCL EXTENSION...
void HandlePragmaOpenCLExtension();
/// Handle the annotation token produced for
/// #pragma clang __debug captured
StmtResult HandlePragmaCaptured();
/// Handle the annotation token produced for
/// #pragma clang loop and #pragma unroll.
bool HandlePragmaLoopHint(LoopHint &Hint);
bool ParsePragmaAttributeSubjectMatchRuleSet(
attr::ParsedSubjectMatchRuleSet &SubjectMatchRules,
SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc);
void HandlePragmaAttribute();
/// GetLookAheadToken - This peeks ahead N tokens and returns that token
/// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1)
/// returns the token after Tok, etc.
///
/// Note that this differs from the Preprocessor's LookAhead method, because
/// the Parser always has one token lexed that the preprocessor doesn't.
///
const Token &GetLookAheadToken(unsigned N) {
if (N == 0 || Tok.is(tok::eof)) return Tok;
return PP.LookAhead(N-1);
}
public:
/// NextToken - This peeks ahead one token and returns it without
/// consuming it.
const Token &NextToken() {
return PP.LookAhead(0);
}
/// getTypeAnnotation - Read a parsed type out of an annotation token.
static ParsedType getTypeAnnotation(const Token &Tok) {
return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
}
private:
static void setTypeAnnotation(Token &Tok, ParsedType T) {
Tok.setAnnotationValue(T.getAsOpaquePtr());
}
static NamedDecl *getNonTypeAnnotation(const Token &Tok) {
return static_cast<NamedDecl*>(Tok.getAnnotationValue());
}
static void setNonTypeAnnotation(Token &Tok, NamedDecl *ND) {
Tok.setAnnotationValue(ND);
}
static IdentifierInfo *getIdentifierAnnotation(const Token &Tok) {
return static_cast<IdentifierInfo*>(Tok.getAnnotationValue());
}
static void setIdentifierAnnotation(Token &Tok, IdentifierInfo *ND) {
Tok.setAnnotationValue(ND);
}
/// Read an already-translated primary expression out of an annotation
/// token.
static ExprResult getExprAnnotation(const Token &Tok) {
return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue());
}
/// Set the primary expression corresponding to the given annotation
/// token.
static void setExprAnnotation(Token &Tok, ExprResult ER) {
Tok.setAnnotationValue(ER.getAsOpaquePointer());
}
public:
// If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to
// find a type name by attempting typo correction.
bool TryAnnotateTypeOrScopeToken();
bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS,
bool IsNewScope);
bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
bool MightBeCXXScopeToken() {
return Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
(Tok.is(tok::annot_template_id) &&
NextToken().is(tok::coloncolon)) ||
Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super);
}
bool TryAnnotateOptionalCXXScopeToken(bool EnteringContext = false) {
return MightBeCXXScopeToken() && TryAnnotateCXXScopeToken(EnteringContext);
}
private:
enum AnnotatedNameKind {
/// Annotation has failed and emitted an error.
ANK_Error,
/// The identifier is a tentatively-declared name.
ANK_TentativeDecl,
/// The identifier is a template name. FIXME: Add an annotation for that.
ANK_TemplateName,
/// The identifier can't be resolved.
ANK_Unresolved,
/// Annotation was successful.
ANK_Success
};
AnnotatedNameKind TryAnnotateName(CorrectionCandidateCallback *CCC = nullptr);
/// Push a tok::annot_cxxscope token onto the token stream.
void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
/// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
/// replacing them with the non-context-sensitive keywords. This returns
/// true if the token was replaced.
bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
const char *&PrevSpec, unsigned &DiagID,
bool &isInvalid) {
if (!getLangOpts().AltiVec && !getLangOpts().ZVector)
return false;
if (Tok.getIdentifierInfo() != Ident_vector &&
Tok.getIdentifierInfo() != Ident_bool &&
(!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel))
return false;
return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
}
/// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
/// identifier token, replacing it with the non-context-sensitive __vector.
/// This returns true if the token was replaced.
bool TryAltiVecVectorToken() {
if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) ||
Tok.getIdentifierInfo() != Ident_vector) return false;
return TryAltiVecVectorTokenOutOfLine();
}
bool TryAltiVecVectorTokenOutOfLine();
bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
const char *&PrevSpec, unsigned &DiagID,
bool &isInvalid);
/// Returns true if the current token is the identifier 'instancetype'.
///
/// Should only be used in Objective-C language modes.
bool isObjCInstancetype() {
assert(getLangOpts().ObjC);
if (Tok.isAnnotation())
return false;
if (!Ident_instancetype)
Ident_instancetype = PP.getIdentifierInfo("instancetype");
return Tok.getIdentifierInfo() == Ident_instancetype;
}
/// TryKeywordIdentFallback - For compatibility with system headers using
/// keywords as identifiers, attempt to convert the current token to an
/// identifier and optionally disable the keyword for the remainder of the
/// translation unit. This returns false if the token was not replaced,
/// otherwise emits a diagnostic and returns true.
bool TryKeywordIdentFallback(bool DisableKeyword);
/// Get the TemplateIdAnnotation from the token.
TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
/// TentativeParsingAction - An object that is used as a kind of "tentative
/// parsing transaction". It gets instantiated to mark the token position and
/// after the token consumption is done, Commit() or Revert() is called to
/// either "commit the consumed tokens" or revert to the previously marked
/// token position. Example:
///
/// TentativeParsingAction TPA(*this);
/// ConsumeToken();
/// ....
/// TPA.Revert();
///
class TentativeParsingAction {
Parser &P;
PreferredTypeBuilder PrevPreferredType;
Token PrevTok;
size_t PrevTentativelyDeclaredIdentifierCount;
unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
bool isActive;
public:
explicit TentativeParsingAction(Parser& p) : P(p) {
PrevPreferredType = P.PreferredType;
PrevTok = P.Tok;
PrevTentativelyDeclaredIdentifierCount =
P.TentativelyDeclaredIdentifiers.size();
PrevParenCount = P.ParenCount;
PrevBracketCount = P.BracketCount;
PrevBraceCount = P.BraceCount;
P.PP.EnableBacktrackAtThisPos();
isActive = true;
}
void Commit() {
assert(isActive && "Parsing action was finished!");
P.TentativelyDeclaredIdentifiers.resize(
PrevTentativelyDeclaredIdentifierCount);
P.PP.CommitBacktrackedTokens();
isActive = false;
}
void Revert() {
assert(isActive && "Parsing action was finished!");
P.PP.Backtrack();
P.PreferredType = PrevPreferredType;
P.Tok = PrevTok;
P.TentativelyDeclaredIdentifiers.resize(
PrevTentativelyDeclaredIdentifierCount);
P.ParenCount = PrevParenCount;
P.BracketCount = PrevBracketCount;
P.BraceCount = PrevBraceCount;
isActive = false;
}
~TentativeParsingAction() {
assert(!isActive && "Forgot to call Commit or Revert!");
}
};
/// A TentativeParsingAction that automatically reverts in its destructor.
/// Useful for disambiguation parses that will always be reverted.
class RevertingTentativeParsingAction
: private Parser::TentativeParsingAction {
public:
RevertingTentativeParsingAction(Parser &P)
: Parser::TentativeParsingAction(P) {}
~RevertingTentativeParsingAction() { Revert(); }
};
class UnannotatedTentativeParsingAction;
/// ObjCDeclContextSwitch - An object used to switch context from
/// an objective-c decl context to its enclosing decl context and
/// back.
class ObjCDeclContextSwitch {
Parser &P;
Decl *DC;
SaveAndRestore<bool> WithinObjCContainer;
public:
explicit ObjCDeclContextSwitch(Parser &p)
: P(p), DC(p.getObjCDeclContext()),
WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) {
if (DC)
P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC));
}
~ObjCDeclContextSwitch() {
if (DC)
P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC));
}
};
/// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
/// input. If so, it is consumed and false is returned.
///
/// If a trivial punctuator misspelling is encountered, a FixIt error
/// diagnostic is issued and false is returned after recovery.
///
/// If the input is malformed, this emits the specified diagnostic and true is
/// returned.
bool ExpectAndConsume(tok::TokenKind ExpectedTok,
unsigned Diag = diag::err_expected,
StringRef DiagMsg = "");
/// The parser expects a semicolon and, if present, will consume it.
///
/// If the next token is not a semicolon, this emits the specified diagnostic,
/// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
/// to the semicolon, consumes that extra token.
bool ExpectAndConsumeSemi(unsigned DiagID);
/// The kind of extra semi diagnostic to emit.
enum ExtraSemiKind {
OutsideFunction = 0,
InsideStruct = 1,
InstanceVariableList = 2,
AfterMemberFunctionDefinition = 3
};
/// Consume any extra semi-colons until the end of the line.
void ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST T = TST_unspecified);
/// Return false if the next token is an identifier. An 'expected identifier'
/// error is emitted otherwise.
///
/// The parser tries to recover from the error by checking if the next token
/// is a C++ keyword when parsing Objective-C++. Return false if the recovery
/// was successful.
bool expectIdentifier();
public:
//===--------------------------------------------------------------------===//
// Scope manipulation
/// ParseScope - Introduces a new scope for parsing. The kind of
/// scope is determined by ScopeFlags. Objects of this type should
/// be created on the stack to coincide with the position where the
/// parser enters the new scope, and this object's constructor will
/// create that new scope. Similarly, once the object is destroyed
/// the parser will exit the scope.
class ParseScope {
Parser *Self;
ParseScope(const ParseScope &) = delete;
void operator=(const ParseScope &) = delete;
public:
// ParseScope - Construct a new object to manage a scope in the
// parser Self where the new Scope is created with the flags
// ScopeFlags, but only when we aren't about to enter a compound statement.
ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true,
bool BeforeCompoundStmt = false)
: Self(Self) {
if (EnteredScope && !BeforeCompoundStmt)
Self->EnterScope(ScopeFlags);
else {
if (BeforeCompoundStmt)
Self->incrementMSManglingNumber();
this->Self = nullptr;
}
}
// Exit - Exit the scope associated with this object now, rather
// than waiting until the object is destroyed.
void Exit() {
if (Self) {
Self->ExitScope();
Self = nullptr;
}
}
~ParseScope() {
Exit();
}
};
/// EnterScope - Start a new scope.
void EnterScope(unsigned ScopeFlags);
/// ExitScope - Pop a scope off the scope stack.
void ExitScope();
private:
/// RAII object used to modify the scope flags for the current scope.
class ParseScopeFlags {
Scope *CurScope;
unsigned OldFlags;
ParseScopeFlags(const ParseScopeFlags &) = delete;
void operator=(const ParseScopeFlags &) = delete;
public:
ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
~ParseScopeFlags();
};
//===--------------------------------------------------------------------===//
// Diagnostic Emission and Error recovery.
public:
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
DiagnosticBuilder Diag(unsigned DiagID) {
return Diag(Tok, DiagID);
}
private:
void SuggestParentheses(SourceLocation Loc, unsigned DK,
SourceRange ParenRange);
void CheckNestedObjCContexts(SourceLocation AtLoc);
public:
/// Control flags for SkipUntil functions.
enum SkipUntilFlags {
StopAtSemi = 1 << 0, ///< Stop skipping at semicolon
/// Stop skipping at specified token, but don't skip the token itself
StopBeforeMatch = 1 << 1,
StopAtCodeCompletion = 1 << 2 ///< Stop at code completion
};
friend constexpr SkipUntilFlags operator|(SkipUntilFlags L,
SkipUntilFlags R) {
return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
static_cast<unsigned>(R));
}
/// SkipUntil - Read tokens until we get to the specified token, then consume
/// it (unless StopBeforeMatch is specified). Because we cannot guarantee
/// that the token will ever occur, this skips to the next token, or to some
/// likely good stopping point. If Flags has StopAtSemi flag, skipping will
/// stop at a ';' character.
///
/// If SkipUntil finds the specified token, it returns true, otherwise it
/// returns false.
bool SkipUntil(tok::TokenKind T,
SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
return SkipUntil(llvm::makeArrayRef(T), Flags);
}
bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2,
SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
tok::TokenKind TokArray[] = {T1, T2};
return SkipUntil(TokArray, Flags);
}
bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
tok::TokenKind TokArray[] = {T1, T2, T3};
return SkipUntil(TokArray, Flags);
}
bool SkipUntil(ArrayRef<tok::TokenKind> Toks,
SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
/// SkipMalformedDecl - Read tokens until we get to some likely good stopping
/// point for skipping past a simple-declaration.
void SkipMalformedDecl();
/// The location of the first statement inside an else that might
/// have a missleading indentation. If there is no
/// MisleadingIndentationChecker on an else active, this location is invalid.
SourceLocation MisleadingIndentationElseLoc;
private:
//===--------------------------------------------------------------------===//
// Lexing and parsing of C++ inline methods.
struct ParsingClass;
/// [class.mem]p1: "... the class is regarded as complete within
/// - function bodies
/// - default arguments
/// - exception-specifications (TODO: C++0x)
/// - and brace-or-equal-initializers for non-static data members
/// (including such things in nested classes)."
/// LateParsedDeclarations build the tree of those elements so they can
/// be parsed after parsing the top-level class.
class LateParsedDeclaration {
public:
virtual ~LateParsedDeclaration();
virtual void ParseLexedMethodDeclarations();
virtual void ParseLexedMemberInitializers();
virtual void ParseLexedMethodDefs();
virtual void ParseLexedAttributes();
virtual void ParseLexedPragmas();
};
/// Inner node of the LateParsedDeclaration tree that parses
/// all its members recursively.
class LateParsedClass : public LateParsedDeclaration {
public:
LateParsedClass(Parser *P, ParsingClass *C);
~LateParsedClass() override;
void ParseLexedMethodDeclarations() override;
void ParseLexedMemberInitializers() override;
void ParseLexedMethodDefs() override;
void ParseLexedAttributes() override;
void ParseLexedPragmas() override;
private:
Parser *Self;
ParsingClass *Class;
};
/// Contains the lexed tokens of an attribute with arguments that
/// may reference member variables and so need to be parsed at the
/// end of the class declaration after parsing all other member
/// member declarations.
/// FIXME: Perhaps we should change the name of LateParsedDeclaration to
/// LateParsedTokens.
struct LateParsedAttribute : public LateParsedDeclaration {
Parser *Self;
CachedTokens Toks;
IdentifierInfo &AttrName;
IdentifierInfo *MacroII = nullptr;
SourceLocation AttrNameLoc;
SmallVector<Decl*, 2> Decls;
explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
SourceLocation Loc)
: Self(P), AttrName(Name), AttrNameLoc(Loc) {}
void ParseLexedAttributes() override;
void addDecl(Decl *D) { Decls.push_back(D); }
};
/// Contains the lexed tokens of a pragma with arguments that
/// may reference member variables and so need to be parsed at the
/// end of the class declaration after parsing all other member
/// member declarations.
class LateParsedPragma : public LateParsedDeclaration {
Parser *Self = nullptr;
AccessSpecifier AS = AS_none;
CachedTokens Toks;
public:
explicit LateParsedPragma(Parser *P, AccessSpecifier AS)
: Self(P), AS(AS) {}
void takeToks(CachedTokens &Cached) { Toks.swap(Cached); }
const CachedTokens &toks() const { return Toks; }
AccessSpecifier getAccessSpecifier() const { return AS; }
void ParseLexedPragmas() override;
};
// A list of late-parsed attributes. Used by ParseGNUAttributes.
class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> {
public:
LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { }
bool parseSoon() { return ParseSoon; }
private:
bool ParseSoon; // Are we planning to parse these shortly after creation?
};
/// Contains the lexed tokens of a member function definition
/// which needs to be parsed at the end of the class declaration
/// after parsing all other member declarations.
struct LexedMethod : public LateParsedDeclaration {
Parser *Self;
Decl *D;
CachedTokens Toks;
/// Whether this member function had an associated template
/// scope. When true, D is a template declaration.
/// otherwise, it is a member function declaration.
bool TemplateScope;
explicit LexedMethod(Parser* P, Decl *MD)
: Self(P), D(MD), TemplateScope(false) {}
void ParseLexedMethodDefs() override;
};
/// LateParsedDefaultArgument - Keeps track of a parameter that may
/// have a default argument that cannot be parsed yet because it
/// occurs within a member function declaration inside the class
/// (C++ [class.mem]p2).
struct LateParsedDefaultArgument {
explicit LateParsedDefaultArgument(Decl *P,
std::unique_ptr<CachedTokens> Toks = nullptr)
: Param(P), Toks(std::move(Toks)) { }
/// Param - The parameter declaration for this parameter.
Decl *Param;
/// Toks - The sequence of tokens that comprises the default
/// argument expression, not including the '=' or the terminating
/// ')' or ','. This will be NULL for parameters that have no
/// default argument.
std::unique_ptr<CachedTokens> Toks;
};
/// LateParsedMethodDeclaration - A method declaration inside a class that
/// contains at least one entity whose parsing needs to be delayed
/// until the class itself is completely-defined, such as a default
/// argument (C++ [class.mem]p2).
struct LateParsedMethodDeclaration : public LateParsedDeclaration {
explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
: Self(P), Method(M), TemplateScope(false),
ExceptionSpecTokens(nullptr) {}
void ParseLexedMethodDeclarations() override;
Parser* Self;
/// Method - The method declaration.
Decl *Method;
/// Whether this member function had an associated template
/// scope. When true, D is a template declaration.
/// otherwise, it is a member function declaration.
bool TemplateScope;
/// DefaultArgs - Contains the parameters of the function and
/// their default arguments. At least one of the parameters will
/// have a default argument, but all of the parameters of the
/// method will be stored so that they can be reintroduced into
/// scope at the appropriate times.
SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
/// The set of tokens that make up an exception-specification that
/// has not yet been parsed.
CachedTokens *ExceptionSpecTokens;
};
/// LateParsedMemberInitializer - An initializer for a non-static class data
/// member whose parsing must to be delayed until the class is completely
/// defined (C++11 [class.mem]p2).
struct LateParsedMemberInitializer : public LateParsedDeclaration {
LateParsedMemberInitializer(Parser *P, Decl *FD)
: Self(P), Field(FD) { }
void ParseLexedMemberInitializers() override;
Parser *Self;
/// Field - The field declaration.
Decl *Field;
/// CachedTokens - The sequence of tokens that comprises the initializer,
/// including any leading '='.
CachedTokens Toks;
};
/// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
/// C++ class, its method declarations that contain parts that won't be
/// parsed until after the definition is completed (C++ [class.mem]p2),
/// the method declarations and possibly attached inline definitions
/// will be stored here with the tokens that will be parsed to create those
/// entities.
typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer;
/// Representation of a class that has been parsed, including
/// any member function declarations or definitions that need to be
/// parsed after the corresponding top-level class is complete.
struct ParsingClass {
ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
: TopLevelClass(TopLevelClass), TemplateScope(false),
IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { }
/// Whether this is a "top-level" class, meaning that it is
/// not nested within another class.
bool TopLevelClass : 1;
/// Whether this class had an associated template
/// scope. When true, TagOrTemplate is a template declaration;
/// otherwise, it is a tag declaration.
bool TemplateScope : 1;
/// Whether this class is an __interface.
bool IsInterface : 1;
/// The class or class template whose definition we are parsing.
Decl *TagOrTemplate;
/// LateParsedDeclarations - Method declarations, inline definitions and
/// nested classes that contain pieces whose parsing will be delayed until
/// the top-level class is fully defined.
LateParsedDeclarationsContainer LateParsedDeclarations;
};
/// The stack of classes that is currently being
/// parsed. Nested and local classes will be pushed onto this stack
/// when they are parsed, and removed afterward.
std::stack<ParsingClass *> ClassStack;
ParsingClass &getCurrentClass() {
assert(!ClassStack.empty() && "No lexed method stacks!");
return *ClassStack.top();
}
/// RAII object used to manage the parsing of a class definition.
class ParsingClassDefinition {
Parser &P;
bool Popped;
Sema::ParsingClassState State;
public:
ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
bool IsInterface)
: P(P), Popped(false),
State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
}
/// Pop this class of the stack.
void Pop() {
assert(!Popped && "Nested class has already been popped");
Popped = true;
P.PopParsingClass(State);
}
~ParsingClassDefinition() {
if (!Popped)
P.PopParsingClass(State);
}
};
/// Contains information about any template-specific
/// information that has been parsed prior to parsing declaration
/// specifiers.
struct ParsedTemplateInfo {
ParsedTemplateInfo()
: Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { }
ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
bool isSpecialization,
bool lastParameterListWasEmpty = false)
: Kind(isSpecialization? ExplicitSpecialization : Template),
TemplateParams(TemplateParams),
LastParameterListWasEmpty(lastParameterListWasEmpty) { }
explicit ParsedTemplateInfo(SourceLocation ExternLoc,
SourceLocation TemplateLoc)
: Kind(ExplicitInstantiation), TemplateParams(nullptr),
ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
LastParameterListWasEmpty(false){ }
/// The kind of template we are parsing.
enum {
/// We are not parsing a template at all.
NonTemplate = 0,
/// We are parsing a template declaration.
Template,
/// We are parsing an explicit specialization.
ExplicitSpecialization,
/// We are parsing an explicit instantiation.
ExplicitInstantiation
} Kind;
/// The template parameter lists, for template declarations
/// and explicit specializations.
TemplateParameterLists *TemplateParams;
/// The location of the 'extern' keyword, if any, for an explicit
/// instantiation
SourceLocation ExternLoc;
/// The location of the 'template' keyword, for an explicit
/// instantiation.
SourceLocation TemplateLoc;
/// Whether the last template parameter list was empty.
bool LastParameterListWasEmpty;
SourceRange getSourceRange() const LLVM_READONLY;
};
void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
static void LateTemplateParserCleanupCallback(void *P);
Sema::ParsingClassState
PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
void DeallocateParsedClasses(ParsingClass *Class);
void PopParsingClass(Sema::ParsingClassState);
enum CachedInitKind {
CIK_DefaultArgument,
CIK_DefaultInitializer
};
NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
ParsedAttributes &AccessAttrs,
ParsingDeclarator &D,
const ParsedTemplateInfo &TemplateInfo,
const VirtSpecifiers &VS,
SourceLocation PureSpecLoc);
void ParseCXXNonStaticMemberInitializer(Decl *VarD);
void ParseLexedAttributes(ParsingClass &Class);
void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
bool EnterScope, bool OnDefinition);
void ParseLexedAttribute(LateParsedAttribute &LA,
bool EnterScope, bool OnDefinition);
void ParseLexedMethodDeclarations(ParsingClass &Class);
void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
void ParseLexedMethodDefs(ParsingClass &Class);
void ParseLexedMethodDef(LexedMethod &LM);
void ParseLexedMemberInitializers(ParsingClass &Class);
void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
void ParseLexedPragmas(ParsingClass &Class);
void ParseLexedPragma(LateParsedPragma &LP);
bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK);
bool ConsumeAndStoreConditional(CachedTokens &Toks);
bool ConsumeAndStoreUntil(tok::TokenKind T1,
CachedTokens &Toks,
bool StopAtSemi = true,
bool ConsumeFinalToken = true) {
return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
}
bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
CachedTokens &Toks,
bool StopAtSemi = true,
bool ConsumeFinalToken = true);
//===--------------------------------------------------------------------===//
// C99 6.9: External Definitions.
struct ParsedAttributesWithRange : ParsedAttributes {
ParsedAttributesWithRange(AttributeFactory &factory)
: ParsedAttributes(factory) {}
void clear() {
ParsedAttributes::clear();
Range = SourceRange();
}
SourceRange Range;
};
struct ParsedAttributesViewWithRange : ParsedAttributesView {
ParsedAttributesViewWithRange() : ParsedAttributesView() {}
void clearListOnly() {
ParsedAttributesView::clearListOnly();
Range = SourceRange();
}
SourceRange Range;
};
DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
ParsingDeclSpec *DS = nullptr);
bool isDeclarationAfterDeclarator();
bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
ParsedAttributesWithRange &attrs,
ParsingDeclSpec *DS = nullptr,
AccessSpecifier AS = AS_none);
DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
ParsingDeclSpec &DS,
AccessSpecifier AS);
void SkipFunctionBody();
Decl *ParseFunctionDefinition(ParsingDeclarator &D,
const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
LateParsedAttrList *LateParsedAttrs = nullptr);
void ParseKNRParamDeclarations(Declarator &D);
// EndLoc is filled with the location of the last token of the simple-asm.
ExprResult ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc);
ExprResult ParseAsmStringLiteral(bool ForAsmLabel);
// Objective-C External Declarations
void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
DeclGroupPtrTy ParseObjCAtDirectives(ParsedAttributesWithRange &Attrs);
DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
ParsedAttributes &prefixAttrs);
class ObjCTypeParamListScope;
ObjCTypeParamList *parseObjCTypeParamList();
ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs(
ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
SmallVectorImpl<IdentifierLocPair> &protocolIdents,
SourceLocation &rAngleLoc, bool mayBeProtocolList = true);
void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
BalancedDelimiterTracker &T,
SmallVectorImpl<Decl *> &AllIvarDecls,
bool RBraceMissing);
void ParseObjCClassInstanceVariables(Decl *interfaceDecl,
tok::ObjCKeywordKind visibility,
SourceLocation atLoc);
bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P,
SmallVectorImpl<SourceLocation> &PLocs,
bool WarnOnDeclarations,
bool ForObjCContainer,
SourceLocation &LAngleLoc,
SourceLocation &EndProtoLoc,
bool consumeLastToken);
/// Parse the first angle-bracket-delimited clause for an
/// Objective-C object or object pointer type, which may be either
/// type arguments or protocol qualifiers.
void parseObjCTypeArgsOrProtocolQualifiers(
ParsedType baseType,
SourceLocation &typeArgsLAngleLoc,
SmallVectorImpl<ParsedType> &typeArgs,
SourceLocation &typeArgsRAngleLoc,
SourceLocation &protocolLAngleLoc,
SmallVectorImpl<Decl *> &protocols,
SmallVectorImpl<SourceLocation> &protocolLocs,
SourceLocation &protocolRAngleLoc,
bool consumeLastToken,
bool warnOnIncompleteProtocols);
/// Parse either Objective-C type arguments or protocol qualifiers; if the
/// former, also parse protocol qualifiers afterward.
void parseObjCTypeArgsAndProtocolQualifiers(
ParsedType baseType,
SourceLocation &typeArgsLAngleLoc,
SmallVectorImpl<ParsedType> &typeArgs,
SourceLocation &typeArgsRAngleLoc,
SourceLocation &protocolLAngleLoc,
SmallVectorImpl<Decl *> &protocols,
SmallVectorImpl<SourceLocation> &protocolLocs,
SourceLocation &protocolRAngleLoc,
bool consumeLastToken);
/// Parse a protocol qualifier type such as '<NSCopying>', which is
/// an anachronistic way of writing 'id<NSCopying>'.
TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc);
/// Parse Objective-C type arguments and protocol qualifiers, extending the
/// current type with the parsed result.
TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc,
ParsedType type,
bool consumeLastToken,
SourceLocation &endLoc);
void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
Decl *CDecl);
DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
ParsedAttributes &prefixAttrs);
struct ObjCImplParsingDataRAII {
Parser &P;
Decl *Dcl;
bool HasCFunction;
typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
LateParsedObjCMethodContainer LateParsedObjCMethods;
ObjCImplParsingDataRAII(Parser &parser, Decl *D)
: P(parser), Dcl(D), HasCFunction(false) {
P.CurParsedObjCImpl = this;
Finished = false;
}
~ObjCImplParsingDataRAII();
void finish(SourceRange AtEnd);
bool isFinished() const { return Finished; }
private:
bool Finished;
};
ObjCImplParsingDataRAII *CurParsedObjCImpl;
void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc,
ParsedAttributes &Attrs);
DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
// Definitions for Objective-c context sensitive keywords recognition.
enum ObjCTypeQual {
objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
objc_nonnull, objc_nullable, objc_null_unspecified,
objc_NumQuals
};
IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
bool isTokIdentifier_in() const;
ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx,
ParsedAttributes *ParamAttrs);
void ParseObjCMethodRequirement();
Decl *ParseObjCMethodPrototype(
tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
bool MethodDefinition = true);
Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
bool MethodDefinition=true);
void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
Decl *ParseObjCMethodDefinition();
public:
//===--------------------------------------------------------------------===//
// C99 6.5: Expressions.
/// TypeCastState - State whether an expression is or may be a type cast.
enum TypeCastState {
NotTypeCast = 0,
MaybeTypeCast,
IsTypeCast
};
ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast);
ExprResult ParseConstantExpressionInExprEvalContext(
TypeCastState isTypeCast = NotTypeCast);
ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast);
ExprResult ParseCaseExpression(SourceLocation CaseLoc);
ExprResult ParseConstraintExpression();
ExprResult
ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause);
ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause);
// Expr that doesn't include commas.
ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast);
ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
unsigned &NumLineToksConsumed,
bool IsUnevaluated);
private:
ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
prec::Level MinPrec);
/// Control what ParseCastExpression will parse.
enum CastParseKind {
AnyCastExpr = 0,
UnaryExprOnly,
PrimaryExprOnly
};
ExprResult ParseCastExpression(CastParseKind ParseKind,
bool isAddressOfOperand,
bool &NotCastExpr,
TypeCastState isTypeCast,
bool isVectorLiteral = false,
bool *NotPrimaryExpression = nullptr);
ExprResult ParseCastExpression(CastParseKind ParseKind,
bool isAddressOfOperand = false,
TypeCastState isTypeCast = NotTypeCast,
bool isVectorLiteral = false,
bool *NotPrimaryExpression = nullptr);
/// Returns true if the next token cannot start an expression.
bool isNotExpressionStart();
/// Returns true if the next token would start a postfix-expression
/// suffix.
bool isPostfixExpressionSuffixStart() {
tok::TokenKind K = Tok.getKind();
return (K == tok::l_square || K == tok::l_paren ||
K == tok::period || K == tok::arrow ||
K == tok::plusplus || K == tok::minusminus);
}
bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less);
void checkPotentialAngleBracket(ExprResult &PotentialTemplateName);
bool checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc &,
const Token &OpToken);
bool checkPotentialAngleBracketDelimiter(const Token &OpToken) {
if (auto *Info = AngleBrackets.getCurrent(*this))
return checkPotentialAngleBracketDelimiter(*Info, OpToken);
return false;
}
ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
ExprResult ParseUnaryExprOrTypeTraitExpression();
ExprResult ParseBuiltinPrimaryExpression();
ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
bool &isCastExpr,
ParsedType &CastTy,
SourceRange &CastRange);
typedef SmallVector<Expr*, 20> ExprListTy;
typedef SmallVector<SourceLocation, 20> CommaLocsTy;
/// ParseExpressionList - Used for C/C++ (argument-)expression-list.
bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
SmallVectorImpl<SourceLocation> &CommaLocs,
llvm::function_ref<void()> ExpressionStarts =
llvm::function_ref<void()>());
/// ParseSimpleExpressionList - A simple comma-separated list of expressions,
/// used for misc language extensions.
bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
SmallVectorImpl<SourceLocation> &CommaLocs);
/// ParenParseOption - Control what ParseParenExpression will parse.
enum ParenParseOption {
SimpleExpr, // Only parse '(' expression ')'
FoldExpr, // Also allow fold-expression <anything>
CompoundStmt, // Also allow '(' compound-statement ')'
CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
CastExpr // Also allow '(' type-name ')' <anything>
};
ExprResult ParseParenExpression(ParenParseOption &ExprType,
bool stopIfCastExpr,
bool isTypeCast,
ParsedType &CastTy,
SourceLocation &RParenLoc);
ExprResult ParseCXXAmbiguousParenExpression(
ParenParseOption &ExprType, ParsedType &CastTy,
BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt);
ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
SourceLocation LParenLoc,
SourceLocation RParenLoc);
ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
ExprResult ParseGenericSelectionExpression();
ExprResult ParseObjCBoolLiteral();
ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T);
//===--------------------------------------------------------------------===//
// C++ Expressions
ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
Token &Replacement);
ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
bool areTokensAdjacent(const Token &A, const Token &B);
void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
bool EnteringContext, IdentifierInfo &II,
CXXScopeSpec &SS);
bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, ParsedType ObjectType,
bool EnteringContext,
bool *MayBePseudoDestructor = nullptr,
bool IsTypename = false,
IdentifierInfo **LastII = nullptr,
bool OnlyNamespace = false,
bool InUsingDeclaration = false);
//===--------------------------------------------------------------------===//
// C++11 5.1.2: Lambda expressions
/// Result of tentatively parsing a lambda-introducer.
enum class LambdaIntroducerTentativeParse {
/// This appears to be a lambda-introducer, which has been fully parsed.
Success,
/// This is a lambda-introducer, but has not been fully parsed, and this
/// function needs to be called again to parse it.
Incomplete,
/// This is definitely an Objective-C message send expression, rather than
/// a lambda-introducer, attribute-specifier, or array designator.
MessageSend,
/// This is not a lambda-introducer.
Invalid,
};
// [...] () -> type {...}
ExprResult ParseLambdaExpression();
ExprResult TryParseLambdaExpression();
bool
ParseLambdaIntroducer(LambdaIntroducer &Intro,
LambdaIntroducerTentativeParse *Tentative = nullptr);
ExprResult ParseLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro);
//===--------------------------------------------------------------------===//
// C++ 5.2p1: C++ Casts
ExprResult ParseCXXCasts();
/// Parse a __builtin_bit_cast(T, E), used to implement C++2a std::bit_cast.
ExprResult ParseBuiltinBitCast();
//===--------------------------------------------------------------------===//
// C++ 5.2p1: C++ Type Identification
ExprResult ParseCXXTypeid();
//===--------------------------------------------------------------------===//
// C++ : Microsoft __uuidof Expression
ExprResult ParseCXXUuidof();
//===--------------------------------------------------------------------===//
// C++ 5.2.4: C++ Pseudo-Destructor Expressions
ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
tok::TokenKind OpKind,
CXXScopeSpec &SS,
ParsedType ObjectType);
//===--------------------------------------------------------------------===//
// C++ 9.3.2: C++ 'this' pointer
ExprResult ParseCXXThis();
//===--------------------------------------------------------------------===//
// C++ 15: C++ Throw Expression
ExprResult ParseThrowExpression();
ExceptionSpecificationType tryParseExceptionSpecification(
bool Delayed,
SourceRange &SpecificationRange,
SmallVectorImpl<ParsedType> &DynamicExceptions,
SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
ExprResult &NoexceptExpr,
CachedTokens *&ExceptionSpecTokens);
// EndLoc is filled with the location of the last token of the specification.
ExceptionSpecificationType ParseDynamicExceptionSpecification(
SourceRange &SpecificationRange,
SmallVectorImpl<ParsedType> &Exceptions,
SmallVectorImpl<SourceRange> &Ranges);
//===--------------------------------------------------------------------===//
// C++0x 8: Function declaration trailing-return-type
TypeResult ParseTrailingReturnType(SourceRange &Range,
bool MayBeFollowedByDirectInit);
//===--------------------------------------------------------------------===//
// C++ 2.13.5: C++ Boolean Literals
ExprResult ParseCXXBoolLiteral();
//===--------------------------------------------------------------------===//
// C++ 5.2.3: Explicit type conversion (functional notation)
ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
/// This should only be called when the current token is known to be part of
/// simple-type-specifier.
void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
//===--------------------------------------------------------------------===//
// C++ 5.3.4 and 5.3.5: C++ new and delete
bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
Declarator &D);
void ParseDirectNewDeclarator(Declarator &D);
ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
ExprResult ParseCXXDeleteExpression(bool UseGlobal,
SourceLocation Start);
//===--------------------------------------------------------------------===//
// C++ if/switch/while/for condition expression.
struct ForRangeInfo;
Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt,
SourceLocation Loc,
Sema::ConditionKind CK,
ForRangeInfo *FRI = nullptr);
//===--------------------------------------------------------------------===//
// C++ Coroutines
ExprResult ParseCoyieldExpression();
//===--------------------------------------------------------------------===//
// C++ Concepts
ExprResult ParseRequiresExpression();
void ParseTrailingRequiresClause(Declarator &D);
//===--------------------------------------------------------------------===//
// C99 6.7.8: Initialization.
/// ParseInitializer
/// initializer: [C99 6.7.8]
/// assignment-expression
/// '{' ...
ExprResult ParseInitializer() {
if (Tok.isNot(tok::l_brace))
return ParseAssignmentExpression();
return ParseBraceInitializer();
}
bool MayBeDesignationStart();
ExprResult ParseBraceInitializer();
ExprResult ParseInitializerWithPotentialDesignator(
llvm::function_ref<void(const Designation &)> CodeCompleteCB);
//===--------------------------------------------------------------------===//
// clang Expressions
ExprResult ParseBlockLiteralExpression(); // ^{...}
//===--------------------------------------------------------------------===//
// Objective-C Expressions
ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
bool isSimpleObjCMessageExpression();
ExprResult ParseObjCMessageExpression();
ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
SourceLocation SuperLoc,
ParsedType ReceiverType,
Expr *ReceiverExpr);
ExprResult ParseAssignmentExprWithObjCMessageExprStart(
SourceLocation LBracloc, SourceLocation SuperLoc,
ParsedType ReceiverType, Expr *ReceiverExpr);
bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
//===--------------------------------------------------------------------===//
// C99 6.8: Statements and Blocks.
/// A SmallVector of statements, with stack size 32 (as that is the only one
/// used.)
typedef SmallVector<Stmt*, 32> StmtVector;
/// A SmallVector of expressions, with stack size 12 (the maximum used.)
typedef SmallVector<Expr*, 12> ExprVector;
/// A SmallVector of types.
typedef SmallVector<ParsedType, 12> TypeVector;
StmtResult
ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
ParsedStmtContext StmtCtx = ParsedStmtContext::SubStmt);
StmtResult ParseStatementOrDeclaration(
StmtVector &Stmts, ParsedStmtContext StmtCtx,
SourceLocation *TrailingElseLoc = nullptr);
StmtResult ParseStatementOrDeclarationAfterAttributes(
StmtVector &Stmts,
ParsedStmtContext StmtCtx,
SourceLocation *TrailingElseLoc,
ParsedAttributesWithRange &Attrs);
StmtResult ParseExprStatement(ParsedStmtContext StmtCtx);
StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs,
ParsedStmtContext StmtCtx);
StmtResult ParseCaseStatement(ParsedStmtContext StmtCtx,
bool MissingCase = false,
ExprResult Expr = ExprResult());
StmtResult ParseDefaultStatement(ParsedStmtContext StmtCtx);
StmtResult ParseCompoundStatement(bool isStmtExpr = false);
StmtResult ParseCompoundStatement(bool isStmtExpr,
unsigned ScopeFlags);
void ParseCompoundStatementLeadingPragmas();
bool ConsumeNullStmt(StmtVector &Stmts);
StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
bool ParseParenExprOrCondition(StmtResult *InitStmt,
Sema::ConditionResult &CondResult,
SourceLocation Loc,
Sema::ConditionKind CK);
StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
StmtResult ParseDoStatement();
StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
StmtResult ParseGotoStatement();
StmtResult ParseContinueStatement();
StmtResult ParseBreakStatement();
StmtResult ParseReturnStatement();
StmtResult ParseAsmStatement(bool &msAsm);
StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
StmtResult ParsePragmaLoopHint(StmtVector &Stmts,
ParsedStmtContext StmtCtx,
SourceLocation *TrailingElseLoc,
ParsedAttributesWithRange &Attrs);
/// Describes the behavior that should be taken for an __if_exists
/// block.
enum IfExistsBehavior {
/// Parse the block; this code is always used.
IEB_Parse,
/// Skip the block entirely; this code is never used.
IEB_Skip,
/// Parse the block as a dependent block, which may be used in
/// some template instantiations but not others.
IEB_Dependent
};
/// Describes the condition of a Microsoft __if_exists or
/// __if_not_exists block.
struct IfExistsCondition {
/// The location of the initial keyword.
SourceLocation KeywordLoc;
/// Whether this is an __if_exists block (rather than an
/// __if_not_exists block).
bool IsIfExists;
/// Nested-name-specifier preceding the name.
CXXScopeSpec SS;
/// The name we're looking for.
UnqualifiedId Name;
/// The behavior of this __if_exists or __if_not_exists block
/// should.
IfExistsBehavior Behavior;
};
bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
void ParseMicrosoftIfExistsExternalDeclaration();
void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
ParsedAttributes &AccessAttrs,
AccessSpecifier &CurAS);
bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
bool &InitExprsOk);
bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
SmallVectorImpl<Expr *> &Constraints,
SmallVectorImpl<Expr *> &Exprs);
//===--------------------------------------------------------------------===//
// C++ 6: Statements and Blocks
StmtResult ParseCXXTryBlock();
StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
StmtResult ParseCXXCatchBlock(bool FnCatch = false);
//===--------------------------------------------------------------------===//
// MS: SEH Statements and Blocks
StmtResult ParseSEHTryBlock();
StmtResult ParseSEHExceptBlock(SourceLocation Loc);
StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
StmtResult ParseSEHLeaveStatement();
//===--------------------------------------------------------------------===//
// Objective-C Statements
StmtResult ParseObjCAtStatement(SourceLocation atLoc,
ParsedStmtContext StmtCtx);
StmtResult ParseObjCTryStmt(SourceLocation atLoc);
StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
//===--------------------------------------------------------------------===//
// C99 6.7: Declarations.
/// A context for parsing declaration specifiers. TODO: flesh this
/// out, there are other significant restrictions on specifiers than
/// would be best implemented in the parser.
enum class DeclSpecContext {
DSC_normal, // normal context
DSC_class, // class context, enables 'friend'
DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
DSC_top_level, // top-level/namespace declaration context
DSC_template_param, // template parameter context
DSC_template_type_arg, // template type argument context
DSC_objc_method_result, // ObjC method result context, enables 'instancetype'
DSC_condition // condition declaration context
};
/// Is this a context in which we are parsing just a type-specifier (or
/// trailing-type-specifier)?
static bool isTypeSpecifier(DeclSpecContext DSC) {
switch (DSC) {
case DeclSpecContext::DSC_normal:
case DeclSpecContext::DSC_template_param:
case DeclSpecContext::DSC_class:
case DeclSpecContext::DSC_top_level:
case DeclSpecContext::DSC_objc_method_result:
case DeclSpecContext::DSC_condition:
return false;
case DeclSpecContext::DSC_template_type_arg:
case DeclSpecContext::DSC_type_specifier:
case DeclSpecContext::DSC_trailing:
case DeclSpecContext::DSC_alias_declaration:
return true;
}
llvm_unreachable("Missing DeclSpecContext case");
}
/// Is this a context in which we can perform class template argument
/// deduction?
static bool isClassTemplateDeductionContext(DeclSpecContext DSC) {
switch (DSC) {
case DeclSpecContext::DSC_normal:
case DeclSpecContext::DSC_template_param:
case DeclSpecContext::DSC_class:
case DeclSpecContext::DSC_top_level:
case DeclSpecContext::DSC_condition:
case DeclSpecContext::DSC_type_specifier:
return true;
case DeclSpecContext::DSC_objc_method_result:
case DeclSpecContext::DSC_template_type_arg:
case DeclSpecContext::DSC_trailing:
case DeclSpecContext::DSC_alias_declaration:
return false;
}
llvm_unreachable("Missing DeclSpecContext case");
}
/// Information on a C++0x for-range-initializer found while parsing a
/// declaration which turns out to be a for-range-declaration.
struct ForRangeInit {
SourceLocation ColonLoc;
ExprResult RangeExpr;
bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
};
struct ForRangeInfo : ForRangeInit {
StmtResult LoopVar;
};
DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context,
SourceLocation &DeclEnd,
ParsedAttributesWithRange &attrs,
SourceLocation *DeclSpecStart = nullptr);
DeclGroupPtrTy
ParseSimpleDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd,
ParsedAttributesWithRange &attrs, bool RequireSemi,
ForRangeInit *FRI = nullptr,
SourceLocation *DeclSpecStart = nullptr);
bool MightBeDeclarator(DeclaratorContext Context);
DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context,
SourceLocation *DeclEnd = nullptr,
ForRangeInit *FRI = nullptr);
Decl *ParseDeclarationAfterDeclarator(Declarator &D,
const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
bool ParseAsmAttributesAfterDeclarator(Declarator &D);
Decl *ParseDeclarationAfterDeclaratorAndAttributes(
Declarator &D,
const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
ForRangeInit *FRI = nullptr);
Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
/// When in code-completion, skip parsing of the function/method body
/// unless the body contains the code-completion point.
///
/// \returns true if the function body was skipped.
bool trySkippingFunctionBody();
bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
const ParsedTemplateInfo &TemplateInfo,
AccessSpecifier AS, DeclSpecContext DSC,
ParsedAttributesWithRange &Attrs);
DeclSpecContext
getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context);
void ParseDeclarationSpecifiers(
DeclSpec &DS,
const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
AccessSpecifier AS = AS_none,
DeclSpecContext DSC = DeclSpecContext::DSC_normal,
LateParsedAttrList *LateAttrs = nullptr);
bool DiagnoseMissingSemiAfterTagDefinition(
DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext,
LateParsedAttrList *LateAttrs = nullptr);
void ParseSpecifierQualifierList(
DeclSpec &DS, AccessSpecifier AS = AS_none,
DeclSpecContext DSC = DeclSpecContext::DSC_normal);
void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
DeclaratorContext Context);
void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
const ParsedTemplateInfo &TemplateInfo,
AccessSpecifier AS, DeclSpecContext DSC);
void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
void ParseStructUnionBody(SourceLocation StartLoc, DeclSpec::TST TagType,
Decl *TagDecl);
void ParseStructDeclaration(
ParsingDeclSpec &DS,
llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback);
bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
bool isTypeSpecifierQualifier();
/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
/// is definitely a type-specifier. Return false if it isn't part of a type
/// specifier or if we're not sure.
bool isKnownToBeTypeSpecifier(const Token &Tok) const;
/// Return true if we know that we are definitely looking at a
/// decl-specifier, and isn't part of an expression such as a function-style
/// cast. Return false if it's no a decl-specifier, or we're not sure.
bool isKnownToBeDeclarationSpecifier() {
if (getLangOpts().CPlusPlus)
return isCXXDeclarationSpecifier() == TPResult::True;
return isDeclarationSpecifier(true);
}
/// isDeclarationStatement - Disambiguates between a declaration or an
/// expression statement, when parsing function bodies.
/// Returns true for declaration, false for expression.
bool isDeclarationStatement() {
if (getLangOpts().CPlusPlus)
return isCXXDeclarationStatement();
return isDeclarationSpecifier(true);
}
/// isForInitDeclaration - Disambiguates between a declaration or an
/// expression in the context of the C 'clause-1' or the C++
// 'for-init-statement' part of a 'for' statement.
/// Returns true for declaration, false for expression.
bool isForInitDeclaration() {
if (getLangOpts().OpenMP)
Actions.startOpenMPLoop();
if (getLangOpts().CPlusPlus)
return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
return isDeclarationSpecifier(true);
}
/// Determine whether this is a C++1z for-range-identifier.
bool isForRangeIdentifier();
/// Determine whether we are currently at the start of an Objective-C
/// class message that appears to be missing the open bracket '['.
bool isStartOfObjCClassMessageMissingOpenBracket();
/// Starting with a scope specifier, identifier, or
/// template-id that refers to the current class, determine whether
/// this is a constructor declarator.
bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false);
/// Specifies the context in which type-id/expression
/// disambiguation will occur.
enum TentativeCXXTypeIdContext {
TypeIdInParens,
TypeIdUnambiguous,
TypeIdAsTemplateArgument
};
/// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
/// whether the parens contain an expression or a type-id.
/// Returns true for a type-id and false for an expression.
bool isTypeIdInParens(bool &isAmbiguous) {
if (getLangOpts().CPlusPlus)
return isCXXTypeId(TypeIdInParens, isAmbiguous);
isAmbiguous = false;
return isTypeSpecifierQualifier();
}
bool isTypeIdInParens() {
bool isAmbiguous;
return isTypeIdInParens(isAmbiguous);
}
/// Checks if the current tokens form type-id or expression.
/// It is similar to isTypeIdInParens but does not suppose that type-id
/// is in parenthesis.
bool isTypeIdUnambiguously() {
bool IsAmbiguous;
if (getLangOpts().CPlusPlus)
return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous);
return isTypeSpecifierQualifier();
}
/// isCXXDeclarationStatement - C++-specialized function that disambiguates
/// between a declaration or an expression statement, when parsing function
/// bodies. Returns true for declaration, false for expression.
bool isCXXDeclarationStatement();
/// isCXXSimpleDeclaration - C++-specialized function that disambiguates
/// between a simple-declaration or an expression-statement.
/// If during the disambiguation process a parsing error is encountered,
/// the function returns true to let the declaration parsing code handle it.
/// Returns false if the statement is disambiguated as expression.
bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
/// isCXXFunctionDeclarator - Disambiguates between a function declarator or
/// a constructor-style initializer, when parsing declaration statements.
/// Returns true for function declarator and false for constructor-style
/// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
/// might be a constructor-style initializer.
/// If during the disambiguation process a parsing error is encountered,
/// the function returns true to let the declaration parsing code handle it.
bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr);
struct ConditionDeclarationOrInitStatementState;
enum class ConditionOrInitStatement {
Expression, ///< Disambiguated as an expression (either kind).
ConditionDecl, ///< Disambiguated as the declaration form of condition.
InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement.
ForRangeDecl, ///< Disambiguated as a for-range declaration.
Error ///< Can't be any of the above!
};
/// Disambiguates between the different kinds of things that can happen
/// after 'if (' or 'switch ('. This could be one of two different kinds of
/// declaration (depending on whether there is a ';' later) or an expression.
ConditionOrInitStatement
isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt,
bool CanBeForRangeDecl);
bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
bool isAmbiguous;
return isCXXTypeId(Context, isAmbiguous);
}
/// TPResult - Used as the result value for functions whose purpose is to
/// disambiguate C++ constructs by "tentatively parsing" them.
enum class TPResult {
True, False, Ambiguous, Error
};
/// Based only on the given token kind, determine whether we know that
/// we're at the start of an expression or a type-specifier-seq (which may
/// be an expression, in C++).
///
/// This routine does not attempt to resolve any of the trick cases, e.g.,
/// those involving lookup of identifiers.
///
/// \returns \c TPR_true if this token starts an expression, \c TPR_false if
/// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
/// tell.
TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
/// isCXXDeclarationSpecifier - Returns TPResult::True if it is a
/// declaration specifier, TPResult::False if it is not,
/// TPResult::Ambiguous if it could be either a decl-specifier or a
/// function-style cast, and TPResult::Error if a parsing error was
/// encountered. If it could be a braced C++11 function-style cast, returns
/// BracedCastResult.
/// Doesn't consume tokens.
TPResult
isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False,
bool *InvalidAsDeclSpec = nullptr);
/// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
/// \c TPResult::Ambiguous, determine whether the decl-specifier would be
/// a type-specifier other than a cv-qualifier.
bool isCXXDeclarationSpecifierAType();
/// Determine whether the current token sequence might be
/// '<' template-argument-list '>'
/// rather than a less-than expression.
TPResult isTemplateArgumentList(unsigned TokensToSkip);
/// Determine whether an '(' after an 'explicit' keyword is part of a C++20
/// 'explicit(bool)' declaration, in earlier language modes where that is an
/// extension.
TPResult isExplicitBool();
/// Determine whether an identifier has been tentatively declared as a
/// non-type. Such tentative declarations should not be found to name a type
/// during a tentative parse, but also should not be annotated as a non-type.
bool isTentativelyDeclared(IdentifierInfo *II);
// "Tentative parsing" functions, used for disambiguation. If a parsing error
// is encountered they will return TPResult::Error.
// Returning TPResult::True/False indicates that the ambiguity was
// resolved and tentative parsing may stop. TPResult::Ambiguous indicates
// that more tentative parsing is necessary for disambiguation.
// They all consume tokens, so backtracking should be used after calling them.
TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
TPResult TryParseTypeofSpecifier();
TPResult TryParseProtocolQualifiers();
TPResult TryParsePtrOperatorSeq();
TPResult TryParseOperatorId();
TPResult TryParseInitDeclaratorList();
TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true,
bool mayHaveDirectInit = false);
TPResult
TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr,
bool VersusTemplateArg = false);
TPResult TryParseFunctionDeclarator();
TPResult TryParseBracketDeclarator();
TPResult TryConsumeDeclarationSpecifier();
public:
TypeResult ParseTypeName(SourceRange *Range = nullptr,
DeclaratorContext Context
= DeclaratorContext::TypeNameContext,
AccessSpecifier AS = AS_none,
Decl **OwnedType = nullptr,
ParsedAttributes *Attrs = nullptr);
private:
void ParseBlockId(SourceLocation CaretLoc);
/// Are [[]] attributes enabled?
bool standardAttributesAllowed() const {
const LangOptions &LO = getLangOpts();
return LO.DoubleSquareBracketAttributes;
}
// Check for the start of an attribute-specifier-seq in a context where an
// attribute is not allowed.
bool CheckProhibitedCXX11Attribute() {
assert(Tok.is(tok::l_square));
if (!standardAttributesAllowed() || NextToken().isNot(tok::l_square))
return false;
return DiagnoseProhibitedCXX11Attribute();
}
bool DiagnoseProhibitedCXX11Attribute();
void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
SourceLocation CorrectLocation) {
if (!standardAttributesAllowed())
return;
if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
Tok.isNot(tok::kw_alignas))
return;
DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
}
void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
SourceLocation CorrectLocation);
void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
DeclSpec &DS, Sema::TagUseKind TUK);
// FixItLoc = possible correct location for the attributes
void ProhibitAttributes(ParsedAttributesWithRange &Attrs,
SourceLocation FixItLoc = SourceLocation()) {
if (Attrs.Range.isInvalid())
return;
DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc);
Attrs.clear();
}
void ProhibitAttributes(ParsedAttributesViewWithRange &Attrs,
SourceLocation FixItLoc = SourceLocation()) {
if (Attrs.Range.isInvalid())
return;
DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc);
Attrs.clearListOnly();
}
void DiagnoseProhibitedAttributes(const SourceRange &Range,
SourceLocation FixItLoc);
// Forbid C++11 and C2x attributes that appear on certain syntactic locations
// which standard permits but we don't supported yet, for example, attributes
// appertain to decl specifiers.
void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
unsigned DiagID);
/// Skip C++11 and C2x attributes and return the end location of the
/// last one.
/// \returns SourceLocation() if there are no attributes.
SourceLocation SkipCXX11Attributes();
/// Diagnose and skip C++11 and C2x attributes that appear in syntactic
/// locations where attributes are not allowed.
void DiagnoseAndSkipCXX11Attributes();
/// Parses syntax-generic attribute arguments for attributes which are
/// known to the implementation, and adds them to the given ParsedAttributes
/// list with the given attribute syntax. Returns the number of arguments
/// parsed for the attribute.
unsigned
ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc,
IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
void MaybeParseGNUAttributes(Declarator &D,
LateParsedAttrList *LateAttrs = nullptr) {
if (Tok.is(tok::kw___attribute)) {
ParsedAttributes attrs(AttrFactory);
SourceLocation endLoc;
ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D);
D.takeAttributes(attrs, endLoc);
}
}
void MaybeParseGNUAttributes(ParsedAttributes &attrs,
SourceLocation *endLoc = nullptr,
LateParsedAttrList *LateAttrs = nullptr) {
if (Tok.is(tok::kw___attribute))
ParseGNUAttributes(attrs, endLoc, LateAttrs);
}
void ParseGNUAttributes(ParsedAttributes &attrs,
SourceLocation *endLoc = nullptr,
LateParsedAttrList *LateAttrs = nullptr,
Declarator *D = nullptr);
void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc,
IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax, Declarator *D);
IdentifierLoc *ParseIdentifierLoc();
unsigned
ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc,
IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
void MaybeParseCXX11Attributes(Declarator &D) {
if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
ParsedAttributesWithRange attrs(AttrFactory);
SourceLocation endLoc;
ParseCXX11Attributes(attrs, &endLoc);
D.takeAttributes(attrs, endLoc);
}
}
void MaybeParseCXX11Attributes(ParsedAttributes &attrs,
SourceLocation *endLoc = nullptr) {
if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
ParsedAttributesWithRange attrsWithRange(AttrFactory);
ParseCXX11Attributes(attrsWithRange, endLoc);
attrs.takeAllFrom(attrsWithRange);
}
}
void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs,
SourceLocation *endLoc = nullptr,
bool OuterMightBeMessageSend = false) {
if (standardAttributesAllowed() &&
isCXX11AttributeSpecifier(false, OuterMightBeMessageSend))
ParseCXX11Attributes(attrs, endLoc);
}
void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
SourceLocation *EndLoc = nullptr);
void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
SourceLocation *EndLoc = nullptr);
/// Parses a C++11 (or C2x)-style attribute argument list. Returns true
/// if this results in adding an attribute to the ParsedAttributes list.
bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc);
IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
SourceLocation *endLoc = nullptr) {
if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
ParseMicrosoftAttributes(attrs, endLoc);
}
void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs);
void ParseMicrosoftAttributes(ParsedAttributes &attrs,
SourceLocation *endLoc = nullptr);
void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
SourceLocation *End = nullptr) {
const auto &LO = getLangOpts();
if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec))
ParseMicrosoftDeclSpecs(Attrs, End);
}
void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
SourceLocation *End = nullptr);
bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs);
void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
SourceLocation SkipExtendedMicrosoftTypeAttributes();
void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
/// Parses opencl_unroll_hint attribute if language is OpenCL v2.0
/// or higher.
/// \return false if error happens.
bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
if (getLangOpts().OpenCL)
return ParseOpenCLUnrollHintAttribute(Attrs);
return true;
}
/// Parses opencl_unroll_hint attribute.
/// \return false if error happens.
bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs);
void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
VersionTuple ParseVersionTuple(SourceRange &Range);
void ParseAvailabilityAttribute(IdentifierInfo &Availability,
SourceLocation AvailabilityLoc,
ParsedAttributes &attrs,
SourceLocation *endLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
Optional<AvailabilitySpec> ParseAvailabilitySpec();
ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol,
SourceLocation Loc,
ParsedAttributes &Attrs,
SourceLocation *EndLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
SourceLocation ObjCBridgeRelatedLoc,
ParsedAttributes &attrs,
SourceLocation *endLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs,
SourceLocation *EndLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
void ParseSwiftNewtypeAttribute(IdentifierInfo &SwiftNewtype,
SourceLocation SwiftNewtypeLoc,
ParsedAttributes &attrs,
SourceLocation *endLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
void
ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
SourceLocation AttrNameLoc, ParsedAttributes &Attrs,
SourceLocation *EndLoc, IdentifierInfo *ScopeName,
SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax);
void ParseTypeofSpecifier(DeclSpec &DS);
SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
SourceLocation StartLoc,
SourceLocation EndLoc);
void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
void ParseAtomicSpecifier(DeclSpec &DS);
ExprResult ParseAlignArgument(SourceLocation Start,
SourceLocation &EllipsisLoc);
void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
SourceLocation *endLoc = nullptr);
void ParsePtrauthQualifier(ParsedAttributes &Attrs);
VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
return isCXX11VirtSpecifier(Tok);
}
void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
SourceLocation FriendLoc);
bool isCXX11FinalKeyword() const;
/// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
/// enter a new C++ declarator scope and exit it when the function is
/// finished.
class DeclaratorScopeObj {
Parser &P;
CXXScopeSpec &SS;
bool EnteredScope;
bool CreatedScope;
public:
DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
: P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
void EnterDeclaratorScope() {
assert(!EnteredScope && "Already entered the scope!");
assert(SS.isSet() && "C++ scope was not set!");
CreatedScope = true;
P.EnterScope(0); // Not a decl scope.
if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
EnteredScope = true;
}
~DeclaratorScopeObj() {
if (EnteredScope) {
assert(SS.isSet() && "C++ scope was cleared ?");
P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
}
if (CreatedScope)
P.ExitScope();
}
};
/// ParseDeclarator - Parse and verify a newly-initialized declarator.
void ParseDeclarator(Declarator &D);
/// A function that parses a variant of direct-declarator.
typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
void ParseDeclaratorInternal(Declarator &D,
DirectDeclParseFunction DirectDeclParser);
enum AttrRequirements {
AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
AR_GNUAttributesParsed = 1 << 1,
AR_CXX11AttributesParsed = 1 << 2,
AR_DeclspecAttributesParsed = 1 << 3,
AR_AllAttributesParsed = AR_GNUAttributesParsed |
AR_CXX11AttributesParsed |
AR_DeclspecAttributesParsed,
AR_VendorAttributesParsed = AR_GNUAttributesParsed |
AR_DeclspecAttributesParsed
};
void ParseTypeQualifierListOpt(
DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed,
bool AtomicAllowed = true, bool IdentifierRequired = false,
Optional<llvm::function_ref<void()>> CodeCompletionHandler = None);
void ParseDirectDeclarator(Declarator &D);
void ParseDecompositionDeclarator(Declarator &D);
void ParseParenDeclarator(Declarator &D);
void ParseFunctionDeclarator(Declarator &D,
ParsedAttributes &attrs,
BalancedDelimiterTracker &Tracker,
bool IsAmbiguous,
bool RequiresArg = false);
void InitCXXThisScopeForDeclaratorIfRelevant(
const Declarator &D, const DeclSpec &DS,
llvm::Optional<Sema::CXXThisScopeRAII> &ThisScope);
bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
SourceLocation &RefQualifierLoc);
bool isFunctionDeclaratorIdentifierList();
void ParseFunctionDeclaratorIdentifierList(
Declarator &D,
SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
void ParseParameterDeclarationClause(
DeclaratorContext DeclaratorContext,
ParsedAttributes &attrs,
SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
SourceLocation &EllipsisLoc);
void ParseBracketDeclarator(Declarator &D);
void ParseMisplacedBracketDeclarator(Declarator &D);
//===--------------------------------------------------------------------===//
// C++ 7: Declarations [dcl.dcl]
/// The kind of attribute specifier we have found.
enum CXX11AttributeKind {
/// This is not an attribute specifier.
CAK_NotAttributeSpecifier,
/// This should be treated as an attribute-specifier.
CAK_AttributeSpecifier,
/// The next tokens are '[[', but this is not an attribute-specifier. This
/// is ill-formed by C++11 [dcl.attr.grammar]p6.
CAK_InvalidAttributeSpecifier
};
CXX11AttributeKind
isCXX11AttributeSpecifier(bool Disambiguate = false,
bool OuterMightBeMessageSend = false);
void DiagnoseUnexpectedNamespace(NamedDecl *Context);
DeclGroupPtrTy ParseNamespace(DeclaratorContext Context,
SourceLocation &DeclEnd,
SourceLocation InlineLoc = SourceLocation());
struct InnerNamespaceInfo {
SourceLocation NamespaceLoc;
SourceLocation InlineLoc;
SourceLocation IdentLoc;
IdentifierInfo *Ident;
};
using InnerNamespaceInfoList = llvm::SmallVector<InnerNamespaceInfo, 4>;
void ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs,
unsigned int index, SourceLocation &InlineLoc,
ParsedAttributes &attrs,
BalancedDelimiterTracker &Tracker);
Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context);
Decl *ParseExportDeclaration();
DeclGroupPtrTy ParseUsingDirectiveOrDeclaration(
DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs);
Decl *ParseUsingDirective(DeclaratorContext Context,
SourceLocation UsingLoc,
SourceLocation &DeclEnd,
ParsedAttributes &attrs);
struct UsingDeclarator {
SourceLocation TypenameLoc;
CXXScopeSpec SS;
UnqualifiedId Name;
SourceLocation EllipsisLoc;
void clear() {
TypenameLoc = EllipsisLoc = SourceLocation();
SS.clear();
Name.clear();
}
};
bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D);
DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context,
const ParsedTemplateInfo &TemplateInfo,
SourceLocation UsingLoc,
SourceLocation &DeclEnd,
AccessSpecifier AS = AS_none);
Decl *ParseAliasDeclarationAfterDeclarator(
const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
ParsedAttributes &Attrs, Decl **OwnedType = nullptr);
Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
SourceLocation AliasLoc, IdentifierInfo *Alias,
SourceLocation &DeclEnd);
//===--------------------------------------------------------------------===//
// C++ 9: classes [class] and C structs/unions.
bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo,
AccessSpecifier AS, bool EnteringContext,
DeclSpecContext DSC,
ParsedAttributesWithRange &Attributes);
void SkipCXXMemberSpecification(SourceLocation StartLoc,
SourceLocation AttrFixitLoc,
unsigned TagType,
Decl *TagDecl);
void ParseCXXMemberSpecification(SourceLocation StartLoc,
SourceLocation AttrFixitLoc,
ParsedAttributesWithRange &Attrs,
unsigned TagType,
Decl *TagDecl);
ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
SourceLocation &EqualLoc);
bool
ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
VirtSpecifiers &VS,
ExprResult &BitfieldSize,
LateParsedAttrList &LateAttrs);
void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
VirtSpecifiers &VS);
DeclGroupPtrTy ParseCXXClassMemberDeclaration(
AccessSpecifier AS, ParsedAttributes &Attr,
const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas(
AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
DeclSpec::TST TagType, Decl *Tag);
void ParseConstructorInitializer(Decl *ConstructorDecl);
MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
Decl *ThisDecl);
//===--------------------------------------------------------------------===//
// C++ 10: Derived classes [class.derived]
TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
SourceLocation &EndLocation);
void ParseBaseClause(Decl *ClassDecl);
BaseResult ParseBaseSpecifier(Decl *ClassDecl);
AccessSpecifier getAccessSpecifierIfPresent() const;
bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
IdentifierInfo *Name,
SourceLocation NameLoc,
bool EnteringContext,
ParsedType ObjectType,
UnqualifiedId &Id,
bool AssumeTemplateId);
bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
ParsedType ObjectType,
UnqualifiedId &Result);
//===--------------------------------------------------------------------===//
// OpenMP: Directives and clauses.
/// Parse clauses for '#pragma omp declare simd'.
DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
CachedTokens &Toks,
SourceLocation Loc);
/// Parses OpenMP context selectors and calls \p Callback for each
/// successfully parsed context selector.
bool
parseOpenMPContextSelectors(SourceLocation Loc,
SmallVectorImpl<Sema::OMPCtxSelectorData> &Data);
/// Parse clauses for '#pragma omp declare variant'.
void ParseOMPDeclareVariantClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks,
SourceLocation Loc);
/// Parse clauses for '#pragma omp declare target'.
DeclGroupPtrTy ParseOMPDeclareTargetClauses();
/// Parse '#pragma omp end declare target'.
void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind DKind,
SourceLocation Loc);
/// Parses declarative OpenMP directives.
DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
AccessSpecifier &AS, ParsedAttributesWithRange &Attrs,
bool Delayed = false, DeclSpec::TST TagType = DeclSpec::TST_unspecified,
Decl *TagDecl = nullptr);
/// Parse 'omp declare reduction' construct.
DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS);
/// Parses initializer for provided omp_priv declaration inside the reduction
/// initializer.
void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm);
/// Parses 'omp declare mapper' directive.
DeclGroupPtrTy ParseOpenMPDeclareMapperDirective(AccessSpecifier AS);
/// Parses variable declaration in 'omp declare mapper' directive.
TypeResult parseOpenMPDeclareMapperVarDecl(SourceRange &Range,
DeclarationName &Name,
AccessSpecifier AS = AS_none);
/// Parses simple list of variables.
///
/// \param Kind Kind of the directive.
/// \param Callback Callback function to be called for the list elements.
/// \param AllowScopeSpecifier true, if the variables can have fully
/// qualified names.
///
bool ParseOpenMPSimpleVarList(
OpenMPDirectiveKind Kind,
const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
Callback,
bool AllowScopeSpecifier);
/// Parses declarative or executable directive.
///
/// \param StmtCtx The context in which we're parsing the directive.
StmtResult
ParseOpenMPDeclarativeOrExecutableDirective(ParsedStmtContext StmtCtx);
/// Parses clause of kind \a CKind for directive of a kind \a Kind.
///
/// \param DKind Kind of current directive.
/// \param CKind Kind of current clause.
/// \param FirstClause true, if this is the first clause of a kind \a CKind
/// in current directive.
///
OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
OpenMPClauseKind CKind, bool FirstClause);
/// Parses clause with a single expression of a kind \a Kind.
///
/// \param Kind Kind of current clause.
/// \param ParseOnly true to skip the clause's semantic actions and return
/// nullptr.
///
OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind,
bool ParseOnly);
/// Parses simple clause of a kind \a Kind.
///
/// \param Kind Kind of current clause.
/// \param ParseOnly true to skip the clause's semantic actions and return
/// nullptr.
///
OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly);
/// Parses clause with a single expression and an additional argument
/// of a kind \a Kind.
///
/// \param Kind Kind of current clause.
/// \param ParseOnly true to skip the clause's semantic actions and return
/// nullptr.
///
OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind,
bool ParseOnly);
/// Parses clause without any additional arguments.
///
/// \param Kind Kind of current clause.
/// \param ParseOnly true to skip the clause's semantic actions and return
/// nullptr.
///
OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false);
/// Parses clause with the list of variables of a kind \a Kind.
///
/// \param Kind Kind of current clause.
/// \param ParseOnly true to skip the clause's semantic actions and return
/// nullptr.
///
OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
OpenMPClauseKind Kind, bool ParseOnly);
public:
/// Parses simple expression in parens for single-expression clauses of OpenMP
/// constructs.
/// \param RLoc Returned location of right paren.
ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc,
bool IsAddressOfOperand = false);
/// Data used for parsing list of variables in OpenMP clauses.
struct OpenMPVarListDataTy {
Expr *TailExpr = nullptr;
SourceLocation ColonLoc;
SourceLocation RLoc;
CXXScopeSpec ReductionOrMapperIdScopeSpec;
DeclarationNameInfo ReductionOrMapperId;
int ExtraModifier = -1; ///< Additional modifier for linear, map, depend or
///< lastprivate clause.
SmallVector<OpenMPMapModifierKind, OMPMapClause::NumberOfModifiers>
MapTypeModifiers;
SmallVector<SourceLocation, OMPMapClause::NumberOfModifiers>
MapTypeModifiersLoc;
bool IsMapTypeImplicit = false;
SourceLocation DepLinMapLastLoc;
};
/// Parses clauses with list.
bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind,
SmallVectorImpl<Expr *> &Vars,
OpenMPVarListDataTy &Data);
bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
bool AllowDestructorName,
bool AllowConstructorName,
bool AllowDeductionGuide,
ParsedType ObjectType,
SourceLocation *TemplateKWLoc,
UnqualifiedId &Result);
/// Parses the mapper modifier in map, to, and from clauses.
bool parseMapperModifier(OpenMPVarListDataTy &Data);
/// Parses map-type-modifiers in map clause.
/// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list)
/// where, map-type-modifier ::= always | close | mapper(mapper-identifier)
bool parseMapTypeModifiers(OpenMPVarListDataTy &Data);
private:
//===--------------------------------------------------------------------===//
// C++ 14: Templates [temp]
// C++ 14.1: Template Parameters [temp.param]
Decl *ParseDeclarationStartingWithTemplate(DeclaratorContext Context,
SourceLocation &DeclEnd,
ParsedAttributes &AccessAttrs,
AccessSpecifier AS = AS_none);
Decl *ParseTemplateDeclarationOrSpecialization(DeclaratorContext Context,
SourceLocation &DeclEnd,
ParsedAttributes &AccessAttrs,
AccessSpecifier AS);
Decl *ParseSingleDeclarationAfterTemplate(
DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd,
ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none);
bool ParseTemplateParameters(unsigned Depth,
SmallVectorImpl<NamedDecl *> &TemplateParams,
SourceLocation &LAngleLoc,
SourceLocation &RAngleLoc);
bool ParseTemplateParameterList(unsigned Depth,
SmallVectorImpl<NamedDecl*> &TemplateParams);
TPResult isStartOfTemplateTypeParameter();
NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position);
NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position);
NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
bool isTypeConstraintAnnotation();
bool TryAnnotateTypeConstraint();
NamedDecl *
ParseConstrainedTemplateTypeParameter(unsigned Depth, unsigned Position);
void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
SourceLocation CorrectLoc,
bool AlreadyHasEllipsis,
bool IdentifierHasName);
void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
Declarator &D);
// C++ 14.3: Template arguments [temp.arg]
typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
bool ConsumeLastToken,
bool ObjCGenericList);
bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
SourceLocation &LAngleLoc,
TemplateArgList &TemplateArgs,
SourceLocation &RAngleLoc);
bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &TemplateName,
bool AllowTypeAnnotation = true,
bool TypeConstraint = false);
void AnnotateTemplateIdTokenAsType(CXXScopeSpec &SS,
bool IsClassName = false);
bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
ParsedTemplateArgument ParseTemplateTemplateArgument();
ParsedTemplateArgument ParseTemplateArgument();
Decl *ParseExplicitInstantiation(DeclaratorContext Context,
SourceLocation ExternLoc,
SourceLocation TemplateLoc,
SourceLocation &DeclEnd,
ParsedAttributes &AccessAttrs,
AccessSpecifier AS = AS_none);
// C++2a: Template, concept definition [temp]
Decl *
ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo,
SourceLocation &DeclEnd);
//===--------------------------------------------------------------------===//
// Modules
DeclGroupPtrTy ParseModuleDecl(bool IsFirstDecl);
Decl *ParseModuleImport(SourceLocation AtLoc);
bool parseMisplacedModuleImport();
bool tryParseMisplacedModuleImport() {
tok::TokenKind Kind = Tok.getKind();
if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end ||
Kind == tok::annot_module_include)
return parseMisplacedModuleImport();
return false;
}
bool ParseModuleName(
SourceLocation UseLoc,
SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
bool IsImport);
//===--------------------------------------------------------------------===//
// C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
ExprResult ParseTypeTrait();
/// Parse the given string as a type.
///
/// This is a dangerous utility function currently employed only by API notes.
/// It is not a general entry-point for safely parsing types from strings.
///
/// \param typeStr The string to be parsed as a type.
/// \param context The name of the context in which this string is being
/// parsed, which will be used in diagnostics.
/// \param includeLoc The location at which this parse was triggered.
TypeResult parseTypeFromString(StringRef typeStr, StringRef context,
SourceLocation includeLoc);
//===--------------------------------------------------------------------===//
// Embarcadero: Arary and Expression Traits
ExprResult ParseArrayTypeTrait();
ExprResult ParseExpressionTrait();
ExprResult ParseBuiltinPtrauthTypeDiscriminator();
//===--------------------------------------------------------------------===//
// Preprocessor code-completion pass-through
void CodeCompleteDirective(bool InConditional) override;
void CodeCompleteInConditionalExclusion() override;
void CodeCompleteMacroName(bool IsDefinition) override;
void CodeCompletePreprocessorExpression() override;
void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
unsigned ArgumentIndex) override;
void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) override;
void CodeCompleteNaturalLanguage() override;
};
} // end namespace clang
#endif
|
stream.c | /*-----------------------------------------------------------------------*/
/* Program: Stream */
/* Original code developed by John D. McCalpin */
/* Programmers: John D. McCalpin */
/* Joe R. Zagar */
/* */
/* This program measures memory transfer rates in MB/s for simple */
/* computational kernels coded in C. */
/*-----------------------------------------------------------------------*/
/* Copyright 1991-2005: John D. McCalpin */
/*-----------------------------------------------------------------------*/
/* License: */
/* 1. You are free to use this program and/or to redistribute */
/* this program. */
/* 2. You are free to modify this program for your own use, */
/* including commercial use, subject to the publication */
/* restrictions in item 3. */
/* 3. You are free to publish results obtained from running this */
/* program, or from works that you derive from this program, */
/* with the following limitations: */
/* 3a. In order to be referred to as "STREAM benchmark results", */
/* published results must be in conformance to the STREAM */
/* Run Rules, (briefly reviewed below) published at */
/* http://www.cs.virginia.edu/stream/ref.html */
/* and incorporated herein by reference. */
/* As the copyright holder, John McCalpin retains the */
/* right to determine conformity with the Run Rules. */
/* 3b. Results based on modified source code or on runs not in */
/* accordance with the STREAM Run Rules must be clearly */
/* labelled whenever they are published. Examples of */
/* proper labelling include: */
/* "tuned STREAM benchmark results" */
/* "based on a variant of the STREAM benchmark code" */
/* Other comparable, clear and reasonable labelling is */
/* acceptable. */
/* 3c. Submission of results to the STREAM benchmark web site */
/* is encouraged, but not required. */
/* 4. Use of this program or creation of derived works based on this */
/* program constitutes acceptance of these licensing restrictions. */
/* 5. Absolutely no warranty is expressed or implied. */
/*-----------------------------------------------------------------------*/
# include <stdio.h>
# include <math.h>
# include <float.h>
# include <limits.h>
# include <sys/time.h>
/* INSTRUCTIONS:
*
* 1) Stream requires a good bit of memory to run. Adjust the
* value of 'N' (below) to give a 'timing calibration' of
* at least 20 clock-ticks. This will provide rate estimates
* that should be good to about 5% precision.
*/
# define N 2000000
# define NTIMES 10
# define OFFSET 0
/*
* 3) Compile the code with full optimization. Many compilers
* generate unreasonably bad code before the optimizer tightens
* things up. If the results are unreasonably good, on the
* other hand, the optimizer might be too smart for me!
*
* Try compiling with:
* cc -O stream_omp.c -o stream_omp
*
* This is known to work on Cray, SGI, IBM, and Sun machines.
*
*
* 4) Mail the results to mccalpin@cs.virginia.edu
* Be sure to include:
* a) computer hardware model number and software revision
* b) the compiler flags
* c) all of the output from the test case.
* Thanks!
*
*/
# define HLINE "-------------------------------------------------------------\n"
# ifndef MIN
# define MIN(x,y) ((x)<(y)?(x):(y))
# endif
# ifndef MAX
# define MAX(x,y) ((x)>(y)?(x):(y))
# endif
static double a[N+OFFSET],
b[N+OFFSET],
c[N+OFFSET];
static double avgtime[4] = {0}, maxtime[4] = {0},
mintime[4] = {FLT_MAX,FLT_MAX,FLT_MAX,FLT_MAX};
static char *label[4] = {"Copy: ", "Scale: ",
"Add: ", "Triad: "};
static double bytes[4] = {
2 * sizeof(double) * N,
2 * sizeof(double) * N,
3 * sizeof(double) * N,
3 * sizeof(double) * N
};
extern double mysecond();
extern void checkSTREAMresults();
#ifdef TUNED
extern void tuned_STREAM_Copy();
extern void tuned_STREAM_Scale(double scalar);
extern void tuned_STREAM_Add();
extern void tuned_STREAM_Triad(double scalar);
#endif
#ifdef _OPENMP
int omp_get_num_threads( );
#endif
int
main()
{
int quantum, checktick();
int BytesPerWord;
register int j, k;
double scalar, t, times[4][NTIMES];
/* --- SETUP --- determine precision and check timing --- */
printf(HLINE);
printf("STREAM version $Revision$\n");
printf(HLINE);
BytesPerWord = sizeof(double);
printf("This system uses %d bytes per DOUBLE PRECISION word.\n",
BytesPerWord);
printf(HLINE);
printf("Array size = %d, Offset = %d\n" , N, OFFSET);
printf("Total memory required = %.1f MB.\n",
(3.0 * BytesPerWord) * ( (double) N / 1048576.0));
printf("Each test is run %d times, but only\n", NTIMES);
printf("the *best* time for each is used.\n");
#ifdef _OPENMP
printf(HLINE);
#pragma omp parallel
{
#pragma omp master
{
k = omp_get_num_threads();
printf ("Number of Threads requested = %i\n",k);
}
}
#endif
printf(HLINE);
#pragma omp parallel
{
printf ("Printing one line per active thread....\n");
}
/* Get initial value for system clock. */
#pragma omp parallel for
for (j=0; j<N; j++) {
a[j] = 1.0;
b[j] = 2.0;
c[j] = 0.0;
}
printf(HLINE);
if ( (quantum = checktick()) >= 1)
printf("Your clock granularity/precision appears to be "
"%d microseconds.\n", quantum);
else
printf("Your clock granularity appears to be "
"less than one microsecond.\n");
t = mysecond();
#pragma omp parallel for
for (j = 0; j < N; j++)
a[j] = 2.0E0 * a[j];
t = 1.0E6 * (mysecond() - t);
printf("Each test below will take on the order"
" of %d microseconds.\n", (int) t );
printf(" (= %d clock ticks)\n", (int) (t/quantum) );
printf("Increase the size of the arrays if this shows that\n");
printf("you are not getting at least 20 clock ticks per test.\n");
printf(HLINE);
printf("WARNING -- The above is only a rough guideline.\n");
printf("For best results, please be sure you know the\n");
printf("precision of your system timer.\n");
printf(HLINE);
/* --- MAIN LOOP --- repeat test cases NTIMES times --- */
scalar = 3.0;
for (k=0; k<NTIMES; k++)
{
times[0][k] = mysecond();
#ifdef TUNED
tuned_STREAM_Copy();
#else
#pragma omp parallel for
for (j=0; j<N; j++)
c[j] = a[j];
#endif
times[0][k] = mysecond() - times[0][k];
times[1][k] = mysecond();
#ifdef TUNED
tuned_STREAM_Scale(scalar);
#else
#pragma omp parallel for
for (j=0; j<N; j++)
b[j] = scalar*c[j];
#endif
times[1][k] = mysecond() - times[1][k];
times[2][k] = mysecond();
#ifdef TUNED
tuned_STREAM_Add();
#else
#pragma omp parallel for
for (j=0; j<N; j++)
c[j] = a[j]+b[j];
#endif
times[2][k] = mysecond() - times[2][k];
times[3][k] = mysecond();
#ifdef TUNED
tuned_STREAM_Triad(scalar);
#else
#pragma omp parallel for
for (j=0; j<N; j++)
a[j] = b[j]+scalar*c[j];
#endif
times[3][k] = mysecond() - times[3][k];
}
/* --- SUMMARY --- */
for (k=1; k<NTIMES; k++) /* note -- skip first iteration */
{
for (j=0; j<4; j++)
{
avgtime[j] = avgtime[j] + times[j][k];
mintime[j] = MIN(mintime[j], times[j][k]);
maxtime[j] = MAX(maxtime[j], times[j][k]);
}
}
printf("Function Rate (MB/s) Avg time Min time Max time\n");
for (j=0; j<4; j++) {
avgtime[j] = avgtime[j]/(double)(NTIMES-1);
printf("%s%11.4f %11.4f %11.4f %11.4f\n", label[j],
1.0E-06 * bytes[j]/mintime[j],
avgtime[j],
mintime[j],
maxtime[j]);
}
printf(HLINE);
/* --- Check Results --- */
checkSTREAMresults();
printf(HLINE);
return 0;
}
# define M 20
int
checktick()
{
int i, minDelta, Delta;
double t1, t2, timesfound[M];
/* Collect a sequence of M unique time values from the system. */
for (i = 0; i < M; i++) {
t1 = mysecond();
while( ((t2=mysecond()) - t1) < 1.0E-6 )
;
timesfound[i] = t1 = t2;
}
/*
* Determine the minimum difference between these M values.
* This result will be our estimate (in microseconds) for the
* clock granularity.
*/
minDelta = 1000000;
for (i = 1; i < M; i++) {
Delta = (int)( 1.0E6 * (timesfound[i]-timesfound[i-1]));
minDelta = MIN(minDelta, MAX(Delta,0));
}
return(minDelta);
}
/* A gettimeofday routine to give access to the wall
clock timer on most UNIX-like systems. */
#include <sys/time.h>
double mysecond()
{
struct timeval tp;
struct timezone tzp;
int i;
i = gettimeofday(&tp,&tzp);
return ( (double) tp.tv_sec + (double) tp.tv_usec * 1.e-6 );
}
void checkSTREAMresults ()
{
double aj,bj,cj,scalar;
double asum,bsum,csum;
double epsilon;
int j,k;
/* reproduce initialization */
aj = 1.0;
bj = 2.0;
cj = 0.0;
/* a[] is modified during timing check */
aj = 2.0E0 * aj;
/* now execute timing loop */
scalar = 3.0;
for (k=0; k<NTIMES; k++)
{
cj = aj;
bj = scalar*cj;
cj = aj+bj;
aj = bj+scalar*cj;
}
aj = aj * (double) (N);
bj = bj * (double) (N);
cj = cj * (double) (N);
asum = 0.0;
bsum = 0.0;
csum = 0.0;
for (j=0; j<N; j++) {
asum += a[j];
bsum += b[j];
csum += c[j];
}
#ifdef VERBOSE
printf ("Results Comparison: \n");
printf (" Expected : %f %f %f \n",aj,bj,cj);
printf (" Observed : %f %f %f \n",asum,bsum,csum);
#endif
#ifndef abs
#define abs(a) ((a) >= 0 ? (a) : -(a))
#endif
epsilon = 1.e-8;
if (abs(aj-asum)/asum > epsilon) {
printf ("Failed Validation on array a[]\n");
printf (" Expected : %f \n",aj);
printf (" Observed : %f \n",asum);
}
else if (abs(bj-bsum)/bsum > epsilon) {
printf ("Failed Validation on array b[]\n");
printf (" Expected : %f \n",bj);
printf (" Observed : %f \n",bsum);
}
else if (abs(cj-csum)/csum > epsilon) {
printf ("Failed Validation on array c[]\n");
printf (" Expected : %f \n",cj);
printf (" Observed : %f \n",csum);
}
else {
printf ("Solution Validates\n");
}
}
void tuned_STREAM_Copy()
{
int j;
#pragma omp parallel for
for (j=0; j<N; j++)
c[j] = a[j];
}
void tuned_STREAM_Scale(double scalar)
{
int j;
#pragma omp parallel for
for (j=0; j<N; j++)
b[j] = scalar*c[j];
}
void tuned_STREAM_Add()
{
int j;
#pragma omp parallel for
for (j=0; j<N; j++)
c[j] = a[j]+b[j];
}
void tuned_STREAM_Triad(double scalar)
{
int j;
#pragma omp parallel for
for (j=0; j<N; j++)
a[j] = b[j]+scalar*c[j];
}
|
omp_flush.c | // RUN: %libomp-compile-and-run
#include <stdio.h>
#include "omp_testsuite.h"
#include "omp_my_sleep.h"
int test_omp_flush()
{
int result1;
int result2;
int dummy;
result1 = 0;
result2 = 0;
#pragma omp parallel
{
int rank;
rank = omp_get_thread_num ();
#pragma omp barrier
if (rank == 1) {
result2 = 3;
#pragma omp flush (result2)
dummy = result2;
}
if (rank == 0) {
my_sleep(SLEEPTIME);
#pragma omp flush (result2)
result1 = result2;
}
} /* end of parallel */
return ((result1 == result2) && (result2 == dummy) && (result2 == 3));
}
int main()
{
int i;
int num_failed=0;
for (i = 0; i < REPETITIONS; i++) {
if(!test_omp_flush()) {
num_failed++;
}
}
return num_failed;
}
|
Parallel.h | /*
* SVRTK : SVR reconstruction based on MIRTK
*
* Copyright 2021- King's College London
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
// SVRTK
#include "svrtk/ReconstructionCardiacVelocity4D.h"
using namespace mirtk;
using namespace svrtk;
using namespace svrtk::Utility;
namespace svrtk::Parallel {
/// Class for computing average of all stacks
class Average {
const Reconstruction *reconstructor;
const Array<RealImage>& stacks;
const Array<RigidTransformation>& stack_transformations;
/// Padding value in target (voxels in the target image with this value will be ignored)
double targetPadding;
/// Padding value in source (voxels outside the source image will be set to this value)
double sourcePadding;
double background;
// Volumetric registrations are stack-to-template while slice-to-volume
// registrations are actually performed as volume-to-slice
// (reasons: technicalities of implementation) so transformations need to be inverted beforehand.
bool linear;
public:
RealImage average;
RealImage weights;
Average(
const Reconstruction *reconstructor,
const Array<RealImage>& stacks,
const Array<RigidTransformation>& stack_transformations,
double targetPadding,
double sourcePadding,
double background,
bool linear = false) :
reconstructor(reconstructor),
stacks(stacks),
stack_transformations(stack_transformations),
targetPadding(targetPadding),
sourcePadding(sourcePadding),
background(background),
linear(linear) {
average.Initialize(reconstructor->_reconstructed.Attributes());
weights.Initialize(reconstructor->_reconstructed.Attributes());
}
Average(Average& x, split) : Average(x.reconstructor, x.stacks, x.stack_transformations, x.targetPadding, x.sourcePadding, x.background, x.linear) {}
void operator()(const blocked_range<size_t>& r) {
GenericLinearInterpolateImageFunction<RealImage> interpolator;
ImageTransformation imagetransformation;
RealImage image;
for (size_t i = r.begin(); i < r.end(); i++) {
image.Initialize(reconstructor->_reconstructed.Attributes());
imagetransformation.Input(&stacks[i]);
imagetransformation.Transformation(&stack_transformations[i]);
imagetransformation.Output(&image);
imagetransformation.TargetPaddingValue(targetPadding);
imagetransformation.SourcePaddingValue(sourcePadding);
imagetransformation.Interpolator(&interpolator);
imagetransformation.Run();
const RealPixel *pi = image.Data();
RealPixel *pa = average.Data();
RealPixel *pw = weights.Data();
for (int p = 0; p < average.NumberOfVoxels(); p++) {
if (pi[p] != background) {
pa[p] += pi[p];
pw[p]++;
}
}
}
}
void join(const Average& y) {
average += y.average;
weights += y.weights;
}
void operator()() {
parallel_reduce(blocked_range<size_t>(0, stacks.size()), *this);
}
};
//-------------------------------------------------------------------
class QualityReport {
Reconstruction *reconstructor;
public:
double out_global_ncc;
double out_global_nrmse;
QualityReport(Reconstruction *reconstructor) : reconstructor(reconstructor) {
out_global_ncc = 0;
out_global_nrmse = 0;
}
QualityReport(QualityReport& x, split) : QualityReport(x.reconstructor) {}
void operator()(const blocked_range<size_t>& r) {
for (size_t inputIndex = r.begin(); inputIndex < r.end(); inputIndex++) {
const double out_ncc = ComputeNCC(reconstructor->_slices[inputIndex], reconstructor->_simulated_slices[inputIndex], 0.1);
if (out_ncc > 0)
out_global_ncc += out_ncc;
double s_diff = 0;
double s_t = 0;
int s_n = 0;
double point_ns = 0;
double point_nt = 0;
for (int x = 0; x < reconstructor->_slices[inputIndex].GetX(); x++) {
for (int y = 0; y < reconstructor->_slices[inputIndex].GetY(); y++) {
for (int z = 0; z < reconstructor->_slices[inputIndex].GetZ(); z++) {
if (reconstructor->_slices[inputIndex](x, y, z) > 0 && reconstructor->_simulated_slices[inputIndex](x, y, z) > 0) {
point_nt = reconstructor->_slices[inputIndex](x, y, z) * exp(-(reconstructor->_bias[inputIndex])(x, y, 0)) * reconstructor->_scale[inputIndex];
point_ns = reconstructor->_simulated_slices[inputIndex](x, y, z);
s_t += point_nt;
s_diff += (point_nt - point_ns) * (point_nt - point_ns);
s_n++;
}
}
}
}
if (s_n > 0 && s_t > 0) {
const double out_nrmse = sqrt(s_diff / s_n) / (s_t / s_n);
out_global_nrmse += out_nrmse;
}
if (!isfinite(out_global_nrmse))
out_global_nrmse = 0;
} //end of loop for a slice inputIndex
}
void join(const QualityReport& y) {
out_global_ncc += y.out_global_ncc;
out_global_nrmse += y.out_global_nrmse;
}
void operator()() {
parallel_reduce(blocked_range<size_t>(0, reconstructor->_slices.size()), *this);
}
};
//-------------------------------------------------------------------
// class for global 3D stack registration
class StackRegistrations {
const Reconstruction *reconstructor;
const Array<RealImage>& stacks;
Array<RigidTransformation>& stack_transformations;
int templateNumber;
const RealImage& target;
const RigidTransformation& offset;
public:
StackRegistrations(
const Reconstruction *reconstructor,
const Array<RealImage>& stacks,
Array<RigidTransformation>& stack_transformations,
int templateNumber,
const RealImage& target,
const RigidTransformation& offset) :
reconstructor(reconstructor),
stacks(stacks),
stack_transformations(stack_transformations),
templateNumber(templateNumber),
target(target),
offset(offset) {}
void operator()(const blocked_range<size_t>& r) const {
RealImage r_source, r_target;
GenericLinearInterpolateImageFunction<RealImage> interpolator;
ResamplingWithPadding<RealPixel> resampling(1.2, 1.2, 1.2, 0);
resampling.Interpolator(&interpolator);
ParameterList params;
Insert(params, "Transformation model", "Rigid");
if (reconstructor->_nmi_bins > 0)
Insert(params, "No. of bins", reconstructor->_nmi_bins);
if (reconstructor->_masked_stacks)
Insert(params, "Background value", 0);
else
Insert(params, "Background value for image 1", 0);
// Insert(params, "Background value", 0);
// Insert(params, "Image (dis-)similarity measure", "NCC");
// Insert(params, "Image interpolation mode", "Linear");
// string type = "box";
// string units = "mm";
// double width = 0;
// Insert(params, string("Local window size [") + type + string("]"), ToString(width) + units);
Transformation *dofout;
GenericRegistrationFilter registration;
registration.Parameter(params);
registration.Output(&dofout);
for (size_t i = r.begin(); i != r.end(); i++) {
r_source.Initialize(stacks[i].Attributes());
resampling.Input(&stacks[i]);
resampling.Output(&r_source);
resampling.Run();
r_target.Initialize(target.Attributes());
resampling.Input(&target);
resampling.Output(&r_target);
resampling.Run();
const Matrix& mo = offset.GetMatrix();
stack_transformations[i].PutMatrix(stack_transformations[i].GetMatrix() * mo);
registration.Input(&r_target, &r_source);
registration.InitialGuess(&stack_transformations[i]);
registration.GuessParameter();
registration.Run();
unique_ptr<RigidTransformation> rigidTransf(dynamic_cast<RigidTransformation*>(dofout));
stack_transformations[i] = *rigidTransf;
stack_transformations[i].PutMatrix(stack_transformations[i].GetMatrix() * mo.Inverse());
//save volumetric registrations
if (reconstructor->_debug) {
stack_transformations[i].Write((boost::format("global-transformation%1%.dof") % i).str().c_str());
stacks[i].Write((boost::format("global-stack%1%.nii.gz") % i).str().c_str());
}
}
}
void operator()() const {
parallel_for(blocked_range<size_t>(0, stacks.size()), *this);
}
};
//-------------------------------------------------------------------
// class for simulation of slice masks
class SimulateMasks {
Reconstruction *reconstructor;
public:
SimulateMasks(SimulateMasks& x, split) : SimulateMasks(x.reconstructor) {}
SimulateMasks(Reconstruction *reconstructor) : reconstructor(reconstructor) {}
void operator()(const blocked_range<size_t>& r) {
for (size_t inputIndex = r.begin(); inputIndex < r.end(); inputIndex++) {
//Calculate simulated slice
RealImage& sim_mask = reconstructor->_slice_masks[inputIndex];
memset(sim_mask.Data(), 0, sizeof(RealPixel) * sim_mask.NumberOfVoxels());
bool slice_inside = false;
for (int i = 0; i < reconstructor->_slice_attributes[inputIndex]._x; i++) {
for (int j = 0; j < reconstructor->_slice_attributes[inputIndex]._y; j++) {
if (reconstructor->_slices[inputIndex](i, j, 0) > -0.01) {
double weight = 0;
const size_t n = reconstructor->_volcoeffs[inputIndex][i][j].size();
for (size_t k = 0; k < n; k++) {
const POINT3D& p = reconstructor->_volcoeffs[inputIndex][i][j][k];
sim_mask(i, j, 0) += p.value * reconstructor->_evaluation_mask(p.x, p.y, p.z);
weight += p.value;
}
if (weight > 0)
sim_mask(i, j, 0) /= weight;
if (sim_mask(i, j, 0) > 0.1)
slice_inside = true;
} else {
sim_mask(i, j, 0) = 0;
}
}
}
if (slice_inside) {
GaussianBlurring<RealPixel> gb(2);
gb.Input(&sim_mask);
gb.Output(&sim_mask);
gb.Run();
RealPixel *pm = sim_mask.Data();
for (int i = 0; i < sim_mask.NumberOfVoxels(); i++)
if (pm[i] > 0.3)
pm[i] = 1;
}
} //end of loop for a slice inputIndex
}
void join(const SimulateMasks& y) {}
void operator()() {
parallel_reduce(blocked_range<size_t>(0, reconstructor->_slices.size()), *this);
}
};
//-------------------------------------------------------------------
/// Class for simulation of slices from the current reconstructed 3D volume - v2 (use this one)
class SimulateSlices {
Reconstruction *reconstructor;
public:
SimulateSlices(SimulateSlices& x, split) : SimulateSlices(x.reconstructor) {}
SimulateSlices(Reconstruction *reconstructor) : reconstructor(reconstructor) {}
void operator()(const blocked_range<size_t>& r) {
for (size_t inputIndex = r.begin(); inputIndex < r.end(); inputIndex++) {
//Calculate simulated slice
RealImage& sim_slice = reconstructor->_simulated_slices[inputIndex];
RealImage& sim_weight = reconstructor->_simulated_weights[inputIndex];
RealImage& sim_inside = reconstructor->_simulated_inside[inputIndex];
memset(sim_slice.Data(), 0, sizeof(RealPixel) * sim_slice.NumberOfVoxels());
memset(sim_weight.Data(), 0, sizeof(RealPixel) * sim_weight.NumberOfVoxels());
memset(sim_inside.Data(), 0, sizeof(RealPixel) * sim_inside.NumberOfVoxels());
reconstructor->_slice_inside[inputIndex] = false;
for (size_t i = 0; i < reconstructor->_volcoeffs[inputIndex].size(); i++)
for (size_t j = 0; j < reconstructor->_volcoeffs[inputIndex][i].size(); j++)
if (reconstructor->_slices[inputIndex](i, j, 0) > -0.01) {
double weight = 0;
for (size_t k = 0; k < reconstructor->_volcoeffs[inputIndex][i][j].size(); k++) {
const POINT3D& p = reconstructor->_volcoeffs[inputIndex][i][j][k];
sim_slice(i, j, 0) += p.value * reconstructor->_reconstructed(p.x, p.y, p.z);
weight += p.value;
if (reconstructor->_mask(p.x, p.y, p.z) > 0.1) {
sim_inside(i, j, 0) = 1;
reconstructor->_slice_inside[inputIndex] = true;
}
}
if (weight > 0) {
sim_slice(i, j, 0) /= weight;
sim_weight(i, j, 0) = weight;
}
};
} //end of loop for a slice inputIndex
}
void join(const SimulateSlices& y) {}
void operator()() {
parallel_reduce(blocked_range<size_t>(0, reconstructor->_slices.size()), *this);
}
};
//-------------------------------------------------------------------
class SimulateSlicesCardiac4D {
ReconstructionCardiac4D *reconstructor;
public:
SimulateSlicesCardiac4D(ReconstructionCardiac4D *reconstructor) : reconstructor(reconstructor) {}
void operator()(const blocked_range<size_t>& r) const {
for (size_t inputIndex = r.begin(); inputIndex != r.end(); inputIndex++) {
const RealImage& slice = reconstructor->_slices[inputIndex];
//Calculate simulated slice
reconstructor->_simulated_slices[inputIndex].Initialize(slice.Attributes());
reconstructor->_simulated_weights[inputIndex].Initialize(slice.Attributes());
reconstructor->_simulated_inside[inputIndex].Initialize(slice.Attributes());
reconstructor->_slice_inside[inputIndex] = false;
for (size_t i = 0; i < reconstructor->_volcoeffs[inputIndex].size(); i++)
for (size_t j = 0; j < reconstructor->_volcoeffs[inputIndex][i].size(); j++)
if (slice(i, j, 0) != -1) {
double weight = 0;
for (size_t k = 0; k < reconstructor->_volcoeffs[inputIndex][i][j].size(); k++) {
const POINT3D& p = reconstructor->_volcoeffs[inputIndex][i][j][k];
for (int outputIndex = 0; outputIndex < reconstructor->_reconstructed4D.GetT(); outputIndex++) {
reconstructor->_simulated_slices[inputIndex](i, j, 0) += reconstructor->_slice_temporal_weight[outputIndex][inputIndex] * p.value * reconstructor->_reconstructed4D(p.x, p.y, p.z, outputIndex);
weight += reconstructor->_slice_temporal_weight[outputIndex][inputIndex] * p.value;
}
if (reconstructor->_mask(p.x, p.y, p.z) == 1) {
reconstructor->_simulated_inside[inputIndex](i, j, 0) = 1;
reconstructor->_slice_inside[inputIndex] = true;
}
}
if (weight > 0) {
reconstructor->_simulated_slices[inputIndex](i, j, 0) /= weight;
reconstructor->_simulated_weights[inputIndex](i, j, 0) = weight;
}
}
}
}
void operator()() const {
parallel_for(blocked_range<size_t>(0, reconstructor->_slices.size()), *this);
}
};
//-------------------------------------------------------------------
/// Simulation of phase slices from velocity volumes
class SimulateSlicesCardiacVelocity4D {
ReconstructionCardiacVelocity4D *reconstructor;
public:
SimulateSlicesCardiacVelocity4D(ReconstructionCardiacVelocity4D *reconstructor) : reconstructor(reconstructor) {}
void operator() (const blocked_range<size_t> &r) const {
for (size_t inputIndex = r.begin(); inputIndex != r.end(); inputIndex++) {
// calculate simulated slice
reconstructor->_simulated_slices[inputIndex].Initialize(reconstructor->_slices[inputIndex].Attributes());
reconstructor->_simulated_weights[inputIndex].Initialize(reconstructor->_slices[inputIndex].Attributes());
reconstructor->_simulated_inside[inputIndex].Initialize(reconstructor->_slices[inputIndex].Attributes());
reconstructor->_slice_inside[inputIndex] = false;
memset(reconstructor->_simulated_velocities[inputIndex][0].Data(), 0, sizeof(RealPixel) * reconstructor->_simulated_velocities[inputIndex][0].NumberOfVoxels());
memset(reconstructor->_simulated_velocities[inputIndex][1].Data(), 0, sizeof(RealPixel) * reconstructor->_simulated_velocities[inputIndex][1].NumberOfVoxels());
memset(reconstructor->_simulated_velocities[inputIndex][2].Data(), 0, sizeof(RealPixel) * reconstructor->_simulated_velocities[inputIndex][2].NumberOfVoxels());
// Gradient magnitude for the current slice
const int gradientIndex = reconstructor->_stack_index[inputIndex];
const double gval = reconstructor->_g_values[gradientIndex];
for (size_t i = 0; i < reconstructor->_volcoeffs[inputIndex].size(); i++)
for (size_t j = 0; j < reconstructor->_volcoeffs[inputIndex][i].size(); j++)
if (reconstructor->_slices[inputIndex](i, j, 0) > -10) {
double weight = 0;
for (size_t k = 0; k < reconstructor->_volcoeffs[inputIndex][i][j].size(); k++) {
const POINT3D& p = reconstructor->_volcoeffs[inputIndex][i][j][k];
for (int outputIndex = 0; outputIndex < reconstructor->_reconstructed4D.GetT(); outputIndex++) {
if (reconstructor->_reconstructed4D.GetT() == 1)
reconstructor->_slice_temporal_weight[outputIndex][inputIndex] = 1;
// Simulation of phase signal from velocity volumes
double sim_signal = 0;
for (size_t velocityIndex = 0; velocityIndex < reconstructor->_reconstructed5DVelocity.size(); velocityIndex++) {
sim_signal += reconstructor->_reconstructed5DVelocity[velocityIndex](p.x, p.y, p.z, outputIndex) * gval * reconstructor->_slice_g_directions[inputIndex][velocityIndex];
reconstructor->_simulated_velocities[inputIndex][velocityIndex](i, j, 0) += reconstructor->_reconstructed5DVelocity[velocityIndex](p.x, p.y, p.z, outputIndex) * reconstructor->_slice_temporal_weight[outputIndex][inputIndex] * p.value;
}
reconstructor->_simulated_slices[inputIndex](i, j, 0) += sim_signal * reconstructor->gamma * reconstructor->_slice_temporal_weight[outputIndex][inputIndex] * p.value;
weight += reconstructor->_slice_temporal_weight[outputIndex][inputIndex] * p.value;
}
if (reconstructor->_mask(p.x, p.y, p.z) == 1) {
reconstructor->_simulated_inside[inputIndex](i, j, 0) = 1;
reconstructor->_slice_inside[inputIndex] = true;
}
}
if (weight > 0) {
reconstructor->_simulated_slices[inputIndex](i, j, 0) /= weight;
reconstructor->_simulated_weights[inputIndex](i, j, 0) = weight;
for (size_t velocityIndex = 0; velocityIndex < reconstructor->_reconstructed5DVelocity.size(); velocityIndex++)
reconstructor->_simulated_velocities[inputIndex][velocityIndex](i, j, 0) /= weight;
}
}
}
}
// execute
void operator() () const {
parallel_for(blocked_range<size_t>(0, reconstructor->_slices.size()), *this);
}
};
//-------------------------------------------------------------------
/// Class for parallel SVR
class SliceToVolumeRegistration {
Reconstruction *reconstructor;
public:
SliceToVolumeRegistration(Reconstruction *reconstructor) : reconstructor(reconstructor) {}
void operator()(const blocked_range<size_t>& r) const {
GreyPixel smin, smax, tmin, tmax;
GreyImage target;
for (size_t inputIndex = r.begin(); inputIndex != r.end(); inputIndex++) {
target = reconstructor->_grey_slices[inputIndex];
target.GetMinMax(&smin, &smax);
if (smax > 1 && (smax - smin) > 1) {
ParameterList params;
Insert(params, "Transformation model", "Rigid");
reconstructor->_grey_reconstructed.GetMinMax(&tmin, &tmax);
if (smin < 1)
Insert(params, "Background value for image 1", -1);
if (tmin < 0)
Insert(params, "Background value for image 2", -1);
else if (tmin < 1)
Insert(params, "Background value for image 2", 0);
if (!reconstructor->_ncc_reg) {
Insert(params, "Image (dis-)similarity measure", "NMI");
if (reconstructor->_nmi_bins > 0)
Insert(params, "No. of bins", reconstructor->_nmi_bins);
} else {
Insert(params, "Image (dis-)similarity measure", "NCC");
const string type = "sigma";
const string units = "mm";
constexpr double width = 0;
Insert(params, string("Local window size [") + type + string("]"), ToString(width) + units);
}
GenericRegistrationFilter registration;
registration.Parameter(params);
//put origin to zero
RigidTransformation offset;
ResetOrigin(target, offset);
const Matrix& mo = offset.GetMatrix();
auto& transformation = reconstructor->_transformations[inputIndex];
transformation.PutMatrix(transformation.GetMatrix() * mo);
// run registration
registration.Input(&target, &reconstructor->_grey_reconstructed);
Transformation *dofout;
registration.Output(&dofout);
registration.InitialGuess(&transformation);
registration.GuessParameter();
registration.Run();
// output transformation
unique_ptr<RigidTransformation> rigidTransf(dynamic_cast<RigidTransformation*>(dofout));
transformation = *rigidTransf;
//undo the offset
transformation.PutMatrix(transformation.GetMatrix() * mo.Inverse());
// save log outputs
if (reconstructor->_reg_log) {
const double tx = transformation.GetTranslationX();
const double ty = transformation.GetTranslationY();
const double tz = transformation.GetTranslationZ();
const double rx = transformation.GetRotationX();
const double ry = transformation.GetRotationY();
const double rz = transformation.GetRotationZ();
cout << boost::format("%1% %1% %1% %1% %1% %1% %1%") % inputIndex % tx % ty % tz % rx % ry % rz << endl;
}
}
}
}
void operator()() const {
parallel_for(blocked_range<size_t>(0, reconstructor->_slices.size()), *this);
}
};
//-------------------------------------------------------------------
class SliceToVolumeRegistrationCardiac4D {
ReconstructionCardiac4D *reconstructor;
public:
SliceToVolumeRegistrationCardiac4D(ReconstructionCardiac4D *reconstructor) : reconstructor(reconstructor) {}
void operator()(const blocked_range<size_t>& r) const {
const ImageAttributes& attr = reconstructor->_reconstructed4D.Attributes();
GreyImage source, target;
ParameterList params;
Insert(params, "Transformation model", "Rigid");
Insert(params, "Image (dis-)similarity measure", "NMI");
if (reconstructor->_nmi_bins > 0)
Insert(params, "No. of bins", reconstructor->_nmi_bins);
Insert(params, "Background value for image 1", 0); // -1
Insert(params, "Background value for image 2", -1);
// Insert(params, "Image (dis-)similarity measure", "NCC");
// Insert(params, "Image interpolation mode", "Linear");
// string type = "sigma";
// string units = "mm";
// double width = 0;
// Insert(params, string("Local window size [") + type + string("]"), ToString(width) + units);
Transformation *dofout;
GenericRegistrationFilter registration;
registration.Parameter(params);
registration.Output(&dofout);
for (size_t inputIndex = r.begin(); inputIndex != r.end(); inputIndex++) {
if (reconstructor->_slice_excluded[inputIndex])
continue;
// ResamplingWithPadding<RealPixel> resampling(attr._dx, attr._dx, attr._dx, -1);
// GenericLinearInterpolateImageFunction<RealImage> interpolator;
// // TARGET
// // get current slice
// RealImage t(reconstructor->_slices[inputIndex].Attributes());
// // resample to spatial resolution of reconstructed volume
// resampling.Input(&reconstructor->_slices[inputIndex]);
// resampling.Output(&t);
// resampling.Interpolator(&interpolator);
// resampling.Run();
// target = t;
// get pixel value min and max
GreyPixel smin, smax;
target = reconstructor->_slices[inputIndex];
target.GetMinMax(&smin, &smax);
// SOURCE
if (smax > 0 && (smax - smin) > 1) {
// put origin to zero
RigidTransformation offset;
ResetOrigin(target, offset);
const Matrix& mo = offset.GetMatrix();
auto& transformation = reconstructor->_transformations[inputIndex];
transformation.PutMatrix(transformation.GetMatrix() * mo);
// TODO: extract the nearest cardiac phase from reconstructed 4D to use as source
source = reconstructor->_reconstructed4D.GetRegion(0, 0, 0, reconstructor->_slice_svr_card_index[inputIndex], attr._x, attr._y, attr._z, reconstructor->_slice_svr_card_index[inputIndex] + 1);
registration.Input(&target, &source);
registration.InitialGuess(&transformation);
registration.GuessParameter();
registration.Run();
unique_ptr<RigidTransformation> rigidTransf(dynamic_cast<RigidTransformation*>(dofout));
transformation = *rigidTransf;
//undo the offset
transformation.PutMatrix(transformation.GetMatrix() * mo.Inverse());
}
}
}
void operator()() const {
parallel_for(blocked_range<size_t>(0, reconstructor->_slices.size()), *this);
}
};
//-------------------------------------------------------------------
/// Class for FFD SVR
class SliceToVolumeRegistrationFFD {
Reconstruction *reconstructor;
public:
SliceToVolumeRegistrationFFD(Reconstruction *reconstructor) : reconstructor(reconstructor) {}
void operator()(const blocked_range<size_t>& r) const {
// define registration model
ParameterList params_init;
Insert(params_init, "Transformation model", "FFD");
if (reconstructor->_ncc_reg) {
Insert(params_init, "Image (dis-)similarity measure", "NCC");
const string type = "box";
const string units = "vox";
constexpr double width = 5;
Insert(params_init, string("Local window size [") + type + string("]"), ToString(width) + units);
}
if (reconstructor->_cp_spacing.size() > 0) {
const int& cp_spacing = reconstructor->_cp_spacing[reconstructor->_current_iteration];
Insert(params_init, "Control point spacing in X", cp_spacing);
Insert(params_init, "Control point spacing in Y", cp_spacing);
Insert(params_init, "Control point spacing in Z", cp_spacing);
}
RealPixel smin, smax;
reconstructor->_reconstructed.GetMinMax(&smin, &smax);
for (size_t inputIndex = r.begin(); inputIndex != r.end(); inputIndex++) {
GenericRegistrationFilter registration;
RealPixel tmin, tmax;
const RealImage& target = reconstructor->_slices[inputIndex];
target.GetMinMax(&smin, &smax);
if (smax > 1 && (smax - smin) > 1) {
ParameterList params = params_init;
// run registration
registration.Parameter(params);
registration.Input(&target, &reconstructor->_reconstructed);
if (reconstructor->_current_iteration == 0) {
MultiLevelFreeFormTransformation *mffd_init;
int current_stack=reconstructor->_stack_index[inputIndex];
Transformation *tt = Transformation::New((boost::format("ms-%1%.dof") % current_stack).str().c_str());
mffd_init = dynamic_cast<MultiLevelFreeFormTransformation*> (tt);
registration.InitialGuess(mffd_init);
} else {
registration.InitialGuess(reconstructor->_mffd_transformations[inputIndex]);
}
Transformation *dofout;
registration.Output(&dofout);
registration.GuessParameter();
registration.Run();
MultiLevelFreeFormTransformation *mffd_dofout = dynamic_cast<MultiLevelFreeFormTransformation*> (dofout);
reconstructor->_mffd_transformations[inputIndex] = mffd_dofout;
}
}
}
void operator()() const {
parallel_for(blocked_range<size_t>(0, reconstructor->_slices.size()), *this);
}
};
//-------------------------------------------------------------------
class RemoteSliceToVolumeRegistration {
Reconstruction *reconstructor;
int svr_range_start;
int svr_range_stop;
const string& str_mirtk_path;
const string& str_current_exchange_file_path;
bool rigid, is4d;
const Array<int>& source_indexes;
string register_cmd;
public:
RemoteSliceToVolumeRegistration(
Reconstruction *reconstructor,
int svr_range_start,
int svr_range_stop,
const string& str_mirtk_path,
const string& str_current_exchange_file_path,
bool rigid = true,
const Array<int>& source_indexes = {}) :
reconstructor(reconstructor),
svr_range_start(svr_range_start),
svr_range_stop(svr_range_stop),
str_mirtk_path(str_mirtk_path),
str_current_exchange_file_path(str_current_exchange_file_path),
rigid(rigid),
source_indexes(source_indexes),
is4d(!source_indexes.empty()) {
// Preallocate memory area
register_cmd.reserve(1500);
// Define registration parameters
const string file_prefix = str_current_exchange_file_path + (rigid ? "/res-" : "/");
register_cmd = str_mirtk_path + "/register ";
register_cmd += file_prefix + "slice-%1%.nii.gz "; // Target
register_cmd += str_current_exchange_file_path + "/current-source" + (is4d ? "-%2%" : "") + ".nii.gz"; // Source
register_cmd += string(" -model ") + (rigid ? "Rigid" : "FFD");
register_cmd += " -bg1 0 -bg2 -1";
register_cmd += " -dofin " + file_prefix + "transformation-%1%.dof";
register_cmd += " -dofout " + file_prefix + "transformation-%1%.dof";
if (reconstructor->_ncc_reg)
register_cmd += string(" -sim NCC -window ") + (rigid ? "0" : "5");
if (!rigid && reconstructor->_cp_spacing.size() > 0)
register_cmd += " -ds " + to_string(reconstructor->_cp_spacing[reconstructor->_current_iteration]);
register_cmd += " -threads 1"; // Remove parallelisation of the register command
register_cmd += " > " + str_current_exchange_file_path + "/log%1%.txt"; // Log
}
void operator()(const blocked_range<size_t>& r) const {
for (size_t inputIndex = r.begin(); inputIndex != r.end(); inputIndex++) {
if (reconstructor->_zero_slices[inputIndex] > 0) {
auto register_cmd_formatter = boost::format(register_cmd) % inputIndex;
if (is4d)
register_cmd_formatter % source_indexes[inputIndex];
if (system(register_cmd_formatter.str().c_str()) == -1)
cerr << "The register command couldn't be executed!" << endl;
}
} // end of inputIndex
}
void operator()() const {
parallel_for(blocked_range<size_t>(svr_range_start, svr_range_stop), *this);
}
};
//-------------------------------------------------------------------
/// Class for calculation of transformation matrices
class CoeffInit {
Reconstruction *reconstructor;
public:
CoeffInit(Reconstruction *reconstructor) : reconstructor(reconstructor) {}
void operator()(const blocked_range<size_t>& r) const {
const RealImage global_reconstructed(reconstructor->_grey_reconstructed.Attributes());
RealImage global_slice, PSF, tPSF;
//get resolution of the volume
double vx, vy, vz;
global_reconstructed.GetPixelSize(&vx, &vy, &vz);
//volume is always isotropic
const double& res = vx;
for (size_t inputIndex = r.begin(); inputIndex != r.end(); inputIndex++) {
global_slice.Initialize(reconstructor->_slices[inputIndex].Attributes());
//prepare storage variable
VOXELCOEFFS empty;
SLICECOEFFS slicecoeffs(global_slice.GetX(), Array<VOXELCOEFFS>(global_slice.GetY(), empty));
// To check whether the slice has an overlap with mask ROI
bool slice_inside = false;
//PSF will be calculated in slice space in higher resolution
//get slice voxel size to define PSF
double dx, dy, dz;
global_slice.GetPixelSize(&dx, &dy, &dz);
//sigma of 3D Gaussian (sinc with FWHM=dx or dy in-plane, Gaussian with FWHM = dz through-plane)
double sigmax, sigmay, sigmaz;
switch (reconstructor->_recon_type) {
case _3D:
sigmax = 1.2 * dx / 2.3548;
sigmay = 1.2 * dy / 2.3548;
sigmaz = dz / 2.3548;
break;
case _1D:
sigmax = 0.5 * dx / 2.3548;
sigmay = 0.5 * dy / 2.3548;
sigmaz = dz / 2.3548;
break;
case _interpolate:
sigmax = sigmay = sigmaz = 0.5 * dx / 2.3548;
break;
}
if (reconstructor->_no_sr) {
sigmax = 0.6 * dx / 2.3548;
sigmay = 0.6 * dy / 2.3548;
sigmaz = 0.6 * dz / 2.3548;
}
//calculate discretized PSF
//isotropic voxel size of PSF - derived from resolution of reconstructed volume
const double size = res / reconstructor->_quality_factor;
//number of voxels in each direction
//the ROI is 2*voxel dimension
int xDim = round(2 * dx / size);
int yDim = round(2 * dy / size);
int zDim = round(2 * dz / size);
///test to make dimension always odd
xDim = xDim / 2 * 2 + 1;
yDim = yDim / 2 * 2 + 1;
zDim = zDim / 2 * 2 + 1;
//image corresponding to PSF
ImageAttributes attr;
attr._x = xDim;
attr._y = yDim;
attr._z = zDim;
attr._dx = size;
attr._dy = size;
attr._dz = size;
PSF.Initialize(attr);
//centre of PSF
double cx = 0.5 * (xDim - 1);
double cy = 0.5 * (yDim - 1);
double cz = 0.5 * (zDim - 1);
PSF.ImageToWorld(cx, cy, cz);
double sum = 0;
for (int i = 0; i < xDim; i++)
for (int j = 0; j < yDim; j++)
for (int k = 0; k < zDim; k++) {
double x = i;
double y = j;
double z = k;
PSF.ImageToWorld(x, y, z);
x -= cx;
y -= cy;
z -= cz;
//continuous PSF does not need to be normalized as discrete will be
PSF(i, j, k) = exp(-x * x / (2 * sigmax * sigmax) - y * y / (2 * sigmay * sigmay) - z * z / (2 * sigmaz * sigmaz));
sum += PSF(i, j, k);
}
PSF /= sum;
if (reconstructor->_debug && inputIndex == 0)
PSF.Write("PSF.nii.gz");
//prepare storage for PSF transformed and resampled to the space of reconstructed volume
//maximum dim of rotated kernel - the next higher odd integer plus two to accound for rounding error of tx,ty,tz.
//Note conversion from PSF image coordinates to tPSF image coordinates *size/res
int dim = floor(ceil(sqrt(double(xDim * xDim + yDim * yDim + zDim * zDim)) * size / res) / 2) * 2 + 1 + 2;
//prepare image attributes. Voxel dimension will be taken from the reconstructed volume
attr._x = dim;
attr._y = dim;
attr._z = dim;
attr._dx = res;
attr._dy = res;
attr._dz = res;
//create matrix from transformed PSF
tPSF.Initialize(attr);
//calculate centre of tPSF in image coordinates
const int centre = (dim - 1) / 2;
//for each voxel in current slice calculate matrix coefficients
bool excluded_slice = false;
for (size_t ff = 0; ff < reconstructor->_force_excluded.size(); ff++) {
if (inputIndex == reconstructor->_force_excluded[ff]) {
excluded_slice = true;
break;
}
}
for (int i = 0; i < global_slice.GetX(); i++)
for (int j = 0; j < global_slice.GetY(); j++)
if (reconstructor->_slices[inputIndex](i, j, 0) > -0.01 && reconstructor->_structural_slice_weight[inputIndex] > 0 && !excluded_slice) {
//calculate centrepoint of slice voxel in volume space (tx,ty,tz)
double x = i;
double y = j;
double z = 0;
global_slice.ImageToWorld(x, y, z);
if (!reconstructor->_ffd)
reconstructor->_transformations[inputIndex].Transform(x, y, z);
else
reconstructor->_mffd_transformations[inputIndex]->Transform(-1, 1, x, y, z);
global_reconstructed.WorldToImage(x, y, z);
int tx = round(x);
int ty = round(y);
int tz = round(z);
// Clear the transformed PSF
memset(tPSF.Data(), 0, sizeof(RealPixel) * tPSF.NumberOfVoxels());
//for each POINT3D of the PSF
for (int ii = 0; ii < xDim; ii++)
for (int jj = 0; jj < yDim; jj++)
for (int kk = 0; kk < zDim; kk++) {
//Calculate the position of the POINT3D of PSF centred over current slice voxel
//This is a bit complicated because slices can be oriented in any direction
//PSF image coordinates
x = ii;
y = jj;
z = kk;
//change to PSF world coordinates - now real sizes in mm
PSF.ImageToWorld(x, y, z);
//centre around the centrepoint of the PSF
x -= cx;
y -= cy;
z -= cz;
//Need to convert (x,y,z) to slice image coordinates because slices can have
//transformations included in them (they are nifti) and those are not reflected in
//PSF. In slice image coordinates we are sure that z is through-plane
//adjust according to voxel size
x /= dx;
y /= dy;
z /= dz;
//centre over current voxel
x += i;
y += j;
//convert from slice image coordinates to world coordinates
global_slice.ImageToWorld(x, y, z);
//Transform to space of reconstructed volume
if (!reconstructor->_ffd)
reconstructor->_transformations[inputIndex].Transform(x, y, z);
else
reconstructor->_mffd_transformations[inputIndex]->Transform(-1, 1, x, y, z);
//Change to image coordinates
global_reconstructed.WorldToImage(x, y, z);
//determine coefficients of volume voxels for position x,y,z
//using linear interpolation
//Find the 8 closest volume voxels
//lowest corner of the cube
int nx = (int)floor(x);
int ny = (int)floor(y);
int nz = (int)floor(z);
//not all neighbours might be in ROI, thus we need to normalize
//(l,m,n) are image coordinates of 8 neighbours in volume space
//for each we check whether it is in volume
sum = 0;
//to find wether the current slice voxel has overlap with ROI
bool inside = false;
for (int l = nx; l <= nx + 1; l++)
if ((l >= 0) && (l < global_reconstructed.GetX()))
for (int m = ny; m <= ny + 1; m++)
if ((m >= 0) && (m < global_reconstructed.GetY()))
for (int n = nz; n <= nz + 1; n++)
if ((n >= 0) && (n < global_reconstructed.GetZ())) {
const double weight = (1 - fabs(l - x)) * (1 - fabs(m - y)) * (1 - fabs(n - z));
sum += weight;
if (reconstructor->_mask(l, m, n) == 1) {
inside = true;
slice_inside = true;
}
}
//if there were no voxels do nothing
if (sum <= 0 || !inside)
continue;
//now calculate the transformed PSF
for (int l = nx; l <= nx + 1; l++)
if ((l >= 0) && (l < global_reconstructed.GetX()))
for (int m = ny; m <= ny + 1; m++)
if ((m >= 0) && (m < global_reconstructed.GetY()))
for (int n = nz; n <= nz + 1; n++)
if (n >= 0 && n < global_reconstructed.GetZ()) {
const double weight = (1 - fabs(l - x)) * (1 - fabs(m - y)) * (1 - fabs(n - z));
//image coordinates in tPSF
//(centre,centre,centre) in tPSF is aligned with (tx,ty,tz)
int aa = l - tx + centre;
int bb = m - ty + centre;
int cc = n - tz + centre;
//resulting value
const double value = PSF(ii, jj, kk) * weight / sum;
//Check that we are in tPSF
if (!(aa < 0 || aa >= dim || bb < 0 || bb >= dim || cc < 0 || cc >= dim))
//update transformed PSF
tPSF(aa, bb, cc) += value;
}
} //end of the loop for PSF points
//store tPSF values
for (int ii = 0; ii < dim; ii++)
for (int jj = 0; jj < dim; jj++)
for (int kk = 0; kk < dim; kk++)
if (tPSF(ii, jj, kk) > 0) {
POINT3D p;
p.x = ii + tx - centre;
p.y = jj + ty - centre;
p.z = kk + tz - centre;
p.value = tPSF(ii, jj, kk);
slicecoeffs[i][j].push_back(p);
}
} //end of loop for slice voxels
reconstructor->_volcoeffs[inputIndex] = slicecoeffs; //move(slicecoeffs);
reconstructor->_slice_inside[inputIndex] = slice_inside;
} //end of loop through the slices
}
void operator()() const {
parallel_for(blocked_range<size_t>(0, reconstructor->_slices.size()), *this);
}
};
//-------------------------------------------------------------------
/// Another version of CoeffInit
class CoeffInitSF {
Reconstruction *reconstructor;
size_t begin;
size_t end;
public:
CoeffInitSF(
Reconstruction *reconstructor,
size_t begin,
size_t end) :
reconstructor(reconstructor),
begin(begin),
end(end) {}
void operator()(const blocked_range<size_t>& r) const {
RealImage PSF, tPSF;
//get resolution of the volume
double vx, vy, vz;
reconstructor->_reconstructed.GetPixelSize(&vx, &vy, &vz);
//volume is always isotropic
const double& res = vx;
for (size_t inputIndex = r.begin(); inputIndex != r.end(); inputIndex++) {
const RealImage& slice = reconstructor->_withMB ? reconstructor->_slicesRwithMB[inputIndex] : reconstructor->_slices[inputIndex];
//prepare structures for storage
SLICECOEFFS slicecoeffs(slice.GetX(), Array<VOXELCOEFFS>(slice.GetY()));
//to check whether the slice has an overlap with mask ROI
bool slice_inside = false;
//PSF will be calculated in slice space in higher resolution
//get slice voxel size to define PSF
double dx, dy, dz;
slice.GetPixelSize(&dx, &dy, &dz);
//sigma of 3D Gaussian (sinc with FWHM=dx or dy in-plane, Gaussian with FWHM = dz through-plane)
double sigmax, sigmay, sigmaz;
switch (reconstructor->_recon_type) {
case _3D:
sigmax = 1.2 * dx / 2.3548;
sigmay = 1.2 * dy / 2.3548;
sigmaz = dz / 2.3548;
break;
case _1D:
sigmax = 0.5 * dx / 2.3548;
sigmay = 0.5 * dy / 2.3548;
sigmaz = dz / 2.3548;
break;
case _interpolate:
sigmax = sigmay = sigmaz = 0.5 * dx / 2.3548;
break;
}
//calculate discretized PSF
//isotropic voxel size of PSF - derived from resolution of reconstructed volume
double size = res / reconstructor->_quality_factor;
//number of voxels in each direction
//the ROI is 2*voxel dimension
int xDim = round(2 * dx / size);
int yDim = round(2 * dy / size);
int zDim = round(2 * dz / size);
///test to make dimension always odd
xDim = xDim / 2 * 2 + 1;
yDim = yDim / 2 * 2 + 1;
zDim = zDim / 2 * 2 + 1;
//image corresponding to PSF
ImageAttributes attr;
attr._x = xDim;
attr._y = yDim;
attr._z = zDim;
attr._dx = size;
attr._dy = size;
attr._dz = size;
PSF.Initialize(attr);
//centre of PSF
double cx = 0.5 * (xDim - 1);
double cy = 0.5 * (yDim - 1);
double cz = 0.5 * (zDim - 1);
PSF.ImageToWorld(cx, cy, cz);
double sum = 0;
for (int i = 0; i < xDim; i++)
for (int j = 0; j < yDim; j++)
for (int k = 0; k < zDim; k++) {
double x = i;
double y = j;
double z = k;
PSF.ImageToWorld(x, y, z);
x -= cx;
y -= cy;
z -= cz;
//continuous PSF does not need to be normalized as discrete will be
PSF(i, j, k) = exp(-x * x / (2 * sigmax * sigmax) - y * y / (2 * sigmay * sigmay) - z * z / (2 * sigmaz * sigmaz));
sum += PSF(i, j, k);
}
PSF /= sum;
if (reconstructor->_debug && inputIndex == 0)
PSF.Write("PSF.nii.gz");
//prepare storage for PSF transformed and resampled to the space of reconstructed volume
//maximum dim of rotated kernel - the next higher odd integer plus two to accound for rounding error of tx,ty,tz.
//Note conversion from PSF image coordinates to tPSF image coordinates *size/res
int dim = floor(ceil(sqrt(double(xDim * xDim + yDim * yDim + zDim * zDim)) * size / res) / 2) * 2 + 1 + 2;
//prepare image attributes. Voxel dimension will be taken from the reconstructed volume
attr._x = dim;
attr._y = dim;
attr._z = dim;
attr._dx = res;
attr._dy = res;
attr._dz = res;
//create matrix from transformed PSF
tPSF.Initialize(attr);
//calculate centre of tPSF in image coordinates
int centre = (dim - 1) / 2;
//for each voxel in current slice calculate matrix coefficients
for (int i = 0; i < slice.GetX(); i++)
for (int j = 0; j < slice.GetY(); j++)
if (slice(i, j, 0) > -0.01) {
//calculate centrepoint of slice voxel in volume space (tx,ty,tz)
double x = i;
double y = j;
double z = 0;
slice.ImageToWorld(x, y, z);
if (reconstructor->_withMB)
reconstructor->_transformationsRwithMB[inputIndex].Transform(x, y, z);
else
reconstructor->_transformations[inputIndex].Transform(x, y, z);
reconstructor->_reconstructed.WorldToImage(x, y, z);
int tx = round(x);
int ty = round(y);
int tz = round(z);
//Clear the transformed PSF
memset(tPSF.Data(), 0, sizeof(RealPixel) * tPSF.NumberOfVoxels());
//for each POINT3D of the PSF
for (int ii = 0; ii < xDim; ii++)
for (int jj = 0; jj < yDim; jj++)
for (int kk = 0; kk < zDim; kk++) {
//Calculate the position of the POINT3D of
//PSF centred over current slice voxel
//This is a bit complicated because slices
//can be oriented in any direction
//PSF image coordinates
x = ii;
y = jj;
z = kk;
//change to PSF world coordinates - now real sizes in mm
PSF.ImageToWorld(x, y, z);
//centre around the centrepoint of the PSF
x -= cx;
y -= cy;
z -= cz;
//Need to convert (x,y,z) to slice image
//coordinates because slices can have
//transformations included in them (they are
//nifti) and those are not reflected in
//PSF. In slice image coordinates we are
//sure that z is through-plane
//adjust according to voxel size
x /= dx;
y /= dy;
z /= dz;
//center over current voxel
x += i;
y += j;
//convert from slice image coordinates to world coordinates
slice.ImageToWorld(x, y, z);
//x+=(vx-cx); y+=(vy-cy); z+=(vz-cz);
//Transform to space of reconstructed volume
if (reconstructor->_withMB)
reconstructor->_transformationsRwithMB[inputIndex].Transform(x, y, z);
else
reconstructor->_transformations[inputIndex].Transform(x, y, z);
//Change to image coordinates
reconstructor->_reconstructed.WorldToImage(x, y, z);
//determine coefficients of volume voxels for position x,y,z
//using linear interpolation
//Find the 8 closest volume voxels
//lowest corner of the cube
int nx = (int)floor(x);
int ny = (int)floor(y);
int nz = (int)floor(z);
//not all neighbours might be in ROI, thus we need to normalize
//(l,m,n) are image coordinates of 8 neighbours in volume space
//for each we check whether it is in volume
sum = 0;
//to find wether the current slice voxel has overlap with ROI
bool inside = false;
for (int l = nx; l <= nx + 1; l++)
if ((l >= 0) && (l < reconstructor->_reconstructed.GetX()))
for (int m = ny; m <= ny + 1; m++)
if ((m >= 0) && (m < reconstructor->_reconstructed.GetY()))
for (int n = nz; n <= nz + 1; n++)
if ((n >= 0) && (n < reconstructor->_reconstructed.GetZ())) {
const double weight = (1 - fabs(l - x)) * (1 - fabs(m - y)) * (1 - fabs(n - z));
sum += weight;
if (reconstructor->_mask(l, m, n) == 1) {
inside = true;
slice_inside = true;
}
}
//if there were no voxels do nothing
if (sum <= 0 || !inside)
continue;
//now calculate the transformed PSF
for (int l = nx; l <= nx + 1; l++)
if ((l >= 0) && (l < reconstructor->_reconstructed.GetX()))
for (int m = ny; m <= ny + 1; m++)
if ((m >= 0) && (m < reconstructor->_reconstructed.GetY()))
for (int n = nz; n <= nz + 1; n++)
if ((n >= 0) && (n < reconstructor->_reconstructed.GetZ())) {
const double weight = (1 - fabs(l - x)) * (1 - fabs(m - y)) * (1 - fabs(n - z));
//image coordinates in tPSF
//(centre,centre,centre) in tPSF is aligned with (tx,ty,tz)
int aa = l - tx + centre;
int bb = m - ty + centre;
int cc = n - tz + centre;
//resulting value
const double value = PSF(ii, jj, kk) * weight / sum;
//Check that we are in tPSF
if (aa < 0 || aa >= dim || bb < 0 || bb >= dim || cc < 0 || cc >= dim) {
stringstream err;
err << "Error while trying to populate tPSF. " << aa << " " << bb << " " << cc << endl;
err << l << " " << m << " " << n << endl;
err << tx << " " << ty << " " << tz << endl;
err << centre << endl;
tPSF.Write("tPSF.nii.gz");
throw runtime_error(err.str());
} else
//update transformed PSF
tPSF(aa, bb, cc) += value;
}
} //end of the loop for PSF points
//store tPSF values
for (int ii = 0; ii < dim; ii++)
for (int jj = 0; jj < dim; jj++)
for (int kk = 0; kk < dim; kk++)
if (tPSF(ii, jj, kk) > 0) {
POINT3D p;
p.x = ii + tx - centre;
p.y = jj + ty - centre;
p.z = kk + tz - centre;
p.value = tPSF(ii, jj, kk);
slicecoeffs[i][j].push_back(p);
}
} //end of loop for slice voxels
// move assignment operation for slicecoeffs should have been more performant and memory efficient
// but it turned out that it consumes more memory and it's less performant (GCC 9.3.0)
reconstructor->_volcoeffsSF[inputIndex % reconstructor->_slicePerDyn] = slicecoeffs;
reconstructor->_slice_insideSF[inputIndex % reconstructor->_slicePerDyn] = slice_inside;
//cerr<<" Done "<<inputIndex % (reconstructor->_slicePerDyn)<<endl;
} //end of loop through the slices
}
void operator()() const {
parallel_for(blocked_range<size_t>(begin, end), *this);
}
};
//-------------------------------------------------------------------
class CoeffInitCardiac4D {
ReconstructionCardiac4D *reconstructor;
public:
CoeffInitCardiac4D(ReconstructionCardiac4D *reconstructor) : reconstructor(reconstructor) {}
void operator()(const blocked_range<size_t>& r) const {
RealImage PSF, tPSF;
//get resolution of the volume
double vx, vy, vz;
reconstructor->_reconstructed4D.GetPixelSize(&vx, &vy, &vz);
//volume is always isotropic
const double& res = vx;
for (size_t inputIndex = r.begin(); inputIndex != r.end(); inputIndex++) {
if (reconstructor->_slice_excluded[inputIndex])
continue;
//read the slice
RealImage& slice = reconstructor->_slices[inputIndex];
//prepare structures for storage
SLICECOEFFS slicecoeffs(slice.GetX(), Array<VOXELCOEFFS>(slice.GetY()));
//to check whether the slice has an overlap with mask ROI
bool slice_inside = false;
//start of a loop for a slice inputIndex
reconstructor->GetVerboseLog() << inputIndex << " ";
//PSF will be calculated in slice space in higher resolution
//get slice voxel size to define PSF
double dx, dy, dz;
slice.GetPixelSize(&dx, &dy, &dz);
//sigma of 3D Gaussian (sinc with FWHM=dx or dy in-plane, Gaussian with FWHM = dz through-plane)
double sigmax, sigmay, sigmaz;
switch (reconstructor->_recon_type) {
case _3D:
sigmax = 1.2 * dx / 2.3548;
sigmay = 1.2 * dy / 2.3548;
sigmaz = dz / 2.3548;
break;
case _1D:
sigmax = 0.5 * dx / 2.3548;
sigmay = 0.5 * dy / 2.3548;
sigmaz = dz / 2.3548;
break;
case _interpolate:
sigmax = sigmay = sigmaz = 0.5 * dx / 2.3548;
break;
}
if (reconstructor->_no_sr) {
sigmax = 0.5 * dx / 2.3548; // 1.2
sigmay = 0.5 * dy / 2.3548; // 1.2
sigmaz = 0.5 * dz / 2.3548; // 1
}
//calculate discretized PSF
//isotropic voxel size of PSF - derived from resolution of reconstructed volume
const double size = res / reconstructor->_quality_factor;
//number of voxels in each direction
//the ROI is 2*voxel dimension
int xDim = round(2 * dx / size);
int yDim = round(2 * dy / size);
int zDim = round(2 * dz / size);
///test to make dimension always odd
xDim = xDim / 2 * 2 + 1;
yDim = yDim / 2 * 2 + 1;
zDim = zDim / 2 * 2 + 1;
///end test
//image corresponding to PSF
ImageAttributes attr;
attr._x = xDim;
attr._y = yDim;
attr._z = zDim;
attr._dx = size;
attr._dy = size;
attr._dz = size;
PSF.Initialize(attr);
//centre of PSF
double cx, cy, cz;
cx = 0.5 * (xDim - 1);
cy = 0.5 * (yDim - 1);
cz = 0.5 * (zDim - 1);
PSF.ImageToWorld(cx, cy, cz);
double sum = 0;
for (int i = 0; i < xDim; i++)
for (int j = 0; j < yDim; j++)
for (int k = 0; k < zDim; k++) {
double x = i;
double y = j;
double z = k;
PSF.ImageToWorld(x, y, z);
x -= cx;
y -= cy;
z -= cz;
//continuous PSF does not need to be normalized as discrete will be
PSF(i, j, k) = exp(-x * x / (2 * sigmax * sigmax) - y * y / (2 * sigmay * sigmay) - z * z / (2 * sigmaz * sigmaz));
sum += PSF(i, j, k);
}
PSF /= sum;
if (reconstructor->_debug && inputIndex == 0)
PSF.Write("PSF.nii.gz");
//prepare storage for PSF transformed and resampled to the space of reconstructed volume
//maximum dim of rotated kernel - the next higher odd integer plus two to accound for rounding error of tx,ty,tz.
//Note conversion from PSF image coordinates to tPSF image coordinates *size/res
int dim = (floor(ceil(sqrt(double(xDim * xDim + yDim * yDim + zDim * zDim)) * size / res) / 2)) * 2 + 1 + 2;
//prepare image attributes. Voxel dimension will be taken from the reconstructed volume
attr._x = dim;
attr._y = dim;
attr._z = dim;
attr._dx = res;
attr._dy = res;
attr._dz = res;
//create matrix from transformed PSF
tPSF.Initialize(attr);
//calculate centre of tPSF in image coordinates
int centre = (dim - 1) / 2;
//for each voxel in current slice calculate matrix coefficients
for (int i = 0; i < slice.GetX(); i++)
for (int j = 0; j < slice.GetY(); j++)
if (slice(i, j, 0) != -1) {
//calculate centrepoint of slice voxel in volume space (tx,ty,tz)
double x = i;
double y = j;
double z = 0;
slice.ImageToWorld(x, y, z);
reconstructor->_transformations[inputIndex].Transform(x, y, z);
reconstructor->_reconstructed4D.WorldToImage(x, y, z);
int tx = round(x);
int ty = round(y);
int tz = round(z);
//Clear the transformed PSF
memset(tPSF.Data(), 0, sizeof(RealPixel) * tPSF.NumberOfVoxels());
//for each POINT3D of the PSF
for (int ii = 0; ii < xDim; ii++)
for (int jj = 0; jj < yDim; jj++)
for (int kk = 0; kk < zDim; kk++) {
//Calculate the position of the POINT3D of
//PSF centred over current slice voxel
//This is a bit complicated because slices
//can be oriented in any direction
//PSF image coordinates
x = ii;
y = jj;
z = kk;
//change to PSF world coordinates - now real sizes in mm
PSF.ImageToWorld(x, y, z);
//centre around the centrepoint of the PSF
x -= cx;
y -= cy;
z -= cz;
//Need to convert (x,y,z) to slice image
//coordinates because slices can have
//transformations included in them (they are
//nifti) and those are not reflected in
//PSF. In slice image coordinates we are
//sure that z is through-plane
//adjust according to voxel size
x /= dx;
y /= dy;
z /= dz;
//center over current voxel
x += i;
y += j;
//convert from slice image coordinates to world coordinates
slice.ImageToWorld(x, y, z);
//x+=(vx-cx); y+=(vy-cy); z+=(vz-cz);
//Transform to space of reconstructed volume
reconstructor->_transformations[inputIndex].Transform(x, y, z);
//Change to image coordinates
reconstructor->_reconstructed4D.WorldToImage(x, y, z);
//determine coefficients of volume voxels for position x,y,z
//using linear interpolation
//Find the 8 closest volume voxels
//lowest corner of the cube
int nx = (int)floor(x);
int ny = (int)floor(y);
int nz = (int)floor(z);
//not all neighbours might be in ROI, thus we need to normalize
//(l,m,n) are image coordinates of 8 neighbours in volume space
//for each we check whether it is in volume
sum = 0;
//to find wether the current slice voxel has overlap with ROI
bool inside = false;
for (int l = nx; l <= nx + 1; l++)
if ((l >= 0) && (l < reconstructor->_reconstructed4D.GetX()))
for (int m = ny; m <= ny + 1; m++)
if ((m >= 0) && (m < reconstructor->_reconstructed4D.GetY()))
for (int n = nz; n <= nz + 1; n++)
if ((n >= 0) && (n < reconstructor->_reconstructed4D.GetZ())) {
const double weight = (1 - fabs(l - x)) * (1 - fabs(m - y)) * (1 - fabs(n - z));
sum += weight;
if (reconstructor->_mask(l, m, n) == 1) {
inside = true;
slice_inside = true;
}
}
//if there were no voxels do nothing
if (sum <= 0 || !inside)
continue;
//now calculate the transformed PSF
for (int l = nx; l <= nx + 1; l++)
if ((l >= 0) && (l < reconstructor->_reconstructed4D.GetX()))
for (int m = ny; m <= ny + 1; m++)
if ((m >= 0) && (m < reconstructor->_reconstructed4D.GetY()))
for (int n = nz; n <= nz + 1; n++)
if (n >= 0 && n < reconstructor->_reconstructed4D.GetZ()) {
const double weight = (1 - fabs(l - x)) * (1 - fabs(m - y)) * (1 - fabs(n - z));
//image coordinates in tPSF
//(centre,centre,centre) in tPSF is aligned with (tx,ty,tz)
int aa = l - tx + centre;
int bb = m - ty + centre;
int cc = n - tz + centre;
//resulting value
const double value = PSF(ii, jj, kk) * weight / sum;
//Check that we are in tPSF
if (aa < 0 || aa >= dim || bb < 0 || bb >= dim || cc < 0 || cc >= dim) {
stringstream err;
err << "Error while trying to populate tPSF. " << aa << " " << bb << " " << cc << endl;
err << l << " " << m << " " << n << endl;
err << tx << " " << ty << " " << tz << endl;
err << centre << endl;
tPSF.Write("tPSF.nii.gz");
throw runtime_error(err.str());
} else
//update transformed PSF
tPSF(aa, bb, cc) += value;
}
} //end of the loop for PSF points
//store tPSF values
for (int ii = 0; ii < dim; ii++)
for (int jj = 0; jj < dim; jj++)
for (int kk = 0; kk < dim; kk++)
if (tPSF(ii, jj, kk) > 0) {
POINT3D p;
p.x = ii + tx - centre;
p.y = jj + ty - centre;
p.z = kk + tz - centre;
p.value = tPSF(ii, jj, kk);
slicecoeffs[i][j].push_back(p);
}
} //end of loop for slice voxels
// move assignment operation for slicecoeffs should have been more performant and memory efficient
// but it turned out that it consumes more memory and it's less performant (GCC 9.3.0)
reconstructor->_volcoeffs[inputIndex] = slicecoeffs;
reconstructor->_slice_inside[inputIndex] = slice_inside;
} //end of loop through the slices
}
void operator()() const {
parallel_for(blocked_range<size_t>(0, reconstructor->_slices.size()), *this);
}
};
//-------------------------------------------------------------------
class SimulateStacksCardiac4D {
ReconstructionCardiac4D *reconstructor;
public:
SimulateStacksCardiac4D(ReconstructionCardiac4D *reconstructor) : reconstructor(reconstructor) {}
void operator()(const blocked_range<size_t>& r) const {
RealImage PSF, tPSF;
//get resolution of the volume
double vx, vy, vz;
reconstructor->_reconstructed4D.GetPixelSize(&vx, &vy, &vz);
//volume is always isotropic
const double& res = vx;
for (size_t inputIndex = r.begin(); inputIndex != r.end(); inputIndex++) {
if (reconstructor->_slice_excluded[inputIndex])
continue;
reconstructor->GetVerboseLog() << inputIndex << " ";
//read the slice
RealImage& slice = reconstructor->_slices[inputIndex];
//prepare structures for storage
SLICECOEFFS slicecoeffs(slice.GetX(), Array<VOXELCOEFFS>(slice.GetY()));
//PSF will be calculated in slice space in higher resolution
//get slice voxel size to define PSF
double dx, dy, dz;
slice.GetPixelSize(&dx, &dy, &dz);
//sigma of 3D Gaussian (sinc with FWHM=dx or dy in-plane, Gaussian with FWHM = dz through-plane)
double sigmax, sigmay, sigmaz;
if (reconstructor->_recon_type == _3D) {
sigmax = 1.2 * dx / 2.3548;
sigmay = 1.2 * dy / 2.3548;
sigmaz = dz / 2.3548;
}
if (reconstructor->_recon_type == _1D) {
sigmax = 0.5 * dx / 2.3548;
sigmay = 0.5 * dy / 2.3548;
sigmaz = dz / 2.3548;
}
if (reconstructor->_recon_type == _interpolate) {
sigmax = 0.5 * dx / 2.3548;
sigmay = 0.5 * dx / 2.3548;
sigmaz = 0.5 * dx / 2.3548;
}
//calculate discretized PSF
//isotropic voxel size of PSF - derived from resolution of reconstructed volume
double size = res / reconstructor->_quality_factor;
//number of voxels in each direction
//the ROI is 2*voxel dimension
int xDim = round(2 * dx / size);
int yDim = round(2 * dy / size);
int zDim = round(2 * dz / size);
///test to make dimension always odd
xDim = xDim / 2 * 2 + 1;
yDim = yDim / 2 * 2 + 1;
zDim = zDim / 2 * 2 + 1;
///end test
//image corresponding to PSF
ImageAttributes attr;
attr._x = xDim;
attr._y = yDim;
attr._z = zDim;
attr._dx = size;
attr._dy = size;
attr._dz = size;
PSF.Initialize(attr);
//centre of PSF
double cx, cy, cz;
cx = 0.5 * (xDim - 1);
cy = 0.5 * (yDim - 1);
cz = 0.5 * (zDim - 1);
PSF.ImageToWorld(cx, cy, cz);
double x, y, z;
double sum = 0;
int i, j, k;
for (i = 0; i < xDim; i++)
for (j = 0; j < yDim; j++)
for (k = 0; k < zDim; k++) {
x = i;
y = j;
z = k;
PSF.ImageToWorld(x, y, z);
x -= cx;
y -= cy;
z -= cz;
//continuous PSF does not need to be normalized as discrete will be
PSF(i, j, k) = exp(-x * x / (2 * sigmax * sigmax) - y * y / (2 * sigmay * sigmay) - z * z / (2 * sigmaz * sigmaz));
sum += PSF(i, j, k);
}
PSF /= sum;
if (reconstructor->_debug)
if (inputIndex == 0)
PSF.Write("PSF.nii.gz");
//prepare storage for PSF transformed and resampled to the space of reconstructed volume
//maximum dim of rotated kernel - the next higher odd integer plus two to accound for rounding error of tx,ty,tz.
//Note conversion from PSF image coordinates to tPSF image coordinates *size/res
int dim = (floor(ceil(sqrt(double(xDim * xDim + yDim * yDim + zDim * zDim)) * size / res) / 2)) * 2 + 1 + 2;
//prepare image attributes. Voxel dimension will be taken from the reconstructed volume
attr._x = dim;
attr._y = dim;
attr._z = dim;
attr._dx = res;
attr._dy = res;
attr._dz = res;
//create matrix from transformed PSF
tPSF.Initialize(attr);
//calculate centre of tPSF in image coordinates
int centre = (dim - 1) / 2;
//for each voxel in current slice calculate matrix coefficients
int ii, jj, kk;
int tx, ty, tz;
int nx, ny, nz;
int l, m, n;
for (i = 0; i < slice.GetX(); i++)
for (j = 0; j < slice.GetY(); j++)
if (slice(i, j, 0) != -1) {
//calculate centrepoint of slice voxel in volume space (tx,ty,tz)
x = i;
y = j;
z = 0;
slice.ImageToWorld(x, y, z);
reconstructor->_transformations[inputIndex].Transform(x, y, z);
reconstructor->_reconstructed4D.WorldToImage(x, y, z);
tx = round(x);
ty = round(y);
tz = round(z);
//Clear the transformed PSF
memset(tPSF.Data(), 0, sizeof(RealPixel) * tPSF.NumberOfVoxels());
//for each POINT3D of the PSF
for (ii = 0; ii < xDim; ii++)
for (jj = 0; jj < yDim; jj++)
for (kk = 0; kk < zDim; kk++) {
//Calculate the position of the POINT3D of
//PSF centred over current slice voxel
//This is a bit complicated because slices
//can be oriented in any direction
//PSF image coordinates
x = ii;
y = jj;
z = kk;
//change to PSF world coordinates - now real sizes in mm
PSF.ImageToWorld(x, y, z);
//centre around the centrepoint of the PSF
x -= cx;
y -= cy;
z -= cz;
//Need to convert (x,y,z) to slice image
//coordinates because slices can have
//transformations included in them (they are
//nifti) and those are not reflected in
//PSF. In slice image coordinates we are
//sure that z is through-plane
//adjust according to voxel size
x /= dx;
y /= dy;
z /= dz;
//center over current voxel
x += i;
y += j;
//convert from slice image coordinates to world coordinates
slice.ImageToWorld(x, y, z);
//x+=(vx-cx); y+=(vy-cy); z+=(vz-cz);
//Transform to space of reconstructed volume
reconstructor->_transformations[inputIndex].Transform(x, y, z);
//Change to image coordinates
reconstructor->_reconstructed4D.WorldToImage(x, y, z);
//determine coefficients of volume voxels for position x,y,z
//using linear interpolation
//Find the 8 closest volume voxels
//lowest corner of the cube
nx = (int)floor(x);
ny = (int)floor(y);
nz = (int)floor(z);
//not all neighbours might be in ROI, thus we need to normalize
//(l,m,n) are image coordinates of 8 neighbours in volume space
//for each we check whether it is in volume
sum = 0;
//to find wether the current slice voxel has overlap with ROI
bool inside = false;
for (l = nx; l <= nx + 1; l++)
if ((l >= 0) && (l < reconstructor->_reconstructed4D.GetX()))
for (m = ny; m <= ny + 1; m++)
if ((m >= 0) && (m < reconstructor->_reconstructed4D.GetY()))
for (n = nz; n <= nz + 1; n++)
if ((n >= 0) && (n < reconstructor->_reconstructed4D.GetZ())) {
const double weight = (1 - fabs(l - x)) * (1 - fabs(m - y)) * (1 - fabs(n - z));
sum += weight;
if (reconstructor->_mask(l, m, n) == 1)
inside = true;
}
//if there were no voxels do nothing
if (sum <= 0 || !inside)
continue;
//now calculate the transformed PSF
for (l = nx; l <= nx + 1; l++)
if ((l >= 0) && (l < reconstructor->_reconstructed4D.GetX()))
for (m = ny; m <= ny + 1; m++)
if ((m >= 0) && (m < reconstructor->_reconstructed4D.GetY()))
for (n = nz; n <= nz + 1; n++)
if ((n >= 0) && (n < reconstructor->_reconstructed4D.GetZ())) {
const double weight = (1 - fabs(l - x)) * (1 - fabs(m - y)) * (1 - fabs(n - z));
//image coordinates in tPSF
//(centre,centre,centre) in tPSF is aligned with (tx,ty,tz)
int aa = l - tx + centre;
int bb = m - ty + centre;
int cc = n - tz + centre;
//resulting value
double value = PSF(ii, jj, kk) * weight / sum;
//Check that we are in tPSF
if ((aa < 0) || (aa >= dim) || (bb < 0) || (bb >= dim) || (cc < 0) || (cc >= dim)) {
stringstream err;
err << "Error while trying to populate tPSF. " << aa << " " << bb << " " << cc << endl;
err << l << " " << m << " " << n << endl;
err << tx << " " << ty << " " << tz << endl;
err << centre << endl;
tPSF.Write("tPSF.nii.gz");
throw runtime_error(err.str());
} else
//update transformed PSF
tPSF(aa, bb, cc) += value;
}
} //end of the loop for PSF points
//store tPSF values
for (ii = 0; ii < dim; ii++)
for (jj = 0; jj < dim; jj++)
for (kk = 0; kk < dim; kk++)
if (tPSF(ii, jj, kk) > 0) {
POINT3D p;
p.x = ii + tx - centre;
p.y = jj + ty - centre;
p.z = kk + tz - centre;
p.value = tPSF(ii, jj, kk);
slicecoeffs[i][j].push_back(p);
}
} //end of loop for slice voxels
//Calculate simulated slice
reconstructor->_simulated_slices[inputIndex].Initialize(reconstructor->_slices[inputIndex].Attributes());
reconstructor->_simulated_weights[inputIndex].Initialize(reconstructor->_slices[inputIndex].Attributes());
for (int i = 0; i < reconstructor->_slices[inputIndex].GetX(); i++)
for (int j = 0; j < reconstructor->_slices[inputIndex].GetY(); j++)
if (reconstructor->_slices[inputIndex](i, j, 0) != -1) {
double weight = 0;
const size_t n = slicecoeffs[i][j].size();
for (size_t k = 0; k < n; k++) {
const POINT3D& p = slicecoeffs[i][j][k];
for (int outputIndex = 0; outputIndex < reconstructor->_reconstructed4D.GetT(); outputIndex++) {
reconstructor->_simulated_slices[inputIndex](i, j, 0) += reconstructor->_slice_temporal_weight[outputIndex][inputIndex] * p.value * reconstructor->_reconstructed4D(p.x, p.y, p.z, outputIndex);
weight += reconstructor->_slice_temporal_weight[outputIndex][inputIndex] * p.value;
}
}
if (weight > 0) {
reconstructor->_simulated_slices[inputIndex](i, j, 0) /= weight;
reconstructor->_simulated_weights[inputIndex](i, j, 0) = weight;
}
}
} //end of loop through the slices
}
void operator()() const {
parallel_for(blocked_range<size_t>(0, reconstructor->_slices.size()), *this);
}
};
//-------------------------------------------------------------------
/// Class for EStep (RS)
class EStep {
Reconstruction *reconstructor;
Array<double>& slice_potential;
public:
EStep(Reconstruction *reconstructor,
Array<double>& slice_potential) :
reconstructor(reconstructor),
slice_potential(slice_potential) {}
void operator()(const blocked_range<size_t>& r) const {
RealImage slice;
for (size_t inputIndex = r.begin(); inputIndex < r.end(); inputIndex++) {
// read the current slice
slice = reconstructor->_slices[inputIndex];
//read current weight image
RealImage& weight = reconstructor->_weights[inputIndex];
memset(weight.Data(), 0, sizeof(RealPixel) * weight.NumberOfVoxels());
double num = 0;
//Calculate error, voxel weights, and slice potential
for (size_t i = 0; i < reconstructor->_volcoeffs[inputIndex].size(); i++)
for (size_t j = 0; j < reconstructor->_volcoeffs[inputIndex][i].size(); j++)
if (slice(i, j, 0) > -0.01) {
//bias correct and scale the slice
slice(i, j, 0) *= exp(-reconstructor->_bias[inputIndex](i, j, 0)) * reconstructor->_scale[inputIndex];
//number of volumetric voxels to which
// current slice voxel contributes
const size_t n = reconstructor->_volcoeffs[inputIndex][i][j].size();
// if n == 0, slice voxel has no overlap with volumetric ROI, do not process it
if (n > 0 && reconstructor->_simulated_weights[inputIndex](i, j, 0) > 0) {
slice(i, j, 0) -= reconstructor->_simulated_slices[inputIndex](i, j, 0);
//calculate norm and voxel-wise weights
//Gaussian distribution for inliers (likelihood)
const double g = reconstructor->G(slice(i, j, 0), reconstructor->_sigma);
//Uniform distribution for outliers (likelihood)
const double m = reconstructor->M(reconstructor->_m);
//voxel_wise posterior
const double w = g * reconstructor->_mix / (g * reconstructor->_mix + m * (1 - reconstructor->_mix));
weight.PutAsDouble(i, j, 0, w);
//calculate slice potentials
if (reconstructor->_simulated_weights[inputIndex](i, j, 0) > 0.99) {
slice_potential[inputIndex] += (1 - w) * (1 - w);
num++;
}
} else
weight.PutAsDouble(i, j, 0, 0);
}
//evaluate slice potential
if (num > 0)
slice_potential[inputIndex] = sqrt(slice_potential[inputIndex] / num);
else
slice_potential[inputIndex] = -1; // slice has no unpadded voxels
}
}
void operator()() const {
parallel_for(blocked_range<size_t>(0, reconstructor->_slices.size()), *this);
}
};
//-------------------------------------------------------------------
/// E-step (todo: optimise for velocity)
class EStepCardiacVelocity4D {
ReconstructionCardiacVelocity4D *reconstructor;
Array<double>& slice_potential;
public:
EStepCardiacVelocity4D(
ReconstructionCardiacVelocity4D *reconstructor,
Array<double>& slice_potential) :
reconstructor(reconstructor),
slice_potential(slice_potential) {}
void operator()(const blocked_range<size_t>& r) const {
for (size_t inputIndex = r.begin(); inputIndex < r.end(); inputIndex++) {
// read the current slice
const RealImage& current_slice = reconstructor->_slices[inputIndex];
RealImage slice = current_slice - reconstructor->_simulated_slices[inputIndex];
memset(reconstructor->_weights[inputIndex].Data(), 0, sizeof(RealPixel) * reconstructor->_weights[inputIndex].NumberOfVoxels());
for (int i = 0; i < current_slice.GetX(); i++)
for (int j = 0; j < current_slice.GetY(); j++)
if (current_slice(i, j, 0) < -10)
slice(i, j, 0) = -15;
double num = 0;
//Calculate error, voxel weights, and slice potential
for (size_t i = 0; i < reconstructor->_volcoeffs[inputIndex].size(); i++)
for (size_t j = 0; j < reconstructor->_volcoeffs[inputIndex][i].size(); j++)
if (slice(i, j, 0) > -10) {
//number of volumetric voxels to which
// current slice voxel contributes
const int n = reconstructor->_volcoeffs[inputIndex][i][j].size();
// if n == 0, slice voxel has no overlap with volumetric ROI, do not process it
if (n > 0 && reconstructor->_simulated_weights[inputIndex](i, j, 0) > 0) {
//calculate norm and voxel-wise weights
//Gaussian distribution for inliers (likelihood)
const double g = reconstructor->G(slice(i, j, 0), reconstructor->_sigma);
//Uniform distribution for outliers (likelihood)
const double m = reconstructor->M(reconstructor->_m);
//voxel_wise posterior
const double weight = g * reconstructor->_mix / (g * reconstructor->_mix + m * (1 - reconstructor->_mix));
reconstructor->_weights[inputIndex].PutAsDouble(i, j, 0, weight);
//calculate slice potentials
if (reconstructor->_simulated_weights[inputIndex](i, j, 0) > 0.99) {
slice_potential[inputIndex] += (1 - weight) * (1 - weight);
num++;
}
} else
reconstructor->_weights[inputIndex].PutAsDouble(i, j, 0, 0);
}
//evaluate slice potential
if (num > 0)
slice_potential[inputIndex] = sqrt(slice_potential[inputIndex] / num);
else
slice_potential[inputIndex] = -1; // slice has no unpadded voxels
}
}
// execute
void operator() () const {
parallel_for(blocked_range<size_t>(0, reconstructor->_slices.size()), *this);
}
};
//-------------------------------------------------------------------
/// Class for slice scale calculation
class Scale {
Reconstruction *reconstructor;
public:
Scale(Reconstruction *reconstructor) : reconstructor(reconstructor) {}
void operator()(const blocked_range<size_t>& r) const {
for (size_t inputIndex = r.begin(); inputIndex != r.end(); inputIndex++) {
//alias the current bias image
const RealImage& b = reconstructor->_bias[inputIndex];
//initialise calculation of scale
double scalenum = 0;
double scaleden = 0;
for (int i = 0; i < reconstructor->_slices[inputIndex].GetX(); i++)
for (int j = 0; j < reconstructor->_slices[inputIndex].GetY(); j++)
if (reconstructor->_slices[inputIndex](i, j, 0) > -0.01) {
if (reconstructor->_simulated_weights[inputIndex](i, j, 0) > 0.99) {
//scale - intensity matching
const double eb = exp(-b(i, j, 0));
scalenum += reconstructor->_weights[inputIndex](i, j, 0) * reconstructor->_slices[inputIndex](i, j, 0) * eb * reconstructor->_simulated_slices[inputIndex](i, j, 0);
scaleden += reconstructor->_weights[inputIndex](i, j, 0) * reconstructor->_slices[inputIndex](i, j, 0) * eb * reconstructor->_slices[inputIndex](i, j, 0) * eb;
}
}
//calculate scale for this slice
reconstructor->_scale[inputIndex] = scaleden > 0 ? scalenum / scaleden : 1;
} //end of loop for a slice inputIndex
}
void operator()() const {
parallel_for(blocked_range<size_t>(0, reconstructor->_slices.size()), *this);
}
};
//-------------------------------------------------------------------
/// Class for slice bias calculation
class Bias {
Reconstruction *reconstructor;
public:
Bias(Reconstruction *reconstructor) : reconstructor(reconstructor) {}
void operator()(const blocked_range<size_t>& r) const {
RealImage slice, wb, wresidual;
GaussianBlurring<RealPixel> gb(reconstructor->_sigma_bias);
for (size_t inputIndex = r.begin(); inputIndex < r.end(); inputIndex++) {
// read the current slice
slice = reconstructor->_slices[inputIndex];
//alias the current bias image
RealImage& b = reconstructor->_bias[inputIndex];
//prepare weight image for bias field
wb = reconstructor->_weights[inputIndex];
wresidual.Initialize(slice.Attributes());
for (int i = 0; i < slice.GetX(); i++)
for (int j = 0; j < slice.GetY(); j++)
if (slice(i, j, 0) > -0.01) {
if (reconstructor->_simulated_weights[inputIndex](i, j, 0) > 0.99) {
//bias-correct and scale current slice
const double eb = exp(-b(i, j, 0));
slice(i, j, 0) *= eb * reconstructor->_scale[inputIndex];
//calculate weight image
wb(i, j, 0) *= slice(i, j, 0);
//calculate weighted residual image make sure it is far from zero to avoid numerical instability
if ((reconstructor->_simulated_slices[inputIndex](i, j, 0) > 1) && (slice(i, j, 0) > 1))
wresidual(i, j, 0) = log(slice(i, j, 0) / reconstructor->_simulated_slices[inputIndex](i, j, 0)) * wb(i, j, 0);
} else {
//do not take into account this voxel when calculating bias field
wresidual(i, j, 0) = 0;
wb(i, j, 0) = 0;
}
}
//calculate bias field for this slice
//smooth weighted residual
gb.Input(&wresidual);
gb.Output(&wresidual);
gb.Run();
//smooth weight image
gb.Input(&wb);
gb.Output(&wb);
gb.Run();
//update bias field
double sum = 0;
double num = 0;
for (int i = 0; i < slice.GetX(); i++)
for (int j = 0; j < slice.GetY(); j++)
if (slice(i, j, 0) > -0.01) {
if (wb(i, j, 0) > 0)
b(i, j, 0) += wresidual(i, j, 0) / wb(i, j, 0);
sum += b(i, j, 0);
num++;
}
//normalize bias field to have zero mean
if (!reconstructor->_global_bias_correction && num > 0) {
const double mean = sum / num;
for (int i = 0; i < slice.GetX(); i++)
for (int j = 0; j < slice.GetY(); j++)
if (slice(i, j, 0) > -0.01)
b(i, j, 0) -= mean;
}
}
}
void operator()() const {
parallel_for(blocked_range<size_t>(0, reconstructor->_slices.size()), *this);
}
};
//-------------------------------------------------------------------
/// Class for SR reconstruction
class Superresolution {
Reconstruction *reconstructor;
public:
RealImage confidence_map;
RealImage addon;
Superresolution(Reconstruction *reconstructor) : reconstructor(reconstructor) {
//Clear addon
addon.Initialize(reconstructor->_reconstructed.Attributes());
//Clear confidence map
confidence_map.Initialize(reconstructor->_reconstructed.Attributes());
}
Superresolution(Superresolution& x, split) : Superresolution(x.reconstructor) {}
void operator()(const blocked_range<size_t>& r) {
//Update reconstructed volume using current slice
for (size_t inputIndex = r.begin(); inputIndex < r.end(); inputIndex++) {
//Distribute error to the volume
for (size_t i = 0; i < reconstructor->_volcoeffs[inputIndex].size(); i++)
for (size_t j = 0; j < reconstructor->_volcoeffs[inputIndex][i].size(); j++)
if (reconstructor->_slices[inputIndex](i, j, 0) > -0.01) {
if (reconstructor->_simulated_slices[inputIndex](i, j, 0) < 0.01)
reconstructor->_slice_dif[inputIndex](i, j, 0) = 0;
#pragma omp simd
for (size_t k = 0; k < reconstructor->_volcoeffs[inputIndex][i][j].size(); k++) {
const POINT3D& p = reconstructor->_volcoeffs[inputIndex][i][j][k];
const auto multiplier = reconstructor->_robust_slices_only ? 1 : reconstructor->_weights[inputIndex](i, j, 0);
double ssim_weight = 1;
if (reconstructor->_structural)
ssim_weight = reconstructor->_slice_ssim_maps[inputIndex](i, j, 0);
bool include_flag = true;
if (reconstructor->_ffd) {
double jac = reconstructor->_mffd_transformations[inputIndex]->Jacobian(p.x, p.y, p.z, 0, 0);
if ((100*jac) < 60)
include_flag = false;
}
if (include_flag) {
addon(p.x, p.y, p.z) += ssim_weight * multiplier * p.value * reconstructor->_slice_weight[inputIndex] * reconstructor->_slice_dif[inputIndex](i, j, 0);
confidence_map(p.x, p.y, p.z) += ssim_weight * multiplier * p.value * reconstructor->_slice_weight[inputIndex];
}
}
}
} //end of loop for a slice inputIndex
}
void join(const Superresolution& y) {
addon += y.addon;
confidence_map += y.confidence_map;
}
void operator()() {
parallel_reduce(blocked_range<size_t>(0, reconstructor->_slices.size()), *this);
}
};
//-------------------------------------------------------------------
class SuperresolutionCardiac4D {
ReconstructionCardiac4D *reconstructor;
public:
RealImage confidence_map;
RealImage addon;
SuperresolutionCardiac4D(ReconstructionCardiac4D *reconstructor) : reconstructor(reconstructor) {
//Clear addon
addon.Initialize(reconstructor->_reconstructed4D.Attributes());
//Clear confidence map
confidence_map.Initialize(reconstructor->_reconstructed4D.Attributes());
}
SuperresolutionCardiac4D(SuperresolutionCardiac4D& x, split) : SuperresolutionCardiac4D(x.reconstructor) {}
void operator()(const blocked_range<size_t>& r) {
RealImage slice;
for (size_t inputIndex = r.begin(); inputIndex < r.end(); inputIndex++) {
if (reconstructor->_volcoeffs[inputIndex].empty())
continue;
// read the current slice
slice = reconstructor->_slices[inputIndex];
//Update reconstructed volume using current slice
//Distribute error to the volume
for (size_t i = 0; i < reconstructor->_volcoeffs[inputIndex].size(); i++)
for (size_t j = 0; j < reconstructor->_volcoeffs[inputIndex][i].size(); j++)
if (slice(i, j, 0) != -1) {
//bias correct and scale the slice
slice(i, j, 0) *= exp(-reconstructor->_bias[inputIndex](i, j, 0)) * reconstructor->_scale[inputIndex];
if (reconstructor->_simulated_slices[inputIndex](i, j, 0) > 0)
slice(i, j, 0) -= reconstructor->_simulated_slices[inputIndex](i, j, 0);
else
slice(i, j, 0) = 0;
#pragma omp simd
for (size_t k = 0; k < reconstructor->_volcoeffs[inputIndex][i][j].size(); k++) {
const POINT3D& p = reconstructor->_volcoeffs[inputIndex][i][j][k];
for (int outputIndex = 0; outputIndex < reconstructor->_reconstructed4D.GetT(); outputIndex++) {
const auto multiplier = reconstructor->_robust_slices_only ? 1 : reconstructor->_weights[inputIndex](i, j, 0);
addon(p.x, p.y, p.z, outputIndex) += reconstructor->_slice_temporal_weight[outputIndex][inputIndex] * p.value * slice(i, j, 0) * multiplier * reconstructor->_slice_weight[inputIndex];
confidence_map(p.x, p.y, p.z, outputIndex) += reconstructor->_slice_temporal_weight[outputIndex][inputIndex] * p.value * multiplier * reconstructor->_slice_weight[inputIndex];
}
}
}
} //end of loop for a slice inputIndex
}
void join(const SuperresolutionCardiac4D& y) {
addon += y.addon;
confidence_map += y.confidence_map;
}
void operator()() {
parallel_reduce(blocked_range<size_t>(0, reconstructor->_slices.size()), *this);
}
};
//-------------------------------------------------------------------
/// Gradient descend step of velocity estimation
class SuperresolutionCardiacVelocity4D {
ReconstructionCardiacVelocity4D *reconstructor;
public:
Array<RealImage> confidence_maps;
Array<RealImage> addons_p;
Array<RealImage> addons_n;
Array<RealImage> addons;
SuperresolutionCardiacVelocity4D(ReconstructionCardiacVelocity4D *reconstructor) : reconstructor(reconstructor) {
addons = confidence_maps = Array<RealImage>(reconstructor->_reconstructed5DVelocity.size(), RealImage(reconstructor->_reconstructed4D.Attributes()));
}
SuperresolutionCardiacVelocity4D(SuperresolutionCardiacVelocity4D& x, split) : SuperresolutionCardiacVelocity4D(x.reconstructor) {}
void operator()(const blocked_range<size_t>& r) {
for (size_t inputIndex = r.begin(); inputIndex < r.end(); inputIndex++) {
if (reconstructor->_volcoeffs[inputIndex].empty())
continue;
// Read the current slice
const RealImage& current_slice = reconstructor->_slices[inputIndex];
// Read the current simulated slice
const RealImage& sim = reconstructor->_simulated_slices[inputIndex];
// Compute error between simulated and original slices
RealImage slice = current_slice - sim;
for (int i = 0; i < current_slice.GetX(); i++)
for (int j = 0; j < current_slice.GetY(); j++)
if (current_slice(i, j, 0) > -10 && sim(i, j, 0) < -10)
slice(i, j, 0) = 0;
// Read the current weight image
const RealImage& w = reconstructor->_weights[inputIndex];
// Gradient moment magnitude for the current slice
const int gradientIndex = reconstructor->_stack_index[inputIndex];
const double gval = reconstructor->_g_values[gradientIndex];
// Update reconstructed velocity volumes using current slice
for (size_t velocityIndex = 0; velocityIndex < reconstructor->_v_directions.size(); velocityIndex++) {
// Compute current velocity component factor
const double v_component = reconstructor->_slice_g_directions[inputIndex][velocityIndex] / (3 * reconstructor->gamma * gval);
// Distribute error to the volume
for (size_t i = 0; i < reconstructor->_volcoeffs[inputIndex].size(); i++)
for (size_t j = 0; j < reconstructor->_volcoeffs[inputIndex][i].size(); j++)
if (slice(i, j, 0) > -10) {
if (sim(i, j, 0) < -10)
slice(i, j, 0) = 0;
for (size_t k = 0; k < reconstructor->_volcoeffs[inputIndex][i][j].size(); k++) {
const POINT3D& p = reconstructor->_volcoeffs[inputIndex][i][j][k];
if (p.value > 0.0) {
for (int outputIndex = 0; outputIndex < reconstructor->_reconstructed4D.GetT(); outputIndex++) {
const auto multiplier = reconstructor->_robust_slices_only ? 1 : reconstructor->_slice_weight[inputIndex];
addons[velocityIndex](p.x, p.y, p.z, outputIndex) += v_component * reconstructor->_slice_temporal_weight[outputIndex][inputIndex] * p.value * slice(i, j, 0) * w(i, j, 0) * multiplier;
confidence_maps[velocityIndex](p.x, p.y, p.z, outputIndex) += reconstructor->_slice_temporal_weight[outputIndex][inputIndex] * p.value * w(i, j, 0) * multiplier;
}
}
}
}
} // end of loop for velocity directions
} //end of loop for a slice inputIndex
}
void join(const SuperresolutionCardiacVelocity4D& y) {
for (size_t i = 0; i < addons.size(); i++) {
addons[i] += y.addons[i];
confidence_maps[i] += y.confidence_maps[i];
}
}
// execute
void operator() () {
parallel_reduce(blocked_range<size_t>(0, reconstructor->_slices.size()), *this);
}
};
//-------------------------------------------------------------------
// class for SStep (local structure-based outlier rejection)
class SStep {
Reconstruction *reconstructor;
size_t N;
public:
SStep(Reconstruction *reconstructor, size_t N) : reconstructor(reconstructor),
N(N) {}
void operator()(const blocked_range<size_t>& r) const {
for (size_t inputIndex = r.begin(); inputIndex != r.end(); inputIndex++) {
reconstructor->SliceSSIMMap(inputIndex);
} //end of loop for a slice inputIndex
}
void operator()() {
parallel_for(blocked_range<size_t>(0, N), *this);
}
};
//-------------------------------------------------------------------
/// Class for MStep (RS)
class MStep {
Reconstruction *reconstructor;
public:
double sigma;
double mix;
double num;
double min;
double max;
MStep(Reconstruction *reconstructor) : reconstructor(reconstructor) {
sigma = 0;
mix = 0;
num = 0;
min = voxel_limits<RealPixel>::max();
max = voxel_limits<RealPixel>::min();
}
MStep(MStep& x, split) : MStep(x.reconstructor) {}
void operator()(const blocked_range<size_t>& r) {
RealImage slice;
for (size_t inputIndex = r.begin(); inputIndex < r.end(); inputIndex++) {
// read the current slice
slice = reconstructor->_slices[inputIndex];
//calculate error
for (int i = 0; i < slice.GetX(); i++)
for (int j = 0; j < slice.GetY(); j++)
if (slice(i, j, 0) > -0.01) {
//bias correct and scale the slice
slice(i, j, 0) *= exp(-reconstructor->_bias[inputIndex](i, j, 0)) * reconstructor->_scale[inputIndex];
//otherwise the error has no meaning - it is equal to slice intensity
if (reconstructor->_simulated_weights[inputIndex](i, j, 0) > 0.99) {
slice(i, j, 0) -= reconstructor->_simulated_slices[inputIndex](i, j, 0);
//sigma and mix
const double e = slice(i, j, 0);
sigma += e * e * reconstructor->_weights[inputIndex](i, j, 0);
mix += reconstructor->_weights[inputIndex](i, j, 0);
//_m
if (e < min)
min = e;
if (e > max)
max = e;
num++;
}
}
} //end of loop for a slice inputIndex
}
void join(const MStep& y) {
if (y.min < min)
min = y.min;
if (y.max > max)
max = y.max;
sigma += y.sigma;
mix += y.mix;
num += y.num;
}
void operator()() {
parallel_reduce(blocked_range<size_t>(0, reconstructor->_slices.size()), *this);
}
};
//-------------------------------------------------------------------
/// M-step (todo: optimise for velocity)
class MStepCardiacVelocity4D {
ReconstructionCardiacVelocity4D *reconstructor;
public:
double sigma;
double mix;
double num;
double min;
double max;
MStepCardiacVelocity4D(ReconstructionCardiacVelocity4D *reconstructor) : reconstructor(reconstructor) {
sigma = 0;
mix = 0;
num = 0;
min = voxel_limits<RealPixel>::max();
max = voxel_limits<RealPixel>::min();
}
MStepCardiacVelocity4D(MStepCardiacVelocity4D& x, split) : MStepCardiacVelocity4D(x.reconstructor) {}
void operator()(const blocked_range<size_t>& r) {
for (size_t inputIndex = r.begin(); inputIndex < r.end(); inputIndex++) {
// read the current slice
const RealImage& current_slice = reconstructor->_slices[inputIndex];
//alias the current weight image
const RealImage& w = reconstructor->_weights[inputIndex];
RealImage slice = current_slice - reconstructor->_simulated_slices[inputIndex];
for (int i = 0; i < current_slice.GetX(); i++)
for (int j = 0; j < current_slice.GetY(); j++)
if (current_slice(i, j, 0) < -10)
slice(i, j, 0) = -15;
//calculate error
for (int i = 0; i < slice.GetX(); i++)
for (int j = 0; j < slice.GetY(); j++)
if (slice(i, j, 0) > -10) {
//otherwise the error has no meaning - it is equal to slice intensity
if (reconstructor->_simulated_weights[inputIndex](i, j, 0) > 0.99) {
//sigma and mix
const double e = slice(i, j, 0);
sigma += e * e * w(i, j, 0);
mix += w(i, j, 0);
//_m
if (e < min)
min = e;
if (e > max)
max = e;
num++;
}
}
} //end of loop for a slice inputIndex
}
void join(const MStepCardiacVelocity4D& y) {
if (y.min < min)
min = y.min;
if (y.max > max)
max = y.max;
sigma += y.sigma;
mix += y.mix;
num += y.num;
}
// execute
void operator() () {
parallel_reduce(blocked_range<size_t>(0, reconstructor->_slices.size()), *this);
}
};
//-------------------------------------------------------------------
/// Class for adaptive regularisation (Part I)
class AdaptiveRegularization1 {
const Reconstruction *reconstructor;
Array<RealImage>& b;
const Array<double>& factor;
const RealImage& original;
public:
AdaptiveRegularization1(
const Reconstruction *reconstructor,
Array<RealImage>& b,
const Array<double>& factor,
const RealImage& original) :
reconstructor(reconstructor),
b(b),
factor(factor),
original(original) {}
void operator()(const blocked_range<size_t>& r) const {
const int dx = reconstructor->_reconstructed.GetX();
const int dy = reconstructor->_reconstructed.GetY();
const int dz = reconstructor->_reconstructed.GetZ();
for (size_t i = r.begin(); i != r.end(); i++) {
for (int x = 0; x < dx; x++)
for (int y = 0; y < dy; y++)
for (int z = 0; z < dz; z++) {
const int xx = x + reconstructor->_directions[i][0];
const int yy = y + reconstructor->_directions[i][1];
const int zz = z + reconstructor->_directions[i][2];
if ((xx >= 0) && (xx < dx) && (yy >= 0) && (yy < dy) && (zz >= 0) && (zz < dz)
&& (reconstructor->_confidence_map(x, y, z) > 0) && (reconstructor->_confidence_map(xx, yy, zz) > 0)) {
const double diff = (original(xx, yy, zz) - original(x, y, z)) * sqrt(factor[i]) / reconstructor->_delta;
b[i](x, y, z) = factor[i] / sqrt(1 + diff * diff);
} else
b[i](x, y, z) = 0;
}
}
}
void operator()() const {
parallel_for(blocked_range<size_t>(0, 13), *this);
}
};
//-------------------------------------------------------------------
/// Class for adaptive regularisation (Part II)
class AdaptiveRegularization2 {
Reconstruction *reconstructor;
const Array<RealImage>& b;
const RealImage& original;
public:
AdaptiveRegularization2(
Reconstruction *reconstructor,
const Array<RealImage>& b,
const RealImage& original) :
reconstructor(reconstructor),
b(b),
original(original) {}
void operator()(const blocked_range<size_t>& r) const {
const int dx = reconstructor->_reconstructed.GetX();
const int dy = reconstructor->_reconstructed.GetY();
const int dz = reconstructor->_reconstructed.GetZ();
for (size_t x = r.begin(); x != r.end(); ++x) {
for (int y = 0; y < dy; y++)
for (int z = 0; z < dz; z++)
if (reconstructor->_confidence_map(x, y, z) > 0) {
double val = 0;
double sum = 0;
// Don't combine the loops, it breaks the compiler optimisation (GCC 9)
for (int i = 0; i < 13; i++) {
const int xx = x + reconstructor->_directions[i][0];
const int yy = y + reconstructor->_directions[i][1];
const int zz = z + reconstructor->_directions[i][2];
if ((xx >= 0) && (xx < dx) && (yy >= 0) && (yy < dy) && (zz >= 0) && (zz < dz)
&& reconstructor->_confidence_map(xx, yy, zz) > 0) {
val += b[i](x, y, z) * original(xx, yy, zz);
sum += b[i](x, y, z);
}
}
for (int i = 0; i < 13; i++) {
const int xx = x - reconstructor->_directions[i][0];
const int yy = y - reconstructor->_directions[i][1];
const int zz = z - reconstructor->_directions[i][2];
if ((xx >= 0) && (xx < dx) && (yy >= 0) && (yy < dy) && (zz >= 0) && (zz < dz)
&& reconstructor->_confidence_map(xx, yy, zz) > 0) {
val += b[i](x, y, z) * original(xx, yy, zz);
sum += b[i](x, y, z);
}
}
val -= sum * original(x, y, z);
val = original(x, y, z) + reconstructor->_alpha * reconstructor->_lambda / (reconstructor->_delta * reconstructor->_delta) * val;
reconstructor->_reconstructed(x, y, z) = val;
}
}
}
void operator()() const {
parallel_for(blocked_range<size_t>(0, reconstructor->_reconstructed.GetX()), *this);
}
};
//-------------------------------------------------------------------
class AdaptiveRegularization1Cardiac4D {
const ReconstructionCardiac4D *reconstructor;
Array<RealImage>& b;
const Array<double>& factor;
const RealImage& original;
public:
AdaptiveRegularization1Cardiac4D(
const ReconstructionCardiac4D *reconstructor,
Array<RealImage>& b,
const Array<double>& factor,
const RealImage& original) :
reconstructor(reconstructor),
b(b),
factor(factor),
original(original) {}
void operator()(const blocked_range<size_t>& r) const {
const int dx = reconstructor->_reconstructed4D.GetX();
const int dy = reconstructor->_reconstructed4D.GetY();
const int dz = reconstructor->_reconstructed4D.GetZ();
const int dt = reconstructor->_reconstructed4D.GetT();
for (size_t i = r.begin(); i != r.end(); i++) {
for (int x = 0; x < dx; x++)
for (int y = 0; y < dy; y++)
for (int z = 0; z < dz; z++) {
const int xx = x + reconstructor->_directions[i][0];
const int yy = y + reconstructor->_directions[i][1];
const int zz = z + reconstructor->_directions[i][2];
for (int t = 0; t < dt; t++) {
if ((xx >= 0) && (xx < dx) && (yy >= 0) && (yy < dy) && (zz >= 0) && (zz < dz)
&& (reconstructor->_confidence_map(x, y, z, t) > 0) && (reconstructor->_confidence_map(xx, yy, zz, t) > 0)) {
const double diff = (original(xx, yy, zz, t) - original(x, y, z, t)) * sqrt(factor[i]) / reconstructor->_delta;
b[i](x, y, z, t) = factor[i] / sqrt(1 + diff * diff);
} else
b[i](x, y, z, t) = 0;
}
}
}
}
void operator()() const {
parallel_for(blocked_range<size_t>(0, 13), *this);
}
};
//-------------------------------------------------------------------
class AdaptiveRegularization2Cardiac4D {
ReconstructionCardiac4D *reconstructor;
const Array<RealImage>& b;
const RealImage& original;
public:
AdaptiveRegularization2Cardiac4D(
ReconstructionCardiac4D *reconstructor,
const Array<RealImage>& b,
const RealImage& original) :
reconstructor(reconstructor),
b(b),
original(original) {}
void operator()(const blocked_range<size_t>& r) const {
const int dx = reconstructor->_reconstructed4D.GetX();
const int dy = reconstructor->_reconstructed4D.GetY();
const int dz = reconstructor->_reconstructed4D.GetZ();
const int dt = reconstructor->_reconstructed4D.GetT();
for (size_t x = r.begin(); x != r.end(); ++x) {
for (int y = 0; y < dy; y++)
for (int z = 0; z < dz; z++)
for (int t = 0; t < dt; t++) {
if (reconstructor->_confidence_map(x, y, z, t) > 0) {
double val = 0;
double sum = 0;
for (int i = 0; i < 13; i++) {
const int xx = x + reconstructor->_directions[i][0];
const int yy = y + reconstructor->_directions[i][1];
const int zz = z + reconstructor->_directions[i][2];
if ((xx >= 0) && (xx < dx) && (yy >= 0) && (yy < dy) && (zz >= 0) && (zz < dz)
&& (reconstructor->_confidence_map(xx, yy, zz, t) > 0)) {
val += b[i](x, y, z, t) * original(xx, yy, zz, t);
sum += b[i](x, y, z, t);
}
}
for (int i = 0; i < 13; i++) {
const int xx = x - reconstructor->_directions[i][0];
const int yy = y - reconstructor->_directions[i][1];
const int zz = z - reconstructor->_directions[i][2];
if ((xx >= 0) && (xx < dx) && (yy >= 0) && (yy < dy) && (zz >= 0) && (zz < dz)
&& (reconstructor->_confidence_map(xx, yy, zz, t) > 0)) {
val += b[i](x, y, z, t) * original(xx, yy, zz, t);
sum += b[i](x, y, z, t);
}
}
val -= sum * original(x, y, z, t);
val = original(x, y, z, t) + reconstructor->_alpha * reconstructor->_lambda / (reconstructor->_delta * reconstructor->_delta) * val;
reconstructor->_reconstructed4D(x, y, z, t) = val;
}
}
}
}
void operator()() const {
parallel_for(blocked_range<size_t>(0, reconstructor->_reconstructed4D.GetX()), *this);
}
};
//-------------------------------------------------------------------
/// Class for bias normalisation
class NormaliseBias {
Reconstruction *reconstructor;
public:
RealImage bias;
NormaliseBias(Reconstruction *reconstructor) : reconstructor(reconstructor) {
bias.Initialize(reconstructor->_reconstructed.Attributes());
}
NormaliseBias(NormaliseBias& x, split) : NormaliseBias(x.reconstructor) {}
void operator()(const blocked_range<size_t>& r) {
RealImage b;
for (size_t inputIndex = r.begin(); inputIndex < r.end(); inputIndex++) {
if (reconstructor->_volcoeffs[inputIndex].empty())
continue;
if (reconstructor->_verbose)
reconstructor->_verbose_log << inputIndex << " ";
// alias to the current slice
const RealImage& slice = reconstructor->_slices[inputIndex];
//read the current bias image
b = reconstructor->_bias[inputIndex];
//read current scale factor
const double scale = reconstructor->_scale[inputIndex];
const RealPixel *pi = slice.Data();
RealPixel *pb = b.Data();
for (int i = 0; i < slice.NumberOfVoxels(); i++)
if (pi[i] > -1 && scale > 0)
pb[i] -= log(scale);
//Distribute slice intensities to the volume
for (size_t i = 0; i < reconstructor->_volcoeffs[inputIndex].size(); i++)
for (size_t j = 0; j < reconstructor->_volcoeffs[inputIndex][i].size(); j++)
if (slice(i, j, 0) > -0.01) {
//add contribution of current slice voxel to all voxel volumes to which it contributes
for (size_t k = 0; k < reconstructor->_volcoeffs[inputIndex][i][j].size(); k++) {
const POINT3D& p = reconstructor->_volcoeffs[inputIndex][i][j][k];
bias(p.x, p.y, p.z) += p.value * b(i, j, 0);
}
}
//end of loop for a slice inputIndex
}
}
void join(const NormaliseBias& y) {
bias += y.bias;
}
void operator()() {
parallel_reduce(blocked_range<size_t>(0, reconstructor->_slices.size()), *this);
}
};
//-------------------------------------------------------------------
class NormaliseBiasCardiac4D {
ReconstructionCardiac4D *reconstructor;
public:
RealImage bias;
RealImage volweight3d;
NormaliseBiasCardiac4D(ReconstructionCardiac4D *reconstructor) : reconstructor(reconstructor) {
ImageAttributes attr = reconstructor->_reconstructed4D.Attributes();
attr._t = 1;
bias.Initialize(attr);
volweight3d.Initialize(attr);
}
NormaliseBiasCardiac4D(NormaliseBiasCardiac4D& x, split) : NormaliseBiasCardiac4D(x.reconstructor) {}
void operator()(const blocked_range<size_t>& r) {
RealImage b;
for (size_t inputIndex = r.begin(); inputIndex < r.end(); inputIndex++) {
if (reconstructor->_volcoeffs[inputIndex].empty())
continue;
if (reconstructor->_verbose)
reconstructor->_verbose_log << inputIndex << " ";
// alias to the current slice
const RealImage& slice = reconstructor->_slices[inputIndex];
//read the current bias image
b = reconstructor->_bias[inputIndex];
//read current scale factor
const double scale = reconstructor->_scale[inputIndex];
const RealPixel *pi = slice.Data();
RealPixel *pb = b.Data();
for (int i = 0; i < slice.NumberOfVoxels(); i++)
if (pi[i] > -1 && scale > 0)
pb[i] -= log(scale);
//Distribute slice intensities to the volume
for (size_t i = 0; i < reconstructor->_volcoeffs[inputIndex].size(); i++)
for (size_t j = 0; j < reconstructor->_volcoeffs[inputIndex][i].size(); j++)
if (slice(i, j, 0) != -1) {
//add contribution of current slice voxel to all voxel volumes
//to which it contributes
for (size_t k = 0; k < reconstructor->_volcoeffs[inputIndex][i][j].size(); k++) {
const POINT3D& p = reconstructor->_volcoeffs[inputIndex][i][j][k];
bias(p.x, p.y, p.z) += p.value * b(i, j, 0);
volweight3d(p.x, p.y, p.z) += p.value;
}
}
//end of loop for a slice inputIndex
}
}
void join(const NormaliseBiasCardiac4D& y) {
bias += y.bias;
volweight3d += y.volweight3d;
}
void operator()() {
parallel_reduce(blocked_range<size_t>(0, reconstructor->_slices.size()), *this);
}
};
//-------------------------------------------------------------------
/// Class for global stack similarity statistics (for the stack selection function)
class GlobalSimilarityStats {
const int nStacks;
const Array<RealImage>& stacks;
const Array<RealImage>& masks;
Array<double>& all_global_ncc_array;
Array<double>& all_global_volume_array;
public:
GlobalSimilarityStats(
const int nStacks,
const Array<RealImage>& stacks,
const Array<RealImage>& masks,
Array<double>& all_global_ncc_array,
Array<double>& all_global_volume_array) :
nStacks(nStacks),
stacks(stacks),
masks(masks),
all_global_ncc_array(all_global_ncc_array),
all_global_volume_array(all_global_volume_array) {}
void operator()(const blocked_range<size_t>& r) const {
Array<RigidTransformation> current_stack_transformations;
for (size_t inputIndex = r.begin(); inputIndex != r.end(); inputIndex++) {
double average_ncc = 0;
double average_volume = 0;
cout << " - " << inputIndex << endl;
GlobalStackStats(stacks[inputIndex], masks[inputIndex], stacks, masks, average_ncc, average_volume, current_stack_transformations);
current_stack_transformations.clear();
cout << " + " << inputIndex << endl;
all_global_ncc_array[inputIndex] = average_ncc;
all_global_volume_array[inputIndex] = average_volume;
}
}
void operator()() const {
parallel_for(blocked_range<size_t>(0, nStacks), *this);
}
};
//-------------------------------------------------------------------
class CalculateCorrectedSlices {
ReconstructionCardiac4D *reconstructor;
public:
CalculateCorrectedSlices(ReconstructionCardiac4D *reconstructor) : reconstructor(reconstructor) {}
void operator()(const blocked_range<size_t>& r) const {
for (size_t inputIndex = r.begin(); inputIndex != r.end(); inputIndex++) {
//read the current slice
RealImage slice = reconstructor->_slices[inputIndex];
//calculate corrected voxels
for (int i = 0; i < slice.GetX(); i++)
for (int j = 0; j < slice.GetY(); j++)
if (slice(i, j, 0) != -1)
//bias correct and scale the voxel
slice(i, j, 0) *= exp(-reconstructor->_bias[inputIndex](i, j, 0)) * reconstructor->_scale[inputIndex];
reconstructor->_corrected_slices[inputIndex] = move(slice);
} //end of loop for a slice inputIndex
}
void operator()() const {
parallel_for(blocked_range<size_t>(0, reconstructor->_slices.size()), *this);
}
};
//-------------------------------------------------------------------
class CalculateError {
ReconstructionCardiac4D *reconstructor;
public:
CalculateError(ReconstructionCardiac4D *reconstructor) : reconstructor(reconstructor) {}
void operator()(const blocked_range<size_t>& r) const {
RealImage slice;
for (size_t inputIndex = r.begin(); inputIndex != r.end(); inputIndex++) {
//read the current slice
slice = reconstructor->_slices[inputIndex];
//initialise
reconstructor->_error[inputIndex].Initialize(slice.Attributes());
//calculate error
for (int i = 0; i < slice.GetX(); i++)
for (int j = 0; j < slice.GetY(); j++)
if (slice(i, j, 0) != -1)
if (reconstructor->_simulated_weights[inputIndex](i, j, 0) > 0) {
//bias correct and scale the voxel
slice(i, j, 0) *= exp(-reconstructor->_bias[inputIndex](i, j, 0)) * reconstructor->_scale[inputIndex];
//subtract simulated voxel
slice(i, j, 0) -= reconstructor->_simulated_slices[inputIndex](i, j, 0);
//assign as error
reconstructor->_error[inputIndex](i, j, 0) = slice(i, j, 0);
}
} //end of loop for a slice inputIndex
}
void operator()() const {
parallel_for(blocked_range<size_t>(0, reconstructor->_slices.size()), *this);
}
};
//-------------------------------------------------------------------
}
|
cpl_tools.c | /*
* This file is part of the ESO Common Pipeline Library
* Copyright (C) 2001-2017 European Southern Observatory
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
/*-----------------------------------------------------------------------------
Includes
-----------------------------------------------------------------------------*/
#include "cpl_tools.h"
#include "cpl_error_impl.h"
#include "cpl_memory.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <float.h>
#include <math.h>
#include <assert.h>
#include <signal.h>
/* Needed by strcmp() */
#include <string.h>
/*-----------------------------------------------------------------------------
Defines
-----------------------------------------------------------------------------*/
#ifndef inline
#define inline /* inline */
#endif
#ifndef CPL_PIX_STACK_SIZE
#define CPL_PIX_STACK_SIZE 50
#endif
/* Swap macros */
#define CPL_INT_SWAP(a,b) { register const cpl_size t=(a); (a)=(b); (b)=t; }
#define CONCAT(a,b) a ## _ ## b
#define CONCAT2X(a,b) CONCAT(a,b)
/*-----------------------------------------------------------------------------
Private variables
-----------------------------------------------------------------------------*/
static cpl_flops flop_count = 0;
/*----------------------------------------------------------------------------*/
/**
* @defgroup cpl_tools Utility functions
*
* This module provides various functions to apply simple operations on
* data arrays (sorting, median computation).
*
* @par Synopsis:
* @code
* #include "cpl_tools.h"
* @endcode
*/
/*----------------------------------------------------------------------------*/
/**@{*/
/*-----------------------------------------------------------------------------
Function codes
-----------------------------------------------------------------------------*/
#define CPL_TYPE_IS_TYPE_PIXEL
#define CPL_TYPE_IS_NUM
#define CPL_TYPE int
#define CPL_TYPE_NAME int
#define CPL_TOOLS_SORT_LT(x,y) ((x) < (y))
#include "cpl_tools_body.h"
#undef CPL_TYPE
#undef CPL_TYPE_NAME
#undef CPL_TOOLS_SORT_LT
#undef CPL_TYPE_IS_TYPE_PIXEL
#define CPL_TYPE_IS_NUM
#define CPL_TYPE long
#define CPL_TYPE_NAME long
#define CPL_TOOLS_SORT_LT(x,y) ((x) < (y))
#include "cpl_tools_body.h"
#undef CPL_TYPE
#undef CPL_TYPE_NAME
#undef CPL_TOOLS_SORT_LT
#define CPL_TYPE_IS_NUM
#define CPL_TYPE long long
#define CPL_TYPE_NAME long_long
#define CPL_TOOLS_SORT_LT(x,y) ((x) < (y))
#include "cpl_tools_body.h"
#undef CPL_TYPE
#undef CPL_TYPE_NAME
#undef CPL_TOOLS_SORT_LT
#define CPL_TYPE cpl_size
#define CPL_TYPE_NAME cplsize
#define CPL_TOOLS_SORT_LT(x,y) ((x) < (y))
#include "cpl_tools_body.h"
#undef CPL_TYPE
#undef CPL_TYPE_NAME
#undef CPL_TOOLS_SORT_LT
#define CPL_TYPE_IS_TYPE_PIXEL
#define CPL_TYPE float
#define CPL_TYPE_NAME float
#define CPL_TOOLS_SORT_LT(x,y) ((x) < (y))
#include "cpl_tools_body.h"
#undef CPL_TYPE
#undef CPL_TYPE_NAME
#undef CPL_TOOLS_SORT_LT
#define CPL_TYPE double
#define CPL_TYPE_NAME double
#define CPL_TOOLS_SORT_LT(x,y) ((x) < (y))
#include "cpl_tools_body.h"
#undef CPL_TYPE
#undef CPL_TYPE_NAME
#undef CPL_TOOLS_SORT_LT
#undef CPL_TYPE_IS_NUM
#undef CPL_TYPE_IS_TYPE_PIXEL
#define CPL_TYPE char *
#define CPL_TYPE_NAME string
#define CPL_TOOLS_SORT_LT(x,y) (((x) == NULL && (y) != NULL) || \
((x) != NULL && (y) != NULL && \
strcmp((x), (y)) < 0))
#include "cpl_tools_body.h"
#undef CPL_TYPE
#undef CPL_TYPE_NAME
#undef CPL_TOOLS_SORT_LT
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Initializer with conditional allocation for ifalloc variable
@param self The ifalloc variable to be conditionally allocated
@param size The number of bytes needed, zero guarantees no heap allocation
@see cpl_ifalloc_free
@note Calling this function with a pointer that has previously been passed
to this function with a non-zero size can lead to a memory leak.
Example of usage:
@code
cpl_ifalloc mybuf;
cpl_ifalloc_set(&mybuf, 0);
if (!myerror) {
double * mynumbers;
cpl_ifalloc_set(&mybuf, mysize * sizeof(*mynumbers));
mynumbers = (double*)cpl_ifalloc_get(&mybuf);
}
cpl_ifalloc_free(&mybuf);
@endcode
*/
/*----------------------------------------------------------------------------*/
inline void cpl_ifalloc_set(cpl_ifalloc * self, size_t size)
{
if (size > (size_t)CPL_IFALLOC_SZ) {
self->data = self->heap = cpl_malloc(size);
} else {
self->data = (void*)(self->stack);
self->heap = NULL;
}
}
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Get pointer to data area of ifalloc variable
@param self The ifalloc variable to accessed
@see cpl_ifalloc_set
@note The returned pointer becomes stale after a call to cpl_ifalloc_free()
*/
/*----------------------------------------------------------------------------*/
inline void * cpl_ifalloc_get(cpl_ifalloc * self)
{
return self->data;
}
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Free all memory associated with ifalloc variable
@param self The ifalloc variable to be deallocated
@see cpl_ifalloc_set
*/
/*----------------------------------------------------------------------------*/
inline void cpl_ifalloc_free(cpl_ifalloc * self)
{
if (self->heap != NULL) cpl_free(self->heap); /* Typically NULL */
}
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Find the FITS BITPIX value corresponding to the given CPL type.
@param type The CPL type.
@return The corresponding FITS BITPIX value, or zero on error.
@note The input type may have its array/pointer bit set, which is ignored.
The supported types (and their corresponding BITPIX) are:
CPL_TYPE_UCHAR: BYTE_IMG (8)
CPL_TYPE_SHORT: SHORT_IMG (16)
CPL_TYPE_USHORT: USHORT_IMG (20)
CPL_TYPE_INT: LONG_IMG (32)
CPL_TYPE_FLOAT: FLOAT_IMG (-32)
CPL_TYPE_DOUBLE: DOUBLE_IMG (-64)
Possible #_cpl_error_code_ set in this function:
- CPL_ERROR_INVALID_TYPE if no BITPIX value corresponds to the type
*/
/*----------------------------------------------------------------------------*/
int cpl_tools_get_bpp(cpl_type type)
{
int bpp;
/* switch on type without POINTER and ARRAY bits */
switch (type & ~CPL_TYPE_POINTER & ~CPL_TYPE_FLAG_ARRAY) {
case CPL_TYPE_UCHAR:
bpp = BYTE_IMG; /* 8 */
break;
case CPL_TYPE_SHORT:
bpp = SHORT_IMG; /* 16 */
break;
case CPL_TYPE_USHORT:
bpp = USHORT_IMG; /* 20 */
break;
case CPL_TYPE_INT:
bpp = LONG_IMG; /* 32 */
break;
case CPL_TYPE_FLOAT:
bpp = FLOAT_IMG; /* -32 */
break;
case CPL_TYPE_DOUBLE:
bpp = DOUBLE_IMG; /* -64 */
break;
default:
bpp = 0;
(void)cpl_error_set_message_(CPL_ERROR_INVALID_TYPE,
"type=0x%x", (int)type);
}
return bpp;
}
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Determine if an integer is a power of 2.
@param p Integer to check.
@return The corresponding power of 2 or -1 if p is not a power of 2
*/
/*----------------------------------------------------------------------------*/
cpl_size cpl_tools_is_power_of_2(cpl_size p)
{
cpl_size ipow = 0;
cpl_size done;
if (p <= 0) return -1;
/* Count until 1st non-zero bit is found */
do {
done = p & 1;
p >>= 1;
ipow++;
} while (!done);
/* The number is a power iff p is now zero */
return p == 0 ? ipow-1 : -1;
}
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Compute x to the power of y
@param x The base
@param y The power
@return x to the power of y
@note Iff y is negative and x is zero an actual division by zero will occur
Apart from a possible difference in round-off the result equals pow(x,y).
*/
/*----------------------------------------------------------------------------*/
double cpl_tools_ipow(double x, int y)
{
double result;
double pow2 = x;
int p = abs(y);
/* Compute the result as a product of powers of 2 of x.
- this method may produce (slightly) different results than pow(x,y) */
/* Handle least significant bit in p here in order to avoid an unnecessary
multiplication of pow2 - which could cause an over- or underflow */
/* Also, 0^0 is 1, while any other power of 0 is 0 */
result = p & 1 ? x : 1.0;
while (p >>= 1) {
pow2 *= pow2;
/* Process least significant bit in p */
if (p & 1) result *= pow2;
}
/* It is left to the caller to ensure that no division by zero occurs */
return y < 0 ? 1.0/result : result;
}
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Add to the FLOPS counter.
@param flops FLOPS to add
@return void
@note If compiled with -DCPL_ADD_FLOPS this function will incur significant
thread scheduling and CPU overhead, if not it will not be used.
*/
/*----------------------------------------------------------------------------*/
inline void cpl_tools_add_flops_(cpl_flops flops)
{
#ifdef _OPENMP
#pragma omp atomic
#endif
flop_count += flops;
}
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Get the FLOPS count.
@return The FLOPS count
@note This function is intended to be used only by the CPL test modules.
@note If compiled with -DCPL_ADD_FLOPS this function will always return zero.
*/
/*----------------------------------------------------------------------------*/
cpl_flops cpl_tools_get_flops(void)
{
return flop_count;
}
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Transform: xhat = x- mean(x)
@param x The vector to be transformed
@param pm On return, *pm is the mean of x
@return The created transformed vector
@note No NULL-pointer check in this internal function
*/
/*----------------------------------------------------------------------------*/
cpl_vector * cpl_vector_transform_mean(const cpl_vector * x, double * pm)
{
cpl_vector * xhat = cpl_vector_duplicate(x);
*pm = cpl_vector_get_mean(xhat);
cpl_vector_subtract_scalar(xhat, *pm);
return xhat;
}
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Count the number of distinct values in the vector
@param self The vector to check, it will be sorted
@param pndistinct The number of distinct values
@return CPL_ERROR_NONE iff the check is sucessful
*/
/*----------------------------------------------------------------------------*/
cpl_error_code cpl_vector_count_distinct(cpl_vector * self,
cpl_size * pndistinct)
{
if (pndistinct == NULL) {
return cpl_error_set_(CPL_ERROR_NULL_INPUT);
} else if (cpl_vector_sort(self, CPL_SORT_ASCENDING)) {
return cpl_error_set_where_();
} else {
const double * dx = cpl_vector_get_data_const(self);
double xmin = dx[0];
const cpl_size n = cpl_vector_get_size(self);
cpl_size i, j;
for (j = i = 1; i < n; i++) {
if (dx[i] > xmin) {
xmin = dx[i];
j++;
}
}
*pndistinct = j;
}
return CPL_ERROR_NONE;
}
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Ensure that the vector has the required number of distinct values
@param self The vector to check
@param ndistinct The (positive) number of distinct values to require
@return CPL_ERROR_NONE iff the check is sucessful
@see cpl_vector_count_distinct()
*/
/*----------------------------------------------------------------------------*/
cpl_error_code cpl_vector_ensure_distinct(const cpl_vector * self,
cpl_size ndistinct)
{
if (ndistinct > 1) {
const cpl_size n = cpl_vector_get_size(self);
if (n < 1) {
return cpl_error_set_where_();
} else if (ndistinct > n) {
return cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND,
"A %" CPL_SIZE_FORMAT "-element "
"vector cannot have at least %"
CPL_SIZE_FORMAT " distinct values",
n, ndistinct);
} else {
cpl_vector * tmp = cpl_vector_duplicate(self);
cpl_size idistinct = 0;
(void)cpl_vector_count_distinct(tmp, &idistinct);
cpl_vector_delete(tmp);
if (idistinct < ndistinct) {
return cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%"
CPL_SIZE_FORMAT "-element vector "
"must have at least %"
CPL_SIZE_FORMAT " (not %"
CPL_SIZE_FORMAT ") distinct "
" values", n, ndistinct,
idistinct);
}
}
} else if (ndistinct < 1) {
return cpl_error_set_(CPL_ERROR_ILLEGAL_INPUT);
}
return CPL_ERROR_NONE;
}
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Copy a rectangular memory area from one place to another
@param self Preallocated location to copy to
@param src Location to copy from
@param size Size of each element [bytes]
@param nx Number of elements in x direction in source
@param ny Number of elements in y direction in source
@param llx Lower left x position (starting with 1)
@param lly Lower left y position (starting with 1)
@param urx Upper right x position
@param ury Upper right y position
@return CPL_ERROR_NONE if OK, otherwise the relevant #_cpl_error_code_.
@note self must have place for (urx-llx+1) * (ury-lly+1) elements of size size
@note No NULL-pointer check in this internal function
@see mempcy()
Possible #_cpl_error_code_ set in this function:
- CPL_ERROR_ILLEGAL_INPUT if the window coordinates are not valid
*/
/*----------------------------------------------------------------------------*/
cpl_error_code cpl_tools_copy_window(void *self, const void *src, size_t size,
cpl_size nx, cpl_size ny,
cpl_size llx, cpl_size lly,
cpl_size urx, cpl_size ury)
{
/* FIXME: Need to do pointer arithmetic */
const char * csrc = (const char*)src;
cpl_ensure_code(size != 0, CPL_ERROR_ILLEGAL_INPUT);
cpl_ensure_code(llx <= urx, CPL_ERROR_ILLEGAL_INPUT);
cpl_ensure_code(lly > 0, CPL_ERROR_ILLEGAL_INPUT);
cpl_ensure_code(lly <= ury, CPL_ERROR_ILLEGAL_INPUT);
cpl_ensure_code(ury <= ny, CPL_ERROR_ILLEGAL_INPUT);
/* assert(sizeof(char) == 1); */
if (llx == 1 && urx == nx) {
/* Number of bytes in one row of self */
const size_t rowsize = size * (size_t)nx;
(void)memcpy(self, csrc + rowsize * (size_t)(lly-1),
rowsize * (size_t)(ury-lly+1));
} else {
/* FIXME: Need to do pointer arithmetic */
char * cself = (char*)self;
/* Number of bytes in one row of self */
const size_t rowsize = size * (size_t)(urx-llx+1);
/* Byte just after last byte to write to self */
const char * cstop = cself + rowsize * (size_t)(ury-lly+1);
cpl_ensure_code(llx > 0, CPL_ERROR_ILLEGAL_INPUT);
cpl_ensure_code(urx <= nx, CPL_ERROR_ILLEGAL_INPUT);
/* Point to first byte to read */
csrc += size * (size_t)((llx - 1) + (lly-1) * nx);
for (; cself < cstop; cself += rowsize, csrc += size * (size_t)nx) {
(void)memcpy(cself, csrc, rowsize);
}
}
return CPL_ERROR_NONE;
}
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Shift a rectangular memory area
@param self Location of 1st element
@param size Size of each element [bytes]
@param nx Number of elements in x direction in source
@param ny Number of elements in y direction in source
@param null Value to insert into 'empty' zone'
@param dx Shift in X
@param dy Shift in Y
@return the #_cpl_error_code_ or CPL_ERROR_NONE
@note No NULL-pointer check in this internal function
@see cpl_mask_shift()
The 'empty zone' in the shifted rectangle is filled with size null's.
The shift values have to be valid:
-nx < x_shift < nx and -ny < y_shift < ny
Possible #_cpl_error_code_ set in this function:
- CPL_ERROR_NULL_INPUT if in is NULL
- CPL_ERROR_ILLEGAL_INPUT if the offsets are too big, or size is zero, or
nx or ny non-positive
*/
/*----------------------------------------------------------------------------*/
cpl_error_code cpl_tools_shift_window(void * self, size_t size,
cpl_size nx, cpl_size ny, int null,
cpl_size dx, cpl_size dy)
{
/* Need to do pointer arithmetic */
char * myself = (char*)self;
/* Number of elements to be set to null */
const size_t sset = (size_t)(labs((long int)dy) * nx) * size;
/* Remainder of buffer will be moved */
const size_t smove = (size_t)(ny * nx) * size - sset;
char * pdest = dy < 0 ? myself : myself + sset;
char * psrc = dy > 0 ? myself : myself + sset; /* const */
char * pset = dy > 0 ? myself : myself + smove;
cpl_ensure_code(size > 0, CPL_ERROR_ILLEGAL_INPUT);
cpl_ensure_code(nx > 0, CPL_ERROR_ILLEGAL_INPUT);
cpl_ensure_code(ny > 0, CPL_ERROR_ILLEGAL_INPUT);
cpl_ensure_code( dx < nx, CPL_ERROR_ILLEGAL_INPUT);
cpl_ensure_code(-dx < nx, CPL_ERROR_ILLEGAL_INPUT);
cpl_ensure_code( dy < ny, CPL_ERROR_ILLEGAL_INPUT);
cpl_ensure_code(-dy < ny, CPL_ERROR_ILLEGAL_INPUT);
if (dx != 0) {
/* Have to shift one row at a time */
/* Size of a row */
const size_t rsize = (size_t)nx * size;
/* Number of elements to be set to null */
const size_t srset = (size_t)labs((long int)dx) * size;
/* Remainder of buffer will be moved */
const size_t srmove = rsize - srset;
char * prdest = dx < 0 ? pdest : pdest + srset;
char * prsrc = dx > 0 ? psrc : psrc + srset;
char * prset = dx > 0 ? pdest : pdest + srmove;
/* source and dest overlap when dy is zero */
void * (*myshift)(void *, const void *, size_t) = dy ? memcpy : memmove;
cpl_size j;
if (dy <= 0) {
for (j = -dy; j < ny; j++,
prdest += rsize, prsrc += rsize, prset += rsize) {
(void)myshift(prdest, prsrc, srmove);
(void)memset(prset, null, srset);
}
} else {
/* With a positive dy the rows must be shifted in reverse
order */
prdest += smove - rsize;
prsrc += smove - rsize;
prset += smove - rsize;
for (j = dy; j < ny; j++,
prdest -= rsize, prsrc -= rsize, prset -= rsize) {
(void)memcpy(prdest, prsrc, srmove);
(void)memset(prset, null, srset);
}
}
} else if (dy != 0) {
/* Shift all rows at once */
(void)memmove(pdest, psrc, smove);
}
/* Set all of the 'empty' rows */
if (dy != 0) (void)memset(pset, null, sset);
return CPL_ERROR_NONE;
}
/**@}*/
|
box_coder_op.h | /* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#pragma once
#include <string>
#include <vector>
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/operators/math/math_function.h"
namespace paddle {
namespace operators {
enum class BoxCodeType { kEncodeCenterSize = 0, kDecodeCenterSize = 1 };
inline BoxCodeType GetBoxCodeType(const std::string &type) {
PADDLE_ENFORCE_EQ(
(type == "encode_center_size") || (type == "decode_center_size"), true,
platform::errors::InvalidArgument(
"The 'code_type' attribute in BoxCoder"
" must be 'encode_center_size' or 'decode_center_size'. "
"But received 'code_type' is %s",
type));
if (type == "encode_center_size") {
return BoxCodeType::kEncodeCenterSize;
} else {
return BoxCodeType::kDecodeCenterSize;
}
}
template <typename DeviceContext, typename T>
class BoxCoderKernel : public framework::OpKernel<T> {
public:
void EncodeCenterSize(const framework::Tensor *target_box,
const framework::Tensor *prior_box,
const framework::Tensor *prior_box_var,
const bool normalized,
const std::vector<float> variance, T *output) const {
int64_t row = target_box->dims()[0];
int64_t col = prior_box->dims()[0];
int64_t len = prior_box->dims()[1];
#ifdef PADDLE_WITH_MKLML
#pragma omp parallel for collapse(2)
#endif
for (int64_t i = 0; i < row; ++i) {
for (int64_t j = 0; j < col; ++j) {
auto *target_box_data = target_box->data<T>();
auto *prior_box_data = prior_box->data<T>();
size_t offset = i * col * len + j * len;
T prior_box_width = prior_box_data[j * len + 2] -
prior_box_data[j * len] + (normalized == false);
T prior_box_height = prior_box_data[j * len + 3] -
prior_box_data[j * len + 1] +
(normalized == false);
T prior_box_center_x = prior_box_data[j * len] + prior_box_width / 2;
T prior_box_center_y =
prior_box_data[j * len + 1] + prior_box_height / 2;
T target_box_center_x =
(target_box_data[i * len + 2] + target_box_data[i * len]) / 2;
T target_box_center_y =
(target_box_data[i * len + 3] + target_box_data[i * len + 1]) / 2;
T target_box_width = target_box_data[i * len + 2] -
target_box_data[i * len] + (normalized == false);
T target_box_height = target_box_data[i * len + 3] -
target_box_data[i * len + 1] +
(normalized == false);
output[offset] =
(target_box_center_x - prior_box_center_x) / prior_box_width;
output[offset + 1] =
(target_box_center_y - prior_box_center_y) / prior_box_height;
output[offset + 2] =
std::log(std::fabs(target_box_width / prior_box_width));
output[offset + 3] =
std::log(std::fabs(target_box_height / prior_box_height));
}
}
if (prior_box_var) {
const T *prior_box_var_data = prior_box_var->data<T>();
#ifdef PADDLE_WITH_MKLML
#pragma omp parallel for collapse(3)
#endif
for (int64_t i = 0; i < row; ++i) {
for (int64_t j = 0; j < col; ++j) {
for (int k = 0; k < 4; ++k) {
size_t offset = i * col * len + j * len;
int prior_var_offset = j * len;
output[offset + k] /= prior_box_var_data[prior_var_offset + k];
}
}
}
} else if (!(variance.empty())) {
#ifdef PADDLE_WITH_MKLML
#pragma omp parallel for collapse(3)
#endif
for (int64_t i = 0; i < row; ++i) {
for (int64_t j = 0; j < col; ++j) {
for (int k = 0; k < 4; ++k) {
size_t offset = i * col * len + j * len;
output[offset + k] /= static_cast<T>(variance[k]);
}
}
}
}
}
template <int axis, int var_size>
void DecodeCenterSize(const framework::Tensor *target_box,
const framework::Tensor *prior_box,
const framework::Tensor *prior_box_var,
const bool normalized, std::vector<float> variance,
T *output) const {
int64_t row = target_box->dims()[0];
int64_t col = target_box->dims()[1];
int64_t len = target_box->dims()[2];
#ifdef PADDLE_WITH_MKLML
#pragma omp parallel for collapse(2)
#endif
for (int64_t i = 0; i < row; ++i) {
for (int64_t j = 0; j < col; ++j) {
auto *target_box_data = target_box->data<T>();
auto *prior_box_data = prior_box->data<T>();
T var_data[4] = {1., 1., 1., 1.};
T *var_ptr = var_data;
size_t offset = i * col * len + j * len;
int prior_box_offset = axis == 0 ? j * len : i * len;
T prior_box_width = prior_box_data[prior_box_offset + 2] -
prior_box_data[prior_box_offset] +
(normalized == false);
T prior_box_height = prior_box_data[prior_box_offset + 3] -
prior_box_data[prior_box_offset + 1] +
(normalized == false);
T prior_box_center_x =
prior_box_data[prior_box_offset] + prior_box_width / 2;
T prior_box_center_y =
prior_box_data[prior_box_offset + 1] + prior_box_height / 2;
T target_box_center_x = 0, target_box_center_y = 0;
T target_box_width = 0, target_box_height = 0;
int prior_var_offset = axis == 0 ? j * len : i * len;
if (var_size == 2) {
std::memcpy(var_ptr, prior_box_var->data<T>() + prior_var_offset,
4 * sizeof(T));
} else if (var_size == 1) {
var_ptr = reinterpret_cast<T *>(variance.data());
}
T box_var_x = *var_ptr;
T box_var_y = *(var_ptr + 1);
T box_var_w = *(var_ptr + 2);
T box_var_h = *(var_ptr + 3);
target_box_center_x =
box_var_x * target_box_data[offset] * prior_box_width +
prior_box_center_x;
target_box_center_y =
box_var_y * target_box_data[offset + 1] * prior_box_height +
prior_box_center_y;
target_box_width =
std::exp(box_var_w * target_box_data[offset + 2]) * prior_box_width;
target_box_height = std::exp(box_var_h * target_box_data[offset + 3]) *
prior_box_height;
output[offset] = target_box_center_x - target_box_width / 2;
output[offset + 1] = target_box_center_y - target_box_height / 2;
output[offset + 2] =
target_box_center_x + target_box_width / 2 - (normalized == false);
output[offset + 3] =
target_box_center_y + target_box_height / 2 - (normalized == false);
}
}
}
void Compute(const framework::ExecutionContext &context) const override {
auto *prior_box = context.Input<framework::Tensor>("PriorBox");
auto *prior_box_var = context.Input<framework::Tensor>("PriorBoxVar");
auto *target_box = context.Input<framework::LoDTensor>("TargetBox");
auto *output_box = context.Output<framework::Tensor>("OutputBox");
std::vector<float> variance = context.Attr<std::vector<float>>("variance");
const int axis = context.Attr<int>("axis");
if (target_box->lod().size()) {
PADDLE_ENFORCE_EQ(target_box->lod().size(), 1UL,
platform::errors::InvalidArgument(
"Input(TargetBox) of BoxCoder operator "
"supports LoD with only one level. But received "
"level = %d",
target_box->lod().size()));
}
if (prior_box_var) {
PADDLE_ENFORCE_EQ(variance.empty(), true,
platform::errors::InvalidArgument(
"Input 'PriorBoxVar' and attribute 'variance' "
"of BoxCoder operator should not be used at the "
"same time."));
}
if (!(variance.empty())) {
PADDLE_ENFORCE_EQ(static_cast<int>(variance.size()), 4,
platform::errors::InvalidArgument(
"Size of attribute 'variance' of BoxCoder "
"operator should be 4. But received "
"size = %d",
variance.size()));
}
auto code_type = GetBoxCodeType(context.Attr<std::string>("code_type"));
bool normalized = context.Attr<bool>("box_normalized");
auto row = target_box->dims()[0];
auto col = prior_box->dims()[0];
if (code_type == BoxCodeType::kDecodeCenterSize) {
col = target_box->dims()[1];
}
auto len = prior_box->dims()[1];
output_box->mutable_data<T>({row, col, len}, context.GetPlace());
T *output = output_box->data<T>();
if (code_type == BoxCodeType::kEncodeCenterSize) {
EncodeCenterSize(target_box, prior_box, prior_box_var, normalized,
variance, output);
} else if (code_type == BoxCodeType::kDecodeCenterSize) {
if (prior_box_var) {
if (axis == 0) {
DecodeCenterSize<0, 2>(target_box, prior_box, prior_box_var,
normalized, variance, output);
} else {
DecodeCenterSize<1, 2>(target_box, prior_box, prior_box_var,
normalized, variance, output);
}
} else if (!(variance.empty())) {
if (axis == 0) {
DecodeCenterSize<0, 1>(target_box, prior_box, prior_box_var,
normalized, variance, output);
} else {
DecodeCenterSize<1, 1>(target_box, prior_box, prior_box_var,
normalized, variance, output);
}
} else {
if (axis == 0) {
DecodeCenterSize<0, 0>(target_box, prior_box, prior_box_var,
normalized, variance, output);
} else {
DecodeCenterSize<1, 0>(target_box, prior_box, prior_box_var,
normalized, variance, output);
}
}
}
}
};
} // namespace operators
} // namespace paddle
|
burgers1d_perf_b.c |
#ifndef TAPENADE
#include <math.h>
#endif
#define Max(x,y) fmax(x,y)
#define Min(x,y) fmin(x,y)
#define Heaviside(x) ((x>=0)?1.0:0.0)
#define u(x) u[x]
#define u_b(x) u_b[x]
#define u_1(x) u_1[x]
#define u_1_b(x) u_1_b[x]
void burgers1d_perf_b(double* u, double* u_b, double* u_1, double* u_1_b, double D, double C, int n) {
int i;
i=0;
u_1_b(i) += (C*Max(0, u_1(i + 1)) + D)*u_b(i + 1);
i=n - 2;
u_1_b(i) += (-C*((-u_1(i) + u_1(i + 1))*Heaviside(-u_1(i)) + (u_1(i) - u_1(i - 1))*Heaviside(u_1(i)) + Max(0, u_1(i)) - Min(0, u_1(i))) - 2.0*D + 1)*u_b(i);
u_1_b(i) += (-C*Min(0, u_1(i - 1)) + D)*u_b(i - 1);
i=1;
u_1_b(i) += (C*Max(0, u_1(i + 1)) + D)*u_b(i + 1);
u_1_b(i) += (-C*((-u_1(i) + u_1(i + 1))*Heaviside(-u_1(i)) + (u_1(i) - u_1(i - 1))*Heaviside(u_1(i)) + Max(0, u_1(i)) - Min(0, u_1(i))) - 2.0*D + 1)*u_b(i);
i=n - 1;
u_1_b(i) += (-C*Min(0, u_1(i - 1)) + D)*u_b(i - 1);
#pragma omp parallel for private(i)
for ( i=2; i<=n - 3; i++ ) {
u_1_b(i) += (C*Max(0, u_1(i + 1)) + D)*u_b(i + 1);
u_1_b(i) += (-C*((-u_1(i) + u_1(i + 1))*Heaviside(-u_1(i)) + (u_1(i) - u_1(i - 1))*Heaviside(u_1(i)) + Max(0, u_1(i)) - Min(0, u_1(i))) - 2.0*D + 1)*u_b(i);
u_1_b(i) += (-C*Min(0, u_1(i - 1)) + D)*u_b(i - 1);
}
}
|
GB_unaryop__abs_fp32_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_fp32_uint8
// op(A') function: GB_tran__abs_fp32_uint8
// C type: float
// A type: uint8_t
// cast: float cij = (float) aij
// unaryop: cij = fabsf (aij)
#define GB_ATYPE \
uint8_t
#define GB_CTYPE \
float
// 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 = fabsf (x) ;
// casting
#define GB_CASTING(z, x) \
float z = (float) 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_FP32 || GxB_NO_UINT8)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__abs_fp32_uint8
(
float *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_fp32_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
|
Referenced.h | #ifndef CRPROPA_REFERENCED_H
#define CRPROPA_REFERENCED_H
#include <stddef.h>
#ifdef DEBUG
#include <iostream>
#include <typeinfo>
#endif
namespace crpropa {
/**
* \addtogroup Core
* @{
*/
/**
@class Referenced
@brief Base class for reference counting
A form of memory management is needed to prevent memory leaks when using MPC in Python via SWIG.
This base class enables reference counting.
Every reference increases the reference counter, every dereference decreases it.
When the counter is decreased to 0, the object is deleted.
Candidate, Module, MagneticField and Source inherit from this class
*/
class Referenced {
public:
inline Referenced() :
_referenceCount(0) {
}
inline Referenced(const Referenced&) :
_referenceCount(0) {
}
inline Referenced& operator =(const Referenced&) {
return *this;
}
inline size_t addReference() const {
int newRef;
#if defined(OPENMP_3_1)
#pragma omp atomic capture
{newRef = _referenceCount++;}
#elif defined(__GNUC__)
newRef = __sync_add_and_fetch(&_referenceCount, 1);
#else
#pragma omp critical
{newRef = _referenceCount++;}
#endif
return newRef;
}
inline size_t removeReference() const {
#ifdef DEBUG
if (_referenceCount == 0)
std::cerr
<< "WARNING: Remove reference from Object with NO references: "
<< typeid(*this).name() << std::endl;
#endif
int newRef;
#if defined(OPENMP_3_1)
#pragma omp atomic capture
{newRef = _referenceCount--;}
#elif defined(__GNUC__)
newRef = __sync_sub_and_fetch(&_referenceCount, 1);
#else
#pragma omp critical
{newRef = _referenceCount--;}
#endif
if (newRef == 0) {
delete this;
}
return newRef;
}
int removeReferenceNoDelete() const {
return --_referenceCount;
}
inline size_t getReferenceCount() const {
return _referenceCount;
}
protected:
virtual inline ~Referenced() {
#ifdef DEBUG
if (_referenceCount)
std::cerr << "WARNING: Deleting Object with references: "
<< typeid(*this).name() << std::endl;
#endif
}
mutable size_t _referenceCount;
};
inline void intrusive_ptr_add_ref(Referenced* p) {
p->addReference();
}
inline void intrusive_ptr_release(Referenced* p) {
p->removeReference();
}
/**
@class ref_ptr
@brief Referenced pointer
*/
template<class T>
class ref_ptr {
public:
typedef T element_type;
ref_ptr() :
_ptr(0) {
}
ref_ptr(T* ptr) :
_ptr(ptr) {
if (_ptr)
_ptr->addReference();
}
ref_ptr(const ref_ptr& rp) :
_ptr(rp._ptr) {
if (_ptr)
_ptr->addReference();
}
template<class Other> ref_ptr(const ref_ptr<Other>& rp) :
_ptr(rp._ptr) {
if (_ptr)
_ptr->addReference();
}
~ref_ptr() {
if (_ptr)
_ptr->removeReference();
_ptr = 0;
}
ref_ptr& operator =(const ref_ptr& rp) {
assign(rp);
return *this;
}
template<class Other> ref_ptr& operator =(const ref_ptr<Other>& rp) {
assign(rp);
return *this;
}
inline ref_ptr& operator =(T* ptr) {
if (_ptr == ptr)
return *this;
T* tmp_ptr = _ptr;
_ptr = ptr;
if (_ptr)
_ptr->addReference();
if (tmp_ptr)
tmp_ptr->removeReference();
return *this;
}
operator T*() const {
return _ptr;
}
T& operator*() const {
return *_ptr;
}
T* operator->() const {
return _ptr;
}
T* get() const {
return _ptr;
}
bool operator!() const {
return _ptr == 0;
} // not required
bool valid() const {
return _ptr != 0;
}
T* release() {
T* tmp = _ptr;
if (_ptr)
_ptr->removeReferenceNoDelete();
_ptr = 0;
return tmp;
}
void swap(ref_ptr& rp) {
T* tmp = _ptr;
_ptr = rp._ptr;
rp._ptr = tmp;
}
private:
template<class Other> void assign(const ref_ptr<Other>& rp) {
if (_ptr == rp._ptr)
return;
T* tmp_ptr = _ptr;
_ptr = rp._ptr;
if (_ptr)
_ptr->addReference();
if (tmp_ptr)
tmp_ptr->removeReference();
}
template<class Other> friend class ref_ptr;
T* _ptr;
};
template<class T> inline
void swap(ref_ptr<T>& rp1, ref_ptr<T>& rp2) {
rp1.swap(rp2);
}
template<class T> inline T* get_pointer(const ref_ptr<T>& rp) {
return rp.get();
}
template<class T, class Y> inline ref_ptr<T> static_pointer_cast(
const ref_ptr<Y>& rp) {
return static_cast<T*>(rp.get());
}
template<class T, class Y> inline ref_ptr<T> dynamic_pointer_cast(
const ref_ptr<Y>& rp) {
return dynamic_cast<T*>(rp.get());
}
template<class T, class Y> inline ref_ptr<T> const_pointer_cast(
const ref_ptr<Y>& rp) {
return const_cast<T*>(rp.get());
}
/** @}*/
} // namespace crpropa
#endif // CRPROPA_REFERENCED_H
|
matmult.c | #include <stdio.h>
#include <stdlib.h>
#include "matmult_initialize.h"
int provided;
#include <mpi.h>
#ifndef MATRIX_SIZE
#define MATRIX_SIZE 512
#endif
#define NRA MATRIX_SIZE /* number of rows in matrix A */
#define NCA MATRIX_SIZE /* number of columns in matrix A */
#define NCB MATRIX_SIZE /* number of columns in matrix B */
double** allocateMatrix(int rows, int cols) {
int i;
double **matrix = (double**)malloc((sizeof(double*)) * rows);
for (i=0; i<rows; i++) {
matrix[i] = (double*)malloc((sizeof(double)) * cols);
}
return matrix;
}
void freeMatrix(double** matrix, int rows, int cols) {
int i;
for (i=0; i<rows; i++) {
free(matrix[i]);
}
free(matrix);
}
__inline double multiply(double a, double b) {
return a * b;
}
// cols_a and rows_b are the same value
void compute(double **a, double **b, double **c, int rows_a, int cols_a, int cols_b) {
int i,j,k;
#pragma omp parallel private(i,j,k) shared(a,b,c)
{
/*** Do matrix multiply sharing iterations on outer loop ***/
/*** Display who does which iterations for demonstration purposes ***/
#pragma omp for nowait
for (i=0; i<rows_a; i++) {
for(j=0; j<cols_b; j++) {
for (k=0; k<cols_a; k++) {
c[i][j] += multiply(a[i][k], b[k][j]);
}
}
}
} /*** End of parallel region ***/
}
void compute_interchange(double **a, double **b, double **c, int rows_a, int cols_a, int cols_b) {
int i,j,k;
#pragma omp parallel private(i,j,k) shared(a,b,c)
{
/*** Do matrix multiply sharing iterations on outer loop ***/
/*** Display who does which iterations for demonstration purposes ***/
#pragma omp for nowait
for (i=0; i<rows_a; i++) {
for (k=0; k<cols_a; k++) {
for(j=0; j<cols_b; j++) {
c[i][j] += multiply(a[i][k], b[k][j]);
}
}
}
} /*** End of parallel region ***/
}
double do_work(void) {
double **a, /* matrix A to be multiplied */
**b, /* matrix B to be multiplied */
**c; /* result matrix C */
a = allocateMatrix(NRA, NCA);
b = allocateMatrix(NCA, NCB);
c = allocateMatrix(NRA, NCB);
/*** Spawn a parallel region explicitly scoping all variables ***/
initialize(a, NRA, NCA);
initialize(b, NCA, NCB);
initialize(c, NRA, NCB);
compute(a, b, c, NRA, NCA, NCB);
compute_interchange(a, b, c, NRA, NCA, NCB);
double result = c[0][1];
freeMatrix(a, NRA, NCA);
freeMatrix(b, NCA, NCB);
freeMatrix(c, NCA, NCB);
return result;
}
int main (int argc, char *argv[])
{
int rc = MPI_Init_thread(&argc, &argv, MPI_THREAD_FUNNELED, &provided);
printf("MPI_Init_thread: provided = %d, MPI_THREAD_FUNNELED=%d\n", provided, MPI_THREAD_FUNNELED);
if (rc != MPI_SUCCESS) {
char *errorstring;
int length = 0;
MPI_Error_string(rc, errorstring, &length);
printf("Error: MPI_Init failed, rc = %d\n%s\n", rc, errorstring);
exit(1);
}
do_work();
MPI_Finalize();
printf ("Done.\n");
return 0;
}
|
fox_floats_timer_caching_omp_fileIO_benchmark.c | /* fox_floats_timer_caching_omp_fileIO_benchmark.c -- uses Fox's algorithm to multiply two square matrices
*
* Implementation of parallel matrix multiplication:
* LaTeX: $C_{i,j} = \sum_{k} A_{i,k}B_{k,j}$
*
* Input:
* Input Matrix file name: A.dat, B.dat
*
* Output:
* Output Matrix file name: C.dat
* Output Sub-matrices file name: SubMatrices.dat
*
* Notes:
* 1. Assumes the number of processes is a perfect square
* 2. The array member of the matrices is statically allocated
*
* See Chap 7, pp. 113 & ff and pp. 125 & ff in PPMPI
*/
/* Compiler command:
* mpiicc -O3 -qopenmp -qopt-report-phase=vec -qopt-report=3 fox_floats_timer_caching_omp_fileIO_benchmark.c
* -o fox_floats_timer_caching_omp_fileIO_benchmark
*
* Run command:
* mpirun -n -4 ./fox_floats_timer_caching_omp
*/
/* Head files */
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <mpi.h>
#include <omp.h>
// define problem scale, matrix row/col size
#define PROBLEM_SCALE 64
// define whether or not Print Matices in the Command Line
#define PRINT_A 0
#define PRINT_B 0
#define PRINT_C 0
#define PRINT_LOCAL_A 0
#define PRINT_LOCAL_B 0
#define PRINT_LOCAL_C 0
// define float precision, 4 byte single-precision float or 8 byte double-precision float
#define FLOAT double
#define FLOAT_MPI MPI_DOUBLE
// Define threads speed-up affnity in the computing
#define NUM_THREADS 2
// Define threads affinity "scatter" or "compact"
#define AFFINITY "KMP_AFFINITY = compact"
/* Type define structure of process grid */
typedef struct {
int p; /* Total number of processes */
MPI_Comm comm; /* Communicator for entire grid */
MPI_Comm row_comm; /* Communicator for my row */
MPI_Comm col_comm; /* Communicator for my col */
int q; /* Order of grid */
int my_row; /* My row number */
int my_col; /* My column number */
int my_rank; /* My rank in the grid comm */
} GRID_INFO_T;
/* Type define structure of local matrix */
#define MAX 2097152 // Maximum number of elements in the array that store the local matrix (2^21)
typedef struct {
int n_bar;
#define Order(A) ((A)->n_bar) // defination with parameters
FLOAT entries[MAX];
#define Entry(A,i,j) (*(((A)->entries) + ((A)->n_bar)*(i) + (j))) // defination with parameters, Array dereference
} LOCAL_MATRIX_T;
/* Function Declarations */
LOCAL_MATRIX_T* Local_matrix_allocate(int n_bar);
void Free_local_matrix(LOCAL_MATRIX_T** local_A);
void Read_matrix_A(char* prompt, LOCAL_MATRIX_T* local_A,
GRID_INFO_T* grid, int n); // Read matrix A from a file
void Read_matrix_B(char* prompt, LOCAL_MATRIX_T* local_B, // for continuous memory access, local A(i,k)*B(k,j) = A(i,k)*B^{T}(j,k)
GRID_INFO_T* grid, int n); // Read matrix B from a file
void Print_matrix_A(char* title, LOCAL_MATRIX_T* local_A,
GRID_INFO_T* grid, int n); // Print matrix A in the command line
void Print_matrix_B(char* title, LOCAL_MATRIX_T* local_B, // Speical print function for local matrix B^{T}(j,k)
GRID_INFO_T* grid, int n); // Print matrix B in the command line
void Print_matrix_C(char* title, LOCAL_MATRIX_T* local_C,
GRID_INFO_T* grid, int n); // Print matrix C in the command line
void Set_to_zero(LOCAL_MATRIX_T* local_A);
void Local_matrix_multiply(LOCAL_MATRIX_T* local_A,
LOCAL_MATRIX_T* local_B, LOCAL_MATRIX_T* local_C);
void Build_matrix_type(LOCAL_MATRIX_T* local_A);
MPI_Datatype local_matrix_mpi_t;
LOCAL_MATRIX_T* temp_mat; // global LOCAL_MATRIX_T* type pointer
void Print_local_matrices_A(char* title, LOCAL_MATRIX_T* local_A,
GRID_INFO_T* grid);
void Print_local_matrices_B(char* title, LOCAL_MATRIX_T* local_B, // Speical print function for local matrix B^{T}(j,k)
GRID_INFO_T* grid);
void Print_local_matrices_C(char* title, LOCAL_MATRIX_T* local_B,
GRID_INFO_T* grid);
void Write_matrix_C(char* title, LOCAL_MATRIX_T* local_C,
GRID_INFO_T* grid, int n); // Write matrix multiplication to a file
void Write_local_matrices_A(char* title, LOCAL_MATRIX_T* local_A,
GRID_INFO_T* grid); // Write local matrix A to a file
void Write_local_matrices_B(char* title, LOCAL_MATRIX_T* local_B, // Speical print function for local matrix B^{T}(j,k)
GRID_INFO_T* grid); // Write local matrix B to a file
void Write_local_matrices_C(char* title, LOCAL_MATRIX_T* local_A,
GRID_INFO_T* grid); // Write local matrix C to a file
/*********************************************************/
main(int argc, char* argv[]) {
FILE *fp;
int p;
int my_rank;
GRID_INFO_T grid;
LOCAL_MATRIX_T* local_A;
LOCAL_MATRIX_T* local_B;
LOCAL_MATRIX_T* local_C;
int n;
int n_bar;
double timer_start;
double timer_end;
int content;
int i;
int j;
void Setup_grid(GRID_INFO_T* grid);
void Fox(int n, GRID_INFO_T* grid, LOCAL_MATRIX_T* local_A,
LOCAL_MATRIX_T* local_B, LOCAL_MATRIX_T* local_C);
// Matrix Generator
fp = fopen("A.dat", "w"); // Generate and print matrix A into a file
for (i = 0; i < PROBLEM_SCALE; i++) {
for (j = 0; j < PROBLEM_SCALE; j++)
if(i == j){
fprintf(fp,"%d ", 1);
}
else {
fprintf(fp,"%d ", 0);
}
fprintf(fp,"\n");
}
fclose(fp);
fp = fopen("B.dat", "w"); // Generate and print matrix B into a file
for (i = 0; i < PROBLEM_SCALE; i++){
for (j = 0; j < PROBLEM_SCALE; j++)
fprintf(fp,"%d ", (i*PROBLEM_SCALE)+j);
fprintf(fp, "\n");
}
fclose(fp);
// SPMD Mode start from here (Processess fork from here)
MPI_Init(&argc, &argv); // MPI initializing
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); // Get my process id in the MPI communicator
// Initial OpenMP Environment
omp_set_num_threads(NUM_THREADS);
kmp_set_defaults(AFFINITY);
Setup_grid(&grid); // Set up Processess grid
if (my_rank == 0) {
fp = fopen("A.dat","r");
n = 0;
while((content = fgetc(fp)) != EOF)
{
//printf("fgetc = %d\n", content);
if(content != 0x20 && content != 0x0A) n++;
}
fclose(fp);
n = (int) sqrt((double) n);
printf("We read the order of the matrices from A.dat is\n %d\n", n);
// while(fgetc(fp) != EOF) n++;
// printf("What's the order of the matrices?\n");
// scanf("%d", &n); // Overall Matrix's Order
}
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD); // MPI broadcast the overall matrix's order
n_bar = n/grid.q; // \bar n is the local matrix's order
local_A = Local_matrix_allocate(n_bar); // Allocate local matrix A
Order(local_A) = n_bar; // Local matrix A's order
Read_matrix_A("Read A from A.dat", local_A, &grid, n); // Read local matrices A from process 0 by using stdin, and send them to each process (Procedure)
if (PRINT_A == 1)
Print_matrix_A("We read A =", local_A, &grid, n);// Print local matrices A from process 0 by using stdout, and send them to each process (Procedure)
local_B = Local_matrix_allocate(n_bar); // Allocate local matrix
Order(local_B) = n_bar; // Local matrix B's order
Read_matrix_B("Read B from B.dat", local_B, &grid, n); // Read local matrix B as it's local transpose from process 0 by using stdin, and send them to each process (Procedure)
if (PRINT_B == 1)
Print_matrix_B("We read B =", local_B, &grid, n);// Print local matrix B as it's local transpose from process 0 by using stdout, and send them to each process (Procedure)
Build_matrix_type(local_A); // Buid local_A's MPI matrix data type
temp_mat = Local_matrix_allocate(n_bar); // Allocate temporary matrix of order n $\time$ n
local_C = Local_matrix_allocate(n_bar); // Allocate matrix local_C
Order(local_C) = n_bar; // Set matrix local_C's order
MPI_Barrier(MPI_COMM_WORLD); // Set the MPI process barrier
timer_start = MPI_Wtime(); // Get the MPI wall time
Fox(n, &grid, local_A, local_B, local_C); // FOX parallel matrix multiplication Algorithm implement function
timer_end = MPI_Wtime(); // Get the MPI wall time
MPI_Barrier(MPI_COMM_WORLD); // Set the MPI process barrier
Write_matrix_C("Write C into the C.dat", local_C, &grid, n); // Print matrix local_C (parallel matrix multiplication result)
if (PRINT_C == 1)
Print_matrix_C("The product is", local_C, &grid, n); // Print matrix local_C (parallel matrix multiplication result)
Write_local_matrices_A("Write split of local matrix A into local_A.dat",
local_A, &grid); // Write local matrix A into file
if (PRINT_LOCAL_A == 1)
Print_local_matrices_A("Split of local matrix A",
local_A, &grid); // Print matrix A split in processess
Write_local_matrices_B("Write split of local matrix B into local_B.dat",
local_B, &grid); // Write local matrix B into file, special for row-major storage
if (PRINT_LOCAL_B == 1)
Print_local_matrices_B("Split of local matrix B",
local_B, &grid); // Print matrix B split in processess, special for row-major storage
Write_local_matrices_C("Write split of local matrix C into local_C.dat",
local_C, &grid); // Print matrix C split in processess
if (PRINT_LOCAL_C == 1)
Print_local_matrices_C("Split of local matrix C",
local_C, &grid); // Print matrix C split in processess
Free_local_matrix(&local_A); // Free local matrix local_A
Free_local_matrix(&local_B); // Free local matrix local_B
Free_local_matrix(&local_C); // Free local matrix local_C
if(my_rank == 0)
printf("Parallel Fox Matrix Multiplication Elapsed time:\n %30.20E seconds\n", timer_end-timer_start);
MPI_Finalize(); // MPI finalize, processes join and resource recycle
} /* main */
/*********************************************************/
void Setup_grid(
GRID_INFO_T* grid /* out */) {
int old_rank;
int dimensions[2];
int wrap_around[2];
int coordinates[2];
int free_coords[2];
/* Set up Global Grid Information */
MPI_Comm_size(MPI_COMM_WORLD, &(grid->p));
MPI_Comm_rank(MPI_COMM_WORLD, &old_rank);
/* We assume p is a perfect square */ // but what if it's not a perfect square
grid->q = (int) sqrt((double) grid->p);
dimensions[0] = dimensions[1] = grid->q;
/* We want a circular shift in second dimension. */
/* Don't care about first */
wrap_around[0] = wrap_around[1] = 1;
MPI_Cart_create(MPI_COMM_WORLD, 2, dimensions,
wrap_around, 1, &(grid->comm));
MPI_Comm_rank(grid->comm, &(grid->my_rank));
MPI_Cart_coords(grid->comm, grid->my_rank, 2,
coordinates);
grid->my_row = coordinates[0];
grid->my_col = coordinates[1];
/* Set up row communicators */
free_coords[0] = 0;
free_coords[1] = 1;
MPI_Cart_sub(grid->comm, free_coords,
&(grid->row_comm));
/* Set up column communicators */
free_coords[0] = 1;
free_coords[1] = 0;
MPI_Cart_sub(grid->comm, free_coords,
&(grid->col_comm));
} /* Setup_grid */
/*********************************************************/
void Fox(
int n /* in */,
GRID_INFO_T* grid /* in */,
LOCAL_MATRIX_T* local_A /* in */,
LOCAL_MATRIX_T* local_B /* in */,
LOCAL_MATRIX_T* local_C /* out */) {
LOCAL_MATRIX_T* temp_A; /* Storage for the sub- */
/* matrix of A used during */
/* the current stage */
int stage;
int bcast_root;
int n_bar; /* n/sqrt(p) */
int source;
int dest;
MPI_Status status;
n_bar = n/grid->q;
Set_to_zero(local_C);
/* Calculate addresses for row circular shift of B */
source = (grid->my_row + 1) % grid->q;
dest = (grid->my_row + grid->q - 1) % grid->q;
/* Set aside storage for the broadcast block of A */
temp_A = Local_matrix_allocate(n_bar);
for (stage = 0; stage < grid->q; stage++) {
bcast_root = (grid->my_row + stage) % grid->q;
if (bcast_root == grid->my_col) { // Process P_{ii} broadcast A_{ii} in process gird's row commnunicator
MPI_Bcast(local_A, 1, local_matrix_mpi_t,
bcast_root, grid->row_comm);
Local_matrix_multiply(local_A, local_B,
local_C);
} else { // temp_A is a buffer for process P_{ij} to store A_{ij}
MPI_Bcast(temp_A, 1, local_matrix_mpi_t,
bcast_root, grid->row_comm);
Local_matrix_multiply(temp_A, local_B,
local_C);
}
MPI_Sendrecv_replace(local_B, 1, local_matrix_mpi_t, // MPI send and receive with single buffer
dest, 0, source, 0, grid->col_comm, &status); // Circular shift of process grid B's row, after local multiplication operation
} /* for */
} /* Fox */
/*********************************************************/
LOCAL_MATRIX_T* Local_matrix_allocate(int local_order) {
LOCAL_MATRIX_T* temp;
temp = (LOCAL_MATRIX_T*) malloc(sizeof(LOCAL_MATRIX_T));
return temp;
} /* Local_matrix_allocate */
/*********************************************************/
void Free_local_matrix(
LOCAL_MATRIX_T** local_A_ptr /* in/out */) {
free(*local_A_ptr);
} /* Free_local_matrix */
/*********************************************************/
/* Read and distribute matrix for matrix A:
* foreach global row of the matrix,
* foreach grid column
* read a block of n_bar floats on process 0
* and send them to the appropriate process.
*/
void Read_matrix_A(
char* prompt /* in */,
LOCAL_MATRIX_T* local_A /* out */,
GRID_INFO_T* grid /* in */,
int n /* in */) {
FILE *fp;
int mat_row, mat_col;
int grid_row, grid_col;
int dest;
int coords[2];
FLOAT* temp;
MPI_Status status;
if (grid->my_rank == 0) { // Process 0 read matrix input from stdin and send them to other processess
fp = fopen("A.dat","r");
temp = (FLOAT*) malloc(Order(local_A)*sizeof(FLOAT));
printf("%s\n", prompt);
fflush(stdout);
for (mat_row = 0; mat_row < n; mat_row++) {
grid_row = mat_row/Order(local_A);
coords[0] = grid_row;
for (grid_col = 0; grid_col < grid->q; grid_col++) {
coords[1] = grid_col;
MPI_Cart_rank(grid->comm, coords, &dest);
if (dest == 0) {
for (mat_col = 0; mat_col < Order(local_A); mat_col++)
fscanf(fp, "%lf",
(local_A->entries)+mat_row*Order(local_A)+mat_col);
/* scanf("%lf",
(local_A->entries)+mat_row*Order(local_A)+mat_col);
*/
} else {
for(mat_col = 0; mat_col < Order(local_A); mat_col++)
fscanf(fp,"%lf", temp + mat_col);
// scanf("%lf", temp + mat_col);
MPI_Send(temp, Order(local_A), FLOAT_MPI, dest, 0,
grid->comm);
}
}
}
free(temp);
fclose(fp);
} else { // Other processess receive matrix from process 0
for (mat_row = 0; mat_row < Order(local_A); mat_row++)
MPI_Recv(&Entry(local_A, mat_row, 0), Order(local_A),
FLOAT_MPI, 0, 0, grid->comm, &status);
}
} /* Read_matrix */
/*********************************************************/
/* Read and distribute matrix for local matrix B's transpose:
* foreach global row of the matrix,
* foreach grid column
* read a block of n_bar floats on process 0
* and send them to the appropriate process.
*/
void Read_matrix_B(
char* prompt /* in */,
LOCAL_MATRIX_T* local_B /* out */,
GRID_INFO_T* grid /* in */,
int n /* in */) {
FILE *fp;
int mat_row, mat_col;
int grid_row, grid_col;
int dest;
int coords[2];
FLOAT *temp;
MPI_Status status;
if (grid->my_rank == 0) { // Process 0 read matrix input from stdin and send them to other processess
fp = fopen("B.dat","r");
temp = (FLOAT*) malloc(Order(local_B)*sizeof(FLOAT));
printf("%s\n", prompt);
fflush(stdout);
for (mat_row = 0; mat_row < n; mat_row++) {
grid_row = mat_row/Order(local_B);
coords[0] = grid_row;
for (grid_col = 0; grid_col < grid->q; grid_col++) {
coords[1] = grid_col;
MPI_Cart_rank(grid->comm, coords, &dest);
if (dest == 0) { // process 0 (local)
for (mat_col = 0; mat_col < Order(local_B); mat_col++)
fscanf(fp, "%lf",
(local_B->entries)+mat_col*Order(local_B)+mat_row); // switch rows and colums in local_B, for column major storage
/* scanf("%lf",
(local_B->entries)+mat_col*Order(local_B)+mat_row); // switch rows and colums in local_B, for column major storage
*/
/* scanf("%lf",
(local_A->entries)+mat_row*Order(local_A)+mat_col); */
} else {
for(mat_col = 0; mat_col < Order(local_B); mat_col++)
fscanf(fp, "%lf", temp + mat_col);
// scanf("%lf", temp + mat_col);
MPI_Send(temp, Order(local_B), FLOAT_MPI, dest, 0,
grid->comm);
}
}
}
free(temp);
fclose(fp);
} else { // Other processess receive matrix from process 0
temp = (FLOAT*) malloc(Order(local_B)*sizeof(FLOAT)); // switch rows and colums in local_B, for column major storage
for (mat_col = 0; mat_col < Order(local_B); mat_col++) {
MPI_Recv(temp, Order(local_B),
FLOAT_MPI, 0, 0, grid->comm, &status); // switch rows and colums in local_B, for column major storage
for(mat_row = 0; mat_row < Order(local_B); mat_row++)
Entry(local_B, mat_row, mat_col) = *(temp + mat_row); // switch rows and colums in local_B, for column major storage
/* MPI_Recv(&Entry(local_A, mat_row, 0), Order(local_A),
FLOAT_MPI, 0, 0, grid->comm, &status); */
}
free(temp);
}
} /* Read_matrix_B */
/*********************************************************/
/* Recive and Print Matrix A:
* foreach global row of the matrix,
* foreach grid column
* send n_bar floats to process 0 from each other process
* receive a block of n_bar floats on process 0 from other processes and print them
*/
void Print_matrix_A(
char* title /* in */,
LOCAL_MATRIX_T* local_A /* out */,
GRID_INFO_T* grid /* in */,
int n /* in */) {
int mat_row, mat_col;
int grid_row, grid_col;
int source;
int coords[2];
FLOAT* temp;
MPI_Status status;
if (grid->my_rank == 0) {
temp = (FLOAT*) malloc(Order(local_A)*sizeof(FLOAT));
printf("%s\n", title);
for (mat_row = 0; mat_row < n; mat_row++) {
grid_row = mat_row/Order(local_A);
coords[0] = grid_row;
for (grid_col = 0; grid_col < grid->q; grid_col++) {
coords[1] = grid_col;
MPI_Cart_rank(grid->comm, coords, &source);
if (source == 0) {
for(mat_col = 0; mat_col < Order(local_A); mat_col++)
printf("%20.15E ", Entry(local_A, mat_row, mat_col));
} else {
MPI_Recv(temp, Order(local_A), FLOAT_MPI, source, 0,
grid->comm, &status);
for(mat_col = 0; mat_col < Order(local_A); mat_col++)
printf("%20.15E ", temp[mat_col]);
}
}
printf("\n");
}
free(temp);
} else {
for (mat_row = 0; mat_row < Order(local_A); mat_row++)
MPI_Send(&Entry(local_A, mat_row, 0), Order(local_A),
FLOAT_MPI, 0, 0, grid->comm);
}
} /* Print_matrix_A */
/*********************************************************/
/* Recive and Print Matrix for local matrix B's transpose:
* foreach global row of the matrix,
* foreach grid column
* send n_bar floats to process 0 from each other process
* receive a block of n_bar floats on process 0 from other processes and print them
*/
void Print_matrix_B(
char* title /* in */,
LOCAL_MATRIX_T* local_B /* out */,
GRID_INFO_T* grid /* in */,
int n /* in */) {
int mat_row, mat_col;
int grid_row, grid_col;
int source;
int coords[2];
FLOAT* temp;
MPI_Status status;
if (grid->my_rank == 0) {
temp = (FLOAT*) malloc(Order(local_B)*sizeof(FLOAT));
printf("%s\n", title);
for (mat_row = 0; mat_row < n; mat_row++) {
grid_row = mat_row/Order(local_B);
coords[0] = grid_row;
for (grid_col = 0; grid_col < grid->q; grid_col++) {
coords[1] = grid_col;
MPI_Cart_rank(grid->comm, coords, &source);
if (source == 0) {
for(mat_col = 0; mat_col < Order(local_B); mat_col++)
printf("%20.15E ", Entry(local_B, mat_col, mat_row)); // switch rows and colums in local_B, for column major storage
// printf("%20.15E ", Entry(local_A, mat_row, mat_col));
} else {
MPI_Recv(temp, Order(local_B), FLOAT_MPI, source, 0,
grid->comm, &status);
for(mat_col = 0; mat_col < Order(local_B); mat_col++)
printf("%20.15E ", temp[mat_col]);
}
}
printf("\n");
}
free(temp);
} else {
temp = (FLOAT*) malloc(Order(local_B)*sizeof(FLOAT));
for (mat_col = 0; mat_col < Order(local_B); mat_col++) {
for(mat_row = 0; mat_row < Order(local_B); mat_row++)
*(temp+mat_row) = Entry(local_B, mat_row, mat_col); // switch rows and colums in local_B, for column major storage
MPI_Send(temp, Order(local_B), FLOAT_MPI, 0, 0, grid->comm);
}
free(temp);
}
} /* Print_matrix_B */
/*********************************************************/
/* Recive and Print Matrix A:
* foreach global row of the matrix,
* foreach grid column
* send n_bar floats to process 0 from each other process
* receive a block of n_bar floats on process 0 from other processes and print them
*/
void Print_matrix_C(
char* title /* in */,
LOCAL_MATRIX_T* local_C /* out */,
GRID_INFO_T* grid /* in */,
int n /* in */) {
int mat_row, mat_col;
int grid_row, grid_col;
int source;
int coords[2];
FLOAT* temp;
MPI_Status status;
if (grid->my_rank == 0) {
temp = (FLOAT*) malloc(Order(local_C)*sizeof(FLOAT));
printf("%s\n", title);
for (mat_row = 0; mat_row < n; mat_row++) {
grid_row = mat_row/Order(local_C);
coords[0] = grid_row;
for (grid_col = 0; grid_col < grid->q; grid_col++) {
coords[1] = grid_col;
MPI_Cart_rank(grid->comm, coords, &source);
if (source == 0) {
for(mat_col = 0; mat_col < Order(local_C); mat_col++)
printf("%20.15E ", Entry(local_C, mat_row, mat_col));
} else {
MPI_Recv(temp, Order(local_C), FLOAT_MPI, source, 0,
grid->comm, &status);
for(mat_col = 0; mat_col < Order(local_C); mat_col++)
printf("%20.15E ", temp[mat_col]);
}
}
printf("\n");
}
free(temp);
} else {
for (mat_row = 0; mat_row < Order(local_C); mat_row++)
MPI_Send(&Entry(local_C, mat_row, 0), Order(local_C),
FLOAT_MPI, 0, 0, grid->comm);
}
} /* Print_matrix_C */
/*********************************************************/
/* Recive and Write Matrix C into a file:
* foreach global row of the matrix,
* foreach grid column
* send n_bar floats to process 0 from each other process
* receive a block of n_bar floats on process 0 from other processes and print them
*/
void Write_matrix_C(
char* title /* in */,
LOCAL_MATRIX_T* local_C /* out */,
GRID_INFO_T* grid /* in */,
int n /* in */) {
FILE *fp;
int mat_row, mat_col;
int grid_row, grid_col;
int source;
int coords[2];
FLOAT* temp;
MPI_Status status;
if (grid->my_rank == 0) {
fp = fopen("C.dat", "w+");
temp = (FLOAT*) malloc(Order(local_C)*sizeof(FLOAT));
printf("%s\n", title);
for (mat_row = 0; mat_row < n; mat_row++) {
grid_row = mat_row/Order(local_C);
coords[0] = grid_row;
for (grid_col = 0; grid_col < grid->q; grid_col++) {
coords[1] = grid_col;
MPI_Cart_rank(grid->comm, coords, &source);
if (source == 0) {
for(mat_col = 0; mat_col < Order(local_C); mat_col++)
fprintf(fp, "%20.15E ", Entry(local_C, mat_row, mat_col));
// printf("%20.15E ", Entry(local_A, mat_row, mat_col));
} else {
MPI_Recv(temp, Order(local_C), FLOAT_MPI, source, 0,
grid->comm, &status);
for(mat_col = 0; mat_col < Order(local_C); mat_col++)
fprintf(fp, "%20.15E ", temp[mat_col]);
// printf("%20.15E ", temp[mat_col]);
}
}
fprintf(fp,"\n");
}
free(temp);
fclose(fp);
} else {
for (mat_row = 0; mat_row < Order(local_C); mat_row++)
MPI_Send(&Entry(local_C, mat_row, 0), Order(local_C),
FLOAT_MPI, 0, 0, grid->comm);
}
} /* Write_matrix_C */
/*********************************************************/
/*
* Set local matrix's element to zero
*/
void Set_to_zero(
LOCAL_MATRIX_T* local_A /* out */) {
int i, j;
for (i = 0; i < Order(local_A); i++)
for (j = 0; j < Order(local_A); j++)
Entry(local_A,i,j) = 0.0E0;
} /* Set_to_zero */
/*********************************************************/
void Build_matrix_type(
LOCAL_MATRIX_T* local_A /* in */) {
MPI_Datatype temp_mpi_t;
int block_lengths[2];
MPI_Aint displacements[2];
MPI_Datatype typelist[2];
MPI_Aint start_address;
MPI_Aint address;
MPI_Type_contiguous(Order(local_A)*Order(local_A),
FLOAT_MPI, &temp_mpi_t); // Creates a contiguous datatype
/*
Synopsis
int MPI_Type_contiguous(int count,
MPI_Datatype oldtype,
MPI_Datatype *newtype)
Input Parameters
count
replication count (nonnegative integer)
oldtype
old datatype (handle)
*/
block_lengths[0] = block_lengths[1] = 1;
typelist[0] = MPI_INT;
typelist[1] = temp_mpi_t;
MPI_Address(local_A, &start_address); // Gets the address of a location in caller's memory
MPI_Address(&(local_A->n_bar), &address);
/*
Synopsis
int MPI_Address(const void *location, MPI_Aint *address)
Input Parameters
location
location in caller memory (choice)
Output Parameters
address
address of location (address integer)
*/
displacements[0] = address - start_address;
MPI_Address(local_A->entries, &address);
displacements[1] = address - start_address;
MPI_Type_struct(2, block_lengths, displacements,
typelist, &local_matrix_mpi_t); // Creates a struct datatype
/*
Synopsis
int MPI_Type_struct(int count,
const int *array_of_blocklengths,
const MPI_Aint *array_of_displacements,
const MPI_Datatype *array_of_types,
MPI_Datatype *newtype)
Input Parameters
count
number of blocks (integer) -- also number of entries in arrays array_of_types , array_of_displacements and array_of_blocklengths
array_of_blocklengths
number of elements in each block (array)
array_of_displacements
byte displacement of each block (array)
array_of_types
type of elements in each block (array of handles to datatype objects)
Output Parameters
newtype
new datatype (handle)
*/
MPI_Type_commit(&local_matrix_mpi_t); // Commits the datatype
/*
Synopsis
int MPI_Type_commit(MPI_Datatype *datatype)
Input Parameters
datatype
datatype (handle)
*/
} /* Build_matrix_type */
/*********************************************************/
/* local matrix multiplication function
* withing OpenMP Thread Acceleration
*/
void Local_matrix_multiply(
LOCAL_MATRIX_T* local_A /* in */,
LOCAL_MATRIX_T* local_B /* in */,
LOCAL_MATRIX_T* local_C /* out */) {
int i, j, k;
// int my_rank;
// MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); // Get my process id in the MPI communicator
#pragma omp parallel for private(i, j, k) shared(local_A, local_B, local_C) num_threads(NUM_THREADS) // Threads acceleration upgrade, parallel task split
for (i = 0; i < Order(local_A); i++) {
// printf("Current in the Fox Kernel:\n my process id is %d, my thread id is %d\n",my_rank,omp_get_thread_num());
for (j = 0; j < Order(local_A); j++)
for (k = 0; k < Order(local_B); k++)
Entry(local_C,i,j) = Entry(local_C,i,j) // switch rows and colums in local_B, for column major storage
+ Entry(local_A,i,k)*Entry(local_B,j,k); // continuous memory access, local matrix multiplication A(i,k)*B^T(j,k)
/* Entry(local_C,i,j) = Entry(local_C,i,j)
+ Entry(local_A,i,k)*Entry(local_B,k,j); // non-continuous memory access, A(i,k)*B^T(j,k) is more proper
*/
}
} /* Local_matrix_multiply */
/*********************************************************/
/* Recive and Print Local Matrix A:
* Process 0 print local matrix local_A
* Other Processess send local matrix local_A to process 0
* And process 0 receive local matrix local_A from other processess
*/
void Print_local_matrices_A(
char* title /* in */,
LOCAL_MATRIX_T* local_A /* in */,
GRID_INFO_T* grid /* in */) {
int coords[2];
int i, j;
int source;
MPI_Status status;
// print by process No.0 in process mesh
if (grid->my_rank == 0) {
printf("%s\n", title);
printf("Process %d > grid_row = %d, grid_col = %d\n",
grid->my_rank, grid->my_row, grid->my_col);
for (i = 0; i < Order(local_A); i++) {
for (j = 0; j < Order(local_A); j++)
printf("%20.15E ", Entry(local_A,i,j));
printf("\n");
}
for (source = 1; source < grid->p; source++) {
MPI_Recv(temp_mat, 1, local_matrix_mpi_t, source, 0,
grid->comm, &status);
MPI_Cart_coords(grid->comm, source, 2, coords);
printf("Process %d > grid_row = %d, grid_col = %d\n",
source, coords[0], coords[1]);
for (i = 0; i < Order(temp_mat); i++) {
for (j = 0; j < Order(temp_mat); j++)
printf("%20.15E ", Entry(temp_mat,i,j));
printf("\n");
}
}
fflush(stdout);
} else {
MPI_Send(local_A, 1, local_matrix_mpi_t, 0, 0, grid->comm);
}
} /* Print_local_matrices_A */
/*********************************************************/
/* Recive and Print Local Matrix for local matrix B's transpose:
* Process 0 print local matrix local_A
* Other Processess send local matrix local_A to process 0
* And process 0 receive local matrix local_A from other processess
*/
void Print_local_matrices_B(
char* title /* in */,
LOCAL_MATRIX_T* local_B /* in */,
GRID_INFO_T* grid /* in */) {
int coords[2];
int i, j;
int source;
MPI_Status status;
// print by process No.0 in process mesh
if (grid->my_rank == 0) {
printf("%s\n", title);
printf("Process %d > grid_row = %d, grid_col = %d\n",
grid->my_rank, grid->my_row, grid->my_col);
for (i = 0; i < Order(local_B); i++) {
for (j = 0; j < Order(local_B); j++)
printf("%20.15E ", Entry(local_B,j,i)); // switch rows and colums in local_B, for column major storage
printf("\n");
}
for (source = 1; source < grid->p; source++) {
MPI_Recv(temp_mat, 1, local_matrix_mpi_t, source, 0,
grid->comm, &status);
MPI_Cart_coords(grid->comm, source, 2, coords);
printf("Process %d > grid_row = %d, grid_col = %d\n",
source, coords[0], coords[1]);
for (i = 0; i < Order(temp_mat); i++) {
for (j = 0; j < Order(temp_mat); j++)
printf("%20.15E ", Entry(temp_mat,j,i)); // switch rows and colums in local_B, for column major storage
printf("\n");
}
}
fflush(stdout);
} else {
MPI_Send(local_B, 1, local_matrix_mpi_t, 0, 0, grid->comm);
}
} /* Print_local_matrices_B */
/*********************************************************/
/* Recive and Print Local Matrix A:
* Process 0 print local matrix local_A
* Other Processess send local matrix local_A to process 0
* And process 0 receive local matrix local_A from other processess
*/
void Print_local_matrices_C(
char* title /* in */,
LOCAL_MATRIX_T* local_C /* in */,
GRID_INFO_T* grid /* in */) {
int coords[2];
int i, j;
int source;
MPI_Status status;
// print by process No.0 in process mesh
if (grid->my_rank == 0) {
printf("%s\n", title);
printf("Process %d > grid_row = %d, grid_col = %d\n",
grid->my_rank, grid->my_row, grid->my_col);
for (i = 0; i < Order(local_C); i++) {
for (j = 0; j < Order(local_C); j++)
printf("%20.15E ", Entry(local_C,i,j));
printf("\n");
}
for (source = 1; source < grid->p; source++) {
MPI_Recv(temp_mat, 1, local_matrix_mpi_t, source, 0,
grid->comm, &status);
MPI_Cart_coords(grid->comm, source, 2, coords);
printf("Process %d > grid_row = %d, grid_col = %d\n",
source, coords[0], coords[1]);
for (i = 0; i < Order(temp_mat); i++) {
for (j = 0; j < Order(temp_mat); j++)
printf("%20.15E ", Entry(temp_mat,i,j));
printf("\n");
}
}
fflush(stdout);
} else {
MPI_Send(local_C, 1, local_matrix_mpi_t, 0, 0, grid->comm);
}
} /* Print_local_matrices_C */
/*********************************************************/
/* Recive and Write Local Matrix A:
* Process 0 print local matrix local_A
* Other Processess send local matrix local_A to process 0
* And process 0 receive local matrix local_A from other processess
*/
void Write_local_matrices_A(
char* title /* in */,
LOCAL_MATRIX_T* local_A /* in */,
GRID_INFO_T* grid /* in */) {
FILE *fp;
int coords[2];
int i, j;
int source;
MPI_Status status;
// print by process No.0 in process mesh
if (grid->my_rank == 0) {
fp = fopen("local_A.dat","w+");
printf("%s\n", title);
fprintf(fp,"Process %d > grid_row = %d, grid_col = %d\n",
grid->my_rank, grid->my_row, grid->my_col);
for (i = 0; i < Order(local_A); i++) {
for (j = 0; j < Order(local_A); j++)
fprintf(fp,"%20.15E ", Entry(local_A,i,j));
fprintf(fp, "\n");
}
for (source = 1; source < grid->p; source++) {
MPI_Recv(temp_mat, 1, local_matrix_mpi_t, source, 0,
grid->comm, &status);
MPI_Cart_coords(grid->comm, source, 2, coords);
fprintf(fp, "Process %d > grid_row = %d, grid_col = %d\n",
source, coords[0], coords[1]);
for (i = 0; i < Order(temp_mat); i++) {
for (j = 0; j < Order(temp_mat); j++)
fprintf(fp, "%20.15E ", Entry(temp_mat,i,j));
fprintf(fp, "\n");
}
}
fflush(stdout);
fclose(fp);
} else {
MPI_Send(local_A, 1, local_matrix_mpi_t, 0, 0, grid->comm);
}
} /* Write_local_matrices_A */
/*********************************************************/
/* Recive and Write Local Matrix for local matrix B's transpose:
* Process 0 print local matrix local_A
* Other Processess send local matrix local_A to process 0
* And process 0 receive local matrix local_A from other processess
*/
void Write_local_matrices_B(
char* title /* in */,
LOCAL_MATRIX_T* local_B /* in */,
GRID_INFO_T* grid /* in */) {
FILE *fp;
int coords[2];
int i, j;
int source;
MPI_Status status;
// print by process No.0 in process mesh
if (grid->my_rank == 0) {
fp = fopen("local_B.dat","w+");
printf("%s\n", title);
fprintf(fp, "Process %d > grid_row = %d, grid_col = %d\n",
grid->my_rank, grid->my_row, grid->my_col);
for (i = 0; i < Order(local_B); i++) {
for (j = 0; j < Order(local_B); j++)
fprintf(fp, "%20.15E ", Entry(local_B,j,i)); // switch rows and colums in local_B, for column major storage
fprintf(fp, "\n");
}
for (source = 1; source < grid->p; source++) {
MPI_Recv(temp_mat, 1, local_matrix_mpi_t, source, 0,
grid->comm, &status);
MPI_Cart_coords(grid->comm, source, 2, coords);
fprintf(fp, "Process %d > grid_row = %d, grid_col = %d\n",
source, coords[0], coords[1]);
for (i = 0; i < Order(temp_mat); i++) {
for (j = 0; j < Order(temp_mat); j++)
fprintf(fp, "%20.15E ", Entry(temp_mat,j,i)); // switch rows and colums in local_B, for column major storage
fprintf(fp, "\n");
}
}
fflush(stdout);
fclose(fp);
} else {
MPI_Send(local_B, 1, local_matrix_mpi_t, 0, 0, grid->comm);
}
} /* Write_local_matrices_B */
/*********************************************************/
/* Recive and Write Local Matrix C:
* Process 0 print local matrix local_C
* Other Processess send local matrix local_C to process 0
* And process 0 receive local matrix local_C from other processess
*/
void Write_local_matrices_C(
char* title /* in */,
LOCAL_MATRIX_T* local_C /* in */,
GRID_INFO_T* grid /* in */) {
FILE *fp;
int coords[2];
int i, j;
int source;
MPI_Status status;
// print by process No.0 in process mesh
if (grid->my_rank == 0) {
fp = fopen("local_C.dat","w+");
printf("%s\n", title);
fprintf(fp, "Process %d > grid_row = %d, grid_col = %d\n",
grid->my_rank, grid->my_row, grid->my_col);
for (i = 0; i < Order(local_C); i++) {
for (j = 0; j < Order(local_C); j++)
fprintf(fp, "%20.15E ", Entry(local_C,i,j));
fprintf(fp, "\n");
}
for (source = 1; source < grid->p; source++) {
MPI_Recv(temp_mat, 1, local_matrix_mpi_t, source, 0,
grid->comm, &status);
MPI_Cart_coords(grid->comm, source, 2, coords);
fprintf(fp, "Process %d > grid_row = %d, grid_col = %d\n",
source, coords[0], coords[1]);
for (i = 0; i < Order(temp_mat); i++) {
for (j = 0; j < Order(temp_mat); j++)
fprintf(fp, "%20.15E ", Entry(temp_mat,i,j));
fprintf(fp, "\n");
}
}
fflush(stdout);
fclose(fp);
} else {
MPI_Send(local_C, 1, local_matrix_mpi_t, 0, 0, grid->comm);
}
} /* Write_local_matrices_C */
|
sageInterface.h | #ifndef ROSE_SAGE_INTERFACE
#define ROSE_SAGE_INTERFACE
#include "sage3basic.hhh"
#include <stdint.h>
#include <utility>
#include "rosePublicConfig.h" // for ROSE_BUILD_JAVA_LANGUAGE_SUPPORT
#include "OmpAttribute.h"
#if 0 // FMZ(07/07/2010): the argument "nextErrorCode" should be call-by-reference
SgFile* determineFileType ( std::vector<std::string> argv, int nextErrorCode, SgProject* project );
#else
SgFile* determineFileType ( std::vector<std::string> argv, int& nextErrorCode, SgProject* project );
#endif
#ifndef ROSE_USE_INTERNAL_FRONTEND_DEVELOPMENT
#include "rewrite.h"
#endif
// DQ (7/20/2008): Added support for unparsing abitrary strings in the unparser.
#include "astUnparseAttribute.h"
#include <set>
#ifndef ROSE_USE_INTERNAL_FRONTEND_DEVELOPMENT
#include "LivenessAnalysis.h"
#include "abstract_handle.h"
#include "ClassHierarchyGraph.h"
#endif
// DQ (8/19/2004): Moved from ROSE/src/midend/astRewriteMechanism/rewrite.h
//! A global function for getting the string associated with an enum (which is defined in global scope)
ROSE_DLL_API std::string getVariantName (VariantT v);
// DQ (12/9/2004): Qing, Rich and Dan have decided to start this namespace within ROSE
// This namespace is specific to interface functions that operate on the Sage III AST.
// The name was chosen so as not to conflict with other classes within ROSE.
// This will become the future home of many interface functions which operate on
// the AST and which are generally useful to users. As a namespace multiple files can be used
// to represent the compete interface and different developers may contribute interface
// functions easily.
// Constructor handling: (We have sageBuilder.h now for this purpose, Liao 2/1/2008)
// We could add simpler layers of support for construction of IR nodes by
// hiding many details in "makeSg***()" functions. Such functions would
// return pointers to the associated Sg*** objects and would be able to hide
// many IR specific details, including:
// memory handling
// optional parameter settings not often required
// use of Sg_File_Info objects (and setting them as transformations)
//
// namespace AST_Interface (this name is taken already by some of Qing's work :-)
//! An alias for Sg_File_Info::generateDefaultFileInfoForTransformationNode()
#define TRANS_FILE Sg_File_Info::generateDefaultFileInfoForTransformationNode()
/** Functions that are useful when operating on the AST.
*
* The Sage III IR design attempts to be minimalist. Thus additional functionality is intended to be presented using separate
* higher level interfaces which work with the IR. This namespace collects functions that operate on the IR and support
* numerous types of operations that are common to general analysis and transformation of the AST. */
namespace SageInterface
{
// Liao 6/22/2016: keep records of loop init-stmt normalization, later help undo it to support autoPar.
struct Transformation_Record
{
// a lookup table to check if a for loop has been normalized for its c99-style init-stmt
std::map <SgForStatement* , bool > forLoopInitNormalizationTable;
// Detailed record about the original declaration (1st in the pair) and the normalization generated new declaration (2nd in the pair)
std::map <SgForStatement* , std::pair<SgVariableDeclaration*, SgVariableDeclaration*> > forLoopInitNormalizationRecord;
} ;
ROSE_DLL_API extern Transformation_Record trans_records;
// DQ (4/3/2014): Added general AST support separate from the AST.
// Container and API for analysis information that is outside of the AST and as a result
// prevents frequent modification of the IR.
class DeclarationSets
{
// DQ (4/3/2014): This stores all associated declarations as a map of sets.
// the key to the map is the first nondefining declaration and the elements of the set are
// all of the associated declarations (including the defining declaration).
private:
//! Map of first-nondefining declaration to all other associated declarations.
std::map<SgDeclarationStatement*,std::set<SgDeclarationStatement*>* > declarationMap;
public:
void addDeclaration(SgDeclarationStatement* decl);
const std::set<SgDeclarationStatement*>* getDeclarations(SgDeclarationStatement* decl);
std::map<SgDeclarationStatement*,std::set<SgDeclarationStatement*>* > & getDeclarationMap();
bool isLocatedInDefiningScope(SgDeclarationStatement* decl);
};
// DQ (4/3/2014): This constructs a data structure that holds analysis information about
// the AST that is separate from the AST. This is intended to be a general mechanism
// to support analysis information without constantly modifying the IR.
DeclarationSets* buildDeclarationSets(SgNode*);
//! An internal counter for generating unique SgName
ROSE_DLL_API extern int gensym_counter;
// tps : 28 Oct 2008 - support for finding the main interpretation
SgAsmInterpretation* getMainInterpretation(SgAsmGenericFile* file);
//! Get the unsigned value of a disassembled constant.
uint64_t getAsmConstant(SgAsmValueExpression* e);
//! Get the signed value of a disassembled constant.
int64_t getAsmSignedConstant(SgAsmValueExpression *e);
//! Function to add "C" style comment to statement.
void addMessageStatement( SgStatement* stmt, std::string message );
//! A persistent attribute to represent a unique name for an expression
class UniqueNameAttribute : public AstAttribute
{
private:
std::string name;
public:
UniqueNameAttribute(std::string n="") {name =n; };
void set_name (std::string n) {name = n;};
std::string get_name () {return name;};
};
// DQ (3/2/2009): Added support for collectiong an merging the referenced symbols in the outlined
// function into the list used to edit the outlined code subtree to fixup references (from symbols
// in the original file to the symbols in the newer separate file).
// typedef rose_hash::unordered_map<SgNode*, SgNode*, hash_nodeptr> ReplacementMapType;
// void supplementReplacementSymbolMap ( const ReplacementMapTraversal::ReplacementMapType & inputReplacementMap );
// CH (4/9/2010): Use boost::hash instead
//#ifdef _MSC_VER
#if 0
inline size_t hash_value(SgNode* t) {return (size_t)t;}
#endif
#if 0
// DQ (8/3/2015): We expect that this is not used and is generating a warnings so we
// can best fix it by removing it.
struct hash_nodeptr
{
// CH (4/9/2010): Use boost::hash instead
//#ifndef _MSC_VER
#if 0
//rose_hash::hash<char*> hasher;
#endif
public:
size_t operator()(SgNode* node) const
{
// CH (4/9/2010): Use boost::hash instead
//#ifdef _MSC_VER
#if 0
return (size_t) hash_value(node);
#else
return (size_t) node;
#endif
}
};
#ifndef SWIG
// DQ (3/10/2013): This appears to be a problem for the SWIG interface (undefined reference at link-time).
void supplementReplacementSymbolMap ( rose_hash::unordered_map<SgNode*, SgNode*, hash_nodeptr> & inputReplacementMap );
#endif
#endif
//------------------------------------------------------------------------
//@{
/*! @name Symbol tables
\brief utility functions for symbol tables
*/
// Liao 1/22/2008, used for get symbols for generating variable reference nodes
// ! Find a variable symbol in current and ancestor scopes for a given name
ROSE_DLL_API SgVariableSymbol *lookupVariableSymbolInParentScopes (const SgName & name, SgScopeStatement *currentScope=NULL);
// DQ (8/21/2013): Modified to make newest function parameters be default arguments.
// DQ (8/16/2013): For now we want to remove the use of default parameters and add the support for template parameters and template arguments.
//! Find a symbol in current and ancestor scopes for a given variable name, starting from top of ScopeStack if currentscope is not given or NULL.
// SgSymbol *lookupSymbolInParentScopes (const SgName & name, SgScopeStatement *currentScope=NULL);
// SgSymbol *lookupSymbolInParentScopes (const SgName & name, SgScopeStatement *currentScope, SgTemplateParameterPtrList* templateParameterList, SgTemplateArgumentPtrList* templateArgumentList);
ROSE_DLL_API SgSymbol *lookupSymbolInParentScopes (const SgName & name, SgScopeStatement *currentScope = NULL, SgTemplateParameterPtrList* templateParameterList = NULL, SgTemplateArgumentPtrList* templateArgumentList = NULL);
// DQ (11/24/2007): Functions moved from the Fortran support so that they could be called from within astPostProcessing.
//!look up the first matched function symbol in parent scopes given only a function name, starting from top of ScopeStack if currentscope is not given or NULL
ROSE_DLL_API SgFunctionSymbol *lookupFunctionSymbolInParentScopes (const SgName & functionName, SgScopeStatement *currentScope=NULL);
// Liao, 1/24/2008, find exact match for a function
//!look up function symbol in parent scopes given both name and function type, starting from top of ScopeStack if currentscope is not given or NULL
ROSE_DLL_API SgFunctionSymbol *lookupFunctionSymbolInParentScopes (const SgName & functionName,
const SgType* t,
SgScopeStatement *currentScope=NULL);
ROSE_DLL_API SgFunctionSymbol *lookupTemplateFunctionSymbolInParentScopes (const SgName & functionName, SgFunctionType * ftype, SgTemplateParameterPtrList * tplparams, SgScopeStatement *currentScope=NULL);
ROSE_DLL_API SgFunctionSymbol *lookupTemplateMemberFunctionSymbolInParentScopes (const SgName & functionName, SgFunctionType * ftype, SgTemplateParameterPtrList * tplparams, SgScopeStatement *currentScope=NULL);
ROSE_DLL_API SgTemplateVariableSymbol * lookupTemplateVariableSymbolInParentScopes (const SgName & name, SgTemplateParameterPtrList * tplparams, SgTemplateArgumentPtrList* tplargs, SgScopeStatement *currentScope=NULL);
// DQ (8/21/2013): Modified to make newest function parameters be default arguments.
// DQ (8/16/2013): For now we want to remove the use of default parameters and add the support for template parameters and template arguments.
// DQ (5/7/2011): Added support for SgClassSymbol (used in name qualification support).
// SgClassSymbol* lookupClassSymbolInParentScopes (const SgName & name, SgScopeStatement *currentScope = NULL);
ROSE_DLL_API SgClassSymbol* lookupClassSymbolInParentScopes (const SgName & name, SgScopeStatement *currentScope = NULL, SgTemplateArgumentPtrList* templateArgumentList = NULL);
ROSE_DLL_API SgTypedefSymbol* lookupTypedefSymbolInParentScopes (const SgName & name, SgScopeStatement *currentScope = NULL);
ROSE_DLL_API SgNonrealSymbol* lookupNonrealSymbolInParentScopes (const SgName & name, SgScopeStatement *currentScope = NULL, SgTemplateParameterPtrList* templateParameterList = NULL, SgTemplateArgumentPtrList* templateArgumentList = NULL);
#if 0
// DQ (8/13/2013): This function does not make since any more, now that we have made the symbol
// table handling more precise and we have to provide template parameters for any template lookup.
// We also have to know if we want to lookup template classes, template functions, or template
// member functions (since each have specific requirements).
SgTemplateSymbol* lookupTemplateSymbolInParentScopes (const SgName & name, SgScopeStatement *currentScope = NULL);
#endif
#if 0
// DQ (8/13/2013): I am not sure if we want this functions in place of lookupTemplateSymbolInParentScopes.
// Where these are called we might not know enough information about the template parameters or function
// types, for example.
SgTemplateClassSymbol* lookupTemplateClassSymbolInParentScopes (const SgName & name, SgScopeStatement *currentScope = NULL, SgTemplateParameterPtrList* templateParameterList = NULL, SgTemplateArgumentPtrList* templateArgumentList = NULL);
SgTemplateFunctionSymbol* lookupTemplateFunctionSymbolInParentScopes (const SgName & name, SgScopeStatement *currentScope = NULL, SgTemplateParameterPtrList* templateParameterList = NULL);
SgTemplateMemberFunctionSymbol* lookupTemplateMemberFunctionSymbolInParentScopes (const SgName & name, SgScopeStatement *currentScope = NULL, SgTemplateParameterPtrList* templateParameterList = NULL);
#endif
// DQ (8/21/2013): Modified to make some of the newest function parameters be default arguments.
// DQ (8/13/2013): I am not sure if we want this functions in place of lookupTemplateSymbolInParentScopes.
ROSE_DLL_API SgTemplateClassSymbol* lookupTemplateClassSymbolInParentScopes (const SgName & name, SgTemplateParameterPtrList* templateParameterList, SgTemplateArgumentPtrList* templateArgumentList, SgScopeStatement *cscope = NULL);
ROSE_DLL_API SgEnumSymbol* lookupEnumSymbolInParentScopes (const SgName & name, SgScopeStatement *currentScope = NULL);
ROSE_DLL_API SgNamespaceSymbol* lookupNamespaceSymbolInParentScopes(const SgName & name, SgScopeStatement *currentScope = NULL);
// DQ (7/17/2011): Added function from cxx branch that I need here for the Java support.
// SgClassSymbol* lookupClassSymbolInParentScopes (const SgName & name, SgScopeStatement *cscope);
/*! \brief set_name of symbol in symbol table.
This function extracts the symbol from the relavant symbol table,
changes the name (at the declaration) and reinserts it into the
symbol table.
\internal I think this is what this function does, I need to double check.
*/
// DQ (12/9/2004): Moved this function (by Alin Jula) from being a member of SgInitializedName
// to this location where it can be a part of the interface for the Sage III AST.
ROSE_DLL_API int set_name (SgInitializedName * initializedNameNode, SgName new_name);
/*! \brief Output function type symbols in global function type symbol table.
*/
void outputGlobalFunctionTypeSymbolTable ();
// DQ (6/27/2005):
/*! \brief Output the local symbol tables.
\implementation Each symbol table is output with the file infor where it is located in the source code.
*/
ROSE_DLL_API void outputLocalSymbolTables (SgNode * node);
class OutputLocalSymbolTables:public AstSimpleProcessing
{
public:
void visit (SgNode * node);
};
/*! \brief Regenerate the symbol table.
\implementation current symbol table must be NULL pointer before calling this
function (for safety, but is this a good idea?)
*/
// DQ (9/28/2005):
void rebuildSymbolTable (SgScopeStatement * scope);
/*! \brief Clear those variable symbols with unknown type (together with initialized names) which are also not referenced by any variable references or declarations under root. If root is NULL, all symbols with unknown type will be deleted.
*/
void clearUnusedVariableSymbols (SgNode* root = NULL);
// DQ (3/1/2009):
//! All the symbol table references in the copied AST need to be reset after rebuilding the copied scope's symbol table.
void fixupReferencesToSymbols( const SgScopeStatement* this_scope, SgScopeStatement* copy_scope, SgCopyHelp & help );
//@}
//------------------------------------------------------------------------
//@{
/*! @name Stringify
\brief Generate a useful string (name) to describe a SgNode
*/
/*! \brief Generate a useful name to describe the SgNode
\internal default names are used for SgNode objects that can not be associated with a name.
*/
// DQ (9/21/2005): General function for extracting the name of declarations (when they have names)
std::string get_name (const SgNode * node);
/*! \brief Generate a useful name to describe the declaration
\internal default names are used for declarations that can not be associated with a name.
*/
// DQ (6/13/2005): General function for extracting the name of declarations (when they have names)
std::string get_name (const SgStatement * stmt);
/*! \brief Generate a useful name to describe the expression
\internal default names are used for expressions that can not be associated with a name.
*/
std::string get_name (const SgExpression * expr);
/*! \brief Generate a useful name to describe the declaration
\internal default names are used for declarations that can not be associated with a name.
*/
// DQ (6/13/2005): General function for extracting the name of declarations (when they have names)
std::string get_name (const SgDeclarationStatement * declaration);
/*! \brief Generate a useful name to describe the scope
\internal default names are used for scope that cannot be associated with a name.
*/
// DQ (6/13/2005): General function for extracting the name of declarations (when they have names)
std::string get_name (const SgScopeStatement * scope);
/*! \brief Generate a useful name to describe the SgSymbol
\internal default names are used for SgSymbol objects that cannot be associated with a name.
*/
// DQ (2/11/2007): Added this function to make debugging support more complete (useful for symbol table debugging support).
std::string get_name (const SgSymbol * symbol);
/*! \brief Generate a useful name to describe the SgType
\internal default names are used for SgType objects that cannot be associated with a name.
*/
std::string get_name (const SgType * type);
/*! \brief Generate a useful name to describe the SgSupport IR node
*/
std::string get_name (const SgSupport * node);
/*! \brief Generate a useful name to describe the SgLocatedNodeSupport IR node
*/
std::string get_name (const SgLocatedNodeSupport * node);
/*! \brief Generate a useful name to describe the SgC_PreprocessorDirectiveStatement IR node
*/
std::string get_name ( const SgC_PreprocessorDirectiveStatement* directive );
/*! \brief Generate a useful name to describe the SgToken IR node
*/
std::string get_name ( const SgToken* token );
// DQ (3/20/2016): Added to refactor some of the DSL infrastructure support.
/*! \brief Generate a useful name to support construction of identifiers from declarations.
This function permits names to be generated that will be unique across translation units
(a specific requirement different from the context of the get_name() functions above).
\internal This supports only a restricted set of declarations presently.
*/
std::string generateUniqueNameForUseAsIdentifier ( SgDeclarationStatement* declaration );
std::string generateUniqueNameForUseAsIdentifier_support ( SgDeclarationStatement* declaration );
/*! \brief Global map of name collisions to support generateUniqueNameForUseAsIdentifier() function.
*/
extern std::map<std::string,int> local_name_collision_map;
extern std::map<std::string,SgNode*> local_name_to_node_map;
extern std::map<SgNode*,std::string> local_node_to_name_map;
/*! \brief Traversal to set the global map of names to node and node to names.collisions to support generateUniqueNameForUseAsIdentifier() function.
*/
void computeUniqueNameForUseAsIdentifier( SgNode* astNode );
/*! \brief Reset map variables used to support generateUniqueNameForUseAsIdentifier() function.
*/
void reset_name_collision_map();
//@}
//------------------------------------------------------------------------
//@{
/*! @name Class utilities
\brief
*/
/*! \brief Get the default destructor from the class declaration
*/
// DQ (6/21/2005): Get the default destructor from the class declaration
SgMemberFunctionDeclaration *getDefaultDestructor (SgClassDeclaration *
classDeclaration);
/*! \brief Get the default constructor from the class declaration
*/
// DQ (6/22/2005): Get the default constructor from the class declaration
ROSE_DLL_API SgMemberFunctionDeclaration *getDefaultConstructor (SgClassDeclaration *
classDeclaration);
/*! \brief Return true if template definition is in the class, false if outside of class.
*/
// DQ (8/27/2005):
bool templateDefinitionIsInClass (SgTemplateInstantiationMemberFunctionDecl
* memberFunctionDeclaration);
/*! \brief Generate a non-defining (forward) declaration from a defining function declaration.
\internal should put into sageBuilder ?
*/
// DQ (9/17/2005):
SgTemplateInstantiationMemberFunctionDecl*
buildForwardFunctionDeclaration
(SgTemplateInstantiationMemberFunctionDecl * memberFunctionInstantiation);
//! Check if a SgNode is a declaration for a structure
bool isStructDeclaration(SgNode * node);
//! Check if a SgNode is a declaration for a union
bool isUnionDeclaration(SgNode * node);
#if 0
// DQ (8/28/2005): This is already a member function of the SgFunctionDeclaration
// (so that it can handle template functions and member functions)
/*! \brief Return true if member function of a template member function,
of false if a non-template member function in a templated class.
*/
// DQ (8/27/2005):
bool isTemplateMemberFunction (SgTemplateInstantiationMemberFunctionDecl *
memberFunctionDeclaration);
#endif
//@}
//------------------------------------------------------------------------
//@{
/*! @name Misc.
\brief Not sure the classifications right now
*/
//! Save AST into a pdf file. Start from a node to find its enclosing file node. The entire file's AST will be saved into a pdf.
void saveToPDF(SgNode* node, std::string filename);
void saveToPDF(SgNode* node); // enable calling from gdb
// DQ (2/12/2012): Added some diagnostic support.
//! Diagnostic function for tracing back through the parent list to understand at runtime where in the AST a failure happened.
void whereAmI(SgNode* node);
//! Extract a SgPragmaDeclaration's leading keyword . For example "#pragma omp parallel" has a keyword of "omp".
std::string extractPragmaKeyword(const SgPragmaDeclaration *);
//! Check if a node is SgOmp*Statement
ROSE_DLL_API bool isOmpStatement(SgNode* );
/*! \brief Return true if function is overloaded.
*/
// DQ (8/27/2005):
bool isOverloaded (SgFunctionDeclaration * functionDeclaration);
// DQ (2/14/2012): Added support function used for variable declarations in conditionals.
//! Support function used for variable declarations in conditionals
void initializeIfStmt(SgIfStmt *ifstmt, SgStatement* conditional, SgStatement * true_body, SgStatement * false_body);
//! Support function used for variable declarations in conditionals
void initializeSwitchStatement(SgSwitchStatement* switchStatement,SgStatement *item_selector,SgStatement *body);
//! Support function used for variable declarations in conditionals
void initializeWhileStatement(SgWhileStmt* whileStatement, SgStatement * condition, SgStatement *body, SgStatement *else_body);
//! Generate unique names for expressions and attach the names as persistent attributes ("UniqueNameAttribute")
void annotateExpressionsWithUniqueNames (SgProject* project);
//! Check if a SgNode is a main() function declaration
ROSE_DLL_API bool isMain (const SgNode* node);
// DQ (6/22/2005):
/*! \brief Generate unique name from C and C++ constructs. The name may contain space.
This is support for the AST merge, but is generally useful as a more general mechanism than
name mangling which is more closely ties to the generation of names to support link-time function name
resolution. This is more general than common name mangling in that it resolves more relevant differences
between C and C++ declarations. (e.g. the type within the declaration: "struct { int:8; } foo;").
\implementation current work does not support expressions.
*/
std::string generateUniqueName ( const SgNode * node, bool ignoreDifferenceBetweenDefiningAndNondefiningDeclarations);
/** Generate a name like __temp#__ that is unique in the current scope and any parent and children scopes. # is a unique integer counter.
* @param baseName the word to be included in the variable names. */
std::string generateUniqueVariableName(SgScopeStatement* scope, std::string baseName = "temp");
// DQ (8/10/2010): Added const to first parameter.
// DQ (3/10/2007):
//! Generate a unique string from the source file position information
std::string declarationPositionString (const SgDeclarationStatement * declaration);
// DQ (1/20/2007):
//! Added mechanism to generate project name from list of file names
ROSE_DLL_API std::string generateProjectName (const SgProject * project, bool supressSuffix = false );
//! Given a SgExpression that represents a named function (or bound member
//! function), return the mentioned function
SgFunctionDeclaration* getDeclarationOfNamedFunction(SgExpression* func);
//! Get the mask expression from the header of a SgForAllStatement
SgExpression* forallMaskExpression(SgForAllStatement* stmt);
//! Find all SgPntrArrRefExp under astNode, then add SgVarRefExp (if any) of SgPntrArrRefExp's dim_info into NodeList_t
void addVarRefExpFromArrayDimInfo(SgNode * astNode, Rose_STL_Container<SgNode *>& NodeList_t);
// DQ (10/6/2006): Added support for faster mangled name generation (caching avoids recomputation).
/*! \brief Support for faster mangled name generation (caching avoids recomputation).
*/
#ifndef SWIG
// DQ (3/10/2013): This appears to be a problem for the SWIG interface (undefined reference at link-time).
void clearMangledNameCache (SgGlobal * globalScope);
void resetMangledNameCache (SgGlobal * globalScope);
#endif
std::string getMangledNameFromCache (SgNode * astNode);
std::string addMangledNameToCache (SgNode * astNode, const std::string & mangledName);
SgDeclarationStatement * getNonInstantiatonDeclarationForClass (SgTemplateInstantiationMemberFunctionDecl * memberFunctionInstantiation);
//! a better version for SgVariableDeclaration::set_baseTypeDefininingDeclaration(), handling all side effects automatically
//! Used to have a struct declaration embedded into a variable declaration
void setBaseTypeDefiningDeclaration(SgVariableDeclaration* var_decl, SgDeclarationStatement *base_decl);
// DQ (10/14/2006): This function tests the AST to see if for a non-defining declaration, the
// bool declarationPreceedsDefinition ( SgClassDeclaration* classNonDefiningDeclaration, SgClassDeclaration* classDefiningDeclaration );
//! Check if a defining declaration comes before of after the non-defining declaration.
bool declarationPreceedsDefinition (SgDeclarationStatement *nonDefiningDeclaration, SgDeclarationStatement *definingDeclaration);
// DQ (10/19/2006): Function calls have interesting context dependent rules to determine if
// they are output with a global qualifier or not. Were this is true we have to avoid global
// qualifiers, since the function's scope has not been defined. This is an example of where
// qualification of function names in function calls are context dependent; an interesting
// example of where the C++ language is not friendly to source-to-source processing :-).
bool functionCallExpressionPreceedsDeclarationWhichAssociatesScope (SgFunctionCallExp * functionCall);
/*! \brief Compute the intersection set for two ASTs.
This is part of a test done by the copy function to compute those IR nodes in the copy that still reference the original AST.
*/
ROSE_DLL_API std::vector < SgNode * >astIntersection (SgNode * original, SgNode * copy, SgCopyHelp * help = NULL);
//! Deep copy an arbitrary subtree
ROSE_DLL_API SgNode* deepCopyNode (const SgNode* subtree);
//! A template function for deep copying a subtree. It is also used to create deepcopy functions with specialized parameter and return types. e.g SgExpression* copyExpression(SgExpression* e);
template <typename NodeType>
NodeType* deepCopy (const NodeType* subtree) {
return dynamic_cast<NodeType*>(deepCopyNode(subtree));
}
//! Deep copy an expression
ROSE_DLL_API SgExpression* copyExpression(SgExpression* e);
//!Deep copy a statement
ROSE_DLL_API SgStatement* copyStatement(SgStatement* s);
// from VarSym.cc in src/midend/astOutlining/src/ASTtools
//! Get the variable symbol for the first initialized name of a declaration stmt.
ROSE_DLL_API SgVariableSymbol* getFirstVarSym (SgVariableDeclaration* decl);
//! Get the first initialized name of a declaration statement
ROSE_DLL_API SgInitializedName* getFirstInitializedName (SgVariableDeclaration* decl);
//! A special purpose statement removal function, originally from inlinerSupport.h, Need Jeremiah's attention to refine it. Please don't use it for now.
ROSE_DLL_API void myRemoveStatement(SgStatement* stmt);
ROSE_DLL_API bool isConstantTrue(SgExpression* e);
ROSE_DLL_API bool isConstantFalse(SgExpression* e);
ROSE_DLL_API bool isCallToParticularFunction(SgFunctionDeclaration* decl, SgExpression* e);
ROSE_DLL_API bool isCallToParticularFunction(const std::string& qualifiedName, size_t arity, SgExpression* e);
//! Check if a declaration has a "static' modifier
bool ROSE_DLL_API isStatic(SgDeclarationStatement* stmt);
//! Set a declaration as static
ROSE_DLL_API void setStatic(SgDeclarationStatement* stmt);
//! Check if a declaration has an "extern" modifier
ROSE_DLL_API bool isExtern(SgDeclarationStatement* stmt);
//! Set a declaration as extern
ROSE_DLL_API void setExtern(SgDeclarationStatement* stmt);
//! Interface for creating a statement whose computation writes its answer into
//! a given variable.
class StatementGenerator {
public:
virtual ~StatementGenerator() {};
virtual SgStatement* generate(SgExpression* where_to_write_answer) = 0;
};
//! Check if a SgNode _s is an assignment statement (any of =,+=,-=,&=,/=, ^=, etc)
//!
//! Return the left hand, right hand expressions and if the left hand variable is also being read
bool isAssignmentStatement(SgNode* _s, SgExpression** lhs=NULL, SgExpression** rhs=NULL, bool* readlhs=NULL);
//! Variable references can be introduced by SgVarRef, SgPntrArrRefExp, SgInitializedName, SgMemberFunctionRef etc. For Dot and Arrow Expressions, their lhs is used to obtain SgInitializedName (coarse grain) by default. Otherwise, fine-grain rhs is used.
ROSE_DLL_API SgInitializedName* convertRefToInitializedName(SgNode* current, bool coarseGrain=true);
//! Build an abstract handle from an AST node, reuse previously built handle when possible
ROSE_DLL_API AbstractHandle::abstract_handle* buildAbstractHandle(SgNode*);
//! Obtain a matching SgNode from an abstract handle string
ROSE_DLL_API SgNode* getSgNodeFromAbstractHandleString(const std::string& input_string);
//! Dump information about a SgNode for debugging
ROSE_DLL_API void dumpInfo(SgNode* node, std::string desc="");
//! Reorder a list of declaration statements based on their appearance order in source files
ROSE_DLL_API std::vector<SgDeclarationStatement*>
sortSgNodeListBasedOnAppearanceOrderInSource(const std::vector<SgDeclarationStatement*>& nodevec);
// DQ (4/13/2013): We need these to support the unparing of operators defined by operator syntax or member function names.
//! Is an overloaded operator a prefix operator (e.g. address operator X * operator&(), dereference operator X & operator*(), unary plus operator X & operator+(), etc.
// bool isPrefixOperator( const SgMemberFunctionRefExp* memberFunctionRefExp );
bool isPrefixOperator( SgExpression* exp );
//! Check for proper names of possible prefix operators (used in isPrefixOperator()).
bool isPrefixOperatorName( const SgName & functionName );
//! Is an overloaded operator a postfix operator. (e.g. ).
bool isPostfixOperator( SgExpression* exp );
//! Is an overloaded operator an index operator (also referred to as call or subscript operators). (e.g. X & operator()() or X & operator[]()).
bool isIndexOperator( SgExpression* exp );
// DQ (1/10/2014): Adding more general support for token based unparsing.
//! Used to support token unparsing (when the output the trailing token sequence).
SgStatement* lastStatementOfScopeWithTokenInfo (SgScopeStatement* scope, std::map<SgNode*,TokenStreamSequenceToNodeMapping*> & tokenStreamSequenceMap);
//@}
//------------------------------------------------------------------------
//@{
/*! @name AST properties
\brief version, language properties of current AST.
*/
// std::string version(); // utility_functions.h, version number
/*! Brief These traverse the memory pool of SgFile IR nodes and determine what languages are in use!
*/
ROSE_DLL_API bool is_Ada_language ();
ROSE_DLL_API bool is_C_language ();
ROSE_DLL_API bool is_Cobol_language ();
ROSE_DLL_API bool is_OpenMP_language ();
ROSE_DLL_API bool is_UPC_language ();
//! Check if dynamic threads compilation is used for UPC programs
ROSE_DLL_API bool is_UPC_dynamic_threads();
ROSE_DLL_API bool is_C99_language ();
ROSE_DLL_API bool is_Cxx_language ();
ROSE_DLL_API bool is_Java_language ();
ROSE_DLL_API bool is_Jovial_language ();
ROSE_DLL_API bool is_Fortran_language ();
ROSE_DLL_API bool is_CAF_language ();
ROSE_DLL_API bool is_PHP_language();
ROSE_DLL_API bool is_Python_language();
ROSE_DLL_API bool is_Cuda_language();
ROSE_DLL_API bool is_OpenCL_language();
ROSE_DLL_API bool is_X10_language();
ROSE_DLL_API bool is_binary_executable();
ROSE_DLL_API bool is_mixed_C_and_Cxx_language ();
ROSE_DLL_API bool is_mixed_Fortran_and_C_language ();
ROSE_DLL_API bool is_mixed_Fortran_and_Cxx_language ();
ROSE_DLL_API bool is_mixed_Fortran_and_C_and_Cxx_language ();
//@}
//------------------------------------------------------------------------
//@{
/*! @name Scope
\brief
*/
// DQ (10/5/2006): Added support for faster (non-quadratic) computation of unique
// labels for scopes in a function (as required for name mangling).
/*! \brief Assigns unique numbers to each SgScopeStatement of a function.
This is used to provide unique names for variables and types defined is
different nested scopes of a function (used in mangled name generation).
*/
void resetScopeNumbers (SgFunctionDefinition * functionDeclaration);
// DQ (10/5/2006): Added support for faster (non-quadratic) computation of unique
// labels for scopes in a function (as required for name mangling).
/*! \brief Clears the cache of scope,integer pairs for the input function.
This is used to clear the cache of computed unique labels for scopes in a function.
This function should be called after any transformation on a function that might effect
the allocation of scopes and cause the existing unique numbers to be incorrect.
This is part of support to provide unique names for variables and types defined is
different nested scopes of a function (used in mangled name generation).
*/
void clearScopeNumbers (SgFunctionDefinition * functionDefinition);
//!Find the enclosing namespace of a declaration
SgNamespaceDefinitionStatement * enclosingNamespaceScope (SgDeclarationStatement * declaration);
// SgNamespaceDefinitionStatement * getEnclosingNamespaceScope (SgNode * node);
bool isPrototypeInScope (SgScopeStatement * scope,
SgFunctionDeclaration * functionDeclaration,
SgDeclarationStatement * startingAtDeclaration);
//!check if node1 is a strict ancestor of node 2. (a node is not considered its own ancestor)
bool ROSE_DLL_API isAncestor(SgNode* node1, SgNode* node2);
//@}
//------------------------------------------------------------------------
//@{
/*! @name Preprocessing Information
\brief #if-#else-#end, comments, #include, etc
*/
//! Dumps a located node's preprocessing information.
void dumpPreprocInfo (SgLocatedNode* locatedNode);
//! Insert #include "filename" or #include <filename> (system header) onto the global scope of a source file, add to be the last #include .. by default among existing headers, Or as the first header. Recommended for use.
PreprocessingInfo * insertHeader(SgSourceFile * source_file, const std::string & header_file_name, bool isSystemHeader, bool asLastHeader);
//! Insert a new header right before stmt, if there are existing headers attached to stmt, insert it as the last or first header as specified by asLastHeader
void insertHeader (SgStatement* stmt, PreprocessingInfo* newheader, bool asLastHeader);
//! Insert #include "filename" or #include <filename> (system header) onto the global scope of a source file
PreprocessingInfo * insertHeader(SgSourceFile * source_file, const std::string & header_file_name, bool isSystemHeader = false, PreprocessingInfo::RelativePositionType position = PreprocessingInfo::before);
//! Insert #include "filename" or #include <filename> (system header) into the global scope containing the current scope, right after other #include XXX.
ROSE_DLL_API PreprocessingInfo* insertHeader(const std::string& filename, PreprocessingInfo::RelativePositionType position=PreprocessingInfo::after, bool isSystemHeader=false, SgScopeStatement* scope=NULL);
//! Identical to movePreprocessingInfo(), except for the stale name and confusing order of parameters. It will be deprecated soon.
ROSE_DLL_API void moveUpPreprocessingInfo (SgStatement* stmt_dst, SgStatement* stmt_src, PreprocessingInfo::RelativePositionType src_position=PreprocessingInfo::undef, PreprocessingInfo::RelativePositionType dst_position=PreprocessingInfo::undef, bool usePrepend= false);
//! Move preprocessing information of stmt_src to stmt_dst, Only move preprocessing information from the specified source-relative position to a specified target position, otherwise move all preprocessing information with position information intact. The preprocessing information is appended to the existing preprocessing information list of the target node by default. Prepending is used if usePreprend is set to true. Optionally, the relative position can be adjust after the moving using dst_position.
ROSE_DLL_API void movePreprocessingInfo (SgStatement* stmt_src, SgStatement* stmt_dst, PreprocessingInfo::RelativePositionType src_position=PreprocessingInfo::undef,
PreprocessingInfo::RelativePositionType dst_position=PreprocessingInfo::undef, bool usePrepend= false);
//!Cut preprocessing information from a source node and save it into a buffer. Used in combination of pastePreprocessingInfo(). The cut-paste operation is similar to moveUpPreprocessingInfo() but it is more flexible in that the destination node can be unknown during the cut operation.
ROSE_DLL_API void cutPreprocessingInfo (SgLocatedNode* src_node, PreprocessingInfo::RelativePositionType pos, AttachedPreprocessingInfoType& save_buf);
//!Paste preprocessing information from a buffer to a destination node. Used in combination of cutPreprocessingInfo()
ROSE_DLL_API void pastePreprocessingInfo (SgLocatedNode* dst_node, PreprocessingInfo::RelativePositionType pos, AttachedPreprocessingInfoType& saved_buf);
//! Attach an arbitrary string to a located node. A workaround to insert irregular statements or vendor-specific attributes.
ROSE_DLL_API PreprocessingInfo* attachArbitraryText(SgLocatedNode* target,
const std::string & text,
PreprocessingInfo::RelativePositionType position=PreprocessingInfo::before);
//!Check if a pragma declaration node has macro calls attached, if yes, replace macro calls within the pragma string with expanded strings. This only works if -rose:wave is turned on.
ROSE_DLL_API void replaceMacroCallsWithExpandedStrings(SgPragmaDeclaration* target);
//@}
//! Build and attach comment onto the global scope of a source file
PreprocessingInfo* attachComment(
SgSourceFile * source_file,
const std::string & content,
PreprocessingInfo::DirectiveType directive_type = PreprocessingInfo::C_StyleComment,
PreprocessingInfo::RelativePositionType position = PreprocessingInfo::before
);
//! Build and attach comment, comment style is inferred from the language type of the target node if not provided
ROSE_DLL_API PreprocessingInfo* attachComment(SgLocatedNode* target, const std::string & content,
PreprocessingInfo::RelativePositionType position=PreprocessingInfo::before,
PreprocessingInfo::DirectiveType dtype= PreprocessingInfo::CpreprocessorUnknownDeclaration);
// DQ (11/25/2009): Added matching support for adding comments to SgAsm nodes.
// Build and attach comment
// void attachComment(SgAsmStatement* target, const std::string & content );
// DQ (7/20/2008): I am not clear were I should put this function, candidates include: SgLocatedNode or SgInterface
//! Add a string to be unparsed to support code generation for back-end specific tools or compilers.
ROSE_DLL_API void addTextForUnparser ( SgNode* astNode, std::string s, AstUnparseAttribute::RelativePositionType inputlocation );
/**
* Add preproccessor guard around a given node.
* It surrounds the node with "#if guard" and "#endif"
*/
void guardNode(SgLocatedNode * target, std::string guard);
//@}
//------------------------------------------------------------------------
//@{
/*! @name Source File Position
\brief set Sg_File_Info for a SgNode
*/
// ************************************************************************
// Newer versions of now depricated functions
// ************************************************************************
// DQ (5/1/2012): This function queries the SageBuilder::SourcePositionClassification mode (stored in the SageBuilder
// interface) and used the specified mode to initialize the source position data (Sg_File_Info objects). This
// function is the only function that should be called directly (though in a namespace we can't define permissions).
//! Set the source code positon for the current (input) node.
ROSE_DLL_API void setSourcePosition(SgNode* node);
// A better name might be "setSourcePositionForSubTree"
//! Set the source code positon for the subtree (including the root).
ROSE_DLL_API void setSourcePositionAtRootAndAllChildren(SgNode *root);
//! DQ (5/1/2012): New function with improved name.
void setSourcePositionAsTransformation(SgNode *node);
// DQ (5/1/2012): Newly renamed function (previous name preserved for backward compatability).
void setSourcePositionPointersToNull(SgNode *node);
// ************************************************************************
// ************************************************************************
// Older deprecated functions
// ************************************************************************
// Liao, 1/8/2007, set file info. for a whole subtree as transformation generated
//! Set current node's source position as transformation generated
ROSE_DLL_API void setOneSourcePositionForTransformation(SgNode *node);
//! Set current node's source position as NULL
ROSE_DLL_API void setOneSourcePositionNull(SgNode *node);
//! Recursively set source position info(Sg_File_Info) as transformation generated
ROSE_DLL_API void setSourcePositionForTransformation (SgNode * root);
//! Set source position info(Sg_File_Info) as transformation generated for all SgNodes in memory pool
// ROSE_DLL_API void setSourcePositionForTransformation_memoryPool();
//! Check if a node is from a system header file
ROSE_DLL_API bool insideSystemHeader (SgLocatedNode* node);
//! Set the source position of SgLocatedNode to Sg_File_Info::generateDefaultFileInfo(). These nodes WILL be unparsed. Not for transformation usage.
// ROSE_DLL_API void setSourcePosition (SgLocatedNode * locatedNode);
// ************************************************************************
//@}
//------------------------------------------------------------------------
//@{
/*! @name Data types
\brief
*/
// from src/midend/astInlining/typeTraits.h
// src/midend/astUtil/astInterface/AstInterface.h
//! Get the right bool type according to C or C++ language input
SgType* getBoolType(SgNode* n);
//! Check if a type is an integral type, only allowing signed/unsigned short, int, long, long long.
////!
////! There is another similar function named SgType::isIntegerType(), which allows additional types char, wchar, and bool to be treated as integer types
ROSE_DLL_API bool isStrictIntegerType(SgType* t);
//!Get the data type of the first initialized name of a declaration statement
ROSE_DLL_API SgType* getFirstVarType(SgVariableDeclaration* decl);
//! Is a type default constructible? This may not quite work properly.
ROSE_DLL_API bool isDefaultConstructible(SgType* type);
//! Is a type copy constructible? This may not quite work properly.
ROSE_DLL_API bool isCopyConstructible(SgType* type);
//! Is a type assignable? This may not quite work properly.
ROSE_DLL_API bool isAssignable(SgType* type);
#ifndef ROSE_USE_INTERNAL_FRONTEND_DEVELOPMENT
//! Check if a class type is a pure virtual class. True means that there is at least
//! one pure virtual function that has not been overridden.
//! In the case of an incomplete class type (forward declaration), this function returns false.
ROSE_DLL_API bool isPureVirtualClass(SgType* type, const ClassHierarchyWrapper& classHierarchy);
#endif
//! Does a type have a trivial (built-in) destructor?
ROSE_DLL_API bool hasTrivialDestructor(SgType* t);
//! Is this type a non-constant reference type? (Handles typedefs correctly)
ROSE_DLL_API bool isNonconstReference(SgType* t);
//! Is this type a const or non-const reference type? (Handles typedefs correctly)
ROSE_DLL_API bool isReferenceType(SgType* t);
//! Is this type a pointer type? (Handles typedefs correctly)
ROSE_DLL_API bool isPointerType(SgType* t);
//! Is this a pointer to a non-const type? Note that this function will return true for const pointers pointing to
//! non-const types. For example, (int* const y) points to a modifiable int, so this function returns true. Meanwhile,
//! it returns false for (int const * x) and (int const * const x) because these types point to a const int.
//! Also, only the outer layer of nested pointers is unwrapped. So the function returns true for (const int ** y), but returns
//! false for const (int * const * x)
ROSE_DLL_API bool isPointerToNonConstType(SgType* type);
//! Is this a const type?
/* const char* p = "aa"; is not treated as having a const type. It is a pointer to const char.
* Similarly, neither for const int b[10]; or const int & c =10;
* The standard says, "A compound type is not cv-qualified by the cv-qualifiers (if any) of
the types from which it is compounded. Any cv-qualifiers applied to an array type affect the array element type, not the array type".
*/
ROSE_DLL_API bool isConstType(SgType* t);
//! Remove const (if present) from a type. stripType() cannot do this because it removes all modifiers.
SgType* removeConst(SgType* t);
//! Is this a volatile type?
ROSE_DLL_API bool isVolatileType(SgType* t);
//! Is this a restrict type?
ROSE_DLL_API bool isRestrictType(SgType* t);
//! Is this a scalar type?
/*! We define the following SgType as scalar types: char, short, int, long , void, Wchar, Float, double, long long, string, bool, complex, imaginary
*/
ROSE_DLL_API bool isScalarType(SgType* t);
//! Check if a type is an integral type, only allowing signed/unsigned short, int, long, long long.
//!
//! There is another similar function named SgType::isIntegerType(), which allows additional types char, wchar, and bool.
ROSE_DLL_API bool isStrictIntegerType(SgType* t);
//! Check if a type is a struct type (a special SgClassType in ROSE)
ROSE_DLL_API bool isStructType(SgType* t);
//! Generate a mangled string for a given type based on Itanium C++ ABI
ROSE_DLL_API std::string mangleType(SgType* type);
//! Generate mangled scalar type names according to Itanium C++ ABI, the input type should pass isScalarType() in ROSE
ROSE_DLL_API std::string mangleScalarType(SgType* type);
//! Generated mangled modifier types, include const, volatile,according to Itanium C++ ABI, with extension to handle UPC shared types.
ROSE_DLL_API std::string mangleModifierType(SgModifierType* type);
//! Calculate the number of elements of an array type: dim1* dim2*... , assume element count is 1 for int a[]; Strip off THREADS if it is a UPC array.
ROSE_DLL_API size_t getArrayElementCount(SgArrayType* t);
//! Get the number of dimensions of an array type
ROSE_DLL_API int getDimensionCount(SgType* t);
//! Get the element type of an array. It recursively find the base type for multi-dimension array types
ROSE_DLL_API SgType* getArrayElementType(SgType* t);
//! Get the element type of an array, pointer or string, or NULL if not applicable. This function only check one level base type. No recursion.
ROSE_DLL_API SgType* getElementType(SgType* t);
/// \brief returns the array dimensions in an array as defined for arrtype
/// \param arrtype the type of a C/C++ array
/// \return an array that contains an expression indicating each dimension's size.
/// OWNERSHIP of the expressions is TRANSFERED TO the CALLER (which
/// becomes responsible for freeing the expressions).
/// Note, the first entry of the array is a SgNullExpression, iff the
/// first array dimension was not specified.
/// \code
/// int x[] = { 1, 2, 3 };
/// \endcode
/// note, the expression does not have to be a constant
/// \code
/// int x[i*5];
/// \endcode
/// \post return-value.empty() == false
/// \post return-value[*] != NULL (no nullptr in the returned vector)
std::vector<SgExpression*>
get_C_array_dimensions(const SgArrayType& arrtype);
/// \brief returns the array dimensions in an array as defined for arrtype
/// \param arrtype the type of a C/C++ array
/// \param varref a reference to an array variable (the variable of type arrtype)
/// \return an array that contains an expression indicating each dimension's size.
/// OWNERSHIP of the expressions is TRANSFERED TO the CALLER (which
/// becomes responsible for freeing the expressions).
/// If the first array dimension was not specified an expression
/// that indicates that size is generated.
/// \code
/// int x[][3] = { 1, 2, 3, 4, 5, 6 };
/// \endcode
/// the entry for the first dimension will be:
/// \code
/// // 3 ... size of 2nd dimension
/// sizeof(x) / (sizeof(int) * 3)
/// \endcode
/// \pre arrtype is the array-type of varref
/// \post return-value.empty() == false
/// \post return-value[*] != NULL (no nullptr in the returned vector)
/// \post !isSgNullExpression(return-value[*])
std::vector<SgExpression*>
get_C_array_dimensions(const SgArrayType& arrtype, const SgVarRefExp& varref);
/// \overload
/// \note see get_C_array_dimensions for SgVarRefExp for details.
/// \todo make initname const
std::vector<SgExpression*>
get_C_array_dimensions(const SgArrayType& arrtype, SgInitializedName& initname);
//! Check if an expression is an array access (SgPntrArrRefExp). If so, return its name expression and subscripts if requested. Users can use convertRefToInitializedName() to get the possible name. It does not check if the expression is a top level SgPntrArrRefExp.
ROSE_DLL_API bool isArrayReference(SgExpression* ref, SgExpression** arrayNameExp=NULL, std::vector<SgExpression*>** subscripts=NULL);
//! Collect variable references in array types. The default NodeQuery::querySubTree() will miss variables referenced in array type's index list. e.g. double *buffer = new double[numItems] ;
ROSE_DLL_API int collectVariableReferencesInArrayTypes (SgLocatedNode* root, Rose_STL_Container<SgNode*> & currentVarRefList);
//! Has a UPC shared type of any kinds (shared-to-shared, private-to-shared, shared-to-private, shared scalar/array)? An optional parameter, mod_type_out, stores the first SgModifierType with UPC access information.
/*!
* Note: we classify private-to-shared as 'has shared' type for convenience here. It is indeed a private type in strict sense.
AST graph for some examples:
- shared scalar: SgModifierType -->base type
- shared array: SgArrayType --> SgModiferType --> base type
- shared to shared: SgModifierType --> SgPointerType --> SgModifierType ->SgTypeInt
- shared to private: SgModifierType --> SgPointerType --> base type
- private to shared: SgPointerType --> SgModifierType --> base type
*/
ROSE_DLL_API bool hasUpcSharedType(SgType* t, SgModifierType ** mod_type_out = NULL );
//! Check if a type is a UPC shared type, including shared array, shared pointers etc. Exclude private pointers to shared types. Optionally return the modifier type with the UPC shared property.
/*!
* ROSE uses SgArrayType of SgModifierType to represent shared arrays, not SgModifierType points to SgArrayType. Also typedef may cause a chain of nodes before reach the actual SgModifierType with UPC shared property.
*/
ROSE_DLL_API bool isUpcSharedType(SgType* t, SgModifierType ** mod_type_out = NULL);
//! Check if a modifier type is a UPC shared type.
ROSE_DLL_API bool isUpcSharedModifierType (SgModifierType* mod_type);
//! Check if an array type is a UPC shared type. ROSE AST represents a UPC shared array as regular array of elements of UPC shared Modifier Type. Not directly a UPC shared Modifier Type of an array.
ROSE_DLL_API bool isUpcSharedArrayType (SgArrayType* array_type);
//! Check if a shared UPC type is strict memory consistency or not. Return false if it is relaxed. (So isUpcRelaxedSharedModifierType() is not necessary.)
ROSE_DLL_API bool isUpcStrictSharedModifierType(SgModifierType* mode_type);
//! Get the block size of a UPC shared modifier type
ROSE_DLL_API size_t getUpcSharedBlockSize(SgModifierType* mod_type);
//! Get the block size of a UPC shared type, including Modifier types and array of modifier types (shared arrays)
ROSE_DLL_API size_t getUpcSharedBlockSize(SgType* t);
//! Is UPC phase-less shared type? Phase-less means block size of the first SgModifierType with UPC information is 1 or 0/unspecified. Also return false if the type is not a UPC shared type.
ROSE_DLL_API bool isUpcPhaseLessSharedType (SgType* t);
//! Is a UPC private-to-shared pointer? SgPointerType comes first compared to SgModifierType with UPC information. Input type must be any of UPC shared types first.
ROSE_DLL_API bool isUpcPrivateToSharedType(SgType* t);
//! Is a UPC array with dimension of X*THREADS
ROSE_DLL_API bool isUpcArrayWithThreads(SgArrayType* t);
//! Lookup a named type based on its name, bottomup searching from a specified scope. Note name collison might be allowed for c (not C++) between typedef and enum/struct. Only the first matched named type will be returned in this case. typedef is returned as it is, not the base type it actually refers to.
ROSE_DLL_API SgType* lookupNamedTypeInParentScopes(const std::string& type_name, SgScopeStatement* scope=NULL);
// DQ (7/22/2014): Added support for comparing expression types in actual arguments with those expected from the formal function parameter types.
//! Get the type of the associated argument expression from the function type.
ROSE_DLL_API SgType* getAssociatedTypeFromFunctionTypeList(SgExpression* actual_argument_expression);
//! Verify that 2 SgTemplateArgument are equivalent (same type, same expression, or same template declaration)
ROSE_DLL_API bool templateArgumentEquivalence(SgTemplateArgument * arg1, SgTemplateArgument * arg2);
//! Verify that 2 SgTemplateArgumentPtrList are equivalent.
ROSE_DLL_API bool templateArgumentListEquivalence(const SgTemplateArgumentPtrList & list1, const SgTemplateArgumentPtrList & list2);
//! Test for equivalence of types independent of access permissions (private or protected modes for members of classes).
ROSE_DLL_API bool isEquivalentType (const SgType* lhs, const SgType* rhs);
//! Test if two types are equivalent SgFunctionType nodes. This is necessary for template function types
//! They may differ in one SgTemplateType pointer but identical otherwise.
ROSE_DLL_API bool isEquivalentFunctionType (const SgFunctionType* lhs, const SgFunctionType* rhs);
//@}
//------------------------------------------------------------------------
//@{
/*! @name Loop handling
\brief
*/
// by Jeremiah
//! Add a step statement to the end of a loop body
//! Add a new label to the end of the loop, with the step statement after
//! it; then change all continue statements in the old loop body into
//! jumps to the label
//!
//! For example:
//! while (a < 5) {if (a < -3) continue;} (adding "a++" to end) becomes
//! while (a < 5) {if (a < -3) goto label; label: a++;}
ROSE_DLL_API void addStepToLoopBody(SgScopeStatement* loopStmt, SgStatement* step);
ROSE_DLL_API void moveForStatementIncrementIntoBody(SgForStatement* f);
ROSE_DLL_API void convertForToWhile(SgForStatement* f);
ROSE_DLL_API void convertAllForsToWhiles(SgNode* top);
//! Change continue statements in a given block of code to gotos to a label
ROSE_DLL_API void changeContinuesToGotos(SgStatement* stmt, SgLabelStatement* label);
//!Return the loop index variable for a for loop
ROSE_DLL_API SgInitializedName* getLoopIndexVariable(SgNode* loop);
//!Check if a SgInitializedName is used as a loop index within a AST subtree
//! This function will use a bottom-up traverse starting from the subtree_root to find all enclosing loops and check if ivar is used as an index for either of them.
ROSE_DLL_API bool isLoopIndexVariable(SgInitializedName* ivar, SgNode* subtree_root);
//! Check if a for loop uses C99 style initialization statement with multiple expressions like for (int i=0, j=0; ..) or for (i=0,j=0;...)
/*!
for (int i=0, j=0; ..) is stored as two variable declarations under SgForInitStatement's init_stmt member
for (i=0,j=0;...) is stored as a single expression statement, with comma expression (i=0,j=0).
*/
ROSE_DLL_API bool hasMultipleInitStatmentsOrExpressions (SgForStatement* for_loop);
//! Routines to get and set the body of a loop
ROSE_DLL_API SgStatement* getLoopBody(SgScopeStatement* loop);
ROSE_DLL_API void setLoopBody(SgScopeStatement* loop, SgStatement* body);
//! Routines to get the condition of a loop. It recognize While-loop, For-loop, and Do-While-loop
ROSE_DLL_API SgStatement* getLoopCondition(SgScopeStatement* loop);
//! Set the condition statement of a loop, including While-loop, For-loop, and Do-While-loop.
ROSE_DLL_API void setLoopCondition(SgScopeStatement* loop, SgStatement* cond);
//! Check if a for-loop has a canonical form, return loop index, bounds, step, and body if requested
//!
//! A canonical form is defined as : one initialization statement, a test expression, and an increment expression , loop index variable should be of an integer type. IsInclusiveUpperBound is true when <= or >= is used for loop condition
ROSE_DLL_API bool isCanonicalForLoop(SgNode* loop, SgInitializedName** ivar=NULL, SgExpression** lb=NULL, SgExpression** ub=NULL, SgExpression** step=NULL, SgStatement** body=NULL, bool *hasIncrementalIterationSpace = NULL, bool* isInclusiveUpperBound = NULL);
//! Check if a Fortran Do loop has a complete canonical form: Do I=1, 10, 1
ROSE_DLL_API bool isCanonicalDoLoop(SgFortranDo* loop,SgInitializedName** ivar/*=NULL*/, SgExpression** lb/*=NULL*/, SgExpression** ub/*=NULL*/, SgExpression** step/*=NULL*/, SgStatement** body/*=NULL*/, bool *hasIncrementalIterationSpace/*= NULL*/, bool* isInclusiveUpperBound/*=NULL*/);
//! Set the lower bound of a loop header for (i=lb; ...)
ROSE_DLL_API void setLoopLowerBound(SgNode* loop, SgExpression* lb);
//! Set the upper bound of a loop header,regardless the condition expression type. for (i=lb; i op up, ...)
ROSE_DLL_API void setLoopUpperBound(SgNode* loop, SgExpression* ub);
//! Set the stride(step) of a loop 's incremental expression, regardless the expression types (i+=s; i= i+s, etc)
ROSE_DLL_API void setLoopStride(SgNode* loop, SgExpression* stride);
//! Normalize loop init stmt by promoting the single variable declaration statement outside of the for loop header's init statement, e.g. for (int i=0;) becomes int i_x; for (i_x=0;..) and rewrite the loop with the new index variable, if necessary
ROSE_DLL_API bool normalizeForLoopInitDeclaration(SgForStatement* loop);
//! Undo the normalization of for loop's C99 init declaration. Previous record of normalization is used to ease the reverse transformation.
ROSE_DLL_API bool unnormalizeForLoopInitDeclaration(SgForStatement* loop);
//! Normalize a for loop, return true if successful. Generated constants will be fold by default.
//!
//! Translations are :
//! For the init statement: for (int i=0;... ) becomes int i; for (i=0;..)
//! For test expression:
//! i<x is normalized to i<= (x-1) and
//! i>x is normalized to i>= (x+1)
//! For increment expression:
//! i++ is normalized to i+=1 and
//! i-- is normalized to i+=-1
//! i-=s is normalized to i+= -s
ROSE_DLL_API bool forLoopNormalization(SgForStatement* loop, bool foldConstant = true);
//! Normalize a for loop's test expression
//! i<x is normalized to i<= (x-1) and
//! i>x is normalized to i>= (x+1)
ROSE_DLL_API bool normalizeForLoopTest(SgForStatement* loop);
ROSE_DLL_API bool normalizeForLoopIncrement(SgForStatement* loop);
//!Normalize a Fortran Do loop. Make the default increment expression (1) explicit
ROSE_DLL_API bool doLoopNormalization(SgFortranDo* loop);
//! Unroll a target loop with a specified unrolling factor. It handles steps larger than 1 and adds a fringe loop if the iteration count is not evenly divisible by the unrolling factor.
ROSE_DLL_API bool loopUnrolling(SgForStatement* loop, size_t unrolling_factor);
//! Interchange/permutate a n-level perfectly-nested loop rooted at 'loop' using a lexicographical order number within (0,depth!).
ROSE_DLL_API bool loopInterchange(SgForStatement* loop, size_t depth, size_t lexicoOrder);
//! Tile the n-level (starting from 1) loop of a perfectly nested loop nest using tiling size s
ROSE_DLL_API bool loopTiling(SgForStatement* loopNest, size_t targetLevel, size_t tileSize);
//Winnie Loop Collapsing
SgExprListExp * loopCollapsing(SgForStatement* target_loop, size_t collapsing_factor);
bool getForLoopInformations(
SgForStatement * for_loop,
SgVariableSymbol * & iterator,
SgExpression * & lower_bound,
SgExpression * & upper_bound,
SgExpression * & stride
);
//@}
//------------------------------------------------------------------------
//@{
/*! @name Topdown search
\brief Top-down traversal from current node to find a node of a specified type
*/
//! Query a subtree to get all nodes of a given type, with an appropriate downcast.
template <typename NodeType>
std::vector<NodeType*> querySubTree(SgNode* top, VariantT variant = (VariantT)NodeType::static_variant)
{
#if 0
printf ("Top of SageInterface::querySubTree() \n");
#endif
Rose_STL_Container<SgNode*> nodes = NodeQuery::querySubTree(top,variant);
std::vector<NodeType*> result(nodes.size(), NULL);
int count = 0;
#if 0
printf ("In SageInterface::querySubTree(): before initialization loop \n");
#endif
for (Rose_STL_Container<SgNode*>::const_iterator i = nodes.begin(); i != nodes.end(); ++i, ++count)
{
#if 0
printf ("In SageInterface::querySubTree(): in loop: count = %d \n",count);
#endif
NodeType* node = dynamic_cast<NodeType*>(*i);
ROSE_ASSERT (node);
result[count] = node;
}
#if 0
printf ("Leaving SageInterface::querySubTree(): after initialization loop \n");
#endif
return result;
}
/*! \brief Returns STL vector of SgFile IR node pointers.
Demonstrates use of restricted traversal over just SgFile IR nodes.
*/
std::vector < SgFile * >generateFileList ();
/** Get the current SgProject IR Node.
*
* The library should never have more than one project and it asserts such. If no project has been created yet then this
* function returns the null pointer. */
ROSE_DLL_API SgProject * getProject();
//! \return the project associated with a node
SgProject * getProject(const SgNode * node);
//! Query memory pools to grab SgNode of a specified type
template <typename NodeType>
static std::vector<NodeType*> getSgNodeListFromMemoryPool()
{
// This function uses a memory pool traversal specific to the SgFile IR nodes
class MyTraversal : public ROSE_VisitTraversal
{
public:
std::vector<NodeType*> resultlist;
void visit ( SgNode* node)
{
NodeType* result = dynamic_cast<NodeType* > (node);
ROSE_ASSERT(result!= NULL);
if (result!= NULL)
{
resultlist.push_back(result);
}
};
virtual ~MyTraversal() {}
};
MyTraversal my_traversal;
NodeType::traverseMemoryPoolNodes(my_traversal);
return my_traversal.resultlist;
}
/*! \brief top-down traversal from current node to find the main() function declaration
*/
ROSE_DLL_API SgFunctionDeclaration* findMain(SgNode* currentNode);
//! Find the last declaration statement within a scope (if any). This is often useful to decide where to insert another variable declaration statement. Pragma declarations are not treated as a declaration by default in this context.
SgStatement* findLastDeclarationStatement(SgScopeStatement * scope, bool includePragma = false);
//midend/programTransformation/partialRedundancyElimination/pre.h
//! Find referenced symbols within an expression
std::vector<SgVariableSymbol*> getSymbolsUsedInExpression(SgExpression* expr);
//! Find break statements inside a particular statement, stopping at nested loops or switches
/*! loops or switch statements defines their own contexts for break
statements. The function will stop immediately if run on a loop or switch
statement. If fortranLabel is non-empty, breaks (EXITs) to that label within
nested loops are included in the returned list.
*/
std::vector<SgBreakStmt*> findBreakStmts(SgStatement* code, const std::string& fortranLabel = "");
//! Find all continue statements inside a particular statement, stopping at nested loops
/*! Nested loops define their own contexts for continue statements. The
function will stop immediately if run on a loop
statement. If fortranLabel is non-empty, continues (CYCLEs) to that label
within nested loops are included in the returned list.
*/
std::vector<SgContinueStmt*> findContinueStmts(SgStatement* code, const std::string& fortranLabel = "");
std::vector<SgGotoStatement*> findGotoStmts(SgStatement* scope, SgLabelStatement* l);
std::vector<SgStatement*> getSwitchCases(SgSwitchStatement* sw);
//! Collect all variable references in a subtree
void collectVarRefs(SgLocatedNode* root, std::vector<SgVarRefExp* >& result);
//! Topdown traverse a subtree from root to find the first declaration given its name, scope (optional, can be NULL), and defining or nondefining flag.
template <typename T>
T* findDeclarationStatement(SgNode* root, std::string name, SgScopeStatement* scope, bool isDefining)
{
bool found = false;
#if 0
printf ("In findDeclarationStatement(): root = %p \n",root);
printf ("In findDeclarationStatement(): name = %s \n",name.c_str());
printf ("In findDeclarationStatement(): scope = %p \n",scope);
printf ("In findDeclarationStatement(): isDefining = %s \n",isDefining ? "true" : "false");
#endif
// Do we really want a NULL pointer to be acceptable input to this function?
// Maybe we should have an assertion that it is non-null?
if (!root) return NULL;
T* decl = dynamic_cast<T*>(root);
#if 0
printf ("In findDeclarationStatement(): decl = %p \n",decl);
#endif
if (decl != NULL)
{
if (scope)
{
if ((decl->get_scope() == scope) && (decl->search_for_symbol_from_symbol_table()->get_name() == name))
{
found = true;
}
}
else // Liao 2/9/2010. We should allow NULL scope
{
#if 0
// DQ (12/6/2016): Include this into the debugging code to aboid compiler warning about unused variable.
SgSymbol* symbol = decl->search_for_symbol_from_symbol_table();
printf ("In findDeclarationStatement(): decl->search_for_symbol_from_symbol_table() = %p \n",symbol);
printf ("In findDeclarationStatement(): decl->search_for_symbol_from_symbol_table()->get_name() = %s \n",symbol->get_name().str());
#endif
if (decl->search_for_symbol_from_symbol_table()->get_name() == name)
{
found = true;
}
}
}
if (found)
{
if (isDefining)
{
#if 0
printf ("In findDeclarationStatement(): decl->get_firstNondefiningDeclaration() = %p \n",decl->get_firstNondefiningDeclaration());
printf ("In findDeclarationStatement(): decl->get_definingDeclaration() = %p \n",decl->get_definingDeclaration());
#endif
ROSE_ASSERT (decl->get_definingDeclaration() != NULL);
#if 0
printf ("In findDeclarationStatement(): returing decl->get_definingDeclaration() = %p \n",decl->get_definingDeclaration());
#endif
return dynamic_cast<T*> (decl->get_definingDeclaration());
}
else
{
#if 0
printf ("In findDeclarationStatement(): returing decl = %p \n",decl);
#endif
return decl;
}
}
std::vector<SgNode*> children = root->get_traversalSuccessorContainer();
#if 0
printf ("In findDeclarationStatement(): children.size() = %zu \n",children.size());
#endif
// DQ (4/10/2016): Note that if we are searching for a function member that has it's defining
// declaration defined outside of the class then it will not be found in the child list.
for (std::vector<SgNode*>::const_iterator i = children.begin(); i != children.end(); ++i)
{
T* target = findDeclarationStatement<T> (*i,name,scope,isDefining);
if (target)
{
return target;
}
}
return NULL;
}
//! Topdown traverse a subtree from root to find the first function declaration matching the given name, scope (optional, can be NULL), and defining or nondefining flag. This is an instantiation of findDeclarationStatement<T>.
SgFunctionDeclaration* findFunctionDeclaration(SgNode* root, std::string name, SgScopeStatement* scope, bool isDefining);
#if 0 //TODO
// 1. preorder traversal from current SgNode till find next SgNode of type V_SgXXX
// until reach the end node
SgNode* getNextSgNode( const SgNode* astSourceNode, VariantT=V_SgNode, SgNode* astEndNode=NULL);
// 2. return all nodes of type VariantT following the source node
std::vector<SgNode*> getAllNextSgNode( const SgNode* astSourceNode, VariantT=V_SgNode, SgNode* astEndNode=NULL);
#endif
//@}
//------------------------------------------------------------------------
//@{
/*! @name Bottom up search
\brief Backwards traverse through the AST to find a node, findEnclosingXXX()
*/
// remember to put const to all arguments.
/** Find a node by type using upward traversal.
*
* Traverse backward through a specified node's ancestors, starting with the node's parent and progressing to more distant
* ancestors, to find the first node matching the specified or derived type. If @p includingSelf is true then the
* starting node, @p astNode, is returned if its type matches, otherwise the search starts at the parent of @p astNode.
*
* For the purposes of this function, the parent (P) of an SgDeclarationStatement node (N) is considered to be the first
* non-defining declaration of N if N has both a defining declaration and a first non-defining declaration and the defining
* declaration is different than the first non-defining declaration.
*
* If no ancestor of the requisite type of subtypes is found then this function returns a null pointer.
*
* If @p astNode is the null pointer, then the return value is a null pointer. That is, if there is no node, then there cannot
* be an enclosing node of the specified type. */
template <typename NodeType>
NodeType* getEnclosingNode(const SgNode* astNode, const bool includingSelf = false)
{
#if 1
// DQ (10/20/2012): This is the older version of this implementation. Until I am sure that
// the newer version (below) is what we want to use I will resolve this conflict by keeping
// the previous version in place.
if (NULL == astNode)
{
return NULL;
}
if ( (includingSelf ) && (dynamic_cast<const NodeType*>(astNode)) )
{
return const_cast<NodeType*>(dynamic_cast<const NodeType*> (astNode));
}
// DQ (3/5/2012): Check for reference to self...
ROSE_ASSERT(astNode->get_parent() != astNode);
SgNode* parent = astNode->get_parent();
// DQ (3/5/2012): Check for loops that will cause infinite loops.
SgNode* previouslySeenParent = parent;
bool foundCycle = false;
while ( (foundCycle == false) && (parent != NULL) && (!dynamic_cast<const NodeType*>(parent)) )
{
ROSE_ASSERT(parent->get_parent() != parent);
#if 0
printf ("In getEnclosingNode(): parent = %p = %s \n",parent,parent->class_name().c_str());
#endif
parent = parent->get_parent();
// DQ (3/5/2012): Check for loops that will cause infinite loops.
// ROSE_ASSERT(parent != previouslySeenParent);
if (parent == previouslySeenParent)
{
foundCycle = true;
}
}
#if 0
printf ("previouslySeenParent = %p = %s \n",previouslySeenParent,previouslySeenParent->class_name().c_str());
#endif
parent = previouslySeenParent;
SgDeclarationStatement* declarationStatement = isSgDeclarationStatement(parent);
if (declarationStatement != NULL)
{
#if 0
printf ("Found a SgDeclarationStatement \n");
#endif
SgDeclarationStatement* definingDeclaration = declarationStatement->get_definingDeclaration();
SgDeclarationStatement* firstNondefiningDeclaration = declarationStatement->get_firstNondefiningDeclaration();
#if 0
printf (" --- declarationStatement = %p \n",declarationStatement);
printf (" --- definingDeclaration = %p \n",definingDeclaration);
if (definingDeclaration != NULL && definingDeclaration->get_parent() != NULL)
printf (" --- definingDeclaration ->get_parent() = %p = %s \n",definingDeclaration->get_parent(),definingDeclaration->get_parent()->class_name().c_str());
printf (" --- firstNondefiningDeclaration = %p \n",firstNondefiningDeclaration);
if (firstNondefiningDeclaration != NULL && firstNondefiningDeclaration->get_parent() != NULL)
printf (" --- firstNondefiningDeclaration ->get_parent() = %p = %s \n",firstNondefiningDeclaration->get_parent(),firstNondefiningDeclaration->get_parent()->class_name().c_str());
#endif
if (definingDeclaration != NULL && declarationStatement != firstNondefiningDeclaration)
{
#if 0
printf ("Found a nondefining declaration so use the non-defining declaration instead \n");
#endif
// DQ (10/19/2012): Use the defining declaration instead.
// parent = firstNondefiningDeclaration;
parent = definingDeclaration;
}
}
#if 0
printf ("reset: previouslySeenParent = %p = %s \n",previouslySeenParent,previouslySeenParent->class_name().c_str());
#endif
// DQ (10/19/2012): This branch is just to document the cycle that was previously detected, it is for
// debugging only. Thus it ony make sense for it to be executed when "(foundCycle == true)". However,
// this will have to be revisited later since it appears clear that it is a problem for the binary analysis
// work when it is visited for this case. Since the cycle is detected, but there is no assertion on the
// cycle, we don't exit when a cycle is identified (which is the point of the code below).
// Note also that I have fixed the code (above and below) to only chase pointers through defining
// declarations (where they exist), this is important since non-defining declarations can be almost
// anywhere (and thus chasing them can make it appear that there are cycles where there are none
// (I think); test2012_234.C demonstrates an example of this.
// DQ (10/9/2012): Robb has suggested this change to fix the binary analysis work.
// if (foundCycle == true)
if (foundCycle == false)
{
while ( (parent != NULL) && (!dynamic_cast<const NodeType*>(parent)) )
{
ROSE_ASSERT(parent->get_parent() != parent);
#if 0
printf ("In getEnclosingNode() (2nd try): parent = %p = %s \n",parent,parent->class_name().c_str());
if (parent->get_file_info() != NULL)
parent->get_file_info()->display("In getEnclosingNode() (2nd try): debug");
#endif
SgDeclarationStatement* declarationStatement = isSgDeclarationStatement(parent);
if (declarationStatement != NULL)
{
#if 0
printf ("Found a SgDeclarationStatement \n");
#endif
SgDeclarationStatement* definingDeclaration = declarationStatement->get_definingDeclaration();
SgDeclarationStatement* firstNondefiningDeclaration = declarationStatement->get_firstNondefiningDeclaration();
#if 0
printf (" --- declarationStatement = %p = %s \n",declarationStatement,(declarationStatement != NULL) ? declarationStatement->class_name().c_str() : "null");
printf (" --- definingDeclaration = %p \n",definingDeclaration);
if (definingDeclaration != NULL && definingDeclaration->get_parent() != NULL)
printf (" --- definingDeclaration ->get_parent() = %p = %s \n",definingDeclaration->get_parent(),definingDeclaration->get_parent()->class_name().c_str());
printf (" --- firstNondefiningDeclaration = %p \n",firstNondefiningDeclaration);
if (firstNondefiningDeclaration != NULL && firstNondefiningDeclaration->get_parent() != NULL)
printf (" --- firstNondefiningDeclaration ->get_parent() = %p = %s \n",firstNondefiningDeclaration->get_parent(),firstNondefiningDeclaration->get_parent()->class_name().c_str());
#endif
if (definingDeclaration != NULL && declarationStatement != firstNondefiningDeclaration)
{
#if 0
printf ("Found a nondefining declaration so use the firstNondefining declaration instead \n");
#endif
// DQ (10/19/2012): Use the defining declaration instead.
// parent = firstNondefiningDeclaration;
parent = definingDeclaration;
}
}
parent = parent->get_parent();
#if 1
// DQ (3/5/2012): Check for loops that will cause infinite loops.
ROSE_ASSERT(parent != previouslySeenParent);
#else
printf ("WARNING::WARNING::WARNING commented out assertion for parent != previouslySeenParent \n");
if (parent == previouslySeenParent)
break;
#endif
}
}
return const_cast<NodeType*>(dynamic_cast<const NodeType*> (parent));
#else
// DQ (10/20/2012): Using Robb's newer version with my modification to use the definingDeclaration rather than firstNondefiningDeclaration (below).
// Find the parent of specified type, but watch out for cycles in the ancestry (which would cause an infinite loop).
// Cast away const because isSg* functions aren't defined for const node pointers; and our return is not const.
SgNode *node = const_cast<SgNode*>(!astNode || includingSelf ? astNode : astNode->get_parent());
std::set<const SgNode*> seen; // nodes we've seen, in order to detect cycles
while (node) {
if (NodeType *found = dynamic_cast<NodeType*>(node))
return found;
// FIXME: Cycle detection could be moved elsewhere so we don't need to do it on every call. [RPM 2012-10-09]
ROSE_ASSERT(seen.insert(node).second);
// Traverse to parent (declaration statements are a special case)
if (SgDeclarationStatement *declarationStatement = isSgDeclarationStatement(node)) {
SgDeclarationStatement *definingDeclaration = declarationStatement->get_definingDeclaration();
SgDeclarationStatement *firstNondefiningDeclaration = declarationStatement->get_firstNondefiningDeclaration();
if (definingDeclaration && firstNondefiningDeclaration && declarationStatement != firstNondefiningDeclaration) {
// DQ (10/19/2012): Use the defining declaration instead.
// node = firstNondefiningDeclaration;
node = definingDeclaration;
}
} else {
node = node->get_parent();
}
}
return NULL;
#endif
}
//! Find enclosing source file node
ROSE_DLL_API SgSourceFile* getEnclosingSourceFile(SgNode* n, const bool includingSelf=false);
//! Get the closest scope from astNode. Return astNode if it is already a scope.
ROSE_DLL_API SgScopeStatement* getScope(const SgNode* astNode);
//! Get the enclosing scope from a node n
ROSE_DLL_API SgScopeStatement* getEnclosingScope(SgNode* n, const bool includingSelf=false);
//! Traverse back through a node's parents to find the enclosing global scope
ROSE_DLL_API SgGlobal* getGlobalScope( const SgNode* astNode);
//! Find the function definition
ROSE_DLL_API SgFunctionDefinition* getEnclosingProcedure(SgNode* n, const bool includingSelf=false);
ROSE_DLL_API SgFunctionDefinition* getEnclosingFunctionDefinition(SgNode* astNode, const bool includingSelf=false);
//! Find the closest enclosing statement, including the given node
ROSE_DLL_API SgStatement* getEnclosingStatement(SgNode* n);
//! Find the closest switch outside a given statement (normally used for case and default statements)
ROSE_DLL_API SgSwitchStatement* findEnclosingSwitch(SgStatement* s);
//! Find enclosing OpenMP clause body statement from s. If s is already one, return it directly.
ROSE_DLL_API SgOmpClauseBodyStatement* findEnclosingOmpClauseBodyStatement(SgStatement* s);
//! Find the closest loop outside the given statement; if fortranLabel is not empty, the Fortran label of the loop must be equal to it
ROSE_DLL_API SgScopeStatement* findEnclosingLoop(SgStatement* s, const std::string& fortranLabel = "", bool stopOnSwitches = false);
//! Find the enclosing function declaration, including its derived instances like isSgProcedureHeaderStatement, isSgProgramHeaderStatement, and isSgMemberFunctionDeclaration.
ROSE_DLL_API SgFunctionDeclaration * getEnclosingFunctionDeclaration (SgNode * astNode, const bool includingSelf=false);
//roseSupport/utility_functions.h
//! get the SgFile node from current node
ROSE_DLL_API SgFile* getEnclosingFileNode (SgNode* astNode );
//! Get the initializer containing an expression if it is within an initializer.
ROSE_DLL_API SgInitializer* getInitializerOfExpression(SgExpression* n);
//! Get the closest class definition enclosing the specified AST node,
ROSE_DLL_API SgClassDefinition* getEnclosingClassDefinition(SgNode* astnode, const bool includingSelf=false);
//! Get the closest class declaration enclosing the specified AST node,
ROSE_DLL_API SgClassDeclaration* getEnclosingClassDeclaration( SgNode* astNode );
// DQ (2/7/2019): Adding support for name qualification of variable references associated with SgPointerMemberType function parameters.
//! Get the enclosing SgExprListExp (used as part of function argument index evaluation in subexpressions).
ROSE_DLL_API SgExprListExp* getEnclosingExprListExp(SgNode* astNode, const bool includingSelf = false);
// DQ (2/7/2019): Need a function to return when an expression is in an expression subtree.
// This is part of index evaluation ofr expressions in function argument lists, but likely usefule elsewhere as well.
ROSE_DLL_API bool isInSubTree(SgExpression* subtree, SgExpression* exp);
// DQ (2/7/2019): Need a function to return the SgFunctionDeclaration from a SgFunctionCallExp.
ROSE_DLL_API SgFunctionDeclaration* getFunctionDeclaration ( SgFunctionCallExp* functionCallExp );
// DQ (2/17/2019): Generalizing this support for SgVarRefExp and SgMemberFunctionRefExp nodes.
// DQ (2/8/2019): Adding support for detecting when to use added name qualification for pointer-to-member expressions.
ROSE_DLL_API bool isDataMemberReference(SgVarRefExp* varRefExp);
// ROSE_DLL_API bool isAddressTaken(SgVarRefExp* varRefExp);
ROSE_DLL_API bool isAddressTaken(SgExpression* refExp);
// DQ (2/17/2019): Adding support for detecting when to use added name qualification for membr function references.
ROSE_DLL_API bool isMemberFunctionMemberReference(SgMemberFunctionRefExp* memberFunctionRefExp);
// DQ (2/15/2019): Adding support for detecting which class a member reference is being made from.
// ROSE_DLL_API SgClassType* getClassTypeForDataMemberReference(SgVarRefExp* varRefExp);
// ROSE_DLL_API std::list<SgClassType*> getClassTypeChainForDataMemberReference(SgVarRefExp* varRefExp);
ROSE_DLL_API std::list<SgClassType*> getClassTypeChainForMemberReference(SgExpression* refExp);
// DQ (2/17/2019): Display the shared nodes in the AST for debugging.
ROSE_DLL_API void outputSharedNodes( SgNode* node );
// TODO
#if 0
SgNode * getEnclosingSgNode(SgNode* source,VariantT, SgNode* endNode=NULL);
std::vector<SgNode *> getAllEnclosingSgNode(SgNode* source,VariantT, SgNode* endNode=NULL);
SgVariableDeclaration* findVariableDeclaratin( const string& varname)
SgClassDeclaration* getEnclosingClassDeclaration( const SgNode* astNode);
// e.g. for some expression, find its parent statement
SgStatement* getEnclosingStatement(const SgNode* astNode);
SgSwitchStatement* getEnclosingSwitch(SgStatement* s);
SgModuleStatement* getEnclosingModuleStatement( const SgNode* astNode);
// used to build a variable reference for compiler generated code in current scope
SgSymbol * findReachingDefinition (SgScopeStatement* startScope, SgName &name);
#endif
//@}
//------------------------------------------------------------------------
//@{
/*! @name AST Walk and Traversal
\brief
*/
// Liao, 1/9/2008
/*!
\brief return the first global scope under current project
*/
ROSE_DLL_API SgGlobal * getFirstGlobalScope(SgProject *project);
/*!
\brief get the last statement within a scope, return NULL if it does not exit
*/
ROSE_DLL_API SgStatement* getLastStatement(SgScopeStatement *scope);
//! Get the first statement within a scope, return NULL if it does not exist. Skip compiler-generated statement by default. Count transformation-generated ones, but excluding those which are not to be outputted in unparsers.
ROSE_DLL_API SgStatement* getFirstStatement(SgScopeStatement *scope,bool includingCompilerGenerated=false);
//!Find the first defining function declaration statement in a scope
ROSE_DLL_API SgFunctionDeclaration* findFirstDefiningFunctionDecl(SgScopeStatement* scope);
//! Get next statement within the same scope of current statement
ROSE_DLL_API SgStatement* getNextStatement(SgStatement * currentStmt);
//! Get previous statement of the current statement. It may return a previous statement of a parent scope by default (climbOutScope is true), otherwise only a previous statement of the same scope is returned.
ROSE_DLL_API SgStatement* getPreviousStatement(SgStatement * currentStmt, bool climbOutScope = true);
#if 0 //TODO
// preorder traversal from current SgNode till find next SgNode of type V_SgXXX
SgNode* getNextSgNode( const SgNode* currentNode, VariantT=V_SgNode);
#endif
// DQ (11/15/2018): Adding support for traversals over the include file tree.
//! return path prefix for subtree of include files.
void listHeaderFiles ( SgIncludeFile* includeFile );
//@}
//------------------------------------------------------------------------
//@{
/*! @name AST Comparison
\brief Compare AST nodes, subtree, etc
*/
//! Check if a SgIntVal node has a given value
ROSE_DLL_API bool isEqualToIntConst(SgExpression* e, int value);
//! Check if two function declarations refer to the same one. Two function declarations are the same when they are a) identical, b) same name in C c) same qualified named and mangled name in C++. A nondefining (prototype) declaration and a defining declaration of a same function are treated as the same.
/*!
* There is a similar function bool compareFunctionDeclarations(SgFunctionDeclaration *f1, SgFunctionDeclaration *f2) from Classhierarchy.C
*/
ROSE_DLL_API bool isSameFunction(SgFunctionDeclaration* func1, SgFunctionDeclaration* func2);
//! Check if a statement is the last statement within its closed scope
ROSE_DLL_API bool isLastStatement(SgStatement* stmt);
//@}
//------------------------------------------------------------------------
//@{
/*! @name AST insert, removal, and replacement
\brief Add, remove,and replace AST
scope->append_statement(), exprListExp->append_expression() etc. are not enough to handle side effect of parent pointers, symbol tables, preprocessing info, defining/nondefining pointers etc.
*/
// DQ (2/24/2009): Simple function to delete an AST subtree (used in outlining).
//! Function to delete AST subtree's nodes only, users must take care of any dangling pointers, symbols or types that result.
ROSE_DLL_API void deleteAST(SgNode* node);
//! Special purpose function for deleting AST expression tress containing valid original expression trees in constant folded expressions (for internal use only).
ROSE_DLL_API void deleteExpressionTreeWithOriginalExpressionSubtrees(SgNode* root);
// DQ (2/25/2009): Added new function to support outliner.
//! Move statements in first block to the second block (preserves order and rebuilds the symbol table).
ROSE_DLL_API void moveStatementsBetweenBlocks ( SgBasicBlock* sourceBlock, SgBasicBlock* targetBlock );
//! Move a variable declaration to a new scope, handle symbol, special scopes like For loop, etc.
ROSE_DLL_API void moveVariableDeclaration(SgVariableDeclaration* decl, SgScopeStatement* target_scope);
//! Append a statement to the end of the current scope, handle side effect of appending statements, e.g. preprocessing info, defining/nondefining pointers etc.
ROSE_DLL_API void appendStatement(SgStatement *stmt, SgScopeStatement* scope=NULL);
//! Append a statement to the end of SgForInitStatement
ROSE_DLL_API void appendStatement(SgStatement *stmt, SgForInitStatement* for_init_stmt);
//! Append a list of statements to the end of the current scope, handle side effect of appending statements, e.g. preprocessing info, defining/nondefining pointers etc.
ROSE_DLL_API void appendStatementList(const std::vector<SgStatement*>& stmt, SgScopeStatement* scope=NULL);
// DQ (2/6/2009): Added function to support outlining into separate file.
//! Append a copy ('decl') of a function ('original_statement') into a 'scope', include any referenced declarations required if the scope is within a compiler generated file. All referenced declarations, including those from headers, are inserted if excludeHeaderFiles is set to true (the new file will not have any headers).
ROSE_DLL_API void appendStatementWithDependentDeclaration( SgDeclarationStatement* decl, SgGlobal* scope, SgStatement* original_statement, bool excludeHeaderFiles );
//! Prepend a statement to the beginning of the current scope, handling side
//! effects as appropriate
ROSE_DLL_API void prependStatement(SgStatement *stmt, SgScopeStatement* scope=NULL);
//! Prepend a statement to the beginning of SgForInitStatement
ROSE_DLL_API void prependStatement(SgStatement *stmt, SgForInitStatement* for_init_stmt);
//! prepend a list of statements to the beginning of the current scope,
//! handling side effects as appropriate
ROSE_DLL_API void prependStatementList(const std::vector<SgStatement*>& stmt, SgScopeStatement* scope=NULL);
//! Check if a scope statement has a simple children statement list
//! so insert additional statements under the scope is straightforward and unambiguous .
//! for example, SgBasicBlock has a simple statement list while IfStmt does not.
ROSE_DLL_API bool hasSimpleChildrenList (SgScopeStatement* scope);
//! Insert a statement before or after the target statement within the target's scope. Move around preprocessing info automatically
ROSE_DLL_API void insertStatement(SgStatement *targetStmt, SgStatement* newStmt, bool insertBefore= true, bool autoMovePreprocessingInfo = true);
//! Insert a list of statements before or after the target statement within the
//target's scope
ROSE_DLL_API void insertStatementList(SgStatement *targetStmt, const std::vector<SgStatement*>& newStmts, bool insertBefore= true);
//! Insert a statement before a target statement
ROSE_DLL_API void insertStatementBefore(SgStatement *targetStmt, SgStatement* newStmt, bool autoMovePreprocessingInfo = true);
//! Insert a list of statements before a target statement
ROSE_DLL_API void insertStatementListBefore(SgStatement *targetStmt, const std::vector<SgStatement*>& newStmts);
//! Insert a statement after a target statement, Move around preprocessing info automatically by default
ROSE_DLL_API void insertStatementAfter(SgStatement *targetStmt, SgStatement* newStmt, bool autoMovePreprocessingInfo = true);
//! Insert a list of statements after a target statement
ROSE_DLL_API void insertStatementListAfter(SgStatement *targetStmt, const std::vector<SgStatement*>& newStmt);
//! Insert a statement after the last declaration within a scope. The statement will be prepended to the scope if there is no declaration statement found
ROSE_DLL_API void insertStatementAfterLastDeclaration(SgStatement* stmt, SgScopeStatement* scope);
//! Insert a list of statements after the last declaration within a scope. The statement will be prepended to the scope if there is no declaration statement found
ROSE_DLL_API void insertStatementAfterLastDeclaration(std::vector<SgStatement*> stmt_list, SgScopeStatement* scope);
//! Insert a statement before the first non-declaration statement in a scope. If the scope has no non-declaration statements
// then the statement is inserted at the end of the scope.
ROSE_DLL_API void insertStatementBeforeFirstNonDeclaration(SgStatement *newStmt, SgScopeStatement *scope,
bool movePreprocessingInfo=true);
//! Insert statements before the first non-declaration statement in a scope. If the scope has no non-declaration statements
//then the new statements are inserted at the end of the scope.
ROSE_DLL_API void insertStatementListBeforeFirstNonDeclaration(const std::vector<SgStatement*> &newStmts, SgScopeStatement *scope);
// DQ (11/21/2018): We need to sometimes insert something after the last statement of the collection from rose_edg_required_macros_and_functions.h.
ROSE_DLL_API SgStatement* lastFrontEndSpecificStatement( SgGlobal* globalScope );
//! Remove a statement from its attach point of the AST. Automatically keep its associated preprocessing information at the original place after the removal. The statement is still in memory and it is up to the users to decide if the removed one will be inserted somewhere else or released from memory (deleteAST()).
ROSE_DLL_API void removeStatement(SgStatement* stmt, bool autoRelocatePreprocessingInfo = true);
//! Deep delete a sub AST tree. It uses postorder traversal to delete each child node. Users must take care of any dangling pointers, symbols or types that result. This is identical to deleteAST()
ROSE_DLL_API void deepDelete(SgNode* root);
//! Replace a statement with another. Move preprocessing information from oldStmt to newStmt if requested.
ROSE_DLL_API void replaceStatement(SgStatement* oldStmt, SgStatement* newStmt, bool movePreprocessinInfo = false);
//! Replace an anchor node with a specified pattern subtree with optional SgVariantExpression. All SgVariantExpression in the pattern will be replaced with copies of the anchor node.
ROSE_DLL_API SgNode* replaceWithPattern (SgNode * anchor, SgNode* new_pattern);
//! Replace all variable references to an old symbol in a scope to being references to a new symbol.
// Essentially replace variable a with b.
ROSE_DLL_API void replaceVariableReferences(SgVariableSymbol* old_sym, SgVariableSymbol* new_sym, SgScopeStatement * scope );
// DQ (11/12/2018): Adding test to avoid issues that we can't test for in the unparsing of header files using the token based unparsing.
//! If header file unparsing and token-based unparsing are used, then some statements in header files
//! used with the same name and different include syntax can't be transformed. This is currently because
//! there is no way to generally test the resulting transformed code generated by ROSE.
ROSE_DLL_API bool statementCanBeTransformed(SgStatement* stmt);
/** Given an expression, generates a temporary variable whose initializer optionally evaluates
* that expression. Then, the var reference expression returned can be used instead of the original
* expression. The temporary variable created can be reassigned to the expression by the returned SgAssignOp;
* this can be used when the expression the variable represents needs to be evaluated. NOTE: This handles
* reference types correctly by using pointer types for the temporary.
* @param expression Expression which will be replaced by a variable
* @param scope scope in which the temporary variable will be generated
* @param reEvaluate an assignment op to reevaluate the expression. Leave NULL if not needed
* @return declaration of the temporary variable, and a a variable reference expression to use instead of
* the original expression. */
std::pair<SgVariableDeclaration*, SgExpression* > createTempVariableForExpression(SgExpression* expression,
SgScopeStatement* scope, bool initializeInDeclaration, SgAssignOp** reEvaluate = NULL);
/* This function creates a temporary variable for a given expression in the given scope
This is different from SageInterface::createTempVariableForExpression in that it does not
try to be smart to create pointers to reference types and so on. The tempt is initialized to expression.
The caller is responsible for setting the parent of SgVariableDeclaration since buildVariableDeclaration
may not set_parent() when the scope stack is empty. See programTransformation/extractFunctionArgumentsNormalization/ExtractFunctionArguments.C for sample usage.
@param expression Expression which will be replaced by a variable
@param scope scope in which the temporary variable will be generated
*/
std::pair<SgVariableDeclaration*, SgExpression*> createTempVariableAndReferenceForExpression
(SgExpression* expression, SgScopeStatement* scope);
//! Append an argument to SgFunctionParameterList, transparently set parent,scope, and symbols for arguments when possible
/*! We recommend to build SgFunctionParameterList before building a function declaration
However, it is still allowed to append new arguments for existing function declarations.
\todo function type , function symbol also need attention.
*/
ROSE_DLL_API SgVariableSymbol* appendArg(SgFunctionParameterList *, SgInitializedName*);
//!Prepend an argument to SgFunctionParameterList
ROSE_DLL_API SgVariableSymbol* prependArg(SgFunctionParameterList *, SgInitializedName*);
//! Append an expression to a SgExprListExp, set the parent pointer also
ROSE_DLL_API void appendExpression(SgExprListExp *, SgExpression*);
//! Append an expression list to a SgExprListExp, set the parent pointers also
ROSE_DLL_API void appendExpressionList(SgExprListExp *, const std::vector<SgExpression*>&);
//! Set parameter list for a function declaration, considering existing parameter list etc.
template <class actualFunction>
void setParameterList(actualFunction *func,SgFunctionParameterList *paralist) {
// TODO consider the difference between C++ and Fortran
// fixup the scope of arguments,no symbols for nondefining function declaration's arguments
// DQ (11/25/2011): templated function so that we can handle both
// SgFunctionDeclaration and SgTemplateFunctionDeclaration (and their associated member
// function derived classes).
ROSE_ASSERT(func != NULL);
ROSE_ASSERT(paralist != NULL);
#if 0
// At this point we don't have cerr and endl defined, so comment this code out.
// Warn to users if a paralist is being shared
if (paralist->get_parent() !=NULL)
{
cerr << "Waring! Setting a used SgFunctionParameterList to function: "
<< (func->get_name()).getString()<<endl
<< " Sharing parameter lists can corrupt symbol tables!"<<endl
<< " Please use deepCopy() to get an exclusive parameter list for each function declaration!"<<endl;
// ROSE_ASSERT(false);
}
#endif
// Liao,2/5/2008 constructor of SgFunctionDeclaration will automatically generate SgFunctionParameterList, so be cautious when set new paralist!!
if (func->get_parameterList() != NULL)
{
if (func->get_parameterList() != paralist)
{
delete func->get_parameterList();
}
}
func->set_parameterList(paralist);
paralist->set_parent(func);
// DQ (5/15/2012): Need to set the declptr in each SgInitializedName IR node.
// This is needed to support the AST Copy mechanism (at least). The files: test2005_150.C,
// test2012_81.C and testcode2012_82.C demonstrate this problem.
SgInitializedNamePtrList & args = paralist->get_args();
for (SgInitializedNamePtrList::iterator i = args.begin(); i != args.end(); i++)
{
(*i)->set_declptr(func);
}
}
//! Set a pragma of a pragma declaration. handle memory release for preexisting pragma, and set parent pointer.
ROSE_DLL_API void setPragma(SgPragmaDeclaration* decl, SgPragma *pragma);
//! Replace an expression with another, used for variable reference substitution and others. the old expression can be deleted (default case) or kept.
ROSE_DLL_API void replaceExpression(SgExpression* oldExp, SgExpression* newExp, bool keepOldExp=false);
//! Replace a given expression with a list of statements produced by a generator
ROSE_DLL_API void replaceExpressionWithStatement(SgExpression* from,
SageInterface::StatementGenerator* to);
//! Similar to replaceExpressionWithStatement, but with more restrictions.
//! Assumptions: from is not within the test of a loop or ifStmt, not currently traversing from or the statement it is in
ROSE_DLL_API void replaceSubexpressionWithStatement(SgExpression* from,
SageInterface::StatementGenerator* to);
//! Set operands for expressions with single operand, such as unary expressions. handle file info, lvalue, pointer downcasting, parent pointer etc.
ROSE_DLL_API void setOperand(SgExpression* target, SgExpression* operand);
//!set left hand operand for binary expressions, transparently downcasting target expressions when necessary
ROSE_DLL_API void setLhsOperand(SgExpression* target, SgExpression* lhs);
//!set left hand operand for binary expression
ROSE_DLL_API void setRhsOperand(SgExpression* target, SgExpression* rhs);
//! Set original expression trees to NULL for SgValueExp or SgCastExp expressions, so you can change the value and have it unparsed correctly.
ROSE_DLL_API void removeAllOriginalExpressionTrees(SgNode* top);
// DQ (1/25/2010): Added support for directories
//! Move file to be generated in a subdirectory (will be generated by the unparser).
ROSE_DLL_API void moveToSubdirectory ( std::string directoryName, SgFile* file );
//! Supporting function to comment relocation in insertStatement() and removeStatement().
ROSE_DLL_API SgStatement* findSurroundingStatementFromSameFile(SgStatement* targetStmt, bool & surroundingStatementPreceedsTargetStatement);
//! Relocate comments and CPP directives from one statement to another.
ROSE_DLL_API void moveCommentsToNewStatement(SgStatement* sourceStatement, const std::vector<int> & indexList, SgStatement* targetStatement, bool surroundingStatementPreceedsTargetStatement);
// DQ (7/19/2015): This is required to support general unparsing of template instantations for the GNU g++
// compiler which does not permit name qualification to be used to support the expression of the namespace
// where a template instantiatoon would be places. Such name qualification would also sometimes require
// global qualification which is also not allowed by the GNU g++ compiler. These issues appear to be
// specific to the GNU compiler versions, at least versions 4.4 through 4.8.
//! Relocate the declaration to be explicitly represented in its associated namespace (required for some backend compilers to process template instantiations).
ROSE_DLL_API void moveDeclarationToAssociatedNamespace ( SgDeclarationStatement* declarationStatement );
ROSE_DLL_API bool isTemplateInstantiationNode(SgNode* node);
ROSE_DLL_API void wrapAllTemplateInstantiationsInAssociatedNamespaces(SgProject* root);
// DQ (12/1/2015): Adding support for fixup internal data struuctures that have references to statements (e.g. macro expansions).
ROSE_DLL_API void resetInternalMapsForTargetStatement(SgStatement* sourceStatement);
// DQ (6/7/2019): Add support for transforming function definitions to function prototypes in a subtree.
// We might have to make this specific to a file (only traversing the functions in that file).
/*!\brief XXX
* This function operates on the new file used to support outlined function definitions.
* We use a copy of the file where the code will be outlined FROM, so that if there are references to
* declarations in the outlined code we can support the outpiled code with those references. This
* approach has the added advantage of also supporting the same include file tree as the original
* file where the outlined code is being taken from.
*/
ROSE_DLL_API void convertFunctionDefinitionsToFunctionPrototypes(SgNode* node);
// DQ (11/10/2019): Lower level support for convertFunctionDefinitionsToFunctionPrototypes().
ROSE_DLL_API void replaceDefiningFunctionDeclarationWithFunctionPrototype ( SgFunctionDeclaration* functionDeclaration );
ROSE_DLL_API std::vector<SgFunctionDeclaration*> generateFunctionDefinitionsList(SgNode* node);
//@}
//------------------------------------------------------------------------
//@{
/*! @name AST repair, fix, and postprocessing.
\brief Mostly used internally when some AST pieces are built without knowing their target
scope/parent, especially during bottom-up construction of AST. The associated symbols,
parent and scope pointers cannot be set on construction then.
A set of utility functions are provided to
patch up scope, parent, symbol for them when the target scope/parent become know.
*/
//! Connect variable reference to the right variable symbols when feasible, return the number of references being fixed.
/*! In AST translation, it is possible to build a variable reference before the variable
is being declared. buildVarRefExp() will use fake initialized name and symbol as placeholders
to get the work done. Users should call fixVariableReference() when AST is complete and all
variable declarations are in place.
*/
ROSE_DLL_API int fixVariableReferences(SgNode* root, bool cleanUnusedSymbol=true);
//!Patch up symbol, scope, and parent information when a SgVariableDeclaration's scope is known.
/*!
It is possible to build a variable declaration without knowing its scope information during bottom-up construction of AST, though top-down construction is recommended in general.
In this case, we have to patch up symbol table, scope and parent information when the scope is known. This function is usually used internally within appendStatment(), insertStatement().
*/
ROSE_DLL_API void fixVariableDeclaration(SgVariableDeclaration* varDecl, SgScopeStatement* scope);
//! Fix symbols, parent and scope pointers. Used internally within appendStatment(), insertStatement() etc when a struct declaration was built without knowing its target scope.
ROSE_DLL_API void fixStructDeclaration(SgClassDeclaration* structDecl, SgScopeStatement* scope);
//! Fix symbols, parent and scope pointers. Used internally within appendStatment(), insertStatement() etc when a class declaration was built without knowing its target scope.
ROSE_DLL_API void fixClassDeclaration(SgClassDeclaration* classDecl, SgScopeStatement* scope);
//! Fix symbols, parent and scope pointers. Used internally within appendStatment(), insertStatement() etc when a namespace declaration was built without knowing its target scope.
ROSE_DLL_API void fixNamespaceDeclaration(SgNamespaceDeclarationStatement* structDecl, SgScopeStatement* scope);
//! Fix symbol table for SgLabelStatement. Used Internally when the label is built without knowing its target scope. Both parameters cannot be NULL.
ROSE_DLL_API void fixLabelStatement(SgLabelStatement* label_stmt, SgScopeStatement* scope);
//! Set a numerical label for a Fortran statement. The statement should have a enclosing function definition already. SgLabelSymbol and SgLabelRefExp are created transparently as needed.
ROSE_DLL_API void setFortranNumericLabel(SgStatement* stmt, int label_value);
//! Suggest next usable (non-conflicting) numeric label value for a Fortran function definition scope
ROSE_DLL_API int suggestNextNumericLabel(SgFunctionDefinition* func_def);
//! Fix the symbol table and set scope (only if scope in declaration is not already set).
ROSE_DLL_API void fixFunctionDeclaration(SgFunctionDeclaration* stmt, SgScopeStatement* scope);
//! Fix the symbol table and set scope (only if scope in declaration is not already set).
ROSE_DLL_API void fixTemplateDeclaration(SgTemplateDeclaration* stmt, SgScopeStatement* scope);
//! A wrapper containing fixes (fixVariableDeclaration(),fixStructDeclaration(), fixLabelStatement(), etc) for all kinds statements. Should be used before attaching the statement into AST.
ROSE_DLL_API void fixStatement(SgStatement* stmt, SgScopeStatement* scope);
// DQ (6/11/2015): This reports the statements that are marked as transformed (used to debug the token-based unparsing).
//! This collects the statements that are marked as transformed (useful in debugging).
ROSE_DLL_API std::set<SgStatement*> collectTransformedStatements( SgNode* node );
//! This collects the statements that are marked as modified (a flag automatically set by all set_* generated functions) (useful in debugging).
ROSE_DLL_API std::set<SgStatement*> collectModifiedStatements( SgNode* node );
//! This collects the SgLocatedNodes that are marked as modified (a flag automatically set by all set_* generated functions) (useful in debugging).
ROSE_DLL_API std::set<SgLocatedNode*> collectModifiedLocatedNodes( SgNode* node );
// DQ (6/5/2019): Use the previously constructed set (above) to reset the IR nodes to be marked as isModified.
//! Use the set of IR nodes and set the isModified flag in each IR node to true.
ROSE_DLL_API void resetModifiedLocatedNodes(const std::set<SgLocatedNode*> & modifiedNodeSet);
// DQ (10/23/2018): Report nodes that are marked as modified.
ROSE_DLL_API void reportModifiedStatements(const std::string & label, SgNode* node);
// DQ (3/22/2019): Translate CPP directives from attached preprocessor information to CPP Directive Declaration IR nodes.
ROSE_DLL_API void translateToUseCppDeclarations( SgNode* n );
ROSE_DLL_API void translateScopeToUseCppDeclarations( SgScopeStatement* scope );
ROSE_DLL_API std::vector<SgC_PreprocessorDirectiveStatement*> translateStatementToUseCppDeclarations( SgStatement* statement, SgScopeStatement* scope);
ROSE_DLL_API void printOutComments ( SgLocatedNode* locatedNode );
ROSE_DLL_API bool skipTranslateToUseCppDeclaration( PreprocessingInfo* currentPreprocessingInfo );
// DQ (12/2/2019): Debugging support.
ROSE_DLL_API void outputFileIds( SgNode* node );
//@}
//! Update defining and nondefining links due to a newly introduced function declaration. Should be used after inserting the function into a scope.
/*! This function not only set the defining and nondefining links of the newly introduced
* function declaration inside a scope, but also update other same function declarations' links
* accordingly if there are any.
* Assumption: The function has already inserted/appended/prepended into the scope before calling this function.
*/
ROSE_DLL_API void updateDefiningNondefiningLinks(SgFunctionDeclaration* func, SgScopeStatement* scope);
//------------------------------------------------------------------------
//@{
/*! @name Advanced AST transformations, analyses, and optimizations
\brief Some complex but commonly used AST transformations.
*/
//! Collect all read and write references within stmt, which can be a function, a scope statement, or a single statement. Note that a reference can be both read and written, like i++
ROSE_DLL_API bool
collectReadWriteRefs(SgStatement* stmt, std::vector<SgNode*>& readRefs, std::vector<SgNode*>& writeRefs, bool useCachedDefUse=false);
//!Collect unique variables which are read or written within a statement. Note that a variable can be both read and written. The statement can be either of a function, a scope, or a single line statement. For accesses to members of aggregate data, we return the coarse grain aggregate mem obj by default.
ROSE_DLL_API bool collectReadWriteVariables(SgStatement* stmt, std::set<SgInitializedName*>& readVars, std::set<SgInitializedName*>& writeVars, bool coarseGrain=true);
//!Collect read only variables within a statement. The statement can be either of a function, a scope, or a single line statement. For accesses to members of aggregate data, we return the coarse grain aggregate mem obj by default.
ROSE_DLL_API void collectReadOnlyVariables(SgStatement* stmt, std::set<SgInitializedName*>& readOnlyVars, bool coarseGrain=true);
//!Collect read only variable symbols within a statement. The statement can be either of a function, a scope, or a single line statement. For accesses to members of aggregate data, we return the coarse grain aggregate mem obj by default.
ROSE_DLL_API void collectReadOnlySymbols(SgStatement* stmt, std::set<SgVariableSymbol*>& readOnlySymbols, bool coarseGrain=true);
//! Check if a variable reference is used by its address: including &a expression and foo(a) when type2 foo(Type& parameter) in C++
ROSE_DLL_API bool isUseByAddressVariableRef(SgVarRefExp* ref);
//! Collect variable references involving use by address: including &a expression and foo(a) when type2 foo(Type& parameter) in C++
ROSE_DLL_API void collectUseByAddressVariableRefs (const SgStatement* s, std::set<SgVarRefExp* >& varSetB);
#ifndef ROSE_USE_INTERNAL_FRONTEND_DEVELOPMENT
//!Call liveness analysis on an entire project
ROSE_DLL_API LivenessAnalysis * call_liveness_analysis(SgProject* project, bool debug=false);
//!get liveIn and liveOut variables for a for loop from liveness analysis result liv.
ROSE_DLL_API void getLiveVariables(LivenessAnalysis * liv, SgForStatement* loop, std::set<SgInitializedName*>& liveIns, std::set<SgInitializedName*> & liveOuts);
#endif
//!Recognize and collect reduction variables and operations within a C/C++ loop, following OpenMP 3.0 specification for allowed reduction variable types and operation types.
ROSE_DLL_API void ReductionRecognition(SgForStatement* loop, std::set< std::pair <SgInitializedName*, OmpSupport::omp_construct_enum> > & results);
//! Constant folding an AST subtree rooted at 'r' (replacing its children with their constant values, if applicable). Please be advised that constant folding on floating point computation may decrease the accuracy of floating point computations!
/*! It is a wrapper function for ConstantFolding::constantFoldingOptimization(). Note that only r's children are replaced with their corresponding constant values, not the input SgNode r itself. You have to call this upon an expression's parent node if you want to fold the expression. */
ROSE_DLL_API void constantFolding(SgNode* r);
//!Instrument(Add a statement, often a function call) into a function right before the return points, handle multiple return statements (with duplicated statement s) and return expressions with side effects. Return the number of statements inserted.
/*! Useful when adding a runtime library call to terminate the runtime system right before the end of a program, especially for OpenMP and UPC runtime systems. Return with complex expressions with side effects are rewritten using an additional assignment statement.
*/
ROSE_DLL_API int instrumentEndOfFunction(SgFunctionDeclaration * func, SgStatement* s);
//! Remove jumps whose label is immediately after the jump. Used to clean up inlined code fragments.
ROSE_DLL_API void removeJumpsToNextStatement(SgNode*);
//! Remove labels which are not targets of any goto statements
ROSE_DLL_API void removeUnusedLabels(SgNode* top);
//! Remove consecutive labels
ROSE_DLL_API void removeConsecutiveLabels(SgNode* top);
//! Merge a variable assignment statement into a matching variable declaration statement. Callers should make sure the merge is semantically correct (by not introducing compilation errors). This function simply does the merge transformation, without eligibility check.
/*!
* e.g. int i; i=10; becomes int i=10; the original i=10 will be deleted after the merge
* if success, return true, otherwise return false (e.g. variable declaration does not match or already has an initializer)
* The original assignment stmt will be removed by default
* This function is a bit ambiguous about the merge direction, to be phased out.
*/
ROSE_DLL_API bool mergeDeclarationAndAssignment (SgVariableDeclaration* decl, SgExprStatement* assign_stmt, bool removeAssignStmt = true);
//! Merge an assignment into its upstream declaration statement. Callers should make sure the merge is semantically correct.
ROSE_DLL_API bool mergeAssignmentWithDeclaration (SgExprStatement* assign_stmt, SgVariableDeclaration* decl, bool removeAssignStmt = true);
//! Merge a declaration statement into a matching followed variable assignment. Callers should make sure the merge is semantically correct (by not introducing compilation errors). This function simply does the merge transformation, without eligibility check.
/*!
* e.g. int i; i=10; becomes int i=10; the original int i; will be deleted after the merge
*/
ROSE_DLL_API bool mergeDeclarationWithAssignment (SgVariableDeclaration* decl, SgExprStatement* assign_stmt);
//! Split a variable declaration with an rhs assignment into two statements: a declaration and an assignment.
/*! Return the generated assignment statement, if any
* e.g. int i =10; becomes int i; i=10;
* This can be seen as a normalization of declarations
*/
ROSE_DLL_API SgExprStatement* splitVariableDeclaration (SgVariableDeclaration* decl);
//! Split declarations within a scope into declarations and assignment statements, by default only top level declarations are considered. Return the number of declarations split.
ROSE_DLL_API int splitVariableDeclaration (SgScopeStatement* scope, bool topLevelOnly = true);
//! Replace an expression with a temporary variable and an assignment statement
/*!
Add a new temporary variable to contain the value of 'from'
Change reference to 'from' to use this new variable
Assumptions: 'from' is not within the test of a loop or 'if'
not currently traversing 'from' or the statement it is in
*/
ROSE_DLL_API SgAssignInitializer* splitExpression(SgExpression* from, std::string newName = "");
//! Split long expressions into blocks of statements
ROSE_DLL_API void splitExpressionIntoBasicBlock(SgExpression* expr);
//! Remove labeled goto statements
ROSE_DLL_API void removeLabeledGotos(SgNode* top);
//! If the given statement contains any break statements in its body, add a new label below the statement and change the breaks into gotos to that new label.
ROSE_DLL_API void changeBreakStatementsToGotos(SgStatement* loopOrSwitch);
//! Check if the body of a 'for' statement is a SgBasicBlock, create one if not.
ROSE_DLL_API SgBasicBlock* ensureBasicBlockAsBodyOfFor(SgForStatement* fs);
//! Check if the body of a 'upc_forall' statement is a SgBasicBlock, create one if not.
ROSE_DLL_API SgBasicBlock* ensureBasicBlockAsBodyOfUpcForAll(SgUpcForAllStatement* fs);
//! Check if the body of a 'while' statement is a SgBasicBlock, create one if not.
ROSE_DLL_API SgBasicBlock* ensureBasicBlockAsBodyOfWhile(SgWhileStmt* ws);
//! Check if the body of a 'do .. while' statement is a SgBasicBlock, create one if not.
ROSE_DLL_API SgBasicBlock* ensureBasicBlockAsBodyOfDoWhile(SgDoWhileStmt* ws);
//! Check if the body of a 'switch' statement is a SgBasicBlock, create one if not.
ROSE_DLL_API SgBasicBlock* ensureBasicBlockAsBodyOfSwitch(SgSwitchStatement* ws);
//! Check if the body of a 'case option' statement is a SgBasicBlock, create one if not.
SgBasicBlock* ensureBasicBlockAsBodyOfCaseOption(SgCaseOptionStmt* cs);
//! Check if the body of a 'default option' statement is a SgBasicBlock, create one if not.
SgBasicBlock* ensureBasicBlockAsBodyOfDefaultOption(SgDefaultOptionStmt * cs);
//! Check if the true body of a 'if' statement is a SgBasicBlock, create one if not.
ROSE_DLL_API SgBasicBlock* ensureBasicBlockAsTrueBodyOfIf(SgIfStmt* ifs);
//! Check if the false body of a 'if' statement is a SgBasicBlock, create one if not when the flag is true.
ROSE_DLL_API SgBasicBlock* ensureBasicBlockAsFalseBodyOfIf(SgIfStmt* ifs, bool createEmptyBody = true);
//! Check if the body of a 'catch' statement is a SgBasicBlock, create one if not.
ROSE_DLL_API SgBasicBlock* ensureBasicBlockAsBodyOfCatch(SgCatchOptionStmt* cos);
//! Check if the body of a SgOmpBodyStatement is a SgBasicBlock, create one if not
ROSE_DLL_API SgBasicBlock* ensureBasicBlockAsBodyOfOmpBodyStmt(SgOmpBodyStatement* ompbodyStmt);
// DQ (1/18/2015): This is added to support better quality token-based unparsing.
//! Remove unused basic block IR nodes added as part of normalization.
ROSE_DLL_API void cleanupNontransformedBasicBlockNode();
// DQ (1/18/2015): This is added to support better quality token-based unparsing.
//! Record where normalization have been done so that we can preform denormalizations as required for the token-based unparsing to generate minimal diffs.
ROSE_DLL_API void recordNormalizations(SgStatement* s);
//! Check if a statement is a (true or false) body of a container-like parent, such as For, Upc_forall, Do-while,
//! switch, If, Catch, OmpBodyStmt, etc
bool isBodyStatement (SgStatement* s);
//! Fix up ifs, loops, while, switch, Catch, OmpBodyStatement, etc. to have blocks as body components. It also adds an empty else body to if statements that don't have them.
void changeAllBodiesToBlocks(SgNode* top, bool createEmptyBody = true);
// The same as changeAllBodiesToBlocks(SgNode* top). Phased out.
//void changeAllLoopBodiesToBlocks(SgNode* top);
//! Make a single statement body to be a basic block. Its parent is if, while, catch, or upc_forall etc.
SgBasicBlock * makeSingleStatementBodyToBlock(SgStatement* singleStmt);
#if 0
/** If s is the body of a loop, catch, or if statement and is already a basic block,
* s is returned unmodified. Otherwise generate a SgBasicBlock between s and its parent
* (a loop, catch, or if statement, etc). */
SgLocatedNode* ensureBasicBlockAsParent(SgStatement* s);
#endif
//! Get the constant value from a constant integer expression; abort on
//! everything else. Note that signed long longs are converted to unsigned.
unsigned long long getIntegerConstantValue(SgValueExp* expr);
//! Get a statement's dependent declarations which declares the types used in the statement. The returned vector of declaration statements are sorted according to their appearance order in the original AST. Any reference to a class or template class from a namespace will treated as a reference to the enclosing namespace.
std::vector<SgDeclarationStatement*> getDependentDeclarations (SgStatement* stmt );
//! Insert an expression (new_exp )before another expression (anchor_exp) has possible side effects, without changing the original semantics. This is achieved by using a comma operator: (new_exp, anchor_exp). The comma operator is returned.
SgCommaOpExp *insertBeforeUsingCommaOp (SgExpression* new_exp, SgExpression* anchor_exp);
//! Insert an expression (new_exp ) after another expression (anchor_exp) has possible side effects, without changing the original semantics. This is done by using two comma operators: type T1; ... ((T1 = anchor_exp, new_exp),T1) )... , where T1 is a temp variable saving the possible side effect of anchor_exp. The top level comma op exp is returned. The reference to T1 in T1 = anchor_exp is saved in temp_ref.
SgCommaOpExp *insertAfterUsingCommaOp (SgExpression* new_exp, SgExpression* anchor_exp, SgStatement** temp_decl = NULL, SgVarRefExp** temp_ref = NULL);
/// \brief moves the body of a function f to a new function f`;
/// f's body is replaced with code that forwards the call to f`.
/// \return a pair indicating the statement containing the call of f`
/// and an initialized name refering to the temporary variable
/// holding the result of f`. In case f returns void
/// the initialized name is NULL.
/// \param definingDeclaration the defining function declaration of f
/// \param newName the name of function f`
/// \details f's new body becomes { f`(...); } and { int res = f`(...); return res; }
/// for functions returning void and a value, respectively.
/// two function declarations are inserted in f's enclosing scope
/// \code
/// result_type f`(...); <--- (1)
/// result_type f (...) { forward call to f` }
/// result_type f`(...) { original code } <--- (2)
/// \endcode
/// Calls to f are not updated, thus in the transformed code all
/// calls will continue calling f (this is also true for
/// recursive function calls from within the body of f`).
/// After the function has created the wrapper,
/// definingDeclaration becomes the wrapper function
/// The definition of f` is the next entry in the
/// statement list; the forward declaration of f` is the previous
/// entry in the statement list.
/// \pre definingDeclaration must be a defining declaration of a
/// free standing function.
/// typeid(SgFunctionDeclaration) == typeid(definingDeclaration)
/// i.e., this function is NOT implemented for class member functions,
/// template functions, procedures, etc.
std::pair<SgStatement*, SgInitializedName*>
wrapFunction(SgFunctionDeclaration& definingDeclaration, SgName newName);
/// \overload
/// \tparam NameGen functor that generates a new name based on the old name.
/// interface: SgName nameGen(const SgName&)
/// \param nameGen name generator
/// \brief see wrapFunction for details
template <class NameGen>
std::pair<SgStatement*, SgInitializedName*>
wrapFunction(SgFunctionDeclaration& definingDeclaration, NameGen nameGen)
{
return wrapFunction(definingDeclaration, nameGen(definingDeclaration.get_name()));
}
/// \brief convenience function that returns the first initialized name in a
/// list of variable declarations.
SgInitializedName& getFirstVariable(SgVariableDeclaration& vardecl);
//@}
// DQ (6/7/2012): Unclear where this function should go...
bool hasTemplateSyntax( const SgName & name );
#if 0
//------------------------AST dump, stringify-----------------------------
//------------------------------------------------------------------------
std::string buildOperatorString ( SgNode* astNode ); //transformationSupport.h
// do we need these?
std::string dump_node(const SgNode* astNode);
std::string dump_tree(const SgNode* astNode);
// or a friendly version of unparseToString(), as a memeber function
std::string SgNode::toString(bool asSubTree=true); // dump node or subtree
//----------------------------AST comparison------------------------------
//------------------------------------------------------------------------
// How to get generic functions for comparison?
bool isNodeEqual(SgNode* node1, SgNode* node2); //?
bool isTreeEqual(SgNode* tree1, SgNode* tree2);
//! Are two expressions equal (using a deep comparison)?
bool expressionTreeEqual(SgExpression*, SgExpression*);
//! Are corresponding expressions in two lists equal (using a deep comparison)?
bool expressionTreeEqualStar(const SgExpressionPtrList&,
const SgExpressionPtrList&);
//----------------------AST verfication/repair----------------------------
//------------------------------------------------------------------------
// sanity check of AST subtree, any suggestions?
// TODO
verifySgNode(SgNode* node, bool subTree=true);
//src/midend/astDiagnostics/AstConsistencyTests.h
// AstTests::runAllTests(SgProject * )
//src/midend/astUtil/astInterface/AstInterface.h.C
//FixSgProject(SgProject &project)
//FixSgTree(SgNode* r)
//src/frontend/SageIII/astPostProcessing
//AstPostProcessing(SgNode * node)
//--------------------------AST modification------------------------------
//------------------------------------------------------------------------
// any operations changing AST tree, including
// insert, copy, delete(remove), replace
// insert before or after some point, argument list is consistent with LowLevelRewrite
void insertAst(SgNode* targetPosition, SgNode* newNode, bool insertBefore=true);
// previous examples
//void myStatementInsert(SgStatement* target,...)
// void AstInterfaceBase::InsertStmt(AstNodePtr const & orig, AstNodePtr const &n, bool insertbefore, bool extractfromBasicBlock)
// copy
// copy children of one basic block to another basic block
//void appendStatementCopy (const SgBasicBlock* a, SgBasicBlock* b);
void copyStatements (const SgBasicBlock* src, SgBasicBlock* dst);
// delete (remove) a node or a whole subtree
void removeSgNode(SgNode* targetNode); // need this?
void removeSgNodeTree(SgNode* subtree); // need this?
void removeStatement( SgStatement* targetStmt);
//Move = delete + insert
void moveAst (SgNode* src, SgNode* target); // need this?
// similar to
void moveStatements (SgBasicBlock* src, SgBasicBlock* target);
// replace= delete old + insert new (via building or copying)
// DQ (1/25/2010): This does not appear to exist as a definition anywhere in ROSE.
// void replaceAst(SgNode* oldNode, SgNode* newNode);
//void replaceChild(SgNode* parent, SgNode* from, SgNode* to);
//bool AstInterface::ReplaceAst( const AstNodePtr& orig, const AstNodePtr& n)
//--------------------------AST transformations---------------------------
//------------------------------------------------------------------------
// Advanced AST modifications through basic AST modifications
// Might not be included in AST utitlity list, but listed here for the record.
// extract statements/content from a scope
void flattenBlocks(SgNode* n);
//src/midend/astInlining/inlinerSupport.h
void renameVariables(SgNode* n);
void renameLabels(SgNode* n, SgFunctionDefinition* enclosingFunctionDefinition);
void simpleCopyAndConstantPropagation(SgNode* top);
void changeAllMembersToPublic(SgNode* n);
void removeVariableDeclaration(SgInitializedName* initname);
//! Convert something like "int a = foo();" into "int a; a = foo();"
SgAssignOp* convertInitializerIntoAssignment(SgAssignInitializer* init);
//! Rewrites a while or for loop so that the official test is changed to
//! "true" and what had previously been the test is now an if-break
//! combination (with an inverted condition) at the beginning of the loop
//! body
void pushTestIntoBody(LoopStatement* loopStmt);
//programTransformation/finiteDifferencing/finiteDifferencing.h
//! Move variables declared in a for statement to just outside that statement.
void moveForDeclaredVariables(SgNode* root);
//------------------------ Is/Has functions ------------------------------
//------------------------------------------------------------------------
// misc. boolean functions
// some of them could moved to SgXXX class as a member function
bool isOverloaded (SgFunctionDeclaration * functionDeclaration);
bool isSwitchCond (const SgStatement* s);
bool isIfCond (const SgStatement* s);
bool isWhileCond (const SgStatement* s);
bool isStdNamespace (const SgScopeStatement* scope);
bool isTemplateInst (const SgDeclarationStatement* decl);
bool isCtor (const SgFunctionDeclaration* func);
bool isDtor (const SgFunctionDeclaration* func);
// src/midend/astInlining/typeTraits.h
bool hasTrivialDestructor(SgType* t);
ROSE_DLL_API bool isNonconstReference(SgType* t);
ROSE_DLL_API bool isReferenceType(SgType* t);
// generic ones, or move to the SgXXX class as a member function
bool isConst(SgNode* node); // const type, variable, function, etc.
// .... and more
bool isConstType (const SgType* type);
bool isConstFunction (const SgFunctionDeclaration* decl);
bool isMemberVariable(const SgInitializedName & var);
//bool isMemberVariable(const SgNode& in);
bool isPrototypeInScope (SgScopeStatement * scope,
SgFunctionDeclaration * functionDeclaration,
SgDeclarationStatement * startingAtDeclaration);
bool MayRedefined(SgExpression* expr, SgNode* root);
// bool isPotentiallyModified(SgExpression* expr, SgNode* root); // inlinderSupport.h
bool hasAddressTaken(SgExpression* expr, SgNode* root);
//src/midend/astInlining/inlinerSupport.C
// can also classified as topdown search
bool containsVariableReference(SgNode* root, SgInitializedName* var);
bool isDeclarationOf(SgVariableDeclaration* decl, SgInitializedName* var);
bool isPotentiallyModifiedDuringLifeOf(SgBasicBlock* sc,
SgInitializedName* toCheck,
SgInitializedName* lifetime)
//src/midend/programTransformation/partialRedundancyElimination/pre.h
bool anyOfListPotentiallyModifiedIn(const std::vector<SgVariableSymbol*>& syms, SgNode* n);
//------------------------ loop handling ---------------------------------
//------------------------------------------------------------------------
//get and set loop control expressions
// 0: init expr, 1: condition expr, 2: stride expr
SgExpression* getForLoopTripleValues(int valuetype,SgForStatement* forstmt );
int setForLoopTripleValues(int valuetype,SgForStatement* forstmt, SgExpression* exp);
bool isLoopIndexVarRef(SgForStatement* forstmt, SgVarRefExp *varref);
SgInitializedName * getLoopIndexVar(SgForStatement* forstmt);
//------------------------expressions-------------------------------------
//------------------------------------------------------------------------
//src/midend/programTransformation/partialRedundancyElimination/pre.h
int countComputationsOfExpressionIn(SgExpression* expr, SgNode* root);
//src/midend/astInlining/replaceExpressionWithStatement.h
void replaceAssignmentStmtWithStatement(SgExprStatement* from, StatementGenerator* to);
void replaceSubexpressionWithStatement(SgExpression* from,
StatementGenerator* to);
SgExpression* getRootOfExpression(SgExpression* n);
//--------------------------preprocessing info. -------------------------
//------------------------------------------------------------------------
//! Removes all preprocessing information at a given position.
void cutPreprocInfo (SgBasicBlock* b,
PreprocessingInfo::RelativePositionType pos,
AttachedPreprocessingInfoType& save_buf);
//! Pastes preprocessing information at the front of a statement.
void pastePreprocInfoFront (AttachedPreprocessingInfoType& save_buf,
SgStatement* s);
//! Pastes preprocessing information at the back of a statement.
void pastePreprocInfoBack (AttachedPreprocessingInfoType& save_buf,
SgStatement* s);
/*!
* \brief Moves 'before' preprocessing information.
* Moves all preprocessing information attached 'before' the source
* statement to the front of the destination statement.
*/
// a generic one for all
/// void movePreprocessingInfo(src, dest, RelativePositionType);
void moveBeforePreprocInfo (SgStatement* src, SgStatement* dest);
void moveInsidePreprocInfo (SgBasicBlock* src, SgBasicBlock* dest);
void moveAfterPreprocInfo (SgStatement* src, SgStatement* dest);
//--------------------------------operator--------------------------------
//------------------------------------------------------------------------
from transformationSupport.h, not sure if they should be included here
/* return enum code for SAGE operators */
operatorCodeType classifyOverloadedOperator(); // transformationSupport.h
/*! \brief generates a source code string from operator name.
This function returns a string representing the elementwise operator (for primative types)
that would be match that associated with the overloaded operator for a user-defined
abstractions (e.g. identifyOperator("operator+()") returns "+").
*/
std::string stringifyOperator (std::string name);
//--------------------------------macro ----------------------------------
//------------------------------------------------------------------------
std::string buildMacro ( std::string s ); //transformationSupport.h
//--------------------------------access functions---------------------------
//----------------------------------get/set sth.-----------------------------
// several categories:
* get/set a direct child/grandchild node or fields
* get/set a property flag value
* get a descendent child node using preorder searching
* get an ancestor node using bottomup/reverse searching
// SgName or string?
std::string getFunctionName (SgFunctionCallExp* functionCallExp);
std::string getFunctionTypeName ( SgFunctionCallExp* functionCallExpression );
// do we need them anymore? or existing member functions are enought?
// a generic one:
std::string get_name (const SgNode* node);
std::string get_name (const SgDeclarationStatement * declaration);
// get/set some property: should moved to SgXXX as an inherent memeber function?
// access modifier
void setExtern (SgFunctionDeclartion*)
void clearExtern()
// similarly for other declarations and other properties
void setExtern (SgVariableDeclaration*)
void setPublic()
void setPrivate()
#endif
// DQ (1/23/2013): Added support for generated a set of source sequence entries.
std::set<unsigned int> collectSourceSequenceNumbers( SgNode* astNode );
//--------------------------------Type Traits (C++)---------------------------
bool HasNoThrowAssign(const SgType * const inputType);
bool HasNoThrowCopy(const SgType * const inputType);
bool HasNoThrowConstructor(const SgType * const inputType);
bool HasTrivialAssign(const SgType * const inputType);
bool HasTrivialCopy(const SgType * const inputType);
bool HasTrivialConstructor(const SgType * const inputType);
bool HasTrivialDestructor(const SgType * const inputType);
bool HasVirtualDestructor(const SgType * const inputType);
bool IsBaseOf(const SgType * const inputBaseType, const SgType * const inputDerivedType);
bool IsAbstract(const SgType * const inputType);
bool IsClass(const SgType * const inputType);
bool IsEmpty(const SgType * const inputType);
bool IsEnum(const SgType * const inputType);
bool IsPod(const SgType * const inputType);
bool IsPolymorphic(const SgType * const inputType);
bool IsStandardLayout(const SgType * const inputType);
bool IsLiteralType(const SgType * const inputType);
bool IsTrivial(const SgType * const inputType);
bool IsUnion(const SgType * const inputType);
SgType * UnderlyingType(SgType *type);
// DQ (3/2/2014): Added a new interface function (used in the snippet insertion support).
// void supportForInitializedNameLists ( SgScopeStatement* scope, SgInitializedNamePtrList & variableList );
// DQ (3/4/2014): Added support for testing two trees for equivalents using the AST iterators.
bool isStructurallyEquivalentAST( SgNode* tree1, SgNode* tree2 );
// JP (10/14/24): Moved code to evaluate a const integer expression (like in array size definitions) to SageInterface
/*! The datastructure is used as the return type for SageInterface::evaluateConstIntegerExpression(). One needs to always check whether hasValue_ is true before accessing value_ */
struct const_int_expr_t {
size_t value_;
bool hasValue_;
};
/*! \brief The function tries to evaluate const integer expressions (such as are used in array dimension sizes). It follows variable symbols, and requires constness. */
struct const_int_expr_t evaluateConstIntegerExpression(SgExpression *expr);
// JP (9/17/14): Added function to test whether two SgType* are equivalent or not
bool checkTypesAreEqual(SgType *typeA, SgType *typeB);
//--------------------------------Java interface functions ---------------------
#ifdef ROSE_BUILD_JAVA_LANGUAGE_SUPPORT
ROSE_DLL_API std::string getTempDirectory(SgProject *project);
ROSE_DLL_API void destroyTempDirectory(std::string);
ROSE_DLL_API SgFile *processFile(SgProject *, std::string, bool unparse = false);
ROSE_DLL_API std::string preprocessPackage(SgProject *, std::string);
ROSE_DLL_API std::string preprocessImport(SgProject *, std::string);
ROSE_DLL_API SgFile* preprocessCompilationUnit(SgProject *, std::string, std::string, bool unparse = true);
ROSE_DLL_API SgClassDefinition *findJavaPackage(SgScopeStatement *, std::string);
ROSE_DLL_API SgClassDefinition *findOrInsertJavaPackage(SgProject *, std::string, bool create_directory = false);
ROSE_DLL_API SgClassDeclaration *findOrImportJavaClass(SgProject *, SgClassDefinition *package_definition, std::string);
ROSE_DLL_API SgClassDeclaration *findOrImportJavaClass(SgProject *, std::string, std::string);
ROSE_DLL_API SgClassDeclaration *findOrImportJavaClass(SgProject *, SgClassType *);
ROSE_DLL_API SgMemberFunctionDeclaration *findJavaMain(SgClassDefinition *);
ROSE_DLL_API SgMemberFunctionDeclaration *findJavaMain(SgClassType *);
#endif // ROSE_BUILD_JAVA_LANGUAGE_SUPPORT
// DQ (8/31/2016): Making this a template function so that we can have it work with user defined filters.
//! This function detects template instantiations that are relevant when filters are used.
/*!
EDG normalizes some in-class template functions and member functions to be redefined outside of a class. this causes the associated template instantiations
to be declared outside of the class, and to be marked as compiler generated (since the compiler generated form outside of the class declaration).
ROSE captures the function definitions, but in the new location (defined outside of the class declaration). This can confuse some simple tests
for template instantiations that are a part of definitions in a file, thus we have this function to detect this specific normalization.
*/
template < class T >
bool isTemplateInstantiationFromTemplateDeclarationSatisfyingFilter (SgFunctionDeclaration* function, T* filter )
{
// DQ (9/1/2016): This function is called in the Call graph generation to avoid filtering out EDG normalized
// function template instnatiations (which come from normalized template functions and member functions).
// Note that because of the EDG normailzation the membr function is moved outside of the class, and
// thus marked as compiler generated. However the template instantiations are always marked as compiler
// generated (if not specializations) and so we want to include a template instantiation that is marked
// as compiler generated, but is from a template declaration that satisfyied a specific user defined filter.
// The complexity of this detection is isolated here, but knowing that it must be called is more complex.
// This function is call in the CG.C file of tests/nonsmoke/functional/roseTests/programAnalysisTests/testCallGraphAnalysis.
bool retval = false;
#define DEBUG_TEMPLATE_NORMALIZATION_DETECTION 0
#if DEBUG_TEMPLATE_NORMALIZATION_DETECTION
printf ("In isNormalizedTemplateInstantiation(): function = %p = %s = %s \n",function,function->class_name().c_str(),function->get_name().str());
#endif
// Test for this to be a template instantation (in which case it was marked as
// compiler generated but we may want to allow it to be used in the call graph,
// if it's template was a part was defined in the current directory).
SgTemplateInstantiationFunctionDecl* templateInstantiationFunction = isSgTemplateInstantiationFunctionDecl(function);
SgTemplateInstantiationMemberFunctionDecl* templateInstantiationMemberFunction = isSgTemplateInstantiationMemberFunctionDecl(function);
if (templateInstantiationFunction != NULL)
{
// When the defining function has been normalized by EDG, only the non-defining declaration will have a source position.
templateInstantiationFunction = isSgTemplateInstantiationFunctionDecl(templateInstantiationFunction->get_firstNondefiningDeclaration());
SgTemplateFunctionDeclaration* templateFunctionDeclaration = templateInstantiationFunction->get_templateDeclaration();
if (templateFunctionDeclaration != NULL)
{
retval = filter->operator()(templateFunctionDeclaration);
}
else
{
// Assume false.
}
#if DEBUG_TEMPLATE_NORMALIZATION_DETECTION
printf (" --- case of templateInstantiationFunction: retval = %s \n",retval ? "true" : "false");
#endif
}
else
{
if (templateInstantiationMemberFunction != NULL)
{
// When the defining function has been normalized by EDG, only the non-defining declaration will have a source position.
templateInstantiationMemberFunction = isSgTemplateInstantiationMemberFunctionDecl(templateInstantiationMemberFunction->get_firstNondefiningDeclaration());
SgTemplateMemberFunctionDeclaration* templateMemberFunctionDeclaration = templateInstantiationMemberFunction->get_templateDeclaration();
if (templateMemberFunctionDeclaration != NULL)
{
retval = filter->operator()(templateMemberFunctionDeclaration);
}
else
{
// Assume false.
}
#if DEBUG_TEMPLATE_NORMALIZATION_DETECTION
printf (" --- case of templateInstantiationMemberFunction: retval = %s \n",retval ? "true" : "false");
#endif
}
}
return retval;
}
void detectCycleInType(SgType * type, const std::string & from);
}// end of namespace
#endif
|
SpatialAveragePooling.c | #ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "generic/SpatialAveragePooling.c"
#else
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->nDimension;
int dimf = 0;
int dimh = 1;
int dimw = 2;
if (ndim == 4) {
dimf++;
dimh++;
dimw++;
}
THNN_ARGCHECK(ndim == 3 || ndim == 4, 2, input,
"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 outputHeight, outputWidth;
int64_t nOutputPlane = nInputPlane;
if(ceil_mode)
{
outputHeight = (int64_t)(ceil((float)(inputHeight - kH + 2*padH) / dH)) + 1;
outputWidth = (int64_t)(ceil((float)(inputWidth - kW + 2*padW) / dW)) + 1;
}
else
{
outputHeight = (int64_t)(floor((float)(inputHeight - kH + 2*padH) / dH)) + 1;
outputWidth = (int64_t)(floor((float)(inputWidth - kW + 2*padW) / dW)) + 1;
}
if (padW || padH)
{
// ensure that the last pooling starts inside the image
// needed to avoid problems in ceil mode
if ((outputHeight - 1)*dH >= inputHeight + padH)
--outputHeight;
if ((outputWidth - 1)*dW >= inputWidth + padW)
--outputWidth;
}
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)
{
real *output_data;
real *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->nDimension == 4) {
nbatch = input->size[0];
dimw++;
dimh++;
dimc++;
}
inputWidth = input->size[dimw];
inputHeight = input->size[dimh];
nInputPlane = input->size[dimc];
if(ceil_mode)
{
outputWidth = (int64_t)(ceil((float)(inputWidth - kW + 2*padW) / dW)) + 1;
outputHeight = (int64_t)(ceil((float)(inputHeight - kH + 2*padH) / dH)) + 1;
}
else
{
outputWidth = (int64_t)(floor((float)(inputWidth - kW + 2*padW) / dW)) + 1;
outputHeight = (int64_t)(floor((float)(inputHeight - kH + 2*padH) / dH)) + 1;
}
if (padW || padH)
{
// ensure that the last pooling starts inside the image
// needed to avoid problems in ceil mode
if ((outputHeight - 1)*dH >= inputHeight + padH)
--outputHeight;
if ((outputWidth - 1)*dW >= inputWidth + padW)
--outputWidth;
}
if (input->nDimension == 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 = THTensor_(data)(input);
output_data = THTensor_(data)(output);
#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... */
real *ptr_output = output_data + p*nInputPlane*outputWidth*outputHeight + k*outputWidth*outputHeight;
real *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 = fminf(hstart + kH, inputHeight + padH);
int64_t wend = fminf(wstart + kW, inputWidth + padW);
int pool_size = (hend - hstart) * (wend - wstart);
hstart = fmaxf(hstart, 0);
wstart = fmaxf(wstart, 0);
hend = fminf(hend, inputHeight);
wend = fminf(wend, inputWidth);
real 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;
}
}
}
}
THTensor_(free)(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)
real *gradOutput_data;
real *gradInput_data;
int64_t k;
THNN_(SpatialAveragePooling_shapeCheck)
(input, gradOutput, kH, kW, dH, dW, padH, padW, ceil_mode);
if (input->nDimension == 4) {
nbatch = input->size[0];
dimw++;
dimh++;
dimc++;
ndim = 4;
}
inputWidth = input->size[dimw];
inputHeight = input->size[dimh];
nInputPlane = input->size[dimc];
if(ceil_mode)
{
outputWidth = (int64_t)(ceil((float)(inputWidth - kW + 2*padW) / dW)) + 1;
outputHeight = (int64_t)(ceil((float)(inputHeight - kH + 2*padH) / dH)) + 1;
}
else
{
outputWidth = (int64_t)(floor((float)(inputWidth - kW + 2*padW) / dW)) + 1;
outputHeight = (int64_t)(floor((float)(inputHeight - kH + 2*padH) / dH)) + 1;
}
if (padW || padH)
{
// ensure that the last pooling starts inside the image
// needed to avoid problems in ceil mode
if ((outputHeight - 1)*dH >= inputHeight + padH)
--outputHeight;
if ((outputWidth - 1)*dW >= inputWidth + padW)
--outputWidth;
}
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 = THTensor_(data)(gradInput);
gradOutput_data = THTensor_(data)(gradOutput);
#pragma omp parallel for private(k)
for(k = 0; k < nInputPlane; k++)
{
int64_t p;
for(p = 0; p < nbatch; p++)
{
real *ptr_gradOutput = gradOutput_data + p*nInputPlane*outputHeight*outputWidth + k*outputWidth*outputHeight;
int64_t xx, yy;
real* ptr_gi = gradInput_data + p*nInputPlane*inputWidth*inputHeight + k*inputWidth*inputHeight;
real *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 = fminf(hstart + kH, inputHeight + padH);
int64_t wend = fminf(wstart + kW, inputWidth + padW);
int pool_size = (hend - hstart) * (wend - wstart);
hstart = fmaxf(hstart, 0);
wstart = fmaxf(wstart, 0);
hend = fminf(hend, inputHeight);
wend = fminf(wend, inputWidth);
real 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;
}
}
}
}
}
THTensor_(free)(gradOutput);
}
#endif
|
DRB095-doall2-taskloop-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.
*/
/*
Two-dimensional array computation:
Only one loop is associated with omp taskloop.
The inner loop's loop iteration variable will be shared if it is shared in the enclosing context.
Data race pairs (we allow multiple ones to preserve the pattern):
Write_set = {j@69:14, j@69:30}
Read_set = {j@69:21, j@69:30, j@70:16}
Any pair from Write_set vs. Write_set and Write_set vs. Read_set is a data race pair.
*/
#include <stdio.h>
#include <omp.h>
int a[100][100];
int main()
{
int i;
int j;
#pragma omp parallel for private (i,j)
for (i = 0; i <= 99; i += 1) {
#pragma omp parallel for private (j)
for (j = 0; j <= 99; j += 1) {
a[i][j] = i + j;
}
}
#pragma omp parallel for private (i,j)
for (i = 0; i <= 99; i += 1) {
#pragma omp parallel for private (j)
for (j = 0; j <= 99; j += 1) {
a[i][j] += 1;
}
}
printf("a[50][50]=%d\n",a[50][50]);
return 0;
}
|
driver1.c | #include "driver.h"
#include "kernel1.h"
double getTime()
{
double time;
#ifdef ERT_OPENMP
time = omp_get_wtime();
#elif ERT_MPI
time = MPI_Wtime();
#else
struct timeval tm;
gettimeofday(&tm, NULL);
time = tm.tv_sec + (tm.tv_usec / 1000000.0);
#endif
return time;
}
int main(int argc, char *argv[]) {
#if 0
if (argc != 3) {
fprintf(stderr, "Usage: %s size unit(GB/MB/KB) \n", argv[0]);
return -1;
}
#endif
int rank = 0;
int nprocs = 1;
int nthreads = 1;
int id = 0;
int provided = -1;
int requested;
#ifdef ERT_MPI
#ifdef ERT_OPENMP
requested = MPI_THREAD_FUNNELED;
MPI_Init_thread(&argc, &argv, requested, &provided);
#else
MPI_Init(&argc, &argv);
#endif // ERT_OPENMP
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
/* printf("The MPI binding provided thread support of: %d\n", provided); */
#endif // ERT_MPI
#ifdef ERT_BGPM
// Use SW mode
Bgpm_Init(BGPM_MODE_SWDISTRIB);
// Generate a Puint event set for counting CPU related events
int evtSet = Bgpm_CreateEventSet();
unsigned evtList[] = { PEVT_IU_IS1_STALL_CYC,
PEVT_IU_IS2_STALL_CYC,
PEVT_CYCLES, // x1 cycles
PEVT_INST_ALL, // All instruction Completions
};
Bgpm_AddEventList(evtSet, evtList, sizeof(evtList)/sizeof(unsigned));
// Apply the event set to HW
Bgpm_Apply(evtSet);
#endif
uint64_t TSIZE = ERT_MEMORY_MAX;
uint64_t PSIZE = TSIZE / nprocs;
#ifdef ERT_INTEL
double * __restrict__ buf = (double *)_mm_malloc(PSIZE, ERT_ALIGN);
#elif ERT_BGPM
double * __restrict__ buf = (double *)bgq_malloc(PSIZE, ERT_ALIGN);
#else
double * __restrict__ buf = malloc(PSIZE);
#endif
if (buf == NULL) {
fprintf(stderr, "Out Of Memory!\n");
return -1;
}
/* printf("array size: %10" PRIu64 " bytes/proc\n", PSIZE); */
#ifdef ERT_OPENMP
#pragma omp parallel private(id)
#endif
{
uint64_t numTrials = 1 << 27;
#ifdef ERT_OPENMP
id = omp_get_thread_num();
nthreads = omp_get_num_threads();
#else
id = 0;
nthreads = 1;
#endif
uint64_t nsize = PSIZE / nthreads;
nsize = nsize & (~(ERT_ALIGN-1));
nsize = nsize / sizeof(double);
uint64_t nid = nsize * id ;
// initialize small chunck of buffer within each thread
initialize(nsize, &buf[nid], 1.0);
double startTime, endTime;
uint64_t n,nNew;
uint64_t t;
int bytes_per_elem;
int mem_accesses_per_elem;
n = ERT_WORKING_SET_MIN;
while (n < nsize) { // working set - nsize
uint64_t ntrials = nsize / n;
if (ntrials < 1)
ntrials = 1;
for (t = ERT_TRIALS_MIN; t <= ntrials; t = t * 2) { // working set - ntrials
#ifdef ERT_MPI
#ifdef ERT_OPENMP
#pragma omp master
#endif
{
MPI_Barrier(MPI_COMM_WORLD);
}
#endif // ERT_MPI
#ifdef ERT_OPENMP
#pragma omp barrier
#endif
if ((id == 0) && (rank==0)) {
#ifdef ERT_BGPM
Bgpm_Start(evtSet);
#endif
startTime = getTime();
}
#ifdef ERT_QPX // QPX intrinsics for IBM BGQ
vecKernel(n, t, &buf[nid]);
#elif ERT_SSE // SSE intrinsics for Hopper(AMD)
sseKernel(n, t, &buf[nid]);
#elif ERT_AVX // AVX intrinsics for Edison(intel xeon)
avxKernel(n, t, &buf[nid]);
#elif ERT_KNC // KNC intrinsics for Babbage(intel mic)
kncKernel(n, t, &buf[nid]);
#else // C-code
kernel(n, t, &buf[nid], &bytes_per_elem, &mem_accesses_per_elem);
#endif
#ifdef ERT_OPENMP
#pragma omp barrier
#endif
#ifdef ERT_MPI
#ifdef ERT_OPENMP
#pragma omp master
#endif
{
MPI_Barrier(MPI_COMM_WORLD);
}
#endif // ERT_MPI
if ((id == 0) && (rank == 0)) {
endTime = getTime();
#ifdef ERT_BGPM
Bgpm_Stop(evtSet);
bgpm_print(evtSet);
#endif
double seconds = (double)(endTime - startTime);
uint64_t working_set_size = n * nthreads * nprocs;
uint64_t total_bytes = t * working_set_size * bytes_per_elem * mem_accesses_per_elem;
uint64_t total_flops = t * working_set_size * ERT_FLOP;
// nsize; trials; microseconds; bytes; single thread bandwidth; total bandwidth
printf("%12" PRIu64 " %12" PRIu64 " %15.3lf %12" PRIu64 " %12" PRIu64 "\n",
working_set_size * bytes_per_elem,
t,
seconds * 1000000,
total_bytes,
total_flops);
} // print
} // working set - ntrials
nNew = 1.1 * n;
if (nNew == n) {
nNew = n+1;
}
n = nNew;
} // working set - nsize
} // parallel region
#ifdef ERT_MPI
MPI_Barrier(MPI_COMM_WORLD);
#endif
#ifdef ERT_BGPM
Bgpm_Disable();
#endif
#ifdef ERT_MPI
MPI_Finalize();
#endif
printf("\n");
printf("META_DATA\n");
printf("MPI_PROCS %d\n", nprocs);
printf("OPENMP_THREADS %d\n", nthreads);
printf("FLOPS %d\n", ERT_FLOP);
return 0;
}
|
pagerank_openmp.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include <string.h>
#include <memory.h>
#include <sys/time.h>
#ifndef REAL
#define REAL float
#endif
#define ALPHA 0.85
#define EPSILON 0.01
#define ARRAY_LENGTH 600000000
#define MAX_TIMES 1000
#define MICRO_IN_SEC 1000000.00
double begin_time, end_time, serial_time=0, parallel_time=0;
double microtime(){
int tv_sec,tv_usec;
double time;
struct timeval tv;
struct timezone tz;
gettimeofday(&tv,&tz);
return tv.tv_sec+tv.tv_usec/MICRO_IN_SEC;
}
typedef struct{
int nodei;
int nodej;
REAL p;
} EDGE;
int caculate(char *ifn);
int check_result(REAL *r, REAL *rtmp, int noden);
int main(int argc,char * argv[])
{
char *ifn=NULL;
if(argc<2)
{
printf("wrong command format! usage:parallel_pagerank INPUTFILENAME\n");
return 0;
}
else
{
ifn=argv[1];
caculate(ifn);
return 0;
}
}
int caculate(char *ifn) {
begin_time = microtime();
FILE *ifp=NULL,*ofp=NULL;
EDGE edge,*array_edge=NULL;
char *ofn="CaculateResult.txt";
int noden,edgen,foffset,linen,i,j,begin,topi,counter,index_i,edge_i;
REAL *r=NULL,*rtmp=NULL,*tmp,*array=NULL;
if((ifp=fopen(ifn,"r"))==NULL)
{
printf("%s file open error!\n",ifn);
exit(0);
}
else
{
printf("%s file opened success!\n",ifn);
}
if((ofp=fopen(ofn,"w"))==NULL)
{
printf("%s file open error!\n",ofn);
fclose(ifp);
exit(0);
}
else
{
printf("%s file opened success!\n",ofn);
}
fscanf(ifp,"%d%d",&noden,&edgen);
foffset=ftell(ifp);
printf("Allocing Memory!\n");
if((array_edge=(EDGE *)malloc(edgen*sizeof(EDGE)))==NULL) {
printf("Memory alloc ERROR !\n");
fclose(ifp);
fclose(ofp);
exit(0);
}
linen=ARRAY_LENGTH/noden;
if(linen<=0) {
printf("ArrayLength is too short for this caculate!\nPlase change the value of ARRAYLENGTH\n");
free(array_edge);
fclose(ifp);
fclose(ofp);
exit(0);
}
if((array=(REAL *)malloc(linen*noden*sizeof(REAL)))==NULL) {
printf("Memory alloc ERROR !\n");
fclose(ifp);
fclose(ofp);
free(array_edge);
exit(0);
}
if((r=(REAL *)malloc(noden*sizeof(REAL)))==NULL) {
printf("Memory alloc ERROR !\n");
fclose(ifp);
fclose(ofp);
free(array);
exit(0);
}
if((rtmp=(REAL *)malloc(noden*sizeof(REAL)))==NULL) {
fclose(ifp);
fclose(ofp);
free(array);
free(r);
exit(0);
}
for(i=0;i<noden;i++) {
*(r+i)=1.0;
}
printf("Memory Alloc done!\n");
printf("Caculating pagerank!\n");
printf("Loding Data!\n");
for(i=0;i<edgen;i++) {
fscanf(ifp,"%d%d%f",&((array_edge+i)->nodei),&((array_edge+i)->nodej),&((array_edge+i)->p));
}
printf("Data loaded!\n");
end_time = microtime();
printf("read file and alloc memory time consuming:%fs\n",end_time-begin_time);
begin_time = end_time;
printf("Begin Caculate!\n");
counter=MAX_TIMES;
REAL pr_tmp=0.0;
REAL matrix_probablity = 0;
begin_time = microtime();
if(noden<=linen) {
/*
end_time = microtime();
printf("read file and alloc memory time consuming:%fs\n",end_time-begin_time);
begin_time = end_time;
*/
#pragma omp parallel for
for(i=0;i<noden*noden;i++) {
array[i]=0;
}
/*
end_time = microtime();
parallel_time += end_time-begin_time;
begin_time = end_time;
*/
for(i=0;i<edgen;i++) {
*(array+(((array_edge+i)->nodei)*noden+(array_edge+i)->nodej))=(array_edge+i)->p;
}
/*
end_time = microtime();
serial_time += end_time-begin_time;
begin_time= end_time;
*/
do {
tmp=rtmp;
rtmp=r;
r=tmp;
//caculate PageRank
//#pragma omp parallel for
for(i=0;i<noden;i++) {
pr_tmp = 0.0;
/*
end_time = microtime();
serial_time += end_time - begin_time;
begin_time = end_time;
*/
#pragma omp parallel for reduction(+:pr_tmp)
for(j=0;j<noden;j++) {
matrix_probablity = array[i*noden+j];
pr_tmp += ( ( ALPHA * matrix_probablity ) + ( 1.0 - ALPHA ) / ( REAL ) noden ) * rtmp[j];
}
/*
end_time = microtime();
parallel_time += end_time - begin_time;
begin_time = end_time;
*/
*(r+i) = pr_tmp;
}
/*
end_time = microtime();
serial_time += end_time-begin_time;
begin_time = end_time;
*/
printf("parallel part time consuming:%fs\n",microtime()-begin_time);
counter--;
printf("counter = %d ", counter);
printf(" first pagerank = %f, noden= %d linen= %d \n",r[0], noden, linen);
} while((!check_result(r,rtmp,noden)) && counter);
} else {
int block_counter=0;
int ii=0;
do {
tmp=rtmp;
rtmp=r;
r=tmp;
begin=0;
edge_i=0;
block_counter=0;
/*
end_time = microtime();
serial_time += end_time-begin_time;
begin_time = end_time;
*/
for(ii=0;ii<noden/linen;ii++) {
/*
end_time = microtime();
serial_time += end_time-begin_time;
begin_time = end_time;
*/
#pragma omp parallel for
for(i=0;i<linen*noden;i++) {
array[i]=0;
}
/*
end_time = microtime();
parallel_time += end_time - begin_time;
begin_time = end_time;
*/
do{
if((array_edge+edge_i)->nodei>=begin+linen) {
break;
} else {
*(array+(((array_edge+edge_i)->nodei%linen)*noden+(array_edge+edge_i)->nodej))=(array_edge+edge_i)->p;
edge_i++;
}
} while(edge_i<edgen);
//#pragma omp parallel for
for(index_i=begin;index_i<begin+linen;index_i++) {
pr_tmp = 0.0;
#pragma omp parallel for reduction(+:pr_tmp)
for(j=0;j<noden;j++) {
matrix_probablity = array[(index_i%linen)*noden+j];
pr_tmp += ( ( ALPHA * matrix_probablity ) + ( 1.0 - ALPHA ) / ( REAL ) noden ) * rtmp[j];
}
*(r+index_i) = pr_tmp;
// r[index_i] = __sec_reduce_add ( (array+(index_i%linen) *noden)[0:noden] * rtmp[0:noden]);
}
begin+=linen;
block_counter++;
if(block_counter%1000 == 0) printf("block_counter:%d\n",block_counter);
if(block_counter == 6000 || block_counter == (noden/linen - 1)){
/*
end_time = microtime();
serial_time += end_time - begin_time;
begin_time = end_time;
*/
printf("block_counter:%d\n parallel part time consuming:%fs\n",block_counter,microtime()-begin_time);
exit(0);
}
}
if(noden%linen != 0) {
/*
end_time = microtime();
serial_time += end_time - begin_time;
begin_time = end_time;
*/
#pragma omp parallel for
for(i=0;i<(noden%linen)*noden;i++) {
array[i]=0;
}
/*
end_time = microtime();
parallel_time += end_time - begin_time;
begin_time = end_time;
*/
do{
if((array_edge+edge_i)->nodei>=begin+linen) {
break;
} else {
*(array+(((array_edge+edge_i)->nodei%linen)*noden+(array_edge+edge_i)->nodej))=(array_edge+edge_i)->p;
edge_i++;
}
} while(edge_i<edgen);
//#pragma omp parallel for
for(index_i=begin;index_i<noden;index_i++) {
pr_tmp = 0.0;
/*
end_time = microtime();
serial_time += end_time - begin_time;
begin_time = end_time;
*/
#pragma omp parallel for reduction(+:pr_tmp)
for(j=0;j<noden;j++) {
matrix_probablity = array[(index_i%linen)*noden+j];
pr_tmp += ( ( ALPHA * matrix_probablity ) + ( 1.0 - ALPHA ) / ( REAL ) noden ) * rtmp[j];
}
/*
end_time = microtime();
parallel_time += end_time - begin_time;
begin_time = end_time;
*/
*(r+index_i) = pr_tmp;
}
block_counter++;
if(block_counter%100 == 0) printf("block_counter=%d begin=%d\n",block_counter,begin);
}
counter--;
printf("counter = %d ", counter);
printf(" first pagerank = %f, noden= %d linen= %d \n",r[0], noden, linen);
} while((!check_result(r,rtmp,noden)) && counter);
}
printf("caculate done !\n");
printf("outputing result to %s\n",ofn);
for(i=0;i<noden;i++) {
fprintf(ofp,"%d\t%f\n",i,*(r+i));
}
printf("output done!,counter times:%d\n",counter);
fclose(ifp);
fclose(ofp);
free(array);
free(array_edge);
free(rtmp);
free(r);
return 0;
}
int check_result(REAL *r, REAL *rtmp, int noden) {
int i;
for(i=0;i<noden;i++) {
if(!(*(r+i)-*(rtmp+i)<EPSILON && *(rtmp+i)-*(r+i)<EPSILON)) {
return 0;
}
}
return 1;
}
|
SpatialFractionalMaxPooling.c | #ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "generic/SpatialFractionalMaxPooling.c"
#else
static int64_t* THNN_(SpatialFractionalMaxPooling_generateIntervals)(
real sample,
int64_t inputSize,
int64_t outputSize,
int poolSize) {
real alpha = (real) (inputSize - poolSize) / (real) (outputSize - 1);
int64_t* sequence = (int64_t*) THAlloc(sizeof(int64_t) * outputSize);
int64_t i;
for (i = 0; i < outputSize - 1; ++i) {
sequence[i] =
(int64_t) ((i + sample) * alpha) - (int64_t) (sample * alpha);
}
sequence[outputSize - 1] = inputSize - poolSize;
return sequence;
}
static void THNN_(SpatialFractionalMaxPooling_updateOutput_frame)(
real* input,
real* output,
THIndex_t* indices,
real* randomSamples,
int64_t numPlanes,
int64_t inputW, int64_t inputH,
int64_t outputW, int64_t outputH,
int poolSizeW, int poolSizeH) {
int64_t plane;
#pragma omp parallel for private(plane)
for (plane = 0; plane < numPlanes; ++plane) {
/* each plane contains 2 random samples, one for W and one for H */
real* randomSamplesForPlane = randomSamples + plane * 2;
/* Generate interval sequence */
int64_t* sequenceW =
THNN_(SpatialFractionalMaxPooling_generateIntervals)(
randomSamplesForPlane[0], inputW, outputW, poolSizeW);
int64_t* sequenceH =
THNN_(SpatialFractionalMaxPooling_generateIntervals)(
randomSamplesForPlane[1], inputH, outputH, poolSizeH);
/* loop over output */
int64_t h, w;
real* inputForPlane = input + plane * inputW * inputH;
real* outputForPlane = output + plane * outputW * outputH;
THIndex_t* indicesForPlane = indices + plane * outputW * outputH;
for (h = 0; h < outputH; ++h) {
int64_t inputHStart = sequenceH[h];
for (w = 0; w < outputW; ++w) {
int64_t inputWStart = sequenceW[w];
real maxVal = -THInf;
int64_t maxIndex = -1;
int64_t h2, w2;
for (h2 = inputHStart; h2 < inputHStart + poolSizeH; ++h2) {
for (w2 = inputWStart; w2 < inputWStart + poolSizeW; ++w2) {
THAssert(h2 >= 0 && h2 < inputH);
THAssert(w2 >= 0 && w2 < inputW);
int64_t planeIndex = h2 * inputW + w2;
real val = inputForPlane[planeIndex];
if (val > maxVal) {
maxVal = val;
maxIndex = planeIndex;
}
}
}
THAssert(maxVal != -THInf);
THAssert(maxIndex != -1);
outputForPlane[h * outputW + w] = maxVal;
/* +1 to lua index */
indicesForPlane[h * outputW + w] = maxIndex + TH_INDEX_BASE;
}
}
THFree(sequenceW);
THFree(sequenceH);
}
}
void THNN_(SpatialFractionalMaxPooling_updateOutput)(
THNNState *state,
THTensor *input,
THTensor *output,
int outputW, int outputH,
int poolSizeW, int poolSizeH,
THIndexTensor *indices,
THTensor *randomSamples) {
int64_t numBatch = 1;
int planeDim = 0;
int heightDim = 1;
int widthDim = 2;
int64_t numInputDims = THTensor_(nDimension)(input);
THNN_ARGCHECK(numInputDims == 3 || numInputDims == 4, 2, input,
"3D or 4D (batch mode) tensor expected for input, but got: %s");
if (numInputDims == 4) {
numBatch = THTensor_(size)(input, 0);
planeDim++;
heightDim++;
widthDim++;
}
/* sizes */
int64_t numPlanes = THTensor_(size)(input, planeDim);
int64_t inputH = THTensor_(size)(input, heightDim);
int64_t inputW = THTensor_(size)(input, widthDim);
THArgCheck(outputH + poolSizeH - 1 <= inputH, 7,
"poolSizeH (%d) too large relative to input height (%d)",
poolSizeH, inputH);
THArgCheck(outputW + poolSizeW - 1 <= inputW, 6,
"poolSizeW (%d) too large relative to input width (%d)",
poolSizeW, inputW);
/* get contiguous input */
input = THTensor_(newContiguous)(input);
if (numInputDims == 3) {
/* resize output */
THTensor_(resize3d)(output, numPlanes, outputH, outputW);
/* indices will contain the locations for each output point */
THIndexTensor_(resize3d)(indices, numPlanes, outputH, outputW);
THNN_(SpatialFractionalMaxPooling_updateOutput_frame)(
THTensor_(data)(input),
THTensor_(data)(output),
THIndexTensor_(data)(indices),
THTensor_(data)(randomSamples),
numPlanes, inputW, inputH, outputW, outputH, poolSizeW, poolSizeH);
} else {
THTensor_(resize4d)(output, numBatch, numPlanes, outputH, outputW);
/* indices will contain the locations for each output point */
THIndexTensor_(resize4d)(indices, numBatch, numPlanes, outputH, outputW);
int64_t batch;
#pragma omp parallel for private(batch)
for (batch = 0; batch < numBatch; ++batch) {
THNN_(SpatialFractionalMaxPooling_updateOutput_frame)(
THTensor_(data)(input) + batch * numPlanes * inputH * inputW,
THTensor_(data)(output) + batch * numPlanes * outputH * outputW,
THIndexTensor_(data)(indices) + batch * numPlanes * outputH * outputW,
THTensor_(data)(randomSamples) + batch * numPlanes * 2,
numPlanes, inputW, inputH, outputW, outputH, poolSizeW, poolSizeH);
}
}
/* cleanup */
THTensor_(free)(input);
}
static void THNN_(SpatialFractionalMaxPooling_updateGradInput_frame)(
real* gradInput,
real* gradOutput,
THIndex_t* indices,
int64_t numPlanes,
int64_t inputW, int64_t inputH,
int64_t outputW, int64_t outputH) {
int64_t plane;
#pragma omp parallel for private(plane)
for (plane = 0; plane < numPlanes; plane++) {
real* gradInputForPlane = gradInput + plane * inputW * inputH;
real* gradOutputForPlane = gradOutput + plane * outputW * outputH;
THIndex_t* indicesForPlane = indices + plane * outputW * outputH;
int64_t h, w;
for (h = 0; h < outputH; ++h) {
for (w = 0; w < outputW; ++w) {
int64_t outputIndex = h * outputW + w;
int64_t index = indicesForPlane[outputIndex] - TH_INDEX_BASE;
THAssert(index >= 0 && index < inputW * inputH);
gradInputForPlane[index] += gradOutputForPlane[outputIndex];
}
}
}
}
void THNN_(SpatialFractionalMaxPooling_updateGradInput)(
THNNState *state,
THTensor *input,
THTensor *gradOutput,
THTensor *gradInput,
int outputW, int outputH,
int poolSizeW, int poolSizeH,
THIndexTensor *indices) {
int64_t numBatch = 1;
int planeDim = 0;
int heightDim = 1;
int widthDim = 2;
int64_t numInputDims = THTensor_(nDimension)(input);
if (numInputDims == 4) {
numBatch = THTensor_(size)(input, 0);
planeDim = 1;
heightDim++;
widthDim++;
}
/* sizes */
int64_t numPlanes = THTensor_(size)(input, planeDim);
int64_t inputH = THTensor_(size)(input, heightDim);
int64_t inputW = THTensor_(size)(input, widthDim);
THArgCheck(outputW == THTensor_(size)(gradOutput, widthDim), 3,
"gradOutput width unexpected");
THArgCheck(outputH == THTensor_(size)(gradOutput, heightDim), 3,
"gradOutput height unexpected");
/* get contiguous gradOutput */
gradOutput = THTensor_(newContiguous)(gradOutput);
/* resize */
THTensor_(resizeAs)(gradInput, input);
THTensor_(zero)(gradInput);
/* backprop */
if (numInputDims == 3) {
THNN_(SpatialFractionalMaxPooling_updateGradInput_frame)(
THTensor_(data)(gradInput),
THTensor_(data)(gradOutput),
THIndexTensor_(data)(indices),
numPlanes, inputW, inputH, outputW, outputH);
} else {
int64_t batch;
#pragma omp parallel for private(batch)
for (batch = 0; batch < numBatch; ++batch) {
THNN_(SpatialFractionalMaxPooling_updateGradInput_frame)(
THTensor_(data)(gradInput) + batch * numPlanes * inputH * inputW,
THTensor_(data)(gradOutput) + batch * numPlanes * outputH * outputW,
THIndexTensor_(data)(indices) + batch * numPlanes * outputH * outputW,
numPlanes, inputW, inputH, outputW, outputH);
}
}
/* cleanup */
THTensor_(free)(gradOutput);
}
#endif
|
kmp_aff_disable_hwloc.c | // RUN: %libomp-compile && env KMP_AFFINITY=disabled KMP_TOPOLOGY_METHOD=hwloc %libomp-run
// REQUIRES: hwloc
#include <stdio.h>
#include <stdlib.h>
// Test will assert() without fix
int test_affinity_disabled_plus_hwloc() {
#pragma omp parallel
{}
return 1;
}
int main(int argc, char **argv) {
int i, j;
int failed = 0;
if (!test_affinity_disabled_plus_hwloc()) {
failed = 1;
}
return failed;
}
|
main.c | void foo(int N, int *A) {
int TSize = 4;
int T[4];
for (int I = 0; I < TSize; ++I)
T[I] = I;
#pragma spf region
#pragma omp parallel default(shared)
{
#pragma omp for
for (int I = 0; I < N; ++I) {
A[I] = I;
for (int J = 0; J < TSize; ++J)
A[I] = A[I] + T[J];
}
}
}
|
Parser.h | //===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines the Parser interface.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_PARSE_PARSER_H
#define LLVM_CLANG_PARSE_PARSER_H
#include "clang/AST/OpenMPClause.h"
#include "clang/AST/Availability.h"
#include "clang/Basic/BitmaskEnum.h"
#include "clang/Basic/OpenMPKinds.h"
#include "clang/Basic/OperatorPrecedence.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Lex/CodeCompletionHandler.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/Sema.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/SaveAndRestore.h"
#include <memory>
#include <stack>
namespace clang {
class PragmaHandler;
class Scope;
class BalancedDelimiterTracker;
class CorrectionCandidateCallback;
class DeclGroupRef;
class DiagnosticBuilder;
struct LoopHint;
class Parser;
class ParsingDeclRAIIObject;
class ParsingDeclSpec;
class ParsingDeclarator;
class ParsingFieldDeclarator;
class ColonProtectionRAIIObject;
class InMessageExpressionRAIIObject;
class PoisonSEHIdentifiersRAIIObject;
class OMPClause;
class ObjCTypeParamList;
class ObjCTypeParameter;
/// Parser - This implements a parser for the C family of languages. After
/// parsing units of the grammar, productions are invoked to handle whatever has
/// been read.
///
class Parser : public CodeCompletionHandler {
friend class ColonProtectionRAIIObject;
friend class InMessageExpressionRAIIObject;
friend class PoisonSEHIdentifiersRAIIObject;
friend class ObjCDeclContextSwitch;
friend class ParenBraceBracketBalancer;
friend class BalancedDelimiterTracker;
Preprocessor &PP;
/// Tok - The current token we are peeking ahead. All parsing methods assume
/// that this is valid.
Token Tok;
// PrevTokLocation - The location of the token we previously
// consumed. This token is used for diagnostics where we expected to
// see a token following another token (e.g., the ';' at the end of
// a statement).
SourceLocation PrevTokLocation;
/// Tracks an expected type for the current token when parsing an expression.
/// Used by code completion for ranking.
PreferredTypeBuilder PreferredType;
unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0;
unsigned short MisplacedModuleBeginCount = 0;
/// Actions - These are the callbacks we invoke as we parse various constructs
/// in the file.
Sema &Actions;
DiagnosticsEngine &Diags;
/// ScopeCache - Cache scopes to reduce malloc traffic.
enum { ScopeCacheSize = 16 };
unsigned NumCachedScopes;
Scope *ScopeCache[ScopeCacheSize];
/// Identifiers used for SEH handling in Borland. These are only
/// allowed in particular circumstances
// __except block
IdentifierInfo *Ident__exception_code,
*Ident___exception_code,
*Ident_GetExceptionCode;
// __except filter expression
IdentifierInfo *Ident__exception_info,
*Ident___exception_info,
*Ident_GetExceptionInfo;
// __finally
IdentifierInfo *Ident__abnormal_termination,
*Ident___abnormal_termination,
*Ident_AbnormalTermination;
/// Contextual keywords for Microsoft extensions.
IdentifierInfo *Ident__except;
mutable IdentifierInfo *Ident_sealed;
/// Ident_super - IdentifierInfo for "super", to support fast
/// comparison.
IdentifierInfo *Ident_super;
/// Ident_vector, Ident_bool - cached IdentifierInfos for "vector" and
/// "bool" fast comparison. Only present if AltiVec or ZVector are enabled.
IdentifierInfo *Ident_vector;
IdentifierInfo *Ident_bool;
/// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison.
/// Only present if AltiVec enabled.
IdentifierInfo *Ident_pixel;
/// Objective-C contextual keywords.
IdentifierInfo *Ident_instancetype;
/// Identifier for "introduced".
IdentifierInfo *Ident_introduced;
/// Identifier for "deprecated".
IdentifierInfo *Ident_deprecated;
/// Identifier for "obsoleted".
IdentifierInfo *Ident_obsoleted;
/// Identifier for "unavailable".
IdentifierInfo *Ident_unavailable;
/// Identifier for "message".
IdentifierInfo *Ident_message;
/// Identifier for "strict".
IdentifierInfo *Ident_strict;
/// Identifier for "replacement".
IdentifierInfo *Ident_replacement;
/// Identifiers used by the 'external_source_symbol' attribute.
IdentifierInfo *Ident_language, *Ident_defined_in,
*Ident_generated_declaration;
/// C++11 contextual keywords.
mutable IdentifierInfo *Ident_final;
mutable IdentifierInfo *Ident_GNU_final;
mutable IdentifierInfo *Ident_override;
// C++2a contextual keywords.
mutable IdentifierInfo *Ident_import;
mutable IdentifierInfo *Ident_module;
// C++ type trait keywords that can be reverted to identifiers and still be
// used as type traits.
llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits;
std::unique_ptr<PragmaHandler> AlignHandler;
std::unique_ptr<PragmaHandler> GCCVisibilityHandler;
std::unique_ptr<PragmaHandler> OptionsHandler;
std::unique_ptr<PragmaHandler> PackHandler;
std::unique_ptr<PragmaHandler> UPCHandler;
std::unique_ptr<PragmaHandler> PUPCHandler;
std::unique_ptr<PragmaHandler> MSStructHandler;
std::unique_ptr<PragmaHandler> UnusedHandler;
std::unique_ptr<PragmaHandler> WeakHandler;
std::unique_ptr<PragmaHandler> RedefineExtnameHandler;
std::unique_ptr<PragmaHandler> FPContractHandler;
std::unique_ptr<PragmaHandler> OpenCLExtensionHandler;
std::unique_ptr<PragmaHandler> OpenMPHandler;
std::unique_ptr<PragmaHandler> PCSectionHandler;
std::unique_ptr<PragmaHandler> MSCommentHandler;
std::unique_ptr<PragmaHandler> MSDetectMismatchHandler;
std::unique_ptr<PragmaHandler> MSPointersToMembers;
std::unique_ptr<PragmaHandler> MSVtorDisp;
std::unique_ptr<PragmaHandler> MSInitSeg;
std::unique_ptr<PragmaHandler> MSDataSeg;
std::unique_ptr<PragmaHandler> MSBSSSeg;
std::unique_ptr<PragmaHandler> MSConstSeg;
std::unique_ptr<PragmaHandler> MSCodeSeg;
std::unique_ptr<PragmaHandler> MSSection;
std::unique_ptr<PragmaHandler> MSRuntimeChecks;
std::unique_ptr<PragmaHandler> MSIntrinsic;
std::unique_ptr<PragmaHandler> MSOptimize;
std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler;
std::unique_ptr<PragmaHandler> OptimizeHandler;
std::unique_ptr<PragmaHandler> LoopHintHandler;
std::unique_ptr<PragmaHandler> UnrollHintHandler;
std::unique_ptr<PragmaHandler> NoUnrollHintHandler;
std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler;
std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler;
std::unique_ptr<PragmaHandler> FPHandler;
std::unique_ptr<PragmaHandler> STDCFENVHandler;
std::unique_ptr<PragmaHandler> STDCCXLIMITHandler;
std::unique_ptr<PragmaHandler> STDCUnknownHandler;
std::unique_ptr<PragmaHandler> AttributePragmaHandler;
std::unique_ptr<CommentHandler> CommentSemaHandler;
/// Whether the '>' token acts as an operator or not. This will be
/// true except when we are parsing an expression within a C++
/// template argument list, where the '>' closes the template
/// argument list.
bool GreaterThanIsOperator;
/// ColonIsSacred - When this is false, we aggressively try to recover from
/// code like "foo : bar" as if it were a typo for "foo :: bar". This is not
/// safe in case statements and a few other things. This is managed by the
/// ColonProtectionRAIIObject RAII object.
bool ColonIsSacred;
/// When true, we are directly inside an Objective-C message
/// send expression.
///
/// This is managed by the \c InMessageExpressionRAIIObject class, and
/// should not be set directly.
bool InMessageExpression;
/// Gets set to true after calling ProduceSignatureHelp, it is for a
/// workaround to make sure ProduceSignatureHelp is only called at the deepest
/// function call.
bool CalledSignatureHelp = false;
/// The "depth" of the template parameters currently being parsed.
unsigned TemplateParameterDepth;
/// RAII class that manages the template parameter depth.
class TemplateParameterDepthRAII {
unsigned &Depth;
unsigned AddedLevels;
public:
explicit TemplateParameterDepthRAII(unsigned &Depth)
: Depth(Depth), AddedLevels(0) {}
~TemplateParameterDepthRAII() {
Depth -= AddedLevels;
}
void operator++() {
++Depth;
++AddedLevels;
}
void addDepth(unsigned D) {
Depth += D;
AddedLevels += D;
}
void setAddedDepth(unsigned D) {
Depth = Depth - AddedLevels + D;
AddedLevels = D;
}
unsigned getDepth() const { return Depth; }
unsigned getOriginalDepth() const { return Depth - AddedLevels; }
};
/// Factory object for creating ParsedAttr objects.
AttributeFactory AttrFactory;
/// Gathers and cleans up TemplateIdAnnotations when parsing of a
/// top-level declaration is finished.
SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
/// Identifiers which have been declared within a tentative parse.
SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
/// Tracker for '<' tokens that might have been intended to be treated as an
/// angle bracket instead of a less-than comparison.
///
/// This happens when the user intends to form a template-id, but typoes the
/// template-name or forgets a 'template' keyword for a dependent template
/// name.
///
/// We track these locations from the point where we see a '<' with a
/// name-like expression on its left until we see a '>' or '>>' that might
/// match it.
struct AngleBracketTracker {
/// Flags used to rank candidate template names when there is more than one
/// '<' in a scope.
enum Priority : unsigned short {
/// A non-dependent name that is a potential typo for a template name.
PotentialTypo = 0x0,
/// A dependent name that might instantiate to a template-name.
DependentName = 0x2,
/// A space appears before the '<' token.
SpaceBeforeLess = 0x0,
/// No space before the '<' token
NoSpaceBeforeLess = 0x1,
LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue*/ DependentName)
};
struct Loc {
Expr *TemplateName;
SourceLocation LessLoc;
AngleBracketTracker::Priority Priority;
unsigned short ParenCount, BracketCount, BraceCount;
bool isActive(Parser &P) const {
return P.ParenCount == ParenCount && P.BracketCount == BracketCount &&
P.BraceCount == BraceCount;
}
bool isActiveOrNested(Parser &P) const {
return isActive(P) || P.ParenCount > ParenCount ||
P.BracketCount > BracketCount || P.BraceCount > BraceCount;
}
};
SmallVector<Loc, 8> Locs;
/// Add an expression that might have been intended to be a template name.
/// In the case of ambiguity, we arbitrarily select the innermost such
/// expression, for example in 'foo < bar < baz', 'bar' is the current
/// candidate. No attempt is made to track that 'foo' is also a candidate
/// for the case where we see a second suspicious '>' token.
void add(Parser &P, Expr *TemplateName, SourceLocation LessLoc,
Priority Prio) {
if (!Locs.empty() && Locs.back().isActive(P)) {
if (Locs.back().Priority <= Prio) {
Locs.back().TemplateName = TemplateName;
Locs.back().LessLoc = LessLoc;
Locs.back().Priority = Prio;
}
} else {
Locs.push_back({TemplateName, LessLoc, Prio,
P.ParenCount, P.BracketCount, P.BraceCount});
}
}
/// Mark the current potential missing template location as having been
/// handled (this happens if we pass a "corresponding" '>' or '>>' token
/// or leave a bracket scope).
void clear(Parser &P) {
while (!Locs.empty() && Locs.back().isActiveOrNested(P))
Locs.pop_back();
}
/// Get the current enclosing expression that might hve been intended to be
/// a template name.
Loc *getCurrent(Parser &P) {
if (!Locs.empty() && Locs.back().isActive(P))
return &Locs.back();
return nullptr;
}
};
AngleBracketTracker AngleBrackets;
IdentifierInfo *getSEHExceptKeyword();
/// True if we are within an Objective-C container while parsing C-like decls.
///
/// This is necessary because Sema thinks we have left the container
/// to parse the C-like decls, meaning Actions.getObjCDeclContext() will
/// be NULL.
bool ParsingInObjCContainer;
/// Whether to skip parsing of function bodies.
///
/// This option can be used, for example, to speed up searches for
/// declarations/definitions when indexing.
bool SkipFunctionBodies;
/// The location of the expression statement that is being parsed right now.
/// Used to determine if an expression that is being parsed is a statement or
/// just a regular sub-expression.
SourceLocation ExprStatementTokLoc;
/// Flags describing a context in which we're parsing a statement.
enum class ParsedStmtContext {
/// This context permits declarations in language modes where declarations
/// are not statements.
AllowDeclarationsInC = 0x1,
/// This context permits standalone OpenMP directives.
AllowStandaloneOpenMPDirectives = 0x2,
/// This context is at the top level of a GNU statement expression.
InStmtExpr = 0x4,
/// The context of a regular substatement.
SubStmt = 0,
/// The context of a compound-statement.
Compound = AllowDeclarationsInC | AllowStandaloneOpenMPDirectives,
LLVM_MARK_AS_BITMASK_ENUM(InStmtExpr)
};
/// Act on an expression statement that might be the last statement in a
/// GNU statement expression. Checks whether we are actually at the end of
/// a statement expression and builds a suitable expression statement.
StmtResult handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx);
public:
Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
~Parser() override;
const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
Preprocessor &getPreprocessor() const { return PP; }
Sema &getActions() const { return Actions; }
AttributeFactory &getAttrFactory() { return AttrFactory; }
const Token &getCurToken() const { return Tok; }
Scope *getCurScope() const { return Actions.getCurScope(); }
void incrementMSManglingNumber() const {
return Actions.incrementMSManglingNumber();
}
Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); }
// Type forwarding. All of these are statically 'void*', but they may all be
// different actual classes based on the actions in place.
typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
typedef OpaquePtr<TemplateName> TemplateTy;
typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists;
typedef Sema::FullExprArg FullExprArg;
// Parsing methods.
/// Initialize - Warm up the parser.
///
void Initialize();
/// Parse the first top-level declaration in a translation unit.
bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result);
/// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
/// the EOF was encountered.
bool ParseTopLevelDecl(DeclGroupPtrTy &Result, bool IsFirstDecl = false);
bool ParseTopLevelDecl() {
DeclGroupPtrTy Result;
return ParseTopLevelDecl(Result);
}
/// ConsumeToken - Consume the current 'peek token' and lex the next one.
/// This does not work with special tokens: string literals, code completion,
/// annotation tokens and balanced tokens must be handled using the specific
/// consume methods.
/// Returns the location of the consumed token.
SourceLocation ConsumeToken() {
assert(!isTokenSpecial() &&
"Should consume special tokens with Consume*Token");
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
bool TryConsumeToken(tok::TokenKind Expected) {
if (Tok.isNot(Expected))
return false;
assert(!isTokenSpecial() &&
"Should consume special tokens with Consume*Token");
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return true;
}
bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) {
if (!TryConsumeToken(Expected))
return false;
Loc = PrevTokLocation;
return true;
}
/// ConsumeAnyToken - Dispatch to the right Consume* method based on the
/// current token type. This should only be used in cases where the type of
/// the token really isn't known, e.g. in error recovery.
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) {
if (isTokenParen())
return ConsumeParen();
if (isTokenBracket())
return ConsumeBracket();
if (isTokenBrace())
return ConsumeBrace();
if (isTokenStringLiteral())
return ConsumeStringToken();
if (Tok.is(tok::code_completion))
return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken()
: handleUnexpectedCodeCompletionToken();
if (Tok.isAnnotation())
return ConsumeAnnotationToken();
return ConsumeToken();
}
SourceLocation getEndOfPreviousToken() {
return PP.getLocForEndOfToken(PrevTokLocation);
}
/// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds
/// to the given nullability kind.
IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) {
return Actions.getNullabilityKeyword(nullability);
}
private:
//===--------------------------------------------------------------------===//
// Low-Level token peeking and consumption methods.
//
/// isTokenParen - Return true if the cur token is '(' or ')'.
bool isTokenParen() const {
return Tok.isOneOf(tok::l_paren, tok::r_paren);
}
/// isTokenBracket - Return true if the cur token is '[' or ']'.
bool isTokenBracket() const {
return Tok.isOneOf(tok::l_square, tok::r_square);
}
/// isTokenBrace - Return true if the cur token is '{' or '}'.
bool isTokenBrace() const {
return Tok.isOneOf(tok::l_brace, tok::r_brace);
}
/// isTokenStringLiteral - True if this token is a string-literal.
bool isTokenStringLiteral() const {
return tok::isStringLiteral(Tok.getKind());
}
/// isTokenSpecial - True if this token requires special consumption methods.
bool isTokenSpecial() const {
return isTokenStringLiteral() || isTokenParen() || isTokenBracket() ||
isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation();
}
/// Returns true if the current token is '=' or is a type of '='.
/// For typos, give a fixit to '='
bool isTokenEqualOrEqualTypo();
/// Return the current token to the token stream and make the given
/// token the current token.
void UnconsumeToken(Token &Consumed) {
Token Next = Tok;
PP.EnterToken(Consumed, /*IsReinject*/true);
PP.Lex(Tok);
PP.EnterToken(Next, /*IsReinject*/true);
}
SourceLocation ConsumeAnnotationToken() {
assert(Tok.isAnnotation() && "wrong consume method");
SourceLocation Loc = Tok.getLocation();
PrevTokLocation = Tok.getAnnotationEndLoc();
PP.Lex(Tok);
return Loc;
}
/// ConsumeParen - This consume method keeps the paren count up-to-date.
///
SourceLocation ConsumeParen() {
assert(isTokenParen() && "wrong consume method");
if (Tok.getKind() == tok::l_paren)
++ParenCount;
else if (ParenCount) {
AngleBrackets.clear(*this);
--ParenCount; // Don't let unbalanced )'s drive the count negative.
}
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
/// ConsumeBracket - This consume method keeps the bracket count up-to-date.
///
SourceLocation ConsumeBracket() {
assert(isTokenBracket() && "wrong consume method");
if (Tok.getKind() == tok::l_square)
++BracketCount;
else if (BracketCount) {
AngleBrackets.clear(*this);
--BracketCount; // Don't let unbalanced ]'s drive the count negative.
}
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
/// ConsumeBrace - This consume method keeps the brace count up-to-date.
///
SourceLocation ConsumeBrace() {
assert(isTokenBrace() && "wrong consume method");
if (Tok.getKind() == tok::l_brace)
++BraceCount;
else if (BraceCount) {
AngleBrackets.clear(*this);
--BraceCount; // Don't let unbalanced }'s drive the count negative.
}
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
/// ConsumeStringToken - Consume the current 'peek token', lexing a new one
/// and returning the token kind. This method is specific to strings, as it
/// handles string literal concatenation, as per C99 5.1.1.2, translation
/// phase #6.
SourceLocation ConsumeStringToken() {
assert(isTokenStringLiteral() &&
"Should only consume string literals with this method");
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
/// Consume the current code-completion token.
///
/// This routine can be called to consume the code-completion token and
/// continue processing in special cases where \c cutOffParsing() isn't
/// desired, such as token caching or completion with lookahead.
SourceLocation ConsumeCodeCompletionToken() {
assert(Tok.is(tok::code_completion));
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
///\ brief When we are consuming a code-completion token without having
/// matched specific position in the grammar, provide code-completion results
/// based on context.
///
/// \returns the source location of the code-completion token.
SourceLocation handleUnexpectedCodeCompletionToken();
/// Abruptly cut off parsing; mainly used when we have reached the
/// code-completion point.
void cutOffParsing() {
if (PP.isCodeCompletionEnabled())
PP.setCodeCompletionReached();
// Cut off parsing by acting as if we reached the end-of-file.
Tok.setKind(tok::eof);
}
/// Determine if we're at the end of the file or at a transition
/// between modules.
bool isEofOrEom() {
tok::TokenKind Kind = Tok.getKind();
return Kind == tok::eof || Kind == tok::annot_module_begin ||
Kind == tok::annot_module_end || Kind == tok::annot_module_include;
}
/// Checks if the \p Level is valid for use in a fold expression.
bool isFoldOperator(prec::Level Level) const;
/// Checks if the \p Kind is a valid operator for fold expressions.
bool isFoldOperator(tok::TokenKind Kind) const;
/// Initialize all pragma handlers.
void initializePragmaHandlers();
/// Destroy and reset all pragma handlers.
void resetPragmaHandlers();
/// Handle the annotation token produced for #pragma unused(...)
void HandlePragmaUnused();
/// Handle the annotation token produced for
/// #pragma GCC visibility...
void HandlePragmaVisibility();
/// Handle the annotation token produced for
/// #pragma pack...
void HandlePragmaPack();
/// \brief Handle the annotation token produced for
/// #pragma upc...
StmtResult HandlePragmaUPC();
/// \brief Handle the annotation token produced for
/// #pragma pupc...
Decl * HandlePragmaPUPC();
/// \brief Handle the annotation token produced for
/// #pragma ms_struct...
void HandlePragmaMSStruct();
/// Handle the annotation token produced for
/// #pragma comment...
void HandlePragmaMSComment();
void HandlePragmaMSPointersToMembers();
void HandlePragmaMSVtorDisp();
void HandlePragmaMSPragma();
bool HandlePragmaMSSection(StringRef PragmaName,
SourceLocation PragmaLocation);
bool HandlePragmaMSSegment(StringRef PragmaName,
SourceLocation PragmaLocation);
bool HandlePragmaMSInitSeg(StringRef PragmaName,
SourceLocation PragmaLocation);
/// Handle the annotation token produced for
/// #pragma align...
void HandlePragmaAlign();
/// Handle the annotation token produced for
/// #pragma clang __debug dump...
void HandlePragmaDump();
/// Handle the annotation token produced for
/// #pragma weak id...
void HandlePragmaWeak();
/// Handle the annotation token produced for
/// #pragma weak id = id...
void HandlePragmaWeakAlias();
/// Handle the annotation token produced for
/// #pragma redefine_extname...
void HandlePragmaRedefineExtname();
/// Handle the annotation token produced for
/// #pragma STDC FP_CONTRACT...
void HandlePragmaFPContract();
/// Handle the annotation token produced for
/// #pragma STDC FENV_ACCESS...
void HandlePragmaFEnvAccess();
/// \brief Handle the annotation token produced for
/// #pragma clang fp ...
void HandlePragmaFP();
/// Handle the annotation token produced for
/// #pragma OPENCL EXTENSION...
void HandlePragmaOpenCLExtension();
/// Handle the annotation token produced for
/// #pragma clang __debug captured
StmtResult HandlePragmaCaptured();
/// Handle the annotation token produced for
/// #pragma clang loop and #pragma unroll.
bool HandlePragmaLoopHint(LoopHint &Hint);
bool ParsePragmaAttributeSubjectMatchRuleSet(
attr::ParsedSubjectMatchRuleSet &SubjectMatchRules,
SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc);
void HandlePragmaAttribute();
/// GetLookAheadToken - This peeks ahead N tokens and returns that token
/// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1)
/// returns the token after Tok, etc.
///
/// Note that this differs from the Preprocessor's LookAhead method, because
/// the Parser always has one token lexed that the preprocessor doesn't.
///
const Token &GetLookAheadToken(unsigned N) {
if (N == 0 || Tok.is(tok::eof)) return Tok;
return PP.LookAhead(N-1);
}
public:
/// NextToken - This peeks ahead one token and returns it without
/// consuming it.
const Token &NextToken() {
return PP.LookAhead(0);
}
/// getTypeAnnotation - Read a parsed type out of an annotation token.
static ParsedType getTypeAnnotation(const Token &Tok) {
return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
}
private:
static void setTypeAnnotation(Token &Tok, ParsedType T) {
Tok.setAnnotationValue(T.getAsOpaquePtr());
}
/// Read an already-translated primary expression out of an annotation
/// token.
static ExprResult getExprAnnotation(const Token &Tok) {
return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue());
}
/// Set the primary expression corresponding to the given annotation
/// token.
static void setExprAnnotation(Token &Tok, ExprResult ER) {
Tok.setAnnotationValue(ER.getAsOpaquePointer());
}
public:
// If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to
// find a type name by attempting typo correction.
bool TryAnnotateTypeOrScopeToken();
bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS,
bool IsNewScope);
bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
private:
enum AnnotatedNameKind {
/// Annotation has failed and emitted an error.
ANK_Error,
/// The identifier is a tentatively-declared name.
ANK_TentativeDecl,
/// The identifier is a template name. FIXME: Add an annotation for that.
ANK_TemplateName,
/// The identifier can't be resolved.
ANK_Unresolved,
/// Annotation was successful.
ANK_Success
};
AnnotatedNameKind TryAnnotateName(bool IsAddressOfOperand,
CorrectionCandidateCallback *CCC = nullptr);
/// Push a tok::annot_cxxscope token onto the token stream.
void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
/// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
/// replacing them with the non-context-sensitive keywords. This returns
/// true if the token was replaced.
bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
const char *&PrevSpec, unsigned &DiagID,
bool &isInvalid) {
if (!getLangOpts().AltiVec && !getLangOpts().ZVector)
return false;
if (Tok.getIdentifierInfo() != Ident_vector &&
Tok.getIdentifierInfo() != Ident_bool &&
(!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel))
return false;
return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
}
/// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
/// identifier token, replacing it with the non-context-sensitive __vector.
/// This returns true if the token was replaced.
bool TryAltiVecVectorToken() {
if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) ||
Tok.getIdentifierInfo() != Ident_vector) return false;
return TryAltiVecVectorTokenOutOfLine();
}
bool TryAltiVecVectorTokenOutOfLine();
bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
const char *&PrevSpec, unsigned &DiagID,
bool &isInvalid);
/// Returns true if the current token is the identifier 'instancetype'.
///
/// Should only be used in Objective-C language modes.
bool isObjCInstancetype() {
assert(getLangOpts().ObjC);
if (Tok.isAnnotation())
return false;
if (!Ident_instancetype)
Ident_instancetype = PP.getIdentifierInfo("instancetype");
return Tok.getIdentifierInfo() == Ident_instancetype;
}
/// TryKeywordIdentFallback - For compatibility with system headers using
/// keywords as identifiers, attempt to convert the current token to an
/// identifier and optionally disable the keyword for the remainder of the
/// translation unit. This returns false if the token was not replaced,
/// otherwise emits a diagnostic and returns true.
bool TryKeywordIdentFallback(bool DisableKeyword);
/// Get the TemplateIdAnnotation from the token.
TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
/// TentativeParsingAction - An object that is used as a kind of "tentative
/// parsing transaction". It gets instantiated to mark the token position and
/// after the token consumption is done, Commit() or Revert() is called to
/// either "commit the consumed tokens" or revert to the previously marked
/// token position. Example:
///
/// TentativeParsingAction TPA(*this);
/// ConsumeToken();
/// ....
/// TPA.Revert();
///
class TentativeParsingAction {
Parser &P;
PreferredTypeBuilder PrevPreferredType;
Token PrevTok;
size_t PrevTentativelyDeclaredIdentifierCount;
unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
bool isActive;
public:
explicit TentativeParsingAction(Parser& p) : P(p) {
PrevPreferredType = P.PreferredType;
PrevTok = P.Tok;
PrevTentativelyDeclaredIdentifierCount =
P.TentativelyDeclaredIdentifiers.size();
PrevParenCount = P.ParenCount;
PrevBracketCount = P.BracketCount;
PrevBraceCount = P.BraceCount;
P.PP.EnableBacktrackAtThisPos();
isActive = true;
}
void Commit() {
assert(isActive && "Parsing action was finished!");
P.TentativelyDeclaredIdentifiers.resize(
PrevTentativelyDeclaredIdentifierCount);
P.PP.CommitBacktrackedTokens();
isActive = false;
}
void Revert() {
assert(isActive && "Parsing action was finished!");
P.PP.Backtrack();
P.PreferredType = PrevPreferredType;
P.Tok = PrevTok;
P.TentativelyDeclaredIdentifiers.resize(
PrevTentativelyDeclaredIdentifierCount);
P.ParenCount = PrevParenCount;
P.BracketCount = PrevBracketCount;
P.BraceCount = PrevBraceCount;
isActive = false;
}
~TentativeParsingAction() {
assert(!isActive && "Forgot to call Commit or Revert!");
}
};
/// A TentativeParsingAction that automatically reverts in its destructor.
/// Useful for disambiguation parses that will always be reverted.
class RevertingTentativeParsingAction
: private Parser::TentativeParsingAction {
public:
RevertingTentativeParsingAction(Parser &P)
: Parser::TentativeParsingAction(P) {}
~RevertingTentativeParsingAction() { Revert(); }
};
class UnannotatedTentativeParsingAction;
/// ObjCDeclContextSwitch - An object used to switch context from
/// an objective-c decl context to its enclosing decl context and
/// back.
class ObjCDeclContextSwitch {
Parser &P;
Decl *DC;
SaveAndRestore<bool> WithinObjCContainer;
public:
explicit ObjCDeclContextSwitch(Parser &p)
: P(p), DC(p.getObjCDeclContext()),
WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) {
if (DC)
P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC));
}
~ObjCDeclContextSwitch() {
if (DC)
P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC));
}
};
/// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
/// input. If so, it is consumed and false is returned.
///
/// If a trivial punctuator misspelling is encountered, a FixIt error
/// diagnostic is issued and false is returned after recovery.
///
/// If the input is malformed, this emits the specified diagnostic and true is
/// returned.
bool ExpectAndConsume(tok::TokenKind ExpectedTok,
unsigned Diag = diag::err_expected,
StringRef DiagMsg = "");
/// The parser expects a semicolon and, if present, will consume it.
///
/// If the next token is not a semicolon, this emits the specified diagnostic,
/// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
/// to the semicolon, consumes that extra token.
bool ExpectAndConsumeSemi(unsigned DiagID);
/// The kind of extra semi diagnostic to emit.
enum ExtraSemiKind {
OutsideFunction = 0,
InsideStruct = 1,
InstanceVariableList = 2,
AfterMemberFunctionDefinition = 3
};
/// Consume any extra semi-colons until the end of the line.
void ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST = TST_unspecified);
/// Return false if the next token is an identifier. An 'expected identifier'
/// error is emitted otherwise.
///
/// The parser tries to recover from the error by checking if the next token
/// is a C++ keyword when parsing Objective-C++. Return false if the recovery
/// was successful.
bool expectIdentifier();
public:
//===--------------------------------------------------------------------===//
// Scope manipulation
/// ParseScope - Introduces a new scope for parsing. The kind of
/// scope is determined by ScopeFlags. Objects of this type should
/// be created on the stack to coincide with the position where the
/// parser enters the new scope, and this object's constructor will
/// create that new scope. Similarly, once the object is destroyed
/// the parser will exit the scope.
class ParseScope {
Parser *Self;
ParseScope(const ParseScope &) = delete;
void operator=(const ParseScope &) = delete;
public:
// ParseScope - Construct a new object to manage a scope in the
// parser Self where the new Scope is created with the flags
// ScopeFlags, but only when we aren't about to enter a compound statement.
ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true,
bool BeforeCompoundStmt = false)
: Self(Self) {
if (EnteredScope && !BeforeCompoundStmt)
Self->EnterScope(ScopeFlags);
else {
if (BeforeCompoundStmt)
Self->incrementMSManglingNumber();
this->Self = nullptr;
}
}
// Exit - Exit the scope associated with this object now, rather
// than waiting until the object is destroyed.
void Exit() {
if (Self) {
Self->ExitScope();
Self = nullptr;
}
}
~ParseScope() {
Exit();
}
};
/// EnterScope - Start a new scope.
void EnterScope(unsigned ScopeFlags);
/// ExitScope - Pop a scope off the scope stack.
void ExitScope();
private:
/// RAII object used to modify the scope flags for the current scope.
class ParseScopeFlags {
Scope *CurScope;
unsigned OldFlags;
ParseScopeFlags(const ParseScopeFlags &) = delete;
void operator=(const ParseScopeFlags &) = delete;
public:
ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
~ParseScopeFlags();
};
//===--------------------------------------------------------------------===//
// Diagnostic Emission and Error recovery.
public:
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
DiagnosticBuilder Diag(unsigned DiagID) {
return Diag(Tok, DiagID);
}
private:
void SuggestParentheses(SourceLocation Loc, unsigned DK,
SourceRange ParenRange);
void CheckNestedObjCContexts(SourceLocation AtLoc);
public:
/// Control flags for SkipUntil functions.
enum SkipUntilFlags {
StopAtSemi = 1 << 0, ///< Stop skipping at semicolon
/// Stop skipping at specified token, but don't skip the token itself
StopBeforeMatch = 1 << 1,
StopAtCodeCompletion = 1 << 2 ///< Stop at code completion
};
friend constexpr SkipUntilFlags operator|(SkipUntilFlags L,
SkipUntilFlags R) {
return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
static_cast<unsigned>(R));
}
/// SkipUntil - Read tokens until we get to the specified token, then consume
/// it (unless StopBeforeMatch is specified). Because we cannot guarantee
/// that the token will ever occur, this skips to the next token, or to some
/// likely good stopping point. If Flags has StopAtSemi flag, skipping will
/// stop at a ';' character.
///
/// If SkipUntil finds the specified token, it returns true, otherwise it
/// returns false.
bool SkipUntil(tok::TokenKind T,
SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
return SkipUntil(llvm::makeArrayRef(T), Flags);
}
bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2,
SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
tok::TokenKind TokArray[] = {T1, T2};
return SkipUntil(TokArray, Flags);
}
bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
tok::TokenKind TokArray[] = {T1, T2, T3};
return SkipUntil(TokArray, Flags);
}
bool SkipUntil(ArrayRef<tok::TokenKind> Toks,
SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
/// SkipMalformedDecl - Read tokens until we get to some likely good stopping
/// point for skipping past a simple-declaration.
void SkipMalformedDecl();
private:
//===--------------------------------------------------------------------===//
// Lexing and parsing of C++ inline methods.
struct ParsingClass;
/// [class.mem]p1: "... the class is regarded as complete within
/// - function bodies
/// - default arguments
/// - exception-specifications (TODO: C++0x)
/// - and brace-or-equal-initializers for non-static data members
/// (including such things in nested classes)."
/// LateParsedDeclarations build the tree of those elements so they can
/// be parsed after parsing the top-level class.
class LateParsedDeclaration {
public:
virtual ~LateParsedDeclaration();
virtual void ParseLexedMethodDeclarations();
virtual void ParseLexedMemberInitializers();
virtual void ParseLexedMethodDefs();
virtual void ParseLexedAttributes();
};
/// Inner node of the LateParsedDeclaration tree that parses
/// all its members recursively.
class LateParsedClass : public LateParsedDeclaration {
public:
LateParsedClass(Parser *P, ParsingClass *C);
~LateParsedClass() override;
void ParseLexedMethodDeclarations() override;
void ParseLexedMemberInitializers() override;
void ParseLexedMethodDefs() override;
void ParseLexedAttributes() override;
private:
Parser *Self;
ParsingClass *Class;
};
/// Contains the lexed tokens of an attribute with arguments that
/// may reference member variables and so need to be parsed at the
/// end of the class declaration after parsing all other member
/// member declarations.
/// FIXME: Perhaps we should change the name of LateParsedDeclaration to
/// LateParsedTokens.
struct LateParsedAttribute : public LateParsedDeclaration {
Parser *Self;
CachedTokens Toks;
IdentifierInfo &AttrName;
IdentifierInfo *MacroII = nullptr;
SourceLocation AttrNameLoc;
SmallVector<Decl*, 2> Decls;
explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
SourceLocation Loc)
: Self(P), AttrName(Name), AttrNameLoc(Loc) {}
void ParseLexedAttributes() override;
void addDecl(Decl *D) { Decls.push_back(D); }
};
// A list of late-parsed attributes. Used by ParseGNUAttributes.
class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> {
public:
LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { }
bool parseSoon() { return ParseSoon; }
private:
bool ParseSoon; // Are we planning to parse these shortly after creation?
};
/// Contains the lexed tokens of a member function definition
/// which needs to be parsed at the end of the class declaration
/// after parsing all other member declarations.
struct LexedMethod : public LateParsedDeclaration {
Parser *Self;
Decl *D;
CachedTokens Toks;
/// Whether this member function had an associated template
/// scope. When true, D is a template declaration.
/// otherwise, it is a member function declaration.
bool TemplateScope;
explicit LexedMethod(Parser* P, Decl *MD)
: Self(P), D(MD), TemplateScope(false) {}
void ParseLexedMethodDefs() override;
};
/// LateParsedDefaultArgument - Keeps track of a parameter that may
/// have a default argument that cannot be parsed yet because it
/// occurs within a member function declaration inside the class
/// (C++ [class.mem]p2).
struct LateParsedDefaultArgument {
explicit LateParsedDefaultArgument(Decl *P,
std::unique_ptr<CachedTokens> Toks = nullptr)
: Param(P), Toks(std::move(Toks)) { }
/// Param - The parameter declaration for this parameter.
Decl *Param;
/// Toks - The sequence of tokens that comprises the default
/// argument expression, not including the '=' or the terminating
/// ')' or ','. This will be NULL for parameters that have no
/// default argument.
std::unique_ptr<CachedTokens> Toks;
};
/// LateParsedMethodDeclaration - A method declaration inside a class that
/// contains at least one entity whose parsing needs to be delayed
/// until the class itself is completely-defined, such as a default
/// argument (C++ [class.mem]p2).
struct LateParsedMethodDeclaration : public LateParsedDeclaration {
explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
: Self(P), Method(M), TemplateScope(false),
ExceptionSpecTokens(nullptr) {}
void ParseLexedMethodDeclarations() override;
Parser* Self;
/// Method - The method declaration.
Decl *Method;
/// Whether this member function had an associated template
/// scope. When true, D is a template declaration.
/// otherwise, it is a member function declaration.
bool TemplateScope;
/// DefaultArgs - Contains the parameters of the function and
/// their default arguments. At least one of the parameters will
/// have a default argument, but all of the parameters of the
/// method will be stored so that they can be reintroduced into
/// scope at the appropriate times.
SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
/// The set of tokens that make up an exception-specification that
/// has not yet been parsed.
CachedTokens *ExceptionSpecTokens;
};
/// LateParsedMemberInitializer - An initializer for a non-static class data
/// member whose parsing must to be delayed until the class is completely
/// defined (C++11 [class.mem]p2).
struct LateParsedMemberInitializer : public LateParsedDeclaration {
LateParsedMemberInitializer(Parser *P, Decl *FD)
: Self(P), Field(FD) { }
void ParseLexedMemberInitializers() override;
Parser *Self;
/// Field - The field declaration.
Decl *Field;
/// CachedTokens - The sequence of tokens that comprises the initializer,
/// including any leading '='.
CachedTokens Toks;
};
/// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
/// C++ class, its method declarations that contain parts that won't be
/// parsed until after the definition is completed (C++ [class.mem]p2),
/// the method declarations and possibly attached inline definitions
/// will be stored here with the tokens that will be parsed to create those
/// entities.
typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer;
/// Representation of a class that has been parsed, including
/// any member function declarations or definitions that need to be
/// parsed after the corresponding top-level class is complete.
struct ParsingClass {
ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
: TopLevelClass(TopLevelClass), TemplateScope(false),
IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { }
/// Whether this is a "top-level" class, meaning that it is
/// not nested within another class.
bool TopLevelClass : 1;
/// Whether this class had an associated template
/// scope. When true, TagOrTemplate is a template declaration;
/// otherwise, it is a tag declaration.
bool TemplateScope : 1;
/// Whether this class is an __interface.
bool IsInterface : 1;
/// The class or class template whose definition we are parsing.
Decl *TagOrTemplate;
/// LateParsedDeclarations - Method declarations, inline definitions and
/// nested classes that contain pieces whose parsing will be delayed until
/// the top-level class is fully defined.
LateParsedDeclarationsContainer LateParsedDeclarations;
};
/// The stack of classes that is currently being
/// parsed. Nested and local classes will be pushed onto this stack
/// when they are parsed, and removed afterward.
std::stack<ParsingClass *> ClassStack;
ParsingClass &getCurrentClass() {
assert(!ClassStack.empty() && "No lexed method stacks!");
return *ClassStack.top();
}
/// RAII object used to manage the parsing of a class definition.
class ParsingClassDefinition {
Parser &P;
bool Popped;
Sema::ParsingClassState State;
public:
ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
bool IsInterface)
: P(P), Popped(false),
State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
}
/// Pop this class of the stack.
void Pop() {
assert(!Popped && "Nested class has already been popped");
Popped = true;
P.PopParsingClass(State);
}
~ParsingClassDefinition() {
if (!Popped)
P.PopParsingClass(State);
}
};
/// Contains information about any template-specific
/// information that has been parsed prior to parsing declaration
/// specifiers.
struct ParsedTemplateInfo {
ParsedTemplateInfo()
: Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { }
ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
bool isSpecialization,
bool lastParameterListWasEmpty = false)
: Kind(isSpecialization? ExplicitSpecialization : Template),
TemplateParams(TemplateParams),
LastParameterListWasEmpty(lastParameterListWasEmpty) { }
explicit ParsedTemplateInfo(SourceLocation ExternLoc,
SourceLocation TemplateLoc)
: Kind(ExplicitInstantiation), TemplateParams(nullptr),
ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
LastParameterListWasEmpty(false){ }
/// The kind of template we are parsing.
enum {
/// We are not parsing a template at all.
NonTemplate = 0,
/// We are parsing a template declaration.
Template,
/// We are parsing an explicit specialization.
ExplicitSpecialization,
/// We are parsing an explicit instantiation.
ExplicitInstantiation
} Kind;
/// The template parameter lists, for template declarations
/// and explicit specializations.
TemplateParameterLists *TemplateParams;
/// The location of the 'extern' keyword, if any, for an explicit
/// instantiation
SourceLocation ExternLoc;
/// The location of the 'template' keyword, for an explicit
/// instantiation.
SourceLocation TemplateLoc;
/// Whether the last template parameter list was empty.
bool LastParameterListWasEmpty;
SourceRange getSourceRange() const LLVM_READONLY;
};
void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
static void LateTemplateParserCleanupCallback(void *P);
Sema::ParsingClassState
PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
void DeallocateParsedClasses(ParsingClass *Class);
void PopParsingClass(Sema::ParsingClassState);
enum CachedInitKind {
CIK_DefaultArgument,
CIK_DefaultInitializer
};
NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
ParsedAttributes &AccessAttrs,
ParsingDeclarator &D,
const ParsedTemplateInfo &TemplateInfo,
const VirtSpecifiers &VS,
SourceLocation PureSpecLoc);
void ParseCXXNonStaticMemberInitializer(Decl *VarD);
void ParseLexedAttributes(ParsingClass &Class);
void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
bool EnterScope, bool OnDefinition);
void ParseLexedAttribute(LateParsedAttribute &LA,
bool EnterScope, bool OnDefinition);
void ParseLexedMethodDeclarations(ParsingClass &Class);
void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
void ParseLexedMethodDefs(ParsingClass &Class);
void ParseLexedMethodDef(LexedMethod &LM);
void ParseLexedMemberInitializers(ParsingClass &Class);
void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK);
bool ConsumeAndStoreConditional(CachedTokens &Toks);
bool ConsumeAndStoreUntil(tok::TokenKind T1,
CachedTokens &Toks,
bool StopAtSemi = true,
bool ConsumeFinalToken = true) {
return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
}
bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
CachedTokens &Toks,
bool StopAtSemi = true,
bool ConsumeFinalToken = true);
//===--------------------------------------------------------------------===//
// C99 6.9: External Definitions.
struct ParsedAttributesWithRange : ParsedAttributes {
ParsedAttributesWithRange(AttributeFactory &factory)
: ParsedAttributes(factory) {}
void clear() {
ParsedAttributes::clear();
Range = SourceRange();
}
SourceRange Range;
};
struct ParsedAttributesViewWithRange : ParsedAttributesView {
ParsedAttributesViewWithRange() : ParsedAttributesView() {}
void clearListOnly() {
ParsedAttributesView::clearListOnly();
Range = SourceRange();
}
SourceRange Range;
};
DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
ParsingDeclSpec *DS = nullptr);
bool isDeclarationAfterDeclarator();
bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
ParsedAttributesWithRange &attrs,
ParsingDeclSpec *DS = nullptr,
AccessSpecifier AS = AS_none);
DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
ParsingDeclSpec &DS,
AccessSpecifier AS);
void SkipFunctionBody();
Decl *ParseFunctionDefinition(ParsingDeclarator &D,
const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
LateParsedAttrList *LateParsedAttrs = nullptr);
void ParseKNRParamDeclarations(Declarator &D);
// EndLoc, if non-NULL, is filled with the location of the last token of
// the simple-asm.
ExprResult ParseSimpleAsm(SourceLocation *EndLoc = nullptr);
ExprResult ParseAsmStringLiteral();
// Objective-C External Declarations
void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
DeclGroupPtrTy ParseObjCAtDirectives(ParsedAttributesWithRange &Attrs);
DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
ParsedAttributes &prefixAttrs);
class ObjCTypeParamListScope;
ObjCTypeParamList *parseObjCTypeParamList();
ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs(
ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
SmallVectorImpl<IdentifierLocPair> &protocolIdents,
SourceLocation &rAngleLoc, bool mayBeProtocolList = true);
void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
BalancedDelimiterTracker &T,
SmallVectorImpl<Decl *> &AllIvarDecls,
bool RBraceMissing);
void ParseObjCClassInstanceVariables(Decl *interfaceDecl,
tok::ObjCKeywordKind visibility,
SourceLocation atLoc);
bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P,
SmallVectorImpl<SourceLocation> &PLocs,
bool WarnOnDeclarations,
bool ForObjCContainer,
SourceLocation &LAngleLoc,
SourceLocation &EndProtoLoc,
bool consumeLastToken);
/// Parse the first angle-bracket-delimited clause for an
/// Objective-C object or object pointer type, which may be either
/// type arguments or protocol qualifiers.
void parseObjCTypeArgsOrProtocolQualifiers(
ParsedType baseType,
SourceLocation &typeArgsLAngleLoc,
SmallVectorImpl<ParsedType> &typeArgs,
SourceLocation &typeArgsRAngleLoc,
SourceLocation &protocolLAngleLoc,
SmallVectorImpl<Decl *> &protocols,
SmallVectorImpl<SourceLocation> &protocolLocs,
SourceLocation &protocolRAngleLoc,
bool consumeLastToken,
bool warnOnIncompleteProtocols);
/// Parse either Objective-C type arguments or protocol qualifiers; if the
/// former, also parse protocol qualifiers afterward.
void parseObjCTypeArgsAndProtocolQualifiers(
ParsedType baseType,
SourceLocation &typeArgsLAngleLoc,
SmallVectorImpl<ParsedType> &typeArgs,
SourceLocation &typeArgsRAngleLoc,
SourceLocation &protocolLAngleLoc,
SmallVectorImpl<Decl *> &protocols,
SmallVectorImpl<SourceLocation> &protocolLocs,
SourceLocation &protocolRAngleLoc,
bool consumeLastToken);
/// Parse a protocol qualifier type such as '<NSCopying>', which is
/// an anachronistic way of writing 'id<NSCopying>'.
TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc);
/// Parse Objective-C type arguments and protocol qualifiers, extending the
/// current type with the parsed result.
TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc,
ParsedType type,
bool consumeLastToken,
SourceLocation &endLoc);
void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
Decl *CDecl);
DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
ParsedAttributes &prefixAttrs);
struct ObjCImplParsingDataRAII {
Parser &P;
Decl *Dcl;
bool HasCFunction;
typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
LateParsedObjCMethodContainer LateParsedObjCMethods;
ObjCImplParsingDataRAII(Parser &parser, Decl *D)
: P(parser), Dcl(D), HasCFunction(false) {
P.CurParsedObjCImpl = this;
Finished = false;
}
~ObjCImplParsingDataRAII();
void finish(SourceRange AtEnd);
bool isFinished() const { return Finished; }
private:
bool Finished;
};
ObjCImplParsingDataRAII *CurParsedObjCImpl;
void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc,
ParsedAttributes &Attrs);
DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
// Definitions for Objective-c context sensitive keywords recognition.
enum ObjCTypeQual {
objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
objc_nonnull, objc_nullable, objc_null_unspecified,
objc_NumQuals
};
IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
bool isTokIdentifier_in() const;
ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx,
ParsedAttributes *ParamAttrs);
void ParseObjCMethodRequirement();
Decl *ParseObjCMethodPrototype(
tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
bool MethodDefinition = true);
Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
bool MethodDefinition=true);
void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
Decl *ParseObjCMethodDefinition();
public:
//===--------------------------------------------------------------------===//
// C99 6.5: Expressions.
/// TypeCastState - State whether an expression is or may be a type cast.
enum TypeCastState {
NotTypeCast = 0,
MaybeTypeCast,
IsTypeCast
};
ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast);
ExprResult ParseConstantExpressionInExprEvalContext(
TypeCastState isTypeCast = NotTypeCast);
ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast);
ExprResult ParseCaseExpression(SourceLocation CaseLoc);
ExprResult ParseConstraintExpression();
// Expr that doesn't include commas.
ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast);
ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
unsigned &NumLineToksConsumed,
bool IsUnevaluated);
private:
ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
prec::Level MinPrec);
ExprResult ParseCastExpression(bool isUnaryExpression,
bool isAddressOfOperand,
bool &NotCastExpr,
TypeCastState isTypeCast,
bool isVectorLiteral = false);
ExprResult ParseCastExpression(bool isUnaryExpression,
bool isAddressOfOperand = false,
TypeCastState isTypeCast = NotTypeCast,
bool isVectorLiteral = false);
/// Returns true if the next token cannot start an expression.
bool isNotExpressionStart();
/// Returns true if the next token would start a postfix-expression
/// suffix.
bool isPostfixExpressionSuffixStart() {
tok::TokenKind K = Tok.getKind();
return (K == tok::l_square || K == tok::l_paren ||
K == tok::period || K == tok::arrow ||
K == tok::plusplus || K == tok::minusminus);
}
bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less);
void checkPotentialAngleBracket(ExprResult &PotentialTemplateName);
bool checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc &,
const Token &OpToken);
bool checkPotentialAngleBracketDelimiter(const Token &OpToken) {
if (auto *Info = AngleBrackets.getCurrent(*this))
return checkPotentialAngleBracketDelimiter(*Info, OpToken);
return false;
}
ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
ExprResult ParseUnaryExprOrTypeTraitExpression();
ExprResult ParseBuiltinPrimaryExpression();
ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
bool &isCastExpr,
ParsedType &CastTy,
SourceRange &CastRange);
typedef SmallVector<Expr*, 20> ExprListTy;
typedef SmallVector<SourceLocation, 20> CommaLocsTy;
/// ParseExpressionList - Used for C/C++ (argument-)expression-list.
bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
SmallVectorImpl<SourceLocation> &CommaLocs,
llvm::function_ref<void()> ExpressionStarts =
llvm::function_ref<void()>());
/// ParseSimpleExpressionList - A simple comma-separated list of expressions,
/// used for misc language extensions.
bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
SmallVectorImpl<SourceLocation> &CommaLocs);
/// ParenParseOption - Control what ParseParenExpression will parse.
enum ParenParseOption {
SimpleExpr, // Only parse '(' expression ')'
FoldExpr, // Also allow fold-expression <anything>
CompoundStmt, // Also allow '(' compound-statement ')'
CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
CastExpr // Also allow '(' type-name ')' <anything>
};
ExprResult ParseParenExpression(ParenParseOption &ExprType,
bool stopIfCastExpr,
bool isTypeCast,
ParsedType &CastTy,
SourceLocation &RParenLoc);
ExprResult ParseCXXAmbiguousParenExpression(
ParenParseOption &ExprType, ParsedType &CastTy,
BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt);
ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
SourceLocation LParenLoc,
SourceLocation RParenLoc);
ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
ExprResult ParseGenericSelectionExpression();
ExprResult ParseObjCBoolLiteral();
ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T);
//===--------------------------------------------------------------------===//
// C++ Expressions
ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
Token &Replacement);
ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
bool areTokensAdjacent(const Token &A, const Token &B);
void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
bool EnteringContext, IdentifierInfo &II,
CXXScopeSpec &SS);
bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
ParsedType ObjectType,
bool EnteringContext,
bool *MayBePseudoDestructor = nullptr,
bool IsTypename = false,
IdentifierInfo **LastII = nullptr,
bool OnlyNamespace = false);
//===--------------------------------------------------------------------===//
// C++11 5.1.2: Lambda expressions
/// Result of tentatively parsing a lambda-introducer.
enum class LambdaIntroducerTentativeParse {
/// This appears to be a lambda-introducer, which has been fully parsed.
Success,
/// This is a lambda-introducer, but has not been fully parsed, and this
/// function needs to be called again to parse it.
Incomplete,
/// This is definitely an Objective-C message send expression, rather than
/// a lambda-introducer, attribute-specifier, or array designator.
MessageSend,
/// This is not a lambda-introducer.
Invalid,
};
// [...] () -> type {...}
ExprResult ParseLambdaExpression();
ExprResult TryParseLambdaExpression();
bool
ParseLambdaIntroducer(LambdaIntroducer &Intro,
LambdaIntroducerTentativeParse *Tentative = nullptr);
ExprResult ParseLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro);
//===--------------------------------------------------------------------===//
// C++ 5.2p1: C++ Casts
ExprResult ParseCXXCasts();
/// Parse a __builtin_bit_cast(T, E), used to implement C++2a std::bit_cast.
ExprResult ParseBuiltinBitCast();
//===--------------------------------------------------------------------===//
// C++ 5.2p1: C++ Type Identification
ExprResult ParseCXXTypeid();
//===--------------------------------------------------------------------===//
// C++ : Microsoft __uuidof Expression
ExprResult ParseCXXUuidof();
//===--------------------------------------------------------------------===//
// C++ 5.2.4: C++ Pseudo-Destructor Expressions
ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
tok::TokenKind OpKind,
CXXScopeSpec &SS,
ParsedType ObjectType);
//===--------------------------------------------------------------------===//
// C++ 9.3.2: C++ 'this' pointer
ExprResult ParseCXXThis();
//===--------------------------------------------------------------------===//
// C++ 15: C++ Throw Expression
ExprResult ParseThrowExpression();
ExceptionSpecificationType tryParseExceptionSpecification(
bool Delayed,
SourceRange &SpecificationRange,
SmallVectorImpl<ParsedType> &DynamicExceptions,
SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
ExprResult &NoexceptExpr,
CachedTokens *&ExceptionSpecTokens);
// EndLoc is filled with the location of the last token of the specification.
ExceptionSpecificationType ParseDynamicExceptionSpecification(
SourceRange &SpecificationRange,
SmallVectorImpl<ParsedType> &Exceptions,
SmallVectorImpl<SourceRange> &Ranges);
//===--------------------------------------------------------------------===//
// C++0x 8: Function declaration trailing-return-type
TypeResult ParseTrailingReturnType(SourceRange &Range,
bool MayBeFollowedByDirectInit);
//===--------------------------------------------------------------------===//
// C++ 2.13.5: C++ Boolean Literals
ExprResult ParseCXXBoolLiteral();
//===--------------------------------------------------------------------===//
// C++ 5.2.3: Explicit type conversion (functional notation)
ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
/// This should only be called when the current token is known to be part of
/// simple-type-specifier.
void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
//===--------------------------------------------------------------------===//
// C++ 5.3.4 and 5.3.5: C++ new and delete
bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
Declarator &D);
void ParseDirectNewDeclarator(Declarator &D);
ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
ExprResult ParseCXXDeleteExpression(bool UseGlobal,
SourceLocation Start);
//===--------------------------------------------------------------------===//
// C++ if/switch/while/for condition expression.
struct ForRangeInfo;
Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt,
SourceLocation Loc,
Sema::ConditionKind CK,
ForRangeInfo *FRI = nullptr);
//===--------------------------------------------------------------------===//
// C++ Coroutines
ExprResult ParseCoyieldExpression();
//===--------------------------------------------------------------------===//
// C99 6.7.8: Initialization.
/// ParseInitializer
/// initializer: [C99 6.7.8]
/// assignment-expression
/// '{' ...
ExprResult ParseInitializer() {
if (Tok.isNot(tok::l_brace))
return ParseAssignmentExpression();
return ParseBraceInitializer();
}
bool MayBeDesignationStart();
ExprResult ParseBraceInitializer();
ExprResult ParseInitializerWithPotentialDesignator();
//===--------------------------------------------------------------------===//
// clang Expressions
ExprResult ParseBlockLiteralExpression(); // ^{...}
//===--------------------------------------------------------------------===//
// Objective-C Expressions
ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
bool isSimpleObjCMessageExpression();
ExprResult ParseObjCMessageExpression();
ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
SourceLocation SuperLoc,
ParsedType ReceiverType,
Expr *ReceiverExpr);
ExprResult ParseAssignmentExprWithObjCMessageExprStart(
SourceLocation LBracloc, SourceLocation SuperLoc,
ParsedType ReceiverType, Expr *ReceiverExpr);
bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
//===--------------------------------------------------------------------===//
// C99 6.8: Statements and Blocks.
/// A SmallVector of statements, with stack size 32 (as that is the only one
/// used.)
typedef SmallVector<Stmt*, 32> StmtVector;
/// A SmallVector of expressions, with stack size 12 (the maximum used.)
typedef SmallVector<Expr*, 12> ExprVector;
/// A SmallVector of types.
typedef SmallVector<ParsedType, 12> TypeVector;
StmtResult
ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
ParsedStmtContext StmtCtx = ParsedStmtContext::SubStmt);
StmtResult ParseStatementOrDeclaration(
StmtVector &Stmts, ParsedStmtContext StmtCtx,
SourceLocation *TrailingElseLoc = nullptr);
StmtResult ParseStatementOrDeclarationAfterAttributes(
StmtVector &Stmts,
ParsedStmtContext StmtCtx,
SourceLocation *TrailingElseLoc,
ParsedAttributesWithRange &Attrs);
StmtResult ParseExprStatement(ParsedStmtContext StmtCtx);
StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs,
ParsedStmtContext StmtCtx);
StmtResult ParseCaseStatement(ParsedStmtContext StmtCtx,
bool MissingCase = false,
ExprResult Expr = ExprResult());
StmtResult ParseDefaultStatement(ParsedStmtContext StmtCtx);
StmtResult ParseCompoundStatement(bool isStmtExpr = false);
StmtResult ParseCompoundStatement(bool isStmtExpr,
unsigned ScopeFlags);
void ParseCompoundStatementLeadingPragmas();
bool ConsumeNullStmt(StmtVector &Stmts);
StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
bool ParseParenExprOrCondition(StmtResult *InitStmt,
Sema::ConditionResult &CondResult,
SourceLocation Loc,
Sema::ConditionKind CK);
StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
StmtResult ParseDoStatement();
StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
StmtResult ParseUPCForAllStatement(SourceLocation *TrailingElseLoc);
StmtResult ParseGotoStatement();
StmtResult ParseContinueStatement();
StmtResult ParseBreakStatement();
StmtResult ParseReturnStatement();
StmtResult ParseUPCNotifyStatement();
StmtResult ParseUPCWaitStatement();
StmtResult ParseUPCBarrierStatement();
StmtResult ParseUPCFenceStatement();
StmtResult ParseAsmStatement(bool &msAsm);
StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
StmtResult ParsePragmaLoopHint(StmtVector &Stmts,
ParsedStmtContext StmtCtx,
SourceLocation *TrailingElseLoc,
ParsedAttributesWithRange &Attrs);
/// Describes the behavior that should be taken for an __if_exists
/// block.
enum IfExistsBehavior {
/// Parse the block; this code is always used.
IEB_Parse,
/// Skip the block entirely; this code is never used.
IEB_Skip,
/// Parse the block as a dependent block, which may be used in
/// some template instantiations but not others.
IEB_Dependent
};
/// Describes the condition of a Microsoft __if_exists or
/// __if_not_exists block.
struct IfExistsCondition {
/// The location of the initial keyword.
SourceLocation KeywordLoc;
/// Whether this is an __if_exists block (rather than an
/// __if_not_exists block).
bool IsIfExists;
/// Nested-name-specifier preceding the name.
CXXScopeSpec SS;
/// The name we're looking for.
UnqualifiedId Name;
/// The behavior of this __if_exists or __if_not_exists block
/// should.
IfExistsBehavior Behavior;
};
bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
void ParseMicrosoftIfExistsExternalDeclaration();
void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
ParsedAttributes &AccessAttrs,
AccessSpecifier &CurAS);
bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
bool &InitExprsOk);
bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
SmallVectorImpl<Expr *> &Constraints,
SmallVectorImpl<Expr *> &Exprs);
//===--------------------------------------------------------------------===//
// C++ 6: Statements and Blocks
StmtResult ParseCXXTryBlock();
StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
StmtResult ParseCXXCatchBlock(bool FnCatch = false);
//===--------------------------------------------------------------------===//
// MS: SEH Statements and Blocks
StmtResult ParseSEHTryBlock();
StmtResult ParseSEHExceptBlock(SourceLocation Loc);
StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
StmtResult ParseSEHLeaveStatement();
//===--------------------------------------------------------------------===//
// Objective-C Statements
StmtResult ParseObjCAtStatement(SourceLocation atLoc,
ParsedStmtContext StmtCtx);
StmtResult ParseObjCTryStmt(SourceLocation atLoc);
StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
//===--------------------------------------------------------------------===//
// C99 6.7: Declarations.
/// A context for parsing declaration specifiers. TODO: flesh this
/// out, there are other significant restrictions on specifiers than
/// would be best implemented in the parser.
enum class DeclSpecContext {
DSC_normal, // normal context
DSC_class, // class context, enables 'friend'
DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
DSC_top_level, // top-level/namespace declaration context
DSC_template_param, // template parameter context
DSC_template_type_arg, // template type argument context
DSC_objc_method_result, // ObjC method result context, enables 'instancetype'
DSC_condition // condition declaration context
};
/// Is this a context in which we are parsing just a type-specifier (or
/// trailing-type-specifier)?
static bool isTypeSpecifier(DeclSpecContext DSC) {
switch (DSC) {
case DeclSpecContext::DSC_normal:
case DeclSpecContext::DSC_template_param:
case DeclSpecContext::DSC_class:
case DeclSpecContext::DSC_top_level:
case DeclSpecContext::DSC_objc_method_result:
case DeclSpecContext::DSC_condition:
return false;
case DeclSpecContext::DSC_template_type_arg:
case DeclSpecContext::DSC_type_specifier:
case DeclSpecContext::DSC_trailing:
case DeclSpecContext::DSC_alias_declaration:
return true;
}
llvm_unreachable("Missing DeclSpecContext case");
}
/// Is this a context in which we can perform class template argument
/// deduction?
static bool isClassTemplateDeductionContext(DeclSpecContext DSC) {
switch (DSC) {
case DeclSpecContext::DSC_normal:
case DeclSpecContext::DSC_template_param:
case DeclSpecContext::DSC_class:
case DeclSpecContext::DSC_top_level:
case DeclSpecContext::DSC_condition:
case DeclSpecContext::DSC_type_specifier:
return true;
case DeclSpecContext::DSC_objc_method_result:
case DeclSpecContext::DSC_template_type_arg:
case DeclSpecContext::DSC_trailing:
case DeclSpecContext::DSC_alias_declaration:
return false;
}
llvm_unreachable("Missing DeclSpecContext case");
}
/// Information on a C++0x for-range-initializer found while parsing a
/// declaration which turns out to be a for-range-declaration.
struct ForRangeInit {
SourceLocation ColonLoc;
ExprResult RangeExpr;
bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
};
struct ForRangeInfo : ForRangeInit {
StmtResult LoopVar;
};
DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context,
SourceLocation &DeclEnd,
ParsedAttributesWithRange &attrs);
DeclGroupPtrTy ParseSimpleDeclaration(DeclaratorContext Context,
SourceLocation &DeclEnd,
ParsedAttributesWithRange &attrs,
bool RequireSemi,
ForRangeInit *FRI = nullptr);
bool MightBeDeclarator(DeclaratorContext Context);
DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context,
SourceLocation *DeclEnd = nullptr,
ForRangeInit *FRI = nullptr);
Decl *ParseDeclarationAfterDeclarator(Declarator &D,
const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
bool ParseAsmAttributesAfterDeclarator(Declarator &D);
Decl *ParseDeclarationAfterDeclaratorAndAttributes(
Declarator &D,
const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
ForRangeInit *FRI = nullptr);
Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
/// When in code-completion, skip parsing of the function/method body
/// unless the body contains the code-completion point.
///
/// \returns true if the function body was skipped.
bool trySkippingFunctionBody();
bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
const ParsedTemplateInfo &TemplateInfo,
AccessSpecifier AS, DeclSpecContext DSC,
ParsedAttributesWithRange &Attrs);
DeclSpecContext
getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context);
void ParseDeclarationSpecifiers(
DeclSpec &DS,
const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
AccessSpecifier AS = AS_none,
DeclSpecContext DSC = DeclSpecContext::DSC_normal,
LateParsedAttrList *LateAttrs = nullptr);
bool DiagnoseMissingSemiAfterTagDefinition(
DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext,
LateParsedAttrList *LateAttrs = nullptr);
void ParseSpecifierQualifierList(
DeclSpec &DS, AccessSpecifier AS = AS_none,
DeclSpecContext DSC = DeclSpecContext::DSC_normal);
void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
DeclaratorContext Context);
void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
const ParsedTemplateInfo &TemplateInfo,
AccessSpecifier AS, DeclSpecContext DSC);
void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
Decl *TagDecl);
void ParseStructDeclaration(
ParsingDeclSpec &DS,
llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback);
bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
bool isTypeSpecifierQualifier();
/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
/// is definitely a type-specifier. Return false if it isn't part of a type
/// specifier or if we're not sure.
bool isKnownToBeTypeSpecifier(const Token &Tok) const;
/// Return true if we know that we are definitely looking at a
/// decl-specifier, and isn't part of an expression such as a function-style
/// cast. Return false if it's no a decl-specifier, or we're not sure.
bool isKnownToBeDeclarationSpecifier() {
if (getLangOpts().CPlusPlus)
return isCXXDeclarationSpecifier() == TPResult::True;
return isDeclarationSpecifier(true);
}
/// isDeclarationStatement - Disambiguates between a declaration or an
/// expression statement, when parsing function bodies.
/// Returns true for declaration, false for expression.
bool isDeclarationStatement() {
if (getLangOpts().CPlusPlus)
return isCXXDeclarationStatement();
return isDeclarationSpecifier(true);
}
/// isForInitDeclaration - Disambiguates between a declaration or an
/// expression in the context of the C 'clause-1' or the C++
// 'for-init-statement' part of a 'for' statement.
/// Returns true for declaration, false for expression.
bool isForInitDeclaration() {
if (getLangOpts().OpenMP)
Actions.startOpenMPLoop();
if (getLangOpts().CPlusPlus)
return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
return isDeclarationSpecifier(true);
}
/// Determine whether this is a C++1z for-range-identifier.
bool isForRangeIdentifier();
/// Determine whether we are currently at the start of an Objective-C
/// class message that appears to be missing the open bracket '['.
bool isStartOfObjCClassMessageMissingOpenBracket();
/// Starting with a scope specifier, identifier, or
/// template-id that refers to the current class, determine whether
/// this is a constructor declarator.
bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false);
/// Specifies the context in which type-id/expression
/// disambiguation will occur.
enum TentativeCXXTypeIdContext {
TypeIdInParens,
TypeIdUnambiguous,
TypeIdAsTemplateArgument
};
/// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
/// whether the parens contain an expression or a type-id.
/// Returns true for a type-id and false for an expression.
bool isTypeIdInParens(bool &isAmbiguous) {
if (getLangOpts().CPlusPlus)
return isCXXTypeId(TypeIdInParens, isAmbiguous);
isAmbiguous = false;
return isTypeSpecifierQualifier();
}
bool isTypeIdInParens() {
bool isAmbiguous;
return isTypeIdInParens(isAmbiguous);
}
/// Checks if the current tokens form type-id or expression.
/// It is similar to isTypeIdInParens but does not suppose that type-id
/// is in parenthesis.
bool isTypeIdUnambiguously() {
bool IsAmbiguous;
if (getLangOpts().CPlusPlus)
return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous);
return isTypeSpecifierQualifier();
}
/// isCXXDeclarationStatement - C++-specialized function that disambiguates
/// between a declaration or an expression statement, when parsing function
/// bodies. Returns true for declaration, false for expression.
bool isCXXDeclarationStatement();
/// isCXXSimpleDeclaration - C++-specialized function that disambiguates
/// between a simple-declaration or an expression-statement.
/// If during the disambiguation process a parsing error is encountered,
/// the function returns true to let the declaration parsing code handle it.
/// Returns false if the statement is disambiguated as expression.
bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
/// isCXXFunctionDeclarator - Disambiguates between a function declarator or
/// a constructor-style initializer, when parsing declaration statements.
/// Returns true for function declarator and false for constructor-style
/// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
/// might be a constructor-style initializer.
/// If during the disambiguation process a parsing error is encountered,
/// the function returns true to let the declaration parsing code handle it.
bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr);
struct ConditionDeclarationOrInitStatementState;
enum class ConditionOrInitStatement {
Expression, ///< Disambiguated as an expression (either kind).
ConditionDecl, ///< Disambiguated as the declaration form of condition.
InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement.
ForRangeDecl, ///< Disambiguated as a for-range declaration.
Error ///< Can't be any of the above!
};
/// Disambiguates between the different kinds of things that can happen
/// after 'if (' or 'switch ('. This could be one of two different kinds of
/// declaration (depending on whether there is a ';' later) or an expression.
ConditionOrInitStatement
isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt,
bool CanBeForRangeDecl);
bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
bool isAmbiguous;
return isCXXTypeId(Context, isAmbiguous);
}
/// TPResult - Used as the result value for functions whose purpose is to
/// disambiguate C++ constructs by "tentatively parsing" them.
enum class TPResult {
True, False, Ambiguous, Error
};
/// Based only on the given token kind, determine whether we know that
/// we're at the start of an expression or a type-specifier-seq (which may
/// be an expression, in C++).
///
/// This routine does not attempt to resolve any of the trick cases, e.g.,
/// those involving lookup of identifiers.
///
/// \returns \c TPR_true if this token starts an expression, \c TPR_false if
/// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
/// tell.
TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
/// isCXXDeclarationSpecifier - Returns TPResult::True if it is a
/// declaration specifier, TPResult::False if it is not,
/// TPResult::Ambiguous if it could be either a decl-specifier or a
/// function-style cast, and TPResult::Error if a parsing error was
/// encountered. If it could be a braced C++11 function-style cast, returns
/// BracedCastResult.
/// Doesn't consume tokens.
TPResult
isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False,
bool *InvalidAsDeclSpec = nullptr);
/// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
/// \c TPResult::Ambiguous, determine whether the decl-specifier would be
/// a type-specifier other than a cv-qualifier.
bool isCXXDeclarationSpecifierAType();
/// Determine whether the current token sequence might be
/// '<' template-argument-list '>'
/// rather than a less-than expression.
TPResult isTemplateArgumentList(unsigned TokensToSkip);
/// Determine whether an identifier has been tentatively declared as a
/// non-type. Such tentative declarations should not be found to name a type
/// during a tentative parse, but also should not be annotated as a non-type.
bool isTentativelyDeclared(IdentifierInfo *II);
// "Tentative parsing" functions, used for disambiguation. If a parsing error
// is encountered they will return TPResult::Error.
// Returning TPResult::True/False indicates that the ambiguity was
// resolved and tentative parsing may stop. TPResult::Ambiguous indicates
// that more tentative parsing is necessary for disambiguation.
// They all consume tokens, so backtracking should be used after calling them.
TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
TPResult TryParseTypeofSpecifier();
TPResult TryParseProtocolQualifiers();
TPResult TryParsePtrOperatorSeq();
TPResult TryParseOperatorId();
TPResult TryParseInitDeclaratorList();
TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true,
bool mayHaveDirectInit = false);
TPResult
TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr,
bool VersusTemplateArg = false);
TPResult TryParseFunctionDeclarator();
TPResult TryParseBracketDeclarator();
TPResult TryConsumeDeclarationSpecifier();
public:
TypeResult ParseTypeName(SourceRange *Range = nullptr,
DeclaratorContext Context
= DeclaratorContext::TypeNameContext,
AccessSpecifier AS = AS_none,
Decl **OwnedType = nullptr,
ParsedAttributes *Attrs = nullptr);
private:
void ParseBlockId(SourceLocation CaretLoc);
/// Are [[]] attributes enabled?
bool standardAttributesAllowed() const {
const LangOptions &LO = getLangOpts();
return LO.DoubleSquareBracketAttributes;
}
// Check for the start of an attribute-specifier-seq in a context where an
// attribute is not allowed.
bool CheckProhibitedCXX11Attribute() {
assert(Tok.is(tok::l_square));
if (!standardAttributesAllowed() || NextToken().isNot(tok::l_square))
return false;
return DiagnoseProhibitedCXX11Attribute();
}
bool DiagnoseProhibitedCXX11Attribute();
void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
SourceLocation CorrectLocation) {
if (!standardAttributesAllowed())
return;
if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
Tok.isNot(tok::kw_alignas))
return;
DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
}
void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
SourceLocation CorrectLocation);
void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
DeclSpec &DS, Sema::TagUseKind TUK);
// FixItLoc = possible correct location for the attributes
void ProhibitAttributes(ParsedAttributesWithRange &Attrs,
SourceLocation FixItLoc = SourceLocation()) {
if (Attrs.Range.isInvalid())
return;
DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc);
Attrs.clear();
}
void ProhibitAttributes(ParsedAttributesViewWithRange &Attrs,
SourceLocation FixItLoc = SourceLocation()) {
if (Attrs.Range.isInvalid())
return;
DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc);
Attrs.clearListOnly();
}
void DiagnoseProhibitedAttributes(const SourceRange &Range,
SourceLocation FixItLoc);
// Forbid C++11 and C2x attributes that appear on certain syntactic locations
// which standard permits but we don't supported yet, for example, attributes
// appertain to decl specifiers.
void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
unsigned DiagID);
/// Skip C++11 and C2x attributes and return the end location of the
/// last one.
/// \returns SourceLocation() if there are no attributes.
SourceLocation SkipCXX11Attributes();
/// Diagnose and skip C++11 and C2x attributes that appear in syntactic
/// locations where attributes are not allowed.
void DiagnoseAndSkipCXX11Attributes();
/// Parses syntax-generic attribute arguments for attributes which are
/// known to the implementation, and adds them to the given ParsedAttributes
/// list with the given attribute syntax. Returns the number of arguments
/// parsed for the attribute.
unsigned
ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc,
IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
void MaybeParseGNUAttributes(Declarator &D,
LateParsedAttrList *LateAttrs = nullptr) {
if (Tok.is(tok::kw___attribute)) {
ParsedAttributes attrs(AttrFactory);
SourceLocation endLoc;
ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D);
D.takeAttributes(attrs, endLoc);
}
}
void MaybeParseGNUAttributes(ParsedAttributes &attrs,
SourceLocation *endLoc = nullptr,
LateParsedAttrList *LateAttrs = nullptr) {
if (Tok.is(tok::kw___attribute))
ParseGNUAttributes(attrs, endLoc, LateAttrs);
}
void ParseGNUAttributes(ParsedAttributes &attrs,
SourceLocation *endLoc = nullptr,
LateParsedAttrList *LateAttrs = nullptr,
Declarator *D = nullptr);
void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc,
IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax, Declarator *D);
IdentifierLoc *ParseIdentifierLoc();
unsigned
ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc,
IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
void MaybeParseCXX11Attributes(Declarator &D) {
if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
ParsedAttributesWithRange attrs(AttrFactory);
SourceLocation endLoc;
ParseCXX11Attributes(attrs, &endLoc);
D.takeAttributes(attrs, endLoc);
}
}
void MaybeParseCXX11Attributes(ParsedAttributes &attrs,
SourceLocation *endLoc = nullptr) {
if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
ParsedAttributesWithRange attrsWithRange(AttrFactory);
ParseCXX11Attributes(attrsWithRange, endLoc);
attrs.takeAllFrom(attrsWithRange);
}
}
void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs,
SourceLocation *endLoc = nullptr,
bool OuterMightBeMessageSend = false) {
if (standardAttributesAllowed() &&
isCXX11AttributeSpecifier(false, OuterMightBeMessageSend))
ParseCXX11Attributes(attrs, endLoc);
}
void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
SourceLocation *EndLoc = nullptr);
void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
SourceLocation *EndLoc = nullptr);
/// Parses a C++11 (or C2x)-style attribute argument list. Returns true
/// if this results in adding an attribute to the ParsedAttributes list.
bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc);
IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
SourceLocation *endLoc = nullptr) {
if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
ParseMicrosoftAttributes(attrs, endLoc);
}
void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs);
void ParseMicrosoftAttributes(ParsedAttributes &attrs,
SourceLocation *endLoc = nullptr);
void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
SourceLocation *End = nullptr) {
const auto &LO = getLangOpts();
if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec))
ParseMicrosoftDeclSpecs(Attrs, End);
}
void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
SourceLocation *End = nullptr);
bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs);
void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
SourceLocation SkipExtendedMicrosoftTypeAttributes();
void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
/// Parses opencl_unroll_hint attribute if language is OpenCL v2.0
/// or higher.
/// \return false if error happens.
bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
if (getLangOpts().OpenCL)
return ParseOpenCLUnrollHintAttribute(Attrs);
return true;
}
/// Parses opencl_unroll_hint attribute.
/// \return false if error happens.
bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs);
void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
VersionTuple ParseVersionTuple(SourceRange &Range);
void ParseAvailabilityAttribute(IdentifierInfo &Availability,
SourceLocation AvailabilityLoc,
ParsedAttributes &attrs,
SourceLocation *endLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
Optional<AvailabilitySpec> ParseAvailabilitySpec();
ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol,
SourceLocation Loc,
ParsedAttributes &Attrs,
SourceLocation *EndLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
SourceLocation ObjCBridgeRelatedLoc,
ParsedAttributes &attrs,
SourceLocation *endLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs,
SourceLocation *EndLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
void
ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
SourceLocation AttrNameLoc, ParsedAttributes &Attrs,
SourceLocation *EndLoc, IdentifierInfo *ScopeName,
SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax);
void ParseTypeofSpecifier(DeclSpec &DS);
SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
SourceLocation StartLoc,
SourceLocation EndLoc);
void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
void ParseAtomicSpecifier(DeclSpec &DS);
ExprResult ParseAlignArgument(SourceLocation Start,
SourceLocation &EllipsisLoc);
void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
SourceLocation *endLoc = nullptr);
VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
return isCXX11VirtSpecifier(Tok);
}
void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
SourceLocation FriendLoc);
bool isCXX11FinalKeyword() const;
/// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
/// enter a new C++ declarator scope and exit it when the function is
/// finished.
class DeclaratorScopeObj {
Parser &P;
CXXScopeSpec &SS;
bool EnteredScope;
bool CreatedScope;
public:
DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
: P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
void EnterDeclaratorScope() {
assert(!EnteredScope && "Already entered the scope!");
assert(SS.isSet() && "C++ scope was not set!");
CreatedScope = true;
P.EnterScope(0); // Not a decl scope.
if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
EnteredScope = true;
}
~DeclaratorScopeObj() {
if (EnteredScope) {
assert(SS.isSet() && "C++ scope was cleared ?");
P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
}
if (CreatedScope)
P.ExitScope();
}
};
/// ParseDeclarator - Parse and verify a newly-initialized declarator.
void ParseDeclarator(Declarator &D);
/// A function that parses a variant of direct-declarator.
typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
void ParseDeclaratorInternal(Declarator &D,
DirectDeclParseFunction DirectDeclParser);
enum AttrRequirements {
AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
AR_GNUAttributesParsed = 1 << 1,
AR_CXX11AttributesParsed = 1 << 2,
AR_DeclspecAttributesParsed = 1 << 3,
AR_AllAttributesParsed = AR_GNUAttributesParsed |
AR_CXX11AttributesParsed |
AR_DeclspecAttributesParsed,
AR_VendorAttributesParsed = AR_GNUAttributesParsed |
AR_DeclspecAttributesParsed
};
void ParseTypeQualifierListOpt(
DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed,
bool AtomicAllowed = true, bool IdentifierRequired = false,
Optional<llvm::function_ref<void()>> CodeCompletionHandler = None);
void ParseDirectDeclarator(Declarator &D);
void ParseDecompositionDeclarator(Declarator &D);
void ParseParenDeclarator(Declarator &D);
void ParseFunctionDeclarator(Declarator &D,
ParsedAttributes &attrs,
BalancedDelimiterTracker &Tracker,
bool IsAmbiguous,
bool RequiresArg = false);
bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
SourceLocation &RefQualifierLoc);
bool isFunctionDeclaratorIdentifierList();
void ParseFunctionDeclaratorIdentifierList(
Declarator &D,
SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
void ParseParameterDeclarationClause(
Declarator &D,
ParsedAttributes &attrs,
SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
SourceLocation &EllipsisLoc);
void ParseBracketDeclarator(Declarator &D);
void ParseMisplacedBracketDeclarator(Declarator &D);
//===--------------------------------------------------------------------===//
// C++ 7: Declarations [dcl.dcl]
/// The kind of attribute specifier we have found.
enum CXX11AttributeKind {
/// This is not an attribute specifier.
CAK_NotAttributeSpecifier,
/// This should be treated as an attribute-specifier.
CAK_AttributeSpecifier,
/// The next tokens are '[[', but this is not an attribute-specifier. This
/// is ill-formed by C++11 [dcl.attr.grammar]p6.
CAK_InvalidAttributeSpecifier
};
CXX11AttributeKind
isCXX11AttributeSpecifier(bool Disambiguate = false,
bool OuterMightBeMessageSend = false);
void DiagnoseUnexpectedNamespace(NamedDecl *Context);
DeclGroupPtrTy ParseNamespace(DeclaratorContext Context,
SourceLocation &DeclEnd,
SourceLocation InlineLoc = SourceLocation());
struct InnerNamespaceInfo {
SourceLocation NamespaceLoc;
SourceLocation InlineLoc;
SourceLocation IdentLoc;
IdentifierInfo *Ident;
};
using InnerNamespaceInfoList = llvm::SmallVector<InnerNamespaceInfo, 4>;
void ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs,
unsigned int index, SourceLocation &InlineLoc,
ParsedAttributes &attrs,
BalancedDelimiterTracker &Tracker);
Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context);
Decl *ParseExportDeclaration();
DeclGroupPtrTy ParseUsingDirectiveOrDeclaration(
DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs);
Decl *ParseUsingDirective(DeclaratorContext Context,
SourceLocation UsingLoc,
SourceLocation &DeclEnd,
ParsedAttributes &attrs);
struct UsingDeclarator {
SourceLocation TypenameLoc;
CXXScopeSpec SS;
UnqualifiedId Name;
SourceLocation EllipsisLoc;
void clear() {
TypenameLoc = EllipsisLoc = SourceLocation();
SS.clear();
Name.clear();
}
};
bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D);
DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context,
const ParsedTemplateInfo &TemplateInfo,
SourceLocation UsingLoc,
SourceLocation &DeclEnd,
AccessSpecifier AS = AS_none);
Decl *ParseAliasDeclarationAfterDeclarator(
const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
ParsedAttributes &Attrs, Decl **OwnedType = nullptr);
Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
SourceLocation AliasLoc, IdentifierInfo *Alias,
SourceLocation &DeclEnd);
//===--------------------------------------------------------------------===//
// C++ 9: classes [class] and C structs/unions.
bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo,
AccessSpecifier AS, bool EnteringContext,
DeclSpecContext DSC,
ParsedAttributesWithRange &Attributes);
void SkipCXXMemberSpecification(SourceLocation StartLoc,
SourceLocation AttrFixitLoc,
unsigned TagType,
Decl *TagDecl);
void ParseCXXMemberSpecification(SourceLocation StartLoc,
SourceLocation AttrFixitLoc,
ParsedAttributesWithRange &Attrs,
unsigned TagType,
Decl *TagDecl);
ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
SourceLocation &EqualLoc);
bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
VirtSpecifiers &VS,
ExprResult &BitfieldSize,
LateParsedAttrList &LateAttrs);
void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
VirtSpecifiers &VS);
DeclGroupPtrTy ParseCXXClassMemberDeclaration(
AccessSpecifier AS, ParsedAttributes &Attr,
const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas(
AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
DeclSpec::TST TagType, Decl *Tag);
void ParseConstructorInitializer(Decl *ConstructorDecl);
MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
Decl *ThisDecl);
//===--------------------------------------------------------------------===//
// C++ 10: Derived classes [class.derived]
TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
SourceLocation &EndLocation);
void ParseBaseClause(Decl *ClassDecl);
BaseResult ParseBaseSpecifier(Decl *ClassDecl);
AccessSpecifier getAccessSpecifierIfPresent() const;
bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
IdentifierInfo *Name,
SourceLocation NameLoc,
bool EnteringContext,
ParsedType ObjectType,
UnqualifiedId &Id,
bool AssumeTemplateId);
bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
ParsedType ObjectType,
UnqualifiedId &Result);
//===--------------------------------------------------------------------===//
// OpenMP: Directives and clauses.
/// Parse clauses for '#pragma omp declare simd'.
DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
CachedTokens &Toks,
SourceLocation Loc);
/// Parse clauses for '#pragma omp declare target'.
DeclGroupPtrTy ParseOMPDeclareTargetClauses();
/// Parse '#pragma omp end declare target'.
void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind DKind,
SourceLocation Loc);
/// Parses declarative OpenMP directives.
DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
AccessSpecifier &AS, ParsedAttributesWithRange &Attrs,
DeclSpec::TST TagType = DeclSpec::TST_unspecified,
Decl *TagDecl = nullptr);
/// Parse 'omp declare reduction' construct.
DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS);
/// Parses initializer for provided omp_priv declaration inside the reduction
/// initializer.
void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm);
/// Parses 'omp declare mapper' directive.
DeclGroupPtrTy ParseOpenMPDeclareMapperDirective(AccessSpecifier AS);
/// Parses variable declaration in 'omp declare mapper' directive.
TypeResult parseOpenMPDeclareMapperVarDecl(SourceRange &Range,
DeclarationName &Name,
AccessSpecifier AS = AS_none);
/// Parses simple list of variables.
///
/// \param Kind Kind of the directive.
/// \param Callback Callback function to be called for the list elements.
/// \param AllowScopeSpecifier true, if the variables can have fully
/// qualified names.
///
bool ParseOpenMPSimpleVarList(
OpenMPDirectiveKind Kind,
const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
Callback,
bool AllowScopeSpecifier);
/// Parses declarative or executable directive.
///
/// \param StmtCtx The context in which we're parsing the directive.
StmtResult
ParseOpenMPDeclarativeOrExecutableDirective(ParsedStmtContext StmtCtx);
/// Parses clause of kind \a CKind for directive of a kind \a Kind.
///
/// \param DKind Kind of current directive.
/// \param CKind Kind of current clause.
/// \param FirstClause true, if this is the first clause of a kind \a CKind
/// in current directive.
///
OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
OpenMPClauseKind CKind, bool FirstClause);
/// Parses clause with a single expression of a kind \a Kind.
///
/// \param Kind Kind of current clause.
/// \param ParseOnly true to skip the clause's semantic actions and return
/// nullptr.
///
OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind,
bool ParseOnly);
/// Parses simple clause of a kind \a Kind.
///
/// \param Kind Kind of current clause.
/// \param ParseOnly true to skip the clause's semantic actions and return
/// nullptr.
///
OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly);
/// Parses clause with a single expression and an additional argument
/// of a kind \a Kind.
///
/// \param Kind Kind of current clause.
/// \param ParseOnly true to skip the clause's semantic actions and return
/// nullptr.
///
OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind,
bool ParseOnly);
/// Parses clause without any additional arguments.
///
/// \param Kind Kind of current clause.
/// \param ParseOnly true to skip the clause's semantic actions and return
/// nullptr.
///
OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false);
/// Parses clause with the list of variables of a kind \a Kind.
///
/// \param Kind Kind of current clause.
/// \param ParseOnly true to skip the clause's semantic actions and return
/// nullptr.
///
OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
OpenMPClauseKind Kind, bool ParseOnly);
public:
/// Parses simple expression in parens for single-expression clauses of OpenMP
/// constructs.
/// \param RLoc Returned location of right paren.
ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc);
/// Data used for parsing list of variables in OpenMP clauses.
struct OpenMPVarListDataTy {
Expr *TailExpr = nullptr;
SourceLocation ColonLoc;
SourceLocation RLoc;
CXXScopeSpec ReductionOrMapperIdScopeSpec;
DeclarationNameInfo ReductionOrMapperId;
OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown;
OpenMPLinearClauseKind LinKind = OMPC_LINEAR_val;
SmallVector<OpenMPMapModifierKind, OMPMapClause::NumberOfModifiers>
MapTypeModifiers;
SmallVector<SourceLocation, OMPMapClause::NumberOfModifiers>
MapTypeModifiersLoc;
OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
bool IsMapTypeImplicit = false;
SourceLocation DepLinMapLoc;
};
/// Parses clauses with list.
bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind,
SmallVectorImpl<Expr *> &Vars,
OpenMPVarListDataTy &Data);
bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
bool AllowDestructorName,
bool AllowConstructorName,
bool AllowDeductionGuide,
ParsedType ObjectType,
SourceLocation *TemplateKWLoc,
UnqualifiedId &Result);
/// Parses the mapper modifier in map, to, and from clauses.
bool parseMapperModifier(OpenMPVarListDataTy &Data);
/// Parses map-type-modifiers in map clause.
/// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list)
/// where, map-type-modifier ::= always | close | mapper(mapper-identifier)
bool parseMapTypeModifiers(OpenMPVarListDataTy &Data);
private:
//===--------------------------------------------------------------------===//
// C++ 14: Templates [temp]
// C++ 14.1: Template Parameters [temp.param]
Decl *ParseDeclarationStartingWithTemplate(DeclaratorContext Context,
SourceLocation &DeclEnd,
ParsedAttributes &AccessAttrs,
AccessSpecifier AS = AS_none);
Decl *ParseTemplateDeclarationOrSpecialization(DeclaratorContext Context,
SourceLocation &DeclEnd,
ParsedAttributes &AccessAttrs,
AccessSpecifier AS);
Decl *ParseSingleDeclarationAfterTemplate(
DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd,
ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none);
bool ParseTemplateParameters(unsigned Depth,
SmallVectorImpl<NamedDecl *> &TemplateParams,
SourceLocation &LAngleLoc,
SourceLocation &RAngleLoc);
bool ParseTemplateParameterList(unsigned Depth,
SmallVectorImpl<NamedDecl*> &TemplateParams);
bool isStartOfTemplateTypeParameter();
NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position);
NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position);
NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
SourceLocation CorrectLoc,
bool AlreadyHasEllipsis,
bool IdentifierHasName);
void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
Declarator &D);
// C++ 14.3: Template arguments [temp.arg]
typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
bool ConsumeLastToken,
bool ObjCGenericList);
bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
SourceLocation &LAngleLoc,
TemplateArgList &TemplateArgs,
SourceLocation &RAngleLoc);
bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &TemplateName,
bool AllowTypeAnnotation = true);
void AnnotateTemplateIdTokenAsType(bool IsClassName = false);
bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
ParsedTemplateArgument ParseTemplateTemplateArgument();
ParsedTemplateArgument ParseTemplateArgument();
Decl *ParseExplicitInstantiation(DeclaratorContext Context,
SourceLocation ExternLoc,
SourceLocation TemplateLoc,
SourceLocation &DeclEnd,
ParsedAttributes &AccessAttrs,
AccessSpecifier AS = AS_none);
// C++2a: Template, concept definition [temp]
Decl *
ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo,
SourceLocation &DeclEnd);
//===--------------------------------------------------------------------===//
// Modules
DeclGroupPtrTy ParseModuleDecl(bool IsFirstDecl);
Decl *ParseModuleImport(SourceLocation AtLoc);
bool parseMisplacedModuleImport();
bool tryParseMisplacedModuleImport() {
tok::TokenKind Kind = Tok.getKind();
if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end ||
Kind == tok::annot_module_include)
return parseMisplacedModuleImport();
return false;
}
bool ParseModuleName(
SourceLocation UseLoc,
SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
bool IsImport);
//===--------------------------------------------------------------------===//
// C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
ExprResult ParseTypeTrait();
//===--------------------------------------------------------------------===//
// Embarcadero: Arary and Expression Traits
ExprResult ParseArrayTypeTrait();
ExprResult ParseExpressionTrait();
//===--------------------------------------------------------------------===//
// Preprocessor code-completion pass-through
void CodeCompleteDirective(bool InConditional) override;
void CodeCompleteInConditionalExclusion() override;
void CodeCompleteMacroName(bool IsDefinition) override;
void CodeCompletePreprocessorExpression() override;
void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
unsigned ArgumentIndex) override;
void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) override;
void CodeCompleteNaturalLanguage() override;
};
} // end namespace clang
#endif
|
omp-for-dynamic.c | #include <stdio.h>
#include <stdlib.h>
#include <omp.h>
int main() {
int i,j;
#pragma omp parallel for schedule(static)
for(i = 0; i < 11; i++)
{
printf("Static Hello World %d\n", i);
}
#pragma omp parallel for schedule(static, 1)
for(i = 0; i < 11; i++)
{
printf("Static1 Hello World %d\n", i);
}
#pragma omp parallel for schedule(static, 2)
for(i = 0; i < 11; i++)
{
printf("Static2 Hello World %d\n", i);
}
printf("\nDynamic loop\n");
#pragma omp parallel for schedule(dynamic)
for(i = 0; i < 9; i++)
{
printf("Thread %d: Dynamic Hello World %d\n", omp_get_thread_num(), i);
}
printf("\nStatic Ordered loop\n");
#pragma omp parallel for schedule(static) ordered
for(i = 0; i < 10; i++)
{
#pragma omp ordered
printf("Thread %d: Static Ordered Hello World %d\n", omp_get_thread_num(), i);
}
printf("\nDynamic Ordered loop\n");
#pragma omp parallel for schedule(dynamic) ordered
for(i = 0; i < 16; i++)
{
#pragma omp ordered
printf("Thread %d: Dynamic Ordered Hello World %d\n", omp_get_thread_num(), i);
}
return 0;
}
|
cg.20190412_parallel_block.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "globals.h"
#include "randdp.h"
#include "timers.h"
#include <omp.h>
//---------------------------------------------------------------------
#define CACHE_LINE_SIZE_PAD 128
#define INT_PAD_SIZE CACHE_LINE_SIZE_PAD/sizeof(int)
#define DOUBLE_PAD_SIZE CACHE_LINE_SIZE_PAD/sizeof(double)
/* common / main_int_mem / */
static int colidx[NZ];
static int rowstr[NA+1];
static int iv[NA];
static int arow[NA];
static int acol[NAZ];
/* common / main_flt_mem / */
static double aelt[NAZ];
static double a[NZ];
static double x[NA+2];
static double z[NA+2];
static double p[NA+2];
static double q[NA+2];
static double r[NA+2];
/* common / partit_size / */
static int naa;
static int nzz;
static int firstrow;
static int lastrow;
static int firstcol;
static int lastcol;
/* common /urando/ */
static double amult;
static double tran;
/* common /timers/ */
static logical timeron;
//---------------------------------------------------------------------
//---------------------------------------------------------------------
static void conj_grad(int colidx[],
int rowstr[],
double x[],
double z[],
double a[],
double p[],
double q[],
double r[],
double *rnorm);
static void makea(int n,
int nz,
double a[],
int colidx[],
int rowstr[],
int firstrow,
int lastrow,
int firstcol,
int lastcol,
int arow[],
int acol[][NONZER+1],
double aelt[][NONZER+1],
int iv[]);
static void sparse(double a[],
int colidx[],
int rowstr[],
int n,
int nz,
int nozer,
int arow[],
int acol[][NONZER+1],
double aelt[][NONZER+1],
int firstrow,
int lastrow,
int nzloc[],
double rcond,
double shift);
static void sprnvc(int n, int nz, int nn1, double v[], int iv[]);
static int icnvrt(double x, int ipwr2);
static void vecset(int n, double v[], int iv[], int *nzv, int i, double val);
//---------------------------------------------------------------------
int main(int argc, char *argv[])
{
omp_set_num_threads(omp_get_num_procs());
int i, j, k, it;
double zeta;
double rnorm;
double norm_temp1, norm_temp2;
double t, mflops, tmax;
//char Class;
logical verified;
double zeta_verify_value, epsilon, err;
char *t_names[T_last];
for (i = 0; i < T_last; i++) {
timer_clear(i);
}
timer_start(T_init);
firstrow = 0;
lastrow = NA-1;
firstcol = 0;
lastcol = NA-1;
zeta_verify_value = VALID_RESULT;
printf("\nCG start...\n\n");
printf(" Size: %11d\n", NA);
printf(" Iterations: %5d\n", NITER);
printf("\n");
naa = NA;
nzz = NZ;
//---------------------------------------------------------------------
// Inialize random number generator
//---------------------------------------------------------------------
tran = 314159265.0;
amult = 1220703125.0;
zeta = randlc(&tran, amult);
//---------------------------------------------------------------------
//
//---------------------------------------------------------------------
makea(naa, nzz, a, colidx, rowstr,
firstrow, lastrow, firstcol, lastcol,
arow,
(int (*)[NONZER+1])(void*)acol,
(double (*)[NONZER+1])(void*)aelt,
iv);
//---------------------------------------------------------------------
// Note: as a result of the above call to makea:
// values of j used in indexing rowstr go from 0 --> lastrow-firstrow
// values of colidx which are col indexes go from firstcol --> lastcol
// So:
// Shift the col index vals from actual (firstcol --> lastcol )
// to local, i.e., (0 --> lastcol-firstcol)
//---------------------------------------------------------------------
#pragma omp parallel default(shared) private(i,j,k)
{
#pragma omp for nowait
for (j = 0; j < lastrow - firstrow + 1; j++) {
for (k = rowstr[j]; k < rowstr[j+1]; k++) {
colidx[k] = colidx[k] - firstcol;
}
}
//---------------------------------------------------------------------
// set starting vector to (1, 1, .... 1)
//---------------------------------------------------------------------
#pragma omp for nowait
for (i = 0; i < NA+1; i++) {
x[i] = 1.0;
}
#pragma omp for nowait
for (j = 0; j < lastcol - firstcol + 1; j++) {
q[j] = 0.0;
z[j] = 0.0;
r[j] = 0.0;
p[j] = 0.0;
}
}
zeta = 0.0;
//---------------------------------------------------------------------
//---->
// Do one iteration untimed to init all code and data page tables
//----> (then reinit, start timing, to niter its)
//---------------------------------------------------------------------
for (it = 1; it <= 1; it++) {
//---------------------------------------------------------------------
// The call to the conjugate gradient routine:
//---------------------------------------------------------------------
conj_grad(colidx, rowstr, x, z, a, p, q, r, &rnorm);
//---------------------------------------------------------------------
// zeta = shift + 1/(x.z)
// So, first: (x.z)
// Also, find norm of z
// So, first: (z.z)
//---------------------------------------------------------------------
norm_temp1 = 0.0;
norm_temp2 = 0.0;
#pragma omp parallel for default(shared) private(j) reduction(+:norm_temp1,norm_temp2)
for (j = 0; j < lastcol - firstcol + 1; j++) {
norm_temp1 = norm_temp1 + x[j] * z[j];
norm_temp2 = norm_temp2 + z[j] * z[j];
}
norm_temp2 = 1.0 / sqrt(norm_temp2);
//---------------------------------------------------------------------
// Normalize z to obtain x
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(j)
for (j = 0; j < lastcol - firstcol + 1; j++) {
x[j] = norm_temp2 * z[j];
}
} // end of do one iteration untimed
//---------------------------------------------------------------------
// set starting vector to (1, 1, .... 1)
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(i)
for (i = 0; i < NA+1; i++) {
x[i] = 1.0;
}
zeta = 0.0;
timer_stop(T_init);
printf(" Initialization time = %15.3f seconds\n", timer_read(T_init));
timer_start(T_bench);
//---------------------------------------------------------------------
//---->
// Main Iteration for inverse power method
//---->
//---------------------------------------------------------------------
for (it = 1; it <= NITER; it++) {
//---------------------------------------------------------------------
// The call to the conjugate gradient routine:
//---------------------------------------------------------------------
if (timeron) timer_start(T_conj_grad);
conj_grad(colidx, rowstr, x, z, a, p, q, r, &rnorm);
if (timeron) timer_stop(T_conj_grad);
//---------------------------------------------------------------------
// zeta = shift + 1/(x.z)
// So, first: (x.z)
// Also, find norm of z
// So, first: (z.z)
//---------------------------------------------------------------------
norm_temp1 = 0.0;
norm_temp2 = 0.0;
#pragma omp parallel for default(shared) private(j) reduction(+:norm_temp1,norm_temp2)
for (j = 0; j < lastcol - firstcol + 1; j++) {
norm_temp1 = norm_temp1 + x[j]*z[j];
norm_temp2 = norm_temp2 + z[j]*z[j];
}
norm_temp2 = 1.0 / sqrt(norm_temp2);
zeta = SHIFT + 1.0 / norm_temp1;
if (it == 1)
printf("\n iteration ||r|| zeta\n");
printf(" %5d %20.14E%20.13f\n", it, rnorm, zeta);
//---------------------------------------------------------------------
// Normalize z to obtain x
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(j)
for (j = 0; j < lastcol - firstcol + 1; j++) {
x[j] = norm_temp2 * z[j];
}
} // end of main iter inv pow meth
timer_stop(T_bench);
//---------------------------------------------------------------------
// End of timed section
//---------------------------------------------------------------------
t = timer_read(T_bench);
printf("\nComplete...\n");
epsilon = 1.0e-10;
err = fabs(zeta - zeta_verify_value) / zeta_verify_value;
if (err <= epsilon) {
verified = true;
printf(" VERIFICATION SUCCESSFUL\n");
printf(" Zeta is %20.13E\n", zeta);
printf(" Error is %20.13E\n", err);
} else {
verified = false;
printf(" VERIFICATION FAILED\n");
printf(" Zeta %20.13E\n", zeta);
printf(" The correct zeta is %20.13E\n", zeta_verify_value);
}
printf("\n\nExecution time : %lf seconds\n\n", t);
return 0;
}
//---------------------------------------------------------------------
// Floaging point arrays here are named as in spec discussion of
// CG algorithm
//---------------------------------------------------------------------
static void conj_grad(int colidx[],
int rowstr[],
double x[],
double z[],
double a[],
double p[],
double q[],
double r[],
double *rnorm)
{
int j, k;
int cgit, cgitmax = 25;
double d, sum, rho, rho0, alpha, beta;
//---------------------------------------------------------------------
// Initialize the CG algorithm:
//---------------------------------------------------------------------
#pragma omp parallel default(shared) private(j)
{
#pragma omp for
for (j = 0; j < naa+1; j++) {
q[j] = 0.0;
z[j] = 0.0;
r[j] = x[j];
p[j] = r[j];
}
//---------------------------------------------------------------------
// rho = r.r
// Now, obtain the norm of r: First, sum squares of r elements locally...
//---------------------------------------------------------------------
#pragma omp for reduction(+:rho)
for (j = 0; j < lastcol - firstcol + 1; j++) {
rho = rho + r[j]*r[j];
}
}
//---------------------------------------------------------------------
//---->
// The conj grad iteration loop
//---->
//---------------------------------------------------------------------
for (cgit = 1; cgit <= cgitmax; cgit++) {
//---------------------------------------------------------------------
// q = A.p
// The partition submatrix-vector multiply: use workspace w
//---------------------------------------------------------------------
//
// NOTE: this version of the multiply is actually (slightly: maybe %5)
// faster on the sp2 on 16 nodes than is the unrolled-by-2 version
// below. On the Cray t3d, the reverse is true, i.e., the
// unrolled-by-two version is some 10% faster.
// The unrolled-by-8 version below is significantly faster
// on the Cray t3d - overall speed of code is 1.5 times faster.
rho0 = rho;
d = 0.0;
rho = 0.0;
#pragma omp parallel default(shared) private(j, k, sum)
{
#pragma omp for
for (j = 0; j < lastrow - firstrow + 1; j++) {
sum = 0.0;
for (k = rowstr[j]; k < rowstr[j+1]; k++) {
sum = sum + a[k]*p[colidx[k]];
}
q[j] = sum;
}
}
//---------------------------------------------------------------------
// Obtain p.q
//---------------------------------------------------------------------
#pragma omp parallel default(shared) private(j)
{
#pragma omp for reduction(+:d)
for (j = 0; j < lastcol - firstcol + 1; j++) {
d = d + p[j]*q[j];
}
}
//---------------------------------------------------------------------
// Obtain alpha = rho / (p.q)
//---------------------------------------------------------------------
alpha = rho0 / d;
//---------------------------------------------------------------------
// Save a temporary of rho
//---------------------------------------------------------------------
//---------------------------------------------------------------------
// Obtain z = z + alpha*p
// and r = r - alpha*q
//---------------------------------------------------------------------
#pragma omp parallel default(shared) private(j)
{
#pragma omp for
for (j = 0; j < lastcol - firstcol + 1; j++) {
z[j] = z[j] + alpha*p[j];
r[j] = r[j] - alpha*q[j];
}
}
//---------------------------------------------------------------------
// rho = r.r
// Now, obtain the norm of r: First, sum squares of r elements locally...
//---------------------------------------------------------------------
#pragma omp parallel default(shared) private(j)
{
#pragma omp for reduction(+:rho)
for (j = 0; j < lastcol - firstcol + 1; j++) {
rho = rho + r[j]*r[j];
}
}
//---------------------------------------------------------------------
// Obtain beta:
//---------------------------------------------------------------------
beta = rho / rho0;
//---------------------------------------------------------------------
// p = r + beta*p
//---------------------------------------------------------------------
#pragma omp parallel default(shared) private(j)
{
#pragma omp for
for (j = 0; j < lastcol - firstcol + 1; j++) {
p[j] = r[j] + beta*p[j];
}
}
} // end of do cgit=1,cgitmax
//---------------------------------------------------------------------
// Compute residual norm explicitly: ||r|| = ||x - A.z||
// First, form A.z
// The partition submatrix-vector multiply
//---------------------------------------------------------------------
/*
for (j = 0; j < lastrow - firstrow + 1; j++) {
printf("j = %d, colidx[%d] = %d, z[%d] = %lf\n", j, j, colidx[j], colidx[j], z[colidx[j]][0]);
}
*/
double d_tmp;
sum = 0.0;
#pragma omp parallel default(shared) private(j, d, d_tmp) shared(sum)
{
#pragma omp for
for (j = 0; j < lastrow - firstrow + 1; j++) {
d = 0.0;
for (k = rowstr[j]; k < rowstr[j+1]; k++) {
d = d + a[k]*z[colidx[k]];
}
r[j] = d;
}
//---------------------------------------------------------------------
// At this point, r contains A.z
//---------------------------------------------------------------------
#pragma omp for reduction(+:sum)
for (j = 0; j < lastcol-firstcol+1; j++) {
d_tmp = x[j] - r[j];
sum = sum + d_tmp*d_tmp;
}
}
*rnorm = sqrt(sum);
}
//---------------------------------------------------------------------
// generate the test problem for benchmark 6
// makea generates a sparse matrix with a
// prescribed sparsity distribution
//
// parameter type usage
//
// input
//
// n i number of cols/rows of matrix
// nz i nonzeros as declared array size
// rcond r*8 condition number
// shift r*8 main diagonal shift
//
// output
//
// a r*8 array for nonzeros
// colidx i col indices
// rowstr i row pointers
//
// workspace
//
// iv, arow, acol i
// aelt r*8
//---------------------------------------------------------------------
static void makea(int n,
int nz,
double a[],
int colidx[],
int rowstr[],
int firstrow,
int lastrow,
int firstcol,
int lastcol,
int arow[],
int acol[][NONZER+1],
double aelt[][NONZER+1],
int iv[])
{
int iouter, ivelt, nzv, nn1;
int ivc[NONZER+1];
double vc[NONZER+1];
//---------------------------------------------------------------------
// nonzer is approximately (int(sqrt(nnza /n)));
//---------------------------------------------------------------------
//---------------------------------------------------------------------
// nn1 is the smallest power of two not less than n
//---------------------------------------------------------------------
nn1 = 1;
do {
nn1 = 2 * nn1;
} while (nn1 < n);
//---------------------------------------------------------------------
// Generate nonzero positions and save for the use in sparse.
//---------------------------------------------------------------------
for (iouter = 0; iouter < n; iouter++) {
nzv = NONZER;
sprnvc(n, nzv, nn1, vc, ivc);
vecset(n, vc, ivc, &nzv, iouter+1, 0.5);
arow[iouter] = nzv;
for (ivelt = 0; ivelt < nzv; ivelt++) {
acol[iouter][ivelt] = ivc[ivelt] - 1;
aelt[iouter][ivelt] = vc[ivelt];
}
}
//---------------------------------------------------------------------
// ... make the sparse matrix from list of elements with duplicates
// (iv is used as workspace)
//---------------------------------------------------------------------
sparse(a, colidx, rowstr, n, nz, NONZER, arow, acol,
aelt, firstrow, lastrow,
iv, RCOND, SHIFT);
}
//---------------------------------------------------------------------
// rows range from firstrow to lastrow
// the rowstr pointers are defined for nrows = lastrow-firstrow+1 values
//---------------------------------------------------------------------
static void sparse(double a[],
int colidx[],
int rowstr[],
int n,
int nz,
int nozer,
int arow[],
int acol[][NONZER+1],
double aelt[][NONZER+1],
int firstrow,
int lastrow,
int nzloc[],
double rcond,
double shift)
{
int nrows;
//---------------------------------------------------
// generate a sparse matrix from a list of
// [col, row, element] tri
//---------------------------------------------------
int i, j, j1, j2, nza, k, kk, nzrow, jcol;
double size, scale, ratio, va;
logical cont40;
//---------------------------------------------------------------------
// how many rows of result
//---------------------------------------------------------------------
nrows = lastrow - firstrow + 1;
//---------------------------------------------------------------------
// ...count the number of triples in each row
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(j)
for (j = 0; j < nrows+1; j++) {
rowstr[j] = 0;
}
for (i = 0; i < n; i++) {
for (nza = 0; nza < arow[i]; nza++) {
j = acol[i][nza] + 1;
rowstr[j] = rowstr[j] + arow[i];
}
}
rowstr[0] = 0;
for (j = 1; j < nrows+1; j++) {
rowstr[j] = rowstr[j] + rowstr[j-1];
}
nza = rowstr[nrows] - 1;
//---------------------------------------------------------------------
// ... rowstr(j) now is the location of the first nonzero
// of row j of a
//---------------------------------------------------------------------
if (nza > nz) {
printf("Space for matrix elements exceeded in sparse\n");
printf("nza, nzmax = %d, %d\n", nza, nz);
exit(EXIT_FAILURE);
}
//---------------------------------------------------------------------
// ... preload data pages
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(j, k)
for (j = 0; j < nrows; j++) {
for (k = rowstr[j]; k < rowstr[j+1]; k++) {
a[k] = 0.0;
colidx[k] = -1;
}
nzloc[j] = 0;
}
//---------------------------------------------------------------------
// ... generate actual values by summing duplicates
//---------------------------------------------------------------------
size = 1.0;
ratio = pow(rcond, (1.0 / (double)(n)));
for (i = 0; i < n; i++) {
for (nza = 0; nza < arow[i]; nza++) {
j = acol[i][nza];
scale = size * aelt[i][nza];
for (nzrow = 0; nzrow < arow[i]; nzrow++) {
jcol = acol[i][nzrow];
va = aelt[i][nzrow] * scale;
//--------------------------------------------------------------------
// ... add the identity * rcond to the generated matrix to bound
// the smallest eigenvalue from below by rcond
//--------------------------------------------------------------------
if (jcol == j && j == i) {
va = va + rcond - shift;
}
cont40 = false;
for (k = rowstr[j]; k < rowstr[j+1]; k++) {
if (colidx[k] > jcol) {
//----------------------------------------------------------------
// ... insert colidx here orderly
//----------------------------------------------------------------
for (kk = rowstr[j+1]-2; kk >= k; kk--) {
if (colidx[kk] > -1) {
a[kk+1] = a[kk];
colidx[kk+1] = colidx[kk];
}
}
colidx[k] = jcol;
a[k] = 0.0;
cont40 = true;
break;
} else if (colidx[k] == -1) {
colidx[k] = jcol;
cont40 = true;
break;
} else if (colidx[k] == jcol) {
//--------------------------------------------------------------
// ... mark the duplicated entry
//--------------------------------------------------------------
nzloc[j] = nzloc[j] + 1;
cont40 = true;
break;
}
}
if (cont40 == false) {
printf("internal error in sparse: i=%d\n", i);
exit(EXIT_FAILURE);
}
a[k] = a[k] + va;
}
}
size = size * ratio;
}
//---------------------------------------------------------------------
// ... remove empty entries and generate final results
//---------------------------------------------------------------------
for (j = 1; j < nrows; j++) {
nzloc[j] = nzloc[j] + nzloc[j-1];
}
for (j = 0; j < nrows; j++) {
if (j > 0) {
j1 = rowstr[j] - nzloc[j-1];
} else {
j1 = 0;
}
j2 = rowstr[j+1] - nzloc[j];
nza = rowstr[j];
for (k = j1; k < j2; k++) {
a[k] = a[nza];
colidx[k] = colidx[nza];
nza = nza + 1;
}
}
#pragma omp parallel for default(shared) private(j)
for (j = 1; j < nrows+1; j++) {
rowstr[j] = rowstr[j] - nzloc[j-1];
}
nza = rowstr[nrows] - 1;
}
//---------------------------------------------------------------------
// generate a sparse n-vector (v, iv)
// having nzv nonzeros
//
// mark(i) is set to 1 if position i is nonzero.
// mark is all zero on entry and is reset to all zero before exit
// this corrects a performance bug found by John G. Lewis, caused by
// reinitialization of mark on every one of the n calls to sprnvc
//---------------------------------------------------------------------
static void sprnvc(int n, int nz, int nn1, double v[], int iv[])
{
int nzv, ii, i;
double vecelt, vecloc;
nzv = 0;
while (nzv < nz) {
vecelt = randlc(&tran, amult);
//---------------------------------------------------------------------
// generate an integer between 1 and n in a portable manner
//---------------------------------------------------------------------
vecloc = randlc(&tran, amult);
i = icnvrt(vecloc, nn1) + 1;
if (i > n) continue;
//---------------------------------------------------------------------
// was this integer generated already?
//---------------------------------------------------------------------
logical was_gen = false;
for (ii = 0; ii < nzv; ii++) {
if (iv[ii] == i) {
was_gen = true;
break;
}
}
if (was_gen) continue;
v[nzv] = vecelt;
iv[nzv] = i;
nzv = nzv + 1;
}
}
//---------------------------------------------------------------------
// scale a double precision number x in (0,1) by a power of 2 and chop it
//---------------------------------------------------------------------
static int icnvrt(double x, int ipwr2)
{
return (int)(ipwr2 * x);
}
//---------------------------------------------------------------------
// set ith element of sparse vector (v, iv) with
// nzv nonzeros to val
//---------------------------------------------------------------------
static void vecset(int n, double v[], int iv[], int *nzv, int i, double val)
{
int k;
logical set;
set = false;
for (k = 0; k < *nzv; k++) {
if (iv[k] == i) {
v[k] = val;
set = true;
}
}
if (set == false) {
v[*nzv] = val;
iv[*nzv] = i;
*nzv = *nzv + 1;
}
}
|
prior_box_op.h | /* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#pragma once
#include <algorithm>
#include <vector>
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/platform/transform.h"
#include "paddle/pten/kernels/funcs/math_function.h"
namespace paddle {
namespace operators {
constexpr int kPriorBoxFLOAT = 1;
constexpr int kPriorBoxDOUBLE = 2;
inline void ExpandAspectRatios(const std::vector<float>& input_aspect_ratior,
bool flip,
std::vector<float>* output_aspect_ratior) {
constexpr float epsilon = 1e-6;
output_aspect_ratior->clear();
output_aspect_ratior->push_back(1.0f);
for (size_t i = 0; i < input_aspect_ratior.size(); ++i) {
float ar = input_aspect_ratior[i];
bool already_exist = false;
for (size_t j = 0; j < output_aspect_ratior->size(); ++j) {
if (fabs(ar - output_aspect_ratior->at(j)) < epsilon) {
already_exist = true;
break;
}
}
if (!already_exist) {
output_aspect_ratior->push_back(ar);
if (flip) {
output_aspect_ratior->push_back(1.0f / ar);
}
}
}
}
template <typename T, typename K>
class PriorBoxOpKernel : public framework::OpKernel<T> {
public:
void Compute(const framework::ExecutionContext& ctx) const override {
auto* input = ctx.Input<paddle::framework::Tensor>("Input");
auto* image = ctx.Input<paddle::framework::Tensor>("Image");
auto* boxes = ctx.Output<paddle::framework::Tensor>("Boxes");
auto* vars = ctx.Output<paddle::framework::Tensor>("Variances");
auto min_sizes = ctx.Attr<std::vector<float>>("min_sizes");
auto max_sizes = ctx.Attr<std::vector<float>>("max_sizes");
auto input_aspect_ratio = ctx.Attr<std::vector<float>>("aspect_ratios");
auto variances = ctx.Attr<std::vector<float>>("variances");
auto flip = ctx.Attr<bool>("flip");
auto clip = ctx.Attr<bool>("clip");
auto min_max_aspect_ratios_order =
ctx.Attr<bool>("min_max_aspect_ratios_order");
std::vector<float> aspect_ratios;
ExpandAspectRatios(input_aspect_ratio, flip, &aspect_ratios);
K step_w = static_cast<K>(ctx.Attr<float>("step_w"));
K step_h = static_cast<K>(ctx.Attr<float>("step_h"));
K offset = static_cast<K>(ctx.Attr<float>("offset"));
auto img_width = image->dims()[3];
auto img_height = image->dims()[2];
auto feature_width = input->dims()[3];
auto feature_height = input->dims()[2];
K step_width, step_height;
if (step_w == 0 || step_h == 0) {
step_width = static_cast<K>(img_width) / feature_width;
step_height = static_cast<K>(img_height) / feature_height;
} else {
step_width = step_w;
step_height = step_h;
}
int num_priors = aspect_ratios.size() * min_sizes.size();
if (max_sizes.size() > 0) {
num_priors += max_sizes.size();
}
boxes->mutable_data<K>(ctx.GetPlace());
vars->mutable_data<K>(ctx.GetPlace());
K* b_t = boxes->data<K>();
for (int h = 0; h < feature_height; ++h) {
for (int w = 0; w < feature_width; ++w) {
K center_x = (w + offset) * step_width;
K center_y = (h + offset) * step_height;
K box_width, box_height;
for (size_t s = 0; s < min_sizes.size(); ++s) {
auto min_size = min_sizes[s];
if (min_max_aspect_ratios_order) {
box_width = box_height = min_size / 2.;
b_t[0] = (center_x - box_width) / img_width;
b_t[1] = (center_y - box_height) / img_height;
b_t[2] = (center_x + box_width) / img_width;
b_t[3] = (center_y + box_height) / img_height;
b_t += 4;
if (max_sizes.size() > 0) {
auto max_size = max_sizes[s];
// square prior with size sqrt(minSize * maxSize)
box_width = box_height = sqrt(min_size * max_size) / 2.;
b_t[0] = (center_x - box_width) / img_width;
b_t[1] = (center_y - box_height) / img_height;
b_t[2] = (center_x + box_width) / img_width;
b_t[3] = (center_y + box_height) / img_height;
b_t += 4;
}
// priors with different aspect ratios
for (size_t r = 0; r < aspect_ratios.size(); ++r) {
float ar = aspect_ratios[r];
if (fabs(ar - 1.) < 1e-6) {
continue;
}
box_width = min_size * sqrt(ar) / 2.;
box_height = min_size / sqrt(ar) / 2.;
b_t[0] = (center_x - box_width) / img_width;
b_t[1] = (center_y - box_height) / img_height;
b_t[2] = (center_x + box_width) / img_width;
b_t[3] = (center_y + box_height) / img_height;
b_t += 4;
}
} else {
// priors with different aspect ratios
for (size_t r = 0; r < aspect_ratios.size(); ++r) {
float ar = aspect_ratios[r];
box_width = min_size * sqrt(ar) / 2.;
box_height = min_size / sqrt(ar) / 2.;
b_t[0] = (center_x - box_width) / img_width;
b_t[1] = (center_y - box_height) / img_height;
b_t[2] = (center_x + box_width) / img_width;
b_t[3] = (center_y + box_height) / img_height;
b_t += 4;
}
if (max_sizes.size() > 0) {
auto max_size = max_sizes[s];
// square prior with size sqrt(minSize * maxSize)
box_width = box_height = sqrt(min_size * max_size) / 2.;
b_t[0] = (center_x - box_width) / img_width;
b_t[1] = (center_y - box_height) / img_height;
b_t[2] = (center_x + box_width) / img_width;
b_t[3] = (center_y + box_height) / img_height;
b_t += 4;
}
}
}
}
}
if (clip) {
K* dt = boxes->data<K>();
std::transform(dt, dt + boxes->numel(), dt, [](K v) -> K {
return std::min<K>(std::max<K>(v, 0.), 1.);
});
}
framework::Tensor var_t;
var_t.mutable_data<K>(
pten::make_ddim({1, static_cast<int>(variances.size())}),
ctx.GetPlace());
auto var_et = framework::EigenTensor<K, 2>::From(var_t);
#ifdef PADDLE_WITH_MKLML
#pragma omp parallel for
#endif
for (size_t i = 0; i < variances.size(); ++i) {
var_et(0, i) = variances[i];
}
int box_num = feature_height * feature_width * num_priors;
auto var_dim = vars->dims();
vars->Resize({box_num, static_cast<int>(variances.size())});
auto e_vars = framework::EigenMatrix<K, Eigen::RowMajor>::From(*vars);
#ifdef PADDLE_WITH_MKLML
#pragma omp parallel for collapse(2)
#endif
for (int i = 0; i < box_num; ++i) {
for (size_t j = 0; j < variances.size(); ++j) {
e_vars(i, j) = variances[j];
}
}
vars->Resize(var_dim);
}
}; // namespace operators
} // namespace operators
} // namespace paddle
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.